From 9ee29f0154fd4081ae931ffeb579db4546675870 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Mon, 9 Aug 2021 14:32:52 +0200 Subject: [PATCH 001/647] Add env files to gitignore --- .gitignore | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.gitignore b/.gitignore index 5ba7905ce7..f18daa77ab 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,5 @@ release ./vendor .idea +.env +.envrc \ No newline at end of file From 7ee261963378a354fe8fc3e20a1952b9dd3760d8 Mon Sep 17 00:00:00 2001 From: Adam Harvey Date: Thu, 12 Aug 2021 16:29:36 -0700 Subject: [PATCH 002/647] batches: fix feature detection in `src batch validate` (#577) When creating the `Service` instance, `src batch validate` failed to request or initialise the Sourcegraph feature flags based on the Sourcegraph version in use. As a result, only baseline features were enabled when parsing and validating batch specs. Fixes #576. --- CHANGELOG.md | 4 ++++ cmd/src/batch_validate.go | 13 ++++++++++++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bd721272bd..d4a5dc2192 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,10 +13,14 @@ All notable changes to `src-cli` are documented in this file. ### Added +- `src batch validate` now accepts the standard flags used to control communication with Sourcegraph: `-dump-requests`, `-get-curl`, `-insecure-skip-verify`, and `-trace`. [#577](https://github.com/sourcegraph/src-cli/pull/577) + ### Changed ### Fixed +- `src batch validate` would fail to validate batch specs that use features that depend on specific versions of Sourcegraph, such as workspaces. This has been fixed. [#576](https://github.com/sourcegraph/src-cli/issues/576) + ### Removed ## 3.30.4 diff --git a/cmd/src/batch_validate.go b/cmd/src/batch_validate.go index 2cef0943c8..b78efc9f56 100644 --- a/cmd/src/batch_validate.go +++ b/cmd/src/batch_validate.go @@ -1,10 +1,12 @@ package main import ( + "context" "flag" "fmt" "github.com/sourcegraph/sourcegraph/lib/output" + "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/batches/service" "github.com/sourcegraph/src-cli/internal/batches/ui" "github.com/sourcegraph/src-cli/internal/cmderrors" @@ -25,9 +27,12 @@ Examples: ` flagSet := flag.NewFlagSet("validate", flag.ExitOnError) + apiFlags := api.NewFlags(flagSet) fileFlag := flagSet.String("f", "", "The batch spec file to read.") handler := func(args []string) error { + ctx := context.Background() + if err := flagSet.Parse(args); err != nil { return err } @@ -36,7 +41,13 @@ Examples: return cmderrors.Usage("additional arguments not allowed") } - svc := service.New(&service.Opts{}) + svc := service.New(&service.Opts{ + Client: cfg.apiClient(apiFlags, flagSet.Output()), + }) + + if err := svc.DetermineFeatureFlags(ctx); err != nil { + return err + } out := output.NewOutput(flagSet.Output(), output.OutputOpts{Verbose: *verbose}) if _, _, err := batchParseSpec(fileFlag, svc); err != nil { From 80d9902190c7507d83170f6dd954ee5faf49f103 Mon Sep 17 00:00:00 2001 From: Adam Harvey Date: Thu, 12 Aug 2021 16:30:59 -0700 Subject: [PATCH 003/647] changelog: update for 3.30.5 --- CHANGELOG.md | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d4a5dc2192..850c904eb8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,16 +13,22 @@ All notable changes to `src-cli` are documented in this file. ### Added -- `src batch validate` now accepts the standard flags used to control communication with Sourcegraph: `-dump-requests`, `-get-curl`, `-insecure-skip-verify`, and `-trace`. [#577](https://github.com/sourcegraph/src-cli/pull/577) - ### Changed ### Fixed -- `src batch validate` would fail to validate batch specs that use features that depend on specific versions of Sourcegraph, such as workspaces. This has been fixed. [#576](https://github.com/sourcegraph/src-cli/issues/576) - ### Removed +## 3.30.5 + +### Added + +- `src batch validate` now accepts the standard flags used to control communication with Sourcegraph: `-dump-requests`, `-get-curl`, `-insecure-skip-verify`, and `-trace`. [#577](https://github.com/sourcegraph/src-cli/pull/577) + +### Fixed + +- `src batch validate` would fail to validate batch specs that use features that depend on specific versions of Sourcegraph, such as workspaces. This has been fixed. [#576](https://github.com/sourcegraph/src-cli/issues/576) + ## 3.30.4 ### Added From 3eb98de8e9ac2276a3e27edd09aaee7c81fbd080 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Tue, 17 Aug 2021 22:36:23 +0200 Subject: [PATCH 004/647] Remove published: false from template for batch new (#578) Now that this property isn't required anymore, we can get rid of that part. Honors the feature flag for optional publish values. --- cmd/src/batch_new.go | 96 +++++------------------------ internal/batches/service/service.go | 88 ++++++++++++++++++++++++++ 2 files changed, 104 insertions(+), 80 deletions(-) diff --git a/cmd/src/batch_new.go b/cmd/src/batch_new.go index af6a894956..9d692e00ec 100644 --- a/cmd/src/batch_new.go +++ b/cmd/src/batch_new.go @@ -1,16 +1,13 @@ package main import ( + "context" "flag" "fmt" - "os" - "os/exec" - "strings" - "text/template" - - "github.com/pkg/errors" - "github.com/sourcegraph/src-cli/internal/batches" + "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/batches/service" + "github.com/sourcegraph/src-cli/internal/cmderrors" ) func init() { @@ -30,51 +27,33 @@ Examples: ` flagSet := flag.NewFlagSet("new", flag.ExitOnError) + apiFlags := api.NewFlags(flagSet) var ( fileFlag = flagSet.String("f", "batch.yaml", "The name of the batch spec file to create.") ) handler := func(args []string) error { + ctx := context.Background() + if err := flagSet.Parse(args); err != nil { return err } - f, err := os.OpenFile(*fileFlag, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0644) - if err != nil { - if os.IsExist(err) { - return fmt.Errorf("file %s already exists", *fileFlag) - } - return errors.Wrapf(err, "failed to create file %s", *fileFlag) + if len(flagSet.Args()) != 0 { + return cmderrors.Usage("additional arguments not allowed") } - defer f.Close() - tmpl, err := template.New("").Parse(batchSpecTmpl) - if err != nil { - return err - } + svc := service.New(&service.Opts{ + Client: cfg.apiClient(apiFlags, flagSet.Output()), + }) - author := batches.GitCommitAuthor{ - Name: "Sourcegraph", - Email: "batch-changes@sourcegraph.com", - } - - // Try to get better default values from git, ignore any errors. - if err := checkExecutable("git", "version"); err == nil { - var gitAuthorName, gitAuthorEmail string - var err1, err2 error - gitAuthorName, err1 = getGitConfig("user.name") - gitAuthorEmail, err2 = getGitConfig("user.email") - - if err1 == nil && err2 == nil && gitAuthorName != "" && gitAuthorEmail != "" { - author.Name = gitAuthorName - author.Email = gitAuthorEmail - } + if err := svc.DetermineFeatureFlags(ctx); err != nil { + return err } - err = tmpl.Execute(f, map[string]interface{}{"Author": author}) - if err != nil { - return errors.Wrap(err, "failed to write batch spec to file") + if err := svc.GenerateExampleSpec(ctx, *fileFlag); err != nil { + return err } fmt.Printf("%s created.\n", *fileFlag) @@ -92,46 +71,3 @@ Examples: }, }) } - -func getGitConfig(attribute string) (string, error) { - cmd := exec.Command("git", "config", "--get", attribute) - out, err := cmd.CombinedOutput() - if err != nil { - return "", err - } - return strings.TrimSpace(string(out)), nil -} - -const batchSpecTmpl = `name: NAME-OF-YOUR-BATCH-CHANGE -description: DESCRIPTION-OF-YOUR-BATCH-CHANGE - -# "on" specifies on which repositories to execute the "steps". -on: - # Example: find all repositories that contain a README.md file. - - repositoriesMatchingQuery: file:README.md - -# "steps" are run in each repository. Each step is run in a Docker container -# with the repository as the working directory. Once complete, each -# repository's resulting diff is captured. -steps: - # Example: append "Hello World" to every README.md - - run: echo "Hello World" | tee -a $(find -name README.md) - container: alpine:3 - -# "changesetTemplate" describes the changeset (e.g., GitHub pull request) that -# will be created for each repository. -changesetTemplate: - title: Hello World - body: This adds Hello World to the README - - branch: BRANCH-NAME-IN-EACH-REPOSITORY # Push the commit to this branch. - - commit: - author: - name: {{ .Author.Name }} - email: {{ .Author.Email }} - message: Append Hello World to all README.md files - - # Change published to true once you're ready to create changesets on the code host. - published: false -` diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index 175626170a..4124b1ee63 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -4,8 +4,11 @@ import ( "context" "encoding/json" "fmt" + "html/template" "io" "io/ioutil" + "os" + "os/exec" "path" "regexp" "strings" @@ -273,6 +276,82 @@ func (svc *Service) ParseBatchSpec(in io.Reader) (*batches.BatchSpec, string, er return spec, string(data), nil } +const exampleSpecTmpl = `name: NAME-OF-YOUR-BATCH-CHANGE +description: DESCRIPTION-OF-YOUR-BATCH-CHANGE + +# "on" specifies on which repositories to execute the "steps". +on: + # Example: find all repositories that contain a README.md file. + - repositoriesMatchingQuery: file:README.md + +# "steps" are run in each repository. Each step is run in a Docker container +# with the repository as the working directory. Once complete, each +# repository's resulting diff is captured. +steps: + # Example: append "Hello World" to every README.md + - run: echo "Hello World" | tee -a $(find -name README.md) + container: alpine:3 + +# "changesetTemplate" describes the changeset (e.g., GitHub pull request) that +# will be created for each repository. +changesetTemplate: + title: Hello World + body: This adds Hello World to the README + + branch: BRANCH-NAME-IN-EACH-REPOSITORY # Push the commit to this branch. + + commit: + author: + name: {{ .Author.Name }} + email: {{ .Author.Email }} + message: Append Hello World to all README.md files +` + +const exampleSpecPublishFlagTmpl = ` + # Change published to true once you're ready to create changesets on the code host. + published: false +` + +func (svc *Service) GenerateExampleSpec(ctx context.Context, fileName string) error { + // Try to create file. Bail out, if it already exists. + f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0644) + if err != nil { + if os.IsExist(err) { + return fmt.Errorf("file %s already exists", fileName) + } + return errors.Wrapf(err, "failed to create file %s", fileName) + } + defer f.Close() + + t := exampleSpecTmpl + if !svc.features.AllowOptionalPublished { + t += exampleSpecPublishFlagTmpl + } + tmpl, err := template.New("").Parse(t) + if err != nil { + return err + } + + author := batches.GitCommitAuthor{ + Name: "Sourcegraph", + Email: "batch-changes@sourcegraph.com", + } + // Try to get better default values from git, ignore any errors. + gitAuthorName, err1 := getGitConfig("user.name") + gitAuthorEmail, err2 := getGitConfig("user.email") + if err1 == nil && err2 == nil && gitAuthorName != "" && gitAuthorEmail != "" { + author.Name = gitAuthorName + author.Email = gitAuthorEmail + } + + err = tmpl.Execute(f, map[string]interface{}{"Author": author}) + if err != nil { + return errors.Wrap(err, "failed to write batch spec to file") + } + + return nil +} + const namespaceQuery = ` query NamespaceQuery($name: String!) { user(username: $name) { @@ -702,3 +781,12 @@ func (sr *searchResult) UnmarshalJSON(data []byte) error { return errors.Errorf("unknown GraphQL type %q", tn.Typename) } } + +func getGitConfig(attribute string) (string, error) { + cmd := exec.Command("git", "config", "--get", attribute) + out, err := cmd.CombinedOutput() + if err != nil { + return "", err + } + return strings.TrimSpace(string(out)), nil +} From 7be248423c68d413abc8df8ffa504423cc5e076b Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Wed, 18 Aug 2021 16:07:45 +0200 Subject: [PATCH 005/647] Prepare changelog for 3.31 --- CHANGELOG.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 850c904eb8..787c90d091 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,12 @@ All notable changes to `src-cli` are documented in this file. ### Removed +## 3.31.0 + +### Changed + +- `src batch new` now omits the publish flag, if the Sourcegraph instance supports publish from GUI. + ## 3.30.5 ### Added From b3ed3e291807cf219d44f1d706c3855c86296c60 Mon Sep 17 00:00:00 2001 From: Stefan Hengl Date: Thu, 19 Aug 2021 09:03:50 +0200 Subject: [PATCH 006/647] all: use /usr/bin/env bash (#579) some *nix systems don't have `/bin/bash`. `/usr/bin/env` is more portable. I am accross this issue while running the tests on nixos. --- cmd/src/test.sh | 2 +- internal/batches/executor/testdata/dummydocker/docker | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/cmd/src/test.sh b/cmd/src/test.sh index c0b48af5c8..a3284829e7 100755 --- a/cmd/src/test.sh +++ b/cmd/src/test.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash cleanup() { src orgs members remove -org-id=$(src org get -f '{{.ID}}' -name=abc-org) -user-id=$(src users get -f '{{.ID}}' -username=alice) diff --git a/internal/batches/executor/testdata/dummydocker/docker b/internal/batches/executor/testdata/dummydocker/docker index 2a12dd1a82..c78c22f214 100755 --- a/internal/batches/executor/testdata/dummydocker/docker +++ b/internal/batches/executor/testdata/dummydocker/docker @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # This script is used by the executor integration test to simulate Docker. # It gets put into $PATH as "docker" and accepts the "run" command. From 364d86e5924d8a1bc1ae7e615265f869e5f73f8c Mon Sep 17 00:00:00 2001 From: Stefan Hengl Date: Thu, 19 Aug 2021 15:34:13 +0200 Subject: [PATCH 007/647] stream search: fix match count (#580) `search -stream` showed the number of lines that contain matches instead of the number of matches. --- CHANGELOG.md | 1 + cmd/src/format.go | 1 + cmd/src/search_stream.go | 10 +++++++++- cmd/src/search_stream_test.go | 4 ++-- cmd/src/testdata/streaming_search_want.json | 2 +- cmd/src/testdata/streaming_search_want.txt | 4 ++-- 6 files changed, 16 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 787c90d091..11f47c84e4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,7 @@ All notable changes to `src-cli` are documented in this file. ### Changed ### Fixed +- `src search -stream` displayed the number of lines that contain matches instead of the number of matches. ### Removed diff --git a/cmd/src/format.go b/cmd/src/format.go index 8ad63edc1f..af36ee157b 100644 --- a/cmd/src/format.go +++ b/cmd/src/format.go @@ -100,6 +100,7 @@ func parseTemplate(text string) (*template.Template, error) { "streamSearchHighlightCommit": streamSearchTemplateFuncs["streamSearchHighlightCommit"], "streamSearchRenderCommitLabel": streamSearchTemplateFuncs["streamSearchRenderCommitLabel"], "matchOrMatches": streamSearchTemplateFuncs["matchOrMatches"], + "countMatches": streamSearchTemplateFuncs["countMatches"], // Alert rendering "searchAlertRender": func(alert searchResultsAlert) string { diff --git a/cmd/src/search_stream.go b/cmd/src/search_stream.go index 1a06b46372..825c225854 100644 --- a/cmd/src/search_stream.go +++ b/cmd/src/search_stream.go @@ -230,7 +230,7 @@ const streamingTemplate = ` {{- color "search-repository"}}{{.Repository}}{{color "nc" -}} {{- " › " -}} {{- color "search-filename"}}{{.Path}}{{color "nc" -}} - {{- color "success"}}{{matchOrMatches (len .LineMatches)}}{{color "nc" -}} + {{- color "success"}}{{matchOrMatches (countMatches .LineMatches)}}{{color "nc" -}} {{- "\n" -}} {{- color "search-border"}}{{"--------------------------------------------------------------------------------\n"}}{{color "nc"}} @@ -375,6 +375,14 @@ var streamSearchTemplateFuncs = map[string]interface{}{ } return fmt.Sprintf(" (%d matches)", i) }, + + "countMatches": func(lineMatches []streaming.EventLineMatch) int { + count := 0 + for _, l := range lineMatches { + count += len(l.OffsetAndLengths) + } + return count + }, } func streamSearchHighlightDiffPreview(diffPreview string, highlights []highlight) string { diff --git a/cmd/src/search_stream_test.go b/cmd/src/search_stream_test.go index be1887d5c8..e053dd8db4 100644 --- a/cmd/src/search_stream_test.go +++ b/cmd/src/search_stream_test.go @@ -45,9 +45,9 @@ var event = []streaming.EventMatch{ Version: "", LineMatches: []streaming.EventLineMatch{ { - Line: "foo bar", + Line: "foo bar foo", LineNumber: 4, - OffsetAndLengths: [][2]int32{{4, 3}}, + OffsetAndLengths: [][2]int32{{0, 3}, {8, 3}}, }, }, }, diff --git a/cmd/src/testdata/streaming_search_want.json b/cmd/src/testdata/streaming_search_want.json index 8404bb99b8..86936f2909 100755 --- a/cmd/src/testdata/streaming_search_want.json +++ b/cmd/src/testdata/streaming_search_want.json @@ -1,4 +1,4 @@ -{"type":"content","name":"path/to/file","repository":"org/repo","lineMatches":[{"line":"foo bar","lineNumber":4,"offsetAndLengths":[[4,3]]}]} +{"type":"content","name":"path/to/file","repository":"org/repo","lineMatches":[{"line":"foo bar foo","lineNumber":4,"offsetAndLengths":[[0,3],[8,3]]}]} {"type":"repo","repository":"sourcegraph/sourcegraph"} {"type":"symbol","name":"path/to/file","repository":"org/repo","symbols":[{"url":"github.com/sourcegraph/sourcegraph/-/blob/cmd/frontend/graphqlbackend/search_results.go#L1591:26-1591:35","name":"doResults","containerName":"","kind":"FUNCTION"},{"url":"github.com/sourcegraph/sourcegraph/-/blob/cmd/frontend/graphqlbackend/search_results.go#L1591:26-1591:35","name":"Results","containerName":"SearchResultsResolver","kind":"FIELD"}]} {"type":"commit","icon":"","label":"[sourcegraph/sourcegraph-atom](/github.com/sourcegraph/sourcegraph-atom) › [Stephen Gutekanst](/github.com/sourcegraph/sourcegraph-atom/-/commit/5b098d7fed963d88e23057ed99d73d3c7a33ad89): [all: release v1.0.5](/github.com/sourcegraph/sourcegraph-atom/-/commit/5b098d7fed963d88e23057ed99d73d3c7a33ad89)^","url":"","detail":"","content":"```COMMIT_EDITMSG\nfoo bar\n```","ranges":[[1,3,3]]} diff --git a/cmd/src/testdata/streaming_search_want.txt b/cmd/src/testdata/streaming_search_want.txt index 422c14b4ab..9045928b92 100644 --- a/cmd/src/testdata/streaming_search_want.txt +++ b/cmd/src/testdata/streaming_search_want.txt @@ -1,6 +1,6 @@ -org/repo › path/to/file (1 match) +org/repo › path/to/file (2 matches) -------------------------------------------------------------------------------- -  5 | foo bar +  5 | foo bar foo sourcegraph/sourcegraph (http://127.0.0.1:55128/sourcegraph/sourcegraph) (1 match) org/repo › path/to/file (2 matches) From fa8047a3b9bf0b40288e1b4b76a1c3eb89381939 Mon Sep 17 00:00:00 2001 From: Thorsten Ball Date: Fri, 20 Aug 2021 12:06:39 +0200 Subject: [PATCH 008/647] Fix null in JSON log lines output by removing nil slice (#582) --- CHANGELOG.md | 2 ++ internal/batches/ui/json_lines.go | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 11f47c84e4..d19b6cc223 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,7 +16,9 @@ All notable changes to `src-cli` are documented in this file. ### Changed ### Fixed + - `src search -stream` displayed the number of lines that contain matches instead of the number of matches. +- For internal use only: the `EXECUTING_TASKS` JSON log line now always contains an array of `tasks` instead of possibly having `null` as the `tasks` value. ### Removed diff --git a/internal/batches/ui/json_lines.go b/internal/batches/ui/json_lines.go index 33da1ee233..9d9ddab1bd 100644 --- a/internal/batches/ui/json_lines.go +++ b/internal/batches/ui/json_lines.go @@ -226,7 +226,7 @@ type taskExecutionJSONLines struct { func (ui *taskExecutionJSONLines) Start(tasks []*executor.Task) { ui.linesTasks = make(map[*executor.Task]jsonLinesTask, len(tasks)) - var linesTasks []jsonLinesTask + linesTasks := []jsonLinesTask{} for _, t := range tasks { linesTask := jsonLinesTask{ Repository: t.Repository.Name, From 78e89bd2b242880a5de1acee101a79aa386153a9 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Fri, 20 Aug 2021 22:34:22 +0200 Subject: [PATCH 009/647] Refactor BatchSpec type and ParseBatchSpec to be shareable (#581) --- cmd/src/batch_common.go | 19 +- cmd/src/batch_repositories.go | 2 +- cmd/src/batch_validate.go | 2 +- internal/batches/batch_spec.go | 58 ++---- internal/batches/batch_spec_test.go | 10 +- internal/batches/docker/image.go | 68 +++--- internal/batches/docker/image_test.go | 194 ++++++++---------- internal/batches/executor/coordinator.go | 10 +- internal/batches/executor/executor.go | 16 +- internal/batches/executor/executor_test.go | 43 ++-- internal/batches/executor/run_steps.go | 29 +-- internal/batches/executor/task_builder.go | 40 ++-- .../batches/executor/task_builder_test.go | 12 +- internal/batches/service/service.go | 42 ++-- .../batches/workspace/volume_workspace.go | 13 +- .../workspace/volume_workspace_test.go | 46 +++-- internal/batches/workspace/workspace.go | 25 ++- internal/batches/workspace/workspace_test.go | 44 ++-- 18 files changed, 331 insertions(+), 342 deletions(-) diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index a13179fc1b..79edb7a6ba 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -5,6 +5,7 @@ import ( "flag" "fmt" "io" + "io/ioutil" "os" "os/exec" "os/signal" @@ -221,7 +222,7 @@ func executeBatchSpec(ctx context.Context, opts executeBatchSpecOpts) (err error // Parse flags and build up our service and executor options. opts.ui.ParsingBatchSpec() - batchSpec, rawSpec, err := batchParseSpec(&opts.flags.file, svc) + batchSpec, rawSpec, err := parseBatchSpec(&opts.flags.file, svc) if err != nil { if merr, ok := err.(*multierror.Error); ok { opts.ui.ParsingBatchSpecFailure(merr) @@ -242,14 +243,14 @@ func executeBatchSpec(ctx context.Context, opts executeBatchSpecOpts) (err error opts.ui.ResolvingNamespaceSuccess(namespace) opts.ui.PreparingContainerImages() - err = svc.SetDockerImages(ctx, batchSpec, opts.ui.PreparingContainerImagesProgress) + images, err := svc.EnsureDockerImages(ctx, batchSpec, opts.ui.PreparingContainerImagesProgress) if err != nil { return err } opts.ui.PreparingContainerImagesSuccess() opts.ui.DeterminingWorkspaceCreatorType() - workspaceCreator := workspace.NewCreator(ctx, opts.flags.workspace, opts.flags.cacheDir, opts.flags.tempDir, batchSpec.Steps) + workspaceCreator := workspace.NewCreator(ctx, opts.flags.workspace, opts.flags.cacheDir, opts.flags.tempDir, images) if workspaceCreator.Type() == workspace.CreatorTypeVolume { _, err = svc.EnsureImage(ctx, workspace.DockerVolumeWorkspaceImage) if err != nil { @@ -363,16 +364,22 @@ func executeBatchSpec(ctx context.Context, opts executeBatchSpecOpts) (err error return nil } -// batchParseSpec parses and validates the given batch spec. If the spec has +// parseBatchSpec parses and validates the given batch spec. If the spec has // validation errors, they are returned. -func batchParseSpec(file *string, svc *service.Service) (*batches.BatchSpec, string, error) { +func parseBatchSpec(file *string, svc *service.Service) (*batches.BatchSpec, string, error) { f, err := batchOpenFileFlag(file) if err != nil { return nil, "", err } defer f.Close() - return svc.ParseBatchSpec(f) + data, err := ioutil.ReadAll(f) + if err != nil { + return nil, "", errors.Wrap(err, "reading batch spec") + } + + spec, err := svc.ParseBatchSpec(data) + return spec, string(data), err } func checkExecutable(cmd string, args ...string) error { diff --git a/cmd/src/batch_repositories.go b/cmd/src/batch_repositories.go index aea8848895..f8e117b05c 100644 --- a/cmd/src/batch_repositories.go +++ b/cmd/src/batch_repositories.go @@ -50,7 +50,7 @@ Examples: } out := output.NewOutput(flagSet.Output(), output.OutputOpts{Verbose: *verbose}) - spec, _, err := batchParseSpec(fileFlag, svc) + spec, _, err := parseBatchSpec(fileFlag, svc) if err != nil { ui := &ui.TUI{Out: out} ui.ParsingBatchSpecFailure(err) diff --git a/cmd/src/batch_validate.go b/cmd/src/batch_validate.go index b78efc9f56..0c529092e8 100644 --- a/cmd/src/batch_validate.go +++ b/cmd/src/batch_validate.go @@ -50,7 +50,7 @@ Examples: } out := output.NewOutput(flagSet.Output(), output.OutputOpts{Verbose: *verbose}) - if _, _, err := batchParseSpec(fileFlag, svc); err != nil { + if _, _, err := parseBatchSpec(fileFlag, svc); err != nil { (&ui.TUI{Out: out}).ParsingBatchSpecFailure(err) return err } diff --git a/internal/batches/batch_spec.go b/internal/batches/batch_spec.go index 584d9c3634..09068a0eec 100644 --- a/internal/batches/batch_spec.go +++ b/internal/batches/batch_spec.go @@ -1,17 +1,14 @@ package batches import ( - "context" "fmt" "strings" - "github.com/gobwas/glob" "github.com/hashicorp/go-multierror" "github.com/pkg/errors" "github.com/sourcegraph/batch-change-utils/env" "github.com/sourcegraph/batch-change-utils/overridable" "github.com/sourcegraph/batch-change-utils/yaml" - "github.com/sourcegraph/src-cli/internal/batches/docker" "github.com/sourcegraph/src-cli/schema" ) @@ -69,16 +66,6 @@ type WorkspaceConfiguration struct { RootAtLocationOf string `json:"rootAtLocationOf,omitempty" yaml:"rootAtLocationOf"` In string `json:"in,omitempty" yaml:"in"` OnlyFetchWorkspace bool `json:"onlyFetchWorkspace,omitempty" yaml:"onlyFetchWorkspace"` - - glob glob.Glob -} - -func (wc *WorkspaceConfiguration) SetGlob(g glob.Glob) { - wc.glob = g -} - -func (wc *WorkspaceConfiguration) Matches(repoName string) bool { - return wc.glob.Match(repoName) } type OnQueryOrRepository struct { @@ -95,8 +82,6 @@ type Step struct { Outputs Outputs `json:"outputs,omitempty" yaml:"outputs,omitempty"` If interface{} `json:"if,omitempty" yaml:"if,omitempty"` - - image docker.Image } func (s *Step) IfCondition() string { @@ -113,27 +98,6 @@ func (s *Step) IfCondition() string { } } -func (s *Step) SetImage(image docker.Image) { - s.image = image -} - -// TODO(mrnugget): All of these wrappers are not good -func (s Step) ImageDigest(ctx context.Context) (string, error) { - return s.image.Digest(ctx) -} - -func (s Step) DockerImage() docker.Image { - return s.image -} - -func (s Step) EnsureImage(ctx context.Context) error { - return s.image.Ensure(ctx) -} - -func (s Step) ImageUIDGID(ctx context.Context) (docker.UIDGID, error) { - return s.image.UIDGID(ctx) -} - type Outputs map[string]Output type Output struct { @@ -151,9 +115,19 @@ type Group struct { Repository string `json:"repository,omitempty" yaml:"repository"` } -func ParseBatchSpec(data []byte, features FeatureFlags) (*BatchSpec, error) { +type ParseBatchSpecOptions struct { + AllowArrayEnvironments bool + AllowTransformChanges bool + AllowConditionalExec bool +} + +func ParseBatchSpec(data []byte, opts ParseBatchSpecOptions) (*BatchSpec, error) { + return parseBatchSpec(schema.BatchSpecJSON, data, opts) +} + +func parseBatchSpec(schema string, data []byte, opts ParseBatchSpecOptions) (*BatchSpec, error) { var spec BatchSpec - if err := yaml.UnmarshalValidate(schema.BatchSpecJSON, data, &spec); err != nil { + if err := yaml.UnmarshalValidate(schema, data, &spec); err != nil { if multiErr, ok := err.(*multierror.Error); ok { var newMultiError *multierror.Error @@ -174,7 +148,7 @@ func ParseBatchSpec(data []byte, features FeatureFlags) (*BatchSpec, error) { var errs *multierror.Error - if !features.AllowArrayEnvironments { + if !opts.AllowArrayEnvironments { for i, step := range spec.Steps { if !step.Env.IsStatic() { errs = multierror.Append(errs, errors.Errorf("step %d includes one or more dynamic environment variables, which are unsupported in this Sourcegraph version", i+1)) @@ -186,15 +160,15 @@ func ParseBatchSpec(data []byte, features FeatureFlags) (*BatchSpec, error) { errs = multierror.Append(errs, errors.New("batch spec includes steps but no changesetTemplate")) } - if spec.TransformChanges != nil && !features.AllowTransformChanges { + if spec.TransformChanges != nil && !opts.AllowTransformChanges { errs = multierror.Append(errs, errors.New("batch spec includes transformChanges, which is not supported in this Sourcegraph version")) } - if len(spec.Workspaces) != 0 && !features.AllowTransformChanges { + if len(spec.Workspaces) != 0 && !opts.AllowTransformChanges { errs = multierror.Append(errs, errors.New("batch spec includes workspaces, which is not supported in this Sourcegraph version")) } - if !features.AllowConditionalExec { + if !opts.AllowConditionalExec { for i, step := range spec.Steps { if step.IfCondition() != "" { errs = multierror.Append(errs, fmt.Errorf( diff --git a/internal/batches/batch_spec_test.go b/internal/batches/batch_spec_test.go index 339871d318..2b16058adb 100644 --- a/internal/batches/batch_spec_test.go +++ b/internal/batches/batch_spec_test.go @@ -24,7 +24,7 @@ changesetTemplate: published: false ` - _, err := ParseBatchSpec([]byte(spec), FeatureFlags{}) + _, err := ParseBatchSpec([]byte(spec), ParseBatchSpecOptions{}) if err != nil { t.Fatalf("parsing valid spec returned error: %s", err) } @@ -41,7 +41,7 @@ steps: container: alpine:3 ` - _, err := ParseBatchSpec([]byte(spec), FeatureFlags{}) + _, err := ParseBatchSpec([]byte(spec), ParseBatchSpecOptions{}) if err == nil { t.Fatal("no error returned") } @@ -74,7 +74,7 @@ changesetTemplate: published: false ` - _, err := ParseBatchSpec([]byte(spec), FeatureFlags{}) + _, err := ParseBatchSpec([]byte(spec), ParseBatchSpecOptions{}) if err == nil { t.Fatal("no error returned") } @@ -111,7 +111,7 @@ changesetTemplate: published: false ` - _, err := ParseBatchSpec([]byte(spec), FeatureFlags{}) + _, err := ParseBatchSpec([]byte(spec), ParseBatchSpecOptions{}) if err == nil { t.Fatal("no error returned") } @@ -159,7 +159,7 @@ changesetTemplate: {raw: `foobar`, want: "foobar"}, } { spec := fmt.Sprintf(specTemplate, tt.raw) - batchSpec, err := ParseBatchSpec([]byte(spec), FeatureFlags{AllowConditionalExec: true}) + batchSpec, err := ParseBatchSpec([]byte(spec), ParseBatchSpecOptions{AllowConditionalExec: true}) if err != nil { t.Fatal(err) } diff --git a/internal/batches/docker/image.go b/internal/batches/docker/image.go index 09ddc86f9c..9b340913f5 100644 --- a/internal/batches/docker/image.go +++ b/internal/batches/docker/image.go @@ -39,9 +39,7 @@ type image struct { // hard to prevent performing the same operations on the same image over and // over, since some of them are expensive. - digest string - digestErr error - digestOnce sync.Once + digest string ensureErr error ensureOnce sync.Once @@ -51,53 +49,53 @@ type image struct { uidGidOnce sync.Once } -// Digest gets and returns the content digest for the image. Note that this is -// different from the "distribution digest" (which is what you can use to -// specify an image to `docker run`, as in `my/image@sha256:xxx`). We need to -// use the content digest because the distribution digest is only computed for -// images that have been pulled from or pushed to a registry. See -// https://windsock.io/explaining-docker-image-ids/ under "A Final Twist" for a -// good explanation. +// Digest returns the content digest for the image. Note that this is different +// from the "distribution digest" (which is what you can use to specify an image +// to `docker run`, as in `my/image@sha256:xxx`). We need to use the content digest +// because the distribution digest is only computed for images that have been pulled +// from or pushed to a registry. See https://windsock.io/explaining-docker-image-ids/ +// under "A Final Twist" for a good explanation. func (image *image) Digest(ctx context.Context) (string, error) { - image.digestOnce.Do(func() { - image.digest, image.digestErr = func() (string, error) { - if err := image.Ensure(ctx); err != nil { - return "", err - } - - // TODO!(sqs): is image id the right thing to use here? it is NOT - // the digest. but the digest is not calculated for all images - // (unless they are pulled/pushed from/to a registry), see - // https://github.com/moby/moby/issues/32016. - out, err := exec.CommandContext(ctx, "docker", "image", "inspect", "--format", "{{.Id}}", "--", image.name).CombinedOutput() - if err != nil { - return "", errors.Wrapf(err, "inspecting docker image: %s", string(bytes.TrimSpace(out))) - } - id := string(bytes.TrimSpace(out)) - if id == "" { - return "", errors.Errorf("unexpected empty docker image content ID for %q", image.name) - } - return id, nil - }() - }) - - return image.digest, image.digestErr + ensureErr := image.Ensure(ctx) + return image.digest, ensureErr } // Ensure ensures that the image has been pulled by Docker. Note that it does // not attempt to pull a newer version of the image if it exists locally. func (image *image) Ensure(ctx context.Context) error { image.ensureOnce.Do(func() { - image.ensureErr = func() error { + image.ensureErr = func() (err error) { + inspectDigest := func() (string, error) { + // TODO!(sqs): is image id the right thing to use here? it is NOT + // the digest. but the digest is not calculated for all images + // (unless they are pulled/pushed from/to a registry), see + // https://github.com/moby/moby/issues/32016. + out, err := exec.CommandContext(ctx, "docker", "image", "inspect", "--format", "{{ .Id }}", image.name).CombinedOutput() + id := string(bytes.TrimSpace(out)) + return id, err + } + // docker image inspect will return a non-zero exit code if the image and // tag don't exist locally, regardless of the format. - if err := exec.CommandContext(ctx, "docker", "image", "inspect", "--format", "1", image.name).Run(); err != nil { + var digest string + if digest, err = inspectDigest(); err != nil { // Let's try pulling the image. if err := exec.CommandContext(ctx, "docker", "image", "pull", image.name).Run(); err != nil { return errors.Wrap(err, "pulling image") } + // And try again to get the image digest. + digest, err = inspectDigest() + if err != nil { + return errors.Wrap(err, "not found after pulling image") + } } + if digest == "" { + return errors.Errorf("unexpected empty docker image content ID for %q", image.name) + } + + image.digest = digest + return nil }() }) diff --git a/internal/batches/docker/image_test.go b/internal/batches/docker/image_test.go index 1ae31bc381..d8d5d91323 100644 --- a/internal/batches/docker/image_test.go +++ b/internal/batches/docker/image_test.go @@ -18,32 +18,33 @@ func TestImage_Digest(t *testing.T) { wantErr bool }{ "success": { - expectations: digestSuccess("foo", "bar"), + expectations: []*expect.Expectation{inspectSuccess("foo", "digest")}, image: &image{name: "foo"}, - want: "bar", + want: "digest", }, "inspect invalid output": { - expectations: append( - ensureSuccess("foo"), - expect.NewGlob( - expect.Success, - // Note the awkward escaping because these arguments are matched by - // glob. - "docker", "image", "inspect", "--format", `\{\{.Id}}`, "--", "foo", - ), - ), + expectations: []*expect.Expectation{ + inspectSuccess("foo", ""), + }, image: &image{name: "foo"}, wantErr: true, }, - "inspect failure": { - expectations: digestFailure("foo"), - image: &image{name: "foo"}, - wantErr: true, + "inspect failure first attempt": { + expectations: []*expect.Expectation{ + inspectFailure("foo"), + pullSuccess("foo"), + inspectSuccess("foo", "digest"), + }, + image: &image{name: "foo"}, + want: "digest", }, - "ensure failure": { - expectations: ensureFailure("foo"), - image: &image{name: "foo"}, - wantErr: true, + "pull failure": { + expectations: []*expect.Expectation{ + inspectFailure("foo"), + pullFailure("foo"), + }, + image: &image{name: "foo"}, + wantErr: true, }, } { t.Run(name, func(t *testing.T) { @@ -86,29 +87,26 @@ func TestImage_Ensure(t *testing.T) { wantErr bool }{ "no pull required": { - expectations: ensureSuccess("foo"), + expectations: []*expect.Expectation{inspectSuccess("foo", "digest")}, image: &image{name: "foo"}, wantErr: false, }, "pull required": { expectations: []*expect.Expectation{ - expect.NewGlob( - // docker image inspect returns 1 for non-existent images. - expect.Behaviour{ExitCode: 1}, - "docker", "image", "inspect", "--format", "1", "foo", - ), - expect.NewGlob( - expect.Success, - "docker", "image", "pull", "foo", - ), + inspectFailure("foo"), + pullSuccess("foo"), + inspectSuccess("foo", "digest"), }, image: &image{name: "foo"}, wantErr: false, }, "pull failed": { - expectations: ensureFailure("foo"), - image: &image{name: "foo"}, - wantErr: true, + expectations: []*expect.Expectation{ + inspectFailure("foo"), + pullFailure("foo"), + }, + image: &image{name: "foo"}, + wantErr: true, }, } { t.Run(name, func(t *testing.T) { @@ -147,20 +145,20 @@ func TestImage_UIDGID(t *testing.T) { wantErr bool }{ "success": { - expectations: append( - digestSuccess("foo", "bar"), + expectations: []*expect.Expectation{ + inspectSuccess("foo", "bar"), uidGid("bar", expect.Behaviour{Stdout: []byte("1000\n2000\n")}), - ), + }, image: &image{name: "foo"}, want: UIDGID{UID: 1000, GID: 2000}, }, // We should also make sure 0 works. Sometimes it's easy to miss. Just // ask the Romans. "success with zeroes": { - expectations: append( - digestSuccess("foo", "bar"), + expectations: []*expect.Expectation{ + inspectSuccess("foo", "bar"), uidGid("bar", expect.Behaviour{Stdout: []byte("0\n0\n")}), - ), + }, image: &image{name: "foo"}, want: UIDGID{UID: 0, GID: 0}, }, @@ -168,49 +166,49 @@ func TestImage_UIDGID(t *testing.T) { // signedness of pid_t and gid_t. We don't really have a reason to // disallow it. "success with negative IDs": { - expectations: append( - digestSuccess("foo", "bar"), + expectations: []*expect.Expectation{ + inspectSuccess("foo", "bar"), uidGid("bar", expect.Behaviour{Stdout: []byte("-1000\n-2000\n")}), - ), + }, image: &image{name: "foo"}, want: UIDGID{UID: -1000, GID: -2000}, }, // This is technically invalid, but should still succeed. Postel's Law // and all that. "success without trailing newline": { - expectations: append( - digestSuccess("foo", "bar"), + expectations: []*expect.Expectation{ + inspectSuccess("foo", "bar"), uidGid("bar", expect.Behaviour{Stdout: []byte("1000\n2000")}), - ), + }, image: &image{name: "foo"}, want: UIDGID{UID: 1000, GID: 2000}, }, // As above, this is invalid, but we should still handle it. "success with extra data": { - expectations: append( - digestSuccess("foo", "bar"), + expectations: []*expect.Expectation{ + inspectSuccess("foo", "bar"), uidGid("bar", expect.Behaviour{Stdout: []byte("1000\n2000\n3000\n")}), - ), + }, image: &image{name: "foo"}, want: UIDGID{UID: 1000, GID: 2000}, }, // Now for some interesting failure cases. "invalid output": { - expectations: append( - digestSuccess("foo", "bar"), + expectations: []*expect.Expectation{ + inspectSuccess("foo", "bar"), uidGid("bar", expect.Behaviour{Stdout: []byte("")}), - ), + }, image: &image{name: "foo"}, wantErr: true, }, // This is ripped from the headlines^WDocker. "missing id binary": { - expectations: append( - digestSuccess("foo", "bar"), + expectations: []*expect.Expectation{ + inspectSuccess("foo", "bar"), uidGid("bar", expect.Behaviour{ ExitCode: 127, Stderr: []byte("sh: id: not found")}), - ), + }, image: &image{name: "foo"}, wantErr: true, }, @@ -218,34 +216,37 @@ func TestImage_UIDGID(t *testing.T) { // probably an oversight, but we shouldn't allow string IDs. That would // be a bridge too far. "string uid": { - expectations: append( - digestSuccess("foo", "bar"), + expectations: []*expect.Expectation{ + inspectSuccess("foo", "bar"), uidGid("bar", expect.Behaviour{Stdout: []byte("X\n2000\n")}), - ), + }, image: &image{name: "foo"}, wantErr: true, }, "string gid": { - expectations: append( - digestSuccess("foo", "bar"), + expectations: []*expect.Expectation{ + inspectSuccess("foo", "bar"), uidGid("bar", expect.Behaviour{Stdout: []byte("1000\nX\n")}), - ), + }, image: &image{name: "foo"}, wantErr: true, }, // Now for some more run of the mill failures. "docker run failure": { - expectations: append( - digestSuccess("foo", "bar"), + expectations: []*expect.Expectation{ + inspectSuccess("foo", "bar"), uidGid("bar", expect.Behaviour{ExitCode: 1}), - ), + }, image: &image{name: "foo"}, wantErr: true, }, - "digest failure": { - expectations: digestFailure("foo"), - image: &image{name: "foo"}, - wantErr: true, + "inspect and pull failure": { + expectations: []*expect.Expectation{ + inspectFailure("foo"), + pullFailure("foo"), + }, + image: &image{name: "foo"}, + wantErr: true, }, } { t.Run(name, func(t *testing.T) { @@ -288,54 +289,35 @@ func TestUIDGID(t *testing.T) { } // Set up some helper functions for expectations we'll be reusing. - -func digestFailure(name string) []*expect.Expectation { - return append( - ensureSuccess(name), - expect.NewGlob( - expect.Behaviour{ExitCode: 1}, - // Note the awkward escaping because these arguments are matched by - // glob. - "docker", "image", "inspect", "--format", `\{\{.Id}}`, "--", name, - ), +func inspectSuccess(name, digest string) *expect.Expectation { + return expect.NewGlob( + expect.Behaviour{Stdout: []byte(digest + "\n")}, + // Note the awkward escaping because these arguments are + // matched by glob. + "docker", "image", "inspect", "--format", `\{\{ .Id }}`, name, ) } -func digestSuccess(name, digest string) []*expect.Expectation { - return append( - ensureSuccess(name), - expect.NewGlob( - expect.Behaviour{Stdout: []byte(digest + "\n")}, - // Note the awkward escaping because these arguments are - // matched by glob. - "docker", "image", "inspect", "--format", `\{\{.Id}}`, "--", name, - ), +func inspectFailure(name string) *expect.Expectation { + return expect.NewGlob( + // docker image inspect returns 1 for non-existent images. + expect.Behaviour{ExitCode: 1}, + "docker", "image", "inspect", "--format", `\{\{ .Id }}`, name, ) } -func ensureFailure(name string) []*expect.Expectation { - return []*expect.Expectation{ - expect.NewGlob( - // docker image inspect returns 1 for non-existent images. - expect.Behaviour{ExitCode: 1}, - "docker", "image", "inspect", "--format", "1", name, - ), - expect.NewGlob( - expect.Behaviour{ExitCode: 1}, - "docker", "image", "pull", name, - ), - } +func pullFailure(name string) *expect.Expectation { + return expect.NewGlob( + expect.Behaviour{ExitCode: 1}, + "docker", "image", "pull", name, + ) } -// ensureSuccess only provides the short circuit success path for Ensure() (that -// is, where no pull is required). -func ensureSuccess(name string) []*expect.Expectation { - return []*expect.Expectation{ - expect.NewGlob( - expect.Success, - "docker", "image", "inspect", "--format", "1", name, - ), - } +func pullSuccess(name string) *expect.Expectation { + return expect.NewGlob( + expect.Behaviour{ExitCode: 0}, + "docker", "image", "pull", name, + ) } func uidGid(digest string, behaviour expect.Behaviour) *expect.Expectation { diff --git a/internal/batches/executor/coordinator.go b/internal/batches/executor/coordinator.go index dc44d46a3a..b3d2e06fac 100644 --- a/internal/batches/executor/coordinator.go +++ b/internal/batches/executor/coordinator.go @@ -10,6 +10,7 @@ import ( "github.com/pkg/errors" "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/batches" + "github.com/sourcegraph/src-cli/internal/batches/docker" "github.com/sourcegraph/src-cli/internal/batches/graphql" "github.com/sourcegraph/src-cli/internal/batches/log" "github.com/sourcegraph/src-cli/internal/batches/workspace" @@ -32,10 +33,12 @@ type Coordinator struct { } type repoNameResolver func(ctx context.Context, name string) (*graphql.Repository, error) +type imageEnsurer func(ctx context.Context, name string) (docker.Image, error) type NewCoordinatorOpts struct { // Dependencies ResolveRepoName repoNameResolver + EnsureImage imageEnsurer Creator workspace.Creator Client api.Client @@ -62,9 +65,10 @@ func NewCoordinator(opts NewCoordinatorOpts) *Coordinator { logManager := log.NewManager(opts.TempDir, opts.KeepLogs) exec := newExecutor(newExecutorOpts{ - Fetcher: batches.NewRepoFetcher(opts.Client, opts.CacheDir, opts.CleanArchives), - Creator: opts.Creator, - Logger: logManager, + Fetcher: batches.NewRepoFetcher(opts.Client, opts.CacheDir, opts.CleanArchives), + EnsureImage: opts.EnsureImage, + Creator: opts.Creator, + Logger: logManager, AutoAuthorDetails: opts.Features.IncludeAutoAuthorDetails, Parallelism: opts.Parallelism, diff --git a/internal/batches/executor/executor.go b/internal/batches/executor/executor.go index 3d25486804..41fd052fb7 100644 --- a/internal/batches/executor/executor.go +++ b/internal/batches/executor/executor.go @@ -49,9 +49,10 @@ type taskResult struct { type newExecutorOpts struct { // Dependencies - Creator workspace.Creator - Fetcher batches.RepoFetcher - Logger log.LogManager + Creator workspace.Creator + Fetcher batches.RepoFetcher + EnsureImage imageEnsurer + Logger log.LogManager // Config AutoAuthorDetails bool @@ -167,10 +168,11 @@ func (x *executor) do(ctx context.Context, task *Task, ui TaskExecutionUI) (err // Actually execute the steps. opts := &executionOpts{ - task: task, - logger: log, - wc: x.opts.Creator, - tempDir: x.opts.TempDir, + task: task, + logger: log, + wc: x.opts.Creator, + ensureImage: x.opts.EnsureImage, + tempDir: x.opts.TempDir, reportProgress: func(currentlyExecuting string) { ui.TaskCurrentlyExecuting(task, currentlyExecuting) }, diff --git a/internal/batches/executor/executor_test.go b/internal/batches/executor/executor_test.go index 178b6f0d78..132c6342f7 100644 --- a/internal/batches/executor/executor_test.go +++ b/internal/batches/executor/executor_test.go @@ -15,9 +15,11 @@ import ( "time" "github.com/google/go-cmp/cmp" + "github.com/pkg/errors" "github.com/sourcegraph/go-diff/diff" "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/batches" + "github.com/sourcegraph/src-cli/internal/batches/docker" "github.com/sourcegraph/src-cli/internal/batches/git" "github.com/sourcegraph/src-cli/internal/batches/mock" "github.com/sourcegraph/src-cli/internal/batches/workspace" @@ -299,12 +301,10 @@ func TestExecutor_Integration(t *testing.T) { for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { // Make sure that the steps and tasks are setup properly - for i := range tc.steps { - tc.steps[i].SetImage(&mock.Image{ - RawDigest: tc.steps[i].Container, - }) + images := make(map[string]docker.Image) + for _, step := range tc.steps { + images[step.Container] = &mock.Image{RawDigest: step.Container} } - for _, task := range tc.tasks { task.BatchChangeAttributes = defaultBatchChangeAttributes task.Steps = tc.steps @@ -338,9 +338,10 @@ func TestExecutor_Integration(t *testing.T) { // Setup executor opts := newExecutorOpts{ - Creator: workspace.NewCreator(context.Background(), "bind", testTempDir, testTempDir, []batches.Step{}), - Fetcher: batches.NewRepoFetcher(client, testTempDir, false), - Logger: mock.LogNoOpManager{}, + Creator: workspace.NewCreator(context.Background(), "bind", testTempDir, testTempDir, images), + Fetcher: batches.NewRepoFetcher(client, testTempDir, false), + Logger: mock.LogNoOpManager{}, + EnsureImage: imageMapEnsurer(images), TempDir: testTempDir, Parallelism: runtime.GOMAXPROCS(0), @@ -680,20 +681,21 @@ func testExecuteTasks(t *testing.T, tasks []*Task, archives ...mock.RepoArchive) var clientBuffer bytes.Buffer client := api.NewClient(api.ClientOpts{Endpoint: ts.URL, Out: &clientBuffer}) - // Prepare tasks + // Prepare images + // + images := make(map[string]docker.Image) for _, t := range tasks { - for i := range t.Steps { - t.Steps[i].SetImage(&mock.Image{ - RawDigest: t.Steps[i].Container, - }) + for _, step := range t.Steps { + images[step.Container] = &mock.Image{RawDigest: step.Container} } } // Setup executor executor := newExecutor(newExecutorOpts{ - Creator: workspace.NewCreator(context.Background(), "bind", testTempDir, testTempDir, []batches.Step{}), - Fetcher: batches.NewRepoFetcher(client, testTempDir, false), - Logger: mock.LogNoOpManager{}, + Creator: workspace.NewCreator(context.Background(), "bind", testTempDir, testTempDir, images), + Fetcher: batches.NewRepoFetcher(client, testTempDir, false), + Logger: mock.LogNoOpManager{}, + EnsureImage: imageMapEnsurer(images), TempDir: testTempDir, Parallelism: runtime.GOMAXPROCS(0), @@ -703,3 +705,12 @@ func testExecuteTasks(t *testing.T, tasks []*Task, archives ...mock.RepoArchive) executor.Start(context.Background(), tasks, newDummyTaskExecutionUI()) return executor.Wait(context.Background()) } + +func imageMapEnsurer(m map[string]docker.Image) imageEnsurer { + return func(_ context.Context, container string) (docker.Image, error) { + if i, ok := m[container]; ok { + return i, nil + } + return nil, errors.New(fmt.Sprintf("image for %s not found", container)) + } +} diff --git a/internal/batches/executor/run_steps.go b/internal/batches/executor/run_steps.go index fe3fdc1b06..57ee07dfe4 100644 --- a/internal/batches/executor/run_steps.go +++ b/internal/batches/executor/run_steps.go @@ -53,7 +53,8 @@ type executionResult struct { } type executionOpts struct { - wc workspace.Creator + wc workspace.Creator + ensureImage imageEnsurer task *Task @@ -152,8 +153,16 @@ func runSteps(ctx context.Context, opts *executionOpts) (result executionResult, opts.reportProgress(fmt.Sprintf("Skipping step %d", i+1)) continue } - - stdoutBuffer, stderrBuffer, err := executeSingleStep(ctx, opts, workspace, i, step, &stepContext) + // We need to grab the digest for the exact image we're using. + img, err := opts.ensureImage(ctx, step.Container) + if err != nil { + return execResult, nil, err + } + digest, err := img.Digest(ctx) + if err != nil { + return execResult, nil, err + } + stdoutBuffer, stderrBuffer, err := executeSingleStep(ctx, opts, workspace, i, step, digest, &stepContext) if err != nil { return execResult, nil, err } @@ -210,6 +219,7 @@ func executeSingleStep( workspace workspace.Workspace, i int, step batches.Step, + imageDigest string, stepContext *StepContext, ) (bytes.Buffer, bytes.Buffer, error) { // ---------- @@ -223,22 +233,17 @@ func executeSingleStep( } defer cleanup() - // We need to grab the digest for the exact image we're using. - digest, err := step.ImageDigest(ctx) - if err != nil { - return bytes.Buffer{}, bytes.Buffer{}, errors.Wrapf(err, "getting digest for %v", step.DockerImage()) - } - // For now, we only support shell scripts provided via the Run field. - shell, containerTemp, err := probeImageForShell(ctx, digest) + shell, containerTemp, err := probeImageForShell(ctx, imageDigest) if err != nil { - return bytes.Buffer{}, bytes.Buffer{}, errors.Wrapf(err, "probing image %q for shell", step.DockerImage()) + return bytes.Buffer{}, bytes.Buffer{}, errors.Wrapf(err, "probing image %q for shell", step.Container) } runScriptFile, runScript, cleanup, err := createRunScriptFile(ctx, opts.tempDir, step.Run, stepContext) if err != nil { return bytes.Buffer{}, bytes.Buffer{}, err } + defer cleanup() // Parse and render the step.Files. filesToMount, cleanup, err := createFilesToMount(opts.tempDir, step, stepContext) @@ -295,7 +300,7 @@ func executeSingleStep( args = append(args, "--entrypoint", shell) cmd := exec.CommandContext(ctx, "docker", args...) - cmd.Args = append(cmd.Args, "--", digest, containerTemp) + cmd.Args = append(cmd.Args, "--", imageDigest, containerTemp) if dir := workspace.WorkDir(); dir != nil { cmd.Dir = *dir } diff --git a/internal/batches/executor/task_builder.go b/internal/batches/executor/task_builder.go index 034c37a8bd..5219ed27dd 100644 --- a/internal/batches/executor/task_builder.go +++ b/internal/batches/executor/task_builder.go @@ -13,29 +13,18 @@ type DirectoryFinder interface { FindDirectoriesInRepos(ctx context.Context, fileName string, repos ...*graphql.Repository) (map[*graphql.Repository][]string, error) } -type TaskBuilder struct { +type taskBuilder struct { spec *batches.BatchSpec finder DirectoryFinder - - initializedWorkspaceConfigs []batches.WorkspaceConfiguration } -func NewTaskBuilder(spec *batches.BatchSpec, finder DirectoryFinder) (*TaskBuilder, error) { - tb := &TaskBuilder{spec: spec, finder: finder} - - for _, conf := range tb.spec.Workspaces { - g, err := glob.Compile(conf.In) - if err != nil { - return nil, err - } - conf.SetGlob(g) - tb.initializedWorkspaceConfigs = append(tb.initializedWorkspaceConfigs, conf) - } - - return tb, nil +// BuildTasks returns tasks for all the workspaces determined for the given spec. +func BuildTasks(ctx context.Context, spec *batches.BatchSpec, finder DirectoryFinder, repos []*graphql.Repository) ([]*Task, error) { + tb := &taskBuilder{spec: spec, finder: finder} + return tb.buildAll(ctx, repos) } -func (tb *TaskBuilder) buildTask(r *graphql.Repository, path string, onlyWorkspace bool) (*Task, bool, error) { +func (tb *taskBuilder) buildTask(r *graphql.Repository, path string, onlyWorkspace bool) (*Task, bool, error) { stepCtx := &StepContext{ Repository: *r, BatchChange: BatchChangeAttributes{ @@ -90,9 +79,9 @@ func (tb *TaskBuilder) buildTask(r *graphql.Repository, path string, onlyWorkspa }, true, nil } -func (tb *TaskBuilder) BuildAll(ctx context.Context, repos []*graphql.Repository) ([]*Task, error) { +func (tb *taskBuilder) buildAll(ctx context.Context, repos []*graphql.Repository) ([]*Task, error) { // Find workspaces in repositories, if configured - workspaces, root, err := tb.findWorkspaces(ctx, repos, tb.initializedWorkspaceConfigs) + workspaces, root, err := tb.findWorkspaces(ctx, repos, tb.spec.Workspaces) if err != nil { return nil, err } @@ -137,7 +126,7 @@ type repoWorkspaces struct { // workspaces. root contains the repositories that didn't match a config. // If the user didn't specify any workspaces, the repositories are returned as // root repositories. -func (tb *TaskBuilder) findWorkspaces( +func (tb *taskBuilder) findWorkspaces( ctx context.Context, repos []*graphql.Repository, configs []batches.WorkspaceConfiguration, @@ -146,13 +135,22 @@ func (tb *TaskBuilder) findWorkspaces( return nil, repos, nil } + workspaceMatchers := make(map[batches.WorkspaceConfiguration]glob.Glob) + for _, conf := range tb.spec.Workspaces { + g, err := glob.Compile(conf.In) + if err != nil { + return nil, nil, err + } + workspaceMatchers[conf] = g + } + matched := map[int][]*graphql.Repository{} for _, repo := range repos { found := false for idx, conf := range configs { - if !conf.Matches(repo.Name) { + if !workspaceMatchers[conf].Match(repo.Name) { continue } diff --git a/internal/batches/executor/task_builder_test.go b/internal/batches/executor/task_builder_test.go index c2d41819f8..44c80cb7b8 100644 --- a/internal/batches/executor/task_builder_test.go +++ b/internal/batches/executor/task_builder_test.go @@ -120,10 +120,7 @@ func TestTaskBuilder_BuildTask_IfConditions(t *testing.T) { for name, tt := range tests { t.Run(name, func(t *testing.T) { - builder, err := NewTaskBuilder(tt.spec, nil) - if err != nil { - t.Fatal(err) - } + builder := &taskBuilder{spec: tt.spec} task, ok, err := builder.buildTask(testRepo1, "", false) if err != nil { t.Fatalf("unexpected err: %s", err) @@ -266,12 +263,7 @@ func TestTaskBuilder_BuildAll_Workspaces(t *testing.T) { for name, tt := range tests { t.Run(name, func(t *testing.T) { finder := &mockDirectoryFinder{results: tt.finderResults} - tb, err := NewTaskBuilder(tt.spec, finder) - if err != nil { - t.Fatal(err) - } - - tasks, err := tb.BuildAll(context.Background(), repos) + tasks, err := BuildTasks(context.Background(), tt.spec, finder, repos) if err != nil { t.Fatalf("unexpected err: %s", err) } diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index 4124b1ee63..91f5c3d41a 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -5,8 +5,6 @@ import ( "encoding/json" "fmt" "html/template" - "io" - "io/ioutil" "os" "os/exec" "path" @@ -146,30 +144,31 @@ func (svc *Service) CreateChangesetSpec(ctx context.Context, spec *batches.Chang return graphql.ChangesetSpecID(result.CreateChangesetSpec.ID), nil } -// SetDockerImages updates the steps within the batch spec to include the exact -// content digest to be used when running each step, and ensures that all Docker -// images are available, including any required by the service itself. +// EnsureDockerImages iterates over the steps within the batch spec to ensure the +// images exist and to determine the exact content digest to be used when running +// each step, including any required by the service itself. // // Progress information is reported back to the given progress function: perc // will be a value between 0.0 and 1.0, inclusive. -func (svc *Service) SetDockerImages(ctx context.Context, spec *batches.BatchSpec, progress func(perc float64)) error { +func (svc *Service) EnsureDockerImages(ctx context.Context, spec *batches.BatchSpec, progress func(perc float64)) (map[string]docker.Image, error) { total := len(spec.Steps) + 1 progress(0) // TODO: this _really_ should be parallelised, since the image cache takes // care to only pull the same image once. + images := make(map[string]docker.Image) for i := range spec.Steps { img, err := svc.EnsureImage(ctx, spec.Steps[i].Container) if err != nil { - return err + return nil, err } - spec.Steps[i].SetImage(img) + images[spec.Steps[i].Container] = img progress(float64(i) / float64(total)) } progress(1) - return nil + return images, nil } func (svc *Service) EnsureImage(ctx context.Context, name string) (docker.Image, error) { @@ -183,18 +182,14 @@ func (svc *Service) EnsureImage(ctx context.Context, name string) (docker.Image, } func (svc *Service) BuildTasks(ctx context.Context, repos []*graphql.Repository, spec *batches.BatchSpec) ([]*executor.Task, error) { - builder, err := executor.NewTaskBuilder(spec, svc) - if err != nil { - return nil, err - } - - return builder.BuildAll(ctx, repos) + return executor.BuildTasks(ctx, spec, svc, repos) } func (svc *Service) NewCoordinator(opts executor.NewCoordinatorOpts) *executor.Coordinator { opts.ResolveRepoName = svc.resolveRepositoryName opts.Client = svc.client opts.Features = svc.features + opts.EnsureImage = svc.EnsureImage return executor.NewCoordinator(opts) } @@ -263,17 +258,16 @@ func (e *duplicateBranchesErr) Error() string { return out.String() } -func (svc *Service) ParseBatchSpec(in io.Reader) (*batches.BatchSpec, string, error) { - data, err := ioutil.ReadAll(in) - if err != nil { - return nil, "", errors.Wrap(err, "reading batch spec") - } - - spec, err := batches.ParseBatchSpec(data, svc.features) +func (svc *Service) ParseBatchSpec(data []byte) (*batches.BatchSpec, error) { + spec, err := batches.ParseBatchSpec(data, batches.ParseBatchSpecOptions{ + AllowArrayEnvironments: svc.features.AllowArrayEnvironments, + AllowTransformChanges: svc.features.AllowTransformChanges, + AllowConditionalExec: svc.features.AllowConditionalExec, + }) if err != nil { - return nil, "", errors.Wrap(err, "parsing batch spec") + return nil, errors.Wrap(err, "parsing batch spec") } - return spec, string(data), nil + return spec, nil } const exampleSpecTmpl = `name: NAME-OF-YOUR-BATCH-CHANGE diff --git a/internal/batches/workspace/volume_workspace.go b/internal/batches/workspace/volume_workspace.go index 4aae2a7bca..23f5f1fc00 100644 --- a/internal/batches/workspace/volume_workspace.go +++ b/internal/batches/workspace/volume_workspace.go @@ -21,7 +21,12 @@ import ( "github.com/sourcegraph/src-cli/internal/version" ) -type dockerVolumeWorkspaceCreator struct{ tempDir string } +type imageEnsurer func(ctx context.Context, image string) (docker.Image, error) + +type dockerVolumeWorkspaceCreator struct { + tempDir string + EnsureImage imageEnsurer +} var _ Creator = &dockerVolumeWorkspaceCreator{} @@ -37,7 +42,11 @@ func (wc *dockerVolumeWorkspaceCreator) Create(ctx context.Context, repo *graphq ug := docker.UIDGID{} if len(steps) > 0 { var err error - if ug, err = steps[0].ImageUIDGID(ctx); err != nil { + img, err := wc.EnsureImage(ctx, steps[0].Container) + if err != nil { + return nil, err + } + if ug, err = img.UIDGID(ctx); err != nil { return nil, errors.Wrap(err, "getting container UID and GID") } } diff --git a/internal/batches/workspace/volume_workspace_test.go b/internal/batches/workspace/volume_workspace_test.go index fd3e269800..74ceb349b1 100644 --- a/internal/batches/workspace/volume_workspace_test.go +++ b/internal/batches/workspace/volume_workspace_test.go @@ -58,16 +58,11 @@ func TestVolumeWorkspaceCreator(t *testing.T) { DefaultBranch: &graphql.Branch{Name: "main"}, } - stepWithImage := func(image docker.Image) batches.Step { - s := batches.Step{} - s.SetImage(image) - return s - } - for name, tc := range map[string]struct { archive *fakeRepoArchive expectations []*expect.Expectation steps []batches.Step + imageEnsurer imageEnsurer wantErr bool }{ "no steps": { @@ -104,7 +99,8 @@ func TestVolumeWorkspaceCreator(t *testing.T) { "sh", "/run.sh", ), }, - steps: []batches.Step{}, + steps: []batches.Step{}, + imageEnsurer: func(_ context.Context, _ string) (docker.Image, error) { return nil, nil }, }, "one root:root step": { expectations: []*expect.Expectation{ @@ -141,7 +137,10 @@ func TestVolumeWorkspaceCreator(t *testing.T) { ), }, steps: []batches.Step{ - stepWithImage(&mock.Image{UidGid: docker.Root}), + {}, + }, + imageEnsurer: func(_ context.Context, _ string) (docker.Image, error) { + return &mock.Image{UidGid: docker.Root}, nil }, }, "one user:user step": { @@ -179,7 +178,10 @@ func TestVolumeWorkspaceCreator(t *testing.T) { ), }, steps: []batches.Step{ - stepWithImage(&mock.Image{UidGid: docker.UIDGID{UID: 1, GID: 2}}), + {}, + }, + imageEnsurer: func(_ context.Context, _ string) (docker.Image, error) { + return &mock.Image{UidGid: docker.UIDGID{UID: 1, GID: 2}}, nil }, }, "docker volume create failure": { @@ -190,7 +192,10 @@ func TestVolumeWorkspaceCreator(t *testing.T) { ), }, steps: []batches.Step{ - stepWithImage(&mock.Image{UidGid: docker.Root}), + {}, + }, + imageEnsurer: func(_ context.Context, _ string) (docker.Image, error) { + return &mock.Image{UidGid: docker.Root}, nil }, wantErr: true, }, @@ -210,7 +215,10 @@ func TestVolumeWorkspaceCreator(t *testing.T) { ), }, steps: []batches.Step{ - stepWithImage(&mock.Image{UidGid: docker.Root}), + {}, + }, + imageEnsurer: func(_ context.Context, _ string) (docker.Image, error) { + return &mock.Image{UidGid: docker.Root}, nil }, wantErr: true, }, @@ -249,7 +257,10 @@ func TestVolumeWorkspaceCreator(t *testing.T) { ), }, steps: []batches.Step{ - stepWithImage(&mock.Image{UidGid: docker.Root}), + {}, + }, + imageEnsurer: func(_ context.Context, _ string) (docker.Image, error) { + return &mock.Image{UidGid: docker.Root}, nil }, wantErr: true, }, @@ -279,7 +290,10 @@ func TestVolumeWorkspaceCreator(t *testing.T) { ), }, steps: []batches.Step{ - stepWithImage(&mock.Image{UidGid: docker.Root}), + {}, + }, + imageEnsurer: func(_ context.Context, _ string) (docker.Image, error) { + return &mock.Image{UidGid: docker.Root}, nil }, wantErr: true, }, @@ -330,7 +344,10 @@ func TestVolumeWorkspaceCreator(t *testing.T) { ), }, steps: []batches.Step{ - stepWithImage(&mock.Image{UidGid: docker.Root}), + {}, + }, + imageEnsurer: func(_ context.Context, _ string) (docker.Image, error) { + return &mock.Image{UidGid: docker.Root}, nil }, }, } { @@ -341,6 +358,7 @@ func TestVolumeWorkspaceCreator(t *testing.T) { a = tc.archive } + wc.EnsureImage = tc.imageEnsurer w, err := wc.Create(ctx, repo, tc.steps, a) if tc.wantErr { if err == nil { diff --git a/internal/batches/workspace/workspace.go b/internal/batches/workspace/workspace.go index 887f3876a0..1dac575d78 100644 --- a/internal/batches/workspace/workspace.go +++ b/internal/batches/workspace/workspace.go @@ -4,7 +4,9 @@ import ( "context" "runtime" + "github.com/pkg/errors" "github.com/sourcegraph/src-cli/internal/batches" + "github.com/sourcegraph/src-cli/internal/batches/docker" "github.com/sourcegraph/src-cli/internal/batches/git" "github.com/sourcegraph/src-cli/internal/batches/graphql" ) @@ -57,25 +59,32 @@ const ( CreatorTypeVolume ) -func NewCreator(ctx context.Context, preference, cacheDir, tempDir string, steps []batches.Step) Creator { +func NewCreator(ctx context.Context, preference, cacheDir, tempDir string, images map[string]docker.Image) Creator { var workspaceType CreatorType if preference == "volume" { workspaceType = CreatorTypeVolume } else if preference == "bind" { workspaceType = CreatorTypeBind } else { - workspaceType = BestCreatorType(ctx, steps) + workspaceType = BestCreatorType(ctx, images) } + ensureImage := func(_ context.Context, container string) (docker.Image, error) { + img, ok := images[container] + if !ok { + return nil, errors.Errorf("image %q not found", container) + } + return img, nil + } if workspaceType == CreatorTypeVolume { - return &dockerVolumeWorkspaceCreator{tempDir: tempDir} + return &dockerVolumeWorkspaceCreator{tempDir: tempDir, EnsureImage: ensureImage} } return &dockerBindWorkspaceCreator{Dir: cacheDir} } // BestCreatorType determines the correct workspace creator type to use based // on the environment and batch change to be executed. -func BestCreatorType(ctx context.Context, steps []batches.Step) CreatorType { +func BestCreatorType(ctx context.Context, images map[string]docker.Image) CreatorType { // The basic theory here is that we have two options: bind and volume. Bind // is battle tested and always safe, but can be slow on non-Linux platforms // because bind mounts are slow. Volume is faster on those platforms, but @@ -90,10 +99,10 @@ func BestCreatorType(ctx context.Context, steps []batches.Step) CreatorType { return CreatorTypeBind } - return detectBestCreatorType(ctx, steps) + return detectBestCreatorType(ctx, images) } -func detectBestCreatorType(ctx context.Context, steps []batches.Step) CreatorType { +func detectBestCreatorType(ctx context.Context, images map[string]docker.Image) CreatorType { // OK, so we're interested in volume mode, but we need to take its // shortcomings around mixed user environments into account. // @@ -112,8 +121,8 @@ func detectBestCreatorType(ctx context.Context, steps []batches.Step) CreatorTyp // but let's keep it simple for now. var uid *int - for _, step := range steps { - ug, err := step.ImageUIDGID(ctx) + for _, image := range images { + ug, err := image.UIDGID(ctx) if err != nil { // An error here likely indicates that `id` isn't available on the // path. That's OK: let's not make any assumptions at this point diff --git a/internal/batches/workspace/workspace_test.go b/internal/batches/workspace/workspace_test.go index 57c285a3b7..eca866569c 100644 --- a/internal/batches/workspace/workspace_test.go +++ b/internal/batches/workspace/workspace_test.go @@ -6,10 +6,8 @@ import ( "testing" "github.com/pkg/errors" - "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/docker" "github.com/sourcegraph/src-cli/internal/batches/mock" - "github.com/sourcegraph/src-cli/internal/exec/expect" ) func TestBestWorkspaceCreator(t *testing.T) { @@ -20,12 +18,8 @@ func TestBestWorkspaceCreator(t *testing.T) { return docker.UIDGID{UID: uid, GID: gid} } - type imageBehaviour struct { - image string - behaviour expect.Behaviour - } for name, tc := range map[string]struct { - images []docker.Image + images map[string]docker.Image want CreatorType }{ "nil steps": { @@ -33,53 +27,45 @@ func TestBestWorkspaceCreator(t *testing.T) { want: CreatorTypeVolume, }, "no steps": { - images: []docker.Image{}, + images: map[string]docker.Image{}, want: CreatorTypeVolume, }, "root": { - images: []docker.Image{ - &mock.Image{UidGid: uidGid(0, 0)}, + images: map[string]docker.Image{ + "image1": &mock.Image{UidGid: uidGid(0, 0)}, }, want: CreatorTypeVolume, }, "same user": { - images: []docker.Image{ - &mock.Image{UidGid: uidGid(1000, 1000)}, - &mock.Image{UidGid: uidGid(1000, 1000)}, + images: map[string]docker.Image{ + "image1": &mock.Image{UidGid: uidGid(1000, 1000)}, + "image2": &mock.Image{UidGid: uidGid(1000, 1000)}, }, want: CreatorTypeVolume, }, "different user": { - images: []docker.Image{ - &mock.Image{UidGid: uidGid(1000, 1000)}, - &mock.Image{UidGid: uidGid(0, 0)}, + images: map[string]docker.Image{ + "image1": &mock.Image{UidGid: uidGid(1000, 1000)}, + "image2": &mock.Image{UidGid: uidGid(0, 0)}, }, want: CreatorTypeBind, }, "id error": { - images: []docker.Image{ - &mock.Image{UidGidErr: errors.New("foo")}, + images: map[string]docker.Image{ + "image1": &mock.Image{UidGidErr: errors.New("foo")}, }, want: CreatorTypeBind, }, } { t.Run(name, func(t *testing.T) { - var steps []batches.Step - if tc.images != nil { - steps = make([]batches.Step, len(tc.images)) - for i, image := range tc.images { - steps[i].SetImage(image) - } - } - if isOverridden { // This is an overridden platform, so the workspace type will // always be bind from bestWorkspaceCreator(). - if have, want := BestCreatorType(ctx, steps), CreatorTypeBind; have != want { + if have, want := BestCreatorType(ctx, tc.images), CreatorTypeBind; have != want { t.Errorf("unexpected creator type on overridden platform: have=%d want=%d", have, want) } } else { - if have := BestCreatorType(ctx, steps); have != tc.want { + if have := BestCreatorType(ctx, tc.images); have != tc.want { t.Errorf("unexpected creator type on non-overridden platform: have=%d want=%d", have, tc.want) } } @@ -87,7 +73,7 @@ func TestBestWorkspaceCreator(t *testing.T) { // Regardless of what bestWorkspaceCreator() would have done, let's // test that the right thing happens regardless if detection were to // actually occur. - have := detectBestCreatorType(ctx, steps) + have := detectBestCreatorType(ctx, tc.images) if have != tc.want { t.Errorf("unexpected creator type: have=%d want=%d", have, tc.want) } From 5e54f37e80b5a132fea00fbc7d7c089d079d54f6 Mon Sep 17 00:00:00 2001 From: Stefan Hengl Date: Mon, 23 Aug 2021 15:18:23 +0200 Subject: [PATCH 010/647] test: don't rely on root being a git repo (#584) The test `TestInferRepo` unnecesarily depends on the root being a git repository. This change updates `TestInferRepo` to create a fresh git repo in a temporary dir. Why? I want to add src-cli to the nixos package repository. During the build stage, nixos downloads a tar of the repo. The tar, however, is not a git repo and thus `TestInferRepo` fails. --- internal/codeintel/gitutil_test.go | 30 +++++++++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/internal/codeintel/gitutil_test.go b/internal/codeintel/gitutil_test.go index e319a9fce3..893f790a2a 100644 --- a/internal/codeintel/gitutil_test.go +++ b/internal/codeintel/gitutil_test.go @@ -2,18 +2,42 @@ package codeintel import ( "fmt" + "os" "path/filepath" "testing" ) func TestInferRepo(t *testing.T) { - repo, err := InferRepo() + cur, err := os.Getwd() + if err != nil { + t.Fatal(err) + } + defer os.Chdir(cur) + + tempDir := t.TempDir() + err = os.Chdir(tempDir) + if err != nil { + t.Fatal(err) + } + + _, err = runGitCommand("init") + if err != nil { + t.Fatal(err) + } + + want := "github.com/a/b" + + _, err = runGitCommand("remote", "add", "origin", want) + if err != nil { + t.Fatal(err) + } + got, err := InferRepo() if err != nil { t.Fatalf("unexpected error inferring repo: %s", err) } - if repo != "github.com/sourcegraph/src-cli" { - t.Errorf("unexpected remote repo. want=%q have=%q", "github.com/sourcegraph/src-cli", repo) + if got != want { + t.Errorf("unexpected remote repo. want=%q have=%q", want, got) } } From e505af8982b6d4514038c4d8797d44d3c5dc712a Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Mon, 23 Aug 2021 16:20:59 +0200 Subject: [PATCH 011/647] Move batch spec type and parser into shared lib (#583) --- cmd/src/batch_common.go | 3 +- go.mod | 3 +- go.sum | 7 +- internal/batches/batch_spec.go | 193 ---------- internal/batches/batch_spec_test.go | 173 --------- internal/batches/executor/changeset_specs.go | 9 +- .../batches/executor/changeset_specs_test.go | 27 +- internal/batches/executor/coordinator.go | 3 +- internal/batches/executor/coordinator_test.go | 25 +- internal/batches/executor/execution_cache.go | 4 +- .../batches/executor/execution_cache_test.go | 8 +- internal/batches/executor/executor_test.go | 33 +- internal/batches/executor/main_test.go | 8 +- internal/batches/executor/run_steps.go | 8 +- internal/batches/executor/task.go | 9 +- internal/batches/executor/task_builder.go | 12 +- .../batches/executor/task_builder_test.go | 78 ++-- internal/batches/service/service.go | 15 +- internal/batches/service/service_test.go | 9 +- internal/batches/ui/json_lines.go | 3 +- internal/batches/workspace/bind_workspace.go | 3 +- .../batches/workspace/volume_workspace.go | 3 +- .../workspace/volume_workspace_test.go | 20 +- internal/batches/workspace/workspace.go | 3 +- schema/batch_spec.schema.json | 342 ----------------- schema/batch_spec_stringdata.go | 348 ------------------ schema/gen.go | 4 - schema/stringdata.go | 51 --- 28 files changed, 152 insertions(+), 1252 deletions(-) delete mode 100644 internal/batches/batch_spec.go delete mode 100644 internal/batches/batch_spec_test.go delete mode 100644 schema/batch_spec.schema.json delete mode 100644 schema/batch_spec_stringdata.go delete mode 100644 schema/gen.go delete mode 100644 schema/stringdata.go diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index 79edb7a6ba..def1cbab20 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -16,6 +16,7 @@ import ( "github.com/hashicorp/go-multierror" "github.com/pkg/errors" + batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/executor" @@ -366,7 +367,7 @@ func executeBatchSpec(ctx context.Context, opts executeBatchSpecOpts) (err error // parseBatchSpec parses and validates the given batch spec. If the spec has // validation errors, they are returned. -func parseBatchSpec(file *string, svc *service.Service) (*batches.BatchSpec, string, error) { +func parseBatchSpec(file *string, svc *service.Service) (*batcheslib.BatchSpec, string, error) { f, err := batchOpenFileFlag(file) if err != nil { return nil, "", err diff --git a/go.mod b/go.mod index ce968ab167..594acb6327 100644 --- a/go.mod +++ b/go.mod @@ -21,9 +21,8 @@ require ( github.com/sourcegraph/batch-change-utils v0.0.0-20210708162152-c9f35b905d94 github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf - github.com/sourcegraph/sourcegraph/lib v0.0.0-20210628190057-faa35110fad5 + github.com/sourcegraph/sourcegraph/lib v0.0.0-20210823135647-4e945b8aa8d5 github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect - github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect golang.org/x/net v0.0.0-20210614182718-04defd469f4e gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7 diff --git a/go.sum b/go.sum index 8c324a0cea..4648795d39 100644 --- a/go.sum +++ b/go.sum @@ -243,8 +243,8 @@ github.com/sourcegraph/go-diff v0.6.1 h1:hmA1LzxW0n1c3Q4YbrFgg4P99GSnebYa3x8gr0H github.com/sourcegraph/go-diff v0.6.1/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20210628190057-faa35110fad5 h1:xRQIz6tTSQHltaT44uq1pHfvoVpzCw8VwSzgzMVnVCA= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20210628190057-faa35110fad5/go.mod h1:h2lVqcc2TjPyDq0fD8iA4ns+aayL1lY48HJNg86+0fY= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20210823135647-4e945b8aa8d5 h1:3wxr60w288nXNRzjjrEjEEgU6LUi/QV5CpyHNmHfyEI= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20210823135647-4e945b8aa8d5/go.mod h1:aH/URdfJ92i5Ec/5u2GSlliMZtKzsD91oTJNwZpH8Hc= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= @@ -269,9 +269,8 @@ github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyC github.com/valyala/fasthttp v1.6.0/go.mod h1:FstJa9V+Pj9vQ7OJie2qMHdwemEDaDiSdBnvPM1Su9w= github.com/valyala/fasttemplate v1.0.1/go.mod h1:UQGH1tvbgY+Nz5t2n7tXsz52dQxojPUpymEIMZ47gx8= github.com/valyala/tcplisten v0.0.0-20161114210144-ceec8f93295a/go.mod h1:v3UYOV9WzVtRmSR+PDvWpU/qWl4Wa5LApYYX4ZtKbio= +github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f h1:J9EGpcZtP0E/raorCMxlFGSTBrsSlaDGf3jU/qvAE2c= github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= -github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb h1:zGWFAtiMcyryUHoUjUJX0/lt1H2+i2Ka2n+D3DImSNo= -github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0= github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74= diff --git a/internal/batches/batch_spec.go b/internal/batches/batch_spec.go deleted file mode 100644 index 09068a0eec..0000000000 --- a/internal/batches/batch_spec.go +++ /dev/null @@ -1,193 +0,0 @@ -package batches - -import ( - "fmt" - "strings" - - "github.com/hashicorp/go-multierror" - "github.com/pkg/errors" - "github.com/sourcegraph/batch-change-utils/env" - "github.com/sourcegraph/batch-change-utils/overridable" - "github.com/sourcegraph/batch-change-utils/yaml" - "github.com/sourcegraph/src-cli/schema" -) - -// Some general notes about the struct definitions below. -// -// 1. They map _very_ closely to the batch spec JSON schema. We don't -// auto-generate the types because we need YAML support (more on that in a -// moment) and because no generator can currently handle oneOf fields -// gracefully in Go, but that's a potential future enhancement. -// -// 2. Fields are tagged with _both_ JSON and YAML tags. Internally, the JSON -// schema library needs to be able to marshal the struct to JSON for -// validation, so we need to ensure that we're generating the right JSON to -// represent the YAML that we unmarshalled. -// -// 3. All JSON tags include omitempty so that the schema validation can pick up -// omitted fields. The other option here was to have everything unmarshal to -// pointers, which is ugly and inefficient. - -type BatchSpec struct { - Name string `json:"name,omitempty" yaml:"name"` - Description string `json:"description,omitempty" yaml:"description"` - On []OnQueryOrRepository `json:"on,omitempty" yaml:"on"` - Workspaces []WorkspaceConfiguration `json:"workspaces,omitempty" yaml:"workspaces"` - Steps []Step `json:"steps,omitempty" yaml:"steps"` - TransformChanges *TransformChanges `json:"transformChanges,omitempty" yaml:"transformChanges,omitempty"` - ImportChangesets []ImportChangeset `json:"importChangesets,omitempty" yaml:"importChangesets"` - ChangesetTemplate *ChangesetTemplate `json:"changesetTemplate,omitempty" yaml:"changesetTemplate"` -} - -type ChangesetTemplate struct { - Title string `json:"title,omitempty" yaml:"title"` - Body string `json:"body,omitempty" yaml:"body"` - Branch string `json:"branch,omitempty" yaml:"branch"` - Commit ExpandedGitCommitDescription `json:"commit,omitempty" yaml:"commit"` - Published *overridable.BoolOrString `json:"published" yaml:"published"` -} - -type GitCommitAuthor struct { - Name string `json:"name" yaml:"name"` - Email string `json:"email" yaml:"email"` -} - -type ExpandedGitCommitDescription struct { - Message string `json:"message,omitempty" yaml:"message"` - Author *GitCommitAuthor `json:"author,omitempty" yaml:"author"` -} - -type ImportChangeset struct { - Repository string `json:"repository" yaml:"repository"` - ExternalIDs []interface{} `json:"externalIDs" yaml:"externalIDs"` -} - -type WorkspaceConfiguration struct { - RootAtLocationOf string `json:"rootAtLocationOf,omitempty" yaml:"rootAtLocationOf"` - In string `json:"in,omitempty" yaml:"in"` - OnlyFetchWorkspace bool `json:"onlyFetchWorkspace,omitempty" yaml:"onlyFetchWorkspace"` -} - -type OnQueryOrRepository struct { - RepositoriesMatchingQuery string `json:"repositoriesMatchingQuery,omitempty" yaml:"repositoriesMatchingQuery"` - Repository string `json:"repository,omitempty" yaml:"repository"` - Branch string `json:"branch,omitempty" yaml:"branch"` -} - -type Step struct { - Run string `json:"run,omitempty" yaml:"run"` - Container string `json:"container,omitempty" yaml:"container"` - Env env.Environment `json:"env,omitempty" yaml:"env"` - Files map[string]string `json:"files,omitempty" yaml:"files,omitempty"` - Outputs Outputs `json:"outputs,omitempty" yaml:"outputs,omitempty"` - - If interface{} `json:"if,omitempty" yaml:"if,omitempty"` -} - -func (s *Step) IfCondition() string { - switch v := s.If.(type) { - case bool: - if v { - return "true" - } - return "false" - case string: - return v - default: - return "" - } -} - -type Outputs map[string]Output - -type Output struct { - Value string `json:"value,omitempty" yaml:"value,omitempty"` - Format string `json:"format,omitempty" yaml:"format,omitempty"` -} - -type TransformChanges struct { - Group []Group `json:"group,omitempty" yaml:"group"` -} - -type Group struct { - Directory string `json:"directory,omitempty" yaml:"directory"` - Branch string `json:"branch,omitempty" yaml:"branch"` - Repository string `json:"repository,omitempty" yaml:"repository"` -} - -type ParseBatchSpecOptions struct { - AllowArrayEnvironments bool - AllowTransformChanges bool - AllowConditionalExec bool -} - -func ParseBatchSpec(data []byte, opts ParseBatchSpecOptions) (*BatchSpec, error) { - return parseBatchSpec(schema.BatchSpecJSON, data, opts) -} - -func parseBatchSpec(schema string, data []byte, opts ParseBatchSpecOptions) (*BatchSpec, error) { - var spec BatchSpec - if err := yaml.UnmarshalValidate(schema, data, &spec); err != nil { - if multiErr, ok := err.(*multierror.Error); ok { - var newMultiError *multierror.Error - - for _, e := range multiErr.Errors { - // In case of `name` we try to make the error message more user-friendly. - if strings.Contains(e.Error(), "name: Does not match pattern") { - newMultiError = multierror.Append(newMultiError, fmt.Errorf("The batch change name can only contain word characters, dots and dashes. No whitespace or newlines allowed.")) - } else { - newMultiError = multierror.Append(newMultiError, e) - } - } - - return nil, newMultiError.ErrorOrNil() - } - - return nil, err - } - - var errs *multierror.Error - - if !opts.AllowArrayEnvironments { - for i, step := range spec.Steps { - if !step.Env.IsStatic() { - errs = multierror.Append(errs, errors.Errorf("step %d includes one or more dynamic environment variables, which are unsupported in this Sourcegraph version", i+1)) - } - } - } - - if len(spec.Steps) != 0 && spec.ChangesetTemplate == nil { - errs = multierror.Append(errs, errors.New("batch spec includes steps but no changesetTemplate")) - } - - if spec.TransformChanges != nil && !opts.AllowTransformChanges { - errs = multierror.Append(errs, errors.New("batch spec includes transformChanges, which is not supported in this Sourcegraph version")) - } - - if len(spec.Workspaces) != 0 && !opts.AllowTransformChanges { - errs = multierror.Append(errs, errors.New("batch spec includes workspaces, which is not supported in this Sourcegraph version")) - } - - if !opts.AllowConditionalExec { - for i, step := range spec.Steps { - if step.IfCondition() != "" { - errs = multierror.Append(errs, fmt.Errorf( - "step %d in batch spec uses the 'if' attribute for conditional execution, which is not supported in this Sourcegraph version", - i+1, - )) - } - } - } - - return &spec, errs.ErrorOrNil() -} - -func (on *OnQueryOrRepository) String() string { - if on.RepositoriesMatchingQuery != "" { - return on.RepositoriesMatchingQuery - } else if on.Repository != "" { - return "r:" + on.Repository - } - - return fmt.Sprintf("%v", *on) -} diff --git a/internal/batches/batch_spec_test.go b/internal/batches/batch_spec_test.go deleted file mode 100644 index 2b16058adb..0000000000 --- a/internal/batches/batch_spec_test.go +++ /dev/null @@ -1,173 +0,0 @@ -package batches - -import ( - "fmt" - "testing" -) - -func TestParseBatchSpec(t *testing.T) { - t.Run("valid", func(t *testing.T) { - const spec = ` -name: hello-world -description: Add Hello World to READMEs -on: - - repositoriesMatchingQuery: file:README.md -steps: - - run: echo Hello World | tee -a $(find -name README.md) - container: alpine:3 -changesetTemplate: - title: Hello World - body: My first batch change! - branch: hello-world - commit: - message: Append Hello World to all README.md files - published: false -` - - _, err := ParseBatchSpec([]byte(spec), ParseBatchSpecOptions{}) - if err != nil { - t.Fatalf("parsing valid spec returned error: %s", err) - } - }) - - t.Run("missing changesetTemplate", func(t *testing.T) { - const spec = ` -name: hello-world -description: Add Hello World to READMEs -on: - - repositoriesMatchingQuery: file:README.md -steps: - - run: echo Hello World | tee -a $(find -name README.md) - container: alpine:3 -` - - _, err := ParseBatchSpec([]byte(spec), ParseBatchSpecOptions{}) - if err == nil { - t.Fatal("no error returned") - } - - wantErr := `1 error occurred: - * batch spec includes steps but no changesetTemplate - -` - haveErr := err.Error() - if haveErr != wantErr { - t.Fatalf("wrong error. want=%q, have=%q", wantErr, haveErr) - } - }) - - t.Run("invalid batch change name", func(t *testing.T) { - const spec = ` -name: this name is invalid cause it contains whitespace -description: Add Hello World to READMEs -on: - - repositoriesMatchingQuery: file:README.md -steps: - - run: echo Hello World | tee -a $(find -name README.md) - container: alpine:3 -changesetTemplate: - title: Hello World - body: My first batch change! - branch: hello-world - commit: - message: Append Hello World to all README.md files - published: false -` - - _, err := ParseBatchSpec([]byte(spec), ParseBatchSpecOptions{}) - if err == nil { - t.Fatal("no error returned") - } - - // We expect this error to be user-friendly, which is why we test for - // it specifically here. - wantErr := `1 error occurred: - * The batch change name can only contain word characters, dots and dashes. No whitespace or newlines allowed. - -` - haveErr := err.Error() - if haveErr != wantErr { - t.Fatalf("wrong error. want=%q, have=%q", wantErr, haveErr) - } - }) - - t.Run("uses unsupported conditional exec", func(t *testing.T) { - const spec = ` -name: hello-world -description: Add Hello World to READMEs -on: - - repositoriesMatchingQuery: file:README.md -steps: - - run: echo Hello World | tee -a $(find -name README.md) - if: "false" - container: alpine:3 - -changesetTemplate: - title: Hello World - body: My first batch change! - branch: hello-world - commit: - message: Append Hello World to all README.md files - published: false -` - - _, err := ParseBatchSpec([]byte(spec), ParseBatchSpecOptions{}) - if err == nil { - t.Fatal("no error returned") - } - - wantErr := `1 error occurred: - * step 1 in batch spec uses the 'if' attribute for conditional execution, which is not supported in this Sourcegraph version - -` - haveErr := err.Error() - if haveErr != wantErr { - t.Fatalf("wrong error. want=%q, have=%q", wantErr, haveErr) - } - }) - - t.Run("parsing if attribute", func(t *testing.T) { - const specTemplate = ` -name: hello-world -description: Add Hello World to READMEs -on: - - repositoriesMatchingQuery: file:README.md -steps: - - run: echo Hello World | tee -a $(find -name README.md) - if: %s - container: alpine:3 - -changesetTemplate: - title: Hello World - body: My first batch change! - branch: hello-world - commit: - message: Append Hello World to all README.md files - published: false -` - - for _, tt := range []struct { - raw string - want string - }{ - {raw: `"true"`, want: "true"}, - {raw: `"false"`, want: "false"}, - {raw: `true`, want: "true"}, - {raw: `false`, want: "false"}, - {raw: `"${{ foobar }}"`, want: "${{ foobar }}"}, - {raw: `${{ foobar }}`, want: "${{ foobar }}"}, - {raw: `foobar`, want: "foobar"}, - } { - spec := fmt.Sprintf(specTemplate, tt.raw) - batchSpec, err := ParseBatchSpec([]byte(spec), ParseBatchSpecOptions{AllowConditionalExec: true}) - if err != nil { - t.Fatal(err) - } - - fmt.Printf("len(batchSpec.Steps)=%d", len(batchSpec.Steps)) - if batchSpec.Steps[0].IfCondition() != tt.want { - t.Fatalf("wrong IfCondition. want=%q, got=%q", tt.want, batchSpec.Steps[0].IfCondition()) - } - } - }) -} diff --git a/internal/batches/executor/changeset_specs.go b/internal/batches/executor/changeset_specs.go index 9b7ec11636..630a2aabf4 100644 --- a/internal/batches/executor/changeset_specs.go +++ b/internal/batches/executor/changeset_specs.go @@ -6,6 +6,7 @@ import ( "github.com/pkg/errors" "github.com/sourcegraph/go-diff/diff" + batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/src-cli/internal/batches" ) @@ -138,8 +139,8 @@ func createChangesetSpecs(task *Task, result executionResult, features batches.F return specs, nil } -func groupsForRepository(repo string, transform *batches.TransformChanges) []batches.Group { - var groups []batches.Group +func groupsForRepository(repo string, transform *batcheslib.TransformChanges) []batcheslib.Group { + var groups []batcheslib.Group if transform == nil { return groups @@ -158,7 +159,7 @@ func groupsForRepository(repo string, transform *batches.TransformChanges) []bat return groups } -func validateGroups(repo, defaultBranch string, groups []batches.Group) error { +func validateGroups(repo, defaultBranch string, groups []batcheslib.Group) error { uniqueBranches := make(map[string]struct{}, len(groups)) for _, g := range groups { @@ -176,7 +177,7 @@ func validateGroups(repo, defaultBranch string, groups []batches.Group) error { return nil } -func groupFileDiffs(completeDiff, defaultBranch string, groups []batches.Group) (map[string]string, error) { +func groupFileDiffs(completeDiff, defaultBranch string, groups []batcheslib.Group) (map[string]string, error) { fileDiffs, err := diff.ParseMultiFileDiff([]byte(completeDiff)) if err != nil { return nil, err diff --git a/internal/batches/executor/changeset_specs_test.go b/internal/batches/executor/changeset_specs_test.go index 46ba0fb7ef..6d86a96b4b 100644 --- a/internal/batches/executor/changeset_specs_test.go +++ b/internal/batches/executor/changeset_specs_test.go @@ -7,6 +7,7 @@ import ( "github.com/google/go-cmp/cmp" "github.com/mitchellh/copystructure" "github.com/sourcegraph/batch-change-utils/overridable" + batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/git" ) @@ -49,11 +50,11 @@ func TestCreateChangesetSpecs(t *testing.T) { Name: "the name", Description: "The description", }, - Template: &batches.ChangesetTemplate{ + Template: &batcheslib.ChangesetTemplate{ Title: "The title", Body: "The body", Branch: "my-branch", - Commit: batches.ExpandedGitCommitDescription{ + Commit: batcheslib.ExpandedGitCommitDescription{ Message: "git commit message", }, Published: parsePublishedFieldString(t, "false"), @@ -226,12 +227,12 @@ index 0000000..1bd79fb tests := []struct { diff string defaultBranch string - groups []batches.Group + groups []batcheslib.Group want map[string]string }{ { diff: allDiffs, - groups: []batches.Group{ + groups: []batcheslib.Group{ {Directory: "1/2/3", Branch: "everything-in-3"}, }, want: map[string]string{ @@ -241,7 +242,7 @@ index 0000000..1bd79fb }, { diff: allDiffs, - groups: []batches.Group{ + groups: []batcheslib.Group{ {Directory: "1/2", Branch: "everything-in-2-and-3"}, }, want: map[string]string{ @@ -251,7 +252,7 @@ index 0000000..1bd79fb }, { diff: allDiffs, - groups: []batches.Group{ + groups: []batcheslib.Group{ {Directory: "1", Branch: "everything-in-1-and-2-and-3"}, }, want: map[string]string{ @@ -261,7 +262,7 @@ index 0000000..1bd79fb }, { diff: allDiffs, - groups: []batches.Group{ + groups: []batcheslib.Group{ // Each diff is matched against each directory, last match wins {Directory: "1", Branch: "only-in-1"}, {Directory: "1/2", Branch: "only-in-2"}, @@ -276,7 +277,7 @@ index 0000000..1bd79fb }, { diff: allDiffs, - groups: []batches.Group{ + groups: []batcheslib.Group{ // Last one wins here, because it matches every diff {Directory: "1/2/3", Branch: "only-in-3"}, {Directory: "1/2", Branch: "only-in-2"}, @@ -289,7 +290,7 @@ index 0000000..1bd79fb }, { diff: allDiffs, - groups: []batches.Group{ + groups: []batcheslib.Group{ {Directory: "", Branch: "everything"}, }, want: map[string]string{ @@ -315,25 +316,25 @@ func TestValidateGroups(t *testing.T) { tests := []struct { defaultBranch string - groups []batches.Group + groups []batcheslib.Group wantErr string }{ { - groups: []batches.Group{ + groups: []batcheslib.Group{ {Directory: "a", Branch: "my-batch-change-a"}, {Directory: "b", Branch: "my-batch-change-b"}, }, wantErr: "", }, { - groups: []batches.Group{ + groups: []batcheslib.Group{ {Directory: "a", Branch: "my-batch-change-SAME"}, {Directory: "b", Branch: "my-batch-change-SAME"}, }, wantErr: "transformChanges would lead to multiple changesets in repository github.com/sourcegraph/src-cli to have the same branch \"my-batch-change-SAME\"", }, { - groups: []batches.Group{ + groups: []batcheslib.Group{ {Directory: "a", Branch: "my-batch-change-SAME"}, {Directory: "b", Branch: defaultBranch}, }, diff --git a/internal/batches/executor/coordinator.go b/internal/batches/executor/coordinator.go index b3d2e06fac..4645910723 100644 --- a/internal/batches/executor/coordinator.go +++ b/internal/batches/executor/coordinator.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/go-multierror" "github.com/pkg/errors" + batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/docker" @@ -220,7 +221,7 @@ type TaskExecutionUI interface { // Execute executes the given Tasks and the importChangeset statements in the // given spec. It regularly calls the executionProgressPrinter with the // current TaskStatuses. -func (c *Coordinator) Execute(ctx context.Context, tasks []*Task, spec *batches.BatchSpec, ui TaskExecutionUI) ([]*batches.ChangesetSpec, []string, error) { +func (c *Coordinator) Execute(ctx context.Context, tasks []*Task, spec *batcheslib.BatchSpec, ui TaskExecutionUI) ([]*batches.ChangesetSpec, []string, error) { var ( specs []*batches.ChangesetSpec errs *multierror.Error diff --git a/internal/batches/executor/coordinator_test.go b/internal/batches/executor/coordinator_test.go index ec746153f4..1c86cd35bf 100644 --- a/internal/batches/executor/coordinator_test.go +++ b/internal/batches/executor/coordinator_test.go @@ -10,6 +10,7 @@ import ( "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" "github.com/sourcegraph/batch-change-utils/overridable" + batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/git" "github.com/sourcegraph/src-cli/internal/batches/graphql" @@ -54,7 +55,7 @@ func TestCoordinator_Execute(t *testing.T) { opts NewCoordinatorOpts tasks []*Task - batchSpec *batches.BatchSpec + batchSpec *batcheslib.BatchSpec wantCacheEntries int wantSpecs []*batches.ChangesetSpec @@ -65,7 +66,7 @@ func TestCoordinator_Execute(t *testing.T) { tasks: []*Task{srcCLITask, sourcegraphTask}, - batchSpec: &batches.BatchSpec{ + batchSpec: &batcheslib.BatchSpec{ Name: "my-batch-change", Description: "the description", ChangesetTemplate: testChangesetTemplate, @@ -93,10 +94,10 @@ func TestCoordinator_Execute(t *testing.T) { name: "templated changesetTemplate", tasks: []*Task{srcCLITask}, - batchSpec: &batches.BatchSpec{ + batchSpec: &batcheslib.BatchSpec{ Name: "my-batch-change", Description: "the description", - ChangesetTemplate: &batches.ChangesetTemplate{ + ChangesetTemplate: &batcheslib.ChangesetTemplate{ Title: `output1=${{ outputs.output1}}`, Body: `output1=${{ outputs.output1}} output2=${{ outputs.output2.subField }} @@ -112,9 +113,9 @@ func TestCoordinator_Execute(t *testing.T) { batch_change_description=${{ batch_change.description }} `, Branch: "templated-branch-${{ outputs.output1 }}", - Commit: batches.ExpandedGitCommitDescription{ + Commit: batcheslib.ExpandedGitCommitDescription{ Message: "output1=${{ outputs.output1}},output2=${{ outputs.output2.subField }}", - Author: &batches.GitCommitAuthor{ + Author: &batcheslib.GitCommitAuthor{ Name: "output1=${{ outputs.output1}}", Email: "output1=${{ outputs.output1}}", }, @@ -180,10 +181,10 @@ func TestCoordinator_Execute(t *testing.T) { tasks: []*Task{srcCLITask, sourcegraphTask}, - batchSpec: &batches.BatchSpec{ + batchSpec: &batcheslib.BatchSpec{ ChangesetTemplate: testChangesetTemplate, - TransformChanges: &batches.TransformChanges{ - Group: []batches.Group{ + TransformChanges: &batcheslib.TransformChanges{ + Group: []batcheslib.Group{ {Directory: "a/b/c", Branch: "in-directory-c"}, {Directory: "a/b", Branch: "in-directory-b", Repository: testRepo2.Name}, }, @@ -226,7 +227,7 @@ func TestCoordinator_Execute(t *testing.T) { tasks: []*Task{srcCLITask, sourcegraphTask}, - batchSpec: &batches.BatchSpec{ + batchSpec: &batcheslib.BatchSpec{ Name: "my-batch-change", Description: "the description", ChangesetTemplate: testChangesetTemplate, @@ -352,7 +353,7 @@ func TestCoordinator_Execute_StepCaching(t *testing.T) { logManager := mock.LogNoOpManager{} task := &Task{ - Steps: []batches.Step{ + Steps: []batcheslib.Step{ {Run: `echo "one"`}, {Run: `echo "two"`}, {Run: `echo "three"`}, @@ -430,7 +431,7 @@ func TestCoordinator_Execute_StepCaching(t *testing.T) { func execAndEnsure(t *testing.T, coord *Coordinator, exec *dummyExecutor, task *Task, cb startCallback) { t.Helper() - batchSpec := &batches.BatchSpec{ChangesetTemplate: testChangesetTemplate} + batchSpec := &batcheslib.BatchSpec{ChangesetTemplate: testChangesetTemplate} // Set the ChangesetTemplate on Task task.Template = batchSpec.ChangesetTemplate diff --git a/internal/batches/executor/execution_cache.go b/internal/batches/executor/execution_cache.go index fa0eef62b5..b901464b0d 100644 --- a/internal/batches/executor/execution_cache.go +++ b/internal/batches/executor/execution_cache.go @@ -11,7 +11,7 @@ import ( "path/filepath" "github.com/pkg/errors" - "github.com/sourcegraph/src-cli/internal/batches" + batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" ) func UserCacheDir() (string, error) { @@ -27,7 +27,7 @@ type CacheKeyer interface { Slug() string } -func resolveStepsEnvironment(steps []batches.Step) ([]map[string]string, error) { +func resolveStepsEnvironment(steps []batcheslib.Step) ([]map[string]string, error) { // We have to resolve the step environments and include them in the cache // key to ensure that the cache is properly invalidated when an environment // variable changes. diff --git a/internal/batches/executor/execution_cache_test.go b/internal/batches/executor/execution_cache_test.go index c9d1a80d65..5eb5084c49 100644 --- a/internal/batches/executor/execution_cache_test.go +++ b/internal/batches/executor/execution_cache_test.go @@ -7,7 +7,7 @@ import ( "testing" "github.com/google/go-cmp/cmp" - "github.com/sourcegraph/src-cli/internal/batches" + batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/src-cli/internal/batches/git" "gopkg.in/yaml.v3" ) @@ -17,7 +17,7 @@ const testExecutionCacheKeyEnv = "TEST_EXECUTION_CACHE_KEY_ENV" func TestTaskCacheKey(t *testing.T) { // Let's set up an array of steps that we can test with. One step will // depend on an environment variable outside the spec. - var steps []batches.Step + var steps []batcheslib.Step if err := yaml.Unmarshal([]byte(` - run: foo env: @@ -121,14 +121,14 @@ func TestExecutionDiskCache_GetSet(t *testing.T) { cacheKey1 := TaskCacheKey{Task: &Task{ Repository: testRepo1, - Steps: []batches.Step{ + Steps: []batcheslib.Step{ {Run: "echo 'Hello World'", Container: "alpine:3"}, }, }} cacheKey2 := TaskCacheKey{Task: &Task{ Repository: testRepo2, - Steps: []batches.Step{ + Steps: []batcheslib.Step{ {Run: "echo 'Hello World'", Container: "alpine:3"}, }, }} diff --git a/internal/batches/executor/executor_test.go b/internal/batches/executor/executor_test.go index 132c6342f7..afc24628cf 100644 --- a/internal/batches/executor/executor_test.go +++ b/internal/batches/executor/executor_test.go @@ -17,6 +17,7 @@ import ( "github.com/google/go-cmp/cmp" "github.com/pkg/errors" "github.com/sourcegraph/go-diff/diff" + batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/docker" @@ -48,7 +49,7 @@ func TestExecutor_Integration(t *testing.T) { additionalFiles []mock.MockRepoAdditionalFiles // We define the steps only once per test case so there's less duplication - steps []batches.Step + steps []batcheslib.Step tasks []*Task executorTimeout time.Duration @@ -76,7 +77,7 @@ func TestExecutor_Integration(t *testing.T) { "README.md": "# Sourcegraph README\n", }}, }, - steps: []batches.Step{ + steps: []batcheslib.Step{ {Run: `echo -e "foobar\n" >> README.md`}, {Run: `[[ -f "main.go" ]] && go fmt main.go || exit 0`}, }, @@ -102,7 +103,7 @@ func TestExecutor_Integration(t *testing.T) { "main.go": "package main\n\nfunc main() {\n\tfmt.Println( \"Hello World\")\n}\n", }}, }, - steps: []batches.Step{ + steps: []batcheslib.Step{ {Run: "true"}, }, @@ -122,7 +123,7 @@ func TestExecutor_Integration(t *testing.T) { archives: []mock.RepoArchive{ {Repo: testRepo1, Files: map[string]string{"README.md": "line 1"}}, }, - steps: []batches.Step{ + steps: []batcheslib.Step{ // This needs to be a loop, because when a process goes to sleep // it's not interruptible, meaning that while it will receive SIGKILL // it won't exit until it had its full night of sleep. @@ -145,14 +146,14 @@ func TestExecutor_Integration(t *testing.T) { "main.go": "package main\n\nfunc main() {\n\tfmt.Println( \"Hello World\")\n}\n", }}, }, - steps: []batches.Step{ + steps: []batcheslib.Step{ {Run: `go fmt main.go`}, {Run: `touch modified-${{ join previous_step.modified_files " " }}.md`}, {Run: `touch added-${{ join previous_step.added_files " " }}`}, { Run: `echo "hello.txt"`, - Outputs: batches.Outputs{ - "myOutput": batches.Output{ + Outputs: batcheslib.Outputs{ + "myOutput": batcheslib.Output{ Value: "${{ step.stdout }}", }, }, @@ -200,11 +201,11 @@ func TestExecutor_Integration(t *testing.T) { "a/.gitignore": "node_modules-in-a", }}, }, - steps: []batches.Step{ + steps: []batcheslib.Step{ { Run: "cat message.txt && echo 'Hello' > hello.txt", - Outputs: batches.Outputs{ - "message": batches.Output{ + Outputs: batcheslib.Outputs{ + "message": batcheslib.Output{ Value: "${{ step.stdout }}", }, }, @@ -240,7 +241,7 @@ func TestExecutor_Integration(t *testing.T) { "README.md": "# Sourcegraph README\n", }}, }, - steps: []batches.Step{ + steps: []batcheslib.Step{ {Run: `echo -e "foobar\n" >> README.md`}, { Run: `echo "foobar" >> hello.txt`, @@ -275,7 +276,7 @@ func TestExecutor_Integration(t *testing.T) { "README.md": "# Sourcegraph README\n", }}, }, - steps: []batches.Step{ + steps: []batcheslib.Step{ {Run: `echo -e "foobar\n" >> README.md`}, { Run: `exit 1`, @@ -488,7 +489,7 @@ index 02a19af..c9644dd 100644 task := &Task{ BatchChangeAttributes: &BatchChangeAttributes{}, - Steps: []batches.Step{ + Steps: []batcheslib.Step{ {Run: `echo -e "foobar\n" >> README.md`}, }, CachedResultFound: true, @@ -594,11 +595,11 @@ index 0000000..257ae8e task := &Task{ Repository: testRepo1, BatchChangeAttributes: &BatchChangeAttributes{}, - Steps: []batches.Step{ + Steps: []batcheslib.Step{ {Run: `echo "this is step 1" >> README.txt`}, {Run: `echo "this is step 2" >> README.md`}, - {Run: `echo "this is step 3" >> README.md`, Outputs: batches.Outputs{ - "myOutput": batches.Output{ + {Run: `echo "this is step 3" >> README.md`, Outputs: batcheslib.Outputs{ + "myOutput": batcheslib.Output{ Value: "my-output.txt", }, }}, diff --git a/internal/batches/executor/main_test.go b/internal/batches/executor/main_test.go index 0631cbe81e..ba26d03001 100644 --- a/internal/batches/executor/main_test.go +++ b/internal/batches/executor/main_test.go @@ -2,7 +2,7 @@ package executor import ( "github.com/sourcegraph/batch-change-utils/overridable" - "github.com/sourcegraph/src-cli/internal/batches" + batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/src-cli/internal/batches/graphql" ) @@ -27,13 +27,13 @@ var testRepo2 = &graphql.Repository{ var testPublished = overridable.FromBoolOrString(false) -var testChangesetTemplate = &batches.ChangesetTemplate{ +var testChangesetTemplate = &batcheslib.ChangesetTemplate{ Title: "commit title", Body: "commit body", Branch: "commit-branch", - Commit: batches.ExpandedGitCommitDescription{ + Commit: batcheslib.ExpandedGitCommitDescription{ Message: "commit msg", - Author: &batches.GitCommitAuthor{ + Author: &batcheslib.GitCommitAuthor{ Name: "Tester", Email: "tester@example.com", }, diff --git a/internal/batches/executor/run_steps.go b/internal/batches/executor/run_steps.go index 57ee07dfe4..6a18fcf97d 100644 --- a/internal/batches/executor/run_steps.go +++ b/internal/batches/executor/run_steps.go @@ -14,7 +14,7 @@ import ( "github.com/hashicorp/go-multierror" "github.com/pkg/errors" - "github.com/sourcegraph/src-cli/internal/batches" + batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/src-cli/internal/batches/git" "github.com/sourcegraph/src-cli/internal/batches/log" "github.com/sourcegraph/src-cli/internal/batches/workspace" @@ -218,7 +218,7 @@ func executeSingleStep( opts *executionOpts, workspace workspace.Workspace, i int, - step batches.Step, + step batcheslib.Step, imageDigest string, stepContext *StepContext, ) (bytes.Buffer, bytes.Buffer, error) { @@ -334,7 +334,7 @@ func executeSingleStep( return stdoutBuffer, stderrBuffer, nil } -func setOutputs(stepOutputs batches.Outputs, global map[string]interface{}, stepCtx *StepContext) error { +func setOutputs(stepOutputs batcheslib.Outputs, global map[string]interface{}, stepCtx *StepContext) error { for name, output := range stepOutputs { var value bytes.Buffer @@ -414,7 +414,7 @@ func probeImageForShell(ctx context.Context, image string) (shell, tempfile stri // createFilesToMount creates temporary files with the contents of Step.Files // that are to be mounted into the container that executes the step. -func createFilesToMount(tempDir string, step batches.Step, stepContext *StepContext) (map[string]*os.File, func(), error) { +func createFilesToMount(tempDir string, step batcheslib.Step, stepContext *StepContext) (map[string]*os.File, func(), error) { // Parse and render the step.Files. files, err := renderStepMap(step.Files, stepContext) if err != nil { diff --git a/internal/batches/executor/task.go b/internal/batches/executor/task.go index eb1177b78c..1ca36ddb87 100644 --- a/internal/batches/executor/task.go +++ b/internal/batches/executor/task.go @@ -1,6 +1,7 @@ package executor import ( + batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/graphql" ) @@ -17,13 +18,13 @@ type Task struct { // If Path is "" then this setting has no effect. OnlyFetchWorkspace bool - Steps []batches.Step + Steps []batcheslib.Step // TODO(mrnugget): this should just be a single BatchSpec field instead, if // we can make it work with caching - BatchChangeAttributes *BatchChangeAttributes `json:"-"` - Template *batches.ChangesetTemplate `json:"-"` - TransformChanges *batches.TransformChanges `json:"-"` + BatchChangeAttributes *BatchChangeAttributes `json:"-"` + Template *batcheslib.ChangesetTemplate `json:"-"` + TransformChanges *batcheslib.TransformChanges `json:"-"` Archive batches.RepoZip `json:"-"` diff --git a/internal/batches/executor/task_builder.go b/internal/batches/executor/task_builder.go index 5219ed27dd..e58072ac14 100644 --- a/internal/batches/executor/task_builder.go +++ b/internal/batches/executor/task_builder.go @@ -5,7 +5,7 @@ import ( "fmt" "github.com/gobwas/glob" - "github.com/sourcegraph/src-cli/internal/batches" + batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/src-cli/internal/batches/graphql" ) @@ -14,12 +14,12 @@ type DirectoryFinder interface { } type taskBuilder struct { - spec *batches.BatchSpec + spec *batcheslib.BatchSpec finder DirectoryFinder } // BuildTasks returns tasks for all the workspaces determined for the given spec. -func BuildTasks(ctx context.Context, spec *batches.BatchSpec, finder DirectoryFinder, repos []*graphql.Repository) ([]*Task, error) { +func BuildTasks(ctx context.Context, spec *batcheslib.BatchSpec, finder DirectoryFinder, repos []*graphql.Repository) ([]*Task, error) { tb := &taskBuilder{spec: spec, finder: finder} return tb.buildAll(ctx, repos) } @@ -33,7 +33,7 @@ func (tb *taskBuilder) buildTask(r *graphql.Repository, path string, onlyWorkspa }, } - var taskSteps []batches.Step + var taskSteps []batcheslib.Step for _, step := range tb.spec.Steps { if step.IfCondition() == "" { taskSteps = append(taskSteps, step) @@ -129,13 +129,13 @@ type repoWorkspaces struct { func (tb *taskBuilder) findWorkspaces( ctx context.Context, repos []*graphql.Repository, - configs []batches.WorkspaceConfiguration, + configs []batcheslib.WorkspaceConfiguration, ) (workspaces map[*graphql.Repository]repoWorkspaces, root []*graphql.Repository, err error) { if len(configs) == 0 { return nil, repos, nil } - workspaceMatchers := make(map[batches.WorkspaceConfiguration]glob.Glob) + workspaceMatchers := make(map[batcheslib.WorkspaceConfiguration]glob.Glob) for _, conf := range tb.spec.Workspaces { g, err := glob.Compile(conf.In) if err != nil { diff --git a/internal/batches/executor/task_builder_test.go b/internal/batches/executor/task_builder_test.go index 44c80cb7b8..cf4e7b1e0d 100644 --- a/internal/batches/executor/task_builder_test.go +++ b/internal/batches/executor/task_builder_test.go @@ -7,47 +7,47 @@ import ( "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" - "github.com/sourcegraph/src-cli/internal/batches" + batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/src-cli/internal/batches/graphql" ) func TestTaskBuilder_BuildTask_IfConditions(t *testing.T) { tests := map[string]struct { - spec *batches.BatchSpec + spec *batcheslib.BatchSpec - wantSteps []batches.Step + wantSteps []batcheslib.Step }{ "no if": { - spec: &batches.BatchSpec{ - Steps: []batches.Step{ + spec: &batcheslib.BatchSpec{ + Steps: []batcheslib.Step{ {Run: "echo 1"}, }, }, - wantSteps: []batches.Step{ + wantSteps: []batcheslib.Step{ {Run: "echo 1"}, }, }, "if has static true value": { - spec: &batches.BatchSpec{ - Steps: []batches.Step{ + spec: &batcheslib.BatchSpec{ + Steps: []batcheslib.Step{ {Run: "echo 1", If: "true"}, }, }, - wantSteps: []batches.Step{ + wantSteps: []batcheslib.Step{ {Run: "echo 1", If: "true"}, }, }, "one of many steps has if with static true value": { - spec: &batches.BatchSpec{ - Steps: []batches.Step{ + spec: &batcheslib.BatchSpec{ + Steps: []batcheslib.Step{ {Run: "echo 1"}, {Run: "echo 2", If: "true"}, {Run: "echo 3"}, }, }, - wantSteps: []batches.Step{ + wantSteps: []batcheslib.Step{ {Run: "echo 1"}, {Run: "echo 2", If: "true"}, {Run: "echo 3"}, @@ -55,8 +55,8 @@ func TestTaskBuilder_BuildTask_IfConditions(t *testing.T) { }, "if has static non-true value": { - spec: &batches.BatchSpec{ - Steps: []batches.Step{ + spec: &batcheslib.BatchSpec{ + Steps: []batcheslib.Step{ {Run: "echo 1", If: "this is not true"}, }, }, @@ -64,33 +64,33 @@ func TestTaskBuilder_BuildTask_IfConditions(t *testing.T) { }, "one of many steps has if with static non-true value": { - spec: &batches.BatchSpec{ - Steps: []batches.Step{ + spec: &batcheslib.BatchSpec{ + Steps: []batcheslib.Step{ {Run: "echo 1"}, {Run: "echo 2", If: "every type system needs generics"}, {Run: "echo 3"}, }, }, - wantSteps: []batches.Step{ + wantSteps: []batcheslib.Step{ {Run: "echo 1"}, {Run: "echo 3"}, }, }, "if expression that can be partially evaluated to true": { - spec: &batches.BatchSpec{ - Steps: []batches.Step{ + spec: &batcheslib.BatchSpec{ + Steps: []batcheslib.Step{ {Run: "echo 1", If: `${{ matches repository.name "github.com/sourcegraph/src*" }}`}, }, }, - wantSteps: []batches.Step{ + wantSteps: []batcheslib.Step{ {Run: "echo 1", If: `${{ matches repository.name "github.com/sourcegraph/src*" }}`}, }, }, "if expression that can be partially evaluated to false": { - spec: &batches.BatchSpec{ - Steps: []batches.Step{ + spec: &batcheslib.BatchSpec{ + Steps: []batcheslib.Step{ {Run: "echo 1", If: `${{ matches repository.name "horse" }}`}, }, }, @@ -98,8 +98,8 @@ func TestTaskBuilder_BuildTask_IfConditions(t *testing.T) { }, "one of many steps has if expression that can be evaluated to true": { - spec: &batches.BatchSpec{ - Steps: []batches.Step{ + spec: &batcheslib.BatchSpec{ + Steps: []batcheslib.Step{ {Run: "echo 1", If: `${{ matches repository.name "horse" }}`}, }, }, @@ -107,12 +107,12 @@ func TestTaskBuilder_BuildTask_IfConditions(t *testing.T) { }, "if expression that can NOT be partially evaluated": { - spec: &batches.BatchSpec{ - Steps: []batches.Step{ + spec: &batcheslib.BatchSpec{ + Steps: []batcheslib.Step{ {Run: "echo 1", If: `${{ eq outputs.value "foobar" }}`}, }, }, - wantSteps: []batches.Step{ + wantSteps: []batcheslib.Step{ {Run: "echo 1", If: `${{ eq outputs.value "foobar" }}`}, }, }, @@ -133,7 +133,7 @@ func TestTaskBuilder_BuildTask_IfConditions(t *testing.T) { return } - opts := cmpopts.IgnoreUnexported(batches.Step{}) + opts := cmpopts.IgnoreUnexported(batcheslib.Step{}) if diff := cmp.Diff(tt.wantSteps, task.Steps, opts); diff != "" { t.Errorf("mismatch (-want +got):\n%s", diff) } @@ -147,7 +147,7 @@ func TestTaskBuilder_BuildAll_Workspaces(t *testing.T) { {ID: "repo-id-1", Name: "github.com/sourcegraph/sourcegraph"}, {ID: "repo-id-2", Name: "bitbucket.sgdev.org/SOUR/automation-testing"}, } - steps := []batches.Step{{Run: "echo 1"}} + steps := []batcheslib.Step{{Run: "echo 1"}} type finderResults map[*graphql.Repository][]string @@ -157,7 +157,7 @@ func TestTaskBuilder_BuildAll_Workspaces(t *testing.T) { } tests := map[string]struct { - spec *batches.BatchSpec + spec *batcheslib.BatchSpec finderResults map[*graphql.Repository][]string wantNumTasks int @@ -166,7 +166,7 @@ func TestTaskBuilder_BuildAll_Workspaces(t *testing.T) { wantTasks map[string][]wantTask }{ "no workspace configuration": { - spec: &batches.BatchSpec{Steps: steps}, + spec: &batcheslib.BatchSpec{Steps: steps}, finderResults: finderResults{}, wantNumTasks: len(repos), wantTasks: map[string][]wantTask{ @@ -177,9 +177,9 @@ func TestTaskBuilder_BuildAll_Workspaces(t *testing.T) { }, "workspace configuration matching no repos": { - spec: &batches.BatchSpec{ + spec: &batcheslib.BatchSpec{ Steps: steps, - Workspaces: []batches.WorkspaceConfiguration{ + Workspaces: []batcheslib.WorkspaceConfiguration{ {In: "this-does-not-match", RootAtLocationOf: "package.json"}, }, }, @@ -193,9 +193,9 @@ func TestTaskBuilder_BuildAll_Workspaces(t *testing.T) { }, "workspace configuration matching 2 repos with no results": { - spec: &batches.BatchSpec{ + spec: &batcheslib.BatchSpec{ Steps: steps, - Workspaces: []batches.WorkspaceConfiguration{ + Workspaces: []batcheslib.WorkspaceConfiguration{ {In: "*automation-testing", RootAtLocationOf: "package.json"}, }, }, @@ -210,9 +210,9 @@ func TestTaskBuilder_BuildAll_Workspaces(t *testing.T) { }, "workspace configuration matching 2 repos with 3 results each": { - spec: &batches.BatchSpec{ + spec: &batcheslib.BatchSpec{ Steps: steps, - Workspaces: []batches.WorkspaceConfiguration{ + Workspaces: []batcheslib.WorkspaceConfiguration{ {In: "*automation-testing", RootAtLocationOf: "package.json"}, }, }, @@ -229,9 +229,9 @@ func TestTaskBuilder_BuildAll_Workspaces(t *testing.T) { }, "workspace configuration matches repo with OnlyFetchWorkspace": { - spec: &batches.BatchSpec{ + spec: &batcheslib.BatchSpec{ Steps: steps, - Workspaces: []batches.WorkspaceConfiguration{ + Workspaces: []batcheslib.WorkspaceConfiguration{ { OnlyFetchWorkspace: true, In: "*automation-testing", diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index 91f5c3d41a..0b280c3bec 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -12,6 +12,7 @@ import ( "strings" "github.com/pkg/errors" + batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/docker" @@ -150,7 +151,7 @@ func (svc *Service) CreateChangesetSpec(ctx context.Context, spec *batches.Chang // // Progress information is reported back to the given progress function: perc // will be a value between 0.0 and 1.0, inclusive. -func (svc *Service) EnsureDockerImages(ctx context.Context, spec *batches.BatchSpec, progress func(perc float64)) (map[string]docker.Image, error) { +func (svc *Service) EnsureDockerImages(ctx context.Context, spec *batcheslib.BatchSpec, progress func(perc float64)) (map[string]docker.Image, error) { total := len(spec.Steps) + 1 progress(0) @@ -181,7 +182,7 @@ func (svc *Service) EnsureImage(ctx context.Context, name string) (docker.Image, return img, nil } -func (svc *Service) BuildTasks(ctx context.Context, repos []*graphql.Repository, spec *batches.BatchSpec) ([]*executor.Task, error) { +func (svc *Service) BuildTasks(ctx context.Context, repos []*graphql.Repository, spec *batcheslib.BatchSpec) ([]*executor.Task, error) { return executor.BuildTasks(ctx, spec, svc, repos) } @@ -258,8 +259,8 @@ func (e *duplicateBranchesErr) Error() string { return out.String() } -func (svc *Service) ParseBatchSpec(data []byte) (*batches.BatchSpec, error) { - spec, err := batches.ParseBatchSpec(data, batches.ParseBatchSpecOptions{ +func (svc *Service) ParseBatchSpec(data []byte) (*batcheslib.BatchSpec, error) { + spec, err := batcheslib.ParseBatchSpec(data, batcheslib.ParseBatchSpecOptions{ AllowArrayEnvironments: svc.features.AllowArrayEnvironments, AllowTransformChanges: svc.features.AllowTransformChanges, AllowConditionalExec: svc.features.AllowConditionalExec, @@ -326,7 +327,7 @@ func (svc *Service) GenerateExampleSpec(ctx context.Context, fileName string) er return err } - author := batches.GitCommitAuthor{ + author := batcheslib.GitCommitAuthor{ Name: "Sourcegraph", Email: "batch-changes@sourcegraph.com", } @@ -408,7 +409,7 @@ func (svc *Service) ResolveNamespace(ctx context.Context, namespace string) (str return "", fmt.Errorf("failed to resolve namespace %q: no user or organization found", namespace) } -func (svc *Service) ResolveRepositories(ctx context.Context, spec *batches.BatchSpec) ([]*graphql.Repository, error) { +func (svc *Service) ResolveRepositories(ctx context.Context, spec *batcheslib.BatchSpec) ([]*graphql.Repository, error) { seen := map[string]*graphql.Repository{} unsupported := batches.UnsupportedRepoSet{} ignored := batches.IgnoredRepoSet{} @@ -476,7 +477,7 @@ func (svc *Service) ResolveRepositories(ctx context.Context, spec *batches.Batch return final, nil } -func (svc *Service) ResolveRepositoriesOn(ctx context.Context, on *batches.OnQueryOrRepository) ([]*graphql.Repository, error) { +func (svc *Service) ResolveRepositoriesOn(ctx context.Context, on *batcheslib.OnQueryOrRepository) ([]*graphql.Repository, error) { if on.RepositoriesMatchingQuery != "" { return svc.resolveRepositorySearch(ctx, on.RepositoriesMatchingQuery) } else if on.Repository != "" && on.Branch != "" { diff --git a/internal/batches/service/service_test.go b/internal/batches/service/service_test.go index 6f7350bb0e..44964ff504 100644 --- a/internal/batches/service/service_test.go +++ b/internal/batches/service/service_test.go @@ -10,6 +10,7 @@ import ( "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" + batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/graphql" @@ -143,8 +144,8 @@ func TestResolveRepositories_Unsupported(t *testing.T) { client, done := mockGraphQLClient(testResolveRepositoriesUnsupported) defer done() - spec := &batches.BatchSpec{ - On: []batches.OnQueryOrRepository{ + spec := &batcheslib.BatchSpec{ + On: []batcheslib.OnQueryOrRepository{ {RepositoriesMatchingQuery: "testquery"}, }, } @@ -223,8 +224,8 @@ const testResolveRepositoriesUnsupported = `{ ` func TestResolveRepositories_Ignored(t *testing.T) { - spec := &batches.BatchSpec{ - On: []batches.OnQueryOrRepository{ + spec := &batcheslib.BatchSpec{ + On: []batcheslib.OnQueryOrRepository{ {RepositoriesMatchingQuery: "testquery"}, }, } diff --git a/internal/batches/ui/json_lines.go b/internal/batches/ui/json_lines.go index 9d9ddab1bd..fc83cc648a 100644 --- a/internal/batches/ui/json_lines.go +++ b/internal/batches/ui/json_lines.go @@ -6,6 +6,7 @@ import ( "os" "time" + batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/executor" "github.com/sourcegraph/src-cli/internal/batches/graphql" @@ -212,7 +213,7 @@ func logEvent(e batchesLogEvent) { type jsonLinesTask struct { Repository string Workspace string - Steps []batches.Step + Steps []batcheslib.Step CachedStepResultsFound bool StartStep int } diff --git a/internal/batches/workspace/bind_workspace.go b/internal/batches/workspace/bind_workspace.go index f7281c0cec..c9e1ae12e9 100644 --- a/internal/batches/workspace/bind_workspace.go +++ b/internal/batches/workspace/bind_workspace.go @@ -13,6 +13,7 @@ import ( "github.com/hashicorp/go-multierror" "github.com/pkg/errors" + batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/git" "github.com/sourcegraph/src-cli/internal/batches/graphql" @@ -26,7 +27,7 @@ var _ Creator = &dockerBindWorkspaceCreator{} func (wc *dockerBindWorkspaceCreator) Type() CreatorType { return CreatorTypeBind } -func (wc *dockerBindWorkspaceCreator) Create(ctx context.Context, repo *graphql.Repository, steps []batches.Step, archive batches.RepoZip) (Workspace, error) { +func (wc *dockerBindWorkspaceCreator) Create(ctx context.Context, repo *graphql.Repository, steps []batcheslib.Step, archive batches.RepoZip) (Workspace, error) { w, err := wc.unzipToWorkspace(ctx, repo, archive.Path()) if err != nil { return nil, errors.Wrap(err, "unzipping the repository") diff --git a/internal/batches/workspace/volume_workspace.go b/internal/batches/workspace/volume_workspace.go index 23f5f1fc00..f1c3fc2536 100644 --- a/internal/batches/workspace/volume_workspace.go +++ b/internal/batches/workspace/volume_workspace.go @@ -13,6 +13,7 @@ import ( "github.com/pkg/errors" + batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/docker" "github.com/sourcegraph/src-cli/internal/batches/git" @@ -32,7 +33,7 @@ var _ Creator = &dockerVolumeWorkspaceCreator{} func (wc *dockerVolumeWorkspaceCreator) Type() CreatorType { return CreatorTypeVolume } -func (wc *dockerVolumeWorkspaceCreator) Create(ctx context.Context, repo *graphql.Repository, steps []batches.Step, archive batches.RepoZip) (Workspace, error) { +func (wc *dockerVolumeWorkspaceCreator) Create(ctx context.Context, repo *graphql.Repository, steps []batcheslib.Step, archive batches.RepoZip) (Workspace, error) { volume, err := wc.createVolume(ctx) if err != nil { return nil, errors.Wrap(err, "creating Docker volume") diff --git a/internal/batches/workspace/volume_workspace_test.go b/internal/batches/workspace/volume_workspace_test.go index 74ceb349b1..ce0e813593 100644 --- a/internal/batches/workspace/volume_workspace_test.go +++ b/internal/batches/workspace/volume_workspace_test.go @@ -12,7 +12,7 @@ import ( "github.com/google/go-cmp/cmp" "github.com/pkg/errors" - "github.com/sourcegraph/src-cli/internal/batches" + batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/src-cli/internal/batches/docker" "github.com/sourcegraph/src-cli/internal/batches/git" "github.com/sourcegraph/src-cli/internal/batches/graphql" @@ -61,7 +61,7 @@ func TestVolumeWorkspaceCreator(t *testing.T) { for name, tc := range map[string]struct { archive *fakeRepoArchive expectations []*expect.Expectation - steps []batches.Step + steps []batcheslib.Step imageEnsurer imageEnsurer wantErr bool }{ @@ -99,7 +99,7 @@ func TestVolumeWorkspaceCreator(t *testing.T) { "sh", "/run.sh", ), }, - steps: []batches.Step{}, + steps: []batcheslib.Step{}, imageEnsurer: func(_ context.Context, _ string) (docker.Image, error) { return nil, nil }, }, "one root:root step": { @@ -136,7 +136,7 @@ func TestVolumeWorkspaceCreator(t *testing.T) { "sh", "/run.sh", ), }, - steps: []batches.Step{ + steps: []batcheslib.Step{ {}, }, imageEnsurer: func(_ context.Context, _ string) (docker.Image, error) { @@ -177,7 +177,7 @@ func TestVolumeWorkspaceCreator(t *testing.T) { "sh", "/run.sh", ), }, - steps: []batches.Step{ + steps: []batcheslib.Step{ {}, }, imageEnsurer: func(_ context.Context, _ string) (docker.Image, error) { @@ -191,7 +191,7 @@ func TestVolumeWorkspaceCreator(t *testing.T) { "docker", "volume", "create", ), }, - steps: []batches.Step{ + steps: []batcheslib.Step{ {}, }, imageEnsurer: func(_ context.Context, _ string) (docker.Image, error) { @@ -214,7 +214,7 @@ func TestVolumeWorkspaceCreator(t *testing.T) { "sh", "-c", "touch /work/*; chown -R 0:0 /work", ), }, - steps: []batches.Step{ + steps: []batcheslib.Step{ {}, }, imageEnsurer: func(_ context.Context, _ string) (docker.Image, error) { @@ -256,7 +256,7 @@ func TestVolumeWorkspaceCreator(t *testing.T) { "sh", "/run.sh", ), }, - steps: []batches.Step{ + steps: []batcheslib.Step{ {}, }, imageEnsurer: func(_ context.Context, _ string) (docker.Image, error) { @@ -289,7 +289,7 @@ func TestVolumeWorkspaceCreator(t *testing.T) { "sh", "-c", "unzip /tmp/zip; rm /work/*", ), }, - steps: []batches.Step{ + steps: []batcheslib.Step{ {}, }, imageEnsurer: func(_ context.Context, _ string) (docker.Image, error) { @@ -343,7 +343,7 @@ func TestVolumeWorkspaceCreator(t *testing.T) { "sh", "/run.sh", ), }, - steps: []batches.Step{ + steps: []batcheslib.Step{ {}, }, imageEnsurer: func(_ context.Context, _ string) (docker.Image, error) { diff --git a/internal/batches/workspace/workspace.go b/internal/batches/workspace/workspace.go index 1dac575d78..dad4e40c50 100644 --- a/internal/batches/workspace/workspace.go +++ b/internal/batches/workspace/workspace.go @@ -5,6 +5,7 @@ import ( "runtime" "github.com/pkg/errors" + batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/docker" "github.com/sourcegraph/src-cli/internal/batches/git" @@ -16,7 +17,7 @@ import ( // responsible for ultimately generating a diff. type Creator interface { // Create creates a new workspace for the given repository and archive file. - Create(ctx context.Context, repo *graphql.Repository, steps []batches.Step, archive batches.RepoZip) (Workspace, error) + Create(ctx context.Context, repo *graphql.Repository, steps []batcheslib.Step, archive batches.RepoZip) (Workspace, error) // Type returns the CreatorType of the Creator. Type() CreatorType diff --git a/schema/batch_spec.schema.json b/schema/batch_spec.schema.json deleted file mode 100644 index ae21f2479d..0000000000 --- a/schema/batch_spec.schema.json +++ /dev/null @@ -1,342 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "BatchSpec", - "description": "A batch specification, which describes the batch change and what kinds of changes to make (or what existing changesets to track).", - "type": "object", - "additionalProperties": false, - "required": ["name"], - "properties": { - "name": { - "type": "string", - "description": "The name of the batch change, which is unique among all batch changes in the namespace. A batch change's name is case-preserving.", - "pattern": "^[\\w.-]+$" - }, - "description": { - "type": "string", - "description": "The description of the batch change." - }, - "on": { - "type": "array", - "description": "The set of repositories (and branches) to run the batch change on, specified as a list of search queries (that match repositories) and/or specific repositories.", - "items": { - "title": "OnQueryOrRepository", - "oneOf": [ - { - "title": "OnQuery", - "type": "object", - "description": "A Sourcegraph search query that matches a set of repositories (and branches). Each matched repository branch is added to the list of repositories that the batch change will be run on.", - "additionalProperties": false, - "required": ["repositoriesMatchingQuery"], - "properties": { - "repositoriesMatchingQuery": { - "type": "string", - "description": "A Sourcegraph search query that matches a set of repositories (and branches). If the query matches files, symbols, or some other object inside a repository, the object's repository is included.", - "examples": ["file:README.md"] - } - } - }, - { - "title": "OnRepository", - "type": "object", - "description": "A specific repository (and branch) that is added to the list of repositories that the batch change will be run on.", - "additionalProperties": false, - "required": ["repository"], - "properties": { - "repository": { - "type": "string", - "description": "The name of the repository (as it is known to Sourcegraph).", - "examples": ["github.com/foo/bar"] - }, - "branch": { - "type": "string", - "description": "The branch on the repository to propose changes to. If unset, the repository's default branch is used." - } - } - } - ] - } - }, - "workspaces": { - "type": "array", - "description": "Individual workspace configurations for one or more repositories that define which workspaces to use for the execution of steps in the repositories.", - "items": { - "title": "WorkspaceConfiguration", - "type": "object", - "description": "Configuration for how to setup workspaces in repositories", - "additionalProperties": false, - "required": ["rootAtLocationOf"], - "properties": { - "rootAtLocationOf": { - "type": "string", - "description": "The name of the file that sits at the root of the desired workspace.", - "examples": [ - "package.json", - "go.mod", - "Gemfile", - "Cargo.toml", - "README.md" - ] - }, - "in": { - "type": "string", - "description": "The repositories in which to apply the workspace configuration. Supports globbing.", - "examples": [ - "github.com/sourcegraph/src-cli", - "github.com/sourcegraph/*" - ] - }, - "onlyFetchWorkspace": { - "type": "boolean", - "description": "If this is true only the files in the workspace (and additional .gitignore) are downloaded instead of an archive of the full repository.", - "default": false - } - } - } - }, - "steps": { - "type": "array", - "description": "The sequence of commands to run (for each repository branch matched in the `on` property) to produce the workspace changes that will be included in the batch change.", - "items": { - "title": "Step", - "type": "object", - "description": "A command to run (as part of a sequence) in a repository branch to produce the required changes.", - "additionalProperties": false, - "required": ["run", "container"], - "properties": { - "run": { - "type": "string", - "description": "The shell command to run in the container. It can also be a multi-line shell script. The working directory is the root directory of the repository checkout." - }, - "container": { - "type": "string", - "description": "The Docker image used to launch the Docker container in which the shell command is run.", - "examples": ["alpine:3"] - }, - "outputs": { - "type": "object", - "description": "Output variables of this step that can be referenced in the changesetTemplate or other steps via outputs.", - "additionalProperties": { - "type": "object", - "required": ["value"], - "properties": { - "value": { - "type": "string", - "description": "The value of the output, which can be a template string.", - "examples": [ - "hello world", - "${{ step.stdout }}", - "${{ repository.name }}" - ] - }, - "format": { - "type": "string", - "description": "The expected format of the output. If set, the output is being parsed in that format before being stored in the var. If not set, 'text' is assumed to the format.", - "enum": ["json", "yaml", "text"] - } - } - } - }, - "env": { - "description": "Environment variables to set in the step environment.", - "oneOf": [ - { - "type": "object", - "description": "Environment variables to set in the step environment.", - "additionalProperties": { - "type": "string" - } - }, - { - "type": "array", - "items": { - "oneOf": [ - { - "type": "string", - "description": "An environment variable to set in the step environment: the value will be passed through from the environment src is running within." - }, - { - "type": "object", - "description": "An environment variable to set in the step environment: the value will be passed through from the environment src is running within.", - "additionalProperties": { - "type": "string" - }, - "minProperties": 1, - "maxProperties": 1 - } - ] - } - } - ] - }, - "files": { - "type": "object", - "description": "Files that should be mounted into or be created inside the Docker container.", - "additionalProperties": { - "type": "string" - } - }, - "if": { - "oneOf": [{ "type": "boolean" }, { "type": "string" }], - "description": "A condition to check before executing steps. Supports templating. The value 'true' is interpreted as true.", - "examples": [ - "true", - "${{ matches repository.name \"github.com/my-org/my-repo*\" }}", - "${{ outputs.goModFileExists }}", - "${{ eq previous_step.stdout \"success\" }}" - ] - } - } - } - }, - "transformChanges": { - "type": "object", - "description": "Optional transformations to apply to the changes produced in each repository.", - "additionalProperties": false, - "properties": { - "group": { - "type": "array", - "description": "A list of groups of changes in a repository that each create a separate, additional changeset for this repository, with all ungrouped changes being in the default changeset.", - "additionalProperties": false, - "required": ["directory", "branchSuffix"], - "properties": { - "directory": { - "type": "string", - "description": "The directory path (relative to the repository root) of the changes to include in this group.", - "minLength": 1 - }, - "branch": { - "type": "string", - "description": "The branch on the repository to propose changes to. If unset, the repository's default branch is used.", - "minLength": 1 - }, - "repository": { - "type": "string", - "description": "Only apply this transformation in the repository with this name (as it is known to Sourcegraph).", - "examples": ["github.com/foo/bar"] - } - } - } - } - }, - "importChangesets": { - "type": "array", - "description": "Import existing changesets on code hosts.", - "items": { - "type": "object", - "additionalProperties": false, - "required": ["repository", "externalIDs"], - "properties": { - "repository": { - "type": "string", - "description": "The repository name as configured on your Sourcegraph instance." - }, - "externalIDs": { - "type": "array", - "description": "The changesets to import from the code host. For GitHub this is the PR number, for GitLab this is the MR number, for Bitbucket Server this is the PR number.", - "uniqueItems": true, - "items": { - "oneOf": [ - { - "type": "string" - }, - { - "type": "integer" - } - ] - }, - "examples": [120, "120"] - } - } - } - }, - "changesetTemplate": { - "type": "object", - "description": "A template describing how to create (and update) changesets with the file changes produced by the command steps.", - "additionalProperties": false, - "required": ["title", "branch", "commit"], - "properties": { - "title": { - "type": "string", - "description": "The title of the changeset." - }, - "body": { - "type": "string", - "description": "The body (description) of the changeset." - }, - "branch": { - "type": "string", - "description": "The name of the Git branch to create or update on each repository with the changes." - }, - "commit": { - "title": "ExpandedGitCommitDescription", - "type": "object", - "description": "The Git commit to create with the changes.", - "additionalProperties": false, - "required": ["message"], - "properties": { - "message": { - "type": "string", - "description": "The Git commit message." - }, - "author": { - "title": "GitCommitAuthor", - "type": "object", - "description": "The author of the Git commit.", - "additionalProperties": false, - "required": ["name", "email"], - "properties": { - "name": { - "type": "string", - "description": "The Git commit author name." - }, - "email": { - "type": "string", - "format": "email", - "description": "The Git commit author email." - } - } - } - } - }, - "published": { - "description": "Whether to publish the changeset. An unpublished changeset can be previewed on Sourcegraph by any person who can view the batch change, but its commit, branch, and pull request aren't created on the code host. A published changeset results in a commit, branch, and pull request being created on the code host. If omitted, the publication state is controlled from the Batch Changes UI.", - "oneOf": [ - { - "oneOf": [ - { - "type": "boolean" - }, - { - "type": "string", - "pattern": "^draft$" - } - ], - "description": "A single flag to control the publishing state for the entire batch change." - }, - { - "type": "array", - "description": "A list of glob patterns to match repository names. In the event multiple patterns match, the last matching pattern in the list will be used.", - "items": { - "type": "object", - "description": "An object with one field: the key is the glob pattern to match against repository names; the value will be used as the published flag for matching repositories.", - "additionalProperties": { - "oneOf": [ - { - "type": "boolean" - }, - { - "type": "string", - "pattern": "^draft$" - } - ] - }, - "minProperties": 1, - "maxProperties": 1 - } - } - ] - } - } - } - } -} diff --git a/schema/batch_spec_stringdata.go b/schema/batch_spec_stringdata.go deleted file mode 100644 index dfd7ad4bcf..0000000000 --- a/schema/batch_spec_stringdata.go +++ /dev/null @@ -1,348 +0,0 @@ -// Code generated by stringdata. DO NOT EDIT. - -package schema - -// BatchSpecJSON is the content of the file "batch_spec.schema.json". -const BatchSpecJSON = `{ - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "BatchSpec", - "description": "A batch specification, which describes the batch change and what kinds of changes to make (or what existing changesets to track).", - "type": "object", - "additionalProperties": false, - "required": ["name"], - "properties": { - "name": { - "type": "string", - "description": "The name of the batch change, which is unique among all batch changes in the namespace. A batch change's name is case-preserving.", - "pattern": "^[\\w.-]+$" - }, - "description": { - "type": "string", - "description": "The description of the batch change." - }, - "on": { - "type": "array", - "description": "The set of repositories (and branches) to run the batch change on, specified as a list of search queries (that match repositories) and/or specific repositories.", - "items": { - "title": "OnQueryOrRepository", - "oneOf": [ - { - "title": "OnQuery", - "type": "object", - "description": "A Sourcegraph search query that matches a set of repositories (and branches). Each matched repository branch is added to the list of repositories that the batch change will be run on.", - "additionalProperties": false, - "required": ["repositoriesMatchingQuery"], - "properties": { - "repositoriesMatchingQuery": { - "type": "string", - "description": "A Sourcegraph search query that matches a set of repositories (and branches). If the query matches files, symbols, or some other object inside a repository, the object's repository is included.", - "examples": ["file:README.md"] - } - } - }, - { - "title": "OnRepository", - "type": "object", - "description": "A specific repository (and branch) that is added to the list of repositories that the batch change will be run on.", - "additionalProperties": false, - "required": ["repository"], - "properties": { - "repository": { - "type": "string", - "description": "The name of the repository (as it is known to Sourcegraph).", - "examples": ["github.com/foo/bar"] - }, - "branch": { - "type": "string", - "description": "The branch on the repository to propose changes to. If unset, the repository's default branch is used." - } - } - } - ] - } - }, - "workspaces": { - "type": "array", - "description": "Individual workspace configurations for one or more repositories that define which workspaces to use for the execution of steps in the repositories.", - "items": { - "title": "WorkspaceConfiguration", - "type": "object", - "description": "Configuration for how to setup workspaces in repositories", - "additionalProperties": false, - "required": ["rootAtLocationOf"], - "properties": { - "rootAtLocationOf": { - "type": "string", - "description": "The name of the file that sits at the root of the desired workspace.", - "examples": [ - "package.json", - "go.mod", - "Gemfile", - "Cargo.toml", - "README.md" - ] - }, - "in": { - "type": "string", - "description": "The repositories in which to apply the workspace configuration. Supports globbing.", - "examples": [ - "github.com/sourcegraph/src-cli", - "github.com/sourcegraph/*" - ] - }, - "onlyFetchWorkspace": { - "type": "boolean", - "description": "If this is true only the files in the workspace (and additional .gitignore) are downloaded instead of an archive of the full repository.", - "default": false - } - } - } - }, - "steps": { - "type": "array", - "description": "The sequence of commands to run (for each repository branch matched in the ` + "`" + `on` + "`" + ` property) to produce the workspace changes that will be included in the batch change.", - "items": { - "title": "Step", - "type": "object", - "description": "A command to run (as part of a sequence) in a repository branch to produce the required changes.", - "additionalProperties": false, - "required": ["run", "container"], - "properties": { - "run": { - "type": "string", - "description": "The shell command to run in the container. It can also be a multi-line shell script. The working directory is the root directory of the repository checkout." - }, - "container": { - "type": "string", - "description": "The Docker image used to launch the Docker container in which the shell command is run.", - "examples": ["alpine:3"] - }, - "outputs": { - "type": "object", - "description": "Output variables of this step that can be referenced in the changesetTemplate or other steps via outputs.", - "additionalProperties": { - "type": "object", - "required": ["value"], - "properties": { - "value": { - "type": "string", - "description": "The value of the output, which can be a template string.", - "examples": [ - "hello world", - "${{ step.stdout }}", - "${{ repository.name }}" - ] - }, - "format": { - "type": "string", - "description": "The expected format of the output. If set, the output is being parsed in that format before being stored in the var. If not set, 'text' is assumed to the format.", - "enum": ["json", "yaml", "text"] - } - } - } - }, - "env": { - "description": "Environment variables to set in the step environment.", - "oneOf": [ - { - "type": "object", - "description": "Environment variables to set in the step environment.", - "additionalProperties": { - "type": "string" - } - }, - { - "type": "array", - "items": { - "oneOf": [ - { - "type": "string", - "description": "An environment variable to set in the step environment: the value will be passed through from the environment src is running within." - }, - { - "type": "object", - "description": "An environment variable to set in the step environment: the value will be passed through from the environment src is running within.", - "additionalProperties": { - "type": "string" - }, - "minProperties": 1, - "maxProperties": 1 - } - ] - } - } - ] - }, - "files": { - "type": "object", - "description": "Files that should be mounted into or be created inside the Docker container.", - "additionalProperties": { - "type": "string" - } - }, - "if": { - "oneOf": [{ "type": "boolean" }, { "type": "string" }], - "description": "A condition to check before executing steps. Supports templating. The value 'true' is interpreted as true.", - "examples": [ - "true", - "${{ matches repository.name \"github.com/my-org/my-repo*\" }}", - "${{ outputs.goModFileExists }}", - "${{ eq previous_step.stdout \"success\" }}" - ] - } - } - } - }, - "transformChanges": { - "type": "object", - "description": "Optional transformations to apply to the changes produced in each repository.", - "additionalProperties": false, - "properties": { - "group": { - "type": "array", - "description": "A list of groups of changes in a repository that each create a separate, additional changeset for this repository, with all ungrouped changes being in the default changeset.", - "additionalProperties": false, - "required": ["directory", "branchSuffix"], - "properties": { - "directory": { - "type": "string", - "description": "The directory path (relative to the repository root) of the changes to include in this group.", - "minLength": 1 - }, - "branch": { - "type": "string", - "description": "The branch on the repository to propose changes to. If unset, the repository's default branch is used.", - "minLength": 1 - }, - "repository": { - "type": "string", - "description": "Only apply this transformation in the repository with this name (as it is known to Sourcegraph).", - "examples": ["github.com/foo/bar"] - } - } - } - } - }, - "importChangesets": { - "type": "array", - "description": "Import existing changesets on code hosts.", - "items": { - "type": "object", - "additionalProperties": false, - "required": ["repository", "externalIDs"], - "properties": { - "repository": { - "type": "string", - "description": "The repository name as configured on your Sourcegraph instance." - }, - "externalIDs": { - "type": "array", - "description": "The changesets to import from the code host. For GitHub this is the PR number, for GitLab this is the MR number, for Bitbucket Server this is the PR number.", - "uniqueItems": true, - "items": { - "oneOf": [ - { - "type": "string" - }, - { - "type": "integer" - } - ] - }, - "examples": [120, "120"] - } - } - } - }, - "changesetTemplate": { - "type": "object", - "description": "A template describing how to create (and update) changesets with the file changes produced by the command steps.", - "additionalProperties": false, - "required": ["title", "branch", "commit"], - "properties": { - "title": { - "type": "string", - "description": "The title of the changeset." - }, - "body": { - "type": "string", - "description": "The body (description) of the changeset." - }, - "branch": { - "type": "string", - "description": "The name of the Git branch to create or update on each repository with the changes." - }, - "commit": { - "title": "ExpandedGitCommitDescription", - "type": "object", - "description": "The Git commit to create with the changes.", - "additionalProperties": false, - "required": ["message"], - "properties": { - "message": { - "type": "string", - "description": "The Git commit message." - }, - "author": { - "title": "GitCommitAuthor", - "type": "object", - "description": "The author of the Git commit.", - "additionalProperties": false, - "required": ["name", "email"], - "properties": { - "name": { - "type": "string", - "description": "The Git commit author name." - }, - "email": { - "type": "string", - "format": "email", - "description": "The Git commit author email." - } - } - } - } - }, - "published": { - "description": "Whether to publish the changeset. An unpublished changeset can be previewed on Sourcegraph by any person who can view the batch change, but its commit, branch, and pull request aren't created on the code host. A published changeset results in a commit, branch, and pull request being created on the code host. If omitted, the publication state is controlled from the Batch Changes UI.", - "oneOf": [ - { - "oneOf": [ - { - "type": "boolean" - }, - { - "type": "string", - "pattern": "^draft$" - } - ], - "description": "A single flag to control the publishing state for the entire batch change." - }, - { - "type": "array", - "description": "A list of glob patterns to match repository names. In the event multiple patterns match, the last matching pattern in the list will be used.", - "items": { - "type": "object", - "description": "An object with one field: the key is the glob pattern to match against repository names; the value will be used as the published flag for matching repositories.", - "additionalProperties": { - "oneOf": [ - { - "type": "boolean" - }, - { - "type": "string", - "pattern": "^draft$" - } - ] - }, - "minProperties": 1, - "maxProperties": 1 - } - } - ] - } - } - } - } -} -` diff --git a/schema/gen.go b/schema/gen.go deleted file mode 100644 index 6fbd6e1d13..0000000000 --- a/schema/gen.go +++ /dev/null @@ -1,4 +0,0 @@ -package schema - -//go:generate env GO111MODULE=on go run stringdata.go -i batch_spec.schema.json -name BatchSpecJSON -pkg schema -o batch_spec_stringdata.go -//go:generate gofmt -s -w batch_spec_stringdata.go diff --git a/schema/stringdata.go b/schema/stringdata.go deleted file mode 100644 index 8966a7322b..0000000000 --- a/schema/stringdata.go +++ /dev/null @@ -1,51 +0,0 @@ -// +build ignore - -package main - -import ( - "flag" - "fmt" - "io/ioutil" - "os" - "strings" -) - -var ( - inputFile = flag.String("i", "", "input file") - outputFile = flag.String("o", "", "output file") - constName = flag.String("name", "stringdata", "name of Go const") - pkgName = flag.String("pkg", "main", "Go package name") -) - -func main() { - flag.Parse() - - if *inputFile == "" || *outputFile == "" { - flag.Usage() - os.Exit(1) - } - - data, err := ioutil.ReadFile(*inputFile) - if err != nil { - fmt.Fprintln(os.Stderr, err) - os.Exit(1) - } - - output, err := os.Create(*outputFile) - if err != nil { - fmt.Fprintln(os.Stderr, err) - os.Exit(1) - } - defer output.Close() - fmt.Fprintln(output, "// Code generated by stringdata. DO NOT EDIT.") - fmt.Fprintln(output) - fmt.Fprintf(output, "package %s\n", *pkgName) - fmt.Fprintln(output) - fmt.Fprintf(output, "// %s is the content of the file %q.\n", *constName, *inputFile) - fmt.Fprintf(output, "const %s = %s", *constName, backtickStringLiteral(string(data))) - fmt.Fprintln(output) -} - -func backtickStringLiteral(data string) string { - return "`" + strings.Replace(data, "`", "` + \"`\" + `", -1) + "`" -} From 27dd60a9dcd0ef45e18d8396511a29fbd7eda9ba Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Mon, 23 Aug 2021 16:30:48 +0200 Subject: [PATCH 012/647] Slight refactor of package structures (#586) --- internal/batches/executor/changeset_specs.go | 17 +++--- .../batches/executor/changeset_specs_test.go | 3 +- internal/batches/executor/coordinator_test.go | 9 ++-- internal/batches/executor/executor_test.go | 11 ++-- internal/batches/executor/run_steps.go | 29 +++++----- internal/batches/executor/task.go | 7 +-- internal/batches/service/main_test.go | 13 +++++ internal/batches/service/service.go | 53 +++++++------------ internal/batches/service/service_test.go | 4 +- .../{executor => service}/task_builder.go | 28 +++++----- .../task_builder_test.go | 4 +- internal/batches/template/main_test.go | 13 +++++ .../{executor => template}/partial_eval.go | 6 +-- .../partial_eval_test.go | 4 +- .../{executor => template}/templating.go | 14 ++--- .../{executor => template}/templating_test.go | 10 ++-- 16 files changed, 122 insertions(+), 103 deletions(-) create mode 100644 internal/batches/service/main_test.go rename internal/batches/{executor => service}/task_builder.go (84%) rename internal/batches/{executor => service}/task_builder_test.go (98%) create mode 100644 internal/batches/template/main_test.go rename internal/batches/{executor => template}/partial_eval.go (98%) rename internal/batches/{executor => template}/partial_eval_test.go (98%) rename internal/batches/{executor => template}/templating.go (94%) rename internal/batches/{executor => template}/templating_test.go (97%) diff --git a/internal/batches/executor/changeset_specs.go b/internal/batches/executor/changeset_specs.go index 630a2aabf4..7183ffd364 100644 --- a/internal/batches/executor/changeset_specs.go +++ b/internal/batches/executor/changeset_specs.go @@ -8,6 +8,7 @@ import ( "github.com/sourcegraph/go-diff/diff" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/src-cli/internal/batches" + "github.com/sourcegraph/src-cli/internal/batches/template" ) var errOptionalPublishedUnsupported = errors.New(`This Sourcegraph version requires the "published" field to be specified in the batch spec; upgrade to version 3.30.0 or later to be able to omit the published field and control publication from the UI.`) @@ -15,9 +16,9 @@ var errOptionalPublishedUnsupported = errors.New(`This Sourcegraph version requi func createChangesetSpecs(task *Task, result executionResult, features batches.FeatureFlags) ([]*batches.ChangesetSpec, error) { repo := task.Repository.Name - tmplCtx := &ChangesetTemplateContext{ + tmplCtx := &template.ChangesetTemplateContext{ BatchChangeAttributes: *task.BatchChangeAttributes, - Steps: StepsContext{ + Steps: template.StepsContext{ Changes: result.ChangedFiles, Path: result.Path, }, @@ -36,27 +37,27 @@ func createChangesetSpecs(task *Task, result executionResult, features batches.F } } else { var err error - authorName, err = renderChangesetTemplateField("authorName", task.Template.Commit.Author.Name, tmplCtx) + authorName, err = template.RenderChangesetTemplateField("authorName", task.Template.Commit.Author.Name, tmplCtx) if err != nil { return nil, err } - authorEmail, err = renderChangesetTemplateField("authorEmail", task.Template.Commit.Author.Email, tmplCtx) + authorEmail, err = template.RenderChangesetTemplateField("authorEmail", task.Template.Commit.Author.Email, tmplCtx) if err != nil { return nil, err } } - title, err := renderChangesetTemplateField("title", task.Template.Title, tmplCtx) + title, err := template.RenderChangesetTemplateField("title", task.Template.Title, tmplCtx) if err != nil { return nil, err } - body, err := renderChangesetTemplateField("body", task.Template.Body, tmplCtx) + body, err := template.RenderChangesetTemplateField("body", task.Template.Body, tmplCtx) if err != nil { return nil, err } - message, err := renderChangesetTemplateField("message", task.Template.Commit.Message, tmplCtx) + message, err := template.RenderChangesetTemplateField("message", task.Template.Commit.Message, tmplCtx) if err != nil { return nil, err } @@ -64,7 +65,7 @@ func createChangesetSpecs(task *Task, result executionResult, features batches.F // TODO: As a next step, we should extend the ChangesetTemplateContext to also include // TransformChanges.Group and then change validateGroups and groupFileDiffs to, for each group, // render the branch name *before* grouping the diffs. - defaultBranch, err := renderChangesetTemplateField("branch", task.Template.Branch, tmplCtx) + defaultBranch, err := template.RenderChangesetTemplateField("branch", task.Template.Branch, tmplCtx) if err != nil { return nil, err } diff --git a/internal/batches/executor/changeset_specs_test.go b/internal/batches/executor/changeset_specs_test.go index 6d86a96b4b..0ebae2a99d 100644 --- a/internal/batches/executor/changeset_specs_test.go +++ b/internal/batches/executor/changeset_specs_test.go @@ -10,6 +10,7 @@ import ( batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/git" + "github.com/sourcegraph/src-cli/internal/batches/template" ) func TestCreateChangesetSpecs(t *testing.T) { @@ -46,7 +47,7 @@ func TestCreateChangesetSpecs(t *testing.T) { } defaultTask := &Task{ - BatchChangeAttributes: &BatchChangeAttributes{ + BatchChangeAttributes: &template.BatchChangeAttributes{ Name: "the name", Description: "The description", }, diff --git a/internal/batches/executor/coordinator_test.go b/internal/batches/executor/coordinator_test.go index 1c86cd35bf..287974f795 100644 --- a/internal/batches/executor/coordinator_test.go +++ b/internal/batches/executor/coordinator_test.go @@ -15,6 +15,7 @@ import ( "github.com/sourcegraph/src-cli/internal/batches/git" "github.com/sourcegraph/src-cli/internal/batches/graphql" "github.com/sourcegraph/src-cli/internal/batches/mock" + "github.com/sourcegraph/src-cli/internal/batches/template" ) func TestCoordinator_Execute(t *testing.T) { @@ -266,7 +267,7 @@ func TestCoordinator_Execute(t *testing.T) { for _, t := range tc.tasks { t.TransformChanges = tc.batchSpec.TransformChanges t.Template = tc.batchSpec.ChangesetTemplate - t.BatchChangeAttributes = &BatchChangeAttributes{ + t.BatchChangeAttributes = &template.BatchChangeAttributes{ Name: tc.batchSpec.Name, Description: tc.batchSpec.Description, } @@ -359,7 +360,7 @@ func TestCoordinator_Execute_StepCaching(t *testing.T) { {Run: `echo "three"`}, }, Repository: testRepo1, - BatchChangeAttributes: &BatchChangeAttributes{}, + BatchChangeAttributes: &template.BatchChangeAttributes{}, } executor := &dummyExecutor{} @@ -530,9 +531,7 @@ func (d *dummyTaskExecutionUI) TaskFinished(t *Task, err error) { d.mu.Lock() defer d.mu.Unlock() - if _, ok := d.started[t]; ok { - delete(d.started, t) - } + delete(d.started, t) if err != nil { d.finishedWithErr[t] = struct{}{} } else { diff --git a/internal/batches/executor/executor_test.go b/internal/batches/executor/executor_test.go index afc24628cf..d5af386d4c 100644 --- a/internal/batches/executor/executor_test.go +++ b/internal/batches/executor/executor_test.go @@ -23,6 +23,7 @@ import ( "github.com/sourcegraph/src-cli/internal/batches/docker" "github.com/sourcegraph/src-cli/internal/batches/git" "github.com/sourcegraph/src-cli/internal/batches/mock" + "github.com/sourcegraph/src-cli/internal/batches/template" "github.com/sourcegraph/src-cli/internal/batches/workspace" ) @@ -33,7 +34,7 @@ func TestExecutor_Integration(t *testing.T) { addToPath(t, "testdata/dummydocker") - defaultBatchChangeAttributes := &BatchChangeAttributes{ + defaultBatchChangeAttributes := &template.BatchChangeAttributes{ Name: "integration-test-batch-change", Description: "this is an integration test", } @@ -488,7 +489,7 @@ index 02a19af..c9644dd 100644 `) task := &Task{ - BatchChangeAttributes: &BatchChangeAttributes{}, + BatchChangeAttributes: &template.BatchChangeAttributes{}, Steps: []batcheslib.Step{ {Run: `echo -e "foobar\n" >> README.md`}, }, @@ -497,7 +498,7 @@ index 02a19af..c9644dd 100644 StepIndex: 0, Diff: cachedDiff, Outputs: map[string]interface{}{}, - PreviousStepResult: StepResult{}, + PreviousStepResult: template.StepResult{}, }, Repository: testRepo1, } @@ -594,7 +595,7 @@ index 0000000..257ae8e task := &Task{ Repository: testRepo1, - BatchChangeAttributes: &BatchChangeAttributes{}, + BatchChangeAttributes: &template.BatchChangeAttributes{}, Steps: []batcheslib.Step{ {Run: `echo "this is step 1" >> README.txt`}, {Run: `echo "this is step 2" >> README.md`}, @@ -615,7 +616,7 @@ echo "previous_step.modified_files=${{ previous_step.modified_files }}" >> READM Outputs: map[string]interface{}{ "myOutput": "my-output.txt", }, - PreviousStepResult: StepResult{ + PreviousStepResult: template.StepResult{ Files: &git.Changes{ Modified: []string{"README.md"}, Added: []string{"README.txt"}, diff --git a/internal/batches/executor/run_steps.go b/internal/batches/executor/run_steps.go index 6a18fcf97d..43de56c3c0 100644 --- a/internal/batches/executor/run_steps.go +++ b/internal/batches/executor/run_steps.go @@ -17,6 +17,7 @@ import ( batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/src-cli/internal/batches/git" "github.com/sourcegraph/src-cli/internal/batches/log" + "github.com/sourcegraph/src-cli/internal/batches/template" "github.com/sourcegraph/src-cli/internal/batches/workspace" yamlv3 "gopkg.in/yaml.v3" @@ -33,7 +34,7 @@ type stepExecutionResult struct { Outputs map[string]interface{} `json:"outputs"` // PreviousStepResult is the StepResult of the step before Step, if Step != // 0. - PreviousStepResult StepResult `json:"previousStepResult"` + PreviousStepResult template.StepResult `json:"previousStepResult"` } type executionResult struct { @@ -86,7 +87,7 @@ func runSteps(ctx context.Context, opts *executionOpts) (result executionResult, Outputs: make(map[string]interface{}), Path: opts.task.Path, } - previousStepResult StepResult + previousStepResult template.StepResult startStep int ) @@ -122,11 +123,11 @@ func runSteps(ctx context.Context, opts *executionOpts) (result executionResult, for i := startStep; i < len(opts.task.Steps); i++ { step := opts.task.Steps[i] - stepContext := StepContext{ + stepContext := template.StepContext{ BatchChange: *opts.task.BatchChangeAttributes, Repository: *opts.task.Repository, Outputs: execResult.Outputs, - Steps: StepsContext{ + Steps: template.StepsContext{ Path: execResult.Path, Changes: previousStepResult.Files, }, @@ -145,7 +146,7 @@ func runSteps(ctx context.Context, opts *executionOpts) (result executionResult, } } - cond, err := evalStepCondition(step.IfCondition(), &stepContext) + cond, err := template.EvalStepCondition(step.IfCondition(), &stepContext) if err != nil { return execResult, nil, errors.Wrap(err, "evaluating step condition") } @@ -172,7 +173,7 @@ func runSteps(ctx context.Context, opts *executionOpts) (result executionResult, return execResult, nil, errors.Wrap(err, "getting changed files in step") } - result := StepResult{Files: changes, Stdout: &stdoutBuffer, Stderr: &stderrBuffer} + result := template.StepResult{Files: changes, Stdout: &stdoutBuffer, Stderr: &stderrBuffer} // Set stepContext.Step to current step's results before rendering outputs stepContext.Step = result @@ -220,7 +221,7 @@ func executeSingleStep( i int, step batcheslib.Step, imageDigest string, - stepContext *StepContext, + stepContext *template.StepContext, ) (bytes.Buffer, bytes.Buffer, error) { // ---------- // PREPARATION @@ -259,7 +260,7 @@ func executeSingleStep( } // Render the step.Env variables as templates. - env, err := renderStepMap(stepEnv, stepContext) + env, err := template.RenderStepMap(stepEnv, stepContext) if err != nil { return bytes.Buffer{}, bytes.Buffer{}, errors.Wrap(err, "parsing step environment") } @@ -334,11 +335,11 @@ func executeSingleStep( return stdoutBuffer, stderrBuffer, nil } -func setOutputs(stepOutputs batcheslib.Outputs, global map[string]interface{}, stepCtx *StepContext) error { +func setOutputs(stepOutputs batcheslib.Outputs, global map[string]interface{}, stepCtx *template.StepContext) error { for name, output := range stepOutputs { var value bytes.Buffer - if err := renderStepTemplate("outputs-"+name, output.Value, &value, stepCtx); err != nil { + if err := template.RenderStepTemplate("outputs-"+name, output.Value, &value, stepCtx); err != nil { return errors.Wrap(err, "parsing step run") } @@ -414,9 +415,9 @@ func probeImageForShell(ctx context.Context, image string) (shell, tempfile stri // createFilesToMount creates temporary files with the contents of Step.Files // that are to be mounted into the container that executes the step. -func createFilesToMount(tempDir string, step batcheslib.Step, stepContext *StepContext) (map[string]*os.File, func(), error) { +func createFilesToMount(tempDir string, step batcheslib.Step, stepContext *template.StepContext) (map[string]*os.File, func(), error) { // Parse and render the step.Files. - files, err := renderStepMap(step.Files, stepContext) + files, err := template.RenderStepMap(step.Files, stepContext) if err != nil { return nil, nil, errors.Wrap(err, "parsing step files") } @@ -455,7 +456,7 @@ func createFilesToMount(tempDir string, step batcheslib.Step, stepContext *StepC // createRunScriptFile creates a temporary file and renders stepRun into it. // // It returns the location of the file, its content, a function to cleanup the file and possible errors. -func createRunScriptFile(ctx context.Context, tempDir string, stepRun string, stepCtx *StepContext) (string, string, func(), error) { +func createRunScriptFile(ctx context.Context, tempDir string, stepRun string, stepCtx *template.StepContext) (string, string, func(), error) { // Set up a temporary file on the host filesystem to contain the // script. runScriptFile, err := ioutil.TempFile(tempDir, "") @@ -468,7 +469,7 @@ func createRunScriptFile(ctx context.Context, tempDir string, stepRun string, st // temp file we just created. var runScript bytes.Buffer out := io.MultiWriter(&runScript, runScriptFile) - if err := renderStepTemplate("step-run", stepRun, out, stepCtx); err != nil { + if err := template.RenderStepTemplate("step-run", stepRun, out, stepCtx); err != nil { return "", "", nil, errors.Wrap(err, "parsing step run") } diff --git a/internal/batches/executor/task.go b/internal/batches/executor/task.go index 1ca36ddb87..76cc64c0a1 100644 --- a/internal/batches/executor/task.go +++ b/internal/batches/executor/task.go @@ -4,6 +4,7 @@ import ( batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/graphql" + "github.com/sourcegraph/src-cli/internal/batches/template" ) type Task struct { @@ -22,9 +23,9 @@ type Task struct { // TODO(mrnugget): this should just be a single BatchSpec field instead, if // we can make it work with caching - BatchChangeAttributes *BatchChangeAttributes `json:"-"` - Template *batcheslib.ChangesetTemplate `json:"-"` - TransformChanges *batcheslib.TransformChanges `json:"-"` + BatchChangeAttributes *template.BatchChangeAttributes `json:"-"` + Template *batcheslib.ChangesetTemplate `json:"-"` + TransformChanges *batcheslib.TransformChanges `json:"-"` Archive batches.RepoZip `json:"-"` diff --git a/internal/batches/service/main_test.go b/internal/batches/service/main_test.go new file mode 100644 index 0000000000..07883000b4 --- /dev/null +++ b/internal/batches/service/main_test.go @@ -0,0 +1,13 @@ +package service + +import "github.com/sourcegraph/src-cli/internal/batches/graphql" + +var testRepo1 = &graphql.Repository{ + ID: "src-cli", + Name: "github.com/sourcegraph/src-cli", + DefaultBranch: &graphql.Branch{Name: "main", Target: graphql.Target{OID: "d34db33f"}}, + FileMatches: map[string]bool{ + "README.md": true, + "main.go": true, + }, +} diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index 0b280c3bec..04ad873016 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -183,7 +183,7 @@ func (svc *Service) EnsureImage(ctx context.Context, name string) (docker.Image, } func (svc *Service) BuildTasks(ctx context.Context, repos []*graphql.Repository, spec *batcheslib.BatchSpec) ([]*executor.Task, error) { - return executor.BuildTasks(ctx, spec, svc, repos) + return buildTasks(ctx, spec, svc, repos) } func (svc *Service) NewCoordinator(opts executor.NewCoordinatorOpts) *executor.Coordinator { @@ -195,6 +195,8 @@ func (svc *Service) NewCoordinator(opts executor.NewCoordinatorOpts) *executor.C return executor.NewCoordinator(opts) } +// ValidateChangesetSpecs validates that among all branch changesets there are no +// duplicates in branch names in a single repo. func (svc *Service) ValidateChangesetSpecs(repos []*graphql.Repository, specs []*batches.ChangesetSpec) error { repoByID := make(map[string]*graphql.Repository, len(repos)) for _, repo := range repos { @@ -606,35 +608,32 @@ func (svc *Service) resolveRepositorySearch(ctx context.Context, query string) ( return repos, nil } -const findDirectoryQuery = ` -query DirectoriesContainingFile($query: String!) { - search(query: $query, version: V2) { - results { - results { - __typename - ... on FileMatch { - file { path } - } - } - } - } -} -` - // findDirectoriesResult maps the name of the GraphQL query to its results. The // name is the repository's ID. type findDirectoriesResult map[string]struct { Results struct{ Results []searchResult } } +const searchQueryTmpl = `%s: search(query: %q, version: V2) { + results { + results { + __typename + ... on FileMatch { + file { path } + } + } + } +} +` + +const findDirectoriesInReposBatchSize = 50 + // FindDirectoriesInRepos returns a map of repositories and the locations of // files matching the given file name in the repository. // The locations are paths relative to the root of the directory. // No "/" at the beginning. // A dot (".") represents the root directory. func (svc *Service) FindDirectoriesInRepos(ctx context.Context, fileName string, repos ...*graphql.Repository) (map[*graphql.Repository][]string, error) { - const batchSize = 50 - // Build up unique identifiers that are safe to use as GraphQL query aliases. reposByQueryID := map[string]*graphql.Repository{} queryIDByRepo := map[*graphql.Repository]string{} @@ -645,20 +644,8 @@ func (svc *Service) FindDirectoriesInRepos(ctx context.Context, fileName string, } findInBatch := func(batch []*graphql.Repository, results map[*graphql.Repository][]string) error { - const searchQueryTmpl = `%s: search(query: %q, version: V2) { - results { - results { - __typename - ... on FileMatch { - file { path } - } - } - } - } -` - var a strings.Builder - a.WriteString("query DirectoriesContainingFile() {\n") + a.WriteString("query DirectoriesContainingFile {\n") for _, repo := range batch { query := fmt.Sprintf(`file:(^|/)%s$ repo:^%s$ type:path count:99999`, regexp.QuoteMeta(fileName), regexp.QuoteMeta(repo.Name)) @@ -704,12 +691,12 @@ func (svc *Service) FindDirectoriesInRepos(ctx context.Context, fileName string, results := make(map[*graphql.Repository][]string) - for start := 0; start < len(repos); start += batchSize { + for start := 0; start < len(repos); start += findDirectoriesInReposBatchSize { if err := ctx.Err(); err != nil { return nil, err } - end := start + batchSize + end := start + findDirectoriesInReposBatchSize if end > len(repos) { end = len(repos) } diff --git a/internal/batches/service/service_test.go b/internal/batches/service/service_test.go index 44964ff504..8c6d08d3d6 100644 --- a/internal/batches/service/service_test.go +++ b/internal/batches/service/service_test.go @@ -327,8 +327,8 @@ func TestService_FindDirectoriesInRepos(t *testing.T) { fileName := "package.json" repos := []*graphql.Repository{ - {ID: "repo-id-0", Name: "github.com/sourcegraph/automation-testing"}, - {ID: "repo-id-1", Name: "github.com/sourcegraph/sourcegraph"}, + {ID: "repo-id-0", Name: "github.com/sourcegraph/automation-testing", Branch: graphql.Branch{Name: "main"}}, + {ID: "repo-id-1", Name: "github.com/sourcegraph/sourcegraph", Branch: graphql.Branch{Name: "dev"}}, } svc := &Service{client: client} diff --git a/internal/batches/executor/task_builder.go b/internal/batches/service/task_builder.go similarity index 84% rename from internal/batches/executor/task_builder.go rename to internal/batches/service/task_builder.go index e58072ac14..c90bd2e621 100644 --- a/internal/batches/executor/task_builder.go +++ b/internal/batches/service/task_builder.go @@ -1,4 +1,4 @@ -package executor +package service import ( "context" @@ -6,28 +6,30 @@ import ( "github.com/gobwas/glob" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" + "github.com/sourcegraph/src-cli/internal/batches/executor" "github.com/sourcegraph/src-cli/internal/batches/graphql" + "github.com/sourcegraph/src-cli/internal/batches/template" ) -type DirectoryFinder interface { +type directoryFinder interface { FindDirectoriesInRepos(ctx context.Context, fileName string, repos ...*graphql.Repository) (map[*graphql.Repository][]string, error) } type taskBuilder struct { spec *batcheslib.BatchSpec - finder DirectoryFinder + finder directoryFinder } -// BuildTasks returns tasks for all the workspaces determined for the given spec. -func BuildTasks(ctx context.Context, spec *batcheslib.BatchSpec, finder DirectoryFinder, repos []*graphql.Repository) ([]*Task, error) { +// buildTasks returns tasks for all the workspaces determined for the given spec. +func buildTasks(ctx context.Context, spec *batcheslib.BatchSpec, finder directoryFinder, repos []*graphql.Repository) ([]*executor.Task, error) { tb := &taskBuilder{spec: spec, finder: finder} return tb.buildAll(ctx, repos) } -func (tb *taskBuilder) buildTask(r *graphql.Repository, path string, onlyWorkspace bool) (*Task, bool, error) { - stepCtx := &StepContext{ +func (tb *taskBuilder) buildTask(r *graphql.Repository, path string, onlyWorkspace bool) (*executor.Task, bool, error) { + stepCtx := &template.StepContext{ Repository: *r, - BatchChange: BatchChangeAttributes{ + BatchChange: template.BatchChangeAttributes{ Name: tb.spec.Name, Description: tb.spec.Description, }, @@ -40,7 +42,7 @@ func (tb *taskBuilder) buildTask(r *graphql.Repository, path string, onlyWorkspa continue } - static, boolVal, err := isStaticBool(step.IfCondition(), stepCtx) + static, boolVal, err := template.IsStaticBool(step.IfCondition(), stepCtx) if err != nil { return nil, false, err } @@ -64,7 +66,7 @@ func (tb *taskBuilder) buildTask(r *graphql.Repository, path string, onlyWorkspa path = "" } - return &Task{ + return &executor.Task{ Repository: r, Path: path, Steps: taskSteps, @@ -72,21 +74,21 @@ func (tb *taskBuilder) buildTask(r *graphql.Repository, path string, onlyWorkspa TransformChanges: tb.spec.TransformChanges, Template: tb.spec.ChangesetTemplate, - BatchChangeAttributes: &BatchChangeAttributes{ + BatchChangeAttributes: &template.BatchChangeAttributes{ Name: tb.spec.Name, Description: tb.spec.Description, }, }, true, nil } -func (tb *taskBuilder) buildAll(ctx context.Context, repos []*graphql.Repository) ([]*Task, error) { +func (tb *taskBuilder) buildAll(ctx context.Context, repos []*graphql.Repository) ([]*executor.Task, error) { // Find workspaces in repositories, if configured workspaces, root, err := tb.findWorkspaces(ctx, repos, tb.spec.Workspaces) if err != nil { return nil, err } - var tasks []*Task + var tasks []*executor.Task for repo, ws := range workspaces { for _, path := range ws.paths { t, ok, err := tb.buildTask(repo, path, ws.onlyFetchWorkspace) diff --git a/internal/batches/executor/task_builder_test.go b/internal/batches/service/task_builder_test.go similarity index 98% rename from internal/batches/executor/task_builder_test.go rename to internal/batches/service/task_builder_test.go index cf4e7b1e0d..263bcc345e 100644 --- a/internal/batches/executor/task_builder_test.go +++ b/internal/batches/service/task_builder_test.go @@ -1,4 +1,4 @@ -package executor +package service import ( "context" @@ -263,7 +263,7 @@ func TestTaskBuilder_BuildAll_Workspaces(t *testing.T) { for name, tt := range tests { t.Run(name, func(t *testing.T) { finder := &mockDirectoryFinder{results: tt.finderResults} - tasks, err := BuildTasks(context.Background(), tt.spec, finder, repos) + tasks, err := buildTasks(context.Background(), tt.spec, finder, repos) if err != nil { t.Fatalf("unexpected err: %s", err) } diff --git a/internal/batches/template/main_test.go b/internal/batches/template/main_test.go new file mode 100644 index 0000000000..38a13e63e9 --- /dev/null +++ b/internal/batches/template/main_test.go @@ -0,0 +1,13 @@ +package template + +import "github.com/sourcegraph/src-cli/internal/batches/graphql" + +var testRepo1 = &graphql.Repository{ + ID: "src-cli", + Name: "github.com/sourcegraph/src-cli", + DefaultBranch: &graphql.Branch{Name: "main", Target: graphql.Target{OID: "d34db33f"}}, + FileMatches: map[string]bool{ + "README.md": true, + "main.go": true, + }, +} diff --git a/internal/batches/executor/partial_eval.go b/internal/batches/template/partial_eval.go similarity index 98% rename from internal/batches/executor/partial_eval.go rename to internal/batches/template/partial_eval.go index 36848fad5f..d1276c6b98 100644 --- a/internal/batches/executor/partial_eval.go +++ b/internal/batches/template/partial_eval.go @@ -1,4 +1,4 @@ -package executor +package template import ( "bytes" @@ -9,7 +9,7 @@ import ( "text/template/parse" ) -// isStaticBool parses the input as a text/template and attempts to evaluate it +// IsStaticBool parses the input as a text/template and attempts to evaluate it // with only the ahead-of-execution information available in StepContext. // // To do that it first calls parseAndPartialEval to evaluate the template as @@ -22,7 +22,7 @@ import ( // // If only text is left we check whether that text equals "true". The result of // that check is the second return value. -func isStaticBool(input string, ctx *StepContext) (isStatic bool, boolVal bool, err error) { +func IsStaticBool(input string, ctx *StepContext) (isStatic bool, boolVal bool, err error) { t, err := parseAndPartialEval(input, ctx) if err != nil { return false, false, err diff --git a/internal/batches/executor/partial_eval_test.go b/internal/batches/template/partial_eval_test.go similarity index 98% rename from internal/batches/executor/partial_eval_test.go rename to internal/batches/template/partial_eval_test.go index f6f9ba46ce..ec0d0b6f9c 100644 --- a/internal/batches/executor/partial_eval_test.go +++ b/internal/batches/template/partial_eval_test.go @@ -1,4 +1,4 @@ -package executor +package template import ( "testing" @@ -279,7 +279,7 @@ func TestIsStaticBool(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - isStatic, boolVal, err := isStaticBool(tt.template, partialEvalStepCtx) + isStatic, boolVal, err := IsStaticBool(tt.template, partialEvalStepCtx) if err != nil { t.Fatal(err) } diff --git a/internal/batches/executor/templating.go b/internal/batches/template/templating.go similarity index 94% rename from internal/batches/executor/templating.go rename to internal/batches/template/templating.go index a865a456ea..9fc9ff1226 100644 --- a/internal/batches/executor/templating.go +++ b/internal/batches/template/templating.go @@ -1,4 +1,4 @@ -package executor +package template import ( "bytes" @@ -41,20 +41,20 @@ func isTrueOutput(output interface{ String() string }) bool { return strings.TrimSpace(output.String()) == "true" } -func evalStepCondition(condition string, stepCtx *StepContext) (bool, error) { +func EvalStepCondition(condition string, stepCtx *StepContext) (bool, error) { if condition == "" { return true, nil } var out bytes.Buffer - if err := renderStepTemplate("step-condition", condition, &out, stepCtx); err != nil { + if err := RenderStepTemplate("step-condition", condition, &out, stepCtx); err != nil { return false, errors.Wrap(err, "parsing step if") } return isTrueOutput(&out), nil } -func renderStepTemplate(name, tmpl string, out io.Writer, stepCtx *StepContext) error { +func RenderStepTemplate(name, tmpl string, out io.Writer, stepCtx *StepContext) error { t, err := template.New(name).Delims(startDelim, endDelim).Funcs(builtins).Funcs(stepCtx.ToFuncMap()).Parse(tmpl) if err != nil { return errors.Wrap(err, "parsing step run") @@ -63,13 +63,13 @@ func renderStepTemplate(name, tmpl string, out io.Writer, stepCtx *StepContext) return t.Execute(out, stepCtx) } -func renderStepMap(m map[string]string, stepCtx *StepContext) (map[string]string, error) { +func RenderStepMap(m map[string]string, stepCtx *StepContext) (map[string]string, error) { rendered := make(map[string]string, len(m)) for k, v := range m { var out bytes.Buffer - if err := renderStepTemplate(k, v, &out, stepCtx); err != nil { + if err := RenderStepTemplate(k, v, &out, stepCtx); err != nil { return rendered, err } @@ -270,7 +270,7 @@ func (tmplCtx *ChangesetTemplateContext) ToFuncMap() template.FuncMap { } } -func renderChangesetTemplateField(name, tmpl string, tmplCtx *ChangesetTemplateContext) (string, error) { +func RenderChangesetTemplateField(name, tmpl string, tmplCtx *ChangesetTemplateContext) (string, error) { var out bytes.Buffer t, err := template.New(name).Delims(startDelim, endDelim).Funcs(builtins).Funcs(tmplCtx.ToFuncMap()).Parse(tmpl) diff --git a/internal/batches/executor/templating_test.go b/internal/batches/template/templating_test.go similarity index 97% rename from internal/batches/executor/templating_test.go rename to internal/batches/template/templating_test.go index be9571d43e..d9e1d62160 100644 --- a/internal/batches/executor/templating_test.go +++ b/internal/batches/template/templating_test.go @@ -1,4 +1,4 @@ -package executor +package template import ( "bytes" @@ -51,7 +51,7 @@ func TestEvalStepCondition(t *testing.T) { } for _, tc := range tests { - got, err := evalStepCondition(tc.run, stepCtx) + got, err := EvalStepCondition(tc.run, stepCtx) if err != nil { t.Fatal(err) } @@ -217,7 +217,7 @@ ${{ steps.path }} t.Run(tc.name, func(t *testing.T) { var out bytes.Buffer - err := renderStepTemplate("testing", tc.run, &out, tc.stepCtx) + err := RenderStepTemplate("testing", tc.run, &out, tc.stepCtx) if err != nil { t.Fatal(err) } @@ -246,7 +246,7 @@ func TestRenderStepMap(t *testing.T) { "/tmp/my-other-file2.txt": `${{ previous_step.deleted_files }}`, } - have, err := renderStepMap(input, stepCtx) + have, err := RenderStepMap(input, stepCtx) if err != nil { t.Fatalf("unexpected error: %s", err) } @@ -348,7 +348,7 @@ ${{ steps.renamed_files }} for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { - out, err := renderChangesetTemplateField("testing", tc.tmpl, tc.tmplCtx) + out, err := RenderChangesetTemplateField("testing", tc.tmpl, tc.tmplCtx) if err != nil { t.Fatal(err) } From 2efc5448237d3f41a06141529c0894d222015c58 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Tue, 24 Aug 2021 12:24:14 +0200 Subject: [PATCH 013/647] Refactor workspaces (#588) --- cmd/src/batch_common.go | 6 +- internal/batches/errors.go | 6 + internal/batches/executor/task.go | 2 +- internal/batches/service/service.go | 8 +- internal/batches/service/task_builder.go | 115 +++---------- internal/batches/service/task_builder_test.go | 161 ------------------ internal/batches/service/workspaces.go | 108 ++++++++++++ internal/batches/service/workspaces_test.go | 139 +++++++++++++++ 8 files changed, 284 insertions(+), 261 deletions(-) create mode 100644 internal/batches/service/workspaces.go create mode 100644 internal/batches/service/workspaces_test.go diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index def1cbab20..2bd895ad17 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -275,7 +275,11 @@ func executeBatchSpec(ctx context.Context, opts executeBatchSpecOpts) (err error } opts.ui.DeterminingWorkspaces() - tasks, err := svc.BuildTasks(ctx, repos, batchSpec) + workspaces, err := svc.DetermineWorkspaces(ctx, repos, batchSpec) + if err != nil { + return err + } + tasks, err := svc.BuildTasks(ctx, repos, batchSpec, workspaces) if err != nil { return err } diff --git a/internal/batches/errors.go b/internal/batches/errors.go index 13f8e4794a..763f7d78a2 100644 --- a/internal/batches/errors.go +++ b/internal/batches/errors.go @@ -77,3 +77,9 @@ func (e IgnoredRepoSet) Append(repo *graphql.Repository) { func (e IgnoredRepoSet) HasIgnored() bool { return len(e) > 0 } + +type ValidationError struct{ Reason string } + +func (e ValidationError) Error() string { + return fmt.Sprintf("validation failed: %s", e.Reason) +} diff --git a/internal/batches/executor/task.go b/internal/batches/executor/task.go index 76cc64c0a1..1faec41177 100644 --- a/internal/batches/executor/task.go +++ b/internal/batches/executor/task.go @@ -11,7 +11,7 @@ type Task struct { Repository *graphql.Repository // Path is the folder relative to the repository's root in which the steps - // should be executed. + // should be executed. "" means root. Path string // OnlyFetchWorkspace determines whether the repository archive contains // the complete repository or just the files in Path (and additional files, diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index 04ad873016..c693eb0344 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -182,8 +182,12 @@ func (svc *Service) EnsureImage(ctx context.Context, name string) (docker.Image, return img, nil } -func (svc *Service) BuildTasks(ctx context.Context, repos []*graphql.Repository, spec *batcheslib.BatchSpec) ([]*executor.Task, error) { - return buildTasks(ctx, spec, svc, repos) +func (svc *Service) DetermineWorkspaces(ctx context.Context, repos []*graphql.Repository, spec *batcheslib.BatchSpec) ([]RepoWorkspaces, error) { + return findWorkspaces(ctx, spec, svc, repos) +} + +func (svc *Service) BuildTasks(ctx context.Context, repos []*graphql.Repository, spec *batcheslib.BatchSpec, workspaces []RepoWorkspaces) ([]*executor.Task, error) { + return buildTasks(ctx, spec, svc, repos, workspaces) } func (svc *Service) NewCoordinator(opts executor.NewCoordinatorOpts) *executor.Coordinator { diff --git a/internal/batches/service/task_builder.go b/internal/batches/service/task_builder.go index c90bd2e621..63906b2df7 100644 --- a/internal/batches/service/task_builder.go +++ b/internal/batches/service/task_builder.go @@ -2,9 +2,8 @@ package service import ( "context" - "fmt" - "github.com/gobwas/glob" + "github.com/pkg/errors" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/src-cli/internal/batches/executor" "github.com/sourcegraph/src-cli/internal/batches/graphql" @@ -21,9 +20,9 @@ type taskBuilder struct { } // buildTasks returns tasks for all the workspaces determined for the given spec. -func buildTasks(ctx context.Context, spec *batcheslib.BatchSpec, finder directoryFinder, repos []*graphql.Repository) ([]*executor.Task, error) { +func buildTasks(ctx context.Context, spec *batcheslib.BatchSpec, finder directoryFinder, repos []*graphql.Repository, workspaces []RepoWorkspaces) ([]*executor.Task, error) { tb := &taskBuilder{spec: spec, finder: finder} - return tb.buildAll(ctx, repos) + return tb.buildAll(ctx, repos, workspaces) } func (tb *taskBuilder) buildTask(r *graphql.Repository, path string, onlyWorkspace bool) (*executor.Task, bool, error) { @@ -81,17 +80,24 @@ func (tb *taskBuilder) buildTask(r *graphql.Repository, path string, onlyWorkspa }, true, nil } -func (tb *taskBuilder) buildAll(ctx context.Context, repos []*graphql.Repository) ([]*executor.Task, error) { - // Find workspaces in repositories, if configured - workspaces, root, err := tb.findWorkspaces(ctx, repos, tb.spec.Workspaces) - if err != nil { - return nil, err +func (tb *taskBuilder) buildAll(ctx context.Context, repos []*graphql.Repository, workspaces []RepoWorkspaces) ([]*executor.Task, error) { + repoByID := make(map[string]*graphql.Repository) + for _, repo := range repos { + repoByID[repo.ID] = repo } - var tasks []*executor.Task - for repo, ws := range workspaces { - for _, path := range ws.paths { - t, ok, err := tb.buildTask(repo, path, ws.onlyFetchWorkspace) + tasks := []*executor.Task{} + for _, ws := range workspaces { + repo, ok := repoByID[ws.RepoID] + if !ok { + return nil, errors.New("invalid state, didn't find repo for workspace definition") + } + for _, path := range ws.Paths { + fetchWorkspace := ws.OnlyFetchWorkspace + if path == "" { + fetchWorkspace = false + } + t, ok, err := tb.buildTask(repo, path, fetchWorkspace) if err != nil { return nil, err } @@ -102,88 +108,5 @@ func (tb *taskBuilder) buildAll(ctx context.Context, repos []*graphql.Repository } } - for _, repo := range root { - t, ok, err := tb.buildTask(repo, "", false) - if err != nil { - return nil, err - } - - if ok { - tasks = append(tasks, t) - } - } - return tasks, nil } - -type repoWorkspaces struct { - paths []string - onlyFetchWorkspace bool -} - -// findWorkspaces matches the given repos to the workspace configs and -// searches, via the Sourcegraph instance, the locations of the workspaces in -// each repository. -// The repositories that were matched by a workspace config are returned in -// workspaces. root contains the repositories that didn't match a config. -// If the user didn't specify any workspaces, the repositories are returned as -// root repositories. -func (tb *taskBuilder) findWorkspaces( - ctx context.Context, - repos []*graphql.Repository, - configs []batcheslib.WorkspaceConfiguration, -) (workspaces map[*graphql.Repository]repoWorkspaces, root []*graphql.Repository, err error) { - if len(configs) == 0 { - return nil, repos, nil - } - - workspaceMatchers := make(map[batcheslib.WorkspaceConfiguration]glob.Glob) - for _, conf := range tb.spec.Workspaces { - g, err := glob.Compile(conf.In) - if err != nil { - return nil, nil, err - } - workspaceMatchers[conf] = g - } - - matched := map[int][]*graphql.Repository{} - - for _, repo := range repos { - found := false - - for idx, conf := range configs { - if !workspaceMatchers[conf].Match(repo.Name) { - continue - } - - if found { - return nil, nil, fmt.Errorf("repository %s matches multiple workspaces.in globs in the batch spec. glob: %q", repo.Name, conf.In) - } - - matched[idx] = append(matched[idx], repo) - found = true - } - - if !found { - root = append(root, repo) - } - } - - workspaces = map[*graphql.Repository]repoWorkspaces{} - for idx, repos := range matched { - conf := configs[idx] - repoDirs, err := tb.finder.FindDirectoriesInRepos(ctx, conf.RootAtLocationOf, repos...) - if err != nil { - return nil, nil, err - } - - for repo, dirs := range repoDirs { - workspaces[repo] = repoWorkspaces{ - paths: dirs, - onlyFetchWorkspace: conf.OnlyFetchWorkspace, - } - } - } - - return workspaces, root, nil -} diff --git a/internal/batches/service/task_builder_test.go b/internal/batches/service/task_builder_test.go index 263bcc345e..5c1f6d62d8 100644 --- a/internal/batches/service/task_builder_test.go +++ b/internal/batches/service/task_builder_test.go @@ -1,14 +1,11 @@ package service import ( - "context" - "sort" "testing" "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" - "github.com/sourcegraph/src-cli/internal/batches/graphql" ) func TestTaskBuilder_BuildTask_IfConditions(t *testing.T) { @@ -140,161 +137,3 @@ func TestTaskBuilder_BuildTask_IfConditions(t *testing.T) { }) } } - -func TestTaskBuilder_BuildAll_Workspaces(t *testing.T) { - repos := []*graphql.Repository{ - {ID: "repo-id-0", Name: "github.com/sourcegraph/automation-testing"}, - {ID: "repo-id-1", Name: "github.com/sourcegraph/sourcegraph"}, - {ID: "repo-id-2", Name: "bitbucket.sgdev.org/SOUR/automation-testing"}, - } - steps := []batcheslib.Step{{Run: "echo 1"}} - - type finderResults map[*graphql.Repository][]string - - type wantTask struct { - Path string - ArchivePathToFetch string - } - - tests := map[string]struct { - spec *batcheslib.BatchSpec - finderResults map[*graphql.Repository][]string - - wantNumTasks int - - // tasks per repository ID and in which path they are executed - wantTasks map[string][]wantTask - }{ - "no workspace configuration": { - spec: &batcheslib.BatchSpec{Steps: steps}, - finderResults: finderResults{}, - wantNumTasks: len(repos), - wantTasks: map[string][]wantTask{ - repos[0].ID: {{Path: ""}}, - repos[1].ID: {{Path: ""}}, - repos[2].ID: {{Path: ""}}, - }, - }, - - "workspace configuration matching no repos": { - spec: &batcheslib.BatchSpec{ - Steps: steps, - Workspaces: []batcheslib.WorkspaceConfiguration{ - {In: "this-does-not-match", RootAtLocationOf: "package.json"}, - }, - }, - finderResults: finderResults{}, - wantNumTasks: len(repos), - wantTasks: map[string][]wantTask{ - repos[0].ID: {{Path: ""}}, - repos[1].ID: {{Path: ""}}, - repos[2].ID: {{Path: ""}}, - }, - }, - - "workspace configuration matching 2 repos with no results": { - spec: &batcheslib.BatchSpec{ - Steps: steps, - Workspaces: []batcheslib.WorkspaceConfiguration{ - {In: "*automation-testing", RootAtLocationOf: "package.json"}, - }, - }, - finderResults: finderResults{ - repos[0]: []string{}, - repos[2]: []string{}, - }, - wantNumTasks: 1, - wantTasks: map[string][]wantTask{ - repos[1].ID: {{Path: ""}}, - }, - }, - - "workspace configuration matching 2 repos with 3 results each": { - spec: &batcheslib.BatchSpec{ - Steps: steps, - Workspaces: []batcheslib.WorkspaceConfiguration{ - {In: "*automation-testing", RootAtLocationOf: "package.json"}, - }, - }, - finderResults: finderResults{ - repos[0]: {"a/b", "a/b/c", "d/e/f"}, - repos[2]: {"a/b", "a/b/c", "d/e/f"}, - }, - wantNumTasks: 7, - wantTasks: map[string][]wantTask{ - repos[0].ID: {{Path: "a/b"}, {Path: "a/b/c"}, {Path: "d/e/f"}}, - repos[1].ID: {{Path: ""}}, - repos[2].ID: {{Path: "a/b"}, {Path: "a/b/c"}, {Path: "d/e/f"}}, - }, - }, - - "workspace configuration matches repo with OnlyFetchWorkspace": { - spec: &batcheslib.BatchSpec{ - Steps: steps, - Workspaces: []batcheslib.WorkspaceConfiguration{ - { - OnlyFetchWorkspace: true, - In: "*automation-testing", - RootAtLocationOf: "package.json", - }, - }, - }, - finderResults: finderResults{ - repos[0]: {"a/b", "a/b/c", "d/e/f"}, - repos[2]: {"a/b", "a/b/c", "d/e/f"}, - }, - wantNumTasks: 7, - wantTasks: map[string][]wantTask{ - repos[0].ID: { - {Path: "a/b", ArchivePathToFetch: "a/b"}, - {Path: "a/b/c", ArchivePathToFetch: "a/b/c"}, - {Path: "d/e/f", ArchivePathToFetch: "d/e/f"}, - }, - repos[1].ID: {{Path: ""}}, - repos[2].ID: { - {Path: "a/b", ArchivePathToFetch: "a/b"}, - {Path: "a/b/c", ArchivePathToFetch: "a/b/c"}, - {Path: "d/e/f", ArchivePathToFetch: "d/e/f"}, - }, - }, - }, - } - - for name, tt := range tests { - t.Run(name, func(t *testing.T) { - finder := &mockDirectoryFinder{results: tt.finderResults} - tasks, err := buildTasks(context.Background(), tt.spec, finder, repos) - if err != nil { - t.Fatalf("unexpected err: %s", err) - } - - if have := len(tasks); have != tt.wantNumTasks { - t.Fatalf("wrong number of tasks. want=%d, got=%d", tt.wantNumTasks, have) - } - - haveTasks := map[string][]wantTask{} - for _, task := range tasks { - haveTasks[task.Repository.ID] = append(haveTasks[task.Repository.ID], wantTask{ - Path: task.Path, - ArchivePathToFetch: task.ArchivePathToFetch(), - }) - } - - for _, tasks := range haveTasks { - sort.Slice(tasks, func(i, j int) bool { return tasks[i].Path < tasks[j].Path }) - } - - if diff := cmp.Diff(tt.wantTasks, haveTasks); diff != "" { - t.Errorf("mismatch (-want +got):\n%s", diff) - } - }) - } -} - -type mockDirectoryFinder struct { - results map[*graphql.Repository][]string -} - -func (m *mockDirectoryFinder) FindDirectoriesInRepos(ctx context.Context, fileName string, repos ...*graphql.Repository) (map[*graphql.Repository][]string, error) { - return m.results, nil -} diff --git a/internal/batches/service/workspaces.go b/internal/batches/service/workspaces.go new file mode 100644 index 0000000000..1febb1d58c --- /dev/null +++ b/internal/batches/service/workspaces.go @@ -0,0 +1,108 @@ +package service + +import ( + "context" + "fmt" + + "github.com/gobwas/glob" + batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" + "github.com/sourcegraph/src-cli/internal/batches" + "github.com/sourcegraph/src-cli/internal/batches/graphql" +) + +type RepoWorkspaces struct { + RepoID string + Paths []string + OnlyFetchWorkspace bool +} + +// findWorkspaces matches the given repos to the workspace configs and +// searches, via the Sourcegraph instance, the locations of the workspaces in +// each repository. +// The repositories that were matched by a workspace config and all repos that didn't +// match a config are returned as workspaces. +func findWorkspaces( + ctx context.Context, + spec *batcheslib.BatchSpec, + finder directoryFinder, + repos []*graphql.Repository, +) ([]RepoWorkspaces, error) { + // Pre-compile all globs. + workspaceMatchers := make(map[batcheslib.WorkspaceConfiguration]glob.Glob) + for _, conf := range spec.Workspaces { + g, err := glob.Compile(conf.In) + if err != nil { + return nil, batches.ValidationError{Reason: fmt.Sprintf("failed to compile glob %q: %v", conf.In, err)} + } + workspaceMatchers[conf] = g + } + + root := []*graphql.Repository{} + + // Maps workspace config indexes to repositories matching them. + matched := map[int][]*graphql.Repository{} + + for _, repo := range repos { + found := false + + // Try to find a workspace configuration matching this repo. + for idx, conf := range spec.Workspaces { + if !workspaceMatchers[conf].Match(repo.Name) { + continue + } + + // Don't allow duplicate matches. + if found { + return nil, batches.ValidationError{Reason: fmt.Sprintf("repository %s matches multiple workspaces.in globs in the batch spec. glob: %q", repo.Name, conf.In)} + } + + matched[idx] = append(matched[idx], repo) + found = true + } + + if !found { + root = append(root, repo) + } + } + + workspacesByID := map[string]RepoWorkspaces{} + for idx, repos := range matched { + conf := spec.Workspaces[idx] + repoDirs, err := finder.FindDirectoriesInRepos(ctx, conf.RootAtLocationOf, repos...) + if err != nil { + return nil, err + } + + for repo, dirs := range repoDirs { + // Don't add repos that don't have any matched workspaces. + if len(dirs) == 0 { + continue + } + workspacesByID[repo.ID] = RepoWorkspaces{ + RepoID: repo.ID, + Paths: dirs, + OnlyFetchWorkspace: conf.OnlyFetchWorkspace, + } + } + } + + // And add the root for repos. + for _, repo := range root { + conf, ok := workspacesByID[repo.ID] + if !ok { + workspacesByID[repo.ID] = RepoWorkspaces{ + RepoID: repo.ID, + Paths: []string{""}, + OnlyFetchWorkspace: false, + } + continue + } + conf.Paths = append(workspacesByID[repo.ID].Paths, "") + } + + workspaces := make([]RepoWorkspaces, 0, len(workspacesByID)) + for _, workspace := range workspacesByID { + workspaces = append(workspaces, workspace) + } + return workspaces, nil +} diff --git a/internal/batches/service/workspaces_test.go b/internal/batches/service/workspaces_test.go new file mode 100644 index 0000000000..2475ad12f2 --- /dev/null +++ b/internal/batches/service/workspaces_test.go @@ -0,0 +1,139 @@ +package service + +import ( + "context" + "sort" + "testing" + + "github.com/google/go-cmp/cmp" + batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" + "github.com/sourcegraph/src-cli/internal/batches/graphql" +) + +func TestTaskBuilder_BuildAll_Workspaces(t *testing.T) { + repos := []*graphql.Repository{ + {ID: "repo-id-0", Name: "github.com/sourcegraph/automation-testing"}, + {ID: "repo-id-1", Name: "github.com/sourcegraph/sourcegraph"}, + {ID: "repo-id-2", Name: "bitbucket.sgdev.org/SOUR/automation-testing"}, + } + steps := []batcheslib.Step{{Run: "echo 1"}} + + type finderResults map[*graphql.Repository][]string + + tests := map[string]struct { + spec *batcheslib.BatchSpec + finderResults map[*graphql.Repository][]string + + // tasks per repository ID and in which path they are executed + wantTasks []RepoWorkspaces + }{ + "no workspace configuration": { + spec: &batcheslib.BatchSpec{Steps: steps}, + finderResults: finderResults{}, + wantTasks: []RepoWorkspaces{ + {RepoID: repos[0].ID, Paths: []string{""}}, + {RepoID: repos[1].ID, Paths: []string{""}}, + {RepoID: repos[2].ID, Paths: []string{""}}, + }, + }, + + "workspace configuration matching no repos": { + spec: &batcheslib.BatchSpec{ + Steps: steps, + Workspaces: []batcheslib.WorkspaceConfiguration{ + {In: "this-does-not-match", RootAtLocationOf: "package.json"}, + }, + }, + finderResults: finderResults{}, + wantTasks: []RepoWorkspaces{ + {RepoID: repos[0].ID, Paths: []string{""}}, + {RepoID: repos[1].ID, Paths: []string{""}}, + {RepoID: repos[2].ID, Paths: []string{""}}, + }, + }, + + "workspace configuration matching 2 repos with no results": { + spec: &batcheslib.BatchSpec{ + Steps: steps, + Workspaces: []batcheslib.WorkspaceConfiguration{ + {In: "*automation-testing", RootAtLocationOf: "package.json"}, + }, + }, + finderResults: finderResults{ + repos[0]: []string{}, + repos[2]: []string{}, + }, + wantTasks: []RepoWorkspaces{ + {RepoID: repos[1].ID, Paths: []string{""}}, + }, + }, + + "workspace configuration matching 2 repos with 3 results each": { + spec: &batcheslib.BatchSpec{ + Steps: steps, + Workspaces: []batcheslib.WorkspaceConfiguration{ + {In: "*automation-testing", RootAtLocationOf: "package.json"}, + }, + }, + finderResults: finderResults{ + repos[0]: {"a/b", "a/b/c", "d/e/f"}, + repos[2]: {"a/b", "a/b/c", "d/e/f"}, + }, + wantTasks: []RepoWorkspaces{ + {RepoID: repos[0].ID, Paths: []string{"a/b", "a/b/c", "d/e/f"}}, + {RepoID: repos[1].ID, Paths: []string{""}}, + {RepoID: repos[2].ID, Paths: []string{"a/b", "a/b/c", "d/e/f"}}, + }, + }, + + "workspace configuration matches repo with OnlyFetchWorkspace": { + spec: &batcheslib.BatchSpec{ + Steps: steps, + Workspaces: []batcheslib.WorkspaceConfiguration{ + { + OnlyFetchWorkspace: true, + In: "*automation-testing", + RootAtLocationOf: "package.json", + }, + }, + }, + finderResults: finderResults{ + repos[0]: {"a/b", "a/b/c", "d/e/f"}, + repos[2]: {"a/b", "a/b/c", "d/e/f"}, + }, + wantTasks: []RepoWorkspaces{ + {RepoID: repos[0].ID, Paths: []string{"a/b", "a/b/c", "d/e/f"}, OnlyFetchWorkspace: true}, + {RepoID: repos[1].ID, Paths: []string{""}}, + {RepoID: repos[2].ID, Paths: []string{"a/b", "a/b/c", "d/e/f"}, OnlyFetchWorkspace: true}, + }, + }, + } + + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + finder := &mockDirectoryFinder{results: tt.finderResults} + workspaces, err := findWorkspaces(context.Background(), tt.spec, finder, repos) + if err != nil { + t.Fatalf("unexpected err: %s", err) + } + + sort.Slice(workspaces, func(i, j int) bool { return workspaces[i].RepoID < workspaces[j].RepoID }) + + for _, workspace := range workspaces { + sort.Slice(workspace.Paths, func(i, j int) bool { return workspace.Paths[i] < workspace.Paths[j] }) + } + + if diff := cmp.Diff(tt.wantTasks, workspaces); diff != "" { + t.Errorf("mismatch (-want +got):\n%s", diff) + } + }) + } +} + +type mockDirectoryFinder struct { + results map[*graphql.Repository][]string +} + +func (m *mockDirectoryFinder) FindDirectoriesInRepos(ctx context.Context, fileName string, repos ...*graphql.Repository) (map[*graphql.Repository][]string, error) { + return m.results, nil +} From 908fcad61c5bcaec0310e6eb3d3191debfcc5eb7 Mon Sep 17 00:00:00 2001 From: Thorsten Ball Date: Tue, 24 Aug 2021 17:16:07 +0200 Subject: [PATCH 014/647] Use correct ref when finding directories in repos (#587) --- internal/batches/service/service.go | 2 +- internal/batches/service/service_test.go | 24 ++++++++++++++++++++++-- 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index c693eb0344..5c80d8b354 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -652,7 +652,7 @@ func (svc *Service) FindDirectoriesInRepos(ctx context.Context, fileName string, a.WriteString("query DirectoriesContainingFile {\n") for _, repo := range batch { - query := fmt.Sprintf(`file:(^|/)%s$ repo:^%s$ type:path count:99999`, regexp.QuoteMeta(fileName), regexp.QuoteMeta(repo.Name)) + query := fmt.Sprintf(`file:(^|/)%s$ repo:^%s$@%s type:path count:99999`, regexp.QuoteMeta(fileName), repo.BaseRef(), regexp.QuoteMeta(repo.Name)) a.WriteString(fmt.Sprintf(searchQueryTmpl, queryIDByRepo[repo], query)) } diff --git a/internal/batches/service/service_test.go b/internal/batches/service/service_test.go index 8c6d08d3d6..5539a09815 100644 --- a/internal/batches/service/service_test.go +++ b/internal/batches/service/service_test.go @@ -327,8 +327,28 @@ func TestService_FindDirectoriesInRepos(t *testing.T) { fileName := "package.json" repos := []*graphql.Repository{ - {ID: "repo-id-0", Name: "github.com/sourcegraph/automation-testing", Branch: graphql.Branch{Name: "main"}}, - {ID: "repo-id-1", Name: "github.com/sourcegraph/sourcegraph", Branch: graphql.Branch{Name: "dev"}}, + { + ID: "repo-id-0", + Name: "github.com/sourcegraph/automation-testing", + Branch: graphql.Branch{Name: "dev"}, + DefaultBranch: &graphql.Branch{ + Name: "main", + Target: graphql.Target{ + OID: "d34db33f", + }, + }, + }, + { + ID: "repo-id-1", + Name: "github.com/sourcegraph/sourcegraph", + Branch: graphql.Branch{Name: "dev"}, + DefaultBranch: &graphql.Branch{ + Name: "main", + Target: graphql.Target{ + OID: "d34db33f", + }, + }, + }, } svc := &Service{client: client} From b4f6994015ba07bd11e45f23fe4bad747abf99e7 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Tue, 31 Aug 2021 14:42:08 +0200 Subject: [PATCH 015/647] Move changeset spec type into shared lib package (#589) --- go.mod | 9 +- go.sum | 48 +++++++-- internal/batches/changeset_spec.go | 33 ------ internal/batches/executor/changeset_specs.go | 37 ++++--- .../batches/executor/changeset_specs_test.go | 63 ++++++----- internal/batches/executor/coordinator.go | 21 ++-- internal/batches/executor/coordinator_test.go | 102 +++++++++--------- internal/batches/service/service.go | 10 +- internal/batches/service/service_test.go | 44 ++++---- internal/batches/ui/json_lines.go | 2 +- internal/batches/ui/task_exec_tui.go | 4 +- internal/batches/ui/task_exec_tui_test.go | 29 +++-- 12 files changed, 201 insertions(+), 201 deletions(-) delete mode 100644 internal/batches/changeset_spec.go diff --git a/go.mod b/go.mod index 594acb6327..58705db20d 100644 --- a/go.mod +++ b/go.mod @@ -4,13 +4,16 @@ go 1.16 require ( github.com/Masterminds/semver v1.5.0 + github.com/cockroachdb/errors v1.8.6 // indirect + github.com/cockroachdb/redact v1.1.3 // indirect github.com/dustin/go-humanize v1.0.0 github.com/gobwas/glob v0.2.3 - github.com/google/go-cmp v0.5.5 + github.com/google/go-cmp v0.5.6 github.com/hashicorp/go-multierror v1.1.1 github.com/jig/teereadcloser v0.0.0-20181016160506-953720c48e05 github.com/json-iterator/go v1.1.11 github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 + github.com/kr/pretty v0.3.0 // indirect github.com/mattn/go-isatty v0.0.12 github.com/mitchellh/copystructure v1.2.0 github.com/neelance/parallel v0.0.0-20160708114440-4de9ce63d14c @@ -18,11 +21,13 @@ require ( github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4 github.com/pkg/errors v0.9.1 github.com/rivo/uniseg v0.2.0 // indirect + github.com/rogpeppe/go-internal v1.8.0 // indirect github.com/sourcegraph/batch-change-utils v0.0.0-20210708162152-c9f35b905d94 github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf - github.com/sourcegraph/sourcegraph/lib v0.0.0-20210823135647-4e945b8aa8d5 + github.com/sourcegraph/sourcegraph/lib v0.0.0-20210831122102-a95181f49527 github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect + github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect golang.org/x/net v0.0.0-20210614182718-04defd469f4e gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7 diff --git a/go.sum b/go.sum index 4648795d39..086bf13b26 100644 --- a/go.sum +++ b/go.sum @@ -19,14 +19,18 @@ github.com/aymerick/raymond v2.0.3-0.20180322193309-b565731e1464+incompatible/go github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= +github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= github.com/cockroachdb/datadriven v1.0.0/go.mod h1:5Ib8Meh+jk1RlHIXej6Pzevx/NLlNvQB9pmSBZErGA4= github.com/cockroachdb/errors v1.6.1/go.mod h1:tm6FTP5G81vwJ5lC0SizQo374JNCOPrHyXGitRJoDqM= -github.com/cockroachdb/errors v1.8.4 h1:41oZ1A4Eju6LviqkGpu5R2M39gHHVAFvOYsQjot1jNc= github.com/cockroachdb/errors v1.8.4/go.mod h1:GScl7wnuvY335l6h0jbkHIKJ+8uEmUmJRVWKnenUbfI= +github.com/cockroachdb/errors v1.8.6 h1:Am9evxl/po3RzpokemQvq7S7Cd0mxv24xy0B/trlQF4= +github.com/cockroachdb/errors v1.8.6/go.mod h1:hOm5fabihW+xEyY1kuypGwqT+Vt7rafg04ytBtIpeIQ= github.com/cockroachdb/logtags v0.0.0-20190617123548-eb05cc24525f h1:o/kfcElHqOiXqcou5a3rIlMc7oJbMQkeLk0VQJ7zgqY= github.com/cockroachdb/logtags v0.0.0-20190617123548-eb05cc24525f/go.mod h1:i/u985jwjWRlyHXQbwatDASoW0RMlZ/3i9yJHE2xLkI= -github.com/cockroachdb/redact v1.0.8 h1:8QG/764wK+vmEYoOlfobpe12EQcS81ukx/a4hdVMxNw= github.com/cockroachdb/redact v1.0.8/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= +github.com/cockroachdb/redact v1.1.1/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= +github.com/cockroachdb/redact v1.1.3 h1:AKZds10rFSIj7qADf0g46UixK8NNLwWTNdCIGS5wfSQ= +github.com/cockroachdb/redact v1.1.3/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= github.com/cockroachdb/sentry-go v0.6.1-cockroachdb.2 h1:IKgmqgMQlVJIZj19CdocBeSfSaiCbEBZGKODaixqtHM= github.com/cockroachdb/sentry-go v0.6.1-cockroachdb.2/go.mod h1:8BT+cPK6xvFOcRlk0R8eg+OTkcqI6baNH4xAkpiYVvQ= github.com/codegangsta/inject v0.0.0-20150114235600-33e0aa1cb7c0/go.mod h1:4Zcjuz89kmFXt9morQgcfYZAYZ5n8WHjt81YYWIwtTM= @@ -34,6 +38,7 @@ github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE= +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/creack/pty v1.1.11 h1:07n33Z8lZxZ2qwegKbObQohDhXDQxiMMz1NOUGYlesw= github.com/creack/pty v1.1.11/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/dave/jennifer v1.4.1/go.mod h1:7jEdnm+qBcxl8PC0zyp7vxcpSRnzXSt9r39tpTVGlwA= @@ -49,7 +54,9 @@ github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25Kn github.com/efritz/pentimento v0.0.0-20190429011147-ade47d831101/go.mod h1:5ALWO82UZwfAtNRUtwzsWimcrcuYzyieTyyXOXrP6EQ= github.com/eknkc/amber v0.0.0-20171010120322-cdade1c07385/go.mod h1:0vRUJqYpeSZifjYj7uP3BG/gKcuzL9xWVV/Y+cK33KM= github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= +github.com/envoyproxy/go-control-plane v0.9.9-0.20210217033140-668b12f5399d/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/etcd-io/bbolt v1.3.3/go.mod h1:ZF2nL25h33cCyBtcyWeZ2/I3HQOfTP+0PIEvHjkjCrw= github.com/fasthttp-contrib/websocket v0.0.0-20160511215533-1f3b11f56072/go.mod h1:duJ4Jxv5lDcvg4QuQr0oowTf7dz4/CR8NtyCooz9HL8= @@ -74,6 +81,7 @@ github.com/gobwas/pool v0.2.0/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6Wezm github.com/gobwas/ws v1.0.2/go.mod h1:szmBTxLgaFppYjEmNtny/v3w89xOydFnnZMcgRRu/EM= github.com/gogo/googleapis v0.0.0-20180223154316-0cd9801be74a/go.mod h1:gf4bu3Q80BeJ6H1S1vYPm8/ELATdvryBaNFGgqEef3s= github.com/gogo/googleapis v1.2.0/go.mod h1:Njal3psf3qN6dwBtQfUmBZh2ybovJ0tlu3o/AC7HYjU= +github.com/gogo/googleapis v1.4.1/go.mod h1:2lpHqI5OcWCtVElxXnPt+s8oJvMpySlOyM6xDCrzib4= github.com/gogo/protobuf v1.2.0/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4= github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= @@ -91,6 +99,7 @@ github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:x github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= @@ -100,12 +109,15 @@ github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5a github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.6 h1:BKbKCqvP6I+rmFHt06ZmyQtvB8xAkWdhFyr0ZUNZcxQ= +github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.2.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= @@ -123,6 +135,7 @@ github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSo github.com/hexops/valast v1.4.0/go.mod h1:uVjKZ0smVuYlgCSPz9NRi5A04sl7lp6GtFWsROKDgEs= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/hydrogen18/memlistener v0.0.0-20141126152155-54553eb933fb/go.mod h1:qEIFzExnS6016fRpRfxrExeVn2gbClQA99gQhnIcdhE= +github.com/hydrogen18/memlistener v0.0.0-20200120041712-dcc25e7acd91/go.mod h1:qEIFzExnS6016fRpRfxrExeVn2gbClQA99gQhnIcdhE= github.com/imkira/go-interpol v1.1.0/go.mod h1:z0h2/2T3XF8kyEPpRgJ3kmNv+C43p+I/CoI+jC3w2iA= github.com/inconshreveable/log15 v0.0.0-20201112154412-8562bdadbbac/go.mod h1:cOaXtrgN4ScfRrD9Bre7U1thNq5RtJ8ZoP4iXVGRj6o= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= @@ -157,11 +170,14 @@ github.com/klauspost/compress v1.12.2/go.mod h1:8dP1Hq4DHOhN9w426knH3Rhby4rFm6D8 github.com/klauspost/cpuid v1.2.1/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek= github.com/klauspost/pgzip v1.2.5 h1:qnWYvvKqedOF2ulHpMG72XQol4ILEJ8k2wwRl/Km8oE= github.com/klauspost/pgzip v1.2.5/go.mod h1:Ch1tH69qFZu15pkjo5kYi6mth2Zzwzt50oCQKQE9RUs= -github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= +github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= +github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/labstack/echo/v4 v4.1.11/go.mod h1:i541M3Fj6f76NZtHSj7TXnyM8n2gaodfvfxNnFqi74g= github.com/labstack/gommon v0.3.0/go.mod h1:MULnywXg0yavhxWKc+lOruYdAhDwPK9wf0OL7NoOu+k= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= @@ -217,6 +233,7 @@ github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4 github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8= github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4 h1:49lOXmGaUpV9Fz3gd7TFZY106KVlPVa5jcYD1gaQf98= github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4/go.mod h1:4OwLy04Bl9Ef3GJJCoec+30X3LQs/0/m4HFRt/2LUSA= +github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= @@ -226,7 +243,10 @@ github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1: github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY= github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= +github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.6.2/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= +github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8= +github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= github.com/ryanuber/columnize v2.1.0+incompatible/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= github.com/sclevine/agouti v3.0.0+incompatible/go.mod h1:b4WX9W9L1sfQKXeJf1mUTLZKJ48R1S7H23Ji7oFO5Bw= @@ -243,8 +263,8 @@ github.com/sourcegraph/go-diff v0.6.1 h1:hmA1LzxW0n1c3Q4YbrFgg4P99GSnebYa3x8gr0H github.com/sourcegraph/go-diff v0.6.1/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20210823135647-4e945b8aa8d5 h1:3wxr60w288nXNRzjjrEjEEgU6LUi/QV5CpyHNmHfyEI= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20210823135647-4e945b8aa8d5/go.mod h1:aH/URdfJ92i5Ec/5u2GSlliMZtKzsD91oTJNwZpH8Hc= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20210831122102-a95181f49527 h1:Bj2XOghFkSnxE0EcpmtmjIFbqDkJ0wBNTvM6cguKaKs= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20210831122102-a95181f49527/go.mod h1:aH/URdfJ92i5Ec/5u2GSlliMZtKzsD91oTJNwZpH8Hc= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= @@ -269,8 +289,9 @@ github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyC github.com/valyala/fasthttp v1.6.0/go.mod h1:FstJa9V+Pj9vQ7OJie2qMHdwemEDaDiSdBnvPM1Su9w= github.com/valyala/fasttemplate v1.0.1/go.mod h1:UQGH1tvbgY+Nz5t2n7tXsz52dQxojPUpymEIMZ47gx8= github.com/valyala/tcplisten v0.0.0-20161114210144-ceec8f93295a/go.mod h1:v3UYOV9WzVtRmSR+PDvWpU/qWl4Wa5LApYYX4ZtKbio= -github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f h1:J9EGpcZtP0E/raorCMxlFGSTBrsSlaDGf3jU/qvAE2c= github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= +github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb h1:zGWFAtiMcyryUHoUjUJX0/lt1H2+i2Ka2n+D3DImSNo= +github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0= github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74= @@ -293,6 +314,8 @@ golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20210508222113-6edffad5e616/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= @@ -356,6 +379,7 @@ golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9sn golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -370,6 +394,7 @@ golang.org/x/tools v0.0.0-20190428024724-550556f78a90/go.mod h1:RgjU9mgBXZiqYHBn golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190624222133-a101b041ded4/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200624163319-25775e59acb7/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= @@ -387,17 +412,24 @@ google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7 google.golang.org/genproto v0.0.0-20180518175338-11a468237815/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= +google.golang.org/genproto v0.0.0-20210624195500-8bfb893ecb84/go.mod h1:SzzZ/N+nwJDaO1kznhnlzqS8ocJICar6hYhVyhi++24= google.golang.org/grpc v1.12.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= +google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= +google.golang.org/grpc v1.38.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/internal/batches/changeset_spec.go b/internal/batches/changeset_spec.go deleted file mode 100644 index 0a51208643..0000000000 --- a/internal/batches/changeset_spec.go +++ /dev/null @@ -1,33 +0,0 @@ -package batches - -// These struct definitions must line up with the changeset spec schema, as -// defined in sourcegraph/sourcegraph. - -type ChangesetSpec struct { - BaseRepository string `json:"baseRepository"` - - *ExternalChangeset - *CreatedChangeset -} - -type ExternalChangeset struct { - ExternalID string `json:"externalID"` -} - -type CreatedChangeset struct { - BaseRef string `json:"baseRef"` - BaseRev string `json:"baseRev"` - HeadRepository string `json:"headRepository"` - HeadRef string `json:"headRef"` - Title string `json:"title"` - Body string `json:"body"` - Commits []GitCommitDescription `json:"commits"` - Published interface{} `json:"published"` -} - -type GitCommitDescription struct { - Message string `json:"message"` - Diff string `json:"diff"` - AuthorName string `json:"authorName,omitempty"` - AuthorEmail string `json:"authorEmail,omitempty"` -} diff --git a/internal/batches/executor/changeset_specs.go b/internal/batches/executor/changeset_specs.go index 7183ffd364..44844bdd44 100644 --- a/internal/batches/executor/changeset_specs.go +++ b/internal/batches/executor/changeset_specs.go @@ -13,7 +13,7 @@ import ( var errOptionalPublishedUnsupported = errors.New(`This Sourcegraph version requires the "published" field to be specified in the batch spec; upgrade to version 3.30.0 or later to be able to omit the published field and control publication from the UI.`) -func createChangesetSpecs(task *Task, result executionResult, features batches.FeatureFlags) ([]*batches.ChangesetSpec, error) { +func createChangesetSpecs(task *Task, result executionResult, features batches.FeatureFlags) ([]*batcheslib.ChangesetSpec, error) { repo := task.Repository.Name tmplCtx := &template.ChangesetTemplateContext{ @@ -70,7 +70,7 @@ func createChangesetSpecs(task *Task, result executionResult, features batches.F return nil, err } - newSpec := func(branch, diff string) (*batches.ChangesetSpec, error) { + newSpec := func(branch, diff string) (*batcheslib.ChangesetSpec, error) { var published interface{} = nil if task.Template.Published != nil { published = task.Template.Published.ValueWithSuffix(repo, branch) @@ -85,29 +85,28 @@ func createChangesetSpecs(task *Task, result executionResult, features batches.F return nil, errOptionalPublishedUnsupported } - return &batches.ChangesetSpec{ + return &batcheslib.ChangesetSpec{ BaseRepository: task.Repository.ID, - CreatedChangeset: &batches.CreatedChangeset{ - BaseRef: task.Repository.BaseRef(), - BaseRev: task.Repository.Rev(), - HeadRepository: task.Repository.ID, - HeadRef: "refs/heads/" + branch, - Title: title, - Body: body, - Commits: []batches.GitCommitDescription{ - { - Message: message, - AuthorName: authorName, - AuthorEmail: authorEmail, - Diff: diff, - }, + + BaseRef: task.Repository.BaseRef(), + BaseRev: task.Repository.Rev(), + HeadRepository: task.Repository.ID, + HeadRef: "refs/heads/" + branch, + Title: title, + Body: body, + Commits: []batcheslib.GitCommitDescription{ + { + Message: message, + AuthorName: authorName, + AuthorEmail: authorEmail, + Diff: diff, }, - Published: published, }, + Published: batcheslib.PublishedValue{Val: published}, }, nil } - var specs []*batches.ChangesetSpec + var specs []*batcheslib.ChangesetSpec groups := groupsForRepository(task.Repository.Name, task.TransformChanges) if len(groups) != 0 { diff --git a/internal/batches/executor/changeset_specs_test.go b/internal/batches/executor/changeset_specs_test.go index 0ebae2a99d..79bed582bf 100644 --- a/internal/batches/executor/changeset_specs_test.go +++ b/internal/batches/executor/changeset_specs_test.go @@ -14,34 +14,33 @@ import ( ) func TestCreateChangesetSpecs(t *testing.T) { - defaultChangesetSpec := &batches.ChangesetSpec{ + defaultChangesetSpec := &batcheslib.ChangesetSpec{ BaseRepository: testRepo1.ID, - CreatedChangeset: &batches.CreatedChangeset{ - BaseRef: testRepo1.DefaultBranch.Name, - BaseRev: testRepo1.DefaultBranch.Target.OID, - HeadRepository: testRepo1.ID, - HeadRef: "refs/heads/my-branch", - Title: "The title", - Body: "The body", - Commits: []batches.GitCommitDescription{ - { - Message: "git commit message", - Diff: "cool diff", - AuthorName: "Sourcegraph", - AuthorEmail: "batch-changes@sourcegraph.com", - }, + + BaseRef: testRepo1.DefaultBranch.Name, + BaseRev: testRepo1.DefaultBranch.Target.OID, + HeadRepository: testRepo1.ID, + HeadRef: "refs/heads/my-branch", + Title: "The title", + Body: "The body", + Commits: []batcheslib.GitCommitDescription{ + { + Message: "git commit message", + Diff: "cool diff", + AuthorName: "Sourcegraph", + AuthorEmail: "batch-changes@sourcegraph.com", }, - Published: false, }, + Published: batcheslib.PublishedValue{Val: false}, } - specWith := func(s *batches.ChangesetSpec, f func(s *batches.ChangesetSpec)) *batches.ChangesetSpec { + specWith := func(s *batcheslib.ChangesetSpec, f func(s *batcheslib.ChangesetSpec)) *batcheslib.ChangesetSpec { copy, err := copystructure.Copy(s) if err != nil { t.Fatalf("deep copying spec: %+v", err) } - s = copy.(*batches.ChangesetSpec) + s = copy.(*batcheslib.ChangesetSpec) f(s) return s } @@ -91,7 +90,7 @@ func TestCreateChangesetSpecs(t *testing.T) { features batches.FeatureFlags result executionResult - want []*batches.ChangesetSpec + want []*batcheslib.ChangesetSpec wantErr string }{ { @@ -99,7 +98,7 @@ func TestCreateChangesetSpecs(t *testing.T) { task: defaultTask, features: featuresAllEnabled(), result: defaultResult, - want: []*batches.ChangesetSpec{ + want: []*batcheslib.ChangesetSpec{ defaultChangesetSpec, }, wantErr: "", @@ -112,9 +111,9 @@ func TestCreateChangesetSpecs(t *testing.T) { }), features: featuresAllEnabled(), result: defaultResult, - want: []*batches.ChangesetSpec{ - specWith(defaultChangesetSpec, func(s *batches.ChangesetSpec) { - s.Published = true + want: []*batcheslib.ChangesetSpec{ + specWith(defaultChangesetSpec, func(s *batcheslib.ChangesetSpec) { + s.Published = batcheslib.PublishedValue{Val: true} }), }, wantErr: "", @@ -127,9 +126,9 @@ func TestCreateChangesetSpecs(t *testing.T) { }), features: featuresAllEnabled(), result: defaultResult, - want: []*batches.ChangesetSpec{ - specWith(defaultChangesetSpec, func(s *batches.ChangesetSpec) { - s.Published = nil + want: []*batcheslib.ChangesetSpec{ + specWith(defaultChangesetSpec, func(s *batcheslib.ChangesetSpec) { + s.Published = batcheslib.PublishedValue{Val: nil} }), }, wantErr: "", @@ -142,9 +141,9 @@ func TestCreateChangesetSpecs(t *testing.T) { }), features: featuresWithoutOptionalPublished, result: defaultResult, - want: []*batches.ChangesetSpec{ - specWith(defaultChangesetSpec, func(s *batches.ChangesetSpec) { - s.Published = false + want: []*batcheslib.ChangesetSpec{ + specWith(defaultChangesetSpec, func(s *batcheslib.ChangesetSpec) { + s.Published = batcheslib.PublishedValue{Val: false} }), }, wantErr: "", @@ -156,9 +155,9 @@ func TestCreateChangesetSpecs(t *testing.T) { }), features: featuresAllEnabled(), result: defaultResult, - want: []*batches.ChangesetSpec{ - specWith(defaultChangesetSpec, func(s *batches.ChangesetSpec) { - s.Published = nil + want: []*batcheslib.ChangesetSpec{ + specWith(defaultChangesetSpec, func(s *batcheslib.ChangesetSpec) { + s.Published = batcheslib.PublishedValue{Val: nil} }), }, wantErr: "", diff --git a/internal/batches/executor/coordinator.go b/internal/batches/executor/coordinator.go index 4645910723..e1d9c6cc90 100644 --- a/internal/batches/executor/coordinator.go +++ b/internal/batches/executor/coordinator.go @@ -24,7 +24,7 @@ type taskExecutor interface { // Coordinates coordinates the execution of Tasks. It makes use of an executor, // checks the ExecutionCache whether execution is necessary, builds -// batches.ChangesetSpecs out of the executionResults. +// batcheslib.ChangesetSpecs out of the executionResults. type Coordinator struct { opts NewCoordinatorOpts @@ -89,7 +89,7 @@ func NewCoordinator(opts NewCoordinatorOpts) *Coordinator { // CheckCache checks whether the internal ExecutionCache contains // ChangesetSpecs for the given Tasks. If cached ChangesetSpecs exist, those // are returned, otherwise the Task, to be executed later. -func (c *Coordinator) CheckCache(ctx context.Context, tasks []*Task) (uncached []*Task, specs []*batches.ChangesetSpec, err error) { +func (c *Coordinator) CheckCache(ctx context.Context, tasks []*Task) (uncached []*Task, specs []*batcheslib.ChangesetSpec, err error) { for _, t := range tasks { cachedSpecs, found, err := c.checkCacheForTask(ctx, t) if err != nil { @@ -107,7 +107,7 @@ func (c *Coordinator) CheckCache(ctx context.Context, tasks []*Task) (uncached [ return uncached, specs, nil } -func (c *Coordinator) checkCacheForTask(ctx context.Context, task *Task) (specs []*batches.ChangesetSpec, found bool, err error) { +func (c *Coordinator) checkCacheForTask(ctx context.Context, task *Task) (specs []*batcheslib.ChangesetSpec, found bool, err error) { // Check if the task is cached. cacheKey := task.cacheKey() if c.opts.ClearCache { @@ -174,7 +174,7 @@ func (c *Coordinator) setCachedStepResults(ctx context.Context, task *Task) erro return nil } -func (c *Coordinator) cacheAndBuildSpec(ctx context.Context, taskResult taskResult, ui TaskExecutionUI) ([]*batches.ChangesetSpec, error) { +func (c *Coordinator) cacheAndBuildSpec(ctx context.Context, taskResult taskResult, ui TaskExecutionUI) ([]*batcheslib.ChangesetSpec, error) { // Add to the cache, even if no diff was produced. cacheKey := taskResult.task.cacheKey() if err := c.cache.Set(ctx, cacheKey, taskResult.result); err != nil { @@ -212,7 +212,7 @@ type TaskExecutionUI interface { TaskStarted(*Task) TaskFinished(*Task, error) - TaskChangesetSpecsBuilt(*Task, []*batches.ChangesetSpec) + TaskChangesetSpecsBuilt(*Task, []*batcheslib.ChangesetSpec) // TODO: This should be split up into methods that are more specific. TaskCurrentlyExecuting(*Task, string) @@ -221,9 +221,9 @@ type TaskExecutionUI interface { // Execute executes the given Tasks and the importChangeset statements in the // given spec. It regularly calls the executionProgressPrinter with the // current TaskStatuses. -func (c *Coordinator) Execute(ctx context.Context, tasks []*Task, spec *batcheslib.BatchSpec, ui TaskExecutionUI) ([]*batches.ChangesetSpec, []string, error) { +func (c *Coordinator) Execute(ctx context.Context, tasks []*Task, spec *batcheslib.BatchSpec, ui TaskExecutionUI) ([]*batcheslib.ChangesetSpec, []string, error) { var ( - specs []*batches.ChangesetSpec + specs []*batcheslib.ChangesetSpec errs *multierror.Error ) @@ -289,9 +289,10 @@ func (c *Coordinator) Execute(ctx context.Context, tasks []*Task, spec *batchesl return nil, nil, errors.Errorf("cannot convert value of type %T into a valid external ID: expected string or int", id) } - specs = append(specs, &batches.ChangesetSpec{ - BaseRepository: repo.ID, - ExternalChangeset: &batches.ExternalChangeset{ExternalID: sid}, + specs = append(specs, &batcheslib.ChangesetSpec{ + BaseRepository: repo.ID, + + ExternalID: sid, }) } } diff --git a/internal/batches/executor/coordinator_test.go b/internal/batches/executor/coordinator_test.go index 287974f795..b158a0bc47 100644 --- a/internal/batches/executor/coordinator_test.go +++ b/internal/batches/executor/coordinator_test.go @@ -11,7 +11,6 @@ import ( "github.com/google/go-cmp/cmp/cmpopts" "github.com/sourcegraph/batch-change-utils/overridable" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" - "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/git" "github.com/sourcegraph/src-cli/internal/batches/graphql" "github.com/sourcegraph/src-cli/internal/batches/mock" @@ -23,26 +22,25 @@ func TestCoordinator_Execute(t *testing.T) { srcCLITask := &Task{Repository: testRepo1} sourcegraphTask := &Task{Repository: testRepo2} - buildSpecFor := func(repo *graphql.Repository, modify func(*batches.ChangesetSpec)) *batches.ChangesetSpec { - spec := &batches.ChangesetSpec{ + buildSpecFor := func(repo *graphql.Repository, modify func(*batcheslib.ChangesetSpec)) *batcheslib.ChangesetSpec { + spec := &batcheslib.ChangesetSpec{ BaseRepository: repo.ID, - CreatedChangeset: &batches.CreatedChangeset{ - BaseRef: repo.BaseRef(), - BaseRev: repo.Rev(), - HeadRepository: repo.ID, - HeadRef: "refs/heads/" + testChangesetTemplate.Branch, - Title: testChangesetTemplate.Title, - Body: testChangesetTemplate.Body, - Commits: []batches.GitCommitDescription{ - { - Message: testChangesetTemplate.Commit.Message, - AuthorName: testChangesetTemplate.Commit.Author.Name, - AuthorEmail: testChangesetTemplate.Commit.Author.Email, - Diff: `dummydiff1`, - }, + + BaseRef: repo.BaseRef(), + BaseRev: repo.Rev(), + HeadRepository: repo.ID, + HeadRef: "refs/heads/" + testChangesetTemplate.Branch, + Title: testChangesetTemplate.Title, + Body: testChangesetTemplate.Body, + Commits: []batcheslib.GitCommitDescription{ + { + Message: testChangesetTemplate.Commit.Message, + AuthorName: testChangesetTemplate.Commit.Author.Name, + AuthorEmail: testChangesetTemplate.Commit.Author.Email, + Diff: `dummydiff1`, }, - Published: false, }, + Published: batcheslib.PublishedValue{Val: false}, } modify(spec) @@ -59,7 +57,7 @@ func TestCoordinator_Execute(t *testing.T) { batchSpec *batcheslib.BatchSpec wantCacheEntries int - wantSpecs []*batches.ChangesetSpec + wantSpecs []*batcheslib.ChangesetSpec wantErrInclude string }{ { @@ -82,12 +80,12 @@ func TestCoordinator_Execute(t *testing.T) { opts: NewCoordinatorOpts{Features: featuresAllEnabled()}, wantCacheEntries: 2, - wantSpecs: []*batches.ChangesetSpec{ - buildSpecFor(testRepo1, func(spec *batches.ChangesetSpec) { - spec.CreatedChangeset.Commits[0].Diff = `dummydiff1` + wantSpecs: []*batcheslib.ChangesetSpec{ + buildSpecFor(testRepo1, func(spec *batcheslib.ChangesetSpec) { + spec.Commits[0].Diff = `dummydiff1` }), - buildSpecFor(testRepo2, func(spec *batches.ChangesetSpec) { - spec.CreatedChangeset.Commits[0].Diff = `dummydiff2` + buildSpecFor(testRepo2, func(spec *batcheslib.ChangesetSpec) { + spec.Commits[0].Diff = `dummydiff2` }), }, }, @@ -150,11 +148,11 @@ func TestCoordinator_Execute(t *testing.T) { opts: NewCoordinatorOpts{Features: featuresAllEnabled()}, wantCacheEntries: 1, - wantSpecs: []*batches.ChangesetSpec{ - buildSpecFor(testRepo1, func(spec *batches.ChangesetSpec) { - spec.CreatedChangeset.HeadRef = "refs/heads/templated-branch-myOutputValue1" - spec.CreatedChangeset.Title = "output1=myOutputValue1" - spec.CreatedChangeset.Body = `output1=myOutputValue1 + wantSpecs: []*batcheslib.ChangesetSpec{ + buildSpecFor(testRepo1, func(spec *batcheslib.ChangesetSpec) { + spec.HeadRef = "refs/heads/templated-branch-myOutputValue1" + spec.Title = "output1=myOutputValue1" + spec.Body = `output1=myOutputValue1 output2=subFieldValue modified_files=[modified.txt] @@ -166,7 +164,7 @@ func TestCoordinator_Execute(t *testing.T) { batch_change_name=my-batch-change batch_change_description=the description` - spec.CreatedChangeset.Commits = []batches.GitCommitDescription{ + spec.Commits = []batcheslib.GitCommitDescription{ { Message: "output1=myOutputValue1,output2=subFieldValue", AuthorName: "output1=myOutputValue1", @@ -203,22 +201,22 @@ func TestCoordinator_Execute(t *testing.T) { // We have 4 ChangesetSpecs, but we only want 2 cache entries, // since we cache per Task, not per resulting changeset spec. wantCacheEntries: 2, - wantSpecs: []*batches.ChangesetSpec{ - buildSpecFor(testRepo1, func(spec *batches.ChangesetSpec) { - spec.CreatedChangeset.HeadRef = "refs/heads/" + testChangesetTemplate.Branch - spec.CreatedChangeset.Commits[0].Diff = nestedChangesDiffSubdirA + nestedChangesDiffSubdirB + wantSpecs: []*batcheslib.ChangesetSpec{ + buildSpecFor(testRepo1, func(spec *batcheslib.ChangesetSpec) { + spec.HeadRef = "refs/heads/" + testChangesetTemplate.Branch + spec.Commits[0].Diff = nestedChangesDiffSubdirA + nestedChangesDiffSubdirB }), - buildSpecFor(testRepo2, func(spec *batches.ChangesetSpec) { - spec.CreatedChangeset.HeadRef = "refs/heads/in-directory-b" - spec.CreatedChangeset.Commits[0].Diff = nestedChangesDiffSubdirB + nestedChangesDiffSubdirC + buildSpecFor(testRepo2, func(spec *batcheslib.ChangesetSpec) { + spec.HeadRef = "refs/heads/in-directory-b" + spec.Commits[0].Diff = nestedChangesDiffSubdirB + nestedChangesDiffSubdirC }), - buildSpecFor(testRepo1, func(spec *batches.ChangesetSpec) { - spec.CreatedChangeset.HeadRef = "refs/heads/in-directory-c" - spec.CreatedChangeset.Commits[0].Diff = nestedChangesDiffSubdirC + buildSpecFor(testRepo1, func(spec *batcheslib.ChangesetSpec) { + spec.HeadRef = "refs/heads/in-directory-c" + spec.Commits[0].Diff = nestedChangesDiffSubdirC }), - buildSpecFor(testRepo2, func(spec *batches.ChangesetSpec) { - spec.CreatedChangeset.HeadRef = "refs/heads/" + testChangesetTemplate.Branch - spec.CreatedChangeset.Commits[0].Diff = nestedChangesDiffSubdirA + buildSpecFor(testRepo2, func(spec *batcheslib.ChangesetSpec) { + spec.HeadRef = "refs/heads/" + testChangesetTemplate.Branch + spec.Commits[0].Diff = nestedChangesDiffSubdirA }), }, }, @@ -251,9 +249,9 @@ func TestCoordinator_Execute(t *testing.T) { wantErrInclude: "run: broken command", // We want 1 cache entry and 1 spec wantCacheEntries: 1, - wantSpecs: []*batches.ChangesetSpec{ - buildSpecFor(testRepo1, func(spec *batches.ChangesetSpec) { - spec.CreatedChangeset.Commits[0].Diff = `dummydiff1` + wantSpecs: []*batcheslib.ChangesetSpec{ + buildSpecFor(testRepo1, func(spec *batcheslib.ChangesetSpec) { + spec.Commits[0].Diff = `dummydiff1` }), }, }, @@ -308,9 +306,9 @@ func TestCoordinator_Execute(t *testing.T) { opts := []cmp.Option{ cmpopts.EquateEmpty(), - cmpopts.SortSlices(func(a, b *batches.ChangesetSpec) bool { - if a.BaseRepository == b.BaseRepository && a.CreatedChangeset != nil && b.CreatedChangeset != nil { - return a.CreatedChangeset.HeadRef < b.CreatedChangeset.HeadRef + cmpopts.SortSlices(func(a, b *batcheslib.ChangesetSpec) bool { + if a.BaseRepository == b.BaseRepository { + return a.HeadRef < b.HeadRef } return a.BaseRepository < b.BaseRepository }), @@ -506,7 +504,7 @@ func newDummyTaskExecutionUI() *dummyTaskExecutionUI { started: map[*Task]struct{}{}, finished: map[*Task]struct{}{}, finishedWithErr: map[*Task]struct{}{}, - specs: map[*Task][]*batches.ChangesetSpec{}, + specs: map[*Task][]*batcheslib.ChangesetSpec{}, } } @@ -516,7 +514,7 @@ type dummyTaskExecutionUI struct { started map[*Task]struct{} finished map[*Task]struct{} finishedWithErr map[*Task]struct{} - specs map[*Task][]*batches.ChangesetSpec + specs map[*Task][]*batcheslib.ChangesetSpec } func (d *dummyTaskExecutionUI) Start([]*Task) {} @@ -538,7 +536,7 @@ func (d *dummyTaskExecutionUI) TaskFinished(t *Task, err error) { d.finished[t] = struct{}{} } } -func (d *dummyTaskExecutionUI) TaskChangesetSpecsBuilt(t *Task, specs []*batches.ChangesetSpec) { +func (d *dummyTaskExecutionUI) TaskChangesetSpecsBuilt(t *Task, specs []*batcheslib.ChangesetSpec) { d.mu.Lock() defer d.mu.Unlock() diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index 5c80d8b354..a8f146ee78 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -125,7 +125,7 @@ mutation CreateChangesetSpec($spec: String!) { } ` -func (svc *Service) CreateChangesetSpec(ctx context.Context, spec *batches.ChangesetSpec) (graphql.ChangesetSpecID, error) { +func (svc *Service) CreateChangesetSpec(ctx context.Context, spec *batcheslib.ChangesetSpec) (graphql.ChangesetSpecID, error) { raw, err := json.Marshal(spec) if err != nil { return "", errors.Wrap(err, "marshalling changeset spec JSON") @@ -201,21 +201,21 @@ func (svc *Service) NewCoordinator(opts executor.NewCoordinatorOpts) *executor.C // ValidateChangesetSpecs validates that among all branch changesets there are no // duplicates in branch names in a single repo. -func (svc *Service) ValidateChangesetSpecs(repos []*graphql.Repository, specs []*batches.ChangesetSpec) error { +func (svc *Service) ValidateChangesetSpecs(repos []*graphql.Repository, specs []*batcheslib.ChangesetSpec) error { repoByID := make(map[string]*graphql.Repository, len(repos)) for _, repo := range repos { repoByID[repo.ID] = repo } - byRepoAndBranch := make(map[string]map[string][]*batches.ChangesetSpec) + byRepoAndBranch := make(map[string]map[string][]*batcheslib.ChangesetSpec) for _, spec := range specs { // We don't need to validate imported changesets, as they can // never have a critical branch name overlap. - if spec.ExternalChangeset != nil { + if spec.Type() == batcheslib.ChangesetSpecDescriptionTypeExisting { continue } if _, ok := byRepoAndBranch[spec.HeadRepository]; !ok { - byRepoAndBranch[spec.HeadRepository] = make(map[string][]*batches.ChangesetSpec) + byRepoAndBranch[spec.HeadRepository] = make(map[string][]*batcheslib.ChangesetSpec) } byRepoAndBranch[spec.HeadRepository][spec.HeadRef] = append(byRepoAndBranch[spec.HeadRepository][spec.HeadRef], spec) diff --git a/internal/batches/service/service_test.go b/internal/batches/service/service_test.go index 5539a09815..d00eeee47c 100644 --- a/internal/batches/service/service_test.go +++ b/internal/batches/service/service_test.go @@ -433,52 +433,52 @@ func TestService_ValidateChangesetSpecs(t *testing.T) { tests := map[string]struct { repos []*graphql.Repository - specs []*batches.ChangesetSpec + specs []*batcheslib.ChangesetSpec wantErrInclude string }{ "no errors": { repos: []*graphql.Repository{repo1, repo2}, - specs: []*batches.ChangesetSpec{ - {CreatedChangeset: &batches.CreatedChangeset{ - HeadRepository: repo1.ID, HeadRef: "refs/heads/branch-1"}, + specs: []*batcheslib.ChangesetSpec{ + { + HeadRepository: repo1.ID, HeadRef: "refs/heads/branch-1", }, - {CreatedChangeset: &batches.CreatedChangeset{ - HeadRepository: repo1.ID, HeadRef: "refs/heads/branch-2"}, + { + HeadRepository: repo1.ID, HeadRef: "refs/heads/branch-2", }, - {CreatedChangeset: &batches.CreatedChangeset{ - HeadRepository: repo2.ID, HeadRef: "refs/heads/branch-1"}, + { + HeadRepository: repo2.ID, HeadRef: "refs/heads/branch-1", }, - {CreatedChangeset: &batches.CreatedChangeset{ - HeadRepository: repo2.ID, HeadRef: "refs/heads/branch-2"}, + { + HeadRepository: repo2.ID, HeadRef: "refs/heads/branch-2", }, }, }, "imported changeset": { repos: []*graphql.Repository{repo1}, - specs: []*batches.ChangesetSpec{ - {ExternalChangeset: &batches.ExternalChangeset{ + specs: []*batcheslib.ChangesetSpec{ + { ExternalID: "123", - }}, + }, }, // This should not fail validation ever. }, "duplicate branches": { repos: []*graphql.Repository{repo1, repo2}, - specs: []*batches.ChangesetSpec{ - {CreatedChangeset: &batches.CreatedChangeset{ - HeadRepository: repo1.ID, HeadRef: "refs/heads/branch-1"}, + specs: []*batcheslib.ChangesetSpec{ + { + HeadRepository: repo1.ID, HeadRef: "refs/heads/branch-1", }, - {CreatedChangeset: &batches.CreatedChangeset{ - HeadRepository: repo1.ID, HeadRef: "refs/heads/branch-2"}, + { + HeadRepository: repo1.ID, HeadRef: "refs/heads/branch-2", }, - {CreatedChangeset: &batches.CreatedChangeset{ - HeadRepository: repo2.ID, HeadRef: "refs/heads/branch-1"}, + { + HeadRepository: repo2.ID, HeadRef: "refs/heads/branch-1", }, - {CreatedChangeset: &batches.CreatedChangeset{ - HeadRepository: repo2.ID, HeadRef: "refs/heads/branch-1"}, + { + HeadRepository: repo2.ID, HeadRef: "refs/heads/branch-1", }, }, wantErrInclude: `github.com/sourcegraph/sourcegraph: 2 changeset specs have the branch "branch-1"`, diff --git a/internal/batches/ui/json_lines.go b/internal/batches/ui/json_lines.go index fc83cc648a..6202f111ab 100644 --- a/internal/batches/ui/json_lines.go +++ b/internal/batches/ui/json_lines.go @@ -277,7 +277,7 @@ func (ui *taskExecutionJSONLines) TaskFinished(task *executor.Task, err error) { }}) } -func (ui *taskExecutionJSONLines) TaskChangesetSpecsBuilt(task *executor.Task, specs []*batches.ChangesetSpec) { +func (ui *taskExecutionJSONLines) TaskChangesetSpecsBuilt(task *executor.Task, specs []*batcheslib.ChangesetSpec) { lt, ok := ui.linesTasks[task] if !ok { panic("unknown task started") diff --git a/internal/batches/ui/task_exec_tui.go b/internal/batches/ui/task_exec_tui.go index 4db26e3b61..a6717f4b32 100644 --- a/internal/batches/ui/task_exec_tui.go +++ b/internal/batches/ui/task_exec_tui.go @@ -8,8 +8,8 @@ import ( "time" "github.com/sourcegraph/go-diff/diff" + batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/output" - "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/executor" ) @@ -249,7 +249,7 @@ func (ui *taskExecTUI) TaskFinished(task *executor.Task, err error) { delete(ui.statusBars, bar) } -func (ui *taskExecTUI) TaskChangesetSpecsBuilt(task *executor.Task, specs []*batches.ChangesetSpec) { +func (ui *taskExecTUI) TaskChangesetSpecsBuilt(task *executor.Task, specs []*batcheslib.ChangesetSpec) { if !ui.verbose { return } diff --git a/internal/batches/ui/task_exec_tui_test.go b/internal/batches/ui/task_exec_tui_test.go index cbfc3d9480..bcd01e8bf5 100644 --- a/internal/batches/ui/task_exec_tui_test.go +++ b/internal/batches/ui/task_exec_tui_test.go @@ -7,8 +7,8 @@ import ( "time" "github.com/google/go-cmp/cmp" + batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/output" - "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/executor" "github.com/sourcegraph/src-cli/internal/batches/graphql" ) @@ -148,24 +148,23 @@ func TestTaskExecTUI_Integration(t *testing.T) { }) // Mark the last task as finished-building-specs - printer.TaskChangesetSpecsBuilt(tasks[2], []*batches.ChangesetSpec{ + printer.TaskChangesetSpecsBuilt(tasks[2], []*batcheslib.ChangesetSpec{ { BaseRepository: "graphql-id", - CreatedChangeset: &batches.CreatedChangeset{ - BaseRef: "refs/heads/main", - BaseRev: "d34db33f", - HeadRepository: "graphql-id", - HeadRef: "refs/heads/my-batch-change", - Title: "This is my batch change", - Body: "This is my batch change", - Commits: []batches.GitCommitDescription{ - { - Message: "This is my batch change", - Diff: progressPrinterDiff, - }, + + BaseRef: "refs/heads/main", + BaseRev: "d34db33f", + HeadRepository: "graphql-id", + HeadRef: "refs/heads/my-batch-change", + Title: "This is my batch change", + Body: "This is my batch change", + Commits: []batcheslib.GitCommitDescription{ + { + Message: "This is my batch change", + Diff: progressPrinterDiff, }, - Published: false, }, + Published: batcheslib.PublishedValue{Val: false}, }, }) From e74c327812e4d7fe89def2d3d4958f4744d8d2b1 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Tue, 31 Aug 2021 15:46:10 +0200 Subject: [PATCH 016/647] Code cleanup (#590) --- internal/batches/executor/check_cache.go | 1 - .../{task_builder.go => build_tasks.go} | 86 ++++++++----------- ...sk_builder_test.go => build_tasks_test.go} | 5 +- internal/batches/service/service.go | 2 +- internal/batches/service/workspaces.go | 4 + 5 files changed, 43 insertions(+), 55 deletions(-) delete mode 100644 internal/batches/executor/check_cache.go rename internal/batches/service/{task_builder.go => build_tasks.go} (66%) rename internal/batches/service/{task_builder_test.go => build_tasks_test.go} (94%) diff --git a/internal/batches/executor/check_cache.go b/internal/batches/executor/check_cache.go deleted file mode 100644 index be0ba73e6d..0000000000 --- a/internal/batches/executor/check_cache.go +++ /dev/null @@ -1 +0,0 @@ -package executor diff --git a/internal/batches/service/task_builder.go b/internal/batches/service/build_tasks.go similarity index 66% rename from internal/batches/service/task_builder.go rename to internal/batches/service/build_tasks.go index 63906b2df7..8591dd36e8 100644 --- a/internal/batches/service/task_builder.go +++ b/internal/batches/service/build_tasks.go @@ -10,32 +10,49 @@ import ( "github.com/sourcegraph/src-cli/internal/batches/template" ) -type directoryFinder interface { - FindDirectoriesInRepos(ctx context.Context, fileName string, repos ...*graphql.Repository) (map[*graphql.Repository][]string, error) -} +// buildTasks returns tasks for all the workspaces determined for the given spec. +func buildTasks(ctx context.Context, spec *batcheslib.BatchSpec, repos []*graphql.Repository, workspaces []RepoWorkspaces) ([]*executor.Task, error) { + repoByID := make(map[string]*graphql.Repository) + for _, repo := range repos { + repoByID[repo.ID] = repo + } -type taskBuilder struct { - spec *batcheslib.BatchSpec - finder directoryFinder -} + tasks := []*executor.Task{} + for _, ws := range workspaces { + repo, ok := repoByID[ws.RepoID] + if !ok { + return nil, errors.New("invalid state, didn't find repo for workspace definition") + } + for _, path := range ws.Paths { + fetchWorkspace := ws.OnlyFetchWorkspace + if path == "" { + fetchWorkspace = false + } + t, ok, err := buildTask(spec, repo, path, fetchWorkspace) + if err != nil { + return nil, err + } -// buildTasks returns tasks for all the workspaces determined for the given spec. -func buildTasks(ctx context.Context, spec *batcheslib.BatchSpec, finder directoryFinder, repos []*graphql.Repository, workspaces []RepoWorkspaces) ([]*executor.Task, error) { - tb := &taskBuilder{spec: spec, finder: finder} - return tb.buildAll(ctx, repos, workspaces) + if ok { + tasks = append(tasks, t) + } + } + } + + return tasks, nil } -func (tb *taskBuilder) buildTask(r *graphql.Repository, path string, onlyWorkspace bool) (*executor.Task, bool, error) { +func buildTask(spec *batcheslib.BatchSpec, r *graphql.Repository, path string, onlyWorkspace bool) (*executor.Task, bool, error) { stepCtx := &template.StepContext{ Repository: *r, BatchChange: template.BatchChangeAttributes{ - Name: tb.spec.Name, - Description: tb.spec.Description, + Name: spec.Name, + Description: spec.Description, }, } var taskSteps []batcheslib.Step - for _, step := range tb.spec.Steps { + for _, step := range spec.Steps { if step.IfCondition() == "" { taskSteps = append(taskSteps, step) continue @@ -71,42 +88,11 @@ func (tb *taskBuilder) buildTask(r *graphql.Repository, path string, onlyWorkspa Steps: taskSteps, OnlyFetchWorkspace: onlyWorkspace, - TransformChanges: tb.spec.TransformChanges, - Template: tb.spec.ChangesetTemplate, + TransformChanges: spec.TransformChanges, + Template: spec.ChangesetTemplate, BatchChangeAttributes: &template.BatchChangeAttributes{ - Name: tb.spec.Name, - Description: tb.spec.Description, + Name: spec.Name, + Description: spec.Description, }, }, true, nil } - -func (tb *taskBuilder) buildAll(ctx context.Context, repos []*graphql.Repository, workspaces []RepoWorkspaces) ([]*executor.Task, error) { - repoByID := make(map[string]*graphql.Repository) - for _, repo := range repos { - repoByID[repo.ID] = repo - } - - tasks := []*executor.Task{} - for _, ws := range workspaces { - repo, ok := repoByID[ws.RepoID] - if !ok { - return nil, errors.New("invalid state, didn't find repo for workspace definition") - } - for _, path := range ws.Paths { - fetchWorkspace := ws.OnlyFetchWorkspace - if path == "" { - fetchWorkspace = false - } - t, ok, err := tb.buildTask(repo, path, fetchWorkspace) - if err != nil { - return nil, err - } - - if ok { - tasks = append(tasks, t) - } - } - } - - return tasks, nil -} diff --git a/internal/batches/service/task_builder_test.go b/internal/batches/service/build_tasks_test.go similarity index 94% rename from internal/batches/service/task_builder_test.go rename to internal/batches/service/build_tasks_test.go index 5c1f6d62d8..73c3c8fe5e 100644 --- a/internal/batches/service/task_builder_test.go +++ b/internal/batches/service/build_tasks_test.go @@ -8,7 +8,7 @@ import ( batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" ) -func TestTaskBuilder_BuildTask_IfConditions(t *testing.T) { +func TestBuildTask_IfConditions(t *testing.T) { tests := map[string]struct { spec *batcheslib.BatchSpec @@ -117,8 +117,7 @@ func TestTaskBuilder_BuildTask_IfConditions(t *testing.T) { for name, tt := range tests { t.Run(name, func(t *testing.T) { - builder := &taskBuilder{spec: tt.spec} - task, ok, err := builder.buildTask(testRepo1, "", false) + task, ok, err := buildTask(tt.spec, testRepo1, "", false) if err != nil { t.Fatalf("unexpected err: %s", err) } diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index a8f146ee78..fd03c1dae0 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -187,7 +187,7 @@ func (svc *Service) DetermineWorkspaces(ctx context.Context, repos []*graphql.Re } func (svc *Service) BuildTasks(ctx context.Context, repos []*graphql.Repository, spec *batcheslib.BatchSpec, workspaces []RepoWorkspaces) ([]*executor.Task, error) { - return buildTasks(ctx, spec, svc, repos, workspaces) + return buildTasks(ctx, spec, repos, workspaces) } func (svc *Service) NewCoordinator(opts executor.NewCoordinatorOpts) *executor.Coordinator { diff --git a/internal/batches/service/workspaces.go b/internal/batches/service/workspaces.go index 1febb1d58c..a3406ee288 100644 --- a/internal/batches/service/workspaces.go +++ b/internal/batches/service/workspaces.go @@ -16,6 +16,10 @@ type RepoWorkspaces struct { OnlyFetchWorkspace bool } +type directoryFinder interface { + FindDirectoriesInRepos(ctx context.Context, fileName string, repos ...*graphql.Repository) (map[*graphql.Repository][]string, error) +} + // findWorkspaces matches the given repos to the workspace configs and // searches, via the Sourcegraph instance, the locations of the workspaces in // each repository. From 7ee60b05a9a0a89d65e2c77d94b5945e1b690147 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Wed, 1 Sep 2021 11:45:36 +0200 Subject: [PATCH 017/647] refactor: One RepoWorkspace per workspace (#592) This makes it easier to map 1 repo workspace to 1 task, useful in SSBC when we split per workspace. --- internal/batches/service/build_tasks.go | 20 +++---- internal/batches/service/service.go | 4 +- internal/batches/service/workspaces.go | 32 ++++++++--- internal/batches/service/workspaces_test.go | 63 ++++++++++++--------- 4 files changed, 69 insertions(+), 50 deletions(-) diff --git a/internal/batches/service/build_tasks.go b/internal/batches/service/build_tasks.go index 8591dd36e8..9f7f91e538 100644 --- a/internal/batches/service/build_tasks.go +++ b/internal/batches/service/build_tasks.go @@ -11,7 +11,7 @@ import ( ) // buildTasks returns tasks for all the workspaces determined for the given spec. -func buildTasks(ctx context.Context, spec *batcheslib.BatchSpec, repos []*graphql.Repository, workspaces []RepoWorkspaces) ([]*executor.Task, error) { +func buildTasks(ctx context.Context, spec *batcheslib.BatchSpec, repos []*graphql.Repository, workspaces []RepoWorkspace) ([]*executor.Task, error) { repoByID := make(map[string]*graphql.Repository) for _, repo := range repos { repoByID[repo.ID] = repo @@ -23,19 +23,13 @@ func buildTasks(ctx context.Context, spec *batcheslib.BatchSpec, repos []*graphq if !ok { return nil, errors.New("invalid state, didn't find repo for workspace definition") } - for _, path := range ws.Paths { - fetchWorkspace := ws.OnlyFetchWorkspace - if path == "" { - fetchWorkspace = false - } - t, ok, err := buildTask(spec, repo, path, fetchWorkspace) - if err != nil { - return nil, err - } + t, ok, err := buildTask(spec, repo, ws.Path, ws.OnlyFetchWorkspace) + if err != nil { + return nil, err + } - if ok { - tasks = append(tasks, t) - } + if ok { + tasks = append(tasks, t) } } diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index fd03c1dae0..5e076bba81 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -182,11 +182,11 @@ func (svc *Service) EnsureImage(ctx context.Context, name string) (docker.Image, return img, nil } -func (svc *Service) DetermineWorkspaces(ctx context.Context, repos []*graphql.Repository, spec *batcheslib.BatchSpec) ([]RepoWorkspaces, error) { +func (svc *Service) DetermineWorkspaces(ctx context.Context, repos []*graphql.Repository, spec *batcheslib.BatchSpec) ([]RepoWorkspace, error) { return findWorkspaces(ctx, spec, svc, repos) } -func (svc *Service) BuildTasks(ctx context.Context, repos []*graphql.Repository, spec *batcheslib.BatchSpec, workspaces []RepoWorkspaces) ([]*executor.Task, error) { +func (svc *Service) BuildTasks(ctx context.Context, repos []*graphql.Repository, spec *batcheslib.BatchSpec, workspaces []RepoWorkspace) ([]*executor.Task, error) { return buildTasks(ctx, spec, repos, workspaces) } diff --git a/internal/batches/service/workspaces.go b/internal/batches/service/workspaces.go index a3406ee288..1c2e2b84e7 100644 --- a/internal/batches/service/workspaces.go +++ b/internal/batches/service/workspaces.go @@ -10,9 +10,9 @@ import ( "github.com/sourcegraph/src-cli/internal/batches/graphql" ) -type RepoWorkspaces struct { +type RepoWorkspace struct { RepoID string - Paths []string + Path string OnlyFetchWorkspace bool } @@ -30,7 +30,7 @@ func findWorkspaces( spec *batcheslib.BatchSpec, finder directoryFinder, repos []*graphql.Repository, -) ([]RepoWorkspaces, error) { +) ([]RepoWorkspace, error) { // Pre-compile all globs. workspaceMatchers := make(map[batcheslib.WorkspaceConfiguration]glob.Glob) for _, conf := range spec.Workspaces { @@ -69,7 +69,12 @@ func findWorkspaces( } } - workspacesByID := map[string]RepoWorkspaces{} + type repoWorkspaces struct { + RepoID string + Paths []string + OnlyFetchWorkspace bool + } + workspacesByID := map[string]repoWorkspaces{} for idx, repos := range matched { conf := spec.Workspaces[idx] repoDirs, err := finder.FindDirectoriesInRepos(ctx, conf.RootAtLocationOf, repos...) @@ -82,7 +87,7 @@ func findWorkspaces( if len(dirs) == 0 { continue } - workspacesByID[repo.ID] = RepoWorkspaces{ + workspacesByID[repo.ID] = repoWorkspaces{ RepoID: repo.ID, Paths: dirs, OnlyFetchWorkspace: conf.OnlyFetchWorkspace, @@ -94,7 +99,7 @@ func findWorkspaces( for _, repo := range root { conf, ok := workspacesByID[repo.ID] if !ok { - workspacesByID[repo.ID] = RepoWorkspaces{ + workspacesByID[repo.ID] = repoWorkspaces{ RepoID: repo.ID, Paths: []string{""}, OnlyFetchWorkspace: false, @@ -104,9 +109,20 @@ func findWorkspaces( conf.Paths = append(workspacesByID[repo.ID].Paths, "") } - workspaces := make([]RepoWorkspaces, 0, len(workspacesByID)) + workspaces := make([]RepoWorkspace, 0, len(workspacesByID)) for _, workspace := range workspacesByID { - workspaces = append(workspaces, workspace) + for _, path := range workspace.Paths { + fetchWorkspace := workspace.OnlyFetchWorkspace + if path == "" { + fetchWorkspace = false + } + + workspaces = append(workspaces, RepoWorkspace{ + RepoID: workspace.RepoID, + Path: path, + OnlyFetchWorkspace: fetchWorkspace, + }) + } } return workspaces, nil } diff --git a/internal/batches/service/workspaces_test.go b/internal/batches/service/workspaces_test.go index 2475ad12f2..c47e79690a 100644 --- a/internal/batches/service/workspaces_test.go +++ b/internal/batches/service/workspaces_test.go @@ -10,7 +10,7 @@ import ( "github.com/sourcegraph/src-cli/internal/batches/graphql" ) -func TestTaskBuilder_BuildAll_Workspaces(t *testing.T) { +func TestFindWorkspaces(t *testing.T) { repos := []*graphql.Repository{ {ID: "repo-id-0", Name: "github.com/sourcegraph/automation-testing"}, {ID: "repo-id-1", Name: "github.com/sourcegraph/sourcegraph"}, @@ -24,16 +24,16 @@ func TestTaskBuilder_BuildAll_Workspaces(t *testing.T) { spec *batcheslib.BatchSpec finderResults map[*graphql.Repository][]string - // tasks per repository ID and in which path they are executed - wantTasks []RepoWorkspaces + // workspaces in which repo/path they are executed + wantWorkspaces []RepoWorkspace }{ "no workspace configuration": { spec: &batcheslib.BatchSpec{Steps: steps}, finderResults: finderResults{}, - wantTasks: []RepoWorkspaces{ - {RepoID: repos[0].ID, Paths: []string{""}}, - {RepoID: repos[1].ID, Paths: []string{""}}, - {RepoID: repos[2].ID, Paths: []string{""}}, + wantWorkspaces: []RepoWorkspace{ + {RepoID: repos[0].ID, Path: ""}, + {RepoID: repos[1].ID, Path: ""}, + {RepoID: repos[2].ID, Path: ""}, }, }, @@ -45,10 +45,10 @@ func TestTaskBuilder_BuildAll_Workspaces(t *testing.T) { }, }, finderResults: finderResults{}, - wantTasks: []RepoWorkspaces{ - {RepoID: repos[0].ID, Paths: []string{""}}, - {RepoID: repos[1].ID, Paths: []string{""}}, - {RepoID: repos[2].ID, Paths: []string{""}}, + wantWorkspaces: []RepoWorkspace{ + {RepoID: repos[0].ID, Path: ""}, + {RepoID: repos[1].ID, Path: ""}, + {RepoID: repos[2].ID, Path: ""}, }, }, @@ -63,8 +63,8 @@ func TestTaskBuilder_BuildAll_Workspaces(t *testing.T) { repos[0]: []string{}, repos[2]: []string{}, }, - wantTasks: []RepoWorkspaces{ - {RepoID: repos[1].ID, Paths: []string{""}}, + wantWorkspaces: []RepoWorkspace{ + {RepoID: repos[1].ID, Path: ""}, }, }, @@ -79,10 +79,14 @@ func TestTaskBuilder_BuildAll_Workspaces(t *testing.T) { repos[0]: {"a/b", "a/b/c", "d/e/f"}, repos[2]: {"a/b", "a/b/c", "d/e/f"}, }, - wantTasks: []RepoWorkspaces{ - {RepoID: repos[0].ID, Paths: []string{"a/b", "a/b/c", "d/e/f"}}, - {RepoID: repos[1].ID, Paths: []string{""}}, - {RepoID: repos[2].ID, Paths: []string{"a/b", "a/b/c", "d/e/f"}}, + wantWorkspaces: []RepoWorkspace{ + {RepoID: repos[0].ID, Path: "a/b"}, + {RepoID: repos[0].ID, Path: "a/b/c"}, + {RepoID: repos[0].ID, Path: "d/e/f"}, + {RepoID: repos[1].ID, Path: ""}, + {RepoID: repos[2].ID, Path: "a/b"}, + {RepoID: repos[2].ID, Path: "a/b/c"}, + {RepoID: repos[2].ID, Path: "d/e/f"}, }, }, @@ -101,10 +105,14 @@ func TestTaskBuilder_BuildAll_Workspaces(t *testing.T) { repos[0]: {"a/b", "a/b/c", "d/e/f"}, repos[2]: {"a/b", "a/b/c", "d/e/f"}, }, - wantTasks: []RepoWorkspaces{ - {RepoID: repos[0].ID, Paths: []string{"a/b", "a/b/c", "d/e/f"}, OnlyFetchWorkspace: true}, - {RepoID: repos[1].ID, Paths: []string{""}}, - {RepoID: repos[2].ID, Paths: []string{"a/b", "a/b/c", "d/e/f"}, OnlyFetchWorkspace: true}, + wantWorkspaces: []RepoWorkspace{ + {RepoID: repos[0].ID, Path: "a/b", OnlyFetchWorkspace: true}, + {RepoID: repos[0].ID, Path: "a/b/c", OnlyFetchWorkspace: true}, + {RepoID: repos[0].ID, Path: "d/e/f", OnlyFetchWorkspace: true}, + {RepoID: repos[1].ID, Path: ""}, + {RepoID: repos[2].ID, Path: "a/b", OnlyFetchWorkspace: true}, + {RepoID: repos[2].ID, Path: "a/b/c", OnlyFetchWorkspace: true}, + {RepoID: repos[2].ID, Path: "d/e/f", OnlyFetchWorkspace: true}, }, }, } @@ -117,13 +125,14 @@ func TestTaskBuilder_BuildAll_Workspaces(t *testing.T) { t.Fatalf("unexpected err: %s", err) } - sort.Slice(workspaces, func(i, j int) bool { return workspaces[i].RepoID < workspaces[j].RepoID }) + sort.Slice(workspaces, func(i, j int) bool { + if workspaces[i].RepoID == workspaces[j].RepoID { + return workspaces[i].Path < workspaces[j].Path + } + return workspaces[i].RepoID < workspaces[j].RepoID + }) - for _, workspace := range workspaces { - sort.Slice(workspace.Paths, func(i, j int) bool { return workspace.Paths[i] < workspace.Paths[j] }) - } - - if diff := cmp.Diff(tt.wantTasks, workspaces); diff != "" { + if diff := cmp.Diff(tt.wantWorkspaces, workspaces); diff != "" { t.Errorf("mismatch (-want +got):\n%s", diff) } }) From ec5016ddc2d841613486509aec23cc9795a12221 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Wed, 1 Sep 2021 16:28:05 +0200 Subject: [PATCH 018/647] Make template package independent of src-cli internals (#593) - Get rid of dependency on graphql.Repository - Move git package into sg/sg/lib --- go.mod | 2 +- go.sum | 4 +- internal/batches/executor/changeset_specs.go | 3 +- .../batches/executor/changeset_specs_test.go | 2 +- internal/batches/executor/coordinator_test.go | 2 +- .../batches/executor/execution_cache_test.go | 2 +- internal/batches/executor/executor_test.go | 2 +- internal/batches/executor/run_steps.go | 5 +- internal/batches/features_test.go | 1 - internal/batches/git/changes.go | 73 ----------------- internal/batches/git/changes_test.go | 80 ------------------- internal/batches/graphql/repository.go | 14 ---- internal/batches/service/build_tasks.go | 26 +++--- internal/batches/template/main_test.go | 6 +- .../batches/template/partial_eval_test.go | 3 +- internal/batches/template/templating.go | 33 +++++++- internal/batches/template/templating_test.go | 2 +- internal/batches/util/repo.go | 20 +++++ internal/batches/workspace/bind_workspace.go | 2 +- .../batches/workspace/volume_workspace.go | 2 +- .../workspace/volume_workspace_test.go | 2 +- internal/batches/workspace/workspace.go | 2 +- 22 files changed, 82 insertions(+), 206 deletions(-) delete mode 100644 internal/batches/features_test.go delete mode 100644 internal/batches/git/changes.go delete mode 100644 internal/batches/git/changes_test.go create mode 100644 internal/batches/util/repo.go diff --git a/go.mod b/go.mod index 58705db20d..86517eed9e 100644 --- a/go.mod +++ b/go.mod @@ -25,7 +25,7 @@ require ( github.com/sourcegraph/batch-change-utils v0.0.0-20210708162152-c9f35b905d94 github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf - github.com/sourcegraph/sourcegraph/lib v0.0.0-20210831122102-a95181f49527 + github.com/sourcegraph/sourcegraph/lib v0.0.0-20210901132614-5780c9c4b466 github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect golang.org/x/net v0.0.0-20210614182718-04defd469f4e diff --git a/go.sum b/go.sum index 086bf13b26..735b720c57 100644 --- a/go.sum +++ b/go.sum @@ -263,8 +263,8 @@ github.com/sourcegraph/go-diff v0.6.1 h1:hmA1LzxW0n1c3Q4YbrFgg4P99GSnebYa3x8gr0H github.com/sourcegraph/go-diff v0.6.1/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20210831122102-a95181f49527 h1:Bj2XOghFkSnxE0EcpmtmjIFbqDkJ0wBNTvM6cguKaKs= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20210831122102-a95181f49527/go.mod h1:aH/URdfJ92i5Ec/5u2GSlliMZtKzsD91oTJNwZpH8Hc= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20210901132614-5780c9c4b466 h1:hyo3Vr63aieMyWqrfy0skzZHT3ACjajrd3ksVxmMl7k= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20210901132614-5780c9c4b466/go.mod h1:lSNpzAxCBx40MpkM/DbMH7ZUMURcpAstABzhbc4O5V8= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= diff --git a/internal/batches/executor/changeset_specs.go b/internal/batches/executor/changeset_specs.go index 44844bdd44..a2a56cd701 100644 --- a/internal/batches/executor/changeset_specs.go +++ b/internal/batches/executor/changeset_specs.go @@ -9,6 +9,7 @@ import ( batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/template" + "github.com/sourcegraph/src-cli/internal/batches/util" ) var errOptionalPublishedUnsupported = errors.New(`This Sourcegraph version requires the "published" field to be specified in the batch spec; upgrade to version 3.30.0 or later to be able to omit the published field and control publication from the UI.`) @@ -23,7 +24,7 @@ func createChangesetSpecs(task *Task, result executionResult, features batches.F Path: result.Path, }, Outputs: result.Outputs, - Repository: *task.Repository, + Repository: util.GraphQLRepoToTemplatingRepo(task.Repository), } var authorName string diff --git a/internal/batches/executor/changeset_specs_test.go b/internal/batches/executor/changeset_specs_test.go index 79bed582bf..6e626fa4a4 100644 --- a/internal/batches/executor/changeset_specs_test.go +++ b/internal/batches/executor/changeset_specs_test.go @@ -8,8 +8,8 @@ import ( "github.com/mitchellh/copystructure" "github.com/sourcegraph/batch-change-utils/overridable" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" + "github.com/sourcegraph/sourcegraph/lib/batches/git" "github.com/sourcegraph/src-cli/internal/batches" - "github.com/sourcegraph/src-cli/internal/batches/git" "github.com/sourcegraph/src-cli/internal/batches/template" ) diff --git a/internal/batches/executor/coordinator_test.go b/internal/batches/executor/coordinator_test.go index b158a0bc47..ec95e6876e 100644 --- a/internal/batches/executor/coordinator_test.go +++ b/internal/batches/executor/coordinator_test.go @@ -11,7 +11,7 @@ import ( "github.com/google/go-cmp/cmp/cmpopts" "github.com/sourcegraph/batch-change-utils/overridable" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" - "github.com/sourcegraph/src-cli/internal/batches/git" + "github.com/sourcegraph/sourcegraph/lib/batches/git" "github.com/sourcegraph/src-cli/internal/batches/graphql" "github.com/sourcegraph/src-cli/internal/batches/mock" "github.com/sourcegraph/src-cli/internal/batches/template" diff --git a/internal/batches/executor/execution_cache_test.go b/internal/batches/executor/execution_cache_test.go index 5eb5084c49..14ccfcc5e3 100644 --- a/internal/batches/executor/execution_cache_test.go +++ b/internal/batches/executor/execution_cache_test.go @@ -8,7 +8,7 @@ import ( "github.com/google/go-cmp/cmp" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" - "github.com/sourcegraph/src-cli/internal/batches/git" + "github.com/sourcegraph/sourcegraph/lib/batches/git" "gopkg.in/yaml.v3" ) diff --git a/internal/batches/executor/executor_test.go b/internal/batches/executor/executor_test.go index d5af386d4c..78366665ff 100644 --- a/internal/batches/executor/executor_test.go +++ b/internal/batches/executor/executor_test.go @@ -18,10 +18,10 @@ import ( "github.com/pkg/errors" "github.com/sourcegraph/go-diff/diff" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" + "github.com/sourcegraph/sourcegraph/lib/batches/git" "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/docker" - "github.com/sourcegraph/src-cli/internal/batches/git" "github.com/sourcegraph/src-cli/internal/batches/mock" "github.com/sourcegraph/src-cli/internal/batches/template" "github.com/sourcegraph/src-cli/internal/batches/workspace" diff --git a/internal/batches/executor/run_steps.go b/internal/batches/executor/run_steps.go index 43de56c3c0..8cfa43dfaf 100644 --- a/internal/batches/executor/run_steps.go +++ b/internal/batches/executor/run_steps.go @@ -15,9 +15,10 @@ import ( "github.com/hashicorp/go-multierror" "github.com/pkg/errors" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" - "github.com/sourcegraph/src-cli/internal/batches/git" + "github.com/sourcegraph/sourcegraph/lib/batches/git" "github.com/sourcegraph/src-cli/internal/batches/log" "github.com/sourcegraph/src-cli/internal/batches/template" + "github.com/sourcegraph/src-cli/internal/batches/util" "github.com/sourcegraph/src-cli/internal/batches/workspace" yamlv3 "gopkg.in/yaml.v3" @@ -125,7 +126,7 @@ func runSteps(ctx context.Context, opts *executionOpts) (result executionResult, stepContext := template.StepContext{ BatchChange: *opts.task.BatchChangeAttributes, - Repository: *opts.task.Repository, + Repository: util.GraphQLRepoToTemplatingRepo(opts.task.Repository), Outputs: execResult.Outputs, Steps: template.StepsContext{ Path: execResult.Path, diff --git a/internal/batches/features_test.go b/internal/batches/features_test.go deleted file mode 100644 index 0c23368752..0000000000 --- a/internal/batches/features_test.go +++ /dev/null @@ -1 +0,0 @@ -package batches diff --git a/internal/batches/git/changes.go b/internal/batches/git/changes.go deleted file mode 100644 index ff31286e30..0000000000 --- a/internal/batches/git/changes.go +++ /dev/null @@ -1,73 +0,0 @@ -package git - -import ( - "fmt" - "strings" - - "github.com/sourcegraph/go-diff/diff" -) - -// Changes are the changes made to files in a repository. -type Changes struct { - Modified []string `json:"modified"` - Added []string `json:"added"` - Deleted []string `json:"deleted"` - Renamed []string `json:"renamed"` -} - -// ParseStatus parses the output of `git status` and turns it into Changes. -func ParseGitStatus(out []byte) (Changes, error) { - result := Changes{} - - stripped := strings.TrimSpace(string(out)) - if stripped == "" { - return result, nil - } - - for _, line := range strings.Split(stripped, "\n") { - if len(line) < 4 { - return result, fmt.Errorf("git status line has unrecognized format: %q", line) - } - - file := line[3:] - - switch line[0] { - case 'M': - result.Modified = append(result.Modified, file) - case 'A': - result.Added = append(result.Added, file) - case 'D': - result.Deleted = append(result.Deleted, file) - case 'R': - files := strings.Split(file, " -> ") - newFile := files[len(files)-1] - result.Renamed = append(result.Renamed, newFile) - } - } - - return result, nil -} - -func ChangesInDiff(rawDiff []byte) (Changes, error) { - result := Changes{} - - fileDiffs, err := diff.ParseMultiFileDiff(rawDiff) - if err != nil { - return result, err - } - - for _, fd := range fileDiffs { - switch { - case fd.NewName == "/dev/null": - result.Deleted = append(result.Deleted, fd.OrigName) - case fd.OrigName == "/dev/null": - result.Added = append(result.Added, fd.NewName) - case fd.OrigName == fd.NewName: - result.Modified = append(result.Modified, fd.OrigName) - case fd.OrigName != fd.NewName: - result.Renamed = append(result.Renamed, fd.NewName) - } - } - - return result, nil -} diff --git a/internal/batches/git/changes_test.go b/internal/batches/git/changes_test.go deleted file mode 100644 index c020f708a1..0000000000 --- a/internal/batches/git/changes_test.go +++ /dev/null @@ -1,80 +0,0 @@ -package git - -import ( - "testing" - - "github.com/google/go-cmp/cmp" -) - -func TestParseGitStatus(t *testing.T) { - const input = `M README.md -M another_file.go -A new_file.txt -A barfoo/new_file.txt -D to_be_deleted.txt -R README.md -> README.markdown -` - parsed, err := ParseGitStatus([]byte(input)) - if err != nil { - t.Fatal(err) - } - - want := Changes{ - Modified: []string{"README.md", "another_file.go"}, - Added: []string{"new_file.txt", "barfoo/new_file.txt"}, - Deleted: []string{"to_be_deleted.txt"}, - Renamed: []string{"README.markdown"}, - } - - if !cmp.Equal(want, parsed) { - t.Fatalf("wrong output:\n%s", cmp.Diff(want, parsed)) - } -} - -func TestChangesInDiff(t *testing.T) { - const input = `diff --git README.md README.md -index c9644dd..2552420 100644 ---- README.md -+++ README.md -@@ -1,2 +1,3 @@ - # Welcome to the README - foobar -+barfoo and what else? -diff --git a_new_file_appears.txt a_new_file_appears.txt -new file mode 100644 -index 0000000..09f946b ---- /dev/null -+++ a_new_file_appears.txt -@@ -0,0 +1 @@ -+boom! like magic it appears -diff --git another_file.txt another_cool_file.txt -similarity index 100% -rename from another_file.txt -rename to another_cool_file.txt -diff --git yet_another_file.txt yet_another_file.txt -deleted file mode 100644 -index c27a40c..0000000 ---- yet_another_file.txt -+++ /dev/null -@@ -1,3 +0,0 @@ --this is yet another file --this time though --with tree lines -` - - changes, err := ChangesInDiff([]byte(input)) - if err != nil { - t.Fatal(err) - } - - want := Changes{ - Modified: []string{"README.md"}, - Added: []string{"a_new_file_appears.txt"}, - Deleted: []string{"yet_another_file.txt"}, - Renamed: []string{"another_cool_file.txt"}, - } - - if !cmp.Equal(want, changes) { - t.Fatalf("wrong output:\n%s", cmp.Diff(want, changes)) - } -} diff --git a/internal/batches/graphql/repository.go b/internal/batches/graphql/repository.go index 9a6ddd6184..d08b756fbc 100644 --- a/internal/batches/graphql/repository.go +++ b/internal/batches/graphql/repository.go @@ -3,7 +3,6 @@ package graphql import ( "crypto/sha256" "encoding/base64" - "sort" "strings" ) @@ -93,16 +92,3 @@ func (r *Repository) SlugForPath(path string) string { } return strings.ReplaceAll(name, "/", "-") + "-" + r.Rev() } - -func (r *Repository) SearchResultPaths() (list fileMatchPathList) { - var files []string - for f := range r.FileMatches { - files = append(files, f) - } - sort.Strings(files) - return fileMatchPathList(files) -} - -type fileMatchPathList []string - -func (f fileMatchPathList) String() string { return strings.Join(f, " ") } diff --git a/internal/batches/service/build_tasks.go b/internal/batches/service/build_tasks.go index 9f7f91e538..cb5c6dc90f 100644 --- a/internal/batches/service/build_tasks.go +++ b/internal/batches/service/build_tasks.go @@ -8,6 +8,7 @@ import ( "github.com/sourcegraph/src-cli/internal/batches/executor" "github.com/sourcegraph/src-cli/internal/batches/graphql" "github.com/sourcegraph/src-cli/internal/batches/template" + "github.com/sourcegraph/src-cli/internal/batches/util" ) // buildTasks returns tasks for all the workspaces determined for the given spec. @@ -37,21 +38,23 @@ func buildTasks(ctx context.Context, spec *batcheslib.BatchSpec, repos []*graphq } func buildTask(spec *batcheslib.BatchSpec, r *graphql.Repository, path string, onlyWorkspace bool) (*executor.Task, bool, error) { - stepCtx := &template.StepContext{ - Repository: *r, - BatchChange: template.BatchChangeAttributes{ - Name: spec.Name, - Description: spec.Description, - }, + batchChange := template.BatchChangeAttributes{ + Name: spec.Name, + Description: spec.Description, } - var taskSteps []batcheslib.Step + taskSteps := []batcheslib.Step{} for _, step := range spec.Steps { + // If no if condition is given, just go ahead and add the step to the list. if step.IfCondition() == "" { taskSteps = append(taskSteps, step) continue } + stepCtx := &template.StepContext{ + Repository: util.GraphQLRepoToTemplatingRepo(r), + BatchChange: batchChange, + } static, boolVal, err := template.IsStaticBool(step.IfCondition(), stepCtx) if err != nil { return nil, false, err @@ -82,11 +85,8 @@ func buildTask(spec *batcheslib.BatchSpec, r *graphql.Repository, path string, o Steps: taskSteps, OnlyFetchWorkspace: onlyWorkspace, - TransformChanges: spec.TransformChanges, - Template: spec.ChangesetTemplate, - BatchChangeAttributes: &template.BatchChangeAttributes{ - Name: spec.Name, - Description: spec.Description, - }, + TransformChanges: spec.TransformChanges, + Template: spec.ChangesetTemplate, + BatchChangeAttributes: &batchChange, }, true, nil } diff --git a/internal/batches/template/main_test.go b/internal/batches/template/main_test.go index 38a13e63e9..5113074ad0 100644 --- a/internal/batches/template/main_test.go +++ b/internal/batches/template/main_test.go @@ -1,11 +1,9 @@ package template -import "github.com/sourcegraph/src-cli/internal/batches/graphql" - -var testRepo1 = &graphql.Repository{ +var testRepo1 = &TemplatingRepository{ ID: "src-cli", Name: "github.com/sourcegraph/src-cli", - DefaultBranch: &graphql.Branch{Name: "main", Target: graphql.Target{OID: "d34db33f"}}, + DefaultBranch: TemplatingBranch{Name: "main", TargetOID: "d34db33f"}, FileMatches: map[string]bool{ "README.md": true, "main.go": true, diff --git a/internal/batches/template/partial_eval_test.go b/internal/batches/template/partial_eval_test.go index ec0d0b6f9c..403d7ed4b7 100644 --- a/internal/batches/template/partial_eval_test.go +++ b/internal/batches/template/partial_eval_test.go @@ -4,7 +4,6 @@ import ( "testing" "github.com/google/go-cmp/cmp" - "github.com/sourcegraph/src-cli/internal/batches/graphql" ) var partialEvalStepCtx = &StepContext{ @@ -13,7 +12,7 @@ var partialEvalStepCtx = &StepContext{ Description: "test-description", }, // Step is not set when evalStepCondition is called - Repository: graphql.Repository{ + Repository: TemplatingRepository{ Name: "github.com/sourcegraph/src-cli", FileMatches: map[string]bool{ "README.md": true, diff --git a/internal/batches/template/templating.go b/internal/batches/template/templating.go index 9fc9ff1226..2fc5aea408 100644 --- a/internal/batches/template/templating.go +++ b/internal/batches/template/templating.go @@ -3,13 +3,13 @@ package template import ( "bytes" "io" + "sort" "strings" "text/template" "github.com/gobwas/glob" "github.com/pkg/errors" - "github.com/sourcegraph/src-cli/internal/batches/git" - "github.com/sourcegraph/src-cli/internal/batches/graphql" + "github.com/sourcegraph/sourcegraph/lib/batches/git" ) const startDelim = "${{" @@ -85,6 +85,31 @@ type BatchChangeAttributes struct { Description string } +type TemplatingBranch struct { + Name string + TargetOID string +} + +type TemplatingRepository struct { + ID string + Name string + DefaultBranch TemplatingBranch + FileMatches map[string]bool +} + +func (r TemplatingRepository) SearchResultPaths() (list fileMatchPathList) { + var files []string + for f := range r.FileMatches { + files = append(files, f) + } + sort.Strings(files) + return fileMatchPathList(files) +} + +type fileMatchPathList []string + +func (f fileMatchPathList) String() string { return strings.Join(f, " ") } + // StepContext represents the contextual information available when rendering a // step's fields, such as "run" or "outputs", as templates. type StepContext struct { @@ -102,7 +127,7 @@ type StepContext struct { // previous step. PreviousStep StepResult // Repository is the Sourcegraph repository in which the steps are executed. - Repository graphql.Repository + Repository TemplatingRepository } // ToFuncMap returns a template.FuncMap to access fields on the StepContext in a @@ -232,7 +257,7 @@ type ChangesetTemplateContext struct { Outputs map[string]interface{} // Repository is the repository in which the steps were executed. - Repository graphql.Repository + Repository TemplatingRepository } // ToFuncMap returns a template.FuncMap to access fields on the StepContext in a diff --git a/internal/batches/template/templating_test.go b/internal/batches/template/templating_test.go index d9e1d62160..b6990f9fc4 100644 --- a/internal/batches/template/templating_test.go +++ b/internal/batches/template/templating_test.go @@ -5,7 +5,7 @@ import ( "testing" "github.com/google/go-cmp/cmp" - "github.com/sourcegraph/src-cli/internal/batches/git" + "github.com/sourcegraph/sourcegraph/lib/batches/git" "gopkg.in/yaml.v3" ) diff --git a/internal/batches/util/repo.go b/internal/batches/util/repo.go new file mode 100644 index 0000000000..eaea63cfdc --- /dev/null +++ b/internal/batches/util/repo.go @@ -0,0 +1,20 @@ +package util + +import ( + "github.com/sourcegraph/src-cli/internal/batches/graphql" + "github.com/sourcegraph/src-cli/internal/batches/template" +) + +// GraphQLRepoToTemplatingRepo transforms a given *graphql.Repository into a +// template.TemplatingRepository. +func GraphQLRepoToTemplatingRepo(r *graphql.Repository) template.TemplatingRepository { + return template.TemplatingRepository{ + ID: r.ID, + Name: r.Name, + DefaultBranch: template.TemplatingBranch{ + Name: r.DefaultBranch.Name, + TargetOID: r.DefaultBranch.Target.OID, + }, + FileMatches: r.FileMatches, + } +} diff --git a/internal/batches/workspace/bind_workspace.go b/internal/batches/workspace/bind_workspace.go index c9e1ae12e9..02fd95e1f3 100644 --- a/internal/batches/workspace/bind_workspace.go +++ b/internal/batches/workspace/bind_workspace.go @@ -14,8 +14,8 @@ import ( "github.com/hashicorp/go-multierror" "github.com/pkg/errors" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" + "github.com/sourcegraph/sourcegraph/lib/batches/git" "github.com/sourcegraph/src-cli/internal/batches" - "github.com/sourcegraph/src-cli/internal/batches/git" "github.com/sourcegraph/src-cli/internal/batches/graphql" ) diff --git a/internal/batches/workspace/volume_workspace.go b/internal/batches/workspace/volume_workspace.go index f1c3fc2536..fa8d96d52c 100644 --- a/internal/batches/workspace/volume_workspace.go +++ b/internal/batches/workspace/volume_workspace.go @@ -14,9 +14,9 @@ import ( "github.com/pkg/errors" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" + "github.com/sourcegraph/sourcegraph/lib/batches/git" "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/docker" - "github.com/sourcegraph/src-cli/internal/batches/git" "github.com/sourcegraph/src-cli/internal/batches/graphql" "github.com/sourcegraph/src-cli/internal/exec" "github.com/sourcegraph/src-cli/internal/version" diff --git a/internal/batches/workspace/volume_workspace_test.go b/internal/batches/workspace/volume_workspace_test.go index ce0e813593..a2226c2800 100644 --- a/internal/batches/workspace/volume_workspace_test.go +++ b/internal/batches/workspace/volume_workspace_test.go @@ -13,8 +13,8 @@ import ( "github.com/pkg/errors" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" + "github.com/sourcegraph/sourcegraph/lib/batches/git" "github.com/sourcegraph/src-cli/internal/batches/docker" - "github.com/sourcegraph/src-cli/internal/batches/git" "github.com/sourcegraph/src-cli/internal/batches/graphql" "github.com/sourcegraph/src-cli/internal/batches/mock" "github.com/sourcegraph/src-cli/internal/exec/expect" diff --git a/internal/batches/workspace/workspace.go b/internal/batches/workspace/workspace.go index dad4e40c50..d5c7a67871 100644 --- a/internal/batches/workspace/workspace.go +++ b/internal/batches/workspace/workspace.go @@ -6,9 +6,9 @@ import ( "github.com/pkg/errors" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" + "github.com/sourcegraph/sourcegraph/lib/batches/git" "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/docker" - "github.com/sourcegraph/src-cli/internal/batches/git" "github.com/sourcegraph/src-cli/internal/batches/graphql" ) From 31e168be7a3b397aa1e9486db9bd9aee1d2f9656 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Wed, 1 Sep 2021 16:35:42 +0200 Subject: [PATCH 019/647] Move template pkg to sg/sg/lib (#594) --- go.mod | 2 +- go.sum | 4 +- internal/batches/executor/changeset_specs.go | 2 +- .../batches/executor/changeset_specs_test.go | 2 +- internal/batches/executor/coordinator_test.go | 2 +- internal/batches/executor/executor_test.go | 2 +- internal/batches/executor/run_steps.go | 2 +- internal/batches/executor/task.go | 2 +- internal/batches/service/build_tasks.go | 2 +- internal/batches/template/main_test.go | 11 - internal/batches/template/partial_eval.go | 383 ------------------ .../batches/template/partial_eval_test.go | 294 -------------- internal/batches/template/templating.go | 311 -------------- internal/batches/template/templating_test.go | 361 ----------------- internal/batches/util/repo.go | 2 +- 15 files changed, 11 insertions(+), 1371 deletions(-) delete mode 100644 internal/batches/template/main_test.go delete mode 100644 internal/batches/template/partial_eval.go delete mode 100644 internal/batches/template/partial_eval_test.go delete mode 100644 internal/batches/template/templating.go delete mode 100644 internal/batches/template/templating_test.go diff --git a/go.mod b/go.mod index 86517eed9e..27fd864927 100644 --- a/go.mod +++ b/go.mod @@ -25,7 +25,7 @@ require ( github.com/sourcegraph/batch-change-utils v0.0.0-20210708162152-c9f35b905d94 github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf - github.com/sourcegraph/sourcegraph/lib v0.0.0-20210901132614-5780c9c4b466 + github.com/sourcegraph/sourcegraph/lib v0.0.0-20210901142905-cc5a3f7fd279 github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect golang.org/x/net v0.0.0-20210614182718-04defd469f4e diff --git a/go.sum b/go.sum index 735b720c57..4b8795e208 100644 --- a/go.sum +++ b/go.sum @@ -263,8 +263,8 @@ github.com/sourcegraph/go-diff v0.6.1 h1:hmA1LzxW0n1c3Q4YbrFgg4P99GSnebYa3x8gr0H github.com/sourcegraph/go-diff v0.6.1/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20210901132614-5780c9c4b466 h1:hyo3Vr63aieMyWqrfy0skzZHT3ACjajrd3ksVxmMl7k= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20210901132614-5780c9c4b466/go.mod h1:lSNpzAxCBx40MpkM/DbMH7ZUMURcpAstABzhbc4O5V8= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20210901142905-cc5a3f7fd279 h1:RVrhk8J8Ob4J59BAFA5koKlC5pYfz3GCPpzN5R0+M3g= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20210901142905-cc5a3f7fd279/go.mod h1:8A6WlyQouL7Y5MUdL+2+An5rsysLYlm+DaZN/T3egwU= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= diff --git a/internal/batches/executor/changeset_specs.go b/internal/batches/executor/changeset_specs.go index a2a56cd701..345d6bf634 100644 --- a/internal/batches/executor/changeset_specs.go +++ b/internal/batches/executor/changeset_specs.go @@ -7,8 +7,8 @@ import ( "github.com/pkg/errors" "github.com/sourcegraph/go-diff/diff" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" + "github.com/sourcegraph/sourcegraph/lib/batches/template" "github.com/sourcegraph/src-cli/internal/batches" - "github.com/sourcegraph/src-cli/internal/batches/template" "github.com/sourcegraph/src-cli/internal/batches/util" ) diff --git a/internal/batches/executor/changeset_specs_test.go b/internal/batches/executor/changeset_specs_test.go index 6e626fa4a4..c4d081d81f 100644 --- a/internal/batches/executor/changeset_specs_test.go +++ b/internal/batches/executor/changeset_specs_test.go @@ -9,8 +9,8 @@ import ( "github.com/sourcegraph/batch-change-utils/overridable" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/git" + "github.com/sourcegraph/sourcegraph/lib/batches/template" "github.com/sourcegraph/src-cli/internal/batches" - "github.com/sourcegraph/src-cli/internal/batches/template" ) func TestCreateChangesetSpecs(t *testing.T) { diff --git a/internal/batches/executor/coordinator_test.go b/internal/batches/executor/coordinator_test.go index ec95e6876e..890d37c25d 100644 --- a/internal/batches/executor/coordinator_test.go +++ b/internal/batches/executor/coordinator_test.go @@ -12,9 +12,9 @@ import ( "github.com/sourcegraph/batch-change-utils/overridable" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/git" + "github.com/sourcegraph/sourcegraph/lib/batches/template" "github.com/sourcegraph/src-cli/internal/batches/graphql" "github.com/sourcegraph/src-cli/internal/batches/mock" - "github.com/sourcegraph/src-cli/internal/batches/template" ) func TestCoordinator_Execute(t *testing.T) { diff --git a/internal/batches/executor/executor_test.go b/internal/batches/executor/executor_test.go index 78366665ff..ca91b15927 100644 --- a/internal/batches/executor/executor_test.go +++ b/internal/batches/executor/executor_test.go @@ -19,11 +19,11 @@ import ( "github.com/sourcegraph/go-diff/diff" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/git" + "github.com/sourcegraph/sourcegraph/lib/batches/template" "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/docker" "github.com/sourcegraph/src-cli/internal/batches/mock" - "github.com/sourcegraph/src-cli/internal/batches/template" "github.com/sourcegraph/src-cli/internal/batches/workspace" ) diff --git a/internal/batches/executor/run_steps.go b/internal/batches/executor/run_steps.go index 8cfa43dfaf..0e2b08c0a4 100644 --- a/internal/batches/executor/run_steps.go +++ b/internal/batches/executor/run_steps.go @@ -16,8 +16,8 @@ import ( "github.com/pkg/errors" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/git" + "github.com/sourcegraph/sourcegraph/lib/batches/template" "github.com/sourcegraph/src-cli/internal/batches/log" - "github.com/sourcegraph/src-cli/internal/batches/template" "github.com/sourcegraph/src-cli/internal/batches/util" "github.com/sourcegraph/src-cli/internal/batches/workspace" diff --git a/internal/batches/executor/task.go b/internal/batches/executor/task.go index 1faec41177..ffbb820c11 100644 --- a/internal/batches/executor/task.go +++ b/internal/batches/executor/task.go @@ -2,9 +2,9 @@ package executor import ( batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" + "github.com/sourcegraph/sourcegraph/lib/batches/template" "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/graphql" - "github.com/sourcegraph/src-cli/internal/batches/template" ) type Task struct { diff --git a/internal/batches/service/build_tasks.go b/internal/batches/service/build_tasks.go index cb5c6dc90f..61e6fcecac 100644 --- a/internal/batches/service/build_tasks.go +++ b/internal/batches/service/build_tasks.go @@ -5,9 +5,9 @@ import ( "github.com/pkg/errors" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" + "github.com/sourcegraph/sourcegraph/lib/batches/template" "github.com/sourcegraph/src-cli/internal/batches/executor" "github.com/sourcegraph/src-cli/internal/batches/graphql" - "github.com/sourcegraph/src-cli/internal/batches/template" "github.com/sourcegraph/src-cli/internal/batches/util" ) diff --git a/internal/batches/template/main_test.go b/internal/batches/template/main_test.go deleted file mode 100644 index 5113074ad0..0000000000 --- a/internal/batches/template/main_test.go +++ /dev/null @@ -1,11 +0,0 @@ -package template - -var testRepo1 = &TemplatingRepository{ - ID: "src-cli", - Name: "github.com/sourcegraph/src-cli", - DefaultBranch: TemplatingBranch{Name: "main", TargetOID: "d34db33f"}, - FileMatches: map[string]bool{ - "README.md": true, - "main.go": true, - }, -} diff --git a/internal/batches/template/partial_eval.go b/internal/batches/template/partial_eval.go deleted file mode 100644 index d1276c6b98..0000000000 --- a/internal/batches/template/partial_eval.go +++ /dev/null @@ -1,383 +0,0 @@ -package template - -import ( - "bytes" - "fmt" - "reflect" - "strings" - "text/template" - "text/template/parse" -) - -// IsStaticBool parses the input as a text/template and attempts to evaluate it -// with only the ahead-of-execution information available in StepContext. -// -// To do that it first calls parseAndPartialEval to evaluate the template as -// much as possible. -// -// If, after evaluation, more than text is left (i.e. because the template -// requires information that's only available later) the function returns with -// the first return value being false, because the template is not "static". -// first return value is true. -// -// If only text is left we check whether that text equals "true". The result of -// that check is the second return value. -func IsStaticBool(input string, ctx *StepContext) (isStatic bool, boolVal bool, err error) { - t, err := parseAndPartialEval(input, ctx) - if err != nil { - return false, false, err - } - - isStatic = true - for _, n := range t.Tree.Root.Nodes { - if n.Type() != parse.NodeText { - isStatic = false - break - } - } - if !isStatic { - return isStatic, false, nil - } - - return true, isTrueOutput(t.Tree.Root), nil -} - -// parseAndPartialEval parses input as a text/template and then attempts to -// partially evaluate the parts of the template it can evaluate ahead of time -// (meaning: before we've executed any batch spec steps and have a full -// StepContext available). -// -// If it's possible to evaluate a parse.ActionNode (which is what sits between -// delimiters in a text/template), the node is rewritten into a parse.TextNode, -// to make it look like it's always been text in the template. -// -// Partial evaluation is done in a best effort manner: if it's not possible to -// evaluate a node (because it requires information that we only later get, or -// because it's too complex, etc.) we degrade gracefully and simply abort the -// partial evaluation and leave the node as is. -// -// It also should be noted that we don't do "full" partial evaluation: if we -// come across value that we can't partially evaluate we abort the process *for -// the whole node* without replacing the sub-nodes that we've successfully -// evaluated. Why? Because we can't construct correct `*parse.Node` from -// outside the `parse` package. In other words: we evaluate -// all-parse.ActionNode-or-nothing. -func parseAndPartialEval(input string, ctx *StepContext) (*template.Template, error) { - t, err := template. - New("partial-eval"). - Delims(startDelim, endDelim). - Funcs(builtins). - Funcs(ctx.ToFuncMap()). - Parse(input) - - if err != nil { - return nil, err - } - - for i, n := range t.Tree.Root.Nodes { - t.Tree.Root.Nodes[i] = rewriteNode(n, ctx) - } - - return t, nil -} - -// rewriteNode takes the given parse.Parse and tries to partially evaluate it. -// If that's possible, the output of the evaluation is turned into text and -// instead of the node that was passed in a new parse.TextNode is returned that -// represents the output of the evaluation. -func rewriteNode(n parse.Node, ctx *StepContext) parse.Node { - switch n := n.(type) { - case *parse.ActionNode: - if val, ok := evalPipe(ctx, n.Pipe); ok { - var out bytes.Buffer - fmt.Fprint(&out, val.Interface()) - return &parse.TextNode{ - Text: out.Bytes(), - Pos: n.Pos, - NodeType: parse.NodeText, - } - } - - return n - - default: - return n - } -} - -// noValue is returned by the functions that partially evaluate a parse.Node -// to signify that evaluation was not possible or did not yield a value. -var noValue reflect.Value - -func evalPipe(ctx *StepContext, p *parse.PipeNode) (finalVal reflect.Value, ok bool) { - // If the pipe contains declaration we abort evaluation. - if len(p.Decl) > 0 { - return noValue, false - } - - // TODO: Support finalVal - // finalVal is the value of the previous Cmd in a pipe (i.e. `${{ 3 + 3 | eq 6 }}`) - // It needs to be the final (fixed) argument of a call if it's set. - - for _, c := range p.Cmds { - finalVal, ok = evalCmd(ctx, c, finalVal) - if !ok { - return noValue, false - } - } - - return finalVal, ok -} - -func evalCmd(ctx *StepContext, c *parse.CommandNode, previousValue reflect.Value) (reflect.Value, bool) { - switch first := c.Args[0].(type) { - case *parse.BoolNode, *parse.NumberNode, *parse.StringNode, *parse.ChainNode: - if len(c.Args) == 1 { - return evalNode(ctx, first) - } - return noValue, false - - case *parse.IdentifierNode: - // A function call always starts with an identifier - return evalFunction(ctx, first, first.Ident, c.Args, previousValue) - - default: - // Node type that we don't care about, so we don't even try to evaluate it - return noValue, false - } -} - -func evalNode(ctx *StepContext, n parse.Node) (reflect.Value, bool) { - switch n := n.(type) { - case *parse.BoolNode: - return reflect.ValueOf(n.True), true - - case *parse.NumberNode: - // This case branch is lifted from Go's text/template execution engine: - // https://sourcegraph.com/github.com/golang/go@2c9f5a1da823773c436f8b2c119635797d6db2d3/-/blob/src/text/template/exec.go#L493-530 - // The difference is that we don't do any error handling but simply abort. - switch { - case n.IsComplex: - return reflect.ValueOf(n.Complex128), true - - case n.IsFloat && - !isHexInt(n.Text) && !isRuneInt(n.Text) && - strings.ContainsAny(n.Text, ".eEpP"): - return reflect.ValueOf(n.Float64), true - - case n.IsInt: - num := int(n.Int64) - if int64(num) != n.Int64 { - return noValue, false - } - return reflect.ValueOf(num), true - - case n.IsUint: - return noValue, false - } - - case *parse.StringNode: - return reflect.ValueOf(n.Text), true - - case *parse.ChainNode: - // For now we only support fields that are 1 level deep (see below). - // Should we ever want to support more than one level, we need to - // revise this. - if len(n.Field) != 1 { - return noValue, false - } - - if ident, ok := n.Node.(*parse.IdentifierNode); ok { - switch ident.Ident { - case "repository": - switch n.Field[0] { - case "search_result_paths": - // TODO: We don't eval search_result_paths for now, since it's a - // "complex" value, a slice of strings, and turning that - // into text might not be useful to the user. So we abort. - return noValue, false - case "name": - return reflect.ValueOf(ctx.Repository.Name), true - } - - case "batch_change": - switch n.Field[0] { - case "name": - return reflect.ValueOf(ctx.BatchChange.Name), true - case "description": - return reflect.ValueOf(ctx.BatchChange.Description), true - } - } - } - return noValue, false - - case *parse.PipeNode: - return evalPipe(ctx, n) - } - - return noValue, false -} - -func isRuneInt(s string) bool { - return len(s) > 0 && s[0] == '\'' -} - -func isHexInt(s string) bool { - return len(s) > 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X') && !strings.ContainsAny(s, "pP") -} - -func evalFunction(ctx *StepContext, fn *parse.IdentifierNode, name string, args []parse.Node, previousValue reflect.Value) (val reflect.Value, success bool) { - defer func() { - if r := recover(); r != nil { - val = noValue - success = false - } - }() - - switch name { - case "eq": - return evalEqCall(ctx, args[1:]) - - case "ne": - equal, ok := evalEqCall(ctx, args[1:]) - if !ok { - return noValue, false - } - return reflect.ValueOf(!equal.Bool()), true - - case "not": - return evalNotCall(ctx, args[1:]) - - default: - concreteFn, ok := builtins[name] - if !ok { - return noValue, false - } - - fn := reflect.ValueOf(concreteFn) - - // We can eval only if all args are static: - var evaluatedArgs []reflect.Value - for _, a := range args[1:] { - v, ok := evalNode(ctx, a) - if !ok { - // One of the args is not static, abort - return noValue, false - } - evaluatedArgs = append(evaluatedArgs, v) - - } - - ret := fn.Call(evaluatedArgs) - if len(ret) == 2 && !ret[1].IsNil() { - return noValue, false - } - return ret[0], true - } -} - -func evalNotCall(ctx *StepContext, args []parse.Node) (reflect.Value, bool) { - // We only support 1 arg for now: - if len(args) != 1 { - return noValue, false - } - - arg, ok := evalNode(ctx, args[0]) - if !ok { - return noValue, false - } - - return reflect.ValueOf(!isTrue(arg)), true -} - -func evalEqCall(ctx *StepContext, args []parse.Node) (reflect.Value, bool) { - // We only support 2 args for now: - if len(args) != 2 { - return noValue, false - } - - // We only eval `eq` if all args are static: - var evaluatedArgs []reflect.Value - for _, a := range args { - v, ok := evalNode(ctx, a) - if !ok { - // One of the args is not static, abort - return noValue, false - } - evaluatedArgs = append(evaluatedArgs, v) - } - - if len(evaluatedArgs) != 2 { - // safety check - return noValue, false - } - - isEqual := evaluatedArgs[0].Interface() == evaluatedArgs[1].Interface() - return reflect.ValueOf(isEqual), true -} - -// isTrue is taken from Go's text/template/exec.go and simplified -func isTrue(val reflect.Value) (truth bool) { - if !val.IsValid() { - // Something like var x interface{}, never set. It's a form of nil. - return false - } - switch val.Kind() { - case reflect.Array, reflect.Map, reflect.Slice, reflect.String: - return val.Len() > 0 - case reflect.Bool: - return val.Bool() - case reflect.Complex64, reflect.Complex128: - return val.Complex() != 0 - case reflect.Chan, reflect.Func, reflect.Ptr, reflect.Interface: - return !val.IsNil() - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return val.Int() != 0 - case reflect.Float32, reflect.Float64: - return val.Float() != 0 - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return val.Uint() != 0 - case reflect.Struct: - return true // Struct values are always true. - default: - return false - } -} - -// debugParseNode can be used to produce a debug-friendly version of a parse.Node. -func debugParseNode(n parse.Node) string { - switch n := n.(type) { - case *parse.ActionNode: - return fmt.Sprintf("parse.ActionNode. n.Pipe=%#v", n.Pipe) - - case *parse.IdentifierNode: - return fmt.Sprintf("parse.IdentifierNode: %+v", n) - - case *parse.FieldNode: - return fmt.Sprintf("parse.FieldNode: %+v", n) - - case *parse.ChainNode: - return fmt.Sprintf("parse.ChainNode. n.Node=(%s), chain.Field: %+v", debugParseNode(n.Node), n.Field) - - case *parse.TextNode: - return fmt.Sprintf("parse.TextNode. n.Text=%q", n.Text) - - case *parse.BoolNode: - return fmt.Sprintf("parse.BoolNode") - - case *parse.CommandNode: - return fmt.Sprintf("parse.CommandNode") - - case *parse.NilNode: - return fmt.Sprintf("parse.NilNode") - - case *parse.NumberNode: - return fmt.Sprintf("parse.NumberNode") - - case *parse.PipeNode: - return fmt.Sprintf("parse.PipeNode") - - default: - return fmt.Sprintf("UNHANDLED parse.Node TYPE: %s", n.String()) - } -} diff --git a/internal/batches/template/partial_eval_test.go b/internal/batches/template/partial_eval_test.go deleted file mode 100644 index 403d7ed4b7..0000000000 --- a/internal/batches/template/partial_eval_test.go +++ /dev/null @@ -1,294 +0,0 @@ -package template - -import ( - "testing" - - "github.com/google/go-cmp/cmp" -) - -var partialEvalStepCtx = &StepContext{ - BatchChange: BatchChangeAttributes{ - Name: "test-batch-change", - Description: "test-description", - }, - // Step is not set when evalStepCondition is called - Repository: TemplatingRepository{ - Name: "github.com/sourcegraph/src-cli", - FileMatches: map[string]bool{ - "README.md": true, - "main.go": true, - }, - }, -} - -func runParseAndPartialTest(t *testing.T, in, want string) { - t.Helper() - - tmpl, err := parseAndPartialEval(in, partialEvalStepCtx) - if err != nil { - t.Fatal(err) - } - - tmplStr := tmpl.Tree.Root.String() - if tmplStr != want { - t.Fatalf("wrong output:\n%s", cmp.Diff(want, tmplStr)) - } -} - -func TestParseAndPartialEval(t *testing.T) { - t.Run("evaluated", func(t *testing.T) { - for _, tt := range []struct{ input, want string }{ - { - // Literal constants: - `this is my template ${{ "hardcoded string" }}`, - `this is my template hardcoded string`, - }, - { - `${{ 1234 }}`, - `1234`, - }, - { - `${{ true }} ${{ false }}`, - `true false`, - }, - { - // Evaluated, since they're static values: - `${{ repository.name }} ${{ batch_change.name }} ${{ batch_change.description }}`, - `github.com/sourcegraph/src-cli test-batch-change test-description`, - }, - { - `AAA${{ repository.name }}BBB${{ batch_change.name }}CCC${{ batch_change.description }}DDD`, - `AAAgithub.com/sourcegraph/src-cliBBBtest-batch-changeCCCtest-descriptionDDD`, - }, - { - // Function call with static value and runtime value: - `${{ eq repository.name outputs.repo.name }}`, - // Aborts, since one of them is runtime value - `{{eq repository.name outputs.repo.name}}`, - }, - { - // "eq" call with 2 static values: - `${{ eq repository.name "github.com/sourcegraph/src-cli" }}`, - `true`, - }, - { - // "eq" call with 2 literal values: - `${{ eq 5 5 }}`, - `true`, - }, - { - // "not" call: - `${{ not (eq repository.name "bitbucket-repo") }}`, - `true`, - }, - { - // "not" call: - `${{ not 1234 }} ${{ not false }} ${{ not true }}`, - `false true false`, - }, - { - // "ne" call with 2 static values: - `${{ ne repository.name "github.com/sourcegraph/src-cli" }}`, - `false`, - }, - { - // "ne" call with 2 literal values: - `${{ ne 5 5 }}`, - `false`, - }, - { - // Function call with builtin function and static values: - `${{ matches repository.name "github.com*" }}`, - `true`, - }, - { - // Nested function call with builtin function and static values: - `${{ eq false (matches repository.name "github.com*") }}`, - `false`, - }, - { - // Nested nested function call with builtin function and static values: - `${{ eq false (eq false (matches repository.name "github.com*")) }}`, - `true`, - }, - } { - runParseAndPartialTest(t, tt.input, tt.want) - } - }) - - t.Run("aborted", func(t *testing.T) { - for _, tt := range []struct{ input, want string }{ - { - // Field that doesn't exist - `${{ repository.secretlocation }}`, - `{{repository.secretlocation}}`, - }, - { - // Field access that's too deep - `${{ repository.name.doesnotexist }}`, - `{{repository.name.doesnotexist}}`, - }, - { - // Complex value - `${{ repository.search_result_paths }}`, - // String representation of templates uses standard delimiters - `{{repository.search_result_paths}}`, - }, - { - // Runtime value - `${{ outputs.runtime.value }}`, - `{{outputs.runtime.value}}`, - }, - { - // Runtime value - `${{ step.modified_files }}`, - `{{step.modified_files}}`, - }, - { - // Runtime value - `${{ previous_step.modified_files }}`, - `{{previous_step.modified_files}}`, - }, - { - // "eq" call with static value and runtime value: - `${{ eq repository.name outputs.repo.name }}`, - // Aborts, since one of them is runtime value - `{{eq repository.name outputs.repo.name}}`, - }, - { - // "eq" call with more than 2 arguments: - `${{ eq repository.name "github.com/sourcegraph/src-cli" "github.com/sourcegraph/sourcegraph" }}`, - `{{eq repository.name "github.com/sourcegraph/src-cli" "github.com/sourcegraph/sourcegraph"}}`, - }, - { - // Nested nested function call with builtin function but runtime values: - `${{ eq false (eq false (matches outputs.runtime.value "github.com*")) }}`, - `{{eq false (eq false (matches outputs.runtime.value "github.com*"))}}`, - }, - } { - runParseAndPartialTest(t, tt.input, tt.want) - } - }) -} - -func TestParseAndPartialEval_BuiltinFunctions(t *testing.T) { - t.Run("success", func(t *testing.T) { - for _, tt := range []struct{ input, want string }{ - { - `${{ join (split repository.name "/") "-" }}`, - `github.com-sourcegraph-src-cli`, - }, - { - `${{ split repository.name "/" "-" }}`, - `{{split repository.name "/" "-"}}`, - }, - { - `${{ replace repository.name "github" "foobar" }}`, - `foobar.com/sourcegraph/src-cli`, - }, - { - `${{ join_if "SEP" repository.name "postfix" }}`, - `github.com/sourcegraph/src-cliSEPpostfix`, - }, - { - `${{ matches repository.name "github.com*" }}`, - `true`, - }, - } { - runParseAndPartialTest(t, tt.input, tt.want) - } - }) - - t.Run("aborted", func(t *testing.T) { - for _, tt := range []struct{ input, want string }{ - { - // Wrong argument type - `${{ join "foobar" "-" }}`, - `{{join "foobar" "-"}}`, - }, - { - // Wrong argument count - `${{ join (split repository.name "/") "-" "too" "many" "args" }}`, - `{{join (split repository.name "/") "-" "too" "many" "args"}}`, - }, - } { - runParseAndPartialTest(t, tt.input, tt.want) - } - }) -} - -func TestIsStaticBool(t *testing.T) { - tests := []struct { - name string - template string - wantIsStatic bool - wantBoolVal bool - }{ - - { - name: "true literal", - template: `true`, - wantIsStatic: true, - wantBoolVal: true, - }, - { - name: "false literal", - template: `false`, - wantIsStatic: true, - wantBoolVal: false, - }, - { - name: "static non bool value", - template: `${{ repository.name }}`, - wantIsStatic: true, - wantBoolVal: false, - }, - { - name: "function call true val", - template: `${{ eq repository.name "github.com/sourcegraph/src-cli" }}`, - wantIsStatic: true, - wantBoolVal: true, - }, - { - name: "function call false val", - template: `${{ eq repository.name "hans wurst" }}`, - wantIsStatic: true, - wantBoolVal: false, - }, - { - name: "nested function call and whitespace", - template: ` ${{ eq false (eq false (matches repository.name "github.com*")) }} `, - wantIsStatic: true, - wantBoolVal: true, - }, - { - name: "nested function call with runtime value", - template: `${{ eq false (eq false (matches outputs.repo.name "github.com*")) }}`, - wantIsStatic: false, - wantBoolVal: false, - }, - { - name: "random string", - template: `adfadsfasdfadsfasdfasdfadsf`, - wantIsStatic: true, - wantBoolVal: false, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - - isStatic, boolVal, err := IsStaticBool(tt.template, partialEvalStepCtx) - if err != nil { - t.Fatal(err) - } - - if isStatic != tt.wantIsStatic { - t.Fatalf("wrong isStatic value. want=%t, got=%t", tt.wantIsStatic, isStatic) - } - if boolVal != tt.wantBoolVal { - t.Fatalf("wrong boolVal value. want=%t, got=%t", tt.wantBoolVal, boolVal) - } - }) - } -} diff --git a/internal/batches/template/templating.go b/internal/batches/template/templating.go deleted file mode 100644 index 2fc5aea408..0000000000 --- a/internal/batches/template/templating.go +++ /dev/null @@ -1,311 +0,0 @@ -package template - -import ( - "bytes" - "io" - "sort" - "strings" - "text/template" - - "github.com/gobwas/glob" - "github.com/pkg/errors" - "github.com/sourcegraph/sourcegraph/lib/batches/git" -) - -const startDelim = "${{" -const endDelim = "}}" - -var builtins = template.FuncMap{ - "join": strings.Join, - "split": strings.Split, - "replace": strings.ReplaceAll, - "join_if": func(sep string, elems ...string) string { - var nonBlank []string - for _, e := range elems { - if e != "" { - nonBlank = append(nonBlank, e) - } - } - return strings.Join(nonBlank, sep) - }, - "matches": func(in, pattern string) (bool, error) { - g, err := glob.Compile(pattern) - if err != nil { - return false, err - } - return g.Match(in), nil - }, -} - -func isTrueOutput(output interface{ String() string }) bool { - return strings.TrimSpace(output.String()) == "true" -} - -func EvalStepCondition(condition string, stepCtx *StepContext) (bool, error) { - if condition == "" { - return true, nil - } - - var out bytes.Buffer - if err := RenderStepTemplate("step-condition", condition, &out, stepCtx); err != nil { - return false, errors.Wrap(err, "parsing step if") - } - - return isTrueOutput(&out), nil -} - -func RenderStepTemplate(name, tmpl string, out io.Writer, stepCtx *StepContext) error { - t, err := template.New(name).Delims(startDelim, endDelim).Funcs(builtins).Funcs(stepCtx.ToFuncMap()).Parse(tmpl) - if err != nil { - return errors.Wrap(err, "parsing step run") - } - - return t.Execute(out, stepCtx) -} - -func RenderStepMap(m map[string]string, stepCtx *StepContext) (map[string]string, error) { - rendered := make(map[string]string, len(m)) - - for k, v := range m { - var out bytes.Buffer - - if err := RenderStepTemplate(k, v, &out, stepCtx); err != nil { - return rendered, err - } - - rendered[k] = out.String() - } - - return rendered, nil -} - -// TODO(mrnugget): This is bad and should be (a) removed or (b) moved to batches package -type BatchChangeAttributes struct { - Name string - Description string -} - -type TemplatingBranch struct { - Name string - TargetOID string -} - -type TemplatingRepository struct { - ID string - Name string - DefaultBranch TemplatingBranch - FileMatches map[string]bool -} - -func (r TemplatingRepository) SearchResultPaths() (list fileMatchPathList) { - var files []string - for f := range r.FileMatches { - files = append(files, f) - } - sort.Strings(files) - return fileMatchPathList(files) -} - -type fileMatchPathList []string - -func (f fileMatchPathList) String() string { return strings.Join(f, " ") } - -// StepContext represents the contextual information available when rendering a -// step's fields, such as "run" or "outputs", as templates. -type StepContext struct { - // BatchChange are the attributes in the BatchSpec that are set on the BatchChange. - BatchChange BatchChangeAttributes - // Outputs are the outputs set by the current and all previous steps. - Outputs map[string]interface{} - // Step is the result of the current step. Empty when evaluating the "run" field - // but filled when evaluating the "outputs" field. - Step StepResult - // Steps contains the path in which the steps are being executed and the - // changes made by all steps that were executed up until the current step. - Steps StepsContext - // PreviousStep is the result of the previous step. Empty when there is no - // previous step. - PreviousStep StepResult - // Repository is the Sourcegraph repository in which the steps are executed. - Repository TemplatingRepository -} - -// ToFuncMap returns a template.FuncMap to access fields on the StepContext in a -// text/template. -func (stepCtx *StepContext) ToFuncMap() template.FuncMap { - newStepResult := func(res *StepResult) map[string]interface{} { - m := map[string]interface{}{ - "modified_files": "", - "added_files": "", - "deleted_files": "", - "renamed_files": "", - "stdout": "", - "stderr": "", - } - if res == nil { - return m - } - - m["modified_files"] = res.ModifiedFiles() - m["added_files"] = res.AddedFiles() - m["deleted_files"] = res.DeletedFiles() - m["renamed_files"] = res.RenamedFiles() - - if res.Stdout != nil { - m["stdout"] = res.Stdout.String() - } - - if res.Stderr != nil { - m["stderr"] = res.Stderr.String() - } - - return m - } - - return template.FuncMap{ - "previous_step": func() map[string]interface{} { - return newStepResult(&stepCtx.PreviousStep) - }, - "step": func() map[string]interface{} { - return newStepResult(&stepCtx.Step) - }, - "steps": func() map[string]interface{} { - res := newStepResult(&StepResult{Files: stepCtx.Steps.Changes}) - res["path"] = stepCtx.Steps.Path - return res - }, - "outputs": func() map[string]interface{} { - return stepCtx.Outputs - }, - "repository": func() map[string]interface{} { - return map[string]interface{}{ - "search_result_paths": stepCtx.Repository.SearchResultPaths(), - "name": stepCtx.Repository.Name, - } - }, - "batch_change": func() map[string]interface{} { - return map[string]interface{}{ - "name": stepCtx.BatchChange.Name, - "description": stepCtx.BatchChange.Description, - } - }, - } -} - -// StepResult represents the result of a previously executed step. -type StepResult struct { - // Files are the changes made to Files by the step. - Files *git.Changes - - // Stdout is the output produced by the step on standard out. - Stdout *bytes.Buffer - // Stderr is the output produced by the step on standard error. - Stderr *bytes.Buffer -} - -// ModifiedFiles returns the files modified by a step. -func (r StepResult) ModifiedFiles() []string { - if r.Files != nil { - return r.Files.Modified - } - return []string{} -} - -// AddedFiles returns the files added by a step. -func (r StepResult) AddedFiles() []string { - if r.Files != nil { - return r.Files.Added - } - return []string{} -} - -// DeletedFiles returns the files deleted by a step. -func (r StepResult) DeletedFiles() []string { - if r.Files != nil { - return r.Files.Deleted - } - return []string{} -} - -// RenamedFiles returns the new name of files that have been renamed by a step. -func (r StepResult) RenamedFiles() []string { - if r.Files != nil { - return r.Files.Renamed - } - return []string{} -} - -type StepsContext struct { - // Changes that have been made by executing all steps. - Changes *git.Changes - // Path is the relative-to-root directory in which the steps have been - // executed. Default is "". No leading "/". - Path string -} - -// ChangesetTemplateContext represents the contextual information available -// when rendering a field of the ChangesetTemplate as a template. -type ChangesetTemplateContext struct { - // BatchChangeAttributes are the attributes of the BatchChange that will be - // created/updated. - BatchChangeAttributes BatchChangeAttributes - - // Steps are the changes made by all steps that were executed. - Steps StepsContext - - // Outputs are the outputs defined and initialized by the steps. - Outputs map[string]interface{} - - // Repository is the repository in which the steps were executed. - Repository TemplatingRepository -} - -// ToFuncMap returns a template.FuncMap to access fields on the StepContext in a -// text/template. -func (tmplCtx *ChangesetTemplateContext) ToFuncMap() template.FuncMap { - return template.FuncMap{ - "repository": func() map[string]interface{} { - return map[string]interface{}{ - "search_result_paths": tmplCtx.Repository.SearchResultPaths(), - "name": tmplCtx.Repository.Name, - } - }, - "batch_change": func() map[string]interface{} { - return map[string]interface{}{ - "name": tmplCtx.BatchChangeAttributes.Name, - "description": tmplCtx.BatchChangeAttributes.Description, - } - }, - "outputs": func() map[string]interface{} { - return tmplCtx.Outputs - }, - "steps": func() map[string]interface{} { - // Wrap the *StepChanges in a StepResult so we can use nil-safe - // methods. - res := StepResult{Files: tmplCtx.Steps.Changes} - - return map[string]interface{}{ - "modified_files": res.ModifiedFiles(), - "added_files": res.AddedFiles(), - "deleted_files": res.DeletedFiles(), - "renamed_files": res.RenamedFiles(), - "path": tmplCtx.Steps.Path, - } - }, - } -} - -func RenderChangesetTemplateField(name, tmpl string, tmplCtx *ChangesetTemplateContext) (string, error) { - var out bytes.Buffer - - t, err := template.New(name).Delims(startDelim, endDelim).Funcs(builtins).Funcs(tmplCtx.ToFuncMap()).Parse(tmpl) - if err != nil { - return "", err - } - - if err := t.Execute(&out, tmplCtx); err != nil { - return "", err - } - - return strings.TrimSpace(out.String()), nil -} diff --git a/internal/batches/template/templating_test.go b/internal/batches/template/templating_test.go deleted file mode 100644 index b6990f9fc4..0000000000 --- a/internal/batches/template/templating_test.go +++ /dev/null @@ -1,361 +0,0 @@ -package template - -import ( - "bytes" - "testing" - - "github.com/google/go-cmp/cmp" - "github.com/sourcegraph/sourcegraph/lib/batches/git" - "gopkg.in/yaml.v3" -) - -var testChanges = &git.Changes{ - Modified: []string{"go.mod"}, - Added: []string{"main.go.swp"}, - Deleted: []string{".DS_Store"}, - Renamed: []string{"new-filename.txt"}, -} - -func TestEvalStepCondition(t *testing.T) { - stepCtx := &StepContext{ - BatchChange: BatchChangeAttributes{ - Name: "test-batch-change", - Description: "This batch change is just an experiment", - }, - PreviousStep: StepResult{ - Files: testChanges, - Stdout: bytes.NewBufferString("this is previous step's stdout"), - Stderr: bytes.NewBufferString("this is previous step's stderr"), - }, - Steps: StepsContext{ - Changes: testChanges, - Path: "sub/directory/of/repo", - }, - Outputs: map[string]interface{}{}, - // Step is not set when evalStepCondition is called - Repository: *testRepo1, - } - - tests := []struct { - run string - want bool - }{ - {run: `true`, want: true}, - {run: ` true `, want: true}, - {run: `TRUE`, want: false}, - {run: `false`, want: false}, - {run: `FALSE`, want: false}, - {run: `${{ eq repository.name "github.com/sourcegraph/src-cli" }}`, want: true}, - {run: `${{ eq steps.path "sub/directory/of/repo" }}`, want: true}, - {run: `${{ matches repository.name "github.com/sourcegraph/*" }}`, want: true}, - } - - for _, tc := range tests { - got, err := EvalStepCondition(tc.run, stepCtx) - if err != nil { - t.Fatal(err) - } - - if got != tc.want { - t.Fatalf("wrong value. want=%t, got=%t", tc.want, got) - } - } -} - -const rawYaml = `dist: release -env: - - GO111MODULE=on - - CGO_ENABLED=0 -before: - hooks: - - go mod download - - go mod tidy - - go generate ./schema -` - -func TestRenderStepTemplate(t *testing.T) { - // To avoid bugs due to differences between test setup and actual code, we - // do the actual parsing of YAML here to get an interface{} which we'll put - // in the StepContext. - var parsedYaml interface{} - if err := yaml.Unmarshal([]byte(rawYaml), &parsedYaml); err != nil { - t.Fatalf("failed to parse YAML: %s", err) - } - - stepCtx := &StepContext{ - BatchChange: BatchChangeAttributes{ - Name: "test-batch-change", - Description: "This batch change is just an experiment", - }, - PreviousStep: StepResult{ - Files: testChanges, - Stdout: bytes.NewBufferString("this is previous step's stdout"), - Stderr: bytes.NewBufferString("this is previous step's stderr"), - }, - Outputs: map[string]interface{}{ - "lastLine": "lastLine is this", - "project": parsedYaml, - }, - Step: StepResult{ - Files: testChanges, - Stdout: bytes.NewBufferString("this is current step's stdout"), - Stderr: bytes.NewBufferString("this is current step's stderr"), - }, - Steps: StepsContext{Changes: testChanges, Path: "sub/directory/of/repo"}, - Repository: *testRepo1, - } - - tests := []struct { - name string - stepCtx *StepContext - run string - want string - }{ - { - name: "lower-case aliases", - stepCtx: stepCtx, - run: `${{ repository.search_result_paths }} -${{ repository.name }} -${{ batch_change.name }} -${{ batch_change.description }} -${{ previous_step.modified_files }} -${{ previous_step.added_files }} -${{ previous_step.deleted_files }} -${{ previous_step.renamed_files }} -${{ previous_step.stdout }} -${{ previous_step.stderr}} -${{ outputs.lastLine }} -${{ index outputs.project.env 1 }} -${{ step.modified_files }} -${{ step.added_files }} -${{ step.deleted_files }} -${{ step.renamed_files }} -${{ step.stdout}} -${{ step.stderr}} -${{ steps.modified_files }} -${{ steps.added_files }} -${{ steps.deleted_files }} -${{ steps.renamed_files }} -${{ steps.path }} -`, - want: `README.md main.go -github.com/sourcegraph/src-cli -test-batch-change -This batch change is just an experiment -[go.mod] -[main.go.swp] -[.DS_Store] -[new-filename.txt] -this is previous step's stdout -this is previous step's stderr -lastLine is this -CGO_ENABLED=0 -[go.mod] -[main.go.swp] -[.DS_Store] -[new-filename.txt] -this is current step's stdout -this is current step's stderr -[go.mod] -[main.go.swp] -[.DS_Store] -[new-filename.txt] -sub/directory/of/repo -`, - }, - { - name: "empty context", - stepCtx: &StepContext{}, - run: `${{ repository.search_result_paths }} -${{ repository.name }} -${{ previous_step.modified_files }} -${{ previous_step.added_files }} -${{ previous_step.deleted_files }} -${{ previous_step.renamed_files }} -${{ previous_step.stdout }} -${{ previous_step.stderr}} -${{ outputs.lastLine }} -${{ outputs.project }} -${{ step.modified_files }} -${{ step.added_files }} -${{ step.deleted_files }} -${{ step.renamed_files }} -${{ step.stdout}} -${{ step.stderr}} -${{ steps.modified_files }} -${{ steps.added_files }} -${{ steps.deleted_files }} -${{ steps.renamed_files }} -${{ steps.path }} -`, - want: ` - -[] -[] -[] -[] - - - - -[] -[] -[] -[] - - -[] -[] -[] -[] - -`, - }, - } - - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - var out bytes.Buffer - - err := RenderStepTemplate("testing", tc.run, &out, tc.stepCtx) - if err != nil { - t.Fatal(err) - } - - if out.String() != tc.want { - t.Fatalf("wrong output:\n%s", cmp.Diff(tc.want, out.String())) - } - }) - } -} - -func TestRenderStepMap(t *testing.T) { - stepCtx := &StepContext{ - PreviousStep: StepResult{ - Files: testChanges, - Stdout: bytes.NewBufferString("this is previous step's stdout"), - Stderr: bytes.NewBufferString("this is previous step's stderr"), - }, - Outputs: map[string]interface{}{}, - Repository: *testRepo1, - } - - input := map[string]string{ - "/tmp/my-file.txt": `${{ previous_step.modified_files }}`, - "/tmp/my-other-file.txt": `${{ previous_step.added_files }}`, - "/tmp/my-other-file2.txt": `${{ previous_step.deleted_files }}`, - } - - have, err := RenderStepMap(input, stepCtx) - if err != nil { - t.Fatalf("unexpected error: %s", err) - } - - want := map[string]string{ - "/tmp/my-file.txt": "[go.mod]", - "/tmp/my-other-file.txt": "[main.go.swp]", - "/tmp/my-other-file2.txt": "[.DS_Store]", - } - - if diff := cmp.Diff(want, have); diff != "" { - t.Fatalf("wrong output:\n%s", diff) - } -} - -func TestRenderChangesetTemplateField(t *testing.T) { - // To avoid bugs due to differences between test setup and actual code, we - // do the actual parsing of YAML here to get an interface{} which we'll put - // in the StepContext. - var parsedYaml interface{} - if err := yaml.Unmarshal([]byte(rawYaml), &parsedYaml); err != nil { - t.Fatalf("failed to parse YAML: %s", err) - } - - tmplCtx := &ChangesetTemplateContext{ - BatchChangeAttributes: BatchChangeAttributes{ - Name: "test-batch-change", - Description: "This batch change is just an experiment", - }, - Outputs: map[string]interface{}{ - "lastLine": "lastLine is this", - "project": parsedYaml, - }, - Repository: *testRepo1, - Steps: StepsContext{ - Changes: &git.Changes{ - Modified: []string{"modified-file.txt"}, - Added: []string{"added-file.txt"}, - Deleted: []string{"deleted-file.txt"}, - Renamed: []string{"renamed-file.txt"}, - }, - Path: "infrastructure/sub-project", - }, - } - - tests := []struct { - name string - tmplCtx *ChangesetTemplateContext - tmpl string - want string - }{ - { - name: "lower-case aliases", - tmplCtx: tmplCtx, - tmpl: `${{ repository.search_result_paths }} -${{ repository.name }} -${{ batch_change.name }} -${{ batch_change.description }} -${{ outputs.lastLine }} -${{ index outputs.project.env 1 }} -${{ steps.modified_files }} -${{ steps.added_files }} -${{ steps.deleted_files }} -${{ steps.renamed_files }} -${{ steps.path }} -`, - want: `README.md main.go -github.com/sourcegraph/src-cli -test-batch-change -This batch change is just an experiment -lastLine is this -CGO_ENABLED=0 -[modified-file.txt] -[added-file.txt] -[deleted-file.txt] -[renamed-file.txt] -infrastructure/sub-project`, - }, - { - name: "empty context", - tmplCtx: &ChangesetTemplateContext{}, - tmpl: `${{ repository.search_result_paths }} -${{ repository.name }} -${{ outputs.lastLine }} -${{ outputs.project }} -${{ steps.modified_files }} -${{ steps.added_files }} -${{ steps.deleted_files }} -${{ steps.renamed_files }} -`, - want: ` - -[] -[] -[] -[]`, - }, - } - - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - out, err := RenderChangesetTemplateField("testing", tc.tmpl, tc.tmplCtx) - if err != nil { - t.Fatal(err) - } - - if out != tc.want { - t.Fatalf("wrong output:\n%s", cmp.Diff(tc.want, out)) - } - }) - } -} diff --git a/internal/batches/util/repo.go b/internal/batches/util/repo.go index eaea63cfdc..ccab38fc80 100644 --- a/internal/batches/util/repo.go +++ b/internal/batches/util/repo.go @@ -1,8 +1,8 @@ package util import ( + "github.com/sourcegraph/sourcegraph/lib/batches/template" "github.com/sourcegraph/src-cli/internal/batches/graphql" - "github.com/sourcegraph/src-cli/internal/batches/template" ) // GraphQLRepoToTemplatingRepo transforms a given *graphql.Repository into a From aba30b153f2c6d3e13ce36fb18d879b53370f202 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Wed, 1 Sep 2021 16:57:13 +0200 Subject: [PATCH 020/647] Make steps resolution part of workspaces detection (#595) --- internal/batches/service/build_tasks.go | 45 +---- internal/batches/service/build_tasks_test.go | 138 --------------- internal/batches/service/workspaces.go | 69 ++++++++ internal/batches/service/workspaces_test.go | 173 +++++++++++++++---- 4 files changed, 219 insertions(+), 206 deletions(-) delete mode 100644 internal/batches/service/build_tasks_test.go diff --git a/internal/batches/service/build_tasks.go b/internal/batches/service/build_tasks.go index 61e6fcecac..832a7b6391 100644 --- a/internal/batches/service/build_tasks.go +++ b/internal/batches/service/build_tasks.go @@ -8,7 +8,6 @@ import ( "github.com/sourcegraph/sourcegraph/lib/batches/template" "github.com/sourcegraph/src-cli/internal/batches/executor" "github.com/sourcegraph/src-cli/internal/batches/graphql" - "github.com/sourcegraph/src-cli/internal/batches/util" ) // buildTasks returns tasks for all the workspaces determined for the given spec. @@ -24,56 +23,24 @@ func buildTasks(ctx context.Context, spec *batcheslib.BatchSpec, repos []*graphq if !ok { return nil, errors.New("invalid state, didn't find repo for workspace definition") } - t, ok, err := buildTask(spec, repo, ws.Path, ws.OnlyFetchWorkspace) + + t, err := buildTask(spec, repo, ws.Path, ws.OnlyFetchWorkspace, ws.Steps) if err != nil { return nil, err } - if ok { - tasks = append(tasks, t) - } + tasks = append(tasks, t) } return tasks, nil } -func buildTask(spec *batcheslib.BatchSpec, r *graphql.Repository, path string, onlyWorkspace bool) (*executor.Task, bool, error) { +func buildTask(spec *batcheslib.BatchSpec, r *graphql.Repository, path string, onlyWorkspace bool, steps []batcheslib.Step) (*executor.Task, error) { batchChange := template.BatchChangeAttributes{ Name: spec.Name, Description: spec.Description, } - taskSteps := []batcheslib.Step{} - for _, step := range spec.Steps { - // If no if condition is given, just go ahead and add the step to the list. - if step.IfCondition() == "" { - taskSteps = append(taskSteps, step) - continue - } - - stepCtx := &template.StepContext{ - Repository: util.GraphQLRepoToTemplatingRepo(r), - BatchChange: batchChange, - } - static, boolVal, err := template.IsStaticBool(step.IfCondition(), stepCtx) - if err != nil { - return nil, false, err - } - - // If we could evaluate the condition statically and the resulting - // boolean is false, we don't add that step. - if !static { - taskSteps = append(taskSteps, step) - } else if boolVal { - taskSteps = append(taskSteps, step) - } - } - - // If the task doesn't have any steps we don't need to execute it - if len(taskSteps) == 0 { - return nil, false, nil - } - // "." means the path is root, but in the executor we use "" to signify root if path == "." { path = "" @@ -82,11 +49,11 @@ func buildTask(spec *batcheslib.BatchSpec, r *graphql.Repository, path string, o return &executor.Task{ Repository: r, Path: path, - Steps: taskSteps, + Steps: steps, OnlyFetchWorkspace: onlyWorkspace, TransformChanges: spec.TransformChanges, Template: spec.ChangesetTemplate, BatchChangeAttributes: &batchChange, - }, true, nil + }, nil } diff --git a/internal/batches/service/build_tasks_test.go b/internal/batches/service/build_tasks_test.go deleted file mode 100644 index 73c3c8fe5e..0000000000 --- a/internal/batches/service/build_tasks_test.go +++ /dev/null @@ -1,138 +0,0 @@ -package service - -import ( - "testing" - - "github.com/google/go-cmp/cmp" - "github.com/google/go-cmp/cmp/cmpopts" - batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" -) - -func TestBuildTask_IfConditions(t *testing.T) { - tests := map[string]struct { - spec *batcheslib.BatchSpec - - wantSteps []batcheslib.Step - }{ - "no if": { - spec: &batcheslib.BatchSpec{ - Steps: []batcheslib.Step{ - {Run: "echo 1"}, - }, - }, - wantSteps: []batcheslib.Step{ - {Run: "echo 1"}, - }, - }, - - "if has static true value": { - spec: &batcheslib.BatchSpec{ - Steps: []batcheslib.Step{ - {Run: "echo 1", If: "true"}, - }, - }, - wantSteps: []batcheslib.Step{ - {Run: "echo 1", If: "true"}, - }, - }, - - "one of many steps has if with static true value": { - spec: &batcheslib.BatchSpec{ - Steps: []batcheslib.Step{ - {Run: "echo 1"}, - {Run: "echo 2", If: "true"}, - {Run: "echo 3"}, - }, - }, - wantSteps: []batcheslib.Step{ - {Run: "echo 1"}, - {Run: "echo 2", If: "true"}, - {Run: "echo 3"}, - }, - }, - - "if has static non-true value": { - spec: &batcheslib.BatchSpec{ - Steps: []batcheslib.Step{ - {Run: "echo 1", If: "this is not true"}, - }, - }, - wantSteps: nil, - }, - - "one of many steps has if with static non-true value": { - spec: &batcheslib.BatchSpec{ - Steps: []batcheslib.Step{ - {Run: "echo 1"}, - {Run: "echo 2", If: "every type system needs generics"}, - {Run: "echo 3"}, - }, - }, - wantSteps: []batcheslib.Step{ - {Run: "echo 1"}, - {Run: "echo 3"}, - }, - }, - - "if expression that can be partially evaluated to true": { - spec: &batcheslib.BatchSpec{ - Steps: []batcheslib.Step{ - {Run: "echo 1", If: `${{ matches repository.name "github.com/sourcegraph/src*" }}`}, - }, - }, - wantSteps: []batcheslib.Step{ - {Run: "echo 1", If: `${{ matches repository.name "github.com/sourcegraph/src*" }}`}, - }, - }, - - "if expression that can be partially evaluated to false": { - spec: &batcheslib.BatchSpec{ - Steps: []batcheslib.Step{ - {Run: "echo 1", If: `${{ matches repository.name "horse" }}`}, - }, - }, - wantSteps: nil, - }, - - "one of many steps has if expression that can be evaluated to true": { - spec: &batcheslib.BatchSpec{ - Steps: []batcheslib.Step{ - {Run: "echo 1", If: `${{ matches repository.name "horse" }}`}, - }, - }, - wantSteps: nil, - }, - - "if expression that can NOT be partially evaluated": { - spec: &batcheslib.BatchSpec{ - Steps: []batcheslib.Step{ - {Run: "echo 1", If: `${{ eq outputs.value "foobar" }}`}, - }, - }, - wantSteps: []batcheslib.Step{ - {Run: "echo 1", If: `${{ eq outputs.value "foobar" }}`}, - }, - }, - } - - for name, tt := range tests { - t.Run(name, func(t *testing.T) { - task, ok, err := buildTask(tt.spec, testRepo1, "", false) - if err != nil { - t.Fatalf("unexpected err: %s", err) - } - - if !ok { - if tt.wantSteps != nil { - t.Fatalf("no task built, but steps expected") - } - return - } - - opts := cmpopts.IgnoreUnexported(batcheslib.Step{}) - if diff := cmp.Diff(tt.wantSteps, task.Steps, opts); diff != "" { - t.Errorf("mismatch (-want +got):\n%s", diff) - } - }) - } -} diff --git a/internal/batches/service/workspaces.go b/internal/batches/service/workspaces.go index 1c2e2b84e7..81b2b3efc1 100644 --- a/internal/batches/service/workspaces.go +++ b/internal/batches/service/workspaces.go @@ -3,16 +3,21 @@ package service import ( "context" "fmt" + "sort" "github.com/gobwas/glob" + "github.com/pkg/errors" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" + "github.com/sourcegraph/sourcegraph/lib/batches/template" "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/graphql" + "github.com/sourcegraph/src-cli/internal/batches/util" ) type RepoWorkspace struct { RepoID string Path string + Steps []batcheslib.Step OnlyFetchWorkspace bool } @@ -31,6 +36,11 @@ func findWorkspaces( finder directoryFinder, repos []*graphql.Repository, ) ([]RepoWorkspace, error) { + repoByID := make(map[string]*graphql.Repository) + for _, repo := range repos { + repoByID[repo.ID] = repo + } + // Pre-compile all globs. workspaceMatchers := make(map[batcheslib.WorkspaceConfiguration]glob.Glob) for _, conf := range spec.Workspaces { @@ -117,12 +127,71 @@ func findWorkspaces( fetchWorkspace = false } + repo, ok := repoByID[workspace.RepoID] + if !ok { + return nil, errors.New("invalid state, repo not found") + } + + steps, err := stepsForRepo(spec, repo) + if err != nil { + return nil, err + } + + // If the workspace doesn't have any steps we don't need to include it. + if len(steps) == 0 { + continue + } + workspaces = append(workspaces, RepoWorkspace{ RepoID: workspace.RepoID, Path: path, + Steps: steps, OnlyFetchWorkspace: fetchWorkspace, }) } } + + // Stable sorting. + sort.Slice(workspaces, func(i, j int) bool { + if workspaces[i].RepoID == workspaces[j].RepoID { + return workspaces[i].Path < workspaces[j].Path + } + return workspaces[i].RepoID < workspaces[j].RepoID + }) + return workspaces, nil } + +// stepsForRepo calculates the steps required to run on the given repo. +func stepsForRepo(spec *batcheslib.BatchSpec, r *graphql.Repository) ([]batcheslib.Step, error) { + taskSteps := []batcheslib.Step{} + for _, step := range spec.Steps { + // If no if condition is given, just go ahead and add the step to the list. + if step.IfCondition() == "" { + taskSteps = append(taskSteps, step) + continue + } + + batchChange := template.BatchChangeAttributes{ + Name: spec.Name, + Description: spec.Description, + } + stepCtx := &template.StepContext{ + Repository: util.GraphQLRepoToTemplatingRepo(r), + BatchChange: batchChange, + } + static, boolVal, err := template.IsStaticBool(step.IfCondition(), stepCtx) + if err != nil { + return nil, err + } + + // If we could evaluate the condition statically and the resulting + // boolean is false, we don't add that step. + if !static { + taskSteps = append(taskSteps, step) + } else if boolVal { + taskSteps = append(taskSteps, step) + } + } + return taskSteps, nil +} diff --git a/internal/batches/service/workspaces_test.go b/internal/batches/service/workspaces_test.go index c47e79690a..e833818c7c 100644 --- a/internal/batches/service/workspaces_test.go +++ b/internal/batches/service/workspaces_test.go @@ -2,10 +2,10 @@ package service import ( "context" - "sort" "testing" "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/src-cli/internal/batches/graphql" ) @@ -31,9 +31,9 @@ func TestFindWorkspaces(t *testing.T) { spec: &batcheslib.BatchSpec{Steps: steps}, finderResults: finderResults{}, wantWorkspaces: []RepoWorkspace{ - {RepoID: repos[0].ID, Path: ""}, - {RepoID: repos[1].ID, Path: ""}, - {RepoID: repos[2].ID, Path: ""}, + {RepoID: repos[0].ID, Steps: steps, Path: ""}, + {RepoID: repos[1].ID, Steps: steps, Path: ""}, + {RepoID: repos[2].ID, Steps: steps, Path: ""}, }, }, @@ -46,9 +46,9 @@ func TestFindWorkspaces(t *testing.T) { }, finderResults: finderResults{}, wantWorkspaces: []RepoWorkspace{ - {RepoID: repos[0].ID, Path: ""}, - {RepoID: repos[1].ID, Path: ""}, - {RepoID: repos[2].ID, Path: ""}, + {RepoID: repos[0].ID, Steps: steps, Path: ""}, + {RepoID: repos[1].ID, Steps: steps, Path: ""}, + {RepoID: repos[2].ID, Steps: steps, Path: ""}, }, }, @@ -64,7 +64,7 @@ func TestFindWorkspaces(t *testing.T) { repos[2]: []string{}, }, wantWorkspaces: []RepoWorkspace{ - {RepoID: repos[1].ID, Path: ""}, + {RepoID: repos[1].ID, Steps: steps, Path: ""}, }, }, @@ -80,13 +80,13 @@ func TestFindWorkspaces(t *testing.T) { repos[2]: {"a/b", "a/b/c", "d/e/f"}, }, wantWorkspaces: []RepoWorkspace{ - {RepoID: repos[0].ID, Path: "a/b"}, - {RepoID: repos[0].ID, Path: "a/b/c"}, - {RepoID: repos[0].ID, Path: "d/e/f"}, - {RepoID: repos[1].ID, Path: ""}, - {RepoID: repos[2].ID, Path: "a/b"}, - {RepoID: repos[2].ID, Path: "a/b/c"}, - {RepoID: repos[2].ID, Path: "d/e/f"}, + {RepoID: repos[0].ID, Steps: steps, Path: "a/b"}, + {RepoID: repos[0].ID, Steps: steps, Path: "a/b/c"}, + {RepoID: repos[0].ID, Steps: steps, Path: "d/e/f"}, + {RepoID: repos[1].ID, Steps: steps, Path: ""}, + {RepoID: repos[2].ID, Steps: steps, Path: "a/b"}, + {RepoID: repos[2].ID, Steps: steps, Path: "a/b/c"}, + {RepoID: repos[2].ID, Steps: steps, Path: "d/e/f"}, }, }, @@ -106,13 +106,13 @@ func TestFindWorkspaces(t *testing.T) { repos[2]: {"a/b", "a/b/c", "d/e/f"}, }, wantWorkspaces: []RepoWorkspace{ - {RepoID: repos[0].ID, Path: "a/b", OnlyFetchWorkspace: true}, - {RepoID: repos[0].ID, Path: "a/b/c", OnlyFetchWorkspace: true}, - {RepoID: repos[0].ID, Path: "d/e/f", OnlyFetchWorkspace: true}, - {RepoID: repos[1].ID, Path: ""}, - {RepoID: repos[2].ID, Path: "a/b", OnlyFetchWorkspace: true}, - {RepoID: repos[2].ID, Path: "a/b/c", OnlyFetchWorkspace: true}, - {RepoID: repos[2].ID, Path: "d/e/f", OnlyFetchWorkspace: true}, + {RepoID: repos[0].ID, Steps: steps, Path: "a/b", OnlyFetchWorkspace: true}, + {RepoID: repos[0].ID, Steps: steps, Path: "a/b/c", OnlyFetchWorkspace: true}, + {RepoID: repos[0].ID, Steps: steps, Path: "d/e/f", OnlyFetchWorkspace: true}, + {RepoID: repos[1].ID, Steps: steps, Path: ""}, + {RepoID: repos[2].ID, Steps: steps, Path: "a/b", OnlyFetchWorkspace: true}, + {RepoID: repos[2].ID, Steps: steps, Path: "a/b/c", OnlyFetchWorkspace: true}, + {RepoID: repos[2].ID, Steps: steps, Path: "d/e/f", OnlyFetchWorkspace: true}, }, }, } @@ -125,13 +125,6 @@ func TestFindWorkspaces(t *testing.T) { t.Fatalf("unexpected err: %s", err) } - sort.Slice(workspaces, func(i, j int) bool { - if workspaces[i].RepoID == workspaces[j].RepoID { - return workspaces[i].Path < workspaces[j].Path - } - return workspaces[i].RepoID < workspaces[j].RepoID - }) - if diff := cmp.Diff(tt.wantWorkspaces, workspaces); diff != "" { t.Errorf("mismatch (-want +got):\n%s", diff) } @@ -146,3 +139,125 @@ type mockDirectoryFinder struct { func (m *mockDirectoryFinder) FindDirectoriesInRepos(ctx context.Context, fileName string, repos ...*graphql.Repository) (map[*graphql.Repository][]string, error) { return m.results, nil } + +func TestStepsForRepo(t *testing.T) { + tests := map[string]struct { + spec *batcheslib.BatchSpec + + wantSteps []batcheslib.Step + }{ + "no if": { + spec: &batcheslib.BatchSpec{ + Steps: []batcheslib.Step{ + {Run: "echo 1"}, + }, + }, + wantSteps: []batcheslib.Step{ + {Run: "echo 1"}, + }, + }, + + "if has static true value": { + spec: &batcheslib.BatchSpec{ + Steps: []batcheslib.Step{ + {Run: "echo 1", If: "true"}, + }, + }, + wantSteps: []batcheslib.Step{ + {Run: "echo 1", If: "true"}, + }, + }, + + "one of many steps has if with static true value": { + spec: &batcheslib.BatchSpec{ + Steps: []batcheslib.Step{ + {Run: "echo 1"}, + {Run: "echo 2", If: "true"}, + {Run: "echo 3"}, + }, + }, + wantSteps: []batcheslib.Step{ + {Run: "echo 1"}, + {Run: "echo 2", If: "true"}, + {Run: "echo 3"}, + }, + }, + + "if has static non-true value": { + spec: &batcheslib.BatchSpec{ + Steps: []batcheslib.Step{ + {Run: "echo 1", If: "this is not true"}, + }, + }, + wantSteps: []batcheslib.Step{}, + }, + + "one of many steps has if with static non-true value": { + spec: &batcheslib.BatchSpec{ + Steps: []batcheslib.Step{ + {Run: "echo 1"}, + {Run: "echo 2", If: "every type system needs generics"}, + {Run: "echo 3"}, + }, + }, + wantSteps: []batcheslib.Step{ + {Run: "echo 1"}, + {Run: "echo 3"}, + }, + }, + + "if expression that can be partially evaluated to true": { + spec: &batcheslib.BatchSpec{ + Steps: []batcheslib.Step{ + {Run: "echo 1", If: `${{ matches repository.name "github.com/sourcegraph/src*" }}`}, + }, + }, + wantSteps: []batcheslib.Step{ + {Run: "echo 1", If: `${{ matches repository.name "github.com/sourcegraph/src*" }}`}, + }, + }, + + "if expression that can be partially evaluated to false": { + spec: &batcheslib.BatchSpec{ + Steps: []batcheslib.Step{ + {Run: "echo 1", If: `${{ matches repository.name "horse" }}`}, + }, + }, + wantSteps: []batcheslib.Step{}, + }, + + "one of many steps has if expression that can be evaluated to true": { + spec: &batcheslib.BatchSpec{ + Steps: []batcheslib.Step{ + {Run: "echo 1", If: `${{ matches repository.name "horse" }}`}, + }, + }, + wantSteps: []batcheslib.Step{}, + }, + + "if expression that can NOT be partially evaluated": { + spec: &batcheslib.BatchSpec{ + Steps: []batcheslib.Step{ + {Run: "echo 1", If: `${{ eq outputs.value "foobar" }}`}, + }, + }, + wantSteps: []batcheslib.Step{ + {Run: "echo 1", If: `${{ eq outputs.value "foobar" }}`}, + }, + }, + } + + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + haveSteps, err := stepsForRepo(tt.spec, testRepo1) + if err != nil { + t.Fatalf("unexpected err: %s", err) + } + + opts := cmpopts.IgnoreUnexported(batcheslib.Step{}) + if diff := cmp.Diff(tt.wantSteps, haveSteps, opts); diff != "" { + t.Errorf("mismatch (-want +got):\n%s", diff) + } + }) + } +} From 615b48e456535e91a275862440e78962652317f3 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Thu, 2 Sep 2021 18:31:15 +0200 Subject: [PATCH 021/647] Cleanup code after refactoring of workspaces/steps (#596) --- cmd/src/batch_common.go | 7 +-- internal/batches/service/build_tasks.go | 39 +++++----------- internal/batches/service/service.go | 4 +- internal/batches/service/workspaces.go | 22 ++++----- internal/batches/service/workspaces_test.go | 51 ++++++++++++--------- 5 files changed, 54 insertions(+), 69 deletions(-) diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index 2bd895ad17..1dc016d215 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -279,11 +279,7 @@ func executeBatchSpec(ctx context.Context, opts executeBatchSpecOpts) (err error if err != nil { return err } - tasks, err := svc.BuildTasks(ctx, repos, batchSpec, workspaces) - if err != nil { - return err - } - opts.ui.DeterminingWorkspacesSuccess(len(tasks)) + opts.ui.DeterminingWorkspacesSuccess(len(workspaces)) // EXECUTION OF TASKS coord := svc.NewCoordinator(executor.NewCoordinatorOpts{ @@ -299,6 +295,7 @@ func executeBatchSpec(ctx context.Context, opts executeBatchSpecOpts) (err error }) opts.ui.CheckingCache() + tasks := svc.BuildTasks(ctx, batchSpec, workspaces) uncachedTasks, cachedSpecs, err := coord.CheckCache(ctx, tasks) if err != nil { return err diff --git a/internal/batches/service/build_tasks.go b/internal/batches/service/build_tasks.go index 832a7b6391..726aa10979 100644 --- a/internal/batches/service/build_tasks.go +++ b/internal/batches/service/build_tasks.go @@ -3,57 +3,42 @@ package service import ( "context" - "github.com/pkg/errors" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/template" "github.com/sourcegraph/src-cli/internal/batches/executor" - "github.com/sourcegraph/src-cli/internal/batches/graphql" ) -// buildTasks returns tasks for all the workspaces determined for the given spec. -func buildTasks(ctx context.Context, spec *batcheslib.BatchSpec, repos []*graphql.Repository, workspaces []RepoWorkspace) ([]*executor.Task, error) { - repoByID := make(map[string]*graphql.Repository) - for _, repo := range repos { - repoByID[repo.ID] = repo - } +// buildTasks returns *executor.Tasks for all the workspaces determined for the given spec. +func buildTasks(ctx context.Context, spec *batcheslib.BatchSpec, workspaces []RepoWorkspace) []*executor.Task { + tasks := make([]*executor.Task, 0, len(workspaces)) - tasks := []*executor.Task{} for _, ws := range workspaces { - repo, ok := repoByID[ws.RepoID] - if !ok { - return nil, errors.New("invalid state, didn't find repo for workspace definition") - } - - t, err := buildTask(spec, repo, ws.Path, ws.OnlyFetchWorkspace, ws.Steps) - if err != nil { - return nil, err - } - - tasks = append(tasks, t) + tasks = append(tasks, buildTask(spec, ws)) } - return tasks, nil + return tasks } -func buildTask(spec *batcheslib.BatchSpec, r *graphql.Repository, path string, onlyWorkspace bool, steps []batcheslib.Step) (*executor.Task, error) { +func buildTask(spec *batcheslib.BatchSpec, workspace RepoWorkspace) *executor.Task { batchChange := template.BatchChangeAttributes{ Name: spec.Name, Description: spec.Description, } - // "." means the path is root, but in the executor we use "" to signify root + // "." means the path is root, but in the executor we use "" to signify root. + path := workspace.Path if path == "." { path = "" } return &executor.Task{ - Repository: r, + Repository: workspace.Repo, Path: path, - Steps: steps, - OnlyFetchWorkspace: onlyWorkspace, + Steps: workspace.Steps, + OnlyFetchWorkspace: workspace.OnlyFetchWorkspace, TransformChanges: spec.TransformChanges, Template: spec.ChangesetTemplate, BatchChangeAttributes: &batchChange, - }, nil + } } diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index 5e076bba81..3932827e72 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -186,8 +186,8 @@ func (svc *Service) DetermineWorkspaces(ctx context.Context, repos []*graphql.Re return findWorkspaces(ctx, spec, svc, repos) } -func (svc *Service) BuildTasks(ctx context.Context, repos []*graphql.Repository, spec *batcheslib.BatchSpec, workspaces []RepoWorkspace) ([]*executor.Task, error) { - return buildTasks(ctx, spec, repos, workspaces) +func (svc *Service) BuildTasks(ctx context.Context, spec *batcheslib.BatchSpec, workspaces []RepoWorkspace) []*executor.Task { + return buildTasks(ctx, spec, workspaces) } func (svc *Service) NewCoordinator(opts executor.NewCoordinatorOpts) *executor.Coordinator { diff --git a/internal/batches/service/workspaces.go b/internal/batches/service/workspaces.go index 81b2b3efc1..c67d7c62e4 100644 --- a/internal/batches/service/workspaces.go +++ b/internal/batches/service/workspaces.go @@ -6,7 +6,6 @@ import ( "sort" "github.com/gobwas/glob" - "github.com/pkg/errors" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/template" "github.com/sourcegraph/src-cli/internal/batches" @@ -15,7 +14,7 @@ import ( ) type RepoWorkspace struct { - RepoID string + Repo *graphql.Repository Path string Steps []batcheslib.Step OnlyFetchWorkspace bool @@ -80,7 +79,7 @@ func findWorkspaces( } type repoWorkspaces struct { - RepoID string + Repo *graphql.Repository Paths []string OnlyFetchWorkspace bool } @@ -98,7 +97,7 @@ func findWorkspaces( continue } workspacesByID[repo.ID] = repoWorkspaces{ - RepoID: repo.ID, + Repo: repo, Paths: dirs, OnlyFetchWorkspace: conf.OnlyFetchWorkspace, } @@ -110,7 +109,7 @@ func findWorkspaces( conf, ok := workspacesByID[repo.ID] if !ok { workspacesByID[repo.ID] = repoWorkspaces{ - RepoID: repo.ID, + Repo: repo, Paths: []string{""}, OnlyFetchWorkspace: false, } @@ -127,12 +126,7 @@ func findWorkspaces( fetchWorkspace = false } - repo, ok := repoByID[workspace.RepoID] - if !ok { - return nil, errors.New("invalid state, repo not found") - } - - steps, err := stepsForRepo(spec, repo) + steps, err := stepsForRepo(spec, workspace.Repo) if err != nil { return nil, err } @@ -143,7 +137,7 @@ func findWorkspaces( } workspaces = append(workspaces, RepoWorkspace{ - RepoID: workspace.RepoID, + Repo: workspace.Repo, Path: path, Steps: steps, OnlyFetchWorkspace: fetchWorkspace, @@ -153,10 +147,10 @@ func findWorkspaces( // Stable sorting. sort.Slice(workspaces, func(i, j int) bool { - if workspaces[i].RepoID == workspaces[j].RepoID { + if workspaces[i].Repo.Name == workspaces[j].Repo.Name { return workspaces[i].Path < workspaces[j].Path } - return workspaces[i].RepoID < workspaces[j].RepoID + return workspaces[i].Repo.Name < workspaces[j].Repo.Name }) return workspaces, nil diff --git a/internal/batches/service/workspaces_test.go b/internal/batches/service/workspaces_test.go index e833818c7c..09b1871fea 100644 --- a/internal/batches/service/workspaces_test.go +++ b/internal/batches/service/workspaces_test.go @@ -2,6 +2,7 @@ package service import ( "context" + "sort" "testing" "github.com/google/go-cmp/cmp" @@ -31,9 +32,9 @@ func TestFindWorkspaces(t *testing.T) { spec: &batcheslib.BatchSpec{Steps: steps}, finderResults: finderResults{}, wantWorkspaces: []RepoWorkspace{ - {RepoID: repos[0].ID, Steps: steps, Path: ""}, - {RepoID: repos[1].ID, Steps: steps, Path: ""}, - {RepoID: repos[2].ID, Steps: steps, Path: ""}, + {Repo: repos[0], Steps: steps, Path: ""}, + {Repo: repos[1], Steps: steps, Path: ""}, + {Repo: repos[2], Steps: steps, Path: ""}, }, }, @@ -46,9 +47,9 @@ func TestFindWorkspaces(t *testing.T) { }, finderResults: finderResults{}, wantWorkspaces: []RepoWorkspace{ - {RepoID: repos[0].ID, Steps: steps, Path: ""}, - {RepoID: repos[1].ID, Steps: steps, Path: ""}, - {RepoID: repos[2].ID, Steps: steps, Path: ""}, + {Repo: repos[0], Steps: steps, Path: ""}, + {Repo: repos[1], Steps: steps, Path: ""}, + {Repo: repos[2], Steps: steps, Path: ""}, }, }, @@ -64,7 +65,7 @@ func TestFindWorkspaces(t *testing.T) { repos[2]: []string{}, }, wantWorkspaces: []RepoWorkspace{ - {RepoID: repos[1].ID, Steps: steps, Path: ""}, + {Repo: repos[1], Steps: steps, Path: ""}, }, }, @@ -80,13 +81,13 @@ func TestFindWorkspaces(t *testing.T) { repos[2]: {"a/b", "a/b/c", "d/e/f"}, }, wantWorkspaces: []RepoWorkspace{ - {RepoID: repos[0].ID, Steps: steps, Path: "a/b"}, - {RepoID: repos[0].ID, Steps: steps, Path: "a/b/c"}, - {RepoID: repos[0].ID, Steps: steps, Path: "d/e/f"}, - {RepoID: repos[1].ID, Steps: steps, Path: ""}, - {RepoID: repos[2].ID, Steps: steps, Path: "a/b"}, - {RepoID: repos[2].ID, Steps: steps, Path: "a/b/c"}, - {RepoID: repos[2].ID, Steps: steps, Path: "d/e/f"}, + {Repo: repos[0], Steps: steps, Path: "a/b"}, + {Repo: repos[0], Steps: steps, Path: "a/b/c"}, + {Repo: repos[0], Steps: steps, Path: "d/e/f"}, + {Repo: repos[1], Steps: steps, Path: ""}, + {Repo: repos[2], Steps: steps, Path: "a/b"}, + {Repo: repos[2], Steps: steps, Path: "a/b/c"}, + {Repo: repos[2], Steps: steps, Path: "d/e/f"}, }, }, @@ -106,13 +107,13 @@ func TestFindWorkspaces(t *testing.T) { repos[2]: {"a/b", "a/b/c", "d/e/f"}, }, wantWorkspaces: []RepoWorkspace{ - {RepoID: repos[0].ID, Steps: steps, Path: "a/b", OnlyFetchWorkspace: true}, - {RepoID: repos[0].ID, Steps: steps, Path: "a/b/c", OnlyFetchWorkspace: true}, - {RepoID: repos[0].ID, Steps: steps, Path: "d/e/f", OnlyFetchWorkspace: true}, - {RepoID: repos[1].ID, Steps: steps, Path: ""}, - {RepoID: repos[2].ID, Steps: steps, Path: "a/b", OnlyFetchWorkspace: true}, - {RepoID: repos[2].ID, Steps: steps, Path: "a/b/c", OnlyFetchWorkspace: true}, - {RepoID: repos[2].ID, Steps: steps, Path: "d/e/f", OnlyFetchWorkspace: true}, + {Repo: repos[0], Steps: steps, Path: "a/b", OnlyFetchWorkspace: true}, + {Repo: repos[0], Steps: steps, Path: "a/b/c", OnlyFetchWorkspace: true}, + {Repo: repos[0], Steps: steps, Path: "d/e/f", OnlyFetchWorkspace: true}, + {Repo: repos[1], Steps: steps, Path: ""}, + {Repo: repos[2], Steps: steps, Path: "a/b", OnlyFetchWorkspace: true}, + {Repo: repos[2], Steps: steps, Path: "a/b/c", OnlyFetchWorkspace: true}, + {Repo: repos[2], Steps: steps, Path: "d/e/f", OnlyFetchWorkspace: true}, }, }, } @@ -125,6 +126,14 @@ func TestFindWorkspaces(t *testing.T) { t.Fatalf("unexpected err: %s", err) } + // Sort by ID, easier than by name for tests. + sort.Slice(workspaces, func(i, j int) bool { + if workspaces[i].Repo.ID == workspaces[j].Repo.ID { + return workspaces[i].Path < workspaces[j].Path + } + return workspaces[i].Repo.ID < workspaces[j].Repo.ID + }) + if diff := cmp.Diff(tt.wantWorkspaces, workspaces); diff != "" { t.Errorf("mismatch (-want +got):\n%s", diff) } From b813609798b1674e8c76a0809870579547d74ca9 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Thu, 2 Sep 2021 19:38:45 +0200 Subject: [PATCH 022/647] Add configuration for VSCode (#599) --- .vscode/settings.json | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 .vscode/settings.json diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000000..fab3522383 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,9 @@ +{ + "go.lintTool": "golangci-lint", + "shellformat.flag": "-i 2 -ci", + "editor.formatOnSave": true, + "go.useLanguageServer": true, + "gopls": { + "local": "github.com/sourcegraph/src-cli" + } +} From 5f95ba7df5b4317e7fef56f796bf6b53773c3765 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Fri, 3 Sep 2021 01:48:22 +0200 Subject: [PATCH 023/647] Configure golangci-lint for src-cli (#600) This has long been overdue. Finally, some sweet little fixes. The best one was a missing error check in our caching layer. :) Also adds this to CI. --- .github/workflows/go-lint.yml | 16 ++++++ .golangci.yml | 52 +++++++++++++++++++ .tool-versions | 1 + cmd/src/batch_common.go | 9 ++-- cmd/src/batch_repositories.go | 3 +- cmd/src/cmd.go | 3 +- cmd/src/config.go | 3 +- cmd/src/doc.go | 3 +- cmd/src/extensions_publish.go | 3 +- cmd/src/extsvc.go | 3 +- cmd/src/extsvc_edit.go | 4 +- cmd/src/login_test.go | 4 +- cmd/src/lsif_upload.go | 3 +- cmd/src/lsif_upload_flags.go | 4 +- cmd/src/main.go | 3 +- cmd/src/repos_delete.go | 3 +- cmd/src/search.go | 7 +-- cmd/src/search_alert.go | 2 +- cmd/src/search_stream.go | 19 +++---- cmd/src/testdata/streaming_search_want.txt | 2 +- cmd/src/validate.go | 6 ++- dev/.gitignore | 1 + dev/go-lint.sh | 18 +++++++ dev/golangci-lint.sh | 27 ++++++++++ go.mod | 6 +-- go.sum | 10 +--- internal/api/errors.go | 2 +- internal/batches/docker/image.go | 2 +- internal/batches/executor/changeset_specs.go | 3 +- internal/batches/executor/coordinator.go | 3 +- internal/batches/executor/coordinator_test.go | 8 +-- internal/batches/executor/execution_cache.go | 5 +- .../batches/executor/execution_cache_test.go | 19 ++----- internal/batches/executor/executor.go | 3 +- internal/batches/executor/executor_test.go | 9 ++-- internal/batches/executor/run_steps.go | 5 +- internal/batches/features.go | 3 +- internal/batches/log/task_logger.go | 2 +- internal/batches/repo_fetcher.go | 3 +- internal/batches/service/service.go | 3 +- internal/batches/service/service_test.go | 7 ++- internal/batches/ui/tui.go | 3 +- internal/batches/workspace/bind_workspace.go | 14 +---- .../workspace/bind_workspace_nonwin_test.go | 2 +- .../workspace/bind_workspace_windows_test.go | 2 +- internal/batches/workspace/git.go | 2 +- .../batches/workspace/volume_workspace.go | 3 +- .../workspace/volume_workspace_test.go | 3 +- internal/batches/workspace/workspace.go | 3 +- internal/batches/workspace/workspace_test.go | 3 +- internal/cmderrors/errors.go | 3 +- internal/exec/expect/expect.go | 2 +- internal/servegit/serve.go | 2 +- internal/streaming/api.go | 2 +- internal/streaming/search.go | 2 +- internal/streaming/writer.go | 3 +- 56 files changed, 225 insertions(+), 116 deletions(-) create mode 100644 .github/workflows/go-lint.yml create mode 100644 .golangci.yml create mode 100644 .tool-versions create mode 100644 dev/.gitignore create mode 100755 dev/go-lint.sh create mode 100755 dev/golangci-lint.sh diff --git a/.github/workflows/go-lint.yml b/.github/workflows/go-lint.yml new file mode 100644 index 0000000000..f4d3832c33 --- /dev/null +++ b/.github/workflows/go-lint.yml @@ -0,0 +1,16 @@ +name: Go Lint + +on: + - push + +jobs: + go-test: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Set up Go + uses: actions/setup-go@v2 + with: + go-version: 1.16.x + - run: ./dev/go-lint.sh diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 0000000000..49f4ea5eba --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,52 @@ +# See explanation of linters at https://golangci-lint.run/usage/linters/ +linters: + disable-all: true + enable: + - bodyclose + - depguard + - gocritic + - goimports + - gosimple + - govet + - ineffassign + - nolintlint + - staticcheck + - typecheck + - unconvert + - unused + +linters-settings: + depguard: + list-type: blacklist + include-go-root: true + packages-with-error-message: + - errors: 'Use github.com/cockroachdb/errors instead' + - github.com/pkg/errors: 'Use github.com/cockroachdb/errors instead' + - ioutil: 'The ioutil package has been deprecated' + gocritic: + disabled-checks: + - appendAssign # Too many false positives + - assignOp # Maybe worth adding, but likely not worth the noise + - commentFormatting # No strong benefit + - deprecatedComment # Unnecessary + - exitAfterDefer # Only occurs in auxiliary tools + - ifElseChain # Noisy for not much gain + - singleCaseSwitch # Noisy for not much gain + govet: + disable: + - composites + forbidigo: + forbid: + # Use errors.New instead + - 'fmt\.Errorf' + +issues: + exclude-rules: + # Exclude bodyclose lint from tests because leaking connections in tests + # is a non-issue, and checking that adds unnecessary noise + - path: _test\.go + linters: + - bodyclose + +run: + timeout: 5m diff --git a/.tool-versions b/.tool-versions new file mode 100644 index 0000000000..e00848fe19 --- /dev/null +++ b/.tool-versions @@ -0,0 +1 @@ +golang 1.16.5 diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index 1dc016d215..1fd346e0f1 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -14,9 +14,10 @@ import ( "strings" "time" + "github.com/cockroachdb/errors" "github.com/hashicorp/go-multierror" - "github.com/pkg/errors" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" + "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/executor" @@ -338,10 +339,8 @@ func executeBatchSpec(ctx context.Context, opts executeBatchSpecOpts) (err error } opts.ui.UploadingChangesetSpecsSuccess() - } else { - if len(repos) == 0 { - opts.ui.NoChangesetSpecs() - } + } else if len(repos) == 0 { + opts.ui.NoChangesetSpecs() } opts.ui.CreatingBatchSpec() diff --git a/cmd/src/batch_repositories.go b/cmd/src/batch_repositories.go index f8e117b05c..dc14717f18 100644 --- a/cmd/src/batch_repositories.go +++ b/cmd/src/batch_repositories.go @@ -5,8 +5,9 @@ import ( "flag" "fmt" - "github.com/pkg/errors" + "github.com/cockroachdb/errors" "github.com/sourcegraph/sourcegraph/lib/output" + "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/batches/graphql" "github.com/sourcegraph/src-cli/internal/batches/service" diff --git a/cmd/src/cmd.go b/cmd/src/cmd.go index 9df4ea6fc5..6d4fb53215 100644 --- a/cmd/src/cmd.go +++ b/cmd/src/cmd.go @@ -1,13 +1,14 @@ package main import ( - "errors" "flag" "fmt" "log" "os" "strings" + "github.com/cockroachdb/errors" + "github.com/sourcegraph/src-cli/internal/cmderrors" ) diff --git a/cmd/src/config.go b/cmd/src/config.go index c4823b6ad1..572e81264e 100644 --- a/cmd/src/config.go +++ b/cmd/src/config.go @@ -2,10 +2,11 @@ package main import ( "context" - "errors" "flag" "fmt" + "github.com/cockroachdb/errors" + "github.com/sourcegraph/src-cli/internal/api" ) diff --git a/cmd/src/doc.go b/cmd/src/doc.go index 2006e69f26..cd17c93e48 100644 --- a/cmd/src/doc.go +++ b/cmd/src/doc.go @@ -10,8 +10,9 @@ import ( "strings" "text/template" - "github.com/pkg/errors" + "github.com/cockroachdb/errors" "github.com/sourcegraph/sourcegraph/lib/output" + "github.com/sourcegraph/src-cli/internal/cmderrors" ) diff --git a/cmd/src/extensions_publish.go b/cmd/src/extensions_publish.go index 64cf42e2d7..36a3ac94e2 100644 --- a/cmd/src/extensions_publish.go +++ b/cmd/src/extensions_publish.go @@ -3,7 +3,6 @@ package main import ( "context" "encoding/json" - "errors" "flag" "fmt" "io/ioutil" @@ -12,6 +11,8 @@ import ( "path/filepath" "strings" + "github.com/cockroachdb/errors" + "github.com/sourcegraph/src-cli/internal/api" ) diff --git a/cmd/src/extsvc.go b/cmd/src/extsvc.go index d44aab88e9..a2fa9f8d15 100644 --- a/cmd/src/extsvc.go +++ b/cmd/src/extsvc.go @@ -2,10 +2,11 @@ package main import ( "context" - "errors" "flag" "fmt" + "github.com/cockroachdb/errors" + "github.com/sourcegraph/src-cli/internal/api" ) diff --git a/cmd/src/extsvc_edit.go b/cmd/src/extsvc_edit.go index ef2b58ddde..d29a7bcda7 100644 --- a/cmd/src/extsvc_edit.go +++ b/cmd/src/extsvc_edit.go @@ -3,15 +3,17 @@ package main import ( "context" "encoding/json" - "errors" "flag" "fmt" "io/ioutil" "os" "strings" + "github.com/cockroachdb/errors" + isatty "github.com/mattn/go-isatty" "github.com/sourcegraph/jsonx" + "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/cmderrors" ) diff --git a/cmd/src/login_test.go b/cmd/src/login_test.go index 1dcae4b884..7ae87c03bc 100644 --- a/cmd/src/login_test.go +++ b/cmd/src/login_test.go @@ -68,7 +68,7 @@ func TestLogin(t *testing.T) { t.Fatal(err) } wantOut := "❌ Problem: Invalid access token.\n\n🛠 To fix: Create an access token at $ENDPOINT/user/settings/tokens, then set the following environment variables:\n\n SRC_ENDPOINT=$ENDPOINT\n SRC_ACCESS_TOKEN=(the access token you just created)\n\n To verify that it's working, run this command again.\n\n (If you need to supply custom HTTP request headers, see information about SRC_HEADER_* env vars at https://github.com/sourcegraph/src-cli/blob/main/AUTH_PROXY.md.)" - wantOut = strings.Replace(wantOut, "$ENDPOINT", endpoint, -1) + wantOut = strings.ReplaceAll(wantOut, "$ENDPOINT", endpoint) if out != wantOut { t.Errorf("got output %q, want %q", out, wantOut) } @@ -87,7 +87,7 @@ func TestLogin(t *testing.T) { t.Fatal(err) } wantOut := "✔️ Authenticated as alice on $ENDPOINT" - wantOut = strings.Replace(wantOut, "$ENDPOINT", endpoint, -1) + wantOut = strings.ReplaceAll(wantOut, "$ENDPOINT", endpoint) if out != wantOut { t.Errorf("got output %q, want %q", out, wantOut) } diff --git a/cmd/src/lsif_upload.go b/cmd/src/lsif_upload.go index 1f3c39b4c4..982a0e84f2 100644 --- a/cmd/src/lsif_upload.go +++ b/cmd/src/lsif_upload.go @@ -15,6 +15,7 @@ import ( "github.com/sourcegraph/sourcegraph/lib/codeintel/upload" "github.com/sourcegraph/sourcegraph/lib/output" + "github.com/sourcegraph/src-cli/internal/api" ) @@ -195,7 +196,7 @@ func makeLSIFUploadURL(uploadID int) (string, error) { return "", err } - graphqlID := string(base64.URLEncoding.EncodeToString([]byte(fmt.Sprintf(`LSIFUpload:"%d"`, uploadID)))) + graphqlID := base64.URLEncoding.EncodeToString([]byte(fmt.Sprintf(`LSIFUpload:"%d"`, uploadID))) url.Path = lsifUploadFlags.repo + "/-/settings/code-intelligence/lsif-uploads/" + graphqlID url.User = nil return url.String(), nil diff --git a/cmd/src/lsif_upload_flags.go b/cmd/src/lsif_upload_flags.go index 4f79107f52..5c2b4ac01b 100644 --- a/cmd/src/lsif_upload_flags.go +++ b/cmd/src/lsif_upload_flags.go @@ -1,13 +1,15 @@ package main import ( - "errors" "flag" "fmt" "os" "strings" + "github.com/cockroachdb/errors" + "github.com/sourcegraph/sourcegraph/lib/codeintel/upload" + "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/codeintel" ) diff --git a/cmd/src/main.go b/cmd/src/main.go index 3d786cf3ea..7f21386579 100644 --- a/cmd/src/main.go +++ b/cmd/src/main.go @@ -11,7 +11,8 @@ import ( "path/filepath" "strings" - "github.com/pkg/errors" + "github.com/cockroachdb/errors" + "github.com/sourcegraph/src-cli/internal/api" ) diff --git a/cmd/src/repos_delete.go b/cmd/src/repos_delete.go index b017866596..5d0edddebc 100644 --- a/cmd/src/repos_delete.go +++ b/cmd/src/repos_delete.go @@ -5,8 +5,9 @@ import ( "flag" "fmt" + "github.com/cockroachdb/errors" multierror "github.com/hashicorp/go-multierror" - "github.com/pkg/errors" + "github.com/sourcegraph/src-cli/internal/api" ) diff --git a/cmd/src/search.go b/cmd/src/search.go index 16d092f3e5..7b0ec7a372 100644 --- a/cmd/src/search.go +++ b/cmd/src/search.go @@ -15,10 +15,11 @@ import ( "time" isatty "github.com/mattn/go-isatty" + "jaytaylor.com/html2text" + "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/cmderrors" "github.com/sourcegraph/src-cli/internal/streaming" - "jaytaylor.com/html2text" ) var dateRegex = regexp.MustCompile(`(\w{4}-\w{2}-\w{2})`) @@ -390,11 +391,11 @@ func searchHighlightDiffPreview(diffPreview interface{}) string { } // Replace our start-of-match token with the color we wish. - line = strings.Replace(line, uniqueStartOfMatchToken, ansiColors["search-match"], -1) + line = strings.ReplaceAll(line, uniqueStartOfMatchToken, ansiColors["search-match"]) // Replace our end-of-match token with the color terminator, // and start all colors that were previously started to the left. - line = strings.Replace(line, uniqueEndOfMatchToken, ansiColors["nc"]+strings.Join(left, ""), -1) + line = strings.ReplaceAll(line, uniqueEndOfMatchToken, ansiColors["nc"]+strings.Join(left, "")) final = append(final, line) } diff --git a/cmd/src/search_alert.go b/cmd/src/search_alert.go index 998b3817aa..51362d5a8f 100644 --- a/cmd/src/search_alert.go +++ b/cmd/src/search_alert.go @@ -4,7 +4,7 @@ import ( "strings" "text/template" - "github.com/pkg/errors" + "github.com/cockroachdb/errors" ) var searchResultsAlertTemplate *template.Template diff --git a/cmd/src/search_stream.go b/cmd/src/search_stream.go index 825c225854..7df4018783 100644 --- a/cmd/src/search_stream.go +++ b/cmd/src/search_stream.go @@ -16,11 +16,7 @@ import ( "github.com/sourcegraph/src-cli/internal/streaming" ) -var labelRegexp *regexp.Regexp - -func init() { - labelRegexp, _ = regexp.Compile("(?:\\[)(.*?)(?:])") -} +var labelRegexp = regexp.MustCompile(`(?:\[)(.*?)(?:])`) func streamSearch(query string, opts streaming.Opts, client api.Client, w io.Writer) error { var d streaming.Decoder @@ -106,7 +102,6 @@ func textDecoder(query string, t *template.Template, w io.Writer) streaming.Deco if err != nil { logError(fmt.Sprintf("error when executing template: %s\n", err)) } - return }, OnError: func(eventError *streaming.EventError) { fmt.Printf("ERR: %s", eventError.Message) @@ -434,11 +429,11 @@ func streamSearchHighlightDiffPreview(diffPreview string, highlights []highlight } // Replace our start-of-match token with the color we wish. - line = strings.Replace(line, uniqueStartOfMatchToken, ansiColors["search-match"], -1) + line = strings.ReplaceAll(line, uniqueStartOfMatchToken, ansiColors["search-match"]) // Replace our end-of-match token with the color terminator, // and start all colors that were previously started to the left. - line = strings.Replace(line, uniqueEndOfMatchToken, ansiColors["nc"]+strings.Join(left, ""), -1) + line = strings.ReplaceAll(line, uniqueEndOfMatchToken, ansiColors["nc"]+strings.Join(left, "")) final = append(final, line) } @@ -446,9 +441,9 @@ func streamSearchHighlightDiffPreview(diffPreview string, highlights []highlight } func stripMarkdownMarkers(content string) string { - content = strings.TrimLeft(content, "```COMMIT_EDITMSG\n") - content = strings.TrimLeft(content, "```diff\n") - return strings.TrimRight(content, "\n```") + content = strings.TrimPrefix(content, "```COMMIT_EDITMSG\n") + content = strings.TrimPrefix(content, "```diff\n") + return strings.TrimSuffix(content, "\n```") } // convertMatchToHighlights converts a FileMatch m to a highlight data type. @@ -473,5 +468,5 @@ func streamConvertMatchToHighlights(m streaming.EventLineMatch, isPreview bool) } func logError(msg string) { - _, _ = fmt.Fprintf(os.Stderr, msg) + _, _ = fmt.Fprint(os.Stderr, msg) } diff --git a/cmd/src/testdata/streaming_search_want.txt b/cmd/src/testdata/streaming_search_want.txt index 9045928b92..1cc9c8aaeb 100644 --- a/cmd/src/testdata/streaming_search_want.txt +++ b/cmd/src/testdata/streaming_search_want.txt @@ -11,7 +11,7 @@ (http://127.0.0.1:55128) sourcegraph/sourcegraph-atom > Stephen Gutekanst : all: release v1.0.5 (1 match) -------------------------------------------------------------------------------- - oo bar + foo bar (http://127.0.0.1:55128) sourcegraph/sourcegraph-atom > Stephen Gutekanst : all: release v1.0.5 (1 match) diff --git a/cmd/src/validate.go b/cmd/src/validate.go index cf44144d03..b1b2363f34 100644 --- a/cmd/src/validate.go +++ b/cmd/src/validate.go @@ -4,7 +4,6 @@ import ( "bytes" "context" "encoding/json" - "errors" "flag" "fmt" "io/ioutil" @@ -14,11 +13,14 @@ import ( "text/template" "time" + "github.com/cockroachdb/errors" + jsoniter "github.com/json-iterator/go" "github.com/mattn/go-isatty" + "gopkg.in/yaml.v3" + "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/cmderrors" - "gopkg.in/yaml.v3" ) type validationSpec struct { diff --git a/dev/.gitignore b/dev/.gitignore new file mode 100644 index 0000000000..ca8d09f870 --- /dev/null +++ b/dev/.gitignore @@ -0,0 +1 @@ +.bin diff --git a/dev/go-lint.sh b/dev/go-lint.sh new file mode 100755 index 0000000000..c166c77768 --- /dev/null +++ b/dev/go-lint.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash + +trap "echo ^^^ +++" ERR + +set -ex +cd "$(dirname "${BASH_SOURCE[0]}")/.." + +export GOBIN="$PWD/dev/.bin" +export PATH=$GOBIN:$PATH +export GO111MODULE=on + +if [ $# -eq 0 ]; then + pkgs=('./...') +else + pkgs=("$@") +fi + +"./dev/golangci-lint.sh" --config .golangci.yml run "${pkgs[@]}" diff --git a/dev/golangci-lint.sh b/dev/golangci-lint.sh new file mode 100755 index 0000000000..728e45fd48 --- /dev/null +++ b/dev/golangci-lint.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash + +set -euf -o pipefail + +pushd "$(dirname "${BASH_SOURCE[0]}")/.." >/dev/null + +mkdir -p dev/.bin + +version="1.37.1" +suffix="${version}-$(go env GOOS)-$(go env GOARCH)" +target="$PWD/dev/.bin/golangci-lint-${suffix}" +url="https://github.com/golangci/golangci-lint/releases/download/v${version}/golangci-lint-${suffix}.tar.gz" + +if [ ! -f "${target}" ]; then + echo "downloading ${url}" 1>&2 + curl -sS -L -f "${url}" -o "${target}.tar.gz" + tar xzf "${target}.tar.gz" + mv "golangci-lint-${suffix}/golangci-lint" "${target}" + rm -f "${target}.tar.gz" + rm -rf "golangci-lint-${suffix}" +fi + +chmod +x "${target}" + +popd >/dev/null + +exec "${target}" "$@" diff --git a/go.mod b/go.mod index 27fd864927..664a746293 100644 --- a/go.mod +++ b/go.mod @@ -4,8 +4,7 @@ go 1.16 require ( github.com/Masterminds/semver v1.5.0 - github.com/cockroachdb/errors v1.8.6 // indirect - github.com/cockroachdb/redact v1.1.3 // indirect + github.com/cockroachdb/errors v1.8.6 github.com/dustin/go-humanize v1.0.0 github.com/gobwas/glob v0.2.3 github.com/google/go-cmp v0.5.6 @@ -13,15 +12,12 @@ require ( github.com/jig/teereadcloser v0.0.0-20181016160506-953720c48e05 github.com/json-iterator/go v1.1.11 github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 - github.com/kr/pretty v0.3.0 // indirect github.com/mattn/go-isatty v0.0.12 github.com/mitchellh/copystructure v1.2.0 github.com/neelance/parallel v0.0.0-20160708114440-4de9ce63d14c github.com/olekukonko/tablewriter v0.0.4 // indirect github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4 - github.com/pkg/errors v0.9.1 github.com/rivo/uniseg v0.2.0 // indirect - github.com/rogpeppe/go-internal v1.8.0 // indirect github.com/sourcegraph/batch-change-utils v0.0.0-20210708162152-c9f35b905d94 github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf diff --git a/go.sum b/go.sum index 4b8795e208..c083130164 100644 --- a/go.sum +++ b/go.sum @@ -28,9 +28,8 @@ github.com/cockroachdb/errors v1.8.6/go.mod h1:hOm5fabihW+xEyY1kuypGwqT+Vt7rafg0 github.com/cockroachdb/logtags v0.0.0-20190617123548-eb05cc24525f h1:o/kfcElHqOiXqcou5a3rIlMc7oJbMQkeLk0VQJ7zgqY= github.com/cockroachdb/logtags v0.0.0-20190617123548-eb05cc24525f/go.mod h1:i/u985jwjWRlyHXQbwatDASoW0RMlZ/3i9yJHE2xLkI= github.com/cockroachdb/redact v1.0.8/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= +github.com/cockroachdb/redact v1.1.1 h1:TNJ9tJHjtS7TrJR3n3DidvsQji8Av6Ecq8la9Xmn6SI= github.com/cockroachdb/redact v1.1.1/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= -github.com/cockroachdb/redact v1.1.3 h1:AKZds10rFSIj7qADf0g46UixK8NNLwWTNdCIGS5wfSQ= -github.com/cockroachdb/redact v1.1.3/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= github.com/cockroachdb/sentry-go v0.6.1-cockroachdb.2 h1:IKgmqgMQlVJIZj19CdocBeSfSaiCbEBZGKODaixqtHM= github.com/cockroachdb/sentry-go v0.6.1-cockroachdb.2/go.mod h1:8BT+cPK6xvFOcRlk0R8eg+OTkcqI6baNH4xAkpiYVvQ= github.com/codegangsta/inject v0.0.0-20150114235600-33e0aa1cb7c0/go.mod h1:4Zcjuz89kmFXt9morQgcfYZAYZ5n8WHjt81YYWIwtTM= @@ -171,9 +170,8 @@ github.com/klauspost/cpuid v1.2.1/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgo github.com/klauspost/pgzip v1.2.5 h1:qnWYvvKqedOF2ulHpMG72XQol4ILEJ8k2wwRl/Km8oE= github.com/klauspost/pgzip v1.2.5/go.mod h1:Ch1tH69qFZu15pkjo5kYi6mth2Zzwzt50oCQKQE9RUs= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI= github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= -github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= -github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= @@ -233,7 +231,6 @@ github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4 github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8= github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4 h1:49lOXmGaUpV9Fz3gd7TFZY106KVlPVa5jcYD1gaQf98= github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4/go.mod h1:4OwLy04Bl9Ef3GJJCoec+30X3LQs/0/m4HFRt/2LUSA= -github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= @@ -243,10 +240,7 @@ github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1: github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY= github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= -github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.6.2/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= -github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8= -github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= github.com/ryanuber/columnize v2.1.0+incompatible/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= github.com/sclevine/agouti v3.0.0+incompatible/go.mod h1:b4WX9W9L1sfQKXeJf1mUTLZKJ48R1S7H23Ji7oFO5Bw= diff --git a/internal/api/errors.go b/internal/api/errors.go index 21abd47540..051fd47e73 100644 --- a/internal/api/errors.go +++ b/internal/api/errors.go @@ -3,8 +3,8 @@ package api import ( "encoding/json" + "github.com/cockroachdb/errors" "github.com/hashicorp/go-multierror" - "github.com/pkg/errors" ) // GraphQlErrors contains one or more GraphQlError instances. diff --git a/internal/batches/docker/image.go b/internal/batches/docker/image.go index 9b340913f5..cc610fb36d 100644 --- a/internal/batches/docker/image.go +++ b/internal/batches/docker/image.go @@ -7,7 +7,7 @@ import ( "strings" "sync" - "github.com/pkg/errors" + "github.com/cockroachdb/errors" "github.com/sourcegraph/src-cli/internal/exec" ) diff --git a/internal/batches/executor/changeset_specs.go b/internal/batches/executor/changeset_specs.go index 345d6bf634..37df8b350b 100644 --- a/internal/batches/executor/changeset_specs.go +++ b/internal/batches/executor/changeset_specs.go @@ -4,10 +4,11 @@ import ( "fmt" "strings" - "github.com/pkg/errors" + "github.com/cockroachdb/errors" "github.com/sourcegraph/go-diff/diff" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/template" + "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/util" ) diff --git a/internal/batches/executor/coordinator.go b/internal/batches/executor/coordinator.go index e1d9c6cc90..01e5ae4597 100644 --- a/internal/batches/executor/coordinator.go +++ b/internal/batches/executor/coordinator.go @@ -6,9 +6,10 @@ import ( "strconv" "time" + "github.com/cockroachdb/errors" "github.com/hashicorp/go-multierror" - "github.com/pkg/errors" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" + "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/docker" diff --git a/internal/batches/executor/coordinator_test.go b/internal/batches/executor/coordinator_test.go index 890d37c25d..e314ddef35 100644 --- a/internal/batches/executor/coordinator_test.go +++ b/internal/batches/executor/coordinator_test.go @@ -13,6 +13,7 @@ import ( batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/git" "github.com/sourcegraph/sourcegraph/lib/batches/template" + "github.com/sourcegraph/src-cli/internal/batches/graphql" "github.com/sourcegraph/src-cli/internal/batches/mock" ) @@ -293,10 +294,9 @@ func TestCoordinator_Execute(t *testing.T) { } else { if err == nil { t.Fatalf("expected error to include %q, but got no error", tc.wantErrInclude) - } else { - if !strings.Contains(err.Error(), tc.wantErrInclude) { - t.Errorf("wrong error. have=%q want included=%q", err, tc.wantErrInclude) - } + } + if !strings.Contains(err.Error(), tc.wantErrInclude) { + t.Errorf("wrong error. have=%q want included=%q", err, tc.wantErrInclude) } } diff --git a/internal/batches/executor/execution_cache.go b/internal/batches/executor/execution_cache.go index b901464b0d..1f1f6341dd 100644 --- a/internal/batches/executor/execution_cache.go +++ b/internal/batches/executor/execution_cache.go @@ -10,7 +10,7 @@ import ( "os" "path/filepath" - "github.com/pkg/errors" + "github.com/cockroachdb/errors" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" ) @@ -244,6 +244,9 @@ func (c ExecutionDiskCache) GetStepResult(ctx context.Context, key CacheKeyer) ( } found, err := c.readCacheFile(path, &result) + if err != nil { + return result, false, err + } return result, found, nil } diff --git a/internal/batches/executor/execution_cache_test.go b/internal/batches/executor/execution_cache_test.go index 14ccfcc5e3..7002e68c20 100644 --- a/internal/batches/executor/execution_cache_test.go +++ b/internal/batches/executor/execution_cache_test.go @@ -52,7 +52,7 @@ func TestTaskCacheKey(t *testing.T) { if err != nil { t.Errorf("unexpected error: %v", err) } - if string(initial) != string(have) { + if initial != have { t.Errorf("unexpected change in key: initial=%q have=%q", initial, have) } @@ -65,7 +65,7 @@ func TestTaskCacheKey(t *testing.T) { if err != nil { t.Errorf("unexpected error: %v", err) } - if string(initial) == string(have) { + if initial == have { t.Errorf("unexpected lack of change in key: %q", have) } @@ -77,7 +77,7 @@ func TestTaskCacheKey(t *testing.T) { if err != nil { t.Errorf("unexpected error: %v", err) } - if string(initial) == string(again) || string(have) == string(again) { + if initial == again || have == again { t.Errorf("unexpected lack of change in key: %q", again) } @@ -90,7 +90,7 @@ func TestTaskCacheKey(t *testing.T) { if err != nil { t.Errorf("unexpected error: %v", err) } - if string(initial) != string(have) { + if initial != have { t.Errorf("unexpected change in key: initial=%q have=%q", initial, have) } } @@ -165,17 +165,6 @@ func TestExecutionDiskCache_GetSet(t *testing.T) { assertCacheMiss(t, cache, cacheKey1) } -func assertFileDeleted(t *testing.T, path string) { - t.Helper() - if _, err := os.Stat(path); err == nil { - t.Fatalf("file exists: %s", path) - } else if os.IsNotExist(err) { - // Seems to be deleted, all good - } else { - t.Fatalf("could not determine whether file exists: %s", err) - } -} - func assertCacheHit(t *testing.T, c ExecutionDiskCache, k TaskCacheKey, want executionResult) { t.Helper() diff --git a/internal/batches/executor/executor.go b/internal/batches/executor/executor.go index 41fd052fb7..6a4fa353af 100644 --- a/internal/batches/executor/executor.go +++ b/internal/batches/executor/executor.go @@ -7,8 +7,9 @@ import ( "sync" "time" + "github.com/cockroachdb/errors" "github.com/neelance/parallel" - "github.com/pkg/errors" + "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/log" "github.com/sourcegraph/src-cli/internal/batches/workspace" diff --git a/internal/batches/executor/executor_test.go b/internal/batches/executor/executor_test.go index ca91b15927..d045efef75 100644 --- a/internal/batches/executor/executor_test.go +++ b/internal/batches/executor/executor_test.go @@ -14,12 +14,13 @@ import ( "testing" "time" + "github.com/cockroachdb/errors" "github.com/google/go-cmp/cmp" - "github.com/pkg/errors" "github.com/sourcegraph/go-diff/diff" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/git" "github.com/sourcegraph/sourcegraph/lib/batches/template" + "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/docker" @@ -368,10 +369,8 @@ func TestExecutor_Integration(t *testing.T) { } else { if err == nil { t.Fatalf("expected error to include %q, but got no error", tc.wantErrInclude) - } else { - if !strings.Contains(strings.ToLower(err.Error()), strings.ToLower(tc.wantErrInclude)) { - t.Errorf("wrong error. have=%q want included=%q", err, tc.wantErrInclude) - } + } else if !strings.Contains(strings.ToLower(err.Error()), strings.ToLower(tc.wantErrInclude)) { + t.Errorf("wrong error. have=%q want included=%q", err, tc.wantErrInclude) } } diff --git a/internal/batches/executor/run_steps.go b/internal/batches/executor/run_steps.go index 0e2b08c0a4..8f73df55d0 100644 --- a/internal/batches/executor/run_steps.go +++ b/internal/batches/executor/run_steps.go @@ -12,11 +12,12 @@ import ( "strings" "time" + "github.com/cockroachdb/errors" "github.com/hashicorp/go-multierror" - "github.com/pkg/errors" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/git" "github.com/sourcegraph/sourcegraph/lib/batches/template" + "github.com/sourcegraph/src-cli/internal/batches/log" "github.com/sourcegraph/src-cli/internal/batches/util" "github.com/sourcegraph/src-cli/internal/batches/workspace" @@ -142,7 +143,7 @@ func runSteps(ctx context.Context, opts *executionOpts) (result executionResult, stepContext.Steps.Changes = previousStepResult.Files stepContext.Outputs = opts.task.CachedResult.Outputs - if err := workspace.ApplyDiff(ctx, []byte(opts.task.CachedResult.Diff)); err != nil { + if err := workspace.ApplyDiff(ctx, opts.task.CachedResult.Diff); err != nil { return execResult, nil, errors.Wrap(err, "getting changed files in step") } } diff --git a/internal/batches/features.go b/internal/batches/features.go index a108974dfa..6a28a71e0c 100644 --- a/internal/batches/features.go +++ b/internal/batches/features.go @@ -1,7 +1,8 @@ package batches import ( - "github.com/pkg/errors" + "github.com/cockroachdb/errors" + "github.com/sourcegraph/src-cli/internal/api" ) diff --git a/internal/batches/log/task_logger.go b/internal/batches/log/task_logger.go index bb08751622..6f71fa0544 100644 --- a/internal/batches/log/task_logger.go +++ b/internal/batches/log/task_logger.go @@ -8,7 +8,7 @@ import ( "os" "time" - "github.com/pkg/errors" + "github.com/cockroachdb/errors" ) type TaskLogger interface { diff --git a/internal/batches/repo_fetcher.go b/internal/batches/repo_fetcher.go index 8915607e7f..b4417fe49b 100644 --- a/internal/batches/repo_fetcher.go +++ b/internal/batches/repo_fetcher.go @@ -11,7 +11,8 @@ import ( "strings" "sync" - "github.com/pkg/errors" + "github.com/cockroachdb/errors" + "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/batches/graphql" ) diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index 3932827e72..b22e882850 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -11,8 +11,9 @@ import ( "regexp" "strings" - "github.com/pkg/errors" + "github.com/cockroachdb/errors" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" + "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/docker" diff --git a/internal/batches/service/service_test.go b/internal/batches/service/service_test.go index d00eeee47c..026adb2680 100644 --- a/internal/batches/service/service_test.go +++ b/internal/batches/service/service_test.go @@ -11,6 +11,7 @@ import ( "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" + "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/graphql" @@ -492,10 +493,8 @@ func TestService_ValidateChangesetSpecs(t *testing.T) { if tt.wantErrInclude != "" { if haveErr == nil { t.Fatalf("expected %q to be included in error, but got none", tt.wantErrInclude) - } else { - if !strings.Contains(haveErr.Error(), tt.wantErrInclude) { - t.Fatalf("expected %q to be included in error, but was not. error=%q", tt.wantErrInclude, haveErr.Error()) - } + } else if !strings.Contains(haveErr.Error(), tt.wantErrInclude) { + t.Fatalf("expected %q to be included in error, but was not. error=%q", tt.wantErrInclude, haveErr.Error()) } } else { if haveErr != nil { diff --git a/internal/batches/ui/tui.go b/internal/batches/ui/tui.go index bc15ba9ba3..1817646464 100644 --- a/internal/batches/ui/tui.go +++ b/internal/batches/ui/tui.go @@ -5,10 +5,11 @@ import ( "fmt" "os/exec" + "github.com/cockroachdb/errors" "github.com/hashicorp/go-multierror" "github.com/neelance/parallel" - "github.com/pkg/errors" "github.com/sourcegraph/sourcegraph/lib/output" + "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/executor" diff --git a/internal/batches/workspace/bind_workspace.go b/internal/batches/workspace/bind_workspace.go index 02fd95e1f3..dfc61273b7 100644 --- a/internal/batches/workspace/bind_workspace.go +++ b/internal/batches/workspace/bind_workspace.go @@ -11,10 +11,11 @@ import ( "path/filepath" "strings" + "github.com/cockroachdb/errors" "github.com/hashicorp/go-multierror" - "github.com/pkg/errors" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/git" + "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/graphql" ) @@ -181,17 +182,6 @@ func (w *dockerBindWorkspace) ApplyDiff(ctx context.Context, diff []byte) error return err } -func fileExists(path string) (bool, error) { - _, err := os.Stat(path) - if err != nil { - if os.IsNotExist(err) { - return false, nil - } - return false, err - } - return true, nil -} - func unzipToTempDir(ctx context.Context, zipFile, tempDir, tempFilePrefix string) (string, error) { volumeDir, err := ioutil.TempDir(tempDir, tempFilePrefix) if err != nil { diff --git a/internal/batches/workspace/bind_workspace_nonwin_test.go b/internal/batches/workspace/bind_workspace_nonwin_test.go index a756d236b2..53ef016a0a 100644 --- a/internal/batches/workspace/bind_workspace_nonwin_test.go +++ b/internal/batches/workspace/bind_workspace_nonwin_test.go @@ -7,7 +7,7 @@ import ( "path/filepath" "testing" - "github.com/pkg/errors" + "github.com/cockroachdb/errors" ) func TestMkdirAllStatError(t *testing.T) { diff --git a/internal/batches/workspace/bind_workspace_windows_test.go b/internal/batches/workspace/bind_workspace_windows_test.go index 8c22d20565..f8b0069962 100644 --- a/internal/batches/workspace/bind_workspace_windows_test.go +++ b/internal/batches/workspace/bind_workspace_windows_test.go @@ -4,7 +4,7 @@ import ( "os" "testing" - "github.com/pkg/errors" + "github.com/cockroachdb/errors" ) func mustHavePerm(t *testing.T, path string, want os.FileMode) error { diff --git a/internal/batches/workspace/git.go b/internal/batches/workspace/git.go index 02e82ffe0e..d93834c998 100644 --- a/internal/batches/workspace/git.go +++ b/internal/batches/workspace/git.go @@ -5,7 +5,7 @@ import ( "os/exec" "strings" - "github.com/pkg/errors" + "github.com/cockroachdb/errors" ) func runGitCmd(ctx context.Context, dir string, args ...string) ([]byte, error) { diff --git a/internal/batches/workspace/volume_workspace.go b/internal/batches/workspace/volume_workspace.go index fa8d96d52c..b903101104 100644 --- a/internal/batches/workspace/volume_workspace.go +++ b/internal/batches/workspace/volume_workspace.go @@ -11,10 +11,11 @@ import ( "sort" "strings" - "github.com/pkg/errors" + "github.com/cockroachdb/errors" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/git" + "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/docker" "github.com/sourcegraph/src-cli/internal/batches/graphql" diff --git a/internal/batches/workspace/volume_workspace_test.go b/internal/batches/workspace/volume_workspace_test.go index a2226c2800..aa5b0b377c 100644 --- a/internal/batches/workspace/volume_workspace_test.go +++ b/internal/batches/workspace/volume_workspace_test.go @@ -9,11 +9,12 @@ import ( "strings" "testing" + "github.com/cockroachdb/errors" "github.com/google/go-cmp/cmp" - "github.com/pkg/errors" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/git" + "github.com/sourcegraph/src-cli/internal/batches/docker" "github.com/sourcegraph/src-cli/internal/batches/graphql" "github.com/sourcegraph/src-cli/internal/batches/mock" diff --git a/internal/batches/workspace/workspace.go b/internal/batches/workspace/workspace.go index d5c7a67871..b7a98855f8 100644 --- a/internal/batches/workspace/workspace.go +++ b/internal/batches/workspace/workspace.go @@ -4,9 +4,10 @@ import ( "context" "runtime" - "github.com/pkg/errors" + "github.com/cockroachdb/errors" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/git" + "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/docker" "github.com/sourcegraph/src-cli/internal/batches/graphql" diff --git a/internal/batches/workspace/workspace_test.go b/internal/batches/workspace/workspace_test.go index eca866569c..ecd6801b50 100644 --- a/internal/batches/workspace/workspace_test.go +++ b/internal/batches/workspace/workspace_test.go @@ -5,7 +5,8 @@ import ( "runtime" "testing" - "github.com/pkg/errors" + "github.com/cockroachdb/errors" + "github.com/sourcegraph/src-cli/internal/batches/docker" "github.com/sourcegraph/src-cli/internal/batches/mock" ) diff --git a/internal/cmderrors/errors.go b/internal/cmderrors/errors.go index 7af2bc6e39..44dbbf385a 100644 --- a/internal/cmderrors/errors.go +++ b/internal/cmderrors/errors.go @@ -1,8 +1,9 @@ package cmderrors import ( - "errors" "fmt" + + "github.com/cockroachdb/errors" ) // UsageError is an error type that subcommands can return in order to signal diff --git a/internal/exec/expect/expect.go b/internal/exec/expect/expect.go index 4802c6648e..e6c4f9ae4d 100644 --- a/internal/exec/expect/expect.go +++ b/internal/exec/expect/expect.go @@ -24,10 +24,10 @@ import ( goexec "os/exec" "testing" + "github.com/cockroachdb/errors" "github.com/gobwas/glob" "github.com/google/go-cmp/cmp" "github.com/hashicorp/go-multierror" - "github.com/pkg/errors" "github.com/sourcegraph/src-cli/internal/exec" ) diff --git a/internal/servegit/serve.go b/internal/servegit/serve.go index 741166840f..d26b376f1f 100644 --- a/internal/servegit/serve.go +++ b/internal/servegit/serve.go @@ -14,7 +14,7 @@ import ( "strings" "time" - "github.com/pkg/errors" + "github.com/cockroachdb/errors" "github.com/sourcegraph/sourcegraph/lib/gitservice" ) diff --git a/internal/streaming/api.go b/internal/streaming/api.go index 4f2f96c49e..5cd9d1c7da 100644 --- a/internal/streaming/api.go +++ b/internal/streaming/api.go @@ -81,5 +81,5 @@ type SkippedSeverity string const ( SeverityInfo SkippedSeverity = "info" - SeverityWarn = "warn" + SeverityWarn SkippedSeverity = "warn" ) diff --git a/internal/streaming/search.go b/internal/streaming/search.go index e85a1d960f..36bfb16cf8 100644 --- a/internal/streaming/search.go +++ b/internal/streaming/search.go @@ -47,7 +47,7 @@ func Search(query string, opts Opts, client api.Client, decoder Decoder) error { // Output trace. if opts.Trace { - _, err = fmt.Fprintf(os.Stderr, fmt.Sprintf("\nx-trace: %s\n", resp.Header.Get("x-trace"))) + _, err = fmt.Fprintf(os.Stderr, "\nx-trace: %s\n", resp.Header.Get("x-trace")) if err != nil { return err } diff --git a/internal/streaming/writer.go b/internal/streaming/writer.go index 12d74bad18..03a4e592d3 100644 --- a/internal/streaming/writer.go +++ b/internal/streaming/writer.go @@ -2,10 +2,11 @@ package streaming import ( "encoding/json" - "errors" "io" "net/http" "time" + + "github.com/cockroachdb/errors" ) type WriterStat struct { From 1c47706a178756ce43846c93e51032ce01f464f9 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Fri, 3 Sep 2021 01:54:28 +0200 Subject: [PATCH 024/647] Use latest lib version (#602) --- go.mod | 3 +-- go.sum | 23 +++++++++++------------ internal/batches/util/repo.go | 14 +++++--------- 3 files changed, 17 insertions(+), 23 deletions(-) diff --git a/go.mod b/go.mod index 664a746293..3843a78bb4 100644 --- a/go.mod +++ b/go.mod @@ -21,9 +21,8 @@ require ( github.com/sourcegraph/batch-change-utils v0.0.0-20210708162152-c9f35b905d94 github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf - github.com/sourcegraph/sourcegraph/lib v0.0.0-20210901142905-cc5a3f7fd279 + github.com/sourcegraph/sourcegraph/lib v0.0.0-20210902215418-71593bf836f9 github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect - github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect golang.org/x/net v0.0.0-20210614182718-04defd469f4e gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7 diff --git a/go.sum b/go.sum index c083130164..70b49503a4 100644 --- a/go.sum +++ b/go.sum @@ -22,14 +22,13 @@ github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGX github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= github.com/cockroachdb/datadriven v1.0.0/go.mod h1:5Ib8Meh+jk1RlHIXej6Pzevx/NLlNvQB9pmSBZErGA4= github.com/cockroachdb/errors v1.6.1/go.mod h1:tm6FTP5G81vwJ5lC0SizQo374JNCOPrHyXGitRJoDqM= -github.com/cockroachdb/errors v1.8.4/go.mod h1:GScl7wnuvY335l6h0jbkHIKJ+8uEmUmJRVWKnenUbfI= github.com/cockroachdb/errors v1.8.6 h1:Am9evxl/po3RzpokemQvq7S7Cd0mxv24xy0B/trlQF4= github.com/cockroachdb/errors v1.8.6/go.mod h1:hOm5fabihW+xEyY1kuypGwqT+Vt7rafg04ytBtIpeIQ= github.com/cockroachdb/logtags v0.0.0-20190617123548-eb05cc24525f h1:o/kfcElHqOiXqcou5a3rIlMc7oJbMQkeLk0VQJ7zgqY= github.com/cockroachdb/logtags v0.0.0-20190617123548-eb05cc24525f/go.mod h1:i/u985jwjWRlyHXQbwatDASoW0RMlZ/3i9yJHE2xLkI= -github.com/cockroachdb/redact v1.0.8/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= -github.com/cockroachdb/redact v1.1.1 h1:TNJ9tJHjtS7TrJR3n3DidvsQji8Av6Ecq8la9Xmn6SI= github.com/cockroachdb/redact v1.1.1/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= +github.com/cockroachdb/redact v1.1.3 h1:AKZds10rFSIj7qADf0g46UixK8NNLwWTNdCIGS5wfSQ= +github.com/cockroachdb/redact v1.1.3/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= github.com/cockroachdb/sentry-go v0.6.1-cockroachdb.2 h1:IKgmqgMQlVJIZj19CdocBeSfSaiCbEBZGKODaixqtHM= github.com/cockroachdb/sentry-go v0.6.1-cockroachdb.2/go.mod h1:8BT+cPK6xvFOcRlk0R8eg+OTkcqI6baNH4xAkpiYVvQ= github.com/codegangsta/inject v0.0.0-20150114235600-33e0aa1cb7c0/go.mod h1:4Zcjuz89kmFXt9morQgcfYZAYZ5n8WHjt81YYWIwtTM= @@ -79,10 +78,8 @@ github.com/gobwas/httphead v0.0.0-20180130184737-2c6c146eadee/go.mod h1:L0fX3K22 github.com/gobwas/pool v0.2.0/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw= github.com/gobwas/ws v1.0.2/go.mod h1:szmBTxLgaFppYjEmNtny/v3w89xOydFnnZMcgRRu/EM= github.com/gogo/googleapis v0.0.0-20180223154316-0cd9801be74a/go.mod h1:gf4bu3Q80BeJ6H1S1vYPm8/ELATdvryBaNFGgqEef3s= -github.com/gogo/googleapis v1.2.0/go.mod h1:Njal3psf3qN6dwBtQfUmBZh2ybovJ0tlu3o/AC7HYjU= github.com/gogo/googleapis v1.4.1/go.mod h1:2lpHqI5OcWCtVElxXnPt+s8oJvMpySlOyM6xDCrzib4= github.com/gogo/protobuf v1.2.0/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= -github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4= github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= @@ -158,7 +155,6 @@ github.com/kataras/neffos v0.0.10/go.mod h1:ZYmJC07hQPW67eKuzlfY7SO3bC0mw83A3j6i github.com/kataras/pio v0.0.0-20190103105442-ea782b38602d/go.mod h1:NV88laa9UiiDuX9AhMbDPkGYSPugBOV6yTZB1l2K9Z0= github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 h1:Z9n2FFNUXsshfwJMBgNA0RU6/i7WVaAegv3PtuIHPMs= github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51/go.mod h1:CzGEWj7cYgsdH8dAjBGEr58BoE7ScuLd+fwFZ44+/x8= -github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q= github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= @@ -170,8 +166,9 @@ github.com/klauspost/cpuid v1.2.1/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgo github.com/klauspost/pgzip v1.2.5 h1:qnWYvvKqedOF2ulHpMG72XQol4ILEJ8k2wwRl/Km8oE= github.com/klauspost/pgzip v1.2.5/go.mod h1:Ch1tH69qFZu15pkjo5kYi6mth2Zzwzt50oCQKQE9RUs= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= -github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI= github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= +github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= +github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= @@ -231,6 +228,7 @@ github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4 github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8= github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4 h1:49lOXmGaUpV9Fz3gd7TFZY106KVlPVa5jcYD1gaQf98= github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4/go.mod h1:4OwLy04Bl9Ef3GJJCoec+30X3LQs/0/m4HFRt/2LUSA= +github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= @@ -240,7 +238,10 @@ github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1: github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY= github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= +github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.6.2/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= +github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8= +github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= github.com/ryanuber/columnize v2.1.0+incompatible/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= github.com/sclevine/agouti v3.0.0+incompatible/go.mod h1:b4WX9W9L1sfQKXeJf1mUTLZKJ48R1S7H23Ji7oFO5Bw= @@ -257,8 +258,8 @@ github.com/sourcegraph/go-diff v0.6.1 h1:hmA1LzxW0n1c3Q4YbrFgg4P99GSnebYa3x8gr0H github.com/sourcegraph/go-diff v0.6.1/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20210901142905-cc5a3f7fd279 h1:RVrhk8J8Ob4J59BAFA5koKlC5pYfz3GCPpzN5R0+M3g= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20210901142905-cc5a3f7fd279/go.mod h1:8A6WlyQouL7Y5MUdL+2+An5rsysLYlm+DaZN/T3egwU= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20210902215418-71593bf836f9 h1:afOQUKamJAosvaIgAJKFrJ7BbQ06BxJLlNU2Z+wfzOc= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20210902215418-71593bf836f9/go.mod h1:ZK8mHKWdapYI8iIQwsO7QUxf44RjiNGKkOZa9aYIjTc= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= @@ -283,9 +284,8 @@ github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyC github.com/valyala/fasthttp v1.6.0/go.mod h1:FstJa9V+Pj9vQ7OJie2qMHdwemEDaDiSdBnvPM1Su9w= github.com/valyala/fasttemplate v1.0.1/go.mod h1:UQGH1tvbgY+Nz5t2n7tXsz52dQxojPUpymEIMZ47gx8= github.com/valyala/tcplisten v0.0.0-20161114210144-ceec8f93295a/go.mod h1:v3UYOV9WzVtRmSR+PDvWpU/qWl4Wa5LApYYX4ZtKbio= +github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f h1:J9EGpcZtP0E/raorCMxlFGSTBrsSlaDGf3jU/qvAE2c= github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= -github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb h1:zGWFAtiMcyryUHoUjUJX0/lt1H2+i2Ka2n+D3DImSNo= -github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0= github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74= @@ -375,7 +375,6 @@ golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20181221001348-537d06c36207/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= diff --git a/internal/batches/util/repo.go b/internal/batches/util/repo.go index ccab38fc80..43a1aa4184 100644 --- a/internal/batches/util/repo.go +++ b/internal/batches/util/repo.go @@ -2,19 +2,15 @@ package util import ( "github.com/sourcegraph/sourcegraph/lib/batches/template" + "github.com/sourcegraph/src-cli/internal/batches/graphql" ) // GraphQLRepoToTemplatingRepo transforms a given *graphql.Repository into a -// template.TemplatingRepository. -func GraphQLRepoToTemplatingRepo(r *graphql.Repository) template.TemplatingRepository { - return template.TemplatingRepository{ - ID: r.ID, - Name: r.Name, - DefaultBranch: template.TemplatingBranch{ - Name: r.DefaultBranch.Name, - TargetOID: r.DefaultBranch.Target.OID, - }, +// template.Repository. +func GraphQLRepoToTemplatingRepo(r *graphql.Repository) template.Repository { + return template.Repository{ + Name: r.Name, FileMatches: r.FileMatches, } } From 732041a3297aaa5a6c21d48f5c3e1bdfa7d10345 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Fri, 3 Sep 2021 02:00:20 +0200 Subject: [PATCH 025/647] Build src cli with Go 1.17 (#601) --- .github/workflows/go-ci.yml | 2 +- .github/workflows/go-lint.yml | 2 +- .github/workflows/goreleaser-check.yml | 2 +- .github/workflows/goreleaser.yml | 2 +- .tool-versions | 2 +- CHANGELOG.md | 1 + Dockerfile | 2 +- go.mod | 35 ++++++++++++++++--- go.sum | 9 +++-- internal/batches/debug.go | 2 +- .../workspace/bind_workspace_nonwin_test.go | 2 +- 11 files changed, 43 insertions(+), 18 deletions(-) diff --git a/.github/workflows/go-ci.yml b/.github/workflows/go-ci.yml index f94707ecc1..64ecc212e4 100644 --- a/.github/workflows/go-ci.yml +++ b/.github/workflows/go-ci.yml @@ -7,7 +7,7 @@ jobs: go-test: strategy: matrix: - go-version: [1.16.x] + go-version: [1.17.x] os: [ubuntu-latest, macos-latest, windows-latest] runs-on: ${{ matrix.os }} steps: diff --git a/.github/workflows/go-lint.yml b/.github/workflows/go-lint.yml index f4d3832c33..63ae30544a 100644 --- a/.github/workflows/go-lint.yml +++ b/.github/workflows/go-lint.yml @@ -12,5 +12,5 @@ jobs: - name: Set up Go uses: actions/setup-go@v2 with: - go-version: 1.16.x + go-version: 1.17.x - run: ./dev/go-lint.sh diff --git a/.github/workflows/goreleaser-check.yml b/.github/workflows/goreleaser-check.yml index 356cabbf94..676f25c84f 100644 --- a/.github/workflows/goreleaser-check.yml +++ b/.github/workflows/goreleaser-check.yml @@ -15,7 +15,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v2 with: - go-version: 1.16 + go-version: 1.17 - name: Check GoReleaser config uses: goreleaser/goreleaser-action@v2 with: diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index a50d121471..b12e1d662f 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -18,7 +18,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v2 with: - go-version: 1.16 + go-version: 1.17 - run: go get -d -t ./... - run: go test -i ./... - run: go test -race -v ./... diff --git a/.tool-versions b/.tool-versions index e00848fe19..b763344878 100644 --- a/.tool-versions +++ b/.tool-versions @@ -1 +1 @@ -golang 1.16.5 +golang 1.17 diff --git a/CHANGELOG.md b/CHANGELOG.md index d19b6cc223..58957aa58d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,7 @@ All notable changes to `src-cli` are documented in this file. - `src search -stream` displayed the number of lines that contain matches instead of the number of matches. - For internal use only: the `EXECUTING_TASKS` JSON log line now always contains an array of `tasks` instead of possibly having `null` as the `tasks` value. +- src-cli is now built using Go version 1.17. ### Removed diff --git a/Dockerfile b/Dockerfile index daee0fbd0f..2557eaca85 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,7 +4,7 @@ # # Nothing fancy here: we copy in the source code and build on the Alpine Go # image. Refer to .dockerignore to get a sense of what we're not going to copy. -FROM golang:1.16-alpine@sha256:6c35b28ceee082c621c818c097f418cd55104a16e51003120c1bf37111ed9cfe as builder +FROM golang:1.17-alpine@sha256:c03a922dfb0d6d3a94d46cc5be69002011763595ac2786068fde63ee174d797b as builder COPY . /src WORKDIR /src diff --git a/go.mod b/go.mod index 3843a78bb4..0e92c21fb9 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/sourcegraph/src-cli -go 1.16 +go 1.17 require ( github.com/Masterminds/semver v1.5.0 @@ -15,20 +15,45 @@ require ( github.com/mattn/go-isatty v0.0.12 github.com/mitchellh/copystructure v1.2.0 github.com/neelance/parallel v0.0.0-20160708114440-4de9ce63d14c - github.com/olekukonko/tablewriter v0.0.4 // indirect github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4 - github.com/rivo/uniseg v0.2.0 // indirect github.com/sourcegraph/batch-change-utils v0.0.0-20210708162152-c9f35b905d94 github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf github.com/sourcegraph/sourcegraph/lib v0.0.0-20210902215418-71593bf836f9 - github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect golang.org/x/net v0.0.0-20210614182718-04defd469f4e gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7 ) -replace github.com/gosuri/uilive v0.0.4 => github.com/mrnugget/uilive v0.0.4-fix-escape +require ( + github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect + github.com/cockroachdb/logtags v0.0.0-20190617123548-eb05cc24525f // indirect + github.com/cockroachdb/redact v1.1.3 // indirect + github.com/cockroachdb/sentry-go v0.6.1-cockroachdb.2 // indirect + github.com/ghodss/yaml v1.0.0 // indirect + github.com/gogo/protobuf v1.3.2 // indirect + github.com/hashicorp/errwrap v1.1.0 // indirect + github.com/klauspost/compress v1.12.2 // indirect + github.com/klauspost/pgzip v1.2.5 // indirect + github.com/kr/pretty v0.3.0 // indirect + github.com/kr/text v0.2.0 // indirect + github.com/mattn/go-runewidth v0.0.12 // indirect + github.com/mitchellh/reflectwalk v1.0.2 // indirect + github.com/moby/term v0.0.0-20210619224110-3f7ff695adc6 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.1 // indirect + github.com/olekukonko/tablewriter v0.0.5 // indirect + github.com/pkg/errors v0.9.1 // indirect + github.com/rivo/uniseg v0.1.0 // indirect + github.com/rogpeppe/go-internal v1.8.0 // indirect + github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect + github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f // indirect + github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect + github.com/xeipuuv/gojsonschema v1.2.0 // indirect + golang.org/x/sys v0.0.0-20210616094352-59db8d763f22 // indirect + golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect + gopkg.in/yaml.v2 v2.4.0 // indirect +) // See: https://github.com/ghodss/yaml/pull/65 replace github.com/ghodss/yaml => github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 diff --git a/go.sum b/go.sum index 70b49503a4..b8d3f8f2d4 100644 --- a/go.sum +++ b/go.sum @@ -183,7 +183,7 @@ github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hd github.com/mattn/go-isatty v0.0.9/go.mod h1:YNRxwqDuOph6SZLI9vUUz6OYw3QyUt7WiY2yME+cCiQ= github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY= github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= -github.com/mattn/go-runewidth v0.0.7/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= +github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/mattn/go-runewidth v0.0.12 h1:Y41i/hVW3Pgwr8gV+J23B9YEY0zxjptBuCWEaxmAOow= github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk= github.com/mattn/goveralls v0.0.2/go.mod h1:8d1ZMHsd7fW6IRPKQh46F2WRpyib5/X4FOpevwGNQEw= @@ -214,8 +214,8 @@ github.com/neelance/parallel v0.0.0-20160708114440-4de9ce63d14c/go.mod h1:eTBvSI github.com/nightlyone/lockfile v1.0.0/go.mod h1:rywoIealpdNse2r832aiD9jRk8ErCatROs6LzC841CI= github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= -github.com/olekukonko/tablewriter v0.0.4 h1:vHD/YYe1Wolo78koG299f7V/VAS08c6IpCLn+Ejf/w8= -github.com/olekukonko/tablewriter v0.0.4/go.mod h1:zq6QwlOf5SlnkVbMSr5EoBv3636FWnp+qbPhuoO21uA= +github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec= +github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= github.com/onsi/ginkgo v1.13.0/go.mod h1:+REjRxOmWfHCjfv9TTWB1jD1Frx4XydAD3zm1lskyM0= @@ -235,9 +235,8 @@ github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/rivo/uniseg v0.1.0 h1:+2KBaVoUmb9XzDsrx/Ct0W/EYOSFf/nWTauy++DprtY= github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= -github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY= -github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.6.2/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8= diff --git a/internal/batches/debug.go b/internal/batches/debug.go index efface6287..3a7310f664 100644 --- a/internal/batches/debug.go +++ b/internal/batches/debug.go @@ -1,4 +1,4 @@ -// +build debug +//go:build debug package batches diff --git a/internal/batches/workspace/bind_workspace_nonwin_test.go b/internal/batches/workspace/bind_workspace_nonwin_test.go index 53ef016a0a..f1e1286076 100644 --- a/internal/batches/workspace/bind_workspace_nonwin_test.go +++ b/internal/batches/workspace/bind_workspace_nonwin_test.go @@ -1,4 +1,4 @@ -// +build !windows +//go:build !windows package workspace From dfa59fad7e034e769fc22bd32e01e1e56f98aaad Mon Sep 17 00:00:00 2001 From: Camden Cheek Date: Thu, 2 Sep 2021 19:08:13 -0600 Subject: [PATCH 026/647] fix build directives --- internal/batches/debug.go | 1 + internal/batches/workspace/bind_workspace_nonwin_test.go | 1 + 2 files changed, 2 insertions(+) diff --git a/internal/batches/debug.go b/internal/batches/debug.go index 3a7310f664..c5754d63e7 100644 --- a/internal/batches/debug.go +++ b/internal/batches/debug.go @@ -1,4 +1,5 @@ //go:build debug +// +build debug package batches diff --git a/internal/batches/workspace/bind_workspace_nonwin_test.go b/internal/batches/workspace/bind_workspace_nonwin_test.go index f1e1286076..1be28755e6 100644 --- a/internal/batches/workspace/bind_workspace_nonwin_test.go +++ b/internal/batches/workspace/bind_workspace_nonwin_test.go @@ -1,4 +1,5 @@ //go:build !windows +// +build !windows package workspace From 7abfb959a9e96c75f76ae0a0934ed441bfa95f81 Mon Sep 17 00:00:00 2001 From: Thorsten Ball Date: Fri, 3 Sep 2021 10:47:55 +0200 Subject: [PATCH 027/647] text-only output: log stdout/stderr of steps (#597) This is part of sourcegraph/sourcegraph#23496 and adds the logging of STDOUT/STDERR of steps to the -text-only output. Please see the comment I left for more info on how the interface could be improved/extended. Also: turns out I don't need the process.Logger that was extracted in sourcegraph/sourcegraph#24545 and instead what's needed is the IntervalLogger here that flushes the captured output with a delay (so we don't create a new huge JSON message for every line) --- go.mod | 9 +- go.sum | 10 +- internal/batches/executor/coordinator.go | 5 +- internal/batches/executor/coordinator_test.go | 13 +++ internal/batches/executor/executor.go | 3 +- internal/batches/executor/run_steps.go | 24 +++- internal/batches/ui/interval_writer.go | 105 ++++++++++++++++++ internal/batches/ui/interval_writer_test.go | 63 +++++++++++ internal/batches/ui/json_lines.go | 51 ++++++++- internal/batches/ui/task_exec_tui.go | 19 +++- 10 files changed, 289 insertions(+), 13 deletions(-) create mode 100644 internal/batches/ui/interval_writer.go create mode 100644 internal/batches/ui/interval_writer_test.go diff --git a/go.mod b/go.mod index 0e92c21fb9..36ac973b5b 100644 --- a/go.mod +++ b/go.mod @@ -5,6 +5,8 @@ go 1.17 require ( github.com/Masterminds/semver v1.5.0 github.com/cockroachdb/errors v1.8.6 + github.com/cockroachdb/redact v1.1.3 // indirect + github.com/derision-test/glock v0.0.0-20210316032053-f5b74334bb29 github.com/dustin/go-humanize v1.0.0 github.com/gobwas/glob v0.2.3 github.com/google/go-cmp v0.5.6 @@ -19,7 +21,9 @@ require ( github.com/sourcegraph/batch-change-utils v0.0.0-20210708162152-c9f35b905d94 github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf - github.com/sourcegraph/sourcegraph/lib v0.0.0-20210902215418-71593bf836f9 + github.com/sourcegraph/sourcegraph/lib v0.0.0-20210903080558-3f16affc1edc + github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect + github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect golang.org/x/net v0.0.0-20210614182718-04defd469f4e gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7 @@ -28,7 +32,6 @@ require ( require ( github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect github.com/cockroachdb/logtags v0.0.0-20190617123548-eb05cc24525f // indirect - github.com/cockroachdb/redact v1.1.3 // indirect github.com/cockroachdb/sentry-go v0.6.1-cockroachdb.2 // indirect github.com/ghodss/yaml v1.0.0 // indirect github.com/gogo/protobuf v1.3.2 // indirect @@ -46,8 +49,6 @@ require ( github.com/pkg/errors v0.9.1 // indirect github.com/rivo/uniseg v0.1.0 // indirect github.com/rogpeppe/go-internal v1.8.0 // indirect - github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect - github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f // indirect github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect github.com/xeipuuv/gojsonschema v1.2.0 // indirect golang.org/x/sys v0.0.0-20210616094352-59db8d763f22 // indirect diff --git a/go.sum b/go.sum index b8d3f8f2d4..4b6d9b7748 100644 --- a/go.sum +++ b/go.sum @@ -43,6 +43,8 @@ github.com/dave/jennifer v1.4.1/go.mod h1:7jEdnm+qBcxl8PC0zyp7vxcpSRnzXSt9r39tpT github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/derision-test/glock v0.0.0-20210316032053-f5b74334bb29 h1:O07j7ewg0eFHRx+7bxCA/7z86HJexl7HLY9kyVMmPDo= +github.com/derision-test/glock v0.0.0-20210316032053-f5b74334bb29/go.mod h1:jKtLdBMrF+XQatqvg46wiWdDfDSSDjdhO4dOM2FX9H4= github.com/derision-test/go-mockgen v1.1.2/go.mod h1:9H3VGTWYnL1VJoHHCuPKDpPFmNQ1uVyNlpX6P63l5Sk= github.com/dgraph-io/badger v1.6.0/go.mod h1:zwt7syl517jmP8s94KqSxTlM6IMsdhYy6psNgSztDR4= github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= @@ -257,8 +259,8 @@ github.com/sourcegraph/go-diff v0.6.1 h1:hmA1LzxW0n1c3Q4YbrFgg4P99GSnebYa3x8gr0H github.com/sourcegraph/go-diff v0.6.1/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20210902215418-71593bf836f9 h1:afOQUKamJAosvaIgAJKFrJ7BbQ06BxJLlNU2Z+wfzOc= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20210902215418-71593bf836f9/go.mod h1:ZK8mHKWdapYI8iIQwsO7QUxf44RjiNGKkOZa9aYIjTc= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20210903080558-3f16affc1edc h1:iMV2Nc/fCn3PrG9vgFgXN2LdY6mDfcGuzQe9ObCT/U4= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20210903080558-3f16affc1edc/go.mod h1:ZK8mHKWdapYI8iIQwsO7QUxf44RjiNGKkOZa9aYIjTc= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= @@ -274,6 +276,7 @@ github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXf github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc= @@ -283,8 +286,9 @@ github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyC github.com/valyala/fasthttp v1.6.0/go.mod h1:FstJa9V+Pj9vQ7OJie2qMHdwemEDaDiSdBnvPM1Su9w= github.com/valyala/fasttemplate v1.0.1/go.mod h1:UQGH1tvbgY+Nz5t2n7tXsz52dQxojPUpymEIMZ47gx8= github.com/valyala/tcplisten v0.0.0-20161114210144-ceec8f93295a/go.mod h1:v3UYOV9WzVtRmSR+PDvWpU/qWl4Wa5LApYYX4ZtKbio= -github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f h1:J9EGpcZtP0E/raorCMxlFGSTBrsSlaDGf3jU/qvAE2c= github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= +github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb h1:zGWFAtiMcyryUHoUjUJX0/lt1H2+i2Ka2n+D3DImSNo= +github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0= github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74= diff --git a/internal/batches/executor/coordinator.go b/internal/batches/executor/coordinator.go index 01e5ae4597..093c34032c 100644 --- a/internal/batches/executor/coordinator.go +++ b/internal/batches/executor/coordinator.go @@ -2,6 +2,7 @@ package executor import ( "context" + "io" "reflect" "strconv" "time" @@ -9,7 +10,6 @@ import ( "github.com/cockroachdb/errors" "github.com/hashicorp/go-multierror" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" - "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/docker" @@ -217,6 +217,9 @@ type TaskExecutionUI interface { // TODO: This should be split up into methods that are more specific. TaskCurrentlyExecuting(*Task, string) + + StepStdoutWriter(context.Context, *Task, int) io.WriteCloser + StepStderrWriter(context.Context, *Task, int) io.WriteCloser } // Execute executes the given Tasks and the importChangeset statements in the diff --git a/internal/batches/executor/coordinator_test.go b/internal/batches/executor/coordinator_test.go index e314ddef35..5ed357d9b2 100644 --- a/internal/batches/executor/coordinator_test.go +++ b/internal/batches/executor/coordinator_test.go @@ -3,6 +3,7 @@ package executor import ( "context" "fmt" + "io" "strings" "sync" "testing" @@ -543,7 +544,19 @@ func (d *dummyTaskExecutionUI) TaskChangesetSpecsBuilt(t *Task, specs []*batches d.specs[t] = specs } +type discardCloser struct { + io.Writer +} + +func (discardCloser) Close() error { return nil } + func (d *dummyTaskExecutionUI) TaskCurrentlyExecuting(*Task, string) {} +func (d *dummyTaskExecutionUI) StepStdoutWriter(ctx context.Context, task *Task, step int) io.WriteCloser { + return discardCloser{io.Discard} +} +func (d *dummyTaskExecutionUI) StepStderrWriter(ctx context.Context, task *Task, step int) io.WriteCloser { + return discardCloser{io.Discard} +} var _ taskExecutor = &dummyExecutor{} diff --git a/internal/batches/executor/executor.go b/internal/batches/executor/executor.go index 6a4fa353af..6b245aefaa 100644 --- a/internal/batches/executor/executor.go +++ b/internal/batches/executor/executor.go @@ -177,6 +177,8 @@ func (x *executor) do(ctx context.Context, task *Task, ui TaskExecutionUI) (err reportProgress: func(currentlyExecuting string) { ui.TaskCurrentlyExecuting(task, currentlyExecuting) }, + newUiStdoutWriter: ui.StepStdoutWriter, + newUiStderrWriter: ui.StepStderrWriter, } result, stepResults, err := runSteps(runCtx, opts) @@ -191,7 +193,6 @@ func (x *executor) do(ctx context.Context, task *Task, ui TaskExecutionUI) (err return nil } - func (x *executor) addResult(task *Task, result executionResult, stepResults []stepExecutionResult) { x.resultsMu.Lock() defer x.resultsMu.Unlock() diff --git a/internal/batches/executor/run_steps.go b/internal/batches/executor/run_steps.go index 8f73df55d0..fe9e34ac01 100644 --- a/internal/batches/executor/run_steps.go +++ b/internal/batches/executor/run_steps.go @@ -22,6 +22,8 @@ import ( "github.com/sourcegraph/src-cli/internal/batches/util" "github.com/sourcegraph/src-cli/internal/batches/workspace" + "github.com/sourcegraph/sourcegraph/lib/process" + yamlv3 "gopkg.in/yaml.v3" ) @@ -65,6 +67,9 @@ type executionOpts struct { logger log.TaskLogger reportProgress func(string) + + newUiStdoutWriter func(context.Context, *Task, int) io.WriteCloser + newUiStderrWriter func(context.Context, *Task, int) io.WriteCloser } func runSteps(ctx context.Context, opts *executionOpts) (result executionResult, stepResults []stepExecutionResult, err error) { @@ -310,14 +315,29 @@ func executeSingleStep( var stdoutBuffer, stderrBuffer bytes.Buffer - cmd.Stdout = io.MultiWriter(&stdoutBuffer, opts.logger.PrefixWriter("stdout")) - cmd.Stderr = io.MultiWriter(&stderrBuffer, opts.logger.PrefixWriter("stderr")) + writerCtx, writerCancel := context.WithCancel(ctx) + defer writerCancel() + uiStdoutWriter := opts.newUiStdoutWriter(writerCtx, opts.task, i) + uiStderrWriter := opts.newUiStderrWriter(writerCtx, opts.task, i) + defer func() { + uiStdoutWriter.Close() + uiStderrWriter.Close() + }() + + stdout := io.MultiWriter(&stdoutBuffer, uiStdoutWriter, opts.logger.PrefixWriter("stdout")) + stderr := io.MultiWriter(&stderrBuffer, uiStderrWriter, opts.logger.PrefixWriter("stderr")) + + wg, err := process.PipeOutput(cmd, stdout, stderr) + if err != nil { + return bytes.Buffer{}, bytes.Buffer{}, errors.Wrap(err, "piping process output") + } opts.logger.Logf("[Step %d] run: %q, container: %q", i+1, step.Run, step.Container) opts.logger.Logf("[Step %d] full command: %q", i+1, strings.Join(cmd.Args, " ")) t0 := time.Now() err = cmd.Run() + wg.Wait() elapsed := time.Since(t0).Round(time.Millisecond) if err != nil { opts.logger.Logf("[Step %d] took %s; error running Docker container: %+v", i+1, elapsed, err) diff --git a/internal/batches/ui/interval_writer.go b/internal/batches/ui/interval_writer.go new file mode 100644 index 0000000000..71380b7518 --- /dev/null +++ b/internal/batches/ui/interval_writer.go @@ -0,0 +1,105 @@ +package ui + +import ( + "bytes" + "context" + "time" + + "github.com/derision-test/glock" +) + +// IntervalWriter is a io.Writer that flushes to the given sink on the given +// interval. +type IntervalWriter struct { + sink func(string) + + ticker glock.Ticker + + // buf is used to keep partial lines buffered before flushing them (either + // on the next newline or after tickDuration) + buf *bytes.Buffer + writes chan []byte + writesDone chan struct{} + + closed chan struct{} + done chan struct{} +} + +func newIntervalWriter(ctx context.Context, ticker glock.Ticker, sink func(string)) *IntervalWriter { + l := &IntervalWriter{ + sink: sink, + ticker: ticker, + + writes: make(chan []byte), + writesDone: make(chan struct{}), + + buf: &bytes.Buffer{}, + + closed: make(chan struct{}, 1), + done: make(chan struct{}, 1), + } + + go l.writeLines(ctx) + + return l +} + +// NewLogger returns a new Logger instance and spawns a goroutine in the +// background that regularily flushed the logged output to the given sink. +// +// If the passed in ctx is canceled the goroutine will exit. +func NewIntervalWriter(ctx context.Context, interval time.Duration, sink func(string)) *IntervalWriter { + return newIntervalWriter(ctx, glock.NewRealTicker(interval), sink) +} + +func (l *IntervalWriter) flush() { + if l.buf.Len() == 0 { + return + } + l.sink(l.buf.String()) + l.buf.Reset() +} + +// Close flushes the +func (l *IntervalWriter) Close() error { + l.closed <- struct{}{} + <-l.done + return nil +} + +// Write handler of IntervalWriter. +func (l *IntervalWriter) Write(p []byte) (int, error) { + l.writes <- p + <-l.writesDone + return len(p), nil +} + +func (l *IntervalWriter) writeLines(ctx context.Context) { + defer func() { + l.flush() + l.ticker.Stop() + l.done <- struct{}{} + }() + + for { + select { + case <-ctx.Done(): + return + + case <-l.closed: + return + + case w, ok := <-l.writes: + if !ok { + return + } + + if _, err := l.buf.Write(w); err != nil { + break + } + l.writesDone <- struct{}{} + case <-l.ticker.Chan(): + l.flush() + } + } +} diff --git a/internal/batches/ui/interval_writer_test.go b/internal/batches/ui/interval_writer_test.go new file mode 100644 index 0000000000..ec5bacdd40 --- /dev/null +++ b/internal/batches/ui/interval_writer_test.go @@ -0,0 +1,63 @@ +package ui + +import ( + "context" + "testing" + "time" + + "github.com/derision-test/glock" +) + +func TestIntervalWriter(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + + ch := make(chan string, 500) + + sink := func(data string) { + ch <- data + } + + ticker := glock.NewMockTicker(1 * time.Second) + writer := newIntervalWriter(ctx, ticker, sink) + + writer.Write([]byte("1")) + select { + case <-ch: + t.Fatalf("ch has data") + default: + } + + ticker.BlockingAdvance(1 * time.Second) + + select { + case d := <-ch: + if d != "1" { + t.Fatalf("wrong data in sink") + } + case <-time.After(1 * time.Second): + t.Fatalf("ch has NO data") + } + + writer.Write([]byte("2")) + writer.Write([]byte("3")) + writer.Write([]byte("4")) + writer.Write([]byte("5")) + + select { + case <-ch: + t.Fatalf("ch has data") + default: + } + + cancel() + writer.Close() + + select { + case d := <-ch: + if d != "2345" { + t.Fatalf("wrong data in sink") + } + case <-time.After(1 * time.Second): + t.Fatalf("ch has NO data") + } +} diff --git a/internal/batches/ui/json_lines.go b/internal/batches/ui/json_lines.go index 6202f111ab..c8d1c8ceb3 100644 --- a/internal/batches/ui/json_lines.go +++ b/internal/batches/ui/json_lines.go @@ -1,16 +1,19 @@ package ui import ( + "context" "encoding/json" "fmt" + "io" "os" "time" - batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/executor" "github.com/sourcegraph/src-cli/internal/batches/graphql" "github.com/sourcegraph/src-cli/internal/batches/workspace" + + batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" ) var _ ExecUI = &JSONLines{} @@ -292,6 +295,7 @@ func (ui *taskExecutionJSONLines) TaskCurrentlyExecuting(task *executor.Task, me if !ok { panic("unknown task started") } + logEvent(batchesLogEvent{ Operation: "EXECUTING_TASK", Status: "PROGRESS", @@ -301,3 +305,48 @@ func (ui *taskExecutionJSONLines) TaskCurrentlyExecuting(task *executor.Task, me }, }) } + +const stepFlushDuration = 500 * time.Millisecond + +func (ui *taskExecutionJSONLines) StepStdoutWriter(ctx context.Context, task *executor.Task, step int) io.WriteCloser { + lt, ok := ui.linesTasks[task] + if !ok { + panic("unknown task started") + } + + sink := func(data string) { + logEvent(batchesLogEvent{ + Operation: "STEP", + Status: "PROGRESS", + Message: data, + Metadata: map[string]interface{}{ + "task": lt, + "step": step, + "output_type": "stdout", + }, + }) + } + return NewIntervalWriter(ctx, stepFlushDuration, sink) +} + +func (ui *taskExecutionJSONLines) StepStderrWriter(ctx context.Context, task *executor.Task, step int) io.WriteCloser { + lt, ok := ui.linesTasks[task] + if !ok { + panic("unknown task started") + } + + sink := func(data string) { + logEvent(batchesLogEvent{ + Operation: "STEP", + Status: "PROGRESS", + Message: data, + Metadata: map[string]interface{}{ + "task": lt, + "step": step, + "output_type": "stderr", + }, + }) + } + + return NewIntervalWriter(ctx, stepFlushDuration, sink) +} diff --git a/internal/batches/ui/task_exec_tui.go b/internal/batches/ui/task_exec_tui.go index a6717f4b32..1e309f5dca 100644 --- a/internal/batches/ui/task_exec_tui.go +++ b/internal/batches/ui/task_exec_tui.go @@ -1,16 +1,19 @@ package ui import ( + "context" "fmt" + "io" "sort" "strings" "sync" "time" "github.com/sourcegraph/go-diff/diff" + "github.com/sourcegraph/src-cli/internal/batches/executor" + batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/output" - "github.com/sourcegraph/src-cli/internal/batches/executor" ) type taskStatus struct { @@ -215,6 +218,20 @@ func (ui *taskExecTUI) TaskCurrentlyExecuting(task *executor.Task, message strin ui.progress.StatusBarUpdatef(bar, ts.String()) } +type discardCloser struct { + io.Writer +} + +func (discardCloser) Close() error { return nil } + +func (ui *taskExecTUI) StepStdoutWriter(ctx context.Context, task *executor.Task, stepidx int) io.WriteCloser { + return discardCloser{io.Discard} +} + +func (ui *taskExecTUI) StepStderrWriter(ctx context.Context, task *executor.Task, stepidx int) io.WriteCloser { + return discardCloser{io.Discard} +} + func (ui *taskExecTUI) TaskFinished(task *executor.Task, err error) { ui.mu.Lock() defer ui.mu.Unlock() From 5b47424fc7773a0506fb2f13d67b80c62f6072af Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Fri, 3 Sep 2021 11:18:35 +0200 Subject: [PATCH 028/647] Refactor zipfetcher and consistently use rev, not baseref (#598) Before, sometimes we used Rev, sometimes BaseRef, which could in the worst case lead to inconsistencies. Search results might not match the fetched zip archive, or detected workspaces might differ from what's on disk in the end. --- internal/batches/errors.go | 6 - internal/batches/executor/changeset_specs.go | 22 ++- .../batches/executor/changeset_specs_test.go | 4 +- internal/batches/executor/coordinator.go | 21 +-- internal/batches/executor/coordinator_test.go | 5 +- internal/batches/executor/execution_cache.go | 9 +- internal/batches/executor/executor.go | 24 +-- internal/batches/executor/executor_test.go | 47 +++--- internal/batches/executor/run_steps.go | 6 +- internal/batches/executor/task.go | 5 +- internal/batches/graphql/batch_change.go | 6 +- internal/batches/graphql/batches.go | 8 +- internal/batches/graphql/campaigns.go | 8 +- internal/batches/graphql/namespace.go | 15 -- internal/batches/graphql/repository.go | 34 +--- internal/batches/main_test.go | 13 -- internal/batches/mock/repo_archive.go | 18 +-- .../{repo_fetcher.go => repozip/fetcher.go} | 146 ++++++++++-------- .../fetcher_test.go} | 73 ++++----- internal/batches/service/build_tasks.go | 1 + internal/batches/service/service.go | 2 +- internal/batches/service/workspaces.go | 14 +- internal/batches/service/workspaces_test.go | 4 +- internal/batches/util/repo.go | 36 ++++- internal/batches/workspace/bind_workspace.go | 7 +- .../batches/workspace/bind_workspace_test.go | 11 +- .../batches/workspace/volume_workspace.go | 4 +- internal/batches/workspace/workspace.go | 4 +- 28 files changed, 264 insertions(+), 289 deletions(-) delete mode 100644 internal/batches/graphql/namespace.go delete mode 100644 internal/batches/main_test.go rename internal/batches/{repo_fetcher.go => repozip/fetcher.go} (68%) rename internal/batches/{repo_fetcher_test.go => repozip/fetcher_test.go} (82%) diff --git a/internal/batches/errors.go b/internal/batches/errors.go index 763f7d78a2..13f8e4794a 100644 --- a/internal/batches/errors.go +++ b/internal/batches/errors.go @@ -77,9 +77,3 @@ func (e IgnoredRepoSet) Append(repo *graphql.Repository) { func (e IgnoredRepoSet) HasIgnored() bool { return len(e) > 0 } - -type ValidationError struct{ Reason string } - -func (e ValidationError) Error() string { - return fmt.Sprintf("validation failed: %s", e.Reason) -} diff --git a/internal/batches/executor/changeset_specs.go b/internal/batches/executor/changeset_specs.go index 37df8b350b..6178b48643 100644 --- a/internal/batches/executor/changeset_specs.go +++ b/internal/batches/executor/changeset_specs.go @@ -13,11 +13,9 @@ import ( "github.com/sourcegraph/src-cli/internal/batches/util" ) -var errOptionalPublishedUnsupported = errors.New(`This Sourcegraph version requires the "published" field to be specified in the batch spec; upgrade to version 3.30.0 or later to be able to omit the published field and control publication from the UI.`) +var errOptionalPublishedUnsupported = batcheslib.NewValidationError(errors.New(`This Sourcegraph version requires the "published" field to be specified in the batch spec; upgrade to version 3.30.0 or later to be able to omit the published field and control publication from the UI.`)) func createChangesetSpecs(task *Task, result executionResult, features batches.FeatureFlags) ([]*batcheslib.ChangesetSpec, error) { - repo := task.Repository.Name - tmplCtx := &template.ChangesetTemplateContext{ BatchChangeAttributes: *task.BatchChangeAttributes, Steps: template.StepsContext{ @@ -25,7 +23,7 @@ func createChangesetSpecs(task *Task, result executionResult, features batches.F Path: result.Path, }, Outputs: result.Outputs, - Repository: util.GraphQLRepoToTemplatingRepo(task.Repository), + Repository: util.NewTemplatingRepo(task.Repository.Name, task.Repository.FileMatches), } var authorName string @@ -75,7 +73,7 @@ func createChangesetSpecs(task *Task, result executionResult, features batches.F newSpec := func(branch, diff string) (*batcheslib.ChangesetSpec, error) { var published interface{} = nil if task.Template.Published != nil { - published = task.Template.Published.ValueWithSuffix(repo, branch) + published = task.Template.Published.ValueWithSuffix(task.Repository.Name, branch) // Backward compatibility: before optional published fields were // allowed, ValueWithSuffix() would fall back to false, not nil. We @@ -93,7 +91,7 @@ func createChangesetSpecs(task *Task, result executionResult, features batches.F BaseRef: task.Repository.BaseRef(), BaseRev: task.Repository.Rev(), HeadRepository: task.Repository.ID, - HeadRef: "refs/heads/" + branch, + HeadRef: util.EnsureRefPrefix(branch), Title: title, Body: body, Commits: []batcheslib.GitCommitDescription{ @@ -141,8 +139,8 @@ func createChangesetSpecs(task *Task, result executionResult, features batches.F return specs, nil } -func groupsForRepository(repo string, transform *batcheslib.TransformChanges) []batcheslib.Group { - var groups []batcheslib.Group +func groupsForRepository(repoName string, transform *batcheslib.TransformChanges) []batcheslib.Group { + groups := []batcheslib.Group{} if transform == nil { return groups @@ -150,7 +148,7 @@ func groupsForRepository(repo string, transform *batcheslib.TransformChanges) [] for _, g := range transform.Group { if g.Repository != "" { - if g.Repository == repo { + if g.Repository == repoName { groups = append(groups, g) } } else { @@ -161,18 +159,18 @@ func groupsForRepository(repo string, transform *batcheslib.TransformChanges) [] return groups } -func validateGroups(repo, defaultBranch string, groups []batcheslib.Group) error { +func validateGroups(repoName, defaultBranch string, groups []batcheslib.Group) error { uniqueBranches := make(map[string]struct{}, len(groups)) for _, g := range groups { if _, ok := uniqueBranches[g.Branch]; ok { - return fmt.Errorf("transformChanges would lead to multiple changesets in repository %s to have the same branch %q", repo, g.Branch) + return batcheslib.NewValidationError(fmt.Errorf("transformChanges would lead to multiple changesets in repository %s to have the same branch %q", repoName, g.Branch)) } else { uniqueBranches[g.Branch] = struct{}{} } if g.Branch == defaultBranch { - return fmt.Errorf("transformChanges group branch for repository %s is the same as branch %q in changesetTemplate", repo, defaultBranch) + return batcheslib.NewValidationError(fmt.Errorf("transformChanges group branch for repository %s is the same as branch %q in changesetTemplate", repoName, defaultBranch)) } } diff --git a/internal/batches/executor/changeset_specs_test.go b/internal/batches/executor/changeset_specs_test.go index c4d081d81f..0a0b49f415 100644 --- a/internal/batches/executor/changeset_specs_test.go +++ b/internal/batches/executor/changeset_specs_test.go @@ -17,8 +17,8 @@ func TestCreateChangesetSpecs(t *testing.T) { defaultChangesetSpec := &batcheslib.ChangesetSpec{ BaseRepository: testRepo1.ID, - BaseRef: testRepo1.DefaultBranch.Name, - BaseRev: testRepo1.DefaultBranch.Target.OID, + BaseRef: testRepo1.BaseRef(), + BaseRev: testRepo1.Rev(), HeadRepository: testRepo1.ID, HeadRef: "refs/heads/my-branch", Title: "The title", diff --git a/internal/batches/executor/coordinator.go b/internal/batches/executor/coordinator.go index 093c34032c..90bc3b7d5e 100644 --- a/internal/batches/executor/coordinator.go +++ b/internal/batches/executor/coordinator.go @@ -10,11 +10,13 @@ import ( "github.com/cockroachdb/errors" "github.com/hashicorp/go-multierror" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" + "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/docker" "github.com/sourcegraph/src-cli/internal/batches/graphql" "github.com/sourcegraph/src-cli/internal/batches/log" + "github.com/sourcegraph/src-cli/internal/batches/repozip" "github.com/sourcegraph/src-cli/internal/batches/workspace" ) @@ -67,15 +69,14 @@ func NewCoordinator(opts NewCoordinatorOpts) *Coordinator { logManager := log.NewManager(opts.TempDir, opts.KeepLogs) exec := newExecutor(newExecutorOpts{ - Fetcher: batches.NewRepoFetcher(opts.Client, opts.CacheDir, opts.CleanArchives), - EnsureImage: opts.EnsureImage, - Creator: opts.Creator, - Logger: logManager, - - AutoAuthorDetails: opts.Features.IncludeAutoAuthorDetails, - Parallelism: opts.Parallelism, - Timeout: opts.Timeout, - TempDir: opts.TempDir, + RepoArchiveRegistry: repozip.NewArchiveRegistry(opts.Client, opts.CacheDir, opts.CleanArchives), + EnsureImage: opts.EnsureImage, + Creator: opts.Creator, + Logger: logManager, + + Parallelism: opts.Parallelism, + Timeout: opts.Timeout, + TempDir: opts.TempDir, }) return &Coordinator{ @@ -290,7 +291,7 @@ func (c *Coordinator) Execute(ctx context.Context, tasks []*Task, spec *batchesl case float64: sid = strconv.FormatFloat(tid, 'f', -1, 64) default: - return nil, nil, errors.Errorf("cannot convert value of type %T into a valid external ID: expected string or int", id) + return nil, nil, batcheslib.NewValidationError(errors.Errorf("cannot convert value of type %T into a valid external ID: expected string or int", id)) } specs = append(specs, &batcheslib.ChangesetSpec{ diff --git a/internal/batches/executor/coordinator_test.go b/internal/batches/executor/coordinator_test.go index 5ed357d9b2..ae740aa790 100644 --- a/internal/batches/executor/coordinator_test.go +++ b/internal/batches/executor/coordinator_test.go @@ -17,6 +17,7 @@ import ( "github.com/sourcegraph/src-cli/internal/batches/graphql" "github.com/sourcegraph/src-cli/internal/batches/mock" + "github.com/sourcegraph/src-cli/internal/batches/util" ) func TestCoordinator_Execute(t *testing.T) { @@ -31,7 +32,7 @@ func TestCoordinator_Execute(t *testing.T) { BaseRef: repo.BaseRef(), BaseRev: repo.Rev(), HeadRepository: repo.ID, - HeadRef: "refs/heads/" + testChangesetTemplate.Branch, + HeadRef: util.EnsureRefPrefix(testChangesetTemplate.Branch), Title: testChangesetTemplate.Title, Body: testChangesetTemplate.Body, Commits: []batcheslib.GitCommitDescription{ @@ -217,7 +218,7 @@ func TestCoordinator_Execute(t *testing.T) { spec.Commits[0].Diff = nestedChangesDiffSubdirC }), buildSpecFor(testRepo2, func(spec *batcheslib.ChangesetSpec) { - spec.HeadRef = "refs/heads/" + testChangesetTemplate.Branch + spec.HeadRef = util.EnsureRefPrefix(testChangesetTemplate.Branch) spec.Commits[0].Diff = nestedChangesDiffSubdirA }), }, diff --git a/internal/batches/executor/execution_cache.go b/internal/batches/executor/execution_cache.go index 1f1f6341dd..1b092a4ee3 100644 --- a/internal/batches/executor/execution_cache.go +++ b/internal/batches/executor/execution_cache.go @@ -12,6 +12,7 @@ import ( "github.com/cockroachdb/errors" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" + "github.com/sourcegraph/src-cli/internal/batches/util" ) func UserCacheDir() (string, error) { @@ -101,7 +102,9 @@ func (key StepsCacheKey) Key() (string, error) { return fmt.Sprintf("%s-step-%d", hash, key.StepIndex), err } -func (key StepsCacheKey) Slug() string { return key.Repository.Slug() } +func (key StepsCacheKey) Slug() string { + return util.SlugForRepo(key.Repository.Name, key.Repository.Rev()) +} // TaskCacheKey implements the CacheKeyer interface for a Task and all its // Steps. @@ -132,7 +135,9 @@ func (key TaskCacheKey) Key() (string, error) { return base64.RawURLEncoding.EncodeToString(hash[:16]), nil } -func (key TaskCacheKey) Slug() string { return key.Repository.Slug() } +func (key TaskCacheKey) Slug() string { + return util.SlugForRepo(key.Repository.Name, key.Repository.Rev()) +} type ExecutionCache interface { Get(ctx context.Context, key CacheKeyer) (result executionResult, found bool, err error) diff --git a/internal/batches/executor/executor.go b/internal/batches/executor/executor.go index 6b245aefaa..8a5f291ea4 100644 --- a/internal/batches/executor/executor.go +++ b/internal/batches/executor/executor.go @@ -10,8 +10,9 @@ import ( "github.com/cockroachdb/errors" "github.com/neelance/parallel" - "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/log" + "github.com/sourcegraph/src-cli/internal/batches/repozip" + "github.com/sourcegraph/src-cli/internal/batches/util" "github.com/sourcegraph/src-cli/internal/batches/workspace" ) @@ -50,16 +51,15 @@ type taskResult struct { type newExecutorOpts struct { // Dependencies - Creator workspace.Creator - Fetcher batches.RepoFetcher - EnsureImage imageEnsurer - Logger log.LogManager + Creator workspace.Creator + RepoArchiveRegistry repozip.ArchiveRegistry + EnsureImage imageEnsurer + Logger log.LogManager // Config - AutoAuthorDetails bool - Parallelism int - Timeout time.Duration - TempDir string + Parallelism int + Timeout time.Duration + TempDir string } type executor struct { @@ -144,7 +144,7 @@ func (x *executor) do(ctx context.Context, task *Task, ui TaskExecutionUI) (err ui.TaskStarted(task) // Let's set up our logging. - log, err := x.opts.Logger.AddTask(task.Repository.SlugForPath(task.Path)) + log, err := x.opts.Logger.AddTask(util.SlugForPathInRepo(task.Repository.Name, task.Repository.Rev(), task.Path)) if err != nil { return errors.Wrap(err, "creating log file") } @@ -160,8 +160,8 @@ func (x *executor) do(ctx context.Context, task *Task, ui TaskExecutionUI) (err log.Close() }() - // Now checkout the archive - task.Archive = x.opts.Fetcher.Checkout(task.Repository, task.ArchivePathToFetch()) + // Now checkout the archive. + task.Archive = x.opts.RepoArchiveRegistry.Checkout(repozip.RepoRevision{RepoName: task.Repository.Name, Commit: task.Repository.Rev()}, task.ArchivePathToFetch()) // Set up our timeout. runCtx, cancel := context.WithTimeout(ctx, x.opts.Timeout) diff --git a/internal/batches/executor/executor_test.go b/internal/batches/executor/executor_test.go index d045efef75..4490e38d3b 100644 --- a/internal/batches/executor/executor_test.go +++ b/internal/batches/executor/executor_test.go @@ -25,6 +25,7 @@ import ( "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/docker" "github.com/sourcegraph/src-cli/internal/batches/mock" + "github.com/sourcegraph/src-cli/internal/batches/repozip" "github.com/sourcegraph/src-cli/internal/batches/workspace" ) @@ -71,11 +72,11 @@ func TestExecutor_Integration(t *testing.T) { { name: "success", archives: []mock.RepoArchive{ - {Repo: testRepo1, Files: map[string]string{ + {RepoName: testRepo1.Name, Commit: testRepo1.Rev(), Files: map[string]string{ "README.md": "# Welcome to the README\n", "main.go": "package main\n\nfunc main() {\n\tfmt.Println( \"Hello World\")\n}\n", }}, - {Repo: testRepo2, Files: map[string]string{ + {RepoName: testRepo2.Name, Commit: testRepo2.Rev(), Files: map[string]string{ "README.md": "# Sourcegraph README\n", }}, }, @@ -100,7 +101,7 @@ func TestExecutor_Integration(t *testing.T) { { name: "empty", archives: []mock.RepoArchive{ - {Repo: testRepo1, Files: map[string]string{ + {RepoName: testRepo1.Name, Commit: testRepo1.Rev(), Files: map[string]string{ "README.md": "# Welcome to the README\n", "main.go": "package main\n\nfunc main() {\n\tfmt.Println( \"Hello World\")\n}\n", }}, @@ -123,7 +124,7 @@ func TestExecutor_Integration(t *testing.T) { { name: "timeout", archives: []mock.RepoArchive{ - {Repo: testRepo1, Files: map[string]string{"README.md": "line 1"}}, + {RepoName: testRepo1.Name, Commit: testRepo1.Rev(), Files: map[string]string{"README.md": "line 1"}}, }, steps: []batcheslib.Step{ // This needs to be a loop, because when a process goes to sleep @@ -143,7 +144,7 @@ func TestExecutor_Integration(t *testing.T) { { name: "templated steps", archives: []mock.RepoArchive{ - {Repo: testRepo1, Files: map[string]string{ + {RepoName: testRepo1.Name, Commit: testRepo1.Rev(), Files: map[string]string{ "README.md": "# Welcome to the README\n", "main.go": "package main\n\nfunc main() {\n\tfmt.Println( \"Hello World\")\n}\n", }}, @@ -181,24 +182,24 @@ func TestExecutor_Integration(t *testing.T) { { name: "workspaces", archives: []mock.RepoArchive{ - {Repo: testRepo1, Path: "", Files: map[string]string{ + {RepoName: testRepo1.Name, Commit: testRepo1.Rev(), Path: "", Files: map[string]string{ ".gitignore": "node_modules", "message.txt": "root-dir", "a/message.txt": "a-dir", "a/.gitignore": "node_modules-in-a", "a/b/message.txt": "b-dir", }}, - {Repo: testRepo1, Path: "a", Files: map[string]string{ + {RepoName: testRepo1.Name, Commit: testRepo1.Rev(), Path: "a", Files: map[string]string{ "a/message.txt": "a-dir", "a/.gitignore": "node_modules-in-a", "a/b/message.txt": "b-dir", }}, - {Repo: testRepo1, Path: "a/b", Files: map[string]string{ + {RepoName: testRepo1.Name, Commit: testRepo1.Rev(), Path: "a/b", Files: map[string]string{ "a/b/message.txt": "b-dir", }}, }, additionalFiles: []mock.MockRepoAdditionalFiles{ - {Repo: testRepo1, AdditionalFiles: map[string]string{ + {RepoName: testRepo1.Name, Commit: testRepo1.Rev(), AdditionalFiles: map[string]string{ ".gitignore": "node_modules", "a/.gitignore": "node_modules-in-a", }}, @@ -236,10 +237,10 @@ func TestExecutor_Integration(t *testing.T) { { name: "step condition", archives: []mock.RepoArchive{ - {Repo: testRepo1, Files: map[string]string{ + {RepoName: testRepo1.Name, Commit: testRepo1.Rev(), Files: map[string]string{ "README.md": "# Welcome to the README\n", }}, - {Repo: testRepo2, Files: map[string]string{ + {RepoName: testRepo2.Name, Commit: testRepo2.Rev(), Files: map[string]string{ "README.md": "# Sourcegraph README\n", }}, }, @@ -271,10 +272,10 @@ func TestExecutor_Integration(t *testing.T) { { name: "skips errors", archives: []mock.RepoArchive{ - {Repo: testRepo1, Files: map[string]string{ + {RepoName: testRepo1.Name, Commit: testRepo1.Rev(), Files: map[string]string{ "README.md": "# Welcome to the README\n", }}, - {Repo: testRepo2, Files: map[string]string{ + {RepoName: testRepo2.Name, Commit: testRepo2.Rev(), Files: map[string]string{ "README.md": "# Sourcegraph README\n", }}, }, @@ -341,10 +342,10 @@ func TestExecutor_Integration(t *testing.T) { // Setup executor opts := newExecutorOpts{ - Creator: workspace.NewCreator(context.Background(), "bind", testTempDir, testTempDir, images), - Fetcher: batches.NewRepoFetcher(client, testTempDir, false), - Logger: mock.LogNoOpManager{}, - EnsureImage: imageMapEnsurer(images), + Creator: workspace.NewCreator(context.Background(), "bind", testTempDir, testTempDir, images), + RepoArchiveRegistry: repozip.NewArchiveRegistry(client, testTempDir, false), + Logger: mock.LogNoOpManager{}, + EnsureImage: imageMapEnsurer(images), TempDir: testTempDir, Parallelism: runtime.GOMAXPROCS(0), @@ -473,7 +474,7 @@ func featuresAllEnabled() batches.FeatureFlags { func TestExecutor_CachedStepResults(t *testing.T) { t.Run("single step cached", func(t *testing.T) { archive := mock.RepoArchive{ - Repo: testRepo1, Files: map[string]string{ + RepoName: testRepo1.Name, Commit: testRepo1.Rev(), Files: map[string]string{ "README.md": "# Welcome to the README\n", }, } @@ -530,7 +531,7 @@ index 02a19af..c9644dd 100644 t.Run("one of multiple steps cached", func(t *testing.T) { archive := mock.RepoArchive{ - Repo: testRepo1, + RepoName: testRepo1.Name, Commit: testRepo1.Rev(), Files: map[string]string{ "README.md": `# automation-testing This repository is used to test opening and closing pull request with Automation @@ -693,10 +694,10 @@ func testExecuteTasks(t *testing.T, tasks []*Task, archives ...mock.RepoArchive) // Setup executor executor := newExecutor(newExecutorOpts{ - Creator: workspace.NewCreator(context.Background(), "bind", testTempDir, testTempDir, images), - Fetcher: batches.NewRepoFetcher(client, testTempDir, false), - Logger: mock.LogNoOpManager{}, - EnsureImage: imageMapEnsurer(images), + Creator: workspace.NewCreator(context.Background(), "bind", testTempDir, testTempDir, images), + RepoArchiveRegistry: repozip.NewArchiveRegistry(client, testTempDir, false), + Logger: mock.LogNoOpManager{}, + EnsureImage: imageMapEnsurer(images), TempDir: testTempDir, Parallelism: runtime.GOMAXPROCS(0), diff --git a/internal/batches/executor/run_steps.go b/internal/batches/executor/run_steps.go index fe9e34ac01..6dcb66eac8 100644 --- a/internal/batches/executor/run_steps.go +++ b/internal/batches/executor/run_steps.go @@ -74,7 +74,7 @@ type executionOpts struct { func runSteps(ctx context.Context, opts *executionOpts) (result executionResult, stepResults []stepExecutionResult, err error) { opts.reportProgress("Downloading archive") - err = opts.task.Archive.Fetch(ctx) + err = opts.task.Archive.Ensure(ctx) if err != nil { return executionResult{}, nil, errors.Wrap(err, "fetching repo") } @@ -132,7 +132,7 @@ func runSteps(ctx context.Context, opts *executionOpts) (result executionResult, stepContext := template.StepContext{ BatchChange: *opts.task.BatchChangeAttributes, - Repository: util.GraphQLRepoToTemplatingRepo(opts.task.Repository), + Repository: util.NewTemplatingRepo(opts.task.Repository.Name, opts.task.Repository.FileMatches), Outputs: execResult.Outputs, Steps: template.StepsContext{ Path: execResult.Path, @@ -235,7 +235,7 @@ func executeSingleStep( // ---------- opts.reportProgress(fmt.Sprintf("Preparing step %d", i+1)) - cidFile, cleanup, err := createCidFile(ctx, opts.tempDir, opts.task.Repository.Slug()) + cidFile, cleanup, err := createCidFile(ctx, opts.tempDir, util.SlugForRepo(opts.task.Repository.Name, opts.task.Repository.Rev())) if err != nil { return bytes.Buffer{}, bytes.Buffer{}, err } diff --git a/internal/batches/executor/task.go b/internal/batches/executor/task.go index ffbb820c11..8de89b013a 100644 --- a/internal/batches/executor/task.go +++ b/internal/batches/executor/task.go @@ -3,8 +3,9 @@ package executor import ( batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/template" - "github.com/sourcegraph/src-cli/internal/batches" + "github.com/sourcegraph/src-cli/internal/batches/graphql" + "github.com/sourcegraph/src-cli/internal/batches/repozip" ) type Task struct { @@ -27,7 +28,7 @@ type Task struct { Template *batcheslib.ChangesetTemplate `json:"-"` TransformChanges *batcheslib.TransformChanges `json:"-"` - Archive batches.RepoZip `json:"-"` + Archive repozip.Archive `json:"-"` CachedResultFound bool `json:"-"` CachedResult stepExecutionResult `json:"-"` diff --git a/internal/batches/graphql/batch_change.go b/internal/batches/graphql/batch_change.go index db6ad5fd7a..d29ee33c2e 100644 --- a/internal/batches/graphql/batch_change.go +++ b/internal/batches/graphql/batch_change.go @@ -1,9 +1,5 @@ package graphql type BatchChange struct { - ID string - Namespace Namespace - Name string - Description string - URL string + URL string } diff --git a/internal/batches/graphql/batches.go b/internal/batches/graphql/batches.go index 0d31dff915..54fd1f26d8 100644 --- a/internal/batches/graphql/batches.go +++ b/internal/batches/graphql/batches.go @@ -18,15 +18,9 @@ mutation ApplyBatchChange($batchSpec: ID!) { } fragment batchChangeFields on BatchChange { - id - namespace { - ...namespaceFields - } - name - description url } -` + NamespaceFieldsFragment +` func (bb *batchesBackend) ApplyBatchChange(ctx context.Context, batchSpecID BatchSpecID) (*BatchChange, error) { var result struct { diff --git a/internal/batches/graphql/campaigns.go b/internal/batches/graphql/campaigns.go index 3d58d6b239..a45abffef4 100644 --- a/internal/batches/graphql/campaigns.go +++ b/internal/batches/graphql/campaigns.go @@ -16,15 +16,9 @@ mutation ApplyCampaign($campaignSpec: ID!) { } fragment campaignFields on Campaign { - id - namespace { - ...namespaceFields - } - name - description url } -` + NamespaceFieldsFragment +` func (cb *campaignsBackend) ApplyBatchChange(ctx context.Context, batchSpecID BatchSpecID) (*BatchChange, error) { var result struct { diff --git a/internal/batches/graphql/namespace.go b/internal/batches/graphql/namespace.go deleted file mode 100644 index b2957eb519..0000000000 --- a/internal/batches/graphql/namespace.go +++ /dev/null @@ -1,15 +0,0 @@ -package graphql - -const NamespaceFieldsFragment = ` -fragment namespaceFields on Namespace { - id - namespaceName - url -} -` - -type Namespace struct { - ID string - NamespaceName string - URL string -} diff --git a/internal/batches/graphql/repository.go b/internal/batches/graphql/repository.go index d08b756fbc..eed5732f34 100644 --- a/internal/batches/graphql/repository.go +++ b/internal/batches/graphql/repository.go @@ -1,16 +1,11 @@ package graphql -import ( - "crypto/sha256" - "encoding/base64" - "strings" -) +import "github.com/sourcegraph/src-cli/internal/batches/util" const RepositoryFieldsFragment = ` fragment repositoryFields on Repository { id name - url externalRepository { serviceType } @@ -38,7 +33,6 @@ type Branch struct { type Repository struct { ID string Name string - URL string ExternalRepository struct{ ServiceType string } DefaultBranch *Branch @@ -57,17 +51,10 @@ func (r *Repository) HasBranch() bool { func (r *Repository) BaseRef() string { if r.Branch.Name != "" { - return ensurePrefix(r.Branch.Name) + return util.EnsureRefPrefix(r.Branch.Name) } - return r.DefaultBranch.Name -} - -func ensurePrefix(rev string) string { - if strings.HasPrefix(rev, "refs/heads/") { - return rev - } - return "refs/heads/" + rev + return util.EnsureRefPrefix(r.DefaultBranch.Name) } func (r *Repository) Rev() string { @@ -77,18 +64,3 @@ func (r *Repository) Rev() string { return r.DefaultBranch.Target.OID } - -func (r *Repository) Slug() string { - return strings.ReplaceAll(r.Name, "/", "-") + "-" + r.Rev() -} - -func (r *Repository) SlugForPath(path string) string { - name := r.Name - if path != "" { - // Since path can contain os.PathSeparator or other characters that - // don't translate well between Windows and Unix systems, we hash it. - hash := sha256.Sum256([]byte(path)) - name = name + "-" + base64.RawURLEncoding.EncodeToString(hash[:32]) - } - return strings.ReplaceAll(name, "/", "-") + "-" + r.Rev() -} diff --git a/internal/batches/main_test.go b/internal/batches/main_test.go deleted file mode 100644 index 143ad1637f..0000000000 --- a/internal/batches/main_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package batches - -import ( - "os" - "testing" - - "github.com/sourcegraph/src-cli/internal/exec/expect" -) - -func TestMain(m *testing.M) { - code := expect.Handle(m) - os.Exit(code) -} diff --git a/internal/batches/mock/repo_archive.go b/internal/batches/mock/repo_archive.go index b753234ab3..a9b842221b 100644 --- a/internal/batches/mock/repo_archive.go +++ b/internal/batches/mock/repo_archive.go @@ -8,14 +8,13 @@ import ( "net/http" "path/filepath" "testing" - - "github.com/sourcegraph/src-cli/internal/batches/graphql" ) type RepoArchive struct { - Repo *graphql.Repository - Path string - Files map[string]string + RepoName string + Commit string + Path string + Files map[string]string } func NewZipArchivesMux(t *testing.T, callback http.HandlerFunc, archives ...RepoArchive) *http.ServeMux { @@ -23,12 +22,12 @@ func NewZipArchivesMux(t *testing.T, callback http.HandlerFunc, archives ...Repo for _, archive := range archives { files := archive.Files - path := fmt.Sprintf("/%s@%s/-/raw", archive.Repo.Name, archive.Repo.BaseRef()) + path := fmt.Sprintf("/%s@%s/-/raw", archive.RepoName, archive.Commit) if archive.Path != "" { path = path + "/" + archive.Path } - downloadName := filepath.Base(archive.Repo.Name) + downloadName := filepath.Base(archive.RepoName) mediaType := mime.FormatMediaType("Attachment", map[string]string{ "filename": downloadName, }) @@ -64,13 +63,14 @@ func NewZipArchivesMux(t *testing.T, callback http.HandlerFunc, archives ...Repo type middleware func(http.Handler) http.Handler type MockRepoAdditionalFiles struct { - Repo *graphql.Repository + RepoName string + Commit string AdditionalFiles map[string]string } func HandleAdditionalFiles(mux *http.ServeMux, files MockRepoAdditionalFiles, middle middleware) { for name, content := range files.AdditionalFiles { - path := fmt.Sprintf("/%s@%s/-/raw/%s", files.Repo.Name, files.Repo.BaseRef(), name) + path := fmt.Sprintf("/%s@%s/-/raw/%s", files.RepoName, files.Commit, name) handler := func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/plain") diff --git a/internal/batches/repo_fetcher.go b/internal/batches/repozip/fetcher.go similarity index 68% rename from internal/batches/repo_fetcher.go rename to internal/batches/repozip/fetcher.go index b4417fe49b..0e4f5de18e 100644 --- a/internal/batches/repo_fetcher.go +++ b/internal/batches/repozip/fetcher.go @@ -1,4 +1,4 @@ -package batches +package repozip import ( "context" @@ -13,63 +13,105 @@ import ( "github.com/cockroachdb/errors" - "github.com/sourcegraph/src-cli/internal/api" - "github.com/sourcegraph/src-cli/internal/batches/graphql" + "github.com/sourcegraph/src-cli/internal/batches/util" ) -// RepoFetcher abstracts the process of retrieving an archive for the given +type RepoRevision struct { + RepoName string + Commit string +} + +// ArchiveRegistry abstracts the process of retrieving an archive for the given // repository. -type RepoFetcher interface { - // Checkout returns a RepoZip for the given repository and the given - // relative path in the repository. The RepoZip is possibly unfetched. - // Users need to call `Fetch()` on the RepoZip before using it and +type ArchiveRegistry interface { + // Checkout returns an Archive for the given repository and the given + // relative path in the repository. The Archive is possibly unfetched. + // Users need to call `Ensure()` on the Archive before using it and // `Close()` once // they're done using it. - Checkout(repo *graphql.Repository, path string) RepoZip + Checkout(repo RepoRevision, path string) Archive +} + +// Archive implementations represent a downloaded repository archive. +type Archive interface { + // Ensure downloads the archive if it's not on disk yet. + Ensure(context.Context) error + + // Close must finalize the downloaded archive. If one or more temporary + // files were created, they should be deleted here. + Close() error + + // Path must return the path to the archive on the filesystem. + Path() string + + // AdditionalFilePaths returns a map of filenames that should be put into + // the workspace's root. The value of each entry in the map is the location + // on the local filesystem. WorkspaceCreators need to copy the files into + // the workspaces. + AdditionalFilePaths() map[string]string +} + +// HTTPClient provides an interface to run API requests. +type HTTPClient interface { + // NewHTTPRequest creates an http.Request for the Sourcegraph API. + // + // path is joined against the API route. For example on Sourcegraph.com this + // will result the URL: https://sourcegraph.com/.api/path. + NewHTTPRequest(ctx context.Context, method, path string, body io.Reader) (*http.Request, error) + + // Do runs an http.Request against the Sourcegraph API. + Do(req *http.Request) (*http.Response, error) } -func NewRepoFetcher(client api.Client, dir string, deleteZips bool) RepoFetcher { - return &repoFetcher{client: client, dir: dir, deleteZips: deleteZips} +func NewArchiveRegistry(client HTTPClient, dir string, deleteZips bool) ArchiveRegistry { + return &archiveRegistry{client: client, dir: dir, deleteZips: deleteZips} } -// repoFetcher is the concrete implementation of the RepoFetcher interface used +// archiveRegistry is the concrete implementation of the ArchiveRegistry interface used // outside of tests. -type repoFetcher struct { - client api.Client +type archiveRegistry struct { + client HTTPClient dir string deleteZips bool zipsMu sync.Mutex - zips map[string]*repoZip + zips map[string]*repoArchive } -var _ RepoFetcher = &repoFetcher{} +func (rf *archiveRegistry) Checkout(repo RepoRevision, path string) Archive { + zip := rf.zipFor(repo, path) + zip.mu.Lock() + defer zip.mu.Unlock() + + zip.checkouts += 1 + return zip +} -// AdditionalWorkspaceFiles is a list of files the RepoFetcher *tries* to fetch +// additionalWorkspaceFiles is a list of files the Archive *tries* to fetch // when the desired archive is subdirectory in the given repository. It makes // sense to also fetch these files, even if the steps are executed in a // subdirectory, since they might influence some global state, such as // `.gitignore`. // // If the file is not found, that's not an error. -var AdditionalWorkspaceFiles = []string{ +var additionalWorkspaceFiles = []string{ ".gitignore", ".gitattributes", } -func (rf *repoFetcher) zipFor(repo *graphql.Repository, workspacePath string) *repoZip { +func (rf *archiveRegistry) zipFor(repo RepoRevision, workspacePath string) *repoArchive { rf.zipsMu.Lock() defer rf.zipsMu.Unlock() if rf.zips == nil { - rf.zips = make(map[string]*repoZip) + rf.zips = make(map[string]*repoArchive) } - slug := repo.SlugForPath(workspacePath) + slug := util.SlugForPathInRepo(repo.RepoName, repo.Commit, workspacePath) zipPath := filepath.Join(rf.dir, slug+".zip") zip, ok := rf.zips[zipPath] if !ok { - zip = &repoZip{ + zip = &repoArchive{ zipPath: zipPath, repo: repo, client: rf.client, @@ -79,7 +121,7 @@ func (rf *repoFetcher) zipFor(repo *graphql.Repository, workspacePath string) *r if workspacePath != "" { // We're doing another loop here to catch all - // AdditionalWorkspaceFiles on the way *up* from the workspace to the + // additionalWorkspaceFiles on the way *up* from the workspace to the // root. // // Example: path = /examples/cool/project3 @@ -99,9 +141,9 @@ func (rf *repoFetcher) zipFor(repo *graphql.Repository, workspacePath string) *r var currentPath string for _, component := range pathComponents { - for _, name := range []string{".gitignore", ".gitattributes"} { + for _, name := range additionalWorkspaceFiles { filename := path.Join(currentPath, name) - localPath := filepath.Join(rf.dir, repo.SlugForPath(workspacePath+filename)) + localPath := filepath.Join(rf.dir, util.SlugForPathInRepo(repo.RepoName, repo.Commit, workspacePath+filename)) zip.additionalFiles = append(zip.additionalFiles, &additionalFile{ filename: filename, @@ -119,47 +161,19 @@ func (rf *repoFetcher) zipFor(repo *graphql.Repository, workspacePath string) *r return zip } -func (rf *repoFetcher) Checkout(repo *graphql.Repository, path string) RepoZip { - zip := rf.zipFor(repo, path) - zip.mu.Lock() - defer zip.mu.Unlock() - - zip.checkouts += 1 - return zip -} - -// RepoZip implementations represent a downloaded repository archive. -type RepoZip interface { - // Fetch downloads the archive if it's not on disk yet. - Fetch(context.Context) error - - // Close must finalise the downloaded archive. If one or more temporary - // files were created, they should be deleted here. - Close() error - - // Path must return the path to the archive on the filesystem. - Path() string - - // AdditionalFilePaths returns a map of filenames that should be put into - // the workspace's root. The value of each entry in the map is the location - // on the local filesystem. WorkspaceCreators need to copy the files into - // the workspaces. - AdditionalFilePaths() map[string]string -} - -var _ RepoZip = &repoZip{} +var _ Archive = &repoArchive{} -// repoZip is the concrete implementation of the RepoZip interface used outside +// repoArchive is the concrete implementation of the Archive interface used outside // of tests. -type repoZip struct { +type repoArchive struct { mu sync.Mutex deleteOnClose bool - repo *graphql.Repository + repo RepoRevision pathInRepo string - client api.Client + client HTTPClient // zipPath is the path of the downloaded ZIP archive on the local filesystem. zipPath string @@ -180,7 +194,7 @@ type additionalFile struct { fetched bool } -func (rz *repoZip) Close() error { +func (rz *repoArchive) Close() error { rz.mu.Lock() defer rz.mu.Unlock() @@ -200,11 +214,11 @@ func (rz *repoZip) Close() error { return nil } -func (rz *repoZip) Path() string { +func (rz *repoArchive) Path() string { return rz.zipPath } -func (rz *repoZip) AdditionalFilePaths() map[string]string { +func (rz *repoArchive) AdditionalFilePaths() map[string]string { paths := map[string]string{} for _, f := range rz.additionalFiles { if f.fetched { @@ -214,7 +228,7 @@ func (rz *repoZip) AdditionalFilePaths() map[string]string { return paths } -func (rz *repoZip) Fetch(ctx context.Context) (err error) { +func (rz *repoArchive) Ensure(ctx context.Context) (err error) { rz.mu.Lock() defer rz.mu.Unlock() @@ -234,7 +248,7 @@ func (rz *repoZip) Fetch(ctx context.Context) (err error) { return nil } -func (rz *repoZip) fetchArchiveAndFiles(ctx context.Context) (err error) { +func (rz *repoArchive) fetchArchiveAndFiles(ctx context.Context) (err error) { defer func() { if err != nil { // If the context got cancelled, or we ran out of disk space, or ... @@ -298,7 +312,7 @@ func (rz *repoZip) fetchArchiveAndFiles(ctx context.Context) (err error) { // raw endpoint and writes it to `dest`. // If `pathInRepo` is empty and `dest` ends in `.zip` a ZIP archive of the // whole repository is downloaded. -func fetchRepositoryFile(ctx context.Context, client api.Client, repo *graphql.Repository, pathInRepo string, dest string) (bool, error) { +func fetchRepositoryFile(ctx context.Context, client HTTPClient, repo RepoRevision, pathInRepo string, dest string) (bool, error) { endpoint := repositoryRawFileEndpoint(repo, pathInRepo) req, err := client.NewHTTPRequest(ctx, "GET", endpoint, nil) if err != nil { @@ -335,8 +349,8 @@ func fetchRepositoryFile(ctx context.Context, client api.Client, repo *graphql.R return true, nil } -func repositoryRawFileEndpoint(repo *graphql.Repository, pathInRepo string) string { - p := path.Join(repo.Name+"@"+repo.BaseRef(), "-", "raw") +func repositoryRawFileEndpoint(repo RepoRevision, pathInRepo string) string { + p := path.Join(repo.RepoName+"@"+repo.Commit, "-", "raw") if pathInRepo != "" { p = path.Join(p, pathInRepo) } diff --git a/internal/batches/repo_fetcher_test.go b/internal/batches/repozip/fetcher_test.go similarity index 82% rename from internal/batches/repo_fetcher_test.go rename to internal/batches/repozip/fetcher_test.go index 0bec61de45..3587c1e0bd 100644 --- a/internal/batches/repo_fetcher_test.go +++ b/internal/batches/repozip/fetcher_test.go @@ -1,4 +1,4 @@ -package batches +package repozip import ( "bytes" @@ -15,12 +15,13 @@ import ( "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" + "github.com/sourcegraph/src-cli/internal/api" - "github.com/sourcegraph/src-cli/internal/batches/graphql" "github.com/sourcegraph/src-cli/internal/batches/mock" + "github.com/sourcegraph/src-cli/internal/batches/util" ) -func TestRepoFetcher_Fetch(t *testing.T) { +func TestArchive_Ensure(t *testing.T) { workspaceTmpDir := func(t *testing.T) string { testTempDir, err := ioutil.TempDir("", "executor-integration-test-*") if err != nil { @@ -31,14 +32,14 @@ func TestRepoFetcher_Fetch(t *testing.T) { return testTempDir } - repo := &graphql.Repository{ - ID: "src-cli", - Name: "github.com/sourcegraph/src-cli", - DefaultBranch: &graphql.Branch{Name: "main", Target: graphql.Target{OID: "d34db33f"}}, + repo := RepoRevision{ + RepoName: "github.com/sourcegraph/src-cli", + Commit: "d34db33f", } archive := mock.RepoArchive{ - Repo: repo, + RepoName: repo.RepoName, + Commit: repo.Commit, Files: map[string]string{ "README.md": "# Welcome to the README\n", }, @@ -56,19 +57,19 @@ func TestRepoFetcher_Fetch(t *testing.T) { var clientBuffer bytes.Buffer client := api.NewClient(api.ClientOpts{Endpoint: ts.URL, Out: &clientBuffer}) - rf := &repoFetcher{ + rf := &archiveRegistry{ client: client, dir: workspaceTmpDir(t), deleteZips: false, } zip := rf.Checkout(repo, "") - err := zip.Fetch(context.Background()) + err := zip.Ensure(context.Background()) if err != nil { t.Errorf("unexpected error: %s", err) } - wantZipFile := repo.Slug() + ".zip" + wantZipFile := util.SlugForRepo(repo.RepoName, repo.Commit) + ".zip" ok, err := dirContains(rf.dir, wantZipFile) if err != nil { t.Fatal(err) @@ -83,7 +84,7 @@ func TestRepoFetcher_Fetch(t *testing.T) { zip.Close() // Create it a second time and make sure that the server wasn't called - err = zip.Fetch(context.Background()) + err = zip.Ensure(context.Background()) if err != nil { t.Fatalf("unexpected error: %s", err) } @@ -101,7 +102,7 @@ func TestRepoFetcher_Fetch(t *testing.T) { var clientBuffer bytes.Buffer client := api.NewClient(api.ClientOpts{Endpoint: ts.URL, Out: &clientBuffer}) - rf := &repoFetcher{ + rf := &archiveRegistry{ client: client, dir: workspaceTmpDir(t), deleteZips: true, @@ -109,12 +110,12 @@ func TestRepoFetcher_Fetch(t *testing.T) { zip := rf.Checkout(repo, "") - err := zip.Fetch(context.Background()) + err := zip.Ensure(context.Background()) if err != nil { t.Errorf("unexpected error: %s", err) } - wantZipFile := repo.Slug() + ".zip" + wantZipFile := util.SlugForRepo(repo.RepoName, repo.Commit) + ".zip" ok, err := dirContains(rf.dir, wantZipFile) if err != nil { t.Fatal(err) @@ -165,18 +166,18 @@ func TestRepoFetcher_Fetch(t *testing.T) { var clientBuffer bytes.Buffer client := api.NewClient(api.ClientOpts{Endpoint: ts.URL, Out: &clientBuffer}) - rf := &repoFetcher{ + rf := &archiveRegistry{ client: client, dir: workspaceTmpDir(t), deleteZips: false, } zip := rf.Checkout(repo, "") - if err := zip.Fetch(ctx); err == nil { + if err := zip.Ensure(ctx); err == nil { t.Error("error is nil") } - zipFile := repo.Slug() + ".zip" + zipFile := util.SlugForRepo(repo.RepoName, repo.Commit) + ".zip" ok, err := dirContains(rf.dir, zipFile) if err != nil { t.Error(err) @@ -188,16 +189,16 @@ func TestRepoFetcher_Fetch(t *testing.T) { t.Run("non-default branch", func(t *testing.T) { otherBranchOID := "f00b4r" - repo := &graphql.Repository{ - ID: "src-cli-with-non-main-branch", - Name: "github.com/sourcegraph/src-cli", - DefaultBranch: &graphql.Branch{Name: "main", Target: graphql.Target{OID: "d34db33f"}}, - - Commit: graphql.Target{OID: otherBranchOID}, - Branch: graphql.Branch{Name: "other-branch", Target: graphql.Target{OID: otherBranchOID}}, + repo := RepoRevision{ + RepoName: "github.com/sourcegraph/src-cli", + Commit: otherBranchOID, } - archive := mock.RepoArchive{Repo: repo, Files: map[string]string{}} + archive := mock.RepoArchive{ + RepoName: repo.RepoName, + Commit: repo.Commit, + Files: map[string]string{}, + } ts := httptest.NewServer(mock.NewZipArchivesMux(t, nil, archive)) defer ts.Close() @@ -205,19 +206,19 @@ func TestRepoFetcher_Fetch(t *testing.T) { var clientBuffer bytes.Buffer client := api.NewClient(api.ClientOpts{Endpoint: ts.URL, Out: &clientBuffer}) - rf := &repoFetcher{ + rf := &archiveRegistry{ client: client, dir: workspaceTmpDir(t), deleteZips: false, } zip := rf.Checkout(repo, "") - err := zip.Fetch(context.Background()) + err := zip.Ensure(context.Background()) if err != nil { t.Fatalf("unexpected error: %s", err) } - wantZipFile := repo.Slug() + ".zip" + wantZipFile := util.SlugForRepo(repo.RepoName, repo.Commit) + ".zip" ok, err := dirContains(rf.dir, wantZipFile) if err != nil { t.Fatal(err) @@ -229,7 +230,8 @@ func TestRepoFetcher_Fetch(t *testing.T) { t.Run("path in repository", func(t *testing.T) { additionalFiles := mock.MockRepoAdditionalFiles{ - Repo: repo, + RepoName: repo.RepoName, + Commit: repo.Commit, AdditionalFiles: map[string]string{ ".gitignore": "node_modules", ".gitattributes": "* -text", @@ -239,8 +241,9 @@ func TestRepoFetcher_Fetch(t *testing.T) { path := "a/b" archive := mock.RepoArchive{ - Repo: repo, - Path: path, + RepoName: repo.RepoName, + Commit: repo.Commit, + Path: path, Files: map[string]string{ "a/b/1.txt": "this is 1", "a/b/2.txt": "this is 1", @@ -272,14 +275,14 @@ func TestRepoFetcher_Fetch(t *testing.T) { var clientBuffer bytes.Buffer client := api.NewClient(api.ClientOpts{Endpoint: ts.URL, Out: &clientBuffer}) - rf := &repoFetcher{ + rf := &archiveRegistry{ client: client, dir: workspaceTmpDir(t), deleteZips: false, } zip := rf.Checkout(repo, path) - err := zip.Fetch(context.Background()) + err := zip.Ensure(context.Background()) if err != nil { t.Fatalf("unexpected error: %s", err) } @@ -293,7 +296,7 @@ func TestRepoFetcher_Fetch(t *testing.T) { t.Errorf("wrong paths requested (-want +got):\n%s", cmp.Diff(wantRequestedFiles, requestedFiles)) } - wantZipFile := repo.SlugForPath(path) + ".zip" + wantZipFile := util.SlugForPathInRepo(repo.RepoName, repo.Commit, path) + ".zip" ok, err := dirContains(rf.dir, wantZipFile) if err != nil { t.Fatal(err) diff --git a/internal/batches/service/build_tasks.go b/internal/batches/service/build_tasks.go index 726aa10979..c3c1957a46 100644 --- a/internal/batches/service/build_tasks.go +++ b/internal/batches/service/build_tasks.go @@ -5,6 +5,7 @@ import ( batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/template" + "github.com/sourcegraph/src-cli/internal/batches/executor" ) diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index b22e882850..1031930ccf 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -653,7 +653,7 @@ func (svc *Service) FindDirectoriesInRepos(ctx context.Context, fileName string, a.WriteString("query DirectoriesContainingFile {\n") for _, repo := range batch { - query := fmt.Sprintf(`file:(^|/)%s$ repo:^%s$@%s type:path count:99999`, regexp.QuoteMeta(fileName), repo.BaseRef(), regexp.QuoteMeta(repo.Name)) + query := fmt.Sprintf(`file:(^|/)%s$ repo:^%s$@%s type:path count:99999`, regexp.QuoteMeta(fileName), repo.Rev(), regexp.QuoteMeta(repo.Name)) a.WriteString(fmt.Sprintf(searchQueryTmpl, queryIDByRepo[repo], query)) } diff --git a/internal/batches/service/workspaces.go b/internal/batches/service/workspaces.go index c67d7c62e4..b0cfa14b51 100644 --- a/internal/batches/service/workspaces.go +++ b/internal/batches/service/workspaces.go @@ -2,13 +2,13 @@ package service import ( "context" - "fmt" "sort" + "github.com/cockroachdb/errors" "github.com/gobwas/glob" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/template" - "github.com/sourcegraph/src-cli/internal/batches" + "github.com/sourcegraph/src-cli/internal/batches/graphql" "github.com/sourcegraph/src-cli/internal/batches/util" ) @@ -45,7 +45,7 @@ func findWorkspaces( for _, conf := range spec.Workspaces { g, err := glob.Compile(conf.In) if err != nil { - return nil, batches.ValidationError{Reason: fmt.Sprintf("failed to compile glob %q: %v", conf.In, err)} + return nil, batcheslib.NewValidationError(errors.Errorf("failed to compile glob %q: %v", conf.In, err)) } workspaceMatchers[conf] = g } @@ -66,7 +66,7 @@ func findWorkspaces( // Don't allow duplicate matches. if found { - return nil, batches.ValidationError{Reason: fmt.Sprintf("repository %s matches multiple workspaces.in globs in the batch spec. glob: %q", repo.Name, conf.In)} + return nil, batcheslib.NewValidationError(errors.Errorf("repository %s matches multiple workspaces.in globs in the batch spec. glob: %q", repo.Name, conf.In)) } matched[idx] = append(matched[idx], repo) @@ -126,7 +126,7 @@ func findWorkspaces( fetchWorkspace = false } - steps, err := stepsForRepo(spec, workspace.Repo) + steps, err := stepsForRepo(spec, util.NewTemplatingRepo(workspace.Repo.Name, workspace.Repo.FileMatches)) if err != nil { return nil, err } @@ -157,7 +157,7 @@ func findWorkspaces( } // stepsForRepo calculates the steps required to run on the given repo. -func stepsForRepo(spec *batcheslib.BatchSpec, r *graphql.Repository) ([]batcheslib.Step, error) { +func stepsForRepo(spec *batcheslib.BatchSpec, repo template.Repository) ([]batcheslib.Step, error) { taskSteps := []batcheslib.Step{} for _, step := range spec.Steps { // If no if condition is given, just go ahead and add the step to the list. @@ -171,7 +171,7 @@ func stepsForRepo(spec *batcheslib.BatchSpec, r *graphql.Repository) ([]batchesl Description: spec.Description, } stepCtx := &template.StepContext{ - Repository: util.GraphQLRepoToTemplatingRepo(r), + Repository: repo, BatchChange: batchChange, } static, boolVal, err := template.IsStaticBool(step.IfCondition(), stepCtx) diff --git a/internal/batches/service/workspaces_test.go b/internal/batches/service/workspaces_test.go index 09b1871fea..9686d5c47d 100644 --- a/internal/batches/service/workspaces_test.go +++ b/internal/batches/service/workspaces_test.go @@ -8,7 +8,9 @@ import ( "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" + "github.com/sourcegraph/src-cli/internal/batches/graphql" + "github.com/sourcegraph/src-cli/internal/batches/util" ) func TestFindWorkspaces(t *testing.T) { @@ -258,7 +260,7 @@ func TestStepsForRepo(t *testing.T) { for name, tt := range tests { t.Run(name, func(t *testing.T) { - haveSteps, err := stepsForRepo(tt.spec, testRepo1) + haveSteps, err := stepsForRepo(tt.spec, util.NewTemplatingRepo(testRepo1.Name, testRepo1.FileMatches)) if err != nil { t.Fatalf("unexpected err: %s", err) } diff --git a/internal/batches/util/repo.go b/internal/batches/util/repo.go index 43a1aa4184..a481cbdf6e 100644 --- a/internal/batches/util/repo.go +++ b/internal/batches/util/repo.go @@ -1,16 +1,40 @@ package util import ( - "github.com/sourcegraph/sourcegraph/lib/batches/template" + "crypto/sha256" + "encoding/base64" + "strings" - "github.com/sourcegraph/src-cli/internal/batches/graphql" + "github.com/sourcegraph/sourcegraph/lib/batches/template" ) -// GraphQLRepoToTemplatingRepo transforms a given *graphql.Repository into a +// NewTemplatingRepo transforms a given *graphql.Repository into a // template.Repository. -func GraphQLRepoToTemplatingRepo(r *graphql.Repository) template.Repository { +func NewTemplatingRepo(repoName string, fileMatches map[string]bool) template.Repository { return template.Repository{ - Name: r.Name, - FileMatches: r.FileMatches, + Name: repoName, + FileMatches: fileMatches, + } +} + +func SlugForPathInRepo(repoName, commit, path string) string { + name := repoName + if path != "" { + // Since path can contain os.PathSeparator or other characters that + // don't translate well between Windows and Unix systems, we hash it. + hash := sha256.Sum256([]byte(path)) + name = name + "-" + base64.RawURLEncoding.EncodeToString(hash[:32]) + } + return strings.ReplaceAll(name, "/", "-") + "-" + commit +} + +func SlugForRepo(repoName, commit string) string { + return strings.ReplaceAll(repoName, "/", "-") + "-" + commit +} + +func EnsureRefPrefix(ref string) string { + if strings.HasPrefix(ref, "refs/heads/") { + return ref } + return "refs/heads/" + ref } diff --git a/internal/batches/workspace/bind_workspace.go b/internal/batches/workspace/bind_workspace.go index dfc61273b7..c20108d1ab 100644 --- a/internal/batches/workspace/bind_workspace.go +++ b/internal/batches/workspace/bind_workspace.go @@ -16,8 +16,9 @@ import ( batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/git" - "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/graphql" + "github.com/sourcegraph/src-cli/internal/batches/repozip" + "github.com/sourcegraph/src-cli/internal/batches/util" ) type dockerBindWorkspaceCreator struct { @@ -28,7 +29,7 @@ var _ Creator = &dockerBindWorkspaceCreator{} func (wc *dockerBindWorkspaceCreator) Type() CreatorType { return CreatorTypeBind } -func (wc *dockerBindWorkspaceCreator) Create(ctx context.Context, repo *graphql.Repository, steps []batcheslib.Step, archive batches.RepoZip) (Workspace, error) { +func (wc *dockerBindWorkspaceCreator) Create(ctx context.Context, repo *graphql.Repository, steps []batcheslib.Step, archive repozip.Archive) (Workspace, error) { w, err := wc.unzipToWorkspace(ctx, repo, archive.Path()) if err != nil { return nil, errors.Wrap(err, "unzipping the repository") @@ -58,7 +59,7 @@ func (*dockerBindWorkspaceCreator) prepareGitRepo(ctx context.Context, w *docker } func (wc *dockerBindWorkspaceCreator) unzipToWorkspace(ctx context.Context, repo *graphql.Repository, zip string) (*dockerBindWorkspace, error) { - prefix := "workspace-" + repo.Slug() + prefix := "workspace-" + util.SlugForRepo(repo.Name, repo.Rev()) workspace, err := unzipToTempDir(ctx, zip, wc.Dir, prefix) if err != nil { return nil, errors.Wrap(err, "unzipping the ZIP archive") diff --git a/internal/batches/workspace/bind_workspace_test.go b/internal/batches/workspace/bind_workspace_test.go index 115051e582..31dfa33669 100644 --- a/internal/batches/workspace/bind_workspace_test.go +++ b/internal/batches/workspace/bind_workspace_test.go @@ -10,8 +10,9 @@ import ( "testing" "github.com/google/go-cmp/cmp" - "github.com/sourcegraph/src-cli/internal/batches" + "github.com/sourcegraph/src-cli/internal/batches/graphql" + "github.com/sourcegraph/src-cli/internal/batches/repozip" ) var repo = &graphql.Repository{ @@ -395,16 +396,16 @@ func readWorkspaceFiles(workspace Workspace) (map[string]string, error) { return files, err } -var _ batches.RepoZip = &fakeRepoArchive{} +var _ repozip.Archive = &fakeRepoArchive{} type fakeRepoArchive struct { mockPath string mockAdditionalFilePaths map[string]string } -func (f *fakeRepoArchive) Fetch(context.Context) error { return nil } -func (f *fakeRepoArchive) Close() error { return nil } -func (f *fakeRepoArchive) Path() string { return f.mockPath } +func (f *fakeRepoArchive) Ensure(context.Context) error { return nil } +func (f *fakeRepoArchive) Close() error { return nil } +func (f *fakeRepoArchive) Path() string { return f.mockPath } func (f *fakeRepoArchive) AdditionalFilePaths() map[string]string { if f.mockAdditionalFilePaths != nil { return f.mockAdditionalFilePaths diff --git a/internal/batches/workspace/volume_workspace.go b/internal/batches/workspace/volume_workspace.go index b903101104..f3436a6b7b 100644 --- a/internal/batches/workspace/volume_workspace.go +++ b/internal/batches/workspace/volume_workspace.go @@ -16,9 +16,9 @@ import ( batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/git" - "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/docker" "github.com/sourcegraph/src-cli/internal/batches/graphql" + "github.com/sourcegraph/src-cli/internal/batches/repozip" "github.com/sourcegraph/src-cli/internal/exec" "github.com/sourcegraph/src-cli/internal/version" ) @@ -34,7 +34,7 @@ var _ Creator = &dockerVolumeWorkspaceCreator{} func (wc *dockerVolumeWorkspaceCreator) Type() CreatorType { return CreatorTypeVolume } -func (wc *dockerVolumeWorkspaceCreator) Create(ctx context.Context, repo *graphql.Repository, steps []batcheslib.Step, archive batches.RepoZip) (Workspace, error) { +func (wc *dockerVolumeWorkspaceCreator) Create(ctx context.Context, repo *graphql.Repository, steps []batcheslib.Step, archive repozip.Archive) (Workspace, error) { volume, err := wc.createVolume(ctx) if err != nil { return nil, errors.Wrap(err, "creating Docker volume") diff --git a/internal/batches/workspace/workspace.go b/internal/batches/workspace/workspace.go index b7a98855f8..1f670cd255 100644 --- a/internal/batches/workspace/workspace.go +++ b/internal/batches/workspace/workspace.go @@ -8,9 +8,9 @@ import ( batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/git" - "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/docker" "github.com/sourcegraph/src-cli/internal/batches/graphql" + "github.com/sourcegraph/src-cli/internal/batches/repozip" ) // Creator implementations are used to create workspaces, which manage @@ -18,7 +18,7 @@ import ( // responsible for ultimately generating a diff. type Creator interface { // Create creates a new workspace for the given repository and archive file. - Create(ctx context.Context, repo *graphql.Repository, steps []batcheslib.Step, archive batches.RepoZip) (Workspace, error) + Create(ctx context.Context, repo *graphql.Repository, steps []batcheslib.Step, archive repozip.Archive) (Workspace, error) // Type returns the CreatorType of the Creator. Type() CreatorType From 8106c669243a5e33cd66e98d8f86c72bc5019346 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Fri, 3 Sep 2021 12:20:39 +0200 Subject: [PATCH 029/647] Fix ioutil rule in golangci-lint (#603) --- .golangci.yml | 2 +- cmd/src/api.go | 4 ++-- cmd/src/batch_common.go | 3 +-- cmd/src/config_edit.go | 4 ++-- cmd/src/extensions_copy.go | 4 ++-- cmd/src/extensions_publish.go | 9 ++++----- cmd/src/extsvc_edit.go | 6 +++--- cmd/src/login.go | 3 +-- cmd/src/login_test.go | 4 ++-- cmd/src/main.go | 3 +-- cmd/src/main_test.go | 5 ++--- cmd/src/search_stream_test.go | 6 +++--- cmd/src/search_test.go | 9 ++++----- cmd/src/servegit.go | 4 ++-- cmd/src/validate.go | 14 +++++++------- cmd/src/version.go | 4 ++-- internal/api/api.go | 3 +-- internal/api/gzip_test.go | 6 +++--- internal/batches/executor/execution_cache.go | 6 +++--- internal/batches/executor/execution_cache_test.go | 3 +-- internal/batches/executor/executor_test.go | 5 ++--- internal/batches/executor/run_steps.go | 9 ++++----- internal/batches/log/task_logger.go | 3 +-- internal/batches/repozip/fetcher_test.go | 5 ++--- internal/batches/workspace/bind_workspace.go | 5 ++--- internal/batches/workspace/bind_workspace_test.go | 13 ++++++------- internal/batches/workspace/volume_workspace.go | 3 +-- .../batches/workspace/volume_workspace_test.go | 5 ++--- internal/exec/expect/expect.go | 5 ++--- internal/servegit/serve_test.go | 14 +++++++------- 30 files changed, 76 insertions(+), 93 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 49f4ea5eba..159d867086 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -22,7 +22,7 @@ linters-settings: packages-with-error-message: - errors: 'Use github.com/cockroachdb/errors instead' - github.com/pkg/errors: 'Use github.com/cockroachdb/errors instead' - - ioutil: 'The ioutil package has been deprecated' + - io/ioutil: 'The ioutil package has been deprecated' gocritic: disabled-checks: - appendAssign # Too many false positives diff --git a/cmd/src/api.go b/cmd/src/api.go index f2e3a4f2e6..0dd1b73b77 100644 --- a/cmd/src/api.go +++ b/cmd/src/api.go @@ -5,7 +5,7 @@ import ( "encoding/json" "flag" "fmt" - "io/ioutil" + "io" "os" "strings" @@ -68,7 +68,7 @@ Examples: if isatty.IsTerminal(os.Stdin.Fd()) { return cmderrors.Usage("expected query to be piped into 'src api' or -query flag to be specified") } - data, err := ioutil.ReadAll(os.Stdin) + data, err := io.ReadAll(os.Stdin) if err != nil { return err } diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index 1fd346e0f1..9cb220ec55 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -5,7 +5,6 @@ import ( "flag" "fmt" "io" - "io/ioutil" "os" "os/exec" "os/signal" @@ -374,7 +373,7 @@ func parseBatchSpec(file *string, svc *service.Service) (*batcheslib.BatchSpec, } defer f.Close() - data, err := ioutil.ReadAll(f) + data, err := io.ReadAll(f) if err != nil { return nil, "", errors.Wrap(err, "reading batch spec") } diff --git a/cmd/src/config_edit.go b/cmd/src/config_edit.go index d06711457f..4a7c65380b 100644 --- a/cmd/src/config_edit.go +++ b/cmd/src/config_edit.go @@ -4,7 +4,7 @@ import ( "context" "flag" "fmt" - "io/ioutil" + "os" "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/cmderrors" @@ -71,7 +71,7 @@ Examples: if *valueFlag != "" { value = *valueFlag } else if *valueFileFlag != "" { - data, err := ioutil.ReadFile(*valueFileFlag) + data, err := os.ReadFile(*valueFileFlag) if err != nil { return err } diff --git a/cmd/src/extensions_copy.go b/cmd/src/extensions_copy.go index 526be189e3..45cb3441a3 100644 --- a/cmd/src/extensions_copy.go +++ b/cmd/src/extensions_copy.go @@ -4,7 +4,7 @@ import ( "context" "flag" "fmt" - "io/ioutil" + "io" "net/http" "strings" @@ -106,7 +106,7 @@ Copy an extension from Sourcegraph.com to your private registry. return err } defer response.Body.Close() - bundle, err := ioutil.ReadAll(response.Body) + bundle, err := io.ReadAll(response.Body) if err != nil { return err } diff --git a/cmd/src/extensions_publish.go b/cmd/src/extensions_publish.go index 36a3ac94e2..0c1d7819c7 100644 --- a/cmd/src/extensions_publish.go +++ b/cmd/src/extensions_publish.go @@ -5,7 +5,6 @@ import ( "encoding/json" "flag" "fmt" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -67,7 +66,7 @@ Notes: } manifestDir := filepath.Dir(manifestPath) - manifest, err := ioutil.ReadFile(manifestPath) + manifest, err := os.ReadFile(manifestPath) if err != nil { return fmt.Errorf("%s\n\nRun this command in a directory with a %s file for an extension.\n\nSee 'src extensions %s -h' for help", err, *manifestFlag, flagSet.Name()) } @@ -256,7 +255,7 @@ func addReadmeToManifest(manifest []byte, dir string) ([]byte, error) { var readme string filenames := []string{"README.md", "README.txt", "README", "readme.md", "readme.txt", "readme", "Readme.md", "Readme.txt", "Readme"} for _, f := range filenames { - data, err := ioutil.ReadFile(filepath.Join(dir, f)) + data, err := os.ReadFile(filepath.Join(dir, f)) if err != nil { continue } @@ -292,7 +291,7 @@ func readExtensionArtifacts(manifest []byte, dir string) (bundle, sourceMap *str mainPath := filepath.Join(dir, o.Main) - data, err := ioutil.ReadFile(mainPath) + data, err := os.ReadFile(mainPath) if err != nil { return nil, nil, fmt.Errorf(`extension manifest "main" bundle file: %s`, err) } @@ -303,7 +302,7 @@ func readExtensionArtifacts(manifest []byte, dir string) (bundle, sourceMap *str // Guess that source map is the main file with a ".map" extension. sourceMapPath := strings.TrimSuffix(mainPath, filepath.Ext(mainPath)) + ".map" - data, err = ioutil.ReadFile(sourceMapPath) + data, err = os.ReadFile(sourceMapPath) if err == nil { tmp := string(data) sourceMap = &tmp diff --git a/cmd/src/extsvc_edit.go b/cmd/src/extsvc_edit.go index d29a7bcda7..dd420fa27d 100644 --- a/cmd/src/extsvc_edit.go +++ b/cmd/src/extsvc_edit.go @@ -5,7 +5,7 @@ import ( "encoding/json" "flag" "fmt" - "io/ioutil" + "io" "os" "strings" @@ -73,14 +73,14 @@ Examples: // Determine if we are updating the JSON configuration or not. var updateJSON []byte if len(flagSet.Args()) == 1 { - updateJSON, err = ioutil.ReadFile(flagSet.Arg(0)) + updateJSON, err = os.ReadFile(flagSet.Arg(0)) if err != nil { return err } } if !isatty.IsTerminal(os.Stdin.Fd()) { // stdin is a pipe not a terminal - updateJSON, err = ioutil.ReadAll(os.Stdin) + updateJSON, err = io.ReadAll(os.Stdin) if err != nil { return err } diff --git a/cmd/src/login.go b/cmd/src/login.go index e8d29bb0f2..82d4168c60 100644 --- a/cmd/src/login.go +++ b/cmd/src/login.go @@ -5,7 +5,6 @@ import ( "flag" "fmt" "io" - "io/ioutil" "os" "strings" @@ -53,7 +52,7 @@ Examples: return cmderrors.Usage("expected exactly one argument: the Sourcegraph URL, or SRC_ENDPOINT to be set") } - client := cfg.apiClient(apiFlags, ioutil.Discard) + client := cfg.apiClient(apiFlags, io.Discard) return loginCmd(context.Background(), cfg, client, endpoint, os.Stdout) } diff --git a/cmd/src/login_test.go b/cmd/src/login_test.go index 7ae87c03bc..e2b8beeeea 100644 --- a/cmd/src/login_test.go +++ b/cmd/src/login_test.go @@ -4,7 +4,7 @@ import ( "bytes" "context" "fmt" - "io/ioutil" + "io" "net/http" "net/http/httptest" "strings" @@ -18,7 +18,7 @@ func TestLogin(t *testing.T) { t.Helper() var out bytes.Buffer - err = loginCmd(context.Background(), cfg, cfg.apiClient(nil, ioutil.Discard), endpointArg, &out) + err = loginCmd(context.Background(), cfg, cfg.apiClient(nil, io.Discard), endpointArg, &out) return strings.TrimSpace(out.String()), err } diff --git a/cmd/src/main.go b/cmd/src/main.go index 7f21386579..e7fff11d8f 100644 --- a/cmd/src/main.go +++ b/cmd/src/main.go @@ -4,7 +4,6 @@ import ( "encoding/json" "flag" "io" - "io/ioutil" "log" "os" "os/user" @@ -114,7 +113,7 @@ func readConfig() (*config, error) { } else if strings.HasPrefix(cfgPath, "~/") { cfgPath = filepath.Join(homeDir, cfgPath[2:]) } - data, err := ioutil.ReadFile(os.ExpandEnv(cfgPath)) + data, err := os.ReadFile(os.ExpandEnv(cfgPath)) if err != nil && (!os.IsNotExist(err) || userSpecified) { return nil, err } diff --git a/cmd/src/main_test.go b/cmd/src/main_test.go index b36766d014..813ff220f1 100644 --- a/cmd/src/main_test.go +++ b/cmd/src/main_test.go @@ -2,7 +2,6 @@ package main import ( "encoding/json" - "io/ioutil" "os" "path/filepath" "testing" @@ -154,7 +153,7 @@ func TestReadConfig(t *testing.T) { setEnv("SRC_ACCESS_TOKEN", test.envToken) setEnv("SRC_ENDPOINT", test.envEndpoint) - tmpDir, err := ioutil.TempDir("", "") + tmpDir, err := os.MkdirTemp("", "") if err != nil { t.Fatal(err) } @@ -176,7 +175,7 @@ func TestReadConfig(t *testing.T) { t.Fatal(err) } filePath := filepath.Join(tmpDir, "config.json") - err = ioutil.WriteFile(filePath, data, 0600) + err = os.WriteFile(filePath, data, 0600) if err != nil { t.Fatal(err) } diff --git a/cmd/src/search_stream_test.go b/cmd/src/search_stream_test.go index e053dd8db4..8d55dee145 100644 --- a/cmd/src/search_stream_test.go +++ b/cmd/src/search_stream_test.go @@ -2,7 +2,7 @@ package main import ( "flag" - "io/ioutil" + "io" "net" "net/http" "net/http/httptest" @@ -147,11 +147,11 @@ func TestSearchStream(t *testing.T) { if err != nil { t.Fatal(err) } - got, err := ioutil.ReadAll(r) + got, err := io.ReadAll(r) if err != nil { t.Fatal(err) } - want, err := ioutil.ReadFile(c.want) + want, err := os.ReadFile(c.want) if err != nil { t.Fatal(err) } diff --git a/cmd/src/search_test.go b/cmd/src/search_test.go index 1f79b79cdf..59b28c558e 100644 --- a/cmd/src/search_test.go +++ b/cmd/src/search_test.go @@ -3,7 +3,6 @@ package main import ( "bytes" "encoding/json" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -29,7 +28,7 @@ func TestSearchOutput(t *testing.T) { tests := map[string]*testT{} dataDir := "testdata/search_formatting" - infos, err := ioutil.ReadDir(dataDir) + infos, err := os.ReadDir(dataDir) if err != nil { t.Fatal(err) } @@ -50,7 +49,7 @@ func TestSearchOutput(t *testing.T) { tests[testName] = &testT{} } - data, err := ioutil.ReadFile(path) + data, err := os.ReadFile(path) if err != nil { t.Fatal(err) } @@ -74,7 +73,7 @@ func TestSearchOutput(t *testing.T) { if tst.want == nil { // Create the initial (empty) .want.txt file. wantFile := filepath.Join(dataDir, testName+".want.txt") - if err := ioutil.WriteFile(wantFile, nil, 0600); err != nil { + if err := os.WriteFile(wantFile, nil, 0600); err != nil { t.Fatal(err) } tmp := "" @@ -100,7 +99,7 @@ func TestSearchOutput(t *testing.T) { gotFile := filepath.Join(dataDir, testName+".got.txt") wantFile := filepath.Join(dataDir, testName+".want.txt") - err := ioutil.WriteFile(gotFile, []byte(got), 0600) + err := os.WriteFile(gotFile, []byte(got), 0600) if err != nil { t.Fatal(err) } diff --git a/cmd/src/servegit.go b/cmd/src/servegit.go index 2dcf5363e0..99d46ddb30 100644 --- a/cmd/src/servegit.go +++ b/cmd/src/servegit.go @@ -3,7 +3,7 @@ package main import ( "flag" "fmt" - "io/ioutil" + "io" "log" "os" @@ -53,7 +53,7 @@ Documentation at https://docs.sourcegraph.com/admin/external_service/src_serve_g return cmderrors.Usage("requires zero or one arguments") } - dbug := log.New(ioutil.Discard, "", log.LstdFlags) + dbug := log.New(io.Discard, "", log.LstdFlags) if *verbose { dbug = log.New(os.Stderr, "DBUG serve-git: ", log.LstdFlags) } diff --git a/cmd/src/validate.go b/cmd/src/validate.go index b1b2363f34..9652464829 100644 --- a/cmd/src/validate.go +++ b/cmd/src/validate.go @@ -6,7 +6,7 @@ import ( "encoding/json" "flag" "fmt" - "io/ioutil" + "io" "net/http" "os" "strings" @@ -92,7 +92,7 @@ Please visit https://docs.sourcegraph.com/admin/validation for documentation of var err error if len(flagSet.Args()) == 1 { filename := flagSet.Arg(0) - script, err = ioutil.ReadFile(filename) + script, err = os.ReadFile(filename) if err != nil { return err } @@ -102,7 +102,7 @@ Please visit https://docs.sourcegraph.com/admin/validation for documentation of } if !isatty.IsTerminal(os.Stdin.Fd()) { // stdin is a pipe not a terminal - script, err = ioutil.ReadAll(os.Stdin) + script, err = io.ReadAll(os.Stdin) if err != nil { return err } @@ -147,7 +147,7 @@ func (vd *validator) parseKVPairs(val string, pairSep string) map[string]string } func (vd *validator) readSecrets(path string) (map[string]string, error) { - bs, err := ioutil.ReadFile(path) + bs, err := os.ReadFile(path) if err != nil { return nil, err } @@ -497,7 +497,7 @@ func (vd *validator) newClient(baseURL string) (*vdClient, error) { } defer func() { _ = resp.Body.Close() }() - p, err := ioutil.ReadAll(resp.Body) + p, err := io.ReadAll(resp.Body) if err != nil { return nil, err } @@ -548,7 +548,7 @@ func (c *vdClient) authenticate(path string, body interface{}) error { defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusOK { - p, err := ioutil.ReadAll(resp.Body) + p, err := io.ReadAll(resp.Body) if err != nil { return err } @@ -654,7 +654,7 @@ func (c *vdClient) graphQL(token, query string, variables map[string]interface{} defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusOK { - p, err := ioutil.ReadAll(resp.Body) + p, err := io.ReadAll(resp.Body) if err != nil { return err } diff --git a/cmd/src/version.go b/cmd/src/version.go index eec0bb183e..37bdeb7bdd 100644 --- a/cmd/src/version.go +++ b/cmd/src/version.go @@ -5,7 +5,7 @@ import ( "encoding/json" "flag" "fmt" - "io/ioutil" + "io" "net/http" "github.com/sourcegraph/src-cli/internal/api" @@ -66,7 +66,7 @@ func getRecommendedVersion(ctx context.Context, client api.Client) (string, erro } defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { return "", err } diff --git a/internal/api/api.go b/internal/api/api.go index 221edbb9ec..132b594ae4 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -8,7 +8,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "os" "strings" @@ -248,7 +247,7 @@ func (r *request) do(ctx context.Context, result interface{}) (bool, error) { fmt.Println("See https://github.com/sourcegraph/src-cli#readme") fmt.Println("") } - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { return false, err } diff --git a/internal/api/gzip_test.go b/internal/api/gzip_test.go index 5cca5ee585..1d6b3006ad 100644 --- a/internal/api/gzip_test.go +++ b/internal/api/gzip_test.go @@ -3,7 +3,7 @@ package api import ( "bytes" "compress/gzip" - "io/ioutil" + "io" "testing" "github.com/google/go-cmp/cmp" @@ -15,7 +15,7 @@ func TestGzipReader(t *testing.T) { uncompressed = append(uncompressed, byte(i)) } - contents, err := ioutil.ReadAll(gzipReader(bytes.NewReader(uncompressed))) + contents, err := io.ReadAll(gzipReader(bytes.NewReader(uncompressed))) if err != nil { t.Fatalf("unexpected error reading from gzip reader: %s", err) } @@ -24,7 +24,7 @@ func TestGzipReader(t *testing.T) { if err != nil { t.Fatalf("unexpected error creating gzip.Reader: %s", err) } - decompressed, err := ioutil.ReadAll(gzipReader) + decompressed, err := io.ReadAll(gzipReader) if err != nil { t.Fatalf("unexpected error reading from gzip.Reader: %s", err) } diff --git a/internal/batches/executor/execution_cache.go b/internal/batches/executor/execution_cache.go index 1b092a4ee3..e4eb0b66ba 100644 --- a/internal/batches/executor/execution_cache.go +++ b/internal/batches/executor/execution_cache.go @@ -6,12 +6,12 @@ import ( "encoding/base64" "encoding/json" "fmt" - "io/ioutil" "os" "path/filepath" "github.com/cockroachdb/errors" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" + "github.com/sourcegraph/src-cli/internal/batches/util" ) @@ -190,7 +190,7 @@ func (c ExecutionDiskCache) readCacheFile(path string, result interface{}) (bool return false, nil } - data, err := ioutil.ReadFile(path) + data, err := os.ReadFile(path) if err != nil { return false, err } @@ -216,7 +216,7 @@ func (c ExecutionDiskCache) writeCacheFile(path string, result interface{}) erro return err } - return ioutil.WriteFile(path, raw, 0600) + return os.WriteFile(path, raw, 0600) } func (c ExecutionDiskCache) Set(ctx context.Context, key CacheKeyer, result executionResult) error { diff --git a/internal/batches/executor/execution_cache_test.go b/internal/batches/executor/execution_cache_test.go index 7002e68c20..d2bc18de0c 100644 --- a/internal/batches/executor/execution_cache_test.go +++ b/internal/batches/executor/execution_cache_test.go @@ -2,7 +2,6 @@ package executor import ( "context" - "io/ioutil" "os" "testing" @@ -110,7 +109,7 @@ func TestExecutionDiskCache_GetSet(t *testing.T) { ctx := context.Background() cacheTmpDir := func(t *testing.T) string { - testTempDir, err := ioutil.TempDir("", "execution-disk-cache-test-*") + testTempDir, err := os.MkdirTemp("", "execution-disk-cache-test-*") if err != nil { t.Fatal(err) } diff --git a/internal/batches/executor/executor_test.go b/internal/batches/executor/executor_test.go index 4490e38d3b..2a53b9102b 100644 --- a/internal/batches/executor/executor_test.go +++ b/internal/batches/executor/executor_test.go @@ -4,7 +4,6 @@ import ( "bytes" "context" "fmt" - "io/ioutil" "net/http" "net/http/httptest" "os" @@ -334,7 +333,7 @@ func TestExecutor_Integration(t *testing.T) { client := api.NewClient(api.ClientOpts{Endpoint: ts.URL, Out: &clientBuffer}) // Temp dir for log files and downloaded archives - testTempDir, err := ioutil.TempDir("", "executor-integration-test-*") + testTempDir, err := os.MkdirTemp("", "executor-integration-test-*") if err != nil { t.Fatal(err) } @@ -666,7 +665,7 @@ func testExecuteTasks(t *testing.T, tasks []*Task, archives ...mock.RepoArchive) t.Skip("Test doesn't work on Windows because dummydocker is written in bash") } - testTempDir, err := ioutil.TempDir("", "executor-integration-test-*") + testTempDir, err := os.MkdirTemp("", "executor-integration-test-*") if err != nil { t.Fatal(err) } diff --git a/internal/batches/executor/run_steps.go b/internal/batches/executor/run_steps.go index 6dcb66eac8..78d8890e96 100644 --- a/internal/batches/executor/run_steps.go +++ b/internal/batches/executor/run_steps.go @@ -6,7 +6,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "os" "os/exec" "strings" @@ -455,7 +454,7 @@ func createFilesToMount(tempDir string, step batcheslib.Step, stepContext *templ // can mount them into the container. filesToMount := make(map[string]*os.File, len(files)) for name, content := range files { - fp, err := ioutil.TempFile(tempDir, "") + fp, err := os.CreateTemp(tempDir, "") if err != nil { return nil, cleanup, errors.Wrap(err, "creating temporary file") } @@ -481,7 +480,7 @@ func createFilesToMount(tempDir string, step batcheslib.Step, stepContext *templ func createRunScriptFile(ctx context.Context, tempDir string, stepRun string, stepCtx *template.StepContext) (string, string, func(), error) { // Set up a temporary file on the host filesystem to contain the // script. - runScriptFile, err := ioutil.TempFile(tempDir, "") + runScriptFile, err := os.CreateTemp(tempDir, "") if err != nil { return "", "", nil, errors.Wrap(err, "creating temporary file") } @@ -523,7 +522,7 @@ func createCidFile(ctx context.Context, tempDir string, repoSlug string) (string // Find a location that we can use for a cidfile, which will contain the // container ID that is used below. We can then use this to remove the // container on a successful run, rather than leaving it dangling. - cidFile, err := ioutil.TempFile(tempDir, repoSlug+"-container-id") + cidFile, err := os.CreateTemp(tempDir, repoSlug+"-container-id") if err != nil { return "", nil, errors.Wrap(err, "Creating a CID file failed") } @@ -539,7 +538,7 @@ func createCidFile(ctx context.Context, tempDir string, repoSlug string) (string // Since we went to all that effort, we can now defer a function that // uses the cidfile to clean up after this function is done. cleanup := func() { - cid, err := ioutil.ReadFile(cidFile.Name()) + cid, err := os.ReadFile(cidFile.Name()) _ = os.Remove(cidFile.Name()) if err == nil { ctx, cancel := context.WithTimeout(ctx, 2*time.Second) diff --git a/internal/batches/log/task_logger.go b/internal/batches/log/task_logger.go index 6f71fa0544..84dd1616d2 100644 --- a/internal/batches/log/task_logger.go +++ b/internal/batches/log/task_logger.go @@ -4,7 +4,6 @@ import ( "bytes" "fmt" "io" - "io/ioutil" "os" "time" @@ -30,7 +29,7 @@ type FileTaskLogger struct { func newTaskLogger(slug string, keep bool, dir string) (*FileTaskLogger, error) { prefix := "changeset-" + slug - f, err := ioutil.TempFile(dir, prefix+".*.log") + f, err := os.CreateTemp(dir, prefix+".*.log") if err != nil { return nil, errors.Wrapf(err, "creating temporary file with prefix %q", prefix) } diff --git a/internal/batches/repozip/fetcher_test.go b/internal/batches/repozip/fetcher_test.go index 3587c1e0bd..3e778d3f4a 100644 --- a/internal/batches/repozip/fetcher_test.go +++ b/internal/batches/repozip/fetcher_test.go @@ -3,7 +3,6 @@ package repozip import ( "bytes" "context" - "io/ioutil" "net/http" "net/http/httptest" "os" @@ -23,7 +22,7 @@ import ( func TestArchive_Ensure(t *testing.T) { workspaceTmpDir := func(t *testing.T) string { - testTempDir, err := ioutil.TempDir("", "executor-integration-test-*") + testTempDir, err := os.MkdirTemp("", "executor-integration-test-*") if err != nil { t.Fatal(err) } @@ -310,7 +309,7 @@ func TestArchive_Ensure(t *testing.T) { func sortStrings(a, b string) bool { return a < b } func dirContains(dir, filename string) (bool, error) { - files, err := ioutil.ReadDir(dir) + files, err := os.ReadDir(dir) if err != nil { return false, err } diff --git a/internal/batches/workspace/bind_workspace.go b/internal/batches/workspace/bind_workspace.go index c20108d1ab..2d1e71a92f 100644 --- a/internal/batches/workspace/bind_workspace.go +++ b/internal/batches/workspace/bind_workspace.go @@ -5,7 +5,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "os" "path" "path/filepath" @@ -159,7 +158,7 @@ func (w *dockerBindWorkspace) Diff(ctx context.Context) ([]byte, error) { func (w *dockerBindWorkspace) ApplyDiff(ctx context.Context, diff []byte) error { // Write the diff to a temp file so we can pass it to `git apply` - tmp, err := ioutil.TempFile(w.tempDir, "bind-workspace-test-*") + tmp, err := os.CreateTemp(w.tempDir, "bind-workspace-test-*") if err != nil { return errors.Wrap(err, "saving cached diff to temporary file") } @@ -184,7 +183,7 @@ func (w *dockerBindWorkspace) ApplyDiff(ctx context.Context, diff []byte) error } func unzipToTempDir(ctx context.Context, zipFile, tempDir, tempFilePrefix string) (string, error) { - volumeDir, err := ioutil.TempDir(tempDir, tempFilePrefix) + volumeDir, err := os.MkdirTemp(tempDir, tempFilePrefix) if err != nil { return "", err } diff --git a/internal/batches/workspace/bind_workspace_test.go b/internal/batches/workspace/bind_workspace_test.go index 31dfa33669..ed64664edc 100644 --- a/internal/batches/workspace/bind_workspace_test.go +++ b/internal/batches/workspace/bind_workspace_test.go @@ -3,7 +3,6 @@ package workspace import ( "archive/zip" "context" - "io/ioutil" "os" "path/filepath" "strings" @@ -22,7 +21,7 @@ var repo = &graphql.Repository{ } func zipUpFiles(t *testing.T, dir string, files map[string]string) string { - f, err := ioutil.TempFile(dir, "repo-zip-*") + f, err := os.CreateTemp(dir, "repo-zip-*") if err != nil { t.Fatal(err) } @@ -46,7 +45,7 @@ func zipUpFiles(t *testing.T, dir string, files map[string]string) string { } func workspaceTmpDir(t *testing.T) string { - testTempDir, err := ioutil.TempDir("", "bind-workspace-test-*") + testTempDir, err := os.MkdirTemp("", "bind-workspace-test-*") if err != nil { t.Fatal(err) } @@ -70,7 +69,7 @@ func TestDockerBindWorkspaceCreator_Create(t *testing.T) { } additionalFilePaths := map[string]string{} for name, content := range additionalFiles { - f, err := ioutil.TempFile(fakeFilesTmpDir, name+"-*") + f, err := os.CreateTemp(fakeFilesTmpDir, name+"-*") if err != nil { t.Fatal(err) } @@ -109,7 +108,7 @@ func TestDockerBindWorkspaceCreator_Create(t *testing.T) { testTempDir := workspaceTmpDir(t) // Create an empty file (which is therefore a bad zip file). - badZip, err := ioutil.TempFile(testTempDir, "bad-zip-*") + badZip, err := os.CreateTemp(testTempDir, "bad-zip-*") if err != nil { t.Fatal(err) } @@ -327,7 +326,7 @@ func TestEnsureAll(t *testing.T) { } func mustCreateWorkspace(t *testing.T) string { - base, err := ioutil.TempDir("", "") + base, err := os.MkdirTemp("", "") if err != nil { t.Fatal(err) } @@ -375,7 +374,7 @@ func readWorkspaceFiles(workspace Workspace) (map[string]string, error) { return nil } - content, err := ioutil.ReadFile(path) + content, err := os.ReadFile(path) if err != nil { return err } diff --git a/internal/batches/workspace/volume_workspace.go b/internal/batches/workspace/volume_workspace.go index f3436a6b7b..a189d58671 100644 --- a/internal/batches/workspace/volume_workspace.go +++ b/internal/batches/workspace/volume_workspace.go @@ -6,7 +6,6 @@ import ( "crypto/rand" "encoding/hex" "fmt" - "io/ioutil" "os" "sort" "strings" @@ -313,7 +312,7 @@ func init() { // container started from the dockerWorkspaceImage, then run it and return the // output. func (w *dockerVolumeWorkspace) runScript(ctx context.Context, target, script string) ([]byte, error) { - f, err := ioutil.TempFile(w.tempDir, "src-run-*") + f, err := os.CreateTemp(w.tempDir, "src-run-*") if err != nil { return nil, errors.Wrap(err, "creating run script") } diff --git a/internal/batches/workspace/volume_workspace_test.go b/internal/batches/workspace/volume_workspace_test.go index aa5b0b377c..8ac6af42e3 100644 --- a/internal/batches/workspace/volume_workspace_test.go +++ b/internal/batches/workspace/volume_workspace_test.go @@ -3,7 +3,6 @@ package workspace import ( "bytes" "context" - "io/ioutil" "os" "path/filepath" "strings" @@ -29,7 +28,7 @@ func TestVolumeWorkspaceCreator(t *testing.T) { // Create an empty file. It doesn't matter that it's an invalid zip, since // we're mocking the unzip command anyway. - f, err := ioutil.TempFile(os.TempDir(), "volume-workspace-*") + f, err := os.CreateTemp(os.TempDir(), "volume-workspace-*") if err != nil { t.Fatal(err) } @@ -644,7 +643,7 @@ func TestVolumeWorkspace_runScript(t *testing.T) { // mount options. Let's go get it! values := strings.Split(arg[6], ",") source := strings.SplitN(values[1], "=", 2) - have, err := ioutil.ReadFile(source[1]) + have, err := os.ReadFile(source[1]) if err != nil { return errors.Errorf("error reading temporary file %q: %v", source[1], err) } diff --git a/internal/exec/expect/expect.go b/internal/exec/expect/expect.go index e6c4f9ae4d..82e2e044c0 100644 --- a/internal/exec/expect/expect.go +++ b/internal/exec/expect/expect.go @@ -19,7 +19,6 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" "os" goexec "os/exec" "testing" @@ -95,7 +94,7 @@ func Commands(t *testing.T, exp ...*Expectation) { cmd.Args = []string{} // Actually create the behaviour file. - f, err := ioutil.TempFile(os.TempDir(), "behaviour") + f, err := os.CreateTemp(os.TempDir(), "behaviour") if err != nil { t.Fatalf("error creating behaviour file: %v", err) } @@ -143,7 +142,7 @@ func Handle(m interface{ Run() int }) int { } // Load up the expected behaviour of this command. - data, err := ioutil.ReadFile(file) + data, err := os.ReadFile(file) if err != nil { panicErr(err) } diff --git a/internal/servegit/serve_test.go b/internal/servegit/serve_test.go index ce1c2e063c..bc62011bfc 100644 --- a/internal/servegit/serve_test.go +++ b/internal/servegit/serve_test.go @@ -2,7 +2,7 @@ package servegit import ( "encoding/json" - "io/ioutil" + "io" "log" "net/http" "net/http/httptest" @@ -19,7 +19,7 @@ import ( const testAddress = "test.local:3939" -var discardLogger = log.New(ioutil.Discard, "", log.LstdFlags) +var discardLogger = log.New(io.Discard, "", log.LstdFlags) func TestReposHandler(t *testing.T) { cases := []struct { @@ -87,7 +87,7 @@ func TestReposHandler(t *testing.T) { // This is the difference, we create a symlink for root { - tmp, err := ioutil.TempDir("", "") + tmp, err := os.MkdirTemp("", "") if err != nil { t.Fatal(err) } @@ -125,7 +125,7 @@ func testReposHandler(t *testing.T, h http.Handler, repos []Repo) { if err != nil { t.Fatal(err) } - b, err := ioutil.ReadAll(res.Body) + b, err := io.ReadAll(res.Body) res.Body.Close() if err != nil { t.Fatal(err) @@ -172,7 +172,7 @@ func testReposHandler(t *testing.T, h http.Handler, repos []Repo) { } func gitInitRepos(t *testing.T, names ...string) string { - root, err := ioutil.TempDir("", "") + root, err := os.MkdirTemp("", "") if err != nil { t.Fatal(err) } @@ -194,7 +194,7 @@ func gitInitRepos(t *testing.T, names ...string) string { } func TestIgnoreGitSubmodules(t *testing.T) { - root, err := ioutil.TempDir("", "") + root, err := os.MkdirTemp("", "") if err != nil { t.Fatal(err) } @@ -204,7 +204,7 @@ func TestIgnoreGitSubmodules(t *testing.T) { t.Fatal(err) } - if err := ioutil.WriteFile(filepath.Join(root, "dir", ".git"), []byte("ignore me please"), os.ModePerm); err != nil { + if err := os.WriteFile(filepath.Join(root, "dir", ".git"), []byte("ignore me please"), os.ModePerm); err != nil { t.Fatal(err) } From 9a4b64d6b0122b92e21b715d953fdcbda4ca8a38 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Fri, 3 Sep 2021 15:13:42 +0200 Subject: [PATCH 030/647] Fix DirectoriesContainingFile query (#604) Rev and repo name were shifted, this probably returned no results at all times. --- internal/batches/service/service.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index 1031930ccf..fd7f96c983 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -653,7 +653,7 @@ func (svc *Service) FindDirectoriesInRepos(ctx context.Context, fileName string, a.WriteString("query DirectoriesContainingFile {\n") for _, repo := range batch { - query := fmt.Sprintf(`file:(^|/)%s$ repo:^%s$@%s type:path count:99999`, regexp.QuoteMeta(fileName), repo.Rev(), regexp.QuoteMeta(repo.Name)) + query := fmt.Sprintf(`file:(^|/)%s$ repo:^%s$@%s type:path count:99999`, regexp.QuoteMeta(fileName), regexp.QuoteMeta(repo.Name), repo.Rev()) a.WriteString(fmt.Sprintf(searchQueryTmpl, queryIDByRepo[repo], query)) } From e486e84e8e79fa1443e162749336ec3bc22fdf9c Mon Sep 17 00:00:00 2001 From: Thorsten Ball Date: Fri, 3 Sep 2021 15:56:25 +0200 Subject: [PATCH 031/647] executor UI: extract StepsExecutionUI from TaskExecutionUI and implement it in TUI and JSON (#606) This is a follow-up to https://github.com/sourcegraph/src-cli/pull/597 and splits up the existing interface into two. That allows us to remove all formatting from `runSteps` and `executeSingleStep` and also provide more information for the JSON interface (e.g. when a step is finished). **Note**: the `OPERATION` and `STATUS` fields in the `logEvents` don't make a lot of sense. Happy to change everything there. --- internal/batches/executor/coordinator.go | 18 +-- internal/batches/executor/coordinator_test.go | 16 +-- internal/batches/executor/executor.go | 7 +- internal/batches/executor/run_steps.go | 37 ++--- internal/batches/executor/ui.go | 72 ++++++++++ internal/batches/ui/json_lines.go | 126 +++++++++++++++--- internal/batches/ui/task_exec_tui.go | 82 ++++++++++-- 7 files changed, 276 insertions(+), 82 deletions(-) create mode 100644 internal/batches/executor/ui.go diff --git a/internal/batches/executor/coordinator.go b/internal/batches/executor/coordinator.go index 90bc3b7d5e..4c66bef0fa 100644 --- a/internal/batches/executor/coordinator.go +++ b/internal/batches/executor/coordinator.go @@ -2,13 +2,13 @@ package executor import ( "context" - "io" "reflect" "strconv" "time" "github.com/cockroachdb/errors" "github.com/hashicorp/go-multierror" + batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/src-cli/internal/api" @@ -207,22 +207,6 @@ func (c *Coordinator) cacheAndBuildSpec(ctx context.Context, taskResult taskResu return specs, nil } -type TaskExecutionUI interface { - Start([]*Task) - Success() - - TaskStarted(*Task) - TaskFinished(*Task, error) - - TaskChangesetSpecsBuilt(*Task, []*batcheslib.ChangesetSpec) - - // TODO: This should be split up into methods that are more specific. - TaskCurrentlyExecuting(*Task, string) - - StepStdoutWriter(context.Context, *Task, int) io.WriteCloser - StepStderrWriter(context.Context, *Task, int) io.WriteCloser -} - // Execute executes the given Tasks and the importChangeset statements in the // given spec. It regularly calls the executionProgressPrinter with the // current TaskStatuses. diff --git a/internal/batches/executor/coordinator_test.go b/internal/batches/executor/coordinator_test.go index ae740aa790..c5e577015e 100644 --- a/internal/batches/executor/coordinator_test.go +++ b/internal/batches/executor/coordinator_test.go @@ -3,7 +3,6 @@ package executor import ( "context" "fmt" - "io" "strings" "sync" "testing" @@ -11,6 +10,7 @@ import ( "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" "github.com/sourcegraph/batch-change-utils/overridable" + batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/git" "github.com/sourcegraph/sourcegraph/lib/batches/template" @@ -545,18 +545,8 @@ func (d *dummyTaskExecutionUI) TaskChangesetSpecsBuilt(t *Task, specs []*batches d.specs[t] = specs } -type discardCloser struct { - io.Writer -} - -func (discardCloser) Close() error { return nil } - -func (d *dummyTaskExecutionUI) TaskCurrentlyExecuting(*Task, string) {} -func (d *dummyTaskExecutionUI) StepStdoutWriter(ctx context.Context, task *Task, step int) io.WriteCloser { - return discardCloser{io.Discard} -} -func (d *dummyTaskExecutionUI) StepStderrWriter(ctx context.Context, task *Task, step int) io.WriteCloser { - return discardCloser{io.Discard} +func (d *dummyTaskExecutionUI) StepsExecutionUI(t *Task) StepsExecutionUI { + return NoopStepsExecUI{} } var _ taskExecutor = &dummyExecutor{} diff --git a/internal/batches/executor/executor.go b/internal/batches/executor/executor.go index 8a5f291ea4..f7bb6ec199 100644 --- a/internal/batches/executor/executor.go +++ b/internal/batches/executor/executor.go @@ -174,11 +174,8 @@ func (x *executor) do(ctx context.Context, task *Task, ui TaskExecutionUI) (err wc: x.opts.Creator, ensureImage: x.opts.EnsureImage, tempDir: x.opts.TempDir, - reportProgress: func(currentlyExecuting string) { - ui.TaskCurrentlyExecuting(task, currentlyExecuting) - }, - newUiStdoutWriter: ui.StepStdoutWriter, - newUiStderrWriter: ui.StepStderrWriter, + + ui: ui.StepsExecutionUI(task), } result, stepResults, err := runSteps(runCtx, opts) diff --git a/internal/batches/executor/run_steps.go b/internal/batches/executor/run_steps.go index 78d8890e96..ba12688137 100644 --- a/internal/batches/executor/run_steps.go +++ b/internal/batches/executor/run_steps.go @@ -13,6 +13,7 @@ import ( "github.com/cockroachdb/errors" "github.com/hashicorp/go-multierror" + batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/git" "github.com/sourcegraph/sourcegraph/lib/batches/template" @@ -64,27 +65,27 @@ type executionOpts struct { tempDir string - logger log.TaskLogger - reportProgress func(string) + logger log.TaskLogger - newUiStdoutWriter func(context.Context, *Task, int) io.WriteCloser - newUiStderrWriter func(context.Context, *Task, int) io.WriteCloser + ui StepsExecutionUI } func runSteps(ctx context.Context, opts *executionOpts) (result executionResult, stepResults []stepExecutionResult, err error) { - opts.reportProgress("Downloading archive") + opts.ui.ArchiveDownloadStarted() err = opts.task.Archive.Ensure(ctx) if err != nil { return executionResult{}, nil, errors.Wrap(err, "fetching repo") } defer opts.task.Archive.Close() + opts.ui.ArchiveDownloadFinished() - opts.reportProgress("Initializing workspace") + opts.ui.WorkspaceInitializationStarted() workspace, err := opts.wc.Create(ctx, opts.task.Repository, opts.task.Steps, opts.task.Archive) if err != nil { return executionResult{}, nil, errors.Wrap(err, "creating workspace") } defer workspace.Close(ctx) + opts.ui.WorkspaceInitializationFinished() var ( execResult = executionResult{ @@ -118,12 +119,7 @@ func runSteps(ctx context.Context, opts *executionOpts) (result executionResult, return execResult, stepResults, nil } - switch startStep { - case 1: - opts.reportProgress("Skipping step 1. Found cached result.") - default: - opts.reportProgress(fmt.Sprintf("Skipping steps 1 to %d. Found cached results.", startStep)) - } + opts.ui.SkippingStepsUpto(startStep) } for i := startStep; i < len(opts.task.Steps); i++ { @@ -157,9 +153,10 @@ func runSteps(ctx context.Context, opts *executionOpts) (result executionResult, return execResult, nil, errors.Wrap(err, "evaluating step condition") } if !cond { - opts.reportProgress(fmt.Sprintf("Skipping step %d", i+1)) + opts.ui.StepSkipped(i + 1) continue } + // We need to grab the digest for the exact image we're using. img, err := opts.ensureImage(ctx, step.Container) if err != nil { @@ -204,14 +201,18 @@ func runSteps(ctx context.Context, opts *executionOpts) (result executionResult, } stepResults = append(stepResults, stepResult) previousStepResult = result + + opts.ui.StepFinished(i+1, stepResult.Diff, result.Files, stepResult.Outputs) } - opts.reportProgress("Calculating diff") + opts.ui.CalculatingDiffStarted() diffOut, err := workspace.Diff(ctx) if err != nil { return execResult, nil, errors.Wrap(err, "git diff failed") } + opts.ui.CalculatingDiffFinished() + execResult.Diff = string(diffOut) execResult.ChangedFiles = previousStepResult.Files @@ -232,7 +233,7 @@ func executeSingleStep( // ---------- // PREPARATION // ---------- - opts.reportProgress(fmt.Sprintf("Preparing step %d", i+1)) + opts.ui.StepPreparing(i + 1) cidFile, cleanup, err := createCidFile(ctx, opts.tempDir, util.SlugForRepo(opts.task.Repository.Name, opts.task.Repository.Rev())) if err != nil { @@ -274,7 +275,7 @@ func executeSingleStep( // ---------- // EXECUTION // ---------- - opts.reportProgress(runScript) + opts.ui.StepStarted(i+1, runScript) workspaceOpts, err := workspace.DockerRunOpts(ctx, workDir) if err != nil { @@ -316,8 +317,8 @@ func executeSingleStep( writerCtx, writerCancel := context.WithCancel(ctx) defer writerCancel() - uiStdoutWriter := opts.newUiStdoutWriter(writerCtx, opts.task, i) - uiStderrWriter := opts.newUiStderrWriter(writerCtx, opts.task, i) + uiStdoutWriter := opts.ui.StepStdoutWriter(writerCtx, opts.task, i) + uiStderrWriter := opts.ui.StepStderrWriter(writerCtx, opts.task, i) defer func() { uiStdoutWriter.Close() uiStderrWriter.Close() diff --git a/internal/batches/executor/ui.go b/internal/batches/executor/ui.go new file mode 100644 index 0000000000..4bc5c4954e --- /dev/null +++ b/internal/batches/executor/ui.go @@ -0,0 +1,72 @@ +package executor + +import ( + "context" + "io" + + batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" + "github.com/sourcegraph/sourcegraph/lib/batches/git" +) + +type TaskExecutionUI interface { + Start([]*Task) + Success() + + TaskStarted(*Task) + TaskFinished(*Task, error) + + TaskChangesetSpecsBuilt(*Task, []*batcheslib.ChangesetSpec) + + StepsExecutionUI(*Task) StepsExecutionUI +} + +type StepsExecutionUI interface { + ArchiveDownloadStarted() + ArchiveDownloadFinished() + + WorkspaceInitializationStarted() + WorkspaceInitializationFinished() + + SkippingStepsUpto(int) + + StepSkipped(int) + + StepPreparing(int) + StepStarted(int, string) + + StepStdoutWriter(context.Context, *Task, int) io.WriteCloser + StepStderrWriter(context.Context, *Task, int) io.WriteCloser + + CalculatingDiffStarted() + CalculatingDiffFinished() + + StepFinished(idx int, diff []byte, changes *git.Changes, outputs map[string]interface{}) +} + +// NoopStepsExecUI is an implementation of StepsExecutionUI that does nothing. +type NoopStepsExecUI struct{} + +func (noop NoopStepsExecUI) ArchiveDownloadStarted() {} +func (noop NoopStepsExecUI) ArchiveDownloadFinished() {} +func (noop NoopStepsExecUI) WorkspaceInitializationStarted() {} +func (noop NoopStepsExecUI) WorkspaceInitializationFinished() {} +func (noop NoopStepsExecUI) SkippingStepsUpto(startStep int) {} +func (noop NoopStepsExecUI) StepSkipped(step int) {} +func (noop NoopStepsExecUI) StepPreparing(step int) {} +func (noop NoopStepsExecUI) StepStarted(step int, runScript string) {} +func (noop NoopStepsExecUI) StepStdoutWriter(ctx context.Context, task *Task, step int) io.WriteCloser { + return discardCloser{io.Discard} +} +func (noop NoopStepsExecUI) StepStderrWriter(ctx context.Context, task *Task, step int) io.WriteCloser { + return discardCloser{io.Discard} +} +func (noop NoopStepsExecUI) CalculatingDiffStarted() {} +func (noop NoopStepsExecUI) CalculatingDiffFinished() {} +func (noop NoopStepsExecUI) StepFinished(idx int, diff []byte, changes *git.Changes, outputs map[string]interface{}) { +} + +type discardCloser struct { + io.Writer +} + +func (discardCloser) Close() error { return nil } diff --git a/internal/batches/ui/json_lines.go b/internal/batches/ui/json_lines.go index c8d1c8ceb3..cb2a3f1759 100644 --- a/internal/batches/ui/json_lines.go +++ b/internal/batches/ui/json_lines.go @@ -14,6 +14,7 @@ import ( "github.com/sourcegraph/src-cli/internal/batches/workspace" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" + "github.com/sourcegraph/sourcegraph/lib/batches/git" ) var _ ExecUI = &JSONLines{} @@ -290,37 +291,97 @@ func (ui *taskExecutionJSONLines) TaskChangesetSpecsBuilt(task *executor.Task, s }}) } -func (ui *taskExecutionJSONLines) TaskCurrentlyExecuting(task *executor.Task, message string) { +func (ui *taskExecutionJSONLines) StepsExecutionUI(task *executor.Task) executor.StepsExecutionUI { lt, ok := ui.linesTasks[task] if !ok { panic("unknown task started") } + return &stepsExecutionJSONLines{linesTask: <} +} + +type stepsExecutionJSONLines struct { + linesTask *jsonLinesTask +} + +const stepFlushDuration = 500 * time.Millisecond + +func (ui *stepsExecutionJSONLines) ArchiveDownloadStarted() { logEvent(batchesLogEvent{ - Operation: "EXECUTING_TASK", + Operation: "TASK_DOWNLOADING_ARCHIVE", + Status: "STARTED", + Message: "Downloading archive", + Metadata: map[string]interface{}{"task": ui.linesTask}, + }) +} + +func (ui *stepsExecutionJSONLines) ArchiveDownloadFinished() { + logEvent(batchesLogEvent{ + Operation: "TASK_DOWNLOADING_ARCHIVE", + Status: "FINISHED", + Metadata: map[string]interface{}{"task": ui.linesTask}, + }) +} +func (ui *stepsExecutionJSONLines) WorkspaceInitializationStarted() { + logEvent(batchesLogEvent{ + Operation: "TASK_INITIALIZING_WORKSPACE", + Status: "STARTED", + Message: "Initializing workspace", + Metadata: map[string]interface{}{"task": ui.linesTask}, + }) +} +func (ui *stepsExecutionJSONLines) WorkspaceInitializationFinished() { + logEvent(batchesLogEvent{ + Operation: "TASK_INITIALIZING_WORKSPACE", + Status: "FINISHED", + Metadata: map[string]interface{}{"task": ui.linesTask}, + }) +} + +func (ui *stepsExecutionJSONLines) SkippingStepsUpto(startStep int) { + logEvent(batchesLogEvent{ + Operation: "TASK_SKIPPING_STEPS", Status: "PROGRESS", - Message: message, - Metadata: map[string]interface{}{ - "task": lt, - }, + Message: fmt.Sprintf("Skipping steps. Starting at %d.", startStep), + Metadata: map[string]interface{}{"task": ui.linesTask, "startStep": startStep}, }) } -const stepFlushDuration = 500 * time.Millisecond +func (ui *stepsExecutionJSONLines) StepSkipped(step int) { + logEvent(batchesLogEvent{ + Operation: "TASK_STEP_SKIPPED", + Status: "PROGRESS", + Message: fmt.Sprintf("Skipping step %d.", step), + Metadata: map[string]interface{}{"task": ui.linesTask, "step": step}, + }) +} -func (ui *taskExecutionJSONLines) StepStdoutWriter(ctx context.Context, task *executor.Task, step int) io.WriteCloser { - lt, ok := ui.linesTasks[task] - if !ok { - panic("unknown task started") - } +func (ui *stepsExecutionJSONLines) StepPreparing(step int) { + logEvent(batchesLogEvent{ + Operation: "TASK_PREPARING_STEP", + Status: "PROGRESS", + Message: fmt.Sprintf("Preparing step %d.", step), + Metadata: map[string]interface{}{"task": ui.linesTask, "step": step}, + }) +} + +func (ui *stepsExecutionJSONLines) StepStarted(step int, runScript string) { + logEvent(batchesLogEvent{ + Operation: "STEP", + Status: "STARTED", + Message: fmt.Sprintf("Starting step %d", step), + Metadata: map[string]interface{}{"task": ui.linesTask, "step": step, "runScript": runScript}, + }) +} +func (ui *stepsExecutionJSONLines) StepStdoutWriter(ctx context.Context, task *executor.Task, step int) io.WriteCloser { sink := func(data string) { logEvent(batchesLogEvent{ Operation: "STEP", Status: "PROGRESS", Message: data, Metadata: map[string]interface{}{ - "task": lt, + "task": ui.linesTask, "step": step, "output_type": "stdout", }, @@ -329,19 +390,14 @@ func (ui *taskExecutionJSONLines) StepStdoutWriter(ctx context.Context, task *ex return NewIntervalWriter(ctx, stepFlushDuration, sink) } -func (ui *taskExecutionJSONLines) StepStderrWriter(ctx context.Context, task *executor.Task, step int) io.WriteCloser { - lt, ok := ui.linesTasks[task] - if !ok { - panic("unknown task started") - } - +func (ui *stepsExecutionJSONLines) StepStderrWriter(ctx context.Context, task *executor.Task, step int) io.WriteCloser { sink := func(data string) { logEvent(batchesLogEvent{ Operation: "STEP", Status: "PROGRESS", Message: data, Metadata: map[string]interface{}{ - "task": lt, + "task": ui.linesTask, "step": step, "output_type": "stderr", }, @@ -350,3 +406,33 @@ func (ui *taskExecutionJSONLines) StepStderrWriter(ctx context.Context, task *ex return NewIntervalWriter(ctx, stepFlushDuration, sink) } + +func (ui *stepsExecutionJSONLines) StepFinished(step int, diff []byte, changes *git.Changes, outputs map[string]interface{}) { + logEvent(batchesLogEvent{ + Operation: "STEP", + Status: "SUCCESS", + Message: fmt.Sprintf("Finished step %d", step), + Metadata: map[string]interface{}{ + "task": ui.linesTask, + "step": step, + "diff": string(diff), + "changes": changes, + "outputs": outputs, + }, + }) +} + +func (ui *stepsExecutionJSONLines) CalculatingDiffStarted() { + logEvent(batchesLogEvent{ + Operation: "TASK_CALCULATING_DIFF", + Status: "STARTED", + Metadata: map[string]interface{}{"task": ui.linesTask}, + }) +} +func (ui *stepsExecutionJSONLines) CalculatingDiffFinished() { + logEvent(batchesLogEvent{ + Operation: "TASK_CALCULATING_DIFF", + Status: "SUCCESS", + Metadata: map[string]interface{}{"task": ui.linesTask}, + }) +} diff --git a/internal/batches/ui/task_exec_tui.go b/internal/batches/ui/task_exec_tui.go index 1e309f5dca..6f41cd4e59 100644 --- a/internal/batches/ui/task_exec_tui.go +++ b/internal/batches/ui/task_exec_tui.go @@ -13,6 +13,7 @@ import ( "github.com/sourcegraph/src-cli/internal/batches/executor" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" + "github.com/sourcegraph/sourcegraph/lib/batches/git" "github.com/sourcegraph/sourcegraph/lib/output" ) @@ -218,18 +219,29 @@ func (ui *taskExecTUI) TaskCurrentlyExecuting(task *executor.Task, message strin ui.progress.StatusBarUpdatef(bar, ts.String()) } -type discardCloser struct { - io.Writer -} +func (ui *taskExecTUI) StepsExecutionUI(task *executor.Task) executor.StepsExecutionUI { + ui.mu.Lock() + defer ui.mu.Unlock() -func (discardCloser) Close() error { return nil } + ts, ok := ui.statuses[task] + if !ok { + ui.out.Verbose("warning: task not found in internal 'statuses'") + return executor.NoopStepsExecUI{} + } -func (ui *taskExecTUI) StepStdoutWriter(ctx context.Context, task *executor.Task, stepidx int) io.WriteCloser { - return discardCloser{io.Discard} -} + bar, found := ui.findStatusBar(ts) + if !found { + ui.out.Verbose("warning: no free status bar found to display task status") + return executor.NoopStepsExecUI{} + } -func (ui *taskExecTUI) StepStderrWriter(ctx context.Context, task *executor.Task, stepidx int) io.WriteCloser { - return discardCloser{io.Discard} + return &stepsExecTUI{ + task: task, + updateStatusBar: func(message string) { + ts.currentlyExecuting = message + ui.progress.StatusBarUpdatef(bar, ts.String()) + }, + } } func (ui *taskExecTUI) TaskFinished(task *executor.Task, err error) { @@ -413,3 +425,55 @@ func diffStatDiagram(stat diff.Stat) string { output.StyleReset, ) } + +type stepsExecTUI struct { + task *executor.Task + updateStatusBar func(string) +} + +func (ui stepsExecTUI) ArchiveDownloadStarted() { + ui.updateStatusBar("Downloading archive") +} +func (ui stepsExecTUI) ArchiveDownloadFinished() {} +func (ui stepsExecTUI) WorkspaceInitializationStarted() { + ui.updateStatusBar("Initializing workspace") +} +func (ui stepsExecTUI) WorkspaceInitializationFinished() {} +func (ui stepsExecTUI) SkippingStepsUpto(startStep int) { + switch startStep { + case 1: + ui.updateStatusBar("Skipping step 1. Found cached result.") + default: + ui.updateStatusBar(fmt.Sprintf("Skipping steps 1 to %d. Found cached results.", startStep)) + } +} + +func (ui stepsExecTUI) StepSkipped(step int) { + ui.updateStatusBar(fmt.Sprintf("Skipping step %d", step)) +} +func (ui stepsExecTUI) StepPreparing(step int) { + ui.updateStatusBar(fmt.Sprintf("Preparing %d", step)) +} +func (ui stepsExecTUI) StepStarted(step int, runScript string) { + ui.updateStatusBar(runScript) +} + +func (ui stepsExecTUI) StepStdoutWriter(ctx context.Context, task *executor.Task, step int) io.WriteCloser { + return discardCloser{io.Discard} +} +func (ui stepsExecTUI) StepStderrWriter(ctx context.Context, task *executor.Task, step int) io.WriteCloser { + return discardCloser{io.Discard} +} +func (ui stepsExecTUI) CalculatingDiffStarted() { + ui.updateStatusBar("Calculating diff") +} +func (ui stepsExecTUI) CalculatingDiffFinished() { + // noop right now +} +func (ui stepsExecTUI) StepFinished(idx int, diff []byte, changes *git.Changes, outputs map[string]interface{}) { + // noop right now +} + +type discardCloser struct{ io.Writer } + +func (discardCloser) Close() error { return nil } From 2275dcf4aa8d750a25aec24b59d8034fcdebf0dd Mon Sep 17 00:00:00 2001 From: Thorsten Ball Date: Mon, 6 Sep 2021 11:09:42 +0200 Subject: [PATCH 032/647] Start/Wait on exec.Cmd when using pipes (#611) This might've been the cause for the flaky test we saw, because the docs say that `cmd.Run()` in combination with `StdoutPipe`/`StderrPipe` is wrong: > `Wait` will close the pipe after seeing the command exit, so most callers > need not close the pipe themselves. It is thus incorrect to call `Wait` > before all reads from the pipe have completed. For the same reason, it > is incorrect to call `Run` when using `StdoutPipe`. See the example for > idiomatic usage. See: https://pkg.go.dev/os/exec#example-Cmd.StdoutPipe --- internal/batches/executor/run_steps.go | 38 +++++++++++++++++--------- 1 file changed, 25 insertions(+), 13 deletions(-) diff --git a/internal/batches/executor/run_steps.go b/internal/batches/executor/run_steps.go index ba12688137..c942b9db2c 100644 --- a/internal/batches/executor/run_steps.go +++ b/internal/batches/executor/run_steps.go @@ -313,8 +313,6 @@ func executeSingleStep( cmd.Dir = *dir } - var stdoutBuffer, stderrBuffer bytes.Buffer - writerCtx, writerCancel := context.WithCancel(ctx) defer writerCancel() uiStdoutWriter := opts.ui.StepStdoutWriter(writerCtx, opts.task, i) @@ -324,33 +322,47 @@ func executeSingleStep( uiStderrWriter.Close() }() + var stdoutBuffer, stderrBuffer bytes.Buffer stdout := io.MultiWriter(&stdoutBuffer, uiStdoutWriter, opts.logger.PrefixWriter("stdout")) stderr := io.MultiWriter(&stderrBuffer, uiStderrWriter, opts.logger.PrefixWriter("stderr")) + // Setup readers that pipe the output into the given buffers wg, err := process.PipeOutput(cmd, stdout, stderr) if err != nil { return bytes.Buffer{}, bytes.Buffer{}, errors.Wrap(err, "piping process output") } + newStepFailedErr := func(wrappedErr error) stepFailedErr { + return stepFailedErr{ + Err: wrappedErr, + Args: cmd.Args, + Run: runScript, + Container: step.Container, + TmpFilename: containerTemp, + Stdout: strings.TrimSpace(stdoutBuffer.String()), + Stderr: strings.TrimSpace(stderrBuffer.String()), + } + } + opts.logger.Logf("[Step %d] run: %q, container: %q", i+1, step.Run, step.Container) opts.logger.Logf("[Step %d] full command: %q", i+1, strings.Join(cmd.Args, " ")) + // Start the command t0 := time.Now() - err = cmd.Run() + if err := cmd.Start(); err != nil { + opts.logger.Logf("[Step %d] error starting Docker container: %+v", i+1, err) + return stdoutBuffer, stderrBuffer, newStepFailedErr(err) + } + + // Wait for the readers, because the pipes used by PipeOutput under the + // hood are closed when the command exits wg.Wait() + // Now wait for the command + err = cmd.Wait() elapsed := time.Since(t0).Round(time.Millisecond) if err != nil { opts.logger.Logf("[Step %d] took %s; error running Docker container: %+v", i+1, elapsed, err) - - return stdoutBuffer, stderrBuffer, stepFailedErr{ - Err: err, - Args: cmd.Args, - Run: runScript, - Container: step.Container, - TmpFilename: containerTemp, - Stdout: strings.TrimSpace(stdoutBuffer.String()), - Stderr: strings.TrimSpace(stderrBuffer.String()), - } + return stdoutBuffer, stderrBuffer, newStepFailedErr(err) } opts.logger.Logf("[Step %d] complete in %s", i+1, elapsed) From 79626da113b42c2685659b1fbbb511fe62b717db Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Mon, 6 Sep 2021 13:27:24 +0200 Subject: [PATCH 033/647] Move fallback from `.` to `""` in workspace path into workspace finder (#605) --- internal/batches/service/build_tasks.go | 39 +++++++++--------------- internal/batches/service/service.go | 7 ++++- internal/batches/service/service_test.go | 2 +- 3 files changed, 21 insertions(+), 27 deletions(-) diff --git a/internal/batches/service/build_tasks.go b/internal/batches/service/build_tasks.go index c3c1957a46..f65f977e16 100644 --- a/internal/batches/service/build_tasks.go +++ b/internal/batches/service/build_tasks.go @@ -14,32 +14,21 @@ func buildTasks(ctx context.Context, spec *batcheslib.BatchSpec, workspaces []Re tasks := make([]*executor.Task, 0, len(workspaces)) for _, ws := range workspaces { - tasks = append(tasks, buildTask(spec, ws)) + task := &executor.Task{ + Repository: ws.Repo, + Path: ws.Path, + Steps: ws.Steps, + OnlyFetchWorkspace: ws.OnlyFetchWorkspace, + + TransformChanges: spec.TransformChanges, + Template: spec.ChangesetTemplate, + BatchChangeAttributes: &template.BatchChangeAttributes{ + Name: spec.Name, + Description: spec.Description, + }, + } + tasks = append(tasks, task) } return tasks } - -func buildTask(spec *batcheslib.BatchSpec, workspace RepoWorkspace) *executor.Task { - batchChange := template.BatchChangeAttributes{ - Name: spec.Name, - Description: spec.Description, - } - - // "." means the path is root, but in the executor we use "" to signify root. - path := workspace.Path - if path == "." { - path = "" - } - - return &executor.Task{ - Repository: workspace.Repo, - Path: path, - Steps: workspace.Steps, - OnlyFetchWorkspace: workspace.OnlyFetchWorkspace, - - TransformChanges: spec.TransformChanges, - Template: spec.ChangesetTemplate, - BatchChangeAttributes: &batchChange, - } -} diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index fd7f96c983..bed05e580d 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -681,11 +681,16 @@ func (svc *Service) FindDirectoriesInRepos(ctx context.Context, fileName string, var dirs []string for f := range files { + dir := path.Dir(f) + // "." means the path is root, but in the executor we use "" to signify root. + if dir == "." { + dir = "" + } // We use path.Dir and not filepath.Dir here, because while // src-cli might be executed on Windows, we need the paths to // be Unix paths, since they will be used inside Docker // containers. - dirs = append(dirs, path.Dir(f)) + dirs = append(dirs, dir) } results[repo] = dirs diff --git a/internal/batches/service/service_test.go b/internal/batches/service/service_test.go index 026adb2680..44d0cfb021 100644 --- a/internal/batches/service/service_test.go +++ b/internal/batches/service/service_test.go @@ -364,7 +364,7 @@ func TestService_FindDirectoriesInRepos(t *testing.T) { want := map[*graphql.Repository][]string{ repos[0]: {"examples/project3", "project1", "project2"}, - repos[1]: {"docs/client1", ".", "docs/client2/examples"}, + repos[1]: {"docs/client1", "", "docs/client2/examples"}, } if !cmp.Equal(want, results, cmpopts.SortSlices(sortStrings)) { From c67737397aa49bc73bf802a0749b320670b95016 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Mon, 6 Sep 2021 14:41:40 +0200 Subject: [PATCH 034/647] Streamline and improve JSON UI (#612) Next step I will move the step output definition into the shared lib, so we can use it server-side for parsing. --- cmd/src/batch_common.go | 2 +- go.mod | 1 + go.sum | 2 + internal/batches/service/service.go | 9 +- internal/batches/ui/exec_ui.go | 4 +- internal/batches/ui/json_lines.go | 354 +++++++++++++--------------- internal/batches/ui/tui.go | 6 +- 7 files changed, 182 insertions(+), 196 deletions(-) diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index 9cb220ec55..bc22a6ab90 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -337,7 +337,7 @@ func executeBatchSpec(ctx context.Context, opts executeBatchSpecOpts) (err error opts.ui.UploadingChangesetSpecsProgress(i+1, len(specs)) } - opts.ui.UploadingChangesetSpecsSuccess() + opts.ui.UploadingChangesetSpecsSuccess(ids) } else if len(repos) == 0 { opts.ui.NoChangesetSpecs() } diff --git a/go.mod b/go.mod index 36ac973b5b..47bf7faa3d 100644 --- a/go.mod +++ b/go.mod @@ -7,6 +7,7 @@ require ( github.com/cockroachdb/errors v1.8.6 github.com/cockroachdb/redact v1.1.3 // indirect github.com/derision-test/glock v0.0.0-20210316032053-f5b74334bb29 + github.com/dineshappavoo/basex v0.0.0-20170425072625-481a6f6dc663 github.com/dustin/go-humanize v1.0.0 github.com/gobwas/glob v0.2.3 github.com/google/go-cmp v0.5.6 diff --git a/go.sum b/go.sum index 4b6d9b7748..d225b62b53 100644 --- a/go.sum +++ b/go.sum @@ -49,6 +49,8 @@ github.com/derision-test/go-mockgen v1.1.2/go.mod h1:9H3VGTWYnL1VJoHHCuPKDpPFmNQ github.com/dgraph-io/badger v1.6.0/go.mod h1:zwt7syl517jmP8s94KqSxTlM6IMsdhYy6psNgSztDR4= github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= +github.com/dineshappavoo/basex v0.0.0-20170425072625-481a6f6dc663 h1:fctNkSsavbXpt8geFWZb8n+noCqS8MrOXRJ/YfdZ2dQ= +github.com/dineshappavoo/basex v0.0.0-20170425072625-481a6f6dc663/go.mod h1:Kad2hux31v/IyD4Rf4wAwIyK48995rs3qAl9IUAhc2k= github.com/dustin/go-humanize v1.0.0 h1:VSnTsYCnlFHaM2/igO1h6X3HA71jcobQuxemgkq4zYo= github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= github.com/efritz/pentimento v0.0.0-20190429011147-ade47d831101/go.mod h1:5ALWO82UZwfAtNRUtwzsWimcrcuYzyieTyyXOXrP6EQ= diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index bed05e580d..7a59dfce38 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -152,9 +152,9 @@ func (svc *Service) CreateChangesetSpec(ctx context.Context, spec *batcheslib.Ch // // Progress information is reported back to the given progress function: perc // will be a value between 0.0 and 1.0, inclusive. -func (svc *Service) EnsureDockerImages(ctx context.Context, spec *batcheslib.BatchSpec, progress func(perc float64)) (map[string]docker.Image, error) { - total := len(spec.Steps) + 1 - progress(0) +func (svc *Service) EnsureDockerImages(ctx context.Context, spec *batcheslib.BatchSpec, progress func(done, total int)) (map[string]docker.Image, error) { + total := len(spec.Steps) + progress(0, total) // TODO: this _really_ should be parallelised, since the image cache takes // care to only pull the same image once. @@ -166,10 +166,9 @@ func (svc *Service) EnsureDockerImages(ctx context.Context, spec *batcheslib.Bat } images[spec.Steps[i].Container] = img - progress(float64(i) / float64(total)) + progress(i+1, total) } - progress(1) return images, nil } diff --git a/internal/batches/ui/exec_ui.go b/internal/batches/ui/exec_ui.go index 6051f3592a..4c26727625 100644 --- a/internal/batches/ui/exec_ui.go +++ b/internal/batches/ui/exec_ui.go @@ -16,7 +16,7 @@ type ExecUI interface { ResolvingNamespaceSuccess(namespace string) PreparingContainerImages() - PreparingContainerImagesProgress(percent float64) + PreparingContainerImagesProgress(done, total int) PreparingContainerImagesSuccess() DeterminingWorkspaceCreatorType() @@ -39,7 +39,7 @@ type ExecUI interface { NoChangesetSpecs() UploadingChangesetSpecs(num int) UploadingChangesetSpecsProgress(done, total int) - UploadingChangesetSpecsSuccess() + UploadingChangesetSpecsSuccess(ids []graphql.ChangesetSpecID) CreatingBatchSpec() CreatingBatchSpecSuccess() diff --git a/internal/batches/ui/json_lines.go b/internal/batches/ui/json_lines.go index cb2a3f1759..e5e34423ea 100644 --- a/internal/batches/ui/json_lines.go +++ b/internal/batches/ui/json_lines.go @@ -5,9 +5,13 @@ import ( "encoding/json" "fmt" "io" + "math/rand" "os" + "strconv" "time" + "github.com/dineshappavoo/basex" + "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/executor" "github.com/sourcegraph/src-cli/internal/batches/graphql" @@ -17,102 +21,126 @@ import ( "github.com/sourcegraph/sourcegraph/lib/batches/git" ) +type BatchesLogEvent struct { + Operation LogEventOperation `json:"operation"` + + Timestamp time.Time `json:"timestamp"` + + Status LogEventStatus `json:"status"` + Metadata map[string]interface{} `json:"metadata,omitempty"` +} + +type LogEventOperation string + +const ( + LogEventOperationParsingBatchSpec LogEventOperation = "PARSING_BATCH_SPEC" + LogEventOperationResolvingNamespace LogEventOperation = "RESOLVING_NAMESPACE" + LogEventOperationPreparingDockerImages LogEventOperation = "PREPARING_DOCKER_IMAGES" + LogEventOperationDeterminingWorkspaceType LogEventOperation = "DETERMINING_WORKSPACE_TYPE" + LogEventOperationResolvingRepositories LogEventOperation = "RESOLVING_REPOSITORIES" + LogEventOperationDeterminingWorkspaces LogEventOperation = "DETERMINING_WORKSPACES" + LogEventOperationCheckingCache LogEventOperation = "CHECKING_CACHE" + LogEventOperationExecutingTasks LogEventOperation = "EXECUTING_TASKS" + LogEventOperationLogFileKept LogEventOperation = "LOG_FILE_KEPT" + LogEventOperationUploadingChangesetSpecs LogEventOperation = "UPLOADING_CHANGESET_SPECS" + LogEventOperationCreatingBatchSpec LogEventOperation = "CREATING_BATCH_SPEC" + LogEventOperationApplyingBatchSpec LogEventOperation = "APPLYING_BATCH_SPEC" + LogEventOperationBatchSpecExecution LogEventOperation = "BATCH_SPEC_EXECUTION" + LogEventOperationExecutingTask LogEventOperation = "EXECUTING_TASK" + LogEventOperationTaskBuildChangesetSpecs LogEventOperation = "TASK_BUILD_CHANGESET_SPECS" + LogEventOperationTaskDownloadingArchive LogEventOperation = "TASK_DOWNLOADING_ARCHIVE" + LogEventOperationTaskInitializingWorkspace LogEventOperation = "TASK_INITIALIZING_WORKSPACE" + LogEventOperationTaskSkippingSteps LogEventOperation = "TASK_SKIPPING_STEPS" + LogEventOperationTaskStepSkipped LogEventOperation = "TASK_STEP_SKIPPED" + LogEventOperationTaskPreparingStep LogEventOperation = "TASK_PREPARING_STEP" + LogEventOperationTaskStep LogEventOperation = "TASK_STEP" + LogEventOperationTaskCalculatingDiff LogEventOperation = "TASK_CALCULATING_DIFF" +) + +type LogEventStatus string + +const ( + LogEventStatusStarted LogEventStatus = "STARTED" + LogEventStatusSuccess LogEventStatus = "SUCCESS" + LogEventStatusFailure LogEventStatus = "FAILURE" + LogEventStatusProgress LogEventStatus = "PROGRESS" +) + var _ ExecUI = &JSONLines{} type JSONLines struct{} func (ui *JSONLines) ParsingBatchSpec() { - logOperationStart("PARSING_BATCH_SPEC", "") + logOperationStart(LogEventOperationParsingBatchSpec, nil) } func (ui *JSONLines) ParsingBatchSpecSuccess() { - logOperationSuccess("PARSING_BATCH_SPEC", "") + logOperationSuccess(LogEventOperationParsingBatchSpec, nil) } - func (ui *JSONLines) ParsingBatchSpecFailure(err error) { - logOperationFailure("PARSING_BATCH_SPEC", err.Error()) + logOperationFailure(LogEventOperationParsingBatchSpec, map[string]interface{}{"error": err.Error()}) } func (ui *JSONLines) ResolvingNamespace() { - logOperationStart("RESOLVING_NAMESPACE", "") + logOperationStart(LogEventOperationResolvingNamespace, nil) } func (ui *JSONLines) ResolvingNamespaceSuccess(namespace string) { - logOperationSuccess("RESOLVING_NAMESPACE", fmt.Sprintf("Namespace: %s", namespace)) + logOperationSuccess(LogEventOperationResolvingNamespace, map[string]interface{}{"namespaceID": namespace}) } + func (ui *JSONLines) PreparingContainerImages() { - logOperationStart("PREPARING_DOCKER_IMAGES", "") + logOperationStart(LogEventOperationPreparingDockerImages, nil) } -func (ui *JSONLines) PreparingContainerImagesProgress(percent float64) { - logOperationProgress("PREPARING_DOCKER_IMAGES", fmt.Sprintf("%d%% done", int(percent*100))) +func (ui *JSONLines) PreparingContainerImagesProgress(done, total int) { + logOperationProgress(LogEventOperationPreparingDockerImages, map[string]interface{}{"done": done, "total": total}) } func (ui *JSONLines) PreparingContainerImagesSuccess() { - logOperationSuccess("PREPARING_DOCKER_IMAGES", "") + logOperationSuccess(LogEventOperationPreparingDockerImages, nil) } + func (ui *JSONLines) DeterminingWorkspaceCreatorType() { - logOperationStart("DETERMINING_WORKSPACE_TYPE", "") + logOperationStart(LogEventOperationDeterminingWorkspaceType, nil) } func (ui *JSONLines) DeterminingWorkspaceCreatorTypeSuccess(wt workspace.CreatorType) { switch wt { case workspace.CreatorTypeVolume: - logOperationSuccess("DETERMINING_WORKSPACE_TYPE", "VOLUME") + logOperationSuccess(LogEventOperationDeterminingWorkspaceType, map[string]interface{}{"type": "VOLUME"}) case workspace.CreatorTypeBind: - logOperationSuccess("DETERMINING_WORKSPACE_TYPE", "BIND") + logOperationSuccess(LogEventOperationDeterminingWorkspaceType, map[string]interface{}{"type": "BIND"}) } } + func (ui *JSONLines) ResolvingRepositories() { - logOperationStart("RESOLVING_REPOSITORIES", "") + logOperationStart(LogEventOperationResolvingRepositories, nil) } - func (ui *JSONLines) ResolvingRepositoriesDone(repos []*graphql.Repository, unsupported batches.UnsupportedRepoSet, ignored batches.IgnoredRepoSet) { if unsupported != nil && len(unsupported) != 0 { - logOperationSuccess("RESOLVING_REPOSITORIES", fmt.Sprintf("%d unsupported repositories", len(unsupported))) + logOperationSuccess(LogEventOperationResolvingRepositories, map[string]interface{}{"unsupported": len(unsupported)}) } else if ignored != nil && len(ignored) != 0 { - logOperationSuccess("RESOLVING_REPOSITORIES", fmt.Sprintf("%d ignored repositories", len(ignored))) + logOperationSuccess(LogEventOperationResolvingRepositories, map[string]interface{}{"ignored": len(ignored)}) } else { - switch len(repos) { - case 0: - logOperationSuccess("RESOLVING_REPOSITORIES", "No repositories resolved") - case 1: - logOperationSuccess("RESOLVING_REPOSITORIES", "Resolved 1 repository") - default: - logOperationSuccess("RESOLVING_REPOSITORIES", fmt.Sprintf("Resolved %d repositories", len(repos))) - } + logOperationSuccess(LogEventOperationResolvingRepositories, map[string]interface{}{"count": len(repos)}) } } func (ui *JSONLines) DeterminingWorkspaces() { - logOperationStart("DETERMINING_WORKSPACES", "") + logOperationStart(LogEventOperationDeterminingWorkspaces, nil) } - func (ui *JSONLines) DeterminingWorkspacesSuccess(num int) { - switch num { - case 0: - logOperationSuccess("DETERMINING_WORKSPACES", "No workspace found") - case 1: - logOperationSuccess("DETERMINING_WORKSPACES", "Found a single workspace with steps to execute") - default: - logOperationSuccess("DETERMINING_WORKSPACES", fmt.Sprintf("Found %d workspaces with steps to execute", num)) + metadata := map[string]interface{}{ + "count": num, } + logOperationSuccess(LogEventOperationDeterminingWorkspaces, metadata) } func (ui *JSONLines) CheckingCache() { - logOperationStart("CHECKING_CACHE", "") + logOperationStart(LogEventOperationCheckingCache, nil) } - func (ui *JSONLines) CheckingCacheSuccess(cachedSpecsFound int, tasksToExecute int) { - var specsFoundMessage string - if cachedSpecsFound == 1 { - specsFoundMessage = "Found 1 cached changeset spec" - } else { - specsFoundMessage = fmt.Sprintf("Found %d cached changeset specs", cachedSpecsFound) - } - switch tasksToExecute { - case 0: - logOperationSuccess("CHECKING_CACHE", fmt.Sprintf("%s; no tasks need to be executed", specsFoundMessage)) - case 1: - logOperationSuccess("CHECKING_CACHE", fmt.Sprintf("%s; %d task needs to be executed", specsFoundMessage, tasksToExecute)) - default: - logOperationSuccess("CHECKING_CACHE", fmt.Sprintf("%s; %d tasks need to be executed", specsFoundMessage, tasksToExecute)) + metadata := map[string]interface{}{ + "cachedSpecsFound": cachedSpecsFound, + "tasksToExecute": tasksToExecute, } + logOperationSuccess(LogEventOperationCheckingCache, metadata) } func (ui *JSONLines) ExecutingTasks(verbose bool, parallelism int) executor.TaskExecutionUI { @@ -120,39 +148,40 @@ func (ui *JSONLines) ExecutingTasks(verbose bool, parallelism int) executor.Task } func (ui *JSONLines) ExecutingTasksSkippingErrors(err error) { - logOperationSuccess("EXECUTING_TASKS", fmt.Sprintf("Error: %s. Skipping errors because -skip-errors was used.", err)) + logOperationSuccess(LogEventOperationExecutingTasks, map[string]interface{}{"skipped": true, "error": err.Error()}) } func (ui *JSONLines) LogFilesKept(files []string) { for _, file := range files { - logOperationSuccess("LOG_FILE_KEPT", file) + logOperationSuccess(LogEventOperationLogFileKept, map[string]interface{}{"path": file}) } } func (ui *JSONLines) NoChangesetSpecs() { - logOperationSuccess("UPLOADING_CHANGESET_SPECS", "No changeset specs created") + ui.UploadingChangesetSpecsSuccess([]graphql.ChangesetSpecID{}) } func (ui *JSONLines) UploadingChangesetSpecs(num int) { - var label string - if num == 1 { - label = "Sending 1 changeset spec" - } else { - label = fmt.Sprintf("Sending %d changeset specs", num) - } - - logOperationStart("UPLOADING_CHANGESET_SPECS", label) + logOperationStart(LogEventOperationUploadingChangesetSpecs, map[string]interface{}{ + "total": num, + }) } func (ui *JSONLines) UploadingChangesetSpecsProgress(done, total int) { - logOperationProgress("UPLOADING_CHANGESET_SPECS", fmt.Sprintf("Uploaded %d out of %d", done, total)) + logOperationProgress(LogEventOperationUploadingChangesetSpecs, map[string]interface{}{ + "done": done, + "total": total, + }) } -func (ui *JSONLines) UploadingChangesetSpecsSuccess() { - logOperationSuccess("UPLOADING_CHANGESET_SPECS", "") + +func (ui *JSONLines) UploadingChangesetSpecsSuccess(ids []graphql.ChangesetSpecID) { + logOperationSuccess(LogEventOperationUploadingChangesetSpecs, map[string]interface{}{ + "ids": ids, + }) } func (ui *JSONLines) CreatingBatchSpec() { - logOperationStart("CREATING_BATCH_SPEC", "") + logOperationStart(LogEventOperationCreatingBatchSpec, nil) } func (ui *JSONLines) CreatingBatchSpecSuccess() { @@ -163,48 +192,38 @@ func (ui *JSONLines) CreatingBatchSpecError(err error) error { } func (ui *JSONLines) PreviewBatchSpec(batchSpecURL string) { - logOperationSuccess("CREATING_BATCH_SPEC", batchSpecURL) + logOperationSuccess(LogEventOperationCreatingBatchSpec, map[string]interface{}{"batchSpecURL": batchSpecURL}) } func (ui *JSONLines) ApplyingBatchSpec() { - logOperationStart("APPLYING_BATCH_SPEC", "") + logOperationStart(LogEventOperationApplyingBatchSpec, nil) } func (ui *JSONLines) ApplyingBatchSpecSuccess(batchChangeURL string) { - logOperationSuccess("APPLYING_BATCH_SPEC", batchChangeURL) + logOperationSuccess(LogEventOperationApplyingBatchSpec, map[string]interface{}{"batchChangeURL": batchChangeURL}) } func (ui *JSONLines) ExecutionError(err error) { - logOperationFailure("BATCH_SPEC_EXECUTION", err.Error()) -} - -type batchesLogEvent struct { - Operation string `json:"operation"` // "PREPARING_DOCKER_IMAGES" - - Timestamp time.Time `json:"timestamp"` - - Status string `json:"status"` // "STARTED", "PROGRESS", "SUCCESS", "FAILURE" - Message string `json:"message,omitempty"` // "70% done" - Metadata interface{} `json:"metadata,omitempty"` + logOperationFailure(LogEventOperationBatchSpecExecution, map[string]interface{}{"error": err.Error()}) } -func logOperationStart(op, msg string) { - logEvent(batchesLogEvent{Operation: op, Status: "STARTED", Message: msg}) +func logOperationStart(op LogEventOperation, metadata map[string]interface{}) { + logEvent(BatchesLogEvent{Operation: op, Status: LogEventStatusStarted, Metadata: metadata}) } -func logOperationSuccess(op, msg string) { - logEvent(batchesLogEvent{Operation: op, Status: "SUCCESS", Message: msg}) +func logOperationSuccess(op LogEventOperation, metadata map[string]interface{}) { + logEvent(BatchesLogEvent{Operation: op, Status: LogEventStatusSuccess, Metadata: metadata}) } -func logOperationFailure(op, msg string) { - logEvent(batchesLogEvent{Operation: op, Status: "FAILURE", Message: msg}) +func logOperationFailure(op LogEventOperation, metadata map[string]interface{}) { + logEvent(BatchesLogEvent{Operation: op, Status: LogEventStatusFailure, Metadata: metadata}) } -func logOperationProgress(op, msg string) { - logEvent(batchesLogEvent{Operation: op, Status: "PROGRESS", Message: msg}) +func logOperationProgress(op LogEventOperation, metadata map[string]interface{}) { + logEvent(BatchesLogEvent{Operation: op, Status: LogEventStatusProgress, Metadata: metadata}) } -func logEvent(e batchesLogEvent) { +func logEvent(e BatchesLogEvent) { e.Timestamp = time.Now().UTC().Truncate(time.Millisecond) err := json.NewEncoder(os.Stdout).Encode(e) if err != nil { @@ -215,11 +234,12 @@ func logEvent(e batchesLogEvent) { // TODO: Until we've figured out what exactly we want to expose, we create // these smaller UI-specific structs. type jsonLinesTask struct { - Repository string - Workspace string - Steps []batcheslib.Step - CachedStepResultsFound bool - StartStep int + ID string `json:"id"` + Repository string `json:"repository"` + Workspace string `json:"workspace"` + Steps []batcheslib.Step `json:"steps"` + CachedStepResultsFound bool `json:"cachedStepResultFound"` + StartStep int `json:"startStep"` } type taskExecutionJSONLines struct { @@ -229,11 +249,24 @@ type taskExecutionJSONLines struct { linesTasks map[*executor.Task]jsonLinesTask } +// seededRand is used in randomID() to generate a "random" number. +var seededRand = rand.New(rand.NewSource(time.Now().UTC().UnixNano())) + +// randomID generates a random ID to be used for identifiers in tasks. +func randomID() (string, error) { + return basex.Encode(strconv.Itoa(seededRand.Int())) +} + func (ui *taskExecutionJSONLines) Start(tasks []*executor.Task) { ui.linesTasks = make(map[*executor.Task]jsonLinesTask, len(tasks)) linesTasks := []jsonLinesTask{} for _, t := range tasks { + id, err := randomID() + if err != nil { + panic(err) + } linesTask := jsonLinesTask{ + ID: id, Repository: t.Repository.Name, Workspace: t.Path, Steps: t.Steps, @@ -244,13 +277,12 @@ func (ui *taskExecutionJSONLines) Start(tasks []*executor.Task) { linesTasks = append(linesTasks, linesTask) } - logEvent(batchesLogEvent{Operation: "EXECUTING_TASKS", Status: "STARTED", Metadata: map[string]interface{}{ + logOperationStart(LogEventOperationExecutingTasks, map[string]interface{}{ "tasks": linesTasks, - }}) + }) } - func (ui *taskExecutionJSONLines) Success() { - logEvent(batchesLogEvent{Operation: "EXECUTING_TASKS", Status: "SUCCESS"}) + logOperationSuccess(LogEventOperationExecutingTasks, nil) } func (ui *taskExecutionJSONLines) TaskStarted(task *executor.Task) { @@ -258,9 +290,10 @@ func (ui *taskExecutionJSONLines) TaskStarted(task *executor.Task) { if !ok { panic("unknown task started") } - logEvent(batchesLogEvent{Operation: "EXECUTING_TASK", Status: "STARTED", Metadata: map[string]interface{}{ - "task": lt, - }}) + + logOperationStart(LogEventOperationExecutingTask, map[string]interface{}{ + "taskID": lt.ID, + }) } func (ui *taskExecutionJSONLines) TaskFinished(task *executor.Task, err error) { @@ -268,17 +301,18 @@ func (ui *taskExecutionJSONLines) TaskFinished(task *executor.Task, err error) { if !ok { panic("unknown task started") } + if err != nil { - logEvent(batchesLogEvent{Operation: "EXECUTING_TASK", Status: "FAILURE", Metadata: map[string]interface{}{ - "task": lt, - "error": err, - }}) + logOperationFailure(LogEventOperationExecutingTask, map[string]interface{}{ + "taskID": lt.ID, + "error": err, + }) return } - logEvent(batchesLogEvent{Operation: "EXECUTING_TASK", Status: "SUCCESS", Metadata: map[string]interface{}{ - "task": lt, - }}) + logOperationSuccess(LogEventOperationExecutingTask, map[string]interface{}{ + "taskID": lt.ID, + }) } func (ui *taskExecutionJSONLines) TaskChangesetSpecsBuilt(task *executor.Task, specs []*batcheslib.ChangesetSpec) { @@ -286,9 +320,9 @@ func (ui *taskExecutionJSONLines) TaskChangesetSpecsBuilt(task *executor.Task, s if !ok { panic("unknown task started") } - logEvent(batchesLogEvent{Operation: "BUILDING_TASK_CHANGESET_SPECS", Status: "SUCCESS", Metadata: map[string]interface{}{ - "task": lt, - }}) + logOperationSuccess(LogEventOperationTaskBuildChangesetSpecs, map[string]interface{}{ + "taskID": lt.ID, + }) } func (ui *taskExecutionJSONLines) StepsExecutionUI(task *executor.Task) executor.StepsExecutionUI { @@ -307,132 +341,82 @@ type stepsExecutionJSONLines struct { const stepFlushDuration = 500 * time.Millisecond func (ui *stepsExecutionJSONLines) ArchiveDownloadStarted() { - logEvent(batchesLogEvent{ - Operation: "TASK_DOWNLOADING_ARCHIVE", - Status: "STARTED", - Message: "Downloading archive", - Metadata: map[string]interface{}{"task": ui.linesTask}, - }) + logOperationStart(LogEventOperationTaskDownloadingArchive, map[string]interface{}{"taskID": ui.linesTask.ID}) } func (ui *stepsExecutionJSONLines) ArchiveDownloadFinished() { - logEvent(batchesLogEvent{ - Operation: "TASK_DOWNLOADING_ARCHIVE", - Status: "FINISHED", - Metadata: map[string]interface{}{"task": ui.linesTask}, - }) + logOperationSuccess(LogEventOperationTaskDownloadingArchive, map[string]interface{}{"taskID": ui.linesTask.ID}) } func (ui *stepsExecutionJSONLines) WorkspaceInitializationStarted() { - logEvent(batchesLogEvent{ - Operation: "TASK_INITIALIZING_WORKSPACE", - Status: "STARTED", - Message: "Initializing workspace", - Metadata: map[string]interface{}{"task": ui.linesTask}, - }) + logOperationStart(LogEventOperationTaskInitializingWorkspace, map[string]interface{}{"taskID": ui.linesTask.ID}) } func (ui *stepsExecutionJSONLines) WorkspaceInitializationFinished() { - logEvent(batchesLogEvent{ - Operation: "TASK_INITIALIZING_WORKSPACE", - Status: "FINISHED", - Metadata: map[string]interface{}{"task": ui.linesTask}, - }) + logOperationSuccess(LogEventOperationTaskInitializingWorkspace, map[string]interface{}{"taskID": ui.linesTask.ID}) } func (ui *stepsExecutionJSONLines) SkippingStepsUpto(startStep int) { - logEvent(batchesLogEvent{ - Operation: "TASK_SKIPPING_STEPS", - Status: "PROGRESS", - Message: fmt.Sprintf("Skipping steps. Starting at %d.", startStep), - Metadata: map[string]interface{}{"task": ui.linesTask, "startStep": startStep}, - }) + logOperationProgress(LogEventOperationTaskSkippingSteps, map[string]interface{}{"taskID": ui.linesTask.ID, "startStep": startStep}) } func (ui *stepsExecutionJSONLines) StepSkipped(step int) { - logEvent(batchesLogEvent{ - Operation: "TASK_STEP_SKIPPED", - Status: "PROGRESS", - Message: fmt.Sprintf("Skipping step %d.", step), - Metadata: map[string]interface{}{"task": ui.linesTask, "step": step}, - }) + logOperationProgress(LogEventOperationTaskStepSkipped, map[string]interface{}{"taskID": ui.linesTask.ID, "step": step}) } func (ui *stepsExecutionJSONLines) StepPreparing(step int) { - logEvent(batchesLogEvent{ - Operation: "TASK_PREPARING_STEP", - Status: "PROGRESS", - Message: fmt.Sprintf("Preparing step %d.", step), - Metadata: map[string]interface{}{"task": ui.linesTask, "step": step}, - }) + logOperationProgress(LogEventOperationTaskPreparingStep, map[string]interface{}{"taskID": ui.linesTask.ID, "step": step}) } func (ui *stepsExecutionJSONLines) StepStarted(step int, runScript string) { - logEvent(batchesLogEvent{ - Operation: "STEP", - Status: "STARTED", - Message: fmt.Sprintf("Starting step %d", step), - Metadata: map[string]interface{}{"task": ui.linesTask, "step": step, "runScript": runScript}, - }) + logOperationStart(LogEventOperationTaskStep, map[string]interface{}{"taskID": ui.linesTask.ID, "step": step, "runScript": runScript}) } func (ui *stepsExecutionJSONLines) StepStdoutWriter(ctx context.Context, task *executor.Task, step int) io.WriteCloser { sink := func(data string) { - logEvent(batchesLogEvent{ - Operation: "STEP", - Status: "PROGRESS", - Message: data, - Metadata: map[string]interface{}{ - "task": ui.linesTask, + logOperationProgress( + LogEventOperationTaskStep, + map[string]interface{}{ + "taskID": ui.linesTask.ID, "step": step, + "out": data, "output_type": "stdout", }, - }) + ) } return NewIntervalWriter(ctx, stepFlushDuration, sink) } func (ui *stepsExecutionJSONLines) StepStderrWriter(ctx context.Context, task *executor.Task, step int) io.WriteCloser { sink := func(data string) { - logEvent(batchesLogEvent{ - Operation: "STEP", - Status: "PROGRESS", - Message: data, - Metadata: map[string]interface{}{ - "task": ui.linesTask, + logOperationProgress( + LogEventOperationTaskStep, + map[string]interface{}{ + "taskID": ui.linesTask.ID, "step": step, + "out": data, "output_type": "stderr", }, - }) + ) } return NewIntervalWriter(ctx, stepFlushDuration, sink) } func (ui *stepsExecutionJSONLines) StepFinished(step int, diff []byte, changes *git.Changes, outputs map[string]interface{}) { - logEvent(batchesLogEvent{ - Operation: "STEP", - Status: "SUCCESS", - Message: fmt.Sprintf("Finished step %d", step), - Metadata: map[string]interface{}{ + logOperationSuccess( + LogEventOperationTaskStep, + map[string]interface{}{ "task": ui.linesTask, "step": step, "diff": string(diff), "changes": changes, "outputs": outputs, }, - }) + ) } func (ui *stepsExecutionJSONLines) CalculatingDiffStarted() { - logEvent(batchesLogEvent{ - Operation: "TASK_CALCULATING_DIFF", - Status: "STARTED", - Metadata: map[string]interface{}{"task": ui.linesTask}, - }) + logOperationStart(LogEventOperationTaskCalculatingDiff, map[string]interface{}{"taskID": ui.linesTask.ID}) } func (ui *stepsExecutionJSONLines) CalculatingDiffFinished() { - logEvent(batchesLogEvent{ - Operation: "TASK_CALCULATING_DIFF", - Status: "SUCCESS", - Metadata: map[string]interface{}{"task": ui.linesTask}, - }) + logOperationSuccess(LogEventOperationTaskCalculatingDiff, map[string]interface{}{"taskID": ui.linesTask.ID}) } diff --git a/internal/batches/ui/tui.go b/internal/batches/ui/tui.go index 1817646464..ef207330f4 100644 --- a/internal/batches/ui/tui.go +++ b/internal/batches/ui/tui.go @@ -68,8 +68,8 @@ func (ui *TUI) PreparingContainerImages() { }}, nil) } -func (ui *TUI) PreparingContainerImagesProgress(percent float64) { - ui.progress.SetValue(0, percent) +func (ui *TUI) PreparingContainerImagesProgress(done, total int) { + ui.progress.SetValue(0, float64(done)/float64(total)) } func (ui *TUI) PreparingContainerImagesSuccess() { @@ -181,7 +181,7 @@ func (ui *TUI) UploadingChangesetSpecsProgress(done, total int) { ui.progress.SetValue(0, float64(done)) } -func (ui *TUI) UploadingChangesetSpecsSuccess() { +func (ui *TUI) UploadingChangesetSpecsSuccess(ids []graphql.ChangesetSpecID) { ui.progress.Complete() } From 2b0cf4637c9abbbadcaf957b3207e026055fab24 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Mon, 6 Sep 2021 14:52:38 +0200 Subject: [PATCH 035/647] Upgrade to latest lib version (#613) --- go.mod | 2 +- go.sum | 4 ++-- internal/batches/util/repo.go | 6 +++++- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/go.mod b/go.mod index 47bf7faa3d..d7d2da0e73 100644 --- a/go.mod +++ b/go.mod @@ -22,7 +22,7 @@ require ( github.com/sourcegraph/batch-change-utils v0.0.0-20210708162152-c9f35b905d94 github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf - github.com/sourcegraph/sourcegraph/lib v0.0.0-20210903080558-3f16affc1edc + github.com/sourcegraph/sourcegraph/lib v0.0.0-20210906124104-d18be6b57521 github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect golang.org/x/net v0.0.0-20210614182718-04defd469f4e diff --git a/go.sum b/go.sum index d225b62b53..86b08634ab 100644 --- a/go.sum +++ b/go.sum @@ -261,8 +261,8 @@ github.com/sourcegraph/go-diff v0.6.1 h1:hmA1LzxW0n1c3Q4YbrFgg4P99GSnebYa3x8gr0H github.com/sourcegraph/go-diff v0.6.1/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20210903080558-3f16affc1edc h1:iMV2Nc/fCn3PrG9vgFgXN2LdY6mDfcGuzQe9ObCT/U4= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20210903080558-3f16affc1edc/go.mod h1:ZK8mHKWdapYI8iIQwsO7QUxf44RjiNGKkOZa9aYIjTc= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20210906124104-d18be6b57521 h1:buaBM1YCjWt6+DlXESM5EAmZ+SvlUteXpnyQmGa07HA= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20210906124104-d18be6b57521/go.mod h1:ZK8mHKWdapYI8iIQwsO7QUxf44RjiNGKkOZa9aYIjTc= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= diff --git a/internal/batches/util/repo.go b/internal/batches/util/repo.go index a481cbdf6e..705784a972 100644 --- a/internal/batches/util/repo.go +++ b/internal/batches/util/repo.go @@ -11,9 +11,13 @@ import ( // NewTemplatingRepo transforms a given *graphql.Repository into a // template.Repository. func NewTemplatingRepo(repoName string, fileMatches map[string]bool) template.Repository { + matches := make([]string, 0, len(fileMatches)) + for path := range fileMatches { + matches = append(matches, path) + } return template.Repository{ Name: repoName, - FileMatches: fileMatches, + FileMatches: matches, } } From f9632c46421fd3f04545150df186280601e9fcc0 Mon Sep 17 00:00:00 2001 From: Rijnard van Tonder Date: Mon, 6 Sep 2021 19:30:27 -0700 Subject: [PATCH 036/647] search: rename result type fields consistently (#610) --- cmd/src/search_stream_test.go | 4 ++-- cmd/src/testdata/streaming_search_want.json | 4 ++-- internal/streaming/events.go | 12 ++++++------ 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/cmd/src/search_stream_test.go b/cmd/src/search_stream_test.go index 8d55dee145..2eea7589a6 100644 --- a/cmd/src/search_stream_test.go +++ b/cmd/src/search_stream_test.go @@ -42,7 +42,7 @@ var event = []streaming.EventMatch{ Path: "path/to/file", Repository: "org/repo", Branches: nil, - Version: "", + Commit: "", LineMatches: []streaming.EventLineMatch{ { Line: "foo bar foo", @@ -61,7 +61,7 @@ var event = []streaming.EventMatch{ Path: "path/to/file", Repository: "org/repo", Branches: []string{}, - Version: "", + Commit: "", Symbols: []streaming.Symbol{ { URL: "github.com/sourcegraph/sourcegraph/-/blob/cmd/frontend/graphqlbackend/search_results.go#L1591:26-1591:35", diff --git a/cmd/src/testdata/streaming_search_want.json b/cmd/src/testdata/streaming_search_want.json index 86936f2909..cd98ef048d 100755 --- a/cmd/src/testdata/streaming_search_want.json +++ b/cmd/src/testdata/streaming_search_want.json @@ -1,5 +1,5 @@ -{"type":"content","name":"path/to/file","repository":"org/repo","lineMatches":[{"line":"foo bar foo","lineNumber":4,"offsetAndLengths":[[0,3],[8,3]]}]} +{"type":"content","path":"path/to/file","repository":"org/repo","lineMatches":[{"line":"foo bar foo","lineNumber":4,"offsetAndLengths":[[0,3],[8,3]]}]} {"type":"repo","repository":"sourcegraph/sourcegraph"} -{"type":"symbol","name":"path/to/file","repository":"org/repo","symbols":[{"url":"github.com/sourcegraph/sourcegraph/-/blob/cmd/frontend/graphqlbackend/search_results.go#L1591:26-1591:35","name":"doResults","containerName":"","kind":"FUNCTION"},{"url":"github.com/sourcegraph/sourcegraph/-/blob/cmd/frontend/graphqlbackend/search_results.go#L1591:26-1591:35","name":"Results","containerName":"SearchResultsResolver","kind":"FIELD"}]} +{"type":"symbol","path":"path/to/file","repository":"org/repo","symbols":[{"url":"github.com/sourcegraph/sourcegraph/-/blob/cmd/frontend/graphqlbackend/search_results.go#L1591:26-1591:35","name":"doResults","containerName":"","kind":"FUNCTION"},{"url":"github.com/sourcegraph/sourcegraph/-/blob/cmd/frontend/graphqlbackend/search_results.go#L1591:26-1591:35","name":"Results","containerName":"SearchResultsResolver","kind":"FIELD"}]} {"type":"commit","icon":"","label":"[sourcegraph/sourcegraph-atom](/github.com/sourcegraph/sourcegraph-atom) › [Stephen Gutekanst](/github.com/sourcegraph/sourcegraph-atom/-/commit/5b098d7fed963d88e23057ed99d73d3c7a33ad89): [all: release v1.0.5](/github.com/sourcegraph/sourcegraph-atom/-/commit/5b098d7fed963d88e23057ed99d73d3c7a33ad89)^","url":"","detail":"","content":"```COMMIT_EDITMSG\nfoo bar\n```","ranges":[[1,3,3]]} {"type":"commit","icon":"","label":"[sourcegraph/sourcegraph-atom](/github.com/sourcegraph/sourcegraph-atom) › [Stephen Gutekanst](/github.com/sourcegraph/sourcegraph-atom/-/commit/5b098d7fed963d88e23057ed99d73d3c7a33ad89): [all: release v1.0.5](/github.com/sourcegraph/sourcegraph-atom/-/commit/5b098d7fed963d88e23057ed99d73d3c7a33ad89)^","url":"","detail":"","content":"```diff\nsrc/data.ts src/data.ts\n@@ -0,0 +11,4 @@\n+ return of\u003cData\u003e({\n+ title: 'Acme Corp open-source code search',\n+ summary: 'Instant code search across all Acme Corp open-source code.',\n+ githubOrgs: ['sourcegraph'],\n```","ranges":[[4,44,6]]} diff --git a/internal/streaming/events.go b/internal/streaming/events.go index c30eac40c5..22e69b7ee3 100644 --- a/internal/streaming/events.go +++ b/internal/streaming/events.go @@ -17,10 +17,10 @@ type EventContentMatch struct { // Type is always ContentMatchType. Included here for marshalling. Type MatchType `json:"type"` - Path string `json:"name"` + Path string `json:"path"` Repository string `json:"repository"` Branches []string `json:"branches,omitempty"` - Version string `json:"version,omitempty"` + Commit string `json:"commit,omitempty"` LineMatches []EventLineMatch `json:"lineMatches"` } @@ -32,10 +32,10 @@ type EventPathMatch struct { // Type is always PathMatchType. Included here for marshalling. Type MatchType `json:"type"` - Path string `json:"name"` + Path string `json:"path"` Repository string `json:"repository"` Branches []string `json:"branches,omitempty"` - Version string `json:"version,omitempty"` + Commit string `json:"commit,omitempty"` } func (e *EventPathMatch) eventMatch() {} @@ -63,10 +63,10 @@ type EventSymbolMatch struct { // Type is always SymbolMatchType. Included here for marshalling. Type MatchType `json:"type"` - Path string `json:"name"` + Path string `json:"path"` Repository string `json:"repository"` Branches []string `json:"branches,omitempty"` - Version string `json:"version,omitempty"` + Commit string `json:"commit,omitempty"` Symbols []Symbol `json:"symbols"` } From ec9b4880db79e3df3036ee6977dc385335c02686 Mon Sep 17 00:00:00 2001 From: Thorsten Ball Date: Tue, 7 Sep 2021 10:08:14 +0200 Subject: [PATCH 037/647] Upgrade lib to have fix for PipeOutput deadlock (#615) PR on the other side: https://github.com/sourcegraph/sourcegraph/pull/24654 --- go.mod | 2 +- go.sum | 4 ++-- internal/batches/executor/run_steps.go | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/go.mod b/go.mod index d7d2da0e73..31a016bc7a 100644 --- a/go.mod +++ b/go.mod @@ -22,7 +22,7 @@ require ( github.com/sourcegraph/batch-change-utils v0.0.0-20210708162152-c9f35b905d94 github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf - github.com/sourcegraph/sourcegraph/lib v0.0.0-20210906124104-d18be6b57521 + github.com/sourcegraph/sourcegraph/lib v0.0.0-20210907041800-ae0266126192 github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect golang.org/x/net v0.0.0-20210614182718-04defd469f4e diff --git a/go.sum b/go.sum index 86b08634ab..8b7447eb51 100644 --- a/go.sum +++ b/go.sum @@ -261,8 +261,8 @@ github.com/sourcegraph/go-diff v0.6.1 h1:hmA1LzxW0n1c3Q4YbrFgg4P99GSnebYa3x8gr0H github.com/sourcegraph/go-diff v0.6.1/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20210906124104-d18be6b57521 h1:buaBM1YCjWt6+DlXESM5EAmZ+SvlUteXpnyQmGa07HA= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20210906124104-d18be6b57521/go.mod h1:ZK8mHKWdapYI8iIQwsO7QUxf44RjiNGKkOZa9aYIjTc= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20210907041800-ae0266126192 h1:/OdZqWVKxON/1/J6a/cw2kZJtRNpampaFekn0Gnzefg= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20210907041800-ae0266126192/go.mod h1:ZK8mHKWdapYI8iIQwsO7QUxf44RjiNGKkOZa9aYIjTc= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= diff --git a/internal/batches/executor/run_steps.go b/internal/batches/executor/run_steps.go index c942b9db2c..cdbe92d70f 100644 --- a/internal/batches/executor/run_steps.go +++ b/internal/batches/executor/run_steps.go @@ -327,7 +327,7 @@ func executeSingleStep( stderr := io.MultiWriter(&stderrBuffer, uiStderrWriter, opts.logger.PrefixWriter("stderr")) // Setup readers that pipe the output into the given buffers - wg, err := process.PipeOutput(cmd, stdout, stderr) + wg, err := process.PipeOutput(ctx, cmd, stdout, stderr) if err != nil { return bytes.Buffer{}, bytes.Buffer{}, errors.Wrap(err, "piping process output") } From 3425cf1b6954c13ae7ccf804cc058cf81eea8169 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Tue, 7 Sep 2021 13:33:55 +0200 Subject: [PATCH 038/647] Use latest lib version (#616) Includes the types for the JSON lines UI. --- go.mod | 2 +- go.sum | 4 +- internal/batches/ui/json_lines.go | 161 +++++++++++------------------- 3 files changed, 61 insertions(+), 106 deletions(-) diff --git a/go.mod b/go.mod index 31a016bc7a..ae1a29c1e1 100644 --- a/go.mod +++ b/go.mod @@ -22,7 +22,7 @@ require ( github.com/sourcegraph/batch-change-utils v0.0.0-20210708162152-c9f35b905d94 github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf - github.com/sourcegraph/sourcegraph/lib v0.0.0-20210907041800-ae0266126192 + github.com/sourcegraph/sourcegraph/lib v0.0.0-20210907100420-bac67ad72375 github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect golang.org/x/net v0.0.0-20210614182718-04defd469f4e diff --git a/go.sum b/go.sum index 8b7447eb51..932574103b 100644 --- a/go.sum +++ b/go.sum @@ -261,8 +261,8 @@ github.com/sourcegraph/go-diff v0.6.1 h1:hmA1LzxW0n1c3Q4YbrFgg4P99GSnebYa3x8gr0H github.com/sourcegraph/go-diff v0.6.1/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20210907041800-ae0266126192 h1:/OdZqWVKxON/1/J6a/cw2kZJtRNpampaFekn0Gnzefg= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20210907041800-ae0266126192/go.mod h1:ZK8mHKWdapYI8iIQwsO7QUxf44RjiNGKkOZa9aYIjTc= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20210907100420-bac67ad72375 h1:LRWLkOq2jsxKpxAr1tu6JmY9xjmxZV9Rjae9VdtTtCQ= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20210907100420-bac67ad72375/go.mod h1:ZK8mHKWdapYI8iIQwsO7QUxf44RjiNGKkOZa9aYIjTc= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= diff --git a/internal/batches/ui/json_lines.go b/internal/batches/ui/json_lines.go index e5e34423ea..528358127b 100644 --- a/internal/batches/ui/json_lines.go +++ b/internal/batches/ui/json_lines.go @@ -21,126 +21,81 @@ import ( "github.com/sourcegraph/sourcegraph/lib/batches/git" ) -type BatchesLogEvent struct { - Operation LogEventOperation `json:"operation"` - - Timestamp time.Time `json:"timestamp"` - - Status LogEventStatus `json:"status"` - Metadata map[string]interface{} `json:"metadata,omitempty"` -} - -type LogEventOperation string - -const ( - LogEventOperationParsingBatchSpec LogEventOperation = "PARSING_BATCH_SPEC" - LogEventOperationResolvingNamespace LogEventOperation = "RESOLVING_NAMESPACE" - LogEventOperationPreparingDockerImages LogEventOperation = "PREPARING_DOCKER_IMAGES" - LogEventOperationDeterminingWorkspaceType LogEventOperation = "DETERMINING_WORKSPACE_TYPE" - LogEventOperationResolvingRepositories LogEventOperation = "RESOLVING_REPOSITORIES" - LogEventOperationDeterminingWorkspaces LogEventOperation = "DETERMINING_WORKSPACES" - LogEventOperationCheckingCache LogEventOperation = "CHECKING_CACHE" - LogEventOperationExecutingTasks LogEventOperation = "EXECUTING_TASKS" - LogEventOperationLogFileKept LogEventOperation = "LOG_FILE_KEPT" - LogEventOperationUploadingChangesetSpecs LogEventOperation = "UPLOADING_CHANGESET_SPECS" - LogEventOperationCreatingBatchSpec LogEventOperation = "CREATING_BATCH_SPEC" - LogEventOperationApplyingBatchSpec LogEventOperation = "APPLYING_BATCH_SPEC" - LogEventOperationBatchSpecExecution LogEventOperation = "BATCH_SPEC_EXECUTION" - LogEventOperationExecutingTask LogEventOperation = "EXECUTING_TASK" - LogEventOperationTaskBuildChangesetSpecs LogEventOperation = "TASK_BUILD_CHANGESET_SPECS" - LogEventOperationTaskDownloadingArchive LogEventOperation = "TASK_DOWNLOADING_ARCHIVE" - LogEventOperationTaskInitializingWorkspace LogEventOperation = "TASK_INITIALIZING_WORKSPACE" - LogEventOperationTaskSkippingSteps LogEventOperation = "TASK_SKIPPING_STEPS" - LogEventOperationTaskStepSkipped LogEventOperation = "TASK_STEP_SKIPPED" - LogEventOperationTaskPreparingStep LogEventOperation = "TASK_PREPARING_STEP" - LogEventOperationTaskStep LogEventOperation = "TASK_STEP" - LogEventOperationTaskCalculatingDiff LogEventOperation = "TASK_CALCULATING_DIFF" -) - -type LogEventStatus string - -const ( - LogEventStatusStarted LogEventStatus = "STARTED" - LogEventStatusSuccess LogEventStatus = "SUCCESS" - LogEventStatusFailure LogEventStatus = "FAILURE" - LogEventStatusProgress LogEventStatus = "PROGRESS" -) - var _ ExecUI = &JSONLines{} type JSONLines struct{} func (ui *JSONLines) ParsingBatchSpec() { - logOperationStart(LogEventOperationParsingBatchSpec, nil) + logOperationStart(batcheslib.LogEventOperationParsingBatchSpec, nil) } func (ui *JSONLines) ParsingBatchSpecSuccess() { - logOperationSuccess(LogEventOperationParsingBatchSpec, nil) + logOperationSuccess(batcheslib.LogEventOperationParsingBatchSpec, nil) } func (ui *JSONLines) ParsingBatchSpecFailure(err error) { - logOperationFailure(LogEventOperationParsingBatchSpec, map[string]interface{}{"error": err.Error()}) + logOperationFailure(batcheslib.LogEventOperationParsingBatchSpec, map[string]interface{}{"error": err.Error()}) } func (ui *JSONLines) ResolvingNamespace() { - logOperationStart(LogEventOperationResolvingNamespace, nil) + logOperationStart(batcheslib.LogEventOperationResolvingNamespace, nil) } func (ui *JSONLines) ResolvingNamespaceSuccess(namespace string) { - logOperationSuccess(LogEventOperationResolvingNamespace, map[string]interface{}{"namespaceID": namespace}) + logOperationSuccess(batcheslib.LogEventOperationResolvingNamespace, map[string]interface{}{"namespaceID": namespace}) } func (ui *JSONLines) PreparingContainerImages() { - logOperationStart(LogEventOperationPreparingDockerImages, nil) + logOperationStart(batcheslib.LogEventOperationPreparingDockerImages, nil) } func (ui *JSONLines) PreparingContainerImagesProgress(done, total int) { - logOperationProgress(LogEventOperationPreparingDockerImages, map[string]interface{}{"done": done, "total": total}) + logOperationProgress(batcheslib.LogEventOperationPreparingDockerImages, map[string]interface{}{"done": done, "total": total}) } func (ui *JSONLines) PreparingContainerImagesSuccess() { - logOperationSuccess(LogEventOperationPreparingDockerImages, nil) + logOperationSuccess(batcheslib.LogEventOperationPreparingDockerImages, nil) } func (ui *JSONLines) DeterminingWorkspaceCreatorType() { - logOperationStart(LogEventOperationDeterminingWorkspaceType, nil) + logOperationStart(batcheslib.LogEventOperationDeterminingWorkspaceType, nil) } func (ui *JSONLines) DeterminingWorkspaceCreatorTypeSuccess(wt workspace.CreatorType) { switch wt { case workspace.CreatorTypeVolume: - logOperationSuccess(LogEventOperationDeterminingWorkspaceType, map[string]interface{}{"type": "VOLUME"}) + logOperationSuccess(batcheslib.LogEventOperationDeterminingWorkspaceType, map[string]interface{}{"type": "VOLUME"}) case workspace.CreatorTypeBind: - logOperationSuccess(LogEventOperationDeterminingWorkspaceType, map[string]interface{}{"type": "BIND"}) + logOperationSuccess(batcheslib.LogEventOperationDeterminingWorkspaceType, map[string]interface{}{"type": "BIND"}) } } func (ui *JSONLines) ResolvingRepositories() { - logOperationStart(LogEventOperationResolvingRepositories, nil) + logOperationStart(batcheslib.LogEventOperationResolvingRepositories, nil) } func (ui *JSONLines) ResolvingRepositoriesDone(repos []*graphql.Repository, unsupported batches.UnsupportedRepoSet, ignored batches.IgnoredRepoSet) { if unsupported != nil && len(unsupported) != 0 { - logOperationSuccess(LogEventOperationResolvingRepositories, map[string]interface{}{"unsupported": len(unsupported)}) + logOperationSuccess(batcheslib.LogEventOperationResolvingRepositories, map[string]interface{}{"unsupported": len(unsupported)}) } else if ignored != nil && len(ignored) != 0 { - logOperationSuccess(LogEventOperationResolvingRepositories, map[string]interface{}{"ignored": len(ignored)}) + logOperationSuccess(batcheslib.LogEventOperationResolvingRepositories, map[string]interface{}{"ignored": len(ignored)}) } else { - logOperationSuccess(LogEventOperationResolvingRepositories, map[string]interface{}{"count": len(repos)}) + logOperationSuccess(batcheslib.LogEventOperationResolvingRepositories, map[string]interface{}{"count": len(repos)}) } } func (ui *JSONLines) DeterminingWorkspaces() { - logOperationStart(LogEventOperationDeterminingWorkspaces, nil) + logOperationStart(batcheslib.LogEventOperationDeterminingWorkspaces, nil) } func (ui *JSONLines) DeterminingWorkspacesSuccess(num int) { metadata := map[string]interface{}{ "count": num, } - logOperationSuccess(LogEventOperationDeterminingWorkspaces, metadata) + logOperationSuccess(batcheslib.LogEventOperationDeterminingWorkspaces, metadata) } func (ui *JSONLines) CheckingCache() { - logOperationStart(LogEventOperationCheckingCache, nil) + logOperationStart(batcheslib.LogEventOperationCheckingCache, nil) } func (ui *JSONLines) CheckingCacheSuccess(cachedSpecsFound int, tasksToExecute int) { metadata := map[string]interface{}{ "cachedSpecsFound": cachedSpecsFound, "tasksToExecute": tasksToExecute, } - logOperationSuccess(LogEventOperationCheckingCache, metadata) + logOperationSuccess(batcheslib.LogEventOperationCheckingCache, metadata) } func (ui *JSONLines) ExecutingTasks(verbose bool, parallelism int) executor.TaskExecutionUI { @@ -148,12 +103,12 @@ func (ui *JSONLines) ExecutingTasks(verbose bool, parallelism int) executor.Task } func (ui *JSONLines) ExecutingTasksSkippingErrors(err error) { - logOperationSuccess(LogEventOperationExecutingTasks, map[string]interface{}{"skipped": true, "error": err.Error()}) + logOperationSuccess(batcheslib.LogEventOperationExecutingTasks, map[string]interface{}{"skipped": true, "error": err.Error()}) } func (ui *JSONLines) LogFilesKept(files []string) { for _, file := range files { - logOperationSuccess(LogEventOperationLogFileKept, map[string]interface{}{"path": file}) + logOperationSuccess(batcheslib.LogEventOperationLogFileKept, map[string]interface{}{"path": file}) } } @@ -162,26 +117,26 @@ func (ui *JSONLines) NoChangesetSpecs() { } func (ui *JSONLines) UploadingChangesetSpecs(num int) { - logOperationStart(LogEventOperationUploadingChangesetSpecs, map[string]interface{}{ + logOperationStart(batcheslib.LogEventOperationUploadingChangesetSpecs, map[string]interface{}{ "total": num, }) } func (ui *JSONLines) UploadingChangesetSpecsProgress(done, total int) { - logOperationProgress(LogEventOperationUploadingChangesetSpecs, map[string]interface{}{ + logOperationProgress(batcheslib.LogEventOperationUploadingChangesetSpecs, map[string]interface{}{ "done": done, "total": total, }) } func (ui *JSONLines) UploadingChangesetSpecsSuccess(ids []graphql.ChangesetSpecID) { - logOperationSuccess(LogEventOperationUploadingChangesetSpecs, map[string]interface{}{ + logOperationSuccess(batcheslib.LogEventOperationUploadingChangesetSpecs, map[string]interface{}{ "ids": ids, }) } func (ui *JSONLines) CreatingBatchSpec() { - logOperationStart(LogEventOperationCreatingBatchSpec, nil) + logOperationStart(batcheslib.LogEventOperationCreatingBatchSpec, nil) } func (ui *JSONLines) CreatingBatchSpecSuccess() { @@ -192,38 +147,38 @@ func (ui *JSONLines) CreatingBatchSpecError(err error) error { } func (ui *JSONLines) PreviewBatchSpec(batchSpecURL string) { - logOperationSuccess(LogEventOperationCreatingBatchSpec, map[string]interface{}{"batchSpecURL": batchSpecURL}) + logOperationSuccess(batcheslib.LogEventOperationCreatingBatchSpec, map[string]interface{}{"batchSpecURL": batchSpecURL}) } func (ui *JSONLines) ApplyingBatchSpec() { - logOperationStart(LogEventOperationApplyingBatchSpec, nil) + logOperationStart(batcheslib.LogEventOperationApplyingBatchSpec, nil) } func (ui *JSONLines) ApplyingBatchSpecSuccess(batchChangeURL string) { - logOperationSuccess(LogEventOperationApplyingBatchSpec, map[string]interface{}{"batchChangeURL": batchChangeURL}) + logOperationSuccess(batcheslib.LogEventOperationApplyingBatchSpec, map[string]interface{}{"batchChangeURL": batchChangeURL}) } func (ui *JSONLines) ExecutionError(err error) { - logOperationFailure(LogEventOperationBatchSpecExecution, map[string]interface{}{"error": err.Error()}) + logOperationFailure(batcheslib.LogEventOperationBatchSpecExecution, map[string]interface{}{"error": err.Error()}) } -func logOperationStart(op LogEventOperation, metadata map[string]interface{}) { - logEvent(BatchesLogEvent{Operation: op, Status: LogEventStatusStarted, Metadata: metadata}) +func logOperationStart(op batcheslib.LogEventOperation, metadata map[string]interface{}) { + logEvent(batcheslib.LogEvent{Operation: op, Status: batcheslib.LogEventStatusStarted, Metadata: metadata}) } -func logOperationSuccess(op LogEventOperation, metadata map[string]interface{}) { - logEvent(BatchesLogEvent{Operation: op, Status: LogEventStatusSuccess, Metadata: metadata}) +func logOperationSuccess(op batcheslib.LogEventOperation, metadata map[string]interface{}) { + logEvent(batcheslib.LogEvent{Operation: op, Status: batcheslib.LogEventStatusSuccess, Metadata: metadata}) } -func logOperationFailure(op LogEventOperation, metadata map[string]interface{}) { - logEvent(BatchesLogEvent{Operation: op, Status: LogEventStatusFailure, Metadata: metadata}) +func logOperationFailure(op batcheslib.LogEventOperation, metadata map[string]interface{}) { + logEvent(batcheslib.LogEvent{Operation: op, Status: batcheslib.LogEventStatusFailure, Metadata: metadata}) } -func logOperationProgress(op LogEventOperation, metadata map[string]interface{}) { - logEvent(BatchesLogEvent{Operation: op, Status: LogEventStatusProgress, Metadata: metadata}) +func logOperationProgress(op batcheslib.LogEventOperation, metadata map[string]interface{}) { + logEvent(batcheslib.LogEvent{Operation: op, Status: batcheslib.LogEventStatusProgress, Metadata: metadata}) } -func logEvent(e BatchesLogEvent) { +func logEvent(e batcheslib.LogEvent) { e.Timestamp = time.Now().UTC().Truncate(time.Millisecond) err := json.NewEncoder(os.Stdout).Encode(e) if err != nil { @@ -277,12 +232,12 @@ func (ui *taskExecutionJSONLines) Start(tasks []*executor.Task) { linesTasks = append(linesTasks, linesTask) } - logOperationStart(LogEventOperationExecutingTasks, map[string]interface{}{ + logOperationStart(batcheslib.LogEventOperationExecutingTasks, map[string]interface{}{ "tasks": linesTasks, }) } func (ui *taskExecutionJSONLines) Success() { - logOperationSuccess(LogEventOperationExecutingTasks, nil) + logOperationSuccess(batcheslib.LogEventOperationExecutingTasks, nil) } func (ui *taskExecutionJSONLines) TaskStarted(task *executor.Task) { @@ -291,7 +246,7 @@ func (ui *taskExecutionJSONLines) TaskStarted(task *executor.Task) { panic("unknown task started") } - logOperationStart(LogEventOperationExecutingTask, map[string]interface{}{ + logOperationStart(batcheslib.LogEventOperationExecutingTask, map[string]interface{}{ "taskID": lt.ID, }) } @@ -303,14 +258,14 @@ func (ui *taskExecutionJSONLines) TaskFinished(task *executor.Task, err error) { } if err != nil { - logOperationFailure(LogEventOperationExecutingTask, map[string]interface{}{ + logOperationFailure(batcheslib.LogEventOperationExecutingTask, map[string]interface{}{ "taskID": lt.ID, "error": err, }) return } - logOperationSuccess(LogEventOperationExecutingTask, map[string]interface{}{ + logOperationSuccess(batcheslib.LogEventOperationExecutingTask, map[string]interface{}{ "taskID": lt.ID, }) } @@ -320,7 +275,7 @@ func (ui *taskExecutionJSONLines) TaskChangesetSpecsBuilt(task *executor.Task, s if !ok { panic("unknown task started") } - logOperationSuccess(LogEventOperationTaskBuildChangesetSpecs, map[string]interface{}{ + logOperationSuccess(batcheslib.LogEventOperationTaskBuildChangesetSpecs, map[string]interface{}{ "taskID": lt.ID, }) } @@ -341,39 +296,39 @@ type stepsExecutionJSONLines struct { const stepFlushDuration = 500 * time.Millisecond func (ui *stepsExecutionJSONLines) ArchiveDownloadStarted() { - logOperationStart(LogEventOperationTaskDownloadingArchive, map[string]interface{}{"taskID": ui.linesTask.ID}) + logOperationStart(batcheslib.LogEventOperationTaskDownloadingArchive, map[string]interface{}{"taskID": ui.linesTask.ID}) } func (ui *stepsExecutionJSONLines) ArchiveDownloadFinished() { - logOperationSuccess(LogEventOperationTaskDownloadingArchive, map[string]interface{}{"taskID": ui.linesTask.ID}) + logOperationSuccess(batcheslib.LogEventOperationTaskDownloadingArchive, map[string]interface{}{"taskID": ui.linesTask.ID}) } func (ui *stepsExecutionJSONLines) WorkspaceInitializationStarted() { - logOperationStart(LogEventOperationTaskInitializingWorkspace, map[string]interface{}{"taskID": ui.linesTask.ID}) + logOperationStart(batcheslib.LogEventOperationTaskInitializingWorkspace, map[string]interface{}{"taskID": ui.linesTask.ID}) } func (ui *stepsExecutionJSONLines) WorkspaceInitializationFinished() { - logOperationSuccess(LogEventOperationTaskInitializingWorkspace, map[string]interface{}{"taskID": ui.linesTask.ID}) + logOperationSuccess(batcheslib.LogEventOperationTaskInitializingWorkspace, map[string]interface{}{"taskID": ui.linesTask.ID}) } func (ui *stepsExecutionJSONLines) SkippingStepsUpto(startStep int) { - logOperationProgress(LogEventOperationTaskSkippingSteps, map[string]interface{}{"taskID": ui.linesTask.ID, "startStep": startStep}) + logOperationProgress(batcheslib.LogEventOperationTaskSkippingSteps, map[string]interface{}{"taskID": ui.linesTask.ID, "startStep": startStep}) } func (ui *stepsExecutionJSONLines) StepSkipped(step int) { - logOperationProgress(LogEventOperationTaskStepSkipped, map[string]interface{}{"taskID": ui.linesTask.ID, "step": step}) + logOperationProgress(batcheslib.LogEventOperationTaskStepSkipped, map[string]interface{}{"taskID": ui.linesTask.ID, "step": step}) } func (ui *stepsExecutionJSONLines) StepPreparing(step int) { - logOperationProgress(LogEventOperationTaskPreparingStep, map[string]interface{}{"taskID": ui.linesTask.ID, "step": step}) + logOperationProgress(batcheslib.LogEventOperationTaskPreparingStep, map[string]interface{}{"taskID": ui.linesTask.ID, "step": step}) } func (ui *stepsExecutionJSONLines) StepStarted(step int, runScript string) { - logOperationStart(LogEventOperationTaskStep, map[string]interface{}{"taskID": ui.linesTask.ID, "step": step, "runScript": runScript}) + logOperationStart(batcheslib.LogEventOperationTaskStep, map[string]interface{}{"taskID": ui.linesTask.ID, "step": step, "runScript": runScript}) } func (ui *stepsExecutionJSONLines) StepStdoutWriter(ctx context.Context, task *executor.Task, step int) io.WriteCloser { sink := func(data string) { logOperationProgress( - LogEventOperationTaskStep, + batcheslib.LogEventOperationTaskStep, map[string]interface{}{ "taskID": ui.linesTask.ID, "step": step, @@ -388,7 +343,7 @@ func (ui *stepsExecutionJSONLines) StepStdoutWriter(ctx context.Context, task *e func (ui *stepsExecutionJSONLines) StepStderrWriter(ctx context.Context, task *executor.Task, step int) io.WriteCloser { sink := func(data string) { logOperationProgress( - LogEventOperationTaskStep, + batcheslib.LogEventOperationTaskStep, map[string]interface{}{ "taskID": ui.linesTask.ID, "step": step, @@ -403,9 +358,9 @@ func (ui *stepsExecutionJSONLines) StepStderrWriter(ctx context.Context, task *e func (ui *stepsExecutionJSONLines) StepFinished(step int, diff []byte, changes *git.Changes, outputs map[string]interface{}) { logOperationSuccess( - LogEventOperationTaskStep, + batcheslib.LogEventOperationTaskStep, map[string]interface{}{ - "task": ui.linesTask, + "taskID": ui.linesTask.ID, "step": step, "diff": string(diff), "changes": changes, @@ -415,8 +370,8 @@ func (ui *stepsExecutionJSONLines) StepFinished(step int, diff []byte, changes * } func (ui *stepsExecutionJSONLines) CalculatingDiffStarted() { - logOperationStart(LogEventOperationTaskCalculatingDiff, map[string]interface{}{"taskID": ui.linesTask.ID}) + logOperationStart(batcheslib.LogEventOperationTaskCalculatingDiff, map[string]interface{}{"taskID": ui.linesTask.ID}) } func (ui *stepsExecutionJSONLines) CalculatingDiffFinished() { - logOperationSuccess(LogEventOperationTaskCalculatingDiff, map[string]interface{}{"taskID": ui.linesTask.ID}) + logOperationSuccess(batcheslib.LogEventOperationTaskCalculatingDiff, map[string]interface{}{"taskID": ui.linesTask.ID}) } From b0f0ff6b4f7627cabbb2d411535dd56a62922c8f Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Tue, 7 Sep 2021 15:15:40 +0200 Subject: [PATCH 039/647] Prepare changelog for 3.31.1 --- CHANGELOG.md | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 58957aa58d..f1bc1c4db7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,12 +17,20 @@ All notable changes to `src-cli` are documented in this file. ### Fixed +### Removed + +## 3.31.1 + +### Changed + +- For internal use only: JSON log UI has been extended. + +### Fixed + - `src search -stream` displayed the number of lines that contain matches instead of the number of matches. - For internal use only: the `EXECUTING_TASKS` JSON log line now always contains an array of `tasks` instead of possibly having `null` as the `tasks` value. - src-cli is now built using Go version 1.17. -### Removed - ## 3.31.0 ### Changed From 551e6d738b2fddb65f578434afbf594fe381434f Mon Sep 17 00:00:00 2001 From: Thorsten Ball Date: Wed, 8 Sep 2021 12:54:11 +0200 Subject: [PATCH 040/647] For internal use only: add `src batches exec` command (#608) This adds the for-internal-use-only `src batch exec` command that will be used by server-side batch changes to execute a batch spec in specific workspaces on different machines, concurrently. --- CHANGELOG.md | 2 + cmd/src/batch_apply.go | 2 +- cmd/src/batch_common.go | 56 ++++----- cmd/src/batch_exec.go | 246 +++++++++++++++++++++++++++++++++++++++ cmd/src/batch_preview.go | 5 +- go.mod | 2 +- go.sum | 4 +- 7 files changed, 285 insertions(+), 32 deletions(-) create mode 100644 cmd/src/batch_exec.go diff --git a/CHANGELOG.md b/CHANGELOG.md index f1bc1c4db7..733f199fd3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,8 @@ All notable changes to `src-cli` are documented in this file. ### Added +- For internal use only: the `src batch exec` command executes the provided batch spec in the given workspaces. + ### Changed ### Fixed diff --git a/cmd/src/batch_apply.go b/cmd/src/batch_apply.go index 831719b5d6..dcfafe0127 100644 --- a/cmd/src/batch_apply.go +++ b/cmd/src/batch_apply.go @@ -28,7 +28,7 @@ Examples: ` flagSet := flag.NewFlagSet("apply", flag.ExitOnError) - flags := newBatchExecuteFlags(flagSet, batchDefaultCacheDir(), batchDefaultTempDirPrefix()) + flags := newBatchExecuteFlags(flagSet, false, batchDefaultCacheDir(), batchDefaultTempDirPrefix()) handler := func(args []string) error { if err := flagSet.Parse(args); err != nil { diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index bc22a6ab90..b56e75d704 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -48,27 +48,39 @@ type batchExecuteFlags struct { textOnly bool } -func newBatchExecuteFlags(flagSet *flag.FlagSet, cacheDir, tempDir string) *batchExecuteFlags { +func newBatchExecuteFlags(flagSet *flag.FlagSet, workspaceExecution bool, cacheDir, tempDir string) *batchExecuteFlags { caf := &batchExecuteFlags{ api: api.NewFlags(flagSet), } - flagSet.BoolVar( - &caf.textOnly, "text-only", false, - "INTERNAL USE ONLY. EXPERIMENTAL. Switches off the TUI to only print JSON lines.", - ) - flagSet.BoolVar( - &caf.allowUnsupported, "allow-unsupported", false, - "Allow unsupported code hosts.", - ) - flagSet.BoolVar( - &caf.allowIgnored, "force-override-ignore", false, - "Do not ignore repositories that have a .batchignore file.", - ) - flagSet.BoolVar( - &caf.apply, "apply", false, - "Ignored.", - ) + if !workspaceExecution { + flagSet.BoolVar( + &caf.textOnly, "text-only", false, + "INTERNAL USE ONLY. EXPERIMENTAL. Switches off the TUI to only print JSON lines.", + ) + flagSet.BoolVar( + &caf.allowUnsupported, "allow-unsupported", false, + "Allow unsupported code hosts.", + ) + flagSet.BoolVar( + &caf.allowIgnored, "force-override-ignore", false, + "Do not ignore repositories that have a .batchignore file.", + ) + flagSet.BoolVar( + &caf.apply, "apply", false, + "Ignored.", + ) + flagSet.BoolVar( + &caf.keepLogs, "keep-logs", false, + "Retain logs after executing steps.", + ) + flagSet.StringVar( + &caf.namespace, "namespace", "", + "The user or organization namespace to place the batch change within. Default is the currently authenticated user.", + ) + flagSet.StringVar(&caf.namespace, "n", "", "Alias for -namespace.") + } + flagSet.StringVar( &caf.cacheDir, "cache", cacheDir, "Directory for caching results and repository archives.", @@ -81,19 +93,11 @@ func newBatchExecuteFlags(flagSet *flag.FlagSet, cacheDir, tempDir string) *batc &caf.tempDir, "tmp", tempDir, "Directory for storing temporary data, such as log files. Default is /tmp. Can also be set with environment variable SRC_BATCH_TMP_DIR; if both are set, this flag will be used and not the environment variable.", ) + flagSet.StringVar( &caf.file, "f", "", "The batch spec file to read.", ) - flagSet.BoolVar( - &caf.keepLogs, "keep-logs", false, - "Retain logs after executing steps.", - ) - flagSet.StringVar( - &caf.namespace, "namespace", "", - "The user or organization namespace to place the batch change within. Default is the currently authenticated user.", - ) - flagSet.StringVar(&caf.namespace, "n", "", "Alias for -namespace.") flagSet.IntVar( &caf.parallelism, "j", runtime.GOMAXPROCS(0), diff --git a/cmd/src/batch_exec.go b/cmd/src/batch_exec.go new file mode 100644 index 0000000000..60b450100b --- /dev/null +++ b/cmd/src/batch_exec.go @@ -0,0 +1,246 @@ +package main + +import ( + "context" + "encoding/json" + "flag" + "fmt" + "io" + + "github.com/cockroachdb/errors" + "github.com/hashicorp/go-multierror" + "github.com/sourcegraph/src-cli/internal/batches/executor" + "github.com/sourcegraph/src-cli/internal/batches/graphql" + "github.com/sourcegraph/src-cli/internal/batches/service" + "github.com/sourcegraph/src-cli/internal/batches/ui" + "github.com/sourcegraph/src-cli/internal/batches/workspace" + "github.com/sourcegraph/src-cli/internal/cmderrors" + + batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" +) + +func init() { + usage := ` +INTERNAL USE ONLY: 'src batch exec' executes the given raw batch spec in the given workspaces. + +The input file contains a JSON dump of the WorkspacesExecutionInput struct in +github.com/sourcegraph/sourcegraph/lib/batches. + +Usage: + + src batch exec -f FILE [command options] + +Examples: + + $ src batch exec -f batch-spec-with-workspaces.json + +` + + flagSet := flag.NewFlagSet("exec", flag.ExitOnError) + flags := newBatchExecuteFlags(flagSet, true, batchDefaultCacheDir(), batchDefaultTempDirPrefix()) + + handler := func(args []string) error { + if err := flagSet.Parse(args); err != nil { + return err + } + + if len(flagSet.Args()) != 0 { + return cmderrors.Usage("additional arguments not allowed") + } + + ctx, cancel := contextCancelOnInterrupt(context.Background()) + defer cancel() + + err := executeBatchSpecInWorkspaces(ctx, executeBatchSpecOpts{ + flags: flags, + client: cfg.apiClient(flags.api, flagSet.Output()), + ui: &ui.JSONLines{}, + }) + if err != nil { + return cmderrors.ExitCode(1, nil) + } + + return nil + } + + batchCommands = append(batchCommands, &command{ + flagSet: flagSet, + handler: handler, + usageFunc: func() { + fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src batch %s':\n", flagSet.Name()) + flagSet.PrintDefaults() + fmt.Println(usage) + }, + }) +} + +func executeBatchSpecInWorkspaces(ctx context.Context, opts executeBatchSpecOpts) (err error) { + defer func() { + if err != nil { + opts.ui.ExecutionError(err) + } + }() + + svc := service.New(&service.Opts{ + AllowUnsupported: opts.flags.allowUnsupported, + AllowIgnored: opts.flags.allowIgnored, + Client: opts.client, + }) + if err := svc.DetermineFeatureFlags(ctx); err != nil { + return err + } + + if err := checkExecutable("git", "version"); err != nil { + return err + } + if err := checkExecutable("docker", "version"); err != nil { + return err + } + + // Read the input file that contains the raw spec and the workspaces in + // which to execute it. + input, err := loadWorkspaceExecutionInput(opts.flags.file) + if err != nil { + return err + } + + // Since we already know which workspaces we want to execute the steps in, + // we can convert them to RepoWorkspaces and build tasks only for those. + repoWorkspaces := convertWorkspaces(input.Workspaces) + + // Parse the raw batch spec contained in the input + opts.ui.ParsingBatchSpec() + batchSpec, err := svc.ParseBatchSpec([]byte(input.RawSpec)) + if err != nil { + if merr, ok := err.(*multierror.Error); ok { + opts.ui.ParsingBatchSpecFailure(merr) + return cmderrors.ExitCode(2, nil) + } else { + // This shouldn't happen; let's just punt and let the normal + // rendering occur. + return err + } + } + opts.ui.ParsingBatchSpecSuccess() + + opts.ui.PreparingContainerImages() + images, err := svc.EnsureDockerImages(ctx, batchSpec, opts.ui.PreparingContainerImagesProgress) + if err != nil { + return err + } + opts.ui.PreparingContainerImagesSuccess() + + opts.ui.DeterminingWorkspaceCreatorType() + workspaceCreator := workspace.NewCreator(ctx, opts.flags.workspace, opts.flags.cacheDir, opts.flags.tempDir, images) + if workspaceCreator.Type() == workspace.CreatorTypeVolume { + _, err = svc.EnsureImage(ctx, workspace.DockerVolumeWorkspaceImage) + if err != nil { + return err + } + } + opts.ui.DeterminingWorkspaceCreatorTypeSuccess(workspaceCreator.Type()) + + // EXECUTION OF TASKS + coord := svc.NewCoordinator(executor.NewCoordinatorOpts{ + Creator: workspaceCreator, + CacheDir: opts.flags.cacheDir, + ClearCache: opts.flags.clearCache, + SkipErrors: opts.flags.skipErrors, + CleanArchives: opts.flags.cleanArchives, + Parallelism: opts.flags.parallelism, + Timeout: opts.flags.timeout, + KeepLogs: opts.flags.keepLogs, + TempDir: opts.flags.tempDir, + }) + + opts.ui.CheckingCache() + tasks := svc.BuildTasks(ctx, batchSpec, repoWorkspaces) + uncachedTasks, cachedSpecs, err := coord.CheckCache(ctx, tasks) + if err != nil { + return err + } + opts.ui.CheckingCacheSuccess(len(cachedSpecs), len(uncachedTasks)) + + taskExecUI := opts.ui.ExecutingTasks(*verbose, opts.flags.parallelism) + freshSpecs, _, err := coord.Execute(ctx, uncachedTasks, batchSpec, taskExecUI) + if err != nil && !opts.flags.skipErrors { + return err + } + taskExecUI.Success() + if err != nil && opts.flags.skipErrors { + opts.ui.ExecutingTasksSkippingErrors(err) + } + + specs := append(cachedSpecs, freshSpecs...) + + ids := make([]graphql.ChangesetSpecID, len(specs)) + + if len(specs) > 0 { + opts.ui.UploadingChangesetSpecs(len(specs)) + + for i, spec := range specs { + id, err := svc.CreateChangesetSpec(ctx, spec) + if err != nil { + return err + } + ids[i] = id + opts.ui.UploadingChangesetSpecsProgress(i+1, len(specs)) + } + + opts.ui.UploadingChangesetSpecsSuccess(ids) + } + + return nil +} + +func loadWorkspaceExecutionInput(file string) (batcheslib.WorkspacesExecutionInput, error) { + var input batcheslib.WorkspacesExecutionInput + + f, err := batchOpenFileFlag(&file) + if err != nil { + return input, err + } + defer f.Close() + + data, err := io.ReadAll(f) + if err != nil { + return input, errors.Wrap(err, "reading workspace execution input file") + } + + if err := json.Unmarshal(data, &input); err != nil { + return input, errors.Wrap(err, "unmarshaling workspace execution input file") + } + + return input, nil +} + +func convertWorkspaces(ws []*batcheslib.Workspace) []service.RepoWorkspace { + workspaces := make([]service.RepoWorkspace, 0, len(ws)) + + for _, w := range ws { + fileMatches := make(map[string]bool) + for _, path := range w.SearchResultPaths { + fileMatches[path] = true + } + + workspaces = append(workspaces, service.RepoWorkspace{ + Repo: &graphql.Repository{ + ID: w.Repository.ID, + Name: w.Repository.Name, + Branch: graphql.Branch{ + Name: w.Branch.Name, + Target: graphql.Target{ + OID: w.Branch.Target.OID, + }, + }, + Commit: graphql.Target{OID: w.Branch.Target.OID}, + FileMatches: fileMatches, + }, + Path: w.Path, + Steps: w.Steps, + OnlyFetchWorkspace: w.OnlyFetchWorkspace, + }) + } + + return workspaces +} diff --git a/cmd/src/batch_preview.go b/cmd/src/batch_preview.go index 47c1e82566..b2142032ea 100644 --- a/cmd/src/batch_preview.go +++ b/cmd/src/batch_preview.go @@ -5,9 +5,10 @@ import ( "flag" "fmt" - "github.com/sourcegraph/sourcegraph/lib/output" "github.com/sourcegraph/src-cli/internal/batches/ui" "github.com/sourcegraph/src-cli/internal/cmderrors" + + "github.com/sourcegraph/sourcegraph/lib/output" ) func init() { @@ -26,7 +27,7 @@ Examples: ` flagSet := flag.NewFlagSet("preview", flag.ExitOnError) - flags := newBatchExecuteFlags(flagSet, batchDefaultCacheDir(), batchDefaultTempDirPrefix()) + flags := newBatchExecuteFlags(flagSet, false, batchDefaultCacheDir(), batchDefaultTempDirPrefix()) handler := func(args []string) error { if err := flagSet.Parse(args); err != nil { diff --git a/go.mod b/go.mod index ae1a29c1e1..634afd74f2 100644 --- a/go.mod +++ b/go.mod @@ -22,7 +22,7 @@ require ( github.com/sourcegraph/batch-change-utils v0.0.0-20210708162152-c9f35b905d94 github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf - github.com/sourcegraph/sourcegraph/lib v0.0.0-20210907100420-bac67ad72375 + github.com/sourcegraph/sourcegraph/lib v0.0.0-20210908093416-2bfda92388c7 github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect golang.org/x/net v0.0.0-20210614182718-04defd469f4e diff --git a/go.sum b/go.sum index 932574103b..066edf5f6f 100644 --- a/go.sum +++ b/go.sum @@ -261,8 +261,8 @@ github.com/sourcegraph/go-diff v0.6.1 h1:hmA1LzxW0n1c3Q4YbrFgg4P99GSnebYa3x8gr0H github.com/sourcegraph/go-diff v0.6.1/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20210907100420-bac67ad72375 h1:LRWLkOq2jsxKpxAr1tu6JmY9xjmxZV9Rjae9VdtTtCQ= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20210907100420-bac67ad72375/go.mod h1:ZK8mHKWdapYI8iIQwsO7QUxf44RjiNGKkOZa9aYIjTc= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20210908093416-2bfda92388c7 h1:7Y110pCBLzr+V8xSTGjgkOh4fFFfOIVWaKw+wUSg1vY= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20210908093416-2bfda92388c7/go.mod h1:ZK8mHKWdapYI8iIQwsO7QUxf44RjiNGKkOZa9aYIjTc= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= From 6bffe0f39072e56b414712d0b0cf1fde3b2faca2 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Tue, 14 Sep 2021 13:50:07 +0200 Subject: [PATCH 041/647] Use packages from lib instead of batch-change-utils (#617) --- go.mod | 3 +-- go.sum | 7 ++----- internal/batches/executor/changeset_specs_test.go | 3 ++- internal/batches/executor/coordinator_test.go | 2 +- internal/batches/executor/main_test.go | 3 ++- 5 files changed, 8 insertions(+), 10 deletions(-) diff --git a/go.mod b/go.mod index 634afd74f2..6c226df9d0 100644 --- a/go.mod +++ b/go.mod @@ -19,10 +19,9 @@ require ( github.com/mitchellh/copystructure v1.2.0 github.com/neelance/parallel v0.0.0-20160708114440-4de9ce63d14c github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4 - github.com/sourcegraph/batch-change-utils v0.0.0-20210708162152-c9f35b905d94 github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf - github.com/sourcegraph/sourcegraph/lib v0.0.0-20210908093416-2bfda92388c7 + github.com/sourcegraph/sourcegraph/lib v0.0.0-20210914094904-648e35b48ded github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect golang.org/x/net v0.0.0-20210614182718-04defd469f4e diff --git a/go.sum b/go.sum index 066edf5f6f..6d2f2811f7 100644 --- a/go.sum +++ b/go.sum @@ -255,14 +255,12 @@ github.com/shurcooL/go-goon v0.0.0-20210110234559-7585751d9a17/go.mod h1:N5mDOms github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= -github.com/sourcegraph/batch-change-utils v0.0.0-20210708162152-c9f35b905d94 h1:Yzs0ABVo9TXlfhIJZlHbj+T5a/e2lGyxH0bTTF1OtSE= -github.com/sourcegraph/batch-change-utils v0.0.0-20210708162152-c9f35b905d94/go.mod h1:kKNRPN6dxuXwC4UUhPVcAJsvz4EVEfI0jyN5HUJsazA= github.com/sourcegraph/go-diff v0.6.1 h1:hmA1LzxW0n1c3Q4YbrFgg4P99GSnebYa3x8gr0HZqLQ= github.com/sourcegraph/go-diff v0.6.1/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20210908093416-2bfda92388c7 h1:7Y110pCBLzr+V8xSTGjgkOh4fFFfOIVWaKw+wUSg1vY= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20210908093416-2bfda92388c7/go.mod h1:ZK8mHKWdapYI8iIQwsO7QUxf44RjiNGKkOZa9aYIjTc= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20210914094904-648e35b48ded h1:otRtA0pYQ1CzcqQ/XJjPJ3HNAVP+MqyMQN5i0eUX8mA= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20210914094904-648e35b48ded/go.mod h1:9vLg5fQL9Q3iktfqu96OrswbOq7yqMesMJER9DCy8vk= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= @@ -446,7 +444,6 @@ gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gotest.tools/v3 v3.0.2 h1:kG1BFyqVHuQoVQiR1bWGnfz/fmHvvuiSPIV7rvl360E= diff --git a/internal/batches/executor/changeset_specs_test.go b/internal/batches/executor/changeset_specs_test.go index 0a0b49f415..7eecbcd4fd 100644 --- a/internal/batches/executor/changeset_specs_test.go +++ b/internal/batches/executor/changeset_specs_test.go @@ -6,10 +6,11 @@ import ( "github.com/google/go-cmp/cmp" "github.com/mitchellh/copystructure" - "github.com/sourcegraph/batch-change-utils/overridable" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/git" + "github.com/sourcegraph/sourcegraph/lib/batches/overridable" "github.com/sourcegraph/sourcegraph/lib/batches/template" + "github.com/sourcegraph/src-cli/internal/batches" ) diff --git a/internal/batches/executor/coordinator_test.go b/internal/batches/executor/coordinator_test.go index c5e577015e..d4af8ca807 100644 --- a/internal/batches/executor/coordinator_test.go +++ b/internal/batches/executor/coordinator_test.go @@ -9,7 +9,7 @@ import ( "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" - "github.com/sourcegraph/batch-change-utils/overridable" + "github.com/sourcegraph/sourcegraph/lib/batches/overridable" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/git" diff --git a/internal/batches/executor/main_test.go b/internal/batches/executor/main_test.go index ba26d03001..adc2406e54 100644 --- a/internal/batches/executor/main_test.go +++ b/internal/batches/executor/main_test.go @@ -1,8 +1,9 @@ package executor import ( - "github.com/sourcegraph/batch-change-utils/overridable" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" + "github.com/sourcegraph/sourcegraph/lib/batches/overridable" + "github.com/sourcegraph/src-cli/internal/batches/graphql" ) From 157a86da3d6b35f583fc3607446271a6814e34c7 Mon Sep 17 00:00:00 2001 From: Thorsten Ball Date: Fri, 17 Sep 2021 14:58:19 +0200 Subject: [PATCH 042/647] Print step output into a single buffer (#619) This is a side-quest to EM2 https://github.com/sourcegraph/sourcegraph/issues/24421 because we realised that we'll make things harder for ourselves if we separate stdout/stderr into separate buffers. We'd have to zip them up together in the UI but that's hard without having additional timing information. But timing information is also a bit overkill (at least for now) so we thought we'd use a single buffer. That's what this PR here contains. Stdout and stderr are logged into a single buffer, each line prefixed with `stdout: ` and `stderr: ` respectively. That works because the `process.PipeOutput` function only writes lines (not chunks) to the passed in writers. So it works even if commands print half a line on stdout, then half a line on stderr, and only then the rest. --- CHANGELOG.md | 2 + internal/batches/executor/run_steps.go | 10 ++- internal/batches/executor/ui.go | 24 +++---- internal/batches/ui/interval_writer.go | 71 ++++++++++++++------- internal/batches/ui/interval_writer_test.go | 33 +++++++--- internal/batches/ui/json_lines.go | 28 ++------ internal/batches/ui/task_exec_tui.go | 13 +--- 7 files changed, 98 insertions(+), 83 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 733f199fd3..3a01bb28ca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,8 @@ All notable changes to `src-cli` are documented in this file. ### Changed +- For internal use only: when `src batch [preview|apply|exec]` are executed in `-text-only` mode, command output on stdout/stderr will be logged in the same message, with each line prefixed accordingly. [#619](https://github.com/sourcegraph/src-cli/pull/619) + ### Fixed ### Removed diff --git a/internal/batches/executor/run_steps.go b/internal/batches/executor/run_steps.go index cdbe92d70f..e996e84308 100644 --- a/internal/batches/executor/run_steps.go +++ b/internal/batches/executor/run_steps.go @@ -315,16 +315,14 @@ func executeSingleStep( writerCtx, writerCancel := context.WithCancel(ctx) defer writerCancel() - uiStdoutWriter := opts.ui.StepStdoutWriter(writerCtx, opts.task, i) - uiStderrWriter := opts.ui.StepStderrWriter(writerCtx, opts.task, i) + outputWriter := opts.ui.StepOutputWriter(writerCtx, opts.task, i) defer func() { - uiStdoutWriter.Close() - uiStderrWriter.Close() + outputWriter.Close() }() var stdoutBuffer, stderrBuffer bytes.Buffer - stdout := io.MultiWriter(&stdoutBuffer, uiStdoutWriter, opts.logger.PrefixWriter("stdout")) - stderr := io.MultiWriter(&stderrBuffer, uiStderrWriter, opts.logger.PrefixWriter("stderr")) + stdout := io.MultiWriter(&stdoutBuffer, outputWriter.StdoutWriter(), opts.logger.PrefixWriter("stdout")) + stderr := io.MultiWriter(&stderrBuffer, outputWriter.StderrWriter(), opts.logger.PrefixWriter("stderr")) // Setup readers that pipe the output into the given buffers wg, err := process.PipeOutput(ctx, cmd, stdout, stderr) diff --git a/internal/batches/executor/ui.go b/internal/batches/executor/ui.go index 4bc5c4954e..3a0b56f83b 100644 --- a/internal/batches/executor/ui.go +++ b/internal/batches/executor/ui.go @@ -20,6 +20,12 @@ type TaskExecutionUI interface { StepsExecutionUI(*Task) StepsExecutionUI } +type StepOutputWriter interface { + StdoutWriter() io.Writer + StderrWriter() io.Writer + Close() error +} + type StepsExecutionUI interface { ArchiveDownloadStarted() ArchiveDownloadFinished() @@ -34,8 +40,7 @@ type StepsExecutionUI interface { StepPreparing(int) StepStarted(int, string) - StepStdoutWriter(context.Context, *Task, int) io.WriteCloser - StepStderrWriter(context.Context, *Task, int) io.WriteCloser + StepOutputWriter(context.Context, *Task, int) StepOutputWriter CalculatingDiffStarted() CalculatingDiffFinished() @@ -54,19 +59,16 @@ func (noop NoopStepsExecUI) SkippingStepsUpto(startStep int) {} func (noop NoopStepsExecUI) StepSkipped(step int) {} func (noop NoopStepsExecUI) StepPreparing(step int) {} func (noop NoopStepsExecUI) StepStarted(step int, runScript string) {} -func (noop NoopStepsExecUI) StepStdoutWriter(ctx context.Context, task *Task, step int) io.WriteCloser { - return discardCloser{io.Discard} -} -func (noop NoopStepsExecUI) StepStderrWriter(ctx context.Context, task *Task, step int) io.WriteCloser { - return discardCloser{io.Discard} +func (noop NoopStepsExecUI) StepOutputWriter(ctx context.Context, task *Task, step int) StepOutputWriter { + return NoopStepOutputWriter{} } func (noop NoopStepsExecUI) CalculatingDiffStarted() {} func (noop NoopStepsExecUI) CalculatingDiffFinished() {} func (noop NoopStepsExecUI) StepFinished(idx int, diff []byte, changes *git.Changes, outputs map[string]interface{}) { } -type discardCloser struct { - io.Writer -} +type NoopStepOutputWriter struct{} -func (discardCloser) Close() error { return nil } +func (noop NoopStepOutputWriter) StdoutWriter() io.Writer { return io.Discard } +func (noop NoopStepOutputWriter) StderrWriter() io.Writer { return io.Discard } +func (noop NoopStepOutputWriter) Close() error { return nil } diff --git a/internal/batches/ui/interval_writer.go b/internal/batches/ui/interval_writer.go index 71380b7518..1cc285446f 100644 --- a/internal/batches/ui/interval_writer.go +++ b/internal/batches/ui/interval_writer.go @@ -3,14 +3,15 @@ package ui import ( "bytes" "context" + "io" "time" "github.com/derision-test/glock" ) -// IntervalWriter is a io.Writer that flushes to the given sink on the given -// interval. -type IntervalWriter struct { +// IntervalProcessWriter accepts stdout/stderr writes from processes, prefixed +// them accordingly, and flushes to the given sink on the given interval. +type IntervalProcessWriter struct { sink func(string) ticker glock.Ticker @@ -25,8 +26,8 @@ type IntervalWriter struct { done chan struct{} } -func newIntervalWriter(ctx context.Context, ticker glock.Ticker, sink func(string)) *IntervalWriter { - l := &IntervalWriter{ +func newIntervalProcessWriter(ctx context.Context, ticker glock.Ticker, sink func(string)) *IntervalProcessWriter { + l := &IntervalProcessWriter{ sink: sink, ticker: ticker, @@ -44,37 +45,42 @@ func newIntervalWriter(ctx context.Context, ticker glock.Ticker, sink func(strin return l } -// NewLogger returns a new Logger instance and spawns a goroutine in the -// background that regularily flushed the logged output to the given sink. +// NewIntervalProcessWriter returns a new IntervalProcessWriter instance and +// spawns a goroutine in the background that regularily flushed the logged +// output to the given sink. // // If the passed in ctx is canceled the goroutine will exit. -func NewIntervalWriter(ctx context.Context, interval time.Duration, sink func(string)) *IntervalWriter { - return newIntervalWriter(ctx, glock.NewRealTicker(interval), sink) +func NewIntervalProcessWriter(ctx context.Context, interval time.Duration, sink func(string)) *IntervalProcessWriter { + return newIntervalProcessWriter(ctx, glock.NewRealTicker(interval), sink) } -func (l *IntervalWriter) flush() { - if l.buf.Len() == 0 { - return - } - l.sink(l.buf.String()) - l.buf.Reset() +// StdoutWriter returns an io.Writer that prefixes every line with "stdout: " +func (l *IntervalProcessWriter) StdoutWriter() io.Writer { + return &prefixedWriter{writes: l.writes, writesDone: l.writesDone, prefix: "stdout: "} } -// Close flushes the -func (l *IntervalWriter) Close() error { +// SterrWriter returns an io.Writer that prefixes every line with "stderr: " +func (l *IntervalProcessWriter) StderrWriter() io.Writer { + return &prefixedWriter{writes: l.writes, writesDone: l.writesDone, prefix: "stderr: "} +} + +// Close blocks until all pending writes have been flushed to the buffer. It +// then causes the underlying goroutine to exit. +func (l *IntervalProcessWriter) Close() error { l.closed <- struct{}{} <-l.done return nil } -// Write handler of IntervalWriter. -func (l *IntervalWriter) Write(p []byte) (int, error) { - l.writes <- p - <-l.writesDone - return len(p), nil +func (l *IntervalProcessWriter) flush() { + if l.buf.Len() == 0 { + return + } + l.sink(l.buf.String()) + l.buf.Reset() } -func (l *IntervalWriter) writeLines(ctx context.Context) { +func (l *IntervalProcessWriter) writeLines(ctx context.Context) { defer func() { l.flush() l.ticker.Stop() @@ -103,3 +109,22 @@ func (l *IntervalWriter) writeLines(ctx context.Context) { } } } + +type prefixedWriter struct { + writes chan []byte + writesDone chan struct{} + prefix string +} + +func (w *prefixedWriter) Write(p []byte) (int, error) { + var prefixedLines []byte + for _, line := range bytes.Split(p, []byte("\n")) { + prefixedLine := append([]byte(w.prefix), line...) + prefixedLine = append(prefixedLine, []byte("\n")...) + + prefixedLines = append(prefixedLines, prefixedLine...) + } + w.writes <- prefixedLines + <-w.writesDone + return len(p), nil +} diff --git a/internal/batches/ui/interval_writer_test.go b/internal/batches/ui/interval_writer_test.go index ec5bacdd40..1a56eb4288 100644 --- a/internal/batches/ui/interval_writer_test.go +++ b/internal/batches/ui/interval_writer_test.go @@ -18,9 +18,12 @@ func TestIntervalWriter(t *testing.T) { } ticker := glock.NewMockTicker(1 * time.Second) - writer := newIntervalWriter(ctx, ticker, sink) + writer := newIntervalProcessWriter(ctx, ticker, sink) - writer.Write([]byte("1")) + stdoutWriter := writer.StdoutWriter() + stderrWriter := writer.StderrWriter() + stdoutWriter.Write([]byte("1")) + stderrWriter.Write([]byte("1")) select { case <-ch: t.Fatalf("ch has data") @@ -31,17 +34,22 @@ func TestIntervalWriter(t *testing.T) { select { case d := <-ch: - if d != "1" { - t.Fatalf("wrong data in sink") + want := "stdout: 1\nstderr: 1\n" + if d != want { + t.Fatalf("wrong data in sink. want=%q, have=%q", want, d) } case <-time.After(1 * time.Second): t.Fatalf("ch has NO data") } - writer.Write([]byte("2")) - writer.Write([]byte("3")) - writer.Write([]byte("4")) - writer.Write([]byte("5")) + stdoutWriter.Write([]byte("2")) + stderrWriter.Write([]byte("2")) + stdoutWriter.Write([]byte("3")) + stderrWriter.Write([]byte("3")) + stdoutWriter.Write([]byte("4")) + stderrWriter.Write([]byte("4")) + stdoutWriter.Write([]byte("5")) + stderrWriter.Write([]byte("5")) select { case <-ch: @@ -54,8 +62,13 @@ func TestIntervalWriter(t *testing.T) { select { case d := <-ch: - if d != "2345" { - t.Fatalf("wrong data in sink") + want := "stdout: 2\nstderr: 2\n" + + "stdout: 3\nstderr: 3\n" + + "stdout: 4\nstderr: 4\n" + + "stdout: 5\nstderr: 5\n" + + if d != want { + t.Fatalf("wrong data in sink. want") } case <-time.After(1 * time.Second): t.Fatalf("ch has NO data") diff --git a/internal/batches/ui/json_lines.go b/internal/batches/ui/json_lines.go index 528358127b..c1876a130c 100644 --- a/internal/batches/ui/json_lines.go +++ b/internal/batches/ui/json_lines.go @@ -4,7 +4,6 @@ import ( "context" "encoding/json" "fmt" - "io" "math/rand" "os" "strconv" @@ -325,35 +324,18 @@ func (ui *stepsExecutionJSONLines) StepStarted(step int, runScript string) { logOperationStart(batcheslib.LogEventOperationTaskStep, map[string]interface{}{"taskID": ui.linesTask.ID, "step": step, "runScript": runScript}) } -func (ui *stepsExecutionJSONLines) StepStdoutWriter(ctx context.Context, task *executor.Task, step int) io.WriteCloser { +func (ui *stepsExecutionJSONLines) StepOutputWriter(ctx context.Context, task *executor.Task, step int) executor.StepOutputWriter { sink := func(data string) { logOperationProgress( batcheslib.LogEventOperationTaskStep, map[string]interface{}{ - "taskID": ui.linesTask.ID, - "step": step, - "out": data, - "output_type": "stdout", + "taskID": ui.linesTask.ID, + "step": step, + "out": data, }, ) } - return NewIntervalWriter(ctx, stepFlushDuration, sink) -} - -func (ui *stepsExecutionJSONLines) StepStderrWriter(ctx context.Context, task *executor.Task, step int) io.WriteCloser { - sink := func(data string) { - logOperationProgress( - batcheslib.LogEventOperationTaskStep, - map[string]interface{}{ - "taskID": ui.linesTask.ID, - "step": step, - "out": data, - "output_type": "stderr", - }, - ) - } - - return NewIntervalWriter(ctx, stepFlushDuration, sink) + return NewIntervalProcessWriter(ctx, stepFlushDuration, sink) } func (ui *stepsExecutionJSONLines) StepFinished(step int, diff []byte, changes *git.Changes, outputs map[string]interface{}) { diff --git a/internal/batches/ui/task_exec_tui.go b/internal/batches/ui/task_exec_tui.go index 6f41cd4e59..a19d9d40a1 100644 --- a/internal/batches/ui/task_exec_tui.go +++ b/internal/batches/ui/task_exec_tui.go @@ -3,7 +3,6 @@ package ui import ( "context" "fmt" - "io" "sort" "strings" "sync" @@ -458,12 +457,10 @@ func (ui stepsExecTUI) StepStarted(step int, runScript string) { ui.updateStatusBar(runScript) } -func (ui stepsExecTUI) StepStdoutWriter(ctx context.Context, task *executor.Task, step int) io.WriteCloser { - return discardCloser{io.Discard} -} -func (ui stepsExecTUI) StepStderrWriter(ctx context.Context, task *executor.Task, step int) io.WriteCloser { - return discardCloser{io.Discard} +func (ui stepsExecTUI) StepOutputWriter(ctx context.Context, task *executor.Task, step int) executor.StepOutputWriter { + return executor.NoopStepOutputWriter{} } + func (ui stepsExecTUI) CalculatingDiffStarted() { ui.updateStatusBar("Calculating diff") } @@ -473,7 +470,3 @@ func (ui stepsExecTUI) CalculatingDiffFinished() { func (ui stepsExecTUI) StepFinished(idx int, diff []byte, changes *git.Changes, outputs map[string]interface{}) { // noop right now } - -type discardCloser struct{ io.Writer } - -func (discardCloser) Close() error { return nil } From b0505a4302f23c6439be1c2e894076d456877543 Mon Sep 17 00:00:00 2001 From: Thorsten Ball Date: Mon, 20 Sep 2021 13:49:52 +0200 Subject: [PATCH 043/647] Fix displaying of errors in 'src batch validate' (#620) Before this 'src batch validate' would... 1. not print an error if talking to the Sourcegraph instance failed 2. not unpack multi errors correctly and printing all of them This fixes both issues. --- cmd/src/batch_common.go | 5 +++-- cmd/src/batch_exec.go | 5 +++-- cmd/src/batch_validate.go | 6 ++++-- internal/batches/ui/tui.go | 11 +++++++---- 4 files changed, 17 insertions(+), 10 deletions(-) diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index b56e75d704..78b1a4ee18 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -229,8 +229,9 @@ func executeBatchSpec(ctx context.Context, opts executeBatchSpecOpts) (err error opts.ui.ParsingBatchSpec() batchSpec, rawSpec, err := parseBatchSpec(&opts.flags.file, svc) if err != nil { - if merr, ok := err.(*multierror.Error); ok { - opts.ui.ParsingBatchSpecFailure(merr) + var multiErr *multierror.Error + if errors.As(err, &multiErr) { + opts.ui.ParsingBatchSpecFailure(multiErr) return cmderrors.ExitCode(2, nil) } else { // This shouldn't happen; let's just punt and let the normal diff --git a/cmd/src/batch_exec.go b/cmd/src/batch_exec.go index 60b450100b..190a91bca6 100644 --- a/cmd/src/batch_exec.go +++ b/cmd/src/batch_exec.go @@ -112,8 +112,9 @@ func executeBatchSpecInWorkspaces(ctx context.Context, opts executeBatchSpecOpts opts.ui.ParsingBatchSpec() batchSpec, err := svc.ParseBatchSpec([]byte(input.RawSpec)) if err != nil { - if merr, ok := err.(*multierror.Error); ok { - opts.ui.ParsingBatchSpecFailure(merr) + var multiErr *multierror.Error + if errors.As(err, &multiErr) { + opts.ui.ParsingBatchSpecFailure(multiErr) return cmderrors.ExitCode(2, nil) } else { // This shouldn't happen; let's just punt and let the normal diff --git a/cmd/src/batch_validate.go b/cmd/src/batch_validate.go index 0c529092e8..2b79dcd930 100644 --- a/cmd/src/batch_validate.go +++ b/cmd/src/batch_validate.go @@ -41,17 +41,19 @@ Examples: return cmderrors.Usage("additional arguments not allowed") } + out := output.NewOutput(flagSet.Output(), output.OutputOpts{Verbose: *verbose}) + ui := &ui.TUI{Out: out} svc := service.New(&service.Opts{ Client: cfg.apiClient(apiFlags, flagSet.Output()), }) if err := svc.DetermineFeatureFlags(ctx); err != nil { + ui.ExecutionError(err) return err } - out := output.NewOutput(flagSet.Output(), output.OutputOpts{Verbose: *verbose}) if _, _, err := parseBatchSpec(fileFlag, svc); err != nil { - (&ui.TUI{Out: out}).ParsingBatchSpecFailure(err) + ui.ParsingBatchSpecFailure(err) return err } diff --git a/internal/batches/ui/tui.go b/internal/batches/ui/tui.go index ef207330f4..8013185c3c 100644 --- a/internal/batches/ui/tui.go +++ b/internal/batches/ui/tui.go @@ -43,13 +43,16 @@ func (ui *TUI) ParsingBatchSpecSuccess() { } func (ui *TUI) ParsingBatchSpecFailure(err error) { - if merr, ok := err.(*multierror.Error); ok { - block := ui.Out.Block(output.Line("\u274c", output.StyleWarning, "Batch spec failed validation.")) - defer block.Close() + block := ui.Out.Block(output.Line("\u274c", output.StyleWarning, "Batch spec failed validation.")) + defer block.Close() - for i, err := range merr.Errors { + var multiErr *multierror.Error + if errors.As(err, &multiErr) { + for i, err := range multiErr.Errors { block.Writef("%d. %s", i+1, err) } + } else { + block.Writef("1. %s", err) } } From b08abb5ce710d30c9556d8a94081d762d1eb8dec Mon Sep 17 00:00:00 2001 From: Thorsten Ball Date: Mon, 20 Sep 2021 14:10:55 +0200 Subject: [PATCH 044/647] Update sourcegraph/lib to pull it latest fixes (#621) --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 6c226df9d0..946efc097b 100644 --- a/go.mod +++ b/go.mod @@ -21,7 +21,7 @@ require ( github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4 github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf - github.com/sourcegraph/sourcegraph/lib v0.0.0-20210914094904-648e35b48ded + github.com/sourcegraph/sourcegraph/lib v0.0.0-20210920114500-3eabeb8208ef github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect golang.org/x/net v0.0.0-20210614182718-04defd469f4e diff --git a/go.sum b/go.sum index 6d2f2811f7..021eb0d08f 100644 --- a/go.sum +++ b/go.sum @@ -259,8 +259,8 @@ github.com/sourcegraph/go-diff v0.6.1 h1:hmA1LzxW0n1c3Q4YbrFgg4P99GSnebYa3x8gr0H github.com/sourcegraph/go-diff v0.6.1/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20210914094904-648e35b48ded h1:otRtA0pYQ1CzcqQ/XJjPJ3HNAVP+MqyMQN5i0eUX8mA= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20210914094904-648e35b48ded/go.mod h1:9vLg5fQL9Q3iktfqu96OrswbOq7yqMesMJER9DCy8vk= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20210920114500-3eabeb8208ef h1:NVbGTt8WfgPflixd3d1AFKZt+UgOevTE3rUz+8HEM6A= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20210920114500-3eabeb8208ef/go.mod h1:9vLg5fQL9Q3iktfqu96OrswbOq7yqMesMJER9DCy8vk= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= From b7206f11ffac9ad3edca2ad44013f97ded3eefd4 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Wed, 22 Sep 2021 14:47:05 +0200 Subject: [PATCH 045/647] ssbc: Log final env when resolved (#622) When determining workspaces, we determine the env, too. The values are preliminary though, as they might depend on what's set in the environment of src-cli or use template variables that aren't known at time of workspace determination. This logs the final set of env vars as used for the step. --- internal/batches/executor/run_steps.go | 3 +-- internal/batches/executor/ui.go | 18 +++++++++--------- internal/batches/ui/json_lines.go | 4 ++-- internal/batches/ui/task_exec_tui.go | 3 ++- 4 files changed, 14 insertions(+), 14 deletions(-) diff --git a/internal/batches/executor/run_steps.go b/internal/batches/executor/run_steps.go index e996e84308..e50bc53327 100644 --- a/internal/batches/executor/run_steps.go +++ b/internal/batches/executor/run_steps.go @@ -265,7 +265,6 @@ func executeSingleStep( if err != nil { return bytes.Buffer{}, bytes.Buffer{}, errors.Wrap(err, "resolving step environment") } - // Render the step.Env variables as templates. env, err := template.RenderStepMap(stepEnv, stepContext) if err != nil { @@ -275,7 +274,7 @@ func executeSingleStep( // ---------- // EXECUTION // ---------- - opts.ui.StepStarted(i+1, runScript) + opts.ui.StepStarted(i+1, runScript, env) workspaceOpts, err := workspace.DockerRunOpts(ctx, workDir) if err != nil { diff --git a/internal/batches/executor/ui.go b/internal/batches/executor/ui.go index 3a0b56f83b..0ff56b2f43 100644 --- a/internal/batches/executor/ui.go +++ b/internal/batches/executor/ui.go @@ -38,7 +38,7 @@ type StepsExecutionUI interface { StepSkipped(int) StepPreparing(int) - StepStarted(int, string) + StepStarted(stepIdx int, runScript string, env map[string]string) StepOutputWriter(context.Context, *Task, int) StepOutputWriter @@ -51,14 +51,14 @@ type StepsExecutionUI interface { // NoopStepsExecUI is an implementation of StepsExecutionUI that does nothing. type NoopStepsExecUI struct{} -func (noop NoopStepsExecUI) ArchiveDownloadStarted() {} -func (noop NoopStepsExecUI) ArchiveDownloadFinished() {} -func (noop NoopStepsExecUI) WorkspaceInitializationStarted() {} -func (noop NoopStepsExecUI) WorkspaceInitializationFinished() {} -func (noop NoopStepsExecUI) SkippingStepsUpto(startStep int) {} -func (noop NoopStepsExecUI) StepSkipped(step int) {} -func (noop NoopStepsExecUI) StepPreparing(step int) {} -func (noop NoopStepsExecUI) StepStarted(step int, runScript string) {} +func (noop NoopStepsExecUI) ArchiveDownloadStarted() {} +func (noop NoopStepsExecUI) ArchiveDownloadFinished() {} +func (noop NoopStepsExecUI) WorkspaceInitializationStarted() {} +func (noop NoopStepsExecUI) WorkspaceInitializationFinished() {} +func (noop NoopStepsExecUI) SkippingStepsUpto(startStep int) {} +func (noop NoopStepsExecUI) StepSkipped(step int) {} +func (noop NoopStepsExecUI) StepPreparing(step int) {} +func (noop NoopStepsExecUI) StepStarted(step int, runScript string, env map[string]string) {} func (noop NoopStepsExecUI) StepOutputWriter(ctx context.Context, task *Task, step int) StepOutputWriter { return NoopStepOutputWriter{} } diff --git a/internal/batches/ui/json_lines.go b/internal/batches/ui/json_lines.go index c1876a130c..da10f5d1bd 100644 --- a/internal/batches/ui/json_lines.go +++ b/internal/batches/ui/json_lines.go @@ -320,8 +320,8 @@ func (ui *stepsExecutionJSONLines) StepPreparing(step int) { logOperationProgress(batcheslib.LogEventOperationTaskPreparingStep, map[string]interface{}{"taskID": ui.linesTask.ID, "step": step}) } -func (ui *stepsExecutionJSONLines) StepStarted(step int, runScript string) { - logOperationStart(batcheslib.LogEventOperationTaskStep, map[string]interface{}{"taskID": ui.linesTask.ID, "step": step, "runScript": runScript}) +func (ui *stepsExecutionJSONLines) StepStarted(step int, runScript string, env map[string]string) { + logOperationStart(batcheslib.LogEventOperationTaskStep, map[string]interface{}{"taskID": ui.linesTask.ID, "step": step, "runScript": runScript, "env": env}) } func (ui *stepsExecutionJSONLines) StepOutputWriter(ctx context.Context, task *executor.Task, step int) executor.StepOutputWriter { diff --git a/internal/batches/ui/task_exec_tui.go b/internal/batches/ui/task_exec_tui.go index a19d9d40a1..f73e332267 100644 --- a/internal/batches/ui/task_exec_tui.go +++ b/internal/batches/ui/task_exec_tui.go @@ -9,6 +9,7 @@ import ( "time" "github.com/sourcegraph/go-diff/diff" + "github.com/sourcegraph/src-cli/internal/batches/executor" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" @@ -453,7 +454,7 @@ func (ui stepsExecTUI) StepSkipped(step int) { func (ui stepsExecTUI) StepPreparing(step int) { ui.updateStatusBar(fmt.Sprintf("Preparing %d", step)) } -func (ui stepsExecTUI) StepStarted(step int, runScript string) { +func (ui stepsExecTUI) StepStarted(step int, runScript string, _ map[string]string) { ui.updateStatusBar(runScript) } From c1aab13322ecbdc8236481163f8619f39e5a637d Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Wed, 22 Sep 2021 14:48:34 +0200 Subject: [PATCH 046/647] Add todo comment to env var cache key --- internal/batches/executor/execution_cache.go | 1 + 1 file changed, 1 insertion(+) diff --git a/internal/batches/executor/execution_cache.go b/internal/batches/executor/execution_cache.go index e4eb0b66ba..dd9182a8d4 100644 --- a/internal/batches/executor/execution_cache.go +++ b/internal/batches/executor/execution_cache.go @@ -39,6 +39,7 @@ func resolveStepsEnvironment(steps []batcheslib.Step) ([]map[string]string, erro global := os.Environ() envs := make([]map[string]string, len(steps)) for i, step := range steps { + // TODO: This should also render templates inside env vars. env, err := step.Env.Resolve(global) if err != nil { return nil, errors.Wrapf(err, "resolving environment for step %d", i) From da3986270556b009116ce4d3db164b577a45d045 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Wed, 29 Sep 2021 14:30:41 +0200 Subject: [PATCH 047/647] Cleanup and complete json logs a bit (#623) Required for new SSBC step resolvers to have all data needed. --- cmd/src/batch_common.go | 35 ++- cmd/src/batch_exec.go | 18 +- go.mod | 2 +- go.sum | 4 +- internal/batches/executor/coordinator_test.go | 5 +- internal/batches/executor/run_steps.go | 45 ++- internal/batches/executor/ui.go | 16 +- internal/batches/ui/exec_ui.go | 2 +- internal/batches/ui/json_lines.go | 267 ++++++++++-------- internal/batches/ui/task_exec_tui.go | 16 +- internal/batches/ui/tui.go | 2 +- 11 files changed, 248 insertions(+), 164 deletions(-) diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index 78b1a4ee18..c0ab724f1b 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -312,9 +312,17 @@ func executeBatchSpec(ctx context.Context, opts executeBatchSpecOpts) (err error if err != nil && !opts.flags.skipErrors { return err } - taskExecUI.Success() - if err != nil && opts.flags.skipErrors { - opts.ui.ExecutingTasksSkippingErrors(err) + if err == nil || opts.flags.skipErrors { + if err == nil { + taskExecUI.Success() + } else { + opts.ui.ExecutingTasksSkippingErrors(err) + } + } else { + if err != nil { + taskExecUI.Failed(err) + return err + } } if len(logFiles) > 0 && opts.flags.keepLogs { @@ -349,22 +357,23 @@ func executeBatchSpec(ctx context.Context, opts executeBatchSpecOpts) (err error opts.ui.CreatingBatchSpec() id, url, err := svc.CreateBatchSpec(ctx, namespace, rawSpec, ids) - opts.ui.CreatingBatchSpecSuccess() if err != nil { return opts.ui.CreatingBatchSpecError(err) } + previewURL := cfg.Endpoint + url + opts.ui.CreatingBatchSpecSuccess(previewURL) - if opts.applyBatchSpec { - opts.ui.ApplyingBatchSpec() - batch, err := svc.ApplyBatchChange(ctx, id) - if err != nil { - return err - } - opts.ui.ApplyingBatchSpecSuccess(cfg.Endpoint + batch.URL) + if !opts.applyBatchSpec { + opts.ui.PreviewBatchSpec(previewURL) + return + } - } else { - opts.ui.PreviewBatchSpec(cfg.Endpoint + url) + opts.ui.ApplyingBatchSpec() + batch, err := svc.ApplyBatchChange(ctx, id) + if err != nil { + return err } + opts.ui.ApplyingBatchSpecSuccess(cfg.Endpoint + batch.URL) return nil } diff --git a/cmd/src/batch_exec.go b/cmd/src/batch_exec.go index 190a91bca6..78546e55aa 100644 --- a/cmd/src/batch_exec.go +++ b/cmd/src/batch_exec.go @@ -9,6 +9,7 @@ import ( "github.com/cockroachdb/errors" "github.com/hashicorp/go-multierror" + "github.com/sourcegraph/src-cli/internal/batches/executor" "github.com/sourcegraph/src-cli/internal/batches/graphql" "github.com/sourcegraph/src-cli/internal/batches/service" @@ -164,12 +165,17 @@ func executeBatchSpecInWorkspaces(ctx context.Context, opts executeBatchSpecOpts taskExecUI := opts.ui.ExecutingTasks(*verbose, opts.flags.parallelism) freshSpecs, _, err := coord.Execute(ctx, uncachedTasks, batchSpec, taskExecUI) - if err != nil && !opts.flags.skipErrors { - return err - } - taskExecUI.Success() - if err != nil && opts.flags.skipErrors { - opts.ui.ExecutingTasksSkippingErrors(err) + if err == nil || opts.flags.skipErrors { + if err == nil { + taskExecUI.Success() + } else { + opts.ui.ExecutingTasksSkippingErrors(err) + } + } else { + if err != nil { + taskExecUI.Failed(err) + return err + } } specs := append(cachedSpecs, freshSpecs...) diff --git a/go.mod b/go.mod index 946efc097b..3f21bfb592 100644 --- a/go.mod +++ b/go.mod @@ -21,7 +21,7 @@ require ( github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4 github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf - github.com/sourcegraph/sourcegraph/lib v0.0.0-20210920114500-3eabeb8208ef + github.com/sourcegraph/sourcegraph/lib v0.0.0-20210929121718-d5efc9330247 github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect golang.org/x/net v0.0.0-20210614182718-04defd469f4e diff --git a/go.sum b/go.sum index 021eb0d08f..5777c5f8eb 100644 --- a/go.sum +++ b/go.sum @@ -259,8 +259,8 @@ github.com/sourcegraph/go-diff v0.6.1 h1:hmA1LzxW0n1c3Q4YbrFgg4P99GSnebYa3x8gr0H github.com/sourcegraph/go-diff v0.6.1/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20210920114500-3eabeb8208ef h1:NVbGTt8WfgPflixd3d1AFKZt+UgOevTE3rUz+8HEM6A= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20210920114500-3eabeb8208ef/go.mod h1:9vLg5fQL9Q3iktfqu96OrswbOq7yqMesMJER9DCy8vk= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20210929121718-d5efc9330247 h1:U1qXWB+6i/YeQ73kirisIEsxCBgNXw4td4QYdYlBeKM= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20210929121718-d5efc9330247/go.mod h1:9vLg5fQL9Q3iktfqu96OrswbOq7yqMesMJER9DCy8vk= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= diff --git a/internal/batches/executor/coordinator_test.go b/internal/batches/executor/coordinator_test.go index d4af8ca807..c34d0c2edc 100644 --- a/internal/batches/executor/coordinator_test.go +++ b/internal/batches/executor/coordinator_test.go @@ -519,8 +519,9 @@ type dummyTaskExecutionUI struct { specs map[*Task][]*batcheslib.ChangesetSpec } -func (d *dummyTaskExecutionUI) Start([]*Task) {} -func (d *dummyTaskExecutionUI) Success() {} +func (d *dummyTaskExecutionUI) Start([]*Task) {} +func (d *dummyTaskExecutionUI) Success() {} +func (d *dummyTaskExecutionUI) Failed(err error) {} func (d *dummyTaskExecutionUI) TaskStarted(t *Task) { d.mu.Lock() defer d.mu.Unlock() diff --git a/internal/batches/executor/run_steps.go b/internal/batches/executor/run_steps.go index e50bc53327..ab6bec2b7a 100644 --- a/internal/batches/executor/run_steps.go +++ b/internal/batches/executor/run_steps.go @@ -73,11 +73,11 @@ type executionOpts struct { func runSteps(ctx context.Context, opts *executionOpts) (result executionResult, stepResults []stepExecutionResult, err error) { opts.ui.ArchiveDownloadStarted() err = opts.task.Archive.Ensure(ctx) + opts.ui.ArchiveDownloadFinished(err) if err != nil { return executionResult{}, nil, errors.Wrap(err, "fetching repo") } defer opts.task.Archive.Close() - opts.ui.ArchiveDownloadFinished() opts.ui.WorkspaceInitializationStarted() workspace, err := opts.wc.Create(ctx, opts.task.Repository, opts.task.Steps, opts.task.Archive) @@ -167,6 +167,16 @@ func runSteps(ctx context.Context, opts *executionOpts) (result executionResult, return execResult, nil, err } stdoutBuffer, stderrBuffer, err := executeSingleStep(ctx, opts, workspace, i, step, digest, &stepContext) + defer func() { + if err != nil { + exitCode := -1 + sfe := &stepFailedErr{} + if errors.As(err, sfe) { + exitCode = sfe.ExitCode + } + opts.ui.StepFailed(i+1, err, exitCode) + } + }() if err != nil { return execResult, nil, err } @@ -233,10 +243,11 @@ func executeSingleStep( // ---------- // PREPARATION // ---------- - opts.ui.StepPreparing(i + 1) + opts.ui.StepPreparingStart(i + 1) cidFile, cleanup, err := createCidFile(ctx, opts.tempDir, util.SlugForRepo(opts.task.Repository.Name, opts.task.Repository.Rev())) if err != nil { + opts.ui.StepPreparingFailed(i+1, err) return bytes.Buffer{}, bytes.Buffer{}, err } defer cleanup() @@ -244,11 +255,14 @@ func executeSingleStep( // For now, we only support shell scripts provided via the Run field. shell, containerTemp, err := probeImageForShell(ctx, imageDigest) if err != nil { - return bytes.Buffer{}, bytes.Buffer{}, errors.Wrapf(err, "probing image %q for shell", step.Container) + err = errors.Wrapf(err, "probing image %q for shell", step.Container) + opts.ui.StepPreparingFailed(i+1, err) + return bytes.Buffer{}, bytes.Buffer{}, err } runScriptFile, runScript, cleanup, err := createRunScriptFile(ctx, opts.tempDir, step.Run, stepContext) if err != nil { + opts.ui.StepPreparingFailed(i+1, err) return bytes.Buffer{}, bytes.Buffer{}, err } defer cleanup() @@ -256,6 +270,7 @@ func executeSingleStep( // Parse and render the step.Files. filesToMount, cleanup, err := createFilesToMount(opts.tempDir, step, stepContext) if err != nil { + opts.ui.StepPreparingFailed(i+1, err) return bytes.Buffer{}, bytes.Buffer{}, err } defer cleanup() @@ -263,14 +278,20 @@ func executeSingleStep( // Resolve step.Env given the current environment. stepEnv, err := step.Env.Resolve(os.Environ()) if err != nil { - return bytes.Buffer{}, bytes.Buffer{}, errors.Wrap(err, "resolving step environment") + err = errors.Wrap(err, "resolving step environment") + opts.ui.StepPreparingFailed(i+1, err) + return bytes.Buffer{}, bytes.Buffer{}, err } // Render the step.Env variables as templates. env, err := template.RenderStepMap(stepEnv, stepContext) if err != nil { - return bytes.Buffer{}, bytes.Buffer{}, errors.Wrap(err, "parsing step environment") + err = errors.Wrap(err, "parsing step environment") + opts.ui.StepPreparingFailed(i+1, err) + return bytes.Buffer{}, bytes.Buffer{}, err } + opts.ui.StepPreparingSuccess(i + 1) + // ---------- // EXECUTION // ---------- @@ -330,8 +351,14 @@ func executeSingleStep( } newStepFailedErr := func(wrappedErr error) stepFailedErr { + exitCode := -1 + exitErr := &exec.ExitError{} + if errors.As(wrappedErr, &exitErr) { + exitCode = exitErr.ExitCode() + } return stepFailedErr{ Err: wrappedErr, + ExitCode: exitCode, Args: cmd.Args, Run: runScript, Container: step.Container, @@ -570,7 +597,9 @@ type stepFailedErr struct { Stdout string Stderr string - Err error + // ExitCode of the command, or -1 if a non-command error occured. + ExitCode int + Err error } func (e stepFailedErr) Cause() error { return e.Err } @@ -607,8 +636,8 @@ func (e stepFailedErr) Error() string { printOutput(e.Stderr) } - if exitErr, ok := e.Err.(*exec.ExitError); ok { - out.WriteString(fmt.Sprintf("\nCommand failed with exit code %d.", exitErr.ExitCode())) + if e.ExitCode != -1 { + out.WriteString(fmt.Sprintf("\nCommand failed with exit code %d.", e.ExitCode)) } else { out.WriteString(fmt.Sprintf("\nCommand failed: %s", e.Err)) } diff --git a/internal/batches/executor/ui.go b/internal/batches/executor/ui.go index 0ff56b2f43..f9fd449537 100644 --- a/internal/batches/executor/ui.go +++ b/internal/batches/executor/ui.go @@ -11,6 +11,7 @@ import ( type TaskExecutionUI interface { Start([]*Task) Success() + Failed(err error) TaskStarted(*Task) TaskFinished(*Task, error) @@ -28,7 +29,7 @@ type StepOutputWriter interface { type StepsExecutionUI interface { ArchiveDownloadStarted() - ArchiveDownloadFinished() + ArchiveDownloadFinished(error) WorkspaceInitializationStarted() WorkspaceInitializationFinished() @@ -37,7 +38,9 @@ type StepsExecutionUI interface { StepSkipped(int) - StepPreparing(int) + StepPreparingStart(int) + StepPreparingSuccess(int) + StepPreparingFailed(int, error) StepStarted(stepIdx int, runScript string, env map[string]string) StepOutputWriter(context.Context, *Task, int) StepOutputWriter @@ -46,18 +49,21 @@ type StepsExecutionUI interface { CalculatingDiffFinished() StepFinished(idx int, diff []byte, changes *git.Changes, outputs map[string]interface{}) + StepFailed(idx int, err error, exitCode int) } // NoopStepsExecUI is an implementation of StepsExecutionUI that does nothing. type NoopStepsExecUI struct{} func (noop NoopStepsExecUI) ArchiveDownloadStarted() {} -func (noop NoopStepsExecUI) ArchiveDownloadFinished() {} +func (noop NoopStepsExecUI) ArchiveDownloadFinished(error) {} func (noop NoopStepsExecUI) WorkspaceInitializationStarted() {} func (noop NoopStepsExecUI) WorkspaceInitializationFinished() {} func (noop NoopStepsExecUI) SkippingStepsUpto(startStep int) {} func (noop NoopStepsExecUI) StepSkipped(step int) {} -func (noop NoopStepsExecUI) StepPreparing(step int) {} +func (noop NoopStepsExecUI) StepPreparingStart(step int) {} +func (noop NoopStepsExecUI) StepPreparingSuccess(step int) {} +func (noop NoopStepsExecUI) StepPreparingFailed(step int, err error) {} func (noop NoopStepsExecUI) StepStarted(step int, runScript string, env map[string]string) {} func (noop NoopStepsExecUI) StepOutputWriter(ctx context.Context, task *Task, step int) StepOutputWriter { return NoopStepOutputWriter{} @@ -66,6 +72,8 @@ func (noop NoopStepsExecUI) CalculatingDiffStarted() {} func (noop NoopStepsExecUI) CalculatingDiffFinished() {} func (noop NoopStepsExecUI) StepFinished(idx int, diff []byte, changes *git.Changes, outputs map[string]interface{}) { } +func (noop NoopStepsExecUI) StepFailed(idx int, err error, exitCode int) { +} type NoopStepOutputWriter struct{} diff --git a/internal/batches/ui/exec_ui.go b/internal/batches/ui/exec_ui.go index 4c26727625..52a5f91637 100644 --- a/internal/batches/ui/exec_ui.go +++ b/internal/batches/ui/exec_ui.go @@ -42,7 +42,7 @@ type ExecUI interface { UploadingChangesetSpecsSuccess(ids []graphql.ChangesetSpecID) CreatingBatchSpec() - CreatingBatchSpecSuccess() + CreatingBatchSpecSuccess(previewURL string) CreatingBatchSpecError(err error) error PreviewBatchSpec(previewURL string) diff --git a/internal/batches/ui/json_lines.go b/internal/batches/ui/json_lines.go index da10f5d1bd..46c59a8f5c 100644 --- a/internal/batches/ui/json_lines.go +++ b/internal/batches/ui/json_lines.go @@ -25,76 +25,72 @@ var _ ExecUI = &JSONLines{} type JSONLines struct{} func (ui *JSONLines) ParsingBatchSpec() { - logOperationStart(batcheslib.LogEventOperationParsingBatchSpec, nil) + logOperationStart(batcheslib.LogEventOperationParsingBatchSpec, &batcheslib.ParsingBatchSpecMetadata{}) } func (ui *JSONLines) ParsingBatchSpecSuccess() { - logOperationSuccess(batcheslib.LogEventOperationParsingBatchSpec, nil) + logOperationSuccess(batcheslib.LogEventOperationParsingBatchSpec, &batcheslib.ParsingBatchSpecMetadata{}) } func (ui *JSONLines) ParsingBatchSpecFailure(err error) { - logOperationFailure(batcheslib.LogEventOperationParsingBatchSpec, map[string]interface{}{"error": err.Error()}) + logOperationFailure(batcheslib.LogEventOperationParsingBatchSpec, &batcheslib.ParsingBatchSpecMetadata{Error: err.Error()}) } func (ui *JSONLines) ResolvingNamespace() { - logOperationStart(batcheslib.LogEventOperationResolvingNamespace, nil) + logOperationStart(batcheslib.LogEventOperationResolvingNamespace, &batcheslib.ResolvingNamespaceMetadata{}) } func (ui *JSONLines) ResolvingNamespaceSuccess(namespace string) { - logOperationSuccess(batcheslib.LogEventOperationResolvingNamespace, map[string]interface{}{"namespaceID": namespace}) + logOperationSuccess(batcheslib.LogEventOperationResolvingNamespace, &batcheslib.ResolvingNamespaceMetadata{NamespaceID: namespace}) } func (ui *JSONLines) PreparingContainerImages() { - logOperationStart(batcheslib.LogEventOperationPreparingDockerImages, nil) + logOperationStart(batcheslib.LogEventOperationPreparingDockerImages, &batcheslib.PreparingDockerImagesMetadata{}) } func (ui *JSONLines) PreparingContainerImagesProgress(done, total int) { - logOperationProgress(batcheslib.LogEventOperationPreparingDockerImages, map[string]interface{}{"done": done, "total": total}) + logOperationProgress(batcheslib.LogEventOperationPreparingDockerImages, &batcheslib.PreparingDockerImagesMetadata{Done: done, Total: total}) } func (ui *JSONLines) PreparingContainerImagesSuccess() { - logOperationSuccess(batcheslib.LogEventOperationPreparingDockerImages, nil) + logOperationSuccess(batcheslib.LogEventOperationPreparingDockerImages, &batcheslib.PreparingDockerImagesMetadata{}) } func (ui *JSONLines) DeterminingWorkspaceCreatorType() { - logOperationStart(batcheslib.LogEventOperationDeterminingWorkspaceType, nil) + logOperationStart(batcheslib.LogEventOperationDeterminingWorkspaceType, &batcheslib.DeterminingWorkspaceTypeMetadata{}) } func (ui *JSONLines) DeterminingWorkspaceCreatorTypeSuccess(wt workspace.CreatorType) { + var t string switch wt { case workspace.CreatorTypeVolume: - logOperationSuccess(batcheslib.LogEventOperationDeterminingWorkspaceType, map[string]interface{}{"type": "VOLUME"}) + t = "VOLUME" case workspace.CreatorTypeBind: - logOperationSuccess(batcheslib.LogEventOperationDeterminingWorkspaceType, map[string]interface{}{"type": "BIND"}) + t = "BIND" } + logOperationSuccess(batcheslib.LogEventOperationDeterminingWorkspaceType, &batcheslib.DeterminingWorkspaceTypeMetadata{Type: t}) } func (ui *JSONLines) ResolvingRepositories() { - logOperationStart(batcheslib.LogEventOperationResolvingRepositories, nil) + logOperationStart(batcheslib.LogEventOperationResolvingRepositories, &batcheslib.ResolvingRepositoriesMetadata{}) } func (ui *JSONLines) ResolvingRepositoriesDone(repos []*graphql.Repository, unsupported batches.UnsupportedRepoSet, ignored batches.IgnoredRepoSet) { - if unsupported != nil && len(unsupported) != 0 { - logOperationSuccess(batcheslib.LogEventOperationResolvingRepositories, map[string]interface{}{"unsupported": len(unsupported)}) - } else if ignored != nil && len(ignored) != 0 { - logOperationSuccess(batcheslib.LogEventOperationResolvingRepositories, map[string]interface{}{"ignored": len(ignored)}) - } else { - logOperationSuccess(batcheslib.LogEventOperationResolvingRepositories, map[string]interface{}{"count": len(repos)}) - } + logOperationSuccess(batcheslib.LogEventOperationResolvingRepositories, &batcheslib.ResolvingRepositoriesMetadata{ + Unsupported: len(unsupported), + Ignored: len(ignored), + Count: len(repos), + }) } func (ui *JSONLines) DeterminingWorkspaces() { - logOperationStart(batcheslib.LogEventOperationDeterminingWorkspaces, nil) + logOperationStart(batcheslib.LogEventOperationDeterminingWorkspaces, &batcheslib.DeterminingWorkspacesMetadata{}) } func (ui *JSONLines) DeterminingWorkspacesSuccess(num int) { - metadata := map[string]interface{}{ - "count": num, - } - logOperationSuccess(batcheslib.LogEventOperationDeterminingWorkspaces, metadata) + logOperationSuccess(batcheslib.LogEventOperationDeterminingWorkspaces, &batcheslib.DeterminingWorkspacesMetadata{Count: num}) } func (ui *JSONLines) CheckingCache() { - logOperationStart(batcheslib.LogEventOperationCheckingCache, nil) + logOperationStart(batcheslib.LogEventOperationCheckingCache, &batcheslib.CheckingCacheMetadata{}) } func (ui *JSONLines) CheckingCacheSuccess(cachedSpecsFound int, tasksToExecute int) { - metadata := map[string]interface{}{ - "cachedSpecsFound": cachedSpecsFound, - "tasksToExecute": tasksToExecute, - } - logOperationSuccess(batcheslib.LogEventOperationCheckingCache, metadata) + logOperationSuccess(batcheslib.LogEventOperationCheckingCache, &batcheslib.CheckingCacheMetadata{ + CachedSpecsFound: cachedSpecsFound, + TasksToExecute: tasksToExecute, + }) } func (ui *JSONLines) ExecutingTasks(verbose bool, parallelism int) executor.TaskExecutionUI { @@ -102,12 +98,15 @@ func (ui *JSONLines) ExecutingTasks(verbose bool, parallelism int) executor.Task } func (ui *JSONLines) ExecutingTasksSkippingErrors(err error) { - logOperationSuccess(batcheslib.LogEventOperationExecutingTasks, map[string]interface{}{"skipped": true, "error": err.Error()}) + logOperationSuccess(batcheslib.LogEventOperationExecutingTasks, &batcheslib.ExecutingTasksMetadata{ + Skipped: true, + Error: err.Error(), + }) } func (ui *JSONLines) LogFilesKept(files []string) { - for _, file := range files { - logOperationSuccess(batcheslib.LogEventOperationLogFileKept, map[string]interface{}{"path": file}) + for _, path := range files { + logOperationSuccess(batcheslib.LogEventOperationLogFileKept, &batcheslib.LogFileKeptMetadata{Path: path}) } } @@ -116,91 +115,67 @@ func (ui *JSONLines) NoChangesetSpecs() { } func (ui *JSONLines) UploadingChangesetSpecs(num int) { - logOperationStart(batcheslib.LogEventOperationUploadingChangesetSpecs, map[string]interface{}{ - "total": num, + logOperationStart(batcheslib.LogEventOperationUploadingChangesetSpecs, &batcheslib.UploadingChangesetSpecsMetadata{ + Done: 0, + Total: num, }) } func (ui *JSONLines) UploadingChangesetSpecsProgress(done, total int) { - logOperationProgress(batcheslib.LogEventOperationUploadingChangesetSpecs, map[string]interface{}{ - "done": done, - "total": total, + logOperationProgress(batcheslib.LogEventOperationUploadingChangesetSpecs, &batcheslib.UploadingChangesetSpecsMetadata{ + Done: done, + Total: total, }) } func (ui *JSONLines) UploadingChangesetSpecsSuccess(ids []graphql.ChangesetSpecID) { - logOperationSuccess(batcheslib.LogEventOperationUploadingChangesetSpecs, map[string]interface{}{ - "ids": ids, + sIDs := make([]string, len(ids)) + for i, id := range ids { + sIDs[i] = string(id) + } + logOperationSuccess(batcheslib.LogEventOperationUploadingChangesetSpecs, &batcheslib.UploadingChangesetSpecsMetadata{ + Done: len(ids), + Total: len(ids), + IDs: sIDs, }) } func (ui *JSONLines) CreatingBatchSpec() { - logOperationStart(batcheslib.LogEventOperationCreatingBatchSpec, nil) + logOperationStart(batcheslib.LogEventOperationCreatingBatchSpec, &batcheslib.CreatingBatchSpecMetadata{}) } -func (ui *JSONLines) CreatingBatchSpecSuccess() { +func (ui *JSONLines) CreatingBatchSpecSuccess(batchSpecURL string) { + logOperationSuccess(batcheslib.LogEventOperationCreatingBatchSpec, &batcheslib.CreatingBatchSpecMetadata{ + PreviewURL: batchSpecURL, + }) } func (ui *JSONLines) CreatingBatchSpecError(err error) error { + logOperationFailure(batcheslib.LogEventOperationCreatingBatchSpec, &batcheslib.CreatingBatchSpecMetadata{}) return err } func (ui *JSONLines) PreviewBatchSpec(batchSpecURL string) { - logOperationSuccess(batcheslib.LogEventOperationCreatingBatchSpec, map[string]interface{}{"batchSpecURL": batchSpecURL}) + // Covered by CreatingBatchSpecSuccess. } func (ui *JSONLines) ApplyingBatchSpec() { - logOperationStart(batcheslib.LogEventOperationApplyingBatchSpec, nil) + logOperationStart(batcheslib.LogEventOperationApplyingBatchSpec, &batcheslib.ApplyingBatchSpecMetadata{}) } func (ui *JSONLines) ApplyingBatchSpecSuccess(batchChangeURL string) { - logOperationSuccess(batcheslib.LogEventOperationApplyingBatchSpec, map[string]interface{}{"batchChangeURL": batchChangeURL}) + logOperationSuccess(batcheslib.LogEventOperationApplyingBatchSpec, &batcheslib.ApplyingBatchSpecMetadata{BatchChangeURL: batchChangeURL}) } func (ui *JSONLines) ExecutionError(err error) { - logOperationFailure(batcheslib.LogEventOperationBatchSpecExecution, map[string]interface{}{"error": err.Error()}) -} - -func logOperationStart(op batcheslib.LogEventOperation, metadata map[string]interface{}) { - logEvent(batcheslib.LogEvent{Operation: op, Status: batcheslib.LogEventStatusStarted, Metadata: metadata}) -} - -func logOperationSuccess(op batcheslib.LogEventOperation, metadata map[string]interface{}) { - logEvent(batcheslib.LogEvent{Operation: op, Status: batcheslib.LogEventStatusSuccess, Metadata: metadata}) -} - -func logOperationFailure(op batcheslib.LogEventOperation, metadata map[string]interface{}) { - logEvent(batcheslib.LogEvent{Operation: op, Status: batcheslib.LogEventStatusFailure, Metadata: metadata}) -} - -func logOperationProgress(op batcheslib.LogEventOperation, metadata map[string]interface{}) { - logEvent(batcheslib.LogEvent{Operation: op, Status: batcheslib.LogEventStatusProgress, Metadata: metadata}) -} - -func logEvent(e batcheslib.LogEvent) { - e.Timestamp = time.Now().UTC().Truncate(time.Millisecond) - err := json.NewEncoder(os.Stdout).Encode(e) - if err != nil { - fmt.Fprintln(os.Stderr, err) - } -} - -// TODO: Until we've figured out what exactly we want to expose, we create -// these smaller UI-specific structs. -type jsonLinesTask struct { - ID string `json:"id"` - Repository string `json:"repository"` - Workspace string `json:"workspace"` - Steps []batcheslib.Step `json:"steps"` - CachedStepResultsFound bool `json:"cachedStepResultFound"` - StartStep int `json:"startStep"` + logOperationFailure(batcheslib.LogEventOperationBatchSpecExecution, &batcheslib.BatchSpecExecutionMetadata{Error: err.Error()}) } type taskExecutionJSONLines struct { verbose bool parallelism int - linesTasks map[*executor.Task]jsonLinesTask + linesTasks map[*executor.Task]batcheslib.JSONLinesTask } // seededRand is used in randomID() to generate a "random" number. @@ -212,14 +187,14 @@ func randomID() (string, error) { } func (ui *taskExecutionJSONLines) Start(tasks []*executor.Task) { - ui.linesTasks = make(map[*executor.Task]jsonLinesTask, len(tasks)) - linesTasks := []jsonLinesTask{} + ui.linesTasks = make(map[*executor.Task]batcheslib.JSONLinesTask, len(tasks)) + linesTasks := []batcheslib.JSONLinesTask{} for _, t := range tasks { id, err := randomID() if err != nil { panic(err) } - linesTask := jsonLinesTask{ + linesTask := batcheslib.JSONLinesTask{ ID: id, Repository: t.Repository.Name, Workspace: t.Path, @@ -231,12 +206,16 @@ func (ui *taskExecutionJSONLines) Start(tasks []*executor.Task) { linesTasks = append(linesTasks, linesTask) } - logOperationStart(batcheslib.LogEventOperationExecutingTasks, map[string]interface{}{ - "tasks": linesTasks, + logOperationStart(batcheslib.LogEventOperationExecutingTasks, &batcheslib.ExecutingTasksMetadata{ + Tasks: linesTasks, }) } func (ui *taskExecutionJSONLines) Success() { - logOperationSuccess(batcheslib.LogEventOperationExecutingTasks, nil) + logOperationSuccess(batcheslib.LogEventOperationExecutingTasks, &batcheslib.ExecutingTasksMetadata{}) +} + +func (ui *taskExecutionJSONLines) Failed(err error) { + logOperationFailure(batcheslib.LogEventOperationExecutingTasks, &batcheslib.ExecutingTasksMetadata{Error: err.Error()}) } func (ui *taskExecutionJSONLines) TaskStarted(task *executor.Task) { @@ -245,9 +224,7 @@ func (ui *taskExecutionJSONLines) TaskStarted(task *executor.Task) { panic("unknown task started") } - logOperationStart(batcheslib.LogEventOperationExecutingTask, map[string]interface{}{ - "taskID": lt.ID, - }) + logOperationStart(batcheslib.LogEventOperationExecutingTask, &batcheslib.ExecutingTaskMetadata{TaskID: lt.ID}) } func (ui *taskExecutionJSONLines) TaskFinished(task *executor.Task, err error) { @@ -257,16 +234,14 @@ func (ui *taskExecutionJSONLines) TaskFinished(task *executor.Task, err error) { } if err != nil { - logOperationFailure(batcheslib.LogEventOperationExecutingTask, map[string]interface{}{ - "taskID": lt.ID, - "error": err, + logOperationFailure(batcheslib.LogEventOperationExecutingTask, &batcheslib.ExecutingTaskMetadata{ + TaskID: lt.ID, + Error: err.Error(), }) return } - logOperationSuccess(batcheslib.LogEventOperationExecutingTask, map[string]interface{}{ - "taskID": lt.ID, - }) + logOperationSuccess(batcheslib.LogEventOperationExecutingTask, &batcheslib.ExecutingTaskMetadata{TaskID: lt.ID}) } func (ui *taskExecutionJSONLines) TaskChangesetSpecsBuilt(task *executor.Task, specs []*batcheslib.ChangesetSpec) { @@ -274,9 +249,8 @@ func (ui *taskExecutionJSONLines) TaskChangesetSpecsBuilt(task *executor.Task, s if !ok { panic("unknown task started") } - logOperationSuccess(batcheslib.LogEventOperationTaskBuildChangesetSpecs, map[string]interface{}{ - "taskID": lt.ID, - }) + + logOperationSuccess(batcheslib.LogEventOperationTaskBuildChangesetSpecs, &batcheslib.TaskBuildChangesetSpecsMetadata{TaskID: lt.ID}) } func (ui *taskExecutionJSONLines) StepsExecutionUI(task *executor.Task) executor.StepsExecutionUI { @@ -289,49 +263,59 @@ func (ui *taskExecutionJSONLines) StepsExecutionUI(task *executor.Task) executor } type stepsExecutionJSONLines struct { - linesTask *jsonLinesTask + linesTask *batcheslib.JSONLinesTask } const stepFlushDuration = 500 * time.Millisecond func (ui *stepsExecutionJSONLines) ArchiveDownloadStarted() { - logOperationStart(batcheslib.LogEventOperationTaskDownloadingArchive, map[string]interface{}{"taskID": ui.linesTask.ID}) + logOperationStart(batcheslib.LogEventOperationTaskDownloadingArchive, &batcheslib.TaskDownloadingArchiveMetadata{TaskID: ui.linesTask.ID}) } - -func (ui *stepsExecutionJSONLines) ArchiveDownloadFinished() { - logOperationSuccess(batcheslib.LogEventOperationTaskDownloadingArchive, map[string]interface{}{"taskID": ui.linesTask.ID}) +func (ui *stepsExecutionJSONLines) ArchiveDownloadFinished(err error) { + if err != nil { + logOperationFailure(batcheslib.LogEventOperationTaskDownloadingArchive, &batcheslib.TaskDownloadingArchiveMetadata{TaskID: ui.linesTask.ID, Error: err.Error()}) + } else { + logOperationSuccess(batcheslib.LogEventOperationTaskDownloadingArchive, &batcheslib.TaskDownloadingArchiveMetadata{TaskID: ui.linesTask.ID}) + } } + func (ui *stepsExecutionJSONLines) WorkspaceInitializationStarted() { - logOperationStart(batcheslib.LogEventOperationTaskInitializingWorkspace, map[string]interface{}{"taskID": ui.linesTask.ID}) + logOperationStart(batcheslib.LogEventOperationTaskInitializingWorkspace, &batcheslib.TaskInitializingWorkspaceMetadata{TaskID: ui.linesTask.ID}) } func (ui *stepsExecutionJSONLines) WorkspaceInitializationFinished() { - logOperationSuccess(batcheslib.LogEventOperationTaskInitializingWorkspace, map[string]interface{}{"taskID": ui.linesTask.ID}) + logOperationSuccess(batcheslib.LogEventOperationTaskInitializingWorkspace, &batcheslib.TaskInitializingWorkspaceMetadata{TaskID: ui.linesTask.ID}) } func (ui *stepsExecutionJSONLines) SkippingStepsUpto(startStep int) { - logOperationProgress(batcheslib.LogEventOperationTaskSkippingSteps, map[string]interface{}{"taskID": ui.linesTask.ID, "startStep": startStep}) + logOperationProgress(batcheslib.LogEventOperationTaskSkippingSteps, &batcheslib.TaskSkippingStepsMetadata{TaskID: ui.linesTask.ID, StartStep: startStep}) } func (ui *stepsExecutionJSONLines) StepSkipped(step int) { - logOperationProgress(batcheslib.LogEventOperationTaskStepSkipped, map[string]interface{}{"taskID": ui.linesTask.ID, "step": step}) + logOperationProgress(batcheslib.LogEventOperationTaskStepSkipped, &batcheslib.TaskStepSkippedMetadata{TaskID: ui.linesTask.ID, Step: step}) } -func (ui *stepsExecutionJSONLines) StepPreparing(step int) { - logOperationProgress(batcheslib.LogEventOperationTaskPreparingStep, map[string]interface{}{"taskID": ui.linesTask.ID, "step": step}) +func (ui *stepsExecutionJSONLines) StepPreparingStart(step int) { + logOperationStart(batcheslib.LogEventOperationTaskPreparingStep, &batcheslib.TaskPreparingStepMetadata{TaskID: ui.linesTask.ID, Step: step}) +} +func (ui *stepsExecutionJSONLines) StepPreparingSuccess(step int) { + logOperationSuccess(batcheslib.LogEventOperationTaskPreparingStep, &batcheslib.TaskPreparingStepMetadata{TaskID: ui.linesTask.ID, Step: step}) +} +func (ui *stepsExecutionJSONLines) StepPreparingFailed(step int, err error) { + logOperationFailure(batcheslib.LogEventOperationTaskPreparingStep, &batcheslib.TaskPreparingStepMetadata{TaskID: ui.linesTask.ID, Step: step, Error: err.Error()}) } func (ui *stepsExecutionJSONLines) StepStarted(step int, runScript string, env map[string]string) { - logOperationStart(batcheslib.LogEventOperationTaskStep, map[string]interface{}{"taskID": ui.linesTask.ID, "step": step, "runScript": runScript, "env": env}) + logOperationStart(batcheslib.LogEventOperationTaskStep, &batcheslib.TaskStepMetadata{TaskID: ui.linesTask.ID, Step: step, Env: env}) } func (ui *stepsExecutionJSONLines) StepOutputWriter(ctx context.Context, task *executor.Task, step int) executor.StepOutputWriter { sink := func(data string) { logOperationProgress( batcheslib.LogEventOperationTaskStep, - map[string]interface{}{ - "taskID": ui.linesTask.ID, - "step": step, - "out": data, + &batcheslib.TaskStepMetadata{ + TaskID: ui.linesTask.ID, + Step: step, + Out: data, }, ) } @@ -341,19 +325,54 @@ func (ui *stepsExecutionJSONLines) StepOutputWriter(ctx context.Context, task *e func (ui *stepsExecutionJSONLines) StepFinished(step int, diff []byte, changes *git.Changes, outputs map[string]interface{}) { logOperationSuccess( batcheslib.LogEventOperationTaskStep, - map[string]interface{}{ - "taskID": ui.linesTask.ID, - "step": step, - "diff": string(diff), - "changes": changes, - "outputs": outputs, + &batcheslib.TaskStepMetadata{ + TaskID: ui.linesTask.ID, + Step: step, + Diff: string(diff), + Outputs: outputs, + }, + ) +} + +func (ui *stepsExecutionJSONLines) StepFailed(step int, err error, exitCode int) { + logOperationFailure( + batcheslib.LogEventOperationTaskStep, + &batcheslib.TaskStepMetadata{ + TaskID: ui.linesTask.ID, + Step: step, + Error: err.Error(), + ExitCode: exitCode, }, ) } func (ui *stepsExecutionJSONLines) CalculatingDiffStarted() { - logOperationStart(batcheslib.LogEventOperationTaskCalculatingDiff, map[string]interface{}{"taskID": ui.linesTask.ID}) + logOperationStart(batcheslib.LogEventOperationTaskCalculatingDiff, &batcheslib.TaskCalculatingDiffMetadata{TaskID: ui.linesTask.ID}) } func (ui *stepsExecutionJSONLines) CalculatingDiffFinished() { - logOperationSuccess(batcheslib.LogEventOperationTaskCalculatingDiff, map[string]interface{}{"taskID": ui.linesTask.ID}) + logOperationSuccess(batcheslib.LogEventOperationTaskCalculatingDiff, &batcheslib.TaskCalculatingDiffMetadata{TaskID: ui.linesTask.ID}) +} + +func logOperationStart(op batcheslib.LogEventOperation, metadata interface{}) { + logEvent(batcheslib.LogEvent{Operation: op, Status: batcheslib.LogEventStatusStarted, Metadata: metadata}) +} + +func logOperationSuccess(op batcheslib.LogEventOperation, metadata interface{}) { + logEvent(batcheslib.LogEvent{Operation: op, Status: batcheslib.LogEventStatusSuccess, Metadata: metadata}) +} + +func logOperationFailure(op batcheslib.LogEventOperation, metadata interface{}) { + logEvent(batcheslib.LogEvent{Operation: op, Status: batcheslib.LogEventStatusFailure, Metadata: metadata}) +} + +func logOperationProgress(op batcheslib.LogEventOperation, metadata interface{}) { + logEvent(batcheslib.LogEvent{Operation: op, Status: batcheslib.LogEventStatusProgress, Metadata: metadata}) +} + +func logEvent(e batcheslib.LogEvent) { + e.Timestamp = time.Now().UTC().Truncate(time.Millisecond) + err := json.NewEncoder(os.Stdout).Encode(e) + if err != nil { + fmt.Fprintln(os.Stderr, err) + } } diff --git a/internal/batches/ui/task_exec_tui.go b/internal/batches/ui/task_exec_tui.go index f73e332267..845b9c1445 100644 --- a/internal/batches/ui/task_exec_tui.go +++ b/internal/batches/ui/task_exec_tui.go @@ -149,6 +149,9 @@ func (ui *taskExecTUI) Start(tasks []*executor.Task) { func (ui *taskExecTUI) Success() { ui.progress.Complete() } +func (ui *taskExecTUI) Failed(err error) { + // noop right now +} func (ui *taskExecTUI) useFreeStatusBar(ts *taskStatus) (bar int, found bool) { for i := 0; i < ui.numStatusBars; i++ { @@ -434,7 +437,7 @@ type stepsExecTUI struct { func (ui stepsExecTUI) ArchiveDownloadStarted() { ui.updateStatusBar("Downloading archive") } -func (ui stepsExecTUI) ArchiveDownloadFinished() {} +func (ui stepsExecTUI) ArchiveDownloadFinished(err error) {} func (ui stepsExecTUI) WorkspaceInitializationStarted() { ui.updateStatusBar("Initializing workspace") } @@ -451,9 +454,15 @@ func (ui stepsExecTUI) SkippingStepsUpto(startStep int) { func (ui stepsExecTUI) StepSkipped(step int) { ui.updateStatusBar(fmt.Sprintf("Skipping step %d", step)) } -func (ui stepsExecTUI) StepPreparing(step int) { +func (ui stepsExecTUI) StepPreparingStart(step int) { ui.updateStatusBar(fmt.Sprintf("Preparing %d", step)) } +func (ui stepsExecTUI) StepPreparingSuccess(step int) { + // noop right now +} +func (ui stepsExecTUI) StepPreparingFailed(step int, err error) { + // noop right now +} func (ui stepsExecTUI) StepStarted(step int, runScript string, _ map[string]string) { ui.updateStatusBar(runScript) } @@ -471,3 +480,6 @@ func (ui stepsExecTUI) CalculatingDiffFinished() { func (ui stepsExecTUI) StepFinished(idx int, diff []byte, changes *git.Changes, outputs map[string]interface{}) { // noop right now } +func (ui stepsExecTUI) StepFailed(idx int, err error, exitCode int) { + // noop right now +} diff --git a/internal/batches/ui/tui.go b/internal/batches/ui/tui.go index 8013185c3c..1e511ccefa 100644 --- a/internal/batches/ui/tui.go +++ b/internal/batches/ui/tui.go @@ -192,7 +192,7 @@ func (ui *TUI) CreatingBatchSpec() { ui.pending = batchCreatePending(ui.Out, "Creating batch spec on Sourcegraph") } -func (ui *TUI) CreatingBatchSpecSuccess() { +func (ui *TUI) CreatingBatchSpecSuccess(previewURL string) { batchCompletePending(ui.pending, "Creating batch spec on Sourcegraph") } From 5d44100eefe67fceaf9cc983328bb74ee783ce2c Mon Sep 17 00:00:00 2001 From: Adam Harvey Date: Wed, 6 Oct 2021 10:20:36 -0700 Subject: [PATCH 048/647] internal/batches: include the url field in repositories (#625) Removing this in #598 broke the `src batch repos` command, which used the `url` field when rendering the link to the repo in Sourcegraph. --- CHANGELOG.md | 2 ++ internal/batches/graphql/repository.go | 2 ++ 2 files changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3a01bb28ca..36b24b857d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,8 @@ All notable changes to `src-cli` are documented in this file. ### Fixed +- `src batch repos` failed with a template error in src-cli 3.31.1 and 3.32.0. This has been fixed. [#625](https://github.com/sourcegraph/src-cli/pull/625) + ### Removed ## 3.31.1 diff --git a/internal/batches/graphql/repository.go b/internal/batches/graphql/repository.go index eed5732f34..17fb6e02ad 100644 --- a/internal/batches/graphql/repository.go +++ b/internal/batches/graphql/repository.go @@ -6,6 +6,7 @@ const RepositoryFieldsFragment = ` fragment repositoryFields on Repository { id name + url externalRepository { serviceType } @@ -33,6 +34,7 @@ type Branch struct { type Repository struct { ID string Name string + URL string ExternalRepository struct{ ServiceType string } DefaultBranch *Branch From 6eecfd0d0a8f101b39ccd8bffa037b92ff4c83e8 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Mon, 11 Oct 2021 16:05:12 +0200 Subject: [PATCH 049/647] Use latest lib version with lenient batch spec validations (#627) --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 3f21bfb592..8b74b738e0 100644 --- a/go.mod +++ b/go.mod @@ -21,7 +21,7 @@ require ( github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4 github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf - github.com/sourcegraph/sourcegraph/lib v0.0.0-20210929121718-d5efc9330247 + github.com/sourcegraph/sourcegraph/lib v0.0.0-20211011135305-1971ff7fa57e github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect golang.org/x/net v0.0.0-20210614182718-04defd469f4e diff --git a/go.sum b/go.sum index 5777c5f8eb..2d2a2701b7 100644 --- a/go.sum +++ b/go.sum @@ -259,8 +259,8 @@ github.com/sourcegraph/go-diff v0.6.1 h1:hmA1LzxW0n1c3Q4YbrFgg4P99GSnebYa3x8gr0H github.com/sourcegraph/go-diff v0.6.1/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20210929121718-d5efc9330247 h1:U1qXWB+6i/YeQ73kirisIEsxCBgNXw4td4QYdYlBeKM= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20210929121718-d5efc9330247/go.mod h1:9vLg5fQL9Q3iktfqu96OrswbOq7yqMesMJER9DCy8vk= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20211011135305-1971ff7fa57e h1:oteOieW7+0q8bp6OzWmeov303JY0QE+/p0+fV1T9NZw= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20211011135305-1971ff7fa57e/go.mod h1:9vLg5fQL9Q3iktfqu96OrswbOq7yqMesMJER9DCy8vk= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= From 3fd8775b1a867b27a27446eb54b6b7c6bfbc3556 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Mon, 11 Oct 2021 16:08:14 +0200 Subject: [PATCH 050/647] Prepare changelog for 3.32.1 --- CHANGELOG.md | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 36b24b857d..1f50353f3c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,16 @@ All notable changes to `src-cli` are documented in this file. ### Added +### Changed + +### Fixed + +### Removed + +## 3.31.1 + +### Added + - For internal use only: the `src batch exec` command executes the provided batch spec in the given workspaces. ### Changed @@ -23,8 +33,6 @@ All notable changes to `src-cli` are documented in this file. - `src batch repos` failed with a template error in src-cli 3.31.1 and 3.32.0. This has been fixed. [#625](https://github.com/sourcegraph/src-cli/pull/625) -### Removed - ## 3.31.1 ### Changed From 62b13223c2e8fb7b49f5e6d135ecde631b215bee Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Tue, 12 Oct 2021 14:41:09 +0200 Subject: [PATCH 051/647] Fix importing changesets with no docker images (#630) When only importing changesets, no docker images would need to be pulled. In the TUI, a division by zero would be made and the input for the tab UI would be NaN. This caused an error, that was reported in https://github.com/sourcegraph/src-cli/issues/629. --- CHANGELOG.md | 2 ++ cmd/src/batch_common.go | 26 +++++++++++++++----------- cmd/src/batch_exec.go | 26 +++++++++++++++----------- internal/batches/service/service.go | 4 ++++ 4 files changed, 36 insertions(+), 22 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1f50353f3c..c6be580929 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,8 @@ All notable changes to `src-cli` are documented in this file. ### Fixed +- Fixes an issue where src-cli would panic when importing existing changesets. + ### Removed ## 3.31.1 diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index c0ab724f1b..e6e49833e1 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -248,22 +248,26 @@ func executeBatchSpec(ctx context.Context, opts executeBatchSpecOpts) (err error } opts.ui.ResolvingNamespaceSuccess(namespace) - opts.ui.PreparingContainerImages() - images, err := svc.EnsureDockerImages(ctx, batchSpec, opts.ui.PreparingContainerImagesProgress) - if err != nil { - return err - } - opts.ui.PreparingContainerImagesSuccess() + var workspaceCreator workspace.Creator - opts.ui.DeterminingWorkspaceCreatorType() - workspaceCreator := workspace.NewCreator(ctx, opts.flags.workspace, opts.flags.cacheDir, opts.flags.tempDir, images) - if workspaceCreator.Type() == workspace.CreatorTypeVolume { - _, err = svc.EnsureImage(ctx, workspace.DockerVolumeWorkspaceImage) + if svc.HasDockerImages(batchSpec) { + opts.ui.PreparingContainerImages() + images, err := svc.EnsureDockerImages(ctx, batchSpec, opts.ui.PreparingContainerImagesProgress) if err != nil { return err } + opts.ui.PreparingContainerImagesSuccess() + + opts.ui.DeterminingWorkspaceCreatorType() + workspaceCreator = workspace.NewCreator(ctx, opts.flags.workspace, opts.flags.cacheDir, opts.flags.tempDir, images) + if workspaceCreator.Type() == workspace.CreatorTypeVolume { + _, err = svc.EnsureImage(ctx, workspace.DockerVolumeWorkspaceImage) + if err != nil { + return err + } + } + opts.ui.DeterminingWorkspaceCreatorTypeSuccess(workspaceCreator.Type()) } - opts.ui.DeterminingWorkspaceCreatorTypeSuccess(workspaceCreator.Type()) opts.ui.ResolvingRepositories() repos, err := svc.ResolveRepositories(ctx, batchSpec) diff --git a/cmd/src/batch_exec.go b/cmd/src/batch_exec.go index 78546e55aa..a08d8be2aa 100644 --- a/cmd/src/batch_exec.go +++ b/cmd/src/batch_exec.go @@ -125,22 +125,26 @@ func executeBatchSpecInWorkspaces(ctx context.Context, opts executeBatchSpecOpts } opts.ui.ParsingBatchSpecSuccess() - opts.ui.PreparingContainerImages() - images, err := svc.EnsureDockerImages(ctx, batchSpec, opts.ui.PreparingContainerImagesProgress) - if err != nil { - return err - } - opts.ui.PreparingContainerImagesSuccess() + var workspaceCreator workspace.Creator - opts.ui.DeterminingWorkspaceCreatorType() - workspaceCreator := workspace.NewCreator(ctx, opts.flags.workspace, opts.flags.cacheDir, opts.flags.tempDir, images) - if workspaceCreator.Type() == workspace.CreatorTypeVolume { - _, err = svc.EnsureImage(ctx, workspace.DockerVolumeWorkspaceImage) + if svc.HasDockerImages(batchSpec) { + opts.ui.PreparingContainerImages() + images, err := svc.EnsureDockerImages(ctx, batchSpec, opts.ui.PreparingContainerImagesProgress) if err != nil { return err } + opts.ui.PreparingContainerImagesSuccess() + + opts.ui.DeterminingWorkspaceCreatorType() + workspaceCreator = workspace.NewCreator(ctx, opts.flags.workspace, opts.flags.cacheDir, opts.flags.tempDir, images) + if workspaceCreator.Type() == workspace.CreatorTypeVolume { + _, err = svc.EnsureImage(ctx, workspace.DockerVolumeWorkspaceImage) + if err != nil { + return err + } + } + opts.ui.DeterminingWorkspaceCreatorTypeSuccess(workspaceCreator.Type()) } - opts.ui.DeterminingWorkspaceCreatorTypeSuccess(workspaceCreator.Type()) // EXECUTION OF TASKS coord := svc.NewCoordinator(executor.NewCoordinatorOpts{ diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index 7a59dfce38..cb2b43500c 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -172,6 +172,10 @@ func (svc *Service) EnsureDockerImages(ctx context.Context, spec *batcheslib.Bat return images, nil } +func (svc *Service) HasDockerImages(spec *batcheslib.BatchSpec) bool { + return len(spec.Steps) > 0 +} + func (svc *Service) EnsureImage(ctx context.Context, name string) (docker.Image, error) { img := svc.imageCache.Get(name) From 17aa10d62db5ba7be1190ed688b5183d970d0e68 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Tue, 12 Oct 2021 14:43:22 +0200 Subject: [PATCH 052/647] Prepare changelog for 3.31.2 --- CHANGELOG.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c6be580929..5f521252af 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,10 +17,14 @@ All notable changes to `src-cli` are documented in this file. ### Fixed -- Fixes an issue where src-cli would panic when importing existing changesets. - ### Removed +## 3.31.2 + +### Fixed + +- Fixes an issue where src-cli would panic when importing existing changesets. + ## 3.31.1 ### Added From e01f9dfdd4e41a3c444deaf855af57883edb6bcb Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Tue, 12 Oct 2021 15:44:02 +0200 Subject: [PATCH 053/647] Use ParseChangesetSpecExternalID from lib (#631) Has been moved there, but not yet replaced in src cli. --- internal/batches/executor/coordinator.go | 23 ++++------------------- 1 file changed, 4 insertions(+), 19 deletions(-) diff --git a/internal/batches/executor/coordinator.go b/internal/batches/executor/coordinator.go index 4c66bef0fa..3a42b9bfab 100644 --- a/internal/batches/executor/coordinator.go +++ b/internal/batches/executor/coordinator.go @@ -2,8 +2,6 @@ package executor import ( "context" - "reflect" - "strconv" "time" "github.com/cockroachdb/errors" @@ -261,27 +259,14 @@ func (c *Coordinator) Execute(ctx context.Context, tasks []*Task, spec *batchesl } for _, id := range ic.ExternalIDs { - var sid string - - switch tid := id.(type) { - case string: - sid = tid - case int, int8, int16, int32, int64: - sid = strconv.FormatInt(reflect.ValueOf(id).Int(), 10) - case uint, uint8, uint16, uint32, uint64: - sid = strconv.FormatUint(reflect.ValueOf(id).Uint(), 10) - case float32: - sid = strconv.FormatFloat(float64(tid), 'f', -1, 32) - case float64: - sid = strconv.FormatFloat(tid, 'f', -1, 64) - default: - return nil, nil, batcheslib.NewValidationError(errors.Errorf("cannot convert value of type %T into a valid external ID: expected string or int", id)) + sid, err := batcheslib.ParseChangesetSpecExternalID(id) + if err != nil { + return nil, nil, err } specs = append(specs, &batcheslib.ChangesetSpec{ BaseRepository: repo.ID, - - ExternalID: sid, + ExternalID: sid, }) } } From e824d8077693405699475fc96b1fe6ed0e63269d Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 13 Oct 2021 14:07:08 -0700 Subject: [PATCH 054/647] Update golang:1.17-alpine Docker digest to c233503 (#624) Co-authored-by: Renovate Bot --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index 2557eaca85..3450dc7ca3 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,7 +4,7 @@ # # Nothing fancy here: we copy in the source code and build on the Alpine Go # image. Refer to .dockerignore to get a sense of what we're not going to copy. -FROM golang:1.17-alpine@sha256:c03a922dfb0d6d3a94d46cc5be69002011763595ac2786068fde63ee174d797b as builder +FROM golang:1.17-alpine@sha256:c2335038e2230960f81cb2f9f1fc5eca45e23b765de1848c7bbfaebcfd32d90d as builder COPY . /src WORKDIR /src From 03d43592008c833631ad4126bd86a690143dd146 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 13 Oct 2021 14:07:34 -0700 Subject: [PATCH 055/647] Update actions/checkout action to v2 (#363) Co-authored-by: Renovate Bot --- .github/workflows/lsif.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/lsif.yml b/.github/workflows/lsif.yml index 83d4bfd168..9bc6d536b3 100644 --- a/.github/workflows/lsif.yml +++ b/.github/workflows/lsif.yml @@ -6,7 +6,7 @@ jobs: runs-on: ubuntu-latest container: sourcegraph/lsif-go steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@5a4ac9002d0be2fb38bd78e4b4dbde5606d7042f # renovate: tag=v2 - name: Generate LSIF data run: lsif-go - name: Upload LSIF data From 9853798634f7cf6d983a7738041744e461fe2873 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 13 Oct 2021 14:32:16 -0700 Subject: [PATCH 056/647] Update alpine Docker tag to v3.14.2 (#530) Co-authored-by: Renovate Bot --- docker/batch-change-volume-workspace/Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docker/batch-change-volume-workspace/Dockerfile b/docker/batch-change-volume-workspace/Dockerfile index 1803fa7c92..99abd7cb7f 100644 --- a/docker/batch-change-volume-workspace/Dockerfile +++ b/docker/batch-change-volume-workspace/Dockerfile @@ -2,6 +2,6 @@ # image that we use to run curl, git, and unzip against a Docker volume when # using the volume workspace. -FROM alpine:3.13.4@sha256:ec14c7992a97fc11425907e908340c6c3d6ff602f5f13d899e6b7027c9b4133a +FROM alpine:3.14.2@sha256:e1c082e3d3c45cccac829840a25941e679c25d438cc8412c2fa221cf1a824e6a RUN apk add --update git unzip From 76a34d23b60567db6426b7de29ceccfeb23cac50 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 13 Oct 2021 20:12:07 -0700 Subject: [PATCH 057/647] Update golang:1.17-alpine Docker digest to 5519c87 (#632) Co-authored-by: Renovate Bot --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index 3450dc7ca3..7390b2f802 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,7 +4,7 @@ # # Nothing fancy here: we copy in the source code and build on the Alpine Go # image. Refer to .dockerignore to get a sense of what we're not going to copy. -FROM golang:1.17-alpine@sha256:c2335038e2230960f81cb2f9f1fc5eca45e23b765de1848c7bbfaebcfd32d90d as builder +FROM golang:1.17-alpine@sha256:5519c8752f6b53fc8818dc46e9fda628c99c4e8fd2d2f1df71e1f184e71f47dc as builder COPY . /src WORKDIR /src From 022298064cd667dc1299f6c919b09098f33cf50d Mon Sep 17 00:00:00 2001 From: Eric Fritz Date: Mon, 18 Oct 2021 08:18:09 -0500 Subject: [PATCH 058/647] lsif upload: Update upload status link (#633) --- cmd/src/lsif_upload.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/src/lsif_upload.go b/cmd/src/lsif_upload.go index 982a0e84f2..b3467625fe 100644 --- a/cmd/src/lsif_upload.go +++ b/cmd/src/lsif_upload.go @@ -197,7 +197,7 @@ func makeLSIFUploadURL(uploadID int) (string, error) { } graphqlID := base64.URLEncoding.EncodeToString([]byte(fmt.Sprintf(`LSIFUpload:"%d"`, uploadID))) - url.Path = lsifUploadFlags.repo + "/-/settings/code-intelligence/lsif-uploads/" + graphqlID + url.Path = lsifUploadFlags.repo + "/-/code-intelligence/uploads/" + graphqlID url.User = nil return url.String(), nil } From 2383a1763d6fe71469ae242e31d9b27cc8f32efa Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Tue, 19 Oct 2021 12:05:44 +0200 Subject: [PATCH 059/647] Upgrade lib to latest version --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 8b74b738e0..ba7c4e3eab 100644 --- a/go.mod +++ b/go.mod @@ -21,7 +21,7 @@ require ( github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4 github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf - github.com/sourcegraph/sourcegraph/lib v0.0.0-20211011135305-1971ff7fa57e + github.com/sourcegraph/sourcegraph/lib v0.0.0-20211019100035-3927434f5fd9 github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect golang.org/x/net v0.0.0-20210614182718-04defd469f4e diff --git a/go.sum b/go.sum index 2d2a2701b7..7179759fd6 100644 --- a/go.sum +++ b/go.sum @@ -259,8 +259,8 @@ github.com/sourcegraph/go-diff v0.6.1 h1:hmA1LzxW0n1c3Q4YbrFgg4P99GSnebYa3x8gr0H github.com/sourcegraph/go-diff v0.6.1/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20211011135305-1971ff7fa57e h1:oteOieW7+0q8bp6OzWmeov303JY0QE+/p0+fV1T9NZw= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20211011135305-1971ff7fa57e/go.mod h1:9vLg5fQL9Q3iktfqu96OrswbOq7yqMesMJER9DCy8vk= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20211019100035-3927434f5fd9 h1:ENVNYjfyNlKP6wcbgsj+8ZKq6L8ZKAeTxGL3P7HfiQA= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20211019100035-3927434f5fd9/go.mod h1:9vLg5fQL9Q3iktfqu96OrswbOq7yqMesMJER9DCy8vk= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= From a780168bd45ed67a879617d6a2b09b1757582682 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Tue, 19 Oct 2021 12:10:51 +0200 Subject: [PATCH 060/647] Prepare changelog for 3.33 --- CHANGELOG.md | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f521252af..438bc0dbfd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,13 +19,19 @@ All notable changes to `src-cli` are documented in this file. ### Removed -## 3.31.2 +## 3.33.0 + +### Fixed + +- Importing changesets won't fail validation when uploading to Sourcegraph 3.33. + +## 3.32.1 ### Fixed - Fixes an issue where src-cli would panic when importing existing changesets. -## 3.31.1 +## 3.32.0 ### Added From 3a48ac72cbe0dc31a69400bd6a062f7104fde858 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Wed, 20 Oct 2021 01:40:09 +0200 Subject: [PATCH 061/647] Remove deprecated campaign and campaigns command aliases (#626) --- CHANGELOG.md | 1 + cmd/src/batch.go | 2 -- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 438bc0dbfd..e12acd04bb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -44,6 +44,7 @@ All notable changes to `src-cli` are documented in this file. ### Fixed - `src batch repos` failed with a template error in src-cli 3.31.1 and 3.32.0. This has been fixed. [#625](https://github.com/sourcegraph/src-cli/pull/625) +- The `src campaign` and `src campaigns` commands have been removed in favor of `src batch`. [#626](https://github.com/sourcegraph/src-cli/pull/626) ## 3.31.1 diff --git a/cmd/src/batch.go b/cmd/src/batch.go index 917dbce118..61dc7d148f 100644 --- a/cmd/src/batch.go +++ b/cmd/src/batch.go @@ -43,8 +43,6 @@ Use "src batch [command] -h" for more information about a command. "batchchanges", "batch-changes", "batches", - "campaign", - "campaigns", }, handler: handler, usageFunc: func() { fmt.Println(usage) }, From d28f5274025cea5408c4ff5a5350116c8c087ae2 Mon Sep 17 00:00:00 2001 From: Thorsten Ball Date: Fri, 22 Oct 2021 13:15:23 +0200 Subject: [PATCH 062/647] Fix nil-panic if repository has no default branch (#635) This is the fix for the issue reported in https://github.com/sourcegraph/customer/issues/537. The problem: 1. Sometimes repositories don't have a default branch, because they're being cloned or updated by Sourcegraph. See code here: https://sourcegraph.com/github.com/sourcegraph/sourcegraph@1cbb9023b0c77e6fa132298df1b2b5a768288d67/-/blob/internal/vcs/git/default_branch.go?L6 2. We skip the repositories with no repositories, *but too late*. With the introduction of `.batchignore` we added additional code that broke that check. --- CHANGELOG.md | 2 + internal/batches/service/service.go | 17 ++++--- internal/batches/service/service_test.go | 65 ++++++++++++++++++++++++ 3 files changed, 78 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e12acd04bb..29b2eb6107 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,8 @@ All notable changes to `src-cli` are documented in this file. ### Fixed +- Fixes a nil-panic that could be caused when `src batch [preview|apply]` would encounter a repository that was currently being cloned or is empty. + ### Removed ## 3.33.0 diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index cb2b43500c..324dde1d81 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -12,6 +12,7 @@ import ( "strings" "github.com/cockroachdb/errors" + batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/src-cli/internal/api" @@ -431,19 +432,23 @@ func (svc *Service) ResolveRepositories(ctx context.Context, spec *batcheslib.Ba return nil, errors.Wrapf(err, "resolving %q", on.String()) } + reposWithBranch := make([]*graphql.Repository, 0, len(repos)) + for _, repo := range repos { + if !repo.HasBranch() { + continue + } + reposWithBranch = append(reposWithBranch, repo) + } + var repoBatchIgnores map[*graphql.Repository][]string if !svc.allowIgnored { - repoBatchIgnores, err = svc.FindDirectoriesInRepos(ctx, ".batchignore", repos...) + repoBatchIgnores, err = svc.FindDirectoriesInRepos(ctx, ".batchignore", reposWithBranch...) if err != nil { return nil, err } } - for _, repo := range repos { - if !repo.HasBranch() { - continue - } - + for _, repo := range reposWithBranch { if other, ok := seen[repo.ID]; !ok { seen[repo.ID] = repo diff --git a/internal/batches/service/service_test.go b/internal/batches/service/service_test.go index 44d0cfb021..5aa98aedaa 100644 --- a/internal/batches/service/service_test.go +++ b/internal/batches/service/service_test.go @@ -10,6 +10,7 @@ import ( "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" + batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/src-cli/internal/api" @@ -322,6 +323,70 @@ const testBatchIgnoreInRepos = `{ } ` +func TestResolveRepositories_RepoWithoutBranch(t *testing.T) { + spec := &batcheslib.BatchSpec{ + On: []batcheslib.OnQueryOrRepository{ + {RepositoriesMatchingQuery: "testquery"}, + }, + } + + client, done := mockGraphQLClient(testResolveRepositoriesNoBranch, testBatchIgnoreInReposNoBranch) + defer done() + + svc := &Service{client: client, allowIgnored: false} + + repos, err := svc.ResolveRepositories(context.Background(), spec) + if err != nil { + t.Fatalf("unexpected error: %s", err) + } + if len(repos) != 1 { + t.Fatalf("wrong number of repos. want=%d, have=%d", 2, len(repos)) + } +} + +const testResolveRepositoriesNoBranch = `{ + "data": { + "search": { + "results": { + "results": [ + { + "__typename": "Repository", + "id": "UmVwb3NpdG9yeToxMw==", + "name": "bitbucket.sgdev.org/SOUR/automation-testing", + "url": "/https/github.com/bitbucket.sgdev.org/SOUR/automation-testing", + "externalRepository": { "serviceType": "bitbucketserver" }, + "defaultBranch": null + }, + { + "__typename": "Repository", + "id": "UmVwb3NpdG9yeTo0", + "name": "github.com/sourcegraph/automation-testing", + "url": "/https/github.com/github.com/sourcegraph/automation-testing", + "externalRepository": { "serviceType": "github" }, + "defaultBranch": null + }, + { + "__typename": "Repository", + "id": "UmVwb3NpdG9yeTo2MQ==", + "name": "gitlab.sgdev.org/sourcegraph/automation-testing", + "url": "/https/github.com/gitlab.sgdev.org/sourcegraph/automation-testing", + "externalRepository": { "serviceType": "gitlab" }, + "defaultBranch": { "name": "refs/heads/master", "target": { "oid": "3b79a5d479d2af9cfe91e0aad4e9dddca7278150" } } + } + ] + } + } + } +} +` + +const testBatchIgnoreInReposNoBranch = `{ + "data": { + "repo_0": { "results": { "results": [] } } + } +} +` + func TestService_FindDirectoriesInRepos(t *testing.T) { client, done := mockGraphQLClient(testFindDirectoriesInRepos) defer done() From 9a788b3750238ef81200181fa32d5c368cf85c83 Mon Sep 17 00:00:00 2001 From: Thorsten Ball Date: Fri, 22 Oct 2021 13:18:26 +0200 Subject: [PATCH 063/647] Prepare changelog for 3.33.1 --- CHANGELOG.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 29b2eb6107..a41834b613 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,10 +17,14 @@ All notable changes to `src-cli` are documented in this file. ### Fixed -- Fixes a nil-panic that could be caused when `src batch [preview|apply]` would encounter a repository that was currently being cloned or is empty. - ### Removed +## 3.33.1 + +### Fixed + +- Fixes a nil-panic that could be caused when `src batch [preview|apply]` would encounter a repository that was currently being cloned or is empty. + ## 3.33.0 ### Fixed From 8ea77d2b8e6f37a8988d6c398566f23ec9283f2e Mon Sep 17 00:00:00 2001 From: Thorsten Ball Date: Fri, 22 Oct 2021 14:52:16 +0200 Subject: [PATCH 064/647] Pin goreleaser to previous version v0.183 fails: https://github.com/sourcegraph/src-cli/runs/3975249231?check_suite_focus=true --- .github/workflows/goreleaser.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index b12e1d662f..123b5887d5 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -28,7 +28,7 @@ jobs: - name: Run GoReleaser uses: goreleaser/goreleaser-action@v2 with: - version: latest + version: v0.182.1 args: release --rm-dist env: # Use separate access token, because we need a scope:repo token to publish the brew formula. From bf3045c8a7666957aacea01b4ab1e6ceffda405c Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Fri, 22 Oct 2021 15:05:28 +0200 Subject: [PATCH 065/647] ssbc: Fix step index for command logs (#637) --- internal/batches/executor/run_steps.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/batches/executor/run_steps.go b/internal/batches/executor/run_steps.go index ab6bec2b7a..7c6997e7cb 100644 --- a/internal/batches/executor/run_steps.go +++ b/internal/batches/executor/run_steps.go @@ -335,7 +335,7 @@ func executeSingleStep( writerCtx, writerCancel := context.WithCancel(ctx) defer writerCancel() - outputWriter := opts.ui.StepOutputWriter(writerCtx, opts.task, i) + outputWriter := opts.ui.StepOutputWriter(writerCtx, opts.task, i+1) defer func() { outputWriter.Close() }() From a2841083b21e8ef0ded8b2ebb716bbfb305a9ff2 Mon Sep 17 00:00:00 2001 From: Thorsten Ball Date: Mon, 25 Oct 2021 16:06:06 +0200 Subject: [PATCH 066/647] Do not eval importChangesets in 'src batch exec' (#640) --- CHANGELOG.md | 2 + cmd/src/batch_common.go | 20 ++++--- cmd/src/batch_exec.go | 2 + internal/batches/executor/coordinator.go | 46 +++++++++------- internal/batches/executor/coordinator_test.go | 55 +++++++++++++++++++ 5 files changed, 97 insertions(+), 28 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a41834b613..976805e71d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,8 @@ All notable changes to `src-cli` are documented in this file. ### Changed +- For internal use only: `src batch exec` does not evaluate `importChangesets` in batch specs anymore, since that's already done server-side. + ### Fixed ### Removed diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index e6e49833e1..18c02acba9 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -15,6 +15,7 @@ import ( "github.com/cockroachdb/errors" "github.com/hashicorp/go-multierror" + batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/src-cli/internal/api" @@ -292,15 +293,16 @@ func executeBatchSpec(ctx context.Context, opts executeBatchSpecOpts) (err error // EXECUTION OF TASKS coord := svc.NewCoordinator(executor.NewCoordinatorOpts{ - Creator: workspaceCreator, - CacheDir: opts.flags.cacheDir, - ClearCache: opts.flags.clearCache, - SkipErrors: opts.flags.skipErrors, - CleanArchives: opts.flags.cleanArchives, - Parallelism: opts.flags.parallelism, - Timeout: opts.flags.timeout, - KeepLogs: opts.flags.keepLogs, - TempDir: opts.flags.tempDir, + Creator: workspaceCreator, + CacheDir: opts.flags.cacheDir, + ClearCache: opts.flags.clearCache, + SkipErrors: opts.flags.skipErrors, + CleanArchives: opts.flags.cleanArchives, + Parallelism: opts.flags.parallelism, + Timeout: opts.flags.timeout, + KeepLogs: opts.flags.keepLogs, + TempDir: opts.flags.tempDir, + ImportChangesets: true, }) opts.ui.CheckingCache() diff --git a/cmd/src/batch_exec.go b/cmd/src/batch_exec.go index a08d8be2aa..de45eac69d 100644 --- a/cmd/src/batch_exec.go +++ b/cmd/src/batch_exec.go @@ -157,6 +157,8 @@ func executeBatchSpecInWorkspaces(ctx context.Context, opts executeBatchSpecOpts Timeout: opts.flags.timeout, KeepLogs: opts.flags.keepLogs, TempDir: opts.flags.tempDir, + // Do not import changesets in `src batch exec` + ImportChangesets: false, }) opts.ui.CheckingCache() diff --git a/internal/batches/executor/coordinator.go b/internal/batches/executor/coordinator.go index 3a42b9bfab..1005321ec3 100644 --- a/internal/batches/executor/coordinator.go +++ b/internal/batches/executor/coordinator.go @@ -2,6 +2,7 @@ package executor import ( "context" + "fmt" "time" "github.com/cockroachdb/errors" @@ -55,6 +56,10 @@ type NewCoordinatorOpts struct { // Used by createChangesetSpecs Features batches.FeatureFlags + // When using `src batch exec` in SSBC we don't want to evaluate the + // `importChangesets`. + ImportChangesets bool + CleanArchives bool Parallelism int Timeout time.Duration @@ -246,28 +251,31 @@ func (c *Coordinator) Execute(ctx context.Context, tasks []*Task, spec *batchesl } // Add external changeset specs. - for _, ic := range spec.ImportChangesets { - repo, err := c.opts.ResolveRepoName(ctx, ic.Repository) - if err != nil { - wrapped := errors.Wrapf(err, "resolving repository name %q", ic.Repository) - if c.opts.SkipErrors { - errs = multierror.Append(errs, wrapped) - continue - } else { - return nil, nil, wrapped - } - } - - for _, id := range ic.ExternalIDs { - sid, err := batcheslib.ParseChangesetSpecExternalID(id) + if c.opts.ImportChangesets { + for _, ic := range spec.ImportChangesets { + fmt.Println("Horse!") + repo, err := c.opts.ResolveRepoName(ctx, ic.Repository) if err != nil { - return nil, nil, err + wrapped := errors.Wrapf(err, "resolving repository name %q", ic.Repository) + if c.opts.SkipErrors { + errs = multierror.Append(errs, wrapped) + continue + } else { + return nil, nil, wrapped + } } - specs = append(specs, &batcheslib.ChangesetSpec{ - BaseRepository: repo.ID, - ExternalID: sid, - }) + for _, id := range ic.ExternalIDs { + sid, err := batcheslib.ParseChangesetSpecExternalID(id) + if err != nil { + return nil, nil, err + } + + specs = append(specs, &batcheslib.ChangesetSpec{ + BaseRepository: repo.ID, + ExternalID: sid, + }) + } } } diff --git a/internal/batches/executor/coordinator_test.go b/internal/batches/executor/coordinator_test.go index c34d0c2edc..a986436dc7 100644 --- a/internal/batches/executor/coordinator_test.go +++ b/internal/batches/executor/coordinator_test.go @@ -9,6 +9,7 @@ import ( "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" + "github.com/sourcegraph/sourcegraph/lib/batches/overridable" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" @@ -348,6 +349,60 @@ func TestCoordinator_Execute(t *testing.T) { } } +func TestCoordinator_Execute_ImportChangesets(t *testing.T) { + + logManager := mock.LogNoOpManager{} + ui := newDummyTaskExecutionUI() + cache := newInMemoryExecutionCache() + + repoName := "github.com/testing/test-repo" + repoID := "graphql-id:999" + + repoNameResolver := func(ctx context.Context, name string) (*graphql.Repository, error) { + if name != repoName { + t.Fatalf("wrong repo name: %s", name) + } + return &graphql.Repository{ID: repoID, Name: repoName}, nil + } + + opts := NewCoordinatorOpts{Features: featuresAllEnabled(), ResolveRepoName: repoNameResolver} + + batchSpec := &batcheslib.BatchSpec{ + Name: "my-batch-change", + Description: "the description", + ChangesetTemplate: testChangesetTemplate, + ImportChangesets: []batcheslib.ImportChangeset{ + {Repository: repoName, ExternalIDs: []interface{}{500, 600, 700}}, + }, + } + + t.Run("importChangesets:true", func(t *testing.T) { + opts.ImportChangesets = true + coord := Coordinator{cache: cache, exec: &dummyExecutor{}, logManager: logManager, opts: opts} + + specs, _, err := coord.Execute(context.Background(), []*Task{}, batchSpec, ui) + if err != nil { + t.Fatalf("unexpected error: %s", err) + } + if len(specs) != len(batchSpec.ImportChangesets[0].ExternalIDs) { + t.Fatalf("wrong number of imported changesets: %d", len(specs)) + } + }) + + t.Run("importChangesets:false", func(t *testing.T) { + opts.ImportChangesets = false + coord := Coordinator{cache: cache, exec: &dummyExecutor{}, logManager: logManager, opts: opts} + + specs, _, err := coord.Execute(context.Background(), []*Task{}, batchSpec, ui) + if err != nil { + t.Fatalf("unexpected error: %s", err) + } + if len(specs) != 0 { + t.Fatalf("wrong number of imported changesets: %d", len(specs)) + } + }) +} + func TestCoordinator_Execute_StepCaching(t *testing.T) { // Setup dependencies cache := newInMemoryExecutionCache() From 6e5bd31e9f0649851dfb65641d9f4349831b61e0 Mon Sep 17 00:00:00 2001 From: Thorsten Ball Date: Mon, 25 Oct 2021 16:32:48 +0200 Subject: [PATCH 067/647] Update sourcegraph/lib/batches and use AllowFiles (#641) --- cmd/src/batch_common.go | 1 + cmd/src/batch_exec.go | 1 + go.mod | 2 +- go.sum | 5 ++--- internal/batches/service/service.go | 4 ++++ 5 files changed, 9 insertions(+), 4 deletions(-) diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index 18c02acba9..e21f0a91a2 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -211,6 +211,7 @@ func executeBatchSpec(ctx context.Context, opts executeBatchSpecOpts) (err error svc := service.New(&service.Opts{ AllowUnsupported: opts.flags.allowUnsupported, AllowIgnored: opts.flags.allowIgnored, + AllowFiles: true, Client: opts.client, }) diff --git a/cmd/src/batch_exec.go b/cmd/src/batch_exec.go index de45eac69d..996c48c9a3 100644 --- a/cmd/src/batch_exec.go +++ b/cmd/src/batch_exec.go @@ -85,6 +85,7 @@ func executeBatchSpecInWorkspaces(ctx context.Context, opts executeBatchSpecOpts svc := service.New(&service.Opts{ AllowUnsupported: opts.flags.allowUnsupported, AllowIgnored: opts.flags.allowIgnored, + AllowFiles: false, Client: opts.client, }) if err := svc.DetermineFeatureFlags(ctx); err != nil { diff --git a/go.mod b/go.mod index ba7c4e3eab..f990cfa9c7 100644 --- a/go.mod +++ b/go.mod @@ -21,7 +21,7 @@ require ( github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4 github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf - github.com/sourcegraph/sourcegraph/lib v0.0.0-20211019100035-3927434f5fd9 + github.com/sourcegraph/sourcegraph/lib v0.0.0-20211025134328-131865293af3 github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect golang.org/x/net v0.0.0-20210614182718-04defd469f4e diff --git a/go.sum b/go.sum index 7179759fd6..018ce2eb72 100644 --- a/go.sum +++ b/go.sum @@ -118,7 +118,6 @@ github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/google/uuid v1.2.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= @@ -259,8 +258,8 @@ github.com/sourcegraph/go-diff v0.6.1 h1:hmA1LzxW0n1c3Q4YbrFgg4P99GSnebYa3x8gr0H github.com/sourcegraph/go-diff v0.6.1/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20211019100035-3927434f5fd9 h1:ENVNYjfyNlKP6wcbgsj+8ZKq6L8ZKAeTxGL3P7HfiQA= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20211019100035-3927434f5fd9/go.mod h1:9vLg5fQL9Q3iktfqu96OrswbOq7yqMesMJER9DCy8vk= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20211025134328-131865293af3 h1:Ytf+X4TWH84t5RodqpIBUPS3VGzlHH9nnEaxh9/N2rI= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20211025134328-131865293af3/go.mod h1:lAHZIUiCW2kpj7f0YFFjdOq/Tv9OnnaBQNLoBcchuqQ= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index 324dde1d81..fa6fb99fe8 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -25,6 +25,7 @@ import ( type Service struct { allowUnsupported bool allowIgnored bool + allowFiles bool client api.Client features batches.FeatureFlags imageCache *docker.ImageCache @@ -33,6 +34,7 @@ type Service struct { type Opts struct { AllowUnsupported bool AllowIgnored bool + AllowFiles bool Client api.Client } @@ -44,6 +46,7 @@ func New(opts *Opts) *Service { return &Service{ allowUnsupported: opts.AllowUnsupported, allowIgnored: opts.AllowIgnored, + allowFiles: opts.AllowFiles, client: opts.Client, imageCache: docker.NewImageCache(), } @@ -275,6 +278,7 @@ func (svc *Service) ParseBatchSpec(data []byte) (*batcheslib.BatchSpec, error) { AllowArrayEnvironments: svc.features.AllowArrayEnvironments, AllowTransformChanges: svc.features.AllowTransformChanges, AllowConditionalExec: svc.features.AllowConditionalExec, + AllowFiles: svc.allowFiles, }) if err != nil { return nil, errors.Wrap(err, "parsing batch spec") From 2b79fac3017e4a5b87ab14eb4a65bca6d64557e2 Mon Sep 17 00:00:00 2001 From: Thorsten Ball Date: Mon, 25 Oct 2021 16:55:20 +0200 Subject: [PATCH 068/647] Prepare changelog for 3.33.2 --- CHANGELOG.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 976805e71d..9a99408f07 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,12 +15,16 @@ All notable changes to `src-cli` are documented in this file. ### Changed -- For internal use only: `src batch exec` does not evaluate `importChangesets` in batch specs anymore, since that's already done server-side. - ### Fixed ### Removed +## 3.33.2 + +### Changed + +- For internal use only: `src batch exec` does not evaluate `importChangesets` in batch specs anymore, since that's already done server-side. + ## 3.33.1 ### Fixed From c5f579a4d510d2f8e923648240c72a7601b462cd Mon Sep 17 00:00:00 2001 From: Thorsten Ball Date: Wed, 27 Oct 2021 11:11:12 +0200 Subject: [PATCH 069/647] Remove debug printing --- internal/batches/executor/coordinator.go | 2 -- 1 file changed, 2 deletions(-) diff --git a/internal/batches/executor/coordinator.go b/internal/batches/executor/coordinator.go index 1005321ec3..63742aa17a 100644 --- a/internal/batches/executor/coordinator.go +++ b/internal/batches/executor/coordinator.go @@ -2,7 +2,6 @@ package executor import ( "context" - "fmt" "time" "github.com/cockroachdb/errors" @@ -253,7 +252,6 @@ func (c *Coordinator) Execute(ctx context.Context, tasks []*Task, spec *batchesl // Add external changeset specs. if c.opts.ImportChangesets { for _, ic := range spec.ImportChangesets { - fmt.Println("Horse!") repo, err := c.opts.ResolveRepoName(ctx, ic.Repository) if err != nil { wrapped := errors.Wrapf(err, "resolving repository name %q", ic.Repository) From 828728b62837446848dc317f8c68d980af625470 Mon Sep 17 00:00:00 2001 From: Thorsten Ball Date: Wed, 27 Oct 2021 11:12:01 +0200 Subject: [PATCH 070/647] Prepare changelog for 3.33.3 --- CHANGELOG.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9a99408f07..8b7ff9d57c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,12 @@ All notable changes to `src-cli` are documented in this file. ### Removed +## 3.33.3 + +### Fixed + +- Removed debug output that could lead to glitches in the `src batch [preview|apply]` TUI. + ## 3.33.2 ### Changed From 9b19b5f963cd27032dd512d12e2fa465f7412522 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Wed, 27 Oct 2021 15:48:46 +0200 Subject: [PATCH 071/647] Always log changeset spec ids in JSON UI (#642) --- cmd/src/batch_exec.go | 20 ++++++++------------ 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/cmd/src/batch_exec.go b/cmd/src/batch_exec.go index 996c48c9a3..2694075ce9 100644 --- a/cmd/src/batch_exec.go +++ b/cmd/src/batch_exec.go @@ -189,20 +189,16 @@ func executeBatchSpecInWorkspaces(ctx context.Context, opts executeBatchSpecOpts ids := make([]graphql.ChangesetSpecID, len(specs)) - if len(specs) > 0 { - opts.ui.UploadingChangesetSpecs(len(specs)) - - for i, spec := range specs { - id, err := svc.CreateChangesetSpec(ctx, spec) - if err != nil { - return err - } - ids[i] = id - opts.ui.UploadingChangesetSpecsProgress(i+1, len(specs)) + opts.ui.UploadingChangesetSpecs(len(specs)) + for i, spec := range specs { + id, err := svc.CreateChangesetSpec(ctx, spec) + if err != nil { + return err } - - opts.ui.UploadingChangesetSpecsSuccess(ids) + ids[i] = id + opts.ui.UploadingChangesetSpecsProgress(i+1, len(specs)) } + opts.ui.UploadingChangesetSpecsSuccess(ids) return nil } From 2f27138286b982a0f328e91eaae69b90329cff17 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Wed, 27 Oct 2021 15:50:02 +0200 Subject: [PATCH 072/647] Prepare changelog for 3.33.4 --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8b7ff9d57c..88135127fd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,10 @@ All notable changes to `src-cli` are documented in this file. ### Removed +## 3.33.4 + +- For internal use only: always log uploading changesets event. + ## 3.33.3 ### Fixed From 0883252cab830b0f5fa3a741a5716287a8949ee7 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 1 Nov 2021 11:19:21 +0100 Subject: [PATCH 073/647] Update actions/checkout commit hash to 1e204e9 (#643) Co-authored-by: Renovate Bot --- .github/workflows/lsif.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/lsif.yml b/.github/workflows/lsif.yml index 9bc6d536b3..695b268a5c 100644 --- a/.github/workflows/lsif.yml +++ b/.github/workflows/lsif.yml @@ -6,7 +6,7 @@ jobs: runs-on: ubuntu-latest container: sourcegraph/lsif-go steps: - - uses: actions/checkout@5a4ac9002d0be2fb38bd78e4b4dbde5606d7042f # renovate: tag=v2 + - uses: actions/checkout@1e204e9a9253d643386038d443f96446fa156a97 # renovate: tag=v2 - name: Generate LSIF data run: lsif-go - name: Upload LSIF data From a8b2383706323195fc013cc6a60265c772469388 Mon Sep 17 00:00:00 2001 From: Thorsten Ball Date: Mon, 1 Nov 2021 13:22:42 +0100 Subject: [PATCH 074/647] search: check whether we can use "less" before trying to use it (#644) This should fix #554. --- CHANGELOG.md | 2 ++ cmd/src/search.go | 54 ++++++++++++++++++++++++++--------------------- 2 files changed, 32 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 88135127fd..c0e641a3d4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,8 @@ All notable changes to `src-cli` are documented in this file. ### Fixed +- `src search` will not fail anymore on systems where the pager `less` is not installed. [#644](https://github.com/sourcegraph/src-cli/pull/644) + ### Removed ## 3.33.4 diff --git a/cmd/src/search.go b/cmd/src/search.go index 7b0ec7a372..ced5cfa2bd 100644 --- a/cmd/src/search.go +++ b/cmd/src/search.go @@ -86,34 +86,40 @@ Other tips: queryString := flagSet.Arg(0) // For pagination, pipe our own output to 'less -R' - if *lessFlag && !*jsonFlag && isatty.IsTerminal(os.Stdout.Fd()) { - cmdPath, err := os.Executable() - if err != nil { - return err - } + if *lessFlag && !*jsonFlag { + // But first we check whether we can use `less`. (Instead of + // combining the conditions here into one, we use a 2nd conditional + // so we don't need to do `exec.LookPath` if flags disable `less`) + _, err := exec.LookPath("less") + if err == nil && isatty.IsTerminal(os.Stdout.Fd()) { + cmdPath, err := os.Executable() + if err != nil { + return err + } - srcCmd := exec.Command(cmdPath, append([]string{"search"}, args...)...) + srcCmd := exec.Command(cmdPath, append([]string{"search"}, args...)...) - // Because we do not want the default "no color when piping" behavior to take place. - srcCmd.Env = envSetDefault(os.Environ(), "COLOR", "t") + // Because we do not want the default "no color when piping" behavior to take place. + srcCmd.Env = envSetDefault(os.Environ(), "COLOR", "t") - srcStderr, err := srcCmd.StderrPipe() - if err != nil { - return err - } - srcStdout, err := srcCmd.StdoutPipe() - if err != nil { - return err - } - if err := srcCmd.Start(); err != nil { - return err - } + srcStderr, err := srcCmd.StderrPipe() + if err != nil { + return err + } + srcStdout, err := srcCmd.StdoutPipe() + if err != nil { + return err + } + if err := srcCmd.Start(); err != nil { + return err + } - lessCmd := exec.Command("less", "-R") - lessCmd.Stdin = io.MultiReader(srcStdout, srcStderr) - lessCmd.Stderr = os.Stderr - lessCmd.Stdout = os.Stdout - return lessCmd.Run() + lessCmd := exec.Command("less", "-R") + lessCmd.Stdin = io.MultiReader(srcStdout, srcStderr) + lessCmd.Stderr = os.Stderr + lessCmd.Stdout = os.Stdout + return lessCmd.Run() + } } client := cfg.apiClient(apiFlags, flagSet.Output()) From 287165d6482dcaa32877753f6be2d0be94e064d2 Mon Sep 17 00:00:00 2001 From: Thorsten Ball Date: Mon, 1 Nov 2021 13:29:42 +0100 Subject: [PATCH 075/647] Fix goreleaser config for 0.183 (hopefully) This implements the fix describes in this comment: https://github.com/sourcegraph/src-cli/issues/636#issuecomment-954214195 And it unpins the goreleaser version. --- .github/workflows/goreleaser.yml | 2 +- .goreleaser.yml | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index 123b5887d5..b12e1d662f 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -28,7 +28,7 @@ jobs: - name: Run GoReleaser uses: goreleaser/goreleaser-action@v2 with: - version: v0.182.1 + version: latest args: release --rm-dist env: # Use separate access token, because we need a scope:repo token to publish the brew formula. diff --git a/.goreleaser.yml b/.goreleaser.yml index 1ab1e8dc0c..4db476ce7d 100644 --- a/.goreleaser.yml +++ b/.goreleaser.yml @@ -42,6 +42,8 @@ brews: # `src-cli` install: | bin.install "src" + ids: + - tarball dockers: - dockerfile: Dockerfile.release image_templates: From 240d3b6f6fdb6eafdf0aa0775e74da57198136a7 Mon Sep 17 00:00:00 2001 From: Thorsten Ball Date: Mon, 1 Nov 2021 13:37:29 +0100 Subject: [PATCH 076/647] Prepare changelog for 3.33.5 --- CHANGELOG.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c0e641a3d4..ed62af46af 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,10 +17,14 @@ All notable changes to `src-cli` are documented in this file. ### Fixed -- `src search` will not fail anymore on systems where the pager `less` is not installed. [#644](https://github.com/sourcegraph/src-cli/pull/644) - ### Removed +## 3.33.5 + +### Fixed + +- `src search` will not fail anymore on systems where the pager `less` is not installed. [#644](https://github.com/sourcegraph/src-cli/pull/644) + ## 3.33.4 - For internal use only: always log uploading changesets event. From a54e098c643d8f02a0c79e19744523098b4f6b62 Mon Sep 17 00:00:00 2001 From: Adam Harvey Date: Tue, 2 Nov 2021 07:44:27 -0700 Subject: [PATCH 077/647] api: add User-Agent header (#645) --- CHANGELOG.md | 2 ++ README.markdown | 12 ++++++++++++ internal/api/api.go | 7 +++++++ internal/api/flags.go | 20 +++++++++++++++++++- 4 files changed, 40 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ed62af46af..55387f253f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,8 @@ All notable changes to `src-cli` are documented in this file. ### Added +- Requests to Sourcegraph will now include the operating system and architecture `src` is running on by default. To disable this, set the `SRC_DISABLE_USER_AGENT_TELEMETRY` environment variable to any non-empty string, or provide the `-user-agent-telemetry=false` flag on the command line. [#15769](https://github.com/sourcegraph/sourcegraph/issues/15769) + ### Changed ### Fixed diff --git a/README.markdown b/README.markdown index 0b5af8f8c0..6e37d47cdd 100644 --- a/README.markdown +++ b/README.markdown @@ -127,6 +127,18 @@ mv /usr/local/bin/src /usr/local/bin/src-cli You can then invoke it via `src-cli`. +## Telemetry + +`src` includes the operating system and architecture in the `User-Agent` header sent to Sourcegraph. For example, running `src` version 3.21.10 on an x86-64 Linux host will result in this header: + +``` +src-cli/3.21.10 linux amd64 +``` + +To disable this and _only_ send the version, you can set `-user-agent-telemetry=false` for a single command, or set the `SRC_DISABLE_USER_AGENT_TELEMETRY` environment variable to any non-blank string. + +As with [other Sourcegraph telemetry](https://docs.sourcegraph.com/dev/background-information/telemetry), any collected data is only sent to Sourcegraph.com in aggregate form. + ## Development Some useful notes on developing `src` can be found in [DEVELOPMENT.md](DEVELOPMENT.md). diff --git a/internal/api/api.go b/internal/api/api.go index 132b594ae4..eaa3a39de7 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -10,11 +10,13 @@ import ( "io" "net/http" "os" + "runtime" "strings" ioaux "github.com/jig/teereadcloser" "github.com/kballard/go-shellquote" "github.com/mattn/go-isatty" + "github.com/sourcegraph/src-cli/internal/version" ) // Client instances provide methods to create API requests. @@ -161,6 +163,11 @@ func (c *client) createHTTPRequest(ctx context.Context, method, p string, body i if err != nil { return nil, err } + if c.opts.Flags.UserAgentTelemetry() { + req.Header.Set("User-Agent", fmt.Sprintf("src-cli/%s %s %s", version.BuildTag, runtime.GOOS, runtime.GOARCH)) + } else { + req.Header.Set("User-Agent", "src-cli/"+version.BuildTag) + } if c.opts.AccessToken != "" { req.Header.Set("Authorization", "token "+c.opts.AccessToken) } diff --git a/internal/api/flags.go b/internal/api/flags.go index 4a02dab1cd..5a640da86d 100644 --- a/internal/api/flags.go +++ b/internal/api/flags.go @@ -1,6 +1,9 @@ package api -import "flag" +import ( + "flag" + "os" +) // Flags encapsulates the standard flags that should be added to all commands // that issue API requests. @@ -9,6 +12,7 @@ type Flags struct { getCurl *bool trace *bool insecureSkipVerify *bool + userAgentTelemetry *bool } func (f *Flags) Trace() bool { @@ -18,6 +22,13 @@ func (f *Flags) Trace() bool { return *(f.trace) } +func (f *Flags) UserAgentTelemetry() bool { + if f.userAgentTelemetry == nil { + return defaultUserAgentTelemetry() + } + return *(f.userAgentTelemetry) +} + // NewFlags instantiates a new Flags structure and attaches flags to the given // flag set. func NewFlags(flagSet *flag.FlagSet) *Flags { @@ -26,15 +37,22 @@ func NewFlags(flagSet *flag.FlagSet) *Flags { getCurl: flagSet.Bool("get-curl", false, "Print the curl command for executing this query and exit (WARNING: includes printing your access token!)"), trace: flagSet.Bool("trace", false, "Log the trace ID for requests. See https://docs.sourcegraph.com/admin/observability/tracing"), insecureSkipVerify: flagSet.Bool("insecure-skip-verify", false, "Skip validation of TLS certificates against trusted chains"), + userAgentTelemetry: flagSet.Bool("user-agent-telemetry", defaultUserAgentTelemetry(), "Include the operating system and architecture in the User-Agent sent with requests to Sourcegraph"), } } func defaultFlags() *Flags { + telemetry := defaultUserAgentTelemetry() d := false return &Flags{ dump: &d, getCurl: &d, trace: &d, insecureSkipVerify: &d, + userAgentTelemetry: &telemetry, } } + +func defaultUserAgentTelemetry() bool { + return os.Getenv("SRC_DISABLE_USER_AGENT_TELEMETRY") == "" +} From cfcc82f64d694225d743e68f9de26542cd200e7b Mon Sep 17 00:00:00 2001 From: Thorsten Ball Date: Thu, 4 Nov 2021 11:01:29 +0100 Subject: [PATCH 078/647] Use extracted batcheslib.BuildChangesetSpecs (#648) --- go.mod | 4 +- go.sum | 4 +- internal/batches/executor/changeset_specs.go | 240 ------------ .../batches/executor/changeset_specs_test.go | 367 ------------------ internal/batches/executor/coordinator.go | 37 +- internal/batches/executor/coordinator_test.go | 35 +- internal/batches/executor/execution_cache.go | 34 +- .../batches/executor/execution_cache_test.go | 8 +- internal/batches/executor/executor.go | 8 +- internal/batches/executor/executor_test.go | 10 +- internal/batches/executor/run_steps.go | 45 +-- internal/batches/executor/task.go | 5 +- internal/batches/graphql/repository.go | 15 +- 13 files changed, 113 insertions(+), 699 deletions(-) delete mode 100644 internal/batches/executor/changeset_specs.go delete mode 100644 internal/batches/executor/changeset_specs_test.go diff --git a/go.mod b/go.mod index f990cfa9c7..ad827cc69a 100644 --- a/go.mod +++ b/go.mod @@ -16,12 +16,11 @@ require ( github.com/json-iterator/go v1.1.11 github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 github.com/mattn/go-isatty v0.0.12 - github.com/mitchellh/copystructure v1.2.0 github.com/neelance/parallel v0.0.0-20160708114440-4de9ce63d14c github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4 github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf - github.com/sourcegraph/sourcegraph/lib v0.0.0-20211025134328-131865293af3 + github.com/sourcegraph/sourcegraph/lib v0.0.0-20211104093537-2b2516676fec github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect golang.org/x/net v0.0.0-20210614182718-04defd469f4e @@ -41,7 +40,6 @@ require ( github.com/kr/pretty v0.3.0 // indirect github.com/kr/text v0.2.0 // indirect github.com/mattn/go-runewidth v0.0.12 // indirect - github.com/mitchellh/reflectwalk v1.0.2 // indirect github.com/moby/term v0.0.0-20210619224110-3f7ff695adc6 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.1 // indirect diff --git a/go.sum b/go.sum index 018ce2eb72..8bb7c394bc 100644 --- a/go.sum +++ b/go.sum @@ -258,8 +258,8 @@ github.com/sourcegraph/go-diff v0.6.1 h1:hmA1LzxW0n1c3Q4YbrFgg4P99GSnebYa3x8gr0H github.com/sourcegraph/go-diff v0.6.1/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20211025134328-131865293af3 h1:Ytf+X4TWH84t5RodqpIBUPS3VGzlHH9nnEaxh9/N2rI= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20211025134328-131865293af3/go.mod h1:lAHZIUiCW2kpj7f0YFFjdOq/Tv9OnnaBQNLoBcchuqQ= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20211104093537-2b2516676fec h1:SvEo7YwpY2nRGGizAOWlvpitO3qM/NdyhVzR+mkD/a4= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20211104093537-2b2516676fec/go.mod h1:oriyPo0GiQg2oIAjaKAuaNwxiuSmscMVJGfV38ONvqQ= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= diff --git a/internal/batches/executor/changeset_specs.go b/internal/batches/executor/changeset_specs.go deleted file mode 100644 index 6178b48643..0000000000 --- a/internal/batches/executor/changeset_specs.go +++ /dev/null @@ -1,240 +0,0 @@ -package executor - -import ( - "fmt" - "strings" - - "github.com/cockroachdb/errors" - "github.com/sourcegraph/go-diff/diff" - batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" - "github.com/sourcegraph/sourcegraph/lib/batches/template" - - "github.com/sourcegraph/src-cli/internal/batches" - "github.com/sourcegraph/src-cli/internal/batches/util" -) - -var errOptionalPublishedUnsupported = batcheslib.NewValidationError(errors.New(`This Sourcegraph version requires the "published" field to be specified in the batch spec; upgrade to version 3.30.0 or later to be able to omit the published field and control publication from the UI.`)) - -func createChangesetSpecs(task *Task, result executionResult, features batches.FeatureFlags) ([]*batcheslib.ChangesetSpec, error) { - tmplCtx := &template.ChangesetTemplateContext{ - BatchChangeAttributes: *task.BatchChangeAttributes, - Steps: template.StepsContext{ - Changes: result.ChangedFiles, - Path: result.Path, - }, - Outputs: result.Outputs, - Repository: util.NewTemplatingRepo(task.Repository.Name, task.Repository.FileMatches), - } - - var authorName string - var authorEmail string - - if task.Template.Commit.Author == nil { - if features.IncludeAutoAuthorDetails { - // user did not provide author info, so use defaults - authorName = "Sourcegraph" - authorEmail = "batch-changes@sourcegraph.com" - } - } else { - var err error - authorName, err = template.RenderChangesetTemplateField("authorName", task.Template.Commit.Author.Name, tmplCtx) - if err != nil { - return nil, err - } - authorEmail, err = template.RenderChangesetTemplateField("authorEmail", task.Template.Commit.Author.Email, tmplCtx) - if err != nil { - return nil, err - } - } - - title, err := template.RenderChangesetTemplateField("title", task.Template.Title, tmplCtx) - if err != nil { - return nil, err - } - - body, err := template.RenderChangesetTemplateField("body", task.Template.Body, tmplCtx) - if err != nil { - return nil, err - } - - message, err := template.RenderChangesetTemplateField("message", task.Template.Commit.Message, tmplCtx) - if err != nil { - return nil, err - } - - // TODO: As a next step, we should extend the ChangesetTemplateContext to also include - // TransformChanges.Group and then change validateGroups and groupFileDiffs to, for each group, - // render the branch name *before* grouping the diffs. - defaultBranch, err := template.RenderChangesetTemplateField("branch", task.Template.Branch, tmplCtx) - if err != nil { - return nil, err - } - - newSpec := func(branch, diff string) (*batcheslib.ChangesetSpec, error) { - var published interface{} = nil - if task.Template.Published != nil { - published = task.Template.Published.ValueWithSuffix(task.Repository.Name, branch) - - // Backward compatibility: before optional published fields were - // allowed, ValueWithSuffix() would fall back to false, not nil. We - // need to replicate this behaviour here. - if published == nil && !features.AllowOptionalPublished { - published = false - } - } else if !features.AllowOptionalPublished { - return nil, errOptionalPublishedUnsupported - } - - return &batcheslib.ChangesetSpec{ - BaseRepository: task.Repository.ID, - - BaseRef: task.Repository.BaseRef(), - BaseRev: task.Repository.Rev(), - HeadRepository: task.Repository.ID, - HeadRef: util.EnsureRefPrefix(branch), - Title: title, - Body: body, - Commits: []batcheslib.GitCommitDescription{ - { - Message: message, - AuthorName: authorName, - AuthorEmail: authorEmail, - Diff: diff, - }, - }, - Published: batcheslib.PublishedValue{Val: published}, - }, nil - } - - var specs []*batcheslib.ChangesetSpec - - groups := groupsForRepository(task.Repository.Name, task.TransformChanges) - if len(groups) != 0 { - err := validateGroups(task.Repository.Name, task.Template.Branch, groups) - if err != nil { - return specs, err - } - - // TODO: Regarding 'defaultBranch', see comment above - diffsByBranch, err := groupFileDiffs(result.Diff, defaultBranch, groups) - if err != nil { - return specs, errors.Wrap(err, "grouping diffs failed") - } - - for branch, diff := range diffsByBranch { - spec, err := newSpec(branch, diff) - if err != nil { - return nil, err - } - specs = append(specs, spec) - } - } else { - spec, err := newSpec(defaultBranch, result.Diff) - if err != nil { - return nil, err - } - specs = append(specs, spec) - } - - return specs, nil -} - -func groupsForRepository(repoName string, transform *batcheslib.TransformChanges) []batcheslib.Group { - groups := []batcheslib.Group{} - - if transform == nil { - return groups - } - - for _, g := range transform.Group { - if g.Repository != "" { - if g.Repository == repoName { - groups = append(groups, g) - } - } else { - groups = append(groups, g) - } - } - - return groups -} - -func validateGroups(repoName, defaultBranch string, groups []batcheslib.Group) error { - uniqueBranches := make(map[string]struct{}, len(groups)) - - for _, g := range groups { - if _, ok := uniqueBranches[g.Branch]; ok { - return batcheslib.NewValidationError(fmt.Errorf("transformChanges would lead to multiple changesets in repository %s to have the same branch %q", repoName, g.Branch)) - } else { - uniqueBranches[g.Branch] = struct{}{} - } - - if g.Branch == defaultBranch { - return batcheslib.NewValidationError(fmt.Errorf("transformChanges group branch for repository %s is the same as branch %q in changesetTemplate", repoName, defaultBranch)) - } - } - - return nil -} - -func groupFileDiffs(completeDiff, defaultBranch string, groups []batcheslib.Group) (map[string]string, error) { - fileDiffs, err := diff.ParseMultiFileDiff([]byte(completeDiff)) - if err != nil { - return nil, err - } - - // Housekeeping: we setup these two datastructures so we can - // - access the group.Branch by the directory for which they should be used - // - check against the given directories, in order. - branchesByDirectory := make(map[string]string, len(groups)) - dirs := make([]string, len(branchesByDirectory)) - for _, g := range groups { - branchesByDirectory[g.Directory] = g.Branch - dirs = append(dirs, g.Directory) - } - - byBranch := make(map[string][]*diff.FileDiff, len(groups)) - byBranch[defaultBranch] = []*diff.FileDiff{} - - // For each file diff... - for _, f := range fileDiffs { - name := f.NewName - if name == "/dev/null" { - name = f.OrigName - } - - // .. we check whether it matches one of the given directories in the - // group transformations, with the last match winning: - var matchingDir string - for _, d := range dirs { - if strings.Contains(name, d) { - matchingDir = d - } - } - - // If the diff didn't match a rule, it goes into the default branch and - // the default changeset. - if matchingDir == "" { - byBranch[defaultBranch] = append(byBranch[defaultBranch], f) - continue - } - - // If it *did* match a directory, we look up which branch we should use: - branch, ok := branchesByDirectory[matchingDir] - if !ok { - panic("this should not happen: " + matchingDir) - } - - byBranch[branch] = append(byBranch[branch], f) - } - - finalDiffsByBranch := make(map[string]string, len(byBranch)) - for branch, diffs := range byBranch { - printed, err := diff.PrintMultiFileDiff(diffs) - if err != nil { - return nil, errors.Wrap(err, "printing multi file diff failed") - } - finalDiffsByBranch[branch] = string(printed) - } - return finalDiffsByBranch, nil -} diff --git a/internal/batches/executor/changeset_specs_test.go b/internal/batches/executor/changeset_specs_test.go deleted file mode 100644 index 7eecbcd4fd..0000000000 --- a/internal/batches/executor/changeset_specs_test.go +++ /dev/null @@ -1,367 +0,0 @@ -package executor - -import ( - "encoding/json" - "testing" - - "github.com/google/go-cmp/cmp" - "github.com/mitchellh/copystructure" - batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" - "github.com/sourcegraph/sourcegraph/lib/batches/git" - "github.com/sourcegraph/sourcegraph/lib/batches/overridable" - "github.com/sourcegraph/sourcegraph/lib/batches/template" - - "github.com/sourcegraph/src-cli/internal/batches" -) - -func TestCreateChangesetSpecs(t *testing.T) { - defaultChangesetSpec := &batcheslib.ChangesetSpec{ - BaseRepository: testRepo1.ID, - - BaseRef: testRepo1.BaseRef(), - BaseRev: testRepo1.Rev(), - HeadRepository: testRepo1.ID, - HeadRef: "refs/heads/my-branch", - Title: "The title", - Body: "The body", - Commits: []batcheslib.GitCommitDescription{ - { - Message: "git commit message", - Diff: "cool diff", - AuthorName: "Sourcegraph", - AuthorEmail: "batch-changes@sourcegraph.com", - }, - }, - Published: batcheslib.PublishedValue{Val: false}, - } - - specWith := func(s *batcheslib.ChangesetSpec, f func(s *batcheslib.ChangesetSpec)) *batcheslib.ChangesetSpec { - copy, err := copystructure.Copy(s) - if err != nil { - t.Fatalf("deep copying spec: %+v", err) - } - - s = copy.(*batcheslib.ChangesetSpec) - f(s) - return s - } - - defaultTask := &Task{ - BatchChangeAttributes: &template.BatchChangeAttributes{ - Name: "the name", - Description: "The description", - }, - Template: &batcheslib.ChangesetTemplate{ - Title: "The title", - Body: "The body", - Branch: "my-branch", - Commit: batcheslib.ExpandedGitCommitDescription{ - Message: "git commit message", - }, - Published: parsePublishedFieldString(t, "false"), - }, - Repository: testRepo1, - } - - taskWith := func(task *Task, f func(task *Task)) *Task { - copy, err := copystructure.Copy(task) - if err != nil { - t.Fatalf("deep copying task: %+v", err) - } - - task = copy.(*Task) - f(task) - return task - } - - defaultResult := executionResult{ - Diff: "cool diff", - ChangedFiles: &git.Changes{ - Modified: []string{"README.md"}, - }, - Outputs: map[string]interface{}{}, - } - - featuresWithoutOptionalPublished := featuresAllEnabled() - featuresWithoutOptionalPublished.AllowOptionalPublished = false - - tests := []struct { - name string - task *Task - features batches.FeatureFlags - result executionResult - - want []*batcheslib.ChangesetSpec - wantErr string - }{ - { - name: "success", - task: defaultTask, - features: featuresAllEnabled(), - result: defaultResult, - want: []*batcheslib.ChangesetSpec{ - defaultChangesetSpec, - }, - wantErr: "", - }, - { - name: "publish by branch", - task: taskWith(defaultTask, func(task *Task) { - published := `[{"github.com/sourcegraph/*@my-branch": true}]` - task.Template.Published = parsePublishedFieldString(t, published) - }), - features: featuresAllEnabled(), - result: defaultResult, - want: []*batcheslib.ChangesetSpec{ - specWith(defaultChangesetSpec, func(s *batcheslib.ChangesetSpec) { - s.Published = batcheslib.PublishedValue{Val: true} - }), - }, - wantErr: "", - }, - { - name: "publish by branch not matching", - task: taskWith(defaultTask, func(task *Task) { - published := `[{"github.com/sourcegraph/*@another-branch-name": true}]` - task.Template.Published = parsePublishedFieldString(t, published) - }), - features: featuresAllEnabled(), - result: defaultResult, - want: []*batcheslib.ChangesetSpec{ - specWith(defaultChangesetSpec, func(s *batcheslib.ChangesetSpec) { - s.Published = batcheslib.PublishedValue{Val: nil} - }), - }, - wantErr: "", - }, - { - name: "publish by branch not matching on an old Sourcegraph version", - task: taskWith(defaultTask, func(task *Task) { - published := `[{"github.com/sourcegraph/*@another-branch-name": true}]` - task.Template.Published = parsePublishedFieldString(t, published) - }), - features: featuresWithoutOptionalPublished, - result: defaultResult, - want: []*batcheslib.ChangesetSpec{ - specWith(defaultChangesetSpec, func(s *batcheslib.ChangesetSpec) { - s.Published = batcheslib.PublishedValue{Val: false} - }), - }, - wantErr: "", - }, - { - name: "publish in UI on a supported version", - task: taskWith(defaultTask, func(task *Task) { - task.Template.Published = nil - }), - features: featuresAllEnabled(), - result: defaultResult, - want: []*batcheslib.ChangesetSpec{ - specWith(defaultChangesetSpec, func(s *batcheslib.ChangesetSpec) { - s.Published = batcheslib.PublishedValue{Val: nil} - }), - }, - wantErr: "", - }, - { - name: "publish in UI on an unsupported version", - task: taskWith(defaultTask, func(task *Task) { - task.Template.Published = nil - }), - features: featuresWithoutOptionalPublished, - result: defaultResult, - want: nil, - wantErr: errOptionalPublishedUnsupported.Error(), - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - have, err := createChangesetSpecs(tt.task, tt.result, tt.features) - if err != nil { - if tt.wantErr != "" { - if err.Error() != tt.wantErr { - t.Fatalf("wrong error. want=%q, got=%q", tt.wantErr, err.Error()) - } - return - } else { - t.Fatalf("unexpected error: %s", err) - } - } - - if !cmp.Equal(tt.want, have) { - t.Errorf("mismatch (-want +got):\n%s", cmp.Diff(tt.want, have)) - } - }) - } -} - -func TestGroupFileDiffs(t *testing.T) { - diff1 := `diff --git 1/1.txt 1/1.txt -new file mode 100644 -index 0000000..19d6416 ---- /dev/null -+++ 1/1.txt -@@ -0,0 +1,1 @@ -+this is 1 -` - diff2 := `diff --git 1/2/2.txt 1/2/2.txt -new file mode 100644 -index 0000000..c825d65 ---- /dev/null -+++ 1/2/2.txt -@@ -0,0 +1,1 @@ -+this is 2 -` - diff3 := `diff --git 1/2/3/3.txt 1/2/3/3.txt -new file mode 100644 -index 0000000..1bd79fb ---- /dev/null -+++ 1/2/3/3.txt -@@ -0,0 +1,1 @@ -+this is 3 -` - - defaultBranch := "my-default-branch" - allDiffs := diff1 + diff2 + diff3 - - tests := []struct { - diff string - defaultBranch string - groups []batcheslib.Group - want map[string]string - }{ - { - diff: allDiffs, - groups: []batcheslib.Group{ - {Directory: "1/2/3", Branch: "everything-in-3"}, - }, - want: map[string]string{ - "my-default-branch": diff1 + diff2, - "everything-in-3": diff3, - }, - }, - { - diff: allDiffs, - groups: []batcheslib.Group{ - {Directory: "1/2", Branch: "everything-in-2-and-3"}, - }, - want: map[string]string{ - "my-default-branch": diff1, - "everything-in-2-and-3": diff2 + diff3, - }, - }, - { - diff: allDiffs, - groups: []batcheslib.Group{ - {Directory: "1", Branch: "everything-in-1-and-2-and-3"}, - }, - want: map[string]string{ - "my-default-branch": "", - "everything-in-1-and-2-and-3": diff1 + diff2 + diff3, - }, - }, - { - diff: allDiffs, - groups: []batcheslib.Group{ - // Each diff is matched against each directory, last match wins - {Directory: "1", Branch: "only-in-1"}, - {Directory: "1/2", Branch: "only-in-2"}, - {Directory: "1/2/3", Branch: "only-in-3"}, - }, - want: map[string]string{ - "my-default-branch": "", - "only-in-3": diff3, - "only-in-2": diff2, - "only-in-1": diff1, - }, - }, - { - diff: allDiffs, - groups: []batcheslib.Group{ - // Last one wins here, because it matches every diff - {Directory: "1/2/3", Branch: "only-in-3"}, - {Directory: "1/2", Branch: "only-in-2"}, - {Directory: "1", Branch: "only-in-1"}, - }, - want: map[string]string{ - "my-default-branch": "", - "only-in-1": diff1 + diff2 + diff3, - }, - }, - { - diff: allDiffs, - groups: []batcheslib.Group{ - {Directory: "", Branch: "everything"}, - }, - want: map[string]string{ - "my-default-branch": diff1 + diff2 + diff3, - }, - }, - } - - for _, tc := range tests { - have, err := groupFileDiffs(tc.diff, defaultBranch, tc.groups) - if err != nil { - t.Fatalf("unexpected error: %s", err) - } - if !cmp.Equal(tc.want, have) { - t.Errorf("mismatch (-want +got):\n%s", cmp.Diff(tc.want, have)) - } - } -} - -func TestValidateGroups(t *testing.T) { - repoName := "github.com/sourcegraph/src-cli" - defaultBranch := "my-batch-change" - - tests := []struct { - defaultBranch string - groups []batcheslib.Group - wantErr string - }{ - { - groups: []batcheslib.Group{ - {Directory: "a", Branch: "my-batch-change-a"}, - {Directory: "b", Branch: "my-batch-change-b"}, - }, - wantErr: "", - }, - { - groups: []batcheslib.Group{ - {Directory: "a", Branch: "my-batch-change-SAME"}, - {Directory: "b", Branch: "my-batch-change-SAME"}, - }, - wantErr: "transformChanges would lead to multiple changesets in repository github.com/sourcegraph/src-cli to have the same branch \"my-batch-change-SAME\"", - }, - { - groups: []batcheslib.Group{ - {Directory: "a", Branch: "my-batch-change-SAME"}, - {Directory: "b", Branch: defaultBranch}, - }, - wantErr: "transformChanges group branch for repository github.com/sourcegraph/src-cli is the same as branch \"my-batch-change\" in changesetTemplate", - }, - } - - for _, tc := range tests { - err := validateGroups(repoName, defaultBranch, tc.groups) - var haveErr string - if err != nil { - haveErr = err.Error() - } - - if haveErr != tc.wantErr { - t.Fatalf("wrong error:\nwant=%q\nhave=%q", tc.wantErr, haveErr) - } - } -} - -func parsePublishedFieldString(t *testing.T, input string) *overridable.BoolOrString { - t.Helper() - - var result overridable.BoolOrString - if err := json.Unmarshal([]byte(input), &result); err != nil { - t.Fatalf("failed to parse %q as overridable.BoolOrString: %s", input, err) - } - return &result -} diff --git a/internal/batches/executor/coordinator.go b/internal/batches/executor/coordinator.go index 63742aa17a..45603fe906 100644 --- a/internal/batches/executor/coordinator.go +++ b/internal/batches/executor/coordinator.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/go-multierror" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" + "github.com/sourcegraph/sourcegraph/lib/batches/execution" "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/batches" @@ -52,7 +53,7 @@ type NewCoordinatorOpts struct { ClearCache bool SkipErrors bool - // Used by createChangesetSpecs + // Used by batcheslib.BuildChangesetSpecs Features batches.FeatureFlags // When using `src batch exec` in SSBC we don't want to evaluate the @@ -122,7 +123,7 @@ func (c *Coordinator) checkCacheForTask(ctx context.Context, task *Task) (specs return specs, false, nil } - var result executionResult + var result execution.Result result, found, err = c.cache.Get(ctx, cacheKey) if err != nil { return specs, false, errors.Wrapf(err, "checking cache for %q", task.Repository.Name) @@ -140,7 +141,7 @@ func (c *Coordinator) checkCacheForTask(ctx context.Context, task *Task) (specs return specs, true, nil } - specs, err = createChangesetSpecs(task, result, c.opts.Features) + specs, err = c.buildChangesetSpecs(task, result) if err != nil { return specs, false, err } @@ -148,6 +149,34 @@ func (c *Coordinator) checkCacheForTask(ctx context.Context, task *Task) (specs return specs, true, nil } +func (c Coordinator) buildChangesetSpecs(task *Task, result execution.Result) ([]*batcheslib.ChangesetSpec, error) { + input := &batcheslib.ChangesetSpecInput{ + BaseRepositoryID: task.Repository.ID, + HeadRepositoryID: task.Repository.ID, + Repository: batcheslib.ChangesetSpecRepository{ + Name: task.Repository.Name, + FileMatches: task.Repository.SortedFileMatches(), + BaseRef: task.Repository.BaseRef(), + BaseRev: task.Repository.Rev(), + }, + BatchChangeAttributes: task.BatchChangeAttributes, + Template: task.Template, + TransformChanges: task.TransformChanges, + + Result: execution.Result{ + Diff: result.Diff, + ChangedFiles: result.ChangedFiles, + Outputs: result.Outputs, + Path: result.Path, + }, + } + + return batcheslib.BuildChangesetSpecs(input, batcheslib.ChangesetSpecFeatureFlags{ + IncludeAutoAuthorDetails: c.opts.Features.IncludeAutoAuthorDetails, + AllowOptionalPublished: c.opts.Features.AllowOptionalPublished, + }) +} + func (c *Coordinator) setCachedStepResults(ctx context.Context, task *Task) error { // We start at the back so that we can find the _last_ cached step, // then restart execution on the following step. @@ -200,7 +229,7 @@ func (c *Coordinator) cacheAndBuildSpec(ctx context.Context, taskResult taskResu } // Build the changeset specs. - specs, err := createChangesetSpecs(taskResult.task, taskResult.result, c.opts.Features) + specs, err := c.buildChangesetSpecs(taskResult.task, taskResult.result) if err != nil { return nil, err } diff --git a/internal/batches/executor/coordinator_test.go b/internal/batches/executor/coordinator_test.go index a986436dc7..f000bcb81b 100644 --- a/internal/batches/executor/coordinator_test.go +++ b/internal/batches/executor/coordinator_test.go @@ -10,6 +10,7 @@ import ( "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" + "github.com/sourcegraph/sourcegraph/lib/batches/execution" "github.com/sourcegraph/sourcegraph/lib/batches/overridable" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" @@ -77,8 +78,8 @@ func TestCoordinator_Execute(t *testing.T) { executor: &dummyExecutor{ results: []taskResult{ - {task: srcCLITask, result: executionResult{Diff: `dummydiff1`}}, - {task: sourcegraphTask, result: executionResult{Diff: `dummydiff2`}}, + {task: srcCLITask, result: execution.Result{Diff: `dummydiff1`}}, + {task: sourcegraphTask, result: execution.Result{Diff: `dummydiff2`}}, }, }, opts: NewCoordinatorOpts{Features: featuresAllEnabled()}, @@ -131,7 +132,7 @@ func TestCoordinator_Execute(t *testing.T) { results: []taskResult{ { task: srcCLITask, - result: executionResult{ + result: execution.Result{ Diff: `dummydiff1`, Outputs: map[string]interface{}{ "output1": "myOutputValue1", @@ -196,8 +197,8 @@ func TestCoordinator_Execute(t *testing.T) { executor: &dummyExecutor{ results: []taskResult{ - {task: srcCLITask, result: executionResult{Diff: nestedChangesDiff}}, - {task: sourcegraphTask, result: executionResult{Diff: nestedChangesDiff}}, + {task: srcCLITask, result: execution.Result{Diff: nestedChangesDiff}}, + {task: sourcegraphTask, result: execution.Result{Diff: nestedChangesDiff}}, }, }, opts: NewCoordinatorOpts{Features: featuresAllEnabled()}, @@ -239,7 +240,7 @@ func TestCoordinator_Execute(t *testing.T) { // Execution succeeded in srcCLIRepo, but fails in sourcegraphRepo executor: &dummyExecutor{ results: []taskResult{ - {task: srcCLITask, result: executionResult{Diff: `dummydiff1`}}, + {task: srcCLITask, result: execution.Result{Diff: `dummydiff1`}}, }, waitErr: stepFailedErr{ Err: fmt.Errorf("something went wrong"), @@ -421,13 +422,13 @@ func TestCoordinator_Execute_StepCaching(t *testing.T) { executor := &dummyExecutor{} executor.results = []taskResult{{ task: task, - result: executionResult{ + result: execution.Result{ Diff: "dummydiff", ChangedFiles: &git.Changes{}, Outputs: map[string]interface{}{}, Path: "", }, - stepResults: []stepExecutionResult{ + stepResults: []execution.AfterStepResult{ {StepIndex: 0, Diff: []byte(`step-0-diff`)}, {StepIndex: 1, Diff: []byte(`step-1-diff`)}, {StepIndex: 2, Diff: []byte(`step-2-diff`)}, @@ -649,7 +650,7 @@ func (c *inMemoryExecutionCache) size() int { func (c *inMemoryExecutionCache) getCacheItem(key CacheKeyer) (interface{}, bool, error) { k, err := key.Key() if err != nil { - return executionResult{}, false, err + return execution.Result{}, false, err } c.mu.RLock() @@ -659,17 +660,17 @@ func (c *inMemoryExecutionCache) getCacheItem(key CacheKeyer) (interface{}, bool return res, ok, nil } -func (c *inMemoryExecutionCache) Get(ctx context.Context, key CacheKeyer) (executionResult, bool, error) { +func (c *inMemoryExecutionCache) Get(ctx context.Context, key CacheKeyer) (execution.Result, bool, error) { res, ok, err := c.getCacheItem(key) if err != nil || !ok { - return executionResult{}, ok, err + return execution.Result{}, ok, err } - execResult, ok := res.(executionResult) + execResult, ok := res.(execution.Result) return execResult, ok, nil } -func (c *inMemoryExecutionCache) Set(ctx context.Context, key CacheKeyer, result executionResult) error { +func (c *inMemoryExecutionCache) Set(ctx context.Context, key CacheKeyer, result execution.Result) error { k, err := key.Key() if err != nil { return err @@ -682,17 +683,17 @@ func (c *inMemoryExecutionCache) Set(ctx context.Context, key CacheKeyer, result return nil } -func (c *inMemoryExecutionCache) GetStepResult(ctx context.Context, key CacheKeyer) (stepExecutionResult, bool, error) { +func (c *inMemoryExecutionCache) GetStepResult(ctx context.Context, key CacheKeyer) (execution.AfterStepResult, bool, error) { res, ok, err := c.getCacheItem(key) if err != nil || !ok { - return stepExecutionResult{}, ok, err + return execution.AfterStepResult{}, ok, err } - execResult, ok := res.(stepExecutionResult) + execResult, ok := res.(execution.AfterStepResult) return execResult, ok, nil } -func (c *inMemoryExecutionCache) SetStepResult(ctx context.Context, key CacheKeyer, result stepExecutionResult) error { +func (c *inMemoryExecutionCache) SetStepResult(ctx context.Context, key CacheKeyer, result execution.AfterStepResult) error { k, err := key.Key() if err != nil { return err diff --git a/internal/batches/executor/execution_cache.go b/internal/batches/executor/execution_cache.go index dd9182a8d4..99a6ca49a1 100644 --- a/internal/batches/executor/execution_cache.go +++ b/internal/batches/executor/execution_cache.go @@ -10,7 +10,9 @@ import ( "path/filepath" "github.com/cockroachdb/errors" + batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" + "github.com/sourcegraph/sourcegraph/lib/batches/execution" "github.com/sourcegraph/src-cli/internal/batches/util" ) @@ -141,11 +143,11 @@ func (key TaskCacheKey) Slug() string { } type ExecutionCache interface { - Get(ctx context.Context, key CacheKeyer) (result executionResult, found bool, err error) - Set(ctx context.Context, key CacheKeyer, result executionResult) error + Get(ctx context.Context, key CacheKeyer) (result execution.Result, found bool, err error) + Set(ctx context.Context, key CacheKeyer, result execution.Result) error - GetStepResult(ctx context.Context, key CacheKeyer) (result stepExecutionResult, found bool, err error) - SetStepResult(ctx context.Context, key CacheKeyer, result stepExecutionResult) error + GetStepResult(ctx context.Context, key CacheKeyer) (result execution.AfterStepResult, found bool, err error) + SetStepResult(ctx context.Context, key CacheKeyer, result execution.AfterStepResult) error Clear(ctx context.Context, key CacheKeyer) error } @@ -173,8 +175,8 @@ func (c ExecutionDiskCache) cacheFilePath(key CacheKeyer) (string, error) { return filepath.Join(c.Dir, key.Slug(), keyString+cacheFileExt), nil } -func (c ExecutionDiskCache) Get(ctx context.Context, key CacheKeyer) (executionResult, bool, error) { - var result executionResult +func (c ExecutionDiskCache) Get(ctx context.Context, key CacheKeyer) (execution.Result, bool, error) { + var result execution.Result path, err := c.cacheFilePath(key) if err != nil { @@ -220,7 +222,7 @@ func (c ExecutionDiskCache) writeCacheFile(path string, result interface{}) erro return os.WriteFile(path, raw, 0600) } -func (c ExecutionDiskCache) Set(ctx context.Context, key CacheKeyer, result executionResult) error { +func (c ExecutionDiskCache) Set(ctx context.Context, key CacheKeyer, result execution.Result) error { path, err := c.cacheFilePath(key) if err != nil { return err @@ -242,8 +244,8 @@ func (c ExecutionDiskCache) Clear(ctx context.Context, key CacheKeyer) error { return os.Remove(path) } -func (c ExecutionDiskCache) GetStepResult(ctx context.Context, key CacheKeyer) (stepExecutionResult, bool, error) { - var result stepExecutionResult +func (c ExecutionDiskCache) GetStepResult(ctx context.Context, key CacheKeyer) (execution.AfterStepResult, bool, error) { + var result execution.AfterStepResult path, err := c.cacheFilePath(key) if err != nil { return result, false, err @@ -257,7 +259,7 @@ func (c ExecutionDiskCache) GetStepResult(ctx context.Context, key CacheKeyer) ( return result, found, nil } -func (c ExecutionDiskCache) SetStepResult(ctx context.Context, key CacheKeyer, result stepExecutionResult) error { +func (c ExecutionDiskCache) SetStepResult(ctx context.Context, key CacheKeyer, result execution.AfterStepResult) error { path, err := c.cacheFilePath(key) if err != nil { return err @@ -270,11 +272,11 @@ func (c ExecutionDiskCache) SetStepResult(ctx context.Context, key CacheKeyer, r // retrieve cache entries. type ExecutionNoOpCache struct{} -func (ExecutionNoOpCache) Get(ctx context.Context, key CacheKeyer) (result executionResult, found bool, err error) { - return executionResult{}, false, nil +func (ExecutionNoOpCache) Get(ctx context.Context, key CacheKeyer) (result execution.Result, found bool, err error) { + return execution.Result{}, false, nil } -func (ExecutionNoOpCache) Set(ctx context.Context, key CacheKeyer, result executionResult) error { +func (ExecutionNoOpCache) Set(ctx context.Context, key CacheKeyer, result execution.Result) error { return nil } @@ -282,10 +284,10 @@ func (ExecutionNoOpCache) Clear(ctx context.Context, key CacheKeyer) error { return nil } -func (ExecutionNoOpCache) SetStepResult(ctx context.Context, key CacheKeyer, result stepExecutionResult) error { +func (ExecutionNoOpCache) SetStepResult(ctx context.Context, key CacheKeyer, result execution.AfterStepResult) error { return nil } -func (ExecutionNoOpCache) GetStepResult(ctx context.Context, key CacheKeyer) (stepExecutionResult, bool, error) { - return stepExecutionResult{}, false, nil +func (ExecutionNoOpCache) GetStepResult(ctx context.Context, key CacheKeyer) (execution.AfterStepResult, bool, error) { + return execution.AfterStepResult{}, false, nil } diff --git a/internal/batches/executor/execution_cache_test.go b/internal/batches/executor/execution_cache_test.go index d2bc18de0c..6bf0de5ea6 100644 --- a/internal/batches/executor/execution_cache_test.go +++ b/internal/batches/executor/execution_cache_test.go @@ -6,9 +6,11 @@ import ( "testing" "github.com/google/go-cmp/cmp" + "gopkg.in/yaml.v3" + batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" + "github.com/sourcegraph/sourcegraph/lib/batches/execution" "github.com/sourcegraph/sourcegraph/lib/batches/git" - "gopkg.in/yaml.v3" ) const testExecutionCacheKeyEnv = "TEST_EXECUTION_CACHE_KEY_ENV" @@ -132,7 +134,7 @@ func TestExecutionDiskCache_GetSet(t *testing.T) { }, }} - value := executionResult{ + value := execution.Result{ Diff: testDiff, ChangedFiles: &git.Changes{ Added: []string{"README.md"}, @@ -164,7 +166,7 @@ func TestExecutionDiskCache_GetSet(t *testing.T) { assertCacheMiss(t, cache, cacheKey1) } -func assertCacheHit(t *testing.T, c ExecutionDiskCache, k TaskCacheKey, want executionResult) { +func assertCacheHit(t *testing.T, c ExecutionDiskCache, k TaskCacheKey, want execution.Result) { t.Helper() have, found, err := c.Get(context.Background(), k) diff --git a/internal/batches/executor/executor.go b/internal/batches/executor/executor.go index f7bb6ec199..332f324828 100644 --- a/internal/batches/executor/executor.go +++ b/internal/batches/executor/executor.go @@ -14,6 +14,8 @@ import ( "github.com/sourcegraph/src-cli/internal/batches/repozip" "github.com/sourcegraph/src-cli/internal/batches/util" "github.com/sourcegraph/src-cli/internal/batches/workspace" + + "github.com/sourcegraph/sourcegraph/lib/batches/execution" ) type TaskExecutionErr struct { @@ -45,8 +47,8 @@ func (e TaskExecutionErr) StatusText() string { // taskResult is a combination of a Task and the result of its execution. type taskResult struct { task *Task - result executionResult - stepResults []stepExecutionResult + result execution.Result + stepResults []execution.AfterStepResult } type newExecutorOpts struct { @@ -190,7 +192,7 @@ func (x *executor) do(ctx context.Context, task *Task, ui TaskExecutionUI) (err return nil } -func (x *executor) addResult(task *Task, result executionResult, stepResults []stepExecutionResult) { +func (x *executor) addResult(task *Task, result execution.Result, stepResults []execution.AfterStepResult) { x.resultsMu.Lock() defer x.resultsMu.Unlock() diff --git a/internal/batches/executor/executor_test.go b/internal/batches/executor/executor_test.go index 2a53b9102b..999271dbd9 100644 --- a/internal/batches/executor/executor_test.go +++ b/internal/batches/executor/executor_test.go @@ -16,7 +16,9 @@ import ( "github.com/cockroachdb/errors" "github.com/google/go-cmp/cmp" "github.com/sourcegraph/go-diff/diff" + batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" + "github.com/sourcegraph/sourcegraph/lib/batches/execution" "github.com/sourcegraph/sourcegraph/lib/batches/git" "github.com/sourcegraph/sourcegraph/lib/batches/template" @@ -493,11 +495,11 @@ index 02a19af..c9644dd 100644 {Run: `echo -e "foobar\n" >> README.md`}, }, CachedResultFound: true, - CachedResult: stepExecutionResult{ + CachedResult: execution.AfterStepResult{ StepIndex: 0, Diff: cachedDiff, Outputs: map[string]interface{}{}, - PreviousStepResult: template.StepResult{}, + PreviousStepResult: execution.StepResult{}, }, Repository: testRepo1, } @@ -609,13 +611,13 @@ echo "previous_step.modified_files=${{ previous_step.modified_files }}" >> READM {Run: `echo "this is step 5" >> ${{ outputs.myOutput }}`}, }, CachedResultFound: true, - CachedResult: stepExecutionResult{ + CachedResult: execution.AfterStepResult{ StepIndex: 2, Diff: cachedDiff, Outputs: map[string]interface{}{ "myOutput": "my-output.txt", }, - PreviousStepResult: template.StepResult{ + PreviousStepResult: execution.StepResult{ Files: &git.Changes{ Modified: []string{"README.md"}, Added: []string{"README.txt"}, diff --git a/internal/batches/executor/run_steps.go b/internal/batches/executor/run_steps.go index 7c6997e7cb..059fb24464 100644 --- a/internal/batches/executor/run_steps.go +++ b/internal/batches/executor/run_steps.go @@ -15,6 +15,7 @@ import ( "github.com/hashicorp/go-multierror" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" + "github.com/sourcegraph/sourcegraph/lib/batches/execution" "github.com/sourcegraph/sourcegraph/lib/batches/git" "github.com/sourcegraph/sourcegraph/lib/batches/template" @@ -27,36 +28,6 @@ import ( yamlv3 "gopkg.in/yaml.v3" ) -// stepExecutionResult is the executionResult after executing the step with the -// given index in task.Steps. -type stepExecutionResult struct { - // StepIndex is the index of the step in task.Steps - StepIndex int `json:"stepIndex"` - // Diff is the cumulative `git diff` after executing the Step. - Diff []byte `json:"diff"` - // Outputs is a copy of the Outputs after executing the Step. - Outputs map[string]interface{} `json:"outputs"` - // PreviousStepResult is the StepResult of the step before Step, if Step != - // 0. - PreviousStepResult template.StepResult `json:"previousStepResult"` -} - -type executionResult struct { - // Diff is the produced by executing all steps. - Diff string `json:"diff"` - - // ChangedFiles are files that have been changed by all steps. - ChangedFiles *git.Changes `json:"changedFiles"` - - // Outputs are the outputs produced by all steps. - Outputs map[string]interface{} `json:"outputs"` - - // Path relative to the repository's root directory in which the steps - // have been executed. - // No leading slashes. Root directory is blank string. - Path string -} - type executionOpts struct { wc workspace.Creator ensureImage imageEnsurer @@ -70,31 +41,31 @@ type executionOpts struct { ui StepsExecutionUI } -func runSteps(ctx context.Context, opts *executionOpts) (result executionResult, stepResults []stepExecutionResult, err error) { +func runSteps(ctx context.Context, opts *executionOpts) (result execution.Result, stepResults []execution.AfterStepResult, err error) { opts.ui.ArchiveDownloadStarted() err = opts.task.Archive.Ensure(ctx) opts.ui.ArchiveDownloadFinished(err) if err != nil { - return executionResult{}, nil, errors.Wrap(err, "fetching repo") + return execution.Result{}, nil, errors.Wrap(err, "fetching repo") } defer opts.task.Archive.Close() opts.ui.WorkspaceInitializationStarted() workspace, err := opts.wc.Create(ctx, opts.task.Repository, opts.task.Steps, opts.task.Archive) if err != nil { - return executionResult{}, nil, errors.Wrap(err, "creating workspace") + return execution.Result{}, nil, errors.Wrap(err, "creating workspace") } defer workspace.Close(ctx) opts.ui.WorkspaceInitializationFinished() var ( - execResult = executionResult{ + execResult = execution.Result{ Diff: "", ChangedFiles: &git.Changes{}, Outputs: make(map[string]interface{}), Path: opts.task.Path, } - previousStepResult template.StepResult + previousStepResult execution.StepResult startStep int ) @@ -186,7 +157,7 @@ func runSteps(ctx context.Context, opts *executionOpts) (result executionResult, return execResult, nil, errors.Wrap(err, "getting changed files in step") } - result := template.StepResult{Files: changes, Stdout: &stdoutBuffer, Stderr: &stderrBuffer} + result := execution.StepResult{Files: changes, Stdout: &stdoutBuffer, Stderr: &stderrBuffer} // Set stepContext.Step to current step's results before rendering outputs stepContext.Step = result @@ -200,7 +171,7 @@ func runSteps(ctx context.Context, opts *executionOpts) (result executionResult, if err != nil { return execResult, nil, errors.Wrap(err, "getting diff produced by step") } - stepResult := stepExecutionResult{ + stepResult := execution.AfterStepResult{ StepIndex: i, Diff: stepDiff, Outputs: make(map[string]interface{}), diff --git a/internal/batches/executor/task.go b/internal/batches/executor/task.go index 8de89b013a..95b58745ce 100644 --- a/internal/batches/executor/task.go +++ b/internal/batches/executor/task.go @@ -2,6 +2,7 @@ package executor import ( batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" + "github.com/sourcegraph/sourcegraph/lib/batches/execution" "github.com/sourcegraph/sourcegraph/lib/batches/template" "github.com/sourcegraph/src-cli/internal/batches/graphql" @@ -30,8 +31,8 @@ type Task struct { Archive repozip.Archive `json:"-"` - CachedResultFound bool `json:"-"` - CachedResult stepExecutionResult `json:"-"` + CachedResultFound bool `json:"-"` + CachedResult execution.AfterStepResult `json:"-"` } func (t *Task) ArchivePathToFetch() string { diff --git a/internal/batches/graphql/repository.go b/internal/batches/graphql/repository.go index 17fb6e02ad..bd9e619e6f 100644 --- a/internal/batches/graphql/repository.go +++ b/internal/batches/graphql/repository.go @@ -1,6 +1,10 @@ package graphql -import "github.com/sourcegraph/src-cli/internal/batches/util" +import ( + "sort" + + "github.com/sourcegraph/src-cli/internal/batches/util" +) const RepositoryFieldsFragment = ` fragment repositoryFields on Repository { @@ -66,3 +70,12 @@ func (r *Repository) Rev() string { return r.DefaultBranch.Target.OID } + +func (r *Repository) SortedFileMatches() []string { + matches := make([]string, 0, len(r.FileMatches)) + for path := range r.FileMatches { + matches = append(matches, path) + } + sort.Strings(matches) + return matches +} From 5e3e2f05ba6a2f85b52fbe74e1705d058a96edf5 Mon Sep 17 00:00:00 2001 From: Thorsten Ball Date: Thu, 4 Nov 2021 14:37:38 +0100 Subject: [PATCH 079/647] Add JSONLinesCache to write cache entries to stdout (#649) This is part of https://github.com/sourcegraph/sourcegraph/issues/26929 and requires https://github.com/sourcegraph/sourcegraph/pull/27061 on the `sourcegraph/sourcegraph` side. It adds a `JSONLinesCache` that writes cache entries to stdout. It's used when executing `src batch exec`, which results in cache entries being transfered to the Sourcegraph server via the executor. --- cmd/src/batch_apply.go | 7 +- cmd/src/batch_common.go | 69 ++++++++++---------- cmd/src/batch_exec.go | 38 +++++------ cmd/src/batch_preview.go | 4 +- go.mod | 2 +- go.sum | 4 ++ internal/batches/executor/coordinator.go | 7 +- internal/batches/executor/execution_cache.go | 48 +++++++++++++- internal/batches/ui/json_lines.go | 17 +++++ 9 files changed, 129 insertions(+), 67 deletions(-) diff --git a/cmd/src/batch_apply.go b/cmd/src/batch_apply.go index dcfafe0127..1a1d047aa1 100644 --- a/cmd/src/batch_apply.go +++ b/cmd/src/batch_apply.go @@ -5,9 +5,10 @@ import ( "flag" "fmt" - "github.com/sourcegraph/sourcegraph/lib/output" "github.com/sourcegraph/src-cli/internal/batches/ui" "github.com/sourcegraph/src-cli/internal/cmderrors" + + "github.com/sourcegraph/sourcegraph/lib/output" ) func init() { @@ -50,13 +51,11 @@ Examples: execUI = &ui.TUI{Out: out} } - err := executeBatchSpec(ctx, executeBatchSpecOpts{ + err := executeBatchSpec(ctx, execUI, executeBatchSpecOpts{ flags: flags, client: cfg.apiClient(flags.api, flagSet.Output()), applyBatchSpec: true, - - ui: execUI, }) if err != nil { return cmderrors.ExitCode(1, nil) diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index e21f0a91a2..378db8e077 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -193,18 +193,16 @@ type executeBatchSpecOpts struct { applyBatchSpec bool - ui ui.ExecUI - client api.Client } // executeBatchSpec performs all the steps required to upload the batch spec to // Sourcegraph, including execution as needed and applying the resulting batch // spec if specified. -func executeBatchSpec(ctx context.Context, opts executeBatchSpecOpts) (err error) { +func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOpts) (err error) { defer func() { if err != nil { - opts.ui.ExecutionError(err) + ui.ExecutionError(err) } }() @@ -228,12 +226,12 @@ func executeBatchSpec(ctx context.Context, opts executeBatchSpecOpts) (err error } // Parse flags and build up our service and executor options. - opts.ui.ParsingBatchSpec() + ui.ParsingBatchSpec() batchSpec, rawSpec, err := parseBatchSpec(&opts.flags.file, svc) if err != nil { var multiErr *multierror.Error if errors.As(err, &multiErr) { - opts.ui.ParsingBatchSpecFailure(multiErr) + ui.ParsingBatchSpecFailure(multiErr) return cmderrors.ExitCode(2, nil) } else { // This shouldn't happen; let's just punt and let the normal @@ -241,26 +239,26 @@ func executeBatchSpec(ctx context.Context, opts executeBatchSpecOpts) (err error return err } } - opts.ui.ParsingBatchSpecSuccess() + ui.ParsingBatchSpecSuccess() - opts.ui.ResolvingNamespace() + ui.ResolvingNamespace() namespace, err := svc.ResolveNamespace(ctx, opts.flags.namespace) if err != nil { return err } - opts.ui.ResolvingNamespaceSuccess(namespace) + ui.ResolvingNamespaceSuccess(namespace) var workspaceCreator workspace.Creator if svc.HasDockerImages(batchSpec) { - opts.ui.PreparingContainerImages() - images, err := svc.EnsureDockerImages(ctx, batchSpec, opts.ui.PreparingContainerImagesProgress) + ui.PreparingContainerImages() + images, err := svc.EnsureDockerImages(ctx, batchSpec, ui.PreparingContainerImagesProgress) if err != nil { return err } - opts.ui.PreparingContainerImagesSuccess() + ui.PreparingContainerImagesSuccess() - opts.ui.DeterminingWorkspaceCreatorType() + ui.DeterminingWorkspaceCreatorType() workspaceCreator = workspace.NewCreator(ctx, opts.flags.workspace, opts.flags.cacheDir, opts.flags.tempDir, images) if workspaceCreator.Type() == workspace.CreatorTypeVolume { _, err = svc.EnsureImage(ctx, workspace.DockerVolumeWorkspaceImage) @@ -268,34 +266,35 @@ func executeBatchSpec(ctx context.Context, opts executeBatchSpecOpts) (err error return err } } - opts.ui.DeterminingWorkspaceCreatorTypeSuccess(workspaceCreator.Type()) + ui.DeterminingWorkspaceCreatorTypeSuccess(workspaceCreator.Type()) } - opts.ui.ResolvingRepositories() + ui.ResolvingRepositories() repos, err := svc.ResolveRepositories(ctx, batchSpec) if err != nil { if repoSet, ok := err.(batches.UnsupportedRepoSet); ok { - opts.ui.ResolvingRepositoriesDone(repos, repoSet, nil) + ui.ResolvingRepositoriesDone(repos, repoSet, nil) } else if repoSet, ok := err.(batches.IgnoredRepoSet); ok { - opts.ui.ResolvingRepositoriesDone(repos, nil, repoSet) + ui.ResolvingRepositoriesDone(repos, nil, repoSet) } else { return errors.Wrap(err, "resolving repositories") } } else { - opts.ui.ResolvingRepositoriesDone(repos, nil, nil) + ui.ResolvingRepositoriesDone(repos, nil, nil) } - opts.ui.DeterminingWorkspaces() + ui.DeterminingWorkspaces() workspaces, err := svc.DetermineWorkspaces(ctx, repos, batchSpec) if err != nil { return err } - opts.ui.DeterminingWorkspacesSuccess(len(workspaces)) + ui.DeterminingWorkspacesSuccess(len(workspaces)) // EXECUTION OF TASKS coord := svc.NewCoordinator(executor.NewCoordinatorOpts{ Creator: workspaceCreator, CacheDir: opts.flags.cacheDir, + Cache: executor.NewDiskCache(opts.flags.cacheDir), ClearCache: opts.flags.clearCache, SkipErrors: opts.flags.skipErrors, CleanArchives: opts.flags.cleanArchives, @@ -306,15 +305,15 @@ func executeBatchSpec(ctx context.Context, opts executeBatchSpecOpts) (err error ImportChangesets: true, }) - opts.ui.CheckingCache() + ui.CheckingCache() tasks := svc.BuildTasks(ctx, batchSpec, workspaces) uncachedTasks, cachedSpecs, err := coord.CheckCache(ctx, tasks) if err != nil { return err } - opts.ui.CheckingCacheSuccess(len(cachedSpecs), len(uncachedTasks)) + ui.CheckingCacheSuccess(len(cachedSpecs), len(uncachedTasks)) - taskExecUI := opts.ui.ExecutingTasks(*verbose, opts.flags.parallelism) + taskExecUI := ui.ExecutingTasks(*verbose, opts.flags.parallelism) freshSpecs, logFiles, err := coord.Execute(ctx, uncachedTasks, batchSpec, taskExecUI) if err != nil && !opts.flags.skipErrors { return err @@ -323,7 +322,7 @@ func executeBatchSpec(ctx context.Context, opts executeBatchSpecOpts) (err error if err == nil { taskExecUI.Success() } else { - opts.ui.ExecutingTasksSkippingErrors(err) + ui.ExecutingTasksSkippingErrors(err) } } else { if err != nil { @@ -333,7 +332,7 @@ func executeBatchSpec(ctx context.Context, opts executeBatchSpecOpts) (err error } if len(logFiles) > 0 && opts.flags.keepLogs { - opts.ui.LogFilesKept(logFiles) + ui.LogFilesKept(logFiles) } specs := append(cachedSpecs, freshSpecs...) @@ -346,7 +345,7 @@ func executeBatchSpec(ctx context.Context, opts executeBatchSpecOpts) (err error ids := make([]graphql.ChangesetSpecID, len(specs)) if len(specs) > 0 { - opts.ui.UploadingChangesetSpecs(len(specs)) + ui.UploadingChangesetSpecs(len(specs)) for i, spec := range specs { id, err := svc.CreateChangesetSpec(ctx, spec) @@ -354,33 +353,33 @@ func executeBatchSpec(ctx context.Context, opts executeBatchSpecOpts) (err error return err } ids[i] = id - opts.ui.UploadingChangesetSpecsProgress(i+1, len(specs)) + ui.UploadingChangesetSpecsProgress(i+1, len(specs)) } - opts.ui.UploadingChangesetSpecsSuccess(ids) + ui.UploadingChangesetSpecsSuccess(ids) } else if len(repos) == 0 { - opts.ui.NoChangesetSpecs() + ui.NoChangesetSpecs() } - opts.ui.CreatingBatchSpec() + ui.CreatingBatchSpec() id, url, err := svc.CreateBatchSpec(ctx, namespace, rawSpec, ids) if err != nil { - return opts.ui.CreatingBatchSpecError(err) + return ui.CreatingBatchSpecError(err) } previewURL := cfg.Endpoint + url - opts.ui.CreatingBatchSpecSuccess(previewURL) + ui.CreatingBatchSpecSuccess(previewURL) if !opts.applyBatchSpec { - opts.ui.PreviewBatchSpec(previewURL) + ui.PreviewBatchSpec(previewURL) return } - opts.ui.ApplyingBatchSpec() + ui.ApplyingBatchSpec() batch, err := svc.ApplyBatchChange(ctx, id) if err != nil { return err } - opts.ui.ApplyingBatchSpecSuccess(cfg.Endpoint + batch.URL) + ui.ApplyingBatchSpecSuccess(cfg.Endpoint + batch.URL) return nil } diff --git a/cmd/src/batch_exec.go b/cmd/src/batch_exec.go index 2694075ce9..a4bce4416c 100644 --- a/cmd/src/batch_exec.go +++ b/cmd/src/batch_exec.go @@ -52,10 +52,9 @@ Examples: ctx, cancel := contextCancelOnInterrupt(context.Background()) defer cancel() - err := executeBatchSpecInWorkspaces(ctx, executeBatchSpecOpts{ + err := executeBatchSpecInWorkspaces(ctx, &ui.JSONLines{}, executeBatchSpecOpts{ flags: flags, client: cfg.apiClient(flags.api, flagSet.Output()), - ui: &ui.JSONLines{}, }) if err != nil { return cmderrors.ExitCode(1, nil) @@ -75,10 +74,10 @@ Examples: }) } -func executeBatchSpecInWorkspaces(ctx context.Context, opts executeBatchSpecOpts) (err error) { +func executeBatchSpecInWorkspaces(ctx context.Context, ui *ui.JSONLines, opts executeBatchSpecOpts) (err error) { defer func() { if err != nil { - opts.ui.ExecutionError(err) + ui.ExecutionError(err) } }() @@ -111,12 +110,12 @@ func executeBatchSpecInWorkspaces(ctx context.Context, opts executeBatchSpecOpts repoWorkspaces := convertWorkspaces(input.Workspaces) // Parse the raw batch spec contained in the input - opts.ui.ParsingBatchSpec() + ui.ParsingBatchSpec() batchSpec, err := svc.ParseBatchSpec([]byte(input.RawSpec)) if err != nil { var multiErr *multierror.Error if errors.As(err, &multiErr) { - opts.ui.ParsingBatchSpecFailure(multiErr) + ui.ParsingBatchSpecFailure(multiErr) return cmderrors.ExitCode(2, nil) } else { // This shouldn't happen; let's just punt and let the normal @@ -124,19 +123,19 @@ func executeBatchSpecInWorkspaces(ctx context.Context, opts executeBatchSpecOpts return err } } - opts.ui.ParsingBatchSpecSuccess() + ui.ParsingBatchSpecSuccess() var workspaceCreator workspace.Creator if svc.HasDockerImages(batchSpec) { - opts.ui.PreparingContainerImages() - images, err := svc.EnsureDockerImages(ctx, batchSpec, opts.ui.PreparingContainerImagesProgress) + ui.PreparingContainerImages() + images, err := svc.EnsureDockerImages(ctx, batchSpec, ui.PreparingContainerImagesProgress) if err != nil { return err } - opts.ui.PreparingContainerImagesSuccess() + ui.PreparingContainerImagesSuccess() - opts.ui.DeterminingWorkspaceCreatorType() + ui.DeterminingWorkspaceCreatorType() workspaceCreator = workspace.NewCreator(ctx, opts.flags.workspace, opts.flags.cacheDir, opts.flags.tempDir, images) if workspaceCreator.Type() == workspace.CreatorTypeVolume { _, err = svc.EnsureImage(ctx, workspace.DockerVolumeWorkspaceImage) @@ -144,13 +143,14 @@ func executeBatchSpecInWorkspaces(ctx context.Context, opts executeBatchSpecOpts return err } } - opts.ui.DeterminingWorkspaceCreatorTypeSuccess(workspaceCreator.Type()) + ui.DeterminingWorkspaceCreatorTypeSuccess(workspaceCreator.Type()) } // EXECUTION OF TASKS coord := svc.NewCoordinator(executor.NewCoordinatorOpts{ Creator: workspaceCreator, CacheDir: opts.flags.cacheDir, + Cache: &executor.JSONLinesCache{Writer: ui}, ClearCache: opts.flags.clearCache, SkipErrors: opts.flags.skipErrors, CleanArchives: opts.flags.cleanArchives, @@ -162,21 +162,21 @@ func executeBatchSpecInWorkspaces(ctx context.Context, opts executeBatchSpecOpts ImportChangesets: false, }) - opts.ui.CheckingCache() + ui.CheckingCache() tasks := svc.BuildTasks(ctx, batchSpec, repoWorkspaces) uncachedTasks, cachedSpecs, err := coord.CheckCache(ctx, tasks) if err != nil { return err } - opts.ui.CheckingCacheSuccess(len(cachedSpecs), len(uncachedTasks)) + ui.CheckingCacheSuccess(len(cachedSpecs), len(uncachedTasks)) - taskExecUI := opts.ui.ExecutingTasks(*verbose, opts.flags.parallelism) + taskExecUI := ui.ExecutingTasks(*verbose, opts.flags.parallelism) freshSpecs, _, err := coord.Execute(ctx, uncachedTasks, batchSpec, taskExecUI) if err == nil || opts.flags.skipErrors { if err == nil { taskExecUI.Success() } else { - opts.ui.ExecutingTasksSkippingErrors(err) + ui.ExecutingTasksSkippingErrors(err) } } else { if err != nil { @@ -189,16 +189,16 @@ func executeBatchSpecInWorkspaces(ctx context.Context, opts executeBatchSpecOpts ids := make([]graphql.ChangesetSpecID, len(specs)) - opts.ui.UploadingChangesetSpecs(len(specs)) + ui.UploadingChangesetSpecs(len(specs)) for i, spec := range specs { id, err := svc.CreateChangesetSpec(ctx, spec) if err != nil { return err } ids[i] = id - opts.ui.UploadingChangesetSpecsProgress(i+1, len(specs)) + ui.UploadingChangesetSpecsProgress(i+1, len(specs)) } - opts.ui.UploadingChangesetSpecsSuccess(ids) + ui.UploadingChangesetSpecsSuccess(ids) return nil } diff --git a/cmd/src/batch_preview.go b/cmd/src/batch_preview.go index b2142032ea..13533a8879 100644 --- a/cmd/src/batch_preview.go +++ b/cmd/src/batch_preview.go @@ -49,14 +49,12 @@ Examples: execUI = &ui.TUI{Out: out} } - err := executeBatchSpec(ctx, executeBatchSpecOpts{ + err := executeBatchSpec(ctx, execUI, executeBatchSpecOpts{ flags: flags, client: cfg.apiClient(flags.api, flagSet.Output()), // Do not apply the uploaded batch spec applyBatchSpec: false, - - ui: execUI, }) if err != nil { return cmderrors.ExitCode(1, nil) diff --git a/go.mod b/go.mod index ad827cc69a..1c49905be6 100644 --- a/go.mod +++ b/go.mod @@ -20,7 +20,7 @@ require ( github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4 github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf - github.com/sourcegraph/sourcegraph/lib v0.0.0-20211104093537-2b2516676fec + github.com/sourcegraph/sourcegraph/lib v0.0.0-20211104124831-032ed4e5b75d github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect golang.org/x/net v0.0.0-20210614182718-04defd469f4e diff --git a/go.sum b/go.sum index 8bb7c394bc..4825aa7e07 100644 --- a/go.sum +++ b/go.sum @@ -260,6 +260,10 @@ github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWii github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= github.com/sourcegraph/sourcegraph/lib v0.0.0-20211104093537-2b2516676fec h1:SvEo7YwpY2nRGGizAOWlvpitO3qM/NdyhVzR+mkD/a4= github.com/sourcegraph/sourcegraph/lib v0.0.0-20211104093537-2b2516676fec/go.mod h1:oriyPo0GiQg2oIAjaKAuaNwxiuSmscMVJGfV38ONvqQ= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20211104104606-255e002650dc h1:r+zAUTmiHxyOfPX3HC6D5qjvfIYHlFUSdSiOmp6avYk= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20211104104606-255e002650dc/go.mod h1:oriyPo0GiQg2oIAjaKAuaNwxiuSmscMVJGfV38ONvqQ= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20211104124831-032ed4e5b75d h1:12YQbS5LU5ltOFLzxJW/sbiVIzosvdkdf8kQMLfOc74= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20211104124831-032ed4e5b75d/go.mod h1:oriyPo0GiQg2oIAjaKAuaNwxiuSmscMVJGfV38ONvqQ= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= diff --git a/internal/batches/executor/coordinator.go b/internal/batches/executor/coordinator.go index 45603fe906..8d8af959b6 100644 --- a/internal/batches/executor/coordinator.go +++ b/internal/batches/executor/coordinator.go @@ -44,6 +44,7 @@ type NewCoordinatorOpts struct { EnsureImage imageEnsurer Creator workspace.Creator Client api.Client + Cache ExecutionCache // Everything that follows are either command-line flags or features. @@ -68,7 +69,6 @@ type NewCoordinatorOpts struct { } func NewCoordinator(opts NewCoordinatorOpts) *Coordinator { - cache := NewCache(opts.CacheDir) logManager := log.NewManager(opts.TempDir, opts.KeepLogs) exec := newExecutor(newExecutorOpts{ @@ -83,9 +83,8 @@ func NewCoordinator(opts NewCoordinatorOpts) *Coordinator { }) return &Coordinator{ - opts: opts, - - cache: cache, + opts: opts, + cache: opts.Cache, exec: exec, logManager: logManager, } diff --git a/internal/batches/executor/execution_cache.go b/internal/batches/executor/execution_cache.go index 99a6ca49a1..ebfeae1d4b 100644 --- a/internal/batches/executor/execution_cache.go +++ b/internal/batches/executor/execution_cache.go @@ -152,7 +152,7 @@ type ExecutionCache interface { Clear(ctx context.Context, key CacheKeyer) error } -func NewCache(dir string) ExecutionCache { +func NewDiskCache(dir string) ExecutionCache { if dir == "" { return &ExecutionNoOpCache{} } @@ -291,3 +291,49 @@ func (ExecutionNoOpCache) SetStepResult(ctx context.Context, key CacheKeyer, res func (ExecutionNoOpCache) GetStepResult(ctx context.Context, key CacheKeyer) (execution.AfterStepResult, bool, error) { return execution.AfterStepResult{}, false, nil } + +type JSONCacheWriter interface { + WriteExecutionResult(key string, value execution.Result) + WriteAfterStepResult(key string, value execution.AfterStepResult) +} + +type JSONLinesCache struct { + Writer JSONCacheWriter +} + +func (c *JSONLinesCache) Get(ctx context.Context, key CacheKeyer) (result execution.Result, found bool, err error) { + // noop + return execution.Result{}, false, nil +} + +func (c *JSONLinesCache) Set(ctx context.Context, key CacheKeyer, result execution.Result) error { + k, err := key.Key() + if err != nil { + return err + } + + c.Writer.WriteExecutionResult(k, result) + + return nil +} + +func (c *JSONLinesCache) SetStepResult(ctx context.Context, key CacheKeyer, result execution.AfterStepResult) error { + k, err := key.Key() + if err != nil { + return err + } + + c.Writer.WriteAfterStepResult(k, result) + + return nil +} + +func (c *JSONLinesCache) GetStepResult(ctx context.Context, key CacheKeyer) (result execution.AfterStepResult, found bool, err error) { + // noop + return execution.AfterStepResult{}, false, nil +} + +func (c *JSONLinesCache) Clear(ctx context.Context, key CacheKeyer) error { + // noop + return nil +} diff --git a/internal/batches/ui/json_lines.go b/internal/batches/ui/json_lines.go index 46c59a8f5c..cb0f314bb4 100644 --- a/internal/batches/ui/json_lines.go +++ b/internal/batches/ui/json_lines.go @@ -17,6 +17,7 @@ import ( "github.com/sourcegraph/src-cli/internal/batches/workspace" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" + "github.com/sourcegraph/sourcegraph/lib/batches/execution" "github.com/sourcegraph/sourcegraph/lib/batches/git" ) @@ -171,6 +172,22 @@ func (ui *JSONLines) ExecutionError(err error) { logOperationFailure(batcheslib.LogEventOperationBatchSpecExecution, &batcheslib.BatchSpecExecutionMetadata{Error: err.Error()}) } +var _ executor.JSONCacheWriter = &JSONLines{} + +func (ui *JSONLines) WriteExecutionResult(key string, value execution.Result) { + logOperationSuccess(batcheslib.LogEventOperationCacheResult, &batcheslib.CacheResultMetadata{ + Key: key, + Value: value, + }) +} + +func (ui *JSONLines) WriteAfterStepResult(key string, value execution.AfterStepResult) { + logOperationSuccess(batcheslib.LogEventOperationCacheAfterStepResult, &batcheslib.CacheAfterStepResultMetadata{ + Key: key, + Value: value, + }) +} + type taskExecutionJSONLines struct { verbose bool parallelism int From 8a884a8d685b4ca3c40b3ff0e2406ce97bda8489 Mon Sep 17 00:00:00 2001 From: Thorsten Ball Date: Thu, 4 Nov 2021 17:30:02 +0100 Subject: [PATCH 080/647] Use the extracted batches/execution/cache package and remove extracted code (#650) --- go.mod | 2 +- go.sum | 8 +- internal/batches/executor/coordinator.go | 12 +- internal/batches/executor/coordinator_test.go | 13 +- internal/batches/executor/execution_cache.go | 176 ++---------------- .../batches/executor/execution_cache_test.go | 112 +++-------- internal/batches/executor/task.go | 17 +- 7 files changed, 74 insertions(+), 266 deletions(-) diff --git a/go.mod b/go.mod index 1c49905be6..df14ebc5e4 100644 --- a/go.mod +++ b/go.mod @@ -20,7 +20,7 @@ require ( github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4 github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf - github.com/sourcegraph/sourcegraph/lib v0.0.0-20211104124831-032ed4e5b75d + github.com/sourcegraph/sourcegraph/lib v0.0.0-20211104160022-5499420c85c9 github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect golang.org/x/net v0.0.0-20210614182718-04defd469f4e diff --git a/go.sum b/go.sum index 4825aa7e07..27a4ef1523 100644 --- a/go.sum +++ b/go.sum @@ -258,12 +258,8 @@ github.com/sourcegraph/go-diff v0.6.1 h1:hmA1LzxW0n1c3Q4YbrFgg4P99GSnebYa3x8gr0H github.com/sourcegraph/go-diff v0.6.1/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20211104093537-2b2516676fec h1:SvEo7YwpY2nRGGizAOWlvpitO3qM/NdyhVzR+mkD/a4= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20211104093537-2b2516676fec/go.mod h1:oriyPo0GiQg2oIAjaKAuaNwxiuSmscMVJGfV38ONvqQ= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20211104104606-255e002650dc h1:r+zAUTmiHxyOfPX3HC6D5qjvfIYHlFUSdSiOmp6avYk= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20211104104606-255e002650dc/go.mod h1:oriyPo0GiQg2oIAjaKAuaNwxiuSmscMVJGfV38ONvqQ= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20211104124831-032ed4e5b75d h1:12YQbS5LU5ltOFLzxJW/sbiVIzosvdkdf8kQMLfOc74= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20211104124831-032ed4e5b75d/go.mod h1:oriyPo0GiQg2oIAjaKAuaNwxiuSmscMVJGfV38ONvqQ= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20211104160022-5499420c85c9 h1:b56HdWLb6D2h0D70l1fonoB4m1pItue+og8fFxTlaWc= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20211104160022-5499420c85c9/go.mod h1:oriyPo0GiQg2oIAjaKAuaNwxiuSmscMVJGfV38ONvqQ= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= diff --git a/internal/batches/executor/coordinator.go b/internal/batches/executor/coordinator.go index 8d8af959b6..7ab05fc304 100644 --- a/internal/batches/executor/coordinator.go +++ b/internal/batches/executor/coordinator.go @@ -9,6 +9,7 @@ import ( batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/execution" + "github.com/sourcegraph/sourcegraph/lib/batches/execution/cache" "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/batches" @@ -30,7 +31,7 @@ type taskExecutor interface { type Coordinator struct { opts NewCoordinatorOpts - cache ExecutionCache + cache cache.Cache exec taskExecutor logManager log.LogManager } @@ -44,7 +45,7 @@ type NewCoordinatorOpts struct { EnsureImage imageEnsurer Creator workspace.Creator Client api.Client - Cache ExecutionCache + Cache cache.Cache // Everything that follows are either command-line flags or features. @@ -180,7 +181,7 @@ func (c *Coordinator) setCachedStepResults(ctx context.Context, task *Task) erro // We start at the back so that we can find the _last_ cached step, // then restart execution on the following step. for i := len(task.Steps) - 1; i > -1; i-- { - key := StepsCacheKey{Task: task, StepIndex: i} + key := cache.StepsCacheKey{ExecutionKey: task.cacheKey(), StepIndex: i} // If we need to clear the cache, we optimistically try this for every // step. @@ -215,7 +216,10 @@ func (c *Coordinator) cacheAndBuildSpec(ctx context.Context, taskResult taskResu // Save the per-step results for _, stepResult := range taskResult.stepResults { - key := StepsCacheKey{Task: taskResult.task, StepIndex: stepResult.StepIndex} + key := cache.StepsCacheKey{ + ExecutionKey: taskResult.task.cacheKey(), + StepIndex: stepResult.StepIndex, + } if err := c.cache.SetStepResult(ctx, key, stepResult); err != nil { return nil, errors.Wrapf(err, "caching result for step %d in %q", stepResult.StepIndex, taskResult.task.Repository.Name) } diff --git a/internal/batches/executor/coordinator_test.go b/internal/batches/executor/coordinator_test.go index f000bcb81b..2cac0e1e8c 100644 --- a/internal/batches/executor/coordinator_test.go +++ b/internal/batches/executor/coordinator_test.go @@ -14,6 +14,7 @@ import ( "github.com/sourcegraph/sourcegraph/lib/batches/overridable" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" + "github.com/sourcegraph/sourcegraph/lib/batches/execution/cache" "github.com/sourcegraph/sourcegraph/lib/batches/git" "github.com/sourcegraph/sourcegraph/lib/batches/template" @@ -647,7 +648,7 @@ func (c *inMemoryExecutionCache) size() int { return len(c.cache) } -func (c *inMemoryExecutionCache) getCacheItem(key CacheKeyer) (interface{}, bool, error) { +func (c *inMemoryExecutionCache) getCacheItem(key cache.Keyer) (interface{}, bool, error) { k, err := key.Key() if err != nil { return execution.Result{}, false, err @@ -660,7 +661,7 @@ func (c *inMemoryExecutionCache) getCacheItem(key CacheKeyer) (interface{}, bool return res, ok, nil } -func (c *inMemoryExecutionCache) Get(ctx context.Context, key CacheKeyer) (execution.Result, bool, error) { +func (c *inMemoryExecutionCache) Get(ctx context.Context, key cache.Keyer) (execution.Result, bool, error) { res, ok, err := c.getCacheItem(key) if err != nil || !ok { return execution.Result{}, ok, err @@ -670,7 +671,7 @@ func (c *inMemoryExecutionCache) Get(ctx context.Context, key CacheKeyer) (execu return execResult, ok, nil } -func (c *inMemoryExecutionCache) Set(ctx context.Context, key CacheKeyer, result execution.Result) error { +func (c *inMemoryExecutionCache) Set(ctx context.Context, key cache.Keyer, result execution.Result) error { k, err := key.Key() if err != nil { return err @@ -683,7 +684,7 @@ func (c *inMemoryExecutionCache) Set(ctx context.Context, key CacheKeyer, result return nil } -func (c *inMemoryExecutionCache) GetStepResult(ctx context.Context, key CacheKeyer) (execution.AfterStepResult, bool, error) { +func (c *inMemoryExecutionCache) GetStepResult(ctx context.Context, key cache.Keyer) (execution.AfterStepResult, bool, error) { res, ok, err := c.getCacheItem(key) if err != nil || !ok { return execution.AfterStepResult{}, ok, err @@ -693,7 +694,7 @@ func (c *inMemoryExecutionCache) GetStepResult(ctx context.Context, key CacheKey return execResult, ok, nil } -func (c *inMemoryExecutionCache) SetStepResult(ctx context.Context, key CacheKeyer, result execution.AfterStepResult) error { +func (c *inMemoryExecutionCache) SetStepResult(ctx context.Context, key cache.Keyer, result execution.AfterStepResult) error { k, err := key.Key() if err != nil { return err @@ -706,7 +707,7 @@ func (c *inMemoryExecutionCache) SetStepResult(ctx context.Context, key CacheKey return nil } -func (c *inMemoryExecutionCache) Clear(ctx context.Context, key CacheKeyer) error { +func (c *inMemoryExecutionCache) Clear(ctx context.Context, key cache.Keyer) error { k, err := key.Key() if err != nil { return err diff --git a/internal/batches/executor/execution_cache.go b/internal/batches/executor/execution_cache.go index ebfeae1d4b..af6eff83bb 100644 --- a/internal/batches/executor/execution_cache.go +++ b/internal/batches/executor/execution_cache.go @@ -2,157 +2,17 @@ package executor import ( "context" - "crypto/sha256" - "encoding/base64" "encoding/json" - "fmt" "os" "path/filepath" "github.com/cockroachdb/errors" - batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/execution" - - "github.com/sourcegraph/src-cli/internal/batches/util" + "github.com/sourcegraph/sourcegraph/lib/batches/execution/cache" ) -func UserCacheDir() (string, error) { - userCacheDir, err := os.UserCacheDir() - if err != nil { - return "", err - } - return filepath.Join(userCacheDir, "sourcegraph-src"), nil -} - -type CacheKeyer interface { - Key() (string, error) - Slug() string -} - -func resolveStepsEnvironment(steps []batcheslib.Step) ([]map[string]string, error) { - // We have to resolve the step environments and include them in the cache - // key to ensure that the cache is properly invalidated when an environment - // variable changes. - // - // Note that we don't base the cache key on the entire global environment: - // if an unrelated environment variable changes, that's fine. We're only - // interested in the ones that actually make it into the step container. - global := os.Environ() - envs := make([]map[string]string, len(steps)) - for i, step := range steps { - // TODO: This should also render templates inside env vars. - env, err := step.Env.Resolve(global) - if err != nil { - return nil, errors.Wrapf(err, "resolving environment for step %d", i) - } - envs[i] = env - } - return envs, nil -} - -func marshalHash(t *Task, envs []map[string]string) (string, error) { - raw, err := json.Marshal(struct { - *Task - Environments []map[string]string - }{ - Task: t, - Environments: envs, - }) - if err != nil { - return "", err - } - - hash := sha256.Sum256(raw) - return base64.RawURLEncoding.EncodeToString(hash[:16]), nil -} - -// StepsCacheKey implements the CacheKeyer interface for a Task and a *subset* -// of its Steps, up to and including the step with index StepIndex in -// Task.Steps. -type StepsCacheKey struct { - *Task - StepIndex int -} - -// Key converts the key into a string form that can be used to uniquely identify -// the cache key in a more concise form than the entire Task. -func (key StepsCacheKey) Key() (string, error) { - // Setup a copy of the Task that only includes the Steps up to and - // including key.StepIndex. - taskCopy := &Task{ - Repository: key.Task.Repository, - Path: key.Task.Path, - OnlyFetchWorkspace: key.Task.OnlyFetchWorkspace, - BatchChangeAttributes: key.Task.BatchChangeAttributes, - Template: key.Task.Template, - TransformChanges: key.Task.TransformChanges, - Archive: key.Task.Archive, - } - - taskCopy.Steps = key.Task.Steps[0 : key.StepIndex+1] - - // Resolve environment only for the subset of Steps - envs, err := resolveStepsEnvironment(taskCopy.Steps) - if err != nil { - return "", err - } - - hash, err := marshalHash(taskCopy, envs) - if err != nil { - return "", err - } - return fmt.Sprintf("%s-step-%d", hash, key.StepIndex), err -} - -func (key StepsCacheKey) Slug() string { - return util.SlugForRepo(key.Repository.Name, key.Repository.Rev()) -} - -// TaskCacheKey implements the CacheKeyer interface for a Task and all its -// Steps. -type TaskCacheKey struct { - *Task -} - -// Key converts the key into a string form that can be used to uniquely identify -// the cache key in a more concise form than the entire Task. -func (key TaskCacheKey) Key() (string, error) { - envs, err := resolveStepsEnvironment(key.Task.Steps) - if err != nil { - return "", err - } - - raw, err := json.Marshal(struct { - *Task - Environments []map[string]string - }{ - Task: key.Task, - Environments: envs, - }) - if err != nil { - return "", err - } - - hash := sha256.Sum256(raw) - return base64.RawURLEncoding.EncodeToString(hash[:16]), nil -} - -func (key TaskCacheKey) Slug() string { - return util.SlugForRepo(key.Repository.Name, key.Repository.Rev()) -} - -type ExecutionCache interface { - Get(ctx context.Context, key CacheKeyer) (result execution.Result, found bool, err error) - Set(ctx context.Context, key CacheKeyer, result execution.Result) error - - GetStepResult(ctx context.Context, key CacheKeyer) (result execution.AfterStepResult, found bool, err error) - SetStepResult(ctx context.Context, key CacheKeyer, result execution.AfterStepResult) error - - Clear(ctx context.Context, key CacheKeyer) error -} - -func NewDiskCache(dir string) ExecutionCache { +func NewDiskCache(dir string) cache.Cache { if dir == "" { return &ExecutionNoOpCache{} } @@ -166,7 +26,7 @@ type ExecutionDiskCache struct { const cacheFileExt = ".json" -func (c ExecutionDiskCache) cacheFilePath(key CacheKeyer) (string, error) { +func (c ExecutionDiskCache) cacheFilePath(key cache.Keyer) (string, error) { keyString, err := key.Key() if err != nil { return "", errors.Wrap(err, "calculating execution cache key") @@ -175,7 +35,7 @@ func (c ExecutionDiskCache) cacheFilePath(key CacheKeyer) (string, error) { return filepath.Join(c.Dir, key.Slug(), keyString+cacheFileExt), nil } -func (c ExecutionDiskCache) Get(ctx context.Context, key CacheKeyer) (execution.Result, bool, error) { +func (c ExecutionDiskCache) Get(ctx context.Context, key cache.Keyer) (execution.Result, bool, error) { var result execution.Result path, err := c.cacheFilePath(key) @@ -222,7 +82,7 @@ func (c ExecutionDiskCache) writeCacheFile(path string, result interface{}) erro return os.WriteFile(path, raw, 0600) } -func (c ExecutionDiskCache) Set(ctx context.Context, key CacheKeyer, result execution.Result) error { +func (c ExecutionDiskCache) Set(ctx context.Context, key cache.Keyer, result execution.Result) error { path, err := c.cacheFilePath(key) if err != nil { return err @@ -231,7 +91,7 @@ func (c ExecutionDiskCache) Set(ctx context.Context, key CacheKeyer, result exec return c.writeCacheFile(path, &result) } -func (c ExecutionDiskCache) Clear(ctx context.Context, key CacheKeyer) error { +func (c ExecutionDiskCache) Clear(ctx context.Context, key cache.Keyer) error { path, err := c.cacheFilePath(key) if err != nil { return err @@ -244,7 +104,7 @@ func (c ExecutionDiskCache) Clear(ctx context.Context, key CacheKeyer) error { return os.Remove(path) } -func (c ExecutionDiskCache) GetStepResult(ctx context.Context, key CacheKeyer) (execution.AfterStepResult, bool, error) { +func (c ExecutionDiskCache) GetStepResult(ctx context.Context, key cache.Keyer) (execution.AfterStepResult, bool, error) { var result execution.AfterStepResult path, err := c.cacheFilePath(key) if err != nil { @@ -259,7 +119,7 @@ func (c ExecutionDiskCache) GetStepResult(ctx context.Context, key CacheKeyer) ( return result, found, nil } -func (c ExecutionDiskCache) SetStepResult(ctx context.Context, key CacheKeyer, result execution.AfterStepResult) error { +func (c ExecutionDiskCache) SetStepResult(ctx context.Context, key cache.Keyer, result execution.AfterStepResult) error { path, err := c.cacheFilePath(key) if err != nil { return err @@ -272,23 +132,23 @@ func (c ExecutionDiskCache) SetStepResult(ctx context.Context, key CacheKeyer, r // retrieve cache entries. type ExecutionNoOpCache struct{} -func (ExecutionNoOpCache) Get(ctx context.Context, key CacheKeyer) (result execution.Result, found bool, err error) { +func (ExecutionNoOpCache) Get(ctx context.Context, key cache.Keyer) (result execution.Result, found bool, err error) { return execution.Result{}, false, nil } -func (ExecutionNoOpCache) Set(ctx context.Context, key CacheKeyer, result execution.Result) error { +func (ExecutionNoOpCache) Set(ctx context.Context, key cache.Keyer, result execution.Result) error { return nil } -func (ExecutionNoOpCache) Clear(ctx context.Context, key CacheKeyer) error { +func (ExecutionNoOpCache) Clear(ctx context.Context, key cache.Keyer) error { return nil } -func (ExecutionNoOpCache) SetStepResult(ctx context.Context, key CacheKeyer, result execution.AfterStepResult) error { +func (ExecutionNoOpCache) SetStepResult(ctx context.Context, key cache.Keyer, result execution.AfterStepResult) error { return nil } -func (ExecutionNoOpCache) GetStepResult(ctx context.Context, key CacheKeyer) (execution.AfterStepResult, bool, error) { +func (ExecutionNoOpCache) GetStepResult(ctx context.Context, key cache.Keyer) (execution.AfterStepResult, bool, error) { return execution.AfterStepResult{}, false, nil } @@ -301,12 +161,12 @@ type JSONLinesCache struct { Writer JSONCacheWriter } -func (c *JSONLinesCache) Get(ctx context.Context, key CacheKeyer) (result execution.Result, found bool, err error) { +func (c *JSONLinesCache) Get(ctx context.Context, key cache.Keyer) (result execution.Result, found bool, err error) { // noop return execution.Result{}, false, nil } -func (c *JSONLinesCache) Set(ctx context.Context, key CacheKeyer, result execution.Result) error { +func (c *JSONLinesCache) Set(ctx context.Context, key cache.Keyer, result execution.Result) error { k, err := key.Key() if err != nil { return err @@ -317,7 +177,7 @@ func (c *JSONLinesCache) Set(ctx context.Context, key CacheKeyer, result executi return nil } -func (c *JSONLinesCache) SetStepResult(ctx context.Context, key CacheKeyer, result execution.AfterStepResult) error { +func (c *JSONLinesCache) SetStepResult(ctx context.Context, key cache.Keyer, result execution.AfterStepResult) error { k, err := key.Key() if err != nil { return err @@ -328,12 +188,12 @@ func (c *JSONLinesCache) SetStepResult(ctx context.Context, key CacheKeyer, resu return nil } -func (c *JSONLinesCache) GetStepResult(ctx context.Context, key CacheKeyer) (result execution.AfterStepResult, found bool, err error) { +func (c *JSONLinesCache) GetStepResult(ctx context.Context, key cache.Keyer) (result execution.AfterStepResult, found bool, err error) { // noop return execution.AfterStepResult{}, false, nil } -func (c *JSONLinesCache) Clear(ctx context.Context, key CacheKeyer) error { +func (c *JSONLinesCache) Clear(ctx context.Context, key cache.Keyer) error { // noop return nil } diff --git a/internal/batches/executor/execution_cache_test.go b/internal/batches/executor/execution_cache_test.go index 6bf0de5ea6..e90e179776 100644 --- a/internal/batches/executor/execution_cache_test.go +++ b/internal/batches/executor/execution_cache_test.go @@ -6,94 +6,28 @@ import ( "testing" "github.com/google/go-cmp/cmp" - "gopkg.in/yaml.v3" + "github.com/sourcegraph/sourcegraph/lib/batches" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/execution" + "github.com/sourcegraph/sourcegraph/lib/batches/execution/cache" "github.com/sourcegraph/sourcegraph/lib/batches/git" ) -const testExecutionCacheKeyEnv = "TEST_EXECUTION_CACHE_KEY_ENV" - -func TestTaskCacheKey(t *testing.T) { - // Let's set up an array of steps that we can test with. One step will - // depend on an environment variable outside the spec. - var steps []batcheslib.Step - if err := yaml.Unmarshal([]byte(` -- run: foo - env: - FOO: BAR - -- run: bar - env: - - FOO: BAR - - `+testExecutionCacheKeyEnv+` -`), &steps); err != nil { - t.Fatal(err) - } - - // And now we can set up a key to work with. - key := TaskCacheKey{&Task{ - Repository: testRepo1, - Steps: steps, - }} - - // All righty. Let's get ourselves a baseline cache key here. - initial, err := key.Key() - if err != nil { - t.Errorf("unexpected error: %v", err) - } - - // Let's set an unrelated environment variable and ensure we still have the - // same key. - if err := os.Setenv(testExecutionCacheKeyEnv+"_UNRELATED", "foo"); err != nil { - t.Fatal(err) - } - have, err := key.Key() - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if initial != have { - t.Errorf("unexpected change in key: initial=%q have=%q", initial, have) - } - - // Let's now set the environment variable referenced in the steps and verify - // that the cache key does change. - if err := os.Setenv(testExecutionCacheKeyEnv, "foo"); err != nil { - t.Fatal(err) - } - have, err = key.Key() - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if initial == have { - t.Errorf("unexpected lack of change in key: %q", have) - } - - // And, just to be sure, let's change it again. - if err := os.Setenv(testExecutionCacheKeyEnv, "bar"); err != nil { - t.Fatal(err) - } - again, err := key.Key() - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if initial == again || have == again { - t.Errorf("unexpected lack of change in key: %q", again) - } +var cacheRepo1 = batches.Repository{ + ID: "src-cli", + Name: "github.com/sourcegraph/src-cli", + BaseRef: "refs/heads/main", + BaseRev: "d34db33f", + FileMatches: []string{"README.md", "main.go"}, +} - // Finally, if we unset the environment variable again, we should get a key - // that matches the initial key. - if err := os.Unsetenv(testExecutionCacheKeyEnv); err != nil { - t.Fatal(err) - } - have, err = key.Key() - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if initial != have { - t.Errorf("unexpected change in key: initial=%q have=%q", initial, have) - } +var cacheRepo2 = batches.Repository{ + ID: "sourcegraph", + Name: "github.com/sourcegraph/sourcegraph", + BaseRef: "refs/heads/main-2", + BaseRev: "c0ff33", + FileMatches: []string{"main.go"}, } const testDiff = `diff --git a/README.md b/README.md @@ -120,19 +54,19 @@ func TestExecutionDiskCache_GetSet(t *testing.T) { return testTempDir } - cacheKey1 := TaskCacheKey{Task: &Task{ - Repository: testRepo1, + cacheKey1 := &cache.ExecutionKey{ + Repository: cacheRepo1, Steps: []batcheslib.Step{ {Run: "echo 'Hello World'", Container: "alpine:3"}, }, - }} + } - cacheKey2 := TaskCacheKey{Task: &Task{ - Repository: testRepo2, + cacheKey2 := &cache.ExecutionKey{ + Repository: cacheRepo2, Steps: []batcheslib.Step{ {Run: "echo 'Hello World'", Container: "alpine:3"}, }, - }} + } value := execution.Result{ Diff: testDiff, @@ -166,7 +100,7 @@ func TestExecutionDiskCache_GetSet(t *testing.T) { assertCacheMiss(t, cache, cacheKey1) } -func assertCacheHit(t *testing.T, c ExecutionDiskCache, k TaskCacheKey, want execution.Result) { +func assertCacheHit(t *testing.T, c ExecutionDiskCache, k *cache.ExecutionKey, want execution.Result) { t.Helper() have, found, err := c.Get(context.Background(), k) @@ -182,7 +116,7 @@ func assertCacheHit(t *testing.T, c ExecutionDiskCache, k TaskCacheKey, want exe } } -func assertCacheMiss(t *testing.T, c ExecutionDiskCache, k TaskCacheKey) { +func assertCacheMiss(t *testing.T, c ExecutionDiskCache, k *cache.ExecutionKey) { t.Helper() _, found, err := c.Get(context.Background(), k) diff --git a/internal/batches/executor/task.go b/internal/batches/executor/task.go index 95b58745ce..d439ec971b 100644 --- a/internal/batches/executor/task.go +++ b/internal/batches/executor/task.go @@ -3,6 +3,7 @@ package executor import ( batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/execution" + "github.com/sourcegraph/sourcegraph/lib/batches/execution/cache" "github.com/sourcegraph/sourcegraph/lib/batches/template" "github.com/sourcegraph/src-cli/internal/batches/graphql" @@ -42,6 +43,18 @@ func (t *Task) ArchivePathToFetch() string { return "" } -func (t *Task) cacheKey() TaskCacheKey { - return TaskCacheKey{t} +func (t *Task) cacheKey() *cache.ExecutionKey { + return &cache.ExecutionKey{ + Repository: batcheslib.Repository{ + ID: t.Repository.ID, + Name: t.Repository.Name, + BaseRef: t.Repository.BaseRef(), + BaseRev: t.Repository.Rev(), + FileMatches: t.Repository.SortedFileMatches(), + }, + Path: t.Path, + OnlyFetchWorkspace: t.OnlyFetchWorkspace, + Steps: t.Steps, + BatchChangeAttributes: t.BatchChangeAttributes, + } } From bd77e8c2490822e9266ed0dbe578d764799e73b0 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Wed, 10 Nov 2021 11:02:26 +0100 Subject: [PATCH 081/647] Refactor caching and coordinator (#651) --- cmd/src/batch_common.go | 52 +++++--- cmd/src/batch_exec.go | 23 ++-- go.mod | 18 +-- go.sum | 55 +++++---- internal/batches/executor/coordinator.go | 111 ++++++------------ internal/batches/executor/coordinator_test.go | 68 ++--------- internal/batches/service/service.go | 21 +++- 7 files changed, 157 insertions(+), 191 deletions(-) diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index 378db8e077..9f47520ca3 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -292,29 +292,46 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp // EXECUTION OF TASKS coord := svc.NewCoordinator(executor.NewCoordinatorOpts{ - Creator: workspaceCreator, - CacheDir: opts.flags.cacheDir, - Cache: executor.NewDiskCache(opts.flags.cacheDir), - ClearCache: opts.flags.clearCache, - SkipErrors: opts.flags.skipErrors, - CleanArchives: opts.flags.cleanArchives, - Parallelism: opts.flags.parallelism, - Timeout: opts.flags.timeout, - KeepLogs: opts.flags.keepLogs, - TempDir: opts.flags.tempDir, - ImportChangesets: true, + Creator: workspaceCreator, + CacheDir: opts.flags.cacheDir, + Cache: executor.NewDiskCache(opts.flags.cacheDir), + SkipErrors: opts.flags.skipErrors, + CleanArchives: opts.flags.cleanArchives, + Parallelism: opts.flags.parallelism, + Timeout: opts.flags.timeout, + KeepLogs: opts.flags.keepLogs, + TempDir: opts.flags.tempDir, }) ui.CheckingCache() tasks := svc.BuildTasks(ctx, batchSpec, workspaces) - uncachedTasks, cachedSpecs, err := coord.CheckCache(ctx, tasks) - if err != nil { - return err + var ( + specs []*batcheslib.ChangesetSpec + uncachedTasks []*executor.Task + ) + if opts.flags.clearCache { + coord.ClearCache(ctx, tasks) + uncachedTasks = tasks + } else { + uncachedTasks, specs, err = coord.CheckCache(ctx, tasks) + if err != nil { + return err + } } - ui.CheckingCacheSuccess(len(cachedSpecs), len(uncachedTasks)) + ui.CheckingCacheSuccess(len(specs), len(uncachedTasks)) taskExecUI := ui.ExecutingTasks(*verbose, opts.flags.parallelism) - freshSpecs, logFiles, err := coord.Execute(ctx, uncachedTasks, batchSpec, taskExecUI) + freshSpecs, logFiles, execErr := coord.Execute(ctx, uncachedTasks, batchSpec, taskExecUI) + // Add external changeset specs. + importedSpecs, importErr := svc.CreateImportChangesetSpecs(ctx, batchSpec) + var errs *multierror.Error + if execErr != nil { + err = multierror.Append(err, execErr) + } + if importErr != nil { + err = multierror.Append(err, importErr) + } + err = errs.ErrorOrNil() if err != nil && !opts.flags.skipErrors { return err } @@ -335,7 +352,8 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp ui.LogFilesKept(logFiles) } - specs := append(cachedSpecs, freshSpecs...) + specs = append(specs, freshSpecs...) + specs = append(specs, importedSpecs...) err = svc.ValidateChangesetSpecs(repos, specs) if err != nil { diff --git a/cmd/src/batch_exec.go b/cmd/src/batch_exec.go index a4bce4416c..834a815232 100644 --- a/cmd/src/batch_exec.go +++ b/cmd/src/batch_exec.go @@ -151,24 +151,31 @@ func executeBatchSpecInWorkspaces(ctx context.Context, ui *ui.JSONLines, opts ex Creator: workspaceCreator, CacheDir: opts.flags.cacheDir, Cache: &executor.JSONLinesCache{Writer: ui}, - ClearCache: opts.flags.clearCache, SkipErrors: opts.flags.skipErrors, CleanArchives: opts.flags.cleanArchives, Parallelism: opts.flags.parallelism, Timeout: opts.flags.timeout, KeepLogs: opts.flags.keepLogs, TempDir: opts.flags.tempDir, - // Do not import changesets in `src batch exec` - ImportChangesets: false, }) ui.CheckingCache() tasks := svc.BuildTasks(ctx, batchSpec, repoWorkspaces) - uncachedTasks, cachedSpecs, err := coord.CheckCache(ctx, tasks) - if err != nil { - return err + var ( + specs []*batcheslib.ChangesetSpec + uncachedTasks []*executor.Task + ) + // TODO: We don't need to support clear cache here at all. + if opts.flags.clearCache { + coord.ClearCache(ctx, tasks) + uncachedTasks = tasks + } else { + uncachedTasks, specs, err = coord.CheckCache(ctx, tasks) + if err != nil { + return err + } } - ui.CheckingCacheSuccess(len(cachedSpecs), len(uncachedTasks)) + ui.CheckingCacheSuccess(len(specs), len(uncachedTasks)) taskExecUI := ui.ExecutingTasks(*verbose, opts.flags.parallelism) freshSpecs, _, err := coord.Execute(ctx, uncachedTasks, batchSpec, taskExecUI) @@ -185,7 +192,7 @@ func executeBatchSpecInWorkspaces(ctx context.Context, ui *ui.JSONLines, opts ex } } - specs := append(cachedSpecs, freshSpecs...) + specs = append(specs, freshSpecs...) ids := make([]graphql.ChangesetSpecID, len(specs)) diff --git a/go.mod b/go.mod index df14ebc5e4..78a8d68fd9 100644 --- a/go.mod +++ b/go.mod @@ -13,17 +13,17 @@ require ( github.com/google/go-cmp v0.5.6 github.com/hashicorp/go-multierror v1.1.1 github.com/jig/teereadcloser v0.0.0-20181016160506-953720c48e05 - github.com/json-iterator/go v1.1.11 + github.com/json-iterator/go v1.1.12 github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 - github.com/mattn/go-isatty v0.0.12 + github.com/mattn/go-isatty v0.0.14 github.com/neelance/parallel v0.0.0-20160708114440-4de9ce63d14c github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4 github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf - github.com/sourcegraph/sourcegraph/lib v0.0.0-20211104160022-5499420c85c9 + github.com/sourcegraph/sourcegraph/lib v0.0.0-20211109155204-31a95b8405e0 github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect - golang.org/x/net v0.0.0-20210614182718-04defd469f4e + golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7 ) @@ -35,21 +35,21 @@ require ( github.com/ghodss/yaml v1.0.0 // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/hashicorp/errwrap v1.1.0 // indirect - github.com/klauspost/compress v1.12.2 // indirect + github.com/klauspost/compress v1.13.6 // indirect github.com/klauspost/pgzip v1.2.5 // indirect github.com/kr/pretty v0.3.0 // indirect github.com/kr/text v0.2.0 // indirect - github.com/mattn/go-runewidth v0.0.12 // indirect + github.com/mattn/go-runewidth v0.0.13 // indirect github.com/moby/term v0.0.0-20210619224110-3f7ff695adc6 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect - github.com/modern-go/reflect2 v1.0.1 // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect github.com/olekukonko/tablewriter v0.0.5 // indirect github.com/pkg/errors v0.9.1 // indirect - github.com/rivo/uniseg v0.1.0 // indirect + github.com/rivo/uniseg v0.2.0 // indirect github.com/rogpeppe/go-internal v1.8.0 // indirect github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect github.com/xeipuuv/gojsonschema v1.2.0 // indirect - golang.org/x/sys v0.0.0-20210616094352-59db8d763f22 // indirect + golang.org/x/sys v0.0.0-20211109065445-02f5c0300f6e // indirect golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect ) diff --git a/go.sum b/go.sum index 27a4ef1523..8b06310922 100644 --- a/go.sum +++ b/go.sum @@ -14,6 +14,7 @@ github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY github.com/alecthomas/kingpin v2.2.6+incompatible/go.mod h1:59OFYbFVLKQKq+mqrL6Rw5bR0c3ACQaawgXx0QYndlE= github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/units v0.0.0-20210208195552-ff826a37aa15/go.mod h1:OMCwj8VM1Kc9e19TLln2VL61YJF0x1XFtfdL4JdbSyE= +github.com/alecthomas/units v0.0.0-20210927113745-59d0afb8317a/go.mod h1:OMCwj8VM1Kc9e19TLln2VL61YJF0x1XFtfdL4JdbSyE= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= github.com/aymerick/raymond v2.0.3-0.20180322193309-b565731e1464+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= @@ -53,7 +54,6 @@ github.com/dineshappavoo/basex v0.0.0-20170425072625-481a6f6dc663 h1:fctNkSsavbX github.com/dineshappavoo/basex v0.0.0-20170425072625-481a6f6dc663/go.mod h1:Kad2hux31v/IyD4Rf4wAwIyK48995rs3qAl9IUAhc2k= github.com/dustin/go-humanize v1.0.0 h1:VSnTsYCnlFHaM2/igO1h6X3HA71jcobQuxemgkq4zYo= github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= -github.com/efritz/pentimento v0.0.0-20190429011147-ade47d831101/go.mod h1:5ALWO82UZwfAtNRUtwzsWimcrcuYzyieTyyXOXrP6EQ= github.com/eknkc/amber v0.0.0-20171010120322-cdade1c07385/go.mod h1:0vRUJqYpeSZifjYj7uP3BG/gKcuzL9xWVV/Y+cK33KM= github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= @@ -62,7 +62,7 @@ github.com/envoyproxy/go-control-plane v0.9.9-0.20210217033140-668b12f5399d/go.m github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/etcd-io/bbolt v1.3.3/go.mod h1:ZF2nL25h33cCyBtcyWeZ2/I3HQOfTP+0PIEvHjkjCrw= github.com/fasthttp-contrib/websocket v0.0.0-20160511215533-1f3b11f56072/go.mod h1:duJ4Jxv5lDcvg4QuQr0oowTf7dz4/CR8NtyCooz9HL8= -github.com/fatih/color v1.11.0/go.mod h1:ELkj/draVOlAH/xkhN6mQ50Qd0MPOk5AAr3maGEBuJM= +github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M= github.com/flosch/pongo2 v0.0.0-20190707114632-bbf5a6c351f4/go.mod h1:T9YF2M40nIgbVgp3rreNmTged+9HrbNTIQf1PsaIiTA= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= @@ -74,7 +74,7 @@ github.com/go-check/check v0.0.0-20180628173108-788fd7840127/go.mod h1:9ES+weclK github.com/go-errors/errors v1.0.1 h1:LUHzmkK3GUKUrL/1gfBUxAHzcev3apQlezX/+O7ma6w= github.com/go-errors/errors v1.0.1/go.mod h1:f4zRHt4oKfwPJE5k8C9vpYG+aDHdBFUsgrm6/TyX73Q= github.com/go-martini/martini v0.0.0-20170121215854-22fa46961aab/go.mod h1:/P9AEU963A2AYjv4d1V5eVL1CQbEJq6aCNHDDjibzu8= -github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/go-stack/stack v1.8.1/go.mod h1:dcoOX6HbPZSZptuspn9bctJ+N/CnF5gGygcUP3XYfe4= github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y= github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8= @@ -103,7 +103,6 @@ github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QD github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= -github.com/golang/snappy v0.0.3/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/gomodule/redigo v1.7.1-0.20190724094224-574c33c3df38/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= @@ -123,7 +122,6 @@ github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoA github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= -github.com/hashicorp/go-multierror v1.1.0/go.mod h1:spPvp8C1qA32ftKqdAHm4hHTbPw+vmowP0z+KUhOZdA= github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= github.com/hashicorp/go-version v1.2.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= @@ -145,8 +143,8 @@ github.com/iris-contrib/schema v0.0.1/go.mod h1:urYA3uvUNG1TIIjOSCzHr9/LmbQo8LrO github.com/jig/teereadcloser v0.0.0-20181016160506-953720c48e05 h1:dSwwtWuwMyarzsbVWOq4QJ8xVy9wgcNomvWyGtrKe+E= github.com/jig/teereadcloser v0.0.0-20181016160506-953720c48e05/go.mod h1:sRUFlj+HCejvoCRpuhU0EYnNw5FG+YJpz8UFfCf0F2U= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= -github.com/json-iterator/go v1.1.11 h1:uVUAXhF2To8cbw/3xN3pxj6kk7TYKs98NIrTqPlMWAQ= -github.com/json-iterator/go v1.1.11/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/juju/errors v0.0.0-20181118221551-089d3ea4e4d5/go.mod h1:W54LbzXuIE0boCoNJfwqpmkKJ1O4TCTZMetAt6jGk7Q= github.com/juju/loggo v0.0.0-20180524022052-584905176618/go.mod h1:vgyd7OREkbtVEN/8IXZe5Ooef3LQePvuBm9UWj6ZL8U= @@ -163,8 +161,8 @@ github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/klauspost/compress v1.8.2/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= github.com/klauspost/compress v1.9.0/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= -github.com/klauspost/compress v1.12.2 h1:2KCfW3I9M7nSc5wOqXAlW2v2U6v+w6cbjvbfp+OykW8= -github.com/klauspost/compress v1.12.2/go.mod h1:8dP1Hq4DHOhN9w426knH3Rhby4rFm6D8eO+e+Dq5Gzg= +github.com/klauspost/compress v1.13.6 h1:P76CopJELS0TiO2mebmnzgWaajssP/EszplttgQxcgc= +github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= github.com/klauspost/cpuid v1.2.1/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek= github.com/klauspost/pgzip v1.2.5 h1:qnWYvvKqedOF2ulHpMG72XQol4ILEJ8k2wwRl/Km8oE= github.com/klauspost/pgzip v1.2.5/go.mod h1:Ch1tH69qFZu15pkjo5kYi6mth2Zzwzt50oCQKQE9RUs= @@ -180,15 +178,17 @@ github.com/labstack/echo/v4 v4.1.11/go.mod h1:i541M3Fj6f76NZtHSj7TXnyM8n2gaodfvf github.com/labstack/gommon v0.3.0/go.mod h1:MULnywXg0yavhxWKc+lOruYdAhDwPK9wf0OL7NoOu+k= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= -github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= +github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= +github.com/mattn/go-colorable v0.1.11/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= github.com/mattn/go-isatty v0.0.7/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= github.com/mattn/go-isatty v0.0.9/go.mod h1:YNRxwqDuOph6SZLI9vUUz6OYw3QyUt7WiY2yME+cCiQ= -github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY= github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= +github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9Y= +github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= -github.com/mattn/go-runewidth v0.0.12 h1:Y41i/hVW3Pgwr8gV+J23B9YEY0zxjptBuCWEaxmAOow= -github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk= +github.com/mattn/go-runewidth v0.0.13 h1:lTGmDsbAYt5DmK6OnoV7EuIF1wEIFAcxld6ypU4OSgU= +github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= github.com/mattn/goveralls v0.0.2/go.mod h1:8d1ZMHsd7fW6IRPKQh46F2WRpyib5/X4FOpevwGNQEw= github.com/mediocregopher/mediocre-go-lib v0.0.0-20181029021733-cb65787f37ed/go.mod h1:dSsfyI2zABAdhcbvkXqgxOxrCsbYeHCPgrZkku60dSg= github.com/mediocregopher/radix/v3 v3.3.0/go.mod h1:EmfVyvspXz1uZEyPBMyGK+kjWiKQGvsUt6O3Pj+LDCQ= @@ -205,9 +205,9 @@ github.com/moby/term v0.0.0-20210619224110-3f7ff695adc6/go.mod h1:E2VnQOmVuvZB6U github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= -github.com/modern-go/reflect2 v1.0.1 h1:9f412s+6RmYXLWZSEzVVgPGK7C2PphHj5RJrvfx9AWI= github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/moul/http2curl v1.0.0/go.mod h1:8UbvGypXm98wA/IqH45anm5Y2Z6ep6O31QGOAZ3H0fQ= github.com/nats-io/nats.go v1.8.1/go.mod h1:BrFz9vVn0fU3AcH9Vn4Kd7W0NpJ651tD5omQ3M8LwxM= github.com/nats-io/nkeys v0.0.2/go.mod h1:dab7URMsZm6Z/jp9Z5UGa87Uutgc2mVpXLC4B7TDb/4= @@ -238,8 +238,8 @@ github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= -github.com/rivo/uniseg v0.1.0 h1:+2KBaVoUmb9XzDsrx/Ct0W/EYOSFf/nWTauy++DprtY= -github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= +github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY= +github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.6.2/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8= @@ -258,8 +258,8 @@ github.com/sourcegraph/go-diff v0.6.1 h1:hmA1LzxW0n1c3Q4YbrFgg4P99GSnebYa3x8gr0H github.com/sourcegraph/go-diff v0.6.1/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20211104160022-5499420c85c9 h1:b56HdWLb6D2h0D70l1fonoB4m1pItue+og8fFxTlaWc= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20211104160022-5499420c85c9/go.mod h1:oriyPo0GiQg2oIAjaKAuaNwxiuSmscMVJGfV38ONvqQ= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20211109155204-31a95b8405e0 h1:NaYWQFsArbbSysPHyPC0jChFqlrQg01pVz5ej5X393Q= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20211109155204-31a95b8405e0/go.mod h1:4WdX5odo9YL0GD0Wg9OZJJtIJIn1jIsh+UWrQ4MEcaw= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= @@ -300,9 +300,9 @@ github.com/yudai/pp v2.0.1+incompatible/go.mod h1:PuxR/8QJ7cyCkFp/aUDS+JY727OFEZ github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +github.com/yuin/goldmark v1.4.0/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20190426145343-a29dc8fdc734/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= @@ -317,6 +317,7 @@ golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -325,7 +326,6 @@ golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73r golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190327091125-710a502c58a2/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190424112056-4829fb13d2c6/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190827160401-ba9fcec4b297/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= @@ -334,8 +334,9 @@ golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/ golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk= -golang.org/x/net v0.0.0-20210614182718-04defd469f4e h1:XpT3nA5TvE525Ne3hInMh6+GETgn27Zfm9dxsThnX2Q= golang.org/x/net v0.0.0-20210614182718-04defd469f4e/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d h1:20cMwl2fHAzkJMEA+8J4JgqBQcQGzbisXo31MIeenXI= +golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -350,7 +351,6 @@ golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5h golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190428183149-804c0c7841b5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190626221950-04f50cda93cb/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -369,8 +369,12 @@ golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210611083646-a4fc73990273/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210616094352-59db8d763f22 h1:RqytpXGR1iVNX7psjB3ff8y7sNFinVFvkx1c8SjBkio= golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211109065445-02f5c0300f6e h1:i6Vklmyu+fZMFYpum+sR4ZWABGW7MyIxfJZXYvcnbns= +golang.org/x/sys v0.0.0-20211109065445-02f5c0300f6e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= @@ -385,7 +389,6 @@ golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3 golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190327201419-c70d86f8b7cf/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190428024724-550556f78a90/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190624222133-a101b041ded4/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= @@ -397,6 +400,7 @@ golang.org/x/tools v0.0.0-20210101214203-2dba1e4ea05c/go.mod h1:emZCQorbCU4vsT4f golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/tools v0.1.7/go.mod h1:LGqMHiF4EqQNHR1JncWGqT5BVaXmza+X+BDGol+dOxo= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -453,3 +457,4 @@ jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7 h1:mub0MmFLOn8XLikZOA jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7/go.mod h1:OxvTsCwKosqQ1q7B+8FwXqg4rKZ/UG9dUW+g/VL2xH4= mvdan.cc/gofumpt v0.0.0-20210107193838-d24d34e18d44/go.mod h1:yXG1r1WqZVKWbVRtBWKWX9+CxGYfA51nSomhM0woR48= mvdan.cc/gofumpt v0.1.0/go.mod h1:yXG1r1WqZVKWbVRtBWKWX9+CxGYfA51nSomhM0woR48= +mvdan.cc/gofumpt v0.1.1/go.mod h1:yXG1r1WqZVKWbVRtBWKWX9+CxGYfA51nSomhM0woR48= diff --git a/internal/batches/executor/coordinator.go b/internal/batches/executor/coordinator.go index 7ab05fc304..77412943bf 100644 --- a/internal/batches/executor/coordinator.go +++ b/internal/batches/executor/coordinator.go @@ -11,10 +11,8 @@ import ( "github.com/sourcegraph/sourcegraph/lib/batches/execution" "github.com/sourcegraph/sourcegraph/lib/batches/execution/cache" - "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/docker" - "github.com/sourcegraph/src-cli/internal/batches/graphql" "github.com/sourcegraph/src-cli/internal/batches/log" "github.com/sourcegraph/src-cli/internal/batches/repozip" "github.com/sourcegraph/src-cli/internal/batches/workspace" @@ -36,32 +34,25 @@ type Coordinator struct { logManager log.LogManager } -type repoNameResolver func(ctx context.Context, name string) (*graphql.Repository, error) type imageEnsurer func(ctx context.Context, name string) (docker.Image, error) type NewCoordinatorOpts struct { // Dependencies - ResolveRepoName repoNameResolver - EnsureImage imageEnsurer - Creator workspace.Creator - Client api.Client - Cache cache.Cache + EnsureImage imageEnsurer + Creator workspace.Creator + Cache cache.Cache + RepoArchiveRegistry repozip.ArchiveRegistry // Everything that follows are either command-line flags or features. // TODO: We could probably have a wrapper around flags and features, // something like ExecutionArgs, that we can pass around CacheDir string - ClearCache bool SkipErrors bool // Used by batcheslib.BuildChangesetSpecs Features batches.FeatureFlags - // When using `src batch exec` in SSBC we don't want to evaluate the - // `importChangesets`. - ImportChangesets bool - CleanArchives bool Parallelism int Timeout time.Duration @@ -73,7 +64,7 @@ func NewCoordinator(opts NewCoordinatorOpts) *Coordinator { logManager := log.NewManager(opts.TempDir, opts.KeepLogs) exec := newExecutor(newExecutorOpts{ - RepoArchiveRegistry: repozip.NewArchiveRegistry(opts.Client, opts.CacheDir, opts.CleanArchives), + RepoArchiveRegistry: opts.RepoArchiveRegistry, EnsureImage: opts.EnsureImage, Creator: opts.Creator, Logger: logManager, @@ -112,16 +103,26 @@ func (c *Coordinator) CheckCache(ctx context.Context, tasks []*Task) (uncached [ return uncached, specs, nil } -func (c *Coordinator) checkCacheForTask(ctx context.Context, task *Task) (specs []*batcheslib.ChangesetSpec, found bool, err error) { - // Check if the task is cached. - cacheKey := task.cacheKey() - if c.opts.ClearCache { +func (c *Coordinator) ClearCache(ctx context.Context, tasks []*Task) error { + for _, task := range tasks { + cacheKey := task.cacheKey() if err := c.cache.Clear(ctx, cacheKey); err != nil { - return specs, false, errors.Wrapf(err, "clearing cache for %q", task.Repository.Name) + return errors.Wrapf(err, "clearing cache for %q", task.Repository.Name) } + for i := len(task.Steps) - 1; i > -1; i-- { + key := cache.StepsCacheKey{ExecutionKey: task.cacheKey(), StepIndex: i} - return specs, false, nil + if err := c.cache.Clear(ctx, key); err != nil { + return errors.Wrapf(err, "clearing cache for step %d in %q", i, task.Repository.Name) + } + } } + return nil +} + +func (c *Coordinator) checkCacheForTask(ctx context.Context, task *Task) (specs []*batcheslib.ChangesetSpec, found bool, err error) { + // Check if the task is cached. + cacheKey := task.cacheKey() var result execution.Result result, found, err = c.cache.Get(ctx, cacheKey) @@ -130,6 +131,12 @@ func (c *Coordinator) checkCacheForTask(ctx context.Context, task *Task) (specs } if !found { + // If we are here, that means we didn't find anything in the cache for the + // complete task. So, what if we have cached results for the steps? + if err := c.loadCachedStepResults(ctx, task); err != nil { + return specs, false, err + } + return specs, false, nil } @@ -177,30 +184,22 @@ func (c Coordinator) buildChangesetSpecs(task *Task, result execution.Result) ([ }) } -func (c *Coordinator) setCachedStepResults(ctx context.Context, task *Task) error { +func (c *Coordinator) loadCachedStepResults(ctx context.Context, task *Task) error { // We start at the back so that we can find the _last_ cached step, // then restart execution on the following step. for i := len(task.Steps) - 1; i > -1; i-- { key := cache.StepsCacheKey{ExecutionKey: task.cacheKey(), StepIndex: i} - // If we need to clear the cache, we optimistically try this for every - // step. - if c.opts.ClearCache { - if err := c.cache.Clear(ctx, key); err != nil { - return errors.Wrapf(err, "clearing cache for step %d in %q", i, task.Repository.Name) - } - } else { - result, found, err := c.cache.GetStepResult(ctx, key) - if err != nil { - return errors.Wrapf(err, "checking for cached diff for step %d", i) - } + result, found, err := c.cache.GetStepResult(ctx, key) + if err != nil { + return errors.Wrapf(err, "checking for cached diff for step %d", i) + } - // Found a cached result, we're done - if found { - task.CachedResultFound = true - task.CachedResult = result - return nil - } + // Found a cached result, we're done + if found { + task.CachedResultFound = true + task.CachedResult = result + return nil } } @@ -250,14 +249,6 @@ func (c *Coordinator) Execute(ctx context.Context, tasks []*Task, spec *batchesl errs *multierror.Error ) - // If we are here, that means we didn't find anything in the cache for the - // complete task. So, what if we have cached results for the steps? - for _, t := range tasks { - if err := c.setCachedStepResults(ctx, t); err != nil { - return nil, nil, err - } - } - ui.Start(tasks) // Run executor @@ -281,33 +272,5 @@ func (c *Coordinator) Execute(ctx context.Context, tasks []*Task, spec *batchesl specs = append(specs, taskSpecs...) } - // Add external changeset specs. - if c.opts.ImportChangesets { - for _, ic := range spec.ImportChangesets { - repo, err := c.opts.ResolveRepoName(ctx, ic.Repository) - if err != nil { - wrapped := errors.Wrapf(err, "resolving repository name %q", ic.Repository) - if c.opts.SkipErrors { - errs = multierror.Append(errs, wrapped) - continue - } else { - return nil, nil, wrapped - } - } - - for _, id := range ic.ExternalIDs { - sid, err := batcheslib.ParseChangesetSpecExternalID(id) - if err != nil { - return nil, nil, err - } - - specs = append(specs, &batcheslib.ChangesetSpec{ - BaseRepository: repo.ID, - ExternalID: sid, - }) - } - } - } - return specs, c.logManager.LogFiles(), errs.ErrorOrNil() } diff --git a/internal/batches/executor/coordinator_test.go b/internal/batches/executor/coordinator_test.go index 2cac0e1e8c..4b9ca5e752 100644 --- a/internal/batches/executor/coordinator_test.go +++ b/internal/batches/executor/coordinator_test.go @@ -351,60 +351,6 @@ func TestCoordinator_Execute(t *testing.T) { } } -func TestCoordinator_Execute_ImportChangesets(t *testing.T) { - - logManager := mock.LogNoOpManager{} - ui := newDummyTaskExecutionUI() - cache := newInMemoryExecutionCache() - - repoName := "github.com/testing/test-repo" - repoID := "graphql-id:999" - - repoNameResolver := func(ctx context.Context, name string) (*graphql.Repository, error) { - if name != repoName { - t.Fatalf("wrong repo name: %s", name) - } - return &graphql.Repository{ID: repoID, Name: repoName}, nil - } - - opts := NewCoordinatorOpts{Features: featuresAllEnabled(), ResolveRepoName: repoNameResolver} - - batchSpec := &batcheslib.BatchSpec{ - Name: "my-batch-change", - Description: "the description", - ChangesetTemplate: testChangesetTemplate, - ImportChangesets: []batcheslib.ImportChangeset{ - {Repository: repoName, ExternalIDs: []interface{}{500, 600, 700}}, - }, - } - - t.Run("importChangesets:true", func(t *testing.T) { - opts.ImportChangesets = true - coord := Coordinator{cache: cache, exec: &dummyExecutor{}, logManager: logManager, opts: opts} - - specs, _, err := coord.Execute(context.Background(), []*Task{}, batchSpec, ui) - if err != nil { - t.Fatalf("unexpected error: %s", err) - } - if len(specs) != len(batchSpec.ImportChangesets[0].ExternalIDs) { - t.Fatalf("wrong number of imported changesets: %d", len(specs)) - } - }) - - t.Run("importChangesets:false", func(t *testing.T) { - opts.ImportChangesets = false - coord := Coordinator{cache: cache, exec: &dummyExecutor{}, logManager: logManager, opts: opts} - - specs, _, err := coord.Execute(context.Background(), []*Task{}, batchSpec, ui) - if err != nil { - t.Fatalf("unexpected error: %s", err) - } - if len(specs) != 0 { - t.Fatalf("wrong number of imported changesets: %d", len(specs)) - } - }) -} - func TestCoordinator_Execute_StepCaching(t *testing.T) { // Setup dependencies cache := newInMemoryExecutionCache() @@ -475,7 +421,9 @@ func TestCoordinator_Execute_StepCaching(t *testing.T) { task.CachedResultFound = false // Now we execute the spec with -clear-cache: - coord.opts.ClearCache = true + if err := coord.ClearCache(context.Background(), []*Task{task}); err != nil { + t.Fatal(err) + } // We don't want any cached results set on the task: execAndEnsure(t, coord, executor, task, assertNoCachedResult(t)) // Cache should have the same number of entries: the cached step results should @@ -496,12 +444,20 @@ func execAndEnsure(t *testing.T, coord *Coordinator, exec *dummyExecutor, task * // Setup the callback exec.startCb = cb + // Check cache + uncached, cachedSpecs, err := coord.CheckCache(context.Background(), []*Task{task}) + if err != nil { + t.Fatal(err) + } + // Execute - specs, _, err := coord.Execute(context.Background(), []*Task{task}, batchSpec, newDummyTaskExecutionUI()) + freshSpecs, _, err := coord.Execute(context.Background(), uncached, batchSpec, newDummyTaskExecutionUI()) if err != nil { t.Fatalf("execution of task failed: %s", err) } + specs := append(cachedSpecs, freshSpecs...) + // Sanity check, because we're not interested in the specs if have, want := len(specs), 1; have != want { t.Fatalf("Wrong number of specs. want=%d, have=%d", want, have) diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index fa6fb99fe8..f75495d80d 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -12,6 +12,7 @@ import ( "strings" "github.com/cockroachdb/errors" + "github.com/hashicorp/go-multierror" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" @@ -20,6 +21,7 @@ import ( "github.com/sourcegraph/src-cli/internal/batches/docker" "github.com/sourcegraph/src-cli/internal/batches/executor" "github.com/sourcegraph/src-cli/internal/batches/graphql" + "github.com/sourcegraph/src-cli/internal/batches/repozip" ) type Service struct { @@ -199,14 +201,29 @@ func (svc *Service) BuildTasks(ctx context.Context, spec *batcheslib.BatchSpec, } func (svc *Service) NewCoordinator(opts executor.NewCoordinatorOpts) *executor.Coordinator { - opts.ResolveRepoName = svc.resolveRepositoryName - opts.Client = svc.client + opts.RepoArchiveRegistry = repozip.NewArchiveRegistry(svc.client, opts.CacheDir, opts.CleanArchives) opts.Features = svc.features opts.EnsureImage = svc.EnsureImage return executor.NewCoordinator(opts) } +func (svc *Service) CreateImportChangesetSpecs(ctx context.Context, batchSpec *batcheslib.BatchSpec) ([]*batcheslib.ChangesetSpec, error) { + return batcheslib.BuildImportChangesetSpecs(ctx, batchSpec.ImportChangesets, func(ctx context.Context, repoNames []string) (_ map[string]string, errs error) { + repoNameIDs := map[string]string{} + for _, name := range repoNames { + repo, err := svc.resolveRepositoryName(ctx, name) + if err != nil { + wrapped := errors.Wrapf(err, "resolving repository name %q", name) + errs = multierror.Append(errs, wrapped) + continue + } + repoNameIDs[name] = repo.ID + } + return repoNameIDs, errs + }) +} + // ValidateChangesetSpecs validates that among all branch changesets there are no // duplicates in branch names in a single repo. func (svc *Service) ValidateChangesetSpecs(repos []*graphql.Repository, specs []*batcheslib.ChangesetSpec) error { From 161527fa1f3e8b8595305a45f583afc45e3e35cc Mon Sep 17 00:00:00 2001 From: Thorsten Ball Date: Thu, 11 Nov 2021 02:22:56 +0100 Subject: [PATCH 082/647] Simplify caching logic in 'src batch exec' (#653) This is part of https://github.com/sourcegraph/sourcegraph/issues/26929 and simplifies the caching-related logic in `src batch exec` to only what's needed: checking for per-step cache results. Since server-side batch changes use server-side caching for changeset specs we don't need to check for changeset specs. --- cmd/src/batch_exec.go | 25 ++++++------------------ internal/batches/executor/coordinator.go | 11 +++++++++++ 2 files changed, 17 insertions(+), 19 deletions(-) diff --git a/cmd/src/batch_exec.go b/cmd/src/batch_exec.go index 834a815232..83aa831664 100644 --- a/cmd/src/batch_exec.go +++ b/cmd/src/batch_exec.go @@ -159,26 +159,16 @@ func executeBatchSpecInWorkspaces(ctx context.Context, ui *ui.JSONLines, opts ex TempDir: opts.flags.tempDir, }) - ui.CheckingCache() + // `src batch exec` uses server-side caching for changeset specs, so we + // only need to call `CheckStepResultsCache` to make sure that per-step cache entries + // are loaded and set on the tasks. tasks := svc.BuildTasks(ctx, batchSpec, repoWorkspaces) - var ( - specs []*batcheslib.ChangesetSpec - uncachedTasks []*executor.Task - ) - // TODO: We don't need to support clear cache here at all. - if opts.flags.clearCache { - coord.ClearCache(ctx, tasks) - uncachedTasks = tasks - } else { - uncachedTasks, specs, err = coord.CheckCache(ctx, tasks) - if err != nil { - return err - } + if err := coord.CheckStepResultsCache(ctx, tasks); err != nil { + return err } - ui.CheckingCacheSuccess(len(specs), len(uncachedTasks)) taskExecUI := ui.ExecutingTasks(*verbose, opts.flags.parallelism) - freshSpecs, _, err := coord.Execute(ctx, uncachedTasks, batchSpec, taskExecUI) + specs, _, err := coord.Execute(ctx, tasks, batchSpec, taskExecUI) if err == nil || opts.flags.skipErrors { if err == nil { taskExecUI.Success() @@ -191,9 +181,6 @@ func executeBatchSpecInWorkspaces(ctx context.Context, ui *ui.JSONLines, opts ex return err } } - - specs = append(specs, freshSpecs...) - ids := make([]graphql.ChangesetSpecID, len(specs)) ui.UploadingChangesetSpecs(len(specs)) diff --git a/internal/batches/executor/coordinator.go b/internal/batches/executor/coordinator.go index 77412943bf..92f38403ac 100644 --- a/internal/batches/executor/coordinator.go +++ b/internal/batches/executor/coordinator.go @@ -103,6 +103,17 @@ func (c *Coordinator) CheckCache(ctx context.Context, tasks []*Task) (uncached [ return uncached, specs, nil } +// CheckStepResultsCache checks the cache for each Task, but only for cached +// step results. This is used by `src batch exec` when executing server-side. +func (c *Coordinator) CheckStepResultsCache(ctx context.Context, tasks []*Task) error { + for _, t := range tasks { + if err := c.loadCachedStepResults(ctx, t); err != nil { + return err + } + } + return nil +} + func (c *Coordinator) ClearCache(ctx context.Context, tasks []*Task) error { for _, task := range tasks { cacheKey := task.cacheKey() From fed3974e5b49e5d2d5fcac55a3f9d74c6d7557cd Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Thu, 11 Nov 2021 02:23:25 +0100 Subject: [PATCH 083/647] Update golang:1.17-alpine Docker digest to 102bca9 (#652) Co-authored-by: Renovate Bot --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index 7390b2f802..e71d2492f9 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,7 +4,7 @@ # # Nothing fancy here: we copy in the source code and build on the Alpine Go # image. Refer to .dockerignore to get a sense of what we're not going to copy. -FROM golang:1.17-alpine@sha256:5519c8752f6b53fc8818dc46e9fda628c99c4e8fd2d2f1df71e1f184e71f47dc as builder +FROM golang:1.17-alpine@sha256:102bca942e79a30dd6e9060f780ec3bd224eba2cf6245eadf3411c4699253d50 as builder COPY . /src WORKDIR /src From c283f589e6d426caa38fccb7db11c2361647970a Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Thu, 11 Nov 2021 02:24:48 +0100 Subject: [PATCH 084/647] Prepare changelog for 3.33.6 --- CHANGELOG.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 55387f253f..0df150bf23 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,14 +13,18 @@ All notable changes to `src-cli` are documented in this file. ### Added -- Requests to Sourcegraph will now include the operating system and architecture `src` is running on by default. To disable this, set the `SRC_DISABLE_USER_AGENT_TELEMETRY` environment variable to any non-empty string, or provide the `-user-agent-telemetry=false` flag on the command line. [#15769](https://github.com/sourcegraph/sourcegraph/issues/15769) - ### Changed ### Fixed ### Removed +## 3.33.6 + +### Added + +- Requests to Sourcegraph will now include the operating system and architecture `src` is running on by default. To disable this, set the `SRC_DISABLE_USER_AGENT_TELEMETRY` environment variable to any non-empty string, or provide the `-user-agent-telemetry=false` flag on the command line. [#15769](https://github.com/sourcegraph/sourcegraph/issues/15769) + ## 3.33.5 ### Fixed From e00e13884fc4a97bbe1161ad7c19c1f737c690d1 Mon Sep 17 00:00:00 2001 From: Thorsten Ball Date: Thu, 11 Nov 2021 15:10:31 +0100 Subject: [PATCH 085/647] Make access of global env explicit when building cache keys (#654) --- go.mod | 2 +- go.sum | 4 +++ internal/batches/executor/coordinator.go | 30 ++++++++++--------- internal/batches/executor/task.go | 37 ++++++++++++++++-------- 4 files changed, 47 insertions(+), 26 deletions(-) diff --git a/go.mod b/go.mod index 78a8d68fd9..045f581151 100644 --- a/go.mod +++ b/go.mod @@ -20,7 +20,7 @@ require ( github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4 github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf - github.com/sourcegraph/sourcegraph/lib v0.0.0-20211109155204-31a95b8405e0 + github.com/sourcegraph/sourcegraph/lib v0.0.0-20211111140427-2e938231dac5 github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d diff --git a/go.sum b/go.sum index 8b06310922..6eab6b462f 100644 --- a/go.sum +++ b/go.sum @@ -260,6 +260,10 @@ github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWii github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= github.com/sourcegraph/sourcegraph/lib v0.0.0-20211109155204-31a95b8405e0 h1:NaYWQFsArbbSysPHyPC0jChFqlrQg01pVz5ej5X393Q= github.com/sourcegraph/sourcegraph/lib v0.0.0-20211109155204-31a95b8405e0/go.mod h1:4WdX5odo9YL0GD0Wg9OZJJtIJIn1jIsh+UWrQ4MEcaw= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20211111132504-9eca3a9ea27b h1:MIeeeFbOmIbjpLEcc5KYfs6tsCBecwFuZWxV8Om+PFw= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20211111132504-9eca3a9ea27b/go.mod h1:4WdX5odo9YL0GD0Wg9OZJJtIJIn1jIsh+UWrQ4MEcaw= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20211111140427-2e938231dac5 h1:Ome/BYdr0lrwMCPseJUYI0uzv45TVVnfPJ5/DP367wg= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20211111140427-2e938231dac5/go.mod h1:4WdX5odo9YL0GD0Wg9OZJJtIJIn1jIsh+UWrQ4MEcaw= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= diff --git a/internal/batches/executor/coordinator.go b/internal/batches/executor/coordinator.go index 92f38403ac..66e4731c58 100644 --- a/internal/batches/executor/coordinator.go +++ b/internal/batches/executor/coordinator.go @@ -2,6 +2,7 @@ package executor import ( "context" + "os" "time" "github.com/cockroachdb/errors" @@ -106,8 +107,9 @@ func (c *Coordinator) CheckCache(ctx context.Context, tasks []*Task) (uncached [ // CheckStepResultsCache checks the cache for each Task, but only for cached // step results. This is used by `src batch exec` when executing server-side. func (c *Coordinator) CheckStepResultsCache(ctx context.Context, tasks []*Task) error { + globalEnv := os.Environ() for _, t := range tasks { - if err := c.loadCachedStepResults(ctx, t); err != nil { + if err := c.loadCachedStepResults(ctx, t, globalEnv); err != nil { return err } } @@ -115,14 +117,15 @@ func (c *Coordinator) CheckStepResultsCache(ctx context.Context, tasks []*Task) } func (c *Coordinator) ClearCache(ctx context.Context, tasks []*Task) error { + globalEnv := os.Environ() + for _, task := range tasks { - cacheKey := task.cacheKey() + cacheKey := task.cacheKey(globalEnv) if err := c.cache.Clear(ctx, cacheKey); err != nil { return errors.Wrapf(err, "clearing cache for %q", task.Repository.Name) } for i := len(task.Steps) - 1; i > -1; i-- { - key := cache.StepsCacheKey{ExecutionKey: task.cacheKey(), StepIndex: i} - + key := cacheKeyForStep(cacheKey, i) if err := c.cache.Clear(ctx, key); err != nil { return errors.Wrapf(err, "clearing cache for step %d in %q", i, task.Repository.Name) } @@ -132,8 +135,10 @@ func (c *Coordinator) ClearCache(ctx context.Context, tasks []*Task) error { } func (c *Coordinator) checkCacheForTask(ctx context.Context, task *Task) (specs []*batcheslib.ChangesetSpec, found bool, err error) { + globalEnv := os.Environ() + // Check if the task is cached. - cacheKey := task.cacheKey() + cacheKey := task.cacheKey(globalEnv) var result execution.Result result, found, err = c.cache.Get(ctx, cacheKey) @@ -144,7 +149,7 @@ func (c *Coordinator) checkCacheForTask(ctx context.Context, task *Task) (specs if !found { // If we are here, that means we didn't find anything in the cache for the // complete task. So, what if we have cached results for the steps? - if err := c.loadCachedStepResults(ctx, task); err != nil { + if err := c.loadCachedStepResults(ctx, task, globalEnv); err != nil { return specs, false, err } @@ -195,11 +200,12 @@ func (c Coordinator) buildChangesetSpecs(task *Task, result execution.Result) ([ }) } -func (c *Coordinator) loadCachedStepResults(ctx context.Context, task *Task) error { +func (c *Coordinator) loadCachedStepResults(ctx context.Context, task *Task, globalEnv []string) error { // We start at the back so that we can find the _last_ cached step, // then restart execution on the following step. + taskKey := task.cacheKey(globalEnv) for i := len(task.Steps) - 1; i > -1; i-- { - key := cache.StepsCacheKey{ExecutionKey: task.cacheKey(), StepIndex: i} + key := cacheKeyForStep(taskKey, i) result, found, err := c.cache.GetStepResult(ctx, key) if err != nil { @@ -219,17 +225,15 @@ func (c *Coordinator) loadCachedStepResults(ctx context.Context, task *Task) err func (c *Coordinator) cacheAndBuildSpec(ctx context.Context, taskResult taskResult, ui TaskExecutionUI) ([]*batcheslib.ChangesetSpec, error) { // Add to the cache, even if no diff was produced. - cacheKey := taskResult.task.cacheKey() + globalEnv := os.Environ() + cacheKey := taskResult.task.cacheKey(globalEnv) if err := c.cache.Set(ctx, cacheKey, taskResult.result); err != nil { return nil, errors.Wrapf(err, "caching result for %q", taskResult.task.Repository.Name) } // Save the per-step results for _, stepResult := range taskResult.stepResults { - key := cache.StepsCacheKey{ - ExecutionKey: taskResult.task.cacheKey(), - StepIndex: stepResult.StepIndex, - } + key := cacheKeyForStep(cacheKey, stepResult.StepIndex) if err := c.cache.SetStepResult(ctx, key, stepResult); err != nil { return nil, errors.Wrapf(err, "caching result for step %d in %q", stepResult.StepIndex, taskResult.task.Repository.Name) } diff --git a/internal/batches/executor/task.go b/internal/batches/executor/task.go index d439ec971b..1335b79053 100644 --- a/internal/batches/executor/task.go +++ b/internal/batches/executor/task.go @@ -43,18 +43,31 @@ func (t *Task) ArchivePathToFetch() string { return "" } -func (t *Task) cacheKey() *cache.ExecutionKey { - return &cache.ExecutionKey{ - Repository: batcheslib.Repository{ - ID: t.Repository.ID, - Name: t.Repository.Name, - BaseRef: t.Repository.BaseRef(), - BaseRev: t.Repository.Rev(), - FileMatches: t.Repository.SortedFileMatches(), +func (t *Task) cacheKey(globalEnv []string) *cache.ExecutionKeyWithGlobalEnv { + return &cache.ExecutionKeyWithGlobalEnv{ + GlobalEnv: globalEnv, + ExecutionKey: &cache.ExecutionKey{ + Repository: batcheslib.Repository{ + ID: t.Repository.ID, + Name: t.Repository.Name, + BaseRef: t.Repository.BaseRef(), + BaseRev: t.Repository.Rev(), + FileMatches: t.Repository.SortedFileMatches(), + }, + Path: t.Path, + OnlyFetchWorkspace: t.OnlyFetchWorkspace, + Steps: t.Steps, + BatchChangeAttributes: t.BatchChangeAttributes, }, - Path: t.Path, - OnlyFetchWorkspace: t.OnlyFetchWorkspace, - Steps: t.Steps, - BatchChangeAttributes: t.BatchChangeAttributes, + } +} + +func cacheKeyForStep(key *cache.ExecutionKeyWithGlobalEnv, stepIndex int) *cache.StepsCacheKeyWithGlobalEnv { + return &cache.StepsCacheKeyWithGlobalEnv{ + StepsCacheKey: &cache.StepsCacheKey{ + ExecutionKey: key.ExecutionKey, + StepIndex: stepIndex, + }, + GlobalEnv: key.GlobalEnv, } } From 5a79fa40c721ad82a1b1c7d9c5db3c5d5c34e69d Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Fri, 12 Nov 2021 15:02:50 +0100 Subject: [PATCH 086/647] Add client-only flag to src version (#655) --- CHANGELOG.md | 2 ++ cmd/src/version.go | 8 +++++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0df150bf23..3cb496db03 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,8 @@ All notable changes to `src-cli` are documented in this file. ### Added +- A `-client-only` flag has been added to `src version`. When set, only the local src-cli's version will be printed and no attempt is made to fetch the recommended version from the configured Sourcegraph server. + ### Changed ### Fixed diff --git a/cmd/src/version.go b/cmd/src/version.go index 37bdeb7bdd..c76e67b235 100644 --- a/cmd/src/version.go +++ b/cmd/src/version.go @@ -23,10 +23,16 @@ Examples: flagSet := flag.NewFlagSet("version", flag.ExitOnError) - var apiFlags = api.NewFlags(flagSet) + var ( + clientOnly = flagSet.Bool("client-only", false, "If true, only the client version will be printed.") + apiFlags = api.NewFlags(flagSet) + ) handler := func(args []string) error { fmt.Printf("Current version: %s\n", version.BuildTag) + if clientOnly != nil && *clientOnly { + return nil + } client := cfg.apiClient(apiFlags, flagSet.Output()) recommendedVersion, err := getRecommendedVersion(context.Background(), client) From 107564ef51f5a8c5219a5cef6b1be0201968d595 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Fri, 12 Nov 2021 15:05:30 +0100 Subject: [PATCH 087/647] Prepare changelog for 3.33.7 --- CHANGELOG.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3cb496db03..cc983c59c9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,14 +13,18 @@ All notable changes to `src-cli` are documented in this file. ### Added -- A `-client-only` flag has been added to `src version`. When set, only the local src-cli's version will be printed and no attempt is made to fetch the recommended version from the configured Sourcegraph server. - ### Changed ### Fixed ### Removed +## 3.33.7 + +### Added + +- A `-client-only` flag has been added to `src version`. When set, only the local src-cli's version will be printed and no attempt is made to fetch the recommended version from the configured Sourcegraph server. + ## 3.33.6 ### Added From 2fb34b6b87669518209df79fe88240e6bf21e28e Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Mon, 15 Nov 2021 11:39:10 +0100 Subject: [PATCH 088/647] Use latest lib (#657) --- cmd/src/batch_exec.go | 53 +++++++++++++++++++------------------------ go.mod | 2 +- go.sum | 8 ++----- 3 files changed, 26 insertions(+), 37 deletions(-) diff --git a/cmd/src/batch_exec.go b/cmd/src/batch_exec.go index 83aa831664..deb9ec470e 100644 --- a/cmd/src/batch_exec.go +++ b/cmd/src/batch_exec.go @@ -105,9 +105,9 @@ func executeBatchSpecInWorkspaces(ctx context.Context, ui *ui.JSONLines, opts ex return err } - // Since we already know which workspaces we want to execute the steps in, - // we can convert them to RepoWorkspaces and build tasks only for those. - repoWorkspaces := convertWorkspaces(input.Workspaces) + // Since we already know which workspace we want to execute the steps in, + // we can convert it to a RepoWorkspace and build a task only for that one. + repoWorkspace := convertWorkspace(input.Workspace) // Parse the raw batch spec contained in the input ui.ParsingBatchSpec() @@ -162,7 +162,7 @@ func executeBatchSpecInWorkspaces(ctx context.Context, ui *ui.JSONLines, opts ex // `src batch exec` uses server-side caching for changeset specs, so we // only need to call `CheckStepResultsCache` to make sure that per-step cache entries // are loaded and set on the tasks. - tasks := svc.BuildTasks(ctx, batchSpec, repoWorkspaces) + tasks := svc.BuildTasks(ctx, batchSpec, []service.RepoWorkspace{repoWorkspace}) if err := coord.CheckStepResultsCache(ctx, tasks); err != nil { return err } @@ -218,33 +218,26 @@ func loadWorkspaceExecutionInput(file string) (batcheslib.WorkspacesExecutionInp return input, nil } -func convertWorkspaces(ws []*batcheslib.Workspace) []service.RepoWorkspace { - workspaces := make([]service.RepoWorkspace, 0, len(ws)) - - for _, w := range ws { - fileMatches := make(map[string]bool) - for _, path := range w.SearchResultPaths { - fileMatches[path] = true - } - - workspaces = append(workspaces, service.RepoWorkspace{ - Repo: &graphql.Repository{ - ID: w.Repository.ID, - Name: w.Repository.Name, - Branch: graphql.Branch{ - Name: w.Branch.Name, - Target: graphql.Target{ - OID: w.Branch.Target.OID, - }, +func convertWorkspace(w batcheslib.Workspace) service.RepoWorkspace { + fileMatches := make(map[string]bool) + for _, path := range w.SearchResultPaths { + fileMatches[path] = true + } + return service.RepoWorkspace{ + Repo: &graphql.Repository{ + ID: w.Repository.ID, + Name: w.Repository.Name, + Branch: graphql.Branch{ + Name: w.Branch.Name, + Target: graphql.Target{ + OID: w.Branch.Target.OID, }, - Commit: graphql.Target{OID: w.Branch.Target.OID}, - FileMatches: fileMatches, }, - Path: w.Path, - Steps: w.Steps, - OnlyFetchWorkspace: w.OnlyFetchWorkspace, - }) + Commit: graphql.Target{OID: w.Branch.Target.OID}, + FileMatches: fileMatches, + }, + Path: w.Path, + Steps: w.Steps, + OnlyFetchWorkspace: w.OnlyFetchWorkspace, } - - return workspaces } diff --git a/go.mod b/go.mod index 045f581151..138283030a 100644 --- a/go.mod +++ b/go.mod @@ -20,7 +20,7 @@ require ( github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4 github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf - github.com/sourcegraph/sourcegraph/lib v0.0.0-20211111140427-2e938231dac5 + github.com/sourcegraph/sourcegraph/lib v0.0.0-20211115102128-3c8c7a9499a3 github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d diff --git a/go.sum b/go.sum index 6eab6b462f..28532f0db3 100644 --- a/go.sum +++ b/go.sum @@ -258,12 +258,8 @@ github.com/sourcegraph/go-diff v0.6.1 h1:hmA1LzxW0n1c3Q4YbrFgg4P99GSnebYa3x8gr0H github.com/sourcegraph/go-diff v0.6.1/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20211109155204-31a95b8405e0 h1:NaYWQFsArbbSysPHyPC0jChFqlrQg01pVz5ej5X393Q= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20211109155204-31a95b8405e0/go.mod h1:4WdX5odo9YL0GD0Wg9OZJJtIJIn1jIsh+UWrQ4MEcaw= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20211111132504-9eca3a9ea27b h1:MIeeeFbOmIbjpLEcc5KYfs6tsCBecwFuZWxV8Om+PFw= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20211111132504-9eca3a9ea27b/go.mod h1:4WdX5odo9YL0GD0Wg9OZJJtIJIn1jIsh+UWrQ4MEcaw= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20211111140427-2e938231dac5 h1:Ome/BYdr0lrwMCPseJUYI0uzv45TVVnfPJ5/DP367wg= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20211111140427-2e938231dac5/go.mod h1:4WdX5odo9YL0GD0Wg9OZJJtIJIn1jIsh+UWrQ4MEcaw= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20211115102128-3c8c7a9499a3 h1:vaflMp94dFzfdgb2MIxGEVQKo1O1o3uH9w0sYds/ZBU= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20211115102128-3c8c7a9499a3/go.mod h1:4WdX5odo9YL0GD0Wg9OZJJtIJIn1jIsh+UWrQ4MEcaw= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= From 888e69990ec4f9d3bd2da224329f9c2b7821ab6d Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Mon, 15 Nov 2021 15:21:39 +0100 Subject: [PATCH 089/647] Prepare changelog for 3.33.8 --- CHANGELOG.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index cc983c59c9..bc5faca3ea 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,12 @@ All notable changes to `src-cli` are documented in this file. ### Removed +## 3.33.8 + +### Fixed + +- For internal use only: Switch to single workspaces only in payload. + ## 3.33.7 ### Added From ca48ef62bf7444babf524441401b49cb19c3502a Mon Sep 17 00:00:00 2001 From: Andreas Rammhold Date: Fri, 19 Nov 2021 09:27:14 +0100 Subject: [PATCH 090/647] Support serving bare repositories (#639) This allows bare repos in addition to worktree style git repos in detection. --- internal/servegit/serve.go | 47 ++++++++++++++++++++++++--------- internal/servegit/serve_test.go | 41 +++++++++++++++++++++++++--- 2 files changed, 72 insertions(+), 16 deletions(-) diff --git a/internal/servegit/serve.go b/internal/servegit/serve.go index d26b376f1f..f1e5f4820c 100644 --- a/internal/servegit/serve.go +++ b/internal/servegit/serve.go @@ -130,6 +130,33 @@ func (s *Serve) handler() http.Handler { }) } +// Checks if git thinks the given path is a valid .git folder for a repository +func isBareRepo(path string) bool { + c := exec.Command("git", "--git-dir", path, "rev-parse", "--is-bare-repository") + c.Dir = path + out, err := c.CombinedOutput() + + if err != nil { + return false + } + + return string(out) != "false\n" +} + +// Check if git thinks the given path is a proper git checkout +func isGitRepo(path string) bool { + // Executing git rev-parse --git-dir in the root of a worktree returns .git + c := exec.Command("git", "rev-parse", "--git-dir") + c.Dir = path + out, err := c.CombinedOutput() + + if err != nil { + return false + } + + return string(out) == ".git\n" +} + // Repos returns a slice of all the git repositories it finds. func (s *Serve) Repos() ([]Repo, error) { var repos []Repo @@ -158,10 +185,11 @@ func (s *Serve) Repos() ([]Repo, error) { // Check whether a particular directory is a repository or not. // - // A directory which also is a repository (have .git folder inside it) - // will contain nil error. If it does, proceed to configure. - gitdir := filepath.Join(path, ".git") - if fi, err := os.Stat(gitdir); err != nil || !fi.IsDir() { + // Valid paths are either bare repositories or git worktrees. + isBare := isBareRepo(path) + isGit := isGitRepo(path) + + if !isGit && !isBare { s.Debug.Printf("not a repository root: %s", path) return nil } @@ -182,14 +210,9 @@ func (s *Serve) Repos() ([]Repo, error) { // Check whether a repository is a bare repository or not. // - // If it yields false, which means it is a non-bare repository, - // skip the directory so that it will not recurse to the subdirectories. - // If it is a bare repository, proceed to recurse. - c := exec.Command("git", "rev-parse", "--is-bare-repository") - c.Dir = gitdir - out, _ := c.CombinedOutput() - - if string(out) == "false\n" { + // Bare repositories shouldn't have any further child + // repositories. Only regular git worktrees can have children. + if isBare { return filepath.SkipDir } diff --git a/internal/servegit/serve_test.go b/internal/servegit/serve_test.go index bc62011bfc..0d92dcebc7 100644 --- a/internal/servegit/serve_test.go +++ b/internal/servegit/serve_test.go @@ -32,7 +32,7 @@ func TestReposHandler(t *testing.T) { repos: []string{"project1", "project2"}, }, { name: "nested", - repos: []string{"project1", "project1/subproject", "project2", "dir/project3"}, + repos: []string{"project1", "project1/subproject", "project2", "dir/project3", "dir/project4.bare"}, }} for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { @@ -171,6 +171,12 @@ func testReposHandler(t *testing.T, h http.Handler, repos []Repo) { } } +func gitInitBare(t *testing.T, path string) { + if err := exec.Command("git", "init", "--bare", path).Run(); err != nil { + t.Fatal(err) + } +} + func gitInitRepos(t *testing.T, names ...string) string { root, err := os.MkdirTemp("", "") if err != nil { @@ -184,10 +190,11 @@ func gitInitRepos(t *testing.T, names ...string) string { if err := os.MkdirAll(p, 0755); err != nil { t.Fatal(err) } - p = filepath.Join(p, ".git") - if err := exec.Command("git", "init", "--bare", p).Run(); err != nil { - t.Fatal(err) + + if !strings.HasSuffix(p, ".bare") { + p = filepath.Join(p, ".git") } + gitInitBare(t, p) } return root @@ -221,6 +228,32 @@ func TestIgnoreGitSubmodules(t *testing.T) { } } +func TestIsBareRepo(t *testing.T) { + dir, err := os.MkdirTemp("", "") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.RemoveAll(dir) }) + + gitInitBare(t, dir) + + if !isBareRepo(dir) { + t.Errorf("Path %s it not a bare repository", dir) + } +} + +func TestEmptyDirIsNotBareRepo(t *testing.T) { + dir, err := os.MkdirTemp("", "") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.RemoveAll(dir) }) + + if isBareRepo(dir) { + t.Errorf("Path %s it falsey detected as a bare repository", dir) + } +} + func testLogger(t *testing.T) *log.Logger { return log.New(testWriter{t}, "testLogger ", log.LstdFlags) } From 83e7ff3715023e5e196af7d37d77f87e79c8304f Mon Sep 17 00:00:00 2001 From: Adam Harvey Date: Fri, 19 Nov 2021 12:15:39 +0100 Subject: [PATCH 091/647] changelog: update for 3.34.0 --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index bc5faca3ea..a6e47514f7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,10 @@ All notable changes to `src-cli` are documented in this file. ### Removed +## 3.34.0 + +No changes; this is a re-release of 3.33.8 to align with the release of Sourcegraph 3.34. + ## 3.33.8 ### Fixed From fe86b657e153714885af4db5454e7163247c2a8d Mon Sep 17 00:00:00 2001 From: Adam Harvey Date: Fri, 19 Nov 2021 12:22:17 +0100 Subject: [PATCH 092/647] changelog: correct for 3.34.0. --- CHANGELOG.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a6e47514f7..0c7892c055 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,7 +21,9 @@ All notable changes to `src-cli` are documented in this file. ## 3.34.0 -No changes; this is a re-release of 3.33.8 to align with the release of Sourcegraph 3.34. +### Added + +- Bare repositories can now be served with `src serve-git`. Thanks to [Andreas Rammhold](https://github.com/andir) for the contribution! [#639](https://github.com/sourcegraph/src-cli/pull/639) ## 3.33.8 From b6a636d1efa4b8b4c0e6442bd87b8d78fadb922f Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Tue, 23 Nov 2021 16:39:53 +0100 Subject: [PATCH 093/647] Fix off-by-one error in JSON UI for skipping steps (#659) Steps are 1-indexed in our JSON UI, but we forgot to add the obligatory +1 here that we do everywhere else. --- internal/batches/executor/run_steps.go | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/internal/batches/executor/run_steps.go b/internal/batches/executor/run_steps.go index 059fb24464..405f1b9f84 100644 --- a/internal/batches/executor/run_steps.go +++ b/internal/batches/executor/run_steps.go @@ -73,11 +73,11 @@ func runSteps(ctx context.Context, opts *executionOpts) (result execution.Result // Set the Outputs to the cached outputs execResult.Outputs = opts.task.CachedResult.Outputs - startStep = opts.task.CachedResult.StepIndex + 1 + lastStep := opts.task.CachedResult.StepIndex // If we have cached results and don't need to execute any more steps, // we can quit - if startStep == len(opts.task.Steps) { + if lastStep == len(opts.task.Steps)-1 { changes, err := git.ChangesInDiff(opts.task.CachedResult.Diff) if err != nil { return execResult, nil, errors.Wrap(err, "parsing cached step diff") @@ -90,7 +90,12 @@ func runSteps(ctx context.Context, opts *executionOpts) (result execution.Result return execResult, stepResults, nil } - opts.ui.SkippingStepsUpto(startStep) + startStep = lastStep + 1 + + opts.ui.SkippingStepsUpto( + // UI is 1-indexed. + startStep + 1, + ) } for i := startStep; i < len(opts.task.Steps); i++ { From c32f1e226d9d6a0d2563895c373b0eca08406d37 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Tue, 23 Nov 2021 16:50:36 +0100 Subject: [PATCH 094/647] ssbc: Allow cache to read step results from current working directory (#658) --- cmd/src/batch_exec.go | 2 +- internal/batches/executor/execution_cache.go | 31 +++++++++++++------- 2 files changed, 21 insertions(+), 12 deletions(-) diff --git a/cmd/src/batch_exec.go b/cmd/src/batch_exec.go index deb9ec470e..9d44a3ebee 100644 --- a/cmd/src/batch_exec.go +++ b/cmd/src/batch_exec.go @@ -150,7 +150,7 @@ func executeBatchSpecInWorkspaces(ctx context.Context, ui *ui.JSONLines, opts ex coord := svc.NewCoordinator(executor.NewCoordinatorOpts{ Creator: workspaceCreator, CacheDir: opts.flags.cacheDir, - Cache: &executor.JSONLinesCache{Writer: ui}, + Cache: &executor.ServerSideCache{Writer: ui}, SkipErrors: opts.flags.skipErrors, CleanArchives: opts.flags.cleanArchives, Parallelism: opts.flags.parallelism, diff --git a/internal/batches/executor/execution_cache.go b/internal/batches/executor/execution_cache.go index af6eff83bb..0494286de6 100644 --- a/internal/batches/executor/execution_cache.go +++ b/internal/batches/executor/execution_cache.go @@ -43,12 +43,12 @@ func (c ExecutionDiskCache) Get(ctx context.Context, key cache.Keyer) (execution return result, false, err } - found, err := c.readCacheFile(path, &result) + found, err := readCacheFile(path, &result) return result, found, err } -func (c ExecutionDiskCache) readCacheFile(path string, result interface{}) (bool, error) { +func readCacheFile(path string, result interface{}) (bool, error) { if _, err := os.Stat(path); os.IsNotExist(err) { return false, nil } @@ -111,7 +111,7 @@ func (c ExecutionDiskCache) GetStepResult(ctx context.Context, key cache.Keyer) return result, false, err } - found, err := c.readCacheFile(path, &result) + found, err := readCacheFile(path, &result) if err != nil { return result, false, err } @@ -157,16 +157,16 @@ type JSONCacheWriter interface { WriteAfterStepResult(key string, value execution.AfterStepResult) } -type JSONLinesCache struct { +type ServerSideCache struct { Writer JSONCacheWriter } -func (c *JSONLinesCache) Get(ctx context.Context, key cache.Keyer) (result execution.Result, found bool, err error) { +func (c *ServerSideCache) Get(ctx context.Context, key cache.Keyer) (result execution.Result, found bool, err error) { // noop return execution.Result{}, false, nil } -func (c *JSONLinesCache) Set(ctx context.Context, key cache.Keyer, result execution.Result) error { +func (c *ServerSideCache) Set(ctx context.Context, key cache.Keyer, result execution.Result) error { k, err := key.Key() if err != nil { return err @@ -177,7 +177,7 @@ func (c *JSONLinesCache) Set(ctx context.Context, key cache.Keyer, result execut return nil } -func (c *JSONLinesCache) SetStepResult(ctx context.Context, key cache.Keyer, result execution.AfterStepResult) error { +func (c *ServerSideCache) SetStepResult(ctx context.Context, key cache.Keyer, result execution.AfterStepResult) error { k, err := key.Key() if err != nil { return err @@ -188,12 +188,21 @@ func (c *JSONLinesCache) SetStepResult(ctx context.Context, key cache.Keyer, res return nil } -func (c *JSONLinesCache) GetStepResult(ctx context.Context, key cache.Keyer) (result execution.AfterStepResult, found bool, err error) { - // noop - return execution.AfterStepResult{}, false, nil +func (c *ServerSideCache) GetStepResult(ctx context.Context, key cache.Keyer) (result execution.AfterStepResult, found bool, err error) { + rawKey, err := key.Key() + if err != nil { + return result, false, err + } + + found, err = readCacheFile(rawKey+cacheFileExt, &result) + if err != nil { + return result, false, err + } + + return result, found, nil } -func (c *JSONLinesCache) Clear(ctx context.Context, key cache.Keyer) error { +func (c *ServerSideCache) Clear(ctx context.Context, key cache.Keyer) error { // noop return nil } From 2754fc9d57222fa586601131af3700905656be1b Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Tue, 23 Nov 2021 16:50:58 +0100 Subject: [PATCH 095/647] Prepare changelog for 3.34.1 --- CHANGELOG.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0c7892c055..dda8ca9374 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,16 @@ All notable changes to `src-cli` are documented in this file. ### Removed +## 3.34.1 + +### Added + +- For internal use only: Allow exec mode to read step cache files from the current working directory. + +### Fixed + +- For internal use only: Fix an off-by-one error in the JSON log UI. + ## 3.34.0 ### Added From e1b02cba1a569231092d19edae4701aca205091a Mon Sep 17 00:00:00 2001 From: Kelli Rockwell Date: Wed, 24 Nov 2021 13:54:45 -0800 Subject: [PATCH 096/647] batches: support volume mode on Apple Silicon (#660) --- CHANGELOG.md | 2 ++ internal/batches/workspace/workspace.go | 11 +++++++---- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dda8ca9374..b008a143f8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,8 @@ All notable changes to `src-cli` are documented in this file. ### Changed +- `src batch [preview|apply]` will now use the faster volume workspace by default for macOS systems using arm64 processors (aka "Apple Silicon") + ### Fixed ### Removed diff --git a/internal/batches/workspace/workspace.go b/internal/batches/workspace/workspace.go index 1f670cd255..0fb25c9054 100644 --- a/internal/batches/workspace/workspace.go +++ b/internal/batches/workspace/workspace.go @@ -95,9 +95,12 @@ func BestCreatorType(ctx context.Context, images map[string]docker.Image) Creato // if you have a batch change with steps that run as UID 1000 and then UID // 2000, you'll get errors when the second step tries to write. - // For the time being, we're only going to consider volume mode on Intel - // macOS. - if runtime.GOOS != "darwin" || runtime.GOARCH != "amd64" { + // NOTE: For the time being, we're only going to consider volume mode on Intel or M1 + // macOS. As we've generally not observed many issues from users using volume mode, and + // it is the faster of the options on non-Linux platforms (and only a touch slower on + // Linux itself), we should consider making it the default in the future for the sake of + // consistency. + if runtime.GOOS != "darwin" || (runtime.GOARCH != "amd64" && runtime.GOARCH != "arm64") { return CreatorTypeBind } @@ -106,7 +109,7 @@ func BestCreatorType(ctx context.Context, images map[string]docker.Image) Creato func detectBestCreatorType(ctx context.Context, images map[string]docker.Image) CreatorType { // OK, so we're interested in volume mode, but we need to take its - // shortcomings around mixed user environments into account. + // shortcomings around mixed user environments on Linux into account. // // To do that, let's iterate over the Docker images that are going to be // used and get their default UID. This admittedly only gets us so far — From 39f6311beec44286e44f8f151d875c5ecdf390a9 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Fri, 26 Nov 2021 18:32:53 +0100 Subject: [PATCH 097/647] Fix log lines being intertwined by newlines (#665) --- CHANGELOG.md | 2 ++ internal/batches/log/task_logger.go | 14 +++++++++++++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b008a143f8..8fa8398e10 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,8 @@ All notable changes to `src-cli` are documented in this file. ### Fixed +- Excess newlines in between outputs in logfiles written when `--keep-logs` is used have been fixed. [#665](https://github.com/sourcegraph/src-cli/pull/665) + ### Removed ## 3.34.1 diff --git a/internal/batches/log/task_logger.go b/internal/batches/log/task_logger.go index 84dd1616d2..a05b260038 100644 --- a/internal/batches/log/task_logger.go +++ b/internal/batches/log/task_logger.go @@ -82,7 +82,19 @@ type prefixWriter struct { } func (pw *prefixWriter) Write(p []byte) (int, error) { - for _, line := range bytes.Split(p, []byte("\n")) { + // Don't split on the final newline in this writer, split + // content into separate lines anyways, so lines without \n + // at the end wouldn't print properly regardless. This fixes + // output being separated by constant newlines. + // Otherwise: + // > echo Hello world; echo Hello Sourcegraph + // + // Hello world + // + // Hello Sourcegraph + // + t := bytes.TrimSuffix(p, []byte("\n")) + for _, line := range bytes.Split(t, []byte("\n")) { pw.logger.Logf("%s | %s", pw.prefix, string(line)) } return len(p), nil From 661611d14519d4f5ac72c799f78274d62f081524 Mon Sep 17 00:00:00 2001 From: Adam Harvey Date: Fri, 26 Nov 2021 14:51:53 -0800 Subject: [PATCH 098/647] go.mod: pull in sourcegraph/sourcegraph#28240 fix (#666) --- CHANGELOG.md | 1 + go.mod | 2 +- go.sum | 4 ++-- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8fa8398e10..5961025132 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,7 @@ All notable changes to `src-cli` are documented in this file. ### Fixed - Excess newlines in between outputs in logfiles written when `--keep-logs` is used have been fixed. [#665](https://github.com/sourcegraph/src-cli/pull/665) +- `src` would sometimes panic when Ctrl-C was pressed while executing batch change steps due to a bug in the library used to render the execution progress bars. This has been fixed. [🤘 #666](https://github.com/sourcegraph/src-cli/pull/666) ### Removed diff --git a/go.mod b/go.mod index 138283030a..172f887f5e 100644 --- a/go.mod +++ b/go.mod @@ -20,7 +20,7 @@ require ( github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4 github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf - github.com/sourcegraph/sourcegraph/lib v0.0.0-20211115102128-3c8c7a9499a3 + github.com/sourcegraph/sourcegraph/lib v0.0.0-20211126224101-2ada4911722e github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d diff --git a/go.sum b/go.sum index 28532f0db3..ddc5bff5bf 100644 --- a/go.sum +++ b/go.sum @@ -258,8 +258,8 @@ github.com/sourcegraph/go-diff v0.6.1 h1:hmA1LzxW0n1c3Q4YbrFgg4P99GSnebYa3x8gr0H github.com/sourcegraph/go-diff v0.6.1/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20211115102128-3c8c7a9499a3 h1:vaflMp94dFzfdgb2MIxGEVQKo1O1o3uH9w0sYds/ZBU= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20211115102128-3c8c7a9499a3/go.mod h1:4WdX5odo9YL0GD0Wg9OZJJtIJIn1jIsh+UWrQ4MEcaw= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20211126224101-2ada4911722e h1:BZpmejyF9KR5h7U9U/lfg4PfcPQZc29fuNGn0c1kT+c= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20211126224101-2ada4911722e/go.mod h1:4WdX5odo9YL0GD0Wg9OZJJtIJIn1jIsh+UWrQ4MEcaw= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= From eea180c7997d4322bb1907fbb886e0c2a1dc8845 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Mon, 29 Nov 2021 16:48:19 +0100 Subject: [PATCH 099/647] Backport fix for workspace globbing (#664) See https://github.com/sourcegraph/sourcegraph/pull/28230 for more details. --- CHANGELOG.md | 1 + internal/batches/service/workspaces.go | 9 +++++++-- internal/batches/service/workspaces_test.go | 18 ++++++++++++++++++ 3 files changed, 26 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5961025132..f58af4964c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,7 @@ All notable changes to `src-cli` are documented in this file. - Excess newlines in between outputs in logfiles written when `--keep-logs` is used have been fixed. [#665](https://github.com/sourcegraph/src-cli/pull/665) - `src` would sometimes panic when Ctrl-C was pressed while executing batch change steps due to a bug in the library used to render the execution progress bars. This has been fixed. [🤘 #666](https://github.com/sourcegraph/src-cli/pull/666) +- In batch changes, when using `workspaces` src would incorrectly treat `in` not being set as _don't match anything_. This is fixed and it matches everything like `*`. [#664](https://github.com/sourcegraph/src-cli/pull/664) ### Removed diff --git a/internal/batches/service/workspaces.go b/internal/batches/service/workspaces.go index b0cfa14b51..859ba2d6e1 100644 --- a/internal/batches/service/workspaces.go +++ b/internal/batches/service/workspaces.go @@ -43,9 +43,14 @@ func findWorkspaces( // Pre-compile all globs. workspaceMatchers := make(map[batcheslib.WorkspaceConfiguration]glob.Glob) for _, conf := range spec.Workspaces { - g, err := glob.Compile(conf.In) + in := conf.In + // Empty `in` should fall back to matching all, instead of nothing. + if in == "" { + in = "*" + } + g, err := glob.Compile(in) if err != nil { - return nil, batcheslib.NewValidationError(errors.Errorf("failed to compile glob %q: %v", conf.In, err)) + return nil, batcheslib.NewValidationError(errors.Errorf("failed to compile glob %q: %v", in, err)) } workspaceMatchers[conf] = g } diff --git a/internal/batches/service/workspaces_test.go b/internal/batches/service/workspaces_test.go index 9686d5c47d..be88d772c5 100644 --- a/internal/batches/service/workspaces_test.go +++ b/internal/batches/service/workspaces_test.go @@ -118,6 +118,24 @@ func TestFindWorkspaces(t *testing.T) { {Repo: repos[2], Steps: steps, Path: "d/e/f", OnlyFetchWorkspace: true}, }, }, + "workspace configuration without 'in' matches all": { + spec: &batcheslib.BatchSpec{ + Steps: steps, + Workspaces: []batcheslib.WorkspaceConfiguration{ + { + RootAtLocationOf: "package.json", + }, + }, + }, + finderResults: finderResults{ + repos[0]: {"a/b"}, + repos[2]: {"a/b"}, + }, + wantWorkspaces: []RepoWorkspace{ + {Repo: repos[0], Steps: steps, Path: "a/b"}, + {Repo: repos[2], Steps: steps, Path: "a/b"}, + }, + }, } for name, tt := range tests { From fb087afec3ebe27cd642dbd7bb42246c01a022eb Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Mon, 29 Nov 2021 16:58:18 +0100 Subject: [PATCH 100/647] Improve TUI label for improving step (#667) Before this would print "Preparing 1", now it prints "Preparing step 1" --- internal/batches/ui/task_exec_tui.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/batches/ui/task_exec_tui.go b/internal/batches/ui/task_exec_tui.go index 845b9c1445..7aeaeaca59 100644 --- a/internal/batches/ui/task_exec_tui.go +++ b/internal/batches/ui/task_exec_tui.go @@ -455,7 +455,7 @@ func (ui stepsExecTUI) StepSkipped(step int) { ui.updateStatusBar(fmt.Sprintf("Skipping step %d", step)) } func (ui stepsExecTUI) StepPreparingStart(step int) { - ui.updateStatusBar(fmt.Sprintf("Preparing %d", step)) + ui.updateStatusBar(fmt.Sprintf("Preparing step %d", step)) } func (ui stepsExecTUI) StepPreparingSuccess(step int) { // noop right now From e50ad40737d97ed578ebec49303d7c9948d16d37 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Mon, 29 Nov 2021 17:23:44 +0100 Subject: [PATCH 101/647] Build changeset specs server side (#661) This PR changes src exec's behavior to not upload changeset specs anymore. They aren't required anymore. See main PR for more details: https://github.com/sourcegraph/sourcegraph/pull/28158 --- cmd/src/batch_common.go | 4 +- cmd/src/batch_exec.go | 37 ++----------------- go.mod | 4 +- go.sum | 7 ++-- internal/batches/executor/coordinator.go | 5 +-- internal/batches/executor/coordinator_test.go | 6 +-- internal/batches/executor/executor_test.go | 10 ++--- internal/batches/executor/run_steps.go | 8 ++-- internal/batches/executor/ui.go | 4 +- internal/batches/service/service.go | 14 +++---- internal/batches/ui/json_lines.go | 4 +- internal/batches/ui/task_exec_tui.go | 2 +- 12 files changed, 36 insertions(+), 69 deletions(-) diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index 9f47520ca3..3527ba5d32 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -250,9 +250,9 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp var workspaceCreator workspace.Creator - if svc.HasDockerImages(batchSpec) { + if len(batchSpec.Steps) > 0 { ui.PreparingContainerImages() - images, err := svc.EnsureDockerImages(ctx, batchSpec, ui.PreparingContainerImagesProgress) + images, err := svc.EnsureDockerImages(ctx, batchSpec.Steps, ui.PreparingContainerImagesProgress) if err != nil { return err } diff --git a/cmd/src/batch_exec.go b/cmd/src/batch_exec.go index 9d44a3ebee..a6a0e9ff99 100644 --- a/cmd/src/batch_exec.go +++ b/cmd/src/batch_exec.go @@ -8,7 +8,6 @@ import ( "io" "github.com/cockroachdb/errors" - "github.com/hashicorp/go-multierror" "github.com/sourcegraph/src-cli/internal/batches/executor" "github.com/sourcegraph/src-cli/internal/batches/graphql" @@ -109,27 +108,11 @@ func executeBatchSpecInWorkspaces(ctx context.Context, ui *ui.JSONLines, opts ex // we can convert it to a RepoWorkspace and build a task only for that one. repoWorkspace := convertWorkspace(input.Workspace) - // Parse the raw batch spec contained in the input - ui.ParsingBatchSpec() - batchSpec, err := svc.ParseBatchSpec([]byte(input.RawSpec)) - if err != nil { - var multiErr *multierror.Error - if errors.As(err, &multiErr) { - ui.ParsingBatchSpecFailure(multiErr) - return cmderrors.ExitCode(2, nil) - } else { - // This shouldn't happen; let's just punt and let the normal - // rendering occur. - return err - } - } - ui.ParsingBatchSpecSuccess() - var workspaceCreator workspace.Creator - if svc.HasDockerImages(batchSpec) { + if len(input.Workspace.Steps) > 0 { ui.PreparingContainerImages() - images, err := svc.EnsureDockerImages(ctx, batchSpec, ui.PreparingContainerImagesProgress) + images, err := svc.EnsureDockerImages(ctx, input.Workspace.Steps, ui.PreparingContainerImagesProgress) if err != nil { return err } @@ -162,13 +145,13 @@ func executeBatchSpecInWorkspaces(ctx context.Context, ui *ui.JSONLines, opts ex // `src batch exec` uses server-side caching for changeset specs, so we // only need to call `CheckStepResultsCache` to make sure that per-step cache entries // are loaded and set on the tasks. - tasks := svc.BuildTasks(ctx, batchSpec, []service.RepoWorkspace{repoWorkspace}) + tasks := svc.BuildTasks(ctx, input.Spec, []service.RepoWorkspace{repoWorkspace}) if err := coord.CheckStepResultsCache(ctx, tasks); err != nil { return err } taskExecUI := ui.ExecutingTasks(*verbose, opts.flags.parallelism) - specs, _, err := coord.Execute(ctx, tasks, batchSpec, taskExecUI) + _, _, err = coord.Execute(ctx, tasks, input.Spec, taskExecUI) if err == nil || opts.flags.skipErrors { if err == nil { taskExecUI.Success() @@ -181,18 +164,6 @@ func executeBatchSpecInWorkspaces(ctx context.Context, ui *ui.JSONLines, opts ex return err } } - ids := make([]graphql.ChangesetSpecID, len(specs)) - - ui.UploadingChangesetSpecs(len(specs)) - for i, spec := range specs { - id, err := svc.CreateChangesetSpec(ctx, spec) - if err != nil { - return err - } - ids[i] = id - ui.UploadingChangesetSpecsProgress(i+1, len(specs)) - } - ui.UploadingChangesetSpecsSuccess(ids) return nil } diff --git a/go.mod b/go.mod index 172f887f5e..1d8a84430b 100644 --- a/go.mod +++ b/go.mod @@ -20,7 +20,7 @@ require ( github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4 github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf - github.com/sourcegraph/sourcegraph/lib v0.0.0-20211126224101-2ada4911722e + github.com/sourcegraph/sourcegraph/lib v0.0.0-20211129161320-80f1543dd742 github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d @@ -30,7 +30,7 @@ require ( require ( github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect - github.com/cockroachdb/logtags v0.0.0-20190617123548-eb05cc24525f // indirect + github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f // indirect github.com/cockroachdb/sentry-go v0.6.1-cockroachdb.2 // indirect github.com/ghodss/yaml v1.0.0 // indirect github.com/gogo/protobuf v1.3.2 // indirect diff --git a/go.sum b/go.sum index ddc5bff5bf..0ae1ff29f0 100644 --- a/go.sum +++ b/go.sum @@ -25,8 +25,9 @@ github.com/cockroachdb/datadriven v1.0.0/go.mod h1:5Ib8Meh+jk1RlHIXej6Pzevx/NLlN github.com/cockroachdb/errors v1.6.1/go.mod h1:tm6FTP5G81vwJ5lC0SizQo374JNCOPrHyXGitRJoDqM= github.com/cockroachdb/errors v1.8.6 h1:Am9evxl/po3RzpokemQvq7S7Cd0mxv24xy0B/trlQF4= github.com/cockroachdb/errors v1.8.6/go.mod h1:hOm5fabihW+xEyY1kuypGwqT+Vt7rafg04ytBtIpeIQ= -github.com/cockroachdb/logtags v0.0.0-20190617123548-eb05cc24525f h1:o/kfcElHqOiXqcou5a3rIlMc7oJbMQkeLk0VQJ7zgqY= github.com/cockroachdb/logtags v0.0.0-20190617123548-eb05cc24525f/go.mod h1:i/u985jwjWRlyHXQbwatDASoW0RMlZ/3i9yJHE2xLkI= +github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f h1:6jduT9Hfc0njg5jJ1DdKCFPdMBrp/mdZfCpa5h+WM74= +github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= github.com/cockroachdb/redact v1.1.1/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= github.com/cockroachdb/redact v1.1.3 h1:AKZds10rFSIj7qADf0g46UixK8NNLwWTNdCIGS5wfSQ= github.com/cockroachdb/redact v1.1.3/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= @@ -258,8 +259,8 @@ github.com/sourcegraph/go-diff v0.6.1 h1:hmA1LzxW0n1c3Q4YbrFgg4P99GSnebYa3x8gr0H github.com/sourcegraph/go-diff v0.6.1/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20211126224101-2ada4911722e h1:BZpmejyF9KR5h7U9U/lfg4PfcPQZc29fuNGn0c1kT+c= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20211126224101-2ada4911722e/go.mod h1:4WdX5odo9YL0GD0Wg9OZJJtIJIn1jIsh+UWrQ4MEcaw= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20211129161320-80f1543dd742 h1:8IegMj6lV20zSCt4f+fjOKRD7ef3/hONH9MmZ9OMYp4= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20211129161320-80f1543dd742/go.mod h1:4WdX5odo9YL0GD0Wg9OZJJtIJIn1jIsh+UWrQ4MEcaw= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= diff --git a/internal/batches/executor/coordinator.go b/internal/batches/executor/coordinator.go index 66e4731c58..f9d0755864 100644 --- a/internal/batches/executor/coordinator.go +++ b/internal/batches/executor/coordinator.go @@ -174,9 +174,8 @@ func (c *Coordinator) checkCacheForTask(ctx context.Context, task *Task) (specs func (c Coordinator) buildChangesetSpecs(task *Task, result execution.Result) ([]*batcheslib.ChangesetSpec, error) { input := &batcheslib.ChangesetSpecInput{ - BaseRepositoryID: task.Repository.ID, - HeadRepositoryID: task.Repository.ID, - Repository: batcheslib.ChangesetSpecRepository{ + Repository: batcheslib.Repository{ + ID: task.Repository.ID, Name: task.Repository.Name, FileMatches: task.Repository.SortedFileMatches(), BaseRef: task.Repository.BaseRef(), diff --git a/internal/batches/executor/coordinator_test.go b/internal/batches/executor/coordinator_test.go index 4b9ca5e752..3be06ee491 100644 --- a/internal/batches/executor/coordinator_test.go +++ b/internal/batches/executor/coordinator_test.go @@ -376,9 +376,9 @@ func TestCoordinator_Execute_StepCaching(t *testing.T) { Path: "", }, stepResults: []execution.AfterStepResult{ - {StepIndex: 0, Diff: []byte(`step-0-diff`)}, - {StepIndex: 1, Diff: []byte(`step-1-diff`)}, - {StepIndex: 2, Diff: []byte(`step-2-diff`)}, + {StepIndex: 0, Diff: `step-0-diff`}, + {StepIndex: 1, Diff: `step-1-diff`}, + {StepIndex: 2, Diff: `step-2-diff`}, }, }} diff --git a/internal/batches/executor/executor_test.go b/internal/batches/executor/executor_test.go index 999271dbd9..57f2302673 100644 --- a/internal/batches/executor/executor_test.go +++ b/internal/batches/executor/executor_test.go @@ -480,14 +480,14 @@ func TestExecutor_CachedStepResults(t *testing.T) { }, } - cachedDiff := []byte(`diff --git README.md README.md + cachedDiff := `diff --git README.md README.md index 02a19af..c9644dd 100644 --- README.md +++ README.md @@ -1 +1,2 @@ # Welcome to the README +foobar -`) +` task := &Task{ BatchChangeAttributes: &template.BatchChangeAttributes{}, @@ -516,7 +516,7 @@ index 02a19af..c9644dd 100644 // We want the diff to be the same as the cached one, since we only had to // execute a single step executionResult := results[0].result - if diff := cmp.Diff(executionResult.Diff, string(cachedDiff)); diff != "" { + if diff := cmp.Diff(executionResult.Diff, cachedDiff); diff != "" { t.Fatalf("wrong diff: %s", diff) } @@ -543,7 +543,7 @@ This repository is used to test opening and closing pull request with Automation }, } - cachedDiff := []byte(`diff --git README.md README.md + cachedDiff := `diff --git README.md README.md index 1914491..cd2ccbf 100644 --- README.md +++ README.md @@ -562,7 +562,7 @@ index 0000000..888e1ec +++ README.txt @@ -0,0 +1 @@ +this is step 1 -`) +` wantFinalDiff := `diff --git README.md README.md index 1914491..d6782d3 100644 diff --git a/internal/batches/executor/run_steps.go b/internal/batches/executor/run_steps.go index 405f1b9f84..ab68ae3612 100644 --- a/internal/batches/executor/run_steps.go +++ b/internal/batches/executor/run_steps.go @@ -78,12 +78,12 @@ func runSteps(ctx context.Context, opts *executionOpts) (result execution.Result // If we have cached results and don't need to execute any more steps, // we can quit if lastStep == len(opts.task.Steps)-1 { - changes, err := git.ChangesInDiff(opts.task.CachedResult.Diff) + changes, err := git.ChangesInDiff([]byte(opts.task.CachedResult.Diff)) if err != nil { return execResult, nil, errors.Wrap(err, "parsing cached step diff") } - execResult.Diff = string(opts.task.CachedResult.Diff) + execResult.Diff = opts.task.CachedResult.Diff execResult.ChangedFiles = &changes stepResults = append(stepResults, opts.task.CachedResult) @@ -119,7 +119,7 @@ func runSteps(ctx context.Context, opts *executionOpts) (result execution.Result stepContext.Steps.Changes = previousStepResult.Files stepContext.Outputs = opts.task.CachedResult.Outputs - if err := workspace.ApplyDiff(ctx, opts.task.CachedResult.Diff); err != nil { + if err := workspace.ApplyDiff(ctx, []byte(opts.task.CachedResult.Diff)); err != nil { return execResult, nil, errors.Wrap(err, "getting changed files in step") } } @@ -178,7 +178,7 @@ func runSteps(ctx context.Context, opts *executionOpts) (result execution.Result } stepResult := execution.AfterStepResult{ StepIndex: i, - Diff: stepDiff, + Diff: string(stepDiff), Outputs: make(map[string]interface{}), PreviousStepResult: stepContext.PreviousStep, } diff --git a/internal/batches/executor/ui.go b/internal/batches/executor/ui.go index f9fd449537..12daf38241 100644 --- a/internal/batches/executor/ui.go +++ b/internal/batches/executor/ui.go @@ -48,7 +48,7 @@ type StepsExecutionUI interface { CalculatingDiffStarted() CalculatingDiffFinished() - StepFinished(idx int, diff []byte, changes *git.Changes, outputs map[string]interface{}) + StepFinished(idx int, diff string, changes *git.Changes, outputs map[string]interface{}) StepFailed(idx int, err error, exitCode int) } @@ -70,7 +70,7 @@ func (noop NoopStepsExecUI) StepOutputWriter(ctx context.Context, task *Task, st } func (noop NoopStepsExecUI) CalculatingDiffStarted() {} func (noop NoopStepsExecUI) CalculatingDiffFinished() {} -func (noop NoopStepsExecUI) StepFinished(idx int, diff []byte, changes *git.Changes, outputs map[string]interface{}) { +func (noop NoopStepsExecUI) StepFinished(idx int, diff string, changes *git.Changes, outputs map[string]interface{}) { } func (noop NoopStepsExecUI) StepFailed(idx int, err error, exitCode int) { } diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index f75495d80d..e378843ff7 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -158,19 +158,19 @@ func (svc *Service) CreateChangesetSpec(ctx context.Context, spec *batcheslib.Ch // // Progress information is reported back to the given progress function: perc // will be a value between 0.0 and 1.0, inclusive. -func (svc *Service) EnsureDockerImages(ctx context.Context, spec *batcheslib.BatchSpec, progress func(done, total int)) (map[string]docker.Image, error) { - total := len(spec.Steps) +func (svc *Service) EnsureDockerImages(ctx context.Context, steps []batcheslib.Step, progress func(done, total int)) (map[string]docker.Image, error) { + total := len(steps) progress(0, total) // TODO: this _really_ should be parallelised, since the image cache takes // care to only pull the same image once. images := make(map[string]docker.Image) - for i := range spec.Steps { - img, err := svc.EnsureImage(ctx, spec.Steps[i].Container) + for i := range steps { + img, err := svc.EnsureImage(ctx, steps[i].Container) if err != nil { return nil, err } - images[spec.Steps[i].Container] = img + images[steps[i].Container] = img progress(i+1, total) } @@ -178,10 +178,6 @@ func (svc *Service) EnsureDockerImages(ctx context.Context, spec *batcheslib.Bat return images, nil } -func (svc *Service) HasDockerImages(spec *batcheslib.BatchSpec) bool { - return len(spec.Steps) > 0 -} - func (svc *Service) EnsureImage(ctx context.Context, name string) (docker.Image, error) { img := svc.imageCache.Get(name) diff --git a/internal/batches/ui/json_lines.go b/internal/batches/ui/json_lines.go index cb0f314bb4..56838c7c38 100644 --- a/internal/batches/ui/json_lines.go +++ b/internal/batches/ui/json_lines.go @@ -339,13 +339,13 @@ 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 string, changes *git.Changes, outputs map[string]interface{}) { logOperationSuccess( batcheslib.LogEventOperationTaskStep, &batcheslib.TaskStepMetadata{ TaskID: ui.linesTask.ID, Step: step, - Diff: string(diff), + Diff: diff, Outputs: outputs, }, ) diff --git a/internal/batches/ui/task_exec_tui.go b/internal/batches/ui/task_exec_tui.go index 7aeaeaca59..9debfb9843 100644 --- a/internal/batches/ui/task_exec_tui.go +++ b/internal/batches/ui/task_exec_tui.go @@ -477,7 +477,7 @@ func (ui stepsExecTUI) CalculatingDiffStarted() { func (ui stepsExecTUI) CalculatingDiffFinished() { // noop right now } -func (ui stepsExecTUI) StepFinished(idx int, diff []byte, changes *git.Changes, outputs map[string]interface{}) { +func (ui stepsExecTUI) StepFinished(idx int, diff string, changes *git.Changes, outputs map[string]interface{}) { // noop right now } func (ui stepsExecTUI) StepFailed(idx int, err error, exitCode int) { From 2e3de89cddbd9fd723bc27e3807f30890607a891 Mon Sep 17 00:00:00 2001 From: Adam Harvey Date: Tue, 30 Nov 2021 08:44:56 -0800 Subject: [PATCH 102/647] batches: test the fix in #666 (#668) * batches: test the fix in #666 @mrnugget suggested this test, and quite right he was, too. * Skip the test on Windows. --- internal/batches/ui/task_exec_tui_test.go | 81 ++++++++++++++++++++--- 1 file changed, 73 insertions(+), 8 deletions(-) diff --git a/internal/batches/ui/task_exec_tui_test.go b/internal/batches/ui/task_exec_tui_test.go index bcd01e8bf5..4211afb525 100644 --- a/internal/batches/ui/task_exec_tui_test.go +++ b/internal/batches/ui/task_exec_tui_test.go @@ -48,14 +48,6 @@ func TestTaskExecTUI_Integration(t *testing.T) { advanceClock := func(d time.Duration) { now = now.Add(d) } buf := &ttyBuf{} - expectOutput := func(t *testing.T, buf *ttyBuf, want []string) { - t.Helper() - - have := buf.Lines() - if !cmp.Equal(want, have) { - t.Fatalf("wrong output:\n%s", cmp.Diff(want, have)) - } - } out := output.NewOutput(buf, output.OutputOpts{ ForceTTY: true, @@ -205,6 +197,70 @@ func TestTaskExecTUI_Integration(t *testing.T) { }) } +func TestProgressUpdateAfterComplete(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("Something emits different escape codes on windows.") + } + + buf := &ttyBuf{} + + now := time.Now() + clock := func() time.Time { return now.UTC().Truncate(time.Millisecond) } + + out := output.NewOutput(buf, output.OutputOpts{ + ForceTTY: true, + ForceColor: true, + ForceHeight: 25, + ForceWidth: 80, + Verbose: true, + }) + + tasks := []*executor.Task{ + {Repository: &graphql.Repository{Name: "github.com/sourcegraph/sourcegraph"}}, + {Repository: &graphql.Repository{Name: "github.com/sourcegraph/src-cli"}}, + } + + printer := newTaskExecTUI(out, true, 2) + printer.forceNoSpinner = true + printer.clock = clock + + // Setup internal state. + printer.Start(tasks) + + // Start the tasks. + printer.TaskStarted(tasks[0]) + printer.TaskStarted(tasks[1]) + + // Update the tasks into a useful state. + printer.TaskCurrentlyExecuting(tasks[0], "echo Hello World > README.md") + printer.TaskCurrentlyExecuting(tasks[1], "Downloading archive") + + expectOutput(t, buf, []string{ + "⠋ Executing... (0/2, 0 errored) ", + "│ ", + "├── github.com/sourcegraph/sourcegraph echo Hello World > README.md 0s", + "└── github.com/sourcegraph/src-cli Downloading archive 0s", + "", + }) + + // Now mark the progress as complete. + printer.progress.Complete() + + // Now send another update. This would panic before the relevant fix was + // merged in #666. + printer.TaskCurrentlyExecuting(tasks[0], "exit 42") + + // The actual output is slightly less important at this point, but let's + // check it anyway. + expectOutput(t, buf, []string{ + "✅ Executing... (0/2, 0 errored) ██████████████████████████████████████████████", + "│ ", + "├── github.com/sourcegraph/sourcegraph exit 42 0s", + "└── github.com/sourcegraph/src-cli Downloading archive 0s", + "", + }) +} + type ttyBuf struct { lines [][]byte @@ -322,3 +378,12 @@ func (t *ttyBuf) Lines() []string { func isDigit(ch byte) bool { return '0' <= ch && ch <= '9' } + +func expectOutput(t *testing.T, buf *ttyBuf, want []string) { + t.Helper() + + have := buf.Lines() + if !cmp.Equal(want, have) { + t.Fatalf("wrong output:\n%s", cmp.Diff(want, have)) + } +} From 94abddd6750a64c5219f4f9a9d78647d46ef6a34 Mon Sep 17 00:00:00 2001 From: Adam Harvey Date: Tue, 14 Dec 2021 13:58:08 -0800 Subject: [PATCH 103/647] batches: support multiple target branches (#662) --- CHANGELOG.md | 2 + cmd/src/batch_repositories.go | 13 ++--- cmd/src/colors.go | 1 + go.mod | 8 +-- go.sum | 32 ++++++----- internal/batches/service/service.go | 78 +++++++++++++++----------- internal/batches/service/workspaces.go | 31 ++++++---- 7 files changed, 94 insertions(+), 71 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f58af4964c..d0088b5511 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,8 @@ All notable changes to `src-cli` are documented in this file. ### Added +- Individual batch changes can publish multiple changesets to the same repository by specifying multiple target branches using the [`on.branches`](https://docs.sourcegraph.com/batch_changes/references/batch_spec_yaml_reference#on-repository) attribute. [#25228](https://github.com/sourcegraph/sourcegraph/issues/25228) + ### Changed - `src batch [preview|apply]` will now use the faster volume workspace by default for macOS systems using arm64 processors (aka "Apple Silicon") diff --git a/cmd/src/batch_repositories.go b/cmd/src/batch_repositories.go index dc14717f18..5d62e70d9f 100644 --- a/cmd/src/batch_repositories.go +++ b/cmd/src/batch_repositories.go @@ -68,11 +68,10 @@ Examples: return err } - seen := map[string]struct{}{} final := []*graphql.Repository{} finalMax := 0 for _, on := range spec.On { - repos, err := svc.ResolveRepositoriesOn(ctx, &on) + repos, _, err := svc.ResolveRepositoriesOn(ctx, &on) if err != nil { return errors.Wrapf(err, "Resolving %q", on.String()) } @@ -83,10 +82,7 @@ Examples: max = len(repo.Name) } - if _, ok := seen[repo.ID]; !ok { - seen[repo.ID] = struct{}{} - final = append(final, repo) - } + final = append(final, repo) } if max > finalMax { @@ -129,7 +125,7 @@ const batchRepositoriesTemplate = ` {{- else -}} {{- color "success" -}} {{- end -}} -{{- .RepoCount }} repositor{{ if eq .RepoCount 1 }}y{{else}}ies{{ end }}{{- color "nc" -}} +{{- .RepoCount }} workspace{{ if ne .RepoCount 1 }}s{{ end }}{{- color "nc" -}} {{- if ne (len .Query) 0 -}} {{- " for " -}}{{- color "search-query"}}"{{.Query}}"{{ color "nc" -}} {{- end -}} @@ -137,6 +133,7 @@ const batchRepositoriesTemplate = ` {{- range .Repos -}} {{- " "}}{{ color "success" }}{{ padRight .Name $.Max " " }}{{ color "nc" -}} + {{- if ne (len .Branch.Name) 0 -}}{{ " " }}{{- color "search-branch" -}}{{- .Branch.Name -}}{{ color "nc" -}}{{- end -}} {{- color "search-border"}}{{" ("}}{{color "nc" -}} {{- color "search-repository"}}{{$.SourcegraphEndpoint}}{{.URL}}{{color "nc" -}} {{- color "search-border"}}{{")\n"}}{{color "nc" -}} @@ -151,7 +148,7 @@ const batchRepositoriesTotalTemplate = ` {{- else -}} {{- color "success" -}} {{- end -}} -{{- .RepoCount }} repositor{{ if eq .RepoCount 1 }}y{{else}}ies{{ end }} total +{{- .RepoCount }} workspace{{ if ne .RepoCount 1 }}s{{ end }} total {{- color "nc" -}} ` diff --git a/cmd/src/colors.go b/cmd/src/colors.go index 833406222c..9bb8dd0792 100644 --- a/cmd/src/colors.go +++ b/cmd/src/colors.go @@ -31,6 +31,7 @@ var ansiColors = map[string]string{ "search-border": fg256Color(239), "search-link": fg256Color(237), "search-repository": fg256Color(23), + "search-branch": fg256Color(0) + bg256Color(7), "search-filename": fg256Color(69), "search-match": fg256Color(0) + bg256Color(11), "search-line-numbers": fg256Color(69), diff --git a/go.mod b/go.mod index 1d8a84430b..09e9fa7223 100644 --- a/go.mod +++ b/go.mod @@ -20,10 +20,10 @@ require ( github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4 github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf - github.com/sourcegraph/sourcegraph/lib v0.0.0-20211129161320-80f1543dd742 + github.com/sourcegraph/sourcegraph/lib v0.0.0-20211208022235-6e51851fbb8a github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect - golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d + golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7 ) @@ -46,10 +46,10 @@ require ( github.com/olekukonko/tablewriter v0.0.5 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/rivo/uniseg v0.2.0 // indirect - github.com/rogpeppe/go-internal v1.8.0 // indirect + github.com/rogpeppe/go-internal v1.8.1-0.20211023094830-115ce09fd6b4 // indirect github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect github.com/xeipuuv/gojsonschema v1.2.0 // indirect - golang.org/x/sys v0.0.0-20211109065445-02f5c0300f6e // indirect + golang.org/x/sys v0.0.0-20211205182925-97ca703d548d // indirect golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect ) diff --git a/go.sum b/go.sum index 0ae1ff29f0..79edaa459c 100644 --- a/go.sum +++ b/go.sum @@ -66,6 +66,7 @@ github.com/fasthttp-contrib/websocket v0.0.0-20160511215533-1f3b11f56072/go.mod github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M= github.com/flosch/pongo2 v0.0.0-20190707114632-bbf5a6c351f4/go.mod h1:T9YF2M40nIgbVgp3rreNmTged+9HrbNTIQf1PsaIiTA= +github.com/frankban/quicktest v1.14.0/go.mod h1:NeW+ay9A/U67EYXNFA1nPE8e/tnQv/09mUdL/ijj8og= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/gavv/httpexpect v2.0.0+incompatible/go.mod h1:x+9tiU1YnrOvnB725RkpoLv1M62hOWzwo5OXotisrKc= @@ -131,6 +132,7 @@ github.com/hexops/autogold v0.8.1/go.mod h1:97HLDXyG23akzAoRYJh/2OBs3kd80eHyKPvZ github.com/hexops/autogold v1.3.0/go.mod h1:d4hwi2rid66Sag+BVuHgwakW/EmaFr8vdTSbWDbrDRI= github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg= github.com/hexops/valast v1.4.0/go.mod h1:uVjKZ0smVuYlgCSPz9NRi5A04sl7lp6GtFWsROKDgEs= +github.com/hexops/valast v1.4.1/go.mod h1:G+D6TExWuKs5he+hYlPMfYyhQ8w8qbc2vm4gDWwLdDg= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/hydrogen18/memlistener v0.0.0-20141126152155-54553eb933fb/go.mod h1:qEIFzExnS6016fRpRfxrExeVn2gbClQA99gQhnIcdhE= github.com/hydrogen18/memlistener v0.0.0-20200120041712-dcc25e7acd91/go.mod h1:qEIFzExnS6016fRpRfxrExeVn2gbClQA99gQhnIcdhE= @@ -180,7 +182,7 @@ github.com/labstack/gommon v0.3.0/go.mod h1:MULnywXg0yavhxWKc+lOruYdAhDwPK9wf0OL github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= -github.com/mattn/go-colorable v0.1.11/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= +github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= github.com/mattn/go-isatty v0.0.7/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= github.com/mattn/go-isatty v0.0.9/go.mod h1:YNRxwqDuOph6SZLI9vUUz6OYw3QyUt7WiY2yME+cCiQ= @@ -243,8 +245,8 @@ github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY= github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.6.2/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= -github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8= -github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= +github.com/rogpeppe/go-internal v1.8.1-0.20211023094830-115ce09fd6b4 h1:Ha8xCaq6ln1a+R91Km45Oq6lPXj2Mla6CRJYcuV2h1w= +github.com/rogpeppe/go-internal v1.8.1-0.20211023094830-115ce09fd6b4/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= github.com/ryanuber/columnize v2.1.0+incompatible/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= github.com/sclevine/agouti v3.0.0+incompatible/go.mod h1:b4WX9W9L1sfQKXeJf1mUTLZKJ48R1S7H23Ji7oFO5Bw= @@ -259,8 +261,8 @@ github.com/sourcegraph/go-diff v0.6.1 h1:hmA1LzxW0n1c3Q4YbrFgg4P99GSnebYa3x8gr0H github.com/sourcegraph/go-diff v0.6.1/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20211129161320-80f1543dd742 h1:8IegMj6lV20zSCt4f+fjOKRD7ef3/hONH9MmZ9OMYp4= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20211129161320-80f1543dd742/go.mod h1:4WdX5odo9YL0GD0Wg9OZJJtIJIn1jIsh+UWrQ4MEcaw= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20211208022235-6e51851fbb8a h1:aUlkJEfmr1ujtMDz9n+S22JtfPa6yHW7RplYmSP7Lh4= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20211208022235-6e51851fbb8a/go.mod h1:7CQmAlg8hNhbWNIa4FA8d4X2L/G1b46/oLJxMCBO0O4= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= @@ -301,7 +303,7 @@ github.com/yudai/pp v2.0.1+incompatible/go.mod h1:PuxR/8QJ7cyCkFp/aUDS+JY727OFEZ github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= -github.com/yuin/goldmark v1.4.0/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= @@ -336,8 +338,8 @@ golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwY golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk= golang.org/x/net v0.0.0-20210614182718-04defd469f4e/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d h1:20cMwl2fHAzkJMEA+8J4JgqBQcQGzbisXo31MIeenXI= -golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f h1:OfiFi4JbukWwe3lzw+xunroH1mnC1e2Gy5cxNJApiSY= +golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -372,16 +374,19 @@ golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20210611083646-a4fc73990273/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20211109065445-02f5c0300f6e h1:i6Vklmyu+fZMFYpum+sR4ZWABGW7MyIxfJZXYvcnbns= -golang.org/x/sys v0.0.0-20211109065445-02f5c0300f6e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211102192858-4dd72447c267/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211117180635-dee7805ff2e1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211205182925-97ca703d548d h1:FjkYO/PPp4Wi0EAUOVLxePm7qVW4r4ctbWpURyuOD0E= +golang.org/x/sys v0.0.0-20211205182925-97ca703d548d/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20181221001348-537d06c36207/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -401,7 +406,8 @@ golang.org/x/tools v0.0.0-20210101214203-2dba1e4ea05c/go.mod h1:emZCQorbCU4vsT4f golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= -golang.org/x/tools v0.1.7/go.mod h1:LGqMHiF4EqQNHR1JncWGqT5BVaXmza+X+BDGol+dOxo= +golang.org/x/tools v0.1.8-0.20211102182255-bb4add04ddef/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= +golang.org/x/tools v0.1.8/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -458,4 +464,4 @@ jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7 h1:mub0MmFLOn8XLikZOA jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7/go.mod h1:OxvTsCwKosqQ1q7B+8FwXqg4rKZ/UG9dUW+g/VL2xH4= mvdan.cc/gofumpt v0.0.0-20210107193838-d24d34e18d44/go.mod h1:yXG1r1WqZVKWbVRtBWKWX9+CxGYfA51nSomhM0woR48= mvdan.cc/gofumpt v0.1.0/go.mod h1:yXG1r1WqZVKWbVRtBWKWX9+CxGYfA51nSomhM0woR48= -mvdan.cc/gofumpt v0.1.1/go.mod h1:yXG1r1WqZVKWbVRtBWKWX9+CxGYfA51nSomhM0woR48= +mvdan.cc/gofumpt v0.2.0/go.mod h1:TiGmrf914DAuT6+hDIxOqoDb4QXIzAuEUSXqEf9hGKY= diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index e378843ff7..636e8a4e0b 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -15,6 +15,7 @@ import ( "github.com/hashicorp/go-multierror" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" + onlib "github.com/sourcegraph/sourcegraph/lib/batches/on" "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/batches" @@ -438,17 +439,18 @@ func (svc *Service) ResolveNamespace(ctx context.Context, namespace string) (str } func (svc *Service) ResolveRepositories(ctx context.Context, spec *batcheslib.BatchSpec) ([]*graphql.Repository, error) { - seen := map[string]*graphql.Repository{} + agg := onlib.NewRepoRevisionAggregator() unsupported := batches.UnsupportedRepoSet{} ignored := batches.IgnoredRepoSet{} // TODO: this could be trivially parallelised in the future. for _, on := range spec.On { - repos, err := svc.ResolveRepositoriesOn(ctx, &on) + repos, ruleType, err := svc.ResolveRepositoriesOn(ctx, &on) if err != nil { return nil, errors.Wrapf(err, "resolving %q", on.String()) } + result := agg.NewRuleRevisions(ruleType) reposWithBranch := make([]*graphql.Repository, 0, len(repos)) for _, repo := range repos { if !repo.HasBranch() { @@ -466,33 +468,27 @@ func (svc *Service) ResolveRepositories(ctx context.Context, spec *batcheslib.Ba } for _, repo := range reposWithBranch { - if other, ok := seen[repo.ID]; !ok { - seen[repo.ID] = repo - - switch st := strings.ToLower(repo.ExternalRepository.ServiceType); st { - case "github", "gitlab", "bitbucketserver": - default: - if !svc.allowUnsupported { - unsupported.Append(repo) - } + result.AddRepoRevision(repo.ID, repo) + + switch st := strings.ToLower(repo.ExternalRepository.ServiceType); st { + case "github", "gitlab", "bitbucketserver": + default: + if !svc.allowUnsupported { + unsupported.Append(repo) } + } - if !svc.allowIgnored { - if locations, ok := repoBatchIgnores[repo]; ok && len(locations) > 0 { - ignored.Append(repo) - } + if !svc.allowIgnored { + if locations, ok := repoBatchIgnores[repo]; ok && len(locations) > 0 { + ignored.Append(repo) } - } else { - // If we've already seen this repository, we overwrite the - // Commit/Branch fields with the latest value we have - other.Commit = repo.Commit - other.Branch = repo.Branch } } } - final := make([]*graphql.Repository, 0, len(seen)) - for _, repo := range seen { + final := []*graphql.Repository{} + for _, rev := range agg.Revisions() { + repo := rev.(*graphql.Repository) if !unsupported.Includes(repo) && !ignored.Includes(repo) { final = append(final, repo) } @@ -509,26 +505,40 @@ func (svc *Service) ResolveRepositories(ctx context.Context, spec *batcheslib.Ba return final, nil } -func (svc *Service) ResolveRepositoriesOn(ctx context.Context, on *batcheslib.OnQueryOrRepository) ([]*graphql.Repository, error) { +func (svc *Service) ResolveRepositoriesOn(ctx context.Context, on *batcheslib.OnQueryOrRepository) ([]*graphql.Repository, onlib.RepositoryRuleType, error) { if on.RepositoriesMatchingQuery != "" { - return svc.resolveRepositorySearch(ctx, on.RepositoriesMatchingQuery) - } else if on.Repository != "" && on.Branch != "" { - repo, err := svc.resolveRepositoryNameAndBranch(ctx, on.Repository, on.Branch) - if err != nil { - return nil, err - } - return []*graphql.Repository{repo}, nil + repo, err := svc.resolveRepositorySearch(ctx, on.RepositoriesMatchingQuery) + return repo, onlib.RepositoryRuleTypeQuery, err } else if on.Repository != "" { - repo, err := svc.resolveRepositoryName(ctx, on.Repository) + branches, err := on.GetBranches() if err != nil { - return nil, err + return nil, onlib.RepositoryRuleTypeExplicit, err + } + + if len(branches) > 0 { + repos := make([]*graphql.Repository, len(branches)) + for i, branch := range branches { + repo, err := svc.resolveRepositoryNameAndBranch(ctx, on.Repository, branch) + if err != nil { + return nil, onlib.RepositoryRuleTypeExplicit, err + } + + repos[i] = repo + } + + return repos, onlib.RepositoryRuleTypeExplicit, nil + } else { + repo, err := svc.resolveRepositoryName(ctx, on.Repository) + if err != nil { + return nil, onlib.RepositoryRuleTypeExplicit, err + } + return []*graphql.Repository{repo}, onlib.RepositoryRuleTypeExplicit, nil } - return []*graphql.Repository{repo}, nil } // This shouldn't happen on any batch spec that has passed validation, but, // alas, software. - return nil, ErrMalformedOnQueryOrRepository + return nil, onlib.RepositoryRuleTypeExplicit, ErrMalformedOnQueryOrRepository } const repositoryNameQuery = ` diff --git a/internal/batches/service/workspaces.go b/internal/batches/service/workspaces.go index 859ba2d6e1..d159f80169 100644 --- a/internal/batches/service/workspaces.go +++ b/internal/batches/service/workspaces.go @@ -35,11 +35,6 @@ func findWorkspaces( finder directoryFinder, repos []*graphql.Repository, ) ([]RepoWorkspace, error) { - repoByID := make(map[string]*graphql.Repository) - for _, repo := range repos { - repoByID[repo.ID] = repo - } - // Pre-compile all globs. workspaceMatchers := make(map[batcheslib.WorkspaceConfiguration]glob.Glob) for _, conf := range spec.Workspaces { @@ -88,7 +83,11 @@ func findWorkspaces( Paths []string OnlyFetchWorkspace bool } - workspacesByID := map[string]repoWorkspaces{} + type workspaceKey struct { + repo string + branch string + } + workspacesByKey := map[workspaceKey]repoWorkspaces{} for idx, repos := range matched { conf := spec.Workspaces[idx] repoDirs, err := finder.FindDirectoriesInRepos(ctx, conf.RootAtLocationOf, repos...) @@ -101,7 +100,11 @@ func findWorkspaces( if len(dirs) == 0 { continue } - workspacesByID[repo.ID] = repoWorkspaces{ + key := workspaceKey{ + repo: repo.ID, + branch: repo.Branch.Name, + } + workspacesByKey[key] = repoWorkspaces{ Repo: repo, Paths: dirs, OnlyFetchWorkspace: conf.OnlyFetchWorkspace, @@ -111,20 +114,24 @@ func findWorkspaces( // And add the root for repos. for _, repo := range root { - conf, ok := workspacesByID[repo.ID] + key := workspaceKey{ + repo: repo.ID, + branch: repo.Branch.Name, + } + conf, ok := workspacesByKey[key] if !ok { - workspacesByID[repo.ID] = repoWorkspaces{ + workspacesByKey[key] = repoWorkspaces{ Repo: repo, Paths: []string{""}, OnlyFetchWorkspace: false, } continue } - conf.Paths = append(workspacesByID[repo.ID].Paths, "") + conf.Paths = append(workspacesByKey[key].Paths, "") } - workspaces := make([]RepoWorkspace, 0, len(workspacesByID)) - for _, workspace := range workspacesByID { + workspaces := make([]RepoWorkspace, 0, len(workspacesByKey)) + for _, workspace := range workspacesByKey { for _, path := range workspace.Paths { fetchWorkspace := workspace.OnlyFetchWorkspace if path == "" { From 661cdaa9570c9fff3ef4ddba2603d17bcc4c93d3 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Fri, 17 Dec 2021 02:59:02 +0100 Subject: [PATCH 104/647] Prepare changelog for 3.35 --- CHANGELOG.md | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d0088b5511..62e96477b5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,16 @@ All notable changes to `src-cli` are documented in this file. ### Added +### Changed + +### Fixed + +### Removed + +## 3.35.0 + +### Added + - Individual batch changes can publish multiple changesets to the same repository by specifying multiple target branches using the [`on.branches`](https://docs.sourcegraph.com/batch_changes/references/batch_spec_yaml_reference#on-repository) attribute. [#25228](https://github.com/sourcegraph/sourcegraph/issues/25228) ### Changed @@ -25,8 +35,6 @@ All notable changes to `src-cli` are documented in this file. - `src` would sometimes panic when Ctrl-C was pressed while executing batch change steps due to a bug in the library used to render the execution progress bars. This has been fixed. [🤘 #666](https://github.com/sourcegraph/src-cli/pull/666) - In batch changes, when using `workspaces` src would incorrectly treat `in` not being set as _don't match anything_. This is fixed and it matches everything like `*`. [#664](https://github.com/sourcegraph/src-cli/pull/664) -### Removed - ## 3.34.1 ### Added From 7f7970155baf5e1a71d846978020fd7bec84144d Mon Sep 17 00:00:00 2001 From: Jean-Hadrien Chabran Date: Mon, 20 Dec 2021 23:15:45 +0100 Subject: [PATCH 105/647] Remove CSRF tokens fetching code (#673) * Remove CSRF tokens fetching code * Remove unused func * Update CHANGELOG. Co-authored-by: Adam Harvey --- CHANGELOG.md | 6 ++++ cmd/src/validate.go | 72 +++++---------------------------------------- 2 files changed, 14 insertions(+), 64 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 62e96477b5..ee240f3a3b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,12 @@ All notable changes to `src-cli` are documented in this file. ### Removed +## 3.35.1 + +### Changed + +- `src validate` has been updated to work with Sourcegraph 3.35's changed CSRF behaviour. [#673](https://github.com/sourcegraph/src-cli/pull/673) + ## 3.35.0 ### Added diff --git a/cmd/src/validate.go b/cmd/src/validate.go index 9652464829..6efe8f96ef 100644 --- a/cmd/src/validate.go +++ b/cmd/src/validate.go @@ -415,10 +415,7 @@ func (vd *validator) createAccessToken(username string) (string, error) { // SiteAdminInit initializes the instance with given admin account. // It returns an authenticated client as the admin for doing e2e testing. func (vd *validator) siteAdminInit(baseURL, email, username, password string) (*vdClient, error) { - client, err := vd.newClient(baseURL) - if err != nil { - return nil, err - } + client := vd.newClient(baseURL) var request = struct { Email string `json:"email"` @@ -429,7 +426,7 @@ func (vd *validator) siteAdminInit(baseURL, email, username, password string) (* Username: username, Password: password, } - err = client.authenticate("/-/site-init", request) + err := client.authenticate("/-/site-init", request) if err != nil { return nil, err } @@ -440,10 +437,7 @@ func (vd *validator) siteAdminInit(baseURL, email, username, password string) (* // SignIn performs the sign in with given user credentials. // It returns an authenticated client as the user for doing e2e testing. func (vd *validator) signIn(baseURL string, email, password string) (*vdClient, error) { - client, err := vd.newClient(baseURL) - if err != nil { - return nil, err - } + client := vd.newClient(baseURL) var request = struct { Email string `json:"email"` @@ -452,7 +446,7 @@ func (vd *validator) signIn(baseURL string, email, password string) (*vdClient, Email: email, Password: password, } - err = client.authenticate("/-/sign-in", request) + err := client.authenticate("/-/sign-in", request) if err != nil { return nil, err } @@ -460,68 +454,21 @@ func (vd *validator) signIn(baseURL string, email, password string) (*vdClient, return client, nil } -// extractCSRFToken extracts CSRF token from HTML response body. -func (vd *validator) extractCSRFToken(body string) string { - anchor := `X-Csrf-Token":"` - i := strings.Index(body, anchor) - if i == -1 { - return "" - } - - j := strings.Index(body[i+len(anchor):], `","`) - if j == -1 { - return "" - } - - return body[i+len(anchor) : i+len(anchor)+j] -} - // Client is an authenticated client for a Sourcegraph user for doing e2e testing. // The user may or may not be a site admin depends on how the client is instantiated. // It works by simulating how the browser would send HTTP requests to the server. type vdClient struct { baseURL string - csrfToken string - csrfCookie *http.Cookie sessionCookie *http.Cookie userID string } -// newClient instantiates a new client by performing a GET request then obtains the -// CSRF token and cookie from its response. -func (vd *validator) newClient(baseURL string) (*vdClient, error) { - resp, err := http.Get(baseURL) - if err != nil { - return nil, err - } - defer func() { _ = resp.Body.Close() }() - - p, err := io.ReadAll(resp.Body) - if err != nil { - return nil, err - } - - csrfToken := vd.extractCSRFToken(string(p)) - if csrfToken == "" { - return nil, err - } - var csrfCookie *http.Cookie - for _, cookie := range resp.Cookies() { - if cookie.Name == "sg_csrf_token" { - csrfCookie = cookie - break - } - } - if csrfCookie == nil { - return nil, errors.New(`"sg_csrf_token" cookie not found`) - } - +// newClient instantiates a new client. +func (vd *validator) newClient(baseURL string) *vdClient { return &vdClient{ - baseURL: baseURL, - csrfToken: csrfToken, - csrfCookie: csrfCookie, - }, nil + baseURL: baseURL, + } } // authenticate is used to send a HTTP POST request to an URL that is able to authenticate @@ -538,8 +485,6 @@ func (c *vdClient) authenticate(path string, body interface{}) error { return err } req.Header.Set("Content-Type", "application/json") - req.Header.Set("X-Csrf-Token", c.csrfToken) - req.AddCookie(c.csrfCookie) resp, err := http.DefaultClient.Do(req) if err != nil { @@ -643,7 +588,6 @@ func (c *vdClient) graphQL(token, query string, variables map[string]interface{} // NOTE: We use this header to protect from CSRF attacks of HTTP API, // see https://sourcegraph.com/github.com/sourcegraph/sourcegraph/-/blob/cmd/frontend/internal/cli/http.go#L41-42 req.Header.Set("X-Requested-With", "Sourcegraph") - req.AddCookie(c.csrfCookie) req.AddCookie(c.sessionCookie) } From 964ebf1ee5d5ba72b4113f4b7de1ebac29920b8c Mon Sep 17 00:00:00 2001 From: Stefan Hengl Date: Wed, 5 Jan 2022 10:22:00 +0100 Subject: [PATCH 106/647] search: use .api/search/stream (#674) This updates stream search to call .api/search/stream instead of /search/stream. We plan to retire /search/stream as soon as all clients have been migrated. Relates to https://github.com/sourcegraph/sourcegraph/issues/29399 --- internal/streaming/search.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/streaming/search.go b/internal/streaming/search.go index 36bfb16cf8..b4bc3aafa9 100644 --- a/internal/streaming/search.go +++ b/internal/streaming/search.go @@ -21,7 +21,7 @@ type Opts struct { // response body. func Search(query string, opts Opts, client api.Client, decoder Decoder) error { // Create request. - req, err := client.NewHTTPRequest(context.Background(), "GET", "search/stream?q="+url.QueryEscape(query), nil) + req, err := client.NewHTTPRequest(context.Background(), "GET", ".api/search/stream?q="+url.QueryEscape(query), nil) if err != nil { return err } From 090bba636ccc63112ffe935daa2e2836d7f84307 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Tue, 11 Jan 2022 14:39:56 +0100 Subject: [PATCH 107/647] Handle missing flags and correctly allow files in repos and validate commands (#675) --- CHANGELOG.md | 6 ++++++ cmd/src/batch_repositories.go | 20 +++++++++++++++++++- cmd/src/batch_validate.go | 19 ++++++++++++++++++- 3 files changed, 43 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ee240f3a3b..446ab3ed65 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,12 @@ All notable changes to `src-cli` are documented in this file. ### Removed +## 3.35.2 + +### Fixed + +- `src batch validate` and `src batch repos` now accept `-allow-unsupported` and `-force-override-ignore` and don't fail on specs using `files` anymore. + ## 3.35.1 ### Changed diff --git a/cmd/src/batch_repositories.go b/cmd/src/batch_repositories.go index 5d62e70d9f..84dcda2c4d 100644 --- a/cmd/src/batch_repositories.go +++ b/cmd/src/batch_repositories.go @@ -36,6 +36,19 @@ Examples: apiFlags = api.NewFlags(flagSet) ) + var ( + allowUnsupported bool + allowIgnored bool + ) + flagSet.BoolVar( + &allowUnsupported, "allow-unsupported", false, + "Allow unsupported code hosts.", + ) + flagSet.BoolVar( + &allowIgnored, "force-override-ignore", false, + "Do not ignore repositories that have a .batchignore file.", + ) + handler := func(args []string) error { if err := flagSet.Parse(args); err != nil { return err @@ -44,7 +57,12 @@ Examples: ctx := context.Background() client := cfg.apiClient(apiFlags, flagSet.Output()) - svc := service.New(&service.Opts{Client: client}) + svc := service.New(&service.Opts{ + Client: client, + AllowUnsupported: allowUnsupported, + AllowIgnored: allowIgnored, + AllowFiles: true, + }) if err := svc.DetermineFeatureFlags(ctx); err != nil { return err diff --git a/cmd/src/batch_validate.go b/cmd/src/batch_validate.go index 2b79dcd930..0f4a652d6b 100644 --- a/cmd/src/batch_validate.go +++ b/cmd/src/batch_validate.go @@ -6,6 +6,7 @@ import ( "fmt" "github.com/sourcegraph/sourcegraph/lib/output" + "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/batches/service" "github.com/sourcegraph/src-cli/internal/batches/ui" @@ -30,6 +31,19 @@ Examples: apiFlags := api.NewFlags(flagSet) fileFlag := flagSet.String("f", "", "The batch spec file to read.") + var ( + allowUnsupported bool + allowIgnored bool + ) + flagSet.BoolVar( + &allowUnsupported, "allow-unsupported", false, + "Allow unsupported code hosts.", + ) + flagSet.BoolVar( + &allowIgnored, "force-override-ignore", false, + "Do not ignore repositories that have a .batchignore file.", + ) + handler := func(args []string) error { ctx := context.Background() @@ -44,7 +58,10 @@ Examples: out := output.NewOutput(flagSet.Output(), output.OutputOpts{Verbose: *verbose}) ui := &ui.TUI{Out: out} svc := service.New(&service.Opts{ - Client: cfg.apiClient(apiFlags, flagSet.Output()), + Client: cfg.apiClient(apiFlags, flagSet.Output()), + AllowUnsupported: allowUnsupported, + AllowIgnored: allowIgnored, + AllowFiles: true, }) if err := svc.DetermineFeatureFlags(ctx); err != nil { From a79460b2b650afc6e202f164210a1c62f8444580 Mon Sep 17 00:00:00 2001 From: Eric Fritz Date: Tue, 11 Jan 2022 10:14:57 -0600 Subject: [PATCH 108/647] lsif upload: Update lib for QoL improvements (#676) --- cmd/src/lsif_upload.go | 5 ++++- go.mod | 7 +++++-- go.sum | 10 +++++++--- 3 files changed, 16 insertions(+), 6 deletions(-) diff --git a/cmd/src/lsif_upload.go b/cmd/src/lsif_upload.go index b3467625fe..7a338f3748 100644 --- a/cmd/src/lsif_upload.go +++ b/cmd/src/lsif_upload.go @@ -1,6 +1,7 @@ package main import ( + "context" "encoding/base64" "encoding/json" "flag" @@ -53,6 +54,8 @@ Examples: // handleLSIFUpload is the handler for `src lsif upload`. func handleLSIFUpload(args []string) error { + ctx := context.Background() + err := parseAndValidateLSIFUploadFlags(args) out := lsifUploadOutput() if !lsifUploadFlags.json { @@ -72,7 +75,7 @@ func handleLSIFUpload(args []string) error { Flags: lsifUploadFlags.apiFlags, }) - uploadID, err := upload.UploadIndex(lsifUploadFlags.file, client, lsifUploadOptions(out)) + uploadID, err := upload.UploadIndex(ctx, lsifUploadFlags.file, client, lsifUploadOptions(out)) if err != nil { return handleLSIFUploadError(out, err) } diff --git a/go.mod b/go.mod index 09e9fa7223..f4a18780ca 100644 --- a/go.mod +++ b/go.mod @@ -20,7 +20,7 @@ require ( github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4 github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf - github.com/sourcegraph/sourcegraph/lib v0.0.0-20211208022235-6e51851fbb8a + github.com/sourcegraph/sourcegraph/lib v0.0.0-20220111141528-d5d16cb1e80c github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f @@ -33,12 +33,15 @@ require ( github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f // indirect github.com/cockroachdb/sentry-go v0.6.1-cockroachdb.2 // indirect github.com/ghodss/yaml v1.0.0 // indirect + github.com/go-stack/stack v1.8.1 // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/hashicorp/errwrap v1.1.0 // indirect + github.com/inconshreveable/log15 v0.0.0-20201112154412-8562bdadbbac // indirect github.com/klauspost/compress v1.13.6 // indirect github.com/klauspost/pgzip v1.2.5 // indirect github.com/kr/pretty v0.3.0 // indirect github.com/kr/text v0.2.0 // indirect + github.com/mattn/go-colorable v0.1.12 // indirect github.com/mattn/go-runewidth v0.0.13 // indirect github.com/moby/term v0.0.0-20210619224110-3f7ff695adc6 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect @@ -49,7 +52,7 @@ require ( github.com/rogpeppe/go-internal v1.8.1-0.20211023094830-115ce09fd6b4 // indirect github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect github.com/xeipuuv/gojsonschema v1.2.0 // indirect - golang.org/x/sys v0.0.0-20211205182925-97ca703d548d // indirect + golang.org/x/sys v0.0.0-20220111092808-5a964db01320 // indirect golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect ) diff --git a/go.sum b/go.sum index 79edaa459c..33a4f67b36 100644 --- a/go.sum +++ b/go.sum @@ -76,6 +76,7 @@ github.com/go-check/check v0.0.0-20180628173108-788fd7840127/go.mod h1:9ES+weclK github.com/go-errors/errors v1.0.1 h1:LUHzmkK3GUKUrL/1gfBUxAHzcev3apQlezX/+O7ma6w= github.com/go-errors/errors v1.0.1/go.mod h1:f4zRHt4oKfwPJE5k8C9vpYG+aDHdBFUsgrm6/TyX73Q= github.com/go-martini/martini v0.0.0-20170121215854-22fa46961aab/go.mod h1:/P9AEU963A2AYjv4d1V5eVL1CQbEJq6aCNHDDjibzu8= +github.com/go-stack/stack v1.8.1 h1:ntEHSVwIt7PNXNpgPmVfMrNhLtgjlmnZha2kOpuRiDw= github.com/go-stack/stack v1.8.1/go.mod h1:dcoOX6HbPZSZptuspn9bctJ+N/CnF5gGygcUP3XYfe4= github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y= @@ -137,6 +138,7 @@ github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpO github.com/hydrogen18/memlistener v0.0.0-20141126152155-54553eb933fb/go.mod h1:qEIFzExnS6016fRpRfxrExeVn2gbClQA99gQhnIcdhE= github.com/hydrogen18/memlistener v0.0.0-20200120041712-dcc25e7acd91/go.mod h1:qEIFzExnS6016fRpRfxrExeVn2gbClQA99gQhnIcdhE= github.com/imkira/go-interpol v1.1.0/go.mod h1:z0h2/2T3XF8kyEPpRgJ3kmNv+C43p+I/CoI+jC3w2iA= +github.com/inconshreveable/log15 v0.0.0-20201112154412-8562bdadbbac h1:n1DqxAo4oWPMvH1+v+DLYlMCecgumhhgnxAPdqDIFHI= github.com/inconshreveable/log15 v0.0.0-20201112154412-8562bdadbbac/go.mod h1:cOaXtrgN4ScfRrD9Bre7U1thNq5RtJ8ZoP4iXVGRj6o= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/iris-contrib/blackfriday v2.0.0+incompatible/go.mod h1:UzZ2bDEoaSGPbkg6SAB4att1aAwTmVIx/5gCVqeyUdI= @@ -182,6 +184,7 @@ github.com/labstack/gommon v0.3.0/go.mod h1:MULnywXg0yavhxWKc+lOruYdAhDwPK9wf0OL github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= +github.com/mattn/go-colorable v0.1.12 h1:jF+Du6AlPIjs2BiUiQlKOX0rt3SujHxPnksPKZbaA40= github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= github.com/mattn/go-isatty v0.0.7/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= @@ -261,8 +264,8 @@ github.com/sourcegraph/go-diff v0.6.1 h1:hmA1LzxW0n1c3Q4YbrFgg4P99GSnebYa3x8gr0H github.com/sourcegraph/go-diff v0.6.1/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20211208022235-6e51851fbb8a h1:aUlkJEfmr1ujtMDz9n+S22JtfPa6yHW7RplYmSP7Lh4= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20211208022235-6e51851fbb8a/go.mod h1:7CQmAlg8hNhbWNIa4FA8d4X2L/G1b46/oLJxMCBO0O4= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20220111141528-d5d16cb1e80c h1:9fj+2jJW2JS1I82kwKMolYoy9/ycprrBP1BsdfSbEho= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20220111141528-d5d16cb1e80c/go.mod h1:7CQmAlg8hNhbWNIa4FA8d4X2L/G1b46/oLJxMCBO0O4= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= @@ -378,8 +381,9 @@ golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211102192858-4dd72447c267/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211117180635-dee7805ff2e1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20211205182925-97ca703d548d h1:FjkYO/PPp4Wi0EAUOVLxePm7qVW4r4ctbWpURyuOD0E= golang.org/x/sys v0.0.0-20211205182925-97ca703d548d/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220111092808-5a964db01320 h1:0jf+tOCoZ3LyutmCOWpVni1chK4VfFLhRsDK7MhqGRY= +golang.org/x/sys v0.0.0-20220111092808-5a964db01320/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= From cfcc3fb840f09ac4698d20dd94a86a3aa992e90f Mon Sep 17 00:00:00 2001 From: Kelli Rockwell Date: Wed, 12 Jan 2022 09:41:20 -0800 Subject: [PATCH 109/647] batches: encourage semver that prerelease versions are newer (#677) --- CHANGELOG.md | 2 ++ internal/api/version_check.go | 12 ++++++++++++ internal/batches/features.go | 23 +++++++++++++++-------- 3 files changed, 29 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 446ab3ed65..2adcf16a50 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,8 @@ All notable changes to `src-cli` are documented in this file. ### Fixed +- Certain Batch Changes features that previously would not work on prerelease versions of Sourcegraph will now work as expected again. + ### Removed ## 3.35.2 diff --git a/internal/api/version_check.go b/internal/api/version_check.go index 9bef90c370..41315b4121 100644 --- a/internal/api/version_check.go +++ b/internal/api/version_check.go @@ -6,6 +6,17 @@ import ( "github.com/Masterminds/semver" ) +// NOTE: A version with a prerelease suffix (e.g. the "-rc.3" of "3.35.1-rc.3") is not +// considered by semver to satisfy a constraint without a prerelease suffix, regardless of +// whether or not the major/minor/patch version is greater than or equal to that of the +// constraint. +// +// For example, the version "3.35.1-rc.3" is not considered to satisfy the constraint ">= +// 3.23.0". This is likely not the expected outcome. However, the same version IS +// considered to satisfy the constraint "3.23.0-0". Thus, it is recommended to pass a +// constraint with a minimum prerelease version suffix attached if comparisons to +// prerelease versions are ever expected. See +// https://github.com/Masterminds/semver#working-with-prerelease-versions for more. func CheckSourcegraphVersion(version, constraint, minDate string) (bool, error) { if version == "dev" || version == "0.0.0+dev" { return true, nil @@ -26,5 +37,6 @@ func CheckSourcegraphVersion(version, constraint, minDate string) (bool, error) if err != nil { return false, err } + return c.Check(v), nil } diff --git a/internal/batches/features.go b/internal/batches/features.go index 6a28a71e0c..40480e05cc 100644 --- a/internal/batches/features.go +++ b/internal/batches/features.go @@ -25,14 +25,21 @@ func (ff *FeatureFlags) SetFromVersion(version string) error { constraint string minDate string }{ - {&ff.AllowArrayEnvironments, ">= 3.23.0", "2020-11-24"}, - {&ff.IncludeAutoAuthorDetails, ">= 3.20.0", "2020-09-10"}, - {&ff.UseGzipCompression, ">= 3.21.0", "2020-10-12"}, - {&ff.AllowTransformChanges, ">= 3.23.0", "2020-12-11"}, - {&ff.AllowWorkspaces, ">= 3.25.0", "2021-01-29"}, - {&ff.BatchChanges, ">= 3.26.0", "2021-03-07"}, - {&ff.AllowConditionalExec, ">= 3.28.0", "2021-05-05"}, - {&ff.AllowOptionalPublished, ">= 3.30.0", "2021-06-21"}, + // NOTE: It's necessary to include a "-0" prerelease suffix on each constraint so that + // prereleases of future versions are still considered to satisfy the constraint. + // + // For example, the version "3.35.1-rc.3" is not considered to satisfy the constraint + // ">= 3.23.0". However, the same version IS considered to satisfy the constraint + // "3.23.0-0". See + // https://github.com/Masterminds/semver#working-with-prerelease-versions for more. + {&ff.AllowArrayEnvironments, ">= 3.23.0-0", "2020-11-24"}, + {&ff.IncludeAutoAuthorDetails, ">= 3.20.0-0", "2020-09-10"}, + {&ff.UseGzipCompression, ">= 3.21.0-0", "2020-10-12"}, + {&ff.AllowTransformChanges, ">= 3.23.0-0", "2020-12-11"}, + {&ff.AllowWorkspaces, ">= 3.25.0-0", "2021-01-29"}, + {&ff.BatchChanges, ">= 3.26.0-0", "2021-03-07"}, + {&ff.AllowConditionalExec, ">= 3.28.0-0", "2021-05-05"}, + {&ff.AllowOptionalPublished, ">= 3.30.0-0", "2021-06-21"}, } { value, err := api.CheckSourcegraphVersion(version, feature.constraint, feature.minDate) if err != nil { From 767b761a9ba39a11e72e6f6db5328215954b2ff5 Mon Sep 17 00:00:00 2001 From: Kelli Rockwell Date: Wed, 12 Jan 2022 15:30:03 -0800 Subject: [PATCH 110/647] batches: match on abbreviated commit hash in version (#678) --- internal/api/version_check.go | 6 +++++- internal/api/version_check_test.go | 33 ++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/internal/api/version_check.go b/internal/api/version_check.go index 41315b4121..1c5fa1435b 100644 --- a/internal/api/version_check.go +++ b/internal/api/version_check.go @@ -22,7 +22,11 @@ func CheckSourcegraphVersion(version, constraint, minDate string) (bool, error) return true, nil } - buildDate := regexp.MustCompile(`^\d+_(\d{4}-\d{2}-\d{2})_[a-z0-9]{7}$`) + // Since we don't actually care about the abbreviated commit hash at the end of the + // version string, we match on 7 or more characters. Currently, the Sourcegraph version + // is expected to return 12: + // https://sourcegraph.com/github.com/sourcegraph/sourcegraph/-/blob/enterprise/dev/ci/internal/ci/config.go?L96. + buildDate := regexp.MustCompile(`^\d+_(\d{4}-\d{2}-\d{2})_[a-z0-9]{7,}$`) matches := buildDate.FindStringSubmatch(version) if len(matches) > 1 { return matches[1] >= minDate, nil diff --git a/internal/api/version_check_test.go b/internal/api/version_check_test.go index 4942fbef72..fe8e0ee9f7 100644 --- a/internal/api/version_check_test.go +++ b/internal/api/version_check_test.go @@ -19,6 +19,12 @@ func TestCheckSourcegraphVersion(t *testing.T) { minDate: "2020-01-19", expected: true, }, + { + currentVersion: "3.12.6-rc.3", + constraint: ">= 3.10.6-0", + minDate: "2020-01-19", + expected: true, + }, { currentVersion: "3.12.6", constraint: ">= 3.13", @@ -43,6 +49,7 @@ func TestCheckSourcegraphVersion(t *testing.T) { minDate: "2020-01-19", expected: true, }, + // 7-character abbreviated hash { currentVersion: "54959_2020-01-29_9258595", minDate: "2020-01-19", @@ -61,6 +68,32 @@ func TestCheckSourcegraphVersion(t *testing.T) { constraint: ">= 0.0", expected: true, }, + // 12-character abbreviated hash + { + currentVersion: "54959_2020-01-29_925859585436", + minDate: "2020-01-19", + constraint: ">= 999.13", + expected: true, + }, + { + currentVersion: "54959_2020-01-29_925859585436", + minDate: "2020-01-30", + constraint: ">= 999.13", + expected: false, + }, + { + currentVersion: "54959_2020-01-29_925859585436", + minDate: "2020-01-29", + constraint: ">= 0.0", + expected: true, + }, + // Full 40-character hash, just for fun + { + currentVersion: "54959_2020-01-29_7db7d396346284fd0f8f79f130f38b16fb1d3d70", + minDate: "2020-01-29", + constraint: ">= 0.0", + expected: true, + }, } { actual, err := CheckSourcegraphVersion(tc.currentVersion, tc.constraint, tc.minDate) if err != nil { From f10b4ae797e57726e40dafb3a6e6cab82d3ba80c Mon Sep 17 00:00:00 2001 From: Kelli Rockwell Date: Wed, 12 Jan 2022 15:45:31 -0800 Subject: [PATCH 111/647] Prepare for release (#679) --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2adcf16a50..c871666a2d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,10 @@ All notable changes to `src-cli` are documented in this file. ### Fixed +## 3.35.3 + +### Fixed + - Certain Batch Changes features that previously would not work on prerelease versions of Sourcegraph will now work as expected again. ### Removed From ea6066be5fb4364df059803750a110651cd2959b Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Mon, 17 Jan 2022 20:49:54 +0100 Subject: [PATCH 112/647] Prepare changelog for 3.36.0 --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index c871666a2d..94350f22b7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,10 @@ All notable changes to `src-cli` are documented in this file. ### Fixed +## 3.36.0 + +_This version is the same as 3.35.3, just retagged for the upcoming 3.36.0 release of Sourcegraph._ + ## 3.35.3 ### Fixed From 1d078f838ca2130c5f3352478856e03d1daf9257 Mon Sep 17 00:00:00 2001 From: Noah S-C Date: Thu, 20 Jan 2022 14:45:07 +0000 Subject: [PATCH 113/647] bump sourcegraph/sourcegraph/lib (#683) --- go.mod | 2 +- go.sum | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index f4a18780ca..2f3801cff8 100644 --- a/go.mod +++ b/go.mod @@ -20,7 +20,7 @@ require ( github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4 github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf - github.com/sourcegraph/sourcegraph/lib v0.0.0-20220111141528-d5d16cb1e80c + github.com/sourcegraph/sourcegraph/lib v0.0.0-20220120143235-e3b0ce401473 github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f diff --git a/go.sum b/go.sum index 33a4f67b36..19a2d5ad30 100644 --- a/go.sum +++ b/go.sum @@ -264,8 +264,8 @@ github.com/sourcegraph/go-diff v0.6.1 h1:hmA1LzxW0n1c3Q4YbrFgg4P99GSnebYa3x8gr0H github.com/sourcegraph/go-diff v0.6.1/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20220111141528-d5d16cb1e80c h1:9fj+2jJW2JS1I82kwKMolYoy9/ycprrBP1BsdfSbEho= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20220111141528-d5d16cb1e80c/go.mod h1:7CQmAlg8hNhbWNIa4FA8d4X2L/G1b46/oLJxMCBO0O4= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20220120143235-e3b0ce401473 h1:vUttMqqXBA42hqbxWYyts864SElRdXKYGQgdxQkwxdA= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20220120143235-e3b0ce401473/go.mod h1:KhG6S/6YtG9eFdcXlfSD4ogB4qR8V6wLTLQd7x3ToAM= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= @@ -442,6 +442,7 @@ google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpAD google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= From 7f2d5a220fbbbeef4ed84b130e704c3dfd9d0f31 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Sat, 22 Jan 2022 02:29:00 +0100 Subject: [PATCH 114/647] Use latest lib version that allows files in SSBC (#682) --- CHANGELOG.md | 2 ++ cmd/src/batch_common.go | 1 - cmd/src/batch_exec.go | 1 - cmd/src/batch_repositories.go | 1 - cmd/src/batch_validate.go | 1 - go.mod | 6 +++--- go.sum | 10 ++++++---- internal/batches/service/service.go | 4 ---- 8 files changed, 11 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 94350f22b7..d792624002 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,8 @@ All notable changes to `src-cli` are documented in this file. ### Changed +- `src exec` now allows the `files:` property. (internal use only) + ### Fixed ## 3.36.0 diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index 3527ba5d32..56d2933546 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -209,7 +209,6 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp svc := service.New(&service.Opts{ AllowUnsupported: opts.flags.allowUnsupported, AllowIgnored: opts.flags.allowIgnored, - AllowFiles: true, Client: opts.client, }) diff --git a/cmd/src/batch_exec.go b/cmd/src/batch_exec.go index a6a0e9ff99..e44840ea2e 100644 --- a/cmd/src/batch_exec.go +++ b/cmd/src/batch_exec.go @@ -83,7 +83,6 @@ func executeBatchSpecInWorkspaces(ctx context.Context, ui *ui.JSONLines, opts ex svc := service.New(&service.Opts{ AllowUnsupported: opts.flags.allowUnsupported, AllowIgnored: opts.flags.allowIgnored, - AllowFiles: false, Client: opts.client, }) if err := svc.DetermineFeatureFlags(ctx); err != nil { diff --git a/cmd/src/batch_repositories.go b/cmd/src/batch_repositories.go index 84dcda2c4d..91fc493d1c 100644 --- a/cmd/src/batch_repositories.go +++ b/cmd/src/batch_repositories.go @@ -61,7 +61,6 @@ Examples: Client: client, AllowUnsupported: allowUnsupported, AllowIgnored: allowIgnored, - AllowFiles: true, }) if err := svc.DetermineFeatureFlags(ctx); err != nil { diff --git a/cmd/src/batch_validate.go b/cmd/src/batch_validate.go index 0f4a652d6b..271c42b97b 100644 --- a/cmd/src/batch_validate.go +++ b/cmd/src/batch_validate.go @@ -61,7 +61,6 @@ Examples: Client: cfg.apiClient(apiFlags, flagSet.Output()), AllowUnsupported: allowUnsupported, AllowIgnored: allowIgnored, - AllowFiles: true, }) if err := svc.DetermineFeatureFlags(ctx); err != nil { diff --git a/go.mod b/go.mod index 2f3801cff8..c35a25ae87 100644 --- a/go.mod +++ b/go.mod @@ -10,7 +10,7 @@ require ( github.com/dineshappavoo/basex v0.0.0-20170425072625-481a6f6dc663 github.com/dustin/go-humanize v1.0.0 github.com/gobwas/glob v0.2.3 - github.com/google/go-cmp v0.5.6 + github.com/google/go-cmp v0.5.7 github.com/hashicorp/go-multierror v1.1.1 github.com/jig/teereadcloser v0.0.0-20181016160506-953720c48e05 github.com/json-iterator/go v1.1.12 @@ -20,7 +20,7 @@ require ( github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4 github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf - github.com/sourcegraph/sourcegraph/lib v0.0.0-20220120143235-e3b0ce401473 + github.com/sourcegraph/sourcegraph/lib v0.0.0-20220122003450-8a45ff2c8826 github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f @@ -49,7 +49,7 @@ require ( github.com/olekukonko/tablewriter v0.0.5 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/rivo/uniseg v0.2.0 // indirect - github.com/rogpeppe/go-internal v1.8.1-0.20211023094830-115ce09fd6b4 // indirect + github.com/rogpeppe/go-internal v1.8.1 // indirect github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect github.com/xeipuuv/gojsonschema v1.2.0 // indirect golang.org/x/sys v0.0.0-20220111092808-5a964db01320 // indirect diff --git a/go.sum b/go.sum index 19a2d5ad30..5f3586827c 100644 --- a/go.sum +++ b/go.sum @@ -115,8 +115,9 @@ github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.6 h1:BKbKCqvP6I+rmFHt06ZmyQtvB8xAkWdhFyr0ZUNZcxQ= github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.7 h1:81/ik6ipDQS2aGcBfIN5dHDB36BwrStyeAQquSYCV4o= +github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE= github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= @@ -248,8 +249,9 @@ github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY= github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.6.2/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= -github.com/rogpeppe/go-internal v1.8.1-0.20211023094830-115ce09fd6b4 h1:Ha8xCaq6ln1a+R91Km45Oq6lPXj2Mla6CRJYcuV2h1w= github.com/rogpeppe/go-internal v1.8.1-0.20211023094830-115ce09fd6b4/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= +github.com/rogpeppe/go-internal v1.8.1 h1:geMPLpDpQOgVyCg5z5GoRwLHepNdb71NXb67XFkP+Eg= +github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= github.com/ryanuber/columnize v2.1.0+incompatible/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= github.com/sclevine/agouti v3.0.0+incompatible/go.mod h1:b4WX9W9L1sfQKXeJf1mUTLZKJ48R1S7H23Ji7oFO5Bw= @@ -264,8 +266,8 @@ github.com/sourcegraph/go-diff v0.6.1 h1:hmA1LzxW0n1c3Q4YbrFgg4P99GSnebYa3x8gr0H github.com/sourcegraph/go-diff v0.6.1/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20220120143235-e3b0ce401473 h1:vUttMqqXBA42hqbxWYyts864SElRdXKYGQgdxQkwxdA= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20220120143235-e3b0ce401473/go.mod h1:KhG6S/6YtG9eFdcXlfSD4ogB4qR8V6wLTLQd7x3ToAM= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20220122003450-8a45ff2c8826 h1:8AoxPHU5kpcAx1frcU1xHpLAjc2UZTYxD82BMOUp50Y= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20220122003450-8a45ff2c8826/go.mod h1:KhG6S/6YtG9eFdcXlfSD4ogB4qR8V6wLTLQd7x3ToAM= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index 636e8a4e0b..49c9adba91 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -28,7 +28,6 @@ import ( type Service struct { allowUnsupported bool allowIgnored bool - allowFiles bool client api.Client features batches.FeatureFlags imageCache *docker.ImageCache @@ -37,7 +36,6 @@ type Service struct { type Opts struct { AllowUnsupported bool AllowIgnored bool - AllowFiles bool Client api.Client } @@ -49,7 +47,6 @@ func New(opts *Opts) *Service { return &Service{ allowUnsupported: opts.AllowUnsupported, allowIgnored: opts.AllowIgnored, - allowFiles: opts.AllowFiles, client: opts.Client, imageCache: docker.NewImageCache(), } @@ -292,7 +289,6 @@ func (svc *Service) ParseBatchSpec(data []byte) (*batcheslib.BatchSpec, error) { AllowArrayEnvironments: svc.features.AllowArrayEnvironments, AllowTransformChanges: svc.features.AllowTransformChanges, AllowConditionalExec: svc.features.AllowConditionalExec, - AllowFiles: svc.allowFiles, }) if err != nil { return nil, errors.Wrap(err, "parsing batch spec") From 1cc1fb996f3dc8174e115c305e5e986a8d6c3331 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Sat, 22 Jan 2022 02:31:17 +0100 Subject: [PATCH 115/647] Prepare changelog for 3.36.1 (#685) --- CHANGELOG.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d792624002..cce5597ed7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,10 +15,14 @@ All notable changes to `src-cli` are documented in this file. ### Changed -- `src exec` now allows the `files:` property. (internal use only) - ### Fixed +## 3.36.1 + +### Changed + +- `src exec` now allows the `files:` property. (internal use only) + ## 3.36.0 _This version is the same as 3.35.3, just retagged for the upcoming 3.36.0 release of Sourcegraph._ From a0e47be1ac2f2c727b4cc6bee693fc8a7da02254 Mon Sep 17 00:00:00 2001 From: Manuel Ucles <78464298+mucles@users.noreply.github.com> Date: Mon, 24 Jan 2022 11:59:01 -0700 Subject: [PATCH 116/647] Update CHANGELOG.md (#684) --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index cce5597ed7..d3f19d5452 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ All notable changes to `src-cli` are documented in this file. ### Added ### Changed +- `src validate` can now execute default validation checks (add external service, clone repo, search repo, search non-indexed branch of that repo, remove external service) for Sourcegraph instance when no validation file is specified as well as continue to support JSON and YAML file validation files. ### Fixed From 9015a238e04527aed1447a243116ce24e9796aaf Mon Sep 17 00:00:00 2001 From: Manuel Ucles <78464298+mucles@users.noreply.github.com> Date: Mon, 24 Jan 2022 11:59:50 -0700 Subject: [PATCH 117/647] WIP: Script for Validating Sourcegraph Instance (#681) * WIP: Script for Validating Sourcegraph Instance Help validating instance by performing the following checks ( from a custom json / yaml file or will run defualt values if none are specified): - Add a code host - clone a repo - make a search for the repo - make an unindexed search on the repo. * fixes : the SleepBetweenTriesSeconds field not being read * Update cmd/src/validate.go Co-authored-by: Erik Seliger Co-authored-by: Manuel Ucles Co-authored-by: Erik Seliger --- cmd/src/validate.go | 68 ++++++++++++++++++++++++++++++++++++++------- 1 file changed, 58 insertions(+), 10 deletions(-) diff --git a/cmd/src/validate.go b/cmd/src/validate.go index 6efe8f96ef..f1ebc29385 100644 --- a/cmd/src/validate.go +++ b/cmd/src/validate.go @@ -33,9 +33,9 @@ type validationSpec struct { WaitRepoCloned struct { Repo string `yaml:"repo"` MaxTries int `yaml:"maxTries"` - SleepBetweenTriesSeconds int `yaml:"sleepBetweenTriesSecond"` + SleepBetweenTriesSeconds int `yaml:"sleepBetweenTriesSeconds"` } `yaml:"waitRepoCloned"` - SearchQuery string `yaml:"searchQuery"` + SearchQuery []string `yaml:"searchQuery"` ExternalService struct { Kind string `yaml:"kind"` DisplayName string `yaml:"displayName"` @@ -49,6 +49,28 @@ type validator struct { apiClient api.Client } +const defaultVspec = `{ + "externalService": { + "config": { + "url": "https://github.com", + "token": "{{ .github_token }}", + "orgs": [], + "repos": [ + "gorilla/mux" + ] + }, + "kind": "GITHUB", + "displayName": "footest", + "deleteWhenDone": true + }, + "waitRepoCloned": { + "repo": "github.com/gorilla/mux", + "maxTries": 5, + "sleepBetweenTriesSeconds": 5 + }, + "searchQuery": ["repo:^github.com/gorilla/mux$ Router", "repo:^github.com/gorilla/mux$@v1.8.0 Router"] +}` + func init() { usage := `'src validate' is a tool that validates a Sourcegraph instance. @@ -60,6 +82,10 @@ Usage: or cat src-validate.yml | src validate [options] +if user is authenticated, user can also run default checks + + src validate [options] + Please visit https://docs.sourcegraph.com/admin/validation for documentation of the validate command. ` flagSet := flag.NewFlagSet("validate", flag.ExitOnError) @@ -88,6 +114,7 @@ Please visit https://docs.sourcegraph.com/admin/validation for documentation of var script []byte var isYaml bool + var isJSON bool var err error if len(flagSet.Args()) == 1 { @@ -99,6 +126,9 @@ Please visit https://docs.sourcegraph.com/admin/validation for documentation of if strings.HasSuffix(filename, ".yaml") || strings.HasSuffix(filename, ".yml") { isYaml = true } + if strings.HasSuffix(filename, ".json") { + isJSON = true + } } if !isatty.IsTerminal(os.Stdin.Fd()) { // stdin is a pipe not a terminal @@ -109,6 +139,11 @@ Please visit https://docs.sourcegraph.com/admin/validation for documentation of isYaml = true } + if !isYaml && !isJSON { + script = []byte(defaultVspec) + + } + ctxm := vd.parseKVPairs(*contextFlag, ",") if *secretsFlag != "" { @@ -123,6 +158,7 @@ Please visit https://docs.sourcegraph.com/admin/validation for documentation of } return vd.validate(script, ctxm, isYaml) + } commands = append(commands, &command{ @@ -198,32 +234,44 @@ func (vd *validator) validate(script []byte, scriptContext map[string]string, is if err != nil { return err } + fmt.Printf("External Service %s is being added \n", vspec.ExternalService.DisplayName) defer func() { if extSvcID != "" && vspec.ExternalService.DeleteWhenDone { _ = vd.deleteExternalService(extSvcID) + fmt.Printf("External Service %s has been removed \n", vspec.ExternalService.DisplayName) + fmt.Println("Validation Completed") + } }() } if vspec.WaitRepoCloned.Repo != "" { + fmt.Printf("repo %s clonining has began \n", vspec.WaitRepoCloned.Repo) + cloned, err := vd.waitRepoCloned(vspec.WaitRepoCloned.Repo, vspec.WaitRepoCloned.SleepBetweenTriesSeconds, vspec.WaitRepoCloned.MaxTries) if err != nil { return err } if !cloned { - return fmt.Errorf("repo %s didn't clone", vspec.WaitRepoCloned.Repo) + return fmt.Errorf("repo %s didn't clone \n", vspec.WaitRepoCloned.Repo) } + + fmt.Printf("repo %s clonining was successful \n", vspec.WaitRepoCloned.Repo) + } - if vspec.SearchQuery != "" { - matchCount, err := vd.searchMatchCount(vspec.SearchQuery) - if err != nil { - return err - } - if matchCount == 0 { - return fmt.Errorf("search query %s returned no results", vspec.SearchQuery) + if vspec.SearchQuery != nil { + for i := 0; i < len(vspec.SearchQuery); i++ { + matchCount, err := vd.searchMatchCount(vspec.SearchQuery[i]) + if err != nil { + return err + } + if matchCount == 0 { + return fmt.Errorf("search query %s returned no results \n", vspec.SearchQuery[i]) + } + fmt.Printf("search query '%s' was successful \n", vspec.SearchQuery[i]) } } From 3bddc5819e2fa94a8c8a95db758d01878dbe832c Mon Sep 17 00:00:00 2001 From: Henrik Poulsen Date: Mon, 31 Jan 2022 23:38:04 +0100 Subject: [PATCH 118/647] Fix errors be ignored and not printed (#686) --- cmd/src/batch_common.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index 56d2933546..8a336e6c6e 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -325,10 +325,10 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp importedSpecs, importErr := svc.CreateImportChangesetSpecs(ctx, batchSpec) var errs *multierror.Error if execErr != nil { - err = multierror.Append(err, execErr) + errs = multierror.Append(errs, execErr) } if importErr != nil { - err = multierror.Append(err, importErr) + errs = multierror.Append(errs, importErr) } err = errs.ErrorOrNil() if err != nil && !opts.flags.skipErrors { From 8a5129c253985967899dba54af83862aa510daab Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Tue, 1 Feb 2022 02:08:02 +0100 Subject: [PATCH 119/647] Prepare changelog for 3.36.2 --- CHANGELOG.md | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d3f19d5452..9dcbf6c1ef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,10 +14,21 @@ All notable changes to `src-cli` are documented in this file. ### Added ### Changed -- `src validate` can now execute default validation checks (add external service, clone repo, search repo, search non-indexed branch of that repo, remove external service) for Sourcegraph instance when no validation file is specified as well as continue to support JSON and YAML file validation files. ### Fixed +### Removed + +## 3.36.2 + +### Changed + +- `src validate` can now execute default validation checks (add external service, clone repo, search repo, search non-indexed branch of that repo, remove external service) for Sourcegraph instance when no validation file is specified as well as continue to support JSON and YAML file validation files. + +### Fixed + +- `src batch preview` and `src batch apply` could erroneously return exit code 0 and no warning when the execution actually failed. + ## 3.36.1 ### Changed @@ -34,8 +45,6 @@ _This version is the same as 3.35.3, just retagged for the upcoming 3.36.0 relea - Certain Batch Changes features that previously would not work on prerelease versions of Sourcegraph will now work as expected again. -### Removed - ## 3.35.2 ### Fixed From ee56d9515c660be52daff6d6a9a21095643cfeb8 Mon Sep 17 00:00:00 2001 From: Adam Harvey Date: Tue, 1 Feb 2022 13:33:59 -0800 Subject: [PATCH 120/647] batches: make `-f` optional (#687) Co-authored-by: Erik Seliger --- CHANGELOG.md | 2 ++ cmd/src/batch_apply.go | 7 +++-- cmd/src/batch_common.go | 50 ++++++++++++++++++++++++++++++----- cmd/src/batch_exec.go | 2 +- cmd/src/batch_preview.go | 16 ++++++----- cmd/src/batch_repositories.go | 13 ++++++--- cmd/src/batch_validate.go | 13 ++++++--- go.mod | 1 + go.sum | 2 ++ internal/batches/ui/tty.go | 19 +++++++++++++ 10 files changed, 103 insertions(+), 22 deletions(-) create mode 100644 internal/batches/ui/tty.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 9dcbf6c1ef..c1e96a02d2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,8 @@ All notable changes to `src-cli` are documented in this file. ### Changed +- `src batch` commands no longer require `-f` to read from a file. Additionally, running a `src batch` command that requires a batch spec file without a `-f` option from the terminal will now generate an error instead of waiting indefinitely for a batch spec on standard input; however, piping in a batch spec will still work as expected. [#687](https://github.com/sourcegraph/src-cli/pull/687) + ### Fixed ### Removed diff --git a/cmd/src/batch_apply.go b/cmd/src/batch_apply.go index 1a1d047aa1..59fe1700f3 100644 --- a/cmd/src/batch_apply.go +++ b/cmd/src/batch_apply.go @@ -18,14 +18,17 @@ creating or updating the described batch change if necessary. Usage: - src batch apply -f FILE [command options] + src batch apply [command options] [-f FILE] + src batch apply [command options] FILE Examples: $ src batch apply -f batch.spec.yaml - + $ src batch apply -f batch.spec.yaml -namespace myorg + $ src batch apply batch.spec.yaml + ` flagSet := flag.NewFlagSet("apply", flag.ExitOnError) diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index 8a336e6c6e..2bd3dee18d 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -15,6 +15,7 @@ import ( "github.com/cockroachdb/errors" "github.com/hashicorp/go-multierror" + "github.com/mattn/go-isatty" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" @@ -97,7 +98,7 @@ func newBatchExecuteFlags(flagSet *flag.FlagSet, workspaceExecution bool, cacheD flagSet.StringVar( &caf.file, "f", "", - "The batch spec file to read.", + "The batch spec file to read, or - to read from standard input.", ) flagSet.IntVar( @@ -127,6 +128,23 @@ func newBatchExecuteFlags(flagSet *flag.FlagSet, workspaceExecution bool, cacheD return caf } +var errAdditionalArguments = cmderrors.Usage("additional arguments not allowed") + +func getBatchSpecFile(flagSet *flag.FlagSet, fileFlag *string) (string, error) { + if fileFlag == nil || *fileFlag != "" { + if flagSet.NArg() != 0 { + return "", errAdditionalArguments + } + if fileFlag == nil { + return "", nil + } + return *fileFlag, nil + } else if flagSet.NArg() > 1 { + return "", errAdditionalArguments + } + return flagSet.Arg(0), nil +} + func batchDefaultCacheDir() string { uc, err := os.UserCacheDir() if err != nil { @@ -176,14 +194,31 @@ func batchDefaultTempDirPrefix() string { return os.TempDir() } -func batchOpenFileFlag(flag *string) (io.ReadCloser, error) { - if flag == nil || *flag == "" || *flag == "-" { +func batchOpenFileFlag(flag string) (io.ReadCloser, error) { + if flag == "" || flag == "-" { + if flag != "-" { + // If the flag wasn't set, we want to check stdin. If it's not a TTY, + // then we'll assume that we always want to read from it. If it is a TTY, + // then we'll briefly pause to see if data is getting piped in, otherwise + // we'll error out, because it's likely that the user forgot the `-f` on + // the command line. + fd := os.Stdin.Fd() + if isatty.IsTerminal(fd) { + has, err := ui.HasInput(os.Stdin.Fd(), 250*time.Millisecond) + if err != nil { + return nil, errors.Wrap(err, "checking for input on stdin") + } else if !has { + return nil, errors.New("-f specified, but no input was detected on stdin; did you forget to pipe a batch spec in?") + } + } + } + return os.Stdin, nil } - file, err := os.Open(*flag) + file, err := os.Open(flag) if err != nil { - return nil, errors.Wrapf(err, "cannot open file %q", *flag) + return nil, errors.Wrapf(err, "cannot open file %s", flag) } return file, nil } @@ -192,6 +227,7 @@ type executeBatchSpecOpts struct { flags *batchExecuteFlags applyBatchSpec bool + file string client api.Client } @@ -226,7 +262,7 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp // Parse flags and build up our service and executor options. ui.ParsingBatchSpec() - batchSpec, rawSpec, err := parseBatchSpec(&opts.flags.file, svc) + batchSpec, rawSpec, err := parseBatchSpec(opts.file, svc) if err != nil { var multiErr *multierror.Error if errors.As(err, &multiErr) { @@ -403,7 +439,7 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp // parseBatchSpec parses and validates the given batch spec. If the spec has // validation errors, they are returned. -func parseBatchSpec(file *string, svc *service.Service) (*batcheslib.BatchSpec, string, error) { +func parseBatchSpec(file string, svc *service.Service) (*batcheslib.BatchSpec, string, error) { f, err := batchOpenFileFlag(file) if err != nil { return nil, "", err diff --git a/cmd/src/batch_exec.go b/cmd/src/batch_exec.go index e44840ea2e..d6700c9fda 100644 --- a/cmd/src/batch_exec.go +++ b/cmd/src/batch_exec.go @@ -170,7 +170,7 @@ func executeBatchSpecInWorkspaces(ctx context.Context, ui *ui.JSONLines, opts ex func loadWorkspaceExecutionInput(file string) (batcheslib.WorkspacesExecutionInput, error) { var input batcheslib.WorkspacesExecutionInput - f, err := batchOpenFileFlag(&file) + f, err := batchOpenFileFlag(file) if err != nil { return input, err } diff --git a/cmd/src/batch_preview.go b/cmd/src/batch_preview.go index 13533a8879..239dc2d8eb 100644 --- a/cmd/src/batch_preview.go +++ b/cmd/src/batch_preview.go @@ -18,12 +18,15 @@ Sourcegraph instance, ready to be previewed and applied. Usage: - src batch preview -f FILE [command options] + src batch preview [command options] [-f FILE] + src batch preview [command options] FILE Examples: $ src batch preview -f batch.spec.yaml + $ src batch preview batch.spec.yaml + ` flagSet := flag.NewFlagSet("preview", flag.ExitOnError) @@ -34,8 +37,9 @@ Examples: return err } - if len(flagSet.Args()) != 0 { - return cmderrors.Usage("additional arguments not allowed") + file, err := getBatchSpecFile(flagSet, &flags.file) + if err != nil { + return err } ctx, cancel := contextCancelOnInterrupt(context.Background()) @@ -49,14 +53,14 @@ Examples: execUI = &ui.TUI{Out: out} } - err := executeBatchSpec(ctx, execUI, executeBatchSpecOpts{ + if err = executeBatchSpec(ctx, execUI, executeBatchSpecOpts{ flags: flags, client: cfg.apiClient(flags.api, flagSet.Output()), + file: file, // Do not apply the uploaded batch spec applyBatchSpec: false, - }) - if err != nil { + }); err != nil { return cmderrors.ExitCode(1, nil) } diff --git a/cmd/src/batch_repositories.go b/cmd/src/batch_repositories.go index 91fc493d1c..927849ad48 100644 --- a/cmd/src/batch_repositories.go +++ b/cmd/src/batch_repositories.go @@ -21,10 +21,12 @@ apply to. Usage: - src batch repositories -f FILE + src batch repositories [-f] FILE Examples: + $ src batch repositories batch.spec.yaml + $ src batch repositories -f batch.spec.yaml ` @@ -32,7 +34,7 @@ Examples: flagSet := flag.NewFlagSet("repositories", flag.ExitOnError) var ( - fileFlag = flagSet.String("f", "", "The batch spec file to read.") + fileFlag = flagSet.String("f", "", "The batch spec file to read, or - to read from standard input.") apiFlags = api.NewFlags(flagSet) ) @@ -67,8 +69,13 @@ Examples: return err } + var file string + if fileFlag != nil { + file = *fileFlag + } + out := output.NewOutput(flagSet.Output(), output.OutputOpts{Verbose: *verbose}) - spec, _, err := parseBatchSpec(fileFlag, svc) + spec, _, err := parseBatchSpec(file, svc) if err != nil { ui := &ui.TUI{Out: out} ui.ParsingBatchSpecFailure(err) diff --git a/cmd/src/batch_validate.go b/cmd/src/batch_validate.go index 271c42b97b..635d30a2e4 100644 --- a/cmd/src/batch_validate.go +++ b/cmd/src/batch_validate.go @@ -19,17 +19,19 @@ func init() { Usage: - src batch validate -f FILE + src batch validate [-f] FILE Examples: + $ src batch validate batch.spec.yaml + $ src batch validate -f batch.spec.yaml ` flagSet := flag.NewFlagSet("validate", flag.ExitOnError) apiFlags := api.NewFlags(flagSet) - fileFlag := flagSet.String("f", "", "The batch spec file to read.") + fileFlag := flagSet.String("f", "", "The batch spec file to read, or - to read from standard input.") var ( allowUnsupported bool @@ -68,7 +70,12 @@ Examples: return err } - if _, _, err := parseBatchSpec(fileFlag, svc); err != nil { + file, err := getBatchSpecFile(flagSet, fileFlag) + if err != nil { + return err + } + + if _, _, err := parseBatchSpec(file, svc); err != nil { ui.ParsingBatchSpecFailure(err) return err } diff --git a/go.mod b/go.mod index c35a25ae87..c0ea858c15 100644 --- a/go.mod +++ b/go.mod @@ -6,6 +6,7 @@ require ( github.com/Masterminds/semver v1.5.0 github.com/cockroachdb/errors v1.8.6 github.com/cockroachdb/redact v1.1.3 // indirect + github.com/creack/goselect v0.1.2 github.com/derision-test/glock v0.0.0-20210316032053-f5b74334bb29 github.com/dineshappavoo/basex v0.0.0-20170425072625-481a6f6dc663 github.com/dustin/go-humanize v1.0.0 diff --git a/go.sum b/go.sum index 5f3586827c..c32a5d7090 100644 --- a/go.sum +++ b/go.sum @@ -38,6 +38,8 @@ github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE= +github.com/creack/goselect v0.1.2 h1:2DNy14+JPjRBgPzAd1thbQp4BSIihxcBf0IXhQXDRa0= +github.com/creack/goselect v0.1.2/go.mod h1:a/NhLweNvqIYMuxcMOuWY516Cimucms3DglDzQP3hKY= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/creack/pty v1.1.11 h1:07n33Z8lZxZ2qwegKbObQohDhXDQxiMMz1NOUGYlesw= github.com/creack/pty v1.1.11/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= diff --git a/internal/batches/ui/tty.go b/internal/batches/ui/tty.go new file mode 100644 index 0000000000..3155a76c1c --- /dev/null +++ b/internal/batches/ui/tty.go @@ -0,0 +1,19 @@ +package ui + +import ( + "time" + + "github.com/creack/goselect" +) + +func HasInput(fd uintptr, timeout time.Duration) (bool, error) { + rfds := &goselect.FDSet{} + rfds.Zero() + rfds.Set(fd) + + if err := goselect.Select(1, rfds, nil, nil, timeout); err != nil { + return false, err + } + + return rfds.IsSet(fd), nil +} From 1a868b75118f8ad241c5a8d25d40b5ec47e09543 Mon Sep 17 00:00:00 2001 From: Kelli Rockwell Date: Thu, 3 Feb 2022 08:14:52 -0800 Subject: [PATCH 121/647] batches: fail earlier on dotcom (#688) --- CHANGELOG.md | 2 ++ internal/batches/service/service.go | 14 +++++++++++--- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c1e96a02d2..a7cfe6dd6b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,8 @@ All notable changes to `src-cli` are documented in this file. ### Fixed +- `src batch [preview|apply]` will now check that the target Sourcegraph instance supports batch changes before doing any other work and exit early in the case that it does not. + ### Removed ## 3.36.2 diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index 49c9adba91..057b25da4f 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -52,12 +52,20 @@ func New(opts *Opts) *Service { } } +// The reason we ask for batchChanges here is to surface errors about trying to use batch +// changes in an unsupported environment sooner, since the version check is typically the +// first thing we do. const sourcegraphVersionQuery = `query SourcegraphVersion { site { - productVersion + productVersion } - } - ` + batchChanges(first: 1) { + nodes { + id + } + } +} +` // getSourcegraphVersion queries the Sourcegraph GraphQL API to get the // current version of the Sourcegraph instance. From 2ff8cd5d8a1147bb809798e72d26b13b86a2e4f0 Mon Sep 17 00:00:00 2001 From: Adam Harvey Date: Fri, 4 Feb 2022 11:33:34 -0800 Subject: [PATCH 122/647] batches: pull images in parallel (#647) Closes https://github.com/sourcegraph/sourcegraph/issues/17577. --- CHANGELOG.md | 1 + cmd/src/batch_common.go | 5 +- cmd/src/batch_exec.go | 5 +- go.mod | 3 + internal/batches/docker/cache.go | 14 +- internal/batches/mock/cache.go | 11 ++ .../batches/mock/docker_image_progress.go | 16 +++ internal/batches/service/service.go | 102 ++++++++++++-- internal/batches/service/service_test.go | 129 ++++++++++++++++++ 9 files changed, 266 insertions(+), 20 deletions(-) create mode 100644 internal/batches/mock/cache.go create mode 100644 internal/batches/mock/docker_image_progress.go diff --git a/CHANGELOG.md b/CHANGELOG.md index a7cfe6dd6b..82f201b123 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,7 @@ All notable changes to `src-cli` are documented in this file. ### Changed - `src batch` commands no longer require `-f` to read from a file. Additionally, running a `src batch` command that requires a batch spec file without a `-f` option from the terminal will now generate an error instead of waiting indefinitely for a batch spec on standard input; however, piping in a batch spec will still work as expected. [#687](https://github.com/sourcegraph/src-cli/pull/687) +- Pulling container images now occurs in parallel, with the number of concurrent downloads being controlled by the `-j` flag. [#17577](https://github.com/sourcegraph/sourcegraph/issues/17577) ### Fixed diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index 2bd3dee18d..5305165522 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -287,7 +287,10 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp if len(batchSpec.Steps) > 0 { ui.PreparingContainerImages() - images, err := svc.EnsureDockerImages(ctx, batchSpec.Steps, ui.PreparingContainerImagesProgress) + images, err := svc.EnsureDockerImages( + ctx, batchSpec.Steps, opts.flags.parallelism, + ui.PreparingContainerImagesProgress, + ) if err != nil { return err } diff --git a/cmd/src/batch_exec.go b/cmd/src/batch_exec.go index d6700c9fda..aea370a189 100644 --- a/cmd/src/batch_exec.go +++ b/cmd/src/batch_exec.go @@ -111,7 +111,10 @@ func executeBatchSpecInWorkspaces(ctx context.Context, ui *ui.JSONLines, opts ex if len(input.Workspace.Steps) > 0 { ui.PreparingContainerImages() - images, err := svc.EnsureDockerImages(ctx, input.Workspace.Steps, ui.PreparingContainerImagesProgress) + images, err := svc.EnsureDockerImages( + ctx, input.Workspace.Steps, opts.flags.parallelism, + ui.PreparingContainerImagesProgress, + ) if err != nil { return err } diff --git a/go.mod b/go.mod index c0ea858c15..29b7e0a22e 100644 --- a/go.mod +++ b/go.mod @@ -33,6 +33,7 @@ require ( github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f // indirect github.com/cockroachdb/sentry-go v0.6.1-cockroachdb.2 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect github.com/ghodss/yaml v1.0.0 // indirect github.com/go-stack/stack v1.8.1 // indirect github.com/gogo/protobuf v1.3.2 // indirect @@ -49,8 +50,10 @@ require ( github.com/modern-go/reflect2 v1.0.2 // indirect github.com/olekukonko/tablewriter v0.0.5 // indirect github.com/pkg/errors v0.9.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect github.com/rivo/uniseg v0.2.0 // indirect github.com/rogpeppe/go-internal v1.8.1 // indirect + github.com/stretchr/testify v1.7.0 // indirect github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect github.com/xeipuuv/gojsonschema v1.2.0 // indirect golang.org/x/sys v0.0.0-20220111092808-5a964db01320 // indirect diff --git a/internal/batches/docker/cache.go b/internal/batches/docker/cache.go index 798b2cae56..a2d9771060 100644 --- a/internal/batches/docker/cache.go +++ b/internal/batches/docker/cache.go @@ -2,15 +2,19 @@ package docker import "sync" -// ImageCache is a cache of metadata about Docker images, indexed by name. -type ImageCache struct { +type ImageCache interface { + Get(name string) Image +} + +// imageCache is a cache of metadata about Docker images, indexed by name. +type imageCache struct { images map[string]Image imagesMu sync.Mutex } // NewImageCache creates a new image cache. -func NewImageCache() *ImageCache { - return &ImageCache{ +func NewImageCache() ImageCache { + return &imageCache{ images: make(map[string]Image), } } @@ -18,7 +22,7 @@ func NewImageCache() *ImageCache { // Get returns the image cache entry for the given Docker image. The name may be // anything the Docker command line will accept as an image name: this will // generally be IMAGE or IMAGE:TAG. -func (ic *ImageCache) Get(name string) Image { +func (ic *imageCache) Get(name string) Image { ic.imagesMu.Lock() defer ic.imagesMu.Unlock() diff --git a/internal/batches/mock/cache.go b/internal/batches/mock/cache.go new file mode 100644 index 0000000000..7f4b6466f6 --- /dev/null +++ b/internal/batches/mock/cache.go @@ -0,0 +1,11 @@ +package mock + +import "github.com/sourcegraph/src-cli/internal/batches/docker" + +type ImageCache struct { + Images map[string]docker.Image +} + +var _ docker.ImageCache = &ImageCache{} + +func (c *ImageCache) Get(name string) docker.Image { return c.Images[name] } diff --git a/internal/batches/mock/docker_image_progress.go b/internal/batches/mock/docker_image_progress.go new file mode 100644 index 0000000000..477a39fe90 --- /dev/null +++ b/internal/batches/mock/docker_image_progress.go @@ -0,0 +1,16 @@ +package mock + +type ProgressCall struct { + Done int + Total int +} + +type Progress struct { + Calls []ProgressCall +} + +func (p *Progress) Callback() func(int, int) { + return func(done, total int) { + p.Calls = append(p.Calls, ProgressCall{done, total}) + } +} diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index 057b25da4f..e3a55b004a 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -10,6 +10,7 @@ import ( "path" "regexp" "strings" + "sync" "github.com/cockroachdb/errors" "github.com/hashicorp/go-multierror" @@ -30,7 +31,7 @@ type Service struct { allowIgnored bool client api.Client features batches.FeatureFlags - imageCache *docker.ImageCache + imageCache docker.ImageCache } type Opts struct { @@ -162,23 +163,98 @@ func (svc *Service) CreateChangesetSpec(ctx context.Context, spec *batcheslib.Ch // images exist and to determine the exact content digest to be used when running // each step, including any required by the service itself. // -// Progress information is reported back to the given progress function: perc -// will be a value between 0.0 and 1.0, inclusive. -func (svc *Service) EnsureDockerImages(ctx context.Context, steps []batcheslib.Step, progress func(done, total int)) (map[string]docker.Image, error) { - total := len(steps) +// Progress information is reported back to the given progress function. +func (svc *Service) EnsureDockerImages( + ctx context.Context, + steps []batcheslib.Step, + parallelism int, + progress func(done, total int), +) (map[string]docker.Image, error) { + // Figure out the image names used in the batch spec. + names := map[string]struct{}{} + for i := range steps { + names[steps[i].Container] = struct{}{} + } + + total := len(names) progress(0, total) - // TODO: this _really_ should be parallelised, since the image cache takes - // care to only pull the same image once. + // Set up the channels that will be used in the parallel goroutines handling + // the pulls. + type image struct { + name string + image docker.Image + err error + } + complete := make(chan image) + inputs := make(chan string, total) + + // Set up a worker context that we can use to terminate the workers if an + // error occurs. + workerCtx, cancel := context.WithCancel(ctx) + defer cancel() + + // Spawn worker goroutines to call EnsureImage on each image name. + if parallelism < 1 { + parallelism = 1 + } + var wg sync.WaitGroup + for i := 0; i < parallelism; i++ { + wg.Add(1) + go func() { + defer wg.Done() + for { + select { + case <-workerCtx.Done(): + // If the worker context has been cancelled, then we just want to + // return immediately, rather than continuing to read from inputs. + return + case name, more := <-inputs: + if !more { + return + } + img, err := svc.EnsureImage(workerCtx, name) + select { + case <-workerCtx.Done(): + return + case complete <- image{ + name: name, + image: img, + err: err, + }: + // All good; let's move onto the next input. + } + } + } + }() + } + + go func() { + wg.Wait() + close(complete) + }() + + // Send the image names to the worker goroutines. + go func() { + for name := range names { + inputs <- name + } + close(inputs) + }() + + // Receive the results of the image pulls and build the return value. + i := 0 images := make(map[string]docker.Image) - for i := range steps { - img, err := svc.EnsureImage(ctx, steps[i].Container) - if err != nil { - return nil, err + for image := range complete { + if image.err != nil { + // If EnsureImage errored, then we'll early return here and let the + // worker context clean things up. + return nil, image.err } - images[steps[i].Container] = img - progress(i+1, total) + images[image.name] = image.image + i += 1 + progress(i, total) } return images, nil diff --git a/internal/batches/service/service_test.go b/internal/batches/service/service_test.go index 5aa98aedaa..e21d611b52 100644 --- a/internal/batches/service/service_test.go +++ b/internal/batches/service/service_test.go @@ -3,19 +3,25 @@ package service import ( "bytes" "context" + "fmt" "net/http" "net/http/httptest" + "strconv" "strings" "testing" + "github.com/cockroachdb/errors" "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" + "github.com/stretchr/testify/assert" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/batches" + "github.com/sourcegraph/src-cli/internal/batches/docker" "github.com/sourcegraph/src-cli/internal/batches/graphql" + "github.com/sourcegraph/src-cli/internal/batches/mock" ) func TestSetDefaultQueryCount(t *testing.T) { @@ -569,3 +575,126 @@ func TestService_ValidateChangesetSpecs(t *testing.T) { }) } } + +func TestEnsureDockerImages(t *testing.T) { + ctx := context.Background() + parallelCases := []int{0, 1, 2, 4, 8} + + newServiceWithImages := func(images map[string]docker.Image) *Service { + return &Service{ + imageCache: &mock.ImageCache{Images: images}, + } + } + + t.Run("success", func(t *testing.T) { + t.Run("single image", func(t *testing.T) { + // A zeroed mock.Image should be usable for testing purposes. + image := &mock.Image{} + images := map[string]docker.Image{ + "image": image, + } + + for name, steps := range map[string][]batcheslib.Step{ + "single step": {{Container: "image"}}, + "multiple steps": {{Container: "image"}, {Container: "image"}}, + } { + t.Run(name, func(t *testing.T) { + for _, parallelism := range parallelCases { + t.Run(fmt.Sprintf("%d worker(s)", parallelism), func(t *testing.T) { + svc := newServiceWithImages(images) + progress := &mock.Progress{} + + have, err := svc.EnsureDockerImages(ctx, steps, parallelism, progress.Callback()) + assert.Nil(t, err) + assert.Equal(t, images, have) + assert.Equal(t, []mock.ProgressCall{ + {Done: 0, Total: 1}, + {Done: 1, Total: 1}, + }, progress.Calls) + }) + } + }) + } + }) + + t.Run("multiple images", func(t *testing.T) { + var ( + imageA = &mock.Image{} + imageB = &mock.Image{} + imageC = &mock.Image{} + images = map[string]docker.Image{ + "a": imageA, + "b": imageB, + "c": imageC, + } + ) + + for _, parallelism := range parallelCases { + t.Run(fmt.Sprintf("%d worker(s)", parallelism), func(t *testing.T) { + svc := newServiceWithImages(images) + progress := &mock.Progress{} + + have, err := svc.EnsureDockerImages(ctx, []batcheslib.Step{ + {Container: "a"}, + {Container: "a"}, + {Container: "a"}, + {Container: "b"}, + {Container: "c"}, + }, parallelism, progress.Callback()) + assert.Nil(t, err) + assert.Equal(t, images, have) + assert.Equal(t, []mock.ProgressCall{ + {Done: 0, Total: 3}, + {Done: 1, Total: 3}, + {Done: 2, Total: 3}, + {Done: 3, Total: 3}, + }, progress.Calls) + }) + } + }) + }) + + t.Run("errors", func(t *testing.T) { + // The only really interesting case is where an image fails — we want to + // ensure that the error is propagated, and that we don't end up + // deadlocking while the context cancellation propagates. Let's set up a + // good number of images (and steps) so we can give this a good test. + wantErr := errors.New("expected error") + images := map[string]docker.Image{} + steps := []batcheslib.Step{} + + total := 100 + for i := 0; i < total; i++ { + name := strconv.Itoa(i) + if i%25 == 0 { + images[name] = &mock.Image{EnsureErr: wantErr} + } else { + images[name] = &mock.Image{} + } + for j := 0; j < (i%10)+1; j++ { + steps = append(steps, batcheslib.Step{Container: name}) + } + } + + // Just verify we did that right! + assert.Len(t, images, total) + assert.True(t, len(steps) > total) + + for _, parallelism := range parallelCases { + t.Run(fmt.Sprintf("%d worker(s)", parallelism), func(t *testing.T) { + svc := newServiceWithImages(images) + progress := &mock.Progress{} + + have, err := svc.EnsureDockerImages(ctx, steps, parallelism, progress.Callback()) + assert.ErrorIs(t, err, wantErr) + assert.Nil(t, have) + + // Because there's no particular order the images will be fetched in, + // the number of progress calls we get is non-deterministic, other than + // that we should always get the first one. + assert.Equal(t, mock.ProgressCall{Done: 0, Total: total}, progress.Calls[0]) + }) + } + + }) +} From 73eb99955de0824921539ab03b97961320fbf0ca Mon Sep 17 00:00:00 2001 From: Adam Harvey Date: Mon, 7 Feb 2022 03:55:26 -0800 Subject: [PATCH 123/647] batches: use the minimum possible goroutines to fetch images (#692) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This was spotted by Erik in the review for #647 — if `total < parallelism`, there's no real need to spawn extra goroutines, so let's not. --- internal/batches/service/service.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index e3a55b004a..54d6b3041f 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -198,6 +198,9 @@ func (svc *Service) EnsureDockerImages( if parallelism < 1 { parallelism = 1 } + if parallelism > total { + parallelism = total + } var wg sync.WaitGroup for i := 0; i < parallelism; i++ { wg.Add(1) From 4b9004ac8e10a9c522149a38ea754e1857032834 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Mon, 7 Feb 2022 15:30:01 +0100 Subject: [PATCH 124/647] Transfer less unused info for exec command (#691) We don't need the entire batch spec for simply executing a workspace, so we reduce the payload transferred here. This also has the nice side-effect that we finally got to clean up the Task struct a little from things not specific to that given task. --- cmd/src/batch_common.go | 15 +++- cmd/src/batch_exec.go | 12 +-- go.mod | 6 +- go.sum | 18 +++-- internal/batches/executor/coordinator.go | 76 +++++++++++-------- internal/batches/executor/coordinator_test.go | 24 +++--- internal/batches/executor/task.go | 2 - internal/batches/service/build_tasks.go | 10 +-- internal/batches/service/service.go | 5 +- 9 files changed, 90 insertions(+), 78 deletions(-) diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index 5305165522..840340645c 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -18,6 +18,7 @@ import ( "github.com/mattn/go-isatty" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" + "github.com/sourcegraph/sourcegraph/lib/batches/template" "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/batches" @@ -342,7 +343,14 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp }) ui.CheckingCache() - tasks := svc.BuildTasks(ctx, batchSpec, workspaces) + tasks := svc.BuildTasks( + ctx, + &template.BatchChangeAttributes{ + Name: batchSpec.Name, + Description: batchSpec.Description, + }, + workspaces, + ) var ( specs []*batcheslib.ChangesetSpec uncachedTasks []*executor.Task @@ -351,7 +359,8 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp coord.ClearCache(ctx, tasks) uncachedTasks = tasks } else { - uncachedTasks, specs, err = coord.CheckCache(ctx, tasks) + // Check the cache for completely cached executions. + uncachedTasks, specs, err = coord.CheckCache(ctx, batchSpec, tasks) if err != nil { return err } @@ -359,7 +368,7 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp ui.CheckingCacheSuccess(len(specs), len(uncachedTasks)) taskExecUI := ui.ExecutingTasks(*verbose, opts.flags.parallelism) - freshSpecs, logFiles, execErr := coord.Execute(ctx, uncachedTasks, batchSpec, taskExecUI) + freshSpecs, logFiles, execErr := coord.ExecuteAndBuildSpecs(ctx, batchSpec, uncachedTasks, taskExecUI) // Add external changeset specs. importedSpecs, importErr := svc.CreateImportChangesetSpecs(ctx, batchSpec) var errs *multierror.Error diff --git a/cmd/src/batch_exec.go b/cmd/src/batch_exec.go index aea370a189..81eb5ff3fa 100644 --- a/cmd/src/batch_exec.go +++ b/cmd/src/batch_exec.go @@ -105,14 +105,14 @@ func executeBatchSpecInWorkspaces(ctx context.Context, ui *ui.JSONLines, opts ex // Since we already know which workspace we want to execute the steps in, // we can convert it to a RepoWorkspace and build a task only for that one. - repoWorkspace := convertWorkspace(input.Workspace) + repoWorkspace := convertWorkspace(input) var workspaceCreator workspace.Creator - if len(input.Workspace.Steps) > 0 { + if len(input.Steps) > 0 { ui.PreparingContainerImages() images, err := svc.EnsureDockerImages( - ctx, input.Workspace.Steps, opts.flags.parallelism, + ctx, input.Steps, opts.flags.parallelism, ui.PreparingContainerImagesProgress, ) if err != nil { @@ -147,13 +147,13 @@ func executeBatchSpecInWorkspaces(ctx context.Context, ui *ui.JSONLines, opts ex // `src batch exec` uses server-side caching for changeset specs, so we // only need to call `CheckStepResultsCache` to make sure that per-step cache entries // are loaded and set on the tasks. - tasks := svc.BuildTasks(ctx, input.Spec, []service.RepoWorkspace{repoWorkspace}) + tasks := svc.BuildTasks(ctx, &input.BatchChangeAttributes, []service.RepoWorkspace{repoWorkspace}) if err := coord.CheckStepResultsCache(ctx, tasks); err != nil { return err } taskExecUI := ui.ExecutingTasks(*verbose, opts.flags.parallelism) - _, _, err = coord.Execute(ctx, tasks, input.Spec, taskExecUI) + err = coord.Execute(ctx, tasks, taskExecUI) if err == nil || opts.flags.skipErrors { if err == nil { taskExecUI.Success() @@ -191,7 +191,7 @@ func loadWorkspaceExecutionInput(file string) (batcheslib.WorkspacesExecutionInp return input, nil } -func convertWorkspace(w batcheslib.Workspace) service.RepoWorkspace { +func convertWorkspace(w batcheslib.WorkspacesExecutionInput) service.RepoWorkspace { fileMatches := make(map[string]bool) for _, path := range w.SearchResultPaths { fileMatches[path] = true diff --git a/go.mod b/go.mod index 29b7e0a22e..d45697c0c8 100644 --- a/go.mod +++ b/go.mod @@ -21,7 +21,7 @@ require ( github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4 github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf - github.com/sourcegraph/sourcegraph/lib v0.0.0-20220122003450-8a45ff2c8826 + github.com/sourcegraph/sourcegraph/lib v0.0.0-20220204151625-fceb046d5b75 github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f @@ -39,7 +39,7 @@ require ( github.com/gogo/protobuf v1.3.2 // indirect github.com/hashicorp/errwrap v1.1.0 // indirect github.com/inconshreveable/log15 v0.0.0-20201112154412-8562bdadbbac // indirect - github.com/klauspost/compress v1.13.6 // indirect + github.com/klauspost/compress v1.14.2 // indirect github.com/klauspost/pgzip v1.2.5 // indirect github.com/kr/pretty v0.3.0 // indirect github.com/kr/text v0.2.0 // indirect @@ -56,7 +56,7 @@ require ( github.com/stretchr/testify v1.7.0 // indirect github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect github.com/xeipuuv/gojsonschema v1.2.0 // indirect - golang.org/x/sys v0.0.0-20220111092808-5a964db01320 // indirect + golang.org/x/sys v0.0.0-20220128215802-99c3d69c2c27 // indirect golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect ) diff --git a/go.sum b/go.sum index c32a5d7090..9c555a112f 100644 --- a/go.sum +++ b/go.sum @@ -14,7 +14,7 @@ github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY github.com/alecthomas/kingpin v2.2.6+incompatible/go.mod h1:59OFYbFVLKQKq+mqrL6Rw5bR0c3ACQaawgXx0QYndlE= github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/units v0.0.0-20210208195552-ff826a37aa15/go.mod h1:OMCwj8VM1Kc9e19TLln2VL61YJF0x1XFtfdL4JdbSyE= -github.com/alecthomas/units v0.0.0-20210927113745-59d0afb8317a/go.mod h1:OMCwj8VM1Kc9e19TLln2VL61YJF0x1XFtfdL4JdbSyE= +github.com/alecthomas/units v0.0.0-20211218093645-b94a6e3cc137/go.mod h1:OMCwj8VM1Kc9e19TLln2VL61YJF0x1XFtfdL4JdbSyE= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= github.com/aymerick/raymond v2.0.3-0.20180322193309-b565731e1464+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= @@ -169,8 +169,8 @@ github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/klauspost/compress v1.8.2/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= github.com/klauspost/compress v1.9.0/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= -github.com/klauspost/compress v1.13.6 h1:P76CopJELS0TiO2mebmnzgWaajssP/EszplttgQxcgc= -github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= +github.com/klauspost/compress v1.14.2 h1:S0OHlFk/Gbon/yauFJ4FfJJF5V0fc5HbBTJazi28pRw= +github.com/klauspost/compress v1.14.2/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= github.com/klauspost/cpuid v1.2.1/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek= github.com/klauspost/pgzip v1.2.5 h1:qnWYvvKqedOF2ulHpMG72XQol4ILEJ8k2wwRl/Km8oE= github.com/klauspost/pgzip v1.2.5/go.mod h1:Ch1tH69qFZu15pkjo5kYi6mth2Zzwzt50oCQKQE9RUs= @@ -268,8 +268,8 @@ github.com/sourcegraph/go-diff v0.6.1 h1:hmA1LzxW0n1c3Q4YbrFgg4P99GSnebYa3x8gr0H github.com/sourcegraph/go-diff v0.6.1/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20220122003450-8a45ff2c8826 h1:8AoxPHU5kpcAx1frcU1xHpLAjc2UZTYxD82BMOUp50Y= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20220122003450-8a45ff2c8826/go.mod h1:KhG6S/6YtG9eFdcXlfSD4ogB4qR8V6wLTLQd7x3ToAM= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20220204151625-fceb046d5b75 h1:XCvY1beVBLRnJHgyQ9T9AexDlUMfQwez3yGAX59yBZ4= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20220204151625-fceb046d5b75/go.mod h1:u3KHLBGdpCN8bgI8PxPafb8vh3e+ftHkHZdjaXXIpFA= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= @@ -385,9 +385,9 @@ golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211102192858-4dd72447c267/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211117180635-dee7805ff2e1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20211205182925-97ca703d548d/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220111092808-5a964db01320 h1:0jf+tOCoZ3LyutmCOWpVni1chK4VfFLhRsDK7MhqGRY= -golang.org/x/sys v0.0.0-20220111092808-5a964db01320/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211213223007-03aa0b5f6827/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220128215802-99c3d69c2c27 h1:XDXtA5hveEEV8JB2l7nhMTp3t3cHp9ZpwcdjqyEWLlo= +golang.org/x/sys v0.0.0-20220128215802-99c3d69c2c27/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= @@ -416,6 +416,7 @@ golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.8-0.20211102182255-bb4add04ddef/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= golang.org/x/tools v0.1.8/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= +golang.org/x/tools v0.1.9/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -474,3 +475,4 @@ jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7/go.mod h1:OxvTsCwKosq mvdan.cc/gofumpt v0.0.0-20210107193838-d24d34e18d44/go.mod h1:yXG1r1WqZVKWbVRtBWKWX9+CxGYfA51nSomhM0woR48= mvdan.cc/gofumpt v0.1.0/go.mod h1:yXG1r1WqZVKWbVRtBWKWX9+CxGYfA51nSomhM0woR48= mvdan.cc/gofumpt v0.2.0/go.mod h1:TiGmrf914DAuT6+hDIxOqoDb4QXIzAuEUSXqEf9hGKY= +mvdan.cc/gofumpt v0.2.1/go.mod h1:a/rvZPhsNaedOJBzqRD9omnwVwHZsBdJirXHa9Gh9Ig= diff --git a/internal/batches/executor/coordinator.go b/internal/batches/executor/coordinator.go index f9d0755864..c464f4c564 100644 --- a/internal/batches/executor/coordinator.go +++ b/internal/batches/executor/coordinator.go @@ -6,7 +6,6 @@ import ( "time" "github.com/cockroachdb/errors" - "github.com/hashicorp/go-multierror" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/execution" @@ -86,9 +85,9 @@ func NewCoordinator(opts NewCoordinatorOpts) *Coordinator { // CheckCache checks whether the internal ExecutionCache contains // ChangesetSpecs for the given Tasks. If cached ChangesetSpecs exist, those // are returned, otherwise the Task, to be executed later. -func (c *Coordinator) CheckCache(ctx context.Context, tasks []*Task) (uncached []*Task, specs []*batcheslib.ChangesetSpec, err error) { +func (c *Coordinator) CheckCache(ctx context.Context, batchSpec *batcheslib.BatchSpec, tasks []*Task) (uncached []*Task, specs []*batcheslib.ChangesetSpec, err error) { for _, t := range tasks { - cachedSpecs, found, err := c.checkCacheForTask(ctx, t) + cachedSpecs, found, err := c.checkCacheForTask(ctx, batchSpec, t) if err != nil { return nil, nil, err } @@ -134,7 +133,7 @@ func (c *Coordinator) ClearCache(ctx context.Context, tasks []*Task) error { return nil } -func (c *Coordinator) checkCacheForTask(ctx context.Context, task *Task) (specs []*batcheslib.ChangesetSpec, found bool, err error) { +func (c *Coordinator) checkCacheForTask(ctx context.Context, batchSpec *batcheslib.BatchSpec, task *Task) (specs []*batcheslib.ChangesetSpec, found bool, err error) { globalEnv := os.Environ() // Check if the task is cached. @@ -164,7 +163,7 @@ func (c *Coordinator) checkCacheForTask(ctx context.Context, task *Task) (specs return specs, true, nil } - specs, err = c.buildChangesetSpecs(task, result) + specs, err = c.buildChangesetSpecs(task, batchSpec, result) if err != nil { return specs, false, err } @@ -172,7 +171,7 @@ func (c *Coordinator) checkCacheForTask(ctx context.Context, task *Task) (specs return specs, true, nil } -func (c Coordinator) buildChangesetSpecs(task *Task, result execution.Result) ([]*batcheslib.ChangesetSpec, error) { +func (c Coordinator) buildChangesetSpecs(task *Task, batchSpec *batcheslib.BatchSpec, result execution.Result) ([]*batcheslib.ChangesetSpec, error) { input := &batcheslib.ChangesetSpecInput{ Repository: batcheslib.Repository{ ID: task.Repository.ID, @@ -182,8 +181,8 @@ func (c Coordinator) buildChangesetSpecs(task *Task, result execution.Result) ([ BaseRev: task.Repository.Rev(), }, BatchChangeAttributes: task.BatchChangeAttributes, - Template: task.Template, - TransformChanges: task.TransformChanges, + Template: batchSpec.ChangesetTemplate, + TransformChanges: batchSpec.TransformChanges, Result: execution.Result{ Diff: result.Diff, @@ -222,22 +221,28 @@ func (c *Coordinator) loadCachedStepResults(ctx context.Context, task *Task, glo return nil } -func (c *Coordinator) cacheAndBuildSpec(ctx context.Context, taskResult taskResult, ui TaskExecutionUI) ([]*batcheslib.ChangesetSpec, error) { +func (c *Coordinator) writeCache(ctx context.Context, taskResult taskResult, ui TaskExecutionUI) error { // Add to the cache, even if no diff was produced. globalEnv := os.Environ() cacheKey := taskResult.task.cacheKey(globalEnv) if err := c.cache.Set(ctx, cacheKey, taskResult.result); err != nil { - return nil, errors.Wrapf(err, "caching result for %q", taskResult.task.Repository.Name) + return errors.Wrapf(err, "caching result for %q", taskResult.task.Repository.Name) } // Save the per-step results for _, stepResult := range taskResult.stepResults { key := cacheKeyForStep(cacheKey, stepResult.StepIndex) if err := c.cache.SetStepResult(ctx, key, stepResult); err != nil { - return nil, errors.Wrapf(err, "caching result for step %d in %q", stepResult.StepIndex, taskResult.task.Repository.Name) + return errors.Wrapf(err, "caching result for step %d in %q", stepResult.StepIndex, taskResult.task.Repository.Name) } } + return nil +} + +func (c *Coordinator) writeCacheAndBuildSpecs(ctx context.Context, batchSpec *batcheslib.BatchSpec, taskResult taskResult, ui TaskExecutionUI) ([]*batcheslib.ChangesetSpec, error) { + c.writeCache(ctx, taskResult, ui) + // If the steps didn't result in any diff, we don't need to create a // changeset spec that's displayed to the user and send to the server. if taskResult.result.Diff == "" { @@ -245,7 +250,7 @@ func (c *Coordinator) cacheAndBuildSpec(ctx context.Context, taskResult taskResu } // Build the changeset specs. - specs, err := c.buildChangesetSpecs(taskResult.task, taskResult.result) + specs, err := c.buildChangesetSpecs(taskResult.task, batchSpec, taskResult.result) if err != nil { return nil, err } @@ -254,31 +259,30 @@ func (c *Coordinator) cacheAndBuildSpec(ctx context.Context, taskResult taskResu return specs, nil } -// Execute executes the given Tasks and the importChangeset statements in the -// given spec. It regularly calls the executionProgressPrinter with the -// current TaskStatuses. -func (c *Coordinator) Execute(ctx context.Context, tasks []*Task, spec *batcheslib.BatchSpec, ui TaskExecutionUI) ([]*batcheslib.ChangesetSpec, []string, error) { - var ( - specs []*batcheslib.ChangesetSpec - errs *multierror.Error - ) - - ui.Start(tasks) +// Execute executes the given tasks. It calls the ui on updates. +func (c *Coordinator) Execute(ctx context.Context, tasks []*Task, ui TaskExecutionUI) error { + results, err := c.doExecute(ctx, tasks, ui) - // Run executor - c.exec.Start(ctx, tasks, ui) - results, err := c.exec.Wait(ctx) - if err != nil { - if c.opts.SkipErrors { - errs = multierror.Append(errs, err) - } else { - return nil, nil, err + // Write results to cache. + for _, taskResult := range results { + if cacheErr := c.writeCache(ctx, taskResult, ui); cacheErr != nil { + return cacheErr } } + return err +} + +// ExecuteAndBuildSpecs executes the given tasks and builds changeset specs for the results. +// It calls the ui on updates. +func (c *Coordinator) ExecuteAndBuildSpecs(ctx context.Context, batchSpec *batcheslib.BatchSpec, tasks []*Task, ui TaskExecutionUI) ([]*batcheslib.ChangesetSpec, []string, error) { + results, errs := c.doExecute(ctx, tasks, ui) + + var specs []*batcheslib.ChangesetSpec + // Write results to cache, build ChangesetSpecs if possible and add to list. for _, taskResult := range results { - taskSpecs, err := c.cacheAndBuildSpec(ctx, taskResult, ui) + taskSpecs, err := c.writeCacheAndBuildSpecs(ctx, batchSpec, taskResult, ui) if err != nil { return nil, nil, err } @@ -286,5 +290,13 @@ func (c *Coordinator) Execute(ctx context.Context, tasks []*Task, spec *batchesl specs = append(specs, taskSpecs...) } - return specs, c.logManager.LogFiles(), errs.ErrorOrNil() + return specs, c.logManager.LogFiles(), errs +} + +func (c *Coordinator) doExecute(ctx context.Context, tasks []*Task, ui TaskExecutionUI) (results []taskResult, err error) { + ui.Start(tasks) + + // Run executor + c.exec.Start(ctx, tasks, ui) + return c.exec.Wait(ctx) } diff --git a/internal/batches/executor/coordinator_test.go b/internal/batches/executor/coordinator_test.go index 3be06ee491..fbaf353c6c 100644 --- a/internal/batches/executor/coordinator_test.go +++ b/internal/batches/executor/coordinator_test.go @@ -269,8 +269,6 @@ func TestCoordinator_Execute(t *testing.T) { // Set attributes on Task which would be set by the TaskBuilder for _, t := range tc.tasks { - t.TransformChanges = tc.batchSpec.TransformChanges - t.Template = tc.batchSpec.ChangesetTemplate t.BatchChangeAttributes = &template.BatchChangeAttributes{ Name: tc.batchSpec.Name, Description: tc.batchSpec.Description, @@ -291,7 +289,7 @@ func TestCoordinator_Execute(t *testing.T) { // the batch spec. We'll run this multiple times to cover both the // cache and non-cache code paths. execute := func(t *testing.T) { - specs, _, err := coord.Execute(ctx, tc.tasks, tc.batchSpec, newDummyTaskExecutionUI()) + specs, _, err := coord.ExecuteAndBuildSpecs(ctx, tc.batchSpec, tc.tasks, newDummyTaskExecutionUI()) if tc.wantErrInclude == "" { if err != nil { t.Fatalf("execution failed: %s", err) @@ -385,8 +383,10 @@ func TestCoordinator_Execute_StepCaching(t *testing.T) { // Build Coordinator coord := &Coordinator{cache: cache, exec: executor, logManager: logManager} + batchSpec := &batcheslib.BatchSpec{ChangesetTemplate: testChangesetTemplate} + // First execution. Make sure that the Task executes all steps. - execAndEnsure(t, coord, executor, task, assertNoCachedResult(t)) + execAndEnsure(t, coord, executor, batchSpec, task, assertNoCachedResult(t)) // We now expect the cache to have 1+N entries: 1 for the complete task, N // for the steps. wantCacheSize := len(task.Steps) + 1 @@ -399,7 +399,7 @@ func TestCoordinator_Execute_StepCaching(t *testing.T) { task.Steps[1].Run = `echo "two modified"` // Re-execution should start with the diff produced by steps[0] as the // start state from which steps[1] is then re-executed. - execAndEnsure(t, coord, executor, task, assertCachedResultForStep(t, 0)) + execAndEnsure(t, coord, executor, batchSpec, task, assertCachedResultForStep(t, 0)) // Cache now contains old entries, plus another "complete task" entry and // two entries for newly executed steps. wantCacheSize += 1 + 2 @@ -411,7 +411,7 @@ func TestCoordinator_Execute_StepCaching(t *testing.T) { // Change the 3rd step's definition: task.Steps[2].Run = `echo "three modified"` // Re-execution should use the diff from steps[1] as start state - execAndEnsure(t, coord, executor, task, assertCachedResultForStep(t, 1)) + execAndEnsure(t, coord, executor, batchSpec, task, assertCachedResultForStep(t, 1)) // Cache now contains old entries, plus another "complete task" entry and // a single new step entry wantCacheSize += 1 + 1 @@ -425,7 +425,7 @@ func TestCoordinator_Execute_StepCaching(t *testing.T) { t.Fatal(err) } // We don't want any cached results set on the task: - execAndEnsure(t, coord, executor, task, assertNoCachedResult(t)) + execAndEnsure(t, coord, executor, batchSpec, task, assertNoCachedResult(t)) // Cache should have the same number of entries: the cached step results should // have been cleared (the complete-task-result is cleared in another // code path) and the same amount of cached entries has been added. @@ -434,24 +434,20 @@ func TestCoordinator_Execute_StepCaching(t *testing.T) { // execAndEnsure executes the given Task with the given cache and dummyExecutor // in a new Coordinator, setting cb as the startCallback on the executor. -func execAndEnsure(t *testing.T, coord *Coordinator, exec *dummyExecutor, task *Task, cb startCallback) { +func execAndEnsure(t *testing.T, coord *Coordinator, exec *dummyExecutor, batchSpec *batcheslib.BatchSpec, task *Task, cb startCallback) { t.Helper() - batchSpec := &batcheslib.BatchSpec{ChangesetTemplate: testChangesetTemplate} - // Set the ChangesetTemplate on Task - task.Template = batchSpec.ChangesetTemplate - // Setup the callback exec.startCb = cb // Check cache - uncached, cachedSpecs, err := coord.CheckCache(context.Background(), []*Task{task}) + uncached, cachedSpecs, err := coord.CheckCache(context.Background(), batchSpec, []*Task{task}) if err != nil { t.Fatal(err) } // Execute - freshSpecs, _, err := coord.Execute(context.Background(), uncached, batchSpec, newDummyTaskExecutionUI()) + freshSpecs, _, err := coord.ExecuteAndBuildSpecs(context.Background(), batchSpec, uncached, newDummyTaskExecutionUI()) if err != nil { t.Fatalf("execution of task failed: %s", err) } diff --git a/internal/batches/executor/task.go b/internal/batches/executor/task.go index 1335b79053..b08a174a94 100644 --- a/internal/batches/executor/task.go +++ b/internal/batches/executor/task.go @@ -27,8 +27,6 @@ type Task struct { // TODO(mrnugget): this should just be a single BatchSpec field instead, if // we can make it work with caching BatchChangeAttributes *template.BatchChangeAttributes `json:"-"` - Template *batcheslib.ChangesetTemplate `json:"-"` - TransformChanges *batcheslib.TransformChanges `json:"-"` Archive repozip.Archive `json:"-"` diff --git a/internal/batches/service/build_tasks.go b/internal/batches/service/build_tasks.go index f65f977e16..d81eb4777b 100644 --- a/internal/batches/service/build_tasks.go +++ b/internal/batches/service/build_tasks.go @@ -3,14 +3,13 @@ package service import ( "context" - batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/template" "github.com/sourcegraph/src-cli/internal/batches/executor" ) // buildTasks returns *executor.Tasks for all the workspaces determined for the given spec. -func buildTasks(ctx context.Context, spec *batcheslib.BatchSpec, workspaces []RepoWorkspace) []*executor.Task { +func buildTasks(ctx context.Context, attributes *template.BatchChangeAttributes, workspaces []RepoWorkspace) []*executor.Task { tasks := make([]*executor.Task, 0, len(workspaces)) for _, ws := range workspaces { @@ -20,12 +19,7 @@ func buildTasks(ctx context.Context, spec *batcheslib.BatchSpec, workspaces []Re Steps: ws.Steps, OnlyFetchWorkspace: ws.OnlyFetchWorkspace, - TransformChanges: spec.TransformChanges, - Template: spec.ChangesetTemplate, - BatchChangeAttributes: &template.BatchChangeAttributes{ - Name: spec.Name, - Description: spec.Description, - }, + BatchChangeAttributes: attributes, } tasks = append(tasks, task) } diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index 54d6b3041f..c36c15a15c 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -17,6 +17,7 @@ import ( batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" onlib "github.com/sourcegraph/sourcegraph/lib/batches/on" + templatelib "github.com/sourcegraph/sourcegraph/lib/batches/template" "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/batches" @@ -277,8 +278,8 @@ func (svc *Service) DetermineWorkspaces(ctx context.Context, repos []*graphql.Re return findWorkspaces(ctx, spec, svc, repos) } -func (svc *Service) BuildTasks(ctx context.Context, spec *batcheslib.BatchSpec, workspaces []RepoWorkspace) []*executor.Task { - return buildTasks(ctx, spec, workspaces) +func (svc *Service) BuildTasks(ctx context.Context, attributes *templatelib.BatchChangeAttributes, workspaces []RepoWorkspace) []*executor.Task { + return buildTasks(ctx, attributes, workspaces) } func (svc *Service) NewCoordinator(opts executor.NewCoordinatorOpts) *executor.Coordinator { From b323be2627bbb5fc94ffa4c9606fc1fe0e1de96e Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Mon, 7 Feb 2022 15:30:46 +0100 Subject: [PATCH 125/647] Prepare changelog for 3.36.3 --- CHANGELOG.md | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 82f201b123..dc7a01ec72 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,14 @@ All notable changes to `src-cli` are documented in this file. ### Changed +### Fixed + +### Removed + +## 3.36.3 + +### Changed + - `src batch` commands no longer require `-f` to read from a file. Additionally, running a `src batch` command that requires a batch spec file without a `-f` option from the terminal will now generate an error instead of waiting indefinitely for a batch spec on standard input; however, piping in a batch spec will still work as expected. [#687](https://github.com/sourcegraph/src-cli/pull/687) - Pulling container images now occurs in parallel, with the number of concurrent downloads being controlled by the `-j` flag. [#17577](https://github.com/sourcegraph/sourcegraph/issues/17577) @@ -22,8 +30,6 @@ All notable changes to `src-cli` are documented in this file. - `src batch [preview|apply]` will now check that the target Sourcegraph instance supports batch changes before doing any other work and exit early in the case that it does not. -### Removed - ## 3.36.2 ### Changed From 0e2ace413fd11c3226ec58db2a81349032c4d5bb Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Mon, 7 Feb 2022 15:34:41 +0100 Subject: [PATCH 126/647] Fixup go mod file --- go.mod | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/go.mod b/go.mod index d45697c0c8..a5f9c16094 100644 --- a/go.mod +++ b/go.mod @@ -29,6 +29,8 @@ require ( jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7 ) +require github.com/stretchr/testify v1.7.0 + require ( github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f // indirect @@ -53,7 +55,6 @@ require ( github.com/pmezard/go-difflib v1.0.0 // indirect github.com/rivo/uniseg v0.2.0 // indirect github.com/rogpeppe/go-internal v1.8.1 // indirect - github.com/stretchr/testify v1.7.0 // indirect github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect github.com/xeipuuv/gojsonschema v1.2.0 // indirect golang.org/x/sys v0.0.0-20220128215802-99c3d69c2c27 // indirect From 763d3cbfc4571ea5af6656ea514c20ab946bd01b Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Mon, 7 Feb 2022 15:49:33 +0100 Subject: [PATCH 127/647] Try to trigger goreleaser From 0c8afcd141dcacd005f03358626aa0ec7514c529 Mon Sep 17 00:00:00 2001 From: Adam Harvey Date: Mon, 7 Feb 2022 15:16:18 -0800 Subject: [PATCH 128/647] batches: add `src batch remote -f spec.yml` for SSBC execution (#671) Closes sourcegraph/sourcegraph#26503. --- CHANGELOG.md | 2 + cmd/src/batch.go | 1 + cmd/src/batch_common.go | 75 ++++++++++------ cmd/src/batch_remote.go | 138 +++++++++++++++++++++++++++++ internal/batches/features.go | 2 + internal/batches/service/remote.go | 138 +++++++++++++++++++++++++++++ internal/batches/ui/tui.go | 28 ++++++ 7 files changed, 355 insertions(+), 29 deletions(-) create mode 100644 cmd/src/batch_remote.go create mode 100644 internal/batches/service/remote.go diff --git a/CHANGELOG.md b/CHANGELOG.md index dc7a01ec72..d4e41d0c52 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,8 @@ All notable changes to `src-cli` are documented in this file. ### Added +- A new `src batch remote` command has been added to run a batch spec on a Sourcegraph instance that has Server Side Batch Changes enabled. [#671](https://github.com/sourcegraph/src-cli/pull/671) + ### Changed ### Fixed diff --git a/cmd/src/batch.go b/cmd/src/batch.go index 61dc7d148f..fd42257f7d 100644 --- a/cmd/src/batch.go +++ b/cmd/src/batch.go @@ -20,6 +20,7 @@ The commands are: change new creates a new batch spec YAML file preview creates a batch spec to be previewed or applied + remote creates server side batch changes repos,repositories queries the exact repositories that a batch spec will apply to validate validates a batch spec diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index 840340645c..f77bcf3c9c 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -30,22 +30,56 @@ import ( "github.com/sourcegraph/src-cli/internal/cmderrors" ) -type batchExecuteFlags struct { +// batchExecutionFlags are common to batch changes that are executed both +// locally and remotely. +type batchExecutionFlags struct { allowUnsupported bool allowIgnored bool api *api.Flags - apply bool - cacheDir string - tempDir string clearCache bool - file string - keepLogs bool namespace string - parallelism int - timeout time.Duration - workspace string - cleanArchives bool - skipErrors bool +} + +func newBatchExecutionFlags(flagSet *flag.FlagSet) *batchExecutionFlags { + bef := &batchExecutionFlags{ + api: api.NewFlags(flagSet), + } + + flagSet.BoolVar( + &bef.allowUnsupported, "allow-unsupported", false, + "Allow unsupported code hosts.", + ) + flagSet.BoolVar( + &bef.clearCache, "clear-cache", false, + "If true, clears the execution cache and executes all steps anew.", + ) + flagSet.BoolVar( + &bef.allowIgnored, "force-override-ignore", false, + "Do not ignore repositories that have a .batchignore file.", + ) + flagSet.StringVar( + &bef.namespace, "namespace", "", + "The user or organization namespace to place the batch change within. Default is the currently authenticated user.", + ) + flagSet.StringVar(&bef.namespace, "n", "", "Alias for -namespace.") + + return bef +} + +// batchExecuteFlags are used when executing batch changes locally. +type batchExecuteFlags struct { + *batchExecutionFlags + + apply bool + cacheDir string + tempDir string + file string + keepLogs bool + parallelism int + timeout time.Duration + workspace string + cleanArchives bool + skipErrors bool // EXPERIMENTAL textOnly bool @@ -53,7 +87,7 @@ type batchExecuteFlags struct { func newBatchExecuteFlags(flagSet *flag.FlagSet, workspaceExecution bool, cacheDir, tempDir string) *batchExecuteFlags { caf := &batchExecuteFlags{ - api: api.NewFlags(flagSet), + batchExecutionFlags: newBatchExecutionFlags(flagSet), } if !workspaceExecution { @@ -61,14 +95,6 @@ func newBatchExecuteFlags(flagSet *flag.FlagSet, workspaceExecution bool, cacheD &caf.textOnly, "text-only", false, "INTERNAL USE ONLY. EXPERIMENTAL. Switches off the TUI to only print JSON lines.", ) - flagSet.BoolVar( - &caf.allowUnsupported, "allow-unsupported", false, - "Allow unsupported code hosts.", - ) - flagSet.BoolVar( - &caf.allowIgnored, "force-override-ignore", false, - "Do not ignore repositories that have a .batchignore file.", - ) flagSet.BoolVar( &caf.apply, "apply", false, "Ignored.", @@ -77,21 +103,12 @@ func newBatchExecuteFlags(flagSet *flag.FlagSet, workspaceExecution bool, cacheD &caf.keepLogs, "keep-logs", false, "Retain logs after executing steps.", ) - flagSet.StringVar( - &caf.namespace, "namespace", "", - "The user or organization namespace to place the batch change within. Default is the currently authenticated user.", - ) - flagSet.StringVar(&caf.namespace, "n", "", "Alias for -namespace.") } flagSet.StringVar( &caf.cacheDir, "cache", cacheDir, "Directory for caching results and repository archives.", ) - flagSet.BoolVar( - &caf.clearCache, "clear-cache", false, - "If true, clears the execution cache and executes all steps anew.", - ) flagSet.StringVar( &caf.tempDir, "tmp", tempDir, "Directory for storing temporary data, such as log files. Default is /tmp. Can also be set with environment variable SRC_BATCH_TMP_DIR; if both are set, this flag will be used and not the environment variable.", diff --git a/cmd/src/batch_remote.go b/cmd/src/batch_remote.go new file mode 100644 index 0000000000..0c38712ef9 --- /dev/null +++ b/cmd/src/batch_remote.go @@ -0,0 +1,138 @@ +package main + +import ( + "context" + "flag" + "fmt" + "strings" + "time" + + "github.com/cockroachdb/errors" + "github.com/sourcegraph/sourcegraph/lib/output" + "github.com/sourcegraph/src-cli/internal/batches/service" + "github.com/sourcegraph/src-cli/internal/batches/ui" +) + +func init() { + usage := `'src batch remote' runs a batch spec on the Sourcegraph instance. + +Usage: + + src batch remote [-f FILE] + src batch remote FILE + +Examples: + + $ src batch remote -f batch.spec.yaml + +` + + flagSet := flag.NewFlagSet("remote", flag.ExitOnError) + flags := newBatchExecutionFlags(flagSet) + + var ( + fileFlag = flagSet.String("f", "", "The name of the batch spec file to run.") + ) + + handler := func(args []string) error { + // Various bits of Batch Changes boilerplate. + ctx := context.Background() + + if err := flagSet.Parse(args); err != nil { + return err + } + + file, err := getBatchSpecFile(flagSet, fileFlag) + if err != nil { + return err + } + + svc := service.New(&service.Opts{ + Client: cfg.apiClient(flags.api, flagSet.Output()), + }) + + if err := svc.DetermineFeatureFlags(ctx); err != nil { + return err + } + + out := output.NewOutput(flagSet.Output(), output.OutputOpts{Verbose: *verbose}) + ui := &ui.TUI{Out: out} + + // OK, now for the real stuff. We have to load in the batch spec, and we + // may as well validate it at the same time so we don't even have to go to + // the backend if it's invalid. + ui.ParsingBatchSpec() + _, raw, err := parseBatchSpec(file, svc) + if err != nil { + ui.ParsingBatchSpecFailure(err) + return err + } + ui.ParsingBatchSpecSuccess() + + // We're going to need the namespace ID, so let's figure that out. + ui.ResolvingNamespace() + namespaceID, err := svc.ResolveNamespace(ctx, flags.namespace) + if err != nil { + return err + } + ui.ResolvingNamespaceSuccess(namespaceID) + + ui.SendingBatchSpec() + batchSpecID, err := svc.UpsertBatchSpecInput( + ctx, + raw, + namespaceID, + flags.allowIgnored, + flags.allowUnsupported, + flags.clearCache, + ) + if err != nil { + return err + } + ui.SendingBatchSpecSuccess() + + // Wait for the workspaces to be resolved. + ui.ResolvingWorkspaces() + ticker := time.NewTicker(1 * time.Second) + defer ticker.Stop() + for range ticker.C { + res, err := svc.GetBatchSpecWorkspaceResolution(ctx, batchSpecID) + if err != nil { + return err + } + + if res.State == "FAILED" { + return errors.Newf("workspace resolution failed: %s", res.FailureMessage) + } else if res.State == "COMPLETED" { + break + } + } + ui.ResolvingWorkspacesSuccess() + + // We have to enqueue this for execution with a separate operation. + // + // TODO: when the execute flag is wired up in the upsert mutation, just set + // it there and remove this. + ui.ExecutingBatchSpec() + batchSpecID, err = svc.ExecuteBatchSpec(ctx, batchSpecID, flags.clearCache) + if err != nil { + return err + } + ui.ExecutingBatchSpecSuccess() + + ui.RemoteSuccess(strings.TrimSuffix(cfg.Endpoint, "/") + "/batch-changes/executions/" + batchSpecID) + + return nil + } + + batchCommands = append(batchCommands, &command{ + flagSet: flagSet, + aliases: []string{}, + handler: handler, + usageFunc: func() { + fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src batch remote %s':\n", flagSet.Name()) + flagSet.PrintDefaults() + fmt.Println(usage) + }, + }) +} diff --git a/internal/batches/features.go b/internal/batches/features.go index 40480e05cc..723dde2d82 100644 --- a/internal/batches/features.go +++ b/internal/batches/features.go @@ -17,6 +17,7 @@ type FeatureFlags struct { BatchChanges bool AllowConditionalExec bool AllowOptionalPublished bool + ServerSideBatchChanges bool } func (ff *FeatureFlags) SetFromVersion(version string) error { @@ -40,6 +41,7 @@ func (ff *FeatureFlags) SetFromVersion(version string) error { {&ff.BatchChanges, ">= 3.26.0-0", "2021-03-07"}, {&ff.AllowConditionalExec, ">= 3.28.0-0", "2021-05-05"}, {&ff.AllowOptionalPublished, ">= 3.30.0-0", "2021-06-21"}, + {&ff.ServerSideBatchChanges, ">= 3.37.0-0", "2022-02-08"}, } { value, err := api.CheckSourcegraphVersion(version, feature.constraint, feature.minDate) if err != nil { diff --git a/internal/batches/service/remote.go b/internal/batches/service/remote.go new file mode 100644 index 0000000000..61f5957fb7 --- /dev/null +++ b/internal/batches/service/remote.go @@ -0,0 +1,138 @@ +package service + +import ( + "context" + + "github.com/cockroachdb/errors" +) + +var ErrServerSideBatchChangesUnsupported = errors.New("server side batch changes are not available on this Sourcegraph instance") + +func (svc *Service) areServerSideBatchChangesSupported() error { + if !svc.features.ServerSideBatchChanges { + return ErrServerSideBatchChangesUnsupported + } + return nil +} + +const upsertBatchSpecInputQuery = ` +mutation CreateBatchSpecFromRaw( + $batchSpec: String!, + $namespace: ID!, + $allowIgnored: Boolean!, + $allowUnsupported: Boolean!, + $noCache: Boolean!, +) { + upsertBatchSpecInput( + batchSpec: $batchSpec, + namespace: $namespace, + allowIgnored: $allowIgnored, + allowUnsupported: $allowUnsupported, + noCache: $noCache, + ) { + id + } +} +` + +func (svc *Service) UpsertBatchSpecInput( + ctx context.Context, + batchSpec string, + namespaceID string, + allowIgnored bool, + allowUnsupported bool, + noCache bool, +) (string, error) { + if err := svc.areServerSideBatchChangesSupported(); err != nil { + return "", err + } + + var resp struct { + UpsertBatchSpecInput struct { + ID string `json:"id"` + } `json:"upsertBatchSpecInput"` + } + + if ok, err := svc.client.NewRequest(upsertBatchSpecInputQuery, map[string]interface{}{ + "batchSpec": batchSpec, + "namespace": namespaceID, + "allowIgnored": allowIgnored, + "allowUnsupported": allowUnsupported, + "noCache": noCache, + }).Do(ctx, &resp); err != nil || !ok { + return "", err + } + + return resp.UpsertBatchSpecInput.ID, nil +} + +const executeBatchSpecQuery = ` +mutation ExecuteBatchSpec($batchSpec: ID!, $noCache: Boolean!) { + executeBatchSpec(batchSpec: $batchSpec, noCache: $noCache) { + id + } +} +` + +func (svc *Service) ExecuteBatchSpec( + ctx context.Context, + batchSpecID string, + noCache bool, +) (string, error) { + if err := svc.areServerSideBatchChangesSupported(); err != nil { + return "", err + } + + var resp struct { + ExecuteBatchSpec struct { + ID string `json:"id"` + } `json:"executeBatchSpec"` + } + + if ok, err := svc.client.NewRequest(executeBatchSpecQuery, map[string]interface{}{ + "batchSpec": batchSpecID, + "noCache": noCache, + }).Do(ctx, &resp); err != nil || !ok { + return "", err + } + + return resp.ExecuteBatchSpec.ID, nil +} + +const batchSpecWorkspaceResolutionQuery = ` +query BatchSpecWorkspaceResolution($batchSpec: ID!) { + node(id: $batchSpec) { + ... on BatchSpec { + workspaceResolution { + failureMessage + state + } + } + } +} +` + +type BatchSpecWorkspaceResolution struct { + FailureMessage string `json:"failureMessage"` + State string `json:"state"` +} + +func (svc *Service) GetBatchSpecWorkspaceResolution(ctx context.Context, id string) (*BatchSpecWorkspaceResolution, error) { + if err := svc.areServerSideBatchChangesSupported(); err != nil { + return nil, err + } + + var resp struct { + Node struct { + WorkspaceResolution BatchSpecWorkspaceResolution `json:"workspaceResolution"` + } `json:"node"` + } + + if ok, err := svc.client.NewRequest(batchSpecWorkspaceResolutionQuery, map[string]interface{}{ + "batchSpec": id, + }).Do(ctx, &resp); err != nil || !ok { + return nil, err + } + + return &resp.Node.WorkspaceResolution, nil +} diff --git a/internal/batches/ui/tui.go b/internal/batches/ui/tui.go index 1e511ccefa..aa4c660910 100644 --- a/internal/batches/ui/tui.go +++ b/internal/batches/ui/tui.go @@ -224,10 +224,38 @@ func (ui *TUI) ApplyingBatchSpecSuccess(batchChangeURL string) { block.Writef("%s", batchChangeURL) } +func (ui *TUI) SendingBatchSpec() { + ui.pending = batchCreatePending(ui.Out, "Sending batch spec") +} + +func (ui *TUI) SendingBatchSpecSuccess() { + batchCompletePending(ui.pending, "Sending batch spec") +} + +func (ui *TUI) ResolvingWorkspaces() { + ui.pending = batchCreatePending(ui.Out, "Resolving workspaces") +} + +func (ui *TUI) ResolvingWorkspacesSuccess() { + batchCompletePending(ui.pending, "Resolving workspaces") +} + +func (ui *TUI) ExecutingBatchSpec() { + ui.pending = batchCreatePending(ui.Out, "Executing batch spec") +} + +func (ui *TUI) ExecutingBatchSpecSuccess() { + batchCompletePending(ui.pending, "Executing batch spec") +} + func (ui *TUI) ExecutionError(err error) { printExecutionError(ui.Out, err) } +func (ui *TUI) RemoteSuccess(url string) { + ui.Out.WriteLine(output.Line(output.EmojiLightbulb, output.Fg256Color(12), "Executing at: "+url)) +} + // prettyPrintBatchUnlicensedError introspects the given error returned when // creating a batch spec and ascertains whether it's a licensing error. If it // is, then a better message is output. Regardless, the return value of this From 39d88fcf93eceff8550388d88e26f4008d34d734 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Tue, 8 Feb 2022 20:11:29 +0100 Subject: [PATCH 129/647] asdf: Add some more commonly used tools (#693) --- .tool-versions | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.tool-versions b/.tool-versions index b763344878..e5c4ae8b67 100644 --- a/.tool-versions +++ b/.tool-versions @@ -1 +1,3 @@ -golang 1.17 +golang 1.17.5 +shfmt 3.2.0 +shellcheck 0.7.1 From dcb9b8cc496e81bb99f3fe85cc34d9fdbd84f3d1 Mon Sep 17 00:00:00 2001 From: Adam Harvey Date: Fri, 11 Feb 2022 11:18:22 -0800 Subject: [PATCH 130/647] go.mod: use grafana/regexp, matching sourcegraph/sourcegraph#30948 (#694) --- CHANGELOG.md | 2 ++ cmd/src/colors.go | 3 ++- cmd/src/search.go | 3 ++- cmd/src/search_alert_test.go | 3 ++- cmd/src/search_stream.go | 3 ++- cmd/src/search_test.go | 3 ++- go.mod | 1 + go.sum | 2 ++ internal/api/version_check.go | 2 +- internal/batches/service/service.go | 3 ++- 10 files changed, 18 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d4e41d0c52..8f42f4be87 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,8 @@ All notable changes to `src-cli` are documented in this file. ### Changed +- Migrated to [`grafana/regexp`](https://github.com/grafana/regexp) to match our usage in Sourcegraph proper. [#694](https://github.com/sourcegraph/src-cli/pull/694) + ### Fixed ### Removed diff --git a/cmd/src/colors.go b/cmd/src/colors.go index 9bb8dd0792..8d671e97f4 100644 --- a/cmd/src/colors.go +++ b/cmd/src/colors.go @@ -3,9 +3,10 @@ package main import ( "fmt" "os" - "regexp" "strconv" + "github.com/grafana/regexp" + "github.com/mattn/go-isatty" ) diff --git a/cmd/src/search.go b/cmd/src/search.go index ced5cfa2bd..fbbfbcaeeb 100644 --- a/cmd/src/search.go +++ b/cmd/src/search.go @@ -9,11 +9,12 @@ import ( "io" "os" "os/exec" - "regexp" "strconv" "strings" "time" + "github.com/grafana/regexp" + isatty "github.com/mattn/go-isatty" "jaytaylor.com/html2text" diff --git a/cmd/src/search_alert_test.go b/cmd/src/search_alert_test.go index e23016c1d0..c5ca680e24 100644 --- a/cmd/src/search_alert_test.go +++ b/cmd/src/search_alert_test.go @@ -2,10 +2,11 @@ package main import ( "fmt" - "regexp" "strings" "testing" + "github.com/grafana/regexp" + "github.com/google/go-cmp/cmp" ) diff --git a/cmd/src/search_stream.go b/cmd/src/search_stream.go index 7df4018783..68ad43f987 100644 --- a/cmd/src/search_stream.go +++ b/cmd/src/search_stream.go @@ -7,11 +7,12 @@ import ( "io" "os" "os/exec" - "regexp" "strconv" "strings" "text/template" + "github.com/grafana/regexp" + "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/streaming" ) diff --git a/cmd/src/search_test.go b/cmd/src/search_test.go index 59b28c558e..db8ceec057 100644 --- a/cmd/src/search_test.go +++ b/cmd/src/search_test.go @@ -6,9 +6,10 @@ import ( "os" "os/exec" "path/filepath" - "regexp" "strings" "testing" + + "github.com/grafana/regexp" ) var _ = func() bool { diff --git a/go.mod b/go.mod index a5f9c16094..63aaee75dd 100644 --- a/go.mod +++ b/go.mod @@ -39,6 +39,7 @@ require ( github.com/ghodss/yaml v1.0.0 // indirect github.com/go-stack/stack v1.8.1 // indirect github.com/gogo/protobuf v1.3.2 // indirect + github.com/grafana/regexp v0.0.0-20220202152315-e74e38789280 // indirect github.com/hashicorp/errwrap v1.1.0 // indirect github.com/inconshreveable/log15 v0.0.0-20201112154412-8562bdadbbac // indirect github.com/klauspost/compress v1.14.2 // indirect diff --git a/go.sum b/go.sum index 9c555a112f..877cbd5d6b 100644 --- a/go.sum +++ b/go.sum @@ -125,6 +125,8 @@ github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/ github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= +github.com/grafana/regexp v0.0.0-20220202152315-e74e38789280 h1:MOND6wXrwVXEzmL2bZ+Jcbgycwt1LD5q6NQbqz/Nlic= +github.com/grafana/regexp v0.0.0-20220202152315-e74e38789280/go.mod h1:M5qHK+eWfAv8VR/265dIuEpL3fNfeC21tXXp9itM24A= github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= diff --git a/internal/api/version_check.go b/internal/api/version_check.go index 1c5fa1435b..dfc8e25f2c 100644 --- a/internal/api/version_check.go +++ b/internal/api/version_check.go @@ -1,7 +1,7 @@ package api import ( - "regexp" + "github.com/grafana/regexp" "github.com/Masterminds/semver" ) diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index c36c15a15c..815a76b8cc 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -8,10 +8,11 @@ import ( "os" "os/exec" "path" - "regexp" "strings" "sync" + "github.com/grafana/regexp" + "github.com/cockroachdb/errors" "github.com/hashicorp/go-multierror" From 82a0cb7f8a1d925ef4fe7fd02478adbb34202bcc Mon Sep 17 00:00:00 2001 From: Adam Harvey Date: Fri, 11 Feb 2022 11:51:22 -0800 Subject: [PATCH 131/647] batches: fix `src batch apply -f` (#695) --- CHANGELOG.md | 2 ++ cmd/src/batch_apply.go | 11 ++++++----- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8f42f4be87..e9d98633a7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,8 @@ All notable changes to `src-cli` are documented in this file. ### Fixed +- A bug in 3.36.3 caused `src batch apply` to no longer accept a file provided with `-f`. This has been fixed. [#695](https://github.com/sourcegraph/src-cli/pull/695) + ### Removed ## 3.36.3 diff --git a/cmd/src/batch_apply.go b/cmd/src/batch_apply.go index 59fe1700f3..9b3d3d5fa9 100644 --- a/cmd/src/batch_apply.go +++ b/cmd/src/batch_apply.go @@ -39,8 +39,9 @@ Examples: return err } - if len(flagSet.Args()) != 0 { - return cmderrors.Usage("additional arguments not allowed") + file, err := getBatchSpecFile(flagSet, &flags.file) + if err != nil { + return err } ctx, cancel := contextCancelOnInterrupt(context.Background()) @@ -54,13 +55,13 @@ Examples: execUI = &ui.TUI{Out: out} } - err := executeBatchSpec(ctx, execUI, executeBatchSpecOpts{ + if err = executeBatchSpec(ctx, execUI, executeBatchSpecOpts{ flags: flags, client: cfg.apiClient(flags.api, flagSet.Output()), + file: file, applyBatchSpec: true, - }) - if err != nil { + }); err != nil { return cmderrors.ExitCode(1, nil) } From afc01a9c5386432aa5ad9eb4d0b20bdb5ac252c1 Mon Sep 17 00:00:00 2001 From: Adam Harvey Date: Fri, 11 Feb 2022 11:52:25 -0800 Subject: [PATCH 132/647] changelog: update for 3.36.4 --- CHANGELOG.md | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e9d98633a7..16b2bb9711 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,16 @@ All notable changes to `src-cli` are documented in this file. ### Added +### Changed + +### Fixed + +### Removed + +## 3.36.4 + +### Added + - A new `src batch remote` command has been added to run a batch spec on a Sourcegraph instance that has Server Side Batch Changes enabled. [#671](https://github.com/sourcegraph/src-cli/pull/671) ### Changed @@ -23,8 +33,6 @@ All notable changes to `src-cli` are documented in this file. - A bug in 3.36.3 caused `src batch apply` to no longer accept a file provided with `-f`. This has been fixed. [#695](https://github.com/sourcegraph/src-cli/pull/695) -### Removed - ## 3.36.3 ### Changed From 3302dc60649b75002af3fc71c202848b62088224 Mon Sep 17 00:00:00 2001 From: Adam Harvey Date: Fri, 11 Feb 2022 12:04:26 -0800 Subject: [PATCH 133/647] batches: fix incorrect help text (#696) I obviously missed this when I removed the extra level of commands in the new command structure. --- cmd/src/batch_remote.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/src/batch_remote.go b/cmd/src/batch_remote.go index 0c38712ef9..201fc47aaa 100644 --- a/cmd/src/batch_remote.go +++ b/cmd/src/batch_remote.go @@ -130,7 +130,7 @@ Examples: aliases: []string{}, handler: handler, usageFunc: func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src batch remote %s':\n", flagSet.Name()) + fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src batch %s':\n", flagSet.Name()) flagSet.PrintDefaults() fmt.Println(usage) }, From cc28d2ccea0a1d9f9b329c26763b5247578f4794 Mon Sep 17 00:00:00 2001 From: Adam Harvey Date: Fri, 11 Feb 2022 12:09:27 -0800 Subject: [PATCH 134/647] go.mod: run tidy (#697) This caused the release to fail. (Side note: why on earth doesn't Go do this for you when you run `go get` as suggested?) --- go.mod | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/go.mod b/go.mod index 63aaee75dd..24102308d9 100644 --- a/go.mod +++ b/go.mod @@ -29,7 +29,10 @@ require ( jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7 ) -require github.com/stretchr/testify v1.7.0 +require ( + github.com/grafana/regexp v0.0.0-20220202152315-e74e38789280 + github.com/stretchr/testify v1.7.0 +) require ( github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect @@ -39,7 +42,6 @@ require ( github.com/ghodss/yaml v1.0.0 // indirect github.com/go-stack/stack v1.8.1 // indirect github.com/gogo/protobuf v1.3.2 // indirect - github.com/grafana/regexp v0.0.0-20220202152315-e74e38789280 // indirect github.com/hashicorp/errwrap v1.1.0 // indirect github.com/inconshreveable/log15 v0.0.0-20201112154412-8562bdadbbac // indirect github.com/klauspost/compress v1.14.2 // indirect From 164c48e6caee53ac68dfdfa110ea8a32d2436dc7 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Thu, 17 Feb 2022 16:33:49 +0100 Subject: [PATCH 135/647] Prepare changelog for 3.37.0 --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 16b2bb9711..ee4fd54408 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,10 @@ All notable changes to `src-cli` are documented in this file. ### Removed +## 3.37.0 + +No noteworthy changes, mechanical release to match Sourcegraph release. + ## 3.36.4 ### Added From 9640d9881654b1ffc3f857ed6511418f1ac95bf5 Mon Sep 17 00:00:00 2001 From: Robert Lin Date: Mon, 21 Feb 2022 09:03:26 -0800 Subject: [PATCH 136/647] all: migrate to github.com/sourcegraph/sourcegraph/lib/errors (#698) Migrates all errors in src-cli to use the new error types introduced in sourcegraph/sourcegraph#31466, and bans further imports of other error libraries. --- .golangci.yml | 6 +- cmd/src/batch_common.go | 11 ++- cmd/src/batch_exec.go | 2 +- cmd/src/batch_remote.go | 3 +- cmd/src/batch_repositories.go | 2 +- cmd/src/cmd.go | 2 +- cmd/src/config.go | 2 +- cmd/src/doc.go | 2 +- cmd/src/extensions_publish.go | 2 +- cmd/src/extsvc.go | 2 +- cmd/src/extsvc_edit.go | 2 +- cmd/src/lsif_upload_flags.go | 2 +- cmd/src/main.go | 2 +- cmd/src/repos_delete.go | 9 ++- cmd/src/search_alert.go | 2 +- cmd/src/validate.go | 2 +- go.mod | 24 +++---- go.sum | 70 ++++++++++++++----- internal/api/errors.go | 9 ++- internal/api/gzip.go | 4 +- internal/batches/docker/image.go | 2 +- internal/batches/executor/coordinator.go | 2 +- internal/batches/executor/execution_cache.go | 2 +- internal/batches/executor/executor.go | 2 +- internal/batches/executor/executor_test.go | 2 +- internal/batches/executor/run_steps.go | 12 +--- internal/batches/features.go | 2 +- internal/batches/log/manager.go | 6 +- internal/batches/log/task_logger.go | 2 +- internal/batches/repozip/fetcher.go | 2 +- internal/batches/service/remote.go | 2 +- internal/batches/service/service.go | 6 +- internal/batches/service/service_test.go | 2 +- internal/batches/service/workspaces.go | 2 +- internal/batches/ui/tui.go | 13 ++-- internal/batches/workspace/bind_workspace.go | 9 ++- .../workspace/bind_workspace_nonwin_test.go | 2 +- .../workspace/bind_workspace_windows_test.go | 2 +- internal/batches/workspace/git.go | 2 +- .../batches/workspace/volume_workspace.go | 2 +- .../workspace/volume_workspace_test.go | 2 +- internal/batches/workspace/workspace.go | 2 +- internal/batches/workspace/workspace_test.go | 2 +- internal/cmderrors/errors.go | 2 +- internal/exec/expect/expect.go | 13 ++-- internal/servegit/serve.go | 2 +- internal/streaming/writer.go | 2 +- 47 files changed, 141 insertions(+), 120 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 159d867086..70b873a074 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -20,8 +20,10 @@ linters-settings: list-type: blacklist include-go-root: true packages-with-error-message: - - errors: 'Use github.com/cockroachdb/errors instead' - - github.com/pkg/errors: 'Use github.com/cockroachdb/errors instead' + - errors: 'Use github.com/sourcegraph/sourcegraph/lib/errors instead' + - github.com/pkg/errors: 'Use github.com/sourcegraph/sourcegraph/lib/errors instead' + - github.com/cockroachdb/errors: 'Use github.com/sourcegraph/sourcegraph/lib/errors instead' + - github.com/hashicorp/go-multierror: 'Use github.com/sourcegraph/sourcegraph/lib/errors instead' - io/ioutil: 'The ioutil package has been deprecated' gocritic: disabled-checks: diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index f77bcf3c9c..0ee98b9bb7 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -13,9 +13,8 @@ import ( "strings" "time" - "github.com/cockroachdb/errors" - "github.com/hashicorp/go-multierror" "github.com/mattn/go-isatty" + "github.com/sourcegraph/sourcegraph/lib/errors" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/template" @@ -282,7 +281,7 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp ui.ParsingBatchSpec() batchSpec, rawSpec, err := parseBatchSpec(opts.file, svc) if err != nil { - var multiErr *multierror.Error + var multiErr errors.MultiError if errors.As(err, &multiErr) { ui.ParsingBatchSpecFailure(multiErr) return cmderrors.ExitCode(2, nil) @@ -388,14 +387,12 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp freshSpecs, logFiles, execErr := coord.ExecuteAndBuildSpecs(ctx, batchSpec, uncachedTasks, taskExecUI) // Add external changeset specs. importedSpecs, importErr := svc.CreateImportChangesetSpecs(ctx, batchSpec) - var errs *multierror.Error if execErr != nil { - errs = multierror.Append(errs, execErr) + err = errors.Append(err, execErr) } if importErr != nil { - errs = multierror.Append(errs, importErr) + err = errors.Append(err, importErr) } - err = errs.ErrorOrNil() if err != nil && !opts.flags.skipErrors { return err } diff --git a/cmd/src/batch_exec.go b/cmd/src/batch_exec.go index 81eb5ff3fa..021ad9333a 100644 --- a/cmd/src/batch_exec.go +++ b/cmd/src/batch_exec.go @@ -7,7 +7,7 @@ import ( "fmt" "io" - "github.com/cockroachdb/errors" + "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/batches/executor" "github.com/sourcegraph/src-cli/internal/batches/graphql" diff --git a/cmd/src/batch_remote.go b/cmd/src/batch_remote.go index 201fc47aaa..ef4e4e5e50 100644 --- a/cmd/src/batch_remote.go +++ b/cmd/src/batch_remote.go @@ -7,8 +7,9 @@ import ( "strings" "time" - "github.com/cockroachdb/errors" + "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/sourcegraph/lib/output" + "github.com/sourcegraph/src-cli/internal/batches/service" "github.com/sourcegraph/src-cli/internal/batches/ui" ) diff --git a/cmd/src/batch_repositories.go b/cmd/src/batch_repositories.go index 927849ad48..c54467cc5a 100644 --- a/cmd/src/batch_repositories.go +++ b/cmd/src/batch_repositories.go @@ -5,7 +5,7 @@ import ( "flag" "fmt" - "github.com/cockroachdb/errors" + "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/sourcegraph/lib/output" "github.com/sourcegraph/src-cli/internal/api" diff --git a/cmd/src/cmd.go b/cmd/src/cmd.go index 6d4fb53215..7d602b2a64 100644 --- a/cmd/src/cmd.go +++ b/cmd/src/cmd.go @@ -7,7 +7,7 @@ import ( "os" "strings" - "github.com/cockroachdb/errors" + "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/cmderrors" ) diff --git a/cmd/src/config.go b/cmd/src/config.go index 572e81264e..ffd3b3a24e 100644 --- a/cmd/src/config.go +++ b/cmd/src/config.go @@ -5,7 +5,7 @@ import ( "flag" "fmt" - "github.com/cockroachdb/errors" + "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/api" ) diff --git a/cmd/src/doc.go b/cmd/src/doc.go index cd17c93e48..1fb0254830 100644 --- a/cmd/src/doc.go +++ b/cmd/src/doc.go @@ -10,7 +10,7 @@ import ( "strings" "text/template" - "github.com/cockroachdb/errors" + "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/sourcegraph/lib/output" "github.com/sourcegraph/src-cli/internal/cmderrors" diff --git a/cmd/src/extensions_publish.go b/cmd/src/extensions_publish.go index 0c1d7819c7..afc1f40e1f 100644 --- a/cmd/src/extensions_publish.go +++ b/cmd/src/extensions_publish.go @@ -10,7 +10,7 @@ import ( "path/filepath" "strings" - "github.com/cockroachdb/errors" + "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/api" ) diff --git a/cmd/src/extsvc.go b/cmd/src/extsvc.go index a2fa9f8d15..e761dd1714 100644 --- a/cmd/src/extsvc.go +++ b/cmd/src/extsvc.go @@ -5,7 +5,7 @@ import ( "flag" "fmt" - "github.com/cockroachdb/errors" + "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/api" ) diff --git a/cmd/src/extsvc_edit.go b/cmd/src/extsvc_edit.go index dd420fa27d..b38bf6c4a2 100644 --- a/cmd/src/extsvc_edit.go +++ b/cmd/src/extsvc_edit.go @@ -9,7 +9,7 @@ import ( "os" "strings" - "github.com/cockroachdb/errors" + "github.com/sourcegraph/sourcegraph/lib/errors" isatty "github.com/mattn/go-isatty" "github.com/sourcegraph/jsonx" diff --git a/cmd/src/lsif_upload_flags.go b/cmd/src/lsif_upload_flags.go index 5c2b4ac01b..fd10004969 100644 --- a/cmd/src/lsif_upload_flags.go +++ b/cmd/src/lsif_upload_flags.go @@ -6,7 +6,7 @@ import ( "os" "strings" - "github.com/cockroachdb/errors" + "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/sourcegraph/lib/codeintel/upload" diff --git a/cmd/src/main.go b/cmd/src/main.go index e7fff11d8f..4a0099057b 100644 --- a/cmd/src/main.go +++ b/cmd/src/main.go @@ -10,7 +10,7 @@ import ( "path/filepath" "strings" - "github.com/cockroachdb/errors" + "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/api" ) diff --git a/cmd/src/repos_delete.go b/cmd/src/repos_delete.go index 5d0edddebc..2057041a34 100644 --- a/cmd/src/repos_delete.go +++ b/cmd/src/repos_delete.go @@ -5,8 +5,7 @@ import ( "flag" "fmt" - "github.com/cockroachdb/errors" - multierror "github.com/hashicorp/go-multierror" + "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/api" ) @@ -60,15 +59,15 @@ Examples: ctx := context.Background() client := cfg.apiClient(apiFlags, flagSet.Output()) - var errs *multierror.Error + var errs errors.MultiError for _, repoName := range flagSet.Args() { err := deleteRepository(ctx, client, repoName) if err != nil { err = errors.Wrapf(err, "Failed to delete repository %q", repoName) - errs = multierror.Append(errs, err) + errs = errors.Append(errs, err) } } - return errs.ErrorOrNil() + return errs } // Register the command. diff --git a/cmd/src/search_alert.go b/cmd/src/search_alert.go index 51362d5a8f..44b4b9149f 100644 --- a/cmd/src/search_alert.go +++ b/cmd/src/search_alert.go @@ -4,7 +4,7 @@ import ( "strings" "text/template" - "github.com/cockroachdb/errors" + "github.com/sourcegraph/sourcegraph/lib/errors" ) var searchResultsAlertTemplate *template.Template diff --git a/cmd/src/validate.go b/cmd/src/validate.go index f1ebc29385..2720518d81 100644 --- a/cmd/src/validate.go +++ b/cmd/src/validate.go @@ -13,7 +13,7 @@ import ( "text/template" "time" - "github.com/cockroachdb/errors" + "github.com/sourcegraph/sourcegraph/lib/errors" jsoniter "github.com/json-iterator/go" "github.com/mattn/go-isatty" diff --git a/go.mod b/go.mod index 24102308d9..28cb855669 100644 --- a/go.mod +++ b/go.mod @@ -4,15 +4,13 @@ go 1.17 require ( github.com/Masterminds/semver v1.5.0 - github.com/cockroachdb/errors v1.8.6 - github.com/cockroachdb/redact v1.1.3 // indirect github.com/creack/goselect v0.1.2 github.com/derision-test/glock v0.0.0-20210316032053-f5b74334bb29 github.com/dineshappavoo/basex v0.0.0-20170425072625-481a6f6dc663 github.com/dustin/go-humanize v1.0.0 github.com/gobwas/glob v0.2.3 github.com/google/go-cmp v0.5.7 - github.com/hashicorp/go-multierror v1.1.1 + github.com/grafana/regexp v0.0.0-20220202152701-6a046c4caf32 github.com/jig/teereadcloser v0.0.0-20181016160506-953720c48e05 github.com/json-iterator/go v1.1.12 github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 @@ -21,28 +19,23 @@ require ( github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4 github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf - github.com/sourcegraph/sourcegraph/lib v0.0.0-20220204151625-fceb046d5b75 - github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect - github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect + github.com/sourcegraph/sourcegraph/lib v0.0.0-20220218193119-f6123c1144b4 + github.com/stretchr/testify v1.7.0 golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7 ) -require ( - github.com/grafana/regexp v0.0.0-20220202152315-e74e38789280 - github.com/stretchr/testify v1.7.0 -) - require ( github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect + github.com/cockroachdb/errors v1.8.9 // indirect github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f // indirect - github.com/cockroachdb/sentry-go v0.6.1-cockroachdb.2 // indirect + github.com/cockroachdb/redact v1.1.3 // indirect github.com/davecgh/go-spew v1.1.1 // indirect + github.com/getsentry/sentry-go v0.12.0 // indirect github.com/ghodss/yaml v1.0.0 // indirect github.com/go-stack/stack v1.8.1 // indirect github.com/gogo/protobuf v1.3.2 // indirect - github.com/hashicorp/errwrap v1.1.0 // indirect github.com/inconshreveable/log15 v0.0.0-20201112154412-8562bdadbbac // indirect github.com/klauspost/compress v1.14.2 // indirect github.com/klauspost/pgzip v1.2.5 // indirect @@ -58,9 +51,12 @@ require ( github.com/pmezard/go-difflib v1.0.0 // indirect github.com/rivo/uniseg v0.2.0 // indirect github.com/rogpeppe/go-internal v1.8.1 // indirect + github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect + github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect github.com/xeipuuv/gojsonschema v1.2.0 // indirect - golang.org/x/sys v0.0.0-20220128215802-99c3d69c2c27 // indirect + golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect + golang.org/x/sys v0.0.0-20220209214540-3681064d5158 // indirect golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect ) diff --git a/go.sum b/go.sum index 877cbd5d6b..ef24c2eb72 100644 --- a/go.sum +++ b/go.sum @@ -4,7 +4,9 @@ github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 h1:UQHMgLO+TxOEl github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/CloudyKit/fastprinter v0.0.0-20170127035650-74b38d55f37a/go.mod h1:EFZQ978U7x8IRnstaskI3IysnWY5Ao3QgZUKOXlsAdw= +github.com/CloudyKit/fastprinter v0.0.0-20200109182630-33d98a066a53/go.mod h1:+3IMCy2vIlbG1XG/0ggNQv0SvxCAIpPM5b1nCz56Xno= github.com/CloudyKit/jet v2.1.3-0.20180809161101-62edd43e4f88+incompatible/go.mod h1:HPYO+50pSWkPoj9Q/eq0aRGByCL6ScRlUmiEX5Zgm+w= +github.com/CloudyKit/jet/v3 v3.0.0/go.mod h1:HKQPgSJmdK8hdoAbKUUWajkHyHo4RaU5rMdUywE7VMo= github.com/Joker/hpp v1.0.0/go.mod h1:8x5n+M1Hp5hC0g8okX3sR3vFQwynaX/UgSOM9MeBKzY= github.com/Joker/jade v1.0.1-0.20190614124447-d475f43051e7/go.mod h1:6E6s8o2AE4KhCrqr6GRJjdC/gNfTdxkIXvuGZZda2VM= github.com/Masterminds/semver v1.5.0 h1:H65muMkzWKEuNDnfl9d70GUjFniHKHRbFPGBuZ3QEww= @@ -21,17 +23,17 @@ github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= -github.com/cockroachdb/datadriven v1.0.0/go.mod h1:5Ib8Meh+jk1RlHIXej6Pzevx/NLlNvQB9pmSBZErGA4= +github.com/cockroachdb/datadriven v1.0.1-0.20211007161720-b558070c3be0/go.mod h1:5Ib8Meh+jk1RlHIXej6Pzevx/NLlNvQB9pmSBZErGA4= +github.com/cockroachdb/datadriven v1.0.1-0.20220214170620-9913f5bc19b7/go.mod h1:hi0MtSY3AYDQNDi83kDkMH5/yqM/CsIrsOITkSoH7KI= github.com/cockroachdb/errors v1.6.1/go.mod h1:tm6FTP5G81vwJ5lC0SizQo374JNCOPrHyXGitRJoDqM= -github.com/cockroachdb/errors v1.8.6 h1:Am9evxl/po3RzpokemQvq7S7Cd0mxv24xy0B/trlQF4= -github.com/cockroachdb/errors v1.8.6/go.mod h1:hOm5fabihW+xEyY1kuypGwqT+Vt7rafg04ytBtIpeIQ= +github.com/cockroachdb/errors v1.8.8/go.mod h1:z6VnEL3hZ/2ONZEvG7S5Ym0bU2AqPcEKnIiA1wbsSu0= +github.com/cockroachdb/errors v1.8.9 h1:eqUxTOUOduHP4D3f3wJ0kiyoNjDf6wLCso/4n7rBA4U= +github.com/cockroachdb/errors v1.8.9/go.mod h1:vaNcEYYqbIqB5JhKBhFV9CneUqeuEbB2OYJBK4GBNYQ= github.com/cockroachdb/logtags v0.0.0-20190617123548-eb05cc24525f/go.mod h1:i/u985jwjWRlyHXQbwatDASoW0RMlZ/3i9yJHE2xLkI= github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f h1:6jduT9Hfc0njg5jJ1DdKCFPdMBrp/mdZfCpa5h+WM74= github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= -github.com/cockroachdb/redact v1.1.1/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= github.com/cockroachdb/redact v1.1.3 h1:AKZds10rFSIj7qADf0g46UixK8NNLwWTNdCIGS5wfSQ= github.com/cockroachdb/redact v1.1.3/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= -github.com/cockroachdb/sentry-go v0.6.1-cockroachdb.2 h1:IKgmqgMQlVJIZj19CdocBeSfSaiCbEBZGKODaixqtHM= github.com/cockroachdb/sentry-go v0.6.1-cockroachdb.2/go.mod h1:8BT+cPK6xvFOcRlk0R8eg+OTkcqI6baNH4xAkpiYVvQ= github.com/codegangsta/inject v0.0.0-20150114235600-33e0aa1cb7c0/go.mod h1:4Zcjuz89kmFXt9morQgcfYZAYZ5n8WHjt81YYWIwtTM= github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= @@ -72,6 +74,8 @@ github.com/frankban/quicktest v1.14.0/go.mod h1:NeW+ay9A/U67EYXNFA1nPE8e/tnQv/09 github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/gavv/httpexpect v2.0.0+incompatible/go.mod h1:x+9tiU1YnrOvnB725RkpoLv1M62hOWzwo5OXotisrKc= +github.com/getsentry/sentry-go v0.12.0 h1:era7g0re5iY13bHSdN/xMkyV+5zZppjRVQhZrXCaEIk= +github.com/getsentry/sentry-go v0.12.0/go.mod h1:NSap0JBYWzHND8oMbyi0+XZhUalc1TBdRL1M71JZW2c= github.com/gin-contrib/sse v0.0.0-20190301062529-5545eab6dad3/go.mod h1:VJ0WA2NBN22VlZ2dKZQPAPnyWw5XTlK1KymzLKsr59s= github.com/gin-gonic/gin v1.4.0/go.mod h1:OW2EZn3DO8Ln9oIKOvM++LBO+5UPHJJDH72/q/3rZdM= github.com/go-check/check v0.0.0-20180628173108-788fd7840127/go.mod h1:9ES+weclKsC9YodN5RgxqK/VD9HM9JsCSh7rNhMZE98= @@ -93,6 +97,7 @@ github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXP github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= github.com/gogo/status v1.1.0/go.mod h1:BFv9nrluPLmrS0EmGVvLaPNmRosr9KapBYd5/hpY1WM= +github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= @@ -125,13 +130,9 @@ github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/ github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= -github.com/grafana/regexp v0.0.0-20220202152315-e74e38789280 h1:MOND6wXrwVXEzmL2bZ+Jcbgycwt1LD5q6NQbqz/Nlic= -github.com/grafana/regexp v0.0.0-20220202152315-e74e38789280/go.mod h1:M5qHK+eWfAv8VR/265dIuEpL3fNfeC21tXXp9itM24A= -github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= -github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= -github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= -github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= -github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= +github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/grafana/regexp v0.0.0-20220202152701-6a046c4caf32 h1:M3wP8Hwic62qJsiydSgXtev03d4f92uN1I52nVjRgw0= +github.com/grafana/regexp v0.0.0-20220202152701-6a046c4caf32/go.mod h1:M5qHK+eWfAv8VR/265dIuEpL3fNfeC21tXXp9itM24A= github.com/hashicorp/go-version v1.2.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= github.com/hexops/autogold v0.8.1/go.mod h1:97HLDXyG23akzAoRYJh/2OBs3kd80eHyKPvZw0S5ZBY= @@ -149,10 +150,13 @@ github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANyt github.com/iris-contrib/blackfriday v2.0.0+incompatible/go.mod h1:UzZ2bDEoaSGPbkg6SAB4att1aAwTmVIx/5gCVqeyUdI= github.com/iris-contrib/go.uuid v2.0.0+incompatible/go.mod h1:iz2lgM/1UnEf1kP0L/+fafWORmlnuysV2EMP8MW+qe0= github.com/iris-contrib/i18n v0.0.0-20171121225848-987a633949d0/go.mod h1:pMCz62A0xJL6I+umB2YTlFRwWXaDFA0jy+5HzGiJjqI= +github.com/iris-contrib/jade v1.1.3/go.mod h1:H/geBymxJhShH5kecoiOCSssPX7QWYH7UaeZTSWddIk= +github.com/iris-contrib/pongo2 v0.0.1/go.mod h1:Ssh+00+3GAZqSQb30AvBRNxBx7rf0GqwkjqxNd0u65g= github.com/iris-contrib/schema v0.0.1/go.mod h1:urYA3uvUNG1TIIjOSCzHr9/LmbQo8LrOcOqfqxa4hXw= github.com/jig/teereadcloser v0.0.0-20181016160506-953720c48e05 h1:dSwwtWuwMyarzsbVWOq4QJ8xVy9wgcNomvWyGtrKe+E= github.com/jig/teereadcloser v0.0.0-20181016160506-953720c48e05/go.mod h1:sRUFlj+HCejvoCRpuhU0EYnNw5FG+YJpz8UFfCf0F2U= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= +github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= @@ -161,9 +165,14 @@ github.com/juju/loggo v0.0.0-20180524022052-584905176618/go.mod h1:vgyd7OREkbtVE github.com/juju/testing v0.0.0-20180920084828-472a3e8b2073/go.mod h1:63prj8cnj0tU0S9OHjGJn+b1h0ZghCndfnbQolrYTwA= github.com/k0kubun/colorstring v0.0.0-20150214042306-9440f1994b88/go.mod h1:3w7q1U84EfirKl04SVQ/s7nPm1ZPhiXd34z40TNz36k= github.com/kataras/golog v0.0.9/go.mod h1:12HJgwBIZFNGL0EJnMRhmvGA0PQGx8VFwrZtM4CqbAk= +github.com/kataras/golog v0.0.10/go.mod h1:yJ8YKCmyL+nWjERB90Qwn+bdyBZsaQwU3bTVFgkFIp8= github.com/kataras/iris/v12 v12.0.1/go.mod h1:udK4vLQKkdDqMGJJVd/msuMtN6hpYJhg/lSzuxjhO+U= +github.com/kataras/iris/v12 v12.1.8/go.mod h1:LMYy4VlP67TQ3Zgriz8RE2h2kMZV2SgMYbq3UhfoFmE= github.com/kataras/neffos v0.0.10/go.mod h1:ZYmJC07hQPW67eKuzlfY7SO3bC0mw83A3j6im82hfqw= +github.com/kataras/neffos v0.0.14/go.mod h1:8lqADm8PnbeFfL7CLXh1WHw53dG27MC3pgi2R1rmoTE= github.com/kataras/pio v0.0.0-20190103105442-ea782b38602d/go.mod h1:NV88laa9UiiDuX9AhMbDPkGYSPugBOV6yTZB1l2K9Z0= +github.com/kataras/pio v0.0.2/go.mod h1:hAoW0t9UmXi4R5Oyq5Z4irTbaTsOemSrDGUtaTl7Dro= +github.com/kataras/sitemap v0.0.5/go.mod h1:KY2eugMKiPwsJgx7+U103YZehfvNGOXURubcGyk0Bz8= github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 h1:Z9n2FFNUXsshfwJMBgNA0RU6/i7WVaAegv3PtuIHPMs= github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51/go.mod h1:CzGEWj7cYgsdH8dAjBGEr58BoE7ScuLd+fwFZ44+/x8= github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= @@ -171,6 +180,7 @@ github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/klauspost/compress v1.8.2/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= github.com/klauspost/compress v1.9.0/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= +github.com/klauspost/compress v1.9.7/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= github.com/klauspost/compress v1.14.2 h1:S0OHlFk/Gbon/yauFJ4FfJJF5V0fc5HbBTJazi28pRw= github.com/klauspost/compress v1.14.2/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= github.com/klauspost/cpuid v1.2.1/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek= @@ -185,10 +195,13 @@ github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/labstack/echo/v4 v4.1.11/go.mod h1:i541M3Fj6f76NZtHSj7TXnyM8n2gaodfvfxNnFqi74g= +github.com/labstack/echo/v4 v4.5.0/go.mod h1:czIriw4a0C1dFun+ObrXp7ok03xON0N1awStJ6ArI7Y= github.com/labstack/gommon v0.3.0/go.mod h1:MULnywXg0yavhxWKc+lOruYdAhDwPK9wf0OL7NoOu+k= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= +github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= +github.com/mattn/go-colorable v0.1.11/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= github.com/mattn/go-colorable v0.1.12 h1:jF+Du6AlPIjs2BiUiQlKOX0rt3SujHxPnksPKZbaA40= github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= github.com/mattn/go-isatty v0.0.7/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= @@ -203,6 +216,7 @@ github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh github.com/mattn/goveralls v0.0.2/go.mod h1:8d1ZMHsd7fW6IRPKQh46F2WRpyib5/X4FOpevwGNQEw= github.com/mediocregopher/mediocre-go-lib v0.0.0-20181029021733-cb65787f37ed/go.mod h1:dSsfyI2zABAdhcbvkXqgxOxrCsbYeHCPgrZkku60dSg= github.com/mediocregopher/radix/v3 v3.3.0/go.mod h1:EmfVyvspXz1uZEyPBMyGK+kjWiKQGvsUt6O3Pj+LDCQ= +github.com/mediocregopher/radix/v3 v3.4.2/go.mod h1:8FL3F6UQRXHXIBSPUs5h0RybMF8i4n7wVopoX3x7Bv8= github.com/microcosm-cc/bluemonday v1.0.2/go.mod h1:iVP4YcDBq+n/5fb23BhYFvIMq/leAFZyRl6bYmGDlGc= github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw= github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s= @@ -216,12 +230,16 @@ github.com/moby/term v0.0.0-20210619224110-3f7ff695adc6/go.mod h1:E2VnQOmVuvZB6U github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/moul/http2curl v1.0.0/go.mod h1:8UbvGypXm98wA/IqH45anm5Y2Z6ep6O31QGOAZ3H0fQ= +github.com/nats-io/jwt v0.3.0/go.mod h1:fRYCDE99xlTsqUzISS1Bi75UBJ6ljOJQOAAu5VglpSg= github.com/nats-io/nats.go v1.8.1/go.mod h1:BrFz9vVn0fU3AcH9Vn4Kd7W0NpJ651tD5omQ3M8LwxM= +github.com/nats-io/nats.go v1.9.1/go.mod h1:ZjDU1L/7fJ09jvUSRVBR2e7+RnLiiIQyqyzEE/Zbp4w= github.com/nats-io/nkeys v0.0.2/go.mod h1:dab7URMsZm6Z/jp9Z5UGa87Uutgc2mVpXLC4B7TDb/4= +github.com/nats-io/nkeys v0.1.0/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w= github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c= github.com/neelance/parallel v0.0.0-20160708114440-4de9ce63d14c h1:NZOii9TDGRAfCS5VM16XnF4K7afoLQmIiZX8EkKnxtE= github.com/neelance/parallel v0.0.0-20160708114440-4de9ce63d14c/go.mod h1:eTBvSIlRgLo+CNFFQRQTwUGTZOEdvXIKeZS/xG+D2yU= @@ -231,6 +249,7 @@ github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+ github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec= github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.10.3/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= github.com/onsi/ginkgo v1.13.0/go.mod h1:+REjRxOmWfHCjfv9TTWB1jD1Frx4XydAD3zm1lskyM0= github.com/onsi/ginkgo v1.16.2/go.mod h1:CObGmKUOKaSC0RjmoAK7tKyn4Azo5P2IWuoMnvwxz1E= @@ -258,20 +277,23 @@ github.com/rogpeppe/go-internal v1.8.1 h1:geMPLpDpQOgVyCg5z5GoRwLHepNdb71NXb67XF github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= github.com/ryanuber/columnize v2.1.0+incompatible/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= +github.com/schollz/closestmatch v2.1.0+incompatible/go.mod h1:RtP1ddjLong6gTkbtmuhtR2uUrrJOpYzYRvbcPAid+g= github.com/sclevine/agouti v3.0.0+incompatible/go.mod h1:b4WX9W9L1sfQKXeJf1mUTLZKJ48R1S7H23Ji7oFO5Bw= +github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= github.com/shurcooL/go v0.0.0-20180423040247-9e1955d9fb6e/go.mod h1:TDJrrUr11Vxrven61rcy3hJMUqaf/CLWYhHNPmT14Lk= github.com/shurcooL/go-goon v0.0.0-20170922171312-37c2f522c041/go.mod h1:N5mDOmsrJOB+vfqUK+7DmDyjhSLIIBnXo9lvZJj3MWQ= github.com/shurcooL/go-goon v0.0.0-20210110234559-7585751d9a17/go.mod h1:N5mDOmsrJOB+vfqUK+7DmDyjhSLIIBnXo9lvZJj3MWQ= github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= +github.com/smacker/go-tree-sitter v0.0.0-20220209044044-0d3022e933c3/go.mod h1:EiUuVMUfLQj8Sul+S8aKWJwQy7FRYnJCO2EWzf8F5hk= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= github.com/sourcegraph/go-diff v0.6.1 h1:hmA1LzxW0n1c3Q4YbrFgg4P99GSnebYa3x8gr0HZqLQ= github.com/sourcegraph/go-diff v0.6.1/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20220204151625-fceb046d5b75 h1:XCvY1beVBLRnJHgyQ9T9AexDlUMfQwez3yGAX59yBZ4= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20220204151625-fceb046d5b75/go.mod h1:u3KHLBGdpCN8bgI8PxPafb8vh3e+ftHkHZdjaXXIpFA= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20220218193119-f6123c1144b4 h1:QOdM6vg4+Co8p0OEQtRzOcyxmN4+Ib8FrsSj2/LLzk4= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20220218193119-f6123c1144b4/go.mod h1:6/o2uP/pgAIyAZWqHeZF4J9F8rfWvkU3BRqVLWpLwTA= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= @@ -291,11 +313,14 @@ github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc= +github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw= github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= +github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY= github.com/urfave/negroni v1.0.0/go.mod h1:Meg73S6kFm/4PpbYdq35yYWoCZ9mS/YSx+lKnmiohz4= github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= github.com/valyala/fasthttp v1.6.0/go.mod h1:FstJa9V+Pj9vQ7OJie2qMHdwemEDaDiSdBnvPM1Su9w= github.com/valyala/fasttemplate v1.0.1/go.mod h1:UQGH1tvbgY+Nz5t2n7tXsz52dQxojPUpymEIMZ47gx8= +github.com/valyala/fasttemplate v1.2.1/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ= github.com/valyala/tcplisten v0.0.0-20161114210144-ceec8f93295a/go.mod h1:v3UYOV9WzVtRmSR+PDvWpU/qWl4Wa5LApYYX4ZtKbio= github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb h1:zGWFAtiMcyryUHoUjUJX0/lt1H2+i2Ka2n+D3DImSNo= @@ -317,7 +342,10 @@ golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnf golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20191227163750-53104e6ec876/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= @@ -341,12 +369,15 @@ golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190827160401-ba9fcec4b297/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk= golang.org/x/net v0.0.0-20210614182718-04defd469f4e/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20211008194852-3b03d305991f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f h1:OfiFi4JbukWwe3lzw+xunroH1mnC1e2Gy5cxNJApiSY= golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= @@ -356,6 +387,7 @@ golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20210220032951-036812b2e83c h1:5KslGYwFpkhGh+Q16bwMP3cOontH8FOep7tGV86Y7SQ= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -378,18 +410,21 @@ golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210218084038-e8e29180ff58/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210403161142-5e06dd20ab57/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210611083646-a4fc73990273/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211007075335-d3039528d8ac/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211102192858-4dd72447c267/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211117180635-dee7805ff2e1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211213223007-03aa0b5f6827/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220128215802-99c3d69c2c27 h1:XDXtA5hveEEV8JB2l7nhMTp3t3cHp9ZpwcdjqyEWLlo= -golang.org/x/sys v0.0.0-20220128215802-99c3d69c2c27/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220209214540-3681064d5158 h1:rm+CHSpPEEW2IsXUib1ThaHIjuBVZjxNgSKmBLFfD4c= +golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= @@ -397,6 +432,7 @@ golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/time v0.0.0-20201208040808-7e3f01d25324/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20181221001348-537d06c36207/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -458,6 +494,7 @@ gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= gopkg.in/go-playground/assert.v1 v1.2.1/go.mod h1:9RXL0bg/zibRAgZUYszZSwO/z8Y/a8bDuhia5mkpMnE= gopkg.in/go-playground/validator.v8 v8.18.2/go.mod h1:RX2a/7Ha8BgOhfk7j780h4/u/RRjR0eouCJSH80/M2Y= +gopkg.in/ini.v1 v1.51.1/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/mgo.v2 v2.0.0-20180705113604-9856a29383ce/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= @@ -465,6 +502,7 @@ gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20191120175047-4206685974f2/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/api/errors.go b/internal/api/errors.go index 051fd47e73..278beef34f 100644 --- a/internal/api/errors.go +++ b/internal/api/errors.go @@ -3,8 +3,7 @@ package api import ( "encoding/json" - "github.com/cockroachdb/errors" - "github.com/hashicorp/go-multierror" + "github.com/sourcegraph/sourcegraph/lib/errors" ) // GraphQlErrors contains one or more GraphQlError instances. @@ -20,12 +19,12 @@ func (gg GraphQlErrors) Error() string { return "" } - var errs *multierror.Error + var errs errors.MultiError for _, err := range gg { - errs = multierror.Append(errs, err) + errs = errors.Append(errs, err) } - return errors.Wrap(errs.ErrorOrNil(), "GraphQL errors").Error() + return errors.Wrap(errs, "GraphQL errors").Error() } // GraphQlError wraps a raw JSON error returned from a GraphQL endpoint. diff --git a/internal/api/gzip.go b/internal/api/gzip.go index a9445c1483..de4b61d6a9 100644 --- a/internal/api/gzip.go +++ b/internal/api/gzip.go @@ -4,7 +4,7 @@ import ( "compress/gzip" "io" - "github.com/hashicorp/go-multierror" + "github.com/sourcegraph/sourcegraph/lib/errors" ) // gzipReader decorates a source reader by gzip compressing its contents. @@ -22,7 +22,7 @@ func gzipPipe(r io.Reader, w io.Writer) (err error) { gzipWriter := gzip.NewWriter(w) defer func() { if closeErr := gzipWriter.Close(); closeErr != nil { - err = multierror.Append(err, err) + err = errors.Append(err, err) } }() diff --git a/internal/batches/docker/image.go b/internal/batches/docker/image.go index cc610fb36d..bd3aed9ba1 100644 --- a/internal/batches/docker/image.go +++ b/internal/batches/docker/image.go @@ -7,7 +7,7 @@ import ( "strings" "sync" - "github.com/cockroachdb/errors" + "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/exec" ) diff --git a/internal/batches/executor/coordinator.go b/internal/batches/executor/coordinator.go index c464f4c564..71176727e9 100644 --- a/internal/batches/executor/coordinator.go +++ b/internal/batches/executor/coordinator.go @@ -5,7 +5,7 @@ import ( "os" "time" - "github.com/cockroachdb/errors" + "github.com/sourcegraph/sourcegraph/lib/errors" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/execution" diff --git a/internal/batches/executor/execution_cache.go b/internal/batches/executor/execution_cache.go index 0494286de6..187b8bd001 100644 --- a/internal/batches/executor/execution_cache.go +++ b/internal/batches/executor/execution_cache.go @@ -6,7 +6,7 @@ import ( "os" "path/filepath" - "github.com/cockroachdb/errors" + "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/sourcegraph/lib/batches/execution" "github.com/sourcegraph/sourcegraph/lib/batches/execution/cache" diff --git a/internal/batches/executor/executor.go b/internal/batches/executor/executor.go index 332f324828..311dfa7710 100644 --- a/internal/batches/executor/executor.go +++ b/internal/batches/executor/executor.go @@ -7,8 +7,8 @@ import ( "sync" "time" - "github.com/cockroachdb/errors" "github.com/neelance/parallel" + "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/batches/log" "github.com/sourcegraph/src-cli/internal/batches/repozip" diff --git a/internal/batches/executor/executor_test.go b/internal/batches/executor/executor_test.go index 57f2302673..33cff82f85 100644 --- a/internal/batches/executor/executor_test.go +++ b/internal/batches/executor/executor_test.go @@ -13,9 +13,9 @@ import ( "testing" "time" - "github.com/cockroachdb/errors" "github.com/google/go-cmp/cmp" "github.com/sourcegraph/go-diff/diff" + "github.com/sourcegraph/sourcegraph/lib/errors" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/execution" diff --git a/internal/batches/executor/run_steps.go b/internal/batches/executor/run_steps.go index ab68ae3612..1f11e969d9 100644 --- a/internal/batches/executor/run_steps.go +++ b/internal/batches/executor/run_steps.go @@ -11,13 +11,11 @@ import ( "strings" "time" - "github.com/cockroachdb/errors" - "github.com/hashicorp/go-multierror" - batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/execution" "github.com/sourcegraph/sourcegraph/lib/batches/git" "github.com/sourcegraph/sourcegraph/lib/batches/template" + "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/batches/log" "github.com/sourcegraph/src-cli/internal/batches/util" @@ -417,11 +415,7 @@ func probeImageForShell(ctx context.Context, image string) (shell, tempfile stri // same time by trying to run /bin/bash -c mktemp, // followed by /bin/sh -c mktemp. - // We'll also set up our error. - err = new(multierror.Error) - - // Now we can iterate through our shell options and try to run mktemp with - // them. + // We can iterate through our shell options and try to run mktemp with them. for _, shell = range []string{"/bin/bash", "/bin/sh"} { stdout := new(bytes.Buffer) stderr := new(bytes.Buffer) @@ -433,7 +427,7 @@ func probeImageForShell(ctx context.Context, image string) (shell, tempfile stri cmd.Stderr = stderr if runErr := cmd.Run(); runErr != nil { - err = multierror.Append(err, errors.Wrapf(runErr, "probing shell %q:\n%s", shell, stderr.String())) + err = errors.Append(err, errors.Wrapf(runErr, "probing shell %q:\n%s", shell, stderr.String())) } else { // Even if there were previous errors, we can now ignore them. err = nil diff --git a/internal/batches/features.go b/internal/batches/features.go index 723dde2d82..b0d1ff2156 100644 --- a/internal/batches/features.go +++ b/internal/batches/features.go @@ -1,7 +1,7 @@ package batches import ( - "github.com/cockroachdb/errors" + "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/api" ) diff --git a/internal/batches/log/manager.go b/internal/batches/log/manager.go index 3f21de76d4..5868c30bdb 100644 --- a/internal/batches/log/manager.go +++ b/internal/batches/log/manager.go @@ -3,7 +3,7 @@ package log import ( "sync" - "github.com/hashicorp/go-multierror" + "github.com/sourcegraph/sourcegraph/lib/errors" ) type LogManager interface { @@ -36,13 +36,13 @@ func (lm *Manager) AddTask(slug string) (TaskLogger, error) { } func (lm *Manager) Close() error { - var errs *multierror.Error + var errs errors.MultiError lm.tasks.Range(func(_, v interface{}) bool { logger := v.(*FileTaskLogger) if err := logger.Close(); err != nil { - errs = multierror.Append(errs, err) + errs = errors.Append(errs, err) } return true diff --git a/internal/batches/log/task_logger.go b/internal/batches/log/task_logger.go index a05b260038..41c1daa3e2 100644 --- a/internal/batches/log/task_logger.go +++ b/internal/batches/log/task_logger.go @@ -7,7 +7,7 @@ import ( "os" "time" - "github.com/cockroachdb/errors" + "github.com/sourcegraph/sourcegraph/lib/errors" ) type TaskLogger interface { diff --git a/internal/batches/repozip/fetcher.go b/internal/batches/repozip/fetcher.go index 0e4f5de18e..85b780b062 100644 --- a/internal/batches/repozip/fetcher.go +++ b/internal/batches/repozip/fetcher.go @@ -11,7 +11,7 @@ import ( "strings" "sync" - "github.com/cockroachdb/errors" + "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/batches/util" ) diff --git a/internal/batches/service/remote.go b/internal/batches/service/remote.go index 61f5957fb7..6d4298eb66 100644 --- a/internal/batches/service/remote.go +++ b/internal/batches/service/remote.go @@ -3,7 +3,7 @@ package service import ( "context" - "github.com/cockroachdb/errors" + "github.com/sourcegraph/sourcegraph/lib/errors" ) var ErrServerSideBatchChangesUnsupported = errors.New("server side batch changes are not available on this Sourcegraph instance") diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index 815a76b8cc..f89245e55b 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -13,12 +13,10 @@ import ( "github.com/grafana/regexp" - "github.com/cockroachdb/errors" - "github.com/hashicorp/go-multierror" - batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" onlib "github.com/sourcegraph/sourcegraph/lib/batches/on" templatelib "github.com/sourcegraph/sourcegraph/lib/batches/template" + "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/batches" @@ -298,7 +296,7 @@ func (svc *Service) CreateImportChangesetSpecs(ctx context.Context, batchSpec *b repo, err := svc.resolveRepositoryName(ctx, name) if err != nil { wrapped := errors.Wrapf(err, "resolving repository name %q", name) - errs = multierror.Append(errs, wrapped) + errs = errors.Append(errs, wrapped) continue } repoNameIDs[name] = repo.ID diff --git a/internal/batches/service/service_test.go b/internal/batches/service/service_test.go index e21d611b52..d6be4e14b7 100644 --- a/internal/batches/service/service_test.go +++ b/internal/batches/service/service_test.go @@ -10,9 +10,9 @@ import ( "strings" "testing" - "github.com/cockroachdb/errors" "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" + "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/stretchr/testify/assert" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" diff --git a/internal/batches/service/workspaces.go b/internal/batches/service/workspaces.go index d159f80169..f8c73b1181 100644 --- a/internal/batches/service/workspaces.go +++ b/internal/batches/service/workspaces.go @@ -4,10 +4,10 @@ import ( "context" "sort" - "github.com/cockroachdb/errors" "github.com/gobwas/glob" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/template" + "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/batches/graphql" "github.com/sourcegraph/src-cli/internal/batches/util" diff --git a/internal/batches/ui/tui.go b/internal/batches/ui/tui.go index aa4c660910..2b001d893b 100644 --- a/internal/batches/ui/tui.go +++ b/internal/batches/ui/tui.go @@ -5,9 +5,8 @@ import ( "fmt" "os/exec" - "github.com/cockroachdb/errors" - "github.com/hashicorp/go-multierror" "github.com/neelance/parallel" + "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/sourcegraph/lib/output" "github.com/sourcegraph/src-cli/internal/api" @@ -46,9 +45,9 @@ func (ui *TUI) ParsingBatchSpecFailure(err error) { block := ui.Out.Block(output.Line("\u274c", output.StyleWarning, "Batch spec failed validation.")) defer block.Close() - var multiErr *multierror.Error + var multiErr errors.MultiError if errors.As(err, &multiErr) { - for i, err := range multiErr.Errors { + for i, err := range multiErr.Errors() { block.Writef("%d. %s", i+1, err) } } else { @@ -338,7 +337,7 @@ func printExecutionError(out *output.Output, err error) { } switch err := err.(type) { - case parallel.Errors, *multierror.Error, api.GraphQlErrors: + case parallel.Errors, errors.MultiError, api.GraphQlErrors: writeErrs(flattenErrs(err)) default: @@ -359,8 +358,8 @@ func flattenErrs(err error) (result []error) { result = append(result, flattenErrs(e)...) } - case *multierror.Error: - for _, e := range errs.Errors { + case errors.MultiError: + for _, e := range errs.Errors() { result = append(result, flattenErrs(e)...) } diff --git a/internal/batches/workspace/bind_workspace.go b/internal/batches/workspace/bind_workspace.go index 2d1e71a92f..9792bdd8e9 100644 --- a/internal/batches/workspace/bind_workspace.go +++ b/internal/batches/workspace/bind_workspace.go @@ -10,10 +10,9 @@ import ( "path/filepath" "strings" - "github.com/cockroachdb/errors" - "github.com/hashicorp/go-multierror" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/git" + "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/batches/graphql" "github.com/sourcegraph/src-cli/internal/batches/repozip" @@ -325,7 +324,7 @@ func mkdirAll(base, path string, perm os.FileMode) error { // ensureAll ensures that all directories under path have the expected // permissions. func ensureAll(base, path string, perm os.FileMode) error { - var errs *multierror.Error + var errs errors.MultiError // In plain English: for each directory in the path parameter, we should // chmod that path to the permissions that are expected. @@ -333,9 +332,9 @@ func ensureAll(base, path string, perm os.FileMode) error { for _, element := range strings.Split(path, string(os.PathSeparator)) { acc = append(acc, element) if err := os.Chmod(filepath.Join(acc...), perm); err != nil { - errs = multierror.Append(errs, err) + errs = errors.Append(errs, err) } } - return errs.ErrorOrNil() + return errs } diff --git a/internal/batches/workspace/bind_workspace_nonwin_test.go b/internal/batches/workspace/bind_workspace_nonwin_test.go index 1be28755e6..2636d4ba15 100644 --- a/internal/batches/workspace/bind_workspace_nonwin_test.go +++ b/internal/batches/workspace/bind_workspace_nonwin_test.go @@ -8,7 +8,7 @@ import ( "path/filepath" "testing" - "github.com/cockroachdb/errors" + "github.com/sourcegraph/sourcegraph/lib/errors" ) func TestMkdirAllStatError(t *testing.T) { diff --git a/internal/batches/workspace/bind_workspace_windows_test.go b/internal/batches/workspace/bind_workspace_windows_test.go index f8b0069962..af21c38f99 100644 --- a/internal/batches/workspace/bind_workspace_windows_test.go +++ b/internal/batches/workspace/bind_workspace_windows_test.go @@ -4,7 +4,7 @@ import ( "os" "testing" - "github.com/cockroachdb/errors" + "github.com/sourcegraph/sourcegraph/lib/errors" ) func mustHavePerm(t *testing.T, path string, want os.FileMode) error { diff --git a/internal/batches/workspace/git.go b/internal/batches/workspace/git.go index d93834c998..fa81c1fff4 100644 --- a/internal/batches/workspace/git.go +++ b/internal/batches/workspace/git.go @@ -5,7 +5,7 @@ import ( "os/exec" "strings" - "github.com/cockroachdb/errors" + "github.com/sourcegraph/sourcegraph/lib/errors" ) func runGitCmd(ctx context.Context, dir string, args ...string) ([]byte, error) { diff --git a/internal/batches/workspace/volume_workspace.go b/internal/batches/workspace/volume_workspace.go index a189d58671..5a05b21cf2 100644 --- a/internal/batches/workspace/volume_workspace.go +++ b/internal/batches/workspace/volume_workspace.go @@ -10,7 +10,7 @@ import ( "sort" "strings" - "github.com/cockroachdb/errors" + "github.com/sourcegraph/sourcegraph/lib/errors" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/git" diff --git a/internal/batches/workspace/volume_workspace_test.go b/internal/batches/workspace/volume_workspace_test.go index 8ac6af42e3..21dbb653ce 100644 --- a/internal/batches/workspace/volume_workspace_test.go +++ b/internal/batches/workspace/volume_workspace_test.go @@ -8,8 +8,8 @@ import ( "strings" "testing" - "github.com/cockroachdb/errors" "github.com/google/go-cmp/cmp" + "github.com/sourcegraph/sourcegraph/lib/errors" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/git" diff --git a/internal/batches/workspace/workspace.go b/internal/batches/workspace/workspace.go index 0fb25c9054..b69e370938 100644 --- a/internal/batches/workspace/workspace.go +++ b/internal/batches/workspace/workspace.go @@ -4,9 +4,9 @@ import ( "context" "runtime" - "github.com/cockroachdb/errors" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/git" + "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/batches/docker" "github.com/sourcegraph/src-cli/internal/batches/graphql" diff --git a/internal/batches/workspace/workspace_test.go b/internal/batches/workspace/workspace_test.go index ecd6801b50..088d7c82bf 100644 --- a/internal/batches/workspace/workspace_test.go +++ b/internal/batches/workspace/workspace_test.go @@ -5,7 +5,7 @@ import ( "runtime" "testing" - "github.com/cockroachdb/errors" + "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/batches/docker" "github.com/sourcegraph/src-cli/internal/batches/mock" diff --git a/internal/cmderrors/errors.go b/internal/cmderrors/errors.go index 44dbbf385a..ded5a7e778 100644 --- a/internal/cmderrors/errors.go +++ b/internal/cmderrors/errors.go @@ -3,7 +3,7 @@ package cmderrors import ( "fmt" - "github.com/cockroachdb/errors" + "github.com/sourcegraph/sourcegraph/lib/errors" ) // UsageError is an error type that subcommands can return in order to signal diff --git a/internal/exec/expect/expect.go b/internal/exec/expect/expect.go index 82e2e044c0..bcd04477fe 100644 --- a/internal/exec/expect/expect.go +++ b/internal/exec/expect/expect.go @@ -23,10 +23,9 @@ import ( goexec "os/exec" "testing" - "github.com/cockroachdb/errors" "github.com/gobwas/glob" "github.com/google/go-cmp/cmp" - "github.com/hashicorp/go-multierror" + "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/exec" ) @@ -194,22 +193,22 @@ func NewGlobValidator(wantName string, wantArg ...string) CommandValidator { } return func(haveName string, haveArg ...string) error { - var errs *multierror.Error + var errs errors.MultiError if !wantNameGlob.Match(haveName) { - errs = multierror.Append(errs, errors.Errorf("name does not match: have=%q want=%q", haveName, wantName)) + errs = errors.Append(errs, errors.Errorf("name does not match: have=%q want=%q", haveName, wantName)) } if len(haveArg) != len(wantArgGlobs) { - errs = multierror.Append(errs, errors.Errorf("unexpected number of arguments:\nhave=%v\nwant=%v", haveArg, wantArg)) + errs = errors.Append(errs, errors.Errorf("unexpected number of arguments:\nhave=%v\nwant=%v", haveArg, wantArg)) } else { for i, g := range wantArgGlobs { if !g.Match(haveArg[i]) { - errs = multierror.Append(errs, errors.Errorf("unexpected argument at position %d:\nhave=%q\nwant=%q\ndiff=%q", i, haveArg[i], wantArg[i], cmp.Diff(haveArg[i], wantArg[i]))) + errs = errors.Append(errs, errors.Errorf("unexpected argument at position %d:\nhave=%q\nwant=%q\ndiff=%q", i, haveArg[i], wantArg[i], cmp.Diff(haveArg[i], wantArg[i]))) } } } - return errs.ErrorOrNil() + return errs } } diff --git a/internal/servegit/serve.go b/internal/servegit/serve.go index f1e5f4820c..de5b9d17c0 100644 --- a/internal/servegit/serve.go +++ b/internal/servegit/serve.go @@ -14,7 +14,7 @@ import ( "strings" "time" - "github.com/cockroachdb/errors" + "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/sourcegraph/lib/gitservice" ) diff --git a/internal/streaming/writer.go b/internal/streaming/writer.go index 03a4e592d3..ea4b4d540a 100644 --- a/internal/streaming/writer.go +++ b/internal/streaming/writer.go @@ -6,7 +6,7 @@ import ( "net/http" "time" - "github.com/cockroachdb/errors" + "github.com/sourcegraph/sourcegraph/lib/errors" ) type WriterStat struct { From da111edf06332698519160c4d93be3a506408111 Mon Sep 17 00:00:00 2001 From: Robert Lin Date: Thu, 24 Feb 2022 04:13:17 -0800 Subject: [PATCH 137/647] workflows: add pr-auditor and test plans to PR templates (#700) Co-authored-by: Sourcegraph --- .github/PULL_REQUEST_TEMPLATE.md | 9 +++++++++ .github/workflows/pr-auditor.yml | 19 +++++++++++++++++++ 2 files changed, 28 insertions(+) create mode 100644 .github/PULL_REQUEST_TEMPLATE.md create mode 100644 .github/workflows/pr-auditor.yml diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000000..a47c1642f4 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,9 @@ +### Test plan + + diff --git a/.github/workflows/pr-auditor.yml b/.github/workflows/pr-auditor.yml new file mode 100644 index 0000000000..3edc2741bb --- /dev/null +++ b/.github/workflows/pr-auditor.yml @@ -0,0 +1,19 @@ +name: pr-auditor +on: + pull_request: + types: [ closed, edited, opened ] + +jobs: + run: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + with: { repository: 'sourcegraph/sourcegraph' } + - uses: actions/setup-go@v2 + with: { go-version: '1.17' } + + - run: ./dev/pr-auditor/check-pr.sh + env: + GITHUB_EVENT_PATH: ${{ env.GITHUB_EVENT_PATH }} + GITHUB_TOKEN: ${{ secrets.CODENOTIFY_GITHUB_TOKEN }} + GITHUB_RUN_URL: https://github.com/sourcegraph/infrastructure/actions/runs/${{ github.run_id }} From 7e7c09f6543ae3ecd67f399202974ff7aef6515f Mon Sep 17 00:00:00 2001 From: Eng Zer Jun Date: Thu, 3 Mar 2022 07:36:31 +0800 Subject: [PATCH 138/647] test: use `T.TempDir` to create temporary test directory (#701) The directory created by `T.TempDir` is automatically removed when the test and all its subtests complete. Reference: https://pkg.go.dev/testing#T.TempDir Signed-off-by: Eng Zer Jun --- cmd/src/main_test.go | 6 +--- .../batches/executor/execution_cache_test.go | 13 +------- internal/batches/executor/executor_test.go | 12 ++----- internal/batches/repozip/fetcher_test.go | 20 +++--------- .../workspace/bind_workspace_nonwin_test.go | 8 +++-- .../batches/workspace/bind_workspace_test.go | 31 +++++-------------- internal/servegit/serve_test.go | 30 +++--------------- 7 files changed, 28 insertions(+), 92 deletions(-) diff --git a/cmd/src/main_test.go b/cmd/src/main_test.go index 813ff220f1..dc05e62030 100644 --- a/cmd/src/main_test.go +++ b/cmd/src/main_test.go @@ -153,12 +153,8 @@ func TestReadConfig(t *testing.T) { setEnv("SRC_ACCESS_TOKEN", test.envToken) setEnv("SRC_ENDPOINT", test.envEndpoint) - tmpDir, err := os.MkdirTemp("", "") - if err != nil { - t.Fatal(err) - } + tmpDir := t.TempDir() testHomeDir = tmpDir - t.Cleanup(func() { os.RemoveAll(tmpDir) }) if test.flagEndpoint != "" { val := test.flagEndpoint diff --git a/internal/batches/executor/execution_cache_test.go b/internal/batches/executor/execution_cache_test.go index e90e179776..fa6d29cf41 100644 --- a/internal/batches/executor/execution_cache_test.go +++ b/internal/batches/executor/execution_cache_test.go @@ -2,7 +2,6 @@ package executor import ( "context" - "os" "testing" "github.com/google/go-cmp/cmp" @@ -44,16 +43,6 @@ index 0000000..3363c39 func TestExecutionDiskCache_GetSet(t *testing.T) { ctx := context.Background() - cacheTmpDir := func(t *testing.T) string { - testTempDir, err := os.MkdirTemp("", "execution-disk-cache-test-*") - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { os.Remove(testTempDir) }) - - return testTempDir - } - cacheKey1 := &cache.ExecutionKey{ Repository: cacheRepo1, Steps: []batcheslib.Step{ @@ -76,7 +65,7 @@ func TestExecutionDiskCache_GetSet(t *testing.T) { Outputs: map[string]interface{}{}, } - cache := ExecutionDiskCache{Dir: cacheTmpDir(t)} + cache := ExecutionDiskCache{Dir: t.TempDir()} // Empty cache, no hits assertCacheMiss(t, cache, cacheKey1) diff --git a/internal/batches/executor/executor_test.go b/internal/batches/executor/executor_test.go index 33cff82f85..37cff66d4d 100644 --- a/internal/batches/executor/executor_test.go +++ b/internal/batches/executor/executor_test.go @@ -335,11 +335,7 @@ func TestExecutor_Integration(t *testing.T) { client := api.NewClient(api.ClientOpts{Endpoint: ts.URL, Out: &clientBuffer}) // Temp dir for log files and downloaded archives - testTempDir, err := os.MkdirTemp("", "executor-integration-test-*") - if err != nil { - t.Fatal(err) - } - defer os.Remove(testTempDir) + testTempDir := t.TempDir() // Setup executor opts := newExecutorOpts{ @@ -667,11 +663,7 @@ func testExecuteTasks(t *testing.T, tasks []*Task, archives ...mock.RepoArchive) t.Skip("Test doesn't work on Windows because dummydocker is written in bash") } - testTempDir, err := os.MkdirTemp("", "executor-integration-test-*") - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { os.Remove(testTempDir) }) + testTempDir := t.TempDir() // Setup dummydocker addToPath(t, "testdata/dummydocker") diff --git a/internal/batches/repozip/fetcher_test.go b/internal/batches/repozip/fetcher_test.go index 3e778d3f4a..f871237e45 100644 --- a/internal/batches/repozip/fetcher_test.go +++ b/internal/batches/repozip/fetcher_test.go @@ -21,16 +21,6 @@ import ( ) func TestArchive_Ensure(t *testing.T) { - workspaceTmpDir := func(t *testing.T) string { - testTempDir, err := os.MkdirTemp("", "executor-integration-test-*") - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { os.Remove(testTempDir) }) - - return testTempDir - } - repo := RepoRevision{ RepoName: "github.com/sourcegraph/src-cli", Commit: "d34db33f", @@ -58,7 +48,7 @@ func TestArchive_Ensure(t *testing.T) { rf := &archiveRegistry{ client: client, - dir: workspaceTmpDir(t), + dir: t.TempDir(), deleteZips: false, } @@ -103,7 +93,7 @@ func TestArchive_Ensure(t *testing.T) { rf := &archiveRegistry{ client: client, - dir: workspaceTmpDir(t), + dir: t.TempDir(), deleteZips: true, } @@ -167,7 +157,7 @@ func TestArchive_Ensure(t *testing.T) { rf := &archiveRegistry{ client: client, - dir: workspaceTmpDir(t), + dir: t.TempDir(), deleteZips: false, } @@ -207,7 +197,7 @@ func TestArchive_Ensure(t *testing.T) { rf := &archiveRegistry{ client: client, - dir: workspaceTmpDir(t), + dir: t.TempDir(), deleteZips: false, } zip := rf.Checkout(repo, "") @@ -276,7 +266,7 @@ func TestArchive_Ensure(t *testing.T) { rf := &archiveRegistry{ client: client, - dir: workspaceTmpDir(t), + dir: t.TempDir(), deleteZips: false, } zip := rf.Checkout(repo, path) diff --git a/internal/batches/workspace/bind_workspace_nonwin_test.go b/internal/batches/workspace/bind_workspace_nonwin_test.go index 2636d4ba15..2943dcd598 100644 --- a/internal/batches/workspace/bind_workspace_nonwin_test.go +++ b/internal/batches/workspace/bind_workspace_nonwin_test.go @@ -17,7 +17,6 @@ func TestMkdirAllStatError(t *testing.T) { // Create a shared workspace. base := mustCreateWorkspace(t) - defer os.RemoveAll(base) // We'll create a directory and a file within it, remove the execute bit on // the directory, and then stat() the file to cause a failure. @@ -34,6 +33,12 @@ func TestMkdirAllStatError(t *testing.T) { if err := os.Chmod(filepath.Join(base, "locked"), 0600); err != nil { t.Fatal(err) } + // Add the execute bit back to the directory so "base" can be cleaned up + t.Cleanup(func() { + if err := os.Chmod(filepath.Join(base, "locked"), 0700); err != nil { + t.Fatal(err) + } + }) err = mkdirAll(base, "locked/file", 0750) if err == nil { @@ -41,7 +46,6 @@ func TestMkdirAllStatError(t *testing.T) { } else if _, ok := err.(errPathExistsAsFile); ok { t.Errorf("unexpected error of type %T: %v", err, err) } - } func mustHavePerm(t *testing.T, path string, want os.FileMode) error { diff --git a/internal/batches/workspace/bind_workspace_test.go b/internal/batches/workspace/bind_workspace_test.go index ed64664edc..3a6ab3fd8d 100644 --- a/internal/batches/workspace/bind_workspace_test.go +++ b/internal/batches/workspace/bind_workspace_test.go @@ -44,19 +44,9 @@ func zipUpFiles(t *testing.T, dir string, files map[string]string) string { return archivePath } -func workspaceTmpDir(t *testing.T) string { - testTempDir, err := os.MkdirTemp("", "bind-workspace-test-*") - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { os.Remove(testTempDir) }) - - return testTempDir -} - func TestDockerBindWorkspaceCreator_Create(t *testing.T) { // Create a zip file for all the other tests to use. - fakeFilesTmpDir := workspaceTmpDir(t) + fakeFilesTmpDir := t.TempDir() filesInZip := map[string]string{ "README.md": "# Welcome to the README\n", } @@ -85,7 +75,7 @@ func TestDockerBindWorkspaceCreator_Create(t *testing.T) { } t.Run("success", func(t *testing.T) { - testTempDir := workspaceTmpDir(t) + testTempDir := t.TempDir() archive := &fakeRepoArchive{mockPath: archivePath} creator := &dockerBindWorkspaceCreator{Dir: testTempDir} @@ -105,7 +95,7 @@ func TestDockerBindWorkspaceCreator_Create(t *testing.T) { }) t.Run("failure", func(t *testing.T) { - testTempDir := workspaceTmpDir(t) + testTempDir := t.TempDir() // Create an empty file (which is therefore a bad zip file). badZip, err := os.CreateTemp(testTempDir, "bad-zip-*") @@ -125,7 +115,7 @@ func TestDockerBindWorkspaceCreator_Create(t *testing.T) { }) t.Run("additional files", func(t *testing.T) { - testTempDir := workspaceTmpDir(t) + testTempDir := t.TempDir() archive := &fakeRepoArchive{ mockPath: archivePath, @@ -158,7 +148,7 @@ func TestDockerBindWorkspaceCreator_Create(t *testing.T) { func TestDockerBindWorkspace_ApplyDiff(t *testing.T) { // Create a zip file for all the other tests to use. - fakeFilesTmpDir := workspaceTmpDir(t) + fakeFilesTmpDir := t.TempDir() filesInZip := map[string]string{ "README.md": "# Welcome to the README\n", } @@ -187,7 +177,7 @@ index 0000000..7bb2542 "README.md": "# Welcome to the README\n\nThis is a new line\n", "new-file.txt": "check this out. this is a new file.\nwritten on a computer. what a blast.\n", } - testTempDir := workspaceTmpDir(t) + testTempDir := t.TempDir() archive := &fakeRepoArchive{mockPath: archivePath} creator := &dockerBindWorkspaceCreator{Dir: testTempDir} @@ -214,7 +204,7 @@ index 0000000..7bb2542 t.Run("failure", func(t *testing.T) { diff := `lol this is not a diff but the computer doesn't know it yet, watch` - testTempDir := workspaceTmpDir(t) + testTempDir := t.TempDir() archive := &fakeRepoArchive{mockPath: archivePath} creator := &dockerBindWorkspaceCreator{Dir: testTempDir} @@ -236,7 +226,6 @@ func TestMkdirAll(t *testing.T) { // Create a shared workspace. base := mustCreateWorkspace(t) - defer os.RemoveAll(base) t.Run("directory exists", func(t *testing.T) { if err := os.MkdirAll(filepath.Join(base, "exist"), 0755); err != nil { @@ -287,7 +276,6 @@ func TestMkdirAll(t *testing.T) { func TestEnsureAll(t *testing.T) { // Create a workspace. base := mustCreateWorkspace(t) - defer os.RemoveAll(base) // Create three nested directories with 0700 permissions. We'll use Chmod // explicitly to avoid any umask issues. @@ -326,10 +314,7 @@ func TestEnsureAll(t *testing.T) { } func mustCreateWorkspace(t *testing.T) string { - base, err := os.MkdirTemp("", "") - if err != nil { - t.Fatal(err) - } + base := t.TempDir() // We'll explicitly set the base workspace to 0700 so we have a known // environment for testing. diff --git a/internal/servegit/serve_test.go b/internal/servegit/serve_test.go index 0d92dcebc7..df80603666 100644 --- a/internal/servegit/serve_test.go +++ b/internal/servegit/serve_test.go @@ -87,11 +87,7 @@ func TestReposHandler(t *testing.T) { // This is the difference, we create a symlink for root { - tmp, err := os.MkdirTemp("", "") - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { os.RemoveAll(tmp) }) + tmp := t.TempDir() symlink := filepath.Join(tmp, "symlink-root") if err := os.Symlink(root, symlink); err != nil { @@ -178,11 +174,7 @@ func gitInitBare(t *testing.T, path string) { } func gitInitRepos(t *testing.T, names ...string) string { - root, err := os.MkdirTemp("", "") - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { os.RemoveAll(root) }) + root := t.TempDir() root = filepath.Join(root, "repos-root") for _, name := range names { @@ -201,11 +193,7 @@ func gitInitRepos(t *testing.T, names ...string) string { } func TestIgnoreGitSubmodules(t *testing.T) { - root, err := os.MkdirTemp("", "") - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { os.RemoveAll(root) }) + root := t.TempDir() if err := os.MkdirAll(filepath.Join(root, "dir"), os.ModePerm); err != nil { t.Fatal(err) @@ -229,11 +217,7 @@ func TestIgnoreGitSubmodules(t *testing.T) { } func TestIsBareRepo(t *testing.T) { - dir, err := os.MkdirTemp("", "") - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { os.RemoveAll(dir) }) + dir := t.TempDir() gitInitBare(t, dir) @@ -243,11 +227,7 @@ func TestIsBareRepo(t *testing.T) { } func TestEmptyDirIsNotBareRepo(t *testing.T) { - dir, err := os.MkdirTemp("", "") - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { os.RemoveAll(dir) }) + dir := t.TempDir() if isBareRepo(dir) { t.Errorf("Path %s it falsey detected as a bare repository", dir) From ee14bba8156c393eb2754145d66e79b030759ff7 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 2 Mar 2022 15:40:55 -0800 Subject: [PATCH 139/647] Update actions/checkout action to v3 (#704) Co-authored-by: Renovate Bot --- .github/workflows/docker.yml | 2 +- .github/workflows/go-ci.yml | 2 +- .github/workflows/go-lint.yml | 2 +- .github/workflows/goreleaser-check.yml | 2 +- .github/workflows/goreleaser.yml | 2 +- .github/workflows/lsif.yml | 2 +- .github/workflows/pr-auditor.yml | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index e7338c4eb6..a729e36a94 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -15,7 +15,7 @@ jobs: runs-on: ubuntu-20.04 steps: - name: Checkout - uses: actions/checkout@v2 + uses: actions/checkout@v3 # We need buildx to be able to build a multi-architecture image. - name: Set up Docker buildx diff --git a/.github/workflows/go-ci.yml b/.github/workflows/go-ci.yml index 64ecc212e4..2c6eda0b69 100644 --- a/.github/workflows/go-ci.yml +++ b/.github/workflows/go-ci.yml @@ -12,7 +12,7 @@ jobs: runs-on: ${{ matrix.os }} steps: - name: Checkout - uses: actions/checkout@v2 + uses: actions/checkout@v3 - name: Set up Go uses: actions/setup-go@v2 with: diff --git a/.github/workflows/go-lint.yml b/.github/workflows/go-lint.yml index 63ae30544a..ef9dfe39ef 100644 --- a/.github/workflows/go-lint.yml +++ b/.github/workflows/go-lint.yml @@ -8,7 +8,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v2 + uses: actions/checkout@v3 - name: Set up Go uses: actions/setup-go@v2 with: diff --git a/.github/workflows/goreleaser-check.yml b/.github/workflows/goreleaser-check.yml index 676f25c84f..9022915f25 100644 --- a/.github/workflows/goreleaser-check.yml +++ b/.github/workflows/goreleaser-check.yml @@ -9,7 +9,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v2 + uses: actions/checkout@v3 with: fetch-depth: 0 - name: Set up Go diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index b12e1d662f..3cf6739266 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -12,7 +12,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v2 + uses: actions/checkout@v3 with: fetch-depth: 0 - name: Set up Go diff --git a/.github/workflows/lsif.yml b/.github/workflows/lsif.yml index 695b268a5c..62db1f0b9d 100644 --- a/.github/workflows/lsif.yml +++ b/.github/workflows/lsif.yml @@ -6,7 +6,7 @@ jobs: runs-on: ubuntu-latest container: sourcegraph/lsif-go steps: - - uses: actions/checkout@1e204e9a9253d643386038d443f96446fa156a97 # renovate: tag=v2 + - uses: actions/checkout@a12a3943b4bdde767164f792f33f40b04645d846 # tag=v3 - name: Generate LSIF data run: lsif-go - name: Upload LSIF data diff --git a/.github/workflows/pr-auditor.yml b/.github/workflows/pr-auditor.yml index 3edc2741bb..d03def8581 100644 --- a/.github/workflows/pr-auditor.yml +++ b/.github/workflows/pr-auditor.yml @@ -7,7 +7,7 @@ jobs: run: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 with: { repository: 'sourcegraph/sourcegraph' } - uses: actions/setup-go@v2 with: { go-version: '1.17' } From b9b7cfa55b2ed8c3fc254fb25f0e7eb1e257d1fc Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 2 Mar 2022 15:41:17 -0800 Subject: [PATCH 140/647] Update actions/setup-go action to v3 (#703) Co-authored-by: Renovate Bot --- .github/workflows/go-ci.yml | 2 +- .github/workflows/go-lint.yml | 2 +- .github/workflows/goreleaser-check.yml | 2 +- .github/workflows/goreleaser.yml | 2 +- .github/workflows/pr-auditor.yml | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/go-ci.yml b/.github/workflows/go-ci.yml index 2c6eda0b69..29b606f2cf 100644 --- a/.github/workflows/go-ci.yml +++ b/.github/workflows/go-ci.yml @@ -14,7 +14,7 @@ jobs: - name: Checkout uses: actions/checkout@v3 - name: Set up Go - uses: actions/setup-go@v2 + uses: actions/setup-go@v3 with: go-version: ${{ matrix.go-version }} - run: go test -i ./... diff --git a/.github/workflows/go-lint.yml b/.github/workflows/go-lint.yml index ef9dfe39ef..80535db3a0 100644 --- a/.github/workflows/go-lint.yml +++ b/.github/workflows/go-lint.yml @@ -10,7 +10,7 @@ jobs: - name: Checkout uses: actions/checkout@v3 - name: Set up Go - uses: actions/setup-go@v2 + uses: actions/setup-go@v3 with: go-version: 1.17.x - run: ./dev/go-lint.sh diff --git a/.github/workflows/goreleaser-check.yml b/.github/workflows/goreleaser-check.yml index 9022915f25..b91c85159c 100644 --- a/.github/workflows/goreleaser-check.yml +++ b/.github/workflows/goreleaser-check.yml @@ -13,7 +13,7 @@ jobs: with: fetch-depth: 0 - name: Set up Go - uses: actions/setup-go@v2 + uses: actions/setup-go@v3 with: go-version: 1.17 - name: Check GoReleaser config diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index 3cf6739266..068ff9e139 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -16,7 +16,7 @@ jobs: with: fetch-depth: 0 - name: Set up Go - uses: actions/setup-go@v2 + uses: actions/setup-go@v3 with: go-version: 1.17 - run: go get -d -t ./... diff --git a/.github/workflows/pr-auditor.yml b/.github/workflows/pr-auditor.yml index d03def8581..a94f500339 100644 --- a/.github/workflows/pr-auditor.yml +++ b/.github/workflows/pr-auditor.yml @@ -9,7 +9,7 @@ jobs: steps: - uses: actions/checkout@v3 with: { repository: 'sourcegraph/sourcegraph' } - - uses: actions/setup-go@v2 + - uses: actions/setup-go@v3 with: { go-version: '1.17' } - run: ./dev/pr-auditor/check-pr.sh From 49bb6b8e79b9b22cf7a849f1aa9f8f7a3f55a653 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 2 Mar 2022 15:45:27 -0800 Subject: [PATCH 141/647] Update alpine Docker tag to v3.15.0 (#670) Co-authored-by: Renovate Bot --- docker/batch-change-volume-workspace/Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docker/batch-change-volume-workspace/Dockerfile b/docker/batch-change-volume-workspace/Dockerfile index 99abd7cb7f..0dc4340f64 100644 --- a/docker/batch-change-volume-workspace/Dockerfile +++ b/docker/batch-change-volume-workspace/Dockerfile @@ -2,6 +2,6 @@ # image that we use to run curl, git, and unzip against a Docker volume when # using the volume workspace. -FROM alpine:3.14.2@sha256:e1c082e3d3c45cccac829840a25941e679c25d438cc8412c2fa221cf1a824e6a +FROM alpine:3.15.0@sha256:21a3deaa0d32a8057914f36584b5288d2e5ecc984380bc0118285c70fa8c9300 RUN apk add --update git unzip From 52a5479832d549501eda5affd02b22c4e1f8b4cd Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 2 Mar 2022 15:47:23 -0800 Subject: [PATCH 142/647] Update golang commit hash to d030a98 (#702) Co-authored-by: Renovate Bot --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index e71d2492f9..bd540f3383 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,7 +4,7 @@ # # Nothing fancy here: we copy in the source code and build on the Alpine Go # image. Refer to .dockerignore to get a sense of what we're not going to copy. -FROM golang:1.17-alpine@sha256:102bca942e79a30dd6e9060f780ec3bd224eba2cf6245eadf3411c4699253d50 as builder +FROM golang:1.17-alpine@sha256:d030a987c28ca403007a69af28ba419fca00fc15f08e7801fc8edee77c00b8ee as builder COPY . /src WORKDIR /src From 943ca65f72fffc648995772807df02dc2d91ce72 Mon Sep 17 00:00:00 2001 From: Adam Harvey Date: Wed, 2 Mar 2022 17:09:42 -0800 Subject: [PATCH 143/647] batches: fix workspace detection test on M1 Macs (#706) --- internal/batches/workspace/workspace_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/batches/workspace/workspace_test.go b/internal/batches/workspace/workspace_test.go index 088d7c82bf..5a6c5dedb8 100644 --- a/internal/batches/workspace/workspace_test.go +++ b/internal/batches/workspace/workspace_test.go @@ -13,7 +13,7 @@ import ( func TestBestWorkspaceCreator(t *testing.T) { ctx := context.Background() - isOverridden := !(runtime.GOOS == "darwin" && runtime.GOARCH == "amd64") + isOverridden := !(runtime.GOOS == "darwin" && (runtime.GOARCH == "amd64" || runtime.GOARCH == "arm64")) uidGid := func(uid, gid int) docker.UIDGID { return docker.UIDGID{UID: uid, GID: gid} From 9387b190cdea463cd768da0119dd78212d4ac489 Mon Sep 17 00:00:00 2001 From: Bolaji Olajide <25608335+BolajiOlajide@users.noreply.github.com> Date: Thu, 10 Mar 2022 12:33:33 +0100 Subject: [PATCH 144/647] Cache step results while steps are executing instead of caching all of them at the end (#709) * feat: cache build steps individually * feat: add tests for individual step caching * chore: remove unused method * Update internal/batches/executor/coordinator.go Co-authored-by: Erik Seliger * Update internal/batches/executor/executor.go Co-authored-by: Erik Seliger * feat: update callback method in executor * feat: optimize writeToCache callback * chore: fix failing tests * Update internal/batches/executor/run_steps.go Co-authored-by: Kelli Rockwell * fix: resolve failing tests Co-authored-by: Erik Seliger Co-authored-by: Kelli Rockwell --- internal/batches/executor/coordinator.go | 29 ++++++++++------ internal/batches/executor/coordinator_test.go | 34 ++++--------------- internal/batches/executor/executor.go | 10 +++--- internal/batches/executor/executor_test.go | 34 ++++++++++++++++--- internal/batches/executor/run_steps.go | 8 +++++ 5 files changed, 68 insertions(+), 47 deletions(-) diff --git a/internal/batches/executor/coordinator.go b/internal/batches/executor/coordinator.go index 71176727e9..57af61d669 100644 --- a/internal/batches/executor/coordinator.go +++ b/internal/batches/executor/coordinator.go @@ -63,6 +63,8 @@ type NewCoordinatorOpts struct { func NewCoordinator(opts NewCoordinatorOpts) *Coordinator { logManager := log.NewManager(opts.TempDir, opts.KeepLogs) + globalEnv := os.Environ() + exec := newExecutor(newExecutorOpts{ RepoArchiveRegistry: opts.RepoArchiveRegistry, EnsureImage: opts.EnsureImage, @@ -72,6 +74,10 @@ func NewCoordinator(opts NewCoordinatorOpts) *Coordinator { Parallelism: opts.Parallelism, Timeout: opts.Timeout, TempDir: opts.TempDir, + WriteStepCacheResult: func(ctx context.Context, stepResult execution.AfterStepResult, task *Task) error { + cacheKey := task.cacheKey(globalEnv) + return writeToCache(ctx, opts.Cache, stepResult, task, cacheKey) + }, }) return &Coordinator{ @@ -221,7 +227,16 @@ func (c *Coordinator) loadCachedStepResults(ctx context.Context, task *Task, glo return nil } -func (c *Coordinator) writeCache(ctx context.Context, taskResult taskResult, ui TaskExecutionUI) error { +func writeToCache(ctx context.Context, cache cache.Cache, stepResult execution.AfterStepResult, task *Task, cacheKey *cache.ExecutionKeyWithGlobalEnv) error { + key := cacheKeyForStep(cacheKey, stepResult.StepIndex) + if err := cache.SetStepResult(ctx, key, stepResult); err != nil { + return errors.Wrapf(err, "caching result for step %d in %q", stepResult.StepIndex, task.Repository.Name) + } + + return nil +} + +func (c *Coordinator) writeExecutionCacheResult(ctx context.Context, taskResult taskResult, ui TaskExecutionUI) error { // Add to the cache, even if no diff was produced. globalEnv := os.Environ() cacheKey := taskResult.task.cacheKey(globalEnv) @@ -229,19 +244,11 @@ func (c *Coordinator) writeCache(ctx context.Context, taskResult taskResult, ui return errors.Wrapf(err, "caching result for %q", taskResult.task.Repository.Name) } - // Save the per-step results - for _, stepResult := range taskResult.stepResults { - key := cacheKeyForStep(cacheKey, stepResult.StepIndex) - if err := c.cache.SetStepResult(ctx, key, stepResult); err != nil { - return errors.Wrapf(err, "caching result for step %d in %q", stepResult.StepIndex, taskResult.task.Repository.Name) - } - } - return nil } func (c *Coordinator) writeCacheAndBuildSpecs(ctx context.Context, batchSpec *batcheslib.BatchSpec, taskResult taskResult, ui TaskExecutionUI) ([]*batcheslib.ChangesetSpec, error) { - c.writeCache(ctx, taskResult, ui) + c.writeExecutionCacheResult(ctx, taskResult, ui) // If the steps didn't result in any diff, we don't need to create a // changeset spec that's displayed to the user and send to the server. @@ -265,7 +272,7 @@ func (c *Coordinator) Execute(ctx context.Context, tasks []*Task, ui TaskExecuti // Write results to cache. for _, taskResult := range results { - if cacheErr := c.writeCache(ctx, taskResult, ui); cacheErr != nil { + if cacheErr := c.writeExecutionCacheResult(ctx, taskResult, ui); cacheErr != nil { return cacheErr } } diff --git a/internal/batches/executor/coordinator_test.go b/internal/batches/executor/coordinator_test.go index fbaf353c6c..c2d8af09f0 100644 --- a/internal/batches/executor/coordinator_test.go +++ b/internal/batches/executor/coordinator_test.go @@ -389,8 +389,8 @@ func TestCoordinator_Execute_StepCaching(t *testing.T) { execAndEnsure(t, coord, executor, batchSpec, task, assertNoCachedResult(t)) // We now expect the cache to have 1+N entries: 1 for the complete task, N // for the steps. - wantCacheSize := len(task.Steps) + 1 - assertCacheSize(t, cache, wantCacheSize) + + assertCacheSize(t, cache, 1) // Reset task task.CachedResultFound = false @@ -399,11 +399,10 @@ func TestCoordinator_Execute_StepCaching(t *testing.T) { task.Steps[1].Run = `echo "two modified"` // Re-execution should start with the diff produced by steps[0] as the // start state from which steps[1] is then re-executed. - execAndEnsure(t, coord, executor, batchSpec, task, assertCachedResultForStep(t, 0)) + execAndEnsure(t, coord, executor, batchSpec, task, assertNoCachedResult(t)) // Cache now contains old entries, plus another "complete task" entry and // two entries for newly executed steps. - wantCacheSize += 1 + 2 - assertCacheSize(t, cache, wantCacheSize) + assertCacheSize(t, cache, 2) // Reset task task.CachedResultFound = false @@ -411,11 +410,10 @@ func TestCoordinator_Execute_StepCaching(t *testing.T) { // Change the 3rd step's definition: task.Steps[2].Run = `echo "three modified"` // Re-execution should use the diff from steps[1] as start state - execAndEnsure(t, coord, executor, batchSpec, task, assertCachedResultForStep(t, 1)) + execAndEnsure(t, coord, executor, batchSpec, task, assertNoCachedResult(t)) // Cache now contains old entries, plus another "complete task" entry and // a single new step entry - wantCacheSize += 1 + 1 - assertCacheSize(t, cache, wantCacheSize) + assertCacheSize(t, cache, 3) // Reset task task.CachedResultFound = false @@ -429,7 +427,7 @@ func TestCoordinator_Execute_StepCaching(t *testing.T) { // Cache should have the same number of entries: the cached step results should // have been cleared (the complete-task-result is cleared in another // code path) and the same amount of cached entries has been added. - assertCacheSize(t, cache, wantCacheSize) + assertCacheSize(t, cache, 3) } // execAndEnsure executes the given Task with the given cache and dummyExecutor @@ -475,24 +473,6 @@ func assertCacheSize(t *testing.T, cache *inMemoryExecutionCache, want int) { } } -// assertCachedResultForStep returns a function that can be used as a -// startCallback on dummyExecutor to assert that the first Task has a cached -// result for the given step. -func assertCachedResultForStep(t *testing.T, step int) func(context.Context, []*Task, TaskExecutionUI) { - return func(c context.Context, tasks []*Task, ui TaskExecutionUI) { - t.Helper() - - task := tasks[0] - if !task.CachedResultFound { - t.Fatalf("CachedResultFound not set") - } - - if have, want := task.CachedResult.StepIndex, step; have != want { - t.Fatalf("CachedResult.Step wrong. have=%d, want=%d", have, want) - } - } -} - // expectCachedResultForStep returns a function that can be used as a // startCallback on dummyExecutor to assert that the first Task has no cached results. func assertNoCachedResult(t *testing.T) func(context.Context, []*Task, TaskExecutionUI) { diff --git a/internal/batches/executor/executor.go b/internal/batches/executor/executor.go index 311dfa7710..f41b584a76 100644 --- a/internal/batches/executor/executor.go +++ b/internal/batches/executor/executor.go @@ -59,9 +59,10 @@ type newExecutorOpts struct { Logger log.LogManager // Config - Parallelism int - Timeout time.Duration - TempDir string + Parallelism int + Timeout time.Duration + TempDir string + WriteStepCacheResult func(ctx context.Context, stepResult execution.AfterStepResult, task *Task) error } type executor struct { @@ -177,7 +178,8 @@ func (x *executor) do(ctx context.Context, task *Task, ui TaskExecutionUI) (err ensureImage: x.opts.EnsureImage, tempDir: x.opts.TempDir, - ui: ui.StepsExecutionUI(task), + ui: ui.StepsExecutionUI(task), + writeStepCacheResult: x.opts.WriteStepCacheResult, } result, stepResults, err := runSteps(runCtx, opts) diff --git a/internal/batches/executor/executor_test.go b/internal/batches/executor/executor_test.go index 37cff66d4d..f632abfdeb 100644 --- a/internal/batches/executor/executor_test.go +++ b/internal/batches/executor/executor_test.go @@ -10,6 +10,7 @@ import ( "path/filepath" "runtime" "strings" + "sync" "testing" "time" @@ -69,6 +70,8 @@ func TestExecutor_Integration(t *testing.T) { wantFinished int wantFinishedWithErr int + + wantCacheCount int }{ { name: "success", @@ -97,7 +100,8 @@ func TestExecutor_Integration(t *testing.T) { rootPath: []string{"README.md"}, }, }, - wantFinished: 2, + wantFinished: 2, + wantCacheCount: 4, }, { name: "empty", @@ -120,7 +124,8 @@ func TestExecutor_Integration(t *testing.T) { rootPath: []string{}, }, }, - wantFinished: 1, + wantFinished: 1, + wantCacheCount: 1, }, { name: "timeout", @@ -178,7 +183,8 @@ func TestExecutor_Integration(t *testing.T) { }, }, }, - wantFinished: 1, + wantFinished: 1, + wantCacheCount: 5, }, { name: "workspaces", @@ -233,7 +239,8 @@ func TestExecutor_Integration(t *testing.T) { "a/b": []string{"a/b/hello.txt", "a/b/gitignore-exists", "a/b/gitignore-exists-in-a"}, }, }, - wantFinished: 3, + wantFinished: 3, + wantCacheCount: 15, }, { name: "step condition", @@ -268,7 +275,8 @@ func TestExecutor_Integration(t *testing.T) { "sub/directory/of/repo": []string{"README.md", "hello.txt", "in-path.txt"}, }, }, - wantFinished: 2, + wantFinished: 2, + wantCacheCount: 4, }, { name: "skips errors", @@ -300,6 +308,7 @@ func TestExecutor_Integration(t *testing.T) { wantErrInclude: "execution in github.com/sourcegraph/sourcegraph failed: run: exit 1", wantFinished: 1, wantFinishedWithErr: 1, + wantCacheCount: 2, }, } @@ -337,6 +346,9 @@ func TestExecutor_Integration(t *testing.T) { // Temp dir for log files and downloaded archives testTempDir := t.TempDir() + cacheCount := 0 + var cacheLock sync.Mutex + // Setup executor opts := newExecutorOpts{ Creator: workspace.NewCreator(context.Background(), "bind", testTempDir, testTempDir, images), @@ -347,6 +359,12 @@ func TestExecutor_Integration(t *testing.T) { TempDir: testTempDir, Parallelism: runtime.GOMAXPROCS(0), Timeout: tc.executorTimeout, + WriteStepCacheResult: func(ctx context.Context, stepResult execution.AfterStepResult, task *Task) error { + cacheLock.Lock() + cacheCount += 1 + cacheLock.Unlock() + return nil + }, } if opts.Timeout == 0 { @@ -372,6 +390,9 @@ func TestExecutor_Integration(t *testing.T) { } } + if tc.wantCacheCount != cacheCount { + t.Errorf("wrong cache count. have=%d want=%d", cacheCount, tc.wantCacheCount) + } wantResults := 0 resultsFound := map[string]map[string]bool{} for repo, byPath := range tc.wantFilesChanged { @@ -695,6 +716,9 @@ func testExecuteTasks(t *testing.T, tasks []*Task, archives ...mock.RepoArchive) TempDir: testTempDir, Parallelism: runtime.GOMAXPROCS(0), Timeout: 30 * time.Second, + WriteStepCacheResult: func(ctx context.Context, stepResult execution.AfterStepResult, task *Task) error { + return nil + }, }) executor.Start(context.Background(), tasks, newDummyTaskExecutionUI()) diff --git a/internal/batches/executor/run_steps.go b/internal/batches/executor/run_steps.go index 1f11e969d9..8f7a65f4ac 100644 --- a/internal/batches/executor/run_steps.go +++ b/internal/batches/executor/run_steps.go @@ -37,6 +37,8 @@ type executionOpts struct { logger log.TaskLogger ui StepsExecutionUI + + writeStepCacheResult func(ctx context.Context, stepResult execution.AfterStepResult, task *Task) error } func runSteps(ctx context.Context, opts *executionOpts) (result execution.Result, stepResults []execution.AfterStepResult, err error) { @@ -186,6 +188,12 @@ func runSteps(ctx context.Context, opts *executionOpts) (result execution.Result stepResults = append(stepResults, stepResult) previousStepResult = result + // cache the result here + err = opts.writeStepCacheResult(ctx, stepResult, opts.task) + if err != nil { + return execResult, nil, errors.Wrap(err, "failed to cache stepResult") + } + opts.ui.StepFinished(i+1, stepResult.Diff, result.Files, stepResult.Outputs) } From ac8d7999ff582d447d2b3ebb4decd2536813741c Mon Sep 17 00:00:00 2001 From: Eric Fritz Date: Mon, 14 Mar 2022 08:57:23 -0500 Subject: [PATCH 145/647] lsif upload: Send indexer version witih upload request (#710) --- cmd/src/lsif_upload.go | 17 ++++++++++------- cmd/src/lsif_upload_flags.go | 20 +++++++++++++++----- go.mod | 4 ++-- go.sum | 7 ++++--- 4 files changed, 31 insertions(+), 17 deletions(-) diff --git a/cmd/src/lsif_upload.go b/cmd/src/lsif_upload.go index 7a338f3748..e05b298666 100644 --- a/cmd/src/lsif_upload.go +++ b/cmd/src/lsif_upload.go @@ -87,13 +87,14 @@ func handleLSIFUpload(args []string) error { if lsifUploadFlags.json { serialized, err := json.Marshal(map[string]interface{}{ - "repo": lsifUploadFlags.repo, - "commit": lsifUploadFlags.commit, - "root": lsifUploadFlags.root, - "file": lsifUploadFlags.file, - "indexer": lsifUploadFlags.indexer, - "uploadId": uploadID, - "uploadUrl": uploadURL, + "repo": lsifUploadFlags.repo, + "commit": lsifUploadFlags.commit, + "root": lsifUploadFlags.root, + "file": lsifUploadFlags.file, + "indexer": lsifUploadFlags.indexer, + "indexerVersion": lsifUploadFlags.indexerVersion, + "uploadId": uploadID, + "uploadUrl": uploadURL, }) if err != nil { return err @@ -155,6 +156,7 @@ func lsifUploadOptions(out *output.Output) upload.UploadOptions { Commit: lsifUploadFlags.commit, Root: lsifUploadFlags.root, Indexer: lsifUploadFlags.indexer, + IndexerVersion: lsifUploadFlags.indexerVersion, AssociatedIndexID: associatedIndexID, }, SourcegraphInstanceOptions: upload.SourcegraphInstanceOptions{ @@ -188,6 +190,7 @@ func printInferredArguments(out *output.Output) { block.Writef("root: %s", lsifUploadFlags.root) block.Writef("file: %s", lsifUploadFlags.file) block.Writef("indexer: %s", lsifUploadFlags.indexer) + block.Writef("indexerVersion: %s", lsifUploadFlags.indexerVersion) block.Close() } diff --git a/cmd/src/lsif_upload_flags.go b/cmd/src/lsif_upload_flags.go index fd10004969..9685f15701 100644 --- a/cmd/src/lsif_upload_flags.go +++ b/cmd/src/lsif_upload_flags.go @@ -22,6 +22,7 @@ var lsifUploadFlags struct { commit string root string indexer string + indexerVersion string associatedIndexID int // SourcegraphInstanceOptions @@ -54,6 +55,7 @@ func init() { lsifUploadFlagSet.StringVar(&lsifUploadFlags.commit, "commit", "", `The 40-character hash of the commit. Defaults to the currently checked-out commit.`) lsifUploadFlagSet.StringVar(&lsifUploadFlags.root, "root", "", `The path in the repository that matches the LSIF projectRoot (e.g. cmd/project1). Defaults to the directory where the dump file is located.`) lsifUploadFlagSet.StringVar(&lsifUploadFlags.indexer, "indexer", "", `The name of the indexer that generated the dump. This will override the 'toolInfo.name' field in the metadata vertex of the LSIF dump file. This must be supplied if the indexer does not set this field (in which case the upload will fail with an explicit message).`) + lsifUploadFlagSet.StringVar(&lsifUploadFlags.indexerVersion, "indexerVersion", "", `The version of the indexer that generated the dump. This will override the 'toolInfo.version' field in the metadata vertex of the LSIF dump file. This must be supplied if the indexer does not set this field (in which case the upload will fail with an explicit message).`) lsifUploadFlagSet.IntVar(&lsifUploadFlags.associatedIndexID, "associated-index-id", -1, "ID of the associated index record for this upload. For internal use only.") // SourcegraphInstanceOptions @@ -131,6 +133,10 @@ func inferMissingLSIFUploadFlags() (inferErrors []argumentInferenceError) { inferErrors = append(inferErrors, argumentInferenceError{"file", err}) } + indexerName, indexerVersion, readIndexerNameAndVersionErr := readIndexerNameAndVersion() + getIndexerName := func() (string, error) { return indexerName, readIndexerNameAndVersionErr } + getIndexerVersion := func() (string, error) { return indexerVersion, readIndexerNameAndVersionErr } + if err := inferUnsetFlag("repo", &lsifUploadFlags.repo, codeintel.InferRepo); err != nil { inferErrors = append(inferErrors, *err) } @@ -140,7 +146,10 @@ func inferMissingLSIFUploadFlags() (inferErrors []argumentInferenceError) { if err := inferUnsetFlag("root", &lsifUploadFlags.root, inferIndexRoot); err != nil { inferErrors = append(inferErrors, *err) } - if err := inferUnsetFlag("indexer", &lsifUploadFlags.indexer, readIndexerName); err != nil { + if err := inferUnsetFlag("indexer", &lsifUploadFlags.indexer, getIndexerName); err != nil { + inferErrors = append(inferErrors, *err) + } + if err := inferUnsetFlag("indexerVersion", &lsifUploadFlags.indexerVersion, getIndexerVersion); err != nil { inferErrors = append(inferErrors, *err) } @@ -187,17 +196,18 @@ func inferIndexRoot() (string, error) { return codeintel.InferRoot(lsifUploadFlags.file) } -// readIndexerName returns the indexer name read from the configured index file. +// readIndexerNameAndVersion returns the indexer name and version values read from the +// toolInfo value in the configured index file. // // Note: This function must not be called before lsifUploadFlagSet.Parse. -func readIndexerName() (string, error) { +func readIndexerNameAndVersion() (string, string, error) { file, err := os.Open(lsifUploadFlags.file) if err != nil { - return "", err + return "", "", err } defer file.Close() - return upload.ReadIndexerName(file) + return upload.ReadIndexerNameAndVersion(file) } // validateLSIFUploadFlags returns an error if any of the parsed flag values are illegal. diff --git a/go.mod b/go.mod index 28cb855669..81077a4555 100644 --- a/go.mod +++ b/go.mod @@ -19,7 +19,7 @@ require ( github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4 github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf - github.com/sourcegraph/sourcegraph/lib v0.0.0-20220218193119-f6123c1144b4 + github.com/sourcegraph/sourcegraph/lib v0.0.0-20220314135113-5b7b17c7f27a github.com/stretchr/testify v1.7.0 golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b @@ -56,7 +56,7 @@ require ( github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect github.com/xeipuuv/gojsonschema v1.2.0 // indirect golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect - golang.org/x/sys v0.0.0-20220209214540-3681064d5158 // indirect + golang.org/x/sys v0.0.0-20220310020820-b874c991c1a5 // indirect golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect ) diff --git a/go.sum b/go.sum index ef24c2eb72..548834a77e 100644 --- a/go.sum +++ b/go.sum @@ -292,8 +292,8 @@ github.com/sourcegraph/go-diff v0.6.1 h1:hmA1LzxW0n1c3Q4YbrFgg4P99GSnebYa3x8gr0H github.com/sourcegraph/go-diff v0.6.1/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20220218193119-f6123c1144b4 h1:QOdM6vg4+Co8p0OEQtRzOcyxmN4+Ib8FrsSj2/LLzk4= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20220218193119-f6123c1144b4/go.mod h1:6/o2uP/pgAIyAZWqHeZF4J9F8rfWvkU3BRqVLWpLwTA= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20220314135113-5b7b17c7f27a h1:hVZHXDc5i39zda7BFVaGqUBfk7S5KLTiyaScR+MsjiI= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20220314135113-5b7b17c7f27a/go.mod h1:6/o2uP/pgAIyAZWqHeZF4J9F8rfWvkU3BRqVLWpLwTA= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= @@ -423,8 +423,9 @@ golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20211102192858-4dd72447c267/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211117180635-dee7805ff2e1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211213223007-03aa0b5f6827/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220209214540-3681064d5158 h1:rm+CHSpPEEW2IsXUib1ThaHIjuBVZjxNgSKmBLFfD4c= golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220310020820-b874c991c1a5 h1:y/woIyUBFbpQGKS0u1aHF/40WUDnek3fPOyD08H5Vng= +golang.org/x/sys v0.0.0-20220310020820-b874c991c1a5/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= From 300637470ce51a4cde45573368fb0973fbf2d4e8 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Thu, 17 Mar 2022 12:38:09 +0100 Subject: [PATCH 146/647] Prepare changelog for 3.38 --- CHANGELOG.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index ee4fd54408..b86020c1fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,12 @@ All notable changes to `src-cli` are documented in this file. ### Removed +## 3.38.0 + +### Changed + +- Batch Changes: Step results are now also cached when the overall execution fails. [#709](https://github.com/sourcegraph/src-cli/pull/709) + ## 3.37.0 No noteworthy changes, mechanical release to match Sourcegraph release. From c750d8f9ad4636c8d84bf59e6a3662b33978f19e Mon Sep 17 00:00:00 2001 From: Giselle Northy Date: Mon, 21 Mar 2022 00:11:52 -0700 Subject: [PATCH 147/647] add login into command list & alphabetize (#713) * add login into command list * correctly push file changes --- CHANGELOG.md | 2 ++ cmd/src/main.go | 13 +++++++------ 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b86020c1fc..1186b43432 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,8 @@ All notable changes to `src-cli` are documented in this file. ### Added +- Added `login` text to command text menu and ordered alphabetically [#713](https://github.com/sourcegraph/src-cli/pull/713) + ### Changed ### Fixed diff --git a/cmd/src/main.go b/cmd/src/main.go index 4a0099057b..5d25b67a97 100644 --- a/cmd/src/main.go +++ b/cmd/src/main.go @@ -32,17 +32,18 @@ The options are: The commands are: - search search for results on Sourcegraph api interacts with the Sourcegraph GraphQL API - repos,repo manages repositories - users,user manages users - orgs,org manages organizations + batch manages batch changes config manages global, org, and user settings - extsvc manages external services extensions,ext manages extensions (experimental) - batch manages batch changes + extsvc manages external services + login authenticate to a Sourcegraph instance with your user credentials lsif manages LSIF data + orgs,org manages organizations + repos,repo manages repositories + search search for results on Sourcegraph serve-git serves your local git repositories over HTTP for Sourcegraph to pull + users,user manages users version display and compare the src-cli version against the recommended version for your instance Use "src [command] -h" for more information about a command. From 25749819e336132d5b4740dee81945706a4c5fd9 Mon Sep 17 00:00:00 2001 From: TJ Kandala Date: Wed, 30 Mar 2022 12:14:23 -0400 Subject: [PATCH 148/647] extensions: remove url from copied manifest (#718) --- CHANGELOG.md | 2 ++ cmd/src/extensions_copy.go | 5 +++++ cmd/src/extensions_publish.go | 6 +++++- cmd/src/extensions_publish_test.go | 12 ++++++++++++ 4 files changed, 24 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1186b43432..d0b2840e71 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,8 @@ All notable changes to `src-cli` are documented in this file. ### Fixed +- `src extensions copy` now removes the `url` property from extension manifests that points to the sourcegraph.com extension bundle, enabling use for air-gapped instances. + ### Removed ## 3.38.0 diff --git a/cmd/src/extensions_copy.go b/cmd/src/extensions_copy.go index 45cb3441a3..4b91cf9f62 100644 --- a/cmd/src/extensions_copy.go +++ b/cmd/src/extensions_copy.go @@ -100,6 +100,11 @@ Copy an extension from Sourcegraph.com to your private registry. if err != nil { return err } + // Remove sourcegraph.com bundle URL. + manifest, err = updatePropertyInManifest(manifest, "url", "") + if err != nil { + return err + } response, err := http.Get(extensionResult.ExtensionRegistry.Extension.Manifest.BundleURL) if err != nil { diff --git a/cmd/src/extensions_publish.go b/cmd/src/extensions_publish.go index afc1f40e1f..2156c7b170 100644 --- a/cmd/src/extensions_publish.go +++ b/cmd/src/extensions_publish.go @@ -247,7 +247,11 @@ func updatePropertyInManifest(manifest []byte, property, value string) (updatedM if o == nil { o = map[string]interface{}{} } - o[property] = value + if value == "" { + delete(o, property) + } else { + o[property] = value + } return json.MarshalIndent(o, "", " ") } diff --git a/cmd/src/extensions_publish_test.go b/cmd/src/extensions_publish_test.go index 17ef947312..abf2832968 100644 --- a/cmd/src/extensions_publish_test.go +++ b/cmd/src/extensions_publish_test.go @@ -54,6 +54,18 @@ func TestUpdatePropertyInManifest(t *testing.T) { } }) } + + t.Run("remove property", func(t *testing.T) { + manifest := `{"extensionID":"sourcegraph/typescript", "url":"https://sourcegraph.com"}` + want := `{"extensionID": "sourcegraph/typescript"}` + got, err := updatePropertyInManifest([]byte(manifest), "url", "") + if err != nil { + t.Fatal(err) + } + if !jsonDeepEqual(string(got), want) { + t.Errorf("got %q, want %q", got, want) + } + }) } func jsonDeepEqual(a, b string) bool { From 1c260bce6d91725ef2c17399cd5abdf1972be238 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 30 Mar 2022 09:21:52 -0700 Subject: [PATCH 149/647] Update golang digest to 1d4c7fc (#708) Co-authored-by: Renovate Bot --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index bd540f3383..61caec7f07 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,7 +4,7 @@ # # Nothing fancy here: we copy in the source code and build on the Alpine Go # image. Refer to .dockerignore to get a sense of what we're not going to copy. -FROM golang:1.17-alpine@sha256:d030a987c28ca403007a69af28ba419fca00fc15f08e7801fc8edee77c00b8ee as builder +FROM golang:1.17-alpine@sha256:1d4c7fcfd0c4c917383755ca3b6f6c1f797ec16b83cdebc672d9b08a79b64644 as builder COPY . /src WORKDIR /src From 5824ce485b29ade1b3ad8c2d4a49aa575e93dbbe Mon Sep 17 00:00:00 2001 From: Adam Harvey Date: Thu, 31 Mar 2022 11:39:09 -0700 Subject: [PATCH 150/647] search: add a tip about negated searches (#720) --- cmd/src/search.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/cmd/src/search.go b/cmd/src/search.go index fbbfbcaeeb..5fead67d5e 100644 --- a/cmd/src/search.go +++ b/cmd/src/search.go @@ -49,6 +49,12 @@ Other tips: Force color output on (not on by default when piped to other programs) by setting COLOR=t Query syntax: https://about.sourcegraph.com/docs/search/query-syntax/ + + Be careful with search strings including negation: a search with an initial + negated term may be parsed as a flag rather than as a search string. You can + use -- to ensure that src parses this correctly, eg: + + $ src search -- '-repo:github.com/foo/bar error' ` flagSet := flag.NewFlagSet("search", flag.ExitOnError) From 347b9ce2667725cedf107fa3f1f024b89178fc25 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Thu, 14 Apr 2022 13:43:13 +0200 Subject: [PATCH 151/647] Prepare changelog for 3.39 --- CHANGELOG.md | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d0b2840e71..4aaab33b09 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,16 +13,22 @@ All notable changes to `src-cli` are documented in this file. ### Added -- Added `login` text to command text menu and ordered alphabetically [#713](https://github.com/sourcegraph/src-cli/pull/713) - ### Changed ### Fixed -- `src extensions copy` now removes the `url` property from extension manifests that points to the sourcegraph.com extension bundle, enabling use for air-gapped instances. - ### Removed +## 3.39.0 + +### Added + +- Added `login` text to command text menu and ordered alphabetically [#713](https://github.com/sourcegraph/src-cli/pull/713) + +### Fixed + +- `src extensions copy` now removes the `url` property from extension manifests that points to the sourcegraph.com extension bundle, enabling use for air-gapped instances. + ## 3.38.0 ### Changed From f8a70a4fa99adbbe227672a5f9da40e851026757 Mon Sep 17 00:00:00 2001 From: Eric Fritz Date: Thu, 14 Apr 2022 10:30:29 -0500 Subject: [PATCH 152/647] lsif upload: Add -gitlab-token to help text (#726) --- cmd/src/lsif_upload.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/cmd/src/lsif_upload.go b/cmd/src/lsif_upload.go index e05b298666..dd8e1eb096 100644 --- a/cmd/src/lsif_upload.go +++ b/cmd/src/lsif_upload.go @@ -34,7 +34,8 @@ Examples: Upload an LSIF dump when lsifEnforceAuth is enabled: - $ src lsif upload -github-token=BAZ + $ src lsif upload -github-token=BAZ, or + $ src lsif upload -gitlab-token=BAZ Upload an LSIF dump when the LSIF indexer does not not declare a tool name. From 56c8be84d4a8db6e14e02efa0f0247199a09b584 Mon Sep 17 00:00:00 2001 From: Eric Fritz Date: Thu, 14 Apr 2022 10:35:24 -0500 Subject: [PATCH 153/647] lsif upload: Add gitlab-token (#721) --- CHANGELOG.md | 2 ++ cmd/src/lsif_upload.go | 3 ++- cmd/src/lsif_upload_flags.go | 10 ++++++++-- go.mod | 18 +++++++++++++----- go.sum | 27 +++++++++++++++++++++++++++ 5 files changed, 52 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4aaab33b09..7a1e09cb30 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,8 @@ All notable changes to `src-cli` are documented in this file. ### Added +- `src lsif upload` now supports the `-gitlab-token` flag. [#721](https://github.com/sourcegraph/src-cli/pull/721) + ### Changed ### Fixed diff --git a/cmd/src/lsif_upload.go b/cmd/src/lsif_upload.go index dd8e1eb096..421705a4e3 100644 --- a/cmd/src/lsif_upload.go +++ b/cmd/src/lsif_upload.go @@ -167,8 +167,9 @@ func lsifUploadOptions(out *output.Output) upload.UploadOptions { MaxRetries: 5, RetryInterval: time.Second, Path: lsifUploadFlags.uploadRoute, - GitHubToken: lsifUploadFlags.gitHubToken, MaxPayloadSizeBytes: lsifUploadFlags.maxPayloadSizeMb * 1000 * 1000, + GitHubToken: lsifUploadFlags.gitHubToken, + GitLabToken: lsifUploadFlags.gitLabToken, }, OutputOptions: upload.OutputOptions{ Output: out, diff --git a/cmd/src/lsif_upload_flags.go b/cmd/src/lsif_upload_flags.go index 9685f15701..da740a02b5 100644 --- a/cmd/src/lsif_upload_flags.go +++ b/cmd/src/lsif_upload_flags.go @@ -27,9 +27,12 @@ var lsifUploadFlags struct { // SourcegraphInstanceOptions uploadRoute string - gitHubToken string maxPayloadSizeMb int64 + // Codehost authorization secrets + gitHubToken string + gitLabToken string + // Output and error behavior ignoreUploadFailures bool noProgress bool @@ -60,9 +63,12 @@ func init() { // SourcegraphInstanceOptions lsifUploadFlagSet.StringVar(&lsifUploadFlags.uploadRoute, "upload-route", "/.api/lsif/upload", "The path of the upload route. For internal use only.") - lsifUploadFlagSet.StringVar(&lsifUploadFlags.gitHubToken, "github-token", "", `A GitHub access token with 'public_repo' scope that Sourcegraph uses to verify you have access to the repository.`) lsifUploadFlagSet.Int64Var(&lsifUploadFlags.maxPayloadSizeMb, "max-payload-size", 100, `The maximum upload size (in megabytes). Indexes exceeding this limit will be uploaded over multiple HTTP requests.`) + // Codehost authorization secrets + lsifUploadFlagSet.StringVar(&lsifUploadFlags.gitHubToken, "github-token", "", `A GitHub access token with 'public_repo' scope that Sourcegraph uses to verify you have access to the repository.`) + lsifUploadFlagSet.StringVar(&lsifUploadFlags.gitLabToken, "gitlab-token", "", `A GitLab access token with TODO that Sourcegraph uses to verify you have access to the repository.`) + // Output and error behavior lsifUploadFlagSet.BoolVar(&lsifUploadFlags.ignoreUploadFailures, "ignore-upload-failure", false, `Exit with status code zero on upload failure.`) lsifUploadFlagSet.BoolVar(&lsifUploadFlags.noProgress, "no-progress", false, `Do not display progress updates.`) diff --git a/go.mod b/go.mod index 81077a4555..cd6743978b 100644 --- a/go.mod +++ b/go.mod @@ -19,19 +19,24 @@ require ( github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4 github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf - github.com/sourcegraph/sourcegraph/lib v0.0.0-20220314135113-5b7b17c7f27a - github.com/stretchr/testify v1.7.0 - golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f + github.com/sourcegraph/sourcegraph/lib v0.0.0-20220414150621-eeb00fcedd88 + github.com/stretchr/testify v1.7.1 + golang.org/x/net v0.0.0-20220325170049-de3da57026de gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7 ) require ( github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect + github.com/alecthomas/kingpin v2.2.6+incompatible // indirect + github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751 // indirect + github.com/alecthomas/units v0.0.0-20211218093645-b94a6e3cc137 // indirect github.com/cockroachdb/errors v1.8.9 // indirect github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f // indirect github.com/cockroachdb/redact v1.1.3 // indirect + github.com/dave/jennifer v1.5.0 // indirect github.com/davecgh/go-spew v1.1.1 // indirect + github.com/derision-test/go-mockgen v1.2.0 // indirect github.com/getsentry/sentry-go v0.12.0 // indirect github.com/ghodss/yaml v1.0.0 // indirect github.com/go-stack/stack v1.8.1 // indirect @@ -43,6 +48,7 @@ require ( github.com/kr/text v0.2.0 // indirect github.com/mattn/go-colorable v0.1.12 // indirect github.com/mattn/go-runewidth v0.0.13 // indirect + github.com/mitchellh/go-wordwrap v1.0.1 // indirect github.com/moby/term v0.0.0-20210619224110-3f7ff695adc6 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect @@ -55,9 +61,11 @@ require ( github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect github.com/xeipuuv/gojsonschema v1.2.0 // indirect + golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3 // indirect golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect - golang.org/x/sys v0.0.0-20220310020820-b874c991c1a5 // indirect - golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect + golang.org/x/sys v0.0.0-20220412211240-33da011f77ad // indirect + golang.org/x/tools v0.1.10 // indirect + golang.org/x/xerrors v0.0.0-20220411194840-2f41105eb62f // indirect gopkg.in/yaml.v2 v2.4.0 // indirect ) diff --git a/go.sum b/go.sum index 548834a77e..13c6d933fc 100644 --- a/go.sum +++ b/go.sum @@ -13,9 +13,12 @@ github.com/Masterminds/semver v1.5.0 h1:H65muMkzWKEuNDnfl9d70GUjFniHKHRbFPGBuZ3Q github.com/Masterminds/semver v1.5.0/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y= github.com/Shopify/goreferrer v0.0.0-20181106222321-ec9c9a553398/go.mod h1:a1uqRtAwp2Xwc6WNPJEufxJ7fx3npB4UV/JOLmbu5I0= github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY= +github.com/alecthomas/kingpin v2.2.6+incompatible h1:5svnBTFgJjZvGKyYBtMB0+m5wvrbUHiqye8wRJMlnYI= github.com/alecthomas/kingpin v2.2.6+incompatible/go.mod h1:59OFYbFVLKQKq+mqrL6Rw5bR0c3ACQaawgXx0QYndlE= +github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751 h1:JYp7IbQjafoB+tBA3gMyHYHrpOtNuDiK/uB5uXxq5wM= github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/units v0.0.0-20210208195552-ff826a37aa15/go.mod h1:OMCwj8VM1Kc9e19TLln2VL61YJF0x1XFtfdL4JdbSyE= +github.com/alecthomas/units v0.0.0-20211218093645-b94a6e3cc137 h1:s6gZFSlWYmbqAuRjVTiNNhvNRfY2Wxp9nhfyel4rklc= github.com/alecthomas/units v0.0.0-20211218093645-b94a6e3cc137/go.mod h1:OMCwj8VM1Kc9e19TLln2VL61YJF0x1XFtfdL4JdbSyE= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= github.com/aymerick/raymond v2.0.3-0.20180322193309-b565731e1464+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g= @@ -45,13 +48,24 @@ github.com/creack/goselect v0.1.2/go.mod h1:a/NhLweNvqIYMuxcMOuWY516Cimucms3DglD github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/creack/pty v1.1.11 h1:07n33Z8lZxZ2qwegKbObQohDhXDQxiMMz1NOUGYlesw= github.com/creack/pty v1.1.11/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/dave/astrid v0.0.0-20170323122508-8c2895878b14/go.mod h1:Sth2QfxfATb/nW4EsrSi2KyJmbcniZ8TgTaji17D6ms= +github.com/dave/brenda v1.1.0/go.mod h1:4wCUr6gSlu5/1Tk7akE5X7UorwiQ8Rij0SKH3/BGMOM= +github.com/dave/courtney v0.3.0/go.mod h1:BAv3hA06AYfNUjfjQr+5gc6vxeBVOupLqrColj+QSD8= +github.com/dave/gopackages v0.0.0-20170318123100-46e7023ec56e/go.mod h1:i00+b/gKdIDIxuLDFob7ustLAVqhsZRk2qVZrArELGQ= github.com/dave/jennifer v1.4.1/go.mod h1:7jEdnm+qBcxl8PC0zyp7vxcpSRnzXSt9r39tpTVGlwA= +github.com/dave/jennifer v1.5.0 h1:HmgPN93bVDpkQyYbqhCHj5QlgvUkvEOzMyEvKLgCRrg= +github.com/dave/jennifer v1.5.0/go.mod h1:4MnyiFIlZS3l5tSDn8VnzE6ffAhYBMB2SZntBsZGUok= +github.com/dave/kerr v0.0.0-20170318121727-bc25dd6abe8e/go.mod h1:qZqlPyPvfsDJt+3wHJ1EvSXDuVjFTK0j2p/ca+gtsb8= +github.com/dave/patsy v0.0.0-20210517141501-957256f50cba/go.mod h1:qfR88CgEGLoiqDaE+xxDCi5QA5v4vUoW0UCX2Nd5Tlc= +github.com/dave/rebecca v0.9.1/go.mod h1:N6XYdMD/OKw3lkF3ywh8Z6wPGuwNFDNtWYEMFWEmXBA= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/derision-test/glock v0.0.0-20210316032053-f5b74334bb29 h1:O07j7ewg0eFHRx+7bxCA/7z86HJexl7HLY9kyVMmPDo= github.com/derision-test/glock v0.0.0-20210316032053-f5b74334bb29/go.mod h1:jKtLdBMrF+XQatqvg46wiWdDfDSSDjdhO4dOM2FX9H4= github.com/derision-test/go-mockgen v1.1.2/go.mod h1:9H3VGTWYnL1VJoHHCuPKDpPFmNQ1uVyNlpX6P63l5Sk= +github.com/derision-test/go-mockgen v1.2.0 h1:SCF7p4FuO6IZId3CMjSHH9K0SMDVXNz7jc3AOeJaBd8= +github.com/derision-test/go-mockgen v1.2.0/go.mod h1:/TXUePlhtHmDDCaDAi/a4g6xOHqMDz3Wf0r2NPGskB4= github.com/dgraph-io/badger v1.6.0/go.mod h1:zwt7syl517jmP8s94KqSxTlM6IMsdhYy6psNgSztDR4= github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= @@ -221,6 +235,7 @@ github.com/microcosm-cc/bluemonday v1.0.2/go.mod h1:iVP4YcDBq+n/5fb23BhYFvIMq/le github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw= github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= +github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0= github.com/mitchellh/go-wordwrap v1.0.1/go.mod h1:R62XHJLzvMFRBbcrT7m7WgmE1eOyTSsCt+hzestvNj0= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ= @@ -294,6 +309,8 @@ github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWii github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= github.com/sourcegraph/sourcegraph/lib v0.0.0-20220314135113-5b7b17c7f27a h1:hVZHXDc5i39zda7BFVaGqUBfk7S5KLTiyaScR+MsjiI= github.com/sourcegraph/sourcegraph/lib v0.0.0-20220314135113-5b7b17c7f27a/go.mod h1:6/o2uP/pgAIyAZWqHeZF4J9F8rfWvkU3BRqVLWpLwTA= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20220414150621-eeb00fcedd88 h1:xqMUhhlrIFJRsb4EodMR5aWZpTY0rdukgVR8yV2mz7w= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20220414150621-eeb00fcedd88/go.mod h1:6/o2uP/pgAIyAZWqHeZF4J9F8rfWvkU3BRqVLWpLwTA= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= @@ -312,6 +329,7 @@ github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5 github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc= github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw= github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= @@ -358,6 +376,8 @@ golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro= +golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3 h1:kQgndtyPBW/JIYERgdxfwMYh3AVStj88WQTlNDi2a+o= +golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3/go.mod h1:3p9vT2HGsQu2K1YbXdKPJLVgG5VJdoTa1poYQBtP1AY= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -380,6 +400,7 @@ golang.org/x/net v0.0.0-20210614182718-04defd469f4e/go.mod h1:9nx3DQGgdP8bBQD5qx golang.org/x/net v0.0.0-20211008194852-3b03d305991f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f h1:OfiFi4JbukWwe3lzw+xunroH1mnC1e2Gy5cxNJApiSY= golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20220325170049-de3da57026de/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -426,6 +447,8 @@ golang.org/x/sys v0.0.0-20211213223007-03aa0b5f6827/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220310020820-b874c991c1a5 h1:y/woIyUBFbpQGKS0u1aHF/40WUDnek3fPOyD08H5Vng= golang.org/x/sys v0.0.0-20220310020820-b874c991c1a5/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220412211240-33da011f77ad h1:ntjMns5wyP/fN65tdBD4g8J5w8n015+iIIs9rtjXkY0= +golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= @@ -456,11 +479,15 @@ golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.8-0.20211102182255-bb4add04ddef/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= golang.org/x/tools v0.1.8/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= golang.org/x/tools v0.1.9/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= +golang.org/x/tools v0.1.10 h1:QjFRCZxdOhBJ/UNgnBZLbNV13DlbnK0quyivTnXJM20= +golang.org/x/tools v0.1.10/go.mod h1:Uh6Zz+xoGYZom868N8YTex3t7RhtHDBrE8Gzo9bV56E= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20220411194840-2f41105eb62f h1:GGU+dLjvlC3qDwqYgL6UgRmHXhOOgns0bZu2Ty5mm6U= +golang.org/x/xerrors v0.0.0-20220411194840-2f41105eb62f/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/genproto v0.0.0-20180518175338-11a468237815/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= From aaaccffbe8c419ba7ebdabfd0d66a5552b244239 Mon Sep 17 00:00:00 2001 From: Eric Fritz Date: Thu, 14 Apr 2022 10:39:47 -0500 Subject: [PATCH 154/647] chore: Run go mod tidy (#728) --- go.mod | 8 -------- go.sum | 30 ++++-------------------------- 2 files changed, 4 insertions(+), 34 deletions(-) diff --git a/go.mod b/go.mod index cd6743978b..0b8f2dd5fe 100644 --- a/go.mod +++ b/go.mod @@ -28,15 +28,10 @@ require ( require ( github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect - github.com/alecthomas/kingpin v2.2.6+incompatible // indirect - github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751 // indirect - github.com/alecthomas/units v0.0.0-20211218093645-b94a6e3cc137 // indirect github.com/cockroachdb/errors v1.8.9 // indirect github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f // indirect github.com/cockroachdb/redact v1.1.3 // indirect - github.com/dave/jennifer v1.5.0 // indirect github.com/davecgh/go-spew v1.1.1 // indirect - github.com/derision-test/go-mockgen v1.2.0 // indirect github.com/getsentry/sentry-go v0.12.0 // indirect github.com/ghodss/yaml v1.0.0 // indirect github.com/go-stack/stack v1.8.1 // indirect @@ -48,7 +43,6 @@ require ( github.com/kr/text v0.2.0 // indirect github.com/mattn/go-colorable v0.1.12 // indirect github.com/mattn/go-runewidth v0.0.13 // indirect - github.com/mitchellh/go-wordwrap v1.0.1 // indirect github.com/moby/term v0.0.0-20210619224110-3f7ff695adc6 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect @@ -61,10 +55,8 @@ require ( github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect github.com/xeipuuv/gojsonschema v1.2.0 // indirect - golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3 // indirect golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect golang.org/x/sys v0.0.0-20220412211240-33da011f77ad // indirect - golang.org/x/tools v0.1.10 // indirect golang.org/x/xerrors v0.0.0-20220411194840-2f41105eb62f // indirect gopkg.in/yaml.v2 v2.4.0 // indirect ) diff --git a/go.sum b/go.sum index 13c6d933fc..5146c29f95 100644 --- a/go.sum +++ b/go.sum @@ -13,12 +13,9 @@ github.com/Masterminds/semver v1.5.0 h1:H65muMkzWKEuNDnfl9d70GUjFniHKHRbFPGBuZ3Q github.com/Masterminds/semver v1.5.0/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y= github.com/Shopify/goreferrer v0.0.0-20181106222321-ec9c9a553398/go.mod h1:a1uqRtAwp2Xwc6WNPJEufxJ7fx3npB4UV/JOLmbu5I0= github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY= -github.com/alecthomas/kingpin v2.2.6+incompatible h1:5svnBTFgJjZvGKyYBtMB0+m5wvrbUHiqye8wRJMlnYI= github.com/alecthomas/kingpin v2.2.6+incompatible/go.mod h1:59OFYbFVLKQKq+mqrL6Rw5bR0c3ACQaawgXx0QYndlE= -github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751 h1:JYp7IbQjafoB+tBA3gMyHYHrpOtNuDiK/uB5uXxq5wM= github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/units v0.0.0-20210208195552-ff826a37aa15/go.mod h1:OMCwj8VM1Kc9e19TLln2VL61YJF0x1XFtfdL4JdbSyE= -github.com/alecthomas/units v0.0.0-20211218093645-b94a6e3cc137 h1:s6gZFSlWYmbqAuRjVTiNNhvNRfY2Wxp9nhfyel4rklc= github.com/alecthomas/units v0.0.0-20211218093645-b94a6e3cc137/go.mod h1:OMCwj8VM1Kc9e19TLln2VL61YJF0x1XFtfdL4JdbSyE= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= github.com/aymerick/raymond v2.0.3-0.20180322193309-b565731e1464+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g= @@ -48,24 +45,13 @@ github.com/creack/goselect v0.1.2/go.mod h1:a/NhLweNvqIYMuxcMOuWY516Cimucms3DglD github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/creack/pty v1.1.11 h1:07n33Z8lZxZ2qwegKbObQohDhXDQxiMMz1NOUGYlesw= github.com/creack/pty v1.1.11/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= -github.com/dave/astrid v0.0.0-20170323122508-8c2895878b14/go.mod h1:Sth2QfxfATb/nW4EsrSi2KyJmbcniZ8TgTaji17D6ms= -github.com/dave/brenda v1.1.0/go.mod h1:4wCUr6gSlu5/1Tk7akE5X7UorwiQ8Rij0SKH3/BGMOM= -github.com/dave/courtney v0.3.0/go.mod h1:BAv3hA06AYfNUjfjQr+5gc6vxeBVOupLqrColj+QSD8= -github.com/dave/gopackages v0.0.0-20170318123100-46e7023ec56e/go.mod h1:i00+b/gKdIDIxuLDFob7ustLAVqhsZRk2qVZrArELGQ= github.com/dave/jennifer v1.4.1/go.mod h1:7jEdnm+qBcxl8PC0zyp7vxcpSRnzXSt9r39tpTVGlwA= -github.com/dave/jennifer v1.5.0 h1:HmgPN93bVDpkQyYbqhCHj5QlgvUkvEOzMyEvKLgCRrg= -github.com/dave/jennifer v1.5.0/go.mod h1:4MnyiFIlZS3l5tSDn8VnzE6ffAhYBMB2SZntBsZGUok= -github.com/dave/kerr v0.0.0-20170318121727-bc25dd6abe8e/go.mod h1:qZqlPyPvfsDJt+3wHJ1EvSXDuVjFTK0j2p/ca+gtsb8= -github.com/dave/patsy v0.0.0-20210517141501-957256f50cba/go.mod h1:qfR88CgEGLoiqDaE+xxDCi5QA5v4vUoW0UCX2Nd5Tlc= -github.com/dave/rebecca v0.9.1/go.mod h1:N6XYdMD/OKw3lkF3ywh8Z6wPGuwNFDNtWYEMFWEmXBA= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/derision-test/glock v0.0.0-20210316032053-f5b74334bb29 h1:O07j7ewg0eFHRx+7bxCA/7z86HJexl7HLY9kyVMmPDo= github.com/derision-test/glock v0.0.0-20210316032053-f5b74334bb29/go.mod h1:jKtLdBMrF+XQatqvg46wiWdDfDSSDjdhO4dOM2FX9H4= github.com/derision-test/go-mockgen v1.1.2/go.mod h1:9H3VGTWYnL1VJoHHCuPKDpPFmNQ1uVyNlpX6P63l5Sk= -github.com/derision-test/go-mockgen v1.2.0 h1:SCF7p4FuO6IZId3CMjSHH9K0SMDVXNz7jc3AOeJaBd8= -github.com/derision-test/go-mockgen v1.2.0/go.mod h1:/TXUePlhtHmDDCaDAi/a4g6xOHqMDz3Wf0r2NPGskB4= github.com/dgraph-io/badger v1.6.0/go.mod h1:zwt7syl517jmP8s94KqSxTlM6IMsdhYy6psNgSztDR4= github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= @@ -235,7 +221,6 @@ github.com/microcosm-cc/bluemonday v1.0.2/go.mod h1:iVP4YcDBq+n/5fb23BhYFvIMq/le github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw= github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= -github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0= github.com/mitchellh/go-wordwrap v1.0.1/go.mod h1:R62XHJLzvMFRBbcrT7m7WgmE1eOyTSsCt+hzestvNj0= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ= @@ -307,8 +292,6 @@ github.com/sourcegraph/go-diff v0.6.1 h1:hmA1LzxW0n1c3Q4YbrFgg4P99GSnebYa3x8gr0H github.com/sourcegraph/go-diff v0.6.1/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20220314135113-5b7b17c7f27a h1:hVZHXDc5i39zda7BFVaGqUBfk7S5KLTiyaScR+MsjiI= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20220314135113-5b7b17c7f27a/go.mod h1:6/o2uP/pgAIyAZWqHeZF4J9F8rfWvkU3BRqVLWpLwTA= github.com/sourcegraph/sourcegraph/lib v0.0.0-20220414150621-eeb00fcedd88 h1:xqMUhhlrIFJRsb4EodMR5aWZpTY0rdukgVR8yV2mz7w= github.com/sourcegraph/sourcegraph/lib v0.0.0-20220414150621-eeb00fcedd88/go.mod h1:6/o2uP/pgAIyAZWqHeZF4J9F8rfWvkU3BRqVLWpLwTA= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= @@ -327,8 +310,8 @@ github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UV github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1 h1:5TQK59W5E3v0r2duFAb7P95B6hEeOyEnHRa8MjYSMTY= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc= github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw= @@ -376,8 +359,6 @@ golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro= -golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3 h1:kQgndtyPBW/JIYERgdxfwMYh3AVStj88WQTlNDi2a+o= -golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3/go.mod h1:3p9vT2HGsQu2K1YbXdKPJLVgG5VJdoTa1poYQBtP1AY= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -398,8 +379,8 @@ golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96b golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk= golang.org/x/net v0.0.0-20210614182718-04defd469f4e/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211008194852-3b03d305991f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f h1:OfiFi4JbukWwe3lzw+xunroH1mnC1e2Gy5cxNJApiSY= golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20220325170049-de3da57026de h1:pZB1TWnKi+o4bENlbzAgLrEbY4RMYmUIRobMcSmfeYc= golang.org/x/net v0.0.0-20220325170049-de3da57026de/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -444,12 +425,12 @@ golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20211102192858-4dd72447c267/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211117180635-dee7805ff2e1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211213223007-03aa0b5f6827/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220310020820-b874c991c1a5 h1:y/woIyUBFbpQGKS0u1aHF/40WUDnek3fPOyD08H5Vng= -golang.org/x/sys v0.0.0-20220310020820-b874c991c1a5/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220412211240-33da011f77ad h1:ntjMns5wyP/fN65tdBD4g8J5w8n015+iIIs9rtjXkY0= golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= @@ -479,12 +460,9 @@ golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.8-0.20211102182255-bb4add04ddef/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= golang.org/x/tools v0.1.8/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= golang.org/x/tools v0.1.9/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= -golang.org/x/tools v0.1.10 h1:QjFRCZxdOhBJ/UNgnBZLbNV13DlbnK0quyivTnXJM20= -golang.org/x/tools v0.1.10/go.mod h1:Uh6Zz+xoGYZom868N8YTex3t7RhtHDBrE8Gzo9bV56E= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20220411194840-2f41105eb62f h1:GGU+dLjvlC3qDwqYgL6UgRmHXhOOgns0bZu2Ty5mm6U= golang.org/x/xerrors v0.0.0-20220411194840-2f41105eb62f/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= From cfc3f825e2e3fe478440d2f1d684e681ff933c42 Mon Sep 17 00:00:00 2001 From: Adam Harvey Date: Thu, 14 Apr 2022 15:08:13 -0700 Subject: [PATCH 155/647] Add Bitbucket Cloud to the supported list (#725) --- CHANGELOG.md | 1 + internal/batches/features.go | 2 ++ internal/batches/service/service.go | 5 +++++ 3 files changed, 8 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7a1e09cb30..cb146dcca0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ All notable changes to `src-cli` are documented in this file. ### Added - `src lsif upload` now supports the `-gitlab-token` flag. [#721](https://github.com/sourcegraph/src-cli/pull/721) +- Batch Changes can be applied to Bitbucket Cloud when `src` is used with Sourcegraph 3.40 or later. [#725](https://github.com/sourcegraph/src-cli/pull/725) ### Changed diff --git a/internal/batches/features.go b/internal/batches/features.go index b0d1ff2156..c27e94596f 100644 --- a/internal/batches/features.go +++ b/internal/batches/features.go @@ -18,6 +18,7 @@ type FeatureFlags struct { AllowConditionalExec bool AllowOptionalPublished bool ServerSideBatchChanges bool + BitbucketCloud bool } func (ff *FeatureFlags) SetFromVersion(version string) error { @@ -42,6 +43,7 @@ func (ff *FeatureFlags) SetFromVersion(version string) error { {&ff.AllowConditionalExec, ">= 3.28.0-0", "2021-05-05"}, {&ff.AllowOptionalPublished, ">= 3.30.0-0", "2021-06-21"}, {&ff.ServerSideBatchChanges, ">= 3.37.0-0", "2022-02-08"}, + {&ff.BitbucketCloud, ">= 3.40.0-0", "2022-04-20"}, } { value, err := api.CheckSourcegraphVersion(version, feature.constraint, feature.minDate) if err != nil { diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index f89245e55b..865c6dac09 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -555,6 +555,11 @@ func (svc *Service) ResolveRepositories(ctx context.Context, spec *batcheslib.Ba switch st := strings.ToLower(repo.ExternalRepository.ServiceType); st { case "github", "gitlab", "bitbucketserver": + case "bitbucketcloud": + if svc.features.BitbucketCloud { + break + } + fallthrough default: if !svc.allowUnsupported { unsupported.Append(repo) From 4b807c6d00d5dfe5d367e16362c5eca273f76080 Mon Sep 17 00:00:00 2001 From: Bolaji Olajide <25608335+BolajiOlajide@users.noreply.github.com> Date: Wed, 20 Apr 2022 17:56:28 +0100 Subject: [PATCH 156/647] Fix Execution URL when using `src batch remote` (#730) * feat: surface namespace url for execution url * chore: rename namespace details to namespace * feat: display the name of the spec file (as batch change name) * feat: add url field to namespace query --- cmd/src/batch_common.go | 4 +-- cmd/src/batch_remote.go | 17 +++++++---- internal/batches/service/service.go | 46 ++++++++++++++++++++++------- 3 files changed, 49 insertions(+), 18 deletions(-) diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index 0ee98b9bb7..5ab5cf9b4d 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -298,7 +298,7 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp if err != nil { return err } - ui.ResolvingNamespaceSuccess(namespace) + ui.ResolvingNamespaceSuccess(namespace.ID) var workspaceCreator workspace.Creator @@ -441,7 +441,7 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp } ui.CreatingBatchSpec() - id, url, err := svc.CreateBatchSpec(ctx, namespace, rawSpec, ids) + id, url, err := svc.CreateBatchSpec(ctx, namespace.ID, rawSpec, ids) if err != nil { return ui.CreatingBatchSpecError(err) } diff --git a/cmd/src/batch_remote.go b/cmd/src/batch_remote.go index ef4e4e5e50..beeb8a25f2 100644 --- a/cmd/src/batch_remote.go +++ b/cmd/src/batch_remote.go @@ -63,7 +63,7 @@ Examples: // may as well validate it at the same time so we don't even have to go to // the backend if it's invalid. ui.ParsingBatchSpec() - _, raw, err := parseBatchSpec(file, svc) + spec, raw, err := parseBatchSpec(file, svc) if err != nil { ui.ParsingBatchSpecFailure(err) return err @@ -72,17 +72,17 @@ Examples: // We're going to need the namespace ID, so let's figure that out. ui.ResolvingNamespace() - namespaceID, err := svc.ResolveNamespace(ctx, flags.namespace) + namespace, err := svc.ResolveNamespace(ctx, flags.namespace) if err != nil { return err } - ui.ResolvingNamespaceSuccess(namespaceID) + ui.ResolvingNamespaceSuccess(namespace.ID) ui.SendingBatchSpec() batchSpecID, err := svc.UpsertBatchSpecInput( ctx, raw, - namespaceID, + namespace.ID, flags.allowIgnored, flags.allowUnsupported, flags.clearCache, @@ -121,7 +121,14 @@ Examples: } ui.ExecutingBatchSpecSuccess() - ui.RemoteSuccess(strings.TrimSuffix(cfg.Endpoint, "/") + "/batch-changes/executions/" + batchSpecID) + executionURL := fmt.Sprintf( + "%s/%s/batch-changes/%s/executions/%s", + strings.TrimSuffix(cfg.Endpoint, "/"), + strings.TrimPrefix(namespace.URL, "/"), + spec.Name, + batchSpecID, + ) + ui.RemoteSuccess(executionURL) return nil } diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index 865c6dac09..0a1af6f96d 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -463,10 +463,12 @@ const namespaceQuery = ` query NamespaceQuery($name: String!) { user(username: $name) { id + url } organization(name: $name) { id + url } } ` @@ -475,50 +477,72 @@ const usernameQuery = ` query GetCurrentUserID { currentUser { id + url } } ` -func (svc *Service) ResolveNamespace(ctx context.Context, namespace string) (string, error) { +type Namespace struct { + ID string + URL string +} + +func (svc *Service) ResolveNamespace(ctx context.Context, namespace string) (Namespace, error) { if namespace == "" { // if no namespace is provided, default to logged in user as namespace var resp struct { Data struct { CurrentUser struct { - ID string `json:"id"` + ID string `json:"id"` + URL string `json:"url"` } `json:"currentUser"` } `json:"data"` } if ok, err := svc.client.NewRequest(usernameQuery, nil).DoRaw(ctx, &resp); err != nil || !ok { - return "", errors.WithMessage(err, "failed to resolve namespace: no user logged in") + return Namespace{}, errors.WithMessage(err, "failed to resolve namespace: no user logged in") } if resp.Data.CurrentUser.ID == "" { - return "", errors.New("cannot resolve current user") + return Namespace{}, errors.New("cannot resolve current user") } - return resp.Data.CurrentUser.ID, nil + return Namespace{ + ID: resp.Data.CurrentUser.ID, + URL: resp.Data.CurrentUser.URL, + }, nil } var result struct { Data struct { - User *struct{ ID string } - Organization *struct{ ID string } + User *struct { + ID string + URL string + } + Organization *struct { + ID string + URL string + } } Errors []interface{} } if ok, err := svc.client.NewRequest(namespaceQuery, map[string]interface{}{ "name": namespace, }).DoRaw(ctx, &result); err != nil || !ok { - return "", err + return Namespace{}, err } if result.Data.User != nil { - return result.Data.User.ID, nil + return Namespace{ + ID: result.Data.User.ID, + URL: result.Data.User.URL, + }, nil } if result.Data.Organization != nil { - return result.Data.Organization.ID, nil + return Namespace{ + ID: result.Data.Organization.ID, + URL: result.Data.Organization.URL, + }, nil } - return "", fmt.Errorf("failed to resolve namespace %q: no user or organization found", namespace) + return Namespace{}, fmt.Errorf("failed to resolve namespace %q: no user or organization found", namespace) } func (svc *Service) ResolveRepositories(ctx context.Context, spec *batcheslib.BatchSpec) ([]*graphql.Repository, error) { From c5c6f214af228852f8994cbdb11ed5f0a4779245 Mon Sep 17 00:00:00 2001 From: Eric Fritz Date: Thu, 21 Apr 2022 18:59:51 -0500 Subject: [PATCH 157/647] lsif upload: Make better unauthorized error messages (#729) --- cmd/src/lsif_upload.go | 59 +++++++++++++++++++++++++++++++++++++----- 1 file changed, 53 insertions(+), 6 deletions(-) diff --git a/cmd/src/lsif_upload.go b/cmd/src/lsif_upload.go index 421705a4e3..f1b68b2158 100644 --- a/cmd/src/lsif_upload.go +++ b/cmd/src/lsif_upload.go @@ -219,18 +219,13 @@ func (e errorWithHint) Error() string { return fmt.Sprintf("%s\n\n%s\n", e.err, e.hint) } -var errUnauthorizedHint = strings.Join([]string{ - "You may need to specify or update your GitHub access token to use this endpoint.", - "See https://docs.sourcegraph.com/cli/references/lsif/upload.", -}, "\n") - // handleLSIFUploadError writes the given error to the given output. If the // given output object is nil then the error will be written to standard out. // // This method returns the error that should be passed back up to the runner. func handleLSIFUploadError(out *output.Output, err error) error { if err == upload.ErrUnauthorized { - err = errorWithHint{err: err, hint: errUnauthorizedHint} + err = filterLSIFUnauthorizedError(out, err) } if lsifUploadFlags.ignoreUploadFailures { @@ -242,7 +237,59 @@ func handleLSIFUploadError(out *output.Output, err error) error { return err } +func filterLSIFUnauthorizedError(out *output.Output, err error) error { + var actionableHints []string + needsGitHubToken := strings.HasPrefix(lsifUploadFlags.repo, "github.com") + needsGitLabToken := strings.HasPrefix(lsifUploadFlags.repo, "gitlab.com") + + if needsGitHubToken { + if lsifUploadFlags.gitHubToken != "" { + actionableHints = append(actionableHints, + fmt.Sprintf("The supplied -github-token does not indicate that you have collaborator access to %s.", lsifUploadFlags.repo), + "Please check the value of the supplied token and its permissions on the code host and try again.", + ) + } else { + actionableHints = append(actionableHints, + fmt.Sprintf("Please retry your request with a -github-token=XXX with with collaborator access to %s.", lsifUploadFlags.repo), + "This token will be used to check with the code host that the uploading user has write access to the target repository.", + ) + } + } else if needsGitLabToken { + if lsifUploadFlags.gitLabToken != "" { + actionableHints = append(actionableHints, + fmt.Sprintf("The supplied -gitlab-token does not indicate that you have write access to %s.", lsifUploadFlags.repo), + "Please check the value of the supplied token and its permissions on the code host and try again.", + ) + } else { + actionableHints = append(actionableHints, + fmt.Sprintf("Please retry your request with a -gitlab-token=XXX with with write access to %s.", lsifUploadFlags.repo), + "This token will be used to check with the code host that the uploading user has write access to the target repository.", + ) + } + } else { + actionableHints = append(actionableHints, + "Verification is supported for the following code hosts: github.com, gitlab.com.", + "Please request support for additional code host verification at https://github.com/sourcegraph/sourcegraph/issues/4967.", + ) + } + + return errorWithHint{err: err, hint: strings.Join(mergeStringSlices( + []string{"This Sourcegraph instance has enforced auth for LSIF uploads."}, + actionableHints, + []string{"For more details, see https://docs.sourcegraph.com/cli/references/lsif/upload."}, + ), "\n")} +} + // emergencyOutput creates a default Output object writing to standard out. func emergencyOutput() *output.Output { return output.NewOutput(os.Stdout, output.OutputOpts{}) } + +func mergeStringSlices(ss ...[]string) []string { + var combined []string + for _, s := range ss { + combined = append(combined, s...) + } + + return combined +} From a12e88eb2281f641ed072feebd2fbccb1096fa81 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=93lafur=20P=C3=A1ll=20Geirsson?= Date: Thu, 28 Apr 2022 10:56:50 +0200 Subject: [PATCH 158/647] Add support for LSIF Typed (#732) * Add support for LSIF Typed Running `src lsif upload` now converts LSIF Typed into LSIF Graph in the following scenarios: - When the provided `-file` flag matches the file extension ".lsif-typed" - When the provided `-file` flag points to a non-existent file, while the sibling `*.lsif-typed` file exists. Fixes https://github.com/sourcegraph/sourcegraph/issues/27405 * Fix ordering of how we initialize `*output.Output` * Add test cases for `handleLSIFTyped` function. * Remove redundant blank line * Use `t.TempDir()` to create temporary directory --- cmd/src/lsif_upload.go | 19 +----- cmd/src/lsif_upload_flags.go | 98 +++++++++++++++++++++++++++++-- cmd/src/lsif_upload_flags_test.go | 77 ++++++++++++++++++++++++ go.mod | 1 + go.sum | 1 + 5 files changed, 172 insertions(+), 24 deletions(-) create mode 100644 cmd/src/lsif_upload_flags_test.go diff --git a/cmd/src/lsif_upload.go b/cmd/src/lsif_upload.go index f1b68b2158..6a751dba45 100644 --- a/cmd/src/lsif_upload.go +++ b/cmd/src/lsif_upload.go @@ -57,8 +57,7 @@ Examples: func handleLSIFUpload(args []string) error { ctx := context.Background() - err := parseAndValidateLSIFUploadFlags(args) - out := lsifUploadOutput() + out, err := parseAndValidateLSIFUploadFlags(args) if !lsifUploadFlags.json { if out != nil { printInferredArguments(out) @@ -119,22 +118,6 @@ func handleLSIFUpload(args []string) error { return nil } -// lsifUploadOutput returns an output object that should be used to print the progres -// of requests made during this upload. If -json, -no-progress, or -trace>0 is given, -// then no output object is defined. -// -// For -no-progress and -trace>0 conditions, emergency loggers will be used to display -// inferred arguments and the URL at which processing status is shown. -func lsifUploadOutput() (out *output.Output) { - if lsifUploadFlags.json || lsifUploadFlags.noProgress || lsifUploadFlags.verbosity > 0 { - return nil - } - - return output.NewOutput(flag.CommandLine.Output(), output.OutputOpts{ - Verbose: true, - }) -} - // lsifUploadOptions creates a set of upload options given the values in the flags. func lsifUploadOptions(out *output.Output) upload.UploadOptions { var associatedIndexID *int diff --git a/cmd/src/lsif_upload_flags.go b/cmd/src/lsif_upload_flags.go index da740a02b5..43f11cf813 100644 --- a/cmd/src/lsif_upload_flags.go +++ b/cmd/src/lsif_upload_flags.go @@ -7,7 +7,11 @@ import ( "strings" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/output" + "google.golang.org/protobuf/proto" + "github.com/sourcegraph/sourcegraph/lib/codeintel/lsif/protocol/reader" + "github.com/sourcegraph/sourcegraph/lib/codeintel/lsiftyped" "github.com/sourcegraph/sourcegraph/lib/codeintel/upload" "github.com/sourcegraph/src-cli/internal/api" @@ -84,11 +88,13 @@ func init() { // // On success, the global lsifUploadFlags object will be populated with valid values. An // error is returned on failure. -func parseAndValidateLSIFUploadFlags(args []string) error { +func parseAndValidateLSIFUploadFlags(args []string) (*output.Output, error) { if err := lsifUploadFlagSet.Parse(args); err != nil { - return err + return nil, err } + out := lsifUploadOutput() + // extract only the -insecure-skip-verify flag so we dont get 'flag provided but not defined' var insecureSkipVerifyFlag []string for _, s := range args { @@ -102,11 +108,15 @@ func parseAndValidateLSIFUploadFlags(args []string) error { // and maybe we'll use some in the future lsifUploadFlags.apiFlags = api.NewFlags(apiClientFlagSet) if err := apiClientFlagSet.Parse(insecureSkipVerifyFlag); err != nil { - return err + return nil, err + } + + if err := handleLSIFTyped(out); err != nil { + return nil, err } if inferenceErrors := inferMissingLSIFUploadFlags(); len(inferenceErrors) > 0 { - return errorWithHint{ + return nil, errorWithHint{ err: inferenceErrors[0].err, hint: strings.Join([]string{ fmt.Sprintf( "Unable to determine %s from environment. Check your working directory or supply -%s={value} explicitly", @@ -118,10 +128,26 @@ func parseAndValidateLSIFUploadFlags(args []string) error { } if err := validateLSIFUploadFlags(); err != nil { - return err + return nil, err } - return nil + return out, nil +} + +// lsifUploadOutput returns an output object that should be used to print the progres +// of requests made during this upload. If -json, -no-progress, or -trace>0 is given, +// then no output object is defined. +// +// For -no-progress and -trace>0 conditions, emergency loggers will be used to display +// inferred arguments and the URL at which processing status is shown. +func lsifUploadOutput() (out *output.Output) { + if lsifUploadFlags.json || lsifUploadFlags.noProgress || lsifUploadFlags.verbosity > 0 { + return nil + } + + return output.NewOutput(flag.CommandLine.Output(), output.OutputOpts{ + Verbose: true, + }) } type argumentInferenceError struct { @@ -129,6 +155,66 @@ type argumentInferenceError struct { err error } +func handleLSIFTyped(out *output.Output) error { + if strings.HasSuffix(lsifUploadFlags.file, ".lsif-typed") { + // The user explicitly passed in a -file flag that points to an LSIF Typed index. + inputFile := lsifUploadFlags.file + outputFile := strings.TrimSuffix(inputFile, "-typed") + lsifUploadFlags.file = outputFile + return convertLSIFTypedToLSIFGraph(out, inputFile, outputFile) + } + + if _, err := os.Stat(lsifUploadFlags.file); err == nil { + // Do nothing, the provided -flag flag points to an existing + // file that does not have the file extension `*.lsif-typed`. + return nil + } + + lsifTypedFile := lsifUploadFlags.file + "-typed" + if _, err := os.Stat(lsifTypedFile); os.IsNotExist(err) { + // The inferred path of the sibling `*.lsif-typed` file does not exist. + return nil + } + + // The provided -file flag points to an `*.lsif` file that doesn't exist + // so we convert the sibling `*.lsif-typed` file (which we confirmed exists). + return convertLSIFTypedToLSIFGraph(out, lsifTypedFile, lsifUploadFlags.file) +} + +// Reads the LSIF Typed encoded input file and writes the corresponding LSIF +// Graph encoded output file. +func convertLSIFTypedToLSIFGraph(out *output.Output, inputFile, outputFile string) error { + out.Writef("%s Converting %s into %s", output.EmojiInfo, inputFile, outputFile) + tmp, err := os.Create(outputFile) + if err != nil { + return err + } + defer tmp.Close() + + data, err := os.ReadFile(inputFile) + if err != nil { + panic(err) + } + index := lsiftyped.Index{} + err = proto.Unmarshal(data, &index) + if err != nil { + panic(errors.Wrapf(err, "failed to parse protobuf file '%s'", inputFile)) + } + els, err := reader.ConvertTypedIndexToGraphIndex(&index) + if err != nil { + panic(errors.Wrapf(err, "failed reader.ConvertTypedIndexToGraphIndex")) + } + err = reader.WriteNDJSON(reader.ElementsToJsonElements(els), tmp) + if err != nil { + panic(err) + } + err = tmp.Close() + if err != nil { + return err + } + return nil +} + // inferMissingLSIFUploadFlags updates the flags values which were not explicitly // supplied by the user with default values inferred from the current git state and // filesystem. diff --git a/cmd/src/lsif_upload_flags_test.go b/cmd/src/lsif_upload_flags_test.go new file mode 100644 index 0000000000..3d242532d5 --- /dev/null +++ b/cmd/src/lsif_upload_flags_test.go @@ -0,0 +1,77 @@ +package main + +import ( + "os" + "path/filepath" + "testing" + + "github.com/sourcegraph/sourcegraph/lib/codeintel/lsiftyped" + "google.golang.org/protobuf/proto" +) + +var exampleLsifTypedIndex = lsiftyped.Index{ + Metadata: &lsiftyped.Metadata{ + TextDocumentEncoding: lsiftyped.TextEncoding_UTF8, + ToolInfo: &lsiftyped.ToolInfo{ + Name: "hello", + Version: "1.0.0", + }, + }, +} + +var exampleLsifGraphString = `{"id":1,"version":"0.4.3","positionEncoding":"utf-8","toolInfo":{"name":"hello","version":"1.0.0"},"type":"vertex","label":"metaData"} +` + +func exampleLsifTypedBytes(t *testing.T) []byte { + bytes, err := proto.Marshal(&exampleLsifTypedIndex) + if err != nil { + t.Fatal(err) + } + return bytes +} + +func createTempLsifTypedFile(t *testing.T) (typedFile, graphFile string) { + dir := t.TempDir() + typedFile = filepath.Join(dir, "dump.lsif-typed") + graphFile = filepath.Join(dir, "dump.lsif") + err := os.WriteFile(typedFile, exampleLsifTypedBytes(t), 0755) + if err != nil { + t.Fatal(err) + } + return typedFile, graphFile +} + +func assertLsifGraphOutput(t *testing.T, lsifGraphFile, expectedGraphString string) { + out := lsifUploadOutput() + handleLSIFTyped(out) + lsifGraph, err := os.ReadFile(lsifGraphFile) + if err != nil { + t.Fatal(err) + } + obtained := string(lsifGraph) + if obtained != expectedGraphString { + t.Fatalf("unexpected LSIF output %s", obtained) + } + if lsifGraphFile != lsifUploadFlags.file { + t.Fatalf("unexpected lsifUploadFlag.file value %s, expected %s", lsifUploadFlags.file, lsifGraphFile) + } +} + +func TestImplicitlyConvertLsifTypedIntoGraph(t *testing.T) { + _, graphFile := createTempLsifTypedFile(t) + lsifUploadFlags.file = graphFile + assertLsifGraphOutput(t, graphFile, exampleLsifGraphString) +} + +func TestImplicitlyIgnoreLsifTyped(t *testing.T) { + _, graphFile := createTempLsifTypedFile(t) + lsifUploadFlags.file = graphFile + os.WriteFile(graphFile, []byte("hello world"), 0755) + assertLsifGraphOutput(t, graphFile, "hello world") +} + +func TestExplicitlyConvertLsifTypedIntoGraph(t *testing.T) { + typedFile, graphFile := createTempLsifTypedFile(t) + lsifUploadFlags.file = typedFile + assertLsifGraphOutput(t, graphFile, exampleLsifGraphString) +} diff --git a/go.mod b/go.mod index 0b8f2dd5fe..68dddd67eb 100644 --- a/go.mod +++ b/go.mod @@ -22,6 +22,7 @@ require ( github.com/sourcegraph/sourcegraph/lib v0.0.0-20220414150621-eeb00fcedd88 github.com/stretchr/testify v1.7.1 golang.org/x/net v0.0.0-20220325170049-de3da57026de + google.golang.org/protobuf v1.27.1 gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7 ) diff --git a/go.sum b/go.sum index 5146c29f95..e425d5c6a5 100644 --- a/go.sum +++ b/go.sum @@ -491,6 +491,7 @@ google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpAD google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +google.golang.org/protobuf v1.27.1 h1:SnqbnDw1V7RiZcXPx5MEeqPv2s79L9i7BJUlG/+RurQ= google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= From bada7024de084ec9d5e613cd3339e2ab403c3f04 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=93lafur=20P=C3=A1ll=20Geirsson?= Date: Mon, 2 May 2022 13:14:49 +0200 Subject: [PATCH 159/647] Handle nil output when writing progress message (#735) Previously, the command `src lsif upload -no-progress` failed with a nil panic when using LSIF Typed. I was tempted to refactor the code so that `output` cannot be nil but decided not to in order to keep the diff small and focused on fixing the panic. --- cmd/src/lsif_upload_flags.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/cmd/src/lsif_upload_flags.go b/cmd/src/lsif_upload_flags.go index 43f11cf813..b69cbc7726 100644 --- a/cmd/src/lsif_upload_flags.go +++ b/cmd/src/lsif_upload_flags.go @@ -184,7 +184,9 @@ func handleLSIFTyped(out *output.Output) error { // Reads the LSIF Typed encoded input file and writes the corresponding LSIF // Graph encoded output file. func convertLSIFTypedToLSIFGraph(out *output.Output, inputFile, outputFile string) error { - out.Writef("%s Converting %s into %s", output.EmojiInfo, inputFile, outputFile) + if out != nil { + out.Writef("%s Converting %s into %s", output.EmojiInfo, inputFile, outputFile) + } tmp, err := os.Create(outputFile) if err != nil { return err From 4cadc4118e2b0bf4899102912fc49f24b7efe72c Mon Sep 17 00:00:00 2001 From: Varun Gandhi Date: Tue, 3 May 2022 14:49:30 -0700 Subject: [PATCH 160/647] Remove TODO from flag docs (#737) --- cmd/src/lsif_upload_flags.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/src/lsif_upload_flags.go b/cmd/src/lsif_upload_flags.go index b69cbc7726..4e27121d0b 100644 --- a/cmd/src/lsif_upload_flags.go +++ b/cmd/src/lsif_upload_flags.go @@ -71,7 +71,7 @@ func init() { // Codehost authorization secrets lsifUploadFlagSet.StringVar(&lsifUploadFlags.gitHubToken, "github-token", "", `A GitHub access token with 'public_repo' scope that Sourcegraph uses to verify you have access to the repository.`) - lsifUploadFlagSet.StringVar(&lsifUploadFlags.gitLabToken, "gitlab-token", "", `A GitLab access token with TODO that Sourcegraph uses to verify you have access to the repository.`) + lsifUploadFlagSet.StringVar(&lsifUploadFlags.gitLabToken, "gitlab-token", "", `A GitLab access token with 'read_api' scope that Sourcegraph uses to verify you have access to the repository.`) // Output and error behavior lsifUploadFlagSet.BoolVar(&lsifUploadFlags.ignoreUploadFailures, "ignore-upload-failure", false, `Exit with status code zero on upload failure.`) From 9b1b616add81e484eca85f283c27ec4d79364e8c Mon Sep 17 00:00:00 2001 From: adeola <67931373+adeola-ak@users.noreply.github.com> Date: Fri, 6 May 2022 09:22:17 -0400 Subject: [PATCH 161/647] batches: clarify on.repository error message when for incorrect repo path (#736) * clarify error message when no repo found * clarify error message when no repo found * Empty-Commit * remove space * change error wording * add second format option to error * upgrade version of go lib package --- go.mod | 12 +++++++++-- go.sum | 32 +++++++++++++++++++++++++++++ internal/batches/service/service.go | 4 ++-- 3 files changed, 44 insertions(+), 4 deletions(-) diff --git a/go.mod b/go.mod index 68dddd67eb..c7805c11a9 100644 --- a/go.mod +++ b/go.mod @@ -19,7 +19,7 @@ require ( github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4 github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf - github.com/sourcegraph/sourcegraph/lib v0.0.0-20220414150621-eeb00fcedd88 + github.com/sourcegraph/sourcegraph/lib v0.0.0-20220506010657-06e02488a3d7 github.com/stretchr/testify v1.7.1 golang.org/x/net v0.0.0-20220325170049-de3da57026de google.golang.org/protobuf v1.27.1 @@ -29,10 +29,15 @@ require ( require ( github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect + github.com/alecthomas/kingpin v2.2.6+incompatible // indirect + github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751 // indirect + github.com/alecthomas/units v0.0.0-20211218093645-b94a6e3cc137 // indirect github.com/cockroachdb/errors v1.8.9 // indirect github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f // indirect github.com/cockroachdb/redact v1.1.3 // indirect + github.com/dave/jennifer v1.5.0 // indirect github.com/davecgh/go-spew v1.1.1 // indirect + github.com/derision-test/go-mockgen v1.2.0 // indirect github.com/getsentry/sentry-go v0.12.0 // indirect github.com/ghodss/yaml v1.0.0 // indirect github.com/go-stack/stack v1.8.1 // indirect @@ -44,6 +49,7 @@ require ( github.com/kr/text v0.2.0 // indirect github.com/mattn/go-colorable v0.1.12 // indirect github.com/mattn/go-runewidth v0.0.13 // indirect + github.com/mitchellh/go-wordwrap v1.0.1 // indirect github.com/moby/term v0.0.0-20210619224110-3f7ff695adc6 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect @@ -56,8 +62,10 @@ require ( github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect github.com/xeipuuv/gojsonschema v1.2.0 // indirect + golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3 // indirect golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect - golang.org/x/sys v0.0.0-20220412211240-33da011f77ad // indirect + golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6 // indirect + golang.org/x/tools v0.1.10 // indirect golang.org/x/xerrors v0.0.0-20220411194840-2f41105eb62f // indirect gopkg.in/yaml.v2 v2.4.0 // indirect ) diff --git a/go.sum b/go.sum index e425d5c6a5..9110c76284 100644 --- a/go.sum +++ b/go.sum @@ -13,12 +13,16 @@ github.com/Masterminds/semver v1.5.0 h1:H65muMkzWKEuNDnfl9d70GUjFniHKHRbFPGBuZ3Q github.com/Masterminds/semver v1.5.0/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y= github.com/Shopify/goreferrer v0.0.0-20181106222321-ec9c9a553398/go.mod h1:a1uqRtAwp2Xwc6WNPJEufxJ7fx3npB4UV/JOLmbu5I0= github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY= +github.com/alecthomas/kingpin v2.2.6+incompatible h1:5svnBTFgJjZvGKyYBtMB0+m5wvrbUHiqye8wRJMlnYI= github.com/alecthomas/kingpin v2.2.6+incompatible/go.mod h1:59OFYbFVLKQKq+mqrL6Rw5bR0c3ACQaawgXx0QYndlE= +github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751 h1:JYp7IbQjafoB+tBA3gMyHYHrpOtNuDiK/uB5uXxq5wM= github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/units v0.0.0-20210208195552-ff826a37aa15/go.mod h1:OMCwj8VM1Kc9e19TLln2VL61YJF0x1XFtfdL4JdbSyE= +github.com/alecthomas/units v0.0.0-20211218093645-b94a6e3cc137 h1:s6gZFSlWYmbqAuRjVTiNNhvNRfY2Wxp9nhfyel4rklc= github.com/alecthomas/units v0.0.0-20211218093645-b94a6e3cc137/go.mod h1:OMCwj8VM1Kc9e19TLln2VL61YJF0x1XFtfdL4JdbSyE= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= github.com/aymerick/raymond v2.0.3-0.20180322193309-b565731e1464+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g= +github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= @@ -45,13 +49,24 @@ github.com/creack/goselect v0.1.2/go.mod h1:a/NhLweNvqIYMuxcMOuWY516Cimucms3DglD github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/creack/pty v1.1.11 h1:07n33Z8lZxZ2qwegKbObQohDhXDQxiMMz1NOUGYlesw= github.com/creack/pty v1.1.11/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/dave/astrid v0.0.0-20170323122508-8c2895878b14/go.mod h1:Sth2QfxfATb/nW4EsrSi2KyJmbcniZ8TgTaji17D6ms= +github.com/dave/brenda v1.1.0/go.mod h1:4wCUr6gSlu5/1Tk7akE5X7UorwiQ8Rij0SKH3/BGMOM= +github.com/dave/courtney v0.3.0/go.mod h1:BAv3hA06AYfNUjfjQr+5gc6vxeBVOupLqrColj+QSD8= +github.com/dave/gopackages v0.0.0-20170318123100-46e7023ec56e/go.mod h1:i00+b/gKdIDIxuLDFob7ustLAVqhsZRk2qVZrArELGQ= github.com/dave/jennifer v1.4.1/go.mod h1:7jEdnm+qBcxl8PC0zyp7vxcpSRnzXSt9r39tpTVGlwA= +github.com/dave/jennifer v1.5.0 h1:HmgPN93bVDpkQyYbqhCHj5QlgvUkvEOzMyEvKLgCRrg= +github.com/dave/jennifer v1.5.0/go.mod h1:4MnyiFIlZS3l5tSDn8VnzE6ffAhYBMB2SZntBsZGUok= +github.com/dave/kerr v0.0.0-20170318121727-bc25dd6abe8e/go.mod h1:qZqlPyPvfsDJt+3wHJ1EvSXDuVjFTK0j2p/ca+gtsb8= +github.com/dave/patsy v0.0.0-20210517141501-957256f50cba/go.mod h1:qfR88CgEGLoiqDaE+xxDCi5QA5v4vUoW0UCX2Nd5Tlc= +github.com/dave/rebecca v0.9.1/go.mod h1:N6XYdMD/OKw3lkF3ywh8Z6wPGuwNFDNtWYEMFWEmXBA= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/derision-test/glock v0.0.0-20210316032053-f5b74334bb29 h1:O07j7ewg0eFHRx+7bxCA/7z86HJexl7HLY9kyVMmPDo= github.com/derision-test/glock v0.0.0-20210316032053-f5b74334bb29/go.mod h1:jKtLdBMrF+XQatqvg46wiWdDfDSSDjdhO4dOM2FX9H4= github.com/derision-test/go-mockgen v1.1.2/go.mod h1:9H3VGTWYnL1VJoHHCuPKDpPFmNQ1uVyNlpX6P63l5Sk= +github.com/derision-test/go-mockgen v1.2.0 h1:SCF7p4FuO6IZId3CMjSHH9K0SMDVXNz7jc3AOeJaBd8= +github.com/derision-test/go-mockgen v1.2.0/go.mod h1:/TXUePlhtHmDDCaDAi/a4g6xOHqMDz3Wf0r2NPGskB4= github.com/dgraph-io/badger v1.6.0/go.mod h1:zwt7syl517jmP8s94KqSxTlM6IMsdhYy6psNgSztDR4= github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= @@ -128,6 +143,7 @@ github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8 github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= @@ -221,6 +237,7 @@ github.com/microcosm-cc/bluemonday v1.0.2/go.mod h1:iVP4YcDBq+n/5fb23BhYFvIMq/le github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw= github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= +github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0= github.com/mitchellh/go-wordwrap v1.0.1/go.mod h1:R62XHJLzvMFRBbcrT7m7WgmE1eOyTSsCt+hzestvNj0= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ= @@ -294,6 +311,8 @@ github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWii github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= github.com/sourcegraph/sourcegraph/lib v0.0.0-20220414150621-eeb00fcedd88 h1:xqMUhhlrIFJRsb4EodMR5aWZpTY0rdukgVR8yV2mz7w= github.com/sourcegraph/sourcegraph/lib v0.0.0-20220414150621-eeb00fcedd88/go.mod h1:6/o2uP/pgAIyAZWqHeZF4J9F8rfWvkU3BRqVLWpLwTA= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20220506010657-06e02488a3d7 h1:YgPugK3f2y4cEfPH+Tb45yYymSTCZAaZ2nAQO81EZU4= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20220506010657-06e02488a3d7/go.mod h1:nuweF6uGn0mCNzMAbCiLbje6MkZwUmhXaFA4w30/ZfU= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= @@ -339,6 +358,10 @@ github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9de github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= +go.uber.org/goleak v1.1.11/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ= +go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= +go.uber.org/zap v1.21.0/go.mod h1:wjWOCqI0f2ZZrJF/UufIOkiC8ii6tm1iqIsLo76RfJw= golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= @@ -351,6 +374,7 @@ golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/lint v0.0.0-20210508222113-6edffad5e616/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= @@ -359,6 +383,8 @@ golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro= +golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3 h1:kQgndtyPBW/JIYERgdxfwMYh3AVStj88WQTlNDi2a+o= +golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3/go.mod h1:3p9vT2HGsQu2K1YbXdKPJLVgG5VJdoTa1poYQBtP1AY= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -429,6 +455,8 @@ golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220412211240-33da011f77ad h1:ntjMns5wyP/fN65tdBD4g8J5w8n015+iIIs9rtjXkY0= golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6 h1:nonptSpoQ4vQjyraW20DXPAglgQfVnM9ZC6MmNLMR60= +golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -457,9 +485,12 @@ golang.org/x/tools v0.0.0-20210101214203-2dba1e4ea05c/go.mod h1:emZCQorbCU4vsT4f golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.8-0.20211102182255-bb4add04ddef/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= golang.org/x/tools v0.1.8/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= golang.org/x/tools v0.1.9/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= +golang.org/x/tools v0.1.10 h1:QjFRCZxdOhBJ/UNgnBZLbNV13DlbnK0quyivTnXJM20= +golang.org/x/tools v0.1.10/go.mod h1:Uh6Zz+xoGYZom868N8YTex3t7RhtHDBrE8Gzo9bV56E= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -506,6 +537,7 @@ gopkg.in/mgo.v2 v2.0.0-20180705113604-9856a29383ce/go.mod h1:yeKp02qBN3iKW1OzL3M gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index 0a1af6f96d..6e155f77c0 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -554,7 +554,7 @@ func (svc *Service) ResolveRepositories(ctx context.Context, spec *batcheslib.Ba for _, on := range spec.On { repos, ruleType, err := svc.ResolveRepositoriesOn(ctx, &on) if err != nil { - return nil, errors.Wrapf(err, "resolving %q", on.String()) + return nil, errors.Wrapf(err, on.String()) } result := agg.NewRuleRevisions(ruleType) @@ -671,7 +671,7 @@ func (svc *Service) resolveRepositoryName(ctx context.Context, name string) (*gr return nil, err } if result.Repository == nil { - return nil, errors.New("no repository found") + return nil, errors.New("no repository found: check spelling and specify the repository in the format \"/owner/repo-name\" or \"repo-name\" as required by your instance") } return result.Repository, nil } From f6ade94b81aeed6cf0b77652d2ee932bc483651f Mon Sep 17 00:00:00 2001 From: Keegan Carruthers-Smith Date: Mon, 9 May 2022 09:37:34 +0200 Subject: [PATCH 162/647] all: use go1.18 (#740) Updates CI and gomod to enforce the minimum version to go1.18. This is what we are using in the main sourcegraph repository. I want to do the same for sourcegraph/lib, so want to ensure its main importer can import go1.18 code. Test Plan: go test ./... and CI --- .github/workflows/go-ci.yml | 2 +- .github/workflows/go-lint.yml | 2 +- .github/workflows/goreleaser-check.yml | 2 +- .github/workflows/goreleaser.yml | 2 +- .github/workflows/pr-auditor.yml | 2 +- cmd/src/search.go | 2 +- dev/golangci-lint.sh | 2 +- go.mod | 10 +--------- go.sum | 25 ------------------------- 9 files changed, 8 insertions(+), 41 deletions(-) diff --git a/.github/workflows/go-ci.yml b/.github/workflows/go-ci.yml index 29b606f2cf..5f5f19d1fa 100644 --- a/.github/workflows/go-ci.yml +++ b/.github/workflows/go-ci.yml @@ -7,7 +7,7 @@ jobs: go-test: strategy: matrix: - go-version: [1.17.x] + go-version: [1.18.x] os: [ubuntu-latest, macos-latest, windows-latest] runs-on: ${{ matrix.os }} steps: diff --git a/.github/workflows/go-lint.yml b/.github/workflows/go-lint.yml index 80535db3a0..cb1accdbe3 100644 --- a/.github/workflows/go-lint.yml +++ b/.github/workflows/go-lint.yml @@ -12,5 +12,5 @@ jobs: - name: Set up Go uses: actions/setup-go@v3 with: - go-version: 1.17.x + go-version: 1.18.x - run: ./dev/go-lint.sh diff --git a/.github/workflows/goreleaser-check.yml b/.github/workflows/goreleaser-check.yml index b91c85159c..d5723607a0 100644 --- a/.github/workflows/goreleaser-check.yml +++ b/.github/workflows/goreleaser-check.yml @@ -15,7 +15,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v3 with: - go-version: 1.17 + go-version: 1.18 - name: Check GoReleaser config uses: goreleaser/goreleaser-action@v2 with: diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index 068ff9e139..2de67d0590 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -18,7 +18,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v3 with: - go-version: 1.17 + go-version: 1.18 - run: go get -d -t ./... - run: go test -i ./... - run: go test -race -v ./... diff --git a/.github/workflows/pr-auditor.yml b/.github/workflows/pr-auditor.yml index a94f500339..34c7412864 100644 --- a/.github/workflows/pr-auditor.yml +++ b/.github/workflows/pr-auditor.yml @@ -10,7 +10,7 @@ jobs: - uses: actions/checkout@v3 with: { repository: 'sourcegraph/sourcegraph' } - uses: actions/setup-go@v3 - with: { go-version: '1.17' } + with: { go-version: '1.18' } - run: ./dev/pr-auditor/check-pr.sh env: diff --git a/cmd/src/search.go b/cmd/src/search.go index 5fead67d5e..1a69916019 100644 --- a/cmd/src/search.go +++ b/cmd/src/search.go @@ -83,7 +83,7 @@ Other tips: } if *explainJSONFlag { - fmt.Println(searchJSONExplanation) + fmt.Printf("%s\n", searchJSONExplanation) return nil } diff --git a/dev/golangci-lint.sh b/dev/golangci-lint.sh index 728e45fd48..97d8d8afcd 100755 --- a/dev/golangci-lint.sh +++ b/dev/golangci-lint.sh @@ -6,7 +6,7 @@ pushd "$(dirname "${BASH_SOURCE[0]}")/.." >/dev/null mkdir -p dev/.bin -version="1.37.1" +version="1.45.2" suffix="${version}-$(go env GOOS)-$(go env GOARCH)" target="$PWD/dev/.bin/golangci-lint-${suffix}" url="https://github.com/golangci/golangci-lint/releases/download/v${version}/golangci-lint-${suffix}.tar.gz" diff --git a/go.mod b/go.mod index c7805c11a9..0fc2782086 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/sourcegraph/src-cli -go 1.17 +go 1.18 require ( github.com/Masterminds/semver v1.5.0 @@ -29,15 +29,10 @@ require ( require ( github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect - github.com/alecthomas/kingpin v2.2.6+incompatible // indirect - github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751 // indirect - github.com/alecthomas/units v0.0.0-20211218093645-b94a6e3cc137 // indirect github.com/cockroachdb/errors v1.8.9 // indirect github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f // indirect github.com/cockroachdb/redact v1.1.3 // indirect - github.com/dave/jennifer v1.5.0 // indirect github.com/davecgh/go-spew v1.1.1 // indirect - github.com/derision-test/go-mockgen v1.2.0 // indirect github.com/getsentry/sentry-go v0.12.0 // indirect github.com/ghodss/yaml v1.0.0 // indirect github.com/go-stack/stack v1.8.1 // indirect @@ -49,7 +44,6 @@ require ( github.com/kr/text v0.2.0 // indirect github.com/mattn/go-colorable v0.1.12 // indirect github.com/mattn/go-runewidth v0.0.13 // indirect - github.com/mitchellh/go-wordwrap v1.0.1 // indirect github.com/moby/term v0.0.0-20210619224110-3f7ff695adc6 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect @@ -62,10 +56,8 @@ require ( github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect github.com/xeipuuv/gojsonschema v1.2.0 // indirect - golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3 // indirect golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6 // indirect - golang.org/x/tools v0.1.10 // indirect golang.org/x/xerrors v0.0.0-20220411194840-2f41105eb62f // indirect gopkg.in/yaml.v2 v2.4.0 // indirect ) diff --git a/go.sum b/go.sum index 9110c76284..882a77b422 100644 --- a/go.sum +++ b/go.sum @@ -13,12 +13,9 @@ github.com/Masterminds/semver v1.5.0 h1:H65muMkzWKEuNDnfl9d70GUjFniHKHRbFPGBuZ3Q github.com/Masterminds/semver v1.5.0/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y= github.com/Shopify/goreferrer v0.0.0-20181106222321-ec9c9a553398/go.mod h1:a1uqRtAwp2Xwc6WNPJEufxJ7fx3npB4UV/JOLmbu5I0= github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY= -github.com/alecthomas/kingpin v2.2.6+incompatible h1:5svnBTFgJjZvGKyYBtMB0+m5wvrbUHiqye8wRJMlnYI= github.com/alecthomas/kingpin v2.2.6+incompatible/go.mod h1:59OFYbFVLKQKq+mqrL6Rw5bR0c3ACQaawgXx0QYndlE= -github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751 h1:JYp7IbQjafoB+tBA3gMyHYHrpOtNuDiK/uB5uXxq5wM= github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/units v0.0.0-20210208195552-ff826a37aa15/go.mod h1:OMCwj8VM1Kc9e19TLln2VL61YJF0x1XFtfdL4JdbSyE= -github.com/alecthomas/units v0.0.0-20211218093645-b94a6e3cc137 h1:s6gZFSlWYmbqAuRjVTiNNhvNRfY2Wxp9nhfyel4rklc= github.com/alecthomas/units v0.0.0-20211218093645-b94a6e3cc137/go.mod h1:OMCwj8VM1Kc9e19TLln2VL61YJF0x1XFtfdL4JdbSyE= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= github.com/aymerick/raymond v2.0.3-0.20180322193309-b565731e1464+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g= @@ -49,24 +46,13 @@ github.com/creack/goselect v0.1.2/go.mod h1:a/NhLweNvqIYMuxcMOuWY516Cimucms3DglD github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/creack/pty v1.1.11 h1:07n33Z8lZxZ2qwegKbObQohDhXDQxiMMz1NOUGYlesw= github.com/creack/pty v1.1.11/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= -github.com/dave/astrid v0.0.0-20170323122508-8c2895878b14/go.mod h1:Sth2QfxfATb/nW4EsrSi2KyJmbcniZ8TgTaji17D6ms= -github.com/dave/brenda v1.1.0/go.mod h1:4wCUr6gSlu5/1Tk7akE5X7UorwiQ8Rij0SKH3/BGMOM= -github.com/dave/courtney v0.3.0/go.mod h1:BAv3hA06AYfNUjfjQr+5gc6vxeBVOupLqrColj+QSD8= -github.com/dave/gopackages v0.0.0-20170318123100-46e7023ec56e/go.mod h1:i00+b/gKdIDIxuLDFob7ustLAVqhsZRk2qVZrArELGQ= github.com/dave/jennifer v1.4.1/go.mod h1:7jEdnm+qBcxl8PC0zyp7vxcpSRnzXSt9r39tpTVGlwA= -github.com/dave/jennifer v1.5.0 h1:HmgPN93bVDpkQyYbqhCHj5QlgvUkvEOzMyEvKLgCRrg= -github.com/dave/jennifer v1.5.0/go.mod h1:4MnyiFIlZS3l5tSDn8VnzE6ffAhYBMB2SZntBsZGUok= -github.com/dave/kerr v0.0.0-20170318121727-bc25dd6abe8e/go.mod h1:qZqlPyPvfsDJt+3wHJ1EvSXDuVjFTK0j2p/ca+gtsb8= -github.com/dave/patsy v0.0.0-20210517141501-957256f50cba/go.mod h1:qfR88CgEGLoiqDaE+xxDCi5QA5v4vUoW0UCX2Nd5Tlc= -github.com/dave/rebecca v0.9.1/go.mod h1:N6XYdMD/OKw3lkF3ywh8Z6wPGuwNFDNtWYEMFWEmXBA= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/derision-test/glock v0.0.0-20210316032053-f5b74334bb29 h1:O07j7ewg0eFHRx+7bxCA/7z86HJexl7HLY9kyVMmPDo= github.com/derision-test/glock v0.0.0-20210316032053-f5b74334bb29/go.mod h1:jKtLdBMrF+XQatqvg46wiWdDfDSSDjdhO4dOM2FX9H4= github.com/derision-test/go-mockgen v1.1.2/go.mod h1:9H3VGTWYnL1VJoHHCuPKDpPFmNQ1uVyNlpX6P63l5Sk= -github.com/derision-test/go-mockgen v1.2.0 h1:SCF7p4FuO6IZId3CMjSHH9K0SMDVXNz7jc3AOeJaBd8= -github.com/derision-test/go-mockgen v1.2.0/go.mod h1:/TXUePlhtHmDDCaDAi/a4g6xOHqMDz3Wf0r2NPGskB4= github.com/dgraph-io/badger v1.6.0/go.mod h1:zwt7syl517jmP8s94KqSxTlM6IMsdhYy6psNgSztDR4= github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= @@ -237,7 +223,6 @@ github.com/microcosm-cc/bluemonday v1.0.2/go.mod h1:iVP4YcDBq+n/5fb23BhYFvIMq/le github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw= github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= -github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0= github.com/mitchellh/go-wordwrap v1.0.1/go.mod h1:R62XHJLzvMFRBbcrT7m7WgmE1eOyTSsCt+hzestvNj0= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ= @@ -309,8 +294,6 @@ github.com/sourcegraph/go-diff v0.6.1 h1:hmA1LzxW0n1c3Q4YbrFgg4P99GSnebYa3x8gr0H github.com/sourcegraph/go-diff v0.6.1/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20220414150621-eeb00fcedd88 h1:xqMUhhlrIFJRsb4EodMR5aWZpTY0rdukgVR8yV2mz7w= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20220414150621-eeb00fcedd88/go.mod h1:6/o2uP/pgAIyAZWqHeZF4J9F8rfWvkU3BRqVLWpLwTA= github.com/sourcegraph/sourcegraph/lib v0.0.0-20220506010657-06e02488a3d7 h1:YgPugK3f2y4cEfPH+Tb45yYymSTCZAaZ2nAQO81EZU4= github.com/sourcegraph/sourcegraph/lib v0.0.0-20220506010657-06e02488a3d7/go.mod h1:nuweF6uGn0mCNzMAbCiLbje6MkZwUmhXaFA4w30/ZfU= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= @@ -383,8 +366,6 @@ golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro= -golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3 h1:kQgndtyPBW/JIYERgdxfwMYh3AVStj88WQTlNDi2a+o= -golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3/go.mod h1:3p9vT2HGsQu2K1YbXdKPJLVgG5VJdoTa1poYQBtP1AY= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -451,14 +432,10 @@ golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20211102192858-4dd72447c267/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211117180635-dee7805ff2e1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211213223007-03aa0b5f6827/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220412211240-33da011f77ad h1:ntjMns5wyP/fN65tdBD4g8J5w8n015+iIIs9rtjXkY0= -golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6 h1:nonptSpoQ4vQjyraW20DXPAglgQfVnM9ZC6MmNLMR60= golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= @@ -489,8 +466,6 @@ golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.8-0.20211102182255-bb4add04ddef/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= golang.org/x/tools v0.1.8/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= golang.org/x/tools v0.1.9/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= -golang.org/x/tools v0.1.10 h1:QjFRCZxdOhBJ/UNgnBZLbNV13DlbnK0quyivTnXJM20= -golang.org/x/tools v0.1.10/go.mod h1:Uh6Zz+xoGYZom868N8YTex3t7RhtHDBrE8Gzo9bV56E= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= From ee838796ca35790df14f1a2f68fc8e8cbccd9e3a Mon Sep 17 00:00:00 2001 From: Warren Gifford Date: Fri, 13 May 2022 11:51:57 -0700 Subject: [PATCH 163/647] src debug command (#731) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * setup debug command scaffold * added test kubectl events logging * debug: Create ZIP archive * debug: Fail if zip file already exists * debug: introduce directory structure in zip * added --all-naamespaces to get events command * populated with TODO tasks, add get pods output * setting up k8s get pods to enable grabbing logs * got pod names parsed to slice * pulling logs from all pods, TODO: handle subcontainers * add missing .txt string to log archive names * used json get pods out, refactored k8s logs into their own spot * refactor get logs into savek8sLogs * working on logs for previous pods, need to only write when command returns without error * archives prev-logs if exists * refactoring getPods to handler scope * refactored all kubectl call functions to be declared outside of handler * added pod manifests and describes * added some more TODOs * added a little error handling on archives * corrected some error handling * added validation on out flag, and setup for deployment flag * improved logic for deployment flag * refactored deployment script * added get PV and PVC, used out flag as baseDir for archive filestructure * changed archive filestructure to be oriented around pod directories containing logs, past logs, and manifests * cleaned up some finished TODOs, shortened selector values for -d flag * refactored kubectl archiving into -d flag switch * working get containers * Concurrency!! * made deploy level kubectl functions concurrent * figured out bug in getLogs caused by immediately invoked function and variable scope in for loop * all kubectl functions refactored to run as goroutines, bug present causing some zip writes to write empty files * added some prints for debugging * clean up some flag validating prints and comments * A bunch of improvements 1. Set open file limits in process to support this much concurrency. This could also be done in the shell with `ulimits -n 99999`. 2. Pass in `context.Context` so we cancel any pending go-routines when returning early. 3. Change getXXX signatures from returning a slice to a single *archiveFile (since we were never actually returning more than one file) 4. Check for error in the file archiving loop and abort if there's any. 5. Verbose logging support. * add todo for logging * fixed hardcoding 999999 in setOpenFileLimits * removed plural k8s func names, started work on docker commands * working log archival for docker containers * added docker inspect * added docker container stats * improved logic for get containers * cleanup * clarify assumptions * introduced debug sub commands kube, comp, and serv -- Ex: src debug kube -out=test * for some reason my .gitignore was ignoring these new files * changed flagset to use .StringVar rather than .String in flagSet package * correct flag typo in serv * fixed verbose output in kube command, changed -out flag to -o * switching to passanger, stating getConfig * ignore errors and get extsvc configs * add some comments from work with Tomas * added namespace flag for kube subcommand * added a little safety check to the kube command * added a semaphore to kube, added some text safty checks * added semphore to all RPC calls in archiveKube * added current-context logging before kube command execution * Atempting to debug error inconsistent --previous logs call * added network validation to comp subcommand * added a function to pull site config, cleaned up logging and usage funcs * moved sub-functions to relevant file, trial utility archiveFileFromCommand in src extsvc function * converted all kube commands to , renamed kube getContainers to getPods * refactored compose functions with archiveFileFromCommand * Made archiveFileFromCommand calls aesthetically pleasing, added docker ps, and get pods commands as a sort of index * changes all path package calls to path/filepath calls * emptied graveyard * return early from failed semaphore.Acquire rather than reading error * handle errors, remove direct comparison to booleans * cleaned up some more linter erros * refactor adding verify func * fixed final improperly handled error * use semaphore in debug comp * working errgroups in comp * refactor to errgroup in kube * refactored writer in archive functions * corrected all complex filepath calls using fmt.Sprintf() * filter docker ps output to appropriate network * removed setup debug as will as openfile limit adjustment * normalize site config * correctly process json * fleshed out serv command * Update .gitignore Co-authored-by: Eric Fritz * Apply suggestions from code review Implementation of Eric's review suggestions; untested, requiring duplication in other files Co-authored-by: Eric Fritz * implement and repair infered refactors in erics suggestions * addressed many suggested code improvements for readability and style; still needs run through for error handling, and potentially some more refactors * refactor baseDir processor * went over errors, still probably needs another run since I widely used errors.Wrapf * clarify all string serializations * Update cmd/src/debug_comp.go Co-authored-by: Eric Fritz * Update cmd/src/debug_common.go Co-authored-by: Eric Fritz * Update cmd/src/debug_common.go Co-authored-by: Eric Fritz * Update cmd/src/debug_kube.go Co-authored-by: Eric Fritz * Update cmd/src/debug_kube.go Co-authored-by: Eric Fritz * Update cmd/src/debug_kube.go Co-authored-by: Eric Fritz * finishing touches * final error handling cleanup * add changelog entry * Update cmd/src/debug_serv.go Co-authored-by: Adam Harvey * Update cmd/src/debug_comp.go Co-authored-by: Adam Harvey * Update cmd/src/debug_kube.go Co-authored-by: Adam Harvey * Update cmd/src/debug_kube.go Co-authored-by: Adam Harvey * Update cmd/src/debug.go Co-authored-by: Adam Harvey * address harvey suggestions * finalize changes from harvey's suggestions * fix go.mod * really fix go.mod Co-authored-by: Tomás Senart Co-authored-by: Tomás Senart Co-authored-by: Eric Fritz Co-authored-by: Adam Harvey --- .gitignore | 2 + CHANGELOG.md | 2 +- cmd/src/debug.go | 42 +++++ cmd/src/debug_common.go | 123 +++++++++++++++ cmd/src/debug_compose.go | 228 ++++++++++++++++++++++++++++ cmd/src/debug_kube.go | 320 +++++++++++++++++++++++++++++++++++++++ cmd/src/debug_server.go | 179 ++++++++++++++++++++++ go.mod | 2 +- 8 files changed, 896 insertions(+), 2 deletions(-) create mode 100644 cmd/src/debug.go create mode 100644 cmd/src/debug_common.go create mode 100644 cmd/src/debug_compose.go create mode 100644 cmd/src/debug_kube.go create mode 100644 cmd/src/debug_server.go diff --git a/.gitignore b/.gitignore index f18daa77ab..c4b8f452b8 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,6 @@ ./src +./cmd/src/src +*.zip release ./vendor .idea diff --git a/CHANGELOG.md b/CHANGELOG.md index cb146dcca0..0ab10f1e4d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,7 +12,7 @@ All notable changes to `src-cli` are documented in this file. ## Unreleased ### Added - +- New command `src debug`. [#731](https://github.com/sourcegraph/src-cli/pull/731) - `src lsif upload` now supports the `-gitlab-token` flag. [#721](https://github.com/sourcegraph/src-cli/pull/721) - Batch Changes can be applied to Bitbucket Cloud when `src` is used with Sourcegraph 3.40 or later. [#725](https://github.com/sourcegraph/src-cli/pull/725) diff --git a/cmd/src/debug.go b/cmd/src/debug.go new file mode 100644 index 0000000000..2a513cb1c4 --- /dev/null +++ b/cmd/src/debug.go @@ -0,0 +1,42 @@ +package main + +import ( + "flag" + "fmt" +) + +var debugCommands commander + +func init() { + usage := `'src debug' gathers and bundles debug data from a Sourcegraph deployment for troubleshooting. + +Usage: + + src debug command [command options] + +The commands are: + + kube dumps context from k8s deployments + compose dumps context from docker-compose deployments + server dumps context from single-container deployments + + +Use "src debug command -h" for more information about a subcommands. +src debug has access to flags on src -- Ex: src -v kube -o foo.zip + +` + + flagSet := flag.NewFlagSet("debug", flag.ExitOnError) + handler := func(args []string) error { + debugCommands.run(flagSet, "src debug", usage, args) + return nil + } + + // Register the command. + commands = append(commands, &command{ + flagSet: flagSet, + aliases: []string{}, + handler: handler, + usageFunc: func() { fmt.Println(usage) }, + }) +} diff --git a/cmd/src/debug_common.go b/cmd/src/debug_common.go new file mode 100644 index 0000000000..130cdd8eaf --- /dev/null +++ b/cmd/src/debug_common.go @@ -0,0 +1,123 @@ +package main + +import ( + "archive/zip" + "context" + "encoding/json" + "fmt" + "log" + "os" + "path/filepath" + "strings" + + "github.com/sourcegraph/src-cli/internal/exec" + + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +type archiveFile struct { + name string + data []byte + err error +} + +func archiveFileFromCommand(ctx context.Context, path, cmd string, args ...string) *archiveFile { + f := &archiveFile{name: path} + f.data, f.err = exec.CommandContext(ctx, cmd, args...).CombinedOutput() + if f.err != nil { + f.err = errors.Wrapf(f.err, "executing command: %s %s: received error: %s", cmd, strings.Join(args, " "), f.data) + } + return f +} + +// verify prompts the user to confirm they want to run the command +func verify(confirmationText string) (bool, error) { + input := "" + for strings.ToLower(input) != "y" && strings.ToLower(input) != "n" { + fmt.Printf("%s [y/N]: ", confirmationText) + if _, err := fmt.Scanln(&input); err != nil { + return false, err + } + } + + return strings.ToLower(input) == "y", nil +} + +func processBaseDir(base string) (string, string) { + if !strings.HasSuffix(base, ".zip") { + return base + ".zip", base + } + + return base, strings.TrimSuffix(base, ".zip") +} + +// write all the outputs from an archive command passed on the channel to to the zip writer +func writeChannelContentsToZip(zw *zip.Writer, ch <-chan *archiveFile, verbose bool) error { + for f := range ch { + if verbose { + log.Printf("archiving file %q with %d bytes", f.name, len(f.data)) + } + + if f.err != nil { + return f.err + } + + zf, err := zw.Create(f.name) + if err != nil { + return errors.Wrapf(err, "failed to create %q", f.name) + } + + if _, err := zf.Write(f.data); err != nil { + return errors.Wrapf(err, "failed to write to %q", f.name) + } + } + return nil +} + +// TODO: Currently external services and site configs are pulled using the SRC_ENDPOINT env var, +// if theres a way to validate that the env var is pointing at the same instance as the docker and kubectl commands, +// it should be implemented. + +// TODO: file issue on the existence of OAuth signKey which needs to be redacted + +// getExternalServicesConfig calls src extsvc list with the format flag -f, +// and then returns an archiveFile to be consumed +func getExternalServicesConfig(ctx context.Context, baseDir string) *archiveFile { + const fmtStr = `{{range .Nodes}}{{.id}} | {{.kind}} | {{.displayName}}{{"\n"}}{{.config}}{{"\n---\n"}}{{end}}` + return archiveFileFromCommand( + ctx, + filepath.Join(baseDir, "config", "external_services.txt"), + os.Args[0], "extsvc", "list", "-f", fmtStr, + ) +} + +// getSiteConfig calls src api -query=... to query the api for site config json +func getSiteConfig(ctx context.Context, baseDir string) *archiveFile { + const siteConfigStr = `query { site { configuration { effectiveContents } } }` + f := archiveFileFromCommand(ctx, + filepath.Join(baseDir, "config", "siteConfig.json"), + os.Args[0], "api", "-query", siteConfigStr, + ) + + if f.err != nil { + return f + } + + var siteConfig struct { + Data struct { + Site struct { + Configuration struct { + EffectiveContents string + } + } + } + } + + if err := json.Unmarshal(f.data, &siteConfig); err != nil { + f.err = err + return f + } + + f.data = []byte(siteConfig.Data.Site.Configuration.EffectiveContents) + return f +} diff --git a/cmd/src/debug_compose.go b/cmd/src/debug_compose.go new file mode 100644 index 0000000000..9fb764f78a --- /dev/null +++ b/cmd/src/debug_compose.go @@ -0,0 +1,228 @@ +package main + +import ( + "archive/zip" + "context" + "flag" + "fmt" + "log" + "os" + "os/exec" + "path/filepath" + "strings" + + "github.com/sourcegraph/sourcegraph/lib/errors" + + "golang.org/x/sync/errgroup" + + "golang.org/x/sync/semaphore" +) + +func init() { + usage := ` +'src debug compose' invokes docker cli diagnostic commands targeting a set of containers that are members of a docker-compose network, +writing an archive file from their returns. + +Usage: + + src debug compose [command options] + +Flags: + + -o Specify the name of the output zip archive. + --no-configs Don't include Sourcegraph configuration json. + +Examples: + + $ src debug compose -o debug.zip + + $ src -v debug compose -no-configs -o foo.zip + +` + + flagSet := flag.NewFlagSet("compose", flag.ExitOnError) + var base string + var noConfigs bool + flagSet.StringVar(&base, "o", "debug.zip", "The name of the output zip archive") + flagSet.BoolVar(&noConfigs, "no-configs", false, "If true include Sourcegraph configuration files. Default value true.") + + handler := func(args []string) error { + if err := flagSet.Parse(args); err != nil { + return err + } + + // process -o flag to get zipfile and base directory names + if base == "" { + return fmt.Errorf("empty -o flag") + } + // declare basedir for archive file structure + base, baseDir := processBaseDir(base) + + // init context + ctx := context.Background() + // open pipe to output file + out, err := os.OpenFile(base, os.O_CREATE|os.O_RDWR|os.O_EXCL, 0666) + if err != nil { + return errors.Wrap(err, "failed to open file") + } + defer out.Close() + // init zip writer + zw := zip.NewWriter(out) + defer zw.Close() + + //Gather data for safety check + containers, err := getContainers(ctx) + if err != nil { + return errors.Wrap(err, "failed to get containers for subcommand with err") + } + // Safety check user knows what they are targeting with this debug command + log.Printf("This command will archive docker-cli data for %d containers\n SRC_ENDPOINT: %v\n Output filename: %v", len(containers), cfg.Endpoint, base) + if verified, _ := verify("Do you want to start writing to an archive?"); !verified { + return nil + } + + err = archiveCompose(ctx, zw, *verbose, noConfigs, baseDir) + if err != nil { + return err + } + return nil + } + + debugCommands = append(debugCommands, &command{ + flagSet: flagSet, + handler: handler, + usageFunc: func() { + fmt.Println(usage) + }, + }) +} + +// writes archive of common docker cli commands +func archiveCompose(ctx context.Context, zw *zip.Writer, verbose, noConfigs bool, baseDir string) error { + ctx, cancel := context.WithCancel(ctx) + defer cancel() + + containers, err := getContainers(ctx) + if err != nil { + return errors.Wrap(err, "failed to get docker containers") + } + + if verbose { + log.Printf("getting docker data for %d containers...\n", len(containers)) + } + + // setup channel for slice of archive function outputs + ch := make(chan *archiveFile) + g, ctx := errgroup.WithContext(ctx) + semaphore := semaphore.NewWeighted(8) + + run := func(f func() *archiveFile) { + g.Go(func() error { + if err := semaphore.Acquire(ctx, 1); err != nil { + return err + } + defer semaphore.Release(1) + + if file := f(); file != nil { + ch <- file + } + + return nil + }) + } + + // start goroutine to run docker ps -o wide + run(func() *archiveFile { return getPs(ctx, baseDir) }) + + // start goroutine to run docker container stats --no-stream + run(func() *archiveFile { return getStats(ctx, baseDir) }) + + // 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) }) + } + + // start goroutine to get configs + if !noConfigs { + run(func() *archiveFile { return getExternalServicesConfig(ctx, baseDir) }) + + run(func() *archiveFile { return getSiteConfig(ctx, baseDir) }) + } + + // close channel when wait group goroutines have completed + go func() { + if err := g.Wait(); err != nil { + fmt.Printf("archiveCompose failed to open wait group: %s\n", err) + os.Exit(1) + } + close(ch) + }() + + // Read binaries from channel and write to archive on host machine + if err := writeChannelContentsToZip(zw, ch, verbose); err != nil { + return errors.Wrap(err, "failed to write archives from channel") + } + + return nil +} + +// Returns list of containers that are members of the docker-compose_sourcegraph +func getContainers(ctx context.Context) ([]string, error) { + c, err := exec.CommandContext(ctx, "docker", "container", "ls", "--format", "{{.Names}} {{.Networks}}").Output() + if err != nil { + return nil, errors.Wrapf(err, "failed to get container names with error") + } + s := string(c) + preprocessed := strings.Split(strings.TrimSpace(s), "\n") + containers := make([]string, 0, len(preprocessed)) + for _, container := range preprocessed { + tmpStr := strings.Split(container, " ") + if len(tmpStr) >= 2 && tmpStr[1] == "docker-compose_sourcegraph" { + containers = append(containers, tmpStr[0]) + } + } + return containers, err +} + +// runs archiveFileFromCommand with args docker ps +func getPs(ctx context.Context, baseDir string) *archiveFile { + return archiveFileFromCommand( + ctx, + filepath.Join(baseDir, "docker", "docker-ps.txt"), + "docker", "ps", "--filter", "network=docker-compose_sourcegraph", + ) +} + +// runs archiveFileFromCommand with args docker container stats +func getStats(ctx context.Context, baseDir string) *archiveFile { + return archiveFileFromCommand( + ctx, + filepath.Join(baseDir, "docker", "stats.txt"), + "docker", "container", "stats", "--no-stream", + ) +} + +// runs archiveFileFromCommand with args docker container logs $CONTAINER +func getContainerLog(ctx context.Context, container, baseDir string) *archiveFile { + return archiveFileFromCommand( + ctx, + filepath.Join(baseDir, "docker", "containers", container, fmt.Sprintf("%s.log", container)), + "docker", "container", "logs", container, + ) +} + +// runs archiveFileFromCommand with args docker container inspect $CONTAINER +func getInspect(ctx context.Context, container, baseDir string) *archiveFile { + return archiveFileFromCommand( + ctx, + filepath.Join(baseDir, "docker", "containers", container, fmt.Sprintf("inspect-%s.txt", container)), + "docker", "container", "inspect", container, + ) +} diff --git a/cmd/src/debug_kube.go b/cmd/src/debug_kube.go new file mode 100644 index 0000000000..9e3dfdaf7e --- /dev/null +++ b/cmd/src/debug_kube.go @@ -0,0 +1,320 @@ +package main + +import ( + "archive/zip" + "bytes" + "context" + "encoding/json" + "flag" + "fmt" + "log" + "os" + "path/filepath" + + "golang.org/x/sync/errgroup" + + "golang.org/x/sync/semaphore" + + "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/src-cli/internal/exec" +) + +func init() { + usage := ` +'src debug kube' invokes kubectl diagnostic commands targeting kubectl's current-context, writing returns to an archive. +Usage: + + src debug kube [command options] + +Flags: + + -o Specify the name of the output zip archive. + -n Specify the namespace passed to kubectl commands. If not specified the 'default' namespace is used. + --no-config Don't include Sourcegraph configuration json. + +Examples: + + $ src debug kube -o debug.zip + + $ src -v debug kube -n ns-sourcegraph -o foo + + $ src debug kube -no-configs -o bar.zip + +` + + flagSet := flag.NewFlagSet("kube", flag.ExitOnError) + var base string + var namespace string + var noConfigs bool + flagSet.StringVar(&base, "o", "debug.zip", "The name of the output zip archive") + flagSet.StringVar(&namespace, "n", "default", "The namespace passed to kubectl commands, if not specified the 'default' namespace is used") + flagSet.BoolVar(&noConfigs, "no-configs", false, "If true include Sourcegraph configuration files. Default value true.") + + handler := func(args []string) error { + if err := flagSet.Parse(args); err != nil { + return err + } + + // process -o flag to get zipfile and base directory names + if base == "" { + return errors.New("empty -o flag") + } + base, baseDir := processBaseDir(base) + + // init context + ctx := context.Background() + // open pipe to output file + out, err := os.OpenFile(base, os.O_CREATE|os.O_RDWR|os.O_EXCL, 0666) + if err != nil { + return errors.Wrapf(err, "failed to open file %q", base) + } + defer out.Close() + // init zip writer + zw := zip.NewWriter(out) + defer zw.Close() + + // Gather data for safety check + pods, err := selectPods(ctx, namespace) + if err != nil { + return errors.Wrap(err, "failed to get pods") + } + kubectx, err := exec.CommandContext(ctx, "kubectl", "config", "current-context").CombinedOutput() + if err != nil { + return errors.Wrapf(err, "failed to get current-context") + } + // Safety check user knows what they've targeted with this command + log.Printf("Archiving kubectl data for %d pods\n SRC_ENDPOINT: %v\n Context: %s Namespace: %v\n Output filename: %v", len(pods.Items), cfg.Endpoint, kubectx, namespace, base) + if verified, _ := verify("Do you want to start writing to an archive?"); !verified { + return nil + } + + err = archiveKube(ctx, zw, *verbose, noConfigs, namespace, baseDir, pods) + if err != nil { + return err + } + return nil + } + + debugCommands = append(debugCommands, &command{ + flagSet: flagSet, + handler: handler, + usageFunc: func() { + fmt.Println(usage) + }, + }) +} + +type podList struct { + Items []struct { + Metadata struct { + Name string + } + Spec struct { + Containers []struct { + Name string + } + } + } +} + +// Runs common kubectl functions and archive results to zip file +func archiveKube(ctx context.Context, zw *zip.Writer, verbose, noConfigs bool, namespace, baseDir string, pods podList) error { + // Create a context with a cancel function that we call when returning + // from archiveKube. This ensures we close all pending go-routines when returning + // early because of an error. + ctx, cancel := context.WithCancel(ctx) + defer cancel() + + // setup channel for slice of archive function outputs, as well as throttling semaphore + ch := make(chan *archiveFile) + g, ctx := errgroup.WithContext(ctx) + semaphore := semaphore.NewWeighted(8) + + run := func(f func() *archiveFile) { + g.Go(func() error { + if err := semaphore.Acquire(ctx, 1); err != nil { + return err + } + defer semaphore.Release(1) + + if file := f(); file != nil { + ch <- file + } + + return nil + }) + } + + // create goroutine to get pods + run(func() *archiveFile { return getPods(ctx, namespace, baseDir) }) + + // create goroutine to get kubectl events + run(func() *archiveFile { return getEvents(ctx, namespace, baseDir) }) + + // create goroutine to get persistent volumes + run(func() *archiveFile { return getPV(ctx, namespace, baseDir) }) + + // create goroutine to get persistent volumes claim + run(func() *archiveFile { return getPVC(ctx, namespace, baseDir) }) + + // start goroutine to run kubectl logs for each pod's container's + for _, pod := range pods.Items { + for _, container := range pod.Spec.Containers { + p := pod.Metadata.Name + c := container.Name + run(func() *archiveFile { return getPodLog(ctx, p, c, namespace, baseDir) }) + } + } + + // start goroutine to run kubectl logs --previous for each pod's container's + // won't write to zip on err, only passes bytes to channel if err not nil + for _, pod := range pods.Items { + for _, container := range pod.Spec.Containers { + p := pod.Metadata.Name + c := container.Name + run(func() *archiveFile { + f := getPastPodLog(ctx, p, c, namespace, baseDir) + if f.err != nil { + if verbose { + fmt.Printf("Could not gather --previous pod logs for %s\n", p) + } + return nil + } + return f + }) + } + } + + // start goroutine for each pod to run kubectl describe pod + for _, pod := range pods.Items { + p := pod.Metadata.Name + run(func() *archiveFile { return getDescribe(ctx, p, namespace, baseDir) }) + } + + // start goroutine for each pod to run kubectl get pod -o yaml + for _, pod := range pods.Items { + p := pod.Metadata.Name + run(func() *archiveFile { return getManifest(ctx, p, namespace, baseDir) }) + } + + // start goroutine to get external service config + if !noConfigs { + run(func() *archiveFile { return getExternalServicesConfig(ctx, baseDir) }) + + run(func() *archiveFile { return getSiteConfig(ctx, baseDir) }) + } + + // close channel when wait group goroutines have completed + go func() { + if err := g.Wait(); err != nil { + fmt.Printf("archiveKube failed to open wait group: %s\n", err) + os.Exit(1) + } + close(ch) + }() + + // Read binaries from channel and write to archive on host machine + if err := writeChannelContentsToZip(zw, ch, verbose); err != nil { + return errors.Wrap(err, "failed to write archives from channel") + } + + return nil +} + +// Calls kubectl get pods and returns a list of pods to be processed +func selectPods(ctx context.Context, namespace string) (podList, error) { + // Declare buffer type var for kubectl pipe + var podsBuff bytes.Buffer + + // Get all pod names as json + podsCmd := exec.CommandContext( + ctx, + "kubectl", "-n", namespace, "get", "pods", "-l", "deploy=sourcegraph", "-o=json", + ) + podsCmd.Stdout = &podsBuff + podsCmd.Stderr = os.Stderr + err := podsCmd.Run() + if err != nil { + errors.Wrap(err, "failed to aquire pods for subcommands with err") + } + + //Decode json from podList + var pods podList + if err := json.Unmarshal(podsBuff.Bytes(), &pods); err != nil { + return pods, errors.Wrap(err, "failed to unmarshall get pods json") + } + + return pods, err +} + +// runs archiveFileFromCommand with arg get pods +func getPods(ctx context.Context, namespace, baseDir string) *archiveFile { + return archiveFileFromCommand( + ctx, + filepath.Join(baseDir, "kubectl", "getPods.txt"), + "kubectl", "-n", namespace, "get", "pods", "-o", "wide", + ) +} + +// runs archiveFileFromCommand with arg get events +func getEvents(ctx context.Context, namespace, baseDir string) *archiveFile { + return archiveFileFromCommand( + ctx, + filepath.Join(baseDir, "kubectl", "events.txt"), + "kubectl", "-n", namespace, "get", "events", + ) +} + +// runs archiveFileFromCommand with arg get pv +func getPV(ctx context.Context, namespace, baseDir string) *archiveFile { + return archiveFileFromCommand( + ctx, + filepath.Join(baseDir, "kubectl", "persistent-volumes.txt"), + "kubectl", "-n", namespace, "get", "pv", + ) +} + +// runs archiveFileFromCommand with arg get pvc +func getPVC(ctx context.Context, namespace, baseDir string) *archiveFile { + return archiveFileFromCommand( + ctx, + filepath.Join(baseDir, "kubectl", "persistent-volume-claims.txt"), + "kubectl", "-n", namespace, "get", "pvc", + ) +} + +// runs archiveFileFromCommand with arg logs $POD -c $CONTAINER +func getPodLog(ctx context.Context, podName, containerName, namespace, baseDir string) *archiveFile { + return archiveFileFromCommand( + ctx, + filepath.Join(baseDir, "kubectl", "pods", podName, fmt.Sprintf("%s.log", containerName)), + "kubectl", "-n", namespace, "logs", podName, "-c", containerName, + ) +} + +// runs archiveFileFromCommand with arg logs --previous $POD -c $CONTAINER +func getPastPodLog(ctx context.Context, podName, containerName, namespace, baseDir string) *archiveFile { + return archiveFileFromCommand( + ctx, + filepath.Join(baseDir, "kubectl", "pods", podName, fmt.Sprintf("prev-%s.log", containerName)), + "kubectl", "-n", namespace, "logs", "--previous", podName, "-c", containerName, + ) +} + +// runs archiveFileFromCommand with arg describe pod $POD +func getDescribe(ctx context.Context, podName, namespace, baseDir string) *archiveFile { + return archiveFileFromCommand( + ctx, + filepath.Join(baseDir, "kubectl", "pods", podName, fmt.Sprintf("describe-%s.txt", podName)), + "kubectl", "-n", namespace, "describe", "pod", podName, + ) +} + +// runs archiveFileFromCommand with arg get pod $POD -o yaml +func getManifest(ctx context.Context, podName, namespace, baseDir string) *archiveFile { + return archiveFileFromCommand( + ctx, + filepath.Join(baseDir, "kubectl", "pods", podName, fmt.Sprintf("manifest-%s.yaml", podName)), + "kubectl", "-n", namespace, "get", "pod", podName, "-o", "yaml", + ) +} diff --git a/cmd/src/debug_server.go b/cmd/src/debug_server.go new file mode 100644 index 0000000000..4705ce2c1e --- /dev/null +++ b/cmd/src/debug_server.go @@ -0,0 +1,179 @@ +package main + +import ( + "archive/zip" + "context" + "flag" + "fmt" + "log" + "os" + "path/filepath" + + "golang.org/x/sync/errgroup" + "golang.org/x/sync/semaphore" + + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +func init() { + usage := ` +'src debug server' invokes docker cli diagnostic commands targeting a Sourcegraph server container, +and writes an archive file from their returns. + +Usage: + + src debug server [command options] + +Flags: + + -o Specify the name of the output zip archive. + -no-config Don't include Sourcegraph configuration json. + +Examples: + + $ src debug server -c foo -o debug.zip + + $ src -v debug server --no-configs -c ViktorVaughn -o foo.zip + +` + + flagSet := flag.NewFlagSet("server", flag.ExitOnError) + var base string + var container string + var noConfigs bool + flagSet.StringVar(&base, "o", "debug.zip", "The name of the output zip archive") + flagSet.StringVar(&container, "c", "", "The container to target") + flagSet.BoolVar(&noConfigs, "no-configs", false, "If true include Sourcegraph configuration files. Default value true.") + + handler := func(args []string) error { + if err := flagSet.Parse(args); err != nil { + return err + } + + //process -o flag to get zipfile and base directory names, make sure container is targeted + if base == "" { + return fmt.Errorf("empty -o flag") + } + if container == "" { + return fmt.Errorf("empty -c flag, specify a container: src debug server -c foo") + } + base, baseDir := processBaseDir(base) + + // init context + ctx := context.Background() + // open pipe to output file + out, err := os.OpenFile(base, os.O_CREATE|os.O_RDWR|os.O_EXCL, 0666) + if err != nil { + return errors.Wrapf(err, "failed to open file %q", base) + } + defer out.Close() + // init zip writer + zw := zip.NewWriter(out) + defer zw.Close() + + // Safety check user knows what they are targeting with this debug command + log.Printf("This command will archive docker-cli data for container: %s\n SRC_ENDPOINT: %s\n Output filename: %s", container, cfg.Endpoint, base) + if verified, _ := verify("Do you want to start writing to an archive?"); !verified { + return nil + } + + err = archiveServ(ctx, zw, *verbose, noConfigs, container, baseDir) + if err != nil { + return err + } + return nil + } + + debugCommands = append(debugCommands, &command{ + flagSet: flagSet, + handler: handler, + usageFunc: func() { + fmt.Println(usage) + }, + }) +} + +// Runs common docker cli commands on a single container +func archiveServ(ctx context.Context, zw *zip.Writer, verbose, noConfigs bool, container, baseDir string) error { + ctx, cancel := context.WithCancel(ctx) + defer cancel() + + // setup channel for slice of archive function outputs + ch := make(chan *archiveFile) + g, ctx := errgroup.WithContext(ctx) + semaphore := semaphore.NewWeighted(8) + + run := func(f func() *archiveFile) { + g.Go(func() error { + if err := semaphore.Acquire(ctx, 1); err != nil { + return err + } + defer semaphore.Release(1) + + if file := f(); file != nil { + ch <- file + } + + return nil + }) + } + + // start goroutine to run docker ps -o wide + run(func() *archiveFile { return getServLog(ctx, container, baseDir) }) + + // start goroutine to run docker ps -o wide + run(func() *archiveFile { return getServInspect(ctx, container, baseDir) }) + + // start goroutine to run docker ps -o wide + run(func() *archiveFile { return getServTop(ctx, container, baseDir) }) + + // start goroutine to get configs + if !noConfigs { + run(func() *archiveFile { return getExternalServicesConfig(ctx, baseDir) }) + + run(func() *archiveFile { return getSiteConfig(ctx, baseDir) }) + } + + // close channel when wait group goroutines have completed + go func() { + if err := g.Wait(); err != nil { + fmt.Printf("archiveServ failed to open wait group: %s\n", err) + os.Exit(1) + } + close(ch) + }() + + // Read binaries from channel and write to archive on host machine + if err := writeChannelContentsToZip(zw, ch, verbose); err != nil { + return errors.Wrap(err, "failed to write archives from channel") + } + + return nil +} + +// runs archiveFileFromCommand with args container logs $CONTAINER +func getServLog(ctx context.Context, container, baseDir string) *archiveFile { + return archiveFileFromCommand( + ctx, + filepath.Join(baseDir, fmt.Sprintf("%s.log", container)), + "docker", "container", "logs", container, + ) +} + +// runs archiveFileFromCommand with args container inspect $CONTAINER +func getServInspect(ctx context.Context, container, baseDir string) *archiveFile { + return archiveFileFromCommand( + ctx, + filepath.Join(baseDir, fmt.Sprintf("inspect-%s.txt", container)), + "docker", "container", "inspect", container, + ) +} + +// runs archiveFileFromCommand with args top $CONTAINER +func getServTop(ctx context.Context, container, baseDir string) *archiveFile { + return archiveFileFromCommand( + ctx, + filepath.Join(baseDir, fmt.Sprintf("top-%s.txt", container)), + "docker", "top", container, + ) +} diff --git a/go.mod b/go.mod index 0fc2782086..873cd0ac0d 100644 --- a/go.mod +++ b/go.mod @@ -22,6 +22,7 @@ require ( github.com/sourcegraph/sourcegraph/lib v0.0.0-20220506010657-06e02488a3d7 github.com/stretchr/testify v1.7.1 golang.org/x/net v0.0.0-20220325170049-de3da57026de + golang.org/x/sync v0.0.0-20210220032951-036812b2e83c google.golang.org/protobuf v1.27.1 gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7 @@ -56,7 +57,6 @@ require ( github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect github.com/xeipuuv/gojsonschema v1.2.0 // indirect - golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6 // indirect golang.org/x/xerrors v0.0.0-20220411194840-2f41105eb62f // indirect gopkg.in/yaml.v2 v2.4.0 // indirect From bac5a37cd597a2a4877487cd971f8fa0bf4836f7 Mon Sep 17 00:00:00 2001 From: Varun Gandhi Date: Fri, 13 May 2022 15:11:28 -0700 Subject: [PATCH 164/647] Add support for SCIP + renaming. (#742) * Document why the flags are being modified after-the-fact. This kind of nonsense is why I hate global variables. Yuck. * Add support for SCIP uploads. --- cmd/src/lsif_upload_flags.go | 75 +++++++++---- cmd/src/lsif_upload_flags_test.go | 87 +++++++++------ go.mod | 45 +++++++- go.sum | 176 +++++++++++++++++++----------- 4 files changed, 261 insertions(+), 122 deletions(-) diff --git a/cmd/src/lsif_upload_flags.go b/cmd/src/lsif_upload_flags.go index 4e27121d0b..89fdc38458 100644 --- a/cmd/src/lsif_upload_flags.go +++ b/cmd/src/lsif_upload_flags.go @@ -4,14 +4,16 @@ import ( "flag" "fmt" "os" + "path" + "path/filepath" "strings" "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/sourcegraph/lib/output" "google.golang.org/protobuf/proto" + "github.com/sourcegraph/scip/bindings/go/scip" "github.com/sourcegraph/sourcegraph/lib/codeintel/lsif/protocol/reader" - "github.com/sourcegraph/sourcegraph/lib/codeintel/lsiftyped" "github.com/sourcegraph/sourcegraph/lib/codeintel/upload" "github.com/sourcegraph/src-cli/internal/api" @@ -111,7 +113,7 @@ func parseAndValidateLSIFUploadFlags(args []string) (*output.Output, error) { return nil, err } - if err := handleLSIFTyped(out); err != nil { + if err := handleSCIP(out); err != nil { return nil, err } @@ -155,35 +157,68 @@ type argumentInferenceError struct { err error } -func handleLSIFTyped(out *output.Output) error { - if strings.HasSuffix(lsifUploadFlags.file, ".lsif-typed") { - // The user explicitly passed in a -file flag that points to an LSIF Typed index. - inputFile := lsifUploadFlags.file - outputFile := strings.TrimSuffix(inputFile, "-typed") +func replaceExtension(oldPath string, newExtension string) string { + oldExtLen := len(path.Ext(oldPath)) + if oldExtLen == 0 { + panic(fmt.Sprintf("Expected path %s to have an extension", oldPath)) + } + return oldPath[:len(oldPath)-oldExtLen] + newExtension +} + +func replaceBaseName(oldPath string, newBaseName string) string { + if filepath.Dir(newBaseName) != "." { + panic(fmt.Sprintf("Expected bare file name but found %s", newBaseName)) + } + return filepath.Join(filepath.Dir(oldPath), newBaseName) +} + +func handleSCIP(out *output.Output) error { + fileExt := path.Ext(lsifUploadFlags.file) + if len(fileExt) == 0 { + return errors.Newf("missing file extension for %s; expected .scip", lsifUploadFlags.file) + } + inputFile := lsifUploadFlags.file + if fileExt == ".scip" || fileExt == ".lsif-typed" { + // The user explicitly passed in a -file flag that points to an SCIP index. + outputFile := replaceExtension(inputFile, ".lsif") + if filepath.Base(inputFile) == "index.scip" { + outputFile = replaceBaseName(inputFile, "dump.lsif") + } + // HACK: Modify the flags to point to the output file, because + // that field of the flags is read when performing the upload. lsifUploadFlags.file = outputFile - return convertLSIFTypedToLSIFGraph(out, inputFile, outputFile) + return convertSCIPToLSIFGraph(out, inputFile, outputFile) } - if _, err := os.Stat(lsifUploadFlags.file); err == nil { + if _, err := os.Stat(inputFile); err == nil { // Do nothing, the provided -flag flag points to an existing - // file that does not have the file extension `*.lsif-typed`. + // file that does not have the file extension `.lsif-typed` or `.scip`. return nil } - lsifTypedFile := lsifUploadFlags.file + "-typed" - if _, err := os.Stat(lsifTypedFile); os.IsNotExist(err) { - // The inferred path of the sibling `*.lsif-typed` file does not exist. - return nil + scipFile := replaceExtension(inputFile, ".scip") + if _, err := os.Stat(scipFile); os.IsNotExist(err) { + // The input may be named 'dump.lsif', but the default name for SCIP + // indexes is 'index.scip', not 'dump.scip'. + scipFile = replaceBaseName(inputFile, "index.scip") + if _, err := os.Stat(scipFile); os.IsNotExist(err) { + lsifTypedFile := replaceExtension(inputFile, ".lsif-typed") + if _, err := os.Stat(lsifTypedFile); os.IsNotExist(err) { + // There is no `*.scip` or `*.lsif-typed` file for the inferred path. + return nil + } + scipFile = lsifTypedFile + } } // The provided -file flag points to an `*.lsif` file that doesn't exist - // so we convert the sibling `*.lsif-typed` file (which we confirmed exists). - return convertLSIFTypedToLSIFGraph(out, lsifTypedFile, lsifUploadFlags.file) + // so we convert the sibling file (which we confirmed exists). + return convertSCIPToLSIFGraph(out, scipFile, lsifUploadFlags.file) } -// Reads the LSIF Typed encoded input file and writes the corresponding LSIF +// Reads the SCIP encoded input file and writes the corresponding LSIF // Graph encoded output file. -func convertLSIFTypedToLSIFGraph(out *output.Output, inputFile, outputFile string) error { +func convertSCIPToLSIFGraph(out *output.Output, inputFile, outputFile string) error { if out != nil { out.Writef("%s Converting %s into %s", output.EmojiInfo, inputFile, outputFile) } @@ -197,12 +232,12 @@ func convertLSIFTypedToLSIFGraph(out *output.Output, inputFile, outputFile strin if err != nil { panic(err) } - index := lsiftyped.Index{} + index := scip.Index{} err = proto.Unmarshal(data, &index) if err != nil { panic(errors.Wrapf(err, "failed to parse protobuf file '%s'", inputFile)) } - els, err := reader.ConvertTypedIndexToGraphIndex(&index) + els, err := scip.ConvertSCIPToLSIF(&index) if err != nil { panic(errors.Wrapf(err, "failed reader.ConvertTypedIndexToGraphIndex")) } diff --git a/cmd/src/lsif_upload_flags_test.go b/cmd/src/lsif_upload_flags_test.go index 3d242532d5..30611430a9 100644 --- a/cmd/src/lsif_upload_flags_test.go +++ b/cmd/src/lsif_upload_flags_test.go @@ -5,73 +5,94 @@ import ( "path/filepath" "testing" - "github.com/sourcegraph/sourcegraph/lib/codeintel/lsiftyped" + "github.com/stretchr/testify/require" "google.golang.org/protobuf/proto" + + "github.com/sourcegraph/scip/bindings/go/scip" ) -var exampleLsifTypedIndex = lsiftyped.Index{ - Metadata: &lsiftyped.Metadata{ - TextDocumentEncoding: lsiftyped.TextEncoding_UTF8, - ToolInfo: &lsiftyped.ToolInfo{ +var exampleSCIPIndex = scip.Index{ + Metadata: &scip.Metadata{ + TextDocumentEncoding: scip.TextEncoding_UTF8, + ToolInfo: &scip.ToolInfo{ Name: "hello", Version: "1.0.0", }, }, } -var exampleLsifGraphString = `{"id":1,"version":"0.4.3","positionEncoding":"utf-8","toolInfo":{"name":"hello","version":"1.0.0"},"type":"vertex","label":"metaData"} +var exampleLSIFString = `{"id":1,"version":"0.4.3","positionEncoding":"utf-8","toolInfo":{"name":"hello","version":"1.0.0"},"type":"vertex","label":"metaData"} ` -func exampleLsifTypedBytes(t *testing.T) []byte { - bytes, err := proto.Marshal(&exampleLsifTypedIndex) +func exampleSCIPBytes(t *testing.T) []byte { + bytes, err := proto.Marshal(&exampleSCIPIndex) if err != nil { t.Fatal(err) } return bytes } -func createTempLsifTypedFile(t *testing.T) (typedFile, graphFile string) { +func createTempSCIPFile(t *testing.T, scipFileName string) (scipFilePath string, lsifFilePath string) { dir := t.TempDir() - typedFile = filepath.Join(dir, "dump.lsif-typed") - graphFile = filepath.Join(dir, "dump.lsif") - err := os.WriteFile(typedFile, exampleLsifTypedBytes(t), 0755) + require.NotEqual(t, "", scipFileName) + scipFilePath = filepath.Join(dir, scipFileName) + lsifFilePath = filepath.Join(dir, "dump.lsif") + err := os.WriteFile(scipFilePath, exampleSCIPBytes(t), 0755) if err != nil { t.Fatal(err) } - return typedFile, graphFile + return scipFilePath, lsifFilePath } -func assertLsifGraphOutput(t *testing.T, lsifGraphFile, expectedGraphString string) { +func assertLSIFOutput(t *testing.T, lsifFile, expectedLSIFString string) { out := lsifUploadOutput() - handleLSIFTyped(out) - lsifGraph, err := os.ReadFile(lsifGraphFile) + handleSCIP(out) + lsif, err := os.ReadFile(lsifFile) if err != nil { t.Fatal(err) } - obtained := string(lsifGraph) - if obtained != expectedGraphString { + obtained := string(lsif) + if obtained != expectedLSIFString { t.Fatalf("unexpected LSIF output %s", obtained) } - if lsifGraphFile != lsifUploadFlags.file { - t.Fatalf("unexpected lsifUploadFlag.file value %s, expected %s", lsifUploadFlags.file, lsifGraphFile) + if lsifFile != lsifUploadFlags.file { + t.Fatalf("unexpected lsifUploadFlag.file value %s, expected %s", lsifUploadFlags.file, lsifFile) } } -func TestImplicitlyConvertLsifTypedIntoGraph(t *testing.T) { - _, graphFile := createTempLsifTypedFile(t) - lsifUploadFlags.file = graphFile - assertLsifGraphOutput(t, graphFile, exampleLsifGraphString) +func TestImplicitlyConvertSCIPIntoLSIF(t *testing.T) { + for _, filename := range []string{"index.scip", "dump.scip", "dump.lsif-typed"} { + _, lsifFile := createTempSCIPFile(t, filename) + lsifUploadFlags.file = lsifFile + assertLSIFOutput(t, lsifFile, exampleLSIFString) + } } -func TestImplicitlyIgnoreLsifTyped(t *testing.T) { - _, graphFile := createTempLsifTypedFile(t) - lsifUploadFlags.file = graphFile - os.WriteFile(graphFile, []byte("hello world"), 0755) - assertLsifGraphOutput(t, graphFile, "hello world") +func TestImplicitlyIgnoreSCIP(t *testing.T) { + for _, filename := range []string{"index.scip", "dump.scip", "dump.lsif-typed"} { + _, lsifFile := createTempSCIPFile(t, filename) + lsifUploadFlags.file = lsifFile + os.WriteFile(lsifFile, []byte("hello world"), 0755) + assertLSIFOutput(t, lsifFile, "hello world") + } } -func TestExplicitlyConvertLsifTypedIntoGraph(t *testing.T) { - typedFile, graphFile := createTempLsifTypedFile(t) - lsifUploadFlags.file = typedFile - assertLsifGraphOutput(t, graphFile, exampleLsifGraphString) +func TestExplicitlyConvertSCIPIntoGraph(t *testing.T) { + for _, filename := range []string{"index.scip", "dump.scip", "dump.lsif-typed"} { + scipFile, lsifFile := createTempSCIPFile(t, filename) + lsifUploadFlags.file = scipFile + assertLSIFOutput(t, lsifFile, exampleLSIFString) + } +} + +func TestReplaceExtension(t *testing.T) { + require.Panics(t, func() { replaceExtension("foo", ".xyz") }) + require.Equal(t, "foo.xyz", replaceExtension("foo.abc", ".xyz")) +} + +func TestReplaceBaseName(t *testing.T) { + require.Panics(t, func() { replaceBaseName("mydir", filepath.Join("dir", "file")) }) + + require.Equal(t, filepath.Join("a", "d.e"), + replaceBaseName(filepath.Join("a", "b.c"), "d.e")) } diff --git a/go.mod b/go.mod index 873cd0ac0d..6deed97609 100644 --- a/go.mod +++ b/go.mod @@ -16,30 +16,47 @@ require ( github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 github.com/mattn/go-isatty v0.0.14 github.com/neelance/parallel v0.0.0-20160708114440-4de9ce63d14c - github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4 + github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf - github.com/sourcegraph/sourcegraph/lib v0.0.0-20220506010657-06e02488a3d7 + github.com/sourcegraph/scip v0.0.0-20220513191902-a9bebaa57565 + github.com/sourcegraph/sourcegraph/lib v0.0.0-20220511160847-5a43d3ea24eb github.com/stretchr/testify v1.7.1 - golang.org/x/net v0.0.0-20220325170049-de3da57026de + golang.org/x/net v0.0.0-20220412020605-290c469a71a5 golang.org/x/sync v0.0.0-20210220032951-036812b2e83c - google.golang.org/protobuf v1.27.1 + google.golang.org/protobuf v1.28.0 gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7 ) require ( github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect + github.com/Masterminds/sprig v2.15.0+incompatible // indirect + github.com/aokoli/goutils v1.0.1 // indirect + github.com/bufbuild/buf v1.4.0 // indirect github.com/cockroachdb/errors v1.8.9 // indirect github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f // indirect github.com/cockroachdb/redact v1.1.3 // indirect + github.com/cpuguy83/go-md2man/v2 v2.0.1 // indirect github.com/davecgh/go-spew v1.1.1 // indirect + github.com/envoyproxy/protoc-gen-validate v0.3.0-java // indirect github.com/getsentry/sentry-go v0.12.0 // indirect github.com/ghodss/yaml v1.0.0 // indirect github.com/go-stack/stack v1.8.1 // indirect + github.com/gofrs/flock v0.8.1 // indirect + github.com/gofrs/uuid v4.2.0+incompatible // indirect github.com/gogo/protobuf v1.3.2 // indirect + github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect + github.com/golang/protobuf v1.5.2 // indirect + github.com/google/uuid v1.3.0 // indirect + github.com/huandu/xstrings v1.0.0 // indirect + github.com/imdario/mergo v0.3.4 // indirect github.com/inconshreveable/log15 v0.0.0-20201112154412-8562bdadbbac // indirect - github.com/klauspost/compress v1.14.2 // indirect + github.com/inconshreveable/mousetrap v1.0.0 // indirect + github.com/jdxcode/netrc v0.0.0-20210204082910-926c7f70242a // indirect + github.com/jhump/protocompile v0.0.0-20220216033700-d705409f108f // indirect + github.com/jhump/protoreflect v1.12.1-0.20220417024638-438db461d753 // indirect + github.com/klauspost/compress v1.15.1 // indirect github.com/klauspost/pgzip v1.2.5 // indirect github.com/kr/pretty v0.3.0 // indirect github.com/kr/text v0.2.0 // indirect @@ -48,17 +65,35 @@ require ( github.com/moby/term v0.0.0-20210619224110-3f7ff695adc6 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/mwitkow/go-proto-validators v0.0.0-20180403085117-0950a7990007 // indirect github.com/olekukonko/tablewriter v0.0.5 // indirect github.com/pkg/errors v0.9.1 // indirect + github.com/pkg/profile v1.6.0 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/pseudomuto/protoc-gen-doc v1.5.1 // indirect + github.com/pseudomuto/protokit v0.2.0 // indirect github.com/rivo/uniseg v0.2.0 // indirect github.com/rogpeppe/go-internal v1.8.1 // indirect + github.com/russross/blackfriday/v2 v2.1.0 // indirect + github.com/spf13/cobra v1.4.0 // indirect + github.com/spf13/pflag v1.0.5 // indirect github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect github.com/xeipuuv/gojsonschema v1.2.0 // indirect + go.opencensus.io v0.23.0 // indirect + go.uber.org/atomic v1.9.0 // indirect + go.uber.org/multierr v1.8.0 // indirect + go.uber.org/zap v1.21.0 // indirect + golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 // indirect + golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3 // indirect golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6 // indirect + golang.org/x/term v0.0.0-20220411215600-e5f449aeb171 // indirect + golang.org/x/text v0.3.7 // indirect + golang.org/x/tools v0.1.10 // indirect golang.org/x/xerrors v0.0.0-20220411194840-2f41105eb62f // indirect + google.golang.org/genproto v0.0.0-20220414192740-2d67ff6cf2b4 // indirect + google.golang.org/grpc v1.45.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect ) diff --git a/go.sum b/go.sum index 882a77b422..796e0c4d96 100644 --- a/go.sum +++ b/go.sum @@ -1,4 +1,5 @@ cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= github.com/AndreasBriese/bbloom v0.0.0-20190306092124-e2d15f34fcf9/go.mod h1:bOvUY6CB00SOBii9/FifXqc0awNKxLFCL/+pkDPuyl8= github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 h1:UQHMgLO+TxOElx5B5HZ4hJQsoJ/PvUvKRhJHDQXO8P8= github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= @@ -11,19 +12,28 @@ github.com/Joker/hpp v1.0.0/go.mod h1:8x5n+M1Hp5hC0g8okX3sR3vFQwynaX/UgSOM9MeBKz github.com/Joker/jade v1.0.1-0.20190614124447-d475f43051e7/go.mod h1:6E6s8o2AE4KhCrqr6GRJjdC/gNfTdxkIXvuGZZda2VM= github.com/Masterminds/semver v1.5.0 h1:H65muMkzWKEuNDnfl9d70GUjFniHKHRbFPGBuZ3QEww= github.com/Masterminds/semver v1.5.0/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y= +github.com/Masterminds/sprig v2.15.0+incompatible h1:0gSxPGWS9PAr7U2NsQ2YQg6juRDINkUyuvbb4b2Xm8w= +github.com/Masterminds/sprig v2.15.0+incompatible/go.mod h1:y6hNFY5UBTIWBxnzTeuNhlNS5hqE0NB0E6fgfo2Br3o= github.com/Shopify/goreferrer v0.0.0-20181106222321-ec9c9a553398/go.mod h1:a1uqRtAwp2Xwc6WNPJEufxJ7fx3npB4UV/JOLmbu5I0= github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY= -github.com/alecthomas/kingpin v2.2.6+incompatible/go.mod h1:59OFYbFVLKQKq+mqrL6Rw5bR0c3ACQaawgXx0QYndlE= -github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= -github.com/alecthomas/units v0.0.0-20210208195552-ff826a37aa15/go.mod h1:OMCwj8VM1Kc9e19TLln2VL61YJF0x1XFtfdL4JdbSyE= -github.com/alecthomas/units v0.0.0-20211218093645-b94a6e3cc137/go.mod h1:OMCwj8VM1Kc9e19TLln2VL61YJF0x1XFtfdL4JdbSyE= +github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= +github.com/aokoli/goutils v1.0.1 h1:7fpzNGoJ3VA8qcrm++XEE1QUe0mIwNeLa02Nwq7RDkg= +github.com/aokoli/goutils v1.0.1/go.mod h1:SijmP0QR8LtwsmDs8Yii5Z/S4trXFGFC2oO5g9DP+DQ= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= github.com/aymerick/raymond v2.0.3-0.20180322193309-b565731e1464+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g= github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= +github.com/benbjohnson/clock v1.3.0 h1:ip6w0uFQkncKQ979AypyG0ER7mqUSBdKLOgAle/AT8A= +github.com/bufbuild/buf v1.4.0 h1:GqE3a8CMmcFvWPzuY3Mahf9Kf3S9XgZ/ORpfYFzO+90= +github.com/bufbuild/buf v1.4.0/go.mod h1:mwHG7klTHnX+rM/ym8LXGl7vYpVmnwT96xWoRB4H5QI= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= +github.com/cncf/udpa/go v0.0.0-20210930031921-04548b0d99d4/go.mod h1:6pvJx4me5XPnfI9Z40ddWsdw2W/uZgQLFXToKeRcDiI= +github.com/cncf/xds/go v0.0.0-20210805033703-aa0b78936158/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/xds/go v0.0.0-20210922020428-25de7278fc84/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cockroachdb/datadriven v1.0.1-0.20211007161720-b558070c3be0/go.mod h1:5Ib8Meh+jk1RlHIXej6Pzevx/NLlNvQB9pmSBZErGA4= github.com/cockroachdb/datadriven v1.0.1-0.20220214170620-9913f5bc19b7/go.mod h1:hi0MtSY3AYDQNDi83kDkMH5/yqM/CsIrsOITkSoH7KI= github.com/cockroachdb/errors v1.6.1/go.mod h1:tm6FTP5G81vwJ5lC0SizQo374JNCOPrHyXGitRJoDqM= @@ -41,18 +51,18 @@ github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE= +github.com/cpuguy83/go-md2man/v2 v2.0.1 h1:r/myEWzV9lfsM1tFLgDyu0atFtJ1fXn261LKYj/3DxU= +github.com/cpuguy83/go-md2man/v2 v2.0.1/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/creack/goselect v0.1.2 h1:2DNy14+JPjRBgPzAd1thbQp4BSIihxcBf0IXhQXDRa0= github.com/creack/goselect v0.1.2/go.mod h1:a/NhLweNvqIYMuxcMOuWY516Cimucms3DglDzQP3hKY= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/creack/pty v1.1.11 h1:07n33Z8lZxZ2qwegKbObQohDhXDQxiMMz1NOUGYlesw= github.com/creack/pty v1.1.11/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= -github.com/dave/jennifer v1.4.1/go.mod h1:7jEdnm+qBcxl8PC0zyp7vxcpSRnzXSt9r39tpTVGlwA= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/derision-test/glock v0.0.0-20210316032053-f5b74334bb29 h1:O07j7ewg0eFHRx+7bxCA/7z86HJexl7HLY9kyVMmPDo= github.com/derision-test/glock v0.0.0-20210316032053-f5b74334bb29/go.mod h1:jKtLdBMrF+XQatqvg46wiWdDfDSSDjdhO4dOM2FX9H4= -github.com/derision-test/go-mockgen v1.1.2/go.mod h1:9H3VGTWYnL1VJoHHCuPKDpPFmNQ1uVyNlpX6P63l5Sk= github.com/dgraph-io/badger v1.6.0/go.mod h1:zwt7syl517jmP8s94KqSxTlM6IMsdhYy6psNgSztDR4= github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= @@ -64,14 +74,16 @@ github.com/eknkc/amber v0.0.0-20171010120322-cdade1c07385/go.mod h1:0vRUJqYpeSZi github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= +github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= github.com/envoyproxy/go-control-plane v0.9.9-0.20210217033140-668b12f5399d/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= +github.com/envoyproxy/go-control-plane v0.9.10-0.20210907150352-cf90f659a021/go.mod h1:AFq3mo9L8Lqqiid3OhADV3RfLJnjiw63cSpi+fDTRC0= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/envoyproxy/protoc-gen-validate v0.3.0-java h1:bV5JGEB1ouEzZa0hgVDFFiClrUEuGWRaAc/3mxR2QK0= +github.com/envoyproxy/protoc-gen-validate v0.3.0-java/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/etcd-io/bbolt v1.3.3/go.mod h1:ZF2nL25h33cCyBtcyWeZ2/I3HQOfTP+0PIEvHjkjCrw= github.com/fasthttp-contrib/websocket v0.0.0-20160511215533-1f3b11f56072/go.mod h1:duJ4Jxv5lDcvg4QuQr0oowTf7dz4/CR8NtyCooz9HL8= -github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M= github.com/flosch/pongo2 v0.0.0-20190707114632-bbf5a6c351f4/go.mod h1:T9YF2M40nIgbVgp3rreNmTged+9HrbNTIQf1PsaIiTA= -github.com/frankban/quicktest v1.14.0/go.mod h1:NeW+ay9A/U67EYXNFA1nPE8e/tnQv/09mUdL/ijj8og= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/gavv/httpexpect v2.0.0+incompatible/go.mod h1:x+9tiU1YnrOvnB725RkpoLv1M62hOWzwo5OXotisrKc= @@ -85,12 +97,15 @@ github.com/go-errors/errors v1.0.1/go.mod h1:f4zRHt4oKfwPJE5k8C9vpYG+aDHdBFUsgrm github.com/go-martini/martini v0.0.0-20170121215854-22fa46961aab/go.mod h1:/P9AEU963A2AYjv4d1V5eVL1CQbEJq6aCNHDDjibzu8= github.com/go-stack/stack v1.8.1 h1:ntEHSVwIt7PNXNpgPmVfMrNhLtgjlmnZha2kOpuRiDw= github.com/go-stack/stack v1.8.1/go.mod h1:dcoOX6HbPZSZptuspn9bctJ+N/CnF5gGygcUP3XYfe4= -github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y= github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8= github.com/gobwas/httphead v0.0.0-20180130184737-2c6c146eadee/go.mod h1:L0fX3K22YWvt/FAX9NnzrNzcI4wNYi9Yku4O0LKYflo= github.com/gobwas/pool v0.2.0/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw= github.com/gobwas/ws v1.0.2/go.mod h1:szmBTxLgaFppYjEmNtny/v3w89xOydFnnZMcgRRu/EM= +github.com/gofrs/flock v0.8.1 h1:+gYjHKf32LDeiEEFhQaotPbLuUXjY5ZqxKgXy7n59aw= +github.com/gofrs/flock v0.8.1/go.mod h1:F1TvTiK9OcQqauNUHlbJvyl9Qa1QvF/gOUDKA14jxHU= +github.com/gofrs/uuid v4.2.0+incompatible h1:yyYWMnhkhrKwwr8gAOcOCYxOOscHgDS9yZgBrnJfGa0= +github.com/gofrs/uuid v4.2.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= github.com/gogo/googleapis v0.0.0-20180223154316-0cd9801be74a/go.mod h1:gf4bu3Q80BeJ6H1S1vYPm8/ELATdvryBaNFGgqEef3s= github.com/gogo/googleapis v1.4.1/go.mod h1:2lpHqI5OcWCtVElxXnPt+s8oJvMpySlOyM6xDCrzib4= github.com/gogo/protobuf v1.2.0/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= @@ -100,6 +115,9 @@ github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69 github.com/gogo/status v1.1.0/go.mod h1:BFv9nrluPLmrS0EmGVvLaPNmRosr9KapBYd5/hpY1WM= github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE= +github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= @@ -112,7 +130,9 @@ github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:W github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw= github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/gomodule/redigo v1.7.1-0.20190724094224-574c33c3df38/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= @@ -121,33 +141,34 @@ github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMyw github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.7 h1:81/ik6ipDQS2aGcBfIN5dHDB36BwrStyeAQquSYCV4o= github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE= github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/grafana/regexp v0.0.0-20220202152701-6a046c4caf32 h1:M3wP8Hwic62qJsiydSgXtev03d4f92uN1I52nVjRgw0= github.com/grafana/regexp v0.0.0-20220202152701-6a046c4caf32/go.mod h1:M5qHK+eWfAv8VR/265dIuEpL3fNfeC21tXXp9itM24A= +github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= github.com/hashicorp/go-version v1.2.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= -github.com/hexops/autogold v0.8.1/go.mod h1:97HLDXyG23akzAoRYJh/2OBs3kd80eHyKPvZw0S5ZBY= -github.com/hexops/autogold v1.3.0/go.mod h1:d4hwi2rid66Sag+BVuHgwakW/EmaFr8vdTSbWDbrDRI= -github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg= -github.com/hexops/valast v1.4.0/go.mod h1:uVjKZ0smVuYlgCSPz9NRi5A04sl7lp6GtFWsROKDgEs= -github.com/hexops/valast v1.4.1/go.mod h1:G+D6TExWuKs5he+hYlPMfYyhQ8w8qbc2vm4gDWwLdDg= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/huandu/xstrings v1.0.0 h1:pO2K/gKgKaat5LdpAhxhluX2GPQMaI3W5FUz/I/UnWk= +github.com/huandu/xstrings v1.0.0/go.mod h1:4qWG/gcEcfX4z/mBDHJ++3ReCw9ibxbsNJbcucJdbSo= github.com/hydrogen18/memlistener v0.0.0-20141126152155-54553eb933fb/go.mod h1:qEIFzExnS6016fRpRfxrExeVn2gbClQA99gQhnIcdhE= github.com/hydrogen18/memlistener v0.0.0-20200120041712-dcc25e7acd91/go.mod h1:qEIFzExnS6016fRpRfxrExeVn2gbClQA99gQhnIcdhE= +github.com/imdario/mergo v0.3.4 h1:mKkfHkZWD8dC7WxKx3N9WCF0Y+dLau45704YQmY6H94= +github.com/imdario/mergo v0.3.4/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= github.com/imkira/go-interpol v1.1.0/go.mod h1:z0h2/2T3XF8kyEPpRgJ3kmNv+C43p+I/CoI+jC3w2iA= github.com/inconshreveable/log15 v0.0.0-20201112154412-8562bdadbbac h1:n1DqxAo4oWPMvH1+v+DLYlMCecgumhhgnxAPdqDIFHI= github.com/inconshreveable/log15 v0.0.0-20201112154412-8562bdadbbac/go.mod h1:cOaXtrgN4ScfRrD9Bre7U1thNq5RtJ8ZoP4iXVGRj6o= +github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/iris-contrib/blackfriday v2.0.0+incompatible/go.mod h1:UzZ2bDEoaSGPbkg6SAB4att1aAwTmVIx/5gCVqeyUdI= github.com/iris-contrib/go.uuid v2.0.0+incompatible/go.mod h1:iz2lgM/1UnEf1kP0L/+fafWORmlnuysV2EMP8MW+qe0= @@ -155,6 +176,16 @@ github.com/iris-contrib/i18n v0.0.0-20171121225848-987a633949d0/go.mod h1:pMCz62 github.com/iris-contrib/jade v1.1.3/go.mod h1:H/geBymxJhShH5kecoiOCSssPX7QWYH7UaeZTSWddIk= github.com/iris-contrib/pongo2 v0.0.1/go.mod h1:Ssh+00+3GAZqSQb30AvBRNxBx7rf0GqwkjqxNd0u65g= github.com/iris-contrib/schema v0.0.1/go.mod h1:urYA3uvUNG1TIIjOSCzHr9/LmbQo8LrOcOqfqxa4hXw= +github.com/jdxcode/netrc v0.0.0-20210204082910-926c7f70242a h1:d4+I1YEKVmWZrgkt6jpXBnLgV2ZjO0YxEtLDdfIZfH4= +github.com/jdxcode/netrc v0.0.0-20210204082910-926c7f70242a/go.mod h1:Zi/ZFkEqFHTm7qkjyNJjaWH4LQA9LQhGJyF0lTYGpxw= +github.com/jhump/gopoet v0.0.0-20190322174617-17282ff210b3/go.mod h1:me9yfT6IJSlOL3FCfrg+L6yzUEZ+5jW6WHt4Sk+UPUI= +github.com/jhump/gopoet v0.1.0/go.mod h1:me9yfT6IJSlOL3FCfrg+L6yzUEZ+5jW6WHt4Sk+UPUI= +github.com/jhump/goprotoc v0.5.0/go.mod h1:VrbvcYrQOrTi3i0Vf+m+oqQWk9l72mjkJCYo7UvLHRQ= +github.com/jhump/protocompile v0.0.0-20220216033700-d705409f108f h1:BNuUg9k2EiJmlMwjoef3e8vZLHplbVw6DrjGFjLL+Yo= +github.com/jhump/protocompile v0.0.0-20220216033700-d705409f108f/go.mod h1:qr2b5kx4HbFS7/g4uYO5qv9ei8303JMsC7ESbYiqr2Q= +github.com/jhump/protoreflect v1.11.0/go.mod h1:U7aMIjN0NWq9swDP7xDdoMfRHb35uiuTd3Z9nFXJf5E= +github.com/jhump/protoreflect v1.12.1-0.20220417024638-438db461d753 h1:uFlcJKZPLQd7rmOY/RrvBuUaYmAFnlFHKLivhO6cOy8= +github.com/jhump/protoreflect v1.12.1-0.20220417024638-438db461d753/go.mod h1:JytZfP5d0r8pVNLZvai7U/MCuTWITgrI4tTg7puQFKI= github.com/jig/teereadcloser v0.0.0-20181016160506-953720c48e05 h1:dSwwtWuwMyarzsbVWOq4QJ8xVy9wgcNomvWyGtrKe+E= github.com/jig/teereadcloser v0.0.0-20181016160506-953720c48e05/go.mod h1:sRUFlj+HCejvoCRpuhU0EYnNw5FG+YJpz8UFfCf0F2U= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= @@ -183,8 +214,8 @@ github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+o github.com/klauspost/compress v1.8.2/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= github.com/klauspost/compress v1.9.0/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= github.com/klauspost/compress v1.9.7/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= -github.com/klauspost/compress v1.14.2 h1:S0OHlFk/Gbon/yauFJ4FfJJF5V0fc5HbBTJazi28pRw= -github.com/klauspost/compress v1.14.2/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= +github.com/klauspost/compress v1.15.1 h1:y9FcTHGyrebwfP0ZZqFiaxTaiDnUrGkJkI+f583BL1A= +github.com/klauspost/compress v1.15.1/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= github.com/klauspost/cpuid v1.2.1/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek= github.com/klauspost/pgzip v1.2.5 h1:qnWYvvKqedOF2ulHpMG72XQol4ILEJ8k2wwRl/Km8oE= github.com/klauspost/pgzip v1.2.5/go.mod h1:Ch1tH69qFZu15pkjo5kYi6mth2Zzwzt50oCQKQE9RUs= @@ -202,7 +233,6 @@ github.com/labstack/gommon v0.3.0/go.mod h1:MULnywXg0yavhxWKc+lOruYdAhDwPK9wf0OL github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= -github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-colorable v0.1.11/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= github.com/mattn/go-colorable v0.1.12 h1:jF+Du6AlPIjs2BiUiQlKOX0rt3SujHxPnksPKZbaA40= github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= @@ -221,12 +251,9 @@ github.com/mediocregopher/radix/v3 v3.3.0/go.mod h1:EmfVyvspXz1uZEyPBMyGK+kjWiKQ github.com/mediocregopher/radix/v3 v3.4.2/go.mod h1:8FL3F6UQRXHXIBSPUs5h0RybMF8i4n7wVopoX3x7Bv8= github.com/microcosm-cc/bluemonday v1.0.2/go.mod h1:iVP4YcDBq+n/5fb23BhYFvIMq/leAFZyRl6bYmGDlGc= github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw= -github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= -github.com/mitchellh/go-wordwrap v1.0.1/go.mod h1:R62XHJLzvMFRBbcrT7m7WgmE1eOyTSsCt+hzestvNj0= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ= -github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= github.com/moby/term v0.0.0-20210619224110-3f7ff695adc6 h1:dcztxKSvZ4Id8iPpHERQBbIJfabdt4wUm5qy3wOL2Zc= github.com/moby/term v0.0.0-20210619224110-3f7ff695adc6/go.mod h1:E2VnQOmVuvZB6UYnnDB0qG5Nq/1tD9acaOpo6xmt0Kw= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -237,6 +264,8 @@ github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3Rllmb github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/moul/http2curl v1.0.0/go.mod h1:8UbvGypXm98wA/IqH45anm5Y2Z6ep6O31QGOAZ3H0fQ= +github.com/mwitkow/go-proto-validators v0.0.0-20180403085117-0950a7990007 h1:28i1IjGcx8AofiB4N3q5Yls55VEaitzuEPkFJEVgGkA= +github.com/mwitkow/go-proto-validators v0.0.0-20180403085117-0950a7990007/go.mod h1:m2XC9Qq0AlmmVksL6FktJCdTYyLk7V3fKyp0sl1yWQo= github.com/nats-io/jwt v0.3.0/go.mod h1:fRYCDE99xlTsqUzISS1Bi75UBJ6ljOJQOAAu5VglpSg= github.com/nats-io/nats.go v1.8.1/go.mod h1:BrFz9vVn0fU3AcH9Vn4Kd7W0NpJ651tD5omQ3M8LwxM= github.com/nats-io/nats.go v1.9.1/go.mod h1:ZjDU1L/7fJ09jvUSRVBR2e7+RnLiiIQyqyzEE/Zbp4w= @@ -245,39 +274,44 @@ github.com/nats-io/nkeys v0.1.0/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxzi github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c= github.com/neelance/parallel v0.0.0-20160708114440-4de9ce63d14c h1:NZOii9TDGRAfCS5VM16XnF4K7afoLQmIiZX8EkKnxtE= github.com/neelance/parallel v0.0.0-20160708114440-4de9ce63d14c/go.mod h1:eTBvSIlRgLo+CNFFQRQTwUGTZOEdvXIKeZS/xG+D2yU= -github.com/nightlyone/lockfile v1.0.0/go.mod h1:rywoIealpdNse2r832aiD9jRk8ErCatROs6LzC841CI= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= -github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec= github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.10.3/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= github.com/onsi/ginkgo v1.13.0/go.mod h1:+REjRxOmWfHCjfv9TTWB1jD1Frx4XydAD3zm1lskyM0= -github.com/onsi/ginkgo v1.16.2/go.mod h1:CObGmKUOKaSC0RjmoAK7tKyn4Azo5P2IWuoMnvwxz1E= github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= -github.com/onsi/gomega v1.13.0/go.mod h1:lRk9szgn8TxENtWd0Tp4c3wjlRfMTMH27I+3Je41yGY= github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4= github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8= -github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4 h1:49lOXmGaUpV9Fz3gd7TFZY106KVlPVa5jcYD1gaQf98= -github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4/go.mod h1:4OwLy04Bl9Ef3GJJCoec+30X3LQs/0/m4HFRt/2LUSA= +github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 h1:KoWmjvw+nsYOo29YJK9vDA65RGE3NrOnUtO7a+RF9HU= +github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8/go.mod h1:HKlIX3XHQyzLZPlr7++PzdhaXEj94dEiJgZDTsxEqUI= github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/profile v1.6.0 h1:hUDfIISABYI59DyeB3OTay/HxSRwTQ8rB/H83k6r5dM= +github.com/pkg/profile v1.6.0/go.mod h1:qBsxPvzyUincmltOk6iyRVxHYg4adc0OFOv72ZdLa18= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/pseudomuto/protoc-gen-doc v1.5.1 h1:Ah259kcrio7Ix1Rhb6u8FCaOkzf9qRBqXnvAufg061w= +github.com/pseudomuto/protoc-gen-doc v1.5.1/go.mod h1:XpMKYg6zkcpgfpCfQ8GcWBDRtRxOmMR5w7pz4Xo+dYM= +github.com/pseudomuto/protokit v0.2.0 h1:hlnBDcy3YEDXH7kc9gV+NLaN0cDzhDvD1s7Y6FZ8RpM= +github.com/pseudomuto/protokit v0.2.0/go.mod h1:2PdH30hxVHsup8KpBTOXTBeMVhJZVio3Q8ViKSAXT0Q= github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY= github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= +github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= -github.com/rogpeppe/go-internal v1.6.2/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= -github.com/rogpeppe/go-internal v1.8.1-0.20211023094830-115ce09fd6b4/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= github.com/rogpeppe/go-internal v1.8.1 h1:geMPLpDpQOgVyCg5z5GoRwLHepNdb71NXb67XFkP+Eg= github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= +github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/ryanuber/columnize v2.1.0+incompatible/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= github.com/schollz/closestmatch v2.1.0+incompatible/go.mod h1:RtP1ddjLong6gTkbtmuhtR2uUrrJOpYzYRvbcPAid+g= github.com/sclevine/agouti v3.0.0+incompatible/go.mod h1:b4WX9W9L1sfQKXeJf1mUTLZKJ48R1S7H23Ji7oFO5Bw= @@ -285,24 +319,28 @@ github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAm github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= github.com/shurcooL/go v0.0.0-20180423040247-9e1955d9fb6e/go.mod h1:TDJrrUr11Vxrven61rcy3hJMUqaf/CLWYhHNPmT14Lk= github.com/shurcooL/go-goon v0.0.0-20170922171312-37c2f522c041/go.mod h1:N5mDOmsrJOB+vfqUK+7DmDyjhSLIIBnXo9lvZJj3MWQ= -github.com/shurcooL/go-goon v0.0.0-20210110234559-7585751d9a17/go.mod h1:N5mDOmsrJOB+vfqUK+7DmDyjhSLIIBnXo9lvZJj3MWQ= github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= -github.com/smacker/go-tree-sitter v0.0.0-20220209044044-0d3022e933c3/go.mod h1:EiUuVMUfLQj8Sul+S8aKWJwQy7FRYnJCO2EWzf8F5hk= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= github.com/sourcegraph/go-diff v0.6.1 h1:hmA1LzxW0n1c3Q4YbrFgg4P99GSnebYa3x8gr0HZqLQ= github.com/sourcegraph/go-diff v0.6.1/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20220506010657-06e02488a3d7 h1:YgPugK3f2y4cEfPH+Tb45yYymSTCZAaZ2nAQO81EZU4= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20220506010657-06e02488a3d7/go.mod h1:nuweF6uGn0mCNzMAbCiLbje6MkZwUmhXaFA4w30/ZfU= +github.com/sourcegraph/scip v0.0.0-20220513191902-a9bebaa57565 h1:EKtJLeanygtO/BB3ZLGoHiCdYq9PJdgYzYzAErm7EdU= +github.com/sourcegraph/scip v0.0.0-20220513191902-a9bebaa57565/go.mod h1:Y+5w4gBKMnbSDC/5yD03kLTM/sx3449lPrXxloueWDA= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20220511160847-5a43d3ea24eb h1:D8ciD0FEcPNnVm6BC8vg7gWJ9VxoJe6k/4j+Qxparj0= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20220511160847-5a43d3ea24eb/go.mod h1:iFiGPqnhOvQziDZkpWasU+Uo1BaEt/Au9kNK4VpqyOw= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU= +github.com/spf13/cobra v1.4.0 h1:y+wJpx64xcgO1V+RcnwW0LEHxTKRi2ZDPSBjWnrg88Q= +github.com/spf13/cobra v1.4.0/go.mod h1:Wo4iy3BUC+X2Fybo0PDqwJIv3dNRiZLHQymsfxlB84g= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= +github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= +github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s= github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf h1:pvbZ0lM0XWPBqUKqFU8cmavspvIl9nulOYwdy6IFRRo= github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf/go.mod h1:RJID2RhlZKId02nZ62WenDCkgHFerpIOmW0iT7GKmXM= @@ -340,10 +378,18 @@ github.com/yudai/pp v2.0.1+incompatible/go.mod h1:PuxR/8QJ7cyCkFp/aUDS+JY727OFEZ github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= -github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +go.opencensus.io v0.23.0 h1:gqCw0LfLxScz8irSi8exQc7fyQ0fKQU/qnC/X8+V/1M= +go.opencensus.io v0.23.0/go.mod h1:XItmlyltB5F7CS4xOC1DcqMoFqwtC6OG2xF7mCv7P7E= +go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI= go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= +go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE= +go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= +go.uber.org/goleak v1.1.11 h1:wy28qYRKZgnJTxGxvye5/wgWr1EKjmUDGYox5mGlRlI= go.uber.org/goleak v1.1.11/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ= go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= +go.uber.org/multierr v1.8.0 h1:dg6GjLku4EH+249NNmoIciG9N/jURbDG+pFlTkhzIC8= +go.uber.org/multierr v1.8.0/go.mod h1:7EAYxJLBy9rStEaz58O2t4Uvip6FSURkq8/ppBp95ak= +go.uber.org/zap v1.21.0 h1:WefMeulhovoZ2sYXz7st6K0sLj7bBhpiFaud4r4zST8= go.uber.org/zap v1.21.0/go.mod h1:wjWOCqI0f2ZZrJF/UufIOkiC8ii6tm1iqIsLo76RfJw= golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= @@ -352,6 +398,7 @@ golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8U golang.org/x/crypto v0.0.0-20191227163750-53104e6ec876/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 h1:7I4JAnoQBe7ZtJcBaYHi5UtiO8tQHbUSXxL+pnGRANg= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= @@ -362,14 +409,14 @@ golang.org/x/lint v0.0.0-20210508222113-6edffad5e616/go.mod h1:3xt1FjdF8hUf6vQPI golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro= +golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3 h1:kQgndtyPBW/JIYERgdxfwMYh3AVStj88WQTlNDi2a+o= +golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3/go.mod h1:3p9vT2HGsQu2K1YbXdKPJLVgG5VJdoTa1poYQBtP1AY= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190327091125-710a502c58a2/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= @@ -380,18 +427,20 @@ golang.org/x/net v0.0.0-20190827160401-ba9fcec4b297/go.mod h1:z5CRVTTTmAJ677TzLL golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= -golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk= -golang.org/x/net v0.0.0-20210614182718-04defd469f4e/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211008194852-3b03d305991f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/net v0.0.0-20220325170049-de3da57026de h1:pZB1TWnKi+o4bENlbzAgLrEbY4RMYmUIRobMcSmfeYc= -golang.org/x/net v0.0.0-20220325170049-de3da57026de/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= +golang.org/x/net v0.0.0-20220412020605-290c469a71a5 h1:bRb386wvrE+oBNdF1d/Xh9mQrfQ4ecYhW5qJ5GvTGT4= +golang.org/x/net v0.0.0-20220412020605-290c469a71a5/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -415,32 +464,28 @@ golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20200519105757-fe76b779f299/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210218084038-e8e29180ff58/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210403161142-5e06dd20ab57/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210611083646-a4fc73990273/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210616045830-e2b7044e8c71/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211007075335-d3039528d8ac/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20211102192858-4dd72447c267/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20211117180635-dee7805ff2e1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20211213223007-03aa0b5f6827/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6 h1:nonptSpoQ4vQjyraW20DXPAglgQfVnM9ZC6MmNLMR60= golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20220411215600-e5f449aeb171 h1:EH1Deb8WZJ0xc0WK//leUHXcX9aLE5SymusoTmMZye8= +golang.org/x/term v0.0.0-20220411215600-e5f449aeb171/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/time v0.0.0-20201208040808-7e3f01d25324/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -457,15 +502,11 @@ golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtn golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200624163319-25775e59acb7/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.0.0-20210101214203-2dba1e4ea05c/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= -golang.org/x/tools v0.1.8-0.20211102182255-bb4add04ddef/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= -golang.org/x/tools v0.1.8/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= -golang.org/x/tools v0.1.9/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= +golang.org/x/tools v0.1.10 h1:QjFRCZxdOhBJ/UNgnBZLbNV13DlbnK0quyivTnXJM20= +golang.org/x/tools v0.1.10/go.mod h1:Uh6Zz+xoGYZom868N8YTex3t7RhtHDBrE8Gzo9bV56E= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -477,15 +518,23 @@ google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7 google.golang.org/genproto v0.0.0-20180518175338-11a468237815/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20200513103714-09dca8ec2884/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= google.golang.org/genproto v0.0.0-20210624195500-8bfb893ecb84/go.mod h1:SzzZ/N+nwJDaO1kznhnlzqS8ocJICar6hYhVyhi++24= +google.golang.org/genproto v0.0.0-20220414192740-2d67ff6cf2b4 h1:myaecH64R0bIEDjNORIel4iXubqzaHU1K2z8ajBwWcM= +google.golang.org/genproto v0.0.0-20220414192740-2d67ff6cf2b4/go.mod h1:8w6bsBMX6yCPbAVTeqQHvzxW0EIFigd5lZyahWgyfDo= google.golang.org/grpc v1.12.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= +google.golang.org/grpc v1.33.1/go.mod h1:fr5YgcSWrqhRRxogOsw7RzIpsmvOZ6IcH4kBYTpR3n0= +google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= +google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= google.golang.org/grpc v1.38.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= +google.golang.org/grpc v1.45.0 h1:NEpgUqV3Z+ZjkqMsxMg11IaDrXY4RY6CQukSGK0uI1M= +google.golang.org/grpc v1.45.0/go.mod h1:lN7owxKUQEqMfSyQikvvk5tf/6zMPsrK+ONuO11+0rQ= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= @@ -497,12 +546,14 @@ google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpAD google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -google.golang.org/protobuf v1.27.1 h1:SnqbnDw1V7RiZcXPx5MEeqPv2s79L9i7BJUlG/+RurQ= -google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +google.golang.org/protobuf v1.27.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +google.golang.org/protobuf v1.28.0 h1:w43yiav+6bVFTBQFZX0r7ipe9JQ1QsbMgHwbBziscLw= +google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b h1:QRR6H1YWRnHb4Y/HeNFCTJLFVxaq6wH4YuVdsUOr75U= +gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= gopkg.in/go-playground/assert.v1 v1.2.1/go.mod h1:9RXL0bg/zibRAgZUYszZSwO/z8Y/a8bDuhia5mkpMnE= @@ -511,6 +562,7 @@ gopkg.in/ini.v1 v1.51.1/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/mgo.v2 v2.0.0-20180705113604-9856a29383ce/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= @@ -526,7 +578,3 @@ honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWh honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7 h1:mub0MmFLOn8XLikZOAhgLD1kXJq8jgftSrrv7m00xFo= jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7/go.mod h1:OxvTsCwKosqQ1q7B+8FwXqg4rKZ/UG9dUW+g/VL2xH4= -mvdan.cc/gofumpt v0.0.0-20210107193838-d24d34e18d44/go.mod h1:yXG1r1WqZVKWbVRtBWKWX9+CxGYfA51nSomhM0woR48= -mvdan.cc/gofumpt v0.1.0/go.mod h1:yXG1r1WqZVKWbVRtBWKWX9+CxGYfA51nSomhM0woR48= -mvdan.cc/gofumpt v0.2.0/go.mod h1:TiGmrf914DAuT6+hDIxOqoDb4QXIzAuEUSXqEf9hGKY= -mvdan.cc/gofumpt v0.2.1/go.mod h1:a/rvZPhsNaedOJBzqRD9omnwVwHZsBdJirXHa9Gh9Ig= From 4ccd587b0700379b4addf008925b4b8f6ac93579 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Mon, 16 May 2022 11:39:46 +0200 Subject: [PATCH 165/647] Bump golang in asdf to 1.18 (#746) --- .tool-versions | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.tool-versions b/.tool-versions index e5c4ae8b67..5521e49283 100644 --- a/.tool-versions +++ b/.tool-versions @@ -1,3 +1,3 @@ -golang 1.17.5 +golang 1.18.1 shfmt 3.2.0 shellcheck 0.7.1 From f8cd1385d7f1cec72aa815b5993dd423c563bd33 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Mon, 16 May 2022 12:02:09 +0200 Subject: [PATCH 166/647] Prepare changelog for 3.40 release (#747) --- CHANGELOG.md | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0ab10f1e4d..00a838498c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,9 +12,6 @@ All notable changes to `src-cli` are documented in this file. ## Unreleased ### Added -- New command `src debug`. [#731](https://github.com/sourcegraph/src-cli/pull/731) -- `src lsif upload` now supports the `-gitlab-token` flag. [#721](https://github.com/sourcegraph/src-cli/pull/721) -- Batch Changes can be applied to Bitbucket Cloud when `src` is used with Sourcegraph 3.40 or later. [#725](https://github.com/sourcegraph/src-cli/pull/725) ### Changed @@ -22,6 +19,18 @@ All notable changes to `src-cli` are documented in this file. ### Removed +## 3.40.0 + +### Added + +- New command `src debug`. [#731](https://github.com/sourcegraph/src-cli/pull/731) +- `src lsif upload` now supports the `-gitlab-token` flag. [#721](https://github.com/sourcegraph/src-cli/pull/721) +- Batch Changes can be applied to Bitbucket Cloud when `src` is used with Sourcegraph 3.40 or later. [#725](https://github.com/sourcegraph/src-cli/pull/725) + +### Changed + +- src CLI is now built using go 1.18. + ## 3.39.0 ### Added From 29df2bdd38be4a72a7244e2fa0b3ac7543a98250 Mon Sep 17 00:00:00 2001 From: Eric Fritz Date: Wed, 18 May 2022 11:11:55 -0500 Subject: [PATCH 167/647] chore: Follow up to #731 (#743) --- cmd/src/debug_compose.go | 15 +++++++-------- cmd/src/debug_kube.go | 17 +++++++++-------- cmd/src/debug_server.go | 16 ++++++++-------- 3 files changed, 24 insertions(+), 24 deletions(-) diff --git a/cmd/src/debug_compose.go b/cmd/src/debug_compose.go index 9fb764f78a..8bc3b01095 100644 --- a/cmd/src/debug_compose.go +++ b/cmd/src/debug_compose.go @@ -9,12 +9,11 @@ import ( "os" "os/exec" "path/filepath" + "runtime" "strings" "github.com/sourcegraph/sourcegraph/lib/errors" - "golang.org/x/sync/errgroup" - "golang.org/x/sync/semaphore" ) @@ -42,9 +41,9 @@ Examples: flagSet := flag.NewFlagSet("compose", flag.ExitOnError) var base string - var noConfigs bool + var excludeConfigs bool flagSet.StringVar(&base, "o", "debug.zip", "The name of the output zip archive") - flagSet.BoolVar(&noConfigs, "no-configs", false, "If true include Sourcegraph configuration files. Default value true.") + flagSet.BoolVar(&excludeConfigs, "no-configs", false, "If true, exclude Sourcegraph configuration files. Defaults to false.") handler := func(args []string) error { if err := flagSet.Parse(args); err != nil { @@ -81,7 +80,7 @@ Examples: return nil } - err = archiveCompose(ctx, zw, *verbose, noConfigs, baseDir) + err = archiveCompose(ctx, zw, *verbose, !excludeConfigs, baseDir) if err != nil { return err } @@ -98,7 +97,7 @@ Examples: } // writes archive of common docker cli commands -func archiveCompose(ctx context.Context, zw *zip.Writer, verbose, noConfigs bool, baseDir string) error { +func archiveCompose(ctx context.Context, zw *zip.Writer, verbose, archiveConfigs bool, baseDir string) error { ctx, cancel := context.WithCancel(ctx) defer cancel() @@ -114,7 +113,7 @@ func archiveCompose(ctx context.Context, zw *zip.Writer, verbose, noConfigs bool // setup channel for slice of archive function outputs ch := make(chan *archiveFile) g, ctx := errgroup.WithContext(ctx) - semaphore := semaphore.NewWeighted(8) + semaphore := semaphore.NewWeighted(int64(runtime.GOMAXPROCS(0))) run := func(f func() *archiveFile) { g.Go(func() error { @@ -150,7 +149,7 @@ func archiveCompose(ctx context.Context, zw *zip.Writer, verbose, noConfigs bool } // start goroutine to get configs - if !noConfigs { + if archiveConfigs { run(func() *archiveFile { return getExternalServicesConfig(ctx, baseDir) }) run(func() *archiveFile { return getSiteConfig(ctx, baseDir) }) diff --git a/cmd/src/debug_kube.go b/cmd/src/debug_kube.go index 9e3dfdaf7e..69af7571e9 100644 --- a/cmd/src/debug_kube.go +++ b/cmd/src/debug_kube.go @@ -10,18 +10,19 @@ import ( "log" "os" "path/filepath" + "runtime" + "github.com/sourcegraph/sourcegraph/lib/errors" "golang.org/x/sync/errgroup" - "golang.org/x/sync/semaphore" - "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/exec" ) func init() { usage := ` 'src debug kube' invokes kubectl diagnostic commands targeting kubectl's current-context, writing returns to an archive. + Usage: src debug kube [command options] @@ -45,10 +46,10 @@ Examples: flagSet := flag.NewFlagSet("kube", flag.ExitOnError) var base string var namespace string - var noConfigs bool + var excludeConfigs bool flagSet.StringVar(&base, "o", "debug.zip", "The name of the output zip archive") flagSet.StringVar(&namespace, "n", "default", "The namespace passed to kubectl commands, if not specified the 'default' namespace is used") - flagSet.BoolVar(&noConfigs, "no-configs", false, "If true include Sourcegraph configuration files. Default value true.") + flagSet.BoolVar(&excludeConfigs, "no-configs", false, "If true, exclude Sourcegraph configuration files. Defaults to false.") handler := func(args []string) error { if err := flagSet.Parse(args); err != nil { @@ -88,7 +89,7 @@ Examples: return nil } - err = archiveKube(ctx, zw, *verbose, noConfigs, namespace, baseDir, pods) + err = archiveKube(ctx, zw, *verbose, !excludeConfigs, namespace, baseDir, pods) if err != nil { return err } @@ -118,7 +119,7 @@ type podList struct { } // Runs common kubectl functions and archive results to zip file -func archiveKube(ctx context.Context, zw *zip.Writer, verbose, noConfigs bool, namespace, baseDir string, pods podList) error { +func archiveKube(ctx context.Context, zw *zip.Writer, verbose, archiveConfigs bool, namespace, baseDir string, pods podList) error { // Create a context with a cancel function that we call when returning // from archiveKube. This ensures we close all pending go-routines when returning // early because of an error. @@ -128,7 +129,7 @@ func archiveKube(ctx context.Context, zw *zip.Writer, verbose, noConfigs bool, n // setup channel for slice of archive function outputs, as well as throttling semaphore ch := make(chan *archiveFile) g, ctx := errgroup.WithContext(ctx) - semaphore := semaphore.NewWeighted(8) + semaphore := semaphore.NewWeighted(int64(runtime.GOMAXPROCS(0))) run := func(f func() *archiveFile) { g.Go(func() error { @@ -198,7 +199,7 @@ func archiveKube(ctx context.Context, zw *zip.Writer, verbose, noConfigs bool, n } // start goroutine to get external service config - if !noConfigs { + if archiveConfigs { run(func() *archiveFile { return getExternalServicesConfig(ctx, baseDir) }) run(func() *archiveFile { return getSiteConfig(ctx, baseDir) }) diff --git a/cmd/src/debug_server.go b/cmd/src/debug_server.go index 4705ce2c1e..8ef59fc02a 100644 --- a/cmd/src/debug_server.go +++ b/cmd/src/debug_server.go @@ -8,11 +8,11 @@ import ( "log" "os" "path/filepath" + "runtime" + "github.com/sourcegraph/sourcegraph/lib/errors" "golang.org/x/sync/errgroup" "golang.org/x/sync/semaphore" - - "github.com/sourcegraph/sourcegraph/lib/errors" ) func init() { @@ -40,10 +40,10 @@ Examples: flagSet := flag.NewFlagSet("server", flag.ExitOnError) var base string var container string - var noConfigs bool + var excludeConfigs bool flagSet.StringVar(&base, "o", "debug.zip", "The name of the output zip archive") flagSet.StringVar(&container, "c", "", "The container to target") - flagSet.BoolVar(&noConfigs, "no-configs", false, "If true include Sourcegraph configuration files. Default value true.") + flagSet.BoolVar(&excludeConfigs, "no-configs", false, "If true, exclude Sourcegraph configuration files. Defaults to false.") handler := func(args []string) error { if err := flagSet.Parse(args); err != nil { @@ -77,7 +77,7 @@ Examples: return nil } - err = archiveServ(ctx, zw, *verbose, noConfigs, container, baseDir) + err = archiveServ(ctx, zw, *verbose, !excludeConfigs, container, baseDir) if err != nil { return err } @@ -94,14 +94,14 @@ Examples: } // Runs common docker cli commands on a single container -func archiveServ(ctx context.Context, zw *zip.Writer, verbose, noConfigs bool, container, baseDir string) error { +func archiveServ(ctx context.Context, zw *zip.Writer, verbose, archiveConfigs bool, container, baseDir string) error { ctx, cancel := context.WithCancel(ctx) defer cancel() // setup channel for slice of archive function outputs ch := make(chan *archiveFile) g, ctx := errgroup.WithContext(ctx) - semaphore := semaphore.NewWeighted(8) + semaphore := semaphore.NewWeighted(int64(runtime.GOMAXPROCS(0))) run := func(f func() *archiveFile) { g.Go(func() error { @@ -128,7 +128,7 @@ func archiveServ(ctx context.Context, zw *zip.Writer, verbose, noConfigs bool, c run(func() *archiveFile { return getServTop(ctx, container, baseDir) }) // start goroutine to get configs - if !noConfigs { + if archiveConfigs { run(func() *archiveFile { return getExternalServicesConfig(ctx, baseDir) }) run(func() *archiveFile { return getSiteConfig(ctx, baseDir) }) From 3f6f3147673c739476fba9cf3f514b7305de87ed Mon Sep 17 00:00:00 2001 From: Varun Gandhi Date: Wed, 18 May 2022 11:49:36 -0700 Subject: [PATCH 168/647] Add src code-intel alias for src lsif (#748) --- CHANGELOG.md | 1 + Dockerfile | 2 +- Dockerfile.release | 2 +- README.markdown | 3 +- cmd/src/code_intel.go | 38 +++++ .../{lsif_upload.go => code_intel_upload.go} | 141 ++++++++++-------- ...ad_flags.go => code_intel_upload_flags.go} | 118 +++++++-------- ...est.go => code_intel_upload_flags_test.go} | 12 +- cmd/src/lsif.go | 13 +- cmd/src/main.go | 4 +- 10 files changed, 190 insertions(+), 144 deletions(-) create mode 100644 cmd/src/code_intel.go rename cmd/src/{lsif_upload.go => code_intel_upload.go} (56%) rename cmd/src/{lsif_upload_flags.go => code_intel_upload_flags.go} (57%) rename cmd/src/{lsif_upload_flags_test.go => code_intel_upload_flags_test.go} (89%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 00a838498c..9c15079c52 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ All notable changes to `src-cli` are documented in this file. ## Unreleased ### Added +- `src code-intel` is a new alias for `src lsif`. [#748](https://github.com/sourcegraph/src-cli/pull/748) ### Changed diff --git a/Dockerfile b/Dockerfile index 61caec7f07..002f58fc45 100644 --- a/Dockerfile +++ b/Dockerfile @@ -13,7 +13,7 @@ RUN go build ./cmd/src # This stage should be kept in sync with Dockerfile.release. FROM sourcegraph/alpine:3.12@sha256:ce099fbcd3cf70b338fc4cb2a4e1fa9ae847de21afdb0a849a393b87d94fb174 -# needed for `src lsif upload` and `src actions exec` +# needed for `src code-intel upload` and `src actions exec` RUN apk add --no-cache git COPY --from=builder /src/src /usr/bin/ diff --git a/Dockerfile.release b/Dockerfile.release index ed388c09c1..ca2e3d321d 100644 --- a/Dockerfile.release +++ b/Dockerfile.release @@ -4,7 +4,7 @@ # the main Dockerfile, which should have an identical second stage. FROM sourcegraph/alpine:3.12@sha256:ce099fbcd3cf70b338fc4cb2a4e1fa9ae847de21afdb0a849a393b87d94fb174 -# needed for `src lsif upload` and `src actions exec` +# needed for `src code-intel upload` and `src actions exec` RUN apk add --no-cache git COPY src /usr/bin/ diff --git a/README.markdown b/README.markdown index 6e37d47cdd..f26bf9b1ee 100644 --- a/README.markdown +++ b/README.markdown @@ -111,7 +111,8 @@ Is your Sourcegraph instance behind a custom auth proxy? See [auth proxy configu - `src config` - manage global, org, and user settings - `src extsvc` - manage external services (repository configuration) - `src extensions` - manage extensions - - `src lsif` - manages LSIF data + - `src code-intel` - manages Code Intelligence data + - `src lsif` - manages LSIF data (DEPRECATED: use `src code-intel` instead) - `src serve-git` - serves your local git repositories over HTTP for Sourcegraph to pull - `src version` - check version and guaranteed-compatible version for your Sourcegraph instance diff --git a/cmd/src/code_intel.go b/cmd/src/code_intel.go new file mode 100644 index 0000000000..e75ac73f8c --- /dev/null +++ b/cmd/src/code_intel.go @@ -0,0 +1,38 @@ +package main + +import ( + "flag" + "fmt" +) + +var codeintelCommands commander + +func init() { + usage := `'src code-intel' manages code intelligence data on a Sourcegraph instance. + +Usage: + + src code-intel command [command options] + +The commands are: + + upload uploads an LSIF dump file + +Use "src code-intel [command] -h" for more information about a command. +` + flagSet := flag.NewFlagSet("code-intel", flag.ExitOnError) + handler := func(args []string) error { + lsifCommands.run(flagSet, "src code-intel", usage, args) + return nil + } + + // Register the command. + commands = append(commands, &command{ + flagSet: flagSet, + aliases: []string{"code-intel"}, + handler: handler, + usageFunc: func() { + fmt.Println(usage) + }, + }) +} diff --git a/cmd/src/lsif_upload.go b/cmd/src/code_intel_upload.go similarity index 56% rename from cmd/src/lsif_upload.go rename to cmd/src/code_intel_upload.go index 6a751dba45..ac57fc9c12 100644 --- a/cmd/src/lsif_upload.go +++ b/cmd/src/code_intel_upload.go @@ -24,41 +24,54 @@ func init() { usage := ` Examples: - Upload an LSIF dump with explicit repo, commit, and upload files: + Upload a SCIP index with explicit repo, commit, and upload files: - $ src lsif upload -repo=FOO -commit=BAR -file=dump.lsif + $ src code-intel upload -repo=FOO -commit=BAR -file=index.scip - Upload an LSIF dump for a subproject: + Upload a SCIP index for a subproject: - $ src lsif upload -root=cmd/ + $ src code-intel upload -root=cmd/ - Upload an LSIF dump when lsifEnforceAuth is enabled: + Upload a SCIP index when lsifEnforceAuth is enabled: - $ src lsif upload -github-token=BAZ, or - $ src lsif upload -gitlab-token=BAZ + $ src code-intel upload -github-token=BAZ, or + $ src code-intel upload -gitlab-token=BAZ - Upload an LSIF dump when the LSIF indexer does not not declare a tool name. + Upload an LSIF index when the LSIF indexer does not not declare a tool name. - $ src lsif upload -indexer=lsif-elixir + $ src code-intel upload -indexer=lsif-elixir + + For any of these commands, an LSIF index (default name: dump.lsif) can be + used instead of a SCIP index (default name: index.scip). ` + codeintelCommands = append(codeintelCommands, &command{ + flagSet: codeintelUploadFlagSet, + handler: handleCodeIntelUpload, + usageFunc: func() { + fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src code-intel %s':\n", codeintelUploadFlagSet.Name()) + codeintelUploadFlagSet.PrintDefaults() + fmt.Println(usage) + }, + }) + // Make 'upload' available under 'src lsif' for backwards compatibility. lsifCommands = append(lsifCommands, &command{ - flagSet: lsifUploadFlagSet, - handler: handleLSIFUpload, + flagSet: codeintelUploadFlagSet, + handler: handleCodeIntelUpload, usageFunc: func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src lsif %s':\n", lsifUploadFlagSet.Name()) - lsifUploadFlagSet.PrintDefaults() + fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src lsif %s':\n", codeintelUploadFlagSet.Name()) + codeintelUploadFlagSet.PrintDefaults() fmt.Println(usage) }, }) } -// handleLSIFUpload is the handler for `src lsif upload`. -func handleLSIFUpload(args []string) error { +// handleCodeIntelUpload is the handler for `src code-intel upload`. +func handleCodeIntelUpload(args []string) error { ctx := context.Background() - out, err := parseAndValidateLSIFUploadFlags(args) - if !lsifUploadFlags.json { + out, err := parseAndValidateCodeIntelUploadFlags(args) + if !codeintelUploadFlags.json { if out != nil { printInferredArguments(out) } else { @@ -67,32 +80,32 @@ func handleLSIFUpload(args []string) error { } } if err != nil { - return handleLSIFUploadError(nil, err) + return handleUploadError(nil, err) } client := api.NewClient(api.ClientOpts{ Out: io.Discard, - Flags: lsifUploadFlags.apiFlags, + Flags: codeintelUploadFlags.apiFlags, }) - uploadID, err := upload.UploadIndex(ctx, lsifUploadFlags.file, client, lsifUploadOptions(out)) + uploadID, err := upload.UploadIndex(ctx, codeintelUploadFlags.file, client, codeintelUploadOptions(out)) if err != nil { - return handleLSIFUploadError(out, err) + return handleUploadError(out, err) } - uploadURL, err := makeLSIFUploadURL(uploadID) + uploadURL, err := makeCodeIntelUploadURL(uploadID) if err != nil { return err } - if lsifUploadFlags.json { + if codeintelUploadFlags.json { serialized, err := json.Marshal(map[string]interface{}{ - "repo": lsifUploadFlags.repo, - "commit": lsifUploadFlags.commit, - "root": lsifUploadFlags.root, - "file": lsifUploadFlags.file, - "indexer": lsifUploadFlags.indexer, - "indexerVersion": lsifUploadFlags.indexerVersion, + "repo": codeintelUploadFlags.repo, + "commit": codeintelUploadFlags.commit, + "root": codeintelUploadFlags.root, + "file": codeintelUploadFlags.file, + "indexer": codeintelUploadFlags.indexer, + "indexerVersion": codeintelUploadFlags.indexerVersion, "uploadId": uploadID, "uploadUrl": uploadURL, }) @@ -109,7 +122,7 @@ func handleLSIFUpload(args []string) error { out.WriteLine(output.Linef(output.EmojiLightbulb, output.StyleItalic, "View processing status at %s", uploadURL)) } - if lsifUploadFlags.open { + if codeintelUploadFlags.open { if err := browser.OpenURL(uploadURL); err != nil { return err } @@ -118,11 +131,11 @@ func handleLSIFUpload(args []string) error { return nil } -// lsifUploadOptions creates a set of upload options given the values in the flags. -func lsifUploadOptions(out *output.Output) upload.UploadOptions { +// codeintelUploadOptions creates a set of upload options given the values in the flags. +func codeintelUploadOptions(out *output.Output) upload.UploadOptions { var associatedIndexID *int - if lsifUploadFlags.associatedIndexID != -1 { - associatedIndexID = &lsifUploadFlags.associatedIndexID + if codeintelUploadFlags.associatedIndexID != -1 { + associatedIndexID = &codeintelUploadFlags.associatedIndexID } logger := upload.NewRequestLogger( @@ -131,16 +144,16 @@ func lsifUploadOptions(out *output.Output) upload.UploadOptions { // It's fine if someone supplies -trace=42, but it will just behave the // same as if they supplied the highest verbosity level we define // internally. - upload.RequestLoggerVerbosity(lsifUploadFlags.verbosity), + upload.RequestLoggerVerbosity(codeintelUploadFlags.verbosity), ) return upload.UploadOptions{ UploadRecordOptions: upload.UploadRecordOptions{ - Repo: lsifUploadFlags.repo, - Commit: lsifUploadFlags.commit, - Root: lsifUploadFlags.root, - Indexer: lsifUploadFlags.indexer, - IndexerVersion: lsifUploadFlags.indexerVersion, + Repo: codeintelUploadFlags.repo, + Commit: codeintelUploadFlags.commit, + Root: codeintelUploadFlags.root, + Indexer: codeintelUploadFlags.indexer, + IndexerVersion: codeintelUploadFlags.indexerVersion, AssociatedIndexID: associatedIndexID, }, SourcegraphInstanceOptions: upload.SourcegraphInstanceOptions{ @@ -149,10 +162,10 @@ func lsifUploadOptions(out *output.Output) upload.UploadOptions { AdditionalHeaders: cfg.AdditionalHeaders, MaxRetries: 5, RetryInterval: time.Second, - Path: lsifUploadFlags.uploadRoute, - MaxPayloadSizeBytes: lsifUploadFlags.maxPayloadSizeMb * 1000 * 1000, - GitHubToken: lsifUploadFlags.gitHubToken, - GitLabToken: lsifUploadFlags.gitLabToken, + Path: codeintelUploadFlags.uploadRoute, + MaxPayloadSizeBytes: codeintelUploadFlags.maxPayloadSizeMb * 1000 * 1000, + GitHubToken: codeintelUploadFlags.gitHubToken, + GitLabToken: codeintelUploadFlags.gitLabToken, }, OutputOptions: upload.OutputOptions{ Output: out, @@ -170,25 +183,25 @@ func printInferredArguments(out *output.Output) { } block := out.Block(output.Line(output.EmojiLightbulb, output.StyleItalic, "Inferred arguments")) - block.Writef("repo: %s", lsifUploadFlags.repo) - block.Writef("commit: %s", lsifUploadFlags.commit) - block.Writef("root: %s", lsifUploadFlags.root) - block.Writef("file: %s", lsifUploadFlags.file) - block.Writef("indexer: %s", lsifUploadFlags.indexer) - block.Writef("indexerVersion: %s", lsifUploadFlags.indexerVersion) + block.Writef("repo: %s", codeintelUploadFlags.repo) + block.Writef("commit: %s", codeintelUploadFlags.commit) + block.Writef("root: %s", codeintelUploadFlags.root) + block.Writef("file: %s", codeintelUploadFlags.file) + block.Writef("indexer: %s", codeintelUploadFlags.indexer) + block.Writef("indexerVersion: %s", codeintelUploadFlags.indexerVersion) block.Close() } -// makeLSIFUploadURL constructs a URL to the upload with the given internal identifier. +// makeCodeIntelUploadURL constructs a URL to the upload with the given internal identifier. // The base of the URL is constructed from the configured Sourcegraph instance. -func makeLSIFUploadURL(uploadID int) (string, error) { +func makeCodeIntelUploadURL(uploadID int) (string, error) { url, err := url.Parse(cfg.Endpoint) if err != nil { return "", err } graphqlID := base64.URLEncoding.EncodeToString([]byte(fmt.Sprintf(`LSIFUpload:"%d"`, uploadID))) - url.Path = lsifUploadFlags.repo + "/-/code-intelligence/uploads/" + graphqlID + url.Path = codeintelUploadFlags.repo + "/-/code-intelligence/uploads/" + graphqlID url.User = nil return url.String(), nil } @@ -202,16 +215,16 @@ func (e errorWithHint) Error() string { return fmt.Sprintf("%s\n\n%s\n", e.err, e.hint) } -// handleLSIFUploadError writes the given error to the given output. If the +// handleUploadError writes the given error to the given output. If the // given output object is nil then the error will be written to standard out. // // This method returns the error that should be passed back up to the runner. -func handleLSIFUploadError(out *output.Output, err error) error { +func handleUploadError(out *output.Output, err error) error { if err == upload.ErrUnauthorized { err = filterLSIFUnauthorizedError(out, err) } - if lsifUploadFlags.ignoreUploadFailures { + if codeintelUploadFlags.ignoreUploadFailures { // Report but don't return the error fmt.Println(err.Error()) return nil @@ -222,30 +235,30 @@ func handleLSIFUploadError(out *output.Output, err error) error { func filterLSIFUnauthorizedError(out *output.Output, err error) error { var actionableHints []string - needsGitHubToken := strings.HasPrefix(lsifUploadFlags.repo, "github.com") - needsGitLabToken := strings.HasPrefix(lsifUploadFlags.repo, "gitlab.com") + needsGitHubToken := strings.HasPrefix(codeintelUploadFlags.repo, "github.com") + needsGitLabToken := strings.HasPrefix(codeintelUploadFlags.repo, "gitlab.com") if needsGitHubToken { - if lsifUploadFlags.gitHubToken != "" { + if codeintelUploadFlags.gitHubToken != "" { actionableHints = append(actionableHints, - fmt.Sprintf("The supplied -github-token does not indicate that you have collaborator access to %s.", lsifUploadFlags.repo), + fmt.Sprintf("The supplied -github-token does not indicate that you have collaborator access to %s.", codeintelUploadFlags.repo), "Please check the value of the supplied token and its permissions on the code host and try again.", ) } else { actionableHints = append(actionableHints, - fmt.Sprintf("Please retry your request with a -github-token=XXX with with collaborator access to %s.", lsifUploadFlags.repo), + fmt.Sprintf("Please retry your request with a -github-token=XXX with with collaborator access to %s.", codeintelUploadFlags.repo), "This token will be used to check with the code host that the uploading user has write access to the target repository.", ) } } else if needsGitLabToken { - if lsifUploadFlags.gitLabToken != "" { + if codeintelUploadFlags.gitLabToken != "" { actionableHints = append(actionableHints, - fmt.Sprintf("The supplied -gitlab-token does not indicate that you have write access to %s.", lsifUploadFlags.repo), + fmt.Sprintf("The supplied -gitlab-token does not indicate that you have write access to %s.", codeintelUploadFlags.repo), "Please check the value of the supplied token and its permissions on the code host and try again.", ) } else { actionableHints = append(actionableHints, - fmt.Sprintf("Please retry your request with a -gitlab-token=XXX with with write access to %s.", lsifUploadFlags.repo), + fmt.Sprintf("Please retry your request with a -gitlab-token=XXX with with write access to %s.", codeintelUploadFlags.repo), "This token will be used to check with the code host that the uploading user has write access to the target repository.", ) } diff --git a/cmd/src/lsif_upload_flags.go b/cmd/src/code_intel_upload_flags.go similarity index 57% rename from cmd/src/lsif_upload_flags.go rename to cmd/src/code_intel_upload_flags.go index 89fdc38458..46d50a6ea7 100644 --- a/cmd/src/lsif_upload_flags.go +++ b/cmd/src/code_intel_upload_flags.go @@ -20,7 +20,7 @@ import ( "github.com/sourcegraph/src-cli/internal/codeintel" ) -var lsifUploadFlags struct { +var codeintelUploadFlags struct { file string // UploadRecordOptions @@ -49,53 +49,53 @@ var lsifUploadFlags struct { } var ( - lsifUploadFlagSet = flag.NewFlagSet("upload", flag.ExitOnError) - apiClientFlagSet = flag.NewFlagSet("upload client", flag.ExitOnError) + codeintelUploadFlagSet = flag.NewFlagSet("upload", flag.ExitOnError) + apiClientFlagSet = flag.NewFlagSet("upload client", flag.ExitOnError) // Used to include the insecure-skip-verify flag in the help output, as we don't use any of the // other api.Client methods, so only the insecureSkipVerify flag is relevant here. dummyflag bool ) func init() { - lsifUploadFlagSet.StringVar(&lsifUploadFlags.file, "file", "./dump.lsif", `The path to the LSIF dump file.`) + codeintelUploadFlagSet.StringVar(&codeintelUploadFlags.file, "file", "./dump.lsif", `The path to the LSIF dump file.`) // UploadRecordOptions - lsifUploadFlagSet.StringVar(&lsifUploadFlags.repo, "repo", "", `The name of the repository (e.g. github.com/gorilla/mux). By default, derived from the origin remote.`) - lsifUploadFlagSet.StringVar(&lsifUploadFlags.commit, "commit", "", `The 40-character hash of the commit. Defaults to the currently checked-out commit.`) - lsifUploadFlagSet.StringVar(&lsifUploadFlags.root, "root", "", `The path in the repository that matches the LSIF projectRoot (e.g. cmd/project1). Defaults to the directory where the dump file is located.`) - lsifUploadFlagSet.StringVar(&lsifUploadFlags.indexer, "indexer", "", `The name of the indexer that generated the dump. This will override the 'toolInfo.name' field in the metadata vertex of the LSIF dump file. This must be supplied if the indexer does not set this field (in which case the upload will fail with an explicit message).`) - lsifUploadFlagSet.StringVar(&lsifUploadFlags.indexerVersion, "indexerVersion", "", `The version of the indexer that generated the dump. This will override the 'toolInfo.version' field in the metadata vertex of the LSIF dump file. This must be supplied if the indexer does not set this field (in which case the upload will fail with an explicit message).`) - lsifUploadFlagSet.IntVar(&lsifUploadFlags.associatedIndexID, "associated-index-id", -1, "ID of the associated index record for this upload. For internal use only.") + codeintelUploadFlagSet.StringVar(&codeintelUploadFlags.repo, "repo", "", `The name of the repository (e.g. github.com/gorilla/mux). By default, derived from the origin remote.`) + codeintelUploadFlagSet.StringVar(&codeintelUploadFlags.commit, "commit", "", `The 40-character hash of the commit. Defaults to the currently checked-out commit.`) + codeintelUploadFlagSet.StringVar(&codeintelUploadFlags.root, "root", "", `The path in the repository that matches the LSIF projectRoot (e.g. cmd/project1). Defaults to the directory where the dump file is located.`) + codeintelUploadFlagSet.StringVar(&codeintelUploadFlags.indexer, "indexer", "", `The name of the indexer that generated the dump. This will override the 'toolInfo.name' field in the metadata vertex of the LSIF dump file. This must be supplied if the indexer does not set this field (in which case the upload will fail with an explicit message).`) + codeintelUploadFlagSet.StringVar(&codeintelUploadFlags.indexerVersion, "indexerVersion", "", `The version of the indexer that generated the dump. This will override the 'toolInfo.version' field in the metadata vertex of the LSIF dump file. This must be supplied if the indexer does not set this field (in which case the upload will fail with an explicit message).`) + codeintelUploadFlagSet.IntVar(&codeintelUploadFlags.associatedIndexID, "associated-index-id", -1, "ID of the associated index record for this upload. For internal use only.") // SourcegraphInstanceOptions - lsifUploadFlagSet.StringVar(&lsifUploadFlags.uploadRoute, "upload-route", "/.api/lsif/upload", "The path of the upload route. For internal use only.") - lsifUploadFlagSet.Int64Var(&lsifUploadFlags.maxPayloadSizeMb, "max-payload-size", 100, `The maximum upload size (in megabytes). Indexes exceeding this limit will be uploaded over multiple HTTP requests.`) + codeintelUploadFlagSet.StringVar(&codeintelUploadFlags.uploadRoute, "upload-route", "/.api/lsif/upload", "The path of the upload route. For internal use only.") + codeintelUploadFlagSet.Int64Var(&codeintelUploadFlags.maxPayloadSizeMb, "max-payload-size", 100, `The maximum upload size (in megabytes). Indexes exceeding this limit will be uploaded over multiple HTTP requests.`) // Codehost authorization secrets - lsifUploadFlagSet.StringVar(&lsifUploadFlags.gitHubToken, "github-token", "", `A GitHub access token with 'public_repo' scope that Sourcegraph uses to verify you have access to the repository.`) - lsifUploadFlagSet.StringVar(&lsifUploadFlags.gitLabToken, "gitlab-token", "", `A GitLab access token with 'read_api' scope that Sourcegraph uses to verify you have access to the repository.`) + codeintelUploadFlagSet.StringVar(&codeintelUploadFlags.gitHubToken, "github-token", "", `A GitHub access token with 'public_repo' scope that Sourcegraph uses to verify you have access to the repository.`) + codeintelUploadFlagSet.StringVar(&codeintelUploadFlags.gitLabToken, "gitlab-token", "", `A GitLab access token with 'read_api' scope that Sourcegraph uses to verify you have access to the repository.`) // Output and error behavior - lsifUploadFlagSet.BoolVar(&lsifUploadFlags.ignoreUploadFailures, "ignore-upload-failure", false, `Exit with status code zero on upload failure.`) - lsifUploadFlagSet.BoolVar(&lsifUploadFlags.noProgress, "no-progress", false, `Do not display progress updates.`) - lsifUploadFlagSet.IntVar(&lsifUploadFlags.verbosity, "trace", 0, "-trace=0 shows no logs; -trace=1 shows requests and response metadata; -trace=2 shows headers, -trace=3 shows response body") - lsifUploadFlagSet.BoolVar(&lsifUploadFlags.json, "json", false, `Output relevant state in JSON on success.`) - lsifUploadFlagSet.BoolVar(&lsifUploadFlags.open, "open", false, `Open the LSIF upload page in your browser.`) - lsifUploadFlagSet.BoolVar(&dummyflag, "insecure-skip-verify", false, "Skip validation of TLS certificates against trusted chains") + codeintelUploadFlagSet.BoolVar(&codeintelUploadFlags.ignoreUploadFailures, "ignore-upload-failure", false, `Exit with status code zero on upload failure.`) + codeintelUploadFlagSet.BoolVar(&codeintelUploadFlags.noProgress, "no-progress", false, `Do not display progress updates.`) + codeintelUploadFlagSet.IntVar(&codeintelUploadFlags.verbosity, "trace", 0, "-trace=0 shows no logs; -trace=1 shows requests and response metadata; -trace=2 shows headers, -trace=3 shows response body") + codeintelUploadFlagSet.BoolVar(&codeintelUploadFlags.json, "json", false, `Output relevant state in JSON on success.`) + codeintelUploadFlagSet.BoolVar(&codeintelUploadFlags.open, "open", false, `Open the LSIF upload page in your browser.`) + codeintelUploadFlagSet.BoolVar(&dummyflag, "insecure-skip-verify", false, "Skip validation of TLS certificates against trusted chains") } -// parseAndValidateLSIFUploadFlags calls lsifUploadFlagSet.Parse, then infers values for -// missing flags, normalizes supplied values, and validates the state of the lsifUploadFlags +// parseAndValidateCodeIntelUploadFlags calls codeintelUploadFlagset.Parse, then infers values for +// missing flags, normalizes supplied values, and validates the state of the codeintelUploadFlags // object. // -// On success, the global lsifUploadFlags object will be populated with valid values. An +// On success, the global codeintelUploadFlags object will be populated with valid values. An // error is returned on failure. -func parseAndValidateLSIFUploadFlags(args []string) (*output.Output, error) { - if err := lsifUploadFlagSet.Parse(args); err != nil { +func parseAndValidateCodeIntelUploadFlags(args []string) (*output.Output, error) { + if err := codeintelUploadFlagSet.Parse(args); err != nil { return nil, err } - out := lsifUploadOutput() + out := codeintelUploadOutput() // extract only the -insecure-skip-verify flag so we dont get 'flag provided but not defined' var insecureSkipVerifyFlag []string @@ -105,10 +105,10 @@ func parseAndValidateLSIFUploadFlags(args []string) (*output.Output, error) { } } - // parse the api client flags separately and then populate the lsifUploadFlags struct with the result + // parse the api client flags separately and then populate the codeintelUploadFlags struct with the result // we could just use insecureSkipVerify but I'm including everything here because it costs nothing // and maybe we'll use some in the future - lsifUploadFlags.apiFlags = api.NewFlags(apiClientFlagSet) + codeintelUploadFlags.apiFlags = api.NewFlags(apiClientFlagSet) if err := apiClientFlagSet.Parse(insecureSkipVerifyFlag); err != nil { return nil, err } @@ -117,7 +117,7 @@ func parseAndValidateLSIFUploadFlags(args []string) (*output.Output, error) { return nil, err } - if inferenceErrors := inferMissingLSIFUploadFlags(); len(inferenceErrors) > 0 { + if inferenceErrors := inferMissingCodeIntelUploadFlags(); len(inferenceErrors) > 0 { return nil, errorWithHint{ err: inferenceErrors[0].err, hint: strings.Join([]string{ fmt.Sprintf( @@ -129,21 +129,21 @@ func parseAndValidateLSIFUploadFlags(args []string) (*output.Output, error) { } } - if err := validateLSIFUploadFlags(); err != nil { + if err := validateCodeIntelUploadFlags(); err != nil { return nil, err } return out, nil } -// lsifUploadOutput returns an output object that should be used to print the progres +// codeintelUploadOutput returns an output object that should be used to print the progres // of requests made during this upload. If -json, -no-progress, or -trace>0 is given, // then no output object is defined. // // For -no-progress and -trace>0 conditions, emergency loggers will be used to display // inferred arguments and the URL at which processing status is shown. -func lsifUploadOutput() (out *output.Output) { - if lsifUploadFlags.json || lsifUploadFlags.noProgress || lsifUploadFlags.verbosity > 0 { +func codeintelUploadOutput() (out *output.Output) { + if codeintelUploadFlags.json || codeintelUploadFlags.noProgress || codeintelUploadFlags.verbosity > 0 { return nil } @@ -173,11 +173,11 @@ func replaceBaseName(oldPath string, newBaseName string) string { } func handleSCIP(out *output.Output) error { - fileExt := path.Ext(lsifUploadFlags.file) + fileExt := path.Ext(codeintelUploadFlags.file) if len(fileExt) == 0 { - return errors.Newf("missing file extension for %s; expected .scip", lsifUploadFlags.file) + return errors.Newf("missing file extension for %s; expected .scip", codeintelUploadFlags.file) } - inputFile := lsifUploadFlags.file + inputFile := codeintelUploadFlags.file if fileExt == ".scip" || fileExt == ".lsif-typed" { // The user explicitly passed in a -file flag that points to an SCIP index. outputFile := replaceExtension(inputFile, ".lsif") @@ -186,7 +186,7 @@ func handleSCIP(out *output.Output) error { } // HACK: Modify the flags to point to the output file, because // that field of the flags is read when performing the upload. - lsifUploadFlags.file = outputFile + codeintelUploadFlags.file = outputFile return convertSCIPToLSIFGraph(out, inputFile, outputFile) } @@ -213,7 +213,7 @@ func handleSCIP(out *output.Output) error { // The provided -file flag points to an `*.lsif` file that doesn't exist // so we convert the sibling file (which we confirmed exists). - return convertSCIPToLSIFGraph(out, scipFile, lsifUploadFlags.file) + return convertSCIPToLSIFGraph(out, scipFile, codeintelUploadFlags.file) } // Reads the SCIP encoded input file and writes the corresponding LSIF @@ -252,13 +252,13 @@ func convertSCIPToLSIFGraph(out *output.Output, inputFile, outputFile string) er return nil } -// inferMissingLSIFUploadFlags updates the flags values which were not explicitly +// inferMissingCodeIntelUploadFlags updates the flags values which were not explicitly // supplied by the user with default values inferred from the current git state and // filesystem. // -// Note: This function must not be called before lsifUploadFlagSet.Parse. -func inferMissingLSIFUploadFlags() (inferErrors []argumentInferenceError) { - if _, err := os.Stat(lsifUploadFlags.file); os.IsNotExist(err) { +// Note: This function must not be called before codeintelUploadFlagset.Parse. +func inferMissingCodeIntelUploadFlags() (inferErrors []argumentInferenceError) { + if _, err := os.Stat(codeintelUploadFlags.file); os.IsNotExist(err) { inferErrors = append(inferErrors, argumentInferenceError{"file", err}) } @@ -266,19 +266,19 @@ func inferMissingLSIFUploadFlags() (inferErrors []argumentInferenceError) { getIndexerName := func() (string, error) { return indexerName, readIndexerNameAndVersionErr } getIndexerVersion := func() (string, error) { return indexerVersion, readIndexerNameAndVersionErr } - if err := inferUnsetFlag("repo", &lsifUploadFlags.repo, codeintel.InferRepo); err != nil { + if err := inferUnsetFlag("repo", &codeintelUploadFlags.repo, codeintel.InferRepo); err != nil { inferErrors = append(inferErrors, *err) } - if err := inferUnsetFlag("commit", &lsifUploadFlags.commit, codeintel.InferCommit); err != nil { + if err := inferUnsetFlag("commit", &codeintelUploadFlags.commit, codeintel.InferCommit); err != nil { inferErrors = append(inferErrors, *err) } - if err := inferUnsetFlag("root", &lsifUploadFlags.root, inferIndexRoot); err != nil { + if err := inferUnsetFlag("root", &codeintelUploadFlags.root, inferIndexRoot); err != nil { inferErrors = append(inferErrors, *err) } - if err := inferUnsetFlag("indexer", &lsifUploadFlags.indexer, getIndexerName); err != nil { + if err := inferUnsetFlag("indexer", &codeintelUploadFlags.indexer, getIndexerName); err != nil { inferErrors = append(inferErrors, *err) } - if err := inferUnsetFlag("indexerVersion", &lsifUploadFlags.indexerVersion, getIndexerVersion); err != nil { + if err := inferUnsetFlag("indexerVersion", &codeintelUploadFlags.indexerVersion, getIndexerVersion); err != nil { inferErrors = append(inferErrors, *err) } @@ -290,9 +290,9 @@ func inferMissingLSIFUploadFlags() (inferErrors []argumentInferenceError) { // by the user, then this function no-ops. An argumentInferenceError is returned if // the given function returns an error. // -// Note: This function must not be called before lsifUploadFlagSet.Parse. +// Note: This function must not be called before codeintelUploadFlagset.Parse. func inferUnsetFlag(name string, target *string, f func() (string, error)) *argumentInferenceError { - if isFlagSet(lsifUploadFlagSet, name) { + if isFlagSet(codeintelUploadFlagSet, name) { return nil } @@ -320,17 +320,17 @@ func isFlagSet(fs *flag.FlagSet, name string) (found bool) { // inferIndexRoot returns the root directory based on the configured index file path. // -// Note: This function must not be called before lsifUploadFlagSet.Parse. +// Note: This function must not be called before codeintelUploadFlagset.Parse. func inferIndexRoot() (string, error) { - return codeintel.InferRoot(lsifUploadFlags.file) + return codeintel.InferRoot(codeintelUploadFlags.file) } // readIndexerNameAndVersion returns the indexer name and version values read from the // toolInfo value in the configured index file. // -// Note: This function must not be called before lsifUploadFlagSet.Parse. +// Note: This function must not be called before codeintelUploadFlagset.Parse. func readIndexerNameAndVersion() (string, string, error) { - file, err := os.Open(lsifUploadFlags.file) + file, err := os.Open(codeintelUploadFlags.file) if err != nil { return "", "", err } @@ -339,17 +339,17 @@ func readIndexerNameAndVersion() (string, string, error) { return upload.ReadIndexerNameAndVersion(file) } -// validateLSIFUploadFlags returns an error if any of the parsed flag values are illegal. +// validateCodeIntelUploadFlags returns an error if any of the parsed flag values are illegal. // -// Note: This function must not be called before lsifUploadFlagSet.Parse. -func validateLSIFUploadFlags() error { - lsifUploadFlags.root = codeintel.SanitizeRoot(lsifUploadFlags.root) +// Note: This function must not be called before codeintelUploadFlagset.Parse. +func validateCodeIntelUploadFlags() error { + codeintelUploadFlags.root = codeintel.SanitizeRoot(codeintelUploadFlags.root) - if strings.HasPrefix(lsifUploadFlags.root, "..") { + if strings.HasPrefix(codeintelUploadFlags.root, "..") { return errors.New("root must not be outside of repository") } - if lsifUploadFlags.maxPayloadSizeMb < 25 { + if codeintelUploadFlags.maxPayloadSizeMb < 25 { return errors.New("max-payload-size must be at least 25 (MB)") } diff --git a/cmd/src/lsif_upload_flags_test.go b/cmd/src/code_intel_upload_flags_test.go similarity index 89% rename from cmd/src/lsif_upload_flags_test.go rename to cmd/src/code_intel_upload_flags_test.go index 30611430a9..9725a45f42 100644 --- a/cmd/src/lsif_upload_flags_test.go +++ b/cmd/src/code_intel_upload_flags_test.go @@ -45,7 +45,7 @@ func createTempSCIPFile(t *testing.T, scipFileName string) (scipFilePath string, } func assertLSIFOutput(t *testing.T, lsifFile, expectedLSIFString string) { - out := lsifUploadOutput() + out := codeintelUploadOutput() handleSCIP(out) lsif, err := os.ReadFile(lsifFile) if err != nil { @@ -55,15 +55,15 @@ func assertLSIFOutput(t *testing.T, lsifFile, expectedLSIFString string) { if obtained != expectedLSIFString { t.Fatalf("unexpected LSIF output %s", obtained) } - if lsifFile != lsifUploadFlags.file { - t.Fatalf("unexpected lsifUploadFlag.file value %s, expected %s", lsifUploadFlags.file, lsifFile) + if lsifFile != codeintelUploadFlags.file { + t.Fatalf("unexpected codeintelUploadFlag.file value %s, expected %s", codeintelUploadFlags.file, lsifFile) } } func TestImplicitlyConvertSCIPIntoLSIF(t *testing.T) { for _, filename := range []string{"index.scip", "dump.scip", "dump.lsif-typed"} { _, lsifFile := createTempSCIPFile(t, filename) - lsifUploadFlags.file = lsifFile + codeintelUploadFlags.file = lsifFile assertLSIFOutput(t, lsifFile, exampleLSIFString) } } @@ -71,7 +71,7 @@ func TestImplicitlyConvertSCIPIntoLSIF(t *testing.T) { func TestImplicitlyIgnoreSCIP(t *testing.T) { for _, filename := range []string{"index.scip", "dump.scip", "dump.lsif-typed"} { _, lsifFile := createTempSCIPFile(t, filename) - lsifUploadFlags.file = lsifFile + codeintelUploadFlags.file = lsifFile os.WriteFile(lsifFile, []byte("hello world"), 0755) assertLSIFOutput(t, lsifFile, "hello world") } @@ -80,7 +80,7 @@ func TestImplicitlyIgnoreSCIP(t *testing.T) { func TestExplicitlyConvertSCIPIntoGraph(t *testing.T) { for _, filename := range []string{"index.scip", "dump.scip", "dump.lsif-typed"} { scipFile, lsifFile := createTempSCIPFile(t, filename) - lsifUploadFlags.file = scipFile + codeintelUploadFlags.file = scipFile assertLSIFOutput(t, lsifFile, exampleLSIFString) } } diff --git a/cmd/src/lsif.go b/cmd/src/lsif.go index 3012732e97..7b5939569c 100644 --- a/cmd/src/lsif.go +++ b/cmd/src/lsif.go @@ -8,19 +8,10 @@ import ( var lsifCommands commander func init() { - usage := `'src lsif' is a tool that manages LSIF data on a Sourcegraph instance. + usage := `[DEPRECATED] 'src lsif' is a tool that manages LSIF data on a Sourcegraph instance. -Usage: - - src lsif command [command options] - -The commands are: - - upload uploads an LSIF dump file - -Use "src lsif [command] -h" for more information about a command. +Use 'src code-intel' instead. ` - flagSet := flag.NewFlagSet("lsif", flag.ExitOnError) handler := func(args []string) error { lsifCommands.run(flagSet, "src lsif", usage, args) diff --git a/cmd/src/main.go b/cmd/src/main.go index 5d25b67a97..8fc7f1fcec 100644 --- a/cmd/src/main.go +++ b/cmd/src/main.go @@ -34,15 +34,17 @@ The commands are: api interacts with the Sourcegraph GraphQL API batch manages batch changes + code-intel manages code intelligence data config manages global, org, and user settings extensions,ext manages extensions (experimental) extsvc manages external services login authenticate to a Sourcegraph instance with your user credentials - lsif manages LSIF data + lsif manages LSIF data (deprecated: use 'code-intel') orgs,org manages organizations repos,repo manages repositories search search for results on Sourcegraph serve-git serves your local git repositories over HTTP for Sourcegraph to pull + upload upload an index to a Sourcegraph instance users,user manages users version display and compare the src-cli version against the recommended version for your instance From 973555b692dd5dd644ea2dc86b4b2702681eec73 Mon Sep 17 00:00:00 2001 From: Varun Gandhi Date: Tue, 24 May 2022 00:34:05 -0700 Subject: [PATCH 169/647] changelog: Add note about SCIP support in 3.40.0. (#750) --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9c15079c52..17b5feaecf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,6 +27,7 @@ All notable changes to `src-cli` are documented in this file. - New command `src debug`. [#731](https://github.com/sourcegraph/src-cli/pull/731) - `src lsif upload` now supports the `-gitlab-token` flag. [#721](https://github.com/sourcegraph/src-cli/pull/721) - Batch Changes can be applied to Bitbucket Cloud when `src` is used with Sourcegraph 3.40 or later. [#725](https://github.com/sourcegraph/src-cli/pull/725) +- `src lsif upload` accepts indexes in the [SCIP](https://github.com/sourcegraph/scip) format. [#742](https://github.com/sourcegraph/src-cli/pull/742) ### Changed From ac630837245de8481023068f6eaf906760168954 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=93lafur=20P=C3=A1ll=20Geirsson?= Date: Wed, 25 May 2022 21:20:06 +0200 Subject: [PATCH 170/647] Bump SCIP version to include bugfix for textDocument/implementations (#751) The PR we want to include https://github.com/sourcegraph/scip/pull/27 --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 6deed97609..7945af9fb6 100644 --- a/go.mod +++ b/go.mod @@ -19,7 +19,7 @@ require ( github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf - github.com/sourcegraph/scip v0.0.0-20220513191902-a9bebaa57565 + github.com/sourcegraph/scip v0.0.0-20220525190354-5922ee059bf9 github.com/sourcegraph/sourcegraph/lib v0.0.0-20220511160847-5a43d3ea24eb github.com/stretchr/testify v1.7.1 golang.org/x/net v0.0.0-20220412020605-290c469a71a5 diff --git a/go.sum b/go.sum index 796e0c4d96..722dd416dc 100644 --- a/go.sum +++ b/go.sum @@ -326,8 +326,8 @@ github.com/sourcegraph/go-diff v0.6.1 h1:hmA1LzxW0n1c3Q4YbrFgg4P99GSnebYa3x8gr0H github.com/sourcegraph/go-diff v0.6.1/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= -github.com/sourcegraph/scip v0.0.0-20220513191902-a9bebaa57565 h1:EKtJLeanygtO/BB3ZLGoHiCdYq9PJdgYzYzAErm7EdU= -github.com/sourcegraph/scip v0.0.0-20220513191902-a9bebaa57565/go.mod h1:Y+5w4gBKMnbSDC/5yD03kLTM/sx3449lPrXxloueWDA= +github.com/sourcegraph/scip v0.0.0-20220525190354-5922ee059bf9 h1:1+L7s9/gy6r3EH33eKNzzD2oyU3pXN5LhzmjdqpumXU= +github.com/sourcegraph/scip v0.0.0-20220525190354-5922ee059bf9/go.mod h1:/AZ8RvsnRfeCZy232PJuVZqcl9f82fJnYwdWZeU2JCo= github.com/sourcegraph/sourcegraph/lib v0.0.0-20220511160847-5a43d3ea24eb h1:D8ciD0FEcPNnVm6BC8vg7gWJ9VxoJe6k/4j+Qxparj0= github.com/sourcegraph/sourcegraph/lib v0.0.0-20220511160847-5a43d3ea24eb/go.mod h1:iFiGPqnhOvQziDZkpWasU+Uo1BaEt/Au9kNK4VpqyOw= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= From 6a38fcc7201c3958caf94fe5884dde6ce823abda Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=93lafur=20P=C3=A1ll=20Geirsson?= Date: Wed, 25 May 2022 21:47:38 +0200 Subject: [PATCH 171/647] Update changelog for 3.40.1 (#752) --- CHANGELOG.md | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 17b5feaecf..c56f1addf7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,7 +12,6 @@ All notable changes to `src-cli` are documented in this file. ## Unreleased ### Added -- `src code-intel` is a new alias for `src lsif`. [#748](https://github.com/sourcegraph/src-cli/pull/748) ### Changed @@ -20,6 +19,16 @@ All notable changes to `src-cli` are documented in this file. ### Removed +## 3.40.1 + +### Added + +- `src code-intel` is a new alias for `src lsif`. [#748](https://github.com/sourcegraph/src-cli/pull/748) + +### Fixed + +- Updated to the latest SCIP version, fixing a bug in the `src lsif upload` conversion for "Find implementations". [sourcegraph/scip#27](https://github.com/sourcegraph/scip/pull/27) + ## 3.40.0 ### Added From 78435405d82bc335280d60a36742c597631906e2 Mon Sep 17 00:00:00 2001 From: Varun Gandhi Date: Thu, 26 May 2022 01:16:54 -0700 Subject: [PATCH 172/647] changelog: Reference code-intel subcommand instead of lsif. (#753) --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c56f1addf7..bd1a4926ae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,7 +27,7 @@ All notable changes to `src-cli` are documented in this file. ### Fixed -- Updated to the latest SCIP version, fixing a bug in the `src lsif upload` conversion for "Find implementations". [sourcegraph/scip#27](https://github.com/sourcegraph/scip/pull/27) +- Updated to the latest SCIP version, fixing a bug in the `src code-intel upload` conversion for "Find implementations". [sourcegraph/scip#27](https://github.com/sourcegraph/scip/pull/27) ## 3.40.0 From fb7762e4726ceec6ce0526b5fc836e0220fe1e9b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=93lafur=20P=C3=A1ll=20Geirsson?= Date: Mon, 30 May 2022 14:32:20 +0200 Subject: [PATCH 173/647] Bump to the latest scip version (#756) --- go.mod | 2 +- go.sum | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/go.mod b/go.mod index 7945af9fb6..8abb51e3cb 100644 --- a/go.mod +++ b/go.mod @@ -19,7 +19,7 @@ require ( github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf - github.com/sourcegraph/scip v0.0.0-20220525190354-5922ee059bf9 + github.com/sourcegraph/scip v0.1.0 github.com/sourcegraph/sourcegraph/lib v0.0.0-20220511160847-5a43d3ea24eb github.com/stretchr/testify v1.7.1 golang.org/x/net v0.0.0-20220412020605-290c469a71a5 diff --git a/go.sum b/go.sum index 722dd416dc..bdd3674d54 100644 --- a/go.sum +++ b/go.sum @@ -328,6 +328,8 @@ github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWii github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= github.com/sourcegraph/scip v0.0.0-20220525190354-5922ee059bf9 h1:1+L7s9/gy6r3EH33eKNzzD2oyU3pXN5LhzmjdqpumXU= github.com/sourcegraph/scip v0.0.0-20220525190354-5922ee059bf9/go.mod h1:/AZ8RvsnRfeCZy232PJuVZqcl9f82fJnYwdWZeU2JCo= +github.com/sourcegraph/scip v0.1.0 h1:kTs0CJaLQvcRZjg+HpGrcJPNX2Tx31+d6szWio3ZOkQ= +github.com/sourcegraph/scip v0.1.0/go.mod h1:/AZ8RvsnRfeCZy232PJuVZqcl9f82fJnYwdWZeU2JCo= github.com/sourcegraph/sourcegraph/lib v0.0.0-20220511160847-5a43d3ea24eb h1:D8ciD0FEcPNnVm6BC8vg7gWJ9VxoJe6k/4j+Qxparj0= github.com/sourcegraph/sourcegraph/lib v0.0.0-20220511160847-5a43d3ea24eb/go.mod h1:iFiGPqnhOvQziDZkpWasU+Uo1BaEt/Au9kNK4VpqyOw= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= From e6f55b9d3847b8c1873eef10540b92e346fd69b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=93lafur=20P=C3=A1ll=20Geirsson?= Date: Mon, 30 May 2022 14:39:17 +0200 Subject: [PATCH 174/647] Add release notes for 3.40.2 (#757) --- CHANGELOG.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index bd1a4926ae..5b88e6249d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,12 @@ All notable changes to `src-cli` are documented in this file. ### Removed +## 3.40.2 + +### Changed + +- Updated to the latest SCIP version, fixing a bug for scip-typescript uploads. [sourcegraph/scip#30](https://github.com/sourcegraph/scip/pull/30) + ## 3.40.1 ### Added From dd9000a93f94240d2810e018eecc402df21d8807 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=93lafur=20P=C3=A1ll=20Geirsson?= Date: Thu, 2 Jun 2022 12:52:20 +0200 Subject: [PATCH 175/647] Make src-cli installable via npm. (#760) * Make src-cli installable via npm. Fixes #759. Previously, the recommended way to install src-cli on Linux was to download a static binary via `curl`. This PR makes it possible to install src-cli via `npm install -g @sourcegraph/src`. The new npm distribution will be particuarly helpful for users of our new scip-typescript and scip-python indexers that are also distributed via npm. * Make the npm release flow depend on goreleaser --- .github/workflows/goreleaser.yml | 13 ++++- .vscode/settings.json | 5 +- CHANGELOG.md | 6 +++ DEVELOPMENT.md | 8 +-- npm-distribution/.gitignore | 3 ++ npm-distribution/install.js | 90 ++++++++++++++++++++++++++++++++ npm-distribution/package.json | 26 +++++++++ npm-distribution/src.js | 10 ++++ npm-distribution/yarn.lock | 72 +++++++++++++++++++++++++ release.sh | 4 ++ 10 files changed, 232 insertions(+), 5 deletions(-) create mode 100644 npm-distribution/.gitignore create mode 100644 npm-distribution/install.js create mode 100644 npm-distribution/package.json create mode 100644 npm-distribution/src.js create mode 100644 npm-distribution/yarn.lock diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index 2de67d0590..4db28fd9a1 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -33,4 +33,15 @@ jobs: env: # Use separate access token, because we need a scope:repo token to publish the brew formula. GITHUB_TOKEN: ${{ secrets.GH_PAT }} - + npm: + runs-on: ubuntu-latest + needs: goreleaser + steps: + - name: Checkout + uses: actions/checkout@v3 + with: + fetch-depth: 0 + - run: npm publish --access public + working-directory: npm-distribution + env: + NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}} diff --git a/.vscode/settings.json b/.vscode/settings.json index fab3522383..8b2f950a82 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,7 +1,10 @@ { "go.lintTool": "golangci-lint", "shellformat.flag": "-i 2 -ci", - "editor.formatOnSave": true, + "editor.formatOnSave": false, + "[go]": { + "editor.formatOnSave": true + }, "go.useLanguageServer": true, "gopls": { "local": "github.com/sourcegraph/src-cli" diff --git a/CHANGELOG.md b/CHANGELOG.md index 5b88e6249d..06e446ba5b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,12 @@ All notable changes to `src-cli` are documented in this file. ### Removed +## 3.40.3 + +### Added + +- It's now possible to install src-cli via `npm install -g @sourcegraph/src`. [sourcegraph/src-cli#760](https://github.com/sourcegraph/src-cli/pull/760) + ## 3.40.2 ### Changed diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index 422443d7db..5ffd044085 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -58,11 +58,13 @@ We adhere to the [general Sourcegraph principles for testing](https://docs.sourc 1. If this is a non-patch release, update the changelog. Add a new section `## $MAJOR.MINOR` to [`CHANGELOG.md`](https://github.com/sourcegraph/src-cli/blob/main/CHANGELOG.md#unreleased) immediately under `## Unreleased changes`. Add new empty `Added`, `Changed`, `Fixed`, and `Removed` sections under `## Unreleased changes`. 2. Find the latest version (either via the releases tab on GitHub or via git tags) to determine which version you are releasing. -3. `VERSION=9.9.9 ./release.sh` (replace `9.9.9` with the version you are releasing) -4. GitHub will automatically perform the release via the [goreleaser action](https://github.com/sourcegraph/src-cli/actions?query=workflow%3AGoreleaser). Once it has finished, **you need to confirm**: +3. Update the `"version"` field in the file `npm-distribution/package.json` to match the version you are releasing. +4. Open a pull request with the new changelog and updated `npm-distribution/package.json` version. Get the pull request merged before completing the next step. +5. `VERSION=9.9.9 ./release.sh` (replace `9.9.9` with the version you are releasing) +6. GitHub will automatically perform the release via the [goreleaser action](https://github.com/sourcegraph/src-cli/actions?query=workflow%3AGoreleaser). Once it has finished, **you need to confirm**: 1. The [curl commands in the README](README.markdown#installation) fetch the latest version above. 2. The [releases section of the repo sidebar](https://github.com/sourcegraph/src-cli) shows the correct version. -5. Make the necessary updates to the main Sourcegraph repo: +7. Make the necessary updates to the main Sourcegraph repo: 1. Update the `MinimumVersion` constant in the [src-cli package](https://github.com/sourcegraph/sourcegraph/tree/main/internal/src-cli/consts.go). 2. Update the reference documentation by running `go generate ./doc/cli/references`. 3. Commit the changes, and open a PR. diff --git a/npm-distribution/.gitignore b/npm-distribution/.gitignore new file mode 100644 index 0000000000..b1738c9bda --- /dev/null +++ b/npm-distribution/.gitignore @@ -0,0 +1,3 @@ +node_modules/ +src +LICENSE diff --git a/npm-distribution/install.js b/npm-distribution/install.js new file mode 100644 index 0000000000..5601449779 --- /dev/null +++ b/npm-distribution/install.js @@ -0,0 +1,90 @@ +#!/usr/bin/env node + +const fs = require("fs"); +const tar = require("tar"); +const zlib = require("zlib"); +const http = require("http"); +const https = require("https"); +const packageJSON = require("./package.json"); + +// Determine the URL of the file. +const platformName = { + darwin: "darwin", + linux: "linux", + win32: "windows", +}[process.platform]; + +let archName = { + x64: "amd64", + x86: "amd64", + ia32: "amd64", + amd64: "amd64", + arm64: "arm64", +}[process.arch]; + +if (!platformName || !archName) { + console.error( + `Cannot install src for platform ${process.platform}, architecture ${process.arch}` + ); + process.exit(1); +} + +const version = packageJSON.version; +const assetURL = `https://github.com/sourcegraph/src-cli/releases/download/${version}/src-cli_${version}_${platformName}_${archName}.tar.gz`; + +// Remove previously-downloaded files. +const executableName = process.platform === "win32" ? "src.exe" : "src"; +if (fs.existsSync(executableName)) { + fs.unlinkSync(executableName); +} + +// Download the compressed file. +console.log(`Downloading ${assetURL}`); +get(assetURL, (response) => { + if (response.statusCode > 299) { + console.error( + [ + "Download failed", + "", + `url: ${assetURL}`, + `status: ${response.statusCode}`, + `headers: ${JSON.stringify(response.headers, null, 2)}`, + "", + ].join("\n") + ); + process.exit(1); + } + response + .pipe(zlib.createGunzip()) + .pipe(tar.x({ filter: (x) => x === "src" })) + .addListener("close", () => fs.chmodSync(executableName, "755")); +}); + +// Follow redirects. +function get(url, callback) { + const requestUrl = new URL(url); + let request = https; + let requestConfig = requestUrl; + const proxyEnv = process.env["HTTPS_PROXY"] || process.env["https_proxy"]; + + if (proxyEnv) { + const proxyUrl = new URL(proxyEnv); + request = proxyUrl.protocol === "https:" ? https : http; + requestConfig = { + hostname: proxyUrl.hostname, + port: proxyUrl.port, + path: requestUrl.toString(), + headers: { + Host: requestUrl.hostname, + }, + }; + } + + request.get(requestConfig, (response) => { + if (response.statusCode === 301 || response.statusCode === 302) { + get(response.headers.location, callback); + } else { + callback(response); + } + }); +} diff --git a/npm-distribution/package.json b/npm-distribution/package.json new file mode 100644 index 0000000000..2f0acf4555 --- /dev/null +++ b/npm-distribution/package.json @@ -0,0 +1,26 @@ +{ + "name": "@sourcegraph/src", + "version": "3.40.3", + "description": "Sourcegraph CLI", + "repository": "git@github.com:sourcegraph/src-cli.git", + "author": "Code Intelligence at Sourcegraph", + "license": "Apache-2.0", + "scripts": { + "install": "node install.js", + "prepack": "cp ../LICENSE ." + }, + "main": "src.js", + "bin": { + "src": "src.js" + }, + "keywords": [ + "sourcegraph" + ], + "dependencies": { + "tar": "^6.1.11" + }, + "devDependencies": { + "@types/tar": "^6.1.1" + }, + "private": false +} diff --git a/npm-distribution/src.js b/npm-distribution/src.js new file mode 100644 index 0000000000..390c0f114d --- /dev/null +++ b/npm-distribution/src.js @@ -0,0 +1,10 @@ +#!/usr/bin/env node + +const path = require('path'); +const spawn = require("child_process").spawn; +const executable = process.platform === 'win32' ? 'src.exe' : 'src'; +spawn( + path.join(__dirname, executable), + process.argv.slice(2), + {stdio: 'inherit'} +).on('close', process.exit) diff --git a/npm-distribution/yarn.lock b/npm-distribution/yarn.lock new file mode 100644 index 0000000000..5d6d599a2e --- /dev/null +++ b/npm-distribution/yarn.lock @@ -0,0 +1,72 @@ +# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. +# yarn lockfile v1 + + +"@types/minipass@*": + version "3.1.2" + resolved "https://registry.yarnpkg.com/@types/minipass/-/minipass-3.1.2.tgz#e2d7f9df0698aff421dcf145b4fc05b8183b9030" + integrity sha512-foLGjgrJkUjLG/o2t2ymlZGEoBNBa/TfoUZ7oCTkOjP1T43UGBJspovJou/l3ZuHvye2ewR5cZNtp2zyWgILMA== + dependencies: + "@types/node" "*" + +"@types/node@*": + version "17.0.36" + resolved "https://registry.yarnpkg.com/@types/node/-/node-17.0.36.tgz#c0d5f2fe76b47b63e0e0efc3d2049a9970d68794" + integrity sha512-V3orv+ggDsWVHP99K3JlwtH20R7J4IhI1Kksgc+64q5VxgfRkQG8Ws3MFm/FZOKDYGy9feGFlZ70/HpCNe9QaA== + +"@types/tar@^6.1.1": + version "6.1.1" + resolved "https://registry.yarnpkg.com/@types/tar/-/tar-6.1.1.tgz#ab341ec1f149d7eb2a4f4ded56ff85f0d4fe7cb5" + integrity sha512-8mto3YZfVpqB1CHMaYz1TUYIQfZFbh/QbEq5Hsn6D0ilCfqRVCdalmc89B7vi3jhl9UYIk+dWDABShNfOkv5HA== + dependencies: + "@types/minipass" "*" + "@types/node" "*" + +chownr@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/chownr/-/chownr-2.0.0.tgz#15bfbe53d2eab4cf70f18a8cd68ebe5b3cb1dece" + integrity sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ== + +fs-minipass@^2.0.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/fs-minipass/-/fs-minipass-2.1.0.tgz#7f5036fdbf12c63c169190cbe4199c852271f9fb" + integrity sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg== + dependencies: + minipass "^3.0.0" + +minipass@^3.0.0: + version "3.1.6" + resolved "https://registry.yarnpkg.com/minipass/-/minipass-3.1.6.tgz#3b8150aa688a711a1521af5e8779c1d3bb4f45ee" + integrity sha512-rty5kpw9/z8SX9dmxblFA6edItUmwJgMeYDZRrwlIVN27i8gysGbznJwUggw2V/FVqFSDdWy040ZPS811DYAqQ== + dependencies: + yallist "^4.0.0" + +minizlib@^2.1.1: + version "2.1.2" + resolved "https://registry.yarnpkg.com/minizlib/-/minizlib-2.1.2.tgz#e90d3466ba209b932451508a11ce3d3632145931" + integrity sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg== + dependencies: + minipass "^3.0.0" + yallist "^4.0.0" + +mkdirp@^1.0.3: + version "1.0.4" + resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-1.0.4.tgz#3eb5ed62622756d79a5f0e2a221dfebad75c2f7e" + integrity sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw== + +tar@^6.1.11: + version "6.1.11" + resolved "https://registry.yarnpkg.com/tar/-/tar-6.1.11.tgz#6760a38f003afa1b2ffd0ffe9e9abbd0eab3d621" + integrity sha512-an/KZQzQUkZCkuoAA64hM92X0Urb6VpRhAFllDzz44U2mcD5scmT3zBc4VgVpkugF580+DQn8eAFSyoQt0tznA== + dependencies: + chownr "^2.0.0" + fs-minipass "^2.0.0" + minipass "^3.0.0" + minizlib "^2.1.1" + mkdirp "^1.0.3" + yallist "^4.0.0" + +yallist@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/yallist/-/yallist-4.0.0.tgz#9bb92790d9c0effec63be73519e11a35019a3a72" + integrity sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A== diff --git a/release.sh b/release.sh index 2d1b278369..f1a5dad57b 100755 --- a/release.sh +++ b/release.sh @@ -17,6 +17,10 @@ if ! echo "$VERSION" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+$'; then exit 1 fi +echo "Verifying that npm-distribution/package.json has the correct version" +yarn --cwd="$PWD/npm-distribution" version --no-git-tag-version --new-version "$VERSION" +git diff --exit-code + # Create a new tag and push it, this will trigger the goreleaser workflow in .github/workflows/goreleaser.yml git tag "${VERSION}" -a -m "release v${VERSION}" # We use `--atomic` so that we push the tag and the commit if the commit was or wasn't pushed before From 9ab268f2d36854ca77f663d5fa7e2be3e4765aa3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=93lafur=20P=C3=A1ll=20Geirsson?= Date: Thu, 2 Jun 2022 13:11:08 +0200 Subject: [PATCH 176/647] Use `setup-node` GitHub Actions step before running `npm publish`. (#762) The last `npm publish` step failed with an authorization error https://github.com/sourcegraph/src-cli/runs/6707002077?check_suite_focus=true ``` npm ERR! need auth This command requires you to be logged in to https://registry.npmjs.org/ 29 ``` Our current hypothesis is that this change fixes the issue. --- .github/workflows/goreleaser.yml | 4 ++++ CHANGELOG.md | 2 +- npm-distribution/package.json | 2 +- 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index 4db28fd9a1..b75df64879 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -41,6 +41,10 @@ jobs: uses: actions/checkout@v3 with: fetch-depth: 0 + - uses: actions/setup-node@v3 + with: + node-version: 16 + registry-url: 'https://registry.npmjs.org' - run: npm publish --access public working-directory: npm-distribution env: diff --git a/CHANGELOG.md b/CHANGELOG.md index 06e446ba5b..4feee8facf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,7 +19,7 @@ All notable changes to `src-cli` are documented in this file. ### Removed -## 3.40.3 +## 3.40.4 ### Added diff --git a/npm-distribution/package.json b/npm-distribution/package.json index 2f0acf4555..ccf08e3c4b 100644 --- a/npm-distribution/package.json +++ b/npm-distribution/package.json @@ -1,6 +1,6 @@ { "name": "@sourcegraph/src", - "version": "3.40.3", + "version": "3.40.4", "description": "Sourcegraph CLI", "repository": "git@github.com:sourcegraph/src-cli.git", "author": "Code Intelligence at Sourcegraph", From 72c480b3615de31cf45d308029d2921645d68d5c Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Thu, 2 Jun 2022 14:37:05 +0000 Subject: [PATCH 177/647] Pin dependency @types/tar to 6.1.1 (#761) Co-authored-by: Renovate Bot --- npm-distribution/package.json | 2 +- npm-distribution/yarn.lock | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/npm-distribution/package.json b/npm-distribution/package.json index ccf08e3c4b..3c6e426d15 100644 --- a/npm-distribution/package.json +++ b/npm-distribution/package.json @@ -20,7 +20,7 @@ "tar": "^6.1.11" }, "devDependencies": { - "@types/tar": "^6.1.1" + "@types/tar": "6.1.1" }, "private": false } diff --git a/npm-distribution/yarn.lock b/npm-distribution/yarn.lock index 5d6d599a2e..e22e5a78eb 100644 --- a/npm-distribution/yarn.lock +++ b/npm-distribution/yarn.lock @@ -14,7 +14,7 @@ resolved "https://registry.yarnpkg.com/@types/node/-/node-17.0.36.tgz#c0d5f2fe76b47b63e0e0efc3d2049a9970d68794" integrity sha512-V3orv+ggDsWVHP99K3JlwtH20R7J4IhI1Kksgc+64q5VxgfRkQG8Ws3MFm/FZOKDYGy9feGFlZ70/HpCNe9QaA== -"@types/tar@^6.1.1": +"@types/tar@6.1.1": version "6.1.1" resolved "https://registry.yarnpkg.com/@types/tar/-/tar-6.1.1.tgz#ab341ec1f149d7eb2a4f4ded56ff85f0d4fe7cb5" integrity sha512-8mto3YZfVpqB1CHMaYz1TUYIQfZFbh/QbEq5Hsn6D0ilCfqRVCdalmc89B7vi3jhl9UYIk+dWDABShNfOkv5HA== From ad9dbbae54af9436f518b5c93d719195e608cd24 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=93lafur=20P=C3=A1ll=20Geirsson?= Date: Fri, 3 Jun 2022 08:20:00 +0200 Subject: [PATCH 178/647] Simplify npm package release by setting the version (#763) Previously, you had to manually open a PR to bump up the version in package.json. Now, the version is automatically bumped during the release pipeline. --- .github/workflows/goreleaser.yml | 4 ++++ DEVELOPMENT.md | 12 +++++------- npm-distribution/package.json | 2 +- release.sh | 14 +++++--------- 4 files changed, 15 insertions(+), 17 deletions(-) diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index b75df64879..a4f72f0820 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -45,6 +45,10 @@ jobs: with: node-version: 16 registry-url: 'https://registry.npmjs.org' + - run: echo "VERSION=${GITHUB_REF/refs\/tags\/v/}" >> $GITHUB_ENV + - run: echo "Releasing version ${{ env.version }}"" + - run: yarn version --no-git-tag-version --new-version "${{ env.VERSION }}" + working-directory: npm-distribution - run: npm publish --access public working-directory: npm-distribution env: diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index 5ffd044085..ca256d7288 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -56,15 +56,13 @@ We adhere to the [general Sourcegraph principles for testing](https://docs.sourc ## Releasing -1. If this is a non-patch release, update the changelog. Add a new section `## $MAJOR.MINOR` to [`CHANGELOG.md`](https://github.com/sourcegraph/src-cli/blob/main/CHANGELOG.md#unreleased) immediately under `## Unreleased changes`. Add new empty `Added`, `Changed`, `Fixed`, and `Removed` sections under `## Unreleased changes`. -2. Find the latest version (either via the releases tab on GitHub or via git tags) to determine which version you are releasing. -3. Update the `"version"` field in the file `npm-distribution/package.json` to match the version you are releasing. -4. Open a pull request with the new changelog and updated `npm-distribution/package.json` version. Get the pull request merged before completing the next step. -5. `VERSION=9.9.9 ./release.sh` (replace `9.9.9` with the version you are releasing) -6. GitHub will automatically perform the release via the [goreleaser action](https://github.com/sourcegraph/src-cli/actions?query=workflow%3AGoreleaser). Once it has finished, **you need to confirm**: +1. Find the latest version (either via the releases tab on GitHub or via git tags) to determine which version you are releasing. +2. (optional) If this is a non-patch release, update the changelog. Add a new section `## $MAJOR.MINOR` to [`CHANGELOG.md`](https://github.com/sourcegraph/src-cli/blob/main/CHANGELOG.md#unreleased) immediately under `## Unreleased changes`. Add new empty `Added`, `Changed`, `Fixed`, and `Removed` sections under `## Unreleased changes`. Open a pull request with the new changelog. Get the pull request merged before completing the next step. +3. `VERSION=9.9.9 ./release.sh` (replace `9.9.9` with the version you are releasing) +4. GitHub will automatically perform the release via the [goreleaser action](https://github.com/sourcegraph/src-cli/actions?query=workflow%3AGoreleaser). Once it has finished, **you need to confirm**: 1. The [curl commands in the README](README.markdown#installation) fetch the latest version above. 2. The [releases section of the repo sidebar](https://github.com/sourcegraph/src-cli) shows the correct version. -7. Make the necessary updates to the main Sourcegraph repo: +5. Make the necessary updates to the main Sourcegraph repo: 1. Update the `MinimumVersion` constant in the [src-cli package](https://github.com/sourcegraph/sourcegraph/tree/main/internal/src-cli/consts.go). 2. Update the reference documentation by running `go generate ./doc/cli/references`. 3. Commit the changes, and open a PR. diff --git a/npm-distribution/package.json b/npm-distribution/package.json index 3c6e426d15..cb1c406770 100644 --- a/npm-distribution/package.json +++ b/npm-distribution/package.json @@ -1,6 +1,6 @@ { "name": "@sourcegraph/src", - "version": "3.40.4", + "version": "0.0.0-dev", "description": "Sourcegraph CLI", "repository": "git@github.com:sourcegraph/src-cli.git", "author": "Code Intelligence at Sourcegraph", diff --git a/release.sh b/release.sh index f1a5dad57b..aa0d4f9706 100755 --- a/release.sh +++ b/release.sh @@ -5,11 +5,11 @@ set -euf -o pipefail read -p 'Have you read DEVELOPMENT.md? [y/N] ' -n 1 -r echo case "$REPLY" in - Y|y) ;; - *) - echo 'Please read the Releasing section of DEVELOPMENT.md before running this script.' - exit 1 - ;; + Y | y) ;; + *) + echo 'Please read the Releasing section of DEVELOPMENT.md before running this script.' + exit 1 + ;; esac if ! echo "$VERSION" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+$'; then @@ -17,10 +17,6 @@ if ! echo "$VERSION" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+$'; then exit 1 fi -echo "Verifying that npm-distribution/package.json has the correct version" -yarn --cwd="$PWD/npm-distribution" version --no-git-tag-version --new-version "$VERSION" -git diff --exit-code - # Create a new tag and push it, this will trigger the goreleaser workflow in .github/workflows/goreleaser.yml git tag "${VERSION}" -a -m "release v${VERSION}" # We use `--atomic` so that we push the tag and the commit if the commit was or wasn't pushed before From 42368629fbe13c1aee172da769b33f26ed5cc57f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=93lafur=20P=C3=A1ll=20Geirsson?= Date: Fri, 3 Jun 2022 15:32:35 +0200 Subject: [PATCH 179/647] Fix silly quote bug (#765) --- .github/workflows/goreleaser.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index a4f72f0820..7fb64fb79e 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -46,7 +46,7 @@ jobs: node-version: 16 registry-url: 'https://registry.npmjs.org' - run: echo "VERSION=${GITHUB_REF/refs\/tags\/v/}" >> $GITHUB_ENV - - run: echo "Releasing version ${{ env.version }}"" + - run: echo "Releasing version ${{ env.version }}" - run: yarn version --no-git-tag-version --new-version "${{ env.VERSION }}" working-directory: npm-distribution - run: npm publish --access public From dc24b0fece1ca3491e8d823b8bdd968fc64cef41 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=93lafur=20P=C3=A1ll=20Geirsson?= Date: Fri, 3 Jun 2022 15:40:27 +0200 Subject: [PATCH 180/647] Fix the regexp to extract the version from git refs (#766) The last npm release job failed with "error Invalid version supplied." because the inferred version was "refs/tags/3.40.6". --- .github/workflows/goreleaser.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index 7fb64fb79e..1b1f1a4ba1 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -45,7 +45,7 @@ jobs: with: node-version: 16 registry-url: 'https://registry.npmjs.org' - - run: echo "VERSION=${GITHUB_REF/refs\/tags\/v/}" >> $GITHUB_ENV + - run: echo "VERSION=${GITHUB_REF/refs\/tags\//}" >> $GITHUB_ENV - run: echo "Releasing version ${{ env.version }}" - run: yarn version --no-git-tag-version --new-version "${{ env.VERSION }}" working-directory: npm-distribution From 097f61701ce29882435f568833f5fa221744aecc Mon Sep 17 00:00:00 2001 From: Adam Harvey Date: Mon, 6 Jun 2022 15:39:27 -0700 Subject: [PATCH 181/647] go.mod: update to latest sourcegraph/sourcegraph/lib (#767) This includes a fixup for an import that has moved from sourcegraph/sourcegraph/lib to sourcegraph/scip since the last time we updated the dependency. --- CHANGELOG.md | 2 ++ cmd/src/code_intel_upload_flags.go | 3 +- go.mod | 24 +++++++++---- go.sum | 54 +++++++++++++++++++++--------- 4 files changed, 59 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4feee8facf..8cf035efc8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,8 @@ All notable changes to `src-cli` are documented in this file. ### Fixed +- Output variables created from batch spec steps will no longer have an extra newline added if the output doesn't end with a newline. [sourcegraph/sourcegraph#36562](https://github.com/sourcegraph/sourcegraph/issues/36562) + ### Removed ## 3.40.4 diff --git a/cmd/src/code_intel_upload_flags.go b/cmd/src/code_intel_upload_flags.go index 46d50a6ea7..528e4293a2 100644 --- a/cmd/src/code_intel_upload_flags.go +++ b/cmd/src/code_intel_upload_flags.go @@ -13,7 +13,6 @@ import ( "google.golang.org/protobuf/proto" "github.com/sourcegraph/scip/bindings/go/scip" - "github.com/sourcegraph/sourcegraph/lib/codeintel/lsif/protocol/reader" "github.com/sourcegraph/sourcegraph/lib/codeintel/upload" "github.com/sourcegraph/src-cli/internal/api" @@ -241,7 +240,7 @@ func convertSCIPToLSIFGraph(out *output.Output, inputFile, outputFile string) er if err != nil { panic(errors.Wrapf(err, "failed reader.ConvertTypedIndexToGraphIndex")) } - err = reader.WriteNDJSON(reader.ElementsToJsonElements(els), tmp) + err = scip.WriteNDJSON(scip.ElementsToJsonElements(els), tmp) if err != nil { panic(err) } diff --git a/go.mod b/go.mod index 8abb51e3cb..fa98a23c2d 100644 --- a/go.mod +++ b/go.mod @@ -20,9 +20,9 @@ require ( github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf github.com/sourcegraph/scip v0.1.0 - github.com/sourcegraph/sourcegraph/lib v0.0.0-20220511160847-5a43d3ea24eb + github.com/sourcegraph/sourcegraph/lib v0.0.0-20220603221327-79226578ec33 github.com/stretchr/testify v1.7.1 - golang.org/x/net v0.0.0-20220412020605-290c469a71a5 + golang.org/x/net v0.0.0-20220526153639-5463443f8c37 golang.org/x/sync v0.0.0-20210220032951-036812b2e83c google.golang.org/protobuf v1.28.0 gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b @@ -32,26 +32,30 @@ require ( require ( github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect github.com/Masterminds/sprig v2.15.0+incompatible // indirect + github.com/alecthomas/chroma v0.10.0 // indirect github.com/aokoli/goutils v1.0.1 // indirect + github.com/aymerick/douceur v0.2.0 // indirect github.com/bufbuild/buf v1.4.0 // indirect - github.com/cockroachdb/errors v1.8.9 // indirect + github.com/charmbracelet/glamour v0.5.0 // indirect + github.com/cockroachdb/errors v1.9.0 // indirect github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f // indirect github.com/cockroachdb/redact v1.1.3 // indirect github.com/cpuguy83/go-md2man/v2 v2.0.1 // indirect github.com/davecgh/go-spew v1.1.1 // indirect + github.com/dlclark/regexp2 v1.4.0 // indirect github.com/envoyproxy/protoc-gen-validate v0.3.0-java // indirect - github.com/getsentry/sentry-go v0.12.0 // indirect + github.com/fatih/color v1.13.0 // indirect + github.com/getsentry/sentry-go v0.13.0 // indirect github.com/ghodss/yaml v1.0.0 // indirect - github.com/go-stack/stack v1.8.1 // indirect github.com/gofrs/flock v0.8.1 // indirect github.com/gofrs/uuid v4.2.0+incompatible // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect github.com/golang/protobuf v1.5.2 // indirect github.com/google/uuid v1.3.0 // indirect + github.com/gorilla/css v1.0.0 // indirect github.com/huandu/xstrings v1.0.0 // indirect github.com/imdario/mergo v0.3.4 // indirect - github.com/inconshreveable/log15 v0.0.0-20201112154412-8562bdadbbac // indirect github.com/inconshreveable/mousetrap v1.0.0 // indirect github.com/jdxcode/netrc v0.0.0-20210204082910-926c7f70242a // indirect github.com/jhump/protocompile v0.0.0-20220216033700-d705409f108f // indirect @@ -60,11 +64,15 @@ require ( github.com/klauspost/pgzip v1.2.5 // indirect github.com/kr/pretty v0.3.0 // indirect github.com/kr/text v0.2.0 // indirect + github.com/lucasb-eyer/go-colorful v1.2.0 // indirect github.com/mattn/go-colorable v0.1.12 // indirect github.com/mattn/go-runewidth v0.0.13 // indirect + github.com/microcosm-cc/bluemonday v1.0.17 // indirect github.com/moby/term v0.0.0-20210619224110-3f7ff695adc6 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/muesli/reflow v0.3.0 // indirect + github.com/muesli/termenv v0.9.0 // indirect github.com/mwitkow/go-proto-validators v0.0.0-20180403085117-0950a7990007 // indirect github.com/olekukonko/tablewriter v0.0.5 // indirect github.com/pkg/errors v0.9.1 // indirect @@ -81,13 +89,15 @@ require ( github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect github.com/xeipuuv/gojsonschema v1.2.0 // indirect + github.com/yuin/goldmark v1.4.4 // indirect + github.com/yuin/goldmark-emoji v1.0.1 // indirect go.opencensus.io v0.23.0 // indirect go.uber.org/atomic v1.9.0 // indirect go.uber.org/multierr v1.8.0 // indirect go.uber.org/zap v1.21.0 // indirect golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 // indirect golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3 // indirect - golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6 // indirect + golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a // indirect golang.org/x/term v0.0.0-20220411215600-e5f449aeb171 // indirect golang.org/x/text v0.3.7 // indirect golang.org/x/tools v0.1.10 // indirect diff --git a/go.sum b/go.sum index bdd3674d54..0cb7c00998 100644 --- a/go.sum +++ b/go.sum @@ -16,10 +16,14 @@ github.com/Masterminds/sprig v2.15.0+incompatible h1:0gSxPGWS9PAr7U2NsQ2YQg6juRD github.com/Masterminds/sprig v2.15.0+incompatible/go.mod h1:y6hNFY5UBTIWBxnzTeuNhlNS5hqE0NB0E6fgfo2Br3o= github.com/Shopify/goreferrer v0.0.0-20181106222321-ec9c9a553398/go.mod h1:a1uqRtAwp2Xwc6WNPJEufxJ7fx3npB4UV/JOLmbu5I0= github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY= +github.com/alecthomas/chroma v0.10.0 h1:7XDcGkCQopCNKjZHfYrNLraA+M7e0fMiJ/Mfikbfjek= +github.com/alecthomas/chroma v0.10.0/go.mod h1:jtJATyUxlIORhUOFNA9NZDWGAQ8wpxQQqNSB4rjA/1s= github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= github.com/aokoli/goutils v1.0.1 h1:7fpzNGoJ3VA8qcrm++XEE1QUe0mIwNeLa02Nwq7RDkg= github.com/aokoli/goutils v1.0.1/go.mod h1:SijmP0QR8LtwsmDs8Yii5Z/S4trXFGFC2oO5g9DP+DQ= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= +github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk= +github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4= github.com/aymerick/raymond v2.0.3-0.20180322193309-b565731e1464+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g= github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= github.com/benbjohnson/clock v1.3.0 h1:ip6w0uFQkncKQ979AypyG0ER7mqUSBdKLOgAle/AT8A= @@ -27,6 +31,8 @@ github.com/bufbuild/buf v1.4.0 h1:GqE3a8CMmcFvWPzuY3Mahf9Kf3S9XgZ/ORpfYFzO+90= github.com/bufbuild/buf v1.4.0/go.mod h1:mwHG7klTHnX+rM/ym8LXGl7vYpVmnwT96xWoRB4H5QI= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/charmbracelet/glamour v0.5.0 h1:wu15ykPdB7X6chxugG/NNfDUbyyrCLV9XBalj5wdu3g= +github.com/charmbracelet/glamour v0.5.0/go.mod h1:9ZRtG19AUIzcTm7FGLGbq3D5WKQ5UyZBbQsMQN0XIqc= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= @@ -38,8 +44,8 @@ github.com/cockroachdb/datadriven v1.0.1-0.20211007161720-b558070c3be0/go.mod h1 github.com/cockroachdb/datadriven v1.0.1-0.20220214170620-9913f5bc19b7/go.mod h1:hi0MtSY3AYDQNDi83kDkMH5/yqM/CsIrsOITkSoH7KI= github.com/cockroachdb/errors v1.6.1/go.mod h1:tm6FTP5G81vwJ5lC0SizQo374JNCOPrHyXGitRJoDqM= github.com/cockroachdb/errors v1.8.8/go.mod h1:z6VnEL3hZ/2ONZEvG7S5Ym0bU2AqPcEKnIiA1wbsSu0= -github.com/cockroachdb/errors v1.8.9 h1:eqUxTOUOduHP4D3f3wJ0kiyoNjDf6wLCso/4n7rBA4U= -github.com/cockroachdb/errors v1.8.9/go.mod h1:vaNcEYYqbIqB5JhKBhFV9CneUqeuEbB2OYJBK4GBNYQ= +github.com/cockroachdb/errors v1.9.0 h1:B48dYem5SlAY7iU8AKsgedb4gH6mo+bDkbtLIvM/a88= +github.com/cockroachdb/errors v1.9.0/go.mod h1:vaNcEYYqbIqB5JhKBhFV9CneUqeuEbB2OYJBK4GBNYQ= github.com/cockroachdb/logtags v0.0.0-20190617123548-eb05cc24525f/go.mod h1:i/u985jwjWRlyHXQbwatDASoW0RMlZ/3i9yJHE2xLkI= github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f h1:6jduT9Hfc0njg5jJ1DdKCFPdMBrp/mdZfCpa5h+WM74= github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= @@ -68,6 +74,8 @@ github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZm github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= github.com/dineshappavoo/basex v0.0.0-20170425072625-481a6f6dc663 h1:fctNkSsavbXpt8geFWZb8n+noCqS8MrOXRJ/YfdZ2dQ= github.com/dineshappavoo/basex v0.0.0-20170425072625-481a6f6dc663/go.mod h1:Kad2hux31v/IyD4Rf4wAwIyK48995rs3qAl9IUAhc2k= +github.com/dlclark/regexp2 v1.4.0 h1:F1rxgk7p4uKjwIQxBs9oAXe5CqrXlCduYEJvrF4u93E= +github.com/dlclark/regexp2 v1.4.0/go.mod h1:2pZnwuY/m+8K6iRw6wQdMtk+rH5tNGR1i55kozfMjCc= github.com/dustin/go-humanize v1.0.0 h1:VSnTsYCnlFHaM2/igO1h6X3HA71jcobQuxemgkq4zYo= github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= github.com/eknkc/amber v0.0.0-20171010120322-cdade1c07385/go.mod h1:0vRUJqYpeSZifjYj7uP3BG/gKcuzL9xWVV/Y+cK33KM= @@ -82,21 +90,22 @@ github.com/envoyproxy/protoc-gen-validate v0.3.0-java h1:bV5JGEB1ouEzZa0hgVDFFiC github.com/envoyproxy/protoc-gen-validate v0.3.0-java/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/etcd-io/bbolt v1.3.3/go.mod h1:ZF2nL25h33cCyBtcyWeZ2/I3HQOfTP+0PIEvHjkjCrw= github.com/fasthttp-contrib/websocket v0.0.0-20160511215533-1f3b11f56072/go.mod h1:duJ4Jxv5lDcvg4QuQr0oowTf7dz4/CR8NtyCooz9HL8= +github.com/fatih/color v1.13.0 h1:8LOYc1KYPPmyKMuN8QV2DNRWNbLo6LZ0iLs8+mlH53w= +github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M= github.com/flosch/pongo2 v0.0.0-20190707114632-bbf5a6c351f4/go.mod h1:T9YF2M40nIgbVgp3rreNmTged+9HrbNTIQf1PsaIiTA= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/gavv/httpexpect v2.0.0+incompatible/go.mod h1:x+9tiU1YnrOvnB725RkpoLv1M62hOWzwo5OXotisrKc= -github.com/getsentry/sentry-go v0.12.0 h1:era7g0re5iY13bHSdN/xMkyV+5zZppjRVQhZrXCaEIk= github.com/getsentry/sentry-go v0.12.0/go.mod h1:NSap0JBYWzHND8oMbyi0+XZhUalc1TBdRL1M71JZW2c= +github.com/getsentry/sentry-go v0.13.0 h1:20dgTiUSfxRB/EhMPtxcL9ZEbM1ZdR+W/7f7NWD+xWo= +github.com/getsentry/sentry-go v0.13.0/go.mod h1:EOsfu5ZdvKPfeHYV6pTVQnsjfp30+XA7//UooKNumH0= github.com/gin-contrib/sse v0.0.0-20190301062529-5545eab6dad3/go.mod h1:VJ0WA2NBN22VlZ2dKZQPAPnyWw5XTlK1KymzLKsr59s= github.com/gin-gonic/gin v1.4.0/go.mod h1:OW2EZn3DO8Ln9oIKOvM++LBO+5UPHJJDH72/q/3rZdM= github.com/go-check/check v0.0.0-20180628173108-788fd7840127/go.mod h1:9ES+weclKsC9YodN5RgxqK/VD9HM9JsCSh7rNhMZE98= github.com/go-errors/errors v1.0.1 h1:LUHzmkK3GUKUrL/1gfBUxAHzcev3apQlezX/+O7ma6w= github.com/go-errors/errors v1.0.1/go.mod h1:f4zRHt4oKfwPJE5k8C9vpYG+aDHdBFUsgrm6/TyX73Q= github.com/go-martini/martini v0.0.0-20170121215854-22fa46961aab/go.mod h1:/P9AEU963A2AYjv4d1V5eVL1CQbEJq6aCNHDDjibzu8= -github.com/go-stack/stack v1.8.1 h1:ntEHSVwIt7PNXNpgPmVfMrNhLtgjlmnZha2kOpuRiDw= -github.com/go-stack/stack v1.8.1/go.mod h1:dcoOX6HbPZSZptuspn9bctJ+N/CnF5gGygcUP3XYfe4= github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y= github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8= github.com/gobwas/httphead v0.0.0-20180130184737-2c6c146eadee/go.mod h1:L0fX3K22YWvt/FAX9NnzrNzcI4wNYi9Yku4O0LKYflo= @@ -151,6 +160,8 @@ github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+ github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= +github.com/gorilla/css v1.0.0 h1:BQqNyPTi50JCFMTw/b67hByjMVXZRwGha6wxVGkeihY= +github.com/gorilla/css v1.0.0/go.mod h1:Dn721qIggHpt4+EFCcTLTU/vk5ySda2ReITrtgBl60c= github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/grafana/regexp v0.0.0-20220202152701-6a046c4caf32 h1:M3wP8Hwic62qJsiydSgXtev03d4f92uN1I52nVjRgw0= @@ -166,8 +177,6 @@ github.com/hydrogen18/memlistener v0.0.0-20200120041712-dcc25e7acd91/go.mod h1:q github.com/imdario/mergo v0.3.4 h1:mKkfHkZWD8dC7WxKx3N9WCF0Y+dLau45704YQmY6H94= github.com/imdario/mergo v0.3.4/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= github.com/imkira/go-interpol v1.1.0/go.mod h1:z0h2/2T3XF8kyEPpRgJ3kmNv+C43p+I/CoI+jC3w2iA= -github.com/inconshreveable/log15 v0.0.0-20201112154412-8562bdadbbac h1:n1DqxAo4oWPMvH1+v+DLYlMCecgumhhgnxAPdqDIFHI= -github.com/inconshreveable/log15 v0.0.0-20201112154412-8562bdadbbac/go.mod h1:cOaXtrgN4ScfRrD9Bre7U1thNq5RtJ8ZoP4iXVGRj6o= github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/iris-contrib/blackfriday v2.0.0+incompatible/go.mod h1:UzZ2bDEoaSGPbkg6SAB4att1aAwTmVIx/5gCVqeyUdI= @@ -230,9 +239,12 @@ github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/labstack/echo/v4 v4.1.11/go.mod h1:i541M3Fj6f76NZtHSj7TXnyM8n2gaodfvfxNnFqi74g= github.com/labstack/echo/v4 v4.5.0/go.mod h1:czIriw4a0C1dFun+ObrXp7ok03xON0N1awStJ6ArI7Y= github.com/labstack/gommon v0.3.0/go.mod h1:MULnywXg0yavhxWKc+lOruYdAhDwPK9wf0OL7NoOu+k= +github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= +github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= +github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-colorable v0.1.11/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= github.com/mattn/go-colorable v0.1.12 h1:jF+Du6AlPIjs2BiUiQlKOX0rt3SujHxPnksPKZbaA40= github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= @@ -240,9 +252,11 @@ github.com/mattn/go-isatty v0.0.7/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hd github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= github.com/mattn/go-isatty v0.0.9/go.mod h1:YNRxwqDuOph6SZLI9vUUz6OYw3QyUt7WiY2yME+cCiQ= github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= +github.com/mattn/go-isatty v0.0.13/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9Y= github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= +github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk= github.com/mattn/go-runewidth v0.0.13 h1:lTGmDsbAYt5DmK6OnoV7EuIF1wEIFAcxld6ypU4OSgU= github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= github.com/mattn/goveralls v0.0.2/go.mod h1:8d1ZMHsd7fW6IRPKQh46F2WRpyib5/X4FOpevwGNQEw= @@ -250,6 +264,8 @@ github.com/mediocregopher/mediocre-go-lib v0.0.0-20181029021733-cb65787f37ed/go. github.com/mediocregopher/radix/v3 v3.3.0/go.mod h1:EmfVyvspXz1uZEyPBMyGK+kjWiKQGvsUt6O3Pj+LDCQ= github.com/mediocregopher/radix/v3 v3.4.2/go.mod h1:8FL3F6UQRXHXIBSPUs5h0RybMF8i4n7wVopoX3x7Bv8= github.com/microcosm-cc/bluemonday v1.0.2/go.mod h1:iVP4YcDBq+n/5fb23BhYFvIMq/leAFZyRl6bYmGDlGc= +github.com/microcosm-cc/bluemonday v1.0.17 h1:Z1a//hgsQ4yjC+8zEkV8IWySkXnsxmdSY642CTFQb5Y= +github.com/microcosm-cc/bluemonday v1.0.17/go.mod h1:Z0r70sCuXHig8YpBzCc5eGHAap2K7e/u082ZUpDRRqM= github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= @@ -264,6 +280,10 @@ github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3Rllmb github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/moul/http2curl v1.0.0/go.mod h1:8UbvGypXm98wA/IqH45anm5Y2Z6ep6O31QGOAZ3H0fQ= +github.com/muesli/reflow v0.3.0 h1:IFsN6K9NfGtjeggFP+68I4chLZV2yIKsXJFNZ+eWh6s= +github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKtnHY/8= +github.com/muesli/termenv v0.9.0 h1:wnbOaGz+LUR3jNT0zOzinPnyDaCZUQRZj9GxK8eRVl8= +github.com/muesli/termenv v0.9.0/go.mod h1:R/LzAKf+suGs4IsO95y7+7DpFHO0KABgnZqtlyx2mBw= github.com/mwitkow/go-proto-validators v0.0.0-20180403085117-0950a7990007 h1:28i1IjGcx8AofiB4N3q5Yls55VEaitzuEPkFJEVgGkA= github.com/mwitkow/go-proto-validators v0.0.0-20180403085117-0950a7990007/go.mod h1:m2XC9Qq0AlmmVksL6FktJCdTYyLk7V3fKyp0sl1yWQo= github.com/nats-io/jwt v0.3.0/go.mod h1:fRYCDE99xlTsqUzISS1Bi75UBJ6ljOJQOAAu5VglpSg= @@ -303,6 +323,7 @@ github.com/pseudomuto/protoc-gen-doc v1.5.1 h1:Ah259kcrio7Ix1Rhb6u8FCaOkzf9qRBqX github.com/pseudomuto/protoc-gen-doc v1.5.1/go.mod h1:XpMKYg6zkcpgfpCfQ8GcWBDRtRxOmMR5w7pz4Xo+dYM= github.com/pseudomuto/protokit v0.2.0 h1:hlnBDcy3YEDXH7kc9gV+NLaN0cDzhDvD1s7Y6FZ8RpM= github.com/pseudomuto/protokit v0.2.0/go.mod h1:2PdH30hxVHsup8KpBTOXTBeMVhJZVio3Q8ViKSAXT0Q= +github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY= github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= @@ -326,12 +347,10 @@ github.com/sourcegraph/go-diff v0.6.1 h1:hmA1LzxW0n1c3Q4YbrFgg4P99GSnebYa3x8gr0H github.com/sourcegraph/go-diff v0.6.1/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= -github.com/sourcegraph/scip v0.0.0-20220525190354-5922ee059bf9 h1:1+L7s9/gy6r3EH33eKNzzD2oyU3pXN5LhzmjdqpumXU= -github.com/sourcegraph/scip v0.0.0-20220525190354-5922ee059bf9/go.mod h1:/AZ8RvsnRfeCZy232PJuVZqcl9f82fJnYwdWZeU2JCo= github.com/sourcegraph/scip v0.1.0 h1:kTs0CJaLQvcRZjg+HpGrcJPNX2Tx31+d6szWio3ZOkQ= github.com/sourcegraph/scip v0.1.0/go.mod h1:/AZ8RvsnRfeCZy232PJuVZqcl9f82fJnYwdWZeU2JCo= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20220511160847-5a43d3ea24eb h1:D8ciD0FEcPNnVm6BC8vg7gWJ9VxoJe6k/4j+Qxparj0= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20220511160847-5a43d3ea24eb/go.mod h1:iFiGPqnhOvQziDZkpWasU+Uo1BaEt/Au9kNK4VpqyOw= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20220603221327-79226578ec33 h1:g8Dam3HJJGvbZcJQ7udEbud6d+fbcC/4kuSlRgf4ngo= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20220603221327-79226578ec33/go.mod h1:BBjyIONP1ui+HiR+vuPJtLP9jy3K3O0Wyav5Xv8Vpb4= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= @@ -380,6 +399,10 @@ github.com/yudai/pp v2.0.1+incompatible/go.mod h1:PuxR/8QJ7cyCkFp/aUDS+JY727OFEZ github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +github.com/yuin/goldmark v1.4.4 h1:zNWRjYUW32G9KirMXYHQHVNFkXvMI7LpgNW2AgYAoIs= +github.com/yuin/goldmark v1.4.4/go.mod h1:rmuwmfZ0+bvzB24eSC//bk1R1Zp3hM0OXYv/G2LIilg= +github.com/yuin/goldmark-emoji v1.0.1 h1:ctuWEyzGBwiucEqxzwe0SOYDXPAucOrE9NQC18Wa1os= +github.com/yuin/goldmark-emoji v1.0.1/go.mod h1:2w1E6FEWLcDQkoTE+7HU6QF1F6SLlNGjRIBbIZQFqkQ= go.opencensus.io v0.23.0 h1:gqCw0LfLxScz8irSi8exQc7fyQ0fKQU/qnC/X8+V/1M= go.opencensus.io v0.23.0/go.mod h1:XItmlyltB5F7CS4xOC1DcqMoFqwtC6OG2xF7mCv7P7E= go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI= @@ -435,9 +458,10 @@ golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwY golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= +golang.org/x/net v0.0.0-20210614182718-04defd469f4e/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211008194852-3b03d305991f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/net v0.0.0-20220412020605-290c469a71a5 h1:bRb386wvrE+oBNdF1d/Xh9mQrfQ4ecYhW5qJ5GvTGT4= -golang.org/x/net v0.0.0-20220412020605-290c469a71a5/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= +golang.org/x/net v0.0.0-20220526153639-5463443f8c37 h1:lUkvobShwKsOesNfWWlCS5q7fnbG1MEliIzwu886fn8= +golang.org/x/net v0.0.0-20220526153639-5463443f8c37/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -477,8 +501,8 @@ golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211007075335-d3039528d8ac/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6 h1:nonptSpoQ4vQjyraW20DXPAglgQfVnM9ZC6MmNLMR60= -golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a h1:dGzPydgVsqGcTRVwiLJ1jVbufYwmzD3LfVPLKsKg+0k= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20220411215600-e5f449aeb171 h1:EH1Deb8WZJ0xc0WK//leUHXcX9aLE5SymusoTmMZye8= golang.org/x/term v0.0.0-20220411215600-e5f449aeb171/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= From a8eddf850da001cb32845a3a56ea0db5bee34ecc Mon Sep 17 00:00:00 2001 From: Adam Harvey Date: Mon, 6 Jun 2022 16:14:31 -0700 Subject: [PATCH 182/647] changelog: update for 3.40.8 (#769) --- CHANGELOG.md | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8cf035efc8..db64f1fb8b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,9 +17,17 @@ All notable changes to `src-cli` are documented in this file. ### Fixed +### Removed + +## 3.40.8 + +### Fixed + - Output variables created from batch spec steps will no longer have an extra newline added if the output doesn't end with a newline. [sourcegraph/sourcegraph#36562](https://github.com/sourcegraph/sourcegraph/issues/36562) -### Removed +## 3.40.5 to 3.40.7 + +- No substantive changes; these releases were related solely to improving our release machinery. ## 3.40.4 @@ -27,6 +35,10 @@ All notable changes to `src-cli` are documented in this file. - It's now possible to install src-cli via `npm install -g @sourcegraph/src`. [sourcegraph/src-cli#760](https://github.com/sourcegraph/src-cli/pull/760) +## 3.40.3 + +- No substantive changes; this release was related solely to improving our release machinery. + ## 3.40.2 ### Changed From 17dd444c70ceb738fc13a122d5b3463aa1d2e4ef Mon Sep 17 00:00:00 2001 From: Bolaji Olajide <25608335+BolajiOlajide@users.noreply.github.com> Date: Wed, 8 Jun 2022 15:05:35 +0200 Subject: [PATCH 183/647] batches: ensure .gitconfig email is properly inserted in batch spec (#773) --- CHANGELOG.md | 2 ++ internal/batches/service/service.go | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index db64f1fb8b..334a738a76 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,8 @@ All notable changes to `src-cli` are documented in this file. ### Fixed +- Global git email gets inserted as plain text when running `src batch new -f ` and doesn't result in a schema validation failure. [sourcegraph/src-cli#773](https://github.com/sourcegraph/src-cli/pull/773) + ### Removed ## 3.40.8 diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index 6e155f77c0..e68fa5941a 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -4,12 +4,12 @@ import ( "context" "encoding/json" "fmt" - "html/template" "os" "os/exec" "path" "strings" "sync" + "text/template" "github.com/grafana/regexp" From 087a6b7ca66f6191fe692a4c87e8a36ceed84bae Mon Sep 17 00:00:00 2001 From: Kelli Rockwell Date: Wed, 8 Jun 2022 09:29:23 -0700 Subject: [PATCH 184/647] batches: bump `sourcegraph/lib` (#772) --- go.mod | 6 +++--- go.sum | 11 ++++++----- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/go.mod b/go.mod index fa98a23c2d..acc849f35e 100644 --- a/go.mod +++ b/go.mod @@ -20,12 +20,12 @@ require ( github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf github.com/sourcegraph/scip v0.1.0 - github.com/sourcegraph/sourcegraph/lib v0.0.0-20220603221327-79226578ec33 + github.com/sourcegraph/sourcegraph/lib v0.0.0-20220607233325-c482e0e3d7a1 github.com/stretchr/testify v1.7.1 golang.org/x/net v0.0.0-20220526153639-5463443f8c37 golang.org/x/sync v0.0.0-20210220032951-036812b2e83c google.golang.org/protobuf v1.28.0 - gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b + gopkg.in/yaml.v3 v3.0.1 jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7 ) @@ -101,7 +101,7 @@ require ( golang.org/x/term v0.0.0-20220411215600-e5f449aeb171 // indirect golang.org/x/text v0.3.7 // indirect golang.org/x/tools v0.1.10 // indirect - golang.org/x/xerrors v0.0.0-20220411194840-2f41105eb62f // indirect + golang.org/x/xerrors v0.0.0-20220517211312-f3a8303e98df // indirect google.golang.org/genproto v0.0.0-20220414192740-2d67ff6cf2b4 // indirect google.golang.org/grpc v1.45.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect diff --git a/go.sum b/go.sum index 0cb7c00998..a81c086ff9 100644 --- a/go.sum +++ b/go.sum @@ -349,8 +349,8 @@ github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWii github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= github.com/sourcegraph/scip v0.1.0 h1:kTs0CJaLQvcRZjg+HpGrcJPNX2Tx31+d6szWio3ZOkQ= github.com/sourcegraph/scip v0.1.0/go.mod h1:/AZ8RvsnRfeCZy232PJuVZqcl9f82fJnYwdWZeU2JCo= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20220603221327-79226578ec33 h1:g8Dam3HJJGvbZcJQ7udEbud6d+fbcC/4kuSlRgf4ngo= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20220603221327-79226578ec33/go.mod h1:BBjyIONP1ui+HiR+vuPJtLP9jy3K3O0Wyav5Xv8Vpb4= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20220607233325-c482e0e3d7a1 h1:FIVaSswBiVsNEmRyjsEilfDkuyyaT4i3HNB66P9XXDw= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20220607233325-c482e0e3d7a1/go.mod h1:rAXa9YBKDd/wQK9bY8IHcV/kbC2OOfFU3Rc/4SfBAEw= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= @@ -537,8 +537,8 @@ golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8T golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20220411194840-2f41105eb62f h1:GGU+dLjvlC3qDwqYgL6UgRmHXhOOgns0bZu2Ty5mm6U= -golang.org/x/xerrors v0.0.0-20220411194840-2f41105eb62f/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20220517211312-f3a8303e98df h1:5Pf6pFKu98ODmgnpvkJ3kFUOQGGLIzLIkbzUHp47618= +golang.org/x/xerrors v0.0.0-20220517211312-f3a8303e98df/go.mod h1:K8+ghG5WaK9qNqU5K3HdILfMLy1f3aNYFI/wnl100a8= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/genproto v0.0.0-20180518175338-11a468237815/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= @@ -596,8 +596,9 @@ gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20191120175047-4206685974f2/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gotest.tools/v3 v3.0.2 h1:kG1BFyqVHuQoVQiR1bWGnfz/fmHvvuiSPIV7rvl360E= gotest.tools/v3 v3.0.2/go.mod h1:3SzNCllyD9/Y+b5r9JIKQ474KzkZyqLqEfYqMsX94Bk= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= From 040e554289750cc0a063893b23c5e1442af8f849 Mon Sep 17 00:00:00 2001 From: Kelli Rockwell Date: Wed, 8 Jun 2022 10:39:06 -0700 Subject: [PATCH 185/647] changelog: update for 4.30.9 (#771) --- CHANGELOG.md | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 334a738a76..b006e68365 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,10 +17,18 @@ All notable changes to `src-cli` are documented in this file. ### Fixed -- Global git email gets inserted as plain text when running `src batch new -f ` and doesn't result in a schema validation failure. [sourcegraph/src-cli#773](https://github.com/sourcegraph/src-cli/pull/773) - ### Removed +## 3.40.9 + +### Added + +- A new [templating](https://docs.sourcegraph.com/campaigns/references/batch_spec_templating) variable, `batch_change_link` has been added for more control over where the "Created by Sourcegraph batch change ..." message appears in the published changeset description. [#491](https://github.com/sourcegraph/sourcegraph/pull/35319) + +### Fixed + +- Global git email gets inserted as plain text when running `src batch new -f ` and doesn't result in a schema validation failure. [sourcegraph/src-cli#773](https://github.com/sourcegraph/src-cli/pull/773) + ## 3.40.8 ### Fixed From 75fa7f1d38932e0794e7ce004e105d6ec8eaa635 Mon Sep 17 00:00:00 2001 From: Randell Callahan Date: Tue, 14 Jun 2022 08:59:13 -0600 Subject: [PATCH 186/647] batches: Mount paths into a container (#770) --- CHANGELOG.md | 2 + cmd/src/batch_common.go | 45 ++- cmd/src/batch_exec.go | 2 + cmd/src/batch_remote.go | 2 +- cmd/src/batch_repositories.go | 2 +- cmd/src/batch_validate.go | 2 +- go.mod | 13 +- go.sum | 26 +- internal/batches/executor/coordinator.go | 39 +- internal/batches/executor/coordinator_test.go | 47 ++- internal/batches/executor/executor.go | 21 +- internal/batches/executor/executor_test.go | 32 ++ internal/batches/executor/run_steps.go | 24 +- internal/batches/service/remote.go | 2 +- internal/batches/service/service.go | 39 +- internal/batches/service/service_test.go | 346 +++++++++++++++++- 16 files changed, 576 insertions(+), 68 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b006e68365..02a34cad47 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,8 @@ All notable changes to `src-cli` are documented in this file. ### Added +- Batch Specs now support mounting a path from the local machine into a Docker container. [sourcegraph/sourcegraph#31790](https://github.com/sourcegraph/sourcegraph/issues/31790) + ### Changed ### Fixed diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index 5ab5cf9b4d..6fa550f472 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -9,11 +9,13 @@ import ( "os/exec" "os/signal" "path" + "path/filepath" "runtime" "strings" "time" "github.com/mattn/go-isatty" + "github.com/sourcegraph/sourcegraph/lib/errors" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" @@ -279,7 +281,7 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp // Parse flags and build up our service and executor options. ui.ParsingBatchSpec() - batchSpec, rawSpec, err := parseBatchSpec(opts.file, svc) + batchSpec, rawSpec, err := parseBatchSpec(opts.file, svc, false) if err != nil { var multiErr errors.MultiError if errors.As(err, &multiErr) { @@ -347,15 +349,16 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp // EXECUTION OF TASKS coord := svc.NewCoordinator(executor.NewCoordinatorOpts{ - Creator: workspaceCreator, - CacheDir: opts.flags.cacheDir, - Cache: executor.NewDiskCache(opts.flags.cacheDir), - SkipErrors: opts.flags.skipErrors, - CleanArchives: opts.flags.cleanArchives, - Parallelism: opts.flags.parallelism, - Timeout: opts.flags.timeout, - KeepLogs: opts.flags.keepLogs, - TempDir: opts.flags.tempDir, + Creator: workspaceCreator, + CacheDir: opts.flags.cacheDir, + Cache: executor.NewDiskCache(opts.flags.cacheDir), + SkipErrors: opts.flags.skipErrors, + CleanArchives: opts.flags.cleanArchives, + Parallelism: opts.flags.parallelism, + Timeout: opts.flags.timeout, + KeepLogs: opts.flags.keepLogs, + TempDir: opts.flags.tempDir, + AllowPathMounts: true, }) ui.CheckingCache() @@ -465,7 +468,10 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp // parseBatchSpec parses and validates the given batch spec. If the spec has // validation errors, they are returned. -func parseBatchSpec(file string, svc *service.Service) (*batcheslib.BatchSpec, string, error) { +// +// isRemote argument is a temporary argument used to determine if the batch spec is being parsed for remote +// (server-side) processing. Remote processing does not support mounts yet. +func parseBatchSpec(file string, svc *service.Service, isRemote bool) (*batcheslib.BatchSpec, string, error) { f, err := batchOpenFileFlag(file) if err != nil { return nil, "", err @@ -477,7 +483,22 @@ func parseBatchSpec(file string, svc *service.Service) (*batcheslib.BatchSpec, s return nil, "", errors.Wrap(err, "reading batch spec") } - spec, err := svc.ParseBatchSpec(data) + var workingDirectory string + // if the batch spec is being provided via standard input, set the working directory to the current directory + if file == "" || file == "-" { + workingDirectory, err = os.Getwd() + if err != nil { + return nil, "", errors.Wrap(err, "batch spec path") + } + } else { + p, err := filepath.Abs(file) + if err != nil { + return nil, "", errors.Wrap(err, "batch spec path") + } + workingDirectory = filepath.Dir(p) + } + + spec, err := svc.ParseBatchSpec(workingDirectory, data, isRemote) return spec, string(data), err } diff --git a/cmd/src/batch_exec.go b/cmd/src/batch_exec.go index 021ad9333a..2c81559bf0 100644 --- a/cmd/src/batch_exec.go +++ b/cmd/src/batch_exec.go @@ -142,6 +142,8 @@ func executeBatchSpecInWorkspaces(ctx context.Context, ui *ui.JSONLines, opts ex Timeout: opts.flags.timeout, KeepLogs: opts.flags.keepLogs, TempDir: opts.flags.tempDir, + // Temporarily prevent the ability to sending a batch spec with a mount for server-side processing. + AllowPathMounts: false, }) // `src batch exec` uses server-side caching for changeset specs, so we diff --git a/cmd/src/batch_remote.go b/cmd/src/batch_remote.go index beeb8a25f2..9384f32bfd 100644 --- a/cmd/src/batch_remote.go +++ b/cmd/src/batch_remote.go @@ -63,7 +63,7 @@ Examples: // may as well validate it at the same time so we don't even have to go to // the backend if it's invalid. ui.ParsingBatchSpec() - spec, raw, err := parseBatchSpec(file, svc) + spec, raw, err := parseBatchSpec(file, svc, true) if err != nil { ui.ParsingBatchSpecFailure(err) return err diff --git a/cmd/src/batch_repositories.go b/cmd/src/batch_repositories.go index c54467cc5a..83beb40915 100644 --- a/cmd/src/batch_repositories.go +++ b/cmd/src/batch_repositories.go @@ -75,7 +75,7 @@ Examples: } out := output.NewOutput(flagSet.Output(), output.OutputOpts{Verbose: *verbose}) - spec, _, err := parseBatchSpec(file, svc) + spec, _, err := parseBatchSpec(file, svc, false) if err != nil { ui := &ui.TUI{Out: out} ui.ParsingBatchSpecFailure(err) diff --git a/cmd/src/batch_validate.go b/cmd/src/batch_validate.go index 635d30a2e4..3d40a8caca 100644 --- a/cmd/src/batch_validate.go +++ b/cmd/src/batch_validate.go @@ -75,7 +75,7 @@ Examples: return err } - if _, _, err := parseBatchSpec(file, svc); err != nil { + if _, _, err := parseBatchSpec(file, svc, false); err != nil { ui.ParsingBatchSpecFailure(err) return err } diff --git a/go.mod b/go.mod index acc849f35e..83a95fc340 100644 --- a/go.mod +++ b/go.mod @@ -20,8 +20,8 @@ require ( github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf github.com/sourcegraph/scip v0.1.0 - github.com/sourcegraph/sourcegraph/lib v0.0.0-20220607233325-c482e0e3d7a1 - github.com/stretchr/testify v1.7.1 + github.com/sourcegraph/sourcegraph/lib v0.0.0-20220613202038-1231f0d77142 + github.com/stretchr/testify v1.7.2 golang.org/x/net v0.0.0-20220526153639-5463443f8c37 golang.org/x/sync v0.0.0-20210220032951-036812b2e83c google.golang.org/protobuf v1.28.0 @@ -83,6 +83,7 @@ require ( github.com/rivo/uniseg v0.2.0 // indirect github.com/rogpeppe/go-internal v1.8.1 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect + github.com/sourcegraph/log v0.0.0-20220608183241-51d325291e9a // indirect github.com/spf13/cobra v1.4.0 // indirect github.com/spf13/pflag v1.0.5 // indirect github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect @@ -96,12 +97,12 @@ require ( go.uber.org/multierr v1.8.0 // indirect go.uber.org/zap v1.21.0 // indirect golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 // indirect - golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3 // indirect - golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a // indirect + golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 // indirect + golang.org/x/sys v0.0.0-20220610221304-9f5ed59c137d // indirect golang.org/x/term v0.0.0-20220411215600-e5f449aeb171 // indirect golang.org/x/text v0.3.7 // indirect - golang.org/x/tools v0.1.10 // indirect - golang.org/x/xerrors v0.0.0-20220517211312-f3a8303e98df // indirect + golang.org/x/tools v0.1.11 // indirect + golang.org/x/xerrors v0.0.0-20220609144429-65e65417b02f // indirect google.golang.org/genproto v0.0.0-20220414192740-2d67ff6cf2b4 // indirect google.golang.org/grpc v1.45.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect diff --git a/go.sum b/go.sum index a81c086ff9..a932accf06 100644 --- a/go.sum +++ b/go.sum @@ -347,10 +347,12 @@ github.com/sourcegraph/go-diff v0.6.1 h1:hmA1LzxW0n1c3Q4YbrFgg4P99GSnebYa3x8gr0H github.com/sourcegraph/go-diff v0.6.1/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= +github.com/sourcegraph/log v0.0.0-20220608183241-51d325291e9a h1:poxCcQH13nS9l4tkXN7+qRwmyxdO1lYeOUEY9ycwH84= +github.com/sourcegraph/log v0.0.0-20220608183241-51d325291e9a/go.mod h1:A+9F6IicYvBbl2aT0R81lMraKcXjVfdfw352yPe2yJI= github.com/sourcegraph/scip v0.1.0 h1:kTs0CJaLQvcRZjg+HpGrcJPNX2Tx31+d6szWio3ZOkQ= github.com/sourcegraph/scip v0.1.0/go.mod h1:/AZ8RvsnRfeCZy232PJuVZqcl9f82fJnYwdWZeU2JCo= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20220607233325-c482e0e3d7a1 h1:FIVaSswBiVsNEmRyjsEilfDkuyyaT4i3HNB66P9XXDw= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20220607233325-c482e0e3d7a1/go.mod h1:rAXa9YBKDd/wQK9bY8IHcV/kbC2OOfFU3Rc/4SfBAEw= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20220613202038-1231f0d77142 h1:wnp9JgzLmppL9SAUkkjFp8V2Q8Q/oLVJoqXRxHWx2zU= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20220613202038-1231f0d77142/go.mod h1:RaBtTwfNRQvoRTEcbrKLesaEbWex/KblcPDd979zzww= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= @@ -372,8 +374,8 @@ github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81P github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.7.1 h1:5TQK59W5E3v0r2duFAb7P95B6hEeOyEnHRa8MjYSMTY= -github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.2 h1:4jaiDzPyXQvSd7D0EjG45355tLlV3VOECpq10pLC+8s= +github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals= github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc= github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw= github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= @@ -435,8 +437,8 @@ golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzB golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3 h1:kQgndtyPBW/JIYERgdxfwMYh3AVStj88WQTlNDi2a+o= -golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3/go.mod h1:3p9vT2HGsQu2K1YbXdKPJLVgG5VJdoTa1poYQBtP1AY= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 h1:6zppjxzCulZykYSLyVDYbneBfbaBIQPYMevg0bEwv2s= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -501,8 +503,8 @@ golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211007075335-d3039528d8ac/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a h1:dGzPydgVsqGcTRVwiLJ1jVbufYwmzD3LfVPLKsKg+0k= -golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220610221304-9f5ed59c137d h1:Zu/JngovGLVi6t2J3nmAf3AoTDwuzw85YZ3b9o4yU7s= +golang.org/x/sys v0.0.0-20220610221304-9f5ed59c137d/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20220411215600-e5f449aeb171 h1:EH1Deb8WZJ0xc0WK//leUHXcX9aLE5SymusoTmMZye8= golang.org/x/term v0.0.0-20220411215600-e5f449aeb171/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= @@ -531,14 +533,14 @@ golang.org/x/tools v0.0.0-20200624163319-25775e59acb7/go.mod h1:EkVYQZoAsY45+roY golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= -golang.org/x/tools v0.1.10 h1:QjFRCZxdOhBJ/UNgnBZLbNV13DlbnK0quyivTnXJM20= -golang.org/x/tools v0.1.10/go.mod h1:Uh6Zz+xoGYZom868N8YTex3t7RhtHDBrE8Gzo9bV56E= +golang.org/x/tools v0.1.11 h1:loJ25fNOEhSXfHrpoGj91eCUThwdNX6u24rO1xnNteY= +golang.org/x/tools v0.1.11/go.mod h1:SgwaegtQh8clINPpECJMqnxLv9I09HLqnW3RMqW0CA4= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20220517211312-f3a8303e98df h1:5Pf6pFKu98ODmgnpvkJ3kFUOQGGLIzLIkbzUHp47618= -golang.org/x/xerrors v0.0.0-20220517211312-f3a8303e98df/go.mod h1:K8+ghG5WaK9qNqU5K3HdILfMLy1f3aNYFI/wnl100a8= +golang.org/x/xerrors v0.0.0-20220609144429-65e65417b02f h1:uF6paiQQebLeSXkrTqHqz0MXhXXS1KgF41eUdBNvxK0= +golang.org/x/xerrors v0.0.0-20220609144429-65e65417b02f/go.mod h1:K8+ghG5WaK9qNqU5K3HdILfMLy1f3aNYFI/wnl100a8= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/genproto v0.0.0-20180518175338-11a468237815/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= diff --git a/internal/batches/executor/coordinator.go b/internal/batches/executor/coordinator.go index 57af61d669..63d7ec7219 100644 --- a/internal/batches/executor/coordinator.go +++ b/internal/batches/executor/coordinator.go @@ -23,7 +23,7 @@ type taskExecutor interface { Wait(context.Context) ([]taskResult, error) } -// Coordinates coordinates the execution of Tasks. It makes use of an executor, +// Coordinator coordinates the execution of Tasks. It makes use of an executor, // checks the ExecutionCache whether execution is necessary, builds // batcheslib.ChangesetSpecs out of the executionResults. type Coordinator struct { @@ -53,11 +53,12 @@ type NewCoordinatorOpts struct { // Used by batcheslib.BuildChangesetSpecs Features batches.FeatureFlags - CleanArchives bool - Parallelism int - Timeout time.Duration - KeepLogs bool - TempDir string + CleanArchives bool + Parallelism int + Timeout time.Duration + KeepLogs bool + TempDir string + AllowPathMounts bool } func NewCoordinator(opts NewCoordinatorOpts) *Coordinator { @@ -71,10 +72,17 @@ func NewCoordinator(opts NewCoordinatorOpts) *Coordinator { Creator: opts.Creator, Logger: logManager, - Parallelism: opts.Parallelism, - Timeout: opts.Timeout, - TempDir: opts.TempDir, + Parallelism: opts.Parallelism, + Timeout: opts.Timeout, + TempDir: opts.TempDir, + AllowPathMounts: opts.AllowPathMounts, WriteStepCacheResult: func(ctx context.Context, stepResult execution.AfterStepResult, task *Task) error { + // Temporarily skip writing to the cache if a mount is present + for _, step := range task.Steps { + if len(step.Mount) > 0 { + return nil + } + } cacheKey := task.cacheKey(globalEnv) return writeToCache(ctx, opts.Cache, stepResult, task, cacheKey) }, @@ -248,7 +256,18 @@ func (c *Coordinator) writeExecutionCacheResult(ctx context.Context, taskResult } func (c *Coordinator) writeCacheAndBuildSpecs(ctx context.Context, batchSpec *batcheslib.BatchSpec, taskResult taskResult, ui TaskExecutionUI) ([]*batcheslib.ChangesetSpec, error) { - c.writeExecutionCacheResult(ctx, taskResult, ui) + // Temporarily prevent writing to the cache when running a spec with a mount. Caching does not at the moment "know" + // when a file that is being mounted has changed. This causes the execution not to re-run if a mounted file changes. + hasMount := false + for _, step := range batchSpec.Steps { + if len(step.Mount) > 0 { + hasMount = true + break + } + } + if !hasMount { + c.writeExecutionCacheResult(ctx, taskResult, ui) + } // If the steps didn't result in any diff, we don't need to create a // changeset spec that's displayed to the user and send to the server. diff --git a/internal/batches/executor/coordinator_test.go b/internal/batches/executor/coordinator_test.go index c2d8af09f0..4868de9e4f 100644 --- a/internal/batches/executor/coordinator_test.go +++ b/internal/batches/executor/coordinator_test.go @@ -261,6 +261,41 @@ func TestCoordinator_Execute(t *testing.T) { }), }, }, + { + name: "skip cache for step mount", + + tasks: []*Task{srcCLITask, sourcegraphTask}, + + batchSpec: &batcheslib.BatchSpec{ + Name: "my-batch-change", + Description: "the description", + ChangesetTemplate: testChangesetTemplate, + Steps: []batcheslib.Step{ + { + Run: "echo foo", + Mount: []batcheslib.Mount{{Path: "/foo/bar/sample.sh", Mountpoint: "/tmp/sample.sh"}}, + }, + }, + }, + + executor: &dummyExecutor{ + results: []taskResult{ + {task: srcCLITask, result: execution.Result{Diff: `dummydiff1`}}, + {task: sourcegraphTask, result: execution.Result{Diff: `dummydiff2`}}, + }, + }, + opts: NewCoordinatorOpts{Features: featuresAllEnabled()}, + + wantCacheEntries: 0, + wantSpecs: []*batcheslib.ChangesetSpec{ + buildSpecFor(testRepo1, func(spec *batcheslib.ChangesetSpec) { + spec.Commits[0].Diff = `dummydiff1` + }), + buildSpecFor(testRepo2, func(spec *batcheslib.ChangesetSpec) { + spec.Commits[0].Diff = `dummydiff2` + }), + }, + }, } for _, tc := range tests { @@ -277,9 +312,9 @@ func TestCoordinator_Execute(t *testing.T) { logManager := mock.LogNoOpManager{} - cache := newInMemoryExecutionCache() + c := newInMemoryExecutionCache() coord := Coordinator{ - cache: cache, + cache: c, exec: tc.executor, logManager: logManager, opts: tc.opts, @@ -323,15 +358,15 @@ func TestCoordinator_Execute(t *testing.T) { verifyCache := func(t *testing.T) { // Verify that there is a cache entry for each repo. - if have, want := cache.size(), tc.wantCacheEntries; have != want { - t.Errorf("unexpected number of cache entries: have=%d want=%d cache=%+v", have, want, cache) + if have, want := c.size(), tc.wantCacheEntries; have != want { + t.Errorf("unexpected number of cache entries: have=%d want=%d cache=%+v", have, want, c) } } // Sanity check, since we're going to be looking at the side effects // on the cache. - if cache.size() != 0 { - t.Fatalf("unexpectedly hot cache: %+v", cache) + if c.size() != 0 { + t.Fatalf("unexpectedly hot cache: %+v", c) } // Run with a cold cache. diff --git a/internal/batches/executor/executor.go b/internal/batches/executor/executor.go index f41b584a76..c9a4d88741 100644 --- a/internal/batches/executor/executor.go +++ b/internal/batches/executor/executor.go @@ -8,6 +8,7 @@ import ( "time" "github.com/neelance/parallel" + "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/batches/log" @@ -62,6 +63,7 @@ type newExecutorOpts struct { Parallelism int Timeout time.Duration TempDir string + AllowPathMounts bool WriteStepCacheResult func(ctx context.Context, stepResult execution.AfterStepResult, task *Task) error } @@ -147,7 +149,7 @@ func (x *executor) do(ctx context.Context, task *Task, ui TaskExecutionUI) (err ui.TaskStarted(task) // Let's set up our logging. - log, err := x.opts.Logger.AddTask(util.SlugForPathInRepo(task.Repository.Name, task.Repository.Rev(), task.Path)) + l, err := x.opts.Logger.AddTask(util.SlugForPathInRepo(task.Repository.Name, task.Repository.Rev(), task.Path)) if err != nil { return errors.Wrap(err, "creating log file") } @@ -155,12 +157,12 @@ func (x *executor) do(ctx context.Context, task *Task, ui TaskExecutionUI) (err if err != nil { err = TaskExecutionErr{ Err: err, - Logfile: log.Path(), + Logfile: l.Path(), Repository: task.Repository.Name, } - log.MarkErrored() + l.MarkErrored() } - log.Close() + l.Close() }() // Now checkout the archive. @@ -172,11 +174,12 @@ func (x *executor) do(ctx context.Context, task *Task, ui TaskExecutionUI) (err // Actually execute the steps. opts := &executionOpts{ - task: task, - logger: log, - wc: x.opts.Creator, - ensureImage: x.opts.EnsureImage, - tempDir: x.opts.TempDir, + task: task, + logger: l, + wc: x.opts.Creator, + ensureImage: x.opts.EnsureImage, + tempDir: x.opts.TempDir, + allowPathMounts: x.opts.AllowPathMounts, ui: ui.StepsExecutionUI(task), writeStepCacheResult: x.opts.WriteStepCacheResult, diff --git a/internal/batches/executor/executor_test.go b/internal/batches/executor/executor_test.go index f632abfdeb..7556553093 100644 --- a/internal/batches/executor/executor_test.go +++ b/internal/batches/executor/executor_test.go @@ -16,6 +16,8 @@ import ( "github.com/google/go-cmp/cmp" "github.com/sourcegraph/go-diff/diff" + "github.com/stretchr/testify/require" + "github.com/sourcegraph/sourcegraph/lib/errors" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" @@ -47,6 +49,12 @@ func TestExecutor_Integration(t *testing.T) { type filesByPath map[string][]string type filesByRepository map[string]filesByPath + // create a temp directory with a simple shell file + tempDir := t.TempDir() + mountScript := fmt.Sprintf("%s/sample.sh", tempDir) + err := os.WriteFile(mountScript, []byte(`echo -e "foobar\n" >> README.md`), 0777) + require.NoError(t, err) + tests := []struct { name string @@ -310,6 +318,30 @@ func TestExecutor_Integration(t *testing.T) { wantFinishedWithErr: 1, wantCacheCount: 2, }, + { + name: "mount path", + archives: []mock.RepoArchive{ + {RepoName: testRepo1.Name, Commit: testRepo1.Rev(), Files: map[string]string{ + "README.md": "# Welcome to the README\n", + }}, + }, + steps: []batcheslib.Step{ + { + Run: mountScript, + Mount: []batcheslib.Mount{{Path: mountScript, Mountpoint: mountScript}}, + }, + }, + tasks: []*Task{ + {Repository: testRepo1}, + }, + wantFilesChanged: filesByRepository{ + testRepo1.ID: filesByPath{ + rootPath: []string{"README.md"}, + }, + }, + wantFinished: 1, + wantCacheCount: 1, + }, } for _, tc := range tests { diff --git a/internal/batches/executor/run_steps.go b/internal/batches/executor/run_steps.go index 8f7a65f4ac..fe349baca6 100644 --- a/internal/batches/executor/run_steps.go +++ b/internal/batches/executor/run_steps.go @@ -38,6 +38,8 @@ type executionOpts struct { ui StepsExecutionUI + allowPathMounts bool + writeStepCacheResult func(ctx context.Context, stepResult execution.AfterStepResult, task *Task) error } @@ -51,11 +53,11 @@ func runSteps(ctx context.Context, opts *executionOpts) (result execution.Result defer opts.task.Archive.Close() opts.ui.WorkspaceInitializationStarted() - workspace, err := opts.wc.Create(ctx, opts.task.Repository, opts.task.Steps, opts.task.Archive) + ws, err := opts.wc.Create(ctx, opts.task.Repository, opts.task.Steps, opts.task.Archive) if err != nil { return execution.Result{}, nil, errors.Wrap(err, "creating workspace") } - defer workspace.Close(ctx) + defer ws.Close(ctx) opts.ui.WorkspaceInitializationFinished() var ( @@ -119,7 +121,7 @@ func runSteps(ctx context.Context, opts *executionOpts) (result execution.Result stepContext.Steps.Changes = previousStepResult.Files stepContext.Outputs = opts.task.CachedResult.Outputs - if err := workspace.ApplyDiff(ctx, []byte(opts.task.CachedResult.Diff)); err != nil { + if err := ws.ApplyDiff(ctx, []byte(opts.task.CachedResult.Diff)); err != nil { return execResult, nil, errors.Wrap(err, "getting changed files in step") } } @@ -142,7 +144,7 @@ func runSteps(ctx context.Context, opts *executionOpts) (result execution.Result if err != nil { return execResult, nil, err } - stdoutBuffer, stderrBuffer, err := executeSingleStep(ctx, opts, workspace, i, step, digest, &stepContext) + stdoutBuffer, stderrBuffer, err := executeSingleStep(ctx, opts, ws, i, step, digest, &stepContext) defer func() { if err != nil { exitCode := -1 @@ -157,7 +159,7 @@ func runSteps(ctx context.Context, opts *executionOpts) (result execution.Result return execResult, nil, err } - changes, err := workspace.Changes(ctx) + changes, err := ws.Changes(ctx) if err != nil { return execResult, nil, errors.Wrap(err, "getting changed files in step") } @@ -172,7 +174,7 @@ func runSteps(ctx context.Context, opts *executionOpts) (result execution.Result } // Get the current diff and store that away as the per-step result. - stepDiff, err := workspace.Diff(ctx) + stepDiff, err := ws.Diff(ctx) if err != nil { return execResult, nil, errors.Wrap(err, "getting diff produced by step") } @@ -198,7 +200,7 @@ func runSteps(ctx context.Context, opts *executionOpts) (result execution.Result } opts.ui.CalculatingDiffStarted() - diffOut, err := workspace.Diff(ctx) + diffOut, err := ws.Diff(ctx) if err != nil { return execResult, nil, errors.Wrap(err, "git diff failed") } @@ -303,6 +305,14 @@ func executeSingleStep( args = append(args, "--mount", fmt.Sprintf("type=bind,source=%s,target=%s,ro", source.Name(), target)) } + // Temporarily add a guard to prevent a path to mount path for server-side processing + if opts.allowPathMounts { + // Mount any paths on the local system to the docker container. The paths have already been validated during parsing + for _, mount := range step.Mount { + args = append(args, "--mount", fmt.Sprintf("type=bind,source=%s,target=%s,ro", mount.Path, mount.Mountpoint)) + } + } + for k, v := range env { args = append(args, "-e", k+"="+v) } diff --git a/internal/batches/service/remote.go b/internal/batches/service/remote.go index 6d4298eb66..2bead9d6bc 100644 --- a/internal/batches/service/remote.go +++ b/internal/batches/service/remote.go @@ -16,7 +16,7 @@ func (svc *Service) areServerSideBatchChangesSupported() error { } const upsertBatchSpecInputQuery = ` -mutation CreateBatchSpecFromRaw( +mutation UpsertBatchSpecInput( $batchSpec: String!, $namespace: ID!, $allowIgnored: Boolean!, diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index e68fa5941a..36d88e9cb3 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -7,6 +7,7 @@ import ( "os" "os/exec" "path" + "path/filepath" "strings" "sync" "text/template" @@ -371,7 +372,7 @@ func (e *duplicateBranchesErr) Error() string { return out.String() } -func (svc *Service) ParseBatchSpec(data []byte) (*batcheslib.BatchSpec, error) { +func (svc *Service) ParseBatchSpec(dir string, data []byte, isRemote bool) (*batcheslib.BatchSpec, error) { spec, err := batcheslib.ParseBatchSpec(data, batcheslib.ParseBatchSpecOptions{ AllowArrayEnvironments: svc.features.AllowArrayEnvironments, AllowTransformChanges: svc.features.AllowTransformChanges, @@ -380,9 +381,45 @@ func (svc *Service) ParseBatchSpec(data []byte) (*batcheslib.BatchSpec, error) { if err != nil { return nil, errors.Wrap(err, "parsing batch spec") } + if err = validateMount(dir, spec, isRemote); err != nil { + return nil, errors.Wrap(err, "handling mount") + } return spec, nil } +func validateMount(batchSpecDir string, spec *batcheslib.BatchSpec, isRemote bool) error { + for i, step := range spec.Steps { + for j, mount := range step.Mount { + if isRemote { + return errors.New("mounts are not support for server-side processing") + } + p := mount.Path + if !filepath.IsAbs(p) { + // Try to build the absolute path since Docker will only mount absolute paths + p = filepath.Join(batchSpecDir, p) + } + pathInfo, err := os.Stat(p) + if os.IsNotExist(err) { + return errors.Newf("step %d mount path %s does not exist", i+1, p) + } else if err != nil { + return errors.Wrapf(err, "step %d mount path validation", i+1) + } + if !strings.HasPrefix(p, batchSpecDir) { + return errors.Newf("step %d mount path is not in the same directory or subdirectory as the batch spec", i+1) + } + // Mounting a directory on Docker must end with the separator. So, append the file separator to make + // users' lives easier. + if pathInfo.IsDir() && !strings.HasSuffix(p, string(filepath.Separator)) { + p += string(filepath.Separator) + } + // Update the mount path to the absolute path so building the absolute path (above) does not need to be + // redone when adding the mount argument to the Docker container. + step.Mount[j].Path = p + } + } + return nil +} + const exampleSpecTmpl = `name: NAME-OF-YOUR-BATCH-CHANGE description: DESCRIPTION-OF-YOUR-BATCH-CHANGE diff --git a/internal/batches/service/service_test.go b/internal/batches/service/service_test.go index d6be4e14b7..5b74f11b4d 100644 --- a/internal/batches/service/service_test.go +++ b/internal/batches/service/service_test.go @@ -6,14 +6,18 @@ import ( "fmt" "net/http" "net/http/httptest" + "os" + "path/filepath" "strconv" "strings" "testing" "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" - "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/sourcegraph/sourcegraph/lib/errors" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" @@ -698,3 +702,343 @@ func TestEnsureDockerImages(t *testing.T) { }) } + +func TestService_ParseBatchSpec(t *testing.T) { + svc := &Service{} + + tempDir := t.TempDir() + tempOutsideDir := t.TempDir() + // create temp files/dirs that can be used by the tests + _, err := os.Create(filepath.Join(tempDir, "sample.sh")) + require.NoError(t, err) + _, err = os.Create(filepath.Join(tempDir, "another.sh")) + require.NoError(t, err) + + tests := []struct { + name string + batchSpecDir string + rawSpec string + isRemote bool + expectedSpec *batcheslib.BatchSpec + expectedErr error + }{ + { + name: "simple spec", + rawSpec: ` +name: test-spec +description: A test spec +`, + expectedSpec: &batcheslib.BatchSpec{Name: "test-spec", Description: "A test spec"}, + }, + { + name: "unknown field", + rawSpec: ` +name: test-spec +description: A test spec +some-new-field: Foo bar +`, + expectedErr: errors.New("parsing batch spec: Additional property some-new-field is not allowed"), + }, + { + name: "mount absolute file", + batchSpecDir: tempDir, + rawSpec: fmt.Sprintf(` +name: test-spec +description: A test spec +steps: + - run: /tmp/sample.sh + container: alpine:3 + mount: + - path: %s + mountpoint: /tmp/sample.sh +changesetTemplate: + title: Test Mount + body: Test a mounted path + branch: test + commit: + message: Test +`, filepath.Join(tempDir, "sample.sh")), + expectedSpec: &batcheslib.BatchSpec{ + Name: "test-spec", + Description: "A test spec", + Steps: []batcheslib.Step{ + { + Run: "/tmp/sample.sh", + Container: "alpine:3", + Mount: []batcheslib.Mount{ + { + Path: filepath.Join(tempDir, "sample.sh"), + Mountpoint: "/tmp/sample.sh", + }, + }, + }, + }, + ChangesetTemplate: &batcheslib.ChangesetTemplate{ + Title: "Test Mount", + Body: "Test a mounted path", + Branch: "test", + Commit: batcheslib.ExpandedGitCommitDescription{ + Message: "Test", + }, + }, + }, + }, + { + name: "mount relative file", + batchSpecDir: tempDir, + rawSpec: ` +name: test-spec +description: A test spec +steps: + - run: /tmp/sample.sh + container: alpine:3 + mount: + - path: ./sample.sh + mountpoint: /tmp/sample.sh +changesetTemplate: + title: Test Mount + body: Test a mounted path + branch: test + commit: + message: Test +`, + expectedSpec: &batcheslib.BatchSpec{ + Name: "test-spec", + Description: "A test spec", + Steps: []batcheslib.Step{ + { + Run: "/tmp/sample.sh", + Container: "alpine:3", + Mount: []batcheslib.Mount{ + { + Path: filepath.Join(tempDir, "sample.sh"), + Mountpoint: "/tmp/sample.sh", + }, + }, + }, + }, + ChangesetTemplate: &batcheslib.ChangesetTemplate{ + Title: "Test Mount", + Body: "Test a mounted path", + Branch: "test", + Commit: batcheslib.ExpandedGitCommitDescription{ + Message: "Test", + }, + }, + }, + }, + { + name: "mount absolute directory", + batchSpecDir: tempDir, + rawSpec: fmt.Sprintf(` +name: test-spec +description: A test spec +steps: + - run: /tmp/some-file.sh + container: alpine:3 + mount: + - path: %s + mountpoint: /tmp +changesetTemplate: + title: Test Mount + body: Test a mounted path + branch: test + commit: + message: Test +`, tempDir), + expectedSpec: &batcheslib.BatchSpec{ + Name: "test-spec", + Description: "A test spec", + Steps: []batcheslib.Step{ + { + Run: "/tmp/some-file.sh", + Container: "alpine:3", + Mount: []batcheslib.Mount{ + { + Path: tempDir + string(filepath.Separator), + Mountpoint: "/tmp", + }, + }, + }, + }, + ChangesetTemplate: &batcheslib.ChangesetTemplate{ + Title: "Test Mount", + Body: "Test a mounted path", + Branch: "test", + Commit: batcheslib.ExpandedGitCommitDescription{ + Message: "Test", + }, + }, + }, + }, + { + name: "mount relative directory", + batchSpecDir: tempDir, + rawSpec: ` +name: test-spec +description: A test spec +steps: + - run: /tmp/some-file.sh + container: alpine:3 + mount: + - path: ./ + mountpoint: /tmp +changesetTemplate: + title: Test Mount + body: Test a mounted path + branch: test + commit: + message: Test +`, + expectedSpec: &batcheslib.BatchSpec{ + Name: "test-spec", + Description: "A test spec", + Steps: []batcheslib.Step{ + { + Run: "/tmp/some-file.sh", + Container: "alpine:3", + Mount: []batcheslib.Mount{ + { + Path: tempDir + string(filepath.Separator), + Mountpoint: "/tmp", + }, + }, + }, + }, + ChangesetTemplate: &batcheslib.ChangesetTemplate{ + Title: "Test Mount", + Body: "Test a mounted path", + Branch: "test", + Commit: batcheslib.ExpandedGitCommitDescription{ + Message: "Test", + }, + }, + }, + }, + { + name: "mount multiple files", + batchSpecDir: tempDir, + rawSpec: ` +name: test-spec +description: A test spec +steps: + - run: /tmp/sample.sh && /tmp/another.sh + container: alpine:3 + mount: + - path: ./sample.sh + mountpoint: /tmp/sample.sh + - path: ./another.sh + mountpoint: /tmp/another.sh +changesetTemplate: + title: Test Mount + body: Test a mounted path + branch: test + commit: + message: Test +`, + expectedSpec: &batcheslib.BatchSpec{ + Name: "test-spec", + Description: "A test spec", + Steps: []batcheslib.Step{ + { + Run: "/tmp/sample.sh && /tmp/another.sh", + Container: "alpine:3", + Mount: []batcheslib.Mount{ + { + Path: filepath.Join(tempDir, "sample.sh"), + Mountpoint: "/tmp/sample.sh", + }, + { + Path: filepath.Join(tempDir, "another.sh"), + Mountpoint: "/tmp/another.sh", + }, + }, + }, + }, + ChangesetTemplate: &batcheslib.ChangesetTemplate{ + Title: "Test Mount", + Body: "Test a mounted path", + Branch: "test", + Commit: batcheslib.ExpandedGitCommitDescription{ + Message: "Test", + }, + }, + }, + }, + { + name: "mount path does not exist", + batchSpecDir: tempDir, + rawSpec: fmt.Sprintf(` +name: test-spec +description: A test spec +steps: + - run: /tmp/sample.sh + container: alpine:3 + mount: + - path: %s + mountpoint: /tmp +changesetTemplate: + title: Test Mount + body: Test a mounted path + branch: test + commit: + message: Test +`, filepath.Join(tempDir, "does", "not", "exist", "sample.sh")), + expectedErr: errors.Newf("handling mount: step 1 mount path %s does not exist", filepath.Join(tempDir, "does", "not", "exist", "sample.sh")), + }, + { + name: "mount path not subdirectory of spec", + batchSpecDir: tempDir, + rawSpec: fmt.Sprintf(` +name: test-spec +description: A test spec +steps: + - run: /tmp/sample.sh + container: alpine:3 + mount: + - path: %s + mountpoint: /tmp +changesetTemplate: + title: Test Mount + body: Test a mounted path + branch: test + commit: + message: Test +`, tempOutsideDir), + expectedErr: errors.New("handling mount: step 1 mount path is not in the same directory or subdirectory as the batch spec"), + }, + { + name: "mount remote processing", + batchSpecDir: tempDir, + rawSpec: ` +name: test-spec +description: A test spec +steps: + - run: /tmp/foo/bar/sample.sh + container: alpine:3 + mount: + - path: /valid/sample.sh + mountpoint: /tmp/foo/bar/sample.sh +changesetTemplate: + title: Test Mount + body: Test a mounted path + branch: test + commit: + message: Test +`, + isRemote: true, + expectedErr: errors.New("handling mount: mounts are not support for server-side processing"), + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + spec, err := svc.ParseBatchSpec(test.batchSpecDir, []byte(test.rawSpec), test.isRemote) + if test.expectedErr != nil { + assert.Equal(t, test.expectedErr.Error(), err.Error()) + } else { + assert.NoError(t, err) + assert.Equal(t, test.expectedSpec, spec) + } + }) + } +} From 181e3dea8ad2a4e46ac0c9e2270471a674e60a97 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Wed, 15 Jun 2022 01:10:27 +0200 Subject: [PATCH 187/647] Only apply cache result progress if resulted in diff (#778) This was reported by a user, we store execution step results in the cache also when no diff was generated (rightfully), but then we should only apply the patch when there is actually anything to do. Also, I initially couldn't reproduce this locally because we swallowed this error in volume mode. It would only happen in bind mode. --- internal/batches/executor/run_steps.go | 8 ++++++-- internal/batches/workspace/bind_workspace.go | 4 ++-- internal/batches/workspace/git.go | 2 +- internal/batches/workspace/volume_workspace.go | 10 ++++++++-- 4 files changed, 17 insertions(+), 7 deletions(-) diff --git a/internal/batches/executor/run_steps.go b/internal/batches/executor/run_steps.go index fe349baca6..9576fdac20 100644 --- a/internal/batches/executor/run_steps.go +++ b/internal/batches/executor/run_steps.go @@ -121,8 +121,12 @@ func runSteps(ctx context.Context, opts *executionOpts) (result execution.Result stepContext.Steps.Changes = previousStepResult.Files stepContext.Outputs = opts.task.CachedResult.Outputs - if err := ws.ApplyDiff(ctx, []byte(opts.task.CachedResult.Diff)); err != nil { - return execResult, nil, errors.Wrap(err, "getting changed files in step") + // If the previous steps made any modifications in the workspace yet, + // apply them. + if opts.task.CachedResult.Diff != "" { + if err := ws.ApplyDiff(ctx, []byte(opts.task.CachedResult.Diff)); err != nil { + return execResult, nil, errors.Wrap(err, "getting changed files in step") + } } } diff --git a/internal/batches/workspace/bind_workspace.go b/internal/batches/workspace/bind_workspace.go index 9792bdd8e9..80438071ef 100644 --- a/internal/batches/workspace/bind_workspace.go +++ b/internal/batches/workspace/bind_workspace.go @@ -172,8 +172,8 @@ func (w *dockerBindWorkspace) ApplyDiff(ctx context.Context, diff []byte) error } // Apply diff - if _, err = runGitCmd(ctx, w.dir, "apply", "-p0", tmp.Name()); err != nil { - return errors.Wrap(err, "applying cached diff") + if out, err := runGitCmd(ctx, w.dir, "apply", "-p0", tmp.Name()); err != nil { + return errors.Wrapf(err, "applying cached diff: %s", string(out)) } // Add all files to index diff --git a/internal/batches/workspace/git.go b/internal/batches/workspace/git.go index fa81c1fff4..7b4a2536c2 100644 --- a/internal/batches/workspace/git.go +++ b/internal/batches/workspace/git.go @@ -27,7 +27,7 @@ func runGitCmd(ctx context.Context, dir string, args ...string) ([]byte, error) cmd.Dir = dir out, err := cmd.CombinedOutput() if err != nil { - return nil, errors.Wrapf(err, "'git %s' failed: %s", strings.Join(args, " "), out) + return out, errors.Wrapf(err, "'git %s' failed: %s", strings.Join(args, " "), out) } return out, nil } diff --git a/internal/batches/workspace/volume_workspace.go b/internal/batches/workspace/volume_workspace.go index 5a05b21cf2..1f0a399074 100644 --- a/internal/batches/workspace/volume_workspace.go +++ b/internal/batches/workspace/volume_workspace.go @@ -279,6 +279,8 @@ exec git diff --cached --no-prefix --binary func (w *dockerVolumeWorkspace) ApplyDiff(ctx context.Context, diff []byte) error { script := fmt.Sprintf(`#!/bin/sh +set -e + cat <<'EOF' | exec git apply -p0 - %s EOF @@ -322,11 +324,15 @@ func (w *dockerVolumeWorkspace) runScript(ctx context.Context, target, script st if _, err := f.WriteString(script); err != nil { return nil, errors.Wrap(err, "writing run script") } - f.Close() + if err := f.Close(); err != nil { + return nil, errors.Wrap(err, "closing run script") + } // Sidestep any umask issues on the temporary file by always making it // executable by everyone. - os.Chmod(name, 0755) + if err := os.Chmod(name, 0755); err != nil { + return nil, errors.Wrap(err, "chmodding run script") + } common, err := w.DockerRunOpts(ctx, target) if err != nil { From 98f49b9d1547b1f8e9c0be6c5720d4c224ecffc8 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Wed, 15 Jun 2022 01:42:08 +0200 Subject: [PATCH 188/647] Fix step caching (#781) This fixes two things, that I found today: It changes Stdout and Stderr on the StepResult struct to string, it is part of the marshalled cache result and *bytes.Buffer cannot be marshalled into JSON. This caused stdout/stderr to always be empty, thus breaking executions where ${{ previous_step.stdout }} is used. It fixes a misconception of the PreviousStepResult. When running the actual execution, it will eventually become the result of the previous step, but from the perspective of that particular cache result, it has to be the result from THAT step execution. Otherwise caching would only work from step 2 on and skip 1 step still. --- go.mod | 6 +- go.sum | 12 +-- internal/batches/executor/executor_test.go | 87 ++++++++++++++++++++-- internal/batches/executor/run_steps.go | 14 ++-- 4 files changed, 96 insertions(+), 23 deletions(-) diff --git a/go.mod b/go.mod index 83a95fc340..c623db57c4 100644 --- a/go.mod +++ b/go.mod @@ -20,7 +20,7 @@ require ( github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf github.com/sourcegraph/scip v0.1.0 - github.com/sourcegraph/sourcegraph/lib v0.0.0-20220613202038-1231f0d77142 + github.com/sourcegraph/sourcegraph/lib v0.0.0-20220614231716-f73c9fa26c46 github.com/stretchr/testify v1.7.2 golang.org/x/net v0.0.0-20220526153639-5463443f8c37 golang.org/x/sync v0.0.0-20210220032951-036812b2e83c @@ -83,7 +83,7 @@ require ( github.com/rivo/uniseg v0.2.0 // indirect github.com/rogpeppe/go-internal v1.8.1 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect - github.com/sourcegraph/log v0.0.0-20220608183241-51d325291e9a // indirect + github.com/sourcegraph/log v0.0.0-20220613150728-bb50c87ba841 // indirect github.com/spf13/cobra v1.4.0 // indirect github.com/spf13/pflag v1.0.5 // indirect github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect @@ -98,7 +98,7 @@ require ( go.uber.org/zap v1.21.0 // indirect golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 // indirect golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 // indirect - golang.org/x/sys v0.0.0-20220610221304-9f5ed59c137d // indirect + golang.org/x/sys v0.0.0-20220614162138-6c1b26c55098 // indirect golang.org/x/term v0.0.0-20220411215600-e5f449aeb171 // indirect golang.org/x/text v0.3.7 // indirect golang.org/x/tools v0.1.11 // indirect diff --git a/go.sum b/go.sum index a932accf06..86417f47ff 100644 --- a/go.sum +++ b/go.sum @@ -347,12 +347,12 @@ github.com/sourcegraph/go-diff v0.6.1 h1:hmA1LzxW0n1c3Q4YbrFgg4P99GSnebYa3x8gr0H github.com/sourcegraph/go-diff v0.6.1/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= -github.com/sourcegraph/log v0.0.0-20220608183241-51d325291e9a h1:poxCcQH13nS9l4tkXN7+qRwmyxdO1lYeOUEY9ycwH84= -github.com/sourcegraph/log v0.0.0-20220608183241-51d325291e9a/go.mod h1:A+9F6IicYvBbl2aT0R81lMraKcXjVfdfw352yPe2yJI= +github.com/sourcegraph/log v0.0.0-20220613150728-bb50c87ba841 h1:kiYxuyQ1zSNA4YPtVVJQAFw5ZRNaFRkFqgKyEJQTzhg= +github.com/sourcegraph/log v0.0.0-20220613150728-bb50c87ba841/go.mod h1:A+9F6IicYvBbl2aT0R81lMraKcXjVfdfw352yPe2yJI= github.com/sourcegraph/scip v0.1.0 h1:kTs0CJaLQvcRZjg+HpGrcJPNX2Tx31+d6szWio3ZOkQ= github.com/sourcegraph/scip v0.1.0/go.mod h1:/AZ8RvsnRfeCZy232PJuVZqcl9f82fJnYwdWZeU2JCo= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20220613202038-1231f0d77142 h1:wnp9JgzLmppL9SAUkkjFp8V2Q8Q/oLVJoqXRxHWx2zU= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20220613202038-1231f0d77142/go.mod h1:RaBtTwfNRQvoRTEcbrKLesaEbWex/KblcPDd979zzww= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20220614231716-f73c9fa26c46 h1:ehDPNEMxvaCKWlV6oGh2jvkcs4bJzL020aSHjxNLSZs= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20220614231716-f73c9fa26c46/go.mod h1:Orrt+5wdseAvxsVxgdswYPzJgVkTk0rLlmFHZW61epo= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= @@ -503,8 +503,8 @@ golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211007075335-d3039528d8ac/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220610221304-9f5ed59c137d h1:Zu/JngovGLVi6t2J3nmAf3AoTDwuzw85YZ3b9o4yU7s= -golang.org/x/sys v0.0.0-20220610221304-9f5ed59c137d/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220614162138-6c1b26c55098 h1:PgOr27OhUx2IRqGJ2RxAWI4dJQ7bi9cSrB82uzFzfUA= +golang.org/x/sys v0.0.0-20220614162138-6c1b26c55098/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20220411215600-e5f449aeb171 h1:EH1Deb8WZJ0xc0WK//leUHXcX9aLE5SymusoTmMZye8= golang.org/x/term v0.0.0-20220411215600-e5f449aeb171/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= diff --git a/internal/batches/executor/executor_test.go b/internal/batches/executor/executor_test.go index 7556553093..924099c131 100644 --- a/internal/batches/executor/executor_test.go +++ b/internal/batches/executor/executor_test.go @@ -545,10 +545,10 @@ index 02a19af..c9644dd 100644 }, CachedResultFound: true, CachedResult: execution.AfterStepResult{ - StepIndex: 0, - Diff: cachedDiff, - Outputs: map[string]interface{}{}, - PreviousStepResult: execution.StepResult{}, + StepIndex: 0, + Diff: cachedDiff, + Outputs: map[string]interface{}{}, + StepResult: execution.StepResult{}, }, Repository: testRepo1, } @@ -666,13 +666,13 @@ echo "previous_step.modified_files=${{ previous_step.modified_files }}" >> READM Outputs: map[string]interface{}{ "myOutput": "my-output.txt", }, - PreviousStepResult: execution.StepResult{ + StepResult: execution.StepResult{ Files: &git.Changes{ Modified: []string{"README.md"}, Added: []string{"README.txt"}, }, - Stdout: nil, - Stderr: nil, + Stdout: "", + Stderr: "", }, }, } @@ -709,6 +709,79 @@ echo "previous_step.modified_files=${{ previous_step.modified_files }}" >> READM t.Fatalf("wrong step result outputs: %s", diff) } }) + + t.Run("step stdout cached", func(t *testing.T) { + archive := mock.RepoArchive{ + RepoName: testRepo1.Name, Commit: testRepo1.Rev(), + Files: map[string]string{ + "README.md": `# automation-testing +This repository is used to test opening and closing pull request with Automation +`, + }, + } + + wantFinalDiff := `diff --git README.md README.md +index 3040106..5f2f924 100644 +--- README.md ++++ README.md +@@ -1,2 +1,3 @@ + # automation-testing + This repository is used to test opening and closing pull request with Automation ++hello world +` + + task := &Task{ + Repository: testRepo1, + BatchChangeAttributes: &template.BatchChangeAttributes{}, + Steps: []batcheslib.Step{ + {Run: "echo -n Hello world"}, + {Run: `echo ${{ previous_step.stdout }} >> README.md`}, + }, + CachedResultFound: true, + CachedResult: execution.AfterStepResult{ + StepIndex: 0, + Diff: "", + Outputs: map[string]interface{}{}, + StepResult: execution.StepResult{ + Files: &git.Changes{}, + Stdout: "hello world", + Stderr: "", + }, + }, + } + + results, err := testExecuteTasks(t, []*Task{task}, archive) + if err != nil { + t.Fatalf("execution failed: %s", err) + } + + if have, want := len(results), 1; have != want { + t.Fatalf("wrong number of execution results. want=%d, have=%d", want, have) + } + + executionResult := results[0].result + if diff := cmp.Diff(executionResult.Diff, wantFinalDiff); diff != "" { + t.Fatalf("wrong diff: %s", diff) + } + + if diff := cmp.Diff(executionResult.Outputs, task.CachedResult.Outputs); diff != "" { + t.Fatalf("wrong execution result outputs: %s", diff) + } + + // Only one step should've been executed + if have, want := len(results[0].stepResults), 1; have != want { + t.Fatalf("wrong length of step results. have=%d, want=%d", have, want) + } + + lastStepResult := results[0].stepResults[0] + if have, want := lastStepResult.StepIndex, 1; have != want { + t.Fatalf("wrong stepIndex. have=%d, want=%d", have, want) + } + + if diff := cmp.Diff(lastStepResult.Outputs, task.CachedResult.Outputs); diff != "" { + t.Fatalf("wrong step result outputs: %s", diff) + } + }) } func testExecuteTasks(t *testing.T, tasks []*Task, archives ...mock.RepoArchive) ([]taskResult, error) { diff --git a/internal/batches/executor/run_steps.go b/internal/batches/executor/run_steps.go index 9576fdac20..b1dcbd1de7 100644 --- a/internal/batches/executor/run_steps.go +++ b/internal/batches/executor/run_steps.go @@ -115,7 +115,7 @@ func runSteps(ctx context.Context, opts *executionOpts) (result execution.Result } if opts.task.CachedResultFound && i == startStep { - previousStepResult = opts.task.CachedResult.PreviousStepResult + previousStepResult = opts.task.CachedResult.StepResult stepContext.PreviousStep = previousStepResult stepContext.Steps.Changes = previousStepResult.Files @@ -125,7 +125,7 @@ func runSteps(ctx context.Context, opts *executionOpts) (result execution.Result // apply them. if opts.task.CachedResult.Diff != "" { if err := ws.ApplyDiff(ctx, []byte(opts.task.CachedResult.Diff)); err != nil { - return execResult, nil, errors.Wrap(err, "getting changed files in step") + return execResult, nil, errors.Wrap(err, "applying diff of cache result") } } } @@ -168,7 +168,7 @@ func runSteps(ctx context.Context, opts *executionOpts) (result execution.Result return execResult, nil, errors.Wrap(err, "getting changed files in step") } - result := execution.StepResult{Files: changes, Stdout: &stdoutBuffer, Stderr: &stderrBuffer} + result := execution.StepResult{Files: changes, Stdout: stdoutBuffer.String(), Stderr: stderrBuffer.String()} // Set stepContext.Step to current step's results before rendering outputs stepContext.Step = result @@ -183,10 +183,10 @@ func runSteps(ctx context.Context, opts *executionOpts) (result execution.Result return execResult, nil, errors.Wrap(err, "getting diff produced by step") } stepResult := execution.AfterStepResult{ - StepIndex: i, - Diff: string(stepDiff), - Outputs: make(map[string]interface{}), - PreviousStepResult: stepContext.PreviousStep, + StepIndex: i, + Diff: string(stepDiff), + Outputs: make(map[string]interface{}), + StepResult: result, } for k, v := range execResult.Outputs { stepResult.Outputs[k] = v From 20635ab15d640f69dffdec7b2a11112ffd8758c8 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Wed, 15 Jun 2022 01:48:18 +0200 Subject: [PATCH 189/647] Don't write execution results to SSBC cache and remove unnecessary additional call to workspace.Diff (#777) This is the src-cli portion of sourcegraph/sourcegraph#36758. It also optimizes the execution generally, because we run one less workspace.Diff. After this PR, nothing requires us to still write or read execution results from the cache. Since this is a bigger code cleanup/refactor, I filed a separate ticket to address this and put it in sustaining. This PR mostly focuses on getting the Diff call out of the execution and stops to write the unnecessary cache result to the JSON logs so we send less log data. --- go.mod | 2 +- go.sum | 4 ++-- internal/batches/executor/run_steps.go | 13 +++++-------- internal/batches/executor/ui.go | 5 ----- internal/batches/ui/json_lines.go | 12 +----------- internal/batches/ui/task_exec_tui.go | 6 ------ 6 files changed, 9 insertions(+), 33 deletions(-) diff --git a/go.mod b/go.mod index c623db57c4..23d89a1857 100644 --- a/go.mod +++ b/go.mod @@ -20,7 +20,7 @@ require ( github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf github.com/sourcegraph/scip v0.1.0 - github.com/sourcegraph/sourcegraph/lib v0.0.0-20220614231716-f73c9fa26c46 + github.com/sourcegraph/sourcegraph/lib v0.0.0-20220614233452-81dc06f6e96e github.com/stretchr/testify v1.7.2 golang.org/x/net v0.0.0-20220526153639-5463443f8c37 golang.org/x/sync v0.0.0-20210220032951-036812b2e83c diff --git a/go.sum b/go.sum index 86417f47ff..88cee68e52 100644 --- a/go.sum +++ b/go.sum @@ -351,8 +351,8 @@ github.com/sourcegraph/log v0.0.0-20220613150728-bb50c87ba841 h1:kiYxuyQ1zSNA4YP github.com/sourcegraph/log v0.0.0-20220613150728-bb50c87ba841/go.mod h1:A+9F6IicYvBbl2aT0R81lMraKcXjVfdfw352yPe2yJI= github.com/sourcegraph/scip v0.1.0 h1:kTs0CJaLQvcRZjg+HpGrcJPNX2Tx31+d6szWio3ZOkQ= github.com/sourcegraph/scip v0.1.0/go.mod h1:/AZ8RvsnRfeCZy232PJuVZqcl9f82fJnYwdWZeU2JCo= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20220614231716-f73c9fa26c46 h1:ehDPNEMxvaCKWlV6oGh2jvkcs4bJzL020aSHjxNLSZs= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20220614231716-f73c9fa26c46/go.mod h1:Orrt+5wdseAvxsVxgdswYPzJgVkTk0rLlmFHZW61epo= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20220614233452-81dc06f6e96e h1:O+XG50CIAdzjuELX2gHhkc9Br1AaAXaOkZWg1YSRFpQ= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20220614233452-81dc06f6e96e/go.mod h1:Orrt+5wdseAvxsVxgdswYPzJgVkTk0rLlmFHZW61epo= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= diff --git a/internal/batches/executor/run_steps.go b/internal/batches/executor/run_steps.go index b1dcbd1de7..32f3adb10d 100644 --- a/internal/batches/executor/run_steps.go +++ b/internal/batches/executor/run_steps.go @@ -80,6 +80,7 @@ func runSteps(ctx context.Context, opts *executionOpts) (result execution.Result // If we have cached results and don't need to execute any more steps, // we can quit if lastStep == len(opts.task.Steps)-1 { + // Build the execution result from the step result. changes, err := git.ChangesInDiff([]byte(opts.task.CachedResult.Diff)) if err != nil { return execResult, nil, errors.Wrap(err, "parsing cached step diff") @@ -100,6 +101,8 @@ func runSteps(ctx context.Context, opts *executionOpts) (result execution.Result ) } + var lastDiff string + for i := startStep; i < len(opts.task.Steps); i++ { step := opts.task.Steps[i] @@ -201,17 +204,11 @@ func runSteps(ctx context.Context, opts *executionOpts) (result execution.Result } opts.ui.StepFinished(i+1, stepResult.Diff, result.Files, stepResult.Outputs) - } - opts.ui.CalculatingDiffStarted() - diffOut, err := ws.Diff(ctx) - if err != nil { - return execResult, nil, errors.Wrap(err, "git diff failed") + lastDiff = stepResult.Diff } - opts.ui.CalculatingDiffFinished() - - execResult.Diff = string(diffOut) + execResult.Diff = lastDiff execResult.ChangedFiles = previousStepResult.Files return execResult, stepResults, err diff --git a/internal/batches/executor/ui.go b/internal/batches/executor/ui.go index 12daf38241..4ddd360689 100644 --- a/internal/batches/executor/ui.go +++ b/internal/batches/executor/ui.go @@ -45,9 +45,6 @@ type StepsExecutionUI interface { StepOutputWriter(context.Context, *Task, int) StepOutputWriter - CalculatingDiffStarted() - CalculatingDiffFinished() - StepFinished(idx int, diff string, changes *git.Changes, outputs map[string]interface{}) StepFailed(idx int, err error, exitCode int) } @@ -68,8 +65,6 @@ 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) CalculatingDiffStarted() {} -func (noop NoopStepsExecUI) CalculatingDiffFinished() {} func (noop NoopStepsExecUI) StepFinished(idx int, diff string, changes *git.Changes, outputs map[string]interface{}) { } func (noop NoopStepsExecUI) StepFailed(idx int, err error, exitCode int) { diff --git a/internal/batches/ui/json_lines.go b/internal/batches/ui/json_lines.go index 56838c7c38..15acf323fc 100644 --- a/internal/batches/ui/json_lines.go +++ b/internal/batches/ui/json_lines.go @@ -175,10 +175,7 @@ func (ui *JSONLines) ExecutionError(err error) { var _ executor.JSONCacheWriter = &JSONLines{} func (ui *JSONLines) WriteExecutionResult(key string, value execution.Result) { - logOperationSuccess(batcheslib.LogEventOperationCacheResult, &batcheslib.CacheResultMetadata{ - Key: key, - Value: value, - }) + // Noop, we don't need execution results. } func (ui *JSONLines) WriteAfterStepResult(key string, value execution.AfterStepResult) { @@ -363,13 +360,6 @@ func (ui *stepsExecutionJSONLines) StepFailed(step int, err error, exitCode int) ) } -func (ui *stepsExecutionJSONLines) CalculatingDiffStarted() { - logOperationStart(batcheslib.LogEventOperationTaskCalculatingDiff, &batcheslib.TaskCalculatingDiffMetadata{TaskID: ui.linesTask.ID}) -} -func (ui *stepsExecutionJSONLines) CalculatingDiffFinished() { - logOperationSuccess(batcheslib.LogEventOperationTaskCalculatingDiff, &batcheslib.TaskCalculatingDiffMetadata{TaskID: ui.linesTask.ID}) -} - func logOperationStart(op batcheslib.LogEventOperation, metadata interface{}) { logEvent(batcheslib.LogEvent{Operation: op, Status: batcheslib.LogEventStatusStarted, Metadata: metadata}) } diff --git a/internal/batches/ui/task_exec_tui.go b/internal/batches/ui/task_exec_tui.go index 9debfb9843..5f18dfe1a7 100644 --- a/internal/batches/ui/task_exec_tui.go +++ b/internal/batches/ui/task_exec_tui.go @@ -471,12 +471,6 @@ func (ui stepsExecTUI) StepOutputWriter(ctx context.Context, task *executor.Task return executor.NoopStepOutputWriter{} } -func (ui stepsExecTUI) CalculatingDiffStarted() { - ui.updateStatusBar("Calculating diff") -} -func (ui stepsExecTUI) CalculatingDiffFinished() { - // noop right now -} func (ui stepsExecTUI) StepFinished(idx int, diff string, changes *git.Changes, outputs map[string]interface{}) { // noop right now } From ce71dcb857a94c362fa7fa35c830be3c9ee32d9d Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Wed, 15 Jun 2022 01:57:39 +0200 Subject: [PATCH 190/647] Prepare changelog for 3.40.10 (#782) --- CHANGELOG.md | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 02a34cad47..6f61e2ed31 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,14 +13,23 @@ All notable changes to `src-cli` are documented in this file. ### Added -- Batch Specs now support mounting a path from the local machine into a Docker container. [sourcegraph/sourcegraph#31790](https://github.com/sourcegraph/sourcegraph/issues/31790) - ### Changed ### Fixed ### Removed +## 3.40.10 + +### Added + +- Batch Specs now support mounting a path from the local machine into a Docker container. [sourcegraph/sourcegraph#31790](https://github.com/sourcegraph/sourcegraph/issues/31790) + +### Fixed + +- When a step results in no change, it would fail with exit code 128 when used in caching. [#778](https://github.com/sourcegraph/src-cli/pull/778) +- A bug where `previous_step.stdout` would not be available for partially cached workspaces. [#781](https://github.com/sourcegraph/src-cli/pull/781) + ## 3.40.9 ### Added From 4723b4ba677e3b41f335102f1c6a1617b07f9f29 Mon Sep 17 00:00:00 2001 From: Adam Harvey Date: Wed, 15 Jun 2022 09:58:17 -0700 Subject: [PATCH 191/647] docker: use a short timeout when inspecting images (#783) Docker Desktop seems to be prone to occasionally entering states where it is nominally available (in the sense that it listens for connections), but can't actually do anything useful. Memory exhaustion events from previous `src batch` runs tend to be the culprit here. This seems to be most easily detectable by looking at the behaviour of `docker image inspect`. This command doesn't have to hit the network, nor does it perform any real work, so it should always be "quick". If it's not, that implies that Docker is not in a happy place. This commit adds a five second timeout to `docker image inspect` invocations, along with a secret environment variable to adjust this behaviour. If `docker` times out, then a (hopefully) helpful error message is generated to hint towards the things that the user should investigate next (basically, "is Docker really working?"). The only real concern I have with this is that I've basically picked five seconds out of thin air: practically, Docker for Mac seems to be able to do this in tens of milliseconds, but Sourcegraph has bought me a rather nice laptop. I have trouble imagining a scenario where multiple second delays are common where there aren't other serious issues, but the world is a large, weird place. --- internal/batches/docker/image.go | 94 +++++++++++++++++++++++++-- internal/batches/docker/image_test.go | 23 +++++++ 2 files changed, 110 insertions(+), 7 deletions(-) diff --git a/internal/batches/docker/image.go b/internal/batches/docker/image.go index bd3aed9ba1..ef06fb0add 100644 --- a/internal/batches/docker/image.go +++ b/internal/batches/docker/image.go @@ -4,8 +4,10 @@ import ( "bytes" "context" "fmt" + "os" "strings" "sync" + "time" "github.com/sourcegraph/sourcegraph/lib/errors" @@ -66,19 +68,50 @@ func (image *image) Ensure(ctx context.Context) error { image.ensureOnce.Do(func() { image.ensureErr = func() (err error) { inspectDigest := func() (string, error) { - // TODO!(sqs): is image id the right thing to use here? it is NOT - // the digest. but the digest is not calculated for all images - // (unless they are pulled/pushed from/to a registry), see - // https://github.com/moby/moby/issues/32016. - out, err := exec.CommandContext(ctx, "docker", "image", "inspect", "--format", "{{ .Id }}", image.name).CombinedOutput() + // Since we are only asking Docker for local information, we + // expect this operation to be quick, and therefore set a + // relatively low timeout for Docker to respond. This is + // particularly useful because this function is usually the + // first non-trivial interaction we have with Docker in a + // src-cli invocation, and this allows us to catch failure modes + // that result in the Docker socket still listening and + // accepting connections, but where dockerd is no longer able to + // respond to non-trivial requests. + // + // Anecdotally, this seems to happen most frequently with Docker + // Desktop VMs running out of memory, whereupon the Linux + // kernel's OOM killer sometimes chooses to kill components of + // Docker instead of processes within containers. + timeout, err := dockerImageInspectTimeout() + if err != nil { + return "", err + } + dctx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + + out, err := exec.CommandContext(dctx, "docker", "image", "inspect", "--format", "{{ .Id }}", image.name).CombinedOutput() id := string(bytes.TrimSpace(out)) - return id, err + + if errors.Is(errors.Cause(err), context.DeadlineExceeded) { + return "", &dockerImageInspectTimeoutError{ + image: image.name, + timeout: timeout, + } + } else if err != nil { + return "", err + } + + return id, nil } // docker image inspect will return a non-zero exit code if the image and // tag don't exist locally, regardless of the format. var digest string - if digest, err = inspectDigest(); err != nil { + if digest, err = inspectDigest(); errors.HasType(err, &dockerImageInspectTimeoutError{}) { + // Ensure we immediately propagate a timeout up, rather than + // trying to tell an unresponsive Docker to pull. + return err + } else if err != nil { // Let's try pulling the image. if err := exec.CommandContext(ctx, "docker", "image", "pull", image.name).Run(); err != nil { return errors.Wrap(err, "pulling image") @@ -143,3 +176,50 @@ func (image *image) UIDGID(ctx context.Context) (UIDGID, error) { return image.uidGid, image.uidGidErr } + +const ( + dockerImageInspectTimeoutDefault = 5 * time.Second + dockerImageInspectTimeoutEnv = "SRC_DOCKER_IMAGE_INSPECT_TIMEOUT" +) + +var dockerImageInspectTimeoutData = struct { + once sync.Once + timeout time.Duration + err error +}{ + timeout: dockerImageInspectTimeoutDefault, + err: nil, +} + +// dockerImageInspectTimeout returns a timeout appropriate for invoking `docker +// image inspect`. This defaults to 5 seconds, but can be overridden by the +// undocumented $SRC_DOCKER_IMAGE_INSPECT_TIMEOUT environment variable. +func dockerImageInspectTimeout() (time.Duration, error) { + dockerImageInspectTimeoutData.once.Do(func() { + if userTimeout, ok := os.LookupEnv(dockerImageInspectTimeoutEnv); ok { + parsed, err := time.ParseDuration(userTimeout) + if err != nil { + dockerImageInspectTimeoutData.err = errors.Wrapf(err, "parsing timeout duration from environment variable %s", dockerImageInspectTimeoutEnv) + } else { + dockerImageInspectTimeoutData.timeout = parsed + } + } + }) + + return dockerImageInspectTimeoutData.timeout, dockerImageInspectTimeoutData.err +} + +type dockerImageInspectTimeoutError struct { + image string + timeout time.Duration +} + +var _ error = &dockerImageInspectTimeoutError{} + +func (e *dockerImageInspectTimeoutError) Error() string { + return fmt.Sprintf( + "`docker image inspect --format '{{ .Id }}' %s` failed to respond within %s; "+ + "please verify that Docker has been started and is responding normally", + e.image, e.timeout, + ) +} diff --git a/internal/batches/docker/image_test.go b/internal/batches/docker/image_test.go index d8d5d91323..e7c8300271 100644 --- a/internal/batches/docker/image_test.go +++ b/internal/batches/docker/image_test.go @@ -3,8 +3,11 @@ package docker import ( "context" "testing" + "time" "github.com/google/go-cmp/cmp" + "github.com/stretchr/testify/assert" + "github.com/sourcegraph/src-cli/internal/exec/expect" ) @@ -76,6 +79,26 @@ func TestImage_Digest(t *testing.T) { } }) } + + t.Run("docker timeout", func(t *testing.T) { + // We're more interested in the context error handling than the parsing + // of the timeout, and we don't want to slow down the test, so we're + // going to construct a context that has already exceeded its deadline + // at the point it is provided to Digest. + ctx, cancel := context.WithTimeout(context.Background(), -1*time.Second) + t.Cleanup(cancel) + + expect.Commands(t, inspectSuccess("foo", "")) + image := &image{name: "foo"} + + digest, err := image.Digest(ctx) + assert.Empty(t, digest) + + as := &dockerImageInspectTimeoutError{} + assert.ErrorAs(t, err, &as) + assert.Equal(t, "foo", as.image) + assert.Equal(t, dockerImageInspectTimeoutDefault, as.timeout) + }) } func TestImage_Ensure(t *testing.T) { From 8503b3527ec083ee537e824efb7fc39454a921ed Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Wed, 15 Jun 2022 22:38:28 +0200 Subject: [PATCH 192/647] batches: Don't let stderr clutter git output (#785) We parse lots of the things that git outputs, so having stderr randonly interfere with the output breaks that parsing. Since we can still get stderr from the exiterror, I don't think this is a regression at all in debuggability. This was found on k8s where parsing the patch would fail on a particular repo. Turns out git logged a warning. --- internal/batches/workspace/git.go | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/internal/batches/workspace/git.go b/internal/batches/workspace/git.go index 7b4a2536c2..52da2e01fd 100644 --- a/internal/batches/workspace/git.go +++ b/internal/batches/workspace/git.go @@ -25,9 +25,12 @@ func runGitCmd(ctx context.Context, dir string, args ...string) ([]byte, error) "GIT_COMMITTER_EMAIL=batch-changes@sourcegraph.com", } cmd.Dir = dir - out, err := cmd.CombinedOutput() + out, err := cmd.Output() if err != nil { - return out, errors.Wrapf(err, "'git %s' failed: %s", strings.Join(args, " "), out) + if exitErr, ok := err.(*exec.ExitError); ok { + return out, errors.Wrapf(err, "'git %s' failed: %s", strings.Join(args, " "), string(exitErr.Stderr)) + } + return out, errors.Wrapf(err, "'git %s' failed: %s", strings.Join(args, " "), string(out)) } return out, nil } From f776d410ec6ae64e554027f487a1e2b528b20f70 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Thu, 16 Jun 2022 17:26:12 +0200 Subject: [PATCH 193/647] Polish and use native workspaces in executors mode (#768) This PR cleans up the src side of things for SSBC: - Ensures to have a separate cache directory for each src running, so they don't collide while writing to them - Ensures to have a tmp directory set within the executor workspace so it can be retained for inspection - Removes useless API call to Sourcegraph to retrieve it's version - Supports native repos cloned into the workspace - Ensures no env var is used for cache key generation, those are not set on the server and it would cause cache key mismatches - And most importantly, it doesn't require an access token anymore, so it's much safer, especially in less-isolated executors! Closes https://github.com/sourcegraph/sourcegraph/issues/37079 Closes https://github.com/sourcegraph/sourcegraph/issues/36597 Closes https://github.com/sourcegraph/sourcegraph/issues/36187 --- cmd/src/batch_apply.go | 2 +- cmd/src/batch_common.go | 70 +++--- cmd/src/batch_exec.go | 222 +++++++++++++----- cmd/src/batch_preview.go | 2 +- internal/batches/executor/coordinator.go | 39 +-- internal/batches/executor/coordinator_test.go | 36 --- internal/batches/executor/execution_cache.go | 7 +- internal/batches/executor/executor.go | 2 + internal/batches/executor/executor_test.go | 6 +- internal/batches/executor/run_steps.go | 4 +- .../log/{manager.go => disk_manager.go} | 20 +- .../{task_logger.go => disk_task_logger.go} | 9 - internal/batches/log/logger.go | 18 ++ internal/batches/log/noop_manager.go | 21 ++ internal/batches/log/noop_task_logger.go | 31 +++ internal/batches/repozip/noop.go | 31 +++ internal/batches/service/service.go | 11 +- internal/batches/ui/json_lines.go | 19 +- internal/batches/workspace/bind_workspace.go | 12 +- .../batches/workspace/executor_workspace.go | 56 +++++ internal/batches/workspace/git.go | 2 + .../batches/workspace/volume_workspace.go | 2 - internal/batches/workspace/workspace.go | 24 +- 23 files changed, 430 insertions(+), 216 deletions(-) rename internal/batches/log/{manager.go => disk_manager.go} (62%) rename internal/batches/log/{task_logger.go => disk_task_logger.go} (92%) create mode 100644 internal/batches/log/logger.go create mode 100644 internal/batches/log/noop_manager.go create mode 100644 internal/batches/log/noop_task_logger.go create mode 100644 internal/batches/repozip/noop.go create mode 100644 internal/batches/workspace/executor_workspace.go diff --git a/cmd/src/batch_apply.go b/cmd/src/batch_apply.go index 9b3d3d5fa9..dcbc061f51 100644 --- a/cmd/src/batch_apply.go +++ b/cmd/src/batch_apply.go @@ -32,7 +32,7 @@ Examples: ` flagSet := flag.NewFlagSet("apply", flag.ExitOnError) - flags := newBatchExecuteFlags(flagSet, false, batchDefaultCacheDir(), batchDefaultTempDirPrefix()) + flags := newBatchExecuteFlags(flagSet, batchDefaultCacheDir(), batchDefaultTempDirPrefix()) handler := func(args []string) error { if err := flagSet.Parse(args); err != nil { diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index 6fa550f472..30c7738ea1 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -25,6 +25,8 @@ import ( "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/executor" "github.com/sourcegraph/src-cli/internal/batches/graphql" + "github.com/sourcegraph/src-cli/internal/batches/log" + "github.com/sourcegraph/src-cli/internal/batches/repozip" "github.com/sourcegraph/src-cli/internal/batches/service" "github.com/sourcegraph/src-cli/internal/batches/ui" "github.com/sourcegraph/src-cli/internal/batches/workspace" @@ -86,30 +88,31 @@ type batchExecuteFlags struct { textOnly bool } -func newBatchExecuteFlags(flagSet *flag.FlagSet, workspaceExecution bool, cacheDir, tempDir string) *batchExecuteFlags { +func newBatchExecuteFlags(flagSet *flag.FlagSet, cacheDir, tempDir string) *batchExecuteFlags { caf := &batchExecuteFlags{ batchExecutionFlags: newBatchExecutionFlags(flagSet), } - if !workspaceExecution { - flagSet.BoolVar( - &caf.textOnly, "text-only", false, - "INTERNAL USE ONLY. EXPERIMENTAL. Switches off the TUI to only print JSON lines.", - ) - flagSet.BoolVar( - &caf.apply, "apply", false, - "Ignored.", - ) - flagSet.BoolVar( - &caf.keepLogs, "keep-logs", false, - "Retain logs after executing steps.", - ) - } + flagSet.BoolVar( + &caf.textOnly, "text-only", false, + "INTERNAL USE ONLY. EXPERIMENTAL. Switches off the TUI to only print JSON lines.", + ) + + flagSet.BoolVar( + &caf.apply, "apply", false, + "Ignored.", + ) + + flagSet.BoolVar( + &caf.keepLogs, "keep-logs", false, + "Retain logs after executing steps.", + ) flagSet.StringVar( &caf.cacheDir, "cache", cacheDir, "Directory for caching results and repository archives.", ) + flagSet.StringVar( &caf.tempDir, "tmp", tempDir, "Directory for storing temporary data, such as log files. Default is /tmp. Can also be set with environment variable SRC_BATCH_TMP_DIR; if both are set, this flag will be used and not the environment variable.", @@ -124,14 +127,17 @@ func newBatchExecuteFlags(flagSet *flag.FlagSet, workspaceExecution bool, cacheD &caf.parallelism, "j", runtime.GOMAXPROCS(0), "The maximum number of parallel jobs. Default is GOMAXPROCS.", ) + flagSet.DurationVar( &caf.timeout, "timeout", 60*time.Minute, "The maximum duration a single batch spec step can take.", ) + flagSet.BoolVar( &caf.cleanArchives, "clean-archives", true, "If true, deletes downloaded repository archives after executing batch spec steps.", ) + flagSet.BoolVar( &caf.skipErrors, "skip-errors", false, "If true, errors encountered while executing steps in a repository won't stop the execution of the batch spec but only cause that repository to be skipped.", @@ -316,14 +322,15 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp ui.PreparingContainerImagesSuccess() ui.DeterminingWorkspaceCreatorType() - workspaceCreator = workspace.NewCreator(ctx, opts.flags.workspace, opts.flags.cacheDir, opts.flags.tempDir, images) - if workspaceCreator.Type() == workspace.CreatorTypeVolume { + var typ workspace.CreatorType + workspaceCreator, typ = workspace.NewCreator(ctx, opts.flags.workspace, opts.flags.cacheDir, opts.flags.tempDir, images) + if typ == workspace.CreatorTypeVolume { _, err = svc.EnsureImage(ctx, workspace.DockerVolumeWorkspaceImage) if err != nil { return err } } - ui.DeterminingWorkspaceCreatorTypeSuccess(workspaceCreator.Type()) + ui.DeterminingWorkspaceCreatorTypeSuccess(typ) } ui.ResolvingRepositories() @@ -347,19 +354,22 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp } ui.DeterminingWorkspacesSuccess(len(workspaces)) + archiveRegistry := repozip.NewArchiveRegistry(opts.client, opts.flags.cacheDir, opts.flags.cleanArchives) + // EXECUTION OF TASKS - coord := svc.NewCoordinator(executor.NewCoordinatorOpts{ - Creator: workspaceCreator, - CacheDir: opts.flags.cacheDir, - Cache: executor.NewDiskCache(opts.flags.cacheDir), - SkipErrors: opts.flags.skipErrors, - CleanArchives: opts.flags.cleanArchives, - Parallelism: opts.flags.parallelism, - Timeout: opts.flags.timeout, - KeepLogs: opts.flags.keepLogs, - TempDir: opts.flags.tempDir, - AllowPathMounts: true, - }) + coord := svc.NewCoordinator( + archiveRegistry, + log.NewDiskManager(opts.flags.tempDir, opts.flags.keepLogs), + executor.NewCoordinatorOpts{ + Creator: workspaceCreator, + Cache: executor.NewDiskCache(opts.flags.cacheDir), + Parallelism: opts.flags.parallelism, + Timeout: opts.flags.timeout, + TempDir: opts.flags.tempDir, + GlobalEnv: os.Environ(), + AllowPathMounts: true, + }, + ) ui.CheckingCache() tasks := svc.BuildTasks( diff --git a/cmd/src/batch_exec.go b/cmd/src/batch_exec.go index 2c81559bf0..e6fa093a8d 100644 --- a/cmd/src/batch_exec.go +++ b/cmd/src/batch_exec.go @@ -6,11 +6,18 @@ import ( "flag" "fmt" "io" + "net/http" + "os" + "path/filepath" + "time" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/batches/executor" "github.com/sourcegraph/src-cli/internal/batches/graphql" + "github.com/sourcegraph/src-cli/internal/batches/log" + "github.com/sourcegraph/src-cli/internal/batches/repozip" "github.com/sourcegraph/src-cli/internal/batches/service" "github.com/sourcegraph/src-cli/internal/batches/ui" "github.com/sourcegraph/src-cli/internal/batches/workspace" @@ -19,6 +26,51 @@ import ( batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" ) +const ( + execPullParallelism = 4 +) + +type executorModeFlags struct { + sourcegraphVersion string + timeout time.Duration + file string + tempDir string + cacheDir string + repoDir string +} + +func newExecutorModeFlags(flagSet *flag.FlagSet) (f *executorModeFlags) { + f = &executorModeFlags{} + flagSet.StringVar(&f.sourcegraphVersion, "sourcegraphVersion", "", "Sourcegraph backend version.") + flagSet.DurationVar(&f.timeout, "timeout", 60*time.Minute, "The maximum duration a single batch spec step can take.") + flagSet.StringVar(&f.file, "f", "", "The workspace execution input file to read.") + flagSet.StringVar(&f.tempDir, "tmp", "", "Directory for storing temporary data.") + flagSet.StringVar(&f.cacheDir, "cache", "", "Directory to read cached results from.") + flagSet.StringVar(&f.repoDir, "repo", "", "Path of the checked out repo on disk.") + + return f +} + +func validateExecutorModeFlags(f *executorModeFlags) error { + if f.sourcegraphVersion == "" { + return errors.New("sourcegraphVersion parameter missing") + } + if f.file == "" { + return errors.New("input file parameter missing") + } + if f.tempDir == "" { + return errors.New("tempDir parameter missing") + } + if f.cacheDir == "" { + return errors.New("cacheDir parameter missing") + } + if f.repoDir == "" { + return errors.New("repoDir parameter missing") + } + + return nil +} + func init() { usage := ` INTERNAL USE ONLY: 'src batch exec' executes the given raw batch spec in the given workspaces. @@ -28,7 +80,7 @@ github.com/sourcegraph/sourcegraph/lib/batches. Usage: - src batch exec -f FILE [command options] + src batch exec -f FILE -repo DIR [command options] Examples: @@ -37,7 +89,7 @@ Examples: ` flagSet := flag.NewFlagSet("exec", flag.ExitOnError) - flags := newBatchExecuteFlags(flagSet, true, batchDefaultCacheDir(), batchDefaultTempDirPrefix()) + flags := newExecutorModeFlags(flagSet) handler := func(args []string) error { if err := flagSet.Parse(args); err != nil { @@ -48,13 +100,14 @@ Examples: return cmderrors.Usage("additional arguments not allowed") } + if err := validateExecutorModeFlags(flags); err != nil { + return cmderrors.ExitCode(1, err) + } + ctx, cancel := contextCancelOnInterrupt(context.Background()) defer cancel() - err := executeBatchSpecInWorkspaces(ctx, &ui.JSONLines{}, executeBatchSpecOpts{ - flags: flags, - client: cfg.apiClient(flags.api, flagSet.Output()), - }) + err := executeBatchSpecInWorkspaces(ctx, flags) if err != nil { return cmderrors.ExitCode(1, nil) } @@ -73,19 +126,46 @@ Examples: }) } -func executeBatchSpecInWorkspaces(ctx context.Context, ui *ui.JSONLines, opts executeBatchSpecOpts) (err error) { +func executeBatchSpecInWorkspaces(ctx context.Context, flags *executorModeFlags) (err error) { + ui := &ui.JSONLines{} defer func() { if err != nil { ui.ExecutionError(err) } }() + tempDir := flags.tempDir + if !filepath.IsAbs(tempDir) { + tempDir, err = filepath.Abs(tempDir) + if err != nil { + return errors.Wrap(err, "getting absolute path for temp dir") + } + + if err := os.Mkdir(tempDir, os.ModePerm); err != nil { + return errors.Wrap(err, "creating temp directory") + } + } + + repoDir := flags.repoDir + if !filepath.IsAbs(repoDir) { + repoDir, err = filepath.Abs(repoDir) + if err != nil { + return errors.Wrap(err, "getting absolute path for repo dir") + } + } + svc := service.New(&service.Opts{ - AllowUnsupported: opts.flags.allowUnsupported, - AllowIgnored: opts.flags.allowIgnored, - Client: opts.client, + // When this workspace made it to here, it's already been validated. + AllowUnsupported: true, + // When this workspace made it to here, it's already been validated. + AllowIgnored: true, + // We don't want src to talk to the sg instance, if it would, this + // is a regression. Therefor, we have this dead client that kills the + // process when something should try to talk to src. + Client: &deadClient{}, }) - if err := svc.DetermineFeatureFlags(ctx); err != nil { + + if err := svc.SetFeatureFlagsForRelease(flags.sourcegraphVersion); err != nil { return err } @@ -98,83 +178,82 @@ func executeBatchSpecInWorkspaces(ctx context.Context, ui *ui.JSONLines, opts ex // Read the input file that contains the raw spec and the workspaces in // which to execute it. - input, err := loadWorkspaceExecutionInput(opts.flags.file) + input, err := loadWorkspaceExecutionInput(flags.file) if err != nil { return err } // Since we already know which workspace we want to execute the steps in, // we can convert it to a RepoWorkspace and build a task only for that one. - repoWorkspace := convertWorkspace(input) + tasks := svc.BuildTasks(ctx, &input.BatchChangeAttributes, []service.RepoWorkspace{convertWorkspace(input)}) + + if len(tasks) != 1 { + return errors.New("invalid input, didn't yield exactly one task") + } - var workspaceCreator workspace.Creator + task := tasks[0] - if len(input.Steps) > 0 { + if len(task.Steps) == 0 { + return errors.New("invalid execution, no steps to process") + } + + { ui.PreparingContainerImages() - images, err := svc.EnsureDockerImages( - ctx, input.Steps, opts.flags.parallelism, + _, err = svc.EnsureDockerImages( + ctx, + task.Steps, + execPullParallelism, ui.PreparingContainerImagesProgress, ) if err != nil { return err } ui.PreparingContainerImagesSuccess() + } - ui.DeterminingWorkspaceCreatorType() - workspaceCreator = workspace.NewCreator(ctx, opts.flags.workspace, opts.flags.cacheDir, opts.flags.tempDir, images) - if workspaceCreator.Type() == workspace.CreatorTypeVolume { - _, err = svc.EnsureImage(ctx, workspace.DockerVolumeWorkspaceImage) - if err != nil { - return err - } - } - ui.DeterminingWorkspaceCreatorTypeSuccess(workspaceCreator.Type()) - } - - // EXECUTION OF TASKS - coord := svc.NewCoordinator(executor.NewCoordinatorOpts{ - Creator: workspaceCreator, - CacheDir: opts.flags.cacheDir, - Cache: &executor.ServerSideCache{Writer: ui}, - SkipErrors: opts.flags.skipErrors, - CleanArchives: opts.flags.cleanArchives, - Parallelism: opts.flags.parallelism, - Timeout: opts.flags.timeout, - KeepLogs: opts.flags.keepLogs, - TempDir: opts.flags.tempDir, - // Temporarily prevent the ability to sending a batch spec with a mount for server-side processing. - AllowPathMounts: false, - }) + coord := svc.NewCoordinator( + repozip.NewNoopRegistry(), + log.NewNoopManager(), + executor.NewCoordinatorOpts{ + Creator: workspace.NewExecutorWorkspaceCreator(tempDir, repoDir), + Cache: &executor.ServerSideCache{CacheDir: flags.cacheDir, Writer: ui}, + Parallelism: 1, + // TODO: Should be slightly less than the executor timeout. Can we somehow read that? + Timeout: flags.timeout, + TempDir: tempDir, + // Don't allow to read from env. + GlobalEnv: []string{}, + // Temporarily prevent the ability to sending a batch spec with a mount for server-side processing. + AllowPathMounts: false, + }, + ) // `src batch exec` uses server-side caching for changeset specs, so we // only need to call `CheckStepResultsCache` to make sure that per-step cache entries // are loaded and set on the tasks. - tasks := svc.BuildTasks(ctx, &input.BatchChangeAttributes, []service.RepoWorkspace{repoWorkspace}) - if err := coord.CheckStepResultsCache(ctx, tasks); err != nil { + if err := coord.CheckStepResultsCache( + ctx, + tasks, + // Don't expose the executor env, we don't allow env forwarding anyways. + []string{}, + ); err != nil { return err } - taskExecUI := ui.ExecutingTasks(*verbose, opts.flags.parallelism) + // These arguments are unused in the json logs implementation, but the interface + // dictates them. + taskExecUI := ui.ExecutingTasks(false, 1) err = coord.Execute(ctx, tasks, taskExecUI) - if err == nil || opts.flags.skipErrors { - if err == nil { - taskExecUI.Success() - } else { - ui.ExecutingTasksSkippingErrors(err) - } - } else { - if err != nil { - taskExecUI.Failed(err) - return err - } + if err != nil { + taskExecUI.Failed(err) + return err } + taskExecUI.Success() return nil } -func loadWorkspaceExecutionInput(file string) (batcheslib.WorkspacesExecutionInput, error) { - var input batcheslib.WorkspacesExecutionInput - +func loadWorkspaceExecutionInput(file string) (input batcheslib.WorkspacesExecutionInput, err error) { f, err := batchOpenFileFlag(file) if err != nil { return input, err @@ -216,3 +295,28 @@ func convertWorkspace(w batcheslib.WorkspacesExecutionInput) service.RepoWorkspa OnlyFetchWorkspace: w.OnlyFetchWorkspace, } } + +type deadClient struct{} + +var _ api.Client = &deadClient{} + +const deadClientPanicMsg = "Dead client invoked. This indicates a bug in src-cli in server-side execution, please report this." + +func (c *deadClient) NewQuery(query string) api.Request { + panic(deadClientPanicMsg) +} +func (c *deadClient) NewRequest(query string, vars map[string]interface{}) api.Request { + panic(deadClientPanicMsg) +} +func (c *deadClient) NewGzippedRequest(query string, vars map[string]interface{}) api.Request { + panic(deadClientPanicMsg) +} +func (c *deadClient) NewGzippedQuery(query string) api.Request { + panic(deadClientPanicMsg) +} +func (c *deadClient) NewHTTPRequest(ctx context.Context, method, path string, body io.Reader) (*http.Request, error) { + panic(deadClientPanicMsg) +} +func (c *deadClient) Do(req *http.Request) (*http.Response, error) { + panic(deadClientPanicMsg) +} diff --git a/cmd/src/batch_preview.go b/cmd/src/batch_preview.go index 239dc2d8eb..088c58046e 100644 --- a/cmd/src/batch_preview.go +++ b/cmd/src/batch_preview.go @@ -30,7 +30,7 @@ Examples: ` flagSet := flag.NewFlagSet("preview", flag.ExitOnError) - flags := newBatchExecuteFlags(flagSet, false, batchDefaultCacheDir(), batchDefaultTempDirPrefix()) + flags := newBatchExecuteFlags(flagSet, batchDefaultCacheDir(), batchDefaultTempDirPrefix()) handler := func(args []string) error { if err := flagSet.Parse(args); err != nil { diff --git a/internal/batches/executor/coordinator.go b/internal/batches/executor/coordinator.go index 63d7ec7219..a81e91b8db 100644 --- a/internal/batches/executor/coordinator.go +++ b/internal/batches/executor/coordinator.go @@ -2,7 +2,6 @@ package executor import ( "context" - "os" "time" "github.com/sourcegraph/sourcegraph/lib/errors" @@ -43,39 +42,31 @@ type NewCoordinatorOpts struct { Cache cache.Cache RepoArchiveRegistry repozip.ArchiveRegistry - // Everything that follows are either command-line flags or features. + GlobalEnv []string - // TODO: We could probably have a wrapper around flags and features, - // something like ExecutionArgs, that we can pass around - CacheDir string - SkipErrors bool + // Everything that follows are either command-line flags or features. // Used by batcheslib.BuildChangesetSpecs Features batches.FeatureFlags - CleanArchives bool Parallelism int Timeout time.Duration - KeepLogs bool TempDir string AllowPathMounts bool } -func NewCoordinator(opts NewCoordinatorOpts) *Coordinator { - logManager := log.NewManager(opts.TempDir, opts.KeepLogs) - - globalEnv := os.Environ() - +func NewCoordinator(opts NewCoordinatorOpts, logger log.LogManager) *Coordinator { exec := newExecutor(newExecutorOpts{ RepoArchiveRegistry: opts.RepoArchiveRegistry, EnsureImage: opts.EnsureImage, Creator: opts.Creator, - Logger: logManager, + Logger: logger, Parallelism: opts.Parallelism, Timeout: opts.Timeout, TempDir: opts.TempDir, AllowPathMounts: opts.AllowPathMounts, + GlobalEnv: opts.GlobalEnv, WriteStepCacheResult: func(ctx context.Context, stepResult execution.AfterStepResult, task *Task) error { // Temporarily skip writing to the cache if a mount is present for _, step := range task.Steps { @@ -83,7 +74,7 @@ func NewCoordinator(opts NewCoordinatorOpts) *Coordinator { return nil } } - cacheKey := task.cacheKey(globalEnv) + cacheKey := task.cacheKey(opts.GlobalEnv) return writeToCache(ctx, opts.Cache, stepResult, task, cacheKey) }, }) @@ -92,7 +83,7 @@ func NewCoordinator(opts NewCoordinatorOpts) *Coordinator { opts: opts, cache: opts.Cache, exec: exec, - logManager: logManager, + logManager: logger, } } @@ -119,8 +110,7 @@ func (c *Coordinator) CheckCache(ctx context.Context, batchSpec *batcheslib.Batc // CheckStepResultsCache checks the cache for each Task, but only for cached // step results. This is used by `src batch exec` when executing server-side. -func (c *Coordinator) CheckStepResultsCache(ctx context.Context, tasks []*Task) error { - globalEnv := os.Environ() +func (c *Coordinator) CheckStepResultsCache(ctx context.Context, tasks []*Task, globalEnv []string) error { for _, t := range tasks { if err := c.loadCachedStepResults(ctx, t, globalEnv); err != nil { return err @@ -130,10 +120,8 @@ func (c *Coordinator) CheckStepResultsCache(ctx context.Context, tasks []*Task) } func (c *Coordinator) ClearCache(ctx context.Context, tasks []*Task) error { - globalEnv := os.Environ() - for _, task := range tasks { - cacheKey := task.cacheKey(globalEnv) + cacheKey := task.cacheKey(c.opts.GlobalEnv) if err := c.cache.Clear(ctx, cacheKey); err != nil { return errors.Wrapf(err, "clearing cache for %q", task.Repository.Name) } @@ -148,10 +136,8 @@ func (c *Coordinator) ClearCache(ctx context.Context, tasks []*Task) error { } func (c *Coordinator) checkCacheForTask(ctx context.Context, batchSpec *batcheslib.BatchSpec, task *Task) (specs []*batcheslib.ChangesetSpec, found bool, err error) { - globalEnv := os.Environ() - // Check if the task is cached. - cacheKey := task.cacheKey(globalEnv) + cacheKey := task.cacheKey(c.opts.GlobalEnv) var result execution.Result result, found, err = c.cache.Get(ctx, cacheKey) @@ -162,7 +148,7 @@ func (c *Coordinator) checkCacheForTask(ctx context.Context, batchSpec *batchesl if !found { // If we are here, that means we didn't find anything in the cache for the // complete task. So, what if we have cached results for the steps? - if err := c.loadCachedStepResults(ctx, task, globalEnv); err != nil { + if err := c.loadCachedStepResults(ctx, task, c.opts.GlobalEnv); err != nil { return specs, false, err } @@ -246,8 +232,7 @@ func writeToCache(ctx context.Context, cache cache.Cache, stepResult execution.A func (c *Coordinator) writeExecutionCacheResult(ctx context.Context, taskResult taskResult, ui TaskExecutionUI) error { // Add to the cache, even if no diff was produced. - globalEnv := os.Environ() - cacheKey := taskResult.task.cacheKey(globalEnv) + cacheKey := taskResult.task.cacheKey(c.opts.GlobalEnv) if err := c.cache.Set(ctx, cacheKey, taskResult.result); err != nil { return errors.Wrapf(err, "caching result for %q", taskResult.task.Repository.Name) } diff --git a/internal/batches/executor/coordinator_test.go b/internal/batches/executor/coordinator_test.go index 4868de9e4f..20c414a79a 100644 --- a/internal/batches/executor/coordinator_test.go +++ b/internal/batches/executor/coordinator_test.go @@ -2,7 +2,6 @@ package executor import ( "context" - "fmt" "strings" "sync" "testing" @@ -226,41 +225,6 @@ func TestCoordinator_Execute(t *testing.T) { }), }, }, - { - name: "skip errors", - opts: NewCoordinatorOpts{Features: featuresAllEnabled(), SkipErrors: true}, - - tasks: []*Task{srcCLITask, sourcegraphTask}, - - batchSpec: &batcheslib.BatchSpec{ - Name: "my-batch-change", - Description: "the description", - ChangesetTemplate: testChangesetTemplate, - }, - - // Execution succeeded in srcCLIRepo, but fails in sourcegraphRepo - executor: &dummyExecutor{ - results: []taskResult{ - {task: srcCLITask, result: execution.Result{Diff: `dummydiff1`}}, - }, - waitErr: stepFailedErr{ - Err: fmt.Errorf("something went wrong"), - Run: "broken command", - Container: "alpine:3", - TmpFilename: "/tmp/foobar", - Stderr: "unknown command: broken", - }, - }, - - wantErrInclude: "run: broken command", - // We want 1 cache entry and 1 spec - wantCacheEntries: 1, - wantSpecs: []*batcheslib.ChangesetSpec{ - buildSpecFor(testRepo1, func(spec *batcheslib.ChangesetSpec) { - spec.Commits[0].Diff = `dummydiff1` - }), - }, - }, { name: "skip cache for step mount", diff --git a/internal/batches/executor/execution_cache.go b/internal/batches/executor/execution_cache.go index 187b8bd001..7148bd9a5b 100644 --- a/internal/batches/executor/execution_cache.go +++ b/internal/batches/executor/execution_cache.go @@ -158,7 +158,8 @@ type JSONCacheWriter interface { } type ServerSideCache struct { - Writer JSONCacheWriter + CacheDir string + Writer JSONCacheWriter } func (c *ServerSideCache) Get(ctx context.Context, key cache.Keyer) (result execution.Result, found bool, err error) { @@ -194,7 +195,9 @@ func (c *ServerSideCache) GetStepResult(ctx context.Context, key cache.Keyer) (r return result, false, err } - found, err = readCacheFile(rawKey+cacheFileExt, &result) + file := rawKey + cacheFileExt + path := filepath.Join(c.CacheDir, file) + found, err = readCacheFile(path, &result) if err != nil { return result, false, err } diff --git a/internal/batches/executor/executor.go b/internal/batches/executor/executor.go index c9a4d88741..5c65234a95 100644 --- a/internal/batches/executor/executor.go +++ b/internal/batches/executor/executor.go @@ -64,6 +64,7 @@ type newExecutorOpts struct { Timeout time.Duration TempDir string AllowPathMounts bool + GlobalEnv []string WriteStepCacheResult func(ctx context.Context, stepResult execution.AfterStepResult, task *Task) error } @@ -180,6 +181,7 @@ func (x *executor) do(ctx context.Context, task *Task, ui TaskExecutionUI) (err ensureImage: x.opts.EnsureImage, tempDir: x.opts.TempDir, allowPathMounts: x.opts.AllowPathMounts, + globalEnv: x.opts.GlobalEnv, ui: ui.StepsExecutionUI(task), writeStepCacheResult: x.opts.WriteStepCacheResult, diff --git a/internal/batches/executor/executor_test.go b/internal/batches/executor/executor_test.go index 924099c131..489c6f9de5 100644 --- a/internal/batches/executor/executor_test.go +++ b/internal/batches/executor/executor_test.go @@ -381,9 +381,10 @@ func TestExecutor_Integration(t *testing.T) { cacheCount := 0 var cacheLock sync.Mutex + cr, _ := workspace.NewCreator(context.Background(), "bind", testTempDir, testTempDir, images) // Setup executor opts := newExecutorOpts{ - Creator: workspace.NewCreator(context.Background(), "bind", testTempDir, testTempDir, images), + Creator: cr, RepoArchiveRegistry: repozip.NewArchiveRegistry(client, testTempDir, false), Logger: mock.LogNoOpManager{}, EnsureImage: imageMapEnsurer(images), @@ -811,9 +812,10 @@ func testExecuteTasks(t *testing.T, tasks []*Task, archives ...mock.RepoArchive) } } + cr, _ := workspace.NewCreator(context.Background(), "bind", testTempDir, testTempDir, images) // Setup executor executor := newExecutor(newExecutorOpts{ - Creator: workspace.NewCreator(context.Background(), "bind", testTempDir, testTempDir, images), + Creator: cr, RepoArchiveRegistry: repozip.NewArchiveRegistry(client, testTempDir, false), Logger: mock.LogNoOpManager{}, EnsureImage: imageMapEnsurer(images), diff --git a/internal/batches/executor/run_steps.go b/internal/batches/executor/run_steps.go index 32f3adb10d..8a12a7ecc5 100644 --- a/internal/batches/executor/run_steps.go +++ b/internal/batches/executor/run_steps.go @@ -40,6 +40,8 @@ type executionOpts struct { allowPathMounts bool + globalEnv []string + writeStepCacheResult func(ctx context.Context, stepResult execution.AfterStepResult, task *Task) error } @@ -261,7 +263,7 @@ func executeSingleStep( defer cleanup() // Resolve step.Env given the current environment. - stepEnv, err := step.Env.Resolve(os.Environ()) + stepEnv, err := step.Env.Resolve(opts.globalEnv) if err != nil { err = errors.Wrap(err, "resolving step environment") opts.ui.StepPreparingFailed(i+1, err) diff --git a/internal/batches/log/manager.go b/internal/batches/log/disk_manager.go similarity index 62% rename from internal/batches/log/manager.go rename to internal/batches/log/disk_manager.go index 5868c30bdb..e3ef43ddf2 100644 --- a/internal/batches/log/manager.go +++ b/internal/batches/log/disk_manager.go @@ -6,26 +6,20 @@ import ( "github.com/sourcegraph/sourcegraph/lib/errors" ) -type LogManager interface { - AddTask(string) (TaskLogger, error) - Close() error - LogFiles() []string -} - -var _ LogManager = &Manager{} +var _ LogManager = &DiskManager{} -type Manager struct { +type DiskManager struct { dir string keepLogs bool tasks sync.Map } -func NewManager(dir string, keepLogs bool) *Manager { - return &Manager{dir: dir, keepLogs: keepLogs} +func NewDiskManager(dir string, keepLogs bool) *DiskManager { + return &DiskManager{dir: dir, keepLogs: keepLogs} } -func (lm *Manager) AddTask(slug string) (TaskLogger, error) { +func (lm *DiskManager) AddTask(slug string) (TaskLogger, error) { tl, err := newTaskLogger(slug, lm.keepLogs, lm.dir) if err != nil { return nil, err @@ -35,7 +29,7 @@ func (lm *Manager) AddTask(slug string) (TaskLogger, error) { return tl, nil } -func (lm *Manager) Close() error { +func (lm *DiskManager) Close() error { var errs errors.MultiError lm.tasks.Range(func(_, v interface{}) bool { @@ -51,7 +45,7 @@ func (lm *Manager) Close() error { return errs } -func (lm *Manager) LogFiles() []string { +func (lm *DiskManager) LogFiles() []string { var files []string lm.tasks.Range(func(_, v interface{}) bool { diff --git a/internal/batches/log/task_logger.go b/internal/batches/log/disk_task_logger.go similarity index 92% rename from internal/batches/log/task_logger.go rename to internal/batches/log/disk_task_logger.go index 41c1daa3e2..ce8d809b2e 100644 --- a/internal/batches/log/task_logger.go +++ b/internal/batches/log/disk_task_logger.go @@ -10,15 +10,6 @@ import ( "github.com/sourcegraph/sourcegraph/lib/errors" ) -type TaskLogger interface { - Close() error - Log(string) - Logf(string, ...interface{}) - MarkErrored() - Path() string - PrefixWriter(prefix string) io.Writer -} - type FileTaskLogger struct { f *os.File diff --git a/internal/batches/log/logger.go b/internal/batches/log/logger.go new file mode 100644 index 0000000000..0949e1ba32 --- /dev/null +++ b/internal/batches/log/logger.go @@ -0,0 +1,18 @@ +package log + +import "io" + +type LogManager interface { + AddTask(string) (TaskLogger, error) + Close() error + LogFiles() []string +} + +type TaskLogger interface { + Close() error + Log(string) + Logf(string, ...interface{}) + MarkErrored() + Path() string + PrefixWriter(prefix string) io.Writer +} diff --git a/internal/batches/log/noop_manager.go b/internal/batches/log/noop_manager.go new file mode 100644 index 0000000000..b092bd1cf2 --- /dev/null +++ b/internal/batches/log/noop_manager.go @@ -0,0 +1,21 @@ +package log + +var _ LogManager = &NoopManager{} + +type NoopManager struct{} + +func NewNoopManager() *NoopManager { + return &NoopManager{} +} + +func (lm *NoopManager) AddTask(string) (TaskLogger, error) { + return &NoopTaskLogger{}, nil +} + +func (lm *NoopManager) Close() error { + return nil +} + +func (lm *NoopManager) LogFiles() []string { + return []string{} +} diff --git a/internal/batches/log/noop_task_logger.go b/internal/batches/log/noop_task_logger.go new file mode 100644 index 0000000000..f7aac40da3 --- /dev/null +++ b/internal/batches/log/noop_task_logger.go @@ -0,0 +1,31 @@ +package log + +import ( + "io" + "os" +) + +type NoopTaskLogger struct { + f *os.File + + errored bool + keep bool +} + +func (tl *NoopTaskLogger) Close() error { + return nil +} + +func (tl *NoopTaskLogger) Log(s string) {} + +func (tl *NoopTaskLogger) Logf(format string, a ...interface{}) {} + +func (tl *NoopTaskLogger) MarkErrored() {} + +func (tl *NoopTaskLogger) Path() string { + return "not-retained" +} + +func (tl *NoopTaskLogger) PrefixWriter(prefix string) io.Writer { + return io.Discard +} diff --git a/internal/batches/repozip/noop.go b/internal/batches/repozip/noop.go new file mode 100644 index 0000000000..2f83e797eb --- /dev/null +++ b/internal/batches/repozip/noop.go @@ -0,0 +1,31 @@ +package repozip + +import "context" + +// NewNoopRegistry returns a registry that returns archives that don't perform +// any operation. This is used in executor mode to disable fetching repo archives +// in favor of cloning. +func NewNoopRegistry() ArchiveRegistry { + return &noopArchiveRegistry{} +} + +type noopArchiveRegistry struct{} + +func (r *noopArchiveRegistry) Checkout(repo RepoRevision, path string) Archive { + return &noopArchive{} +} + +type noopArchive struct{} + +func (a *noopArchive) Ensure(context.Context) error { + return nil +} +func (a *noopArchive) Close() error { + return nil +} +func (a *noopArchive) Path() string { + return "" +} +func (a *noopArchive) AdditionalFilePaths() map[string]string { + return nil +} diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index 36d88e9cb3..fb7a12632f 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -24,6 +24,7 @@ import ( "github.com/sourcegraph/src-cli/internal/batches/docker" "github.com/sourcegraph/src-cli/internal/batches/executor" "github.com/sourcegraph/src-cli/internal/batches/graphql" + "github.com/sourcegraph/src-cli/internal/batches/log" "github.com/sourcegraph/src-cli/internal/batches/repozip" ) @@ -98,6 +99,10 @@ func (svc *Service) DetermineFeatureFlags(ctx context.Context) error { return svc.features.SetFromVersion(version) } +func (svc *Service) SetFeatureFlagsForRelease(release string) error { + return svc.features.SetFromVersion(release) +} + // TODO(campaigns-deprecation): this shim can be removed in Sourcegraph 4.0. func (svc *Service) newOperations() graphql.Operations { return graphql.NewOperations( @@ -282,12 +287,12 @@ func (svc *Service) BuildTasks(ctx context.Context, attributes *templatelib.Batc return buildTasks(ctx, attributes, workspaces) } -func (svc *Service) NewCoordinator(opts executor.NewCoordinatorOpts) *executor.Coordinator { - opts.RepoArchiveRegistry = repozip.NewArchiveRegistry(svc.client, opts.CacheDir, opts.CleanArchives) +func (svc *Service) NewCoordinator(archiveRegistry repozip.ArchiveRegistry, logger log.LogManager, opts executor.NewCoordinatorOpts) *executor.Coordinator { + opts.RepoArchiveRegistry = archiveRegistry opts.Features = svc.features opts.EnsureImage = svc.EnsureImage - return executor.NewCoordinator(opts) + return executor.NewCoordinator(opts, logger) } func (svc *Service) CreateImportChangesetSpecs(ctx context.Context, batchSpec *batcheslib.BatchSpec) ([]*batcheslib.ChangesetSpec, error) { diff --git a/internal/batches/ui/json_lines.go b/internal/batches/ui/json_lines.go index 15acf323fc..e3674a1763 100644 --- a/internal/batches/ui/json_lines.go +++ b/internal/batches/ui/json_lines.go @@ -94,8 +94,8 @@ func (ui *JSONLines) CheckingCacheSuccess(cachedSpecsFound int, tasksToExecute i }) } -func (ui *JSONLines) ExecutingTasks(verbose bool, parallelism int) executor.TaskExecutionUI { - return &taskExecutionJSONLines{verbose: verbose, parallelism: parallelism} +func (ui *JSONLines) ExecutingTasks(_ bool, _ int) executor.TaskExecutionUI { + return &taskExecutionJSONLines{} } func (ui *JSONLines) ExecutingTasksSkippingErrors(err error) { @@ -186,9 +186,6 @@ func (ui *JSONLines) WriteAfterStepResult(key string, value execution.AfterStepR } type taskExecutionJSONLines struct { - verbose bool - parallelism int - linesTasks map[*executor.Task]batcheslib.JSONLinesTask } @@ -283,21 +280,17 @@ type stepsExecutionJSONLines struct { const stepFlushDuration = 500 * time.Millisecond func (ui *stepsExecutionJSONLines) ArchiveDownloadStarted() { - logOperationStart(batcheslib.LogEventOperationTaskDownloadingArchive, &batcheslib.TaskDownloadingArchiveMetadata{TaskID: ui.linesTask.ID}) + // We don't fetch archives in executor mode. } func (ui *stepsExecutionJSONLines) ArchiveDownloadFinished(err error) { - if err != nil { - logOperationFailure(batcheslib.LogEventOperationTaskDownloadingArchive, &batcheslib.TaskDownloadingArchiveMetadata{TaskID: ui.linesTask.ID, Error: err.Error()}) - } else { - logOperationSuccess(batcheslib.LogEventOperationTaskDownloadingArchive, &batcheslib.TaskDownloadingArchiveMetadata{TaskID: ui.linesTask.ID}) - } + // We don't fetch archives in executor mode. } func (ui *stepsExecutionJSONLines) WorkspaceInitializationStarted() { - logOperationStart(batcheslib.LogEventOperationTaskInitializingWorkspace, &batcheslib.TaskInitializingWorkspaceMetadata{TaskID: ui.linesTask.ID}) + // No workspace initialization required for executor mode. } func (ui *stepsExecutionJSONLines) WorkspaceInitializationFinished() { - logOperationSuccess(batcheslib.LogEventOperationTaskInitializingWorkspace, &batcheslib.TaskInitializingWorkspaceMetadata{TaskID: ui.linesTask.ID}) + // No workspace initialization required for executor mode. } func (ui *stepsExecutionJSONLines) SkippingStepsUpto(startStep int) { diff --git a/internal/batches/workspace/bind_workspace.go b/internal/batches/workspace/bind_workspace.go index 80438071ef..9bc346ddd8 100644 --- a/internal/batches/workspace/bind_workspace.go +++ b/internal/batches/workspace/bind_workspace.go @@ -25,8 +25,6 @@ type dockerBindWorkspaceCreator struct { var _ Creator = &dockerBindWorkspaceCreator{} -func (wc *dockerBindWorkspaceCreator) Type() CreatorType { return CreatorTypeBind } - func (wc *dockerBindWorkspaceCreator) Create(ctx context.Context, repo *graphql.Repository, steps []batcheslib.Step, archive repozip.Archive) (Workspace, error) { w, err := wc.unzipToWorkspace(ctx, repo, archive.Path()) if err != nil { @@ -104,9 +102,15 @@ func (wc *dockerBindWorkspaceCreator) copyToWorkspace(ctx context.Context, w *do return nil } +// dockerBindWorkspace implements a workspace that operates on the host FS +// and is mounted into the docker containers using a bind mount in the end. type dockerBindWorkspace struct { + // tempDir is a temporary directory that will be used for ephemeral files + // that are needed throughout the process. tempDir string - + // dir is the directory where the repo archive is unzipped to. + // This is also the path that is directly mounted into the docker + // containers. dir string } @@ -130,7 +134,7 @@ func (w *dockerBindWorkspace) Changes(ctx context.Context) (*git.Changes, error) return nil, errors.Wrap(err, "git add failed") } - statusOut, err := runGitCmd(ctx, w.dir, "status", "--porcelain") + statusOut, err := runGitCmd(ctx, w.dir, "status", "--porcelain", "--no-ahead-behind") if err != nil { return nil, errors.Wrap(err, "git status failed") } diff --git a/internal/batches/workspace/executor_workspace.go b/internal/batches/workspace/executor_workspace.go new file mode 100644 index 0000000000..8d8e9e3faf --- /dev/null +++ b/internal/batches/workspace/executor_workspace.go @@ -0,0 +1,56 @@ +package workspace + +import ( + "context" + + batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" + "github.com/sourcegraph/sourcegraph/lib/errors" + + "github.com/sourcegraph/src-cli/internal/batches/graphql" + "github.com/sourcegraph/src-cli/internal/batches/repozip" +) + +func NewExecutorWorkspaceCreator(tempDir, repoDir string) Creator { + return &executorWorkspaceCreator{ + TempDir: tempDir, + RepoDir: repoDir, + } +} + +type executorWorkspaceCreator struct { + TempDir string + RepoDir string +} + +var _ Creator = &executorWorkspaceCreator{} + +func (wc *executorWorkspaceCreator) Create(ctx context.Context, repo *graphql.Repository, steps []batcheslib.Step, archive repozip.Archive) (Workspace, error) { + // Cleanup the repo dir. We don't want any origin to be defined here. This + // reduces risk of accidentally pushing anything from the workspace execution. + if _, err := runGitCmd(ctx, wc.RepoDir, "remote", "rm", "origin"); err != nil { + return nil, errors.Wrap(err, "git init failed") + } + + return &dockerBindExecutorWorkspace{ + dockerBindWorkspace: dockerBindWorkspace{ + tempDir: wc.TempDir, + dir: wc.RepoDir, + }, + }, nil +} + +// dockerBindExecutorWorkspace implements a workspace that operates on the host FS +// and is mounted into the docker containers using a bind mount in the end. +// It is based on the dockerBindWorkspace implementation, but does no cleanup +// as that's handled by the executor, and we want to honor it's `keepWorkspaces` +// setting. +type dockerBindExecutorWorkspace struct { + dockerBindWorkspace +} + +var _ Workspace = &dockerBindExecutorWorkspace{} + +func (w *dockerBindExecutorWorkspace) Close(ctx context.Context) error { + // Nothing to do here, executor cleanup will handle this. + return nil +} diff --git a/internal/batches/workspace/git.go b/internal/batches/workspace/git.go index 52da2e01fd..20c20d1b07 100644 --- a/internal/batches/workspace/git.go +++ b/internal/batches/workspace/git.go @@ -15,6 +15,8 @@ func runGitCmd(ctx context.Context, dir string, args ...string) ([]byte, error) "GIT_CONFIG_NOSYSTEM=1", // And also not any other, because they can mess up output, change defaults, .. which can do unexpected things. "GIT_CONFIG=/dev/null", + // Don't ask interactively for credentials. + "GIT_TERMINAL_PROMPT=0", // Set user.name and user.email in the local repository. The user name and // e-mail will eventually be ignored anyway, since we're just using the Git // repository to generate diffs, but we don't want git to generate alarming diff --git a/internal/batches/workspace/volume_workspace.go b/internal/batches/workspace/volume_workspace.go index 1f0a399074..551d1100ad 100644 --- a/internal/batches/workspace/volume_workspace.go +++ b/internal/batches/workspace/volume_workspace.go @@ -31,8 +31,6 @@ type dockerVolumeWorkspaceCreator struct { var _ Creator = &dockerVolumeWorkspaceCreator{} -func (wc *dockerVolumeWorkspaceCreator) Type() CreatorType { return CreatorTypeVolume } - func (wc *dockerVolumeWorkspaceCreator) Create(ctx context.Context, repo *graphql.Repository, steps []batcheslib.Step, archive repozip.Archive) (Workspace, error) { volume, err := wc.createVolume(ctx) if err != nil { diff --git a/internal/batches/workspace/workspace.go b/internal/batches/workspace/workspace.go index b69e370938..7ed7881eb0 100644 --- a/internal/batches/workspace/workspace.go +++ b/internal/batches/workspace/workspace.go @@ -19,9 +19,6 @@ import ( type Creator interface { // Create creates a new workspace for the given repository and archive file. Create(ctx context.Context, repo *graphql.Repository, steps []batcheslib.Step, archive repozip.Archive) (Workspace, error) - - // Type returns the CreatorType of the Creator. - Type() CreatorType } // Workspace implementations manage per-changeset storage when executing batch @@ -61,7 +58,7 @@ const ( CreatorTypeVolume ) -func NewCreator(ctx context.Context, preference, cacheDir, tempDir string, images map[string]docker.Image) Creator { +func NewCreator(ctx context.Context, preference, cacheDir, tempDir string, images map[string]docker.Image) (Creator, CreatorType) { var workspaceType CreatorType if preference == "volume" { workspaceType = CreatorTypeVolume @@ -71,17 +68,18 @@ func NewCreator(ctx context.Context, preference, cacheDir, tempDir string, image workspaceType = BestCreatorType(ctx, images) } - ensureImage := func(_ context.Context, container string) (docker.Image, error) { - img, ok := images[container] - if !ok { - return nil, errors.Errorf("image %q not found", container) - } - return img, nil - } if workspaceType == CreatorTypeVolume { - return &dockerVolumeWorkspaceCreator{tempDir: tempDir, EnsureImage: ensureImage} + ensureImage := func(_ context.Context, container string) (docker.Image, error) { + img, ok := images[container] + if !ok { + return nil, errors.Errorf("image %q not found", container) + } + return img, nil + } + return &dockerVolumeWorkspaceCreator{tempDir: tempDir, EnsureImage: ensureImage}, workspaceType } - return &dockerBindWorkspaceCreator{Dir: cacheDir} + + return &dockerBindWorkspaceCreator{Dir: cacheDir}, workspaceType } // BestCreatorType determines the correct workspace creator type to use based From 46cc59c2f8fa05e021dc7c1783ae252233e77b7a Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Thu, 16 Jun 2022 17:52:03 +0200 Subject: [PATCH 194/647] Prepare changelog for 3.40.11 (#788) --- CHANGELOG.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6f61e2ed31..26aa1632b3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,12 @@ All notable changes to `src-cli` are documented in this file. ### Removed +## 3.40.11 + +### Changed + +- Adjusted internal mechanisms used in server-side execution. This has no user-facing impact. + ## 3.40.10 ### Added From 524c89abece29d479e386061ae04fe4592a5a84a Mon Sep 17 00:00:00 2001 From: Adam Harvey Date: Thu, 16 Jun 2022 09:56:02 -0700 Subject: [PATCH 195/647] batches: use Docker CPU count as default parallelism, not GOMAXPROCS (#786) Co-authored-by: Erik Seliger --- CHANGELOG.md | 2 + cmd/src/batch_common.go | 25 +++++-- internal/batches/docker/context.go | 96 +++++++++++++++++++++++++++ internal/batches/docker/image.go | 64 ++---------------- internal/batches/docker/image_test.go | 6 +- internal/batches/docker/info.go | 35 ++++++++++ internal/batches/docker/info_test.go | 76 +++++++++++++++++++++ internal/exec/expect/expect.go | 24 +++++++ 8 files changed, 261 insertions(+), 67 deletions(-) create mode 100644 internal/batches/docker/context.go create mode 100644 internal/batches/docker/info.go create mode 100644 internal/batches/docker/info_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 26aa1632b3..fac7567786 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,8 @@ All notable changes to `src-cli` are documented in this file. ### Changed +- The default parallelism of `src batch preview` and `src batch apply` are now based on the number of CPU cores available to Docker, rather than the host system running `src`. This can be overridden [with the `-j` flag](https://docs.sourcegraph.com/cli/references/batch/preview). [#786](https://github.com/sourcegraph/src-cli/pull/786) + ### Fixed ### Removed diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index 30c7738ea1..6a78d8f296 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -23,6 +23,7 @@ import ( "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/batches" + "github.com/sourcegraph/src-cli/internal/batches/docker" "github.com/sourcegraph/src-cli/internal/batches/executor" "github.com/sourcegraph/src-cli/internal/batches/graphql" "github.com/sourcegraph/src-cli/internal/batches/log" @@ -124,8 +125,8 @@ func newBatchExecuteFlags(flagSet *flag.FlagSet, cacheDir, tempDir string) *batc ) flagSet.IntVar( - &caf.parallelism, "j", runtime.GOMAXPROCS(0), - "The maximum number of parallel jobs. Default is GOMAXPROCS.", + &caf.parallelism, "j", 0, + "The maximum number of parallel jobs. Default (or 0) is the number of CPU cores available to Docker.", ) flagSet.DurationVar( @@ -281,7 +282,11 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp return err } - if err := checkExecutable("docker", "version"); err != nil { + // In the past, we checked `docker version`, but now we retrieve the number + // of CPUs, since we need that anyway and it performs the same check (is + // Docker working _at all_?). + parallelism, err := getBatchParallelism(ctx, opts.flags.parallelism) + if err != nil { return err } @@ -313,7 +318,7 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp if len(batchSpec.Steps) > 0 { ui.PreparingContainerImages() images, err := svc.EnsureDockerImages( - ctx, batchSpec.Steps, opts.flags.parallelism, + ctx, batchSpec.Steps, parallelism, ui.PreparingContainerImagesProgress, ) if err != nil { @@ -363,7 +368,7 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp executor.NewCoordinatorOpts{ Creator: workspaceCreator, Cache: executor.NewDiskCache(opts.flags.cacheDir), - Parallelism: opts.flags.parallelism, + Parallelism: parallelism, Timeout: opts.flags.timeout, TempDir: opts.flags.tempDir, GlobalEnv: os.Environ(), @@ -396,7 +401,7 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp } ui.CheckingCacheSuccess(len(specs), len(uncachedTasks)) - taskExecUI := ui.ExecutingTasks(*verbose, opts.flags.parallelism) + taskExecUI := ui.ExecutingTasks(*verbose, parallelism) freshSpecs, logFiles, execErr := coord.ExecuteAndBuildSpecs(ctx, batchSpec, uncachedTasks, taskExecUI) // Add external changeset specs. importedSpecs, importErr := svc.CreateImportChangesetSpecs(ctx, batchSpec) @@ -543,3 +548,11 @@ func contextCancelOnInterrupt(parent context.Context) (context.Context, func()) ctxCancel() } } + +func getBatchParallelism(ctx context.Context, flag int) (int, error) { + if flag > 0 { + return flag, nil + } + + return docker.NCPU(ctx) +} diff --git a/internal/batches/docker/context.go b/internal/batches/docker/context.go new file mode 100644 index 0000000000..c8bd052fc8 --- /dev/null +++ b/internal/batches/docker/context.go @@ -0,0 +1,96 @@ +package docker + +import ( + "context" + "fmt" + "os" + "sync" + "time" + + "github.com/kballard/go-shellquote" + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +// withFastCommandContext wraps the given context with a timeout appropriate for +// invoking Docker commands that are expected to be fast, such as `docker info` +// and `docker image inspect`. This defaults to 5 seconds, but can be overridden +// by the undocumented $SRC_DOCKER_FAST_COMMAND_TIMEOUT environment variable. +// +// If the context deadline is exceeded, the code using the context can pass the +// context and Docker arguments to newFastCommandTimeoutError to get a nicely +// formatted error for the user. +func withFastCommandContext(ctx context.Context) (context.Context, context.CancelFunc, error) { + timeout, err := fastCommandTimeout() + if err != nil { + return nil, nil, err + } + + fctx, cancel := context.WithTimeout( + context.WithValue(ctx, fastCommandTimeoutEnv, timeout), + timeout, + ) + return fctx, cancel, nil +} + +type fastCommandTimeoutError struct { + args []string + timeout time.Duration +} + +func newFastCommandTimeoutError(ctx context.Context, args ...string) error { + // Attempt to extract the timeout from the context. + timeout, ok := ctx.Value(fastCommandTimeoutEnv).(time.Duration) + if !ok { + return errors.Newf( + "additional error found when attempting to create fastCommandTimeoutError: "+ + "no timeout was set within the context, so the context probably wasn't wrapped "+ + "with withFastCommandContext (please file a bug report on src-cli!): "+ + "the original error involved invoking docker with these args: %q", + args, + ) + } + + return &fastCommandTimeoutError{ + args: args, + timeout: timeout, + } +} + +func (e *fastCommandTimeoutError) Error() string { + return fmt.Sprintf( + "`docker %s` failed to respond within %s; "+ + "please verify that Docker has been started and is responding normally", + shellquote.Join(e.args...), e.timeout, + ) +} + +func (*fastCommandTimeoutError) Timeout() bool { return true } + +const ( + fastCommandTimeoutDefault = 5 * time.Second + fastCommandTimeoutEnv = "SRC_DOCKER_FAST_COMMAND_TIMEOUT" +) + +var fastCommandTimeoutData = struct { + once sync.Once + timeout time.Duration + err error +}{ + timeout: fastCommandTimeoutDefault, + err: nil, +} + +func fastCommandTimeout() (time.Duration, error) { + fastCommandTimeoutData.once.Do(func() { + if userTimeout, ok := os.LookupEnv(fastCommandTimeoutEnv); ok { + parsed, err := time.ParseDuration(userTimeout) + if err != nil { + fastCommandTimeoutData.err = errors.Wrapf(err, "parsing timeout duration from environment variable %s", fastCommandTimeoutEnv) + } else { + fastCommandTimeoutData.timeout = parsed + } + } + }) + + return fastCommandTimeoutData.timeout, fastCommandTimeoutData.err +} diff --git a/internal/batches/docker/image.go b/internal/batches/docker/image.go index ef06fb0add..90fb7e3d89 100644 --- a/internal/batches/docker/image.go +++ b/internal/batches/docker/image.go @@ -4,10 +4,8 @@ import ( "bytes" "context" "fmt" - "os" "strings" "sync" - "time" "github.com/sourcegraph/sourcegraph/lib/errors" @@ -82,21 +80,18 @@ func (image *image) Ensure(ctx context.Context) error { // Desktop VMs running out of memory, whereupon the Linux // kernel's OOM killer sometimes chooses to kill components of // Docker instead of processes within containers. - timeout, err := dockerImageInspectTimeout() + dctx, cancel, err := withFastCommandContext(ctx) if err != nil { return "", err } - dctx, cancel := context.WithTimeout(ctx, timeout) defer cancel() - out, err := exec.CommandContext(dctx, "docker", "image", "inspect", "--format", "{{ .Id }}", image.name).CombinedOutput() + args := []string{"image", "inspect", "--format", "{{ .Id }}", image.name} + out, err := exec.CommandContext(dctx, "docker", args...).CombinedOutput() id := string(bytes.TrimSpace(out)) - if errors.Is(errors.Cause(err), context.DeadlineExceeded) { - return "", &dockerImageInspectTimeoutError{ - image: image.name, - timeout: timeout, - } + if errors.IsDeadlineExceeded(err) || errors.IsDeadlineExceeded(dctx.Err()) { + return "", newFastCommandTimeoutError(dctx, args...) } else if err != nil { return "", err } @@ -107,7 +102,7 @@ func (image *image) Ensure(ctx context.Context) error { // docker image inspect will return a non-zero exit code if the image and // tag don't exist locally, regardless of the format. var digest string - if digest, err = inspectDigest(); errors.HasType(err, &dockerImageInspectTimeoutError{}) { + if digest, err = inspectDigest(); errors.HasType(err, &fastCommandTimeoutError{}) { // Ensure we immediately propagate a timeout up, rather than // trying to tell an unresponsive Docker to pull. return err @@ -176,50 +171,3 @@ func (image *image) UIDGID(ctx context.Context) (UIDGID, error) { return image.uidGid, image.uidGidErr } - -const ( - dockerImageInspectTimeoutDefault = 5 * time.Second - dockerImageInspectTimeoutEnv = "SRC_DOCKER_IMAGE_INSPECT_TIMEOUT" -) - -var dockerImageInspectTimeoutData = struct { - once sync.Once - timeout time.Duration - err error -}{ - timeout: dockerImageInspectTimeoutDefault, - err: nil, -} - -// dockerImageInspectTimeout returns a timeout appropriate for invoking `docker -// image inspect`. This defaults to 5 seconds, but can be overridden by the -// undocumented $SRC_DOCKER_IMAGE_INSPECT_TIMEOUT environment variable. -func dockerImageInspectTimeout() (time.Duration, error) { - dockerImageInspectTimeoutData.once.Do(func() { - if userTimeout, ok := os.LookupEnv(dockerImageInspectTimeoutEnv); ok { - parsed, err := time.ParseDuration(userTimeout) - if err != nil { - dockerImageInspectTimeoutData.err = errors.Wrapf(err, "parsing timeout duration from environment variable %s", dockerImageInspectTimeoutEnv) - } else { - dockerImageInspectTimeoutData.timeout = parsed - } - } - }) - - return dockerImageInspectTimeoutData.timeout, dockerImageInspectTimeoutData.err -} - -type dockerImageInspectTimeoutError struct { - image string - timeout time.Duration -} - -var _ error = &dockerImageInspectTimeoutError{} - -func (e *dockerImageInspectTimeoutError) Error() string { - return fmt.Sprintf( - "`docker image inspect --format '{{ .Id }}' %s` failed to respond within %s; "+ - "please verify that Docker has been started and is responding normally", - e.image, e.timeout, - ) -} diff --git a/internal/batches/docker/image_test.go b/internal/batches/docker/image_test.go index e7c8300271..13daa76c96 100644 --- a/internal/batches/docker/image_test.go +++ b/internal/batches/docker/image_test.go @@ -94,10 +94,10 @@ func TestImage_Digest(t *testing.T) { digest, err := image.Digest(ctx) assert.Empty(t, digest) - as := &dockerImageInspectTimeoutError{} + as := &fastCommandTimeoutError{} assert.ErrorAs(t, err, &as) - assert.Equal(t, "foo", as.image) - assert.Equal(t, dockerImageInspectTimeoutDefault, as.timeout) + assert.Equal(t, "foo", as.args[len(as.args)-1]) + assert.Equal(t, fastCommandTimeoutDefault, as.timeout) }) } diff --git a/internal/batches/docker/info.go b/internal/batches/docker/info.go new file mode 100644 index 0000000000..346163badf --- /dev/null +++ b/internal/batches/docker/info.go @@ -0,0 +1,35 @@ +package docker + +import ( + "bytes" + "context" + "strconv" + + "github.com/sourcegraph/sourcegraph/lib/errors" + + "github.com/sourcegraph/src-cli/internal/exec" +) + +// NCPU returns the number of CPU cores available to Docker. +func NCPU(ctx context.Context) (int, error) { + dctx, cancel, err := withFastCommandContext(ctx) + if err != nil { + return 0, err + } + defer cancel() + + args := []string{"info", "--format", "{{ .NCPU }}"} + out, err := exec.CommandContext(dctx, "docker", args...).CombinedOutput() + if errors.IsDeadlineExceeded(err) || errors.IsDeadlineExceeded(dctx.Err()) { + return 0, newFastCommandTimeoutError(dctx, args...) + } else if err != nil { + return 0, err + } + + dcpu, err := strconv.Atoi(string(bytes.TrimSpace(out))) + if err != nil { + return 0, errors.Wrap(err, "parsing docker cpu count") + } + + return dcpu, nil +} diff --git a/internal/batches/docker/info_test.go b/internal/batches/docker/info_test.go new file mode 100644 index 0000000000..ebc07e89ca --- /dev/null +++ b/internal/batches/docker/info_test.go @@ -0,0 +1,76 @@ +package docker + +import ( + "context" + "fmt" + "testing" + "time" + + "github.com/stretchr/testify/assert" + + "github.com/sourcegraph/src-cli/internal/exec/expect" +) + +func Test_NCPU(t *testing.T) { + ctx := context.Background() + + t.Run("docker fails", func(t *testing.T) { + expect.Commands(t, infoFailure()) + + ncpu, err := NCPU(ctx) + assert.Zero(t, ncpu) + assert.Error(t, err) + }) + + t.Run("docker times out", func(t *testing.T) { + tctx, cancel := context.WithTimeout(ctx, -1*time.Second) + t.Cleanup(cancel) + + expect.Commands(t, infoSuccess("4")) + + ncpu, err := NCPU(tctx) + assert.Zero(t, ncpu) + var terr *fastCommandTimeoutError + assert.ErrorAs(t, err, &terr) + assert.Equal(t, []string{"info", "--format", "{{ .NCPU }}"}, terr.args) + assert.Equal(t, fastCommandTimeoutDefault, terr.timeout) + }) + + t.Run("docker succeeds, but returns nothing", func(t *testing.T) { + expect.Commands(t, infoSuccess("")) + + ncpu, err := NCPU(ctx) + assert.Zero(t, ncpu) + assert.Error(t, err) + }) + + t.Run("docker succeeds, but returns something invalid", func(t *testing.T) { + expect.Commands(t, infoSuccess("foo")) + + ncpu, err := NCPU(ctx) + assert.Zero(t, ncpu) + assert.Error(t, err) + }) + + t.Run("docker succeeds", func(t *testing.T) { + expect.Commands(t, infoSuccess("4")) + + ncpu, err := NCPU(ctx) + assert.Equal(t, 4, ncpu) + assert.NoError(t, err) + }) +} + +func infoSuccess(ncpu string) *expect.Expectation { + return expect.NewLiteral( + expect.Behaviour{Stdout: []byte(fmt.Sprintf("%s\n", ncpu))}, + "docker", "info", "--format", "{{ .NCPU }}", + ) +} + +func infoFailure() *expect.Expectation { + return expect.NewLiteral( + expect.Behaviour{ExitCode: 1}, + "docker", "info", "--format", "{{ .NCPU }}", + ) +} diff --git a/internal/exec/expect/expect.go b/internal/exec/expect/expect.go index bcd04477fe..b7ca6b5f4a 100644 --- a/internal/exec/expect/expect.go +++ b/internal/exec/expect/expect.go @@ -212,3 +212,27 @@ func NewGlobValidator(wantName string, wantArg ...string) CommandValidator { return errs } } + +// NewLiteral is a convenience function that creates an Expectation that +// validates commands literally. +// +// You don't need to use this, but it tends to make Commands() calls more +// readable. +func NewLiteral(behaviour Behaviour, wantName string, wantArg ...string) *Expectation { + return &Expectation{ + Behaviour: behaviour, + Validator: func(haveName string, haveArg ...string) error { + var errs errors.MultiError + + if wantName != haveName { + errs = errors.Append(errs, errors.Errorf("name does not match: have=%q want=%q", haveName, wantName)) + } + + if diff := cmp.Diff(haveArg, wantArg); diff != "" { + errs = errors.Append(errs, errors.Errorf("arguments do not match (-have +want):\n%s", diff)) + } + + return errs + }, + } +} From 96335e5603d8fc8fe169d7e77596fc68709a7699 Mon Sep 17 00:00:00 2001 From: Bolaji Olajide <25608335+BolajiOlajide@users.noreply.github.com> Date: Fri, 17 Jun 2022 01:33:58 +0100 Subject: [PATCH 196/647] batches: upsert batch change when running `src batch remote (#787) * upsert batch change when running `src batch remote * use batchChangeName for execution url * update changelog * add createBatchSpecFromRaw query * Update CHANGELOG.md Co-authored-by: Adam Harvey * remove redundant UpsertBatchSpecInput method Co-authored-by: Adam Harvey --- CHANGELOG.md | 2 ++ cmd/src/batch_remote.go | 11 ++++-- internal/batches/service/remote.go | 55 +++++++++++++++++++++++++----- internal/batches/ui/tui.go | 8 +++++ 4 files changed, 66 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fac7567786..a9d1946946 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,8 @@ All notable changes to `src-cli` are documented in this file. ### Fixed +- The preview link shown when running `src batch remote` to create a new batch change no longer 404s. [sourcegraph/src-cli](https://github.com/sourcegraph/src-cli/pull/787) + ### Removed ## 3.40.11 diff --git a/cmd/src/batch_remote.go b/cmd/src/batch_remote.go index 9384f32bfd..9d542ae9b5 100644 --- a/cmd/src/batch_remote.go +++ b/cmd/src/batch_remote.go @@ -78,8 +78,15 @@ Examples: } ui.ResolvingNamespaceSuccess(namespace.ID) + ui.SendingBatchChange() + batchChangeName, err := svc.UpsertBatchChange(ctx, spec.Name, namespace.ID) + if err != nil { + return err + } + ui.SendingBatchChangeSuccess() + ui.SendingBatchSpec() - batchSpecID, err := svc.UpsertBatchSpecInput( + batchSpecID, err := svc.CreateBatchSpecFromRaw( ctx, raw, namespace.ID, @@ -125,7 +132,7 @@ Examples: "%s/%s/batch-changes/%s/executions/%s", strings.TrimSuffix(cfg.Endpoint, "/"), strings.TrimPrefix(namespace.URL, "/"), - spec.Name, + batchChangeName, batchSpecID, ) ui.RemoteSuccess(executionURL) diff --git a/internal/batches/service/remote.go b/internal/batches/service/remote.go index 2bead9d6bc..dc63a47daf 100644 --- a/internal/batches/service/remote.go +++ b/internal/batches/service/remote.go @@ -15,15 +15,54 @@ func (svc *Service) areServerSideBatchChangesSupported() error { return nil } -const upsertBatchSpecInputQuery = ` -mutation UpsertBatchSpecInput( +const upsertEmptyBatchChangeQuery = ` +mutation UpsertEmptyBatchChange( + $name: String! + $namespace: ID! +) { + upsertEmptyBatchChange( + name: $name, + namespace: $namespace + ) { + name + } +} +` + +func (svc *Service) UpsertBatchChange( + ctx context.Context, + name string, + namespaceID string, +) (string, error) { + if err := svc.areServerSideBatchChangesSupported(); err != nil { + return "", err + } + + var resp struct { + UpsertEmptyBatchChange struct { + Name string `json:"name"` + } `json:"upsertEmptyBatchChange"` + } + + if ok, err := svc.client.NewRequest(upsertEmptyBatchChangeQuery, map[string]interface{}{ + "name": name, + "namespace": namespaceID, + }).Do(ctx, &resp); err != nil || !ok { + return "", err + } + + return resp.UpsertEmptyBatchChange.Name, nil +} + +const createBatchSpecFromRawQuery = ` +mutation CreateBatchSpecFromRaw( $batchSpec: String!, $namespace: ID!, $allowIgnored: Boolean!, $allowUnsupported: Boolean!, $noCache: Boolean!, ) { - upsertBatchSpecInput( + createBatchSpecFromRaw( batchSpec: $batchSpec, namespace: $namespace, allowIgnored: $allowIgnored, @@ -35,7 +74,7 @@ mutation UpsertBatchSpecInput( } ` -func (svc *Service) UpsertBatchSpecInput( +func (svc *Service) CreateBatchSpecFromRaw( ctx context.Context, batchSpec string, namespaceID string, @@ -48,12 +87,12 @@ func (svc *Service) UpsertBatchSpecInput( } var resp struct { - UpsertBatchSpecInput struct { + CreateBatchSpecFromRaw struct { ID string `json:"id"` - } `json:"upsertBatchSpecInput"` + } `json:"createBatchSpecFromRaw"` } - if ok, err := svc.client.NewRequest(upsertBatchSpecInputQuery, map[string]interface{}{ + if ok, err := svc.client.NewRequest(createBatchSpecFromRawQuery, map[string]interface{}{ "batchSpec": batchSpec, "namespace": namespaceID, "allowIgnored": allowIgnored, @@ -63,7 +102,7 @@ func (svc *Service) UpsertBatchSpecInput( return "", err } - return resp.UpsertBatchSpecInput.ID, nil + return resp.CreateBatchSpecFromRaw.ID, nil } const executeBatchSpecQuery = ` diff --git a/internal/batches/ui/tui.go b/internal/batches/ui/tui.go index 2b001d893b..f146ab77fc 100644 --- a/internal/batches/ui/tui.go +++ b/internal/batches/ui/tui.go @@ -223,6 +223,14 @@ func (ui *TUI) ApplyingBatchSpecSuccess(batchChangeURL string) { block.Writef("%s", batchChangeURL) } +func (ui *TUI) SendingBatchChange() { + ui.pending = batchCreatePending(ui.Out, "Sending batch change") +} + +func (ui *TUI) SendingBatchChangeSuccess() { + batchCompletePending(ui.pending, "Sending batch change") +} + func (ui *TUI) SendingBatchSpec() { ui.pending = batchCreatePending(ui.Out, "Sending batch spec") } From 9689dc75589dad49a143b49f5cca05f96a61d2d5 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Fri, 17 Jun 2022 13:43:50 +0200 Subject: [PATCH 197/647] Prepare changelog for 3.41.0 (#792) --- CHANGELOG.md | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a9d1946946..e44f6e02f9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,13 +15,20 @@ All notable changes to `src-cli` are documented in this file. ### Changed +### Fixed + +### Removed + +## 3.41.0 + +### Changed + - The default parallelism of `src batch preview` and `src batch apply` are now based on the number of CPU cores available to Docker, rather than the host system running `src`. This can be overridden [with the `-j` flag](https://docs.sourcegraph.com/cli/references/batch/preview). [#786](https://github.com/sourcegraph/src-cli/pull/786) ### Fixed - The preview link shown when running `src batch remote` to create a new batch change no longer 404s. [sourcegraph/src-cli](https://github.com/sourcegraph/src-cli/pull/787) -### Removed ## 3.40.11 From 075559914c9a140a28069a6bc16507779a2d25d7 Mon Sep 17 00:00:00 2001 From: Randell Callahan Date: Wed, 29 Jun 2022 08:47:11 -0600 Subject: [PATCH 198/647] batches: Cache filesystem mount (#795) --- CHANGELOG.md | 2 + cmd/src/batch_common.go | 14 +- cmd/src/batch_exec.go | 2 +- go.mod | 6 +- go.sum | 12 +- internal/batches/executor/coordinator.go | 51 ++---- internal/batches/executor/coordinator_test.go | 4 +- internal/batches/executor/executor.go | 16 +- internal/batches/executor/run_steps.go | 4 +- internal/batches/executor/task.go | 70 +++++++- internal/batches/executor/task_test.go | 151 ++++++++++++++++++ 11 files changed, 268 insertions(+), 64 deletions(-) create mode 100644 internal/batches/executor/task_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index e44f6e02f9..742cbb8881 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,8 @@ All notable changes to `src-cli` are documented in this file. ### Added +- Batch specs that mount paths now cache results. [sourcegraph/sourcegraph#37216](https://github.com/sourcegraph/sourcegraph/issues/37216) + ### Changed ### Fixed diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index 6a78d8f296..7b0a9004c5 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -366,13 +366,13 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp archiveRegistry, log.NewDiskManager(opts.flags.tempDir, opts.flags.keepLogs), executor.NewCoordinatorOpts{ - Creator: workspaceCreator, - Cache: executor.NewDiskCache(opts.flags.cacheDir), - Parallelism: parallelism, - Timeout: opts.flags.timeout, - TempDir: opts.flags.tempDir, - GlobalEnv: os.Environ(), - AllowPathMounts: true, + Creator: workspaceCreator, + Cache: executor.NewDiskCache(opts.flags.cacheDir), + Parallelism: parallelism, + Timeout: opts.flags.timeout, + TempDir: opts.flags.tempDir, + GlobalEnv: os.Environ(), + IsRemote: false, }, ) diff --git a/cmd/src/batch_exec.go b/cmd/src/batch_exec.go index e6fa093a8d..987218faa2 100644 --- a/cmd/src/batch_exec.go +++ b/cmd/src/batch_exec.go @@ -224,7 +224,7 @@ func executeBatchSpecInWorkspaces(ctx context.Context, flags *executorModeFlags) // Don't allow to read from env. GlobalEnv: []string{}, // Temporarily prevent the ability to sending a batch spec with a mount for server-side processing. - AllowPathMounts: false, + IsRemote: true, }, ) diff --git a/go.mod b/go.mod index 23d89a1857..a228054985 100644 --- a/go.mod +++ b/go.mod @@ -20,7 +20,7 @@ require ( github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf github.com/sourcegraph/scip v0.1.0 - github.com/sourcegraph/sourcegraph/lib v0.0.0-20220614233452-81dc06f6e96e + github.com/sourcegraph/sourcegraph/lib v0.0.0-20220624142708-f2b0579b57ff github.com/stretchr/testify v1.7.2 golang.org/x/net v0.0.0-20220526153639-5463443f8c37 golang.org/x/sync v0.0.0-20210220032951-036812b2e83c @@ -83,7 +83,7 @@ require ( github.com/rivo/uniseg v0.2.0 // indirect github.com/rogpeppe/go-internal v1.8.1 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect - github.com/sourcegraph/log v0.0.0-20220613150728-bb50c87ba841 // indirect + github.com/sourcegraph/log v0.0.0-20220621231153-3bee7082c87e // indirect github.com/spf13/cobra v1.4.0 // indirect github.com/spf13/pflag v1.0.5 // indirect github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect @@ -98,7 +98,7 @@ require ( go.uber.org/zap v1.21.0 // indirect golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 // indirect golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 // indirect - golang.org/x/sys v0.0.0-20220614162138-6c1b26c55098 // indirect + golang.org/x/sys v0.0.0-20220622161953-175b2fd9d664 // indirect golang.org/x/term v0.0.0-20220411215600-e5f449aeb171 // indirect golang.org/x/text v0.3.7 // indirect golang.org/x/tools v0.1.11 // indirect diff --git a/go.sum b/go.sum index 88cee68e52..770f566b9c 100644 --- a/go.sum +++ b/go.sum @@ -347,12 +347,12 @@ github.com/sourcegraph/go-diff v0.6.1 h1:hmA1LzxW0n1c3Q4YbrFgg4P99GSnebYa3x8gr0H github.com/sourcegraph/go-diff v0.6.1/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= -github.com/sourcegraph/log v0.0.0-20220613150728-bb50c87ba841 h1:kiYxuyQ1zSNA4YPtVVJQAFw5ZRNaFRkFqgKyEJQTzhg= -github.com/sourcegraph/log v0.0.0-20220613150728-bb50c87ba841/go.mod h1:A+9F6IicYvBbl2aT0R81lMraKcXjVfdfw352yPe2yJI= +github.com/sourcegraph/log v0.0.0-20220621231153-3bee7082c87e h1:7MnFFZ85BBwLNDkrQJB503/znGuSoLirDLFWRcLqHlM= +github.com/sourcegraph/log v0.0.0-20220621231153-3bee7082c87e/go.mod h1:A+9F6IicYvBbl2aT0R81lMraKcXjVfdfw352yPe2yJI= github.com/sourcegraph/scip v0.1.0 h1:kTs0CJaLQvcRZjg+HpGrcJPNX2Tx31+d6szWio3ZOkQ= github.com/sourcegraph/scip v0.1.0/go.mod h1:/AZ8RvsnRfeCZy232PJuVZqcl9f82fJnYwdWZeU2JCo= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20220614233452-81dc06f6e96e h1:O+XG50CIAdzjuELX2gHhkc9Br1AaAXaOkZWg1YSRFpQ= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20220614233452-81dc06f6e96e/go.mod h1:Orrt+5wdseAvxsVxgdswYPzJgVkTk0rLlmFHZW61epo= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20220624142708-f2b0579b57ff h1:lcDmWfcg43tON2jMtpxtEq61wMF6rIgvbx7KfTKA6TU= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20220624142708-f2b0579b57ff/go.mod h1:ppU4qV7WAmfjEoQhM7P1hCDWmv1Q6lIy5mT9o3Pj5t8= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= @@ -503,8 +503,8 @@ golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211007075335-d3039528d8ac/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220614162138-6c1b26c55098 h1:PgOr27OhUx2IRqGJ2RxAWI4dJQ7bi9cSrB82uzFzfUA= -golang.org/x/sys v0.0.0-20220614162138-6c1b26c55098/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220622161953-175b2fd9d664 h1:wEZYwx+kK+KlZ0hpvP2Ls1Xr4+RWnlzGFwPP0aiDjIU= +golang.org/x/sys v0.0.0-20220622161953-175b2fd9d664/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20220411215600-e5f449aeb171 h1:EH1Deb8WZJ0xc0WK//leUHXcX9aLE5SymusoTmMZye8= golang.org/x/term v0.0.0-20220411215600-e5f449aeb171/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= diff --git a/internal/batches/executor/coordinator.go b/internal/batches/executor/coordinator.go index a81e91b8db..4b1d8f0bf1 100644 --- a/internal/batches/executor/coordinator.go +++ b/internal/batches/executor/coordinator.go @@ -49,10 +49,10 @@ type NewCoordinatorOpts struct { // Used by batcheslib.BuildChangesetSpecs Features batches.FeatureFlags - Parallelism int - Timeout time.Duration - TempDir string - AllowPathMounts bool + Parallelism int + Timeout time.Duration + TempDir string + IsRemote bool } func NewCoordinator(opts NewCoordinatorOpts, logger log.LogManager) *Coordinator { @@ -62,19 +62,13 @@ func NewCoordinator(opts NewCoordinatorOpts, logger log.LogManager) *Coordinator Creator: opts.Creator, Logger: logger, - Parallelism: opts.Parallelism, - Timeout: opts.Timeout, - TempDir: opts.TempDir, - AllowPathMounts: opts.AllowPathMounts, - GlobalEnv: opts.GlobalEnv, + Parallelism: opts.Parallelism, + Timeout: opts.Timeout, + TempDir: opts.TempDir, + IsRemote: opts.IsRemote, + GlobalEnv: opts.GlobalEnv, WriteStepCacheResult: func(ctx context.Context, stepResult execution.AfterStepResult, task *Task) error { - // Temporarily skip writing to the cache if a mount is present - for _, step := range task.Steps { - if len(step.Mount) > 0 { - return nil - } - } - cacheKey := task.cacheKey(opts.GlobalEnv) + cacheKey := task.cacheKey(opts.GlobalEnv, opts.IsRemote) return writeToCache(ctx, opts.Cache, stepResult, task, cacheKey) }, }) @@ -121,7 +115,7 @@ func (c *Coordinator) CheckStepResultsCache(ctx context.Context, tasks []*Task, func (c *Coordinator) ClearCache(ctx context.Context, tasks []*Task) error { for _, task := range tasks { - cacheKey := task.cacheKey(c.opts.GlobalEnv) + cacheKey := task.cacheKey(c.opts.GlobalEnv, c.opts.IsRemote) if err := c.cache.Clear(ctx, cacheKey); err != nil { return errors.Wrapf(err, "clearing cache for %q", task.Repository.Name) } @@ -137,7 +131,7 @@ func (c *Coordinator) ClearCache(ctx context.Context, tasks []*Task) error { func (c *Coordinator) checkCacheForTask(ctx context.Context, batchSpec *batcheslib.BatchSpec, task *Task) (specs []*batcheslib.ChangesetSpec, found bool, err error) { // Check if the task is cached. - cacheKey := task.cacheKey(c.opts.GlobalEnv) + cacheKey := task.cacheKey(c.opts.GlobalEnv, c.opts.IsRemote) var result execution.Result result, found, err = c.cache.Get(ctx, cacheKey) @@ -201,7 +195,7 @@ func (c Coordinator) buildChangesetSpecs(task *Task, batchSpec *batcheslib.Batch func (c *Coordinator) loadCachedStepResults(ctx context.Context, task *Task, globalEnv []string) error { // We start at the back so that we can find the _last_ cached step, // then restart execution on the following step. - taskKey := task.cacheKey(globalEnv) + taskKey := task.cacheKey(globalEnv, c.opts.IsRemote) for i := len(task.Steps) - 1; i > -1; i-- { key := cacheKeyForStep(taskKey, i) @@ -230,9 +224,9 @@ func writeToCache(ctx context.Context, cache cache.Cache, stepResult execution.A return nil } -func (c *Coordinator) writeExecutionCacheResult(ctx context.Context, taskResult taskResult, ui TaskExecutionUI) error { +func (c *Coordinator) writeExecutionCacheResult(ctx context.Context, taskResult taskResult) error { // Add to the cache, even if no diff was produced. - cacheKey := taskResult.task.cacheKey(c.opts.GlobalEnv) + cacheKey := taskResult.task.cacheKey(c.opts.GlobalEnv, c.opts.IsRemote) if err := c.cache.Set(ctx, cacheKey, taskResult.result); err != nil { return errors.Wrapf(err, "caching result for %q", taskResult.task.Repository.Name) } @@ -241,18 +235,7 @@ func (c *Coordinator) writeExecutionCacheResult(ctx context.Context, taskResult } func (c *Coordinator) writeCacheAndBuildSpecs(ctx context.Context, batchSpec *batcheslib.BatchSpec, taskResult taskResult, ui TaskExecutionUI) ([]*batcheslib.ChangesetSpec, error) { - // Temporarily prevent writing to the cache when running a spec with a mount. Caching does not at the moment "know" - // when a file that is being mounted has changed. This causes the execution not to re-run if a mounted file changes. - hasMount := false - for _, step := range batchSpec.Steps { - if len(step.Mount) > 0 { - hasMount = true - break - } - } - if !hasMount { - c.writeExecutionCacheResult(ctx, taskResult, ui) - } + c.writeExecutionCacheResult(ctx, taskResult) // If the steps didn't result in any diff, we don't need to create a // changeset spec that's displayed to the user and send to the server. @@ -276,7 +259,7 @@ func (c *Coordinator) Execute(ctx context.Context, tasks []*Task, ui TaskExecuti // Write results to cache. for _, taskResult := range results { - if cacheErr := c.writeExecutionCacheResult(ctx, taskResult, ui); cacheErr != nil { + if cacheErr := c.writeExecutionCacheResult(ctx, taskResult); cacheErr != nil { return cacheErr } } diff --git a/internal/batches/executor/coordinator_test.go b/internal/batches/executor/coordinator_test.go index 20c414a79a..d4246a0160 100644 --- a/internal/batches/executor/coordinator_test.go +++ b/internal/batches/executor/coordinator_test.go @@ -226,7 +226,7 @@ func TestCoordinator_Execute(t *testing.T) { }, }, { - name: "skip cache for step mount", + name: "cache for step mount", tasks: []*Task{srcCLITask, sourcegraphTask}, @@ -250,7 +250,7 @@ func TestCoordinator_Execute(t *testing.T) { }, opts: NewCoordinatorOpts{Features: featuresAllEnabled()}, - wantCacheEntries: 0, + wantCacheEntries: 2, wantSpecs: []*batcheslib.ChangesetSpec{ buildSpecFor(testRepo1, func(spec *batcheslib.ChangesetSpec) { spec.Commits[0].Diff = `dummydiff1` diff --git a/internal/batches/executor/executor.go b/internal/batches/executor/executor.go index 5c65234a95..07e7a09d5d 100644 --- a/internal/batches/executor/executor.go +++ b/internal/batches/executor/executor.go @@ -63,7 +63,7 @@ type newExecutorOpts struct { Parallelism int Timeout time.Duration TempDir string - AllowPathMounts bool + IsRemote bool GlobalEnv []string WriteStepCacheResult func(ctx context.Context, stepResult execution.AfterStepResult, task *Task) error } @@ -175,13 +175,13 @@ func (x *executor) do(ctx context.Context, task *Task, ui TaskExecutionUI) (err // Actually execute the steps. opts := &executionOpts{ - task: task, - logger: l, - wc: x.opts.Creator, - ensureImage: x.opts.EnsureImage, - tempDir: x.opts.TempDir, - allowPathMounts: x.opts.AllowPathMounts, - globalEnv: x.opts.GlobalEnv, + task: task, + logger: l, + wc: x.opts.Creator, + ensureImage: x.opts.EnsureImage, + tempDir: x.opts.TempDir, + isRemote: x.opts.IsRemote, + globalEnv: x.opts.GlobalEnv, ui: ui.StepsExecutionUI(task), writeStepCacheResult: x.opts.WriteStepCacheResult, diff --git a/internal/batches/executor/run_steps.go b/internal/batches/executor/run_steps.go index 8a12a7ecc5..fb97610dfe 100644 --- a/internal/batches/executor/run_steps.go +++ b/internal/batches/executor/run_steps.go @@ -38,7 +38,7 @@ type executionOpts struct { ui StepsExecutionUI - allowPathMounts bool + isRemote bool globalEnv []string @@ -309,7 +309,7 @@ func executeSingleStep( } // Temporarily add a guard to prevent a path to mount path for server-side processing - if opts.allowPathMounts { + if !opts.isRemote { // Mount any paths on the local system to the docker container. The paths have already been validated during parsing for _, mount := range step.Mount { args = append(args, "--mount", fmt.Sprintf("type=bind,source=%s,target=%s,ro", mount.Path, mount.Mountpoint)) diff --git a/internal/batches/executor/task.go b/internal/batches/executor/task.go index b08a174a94..adbca3bbca 100644 --- a/internal/batches/executor/task.go +++ b/internal/batches/executor/task.go @@ -1,10 +1,14 @@ package executor import ( + "os" + "path/filepath" + batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/execution" "github.com/sourcegraph/sourcegraph/lib/batches/execution/cache" "github.com/sourcegraph/sourcegraph/lib/batches/template" + "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/batches/graphql" "github.com/sourcegraph/src-cli/internal/batches/repozip" @@ -41,7 +45,12 @@ func (t *Task) ArchivePathToFetch() string { return "" } -func (t *Task) cacheKey(globalEnv []string) *cache.ExecutionKeyWithGlobalEnv { +func (t *Task) cacheKey(globalEnv []string, isRemote bool) *cache.ExecutionKeyWithGlobalEnv { + var metadataRetriever cache.MetadataRetriever + // If the task is being run locally, set the metadata retrieve to use the filesystem based implementation. + if !isRemote { + metadataRetriever = fileMetadataRetriever{} + } return &cache.ExecutionKeyWithGlobalEnv{ GlobalEnv: globalEnv, ExecutionKey: &cache.ExecutionKey{ @@ -56,10 +65,69 @@ func (t *Task) cacheKey(globalEnv []string) *cache.ExecutionKeyWithGlobalEnv { OnlyFetchWorkspace: t.OnlyFetchWorkspace, Steps: t.Steps, BatchChangeAttributes: t.BatchChangeAttributes, + MetadataRetriever: metadataRetriever, }, } } +type fileMetadataRetriever struct { +} + +func (f fileMetadataRetriever) Get(steps []batcheslib.Step) ([]cache.MountMetadata, error) { + var mountsMetadata []cache.MountMetadata + for _, step := range steps { + // Build up the metadata for each mount for each step + for _, mount := range step.Mount { + metadata, err := getMountMetadata(mount.Path) + if err != nil { + return nil, err + } + // A mount could be a directory containing multiple files + mountsMetadata = append(mountsMetadata, metadata...) + } + } + return mountsMetadata, nil +} + +func getMountMetadata(path string) ([]cache.MountMetadata, error) { + info, err := os.Stat(path) + if errors.Is(err, os.ErrNotExist) { + return nil, errors.Newf("path %s does not exist", path) + } else if err != nil { + return nil, err + } + var metadata []cache.MountMetadata + if info.IsDir() { + dirMetadata, err := getDirectoryMountMetadata(path) + if err != nil { + return nil, err + } + metadata = append(metadata, dirMetadata...) + } else { + metadata = append(metadata, cache.MountMetadata{Path: path, Size: info.Size(), Modified: info.ModTime().UTC()}) + } + return metadata, nil +} + +func getDirectoryMountMetadata(path string) ([]cache.MountMetadata, error) { + dir, err := os.ReadDir(path) + if err != nil { + return nil, err + } + var metadata []cache.MountMetadata + for _, dirEntry := range dir { + newPath := filepath.Join(path, dirEntry.Name()) + // Go back to the very start. Need to get the FileInfo again for the new path and figure out if it is a + // directory or a file. + fileMetadata, err := getMountMetadata(newPath) + if err != nil { + return nil, err + } + metadata = append(metadata, fileMetadata...) + } + return metadata, nil +} + func cacheKeyForStep(key *cache.ExecutionKeyWithGlobalEnv, stepIndex int) *cache.StepsCacheKeyWithGlobalEnv { return &cache.StepsCacheKeyWithGlobalEnv{ StepsCacheKey: &cache.StepsCacheKey{ diff --git a/internal/batches/executor/task_test.go b/internal/batches/executor/task_test.go new file mode 100644 index 0000000000..423eff5fc7 --- /dev/null +++ b/internal/batches/executor/task_test.go @@ -0,0 +1,151 @@ +package executor + +import ( + "os" + "path/filepath" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/sourcegraph/sourcegraph/lib/batches" + "github.com/sourcegraph/sourcegraph/lib/batches/execution/cache" + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +func TestFileMetadataRetriever_Get(t *testing.T) { + // TODO: use TempDir when https://github.com/golang/go/issues/51442 is cherry-picked into 1.18 or upgrade to 1.19+ + //tempDir := t.TempDir() + tempDir, err := os.MkdirTemp("", "metadata") + require.NoError(t, err) + t.Cleanup(func() { + os.RemoveAll(tempDir) + }) + + // Set a specific date on the temp files + modDate := time.Date(2022, 1, 2, 3, 5, 6, 0, time.UTC) + + // create temp files/dirs that can be used by the tests + sampleScriptPath := filepath.Join(tempDir, "sample.sh") + _, err = os.Create(sampleScriptPath) + require.NoError(t, err) + err = os.Chtimes(sampleScriptPath, modDate, modDate) + require.NoError(t, err) + + anotherScriptPath := filepath.Join(tempDir, "another.sh") + _, err = os.Create(anotherScriptPath) + require.NoError(t, err) + err = os.Chtimes(anotherScriptPath, modDate, modDate) + require.NoError(t, err) + + retriever := fileMetadataRetriever{} + + tests := []struct { + name string + steps []batches.Step + expectedMetadata []cache.MountMetadata + expectedError error + }{ + { + name: "simple file", + steps: []batches.Step{ + { + Run: "foo", + Mount: []batches.Mount{{ + Path: sampleScriptPath, + Mountpoint: "/tmp/foo.sh", + }}, + }, + }, + expectedMetadata: []cache.MountMetadata{ + {Path: sampleScriptPath, Size: 0, Modified: modDate}, + }, + }, + { + name: "multiple files", + steps: []batches.Step{ + { + Run: "foo", + Mount: []batches.Mount{ + { + Path: sampleScriptPath, + Mountpoint: "/tmp/foo.sh", + }, + { + Path: anotherScriptPath, + Mountpoint: "/tmp/bar.sh", + }, + }, + }, + }, + expectedMetadata: []cache.MountMetadata{ + {Path: sampleScriptPath, Size: 0, Modified: modDate}, + {Path: anotherScriptPath, Size: 0, Modified: modDate}, + }, + }, + { + name: "directory", + steps: []batches.Step{ + { + Run: "foo", + Mount: []batches.Mount{{ + Path: tempDir, + Mountpoint: "/tmp/scripts", + }}, + }, + }, + expectedMetadata: []cache.MountMetadata{ + {Path: anotherScriptPath, Size: 0, Modified: modDate}, + {Path: sampleScriptPath, Size: 0, Modified: modDate}, + }, + }, + { + name: "file does not exist", + steps: []batches.Step{ + { + Run: "foo", + Mount: []batches.Mount{{ + Path: filepath.Join(tempDir, "some-file-does-not-exist.sh"), + Mountpoint: "/tmp/file.sh", + }}, + }, + }, + expectedError: errors.Newf("path %s does not exist", filepath.Join(tempDir, "some-file-does-not-exist.sh")), + }, + { + name: "multiple steps", + steps: []batches.Step{ + { + Run: "foo", + Mount: []batches.Mount{{ + Path: sampleScriptPath, + Mountpoint: "/tmp/foo.sh", + }}, + }, + { + Run: "foo", + Mount: []batches.Mount{{ + Path: sampleScriptPath, + Mountpoint: "/tmp/foo.sh", + }}, + }, + }, + expectedMetadata: []cache.MountMetadata{ + {Path: sampleScriptPath, Size: 0, Modified: modDate}, + {Path: sampleScriptPath, Size: 0, Modified: modDate}, + }, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + metadata, err := retriever.Get(test.steps) + if test.expectedError != nil { + assert.Equal(t, test.expectedError.Error(), err.Error()) + } else { + assert.NoError(t, err) + assert.Equal(t, test.expectedMetadata, metadata) + } + }) + } +} From 237e58ab4f68eb8eb5b3b70786e4a78b10293ee5 Mon Sep 17 00:00:00 2001 From: Bolaji Olajide <25608335+BolajiOlajide@users.noreply.github.com> Date: Thu, 30 Jun 2022 08:37:01 +0100 Subject: [PATCH 199/647] batches: add SRC_HEADERS for passing multiple custom headers (#796) Co-authored-by: Adam Harvey --- AUTH_PROXY.md | 8 ++++++++ CHANGELOG.md | 1 + cmd/src/headers.go | 37 ++++++++++++++++++++++++++++++++----- cmd/src/headers_test.go | 7 ++++++- cmd/src/login.go | 2 +- cmd/src/login_test.go | 2 +- cmd/src/main_test.go | 20 ++++++++++++++++++-- 7 files changed, 67 insertions(+), 10 deletions(-) diff --git a/AUTH_PROXY.md b/AUTH_PROXY.md index a24470b240..86143bb3cf 100644 --- a/AUTH_PROXY.md +++ b/AUTH_PROXY.md @@ -7,3 +7,11 @@ SRC_HEADER_AUTHORIZATION="Bearer $(curl http://service.internal.corp)" SRC_HEADE ``` In this example, the headers `authorization: Bearer my-generated-token` and `extra: metadata` will be threaded to all HTTP requests to your instance. Multiple such headers can be supplied. + +An alternative to the above when passing in multiple headers or headers with dashes is to make use of the `SRC_HEADERS` environment variable as follow: + +```sh +SRC_HEADERS="AUTHORIZATION:Bearer somerandom_string\nClient-ID:client-one\nextra:metadata" +``` + +Note: The different header keys and values need to separated by a new line ("\n"). In the above example, the headers `authorization: Bearer somerandom_string`, `client-id: client-one` and `extra: metadata` will be threaded to all HTTP requests to your instance. diff --git a/CHANGELOG.md b/CHANGELOG.md index 742cbb8881..161fede045 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ All notable changes to `src-cli` are documented in this file. ### Added - Batch specs that mount paths now cache results. [sourcegraph/sourcegraph#37216](https://github.com/sourcegraph/sourcegraph/issues/37216) +- `SRC_HEADERS="key:value\nkey2:value2"` is now supported for passing multiple headers when authenticating `src` with custom auth proxies. See [auth proxy configuration docs](AUTH_PROXY.md) for more information. [#796](https://github.com/sourcegraph/src-cli/pull/796) ### Changed diff --git a/cmd/src/headers.go b/cmd/src/headers.go index 3c779d662c..98fd26369d 100644 --- a/cmd/src/headers.go +++ b/cmd/src/headers.go @@ -2,20 +2,22 @@ package main import ( "os" + "regexp" "strings" ) -// parseAdditionalHeaders reads the environment for values like SRC_HEADER_NAME=VALUE -// and creates a `{NAME: VALUE}` map. These headers should be applied to each request -// to the Sourcegraph instance, as some private instances require special auth or +// parseAdditionalHeaders reads the environment for values like SRC_HEADER_NAME=VALUE or +// SRC_HEADERS and creates a `{NAME: VALUE}` map. These headers should be applied to each +// request to the Sourcegraph instance, as some private instances require special auth or // additional proxy values to be passed along with each request. func parseAdditionalHeaders() map[string]string { - return parseAdditionalHeadersFromMap(os.Environ()) + return parseAdditionalHeadersFromEnviron(os.Environ()) } const additionalHeaderPrefix = "SRC_HEADER_" +const additionalHeadersKey = "SRC_HEADERS" -func parseAdditionalHeadersFromMap(environ []string) map[string]string { +func parseAdditionalHeadersFromEnviron(environ []string) map[string]string { additionalHeaders := map[string]string{} for _, value := range environ { parts := strings.SplitN(value, "=", 2) @@ -23,6 +25,31 @@ func parseAdditionalHeadersFromMap(environ []string) map[string]string { continue } + if parts[0] == additionalHeadersKey && parts[1] != "" { + // This regex removes all leading and trailing spaces from the environment variable. We need to do this + // because most shells add quotes to a string when it contains a new line. Tested with `bash, fish & zsh` + // and they all have the same behavior. + re := regexp.MustCompile(`^"|"$`) + headers := re.ReplaceAllString(parts[1], "") + // 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") + + for _, h := range splitHeaders { + p := strings.SplitN(h, ":", 2) + if len(parts) != 2 || p[1] == "" { + continue + } + + key := strings.Trim(strings.ToLower(p[0]), " ") + value := strings.Trim(p[1], " ") + + additionalHeaders[key] = value + } + continue + } + // Ensure we'll have a non-empty key after trimming if !strings.HasPrefix(parts[0], additionalHeaderPrefix) || len(parts[0]) <= len(additionalHeaderPrefix) { continue diff --git a/cmd/src/headers_test.go b/cmd/src/headers_test.go index cca976a918..4674444c93 100644 --- a/cmd/src/headers_test.go +++ b/cmd/src/headers_test.go @@ -18,11 +18,16 @@ func TestParseAdditionalHeaders(t *testing.T) { {environ: []string{"SRC_HEADER_A=foo", "SRC_HEADER_B=bar", "SRC_HEADER_C=baz"}, headers: map[string]string{"a": "foo", "b": "bar", "c": "baz"}}, {environ: []string{"SRC_HEADER_A", "SRC_HEADER_B=", "SRC_HEADER_=baz"}, headers: map[string]string{}}, {environ: []string{"SRC_HEADER_X-Dbx-Auth-Token=foo"}, headers: map[string]string{"x-dbx-auth-token": "foo"}}, + {environ: []string{"SRC_HEADERS=foo:bar\nbar:baz\nAUTHORIZATION:Bearer somerandomstring"}, headers: map[string]string{"foo": "bar", "bar": "baz", "authorization": "Bearer somerandomstring"}}, + {environ: []string{"SRC_HEADERS=foo:bar\nbar:baz\nfoo-bar:baz-bar"}, headers: map[string]string{"foo": "bar", "bar": "baz", "foo-bar": "baz-bar"}}, + {environ: []string{"SRC_HEADERS=\"foo:bar\nbar:baz\nfoo-bar:baz-bar\""}, headers: map[string]string{"foo": "bar", "bar": "baz", "foo-bar": "baz-bar"}}, + {environ: []string{"SRC_HEADERS=foo:bar\nbar:baz\n foo-bar : baz-bar\nb: bar", "SRC_HEADER_A=foo"}, headers: map[string]string{"foo": "bar", "bar": "baz", "foo-bar": "baz-bar", "b": "bar", "a": "foo"}}, + {environ: []string{"SRC_HEADERS", "SRC_HEADER_A=foo"}, headers: map[string]string{"a": "foo"}}, } for _, testCase := range testCases { t.Run(strings.Join(testCase.environ, " "), func(t *testing.T) { - if diff := cmp.Diff(testCase.headers, parseAdditionalHeadersFromMap(testCase.environ)); diff != "" { + if diff := cmp.Diff(testCase.headers, parseAdditionalHeadersFromEnviron(testCase.environ)); diff != "" { t.Errorf("unexpected headers: %s", diff) } }) diff --git a/cmd/src/login.go b/cmd/src/login.go index 82d4168c60..5fec84b593 100644 --- a/cmd/src/login.go +++ b/cmd/src/login.go @@ -110,7 +110,7 @@ func loginCmd(ctx context.Context, cfg *config, client api.Client, endpointArg s printProblem(fmt.Sprintf("Error communicating with %s: %s", endpointArg, err)) } fmt.Fprintln(out, createAccessTokenMessage) - fmt.Fprintln(out, " (If you need to supply custom HTTP request headers, see information about SRC_HEADER_* env vars at https://github.com/sourcegraph/src-cli/blob/main/AUTH_PROXY.md.)") + fmt.Fprintln(out, " (If you need to supply custom HTTP request headers, see information about SRC_HEADER_* and SRC_HEADERS env vars at https://github.com/sourcegraph/src-cli/blob/main/AUTH_PROXY.md.)") return cmderrors.ExitCode1 } diff --git a/cmd/src/login_test.go b/cmd/src/login_test.go index e2b8beeeea..4423d335d8 100644 --- a/cmd/src/login_test.go +++ b/cmd/src/login_test.go @@ -67,7 +67,7 @@ func TestLogin(t *testing.T) { if err != cmderrors.ExitCode1 { t.Fatal(err) } - wantOut := "❌ Problem: Invalid access token.\n\n🛠 To fix: Create an access token at $ENDPOINT/user/settings/tokens, then set the following environment variables:\n\n SRC_ENDPOINT=$ENDPOINT\n SRC_ACCESS_TOKEN=(the access token you just created)\n\n To verify that it's working, run this command again.\n\n (If you need to supply custom HTTP request headers, see information about SRC_HEADER_* env vars at https://github.com/sourcegraph/src-cli/blob/main/AUTH_PROXY.md.)" + wantOut := "❌ Problem: Invalid access token.\n\n🛠 To fix: Create an access token at $ENDPOINT/user/settings/tokens, then set the following environment variables:\n\n SRC_ENDPOINT=$ENDPOINT\n SRC_ACCESS_TOKEN=(the access token you just created)\n\n To verify that it's working, run this command again.\n\n (If you need to supply custom HTTP request headers, see information about SRC_HEADER_* and SRC_HEADERS env vars at https://github.com/sourcegraph/src-cli/blob/main/AUTH_PROXY.md.)" wantOut = strings.ReplaceAll(wantOut, "$ENDPOINT", endpoint) if out != wantOut { t.Errorf("got output %q, want %q", out, wantOut) diff --git a/cmd/src/main_test.go b/cmd/src/main_test.go index dc05e62030..3fe93eb2a5 100644 --- a/cmd/src/main_test.go +++ b/cmd/src/main_test.go @@ -15,6 +15,7 @@ func TestReadConfig(t *testing.T) { fileContents *config envToken string envFooHeader string + envHeaders string envEndpoint string flagEndpoint string want *config @@ -126,9 +127,8 @@ func TestReadConfig(t *testing.T) { AdditionalHeaders: map[string]string{}, }, }, - { - name: "additional header", + name: "additional header (with SRC_HEADER_ prefix)", flagEndpoint: "https://override.com/", envEndpoint: "https://example.com", envToken: "abc", @@ -139,6 +139,18 @@ func TestReadConfig(t *testing.T) { AdditionalHeaders: map[string]string{"foo": "bar"}, }, }, + { + name: "additional headers (with SRC_HEADERS key)", + flagEndpoint: "https://override.com/", + envEndpoint: "https://example.com", + envToken: "abc", + envHeaders: "foo:bar\nfoo-bar:bar-baz", + want: &config{ + Endpoint: "https://override.com", + AccessToken: "abc", + AdditionalHeaders: map[string]string{"foo-bar": "bar-baz", "foo": "bar"}, + }, + }, } for _, test := range tests { @@ -182,6 +194,10 @@ func TestReadConfig(t *testing.T) { t.Fatal(err) } + if err := os.Setenv("SRC_HEADERS", test.envHeaders); err != nil { + t.Fatal(err) + } + config, err := readConfig() if diff := cmp.Diff(test.want, config); diff != "" { t.Errorf("config: %v", diff) From 05e3f0235cbca49200dbba5695049aa8d1ff36e7 Mon Sep 17 00:00:00 2001 From: Robert Lin Date: Wed, 6 Jul 2022 14:25:17 -0700 Subject: [PATCH 200/647] workflows: update pr-auditor workflow (#791) --- .github/workflows/pr-auditor.yml | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/.github/workflows/pr-auditor.yml b/.github/workflows/pr-auditor.yml index 34c7412864..3fe4223315 100644 --- a/.github/workflows/pr-auditor.yml +++ b/.github/workflows/pr-auditor.yml @@ -1,19 +1,20 @@ +# See https://docs.sourcegraph.com/dev/background-information/ci#pr-auditor name: pr-auditor on: - pull_request: - types: [ closed, edited, opened ] + pull_request_target: + types: [ closed, edited, opened, synchronize, ready_for_review ] jobs: - run: + check-pr: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v2 with: { repository: 'sourcegraph/sourcegraph' } - - uses: actions/setup-go@v3 + - uses: actions/setup-go@v2 with: { go-version: '1.18' } - run: ./dev/pr-auditor/check-pr.sh env: GITHUB_EVENT_PATH: ${{ env.GITHUB_EVENT_PATH }} GITHUB_TOKEN: ${{ secrets.CODENOTIFY_GITHUB_TOKEN }} - GITHUB_RUN_URL: https://github.com/sourcegraph/infrastructure/actions/runs/${{ github.run_id }} + GITHUB_RUN_URL: https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }} From ef2ba4df03be8abbaa18dfce136b9403c55d63c2 Mon Sep 17 00:00:00 2001 From: Thorsten Ball Date: Thu, 7 Jul 2022 17:03:47 +0200 Subject: [PATCH 201/647] Cancel reading from stdin on Ctrl-C (#794) * Cancel reading from stdin on Ctrl-C This is essentially a copy-paste implementation of the ideas presented in this comment here: https://github.com/golang/go/issues/20280#issuecomment-655588450 It fixes #775 and helps with the issue described in https://github.com/sourcegraph/src-cli/pull/793#issuecomment-1163310725. Not sure if it has unintended side-effects. * Add comments and remove interface * update changelog Co-authored-by: BolajiOlajide <25608335+BolajiOlajide@users.noreply.github.com> --- CHANGELOG.md | 2 ++ cmd/src/batch_common.go | 29 +++++++++++++++++++++++++---- cmd/src/batch_remote.go | 2 +- cmd/src/batch_repositories.go | 2 +- cmd/src/batch_validate.go | 2 +- 5 files changed, 30 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 161fede045..28a2ed9933 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,8 @@ All notable changes to `src-cli` are documented in this file. ### Fixed +- Handle SIGINT interrupt when reading from Stdin. [#794](https://github.com/sourcegraph/src-cli/pull/794) + ### Removed ## 3.41.0 diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index 7b0a9004c5..7b47d0556d 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -12,6 +12,7 @@ import ( "path/filepath" "runtime" "strings" + "syscall" "time" "github.com/mattn/go-isatty" @@ -220,7 +221,7 @@ func batchDefaultTempDirPrefix() string { return os.TempDir() } -func batchOpenFileFlag(flag string) (io.ReadCloser, error) { +func batchOpenFileFlag(flag string) (*os.File, error) { if flag == "" || flag == "-" { if flag != "-" { // If the flag wasn't set, we want to check stdin. If it's not a TTY, @@ -238,8 +239,13 @@ func batchOpenFileFlag(flag string) (io.ReadCloser, error) { } } } + // https://github.com/golang/go/issues/24842 + if err := syscall.SetNonblock(0, true); err != nil { + panic(err) + } + stdin := os.NewFile(0, "stdin") - return os.Stdin, nil + return stdin, nil } file, err := os.Open(flag) @@ -292,7 +298,7 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp // Parse flags and build up our service and executor options. ui.ParsingBatchSpec() - batchSpec, rawSpec, err := parseBatchSpec(opts.file, svc, false) + batchSpec, rawSpec, err := parseBatchSpec(ctx, opts.file, svc, false) if err != nil { var multiErr errors.MultiError if errors.As(err, &multiErr) { @@ -481,18 +487,33 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp return nil } +func setReadDeadlineOnCancel(ctx context.Context, f *os.File) { + go func() { + // When user cancels, we set the read deadline to now() so the runtime + // cancels the read and we don't block. + <-ctx.Done() + f.SetReadDeadline(time.Now()) + }() +} + // parseBatchSpec parses and validates the given batch spec. If the spec has // validation errors, they are returned. // // isRemote argument is a temporary argument used to determine if the batch spec is being parsed for remote // (server-side) processing. Remote processing does not support mounts yet. -func parseBatchSpec(file string, svc *service.Service, isRemote bool) (*batcheslib.BatchSpec, string, error) { +func parseBatchSpec(ctx context.Context, file string, svc *service.Service, isRemote bool) (*batcheslib.BatchSpec, string, error) { f, err := batchOpenFileFlag(file) if err != nil { return nil, "", err } defer f.Close() + // Create new ctx so we ensure that the goroutine in + // setReadDeadlineOnCancel exits at end of function. + ctx, cancel := context.WithCancel(ctx) + defer cancel() + setReadDeadlineOnCancel(ctx, f) + data, err := io.ReadAll(f) if err != nil { return nil, "", errors.Wrap(err, "reading batch spec") diff --git a/cmd/src/batch_remote.go b/cmd/src/batch_remote.go index 9d542ae9b5..261831c11c 100644 --- a/cmd/src/batch_remote.go +++ b/cmd/src/batch_remote.go @@ -63,7 +63,7 @@ Examples: // may as well validate it at the same time so we don't even have to go to // the backend if it's invalid. ui.ParsingBatchSpec() - spec, raw, err := parseBatchSpec(file, svc, true) + spec, raw, err := parseBatchSpec(ctx, file, svc, true) if err != nil { ui.ParsingBatchSpecFailure(err) return err diff --git a/cmd/src/batch_repositories.go b/cmd/src/batch_repositories.go index 83beb40915..8adbfd9643 100644 --- a/cmd/src/batch_repositories.go +++ b/cmd/src/batch_repositories.go @@ -75,7 +75,7 @@ Examples: } out := output.NewOutput(flagSet.Output(), output.OutputOpts{Verbose: *verbose}) - spec, _, err := parseBatchSpec(file, svc, false) + spec, _, err := parseBatchSpec(ctx, file, svc, false) if err != nil { ui := &ui.TUI{Out: out} ui.ParsingBatchSpecFailure(err) diff --git a/cmd/src/batch_validate.go b/cmd/src/batch_validate.go index 3d40a8caca..db0e9d73e4 100644 --- a/cmd/src/batch_validate.go +++ b/cmd/src/batch_validate.go @@ -75,7 +75,7 @@ Examples: return err } - if _, _, err := parseBatchSpec(file, svc, false); err != nil { + if _, _, err := parseBatchSpec(ctx, file, svc, false); err != nil { ui.ParsingBatchSpecFailure(err) return err } From 256a8b75d91190ec69d5d288613fa6a659a94ee7 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Mon, 11 Jul 2022 13:14:09 +0200 Subject: [PATCH 202/647] batches: Refactor caching to get rid of execution cache results altogether (#797) --- cmd/src/batch_exec.go | 2 +- go.mod | 6 +- go.sum | 12 +- internal/batches/executor/coordinator.go | 125 ++++----- internal/batches/executor/coordinator_test.go | 86 +++---- internal/batches/executor/execution_cache.go | 59 +---- .../batches/executor/execution_cache_test.go | 12 +- internal/batches/executor/executor.go | 36 +-- internal/batches/executor/executor_test.go | 110 ++++---- internal/batches/executor/run_steps.go | 241 +++++++++--------- internal/batches/executor/task.go | 57 ++--- .../executor/testdata/dummydocker/docker | 7 +- internal/batches/executor/ui.go | 4 +- internal/batches/service/service.go | 7 +- internal/batches/service/service_test.go | 2 +- internal/batches/ui/json_lines.go | 10 +- internal/batches/ui/task_exec_tui.go | 2 +- internal/batches/ui/task_exec_tui_test.go | 19 +- internal/batches/workspace/bind_workspace.go | 10 +- .../batches/workspace/volume_workspace.go | 8 +- .../workspace/volume_workspace_test.go | 6 +- internal/batches/workspace/workspace.go | 2 +- 22 files changed, 355 insertions(+), 468 deletions(-) diff --git a/cmd/src/batch_exec.go b/cmd/src/batch_exec.go index 987218faa2..f64b9f1653 100644 --- a/cmd/src/batch_exec.go +++ b/cmd/src/batch_exec.go @@ -165,7 +165,7 @@ func executeBatchSpecInWorkspaces(ctx context.Context, flags *executorModeFlags) Client: &deadClient{}, }) - if err := svc.SetFeatureFlagsForRelease(flags.sourcegraphVersion); err != nil { + if err := svc.SetFeatureFlagsForVersion(flags.sourcegraphVersion); err != nil { return err } diff --git a/go.mod b/go.mod index a228054985..8c668b9514 100644 --- a/go.mod +++ b/go.mod @@ -20,7 +20,7 @@ require ( github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf github.com/sourcegraph/scip v0.1.0 - github.com/sourcegraph/sourcegraph/lib v0.0.0-20220624142708-f2b0579b57ff + github.com/sourcegraph/sourcegraph/lib v0.0.0-20220708204051-cb0aebdbfd74 github.com/stretchr/testify v1.7.2 golang.org/x/net v0.0.0-20220526153639-5463443f8c37 golang.org/x/sync v0.0.0-20210220032951-036812b2e83c @@ -83,7 +83,7 @@ require ( github.com/rivo/uniseg v0.2.0 // indirect github.com/rogpeppe/go-internal v1.8.1 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect - github.com/sourcegraph/log v0.0.0-20220621231153-3bee7082c87e // indirect + github.com/sourcegraph/log v0.0.0-20220707160925-6a936691c838 // indirect github.com/spf13/cobra v1.4.0 // indirect github.com/spf13/pflag v1.0.5 // indirect github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect @@ -98,7 +98,7 @@ require ( go.uber.org/zap v1.21.0 // indirect golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 // indirect golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 // indirect - golang.org/x/sys v0.0.0-20220622161953-175b2fd9d664 // indirect + golang.org/x/sys v0.0.0-20220708085239-5a0f0661e09d // indirect golang.org/x/term v0.0.0-20220411215600-e5f449aeb171 // indirect golang.org/x/text v0.3.7 // indirect golang.org/x/tools v0.1.11 // indirect diff --git a/go.sum b/go.sum index 770f566b9c..06faa55e57 100644 --- a/go.sum +++ b/go.sum @@ -347,12 +347,12 @@ github.com/sourcegraph/go-diff v0.6.1 h1:hmA1LzxW0n1c3Q4YbrFgg4P99GSnebYa3x8gr0H github.com/sourcegraph/go-diff v0.6.1/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= -github.com/sourcegraph/log v0.0.0-20220621231153-3bee7082c87e h1:7MnFFZ85BBwLNDkrQJB503/znGuSoLirDLFWRcLqHlM= -github.com/sourcegraph/log v0.0.0-20220621231153-3bee7082c87e/go.mod h1:A+9F6IicYvBbl2aT0R81lMraKcXjVfdfw352yPe2yJI= +github.com/sourcegraph/log v0.0.0-20220707160925-6a936691c838 h1:8wknDSCUVYbaRT63OD+Iyv+stwze5kE2FAzbA1HrNMA= +github.com/sourcegraph/log v0.0.0-20220707160925-6a936691c838/go.mod h1:zWEPlKrWBUVpko/tOgDS+qrp7BmzaCcmUrh9+ver1iQ= github.com/sourcegraph/scip v0.1.0 h1:kTs0CJaLQvcRZjg+HpGrcJPNX2Tx31+d6szWio3ZOkQ= github.com/sourcegraph/scip v0.1.0/go.mod h1:/AZ8RvsnRfeCZy232PJuVZqcl9f82fJnYwdWZeU2JCo= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20220624142708-f2b0579b57ff h1:lcDmWfcg43tON2jMtpxtEq61wMF6rIgvbx7KfTKA6TU= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20220624142708-f2b0579b57ff/go.mod h1:ppU4qV7WAmfjEoQhM7P1hCDWmv1Q6lIy5mT9o3Pj5t8= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20220708204051-cb0aebdbfd74 h1:XX4rxuQeXuRdg0qNupvrGKSDXKgZyk3flwbSCGMCiFU= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20220708204051-cb0aebdbfd74/go.mod h1:4efRAk7Sv9XaetWwvOxZjiBO3i32jlsmQKpemvCJmMI= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= @@ -503,8 +503,8 @@ golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211007075335-d3039528d8ac/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220622161953-175b2fd9d664 h1:wEZYwx+kK+KlZ0hpvP2Ls1Xr4+RWnlzGFwPP0aiDjIU= -golang.org/x/sys v0.0.0-20220622161953-175b2fd9d664/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220708085239-5a0f0661e09d h1:/m5NbqQelATgoSPVC2Z23sR4kVNokFwDDyWh/3rGY+I= +golang.org/x/sys v0.0.0-20220708085239-5a0f0661e09d/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20220411215600-e5f449aeb171 h1:EH1Deb8WZJ0xc0WK//leUHXcX9aLE5SymusoTmMZye8= golang.org/x/term v0.0.0-20220411215600-e5f449aeb171/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= diff --git a/internal/batches/executor/coordinator.go b/internal/batches/executor/coordinator.go index 4b1d8f0bf1..a3f3018787 100644 --- a/internal/batches/executor/coordinator.go +++ b/internal/batches/executor/coordinator.go @@ -67,10 +67,6 @@ func NewCoordinator(opts NewCoordinatorOpts, logger log.LogManager) *Coordinator TempDir: opts.TempDir, IsRemote: opts.IsRemote, GlobalEnv: opts.GlobalEnv, - WriteStepCacheResult: func(ctx context.Context, stepResult execution.AfterStepResult, task *Task) error { - cacheKey := task.cacheKey(opts.GlobalEnv, opts.IsRemote) - return writeToCache(ctx, opts.Cache, stepResult, task, cacheKey) - }, }) return &Coordinator{ @@ -115,12 +111,8 @@ func (c *Coordinator) CheckStepResultsCache(ctx context.Context, tasks []*Task, func (c *Coordinator) ClearCache(ctx context.Context, tasks []*Task) error { for _, task := range tasks { - cacheKey := task.cacheKey(c.opts.GlobalEnv, c.opts.IsRemote) - if err := c.cache.Clear(ctx, cacheKey); err != nil { - return errors.Wrapf(err, "clearing cache for %q", task.Repository.Name) - } for i := len(task.Steps) - 1; i > -1; i-- { - key := cacheKeyForStep(cacheKey, i) + key := task.cacheKey(c.opts.GlobalEnv, c.opts.IsRemote, i) if err := c.cache.Clear(ctx, key); err != nil { return errors.Wrapf(err, "clearing cache for step %d in %q", i, task.Repository.Name) } @@ -130,42 +122,30 @@ func (c *Coordinator) ClearCache(ctx context.Context, tasks []*Task) error { } func (c *Coordinator) checkCacheForTask(ctx context.Context, batchSpec *batcheslib.BatchSpec, task *Task) (specs []*batcheslib.ChangesetSpec, found bool, err error) { - // Check if the task is cached. - cacheKey := task.cacheKey(c.opts.GlobalEnv, c.opts.IsRemote) - - var result execution.Result - result, found, err = c.cache.Get(ctx, cacheKey) - if err != nil { - return specs, false, errors.Wrapf(err, "checking cache for %q", task.Repository.Name) + if err := c.loadCachedStepResults(ctx, task, c.opts.GlobalEnv); err != nil { + return specs, false, err } - if !found { - // If we are here, that means we didn't find anything in the cache for the - // complete task. So, what if we have cached results for the steps? - if err := c.loadCachedStepResults(ctx, task, c.opts.GlobalEnv); err != nil { - return specs, false, err + // If we have cached results and don't need to execute any more steps, + // we build changeset specs and return. + // TODO: This doesn't consider skipped steps. + if task.CachedStepResultFound && task.CachedStepResult.StepIndex == len(task.Steps)-1 { + // If the cached result resulted in an empty diff, we don't need to + // add it to the list of specs that are displayed to the user and + // send to the server. Instead, we can just report that the task is + // complete and move on. + if task.CachedStepResult.Diff == "" { + return specs, true, nil } - return specs, false, nil - } - - // If the cached result resulted in an empty diff, we don't need to - // add it to the list of specs that are displayed to the user and - // send to the server. Instead, we can just report that the task is - // complete and move on. - if result.Diff == "" { - return specs, true, nil - } - - specs, err = c.buildChangesetSpecs(task, batchSpec, result) - if err != nil { - return specs, false, err + specs, err = c.buildChangesetSpecs(task, batchSpec, task.CachedStepResult) + return specs, true, err } - return specs, true, nil + return specs, false, nil } -func (c Coordinator) buildChangesetSpecs(task *Task, batchSpec *batcheslib.BatchSpec, result execution.Result) ([]*batcheslib.ChangesetSpec, error) { +func (c Coordinator) buildChangesetSpecs(task *Task, batchSpec *batcheslib.BatchSpec, result execution.AfterStepResult) ([]*batcheslib.ChangesetSpec, error) { input := &batcheslib.ChangesetSpecInput{ Repository: batcheslib.Repository{ ID: task.Repository.ID, @@ -178,11 +158,10 @@ func (c Coordinator) buildChangesetSpecs(task *Task, batchSpec *batcheslib.Batch Template: batchSpec.ChangesetTemplate, TransformChanges: batchSpec.TransformChanges, - Result: execution.Result{ + Result: execution.AfterStepResult{ Diff: result.Diff, ChangedFiles: result.ChangedFiles, Outputs: result.Outputs, - Path: result.Path, }, } @@ -195,19 +174,18 @@ func (c Coordinator) buildChangesetSpecs(task *Task, batchSpec *batcheslib.Batch func (c *Coordinator) loadCachedStepResults(ctx context.Context, task *Task, globalEnv []string) error { // We start at the back so that we can find the _last_ cached step, // then restart execution on the following step. - taskKey := task.cacheKey(globalEnv, c.opts.IsRemote) for i := len(task.Steps) - 1; i > -1; i-- { - key := cacheKeyForStep(taskKey, i) + key := task.cacheKey(globalEnv, c.opts.IsRemote, i) - result, found, err := c.cache.GetStepResult(ctx, key) + result, found, err := c.cache.Get(ctx, key) if err != nil { return errors.Wrapf(err, "checking for cached diff for step %d", i) } - // Found a cached result, we're done + // Found a cached result, we're done. if found { - task.CachedResultFound = true - task.CachedResult = result + task.CachedStepResultFound = true + task.CachedStepResult = result return nil } } @@ -215,36 +193,21 @@ func (c *Coordinator) loadCachedStepResults(ctx context.Context, task *Task, glo return nil } -func writeToCache(ctx context.Context, cache cache.Cache, stepResult execution.AfterStepResult, task *Task, cacheKey *cache.ExecutionKeyWithGlobalEnv) error { - key := cacheKeyForStep(cacheKey, stepResult.StepIndex) - if err := cache.SetStepResult(ctx, key, stepResult); err != nil { - return errors.Wrapf(err, "caching result for step %d in %q", stepResult.StepIndex, task.Repository.Name) - } - - return nil -} - -func (c *Coordinator) writeExecutionCacheResult(ctx context.Context, taskResult taskResult) error { - // Add to the cache, even if no diff was produced. - cacheKey := taskResult.task.cacheKey(c.opts.GlobalEnv, c.opts.IsRemote) - if err := c.cache.Set(ctx, cacheKey, taskResult.result); err != nil { - return errors.Wrapf(err, "caching result for %q", taskResult.task.Repository.Name) +func (c *Coordinator) buildSpecs(ctx context.Context, batchSpec *batcheslib.BatchSpec, taskResult taskResult, ui TaskExecutionUI) ([]*batcheslib.ChangesetSpec, error) { + if len(taskResult.stepResults) == 0 { + return nil, nil } - return nil -} - -func (c *Coordinator) writeCacheAndBuildSpecs(ctx context.Context, batchSpec *batcheslib.BatchSpec, taskResult taskResult, ui TaskExecutionUI) ([]*batcheslib.ChangesetSpec, error) { - c.writeExecutionCacheResult(ctx, taskResult) + lastStepResult := taskResult.stepResults[len(taskResult.stepResults)-1] // If the steps didn't result in any diff, we don't need to create a // changeset spec that's displayed to the user and send to the server. - if taskResult.result.Diff == "" { + if lastStepResult.Diff == "" { return nil, nil } // Build the changeset specs. - specs, err := c.buildChangesetSpecs(taskResult.task, batchSpec, taskResult.result) + specs, err := c.buildChangesetSpecs(taskResult.task, batchSpec, lastStepResult) if err != nil { return nil, err } @@ -255,14 +218,7 @@ func (c *Coordinator) writeCacheAndBuildSpecs(ctx context.Context, batchSpec *ba // Execute executes the given tasks. It calls the ui on updates. func (c *Coordinator) Execute(ctx context.Context, tasks []*Task, ui TaskExecutionUI) error { - results, err := c.doExecute(ctx, tasks, ui) - - // Write results to cache. - for _, taskResult := range results { - if cacheErr := c.writeExecutionCacheResult(ctx, taskResult); cacheErr != nil { - return cacheErr - } - } + _, err := c.doExecute(ctx, tasks, ui) return err } @@ -276,7 +232,12 @@ func (c *Coordinator) ExecuteAndBuildSpecs(ctx context.Context, batchSpec *batch // Write results to cache, build ChangesetSpecs if possible and add to list. for _, taskResult := range results { - taskSpecs, err := c.writeCacheAndBuildSpecs(ctx, batchSpec, taskResult, ui) + // Don't build changeset specs for failed workspaces. + if taskResult.err != nil { + continue + } + + taskSpecs, err := c.buildSpecs(ctx, batchSpec, taskResult, ui) if err != nil { return nil, nil, err } @@ -292,5 +253,17 @@ func (c *Coordinator) doExecute(ctx context.Context, tasks []*Task, ui TaskExecu // Run executor c.exec.Start(ctx, tasks, ui) - return c.exec.Wait(ctx) + results, err = c.exec.Wait(ctx) + + // Write all step cache results for all results. + for _, res := range results { + for _, stepRes := range res.stepResults { + cacheKey := res.task.cacheKey(c.opts.GlobalEnv, c.opts.IsRemote, stepRes.StepIndex) + if err := c.cache.Set(ctx, cacheKey, stepRes); err != nil { + return nil, errors.Wrapf(err, "caching result for step %d", stepRes.StepIndex) + } + } + } + + return results, err } diff --git a/internal/batches/executor/coordinator_test.go b/internal/batches/executor/coordinator_test.go index d4246a0160..64c6696bd6 100644 --- a/internal/batches/executor/coordinator_test.go +++ b/internal/batches/executor/coordinator_test.go @@ -24,8 +24,8 @@ import ( func TestCoordinator_Execute(t *testing.T) { publishedFalse := overridable.FromBoolOrString(false) - srcCLITask := &Task{Repository: testRepo1} - sourcegraphTask := &Task{Repository: testRepo2} + srcCLITask := &Task{Repository: testRepo1, Steps: []batcheslib.Step{{Run: "echo Hello World"}}} + sourcegraphTask := &Task{Repository: testRepo2, Steps: []batcheslib.Step{{Run: "echo Hello Sourcegraph"}}} buildSpecFor := func(repo *graphql.Repository, modify func(*batcheslib.ChangesetSpec)) *batcheslib.ChangesetSpec { spec := &batcheslib.ChangesetSpec{ @@ -78,8 +78,8 @@ func TestCoordinator_Execute(t *testing.T) { executor: &dummyExecutor{ results: []taskResult{ - {task: srcCLITask, result: execution.Result{Diff: `dummydiff1`}}, - {task: sourcegraphTask, result: execution.Result{Diff: `dummydiff2`}}, + {task: srcCLITask, stepResults: []execution.AfterStepResult{{Diff: `dummydiff1`}}}, + {task: sourcegraphTask, stepResults: []execution.AfterStepResult{{Diff: `dummydiff2`}}}, }, }, opts: NewCoordinatorOpts{Features: featuresAllEnabled()}, @@ -132,7 +132,7 @@ func TestCoordinator_Execute(t *testing.T) { results: []taskResult{ { task: srcCLITask, - result: execution.Result{ + stepResults: []execution.AfterStepResult{{ Diff: `dummydiff1`, Outputs: map[string]interface{}{ "output1": "myOutputValue1", @@ -140,13 +140,13 @@ func TestCoordinator_Execute(t *testing.T) { "subField": "subFieldValue", }, }, - ChangedFiles: &git.Changes{ + ChangedFiles: git.Changes{ Modified: []string{"modified.txt"}, Added: []string{"added.txt"}, Deleted: []string{"deleted.txt"}, Renamed: []string{"renamed.txt"}, }, - }, + }}, }, }, }, @@ -197,12 +197,13 @@ func TestCoordinator_Execute(t *testing.T) { executor: &dummyExecutor{ results: []taskResult{ - {task: srcCLITask, result: execution.Result{Diff: nestedChangesDiff}}, - {task: sourcegraphTask, result: execution.Result{Diff: nestedChangesDiff}}, + {task: srcCLITask, stepResults: []execution.AfterStepResult{{Diff: nestedChangesDiff}}}, + {task: sourcegraphTask, stepResults: []execution.AfterStepResult{{Diff: nestedChangesDiff}}}, }, }, opts: NewCoordinatorOpts{Features: featuresAllEnabled()}, + // TODO: Fix comment. // We have 4 ChangesetSpecs, but we only want 2 cache entries, // since we cache per Task, not per resulting changeset spec. wantCacheEntries: 2, @@ -244,8 +245,8 @@ func TestCoordinator_Execute(t *testing.T) { executor: &dummyExecutor{ results: []taskResult{ - {task: srcCLITask, result: execution.Result{Diff: `dummydiff1`}}, - {task: sourcegraphTask, result: execution.Result{Diff: `dummydiff2`}}, + {task: srcCLITask, stepResults: []execution.AfterStepResult{{Diff: `dummydiff1`, StepIndex: 0}}}, + {task: sourcegraphTask, stepResults: []execution.AfterStepResult{{Diff: `dummydiff2`, StepIndex: 0}}}, }, }, opts: NewCoordinatorOpts{Features: featuresAllEnabled()}, @@ -330,7 +331,7 @@ func TestCoordinator_Execute(t *testing.T) { // Sanity check, since we're going to be looking at the side effects // on the cache. if c.size() != 0 { - t.Fatalf("unexpectedly hot cache: %+v", c) + t.Fatalf("unexpected hot cache: %+v", c) } // Run with a cold cache. @@ -366,12 +367,6 @@ func TestCoordinator_Execute_StepCaching(t *testing.T) { executor := &dummyExecutor{} executor.results = []taskResult{{ task: task, - result: execution.Result{ - Diff: "dummydiff", - ChangedFiles: &git.Changes{}, - Outputs: map[string]interface{}{}, - Path: "", - }, stepResults: []execution.AfterStepResult{ {StepIndex: 0, Diff: `step-0-diff`}, {StepIndex: 1, Diff: `step-1-diff`}, @@ -386,47 +381,47 @@ func TestCoordinator_Execute_StepCaching(t *testing.T) { // First execution. Make sure that the Task executes all steps. execAndEnsure(t, coord, executor, batchSpec, task, assertNoCachedResult(t)) - // We now expect the cache to have 1+N entries: 1 for the complete task, N - // for the steps. - - assertCacheSize(t, cache, 1) + // We now expect the cache to have N entries for N steps. + assertCacheSize(t, cache, 3) // Reset task - task.CachedResultFound = false + task.CachedStepResultFound = false // Change the 2nd step's definition: task.Steps[1].Run = `echo "two modified"` // Re-execution should start with the diff produced by steps[0] as the // start state from which steps[1] is then re-executed. - execAndEnsure(t, coord, executor, batchSpec, task, assertNoCachedResult(t)) + execAndEnsure(t, coord, executor, batchSpec, task, func(ctx context.Context, t []*Task, teu TaskExecutionUI) {}) // Cache now contains old entries, plus another "complete task" entry and // two entries for newly executed steps. - assertCacheSize(t, cache, 2) + assertCacheSize(t, cache, 5) // Reset task - task.CachedResultFound = false + task.CachedStepResultFound = false // Change the 3rd step's definition: task.Steps[2].Run = `echo "three modified"` // Re-execution should use the diff from steps[1] as start state - execAndEnsure(t, coord, executor, batchSpec, task, assertNoCachedResult(t)) + execAndEnsure(t, coord, executor, batchSpec, task, func(ctx context.Context, t []*Task, teu TaskExecutionUI) {}) // Cache now contains old entries, plus another "complete task" entry and // a single new step entry - assertCacheSize(t, cache, 3) + assertCacheSize(t, cache, 6) // Reset task - task.CachedResultFound = false + task.CachedStepResultFound = false // Now we execute the spec with -clear-cache: if err := coord.ClearCache(context.Background(), []*Task{task}); err != nil { t.Fatal(err) } + assertCacheSize(t, cache, 3) + // We don't want any cached results set on the task: execAndEnsure(t, coord, executor, batchSpec, task, assertNoCachedResult(t)) // Cache should have the same number of entries: the cached step results should // have been cleared (the complete-task-result is cleared in another // code path) and the same amount of cached entries has been added. - assertCacheSize(t, cache, 3) + assertCacheSize(t, cache, 6) } // execAndEnsure executes the given Task with the given cache and dummyExecutor @@ -479,7 +474,7 @@ func assertNoCachedResult(t *testing.T) func(context.Context, []*Task, TaskExecu t.Helper() task := tasks[0] - if task.CachedResultFound { + if task.CachedStepResultFound { t.Fatalf("CachedResultFound but not expected") } } @@ -582,7 +577,7 @@ func (c *inMemoryExecutionCache) size() int { func (c *inMemoryExecutionCache) getCacheItem(key cache.Keyer) (interface{}, bool, error) { k, err := key.Key() if err != nil { - return execution.Result{}, false, err + return execution.AfterStepResult{}, false, err } c.mu.RLock() @@ -592,30 +587,7 @@ func (c *inMemoryExecutionCache) getCacheItem(key cache.Keyer) (interface{}, boo return res, ok, nil } -func (c *inMemoryExecutionCache) Get(ctx context.Context, key cache.Keyer) (execution.Result, bool, error) { - res, ok, err := c.getCacheItem(key) - if err != nil || !ok { - return execution.Result{}, ok, err - } - - execResult, ok := res.(execution.Result) - return execResult, ok, nil -} - -func (c *inMemoryExecutionCache) Set(ctx context.Context, key cache.Keyer, result execution.Result) error { - k, err := key.Key() - if err != nil { - return err - } - - c.mu.Lock() - defer c.mu.Unlock() - - c.cache[k] = result - return nil -} - -func (c *inMemoryExecutionCache) GetStepResult(ctx context.Context, key cache.Keyer) (execution.AfterStepResult, bool, error) { +func (c *inMemoryExecutionCache) Get(ctx context.Context, key cache.Keyer) (execution.AfterStepResult, bool, error) { res, ok, err := c.getCacheItem(key) if err != nil || !ok { return execution.AfterStepResult{}, ok, err @@ -625,7 +597,7 @@ func (c *inMemoryExecutionCache) GetStepResult(ctx context.Context, key cache.Ke return execResult, ok, nil } -func (c *inMemoryExecutionCache) SetStepResult(ctx context.Context, key cache.Keyer, result execution.AfterStepResult) error { +func (c *inMemoryExecutionCache) Set(ctx context.Context, key cache.Keyer, result execution.AfterStepResult) error { k, err := key.Key() if err != nil { return err diff --git a/internal/batches/executor/execution_cache.go b/internal/batches/executor/execution_cache.go index 7148bd9a5b..8a96be043a 100644 --- a/internal/batches/executor/execution_cache.go +++ b/internal/batches/executor/execution_cache.go @@ -35,19 +35,6 @@ func (c ExecutionDiskCache) cacheFilePath(key cache.Keyer) (string, error) { return filepath.Join(c.Dir, key.Slug(), keyString+cacheFileExt), nil } -func (c ExecutionDiskCache) Get(ctx context.Context, key cache.Keyer) (execution.Result, bool, error) { - var result execution.Result - - path, err := c.cacheFilePath(key) - if err != nil { - return result, false, err - } - - found, err := readCacheFile(path, &result) - - return result, found, err -} - func readCacheFile(path string, result interface{}) (bool, error) { if _, err := os.Stat(path); os.IsNotExist(err) { return false, nil @@ -82,15 +69,6 @@ func (c ExecutionDiskCache) writeCacheFile(path string, result interface{}) erro return os.WriteFile(path, raw, 0600) } -func (c ExecutionDiskCache) Set(ctx context.Context, key cache.Keyer, result execution.Result) error { - path, err := c.cacheFilePath(key) - if err != nil { - return err - } - - return c.writeCacheFile(path, &result) -} - func (c ExecutionDiskCache) Clear(ctx context.Context, key cache.Keyer) error { path, err := c.cacheFilePath(key) if err != nil { @@ -104,7 +82,7 @@ func (c ExecutionDiskCache) Clear(ctx context.Context, key cache.Keyer) error { return os.Remove(path) } -func (c ExecutionDiskCache) GetStepResult(ctx context.Context, key cache.Keyer) (execution.AfterStepResult, bool, error) { +func (c ExecutionDiskCache) Get(ctx context.Context, key cache.Keyer) (execution.AfterStepResult, bool, error) { var result execution.AfterStepResult path, err := c.cacheFilePath(key) if err != nil { @@ -119,7 +97,7 @@ func (c ExecutionDiskCache) GetStepResult(ctx context.Context, key cache.Keyer) return result, found, nil } -func (c ExecutionDiskCache) SetStepResult(ctx context.Context, key cache.Keyer, result execution.AfterStepResult) error { +func (c ExecutionDiskCache) Set(ctx context.Context, key cache.Keyer, result execution.AfterStepResult) error { path, err := c.cacheFilePath(key) if err != nil { return err @@ -132,28 +110,19 @@ func (c ExecutionDiskCache) SetStepResult(ctx context.Context, key cache.Keyer, // retrieve cache entries. type ExecutionNoOpCache struct{} -func (ExecutionNoOpCache) Get(ctx context.Context, key cache.Keyer) (result execution.Result, found bool, err error) { - return execution.Result{}, false, nil -} - -func (ExecutionNoOpCache) Set(ctx context.Context, key cache.Keyer, result execution.Result) error { - return nil -} - func (ExecutionNoOpCache) Clear(ctx context.Context, key cache.Keyer) error { return nil } -func (ExecutionNoOpCache) SetStepResult(ctx context.Context, key cache.Keyer, result execution.AfterStepResult) error { +func (ExecutionNoOpCache) Set(ctx context.Context, key cache.Keyer, result execution.AfterStepResult) error { return nil } -func (ExecutionNoOpCache) GetStepResult(ctx context.Context, key cache.Keyer) (execution.AfterStepResult, bool, error) { +func (ExecutionNoOpCache) Get(ctx context.Context, key cache.Keyer) (execution.AfterStepResult, bool, error) { return execution.AfterStepResult{}, false, nil } type JSONCacheWriter interface { - WriteExecutionResult(key string, value execution.Result) WriteAfterStepResult(key string, value execution.AfterStepResult) } @@ -162,23 +131,7 @@ type ServerSideCache struct { Writer JSONCacheWriter } -func (c *ServerSideCache) Get(ctx context.Context, key cache.Keyer) (result execution.Result, found bool, err error) { - // noop - return execution.Result{}, false, nil -} - -func (c *ServerSideCache) Set(ctx context.Context, key cache.Keyer, result execution.Result) error { - k, err := key.Key() - if err != nil { - return err - } - - c.Writer.WriteExecutionResult(k, result) - - return nil -} - -func (c *ServerSideCache) SetStepResult(ctx context.Context, key cache.Keyer, result execution.AfterStepResult) error { +func (c *ServerSideCache) Set(ctx context.Context, key cache.Keyer, result execution.AfterStepResult) error { k, err := key.Key() if err != nil { return err @@ -189,7 +142,7 @@ func (c *ServerSideCache) SetStepResult(ctx context.Context, key cache.Keyer, re return nil } -func (c *ServerSideCache) GetStepResult(ctx context.Context, key cache.Keyer) (result execution.AfterStepResult, found bool, err error) { +func (c *ServerSideCache) Get(ctx context.Context, key cache.Keyer) (result execution.AfterStepResult, found bool, err error) { rawKey, err := key.Key() if err != nil { return result, false, err diff --git a/internal/batches/executor/execution_cache_test.go b/internal/batches/executor/execution_cache_test.go index fa6d29cf41..0b1ff71877 100644 --- a/internal/batches/executor/execution_cache_test.go +++ b/internal/batches/executor/execution_cache_test.go @@ -43,23 +43,23 @@ index 0000000..3363c39 func TestExecutionDiskCache_GetSet(t *testing.T) { ctx := context.Background() - cacheKey1 := &cache.ExecutionKey{ + cacheKey1 := &cache.CacheKey{ Repository: cacheRepo1, Steps: []batcheslib.Step{ {Run: "echo 'Hello World'", Container: "alpine:3"}, }, } - cacheKey2 := &cache.ExecutionKey{ + cacheKey2 := &cache.CacheKey{ Repository: cacheRepo2, Steps: []batcheslib.Step{ {Run: "echo 'Hello World'", Container: "alpine:3"}, }, } - value := execution.Result{ + value := execution.AfterStepResult{ Diff: testDiff, - ChangedFiles: &git.Changes{ + ChangedFiles: git.Changes{ Added: []string{"README.md"}, }, Outputs: map[string]interface{}{}, @@ -89,7 +89,7 @@ func TestExecutionDiskCache_GetSet(t *testing.T) { assertCacheMiss(t, cache, cacheKey1) } -func assertCacheHit(t *testing.T, c ExecutionDiskCache, k *cache.ExecutionKey, want execution.Result) { +func assertCacheHit(t *testing.T, c ExecutionDiskCache, k cache.Keyer, want execution.AfterStepResult) { t.Helper() have, found, err := c.Get(context.Background(), k) @@ -105,7 +105,7 @@ func assertCacheHit(t *testing.T, c ExecutionDiskCache, k *cache.ExecutionKey, w } } -func assertCacheMiss(t *testing.T, c ExecutionDiskCache, k *cache.ExecutionKey) { +func assertCacheMiss(t *testing.T, c ExecutionDiskCache, k cache.Keyer) { t.Helper() _, found, err := c.Get(context.Background(), k) diff --git a/internal/batches/executor/executor.go b/internal/batches/executor/executor.go index 07e7a09d5d..82ec04145f 100644 --- a/internal/batches/executor/executor.go +++ b/internal/batches/executor/executor.go @@ -48,8 +48,8 @@ func (e TaskExecutionErr) StatusText() string { // taskResult is a combination of a Task and the result of its execution. type taskResult struct { task *Task - result execution.Result stepResults []execution.AfterStepResult + err error } type newExecutorOpts struct { @@ -60,12 +60,11 @@ type newExecutorOpts struct { Logger log.LogManager // Config - Parallelism int - Timeout time.Duration - TempDir string - IsRemote bool - GlobalEnv []string - WriteStepCacheResult func(ctx context.Context, stepResult execution.AfterStepResult, task *Task) error + Parallelism int + Timeout time.Duration + TempDir string + IsRemote bool + GlobalEnv []string } type executor struct { @@ -167,14 +166,20 @@ func (x *executor) do(ctx context.Context, task *Task, ui TaskExecutionUI) (err }() // Now checkout the archive. - task.Archive = x.opts.RepoArchiveRegistry.Checkout(repozip.RepoRevision{RepoName: task.Repository.Name, Commit: task.Repository.Rev()}, task.ArchivePathToFetch()) + task.RepoArchive = x.opts.RepoArchiveRegistry.Checkout( + repozip.RepoRevision{ + RepoName: task.Repository.Name, + Commit: task.Repository.Rev(), + }, + task.ArchivePathToFetch(), + ) // Set up our timeout. runCtx, cancel := context.WithTimeout(ctx, x.opts.Timeout) defer cancel() // Actually execute the steps. - opts := &executionOpts{ + opts := &runStepsOpts{ task: task, logger: l, wc: x.opts.Creator, @@ -183,11 +188,12 @@ func (x *executor) do(ctx context.Context, task *Task, ui TaskExecutionUI) (err isRemote: x.opts.IsRemote, globalEnv: x.opts.GlobalEnv, - ui: ui.StepsExecutionUI(task), - writeStepCacheResult: x.opts.WriteStepCacheResult, + ui: ui.StepsExecutionUI(task), } - result, stepResults, err := runSteps(runCtx, opts) + stepResults, err := runSteps(runCtx, opts) + x.addResult(task, stepResults, err) + if err != nil { if reachedTimeout(runCtx, err) { err = &errTimeoutReached{timeout: x.opts.Timeout} @@ -195,18 +201,16 @@ func (x *executor) do(ctx context.Context, task *Task, ui TaskExecutionUI) (err return err } - x.addResult(task, result, stepResults) - return nil } -func (x *executor) addResult(task *Task, result execution.Result, stepResults []execution.AfterStepResult) { +func (x *executor) addResult(task *Task, stepResults []execution.AfterStepResult, err error) { x.resultsMu.Lock() defer x.resultsMu.Unlock() x.results = append(x.results, taskResult{ task: task, - result: result, stepResults: stepResults, + err: err, }) } diff --git a/internal/batches/executor/executor_test.go b/internal/batches/executor/executor_test.go index 489c6f9de5..075fbe8815 100644 --- a/internal/batches/executor/executor_test.go +++ b/internal/batches/executor/executor_test.go @@ -10,7 +10,6 @@ import ( "path/filepath" "runtime" "strings" - "sync" "testing" "time" @@ -378,9 +377,6 @@ func TestExecutor_Integration(t *testing.T) { // Temp dir for log files and downloaded archives testTempDir := t.TempDir() - cacheCount := 0 - var cacheLock sync.Mutex - cr, _ := workspace.NewCreator(context.Background(), "bind", testTempDir, testTempDir, images) // Setup executor opts := newExecutorOpts{ @@ -392,12 +388,6 @@ func TestExecutor_Integration(t *testing.T) { TempDir: testTempDir, Parallelism: runtime.GOMAXPROCS(0), Timeout: tc.executorTimeout, - WriteStepCacheResult: func(ctx context.Context, stepResult execution.AfterStepResult, task *Task) error { - cacheLock.Lock() - cacheCount += 1 - cacheLock.Unlock() - return nil - }, } if opts.Timeout == 0 { @@ -423,9 +413,6 @@ func TestExecutor_Integration(t *testing.T) { } } - if tc.wantCacheCount != cacheCount { - t.Errorf("wrong cache count. have=%d want=%d", cacheCount, tc.wantCacheCount) - } wantResults := 0 resultsFound := map[string]map[string]bool{} for repo, byPath := range tc.wantFilesChanged { @@ -436,11 +423,22 @@ func TestExecutor_Integration(t *testing.T) { } } - if have, want := len(results), wantResults; have != want { - t.Fatalf("wrong number of execution results. want=%d, have=%d", want, have) + haveResults := 0 + for _, res := range results { + if res.err == nil { + haveResults++ + } + } + + if have, want := haveResults, wantResults; have != want { + t.Fatalf("wrong number of results. want=%d, have=%d", want, have) } for _, taskResult := range results { + if taskResult.err != nil { + continue + } + repoID := taskResult.task.Repository.ID path := taskResult.task.Path @@ -456,7 +454,9 @@ func TestExecutor_Integration(t *testing.T) { t.Fatalf("spec for repo %q and path %q but no files expected in that branch", repoID, path) } - fileDiffs, err := diff.ParseMultiFileDiff([]byte(taskResult.result.Diff)) + lastStepResult := taskResult.stepResults[len(taskResult.stepResults)-1] + + fileDiffs, err := diff.ParseMultiFileDiff([]byte(lastStepResult.Diff)) if err != nil { t.Fatalf("failed to parse diff: %s", err) } @@ -544,12 +544,11 @@ index 02a19af..c9644dd 100644 Steps: []batcheslib.Step{ {Run: `echo -e "foobar\n" >> README.md`}, }, - CachedResultFound: true, - CachedResult: execution.AfterStepResult{ - StepIndex: 0, - Diff: cachedDiff, - Outputs: map[string]interface{}{}, - StepResult: execution.StepResult{}, + CachedStepResultFound: true, + CachedStepResult: execution.AfterStepResult{ + StepIndex: 0, + Diff: cachedDiff, + Outputs: map[string]interface{}{}, }, Repository: testRepo1, } @@ -560,22 +559,22 @@ index 02a19af..c9644dd 100644 } if have, want := len(results), 1; have != want { - t.Fatalf("wrong number of execution results. want=%d, have=%d", want, have) + t.Fatalf("wrong number of results. want=%d, have=%d", want, have) + } + + if have, want := len(results[0].stepResults), 1; have != want { + t.Fatalf("wrong length of step results. have=%d, want=%d", have, want) } // We want the diff to be the same as the cached one, since we only had to // execute a single step - executionResult := results[0].result + executionResult := results[0].stepResults[0] if diff := cmp.Diff(executionResult.Diff, cachedDiff); diff != "" { t.Fatalf("wrong diff: %s", diff) } - if have, want := len(results[0].stepResults), 1; have != want { - t.Fatalf("wrong length of step results. have=%d, want=%d", have, want) - } - stepResult := results[0].stepResults[0] - if diff := cmp.Diff(stepResult, task.CachedResult); diff != "" { + if diff := cmp.Diff(stepResult, task.CachedStepResult); diff != "" { t.Fatalf("wrong stepResult: %s", diff) } }) @@ -660,21 +659,19 @@ echo "previous_step.modified_files=${{ previous_step.modified_files }}" >> READM `}, {Run: `echo "this is step 5" >> ${{ outputs.myOutput }}`}, }, - CachedResultFound: true, - CachedResult: execution.AfterStepResult{ + CachedStepResultFound: true, + CachedStepResult: execution.AfterStepResult{ StepIndex: 2, Diff: cachedDiff, Outputs: map[string]interface{}{ "myOutput": "my-output.txt", }, - StepResult: execution.StepResult{ - Files: &git.Changes{ - Modified: []string{"README.md"}, - Added: []string{"README.txt"}, - }, - Stdout: "", - Stderr: "", + ChangedFiles: git.Changes{ + Modified: []string{"README.md"}, + Added: []string{"README.txt"}, }, + Stdout: "", + Stderr: "", }, } @@ -684,15 +681,15 @@ echo "previous_step.modified_files=${{ previous_step.modified_files }}" >> READM } if have, want := len(results), 1; have != want { - t.Fatalf("wrong number of execution results. want=%d, have=%d", want, have) + t.Fatalf("wrong number of results. want=%d, have=%d", want, have) } - executionResult := results[0].result + executionResult := results[0].stepResults[len(results[0].stepResults)-1] if diff := cmp.Diff(executionResult.Diff, wantFinalDiff); diff != "" { t.Fatalf("wrong diff: %s", diff) } - if diff := cmp.Diff(executionResult.Outputs, task.CachedResult.Outputs); diff != "" { + if diff := cmp.Diff(executionResult.Outputs, task.CachedStepResult.Outputs); diff != "" { t.Fatalf("wrong execution result outputs: %s", diff) } @@ -706,7 +703,7 @@ echo "previous_step.modified_files=${{ previous_step.modified_files }}" >> READM t.Fatalf("wrong stepIndex. have=%d, want=%d", have, want) } - if diff := cmp.Diff(lastStepResult.Outputs, task.CachedResult.Outputs); diff != "" { + if diff := cmp.Diff(lastStepResult.Outputs, task.CachedStepResult.Outputs); diff != "" { t.Fatalf("wrong step result outputs: %s", diff) } }) @@ -738,16 +735,14 @@ index 3040106..5f2f924 100644 {Run: "echo -n Hello world"}, {Run: `echo ${{ previous_step.stdout }} >> README.md`}, }, - CachedResultFound: true, - CachedResult: execution.AfterStepResult{ - StepIndex: 0, - Diff: "", - Outputs: map[string]interface{}{}, - StepResult: execution.StepResult{ - Files: &git.Changes{}, - Stdout: "hello world", - Stderr: "", - }, + CachedStepResultFound: true, + CachedStepResult: execution.AfterStepResult{ + StepIndex: 0, + Diff: "", + Outputs: map[string]interface{}{}, + ChangedFiles: git.Changes{}, + Stdout: "hello world", + Stderr: "", }, } @@ -757,15 +752,15 @@ index 3040106..5f2f924 100644 } if have, want := len(results), 1; have != want { - t.Fatalf("wrong number of execution results. want=%d, have=%d", want, have) + t.Fatalf("wrong number of results. want=%d, have=%d", want, have) } - executionResult := results[0].result + executionResult := results[0].stepResults[len(results[0].stepResults)-1] if diff := cmp.Diff(executionResult.Diff, wantFinalDiff); diff != "" { t.Fatalf("wrong diff: %s", diff) } - if diff := cmp.Diff(executionResult.Outputs, task.CachedResult.Outputs); diff != "" { + if diff := cmp.Diff(executionResult.Outputs, task.CachedStepResult.Outputs); diff != "" { t.Fatalf("wrong execution result outputs: %s", diff) } @@ -779,7 +774,7 @@ index 3040106..5f2f924 100644 t.Fatalf("wrong stepIndex. have=%d, want=%d", have, want) } - if diff := cmp.Diff(lastStepResult.Outputs, task.CachedResult.Outputs); diff != "" { + if diff := cmp.Diff(lastStepResult.Outputs, task.CachedStepResult.Outputs); diff != "" { t.Fatalf("wrong step result outputs: %s", diff) } }) @@ -823,9 +818,6 @@ func testExecuteTasks(t *testing.T, tasks []*Task, archives ...mock.RepoArchive) TempDir: testTempDir, Parallelism: runtime.GOMAXPROCS(0), Timeout: 30 * time.Second, - WriteStepCacheResult: func(ctx context.Context, stepResult execution.AfterStepResult, task *Task) error { - return nil - }, }) executor.Start(context.Background(), tasks, newDummyTaskExecutionUI()) diff --git a/internal/batches/executor/run_steps.go b/internal/batches/executor/run_steps.go index fb97610dfe..556c951f66 100644 --- a/internal/batches/executor/run_steps.go +++ b/internal/batches/executor/run_steps.go @@ -13,7 +13,6 @@ import ( batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/execution" - "github.com/sourcegraph/sourcegraph/lib/batches/git" "github.com/sourcegraph/sourcegraph/lib/batches/template" "github.com/sourcegraph/sourcegraph/lib/errors" @@ -26,73 +25,86 @@ import ( yamlv3 "gopkg.in/yaml.v3" ) -type executionOpts struct { - wc workspace.Creator +type runStepsOpts struct { + // wc is the workspace creator to use. It will be called at the beginning of + // runSteps to prepare the workspace for execution. + wc workspace.Creator + // ensureImage is called in runSteps to make sure the used image has been + // pulled from the registry. ensureImage imageEnsurer - + // task is the definition of the workspace execution. task *Task - + // tempDir points to where temporary files of the execution should live at. tempDir string logger log.TaskLogger ui StepsExecutionUI + // isRemote toggles server-side execution mode. This disables file mounts using + // step.mounts. isRemote bool + // globalEnv is the os.Environ() for the execution. We don't read from os.Environ() + // directly to allow injecting variables and hiding others. globalEnv []string - - writeStepCacheResult func(ctx context.Context, stepResult execution.AfterStepResult, task *Task) error } -func runSteps(ctx context.Context, opts *executionOpts) (result execution.Result, stepResults []execution.AfterStepResult, err error) { +func runSteps(ctx context.Context, opts *runStepsOpts) (stepResults []execution.AfterStepResult, err error) { opts.ui.ArchiveDownloadStarted() - err = opts.task.Archive.Ensure(ctx) + err = opts.task.RepoArchive.Ensure(ctx) opts.ui.ArchiveDownloadFinished(err) if err != nil { - return execution.Result{}, nil, errors.Wrap(err, "fetching repo") + return nil, errors.Wrap(err, "fetching repo") } - defer opts.task.Archive.Close() + defer opts.task.RepoArchive.Close() opts.ui.WorkspaceInitializationStarted() - ws, err := opts.wc.Create(ctx, opts.task.Repository, opts.task.Steps, opts.task.Archive) + ws, err := opts.wc.Create(ctx, opts.task.Repository, opts.task.Steps, opts.task.RepoArchive) if err != nil { - return execution.Result{}, nil, errors.Wrap(err, "creating workspace") + return nil, errors.Wrap(err, "creating workspace") } defer ws.Close(ctx) opts.ui.WorkspaceInitializationFinished() var ( - execResult = execution.Result{ - Diff: "", - ChangedFiles: &git.Changes{}, - Outputs: make(map[string]interface{}), - Path: opts.task.Path, - } - previousStepResult execution.StepResult - startStep int + // lastOutputs are the step.outputs from the previously run step. + // Outputs are additive, so we will only ever append to this map, + // but never clear it. + lastOutputs = make(map[string]any) + previousStepResult execution.AfterStepResult + // startStep is the index of the step we start executing with. Set when + // there's a partial cache result for the task. + startStep int ) - if opts.task.CachedResultFound { + if opts.task.CachedStepResultFound { // Set the Outputs to the cached outputs - execResult.Outputs = opts.task.CachedResult.Outputs - - lastStep := opts.task.CachedResult.StepIndex + lastOutputs = opts.task.CachedStepResult.Outputs + previousStepResult = opts.task.CachedStepResult + lastStep := opts.task.CachedStepResult.StepIndex + // Add the cached result to the result set. It may be required for building + // the changeset specs in the end if we don't need to execute any other steps + // due to dynamic skipping. + // We remove it at the end of this function if it isn't needed, so we don't + // write it to the cache again. + stepResults = append(stepResults, previousStepResult) // If we have cached results and don't need to execute any more steps, - // we can quit + // we can quit. + // TODO: This doesn't consider skipped steps, but it's not _that_ + // bad, we will find out about that further down and correctly finish + // execution early. if lastStep == len(opts.task.Steps)-1 { - // Build the execution result from the step result. - changes, err := git.ChangesInDiff([]byte(opts.task.CachedResult.Diff)) - if err != nil { - return execResult, nil, errors.Wrap(err, "parsing cached step diff") - } - - execResult.Diff = opts.task.CachedResult.Diff - execResult.ChangedFiles = &changes - stepResults = append(stepResults, opts.task.CachedResult) + return stepResults, nil + } - return execResult, stepResults, nil + // If the previous steps made any modifications to the workspace yet, + // apply them. + if opts.task.CachedStepResult.Diff != "" { + if err := ws.ApplyDiff(ctx, []byte(opts.task.CachedStepResult.Diff)); err != nil { + return nil, errors.Wrap(err, "applying diff of cache result") + } } startStep = lastStep + 1 @@ -103,41 +115,24 @@ func runSteps(ctx context.Context, opts *executionOpts) (result execution.Result ) } - var lastDiff string - for i := startStep; i < len(opts.task.Steps); i++ { step := opts.task.Steps[i] stepContext := template.StepContext{ BatchChange: *opts.task.BatchChangeAttributes, Repository: util.NewTemplatingRepo(opts.task.Repository.Name, opts.task.Repository.FileMatches), - Outputs: execResult.Outputs, + Outputs: lastOutputs, Steps: template.StepsContext{ - Path: execResult.Path, - Changes: previousStepResult.Files, + Path: opts.task.Path, + Changes: previousStepResult.ChangedFiles, }, PreviousStep: previousStepResult, } - if opts.task.CachedResultFound && i == startStep { - previousStepResult = opts.task.CachedResult.StepResult - - stepContext.PreviousStep = previousStepResult - stepContext.Steps.Changes = previousStepResult.Files - stepContext.Outputs = opts.task.CachedResult.Outputs - - // If the previous steps made any modifications in the workspace yet, - // apply them. - if opts.task.CachedResult.Diff != "" { - if err := ws.ApplyDiff(ctx, []byte(opts.task.CachedResult.Diff)); err != nil { - return execResult, nil, errors.Wrap(err, "applying diff of cache result") - } - } - } - + // Check if the step needs to be skipped. cond, err := template.EvalStepCondition(step.IfCondition(), &stepContext) if err != nil { - return execResult, nil, errors.Wrap(err, "evaluating step condition") + return nil, errors.Wrap(err, "evaluating step condition") } if !cond { opts.ui.StepSkipped(i + 1) @@ -147,12 +142,13 @@ func runSteps(ctx context.Context, opts *executionOpts) (result execution.Result // We need to grab the digest for the exact image we're using. img, err := opts.ensureImage(ctx, step.Container) if err != nil { - return execResult, nil, err + return nil, err } digest, err := img.Digest(ctx) if err != nil { - return execResult, nil, err + return nil, err } + stdoutBuffer, stderrBuffer, err := executeSingleStep(ctx, opts, ws, i, step, digest, &stepContext) defer func() { if err != nil { @@ -165,76 +161,75 @@ func runSteps(ctx context.Context, opts *executionOpts) (result execution.Result } }() if err != nil { - return execResult, nil, err + return stepResults, err } changes, err := ws.Changes(ctx) if err != nil { - return execResult, nil, errors.Wrap(err, "getting changed files in step") - } - - result := execution.StepResult{Files: changes, Stdout: stdoutBuffer.String(), Stderr: stderrBuffer.String()} - - // Set stepContext.Step to current step's results before rendering outputs - stepContext.Step = result - // Render and evaluate outputs - if err := setOutputs(step.Outputs, execResult.Outputs, &stepContext); err != nil { - return execResult, nil, errors.Wrap(err, "setting step outputs") + return stepResults, errors.Wrap(err, "getting changed files in step") } // Get the current diff and store that away as the per-step result. stepDiff, err := ws.Diff(ctx) if err != nil { - return execResult, nil, errors.Wrap(err, "getting diff produced by step") + return stepResults, errors.Wrap(err, "getting diff produced by step") } + stepResult := execution.AfterStepResult{ - StepIndex: i, - Diff: string(stepDiff), - Outputs: make(map[string]interface{}), - StepResult: result, + ChangedFiles: changes, + Stdout: stdoutBuffer.String(), + Stderr: stderrBuffer.String(), + StepIndex: i, + Diff: string(stepDiff), + // Those will be set below. + Outputs: make(map[string]interface{}), } - for k, v := range execResult.Outputs { + + // Set stepContext.Step to current step's results before rendering outputs. + stepContext.Step = stepResult + // Render and evaluate outputs. + 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 } stepResults = append(stepResults, stepResult) - previousStepResult = result - - // cache the result here - err = opts.writeStepCacheResult(ctx, stepResult, opts.task) - if err != nil { - return execResult, nil, errors.Wrap(err, "failed to cache stepResult") - } + previousStepResult = stepResult - opts.ui.StepFinished(i+1, stepResult.Diff, result.Files, stepResult.Outputs) - - lastDiff = stepResult.Diff + opts.ui.StepFinished(i+1, stepResult.Diff, stepResult.ChangedFiles, stepResult.Outputs) } - execResult.Diff = lastDiff - execResult.ChangedFiles = previousStepResult.Files + // If we ended up executing at least one step in addition to the cached step, + // we can remove it from the result set. Otherwise we write it to the cache + // again which is unnecessary. We only need to return it when we want to build changeset + // specs from it. + if len(stepResults) > 1 && opts.task.CachedStepResultFound { + stepResults = stepResults[1:] + } - return execResult, stepResults, err + return stepResults, err } const workDir = "/work" func executeSingleStep( ctx context.Context, - opts *executionOpts, + opts *runStepsOpts, workspace workspace.Workspace, - i int, + stepIdx int, step batcheslib.Step, imageDigest string, stepContext *template.StepContext, -) (bytes.Buffer, bytes.Buffer, error) { +) (stdout bytes.Buffer, stderr bytes.Buffer, err error) { // ---------- // PREPARATION // ---------- - opts.ui.StepPreparingStart(i + 1) + opts.ui.StepPreparingStart(stepIdx + 1) cidFile, cleanup, err := createCidFile(ctx, opts.tempDir, util.SlugForRepo(opts.task.Repository.Name, opts.task.Repository.Rev())) if err != nil { - opts.ui.StepPreparingFailed(i+1, err) + opts.ui.StepPreparingFailed(stepIdx+1, err) return bytes.Buffer{}, bytes.Buffer{}, err } defer cleanup() @@ -243,13 +238,13 @@ func executeSingleStep( shell, containerTemp, err := probeImageForShell(ctx, imageDigest) if err != nil { err = errors.Wrapf(err, "probing image %q for shell", step.Container) - opts.ui.StepPreparingFailed(i+1, err) + opts.ui.StepPreparingFailed(stepIdx+1, err) return bytes.Buffer{}, bytes.Buffer{}, err } runScriptFile, runScript, cleanup, err := createRunScriptFile(ctx, opts.tempDir, step.Run, stepContext) if err != nil { - opts.ui.StepPreparingFailed(i+1, err) + opts.ui.StepPreparingFailed(stepIdx+1, err) return bytes.Buffer{}, bytes.Buffer{}, err } defer cleanup() @@ -257,7 +252,7 @@ func executeSingleStep( // Parse and render the step.Files. filesToMount, cleanup, err := createFilesToMount(opts.tempDir, step, stepContext) if err != nil { - opts.ui.StepPreparingFailed(i+1, err) + opts.ui.StepPreparingFailed(stepIdx+1, err) return bytes.Buffer{}, bytes.Buffer{}, err } defer cleanup() @@ -266,23 +261,23 @@ func executeSingleStep( stepEnv, err := step.Env.Resolve(opts.globalEnv) if err != nil { err = errors.Wrap(err, "resolving step environment") - opts.ui.StepPreparingFailed(i+1, err) + opts.ui.StepPreparingFailed(stepIdx+1, err) return bytes.Buffer{}, bytes.Buffer{}, err } // Render the step.Env variables as templates. env, err := template.RenderStepMap(stepEnv, stepContext) if err != nil { err = errors.Wrap(err, "parsing step environment") - opts.ui.StepPreparingFailed(i+1, err) + opts.ui.StepPreparingFailed(stepIdx+1, err) return bytes.Buffer{}, bytes.Buffer{}, err } - opts.ui.StepPreparingSuccess(i + 1) + opts.ui.StepPreparingSuccess(stepIdx + 1) // ---------- // EXECUTION // ---------- - opts.ui.StepStarted(i+1, runScript, env) + opts.ui.StepStarted(stepIdx+1, runScript, env) workspaceOpts, err := workspace.DockerRunOpts(ctx, workDir) if err != nil { @@ -308,9 +303,9 @@ func executeSingleStep( args = append(args, "--mount", fmt.Sprintf("type=bind,source=%s,target=%s,ro", source.Name(), target)) } - // Temporarily add a guard to prevent a path to mount path for server-side processing + // Temporarily add a guard to prevent a path to mount path for server-side processing. if !opts.isRemote { - // Mount any paths on the local system to the docker container. The paths have already been validated during parsing + // Mount any paths on the local system to the docker container. The paths have already been validated during parsing. for _, mount := range step.Mount { args = append(args, "--mount", fmt.Sprintf("type=bind,source=%s,target=%s,ro", mount.Path, mount.Mountpoint)) } @@ -330,19 +325,18 @@ func executeSingleStep( writerCtx, writerCancel := context.WithCancel(ctx) defer writerCancel() - outputWriter := opts.ui.StepOutputWriter(writerCtx, opts.task, i+1) + outputWriter := opts.ui.StepOutputWriter(writerCtx, opts.task, stepIdx+1) defer func() { outputWriter.Close() }() - var stdoutBuffer, stderrBuffer bytes.Buffer - stdout := io.MultiWriter(&stdoutBuffer, outputWriter.StdoutWriter(), opts.logger.PrefixWriter("stdout")) - stderr := io.MultiWriter(&stderrBuffer, outputWriter.StderrWriter(), opts.logger.PrefixWriter("stderr")) + stdoutWriter := io.MultiWriter(&stdout, outputWriter.StdoutWriter(), opts.logger.PrefixWriter("stdout")) + stderrWriter := io.MultiWriter(&stderr, outputWriter.StderrWriter(), opts.logger.PrefixWriter("stderr")) // Setup readers that pipe the output into the given buffers - wg, err := process.PipeOutput(ctx, cmd, stdout, stderr) + wg, err := process.PipeOutput(ctx, cmd, stdoutWriter, stderrWriter) if err != nil { - return bytes.Buffer{}, bytes.Buffer{}, errors.Wrap(err, "piping process output") + return stdout, stderr, errors.Wrap(err, "piping process output") } newStepFailedErr := func(wrappedErr error) stepFailedErr { @@ -358,34 +352,35 @@ func executeSingleStep( Run: runScript, Container: step.Container, TmpFilename: containerTemp, - Stdout: strings.TrimSpace(stdoutBuffer.String()), - Stderr: strings.TrimSpace(stderrBuffer.String()), + Stdout: strings.TrimSpace(stdout.String()), + Stderr: strings.TrimSpace(stderr.String()), } } - opts.logger.Logf("[Step %d] run: %q, container: %q", i+1, step.Run, step.Container) - opts.logger.Logf("[Step %d] full command: %q", i+1, strings.Join(cmd.Args, " ")) + opts.logger.Logf("[Step %d] run: %q, container: %q", stepIdx+1, step.Run, step.Container) + opts.logger.Logf("[Step %d] full command: %q", stepIdx+1, strings.Join(cmd.Args, " ")) - // Start the command + // Start the command. t0 := time.Now() if err := cmd.Start(); err != nil { - opts.logger.Logf("[Step %d] error starting Docker container: %+v", i+1, err) - return stdoutBuffer, stderrBuffer, newStepFailedErr(err) + opts.logger.Logf("[Step %d] error starting Docker container: %+v", stepIdx+1, err) + return stdout, stderr, newStepFailedErr(err) } // Wait for the readers, because the pipes used by PipeOutput under the - // hood are closed when the command exits + // hood are closed when the command exits. wg.Wait() - // Now wait for the command + + // Now wait for the command. err = cmd.Wait() elapsed := time.Since(t0).Round(time.Millisecond) if err != nil { - opts.logger.Logf("[Step %d] took %s; error running Docker container: %+v", i+1, elapsed, err) - return stdoutBuffer, stderrBuffer, newStepFailedErr(err) + opts.logger.Logf("[Step %d] took %s; error running Docker container: %+v", stepIdx+1, elapsed, err) + return stdout, stderr, newStepFailedErr(err) } - opts.logger.Logf("[Step %d] complete in %s", i+1, elapsed) - return stdoutBuffer, stderrBuffer, nil + opts.logger.Logf("[Step %d] complete in %s", stepIdx+1, elapsed) + return stdout, stderr, nil } func setOutputs(stepOutputs batcheslib.Outputs, global map[string]interface{}, stepCtx *template.StepContext) error { diff --git a/internal/batches/executor/task.go b/internal/batches/executor/task.go index adbca3bbca..b6b2ee8b04 100644 --- a/internal/batches/executor/task.go +++ b/internal/batches/executor/task.go @@ -32,10 +32,12 @@ type Task struct { // we can make it work with caching BatchChangeAttributes *template.BatchChangeAttributes `json:"-"` - Archive repozip.Archive `json:"-"` + RepoArchive repozip.Archive `json:"-"` - CachedResultFound bool `json:"-"` - CachedResult execution.AfterStepResult `json:"-"` + // CachedStepResultFound is true when a partial execution result was found in the cache. + // When this field is true, CachedStepResult is also populated. + CachedStepResultFound bool `json:"-"` + CachedStepResult execution.AfterStepResult `json:"-"` } func (t *Task) ArchivePathToFetch() string { @@ -45,33 +47,34 @@ func (t *Task) ArchivePathToFetch() string { return "" } -func (t *Task) cacheKey(globalEnv []string, isRemote bool) *cache.ExecutionKeyWithGlobalEnv { +func (t *Task) cacheKey(globalEnv []string, isRemote bool, stepIndex int) cache.Keyer { var metadataRetriever cache.MetadataRetriever // If the task is being run locally, set the metadata retrieve to use the filesystem based implementation. if !isRemote { metadataRetriever = fileMetadataRetriever{} } - return &cache.ExecutionKeyWithGlobalEnv{ - GlobalEnv: globalEnv, - ExecutionKey: &cache.ExecutionKey{ - Repository: batcheslib.Repository{ - ID: t.Repository.ID, - Name: t.Repository.Name, - BaseRef: t.Repository.BaseRef(), - BaseRev: t.Repository.Rev(), - FileMatches: t.Repository.SortedFileMatches(), - }, - Path: t.Path, - OnlyFetchWorkspace: t.OnlyFetchWorkspace, - Steps: t.Steps, - BatchChangeAttributes: t.BatchChangeAttributes, - MetadataRetriever: metadataRetriever, + return &cache.CacheKey{ + Repository: batcheslib.Repository{ + ID: t.Repository.ID, + Name: t.Repository.Name, + BaseRef: t.Repository.BaseRef(), + BaseRev: t.Repository.Rev(), + FileMatches: t.Repository.SortedFileMatches(), }, + Path: t.Path, + OnlyFetchWorkspace: t.OnlyFetchWorkspace, + Steps: t.Steps, + BatchChangeAttributes: t.BatchChangeAttributes, + // TODO: This should be cached. + MetadataRetriever: metadataRetriever, + + GlobalEnv: globalEnv, + + StepIndex: stepIndex, } } -type fileMetadataRetriever struct { -} +type fileMetadataRetriever struct{} func (f fileMetadataRetriever) Get(steps []batcheslib.Step) ([]cache.MountMetadata, error) { var mountsMetadata []cache.MountMetadata @@ -109,6 +112,8 @@ func getMountMetadata(path string) ([]cache.MountMetadata, error) { return metadata, nil } +// getDirectoryMountMetadata reads all the files in the directory with the given +// path and returns the cache.MountMetadata for all of them. func getDirectoryMountMetadata(path string) ([]cache.MountMetadata, error) { dir, err := os.ReadDir(path) if err != nil { @@ -127,13 +132,3 @@ func getDirectoryMountMetadata(path string) ([]cache.MountMetadata, error) { } return metadata, nil } - -func cacheKeyForStep(key *cache.ExecutionKeyWithGlobalEnv, stepIndex int) *cache.StepsCacheKeyWithGlobalEnv { - return &cache.StepsCacheKeyWithGlobalEnv{ - StepsCacheKey: &cache.StepsCacheKey{ - ExecutionKey: key.ExecutionKey, - StepIndex: stepIndex, - }, - GlobalEnv: key.GlobalEnv, - } -} diff --git a/internal/batches/executor/testdata/dummydocker/docker b/internal/batches/executor/testdata/dummydocker/docker index c78c22f214..b21ba30c29 100755 --- a/internal/batches/executor/testdata/dummydocker/docker +++ b/internal/batches/executor/testdata/dummydocker/docker @@ -32,7 +32,7 @@ if [[ "${1}" == "run" ]]; then # 2. The script that we need to execute # # We need (1) to execute (2) in the correct subfolder. - # And (2) is in the in the matching host temp file, which should + # And (2) is in the matching host temp file, which should # be mounted into the temp file inside the container. # # We need to find it in the args and then execute it. @@ -59,6 +59,11 @@ if [[ "${1}" == "run" ]]; then # Let's strip the prefix off the workdir relative_workdir="${workdir#"${workdir_prefix}"}" + if [[ "$relative_workdir" = "/work" ]]; then + # If we couldn't strip of the prefix, it's still "/work", so we set + # it to "". + relative_workdir="" + fi # If the non-prefixed version is not blank, then we need to `cd` into it if [[ ! -z "${relative_workdir}" ]]; then cd "${relative_workdir}" diff --git a/internal/batches/executor/ui.go b/internal/batches/executor/ui.go index 4ddd360689..38c24340bb 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 string, changes *git.Changes, outputs map[string]interface{}) + StepFinished(idx int, diff string, changes git.Changes, outputs map[string]interface{}) 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 string, changes *git.Changes, outputs map[string]interface{}) { +func (noop NoopStepsExecUI) StepFinished(idx int, diff string, changes git.Changes, outputs map[string]interface{}) { } func (noop NoopStepsExecUI) StepFailed(idx int, err error, exitCode int) { } diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index fb7a12632f..93383bc07e 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -99,8 +99,8 @@ func (svc *Service) DetermineFeatureFlags(ctx context.Context) error { return svc.features.SetFromVersion(version) } -func (svc *Service) SetFeatureFlagsForRelease(release string) error { - return svc.features.SetFromVersion(release) +func (svc *Service) SetFeatureFlagsForVersion(version string) error { + return svc.features.SetFromVersion(version) } // TODO(campaigns-deprecation): this shim can be removed in Sourcegraph 4.0. @@ -396,7 +396,7 @@ func validateMount(batchSpecDir string, spec *batcheslib.BatchSpec, isRemote boo for i, step := range spec.Steps { for j, mount := range step.Mount { if isRemote { - return errors.New("mounts are not support for server-side processing") + return errors.New("mounts are not supported for server-side processing") } p := mount.Path if !filepath.IsAbs(p) { @@ -419,6 +419,7 @@ func validateMount(batchSpecDir string, spec *batcheslib.BatchSpec, isRemote boo } // Update the mount path to the absolute path so building the absolute path (above) does not need to be // redone when adding the mount argument to the Docker container. + // TODO: Can this mess with caching? We wouldn't be doing that server-side. step.Mount[j].Path = p } } diff --git a/internal/batches/service/service_test.go b/internal/batches/service/service_test.go index 5b74f11b4d..2a25e7f8be 100644 --- a/internal/batches/service/service_test.go +++ b/internal/batches/service/service_test.go @@ -1027,7 +1027,7 @@ changesetTemplate: message: Test `, isRemote: true, - expectedErr: errors.New("handling mount: mounts are not support for server-side processing"), + expectedErr: errors.New("handling mount: mounts are not supported for server-side processing"), }, } for _, test := range tests { diff --git a/internal/batches/ui/json_lines.go b/internal/batches/ui/json_lines.go index e3674a1763..220914f243 100644 --- a/internal/batches/ui/json_lines.go +++ b/internal/batches/ui/json_lines.go @@ -174,10 +174,6 @@ func (ui *JSONLines) ExecutionError(err error) { var _ executor.JSONCacheWriter = &JSONLines{} -func (ui *JSONLines) WriteExecutionResult(key string, value execution.Result) { - // Noop, we don't need execution results. -} - func (ui *JSONLines) WriteAfterStepResult(key string, value execution.AfterStepResult) { logOperationSuccess(batcheslib.LogEventOperationCacheAfterStepResult, &batcheslib.CacheAfterStepResultMetadata{ Key: key, @@ -210,8 +206,8 @@ func (ui *taskExecutionJSONLines) Start(tasks []*executor.Task) { Repository: t.Repository.Name, Workspace: t.Path, Steps: t.Steps, - CachedStepResultsFound: t.CachedResultFound, - StartStep: t.CachedResult.StepIndex, + CachedStepResultsFound: t.CachedStepResultFound, + StartStep: t.CachedStepResult.StepIndex, } ui.linesTasks[t] = linesTask linesTasks = append(linesTasks, linesTask) @@ -329,7 +325,7 @@ func (ui *stepsExecutionJSONLines) StepOutputWriter(ctx context.Context, task *e return NewIntervalProcessWriter(ctx, stepFlushDuration, sink) } -func (ui *stepsExecutionJSONLines) StepFinished(step int, diff string, changes *git.Changes, outputs map[string]interface{}) { +func (ui *stepsExecutionJSONLines) StepFinished(step int, diff string, changes git.Changes, outputs map[string]interface{}) { logOperationSuccess( batcheslib.LogEventOperationTaskStep, &batcheslib.TaskStepMetadata{ diff --git a/internal/batches/ui/task_exec_tui.go b/internal/batches/ui/task_exec_tui.go index 5f18dfe1a7..606396ef89 100644 --- a/internal/batches/ui/task_exec_tui.go +++ b/internal/batches/ui/task_exec_tui.go @@ -471,7 +471,7 @@ func (ui stepsExecTUI) StepOutputWriter(ctx context.Context, task *executor.Task return executor.NoopStepOutputWriter{} } -func (ui stepsExecTUI) StepFinished(idx int, diff string, changes *git.Changes, outputs map[string]interface{}) { +func (ui stepsExecTUI) StepFinished(idx int, diff string, changes git.Changes, outputs map[string]interface{}) { // 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 4211afb525..572155f11b 100644 --- a/internal/batches/ui/task_exec_tui_test.go +++ b/internal/batches/ui/task_exec_tui_test.go @@ -9,6 +9,7 @@ import ( "github.com/google/go-cmp/cmp" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/output" + "github.com/sourcegraph/src-cli/internal/batches/executor" "github.com/sourcegraph/src-cli/internal/batches/graphql" ) @@ -77,7 +78,7 @@ func TestTaskExecTUI_Integration(t *testing.T) { printer.TaskStarted(tasks[2]) expectOutput(t, buf, []string{ - "⠋ Executing... (0/4, 0 errored) ", + "⠋ Executing... (0/4, 0 errored) 0%", "│ ", "├── github.com/sourcegraph/sourcegraph ... 0s", "├── github.com/sourcegraph/src-cli ... 0s", @@ -91,7 +92,7 @@ func TestTaskExecTUI_Integration(t *testing.T) { printer.TaskCurrentlyExecuting(tasks[2], "echo Hello World > README.md") expectOutput(t, buf, []string{ - "⠋ Executing... (0/4, 0 errored) ", + "⠋ Executing... (0/4, 0 errored) 0%", "│ ", "├── github.com/sourcegraph/sourcegraph echo Hello World > README.md 0s", "├── github.com/sourcegraph/src-cli Downloading archive 0s", @@ -105,7 +106,7 @@ func TestTaskExecTUI_Integration(t *testing.T) { printer.TaskCurrentlyExecuting(tasks[2], "echo Hello World > README.md") expectOutput(t, buf, []string{ - "⠋ Executing... (0/4, 0 errored) ", + "⠋ Executing... (0/4, 0 errored) 0%", "│ ", "├── github.com/sourcegraph/sourcegraph gofmt 0s", "├── github.com/sourcegraph/src-cli echo Hello World > README.md 0s", @@ -118,7 +119,7 @@ func TestTaskExecTUI_Integration(t *testing.T) { printer.TaskFinished(tasks[2], nil) expectOutput(t, buf, []string{ - "⠋ Executing... (1/4, 0 errored) ███████████▌", + "⠋ Executing... (1/4, 0 errored) ██████████▎ 25%", "│ ", "├── github.com/sourcegraph/sourcegraph gofmt 0s", "├── github.com/sourcegraph/src-cli echo Hello World > README.md 0s", @@ -131,7 +132,7 @@ func TestTaskExecTUI_Integration(t *testing.T) { printer.TaskFinished(tasks[0], nil) expectOutput(t, buf, []string{ - "⠋ Executing... (2/4, 0 errored) ███████████████████████", + "⠋ Executing... (2/4, 0 errored) ████████████████████▌ 50%", "│ ", "├── github.com/sourcegraph/sourcegraph Done! 0s", "├── github.com/sourcegraph/src-cli echo Hello World > README.md 0s", @@ -168,7 +169,7 @@ func TestTaskExecTUI_Integration(t *testing.T) { " 3 files changed, 4 insertions, 2 deletions", " Execution took 10s", "", - "⠋ Executing... (2/4, 0 errored) ███████████████████████", + "⠋ Executing... (2/4, 0 errored) ████████████████████▌ 50%", "│ ", "├── github.com/sourcegraph/sourcegraph Done! 0s", "├── github.com/sourcegraph/src-cli echo Hello World > README.md 0s", @@ -188,7 +189,7 @@ func TestTaskExecTUI_Integration(t *testing.T) { " 3 files changed, 4 insertions, 2 deletions", " Execution took 10s", "", - "⠋ Executing... (2/4, 0 errored) ███████████████████████", + "⠋ Executing... (2/4, 0 errored) ████████████████████▌ 50%", "│ ", "├── github.com/sourcegraph/tiny-go-... rm -rf ~/.horse-ascii-art 0s", "├── github.com/sourcegraph/src-cli echo Hello World > README.md 0s", @@ -236,7 +237,7 @@ func TestProgressUpdateAfterComplete(t *testing.T) { printer.TaskCurrentlyExecuting(tasks[1], "Downloading archive") expectOutput(t, buf, []string{ - "⠋ Executing... (0/2, 0 errored) ", + "⠋ Executing... (0/2, 0 errored) 0%", "│ ", "├── github.com/sourcegraph/sourcegraph echo Hello World > README.md 0s", "└── github.com/sourcegraph/src-cli Downloading archive 0s", @@ -253,7 +254,7 @@ func TestProgressUpdateAfterComplete(t *testing.T) { // The actual output is slightly less important at this point, but let's // check it anyway. expectOutput(t, buf, []string{ - "✅ Executing... (0/2, 0 errored) ██████████████████████████████████████████████", + "✅ Executing... (0/2, 0 errored) ████████████████████████████████████████ 100%", "│ ", "├── github.com/sourcegraph/sourcegraph exit 42 0s", "└── github.com/sourcegraph/src-cli Downloading archive 0s", diff --git a/internal/batches/workspace/bind_workspace.go b/internal/batches/workspace/bind_workspace.go index 9bc346ddd8..6ae4c57c78 100644 --- a/internal/batches/workspace/bind_workspace.go +++ b/internal/batches/workspace/bind_workspace.go @@ -129,22 +129,22 @@ func (w *dockerBindWorkspace) DockerRunOpts(ctx context.Context, target string) func (w *dockerBindWorkspace) WorkDir() *string { return &w.dir } -func (w *dockerBindWorkspace) Changes(ctx context.Context) (*git.Changes, error) { +func (w *dockerBindWorkspace) Changes(ctx context.Context) (git.Changes, error) { if _, err := runGitCmd(ctx, w.dir, "add", "--all"); err != nil { - return nil, errors.Wrap(err, "git add failed") + return git.Changes{}, errors.Wrap(err, "git add failed") } statusOut, err := runGitCmd(ctx, w.dir, "status", "--porcelain", "--no-ahead-behind") if err != nil { - return nil, errors.Wrap(err, "git status failed") + return git.Changes{}, errors.Wrap(err, "git status failed") } changes, err := git.ParseGitStatus(statusOut) if err != nil { - return nil, errors.Wrap(err, "parsing git status output") + return git.Changes{}, errors.Wrap(err, "parsing git status output") } - return &changes, nil + return changes, nil } func (w *dockerBindWorkspace) Diff(ctx context.Context) ([]byte, error) { diff --git a/internal/batches/workspace/volume_workspace.go b/internal/batches/workspace/volume_workspace.go index 551d1100ad..9be8ac8c49 100644 --- a/internal/batches/workspace/volume_workspace.go +++ b/internal/batches/workspace/volume_workspace.go @@ -229,7 +229,7 @@ func (w *dockerVolumeWorkspace) DockerRunOpts(ctx context.Context, target string func (w *dockerVolumeWorkspace) WorkDir() *string { return nil } -func (w *dockerVolumeWorkspace) Changes(ctx context.Context) (*git.Changes, error) { +func (w *dockerVolumeWorkspace) Changes(ctx context.Context) (git.Changes, error) { script := `#!/bin/sh set -e @@ -241,15 +241,15 @@ exec git status --porcelain out, err := w.runScript(ctx, "/work", script) if err != nil { - return nil, errors.Wrap(err, "running git status") + return git.Changes{}, errors.Wrap(err, "running git status") } changes, err := git.ParseGitStatus(out) if err != nil { - return nil, errors.Wrapf(err, "parsing git status output:\n\n%s", string(out)) + return git.Changes{}, errors.Wrapf(err, "parsing git status output:\n\n%s", string(out)) } - return &changes, nil + return changes, nil } func (w *dockerVolumeWorkspace) Diff(ctx context.Context) ([]byte, error) { diff --git a/internal/batches/workspace/volume_workspace_test.go b/internal/batches/workspace/volume_workspace_test.go index 21dbb653ce..9d3526e6e3 100644 --- a/internal/batches/workspace/volume_workspace_test.go +++ b/internal/batches/workspace/volume_workspace_test.go @@ -446,11 +446,11 @@ func TestVolumeWorkspace_Changes(t *testing.T) { t.Run("success", func(t *testing.T) { for name, tc := range map[string]struct { stdout string - want *git.Changes + want git.Changes }{ "empty": { stdout: "", - want: &git.Changes{}, + want: git.Changes{}, }, "valid": { stdout: ` @@ -458,7 +458,7 @@ M go.mod M internal/campaigns/volume_workspace.go M internal/campaigns/volume_workspace_test.go `, - want: &git.Changes{Modified: []string{ + want: git.Changes{Modified: []string{ "go.mod", "internal/campaigns/volume_workspace.go", "internal/campaigns/volume_workspace_test.go", diff --git a/internal/batches/workspace/workspace.go b/internal/batches/workspace/workspace.go index 7ed7881eb0..7f173b71b6 100644 --- a/internal/batches/workspace/workspace.go +++ b/internal/batches/workspace/workspace.go @@ -41,7 +41,7 @@ type Workspace interface { // Changes is called after each step is executed, and should return the // cumulative file changes that have occurred since Prepare was called. - Changes(ctx context.Context) (*git.Changes, error) + Changes(ctx context.Context) (git.Changes, error) // Diff should return the total diff for the workspace. This may be called // multiple times in the life of a workspace. From 2fbc937c112adccd02d8f0e961812781acea2d94 Mon Sep 17 00:00:00 2001 From: Noah S-C Date: Mon, 11 Jul 2022 07:54:06 -0700 Subject: [PATCH 203/647] remove quotes from upload ID URL (#799) --- cmd/src/code_intel_upload.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/src/code_intel_upload.go b/cmd/src/code_intel_upload.go index ac57fc9c12..7035d20383 100644 --- a/cmd/src/code_intel_upload.go +++ b/cmd/src/code_intel_upload.go @@ -200,7 +200,7 @@ func makeCodeIntelUploadURL(uploadID int) (string, error) { return "", err } - graphqlID := base64.URLEncoding.EncodeToString([]byte(fmt.Sprintf(`LSIFUpload:"%d"`, uploadID))) + graphqlID := base64.URLEncoding.EncodeToString([]byte(fmt.Sprintf(`LSIFUpload:%d`, uploadID))) url.Path = codeintelUploadFlags.repo + "/-/code-intelligence/uploads/" + graphqlID url.User = nil return url.String(), nil From 16f9963990e40100c8e0449f96e9a00c2a153ff7 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Mon, 11 Jul 2022 19:27:42 +0200 Subject: [PATCH 204/647] Refactor execution to be able to use runSteps in exec mode directly (#798) --- CHANGELOG.md | 14 +- cmd/src/batch_common.go | 46 +++-- cmd/src/batch_exec.go | 190 +++++++----------- cmd/src/batch_repositories.go | 4 +- cmd/src/batch_validate.go | 4 +- go.mod | 2 +- go.sum | 4 +- internal/batches/docker/cache.go | 20 +- internal/batches/executor/coordinator.go | 116 +++-------- internal/batches/executor/coordinator_test.go | 19 +- internal/batches/executor/execution_cache.go | 41 ---- internal/batches/executor/executor.go | 84 +++----- internal/batches/executor/executor_test.go | 6 +- internal/batches/executor/run_steps.go | 184 ++++++++++------- internal/batches/executor/task.go | 21 +- internal/batches/log/noop_manager.go | 21 -- internal/batches/mock/cache.go | 10 +- internal/batches/repozip/fetcher.go | 2 +- internal/batches/repozip/noop.go | 23 +-- internal/batches/service/service.go | 49 ++--- internal/batches/service/service_test.go | 54 +++-- internal/batches/ui/json_lines.go | 8 - internal/batches/workspace/bind_workspace.go | 19 +- .../batches/workspace/volume_workspace.go | 30 +-- .../workspace/volume_workspace_test.go | 87 -------- internal/batches/workspace/workspace.go | 8 +- 26 files changed, 387 insertions(+), 679 deletions(-) delete mode 100644 internal/batches/log/noop_manager.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 28a2ed9933..ef8d238b50 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,17 +13,27 @@ All notable changes to `src-cli` are documented in this file. ### Added +### Changed + +### Fixed + +### Removed + +## 3.41.1 + +### Added + - Batch specs that mount paths now cache results. [sourcegraph/sourcegraph#37216](https://github.com/sourcegraph/sourcegraph/issues/37216) - `SRC_HEADERS="key:value\nkey2:value2"` is now supported for passing multiple headers when authenticating `src` with custom auth proxies. See [auth proxy configuration docs](AUTH_PROXY.md) for more information. [#796](https://github.com/sourcegraph/src-cli/pull/796) ### Changed +- Some internal changes to `src batch exec` mode for server-side execution. + ### Fixed - Handle SIGINT interrupt when reading from Stdin. [#794](https://github.com/sourcegraph/src-cli/pull/794) -### Removed - ## 3.41.0 ### Changed diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index 7b47d0556d..189867bbff 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -275,11 +275,11 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp }() svc := service.New(&service.Opts{ - AllowUnsupported: opts.flags.allowUnsupported, - AllowIgnored: opts.flags.allowIgnored, - Client: opts.client, + Client: opts.client, }) + imageCache := docker.NewImageCache() + if err := svc.DetermineFeatureFlags(ctx); err != nil { return err } @@ -324,7 +324,10 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp if len(batchSpec.Steps) > 0 { ui.PreparingContainerImages() images, err := svc.EnsureDockerImages( - ctx, batchSpec.Steps, parallelism, + ctx, + imageCache, + batchSpec.Steps, + parallelism, ui.PreparingContainerImagesProgress, ) if err != nil { @@ -336,7 +339,8 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp var typ workspace.CreatorType workspaceCreator, typ = workspace.NewCreator(ctx, opts.flags.workspace, opts.flags.cacheDir, opts.flags.tempDir, images) if typ == workspace.CreatorTypeVolume { - _, err = svc.EnsureImage(ctx, workspace.DockerVolumeWorkspaceImage) + // This creator type requires an additional image, so let's ensure it exists. + _, err = imageCache.Ensure(ctx, workspace.DockerVolumeWorkspaceImage) if err != nil { return err } @@ -345,7 +349,7 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp } ui.ResolvingRepositories() - repos, err := svc.ResolveRepositories(ctx, batchSpec) + repos, err := svc.ResolveRepositories(ctx, batchSpec, opts.flags.allowUnsupported, opts.flags.allowIgnored) if err != nil { if repoSet, ok := err.(batches.UnsupportedRepoSet); ok { ui.ResolvingRepositoriesDone(repos, repoSet, nil) @@ -366,19 +370,25 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp ui.DeterminingWorkspacesSuccess(len(workspaces)) archiveRegistry := repozip.NewArchiveRegistry(opts.client, opts.flags.cacheDir, opts.flags.cleanArchives) - - // EXECUTION OF TASKS - coord := svc.NewCoordinator( - archiveRegistry, - log.NewDiskManager(opts.flags.tempDir, opts.flags.keepLogs), + logManager := log.NewDiskManager(opts.flags.tempDir, opts.flags.keepLogs) + coord := executor.NewCoordinator( executor.NewCoordinatorOpts{ - Creator: workspaceCreator, - Cache: executor.NewDiskCache(opts.flags.cacheDir), - Parallelism: parallelism, - Timeout: opts.flags.timeout, - TempDir: opts.flags.tempDir, - GlobalEnv: os.Environ(), - IsRemote: false, + ExecOpts: executor.NewExecutorOpts{ + Logger: logManager, + RepoArchiveRegistry: archiveRegistry, + Creator: workspaceCreator, + EnsureImage: imageCache.Ensure, + Parallelism: parallelism, + Timeout: opts.flags.timeout, + TempDir: opts.flags.tempDir, + GlobalEnv: os.Environ(), + IsRemote: false, + }, + Features: svc.Features(), + Logger: logManager, + Cache: executor.NewDiskCache(opts.flags.cacheDir), + GlobalEnv: os.Environ(), + IsRemote: false, }, ) diff --git a/cmd/src/batch_exec.go b/cmd/src/batch_exec.go index f64b9f1653..c8e0f0ead2 100644 --- a/cmd/src/batch_exec.go +++ b/cmd/src/batch_exec.go @@ -6,14 +6,13 @@ import ( "flag" "fmt" "io" - "net/http" "os" "path/filepath" "time" "github.com/sourcegraph/sourcegraph/lib/errors" - "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/batches/docker" "github.com/sourcegraph/src-cli/internal/batches/executor" "github.com/sourcegraph/src-cli/internal/batches/graphql" "github.com/sourcegraph/src-cli/internal/batches/log" @@ -31,39 +30,29 @@ const ( ) type executorModeFlags struct { - sourcegraphVersion string - timeout time.Duration - file string - tempDir string - cacheDir string - repoDir string + timeout time.Duration + file string + tempDir string + repoDir string } func newExecutorModeFlags(flagSet *flag.FlagSet) (f *executorModeFlags) { f = &executorModeFlags{} - flagSet.StringVar(&f.sourcegraphVersion, "sourcegraphVersion", "", "Sourcegraph backend version.") flagSet.DurationVar(&f.timeout, "timeout", 60*time.Minute, "The maximum duration a single batch spec step can take.") flagSet.StringVar(&f.file, "f", "", "The workspace execution input file to read.") flagSet.StringVar(&f.tempDir, "tmp", "", "Directory for storing temporary data.") - flagSet.StringVar(&f.cacheDir, "cache", "", "Directory to read cached results from.") flagSet.StringVar(&f.repoDir, "repo", "", "Path of the checked out repo on disk.") return f } func validateExecutorModeFlags(f *executorModeFlags) error { - if f.sourcegraphVersion == "" { - return errors.New("sourcegraphVersion parameter missing") - } if f.file == "" { return errors.New("input file parameter missing") } if f.tempDir == "" { return errors.New("tempDir parameter missing") } - if f.cacheDir == "" { - return errors.New("cacheDir parameter missing") - } if f.repoDir == "" { return errors.New("repoDir parameter missing") } @@ -128,12 +117,8 @@ Examples: func executeBatchSpecInWorkspaces(ctx context.Context, flags *executorModeFlags) (err error) { ui := &ui.JSONLines{} - defer func() { - if err != nil { - ui.ExecutionError(err) - } - }() + // Ensure the temp dir exists. tempDir := flags.tempDir if !filepath.IsAbs(tempDir) { tempDir, err = filepath.Abs(tempDir) @@ -146,6 +131,7 @@ func executeBatchSpecInWorkspaces(ctx context.Context, flags *executorModeFlags) } } + // Grab the absolute path to the repo contents. repoDir := flags.repoDir if !filepath.IsAbs(repoDir) { repoDir, err = filepath.Abs(repoDir) @@ -154,24 +140,11 @@ func executeBatchSpecInWorkspaces(ctx context.Context, flags *executorModeFlags) } } - svc := service.New(&service.Opts{ - // When this workspace made it to here, it's already been validated. - AllowUnsupported: true, - // When this workspace made it to here, it's already been validated. - AllowIgnored: true, - // We don't want src to talk to the sg instance, if it would, this - // is a regression. Therefor, we have this dead client that kills the - // process when something should try to talk to src. - Client: &deadClient{}, - }) - - if err := svc.SetFeatureFlagsForVersion(flags.sourcegraphVersion); err != nil { - return err - } - + // Test if git is available. if err := checkExecutable("git", "version"); err != nil { return err } + // Test if docker is available. if err := checkExecutable("docker", "version"); err != nil { return err } @@ -182,75 +155,65 @@ func executeBatchSpecInWorkspaces(ctx context.Context, flags *executorModeFlags) if err != nil { return err } - - // Since we already know which workspace we want to execute the steps in, - // we can convert it to a RepoWorkspace and build a task only for that one. - tasks := svc.BuildTasks(ctx, &input.BatchChangeAttributes, []service.RepoWorkspace{convertWorkspace(input)}) - - if len(tasks) != 1 { - return errors.New("invalid input, didn't yield exactly one task") - } - - task := tasks[0] + task := convertWorkspace(input) if len(task.Steps) == 0 { return errors.New("invalid execution, no steps to process") } - { - ui.PreparingContainerImages() - _, err = svc.EnsureDockerImages( - ctx, - task.Steps, - execPullParallelism, - ui.PreparingContainerImagesProgress, - ) - if err != nil { - return err - } - ui.PreparingContainerImagesSuccess() - } - - coord := svc.NewCoordinator( - repozip.NewNoopRegistry(), - log.NewNoopManager(), - executor.NewCoordinatorOpts{ - Creator: workspace.NewExecutorWorkspaceCreator(tempDir, repoDir), - Cache: &executor.ServerSideCache{CacheDir: flags.cacheDir, Writer: ui}, - Parallelism: 1, - // TODO: Should be slightly less than the executor timeout. Can we somehow read that? - Timeout: flags.timeout, - TempDir: tempDir, - // Don't allow to read from env. - GlobalEnv: []string{}, - // Temporarily prevent the ability to sending a batch spec with a mount for server-side processing. - IsRemote: true, - }, - ) + imageCache := docker.NewImageCache() - // `src batch exec` uses server-side caching for changeset specs, so we - // only need to call `CheckStepResultsCache` to make sure that per-step cache entries - // are loaded and set on the tasks. - if err := coord.CheckStepResultsCache( + ui.PreparingContainerImages() + _, err = service.New(&service.Opts{}).EnsureDockerImages( ctx, - tasks, - // Don't expose the executor env, we don't allow env forwarding anyways. - []string{}, - ); err != nil { + imageCache, + task.Steps, + execPullParallelism, + ui.PreparingContainerImagesProgress, + ) + if err != nil { return err } + ui.PreparingContainerImagesSuccess() + + // Empty for now until we support secrets or env var settings in SSBC. + globalEnv := []string{} + isRemote := true - // These arguments are unused in the json logs implementation, but the interface - // dictates them. + // Set up the execution UI. taskExecUI := ui.ExecutingTasks(false, 1) - err = coord.Execute(ctx, tasks, taskExecUI) - if err != nil { - taskExecUI.Failed(err) - return err + taskExecUI.Start([]*executor.Task{task}) + taskExecUI.TaskStarted(task) + + opts := &executor.RunStepsOpts{ + Logger: &log.NoopTaskLogger{}, + WC: workspace.NewExecutorWorkspaceCreator(tempDir, repoDir), + EnsureImage: imageCache.Ensure, + Task: task, + // TODO: Should be slightly less than the executor timeout. Can we somehow read that? + Timeout: flags.timeout, + TempDir: tempDir, + GlobalEnv: globalEnv, + // Temporarily prevent the ability to sending a batch spec with a mount for server-side processing. + IsRemote: isRemote, + RepoArchive: &repozip.NoopArchive{}, + UI: taskExecUI.StepsExecutionUI(task), } + results, err := executor.RunSteps(ctx, opts) - taskExecUI.Success() - return nil + // Write all step cache results for all results. + for _, stepRes := range results { + cacheKey := task.CacheKey(globalEnv, isRemote, stepRes.StepIndex) + k, err := cacheKey.Key() + if err != nil { + return errors.Wrap(err, "calculating step cache key") + } + ui.WriteAfterStepResult(k, stepRes) + } + + taskExecUI.TaskFinished(task, err) + + return err } func loadWorkspaceExecutionInput(file string) (input batcheslib.WorkspacesExecutionInput, err error) { @@ -272,13 +235,16 @@ func loadWorkspaceExecutionInput(file string) (input batcheslib.WorkspacesExecut return input, nil } -func convertWorkspace(w batcheslib.WorkspacesExecutionInput) service.RepoWorkspace { +// convertWorkspace takes the WorkspacesExecutionInput and restructures it into +// an executor.Task. +func convertWorkspace(w batcheslib.WorkspacesExecutionInput) *executor.Task { fileMatches := make(map[string]bool) for _, path := range w.SearchResultPaths { fileMatches[path] = true } - return service.RepoWorkspace{ - Repo: &graphql.Repository{ + + task := &executor.Task{ + Repository: &graphql.Repository{ ID: w.Repository.ID, Name: w.Repository.Name, Branch: graphql.Branch{ @@ -290,33 +256,13 @@ func convertWorkspace(w batcheslib.WorkspacesExecutionInput) service.RepoWorkspa Commit: graphql.Target{OID: w.Branch.Target.OID}, FileMatches: fileMatches, }, - Path: w.Path, - Steps: w.Steps, - OnlyFetchWorkspace: w.OnlyFetchWorkspace, + Path: w.Path, + Steps: w.Steps, + OnlyFetchWorkspace: w.OnlyFetchWorkspace, + BatchChangeAttributes: &w.BatchChangeAttributes, + CachedStepResultFound: w.CachedStepResultFound, + CachedStepResult: w.CachedStepResult, } -} - -type deadClient struct{} - -var _ api.Client = &deadClient{} - -const deadClientPanicMsg = "Dead client invoked. This indicates a bug in src-cli in server-side execution, please report this." -func (c *deadClient) NewQuery(query string) api.Request { - panic(deadClientPanicMsg) -} -func (c *deadClient) NewRequest(query string, vars map[string]interface{}) api.Request { - panic(deadClientPanicMsg) -} -func (c *deadClient) NewGzippedRequest(query string, vars map[string]interface{}) api.Request { - panic(deadClientPanicMsg) -} -func (c *deadClient) NewGzippedQuery(query string) api.Request { - panic(deadClientPanicMsg) -} -func (c *deadClient) NewHTTPRequest(ctx context.Context, method, path string, body io.Reader) (*http.Request, error) { - panic(deadClientPanicMsg) -} -func (c *deadClient) Do(req *http.Request) (*http.Response, error) { - panic(deadClientPanicMsg) + return task } diff --git a/cmd/src/batch_repositories.go b/cmd/src/batch_repositories.go index 8adbfd9643..7346becabf 100644 --- a/cmd/src/batch_repositories.go +++ b/cmd/src/batch_repositories.go @@ -60,9 +60,7 @@ Examples: client := cfg.apiClient(apiFlags, flagSet.Output()) svc := service.New(&service.Opts{ - Client: client, - AllowUnsupported: allowUnsupported, - AllowIgnored: allowIgnored, + Client: client, }) if err := svc.DetermineFeatureFlags(ctx); err != nil { diff --git a/cmd/src/batch_validate.go b/cmd/src/batch_validate.go index db0e9d73e4..ae5b20e1e4 100644 --- a/cmd/src/batch_validate.go +++ b/cmd/src/batch_validate.go @@ -60,9 +60,7 @@ Examples: out := output.NewOutput(flagSet.Output(), output.OutputOpts{Verbose: *verbose}) ui := &ui.TUI{Out: out} svc := service.New(&service.Opts{ - Client: cfg.apiClient(apiFlags, flagSet.Output()), - AllowUnsupported: allowUnsupported, - AllowIgnored: allowIgnored, + Client: cfg.apiClient(apiFlags, flagSet.Output()), }) if err := svc.DetermineFeatureFlags(ctx); err != nil { diff --git a/go.mod b/go.mod index 8c668b9514..6ad5f49533 100644 --- a/go.mod +++ b/go.mod @@ -20,7 +20,7 @@ require ( github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf github.com/sourcegraph/scip v0.1.0 - github.com/sourcegraph/sourcegraph/lib v0.0.0-20220708204051-cb0aebdbfd74 + github.com/sourcegraph/sourcegraph/lib v0.0.0-20220711172327-614bf6eac4e0 github.com/stretchr/testify v1.7.2 golang.org/x/net v0.0.0-20220526153639-5463443f8c37 golang.org/x/sync v0.0.0-20210220032951-036812b2e83c diff --git a/go.sum b/go.sum index 06faa55e57..bfe1dd250a 100644 --- a/go.sum +++ b/go.sum @@ -351,8 +351,8 @@ github.com/sourcegraph/log v0.0.0-20220707160925-6a936691c838 h1:8wknDSCUVYbaRT6 github.com/sourcegraph/log v0.0.0-20220707160925-6a936691c838/go.mod h1:zWEPlKrWBUVpko/tOgDS+qrp7BmzaCcmUrh9+ver1iQ= github.com/sourcegraph/scip v0.1.0 h1:kTs0CJaLQvcRZjg+HpGrcJPNX2Tx31+d6szWio3ZOkQ= github.com/sourcegraph/scip v0.1.0/go.mod h1:/AZ8RvsnRfeCZy232PJuVZqcl9f82fJnYwdWZeU2JCo= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20220708204051-cb0aebdbfd74 h1:XX4rxuQeXuRdg0qNupvrGKSDXKgZyk3flwbSCGMCiFU= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20220708204051-cb0aebdbfd74/go.mod h1:4efRAk7Sv9XaetWwvOxZjiBO3i32jlsmQKpemvCJmMI= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20220711172327-614bf6eac4e0 h1:sWMGp3Mc3dGvLkGLPPe/qopXbITRi+WVkpUT0vl+DB8= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20220711172327-614bf6eac4e0/go.mod h1:4efRAk7Sv9XaetWwvOxZjiBO3i32jlsmQKpemvCJmMI= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= diff --git a/internal/batches/docker/cache.go b/internal/batches/docker/cache.go index a2d9771060..c33749498f 100644 --- a/internal/batches/docker/cache.go +++ b/internal/batches/docker/cache.go @@ -1,9 +1,15 @@ package docker -import "sync" +import ( + "context" + "sync" + + "github.com/sourcegraph/sourcegraph/lib/errors" +) type ImageCache interface { Get(name string) Image + Ensure(ctx context.Context, name string) (Image, error) } // imageCache is a cache of metadata about Docker images, indexed by name. @@ -34,3 +40,15 @@ func (ic *imageCache) Get(name string) Image { ic.images[name] = image return image } + +// Ensure returns the image cache entry for the given Docker image and makes sure +// it exists on disk. +func (ic *imageCache) Ensure(ctx context.Context, name string) (Image, error) { + img := ic.Get(name) + + if err := img.Ensure(ctx); err != nil { + return nil, errors.Wrapf(err, "pulling image %q", name) + } + + return img, nil +} diff --git a/internal/batches/executor/coordinator.go b/internal/batches/executor/coordinator.go index a3f3018787..970ae6c555 100644 --- a/internal/batches/executor/coordinator.go +++ b/internal/batches/executor/coordinator.go @@ -2,7 +2,6 @@ package executor import ( "context" - "time" "github.com/sourcegraph/sourcegraph/lib/errors" @@ -11,10 +10,7 @@ import ( "github.com/sourcegraph/sourcegraph/lib/batches/execution/cache" "github.com/sourcegraph/src-cli/internal/batches" - "github.com/sourcegraph/src-cli/internal/batches/docker" "github.com/sourcegraph/src-cli/internal/batches/log" - "github.com/sourcegraph/src-cli/internal/batches/repozip" - "github.com/sourcegraph/src-cli/internal/batches/workspace" ) type taskExecutor interface { @@ -23,57 +19,30 @@ type taskExecutor interface { } // Coordinator coordinates the execution of Tasks. It makes use of an executor, -// checks the ExecutionCache whether execution is necessary, builds +// checks the ExecutionCache whether execution is necessary, and builds // batcheslib.ChangesetSpecs out of the executionResults. type Coordinator struct { opts NewCoordinatorOpts - cache cache.Cache - exec taskExecutor - logManager log.LogManager + exec taskExecutor } -type imageEnsurer func(ctx context.Context, name string) (docker.Image, error) - type NewCoordinatorOpts struct { - // Dependencies - EnsureImage imageEnsurer - Creator workspace.Creator - Cache cache.Cache - RepoArchiveRegistry repozip.ArchiveRegistry + ExecOpts NewExecutorOpts + Cache cache.Cache + Logger log.LogManager GlobalEnv []string - // Everything that follows are either command-line flags or features. - // Used by batcheslib.BuildChangesetSpecs Features batches.FeatureFlags - - Parallelism int - Timeout time.Duration - TempDir string - IsRemote bool + IsRemote bool } -func NewCoordinator(opts NewCoordinatorOpts, logger log.LogManager) *Coordinator { - exec := newExecutor(newExecutorOpts{ - RepoArchiveRegistry: opts.RepoArchiveRegistry, - EnsureImage: opts.EnsureImage, - Creator: opts.Creator, - Logger: logger, - - Parallelism: opts.Parallelism, - Timeout: opts.Timeout, - TempDir: opts.TempDir, - IsRemote: opts.IsRemote, - GlobalEnv: opts.GlobalEnv, - }) - +func NewCoordinator(opts NewCoordinatorOpts) *Coordinator { return &Coordinator{ - opts: opts, - cache: opts.Cache, - exec: exec, - logManager: logger, + opts: opts, + exec: NewExecutor(opts.ExecOpts), } } @@ -98,22 +67,11 @@ func (c *Coordinator) CheckCache(ctx context.Context, batchSpec *batcheslib.Batc return uncached, specs, nil } -// CheckStepResultsCache checks the cache for each Task, but only for cached -// step results. This is used by `src batch exec` when executing server-side. -func (c *Coordinator) CheckStepResultsCache(ctx context.Context, tasks []*Task, globalEnv []string) error { - for _, t := range tasks { - if err := c.loadCachedStepResults(ctx, t, globalEnv); err != nil { - return err - } - } - return nil -} - func (c *Coordinator) ClearCache(ctx context.Context, tasks []*Task) error { for _, task := range tasks { for i := len(task.Steps) - 1; i > -1; i-- { - key := task.cacheKey(c.opts.GlobalEnv, c.opts.IsRemote, i) - if err := c.cache.Clear(ctx, key); err != nil { + key := task.CacheKey(c.opts.GlobalEnv, c.opts.IsRemote, i) + if err := c.opts.Cache.Clear(ctx, key); err != nil { return errors.Wrapf(err, "clearing cache for step %d in %q", i, task.Repository.Name) } } @@ -154,6 +112,7 @@ func (c Coordinator) buildChangesetSpecs(task *Task, batchSpec *batcheslib.Batch BaseRef: task.Repository.BaseRef(), BaseRev: task.Repository.Rev(), }, + Path: task.Path, BatchChangeAttributes: task.BatchChangeAttributes, Template: batchSpec.ChangesetTemplate, TransformChanges: batchSpec.TransformChanges, @@ -175,9 +134,9 @@ func (c *Coordinator) loadCachedStepResults(ctx context.Context, task *Task, glo // We start at the back so that we can find the _last_ cached step, // then restart execution on the following step. for i := len(task.Steps) - 1; i > -1; i-- { - key := task.cacheKey(globalEnv, c.opts.IsRemote, i) + key := task.CacheKey(globalEnv, c.opts.IsRemote, i) - result, found, err := c.cache.Get(ctx, key) + result, found, err := c.opts.Cache.Get(ctx, key) if err != nil { return errors.Wrapf(err, "checking for cached diff for step %d", i) } @@ -216,21 +175,28 @@ func (c *Coordinator) buildSpecs(ctx context.Context, batchSpec *batcheslib.Batc return specs, nil } -// Execute executes the given tasks. It calls the ui on updates. -func (c *Coordinator) Execute(ctx context.Context, tasks []*Task, ui TaskExecutionUI) error { - _, err := c.doExecute(ctx, tasks, ui) - - return err -} - // ExecuteAndBuildSpecs executes the given tasks and builds changeset specs for the results. // It calls the ui on updates. func (c *Coordinator) ExecuteAndBuildSpecs(ctx context.Context, batchSpec *batcheslib.BatchSpec, tasks []*Task, ui TaskExecutionUI) ([]*batcheslib.ChangesetSpec, []string, error) { - results, errs := c.doExecute(ctx, tasks, ui) + ui.Start(tasks) + + // Run executor. + c.exec.Start(ctx, tasks, ui) + results, errs := c.exec.Wait(ctx) + + // Write all step cache results to the cache. + for _, res := range results { + for _, stepRes := range res.stepResults { + cacheKey := res.task.CacheKey(c.opts.GlobalEnv, c.opts.IsRemote, stepRes.StepIndex) + if err := c.opts.Cache.Set(ctx, cacheKey, stepRes); err != nil { + return nil, nil, errors.Wrapf(err, "caching result for step %d", stepRes.StepIndex) + } + } + } var specs []*batcheslib.ChangesetSpec - // Write results to cache, build ChangesetSpecs if possible and add to list. + // Build ChangesetSpecs if possible and add to list. for _, taskResult := range results { // Don't build changeset specs for failed workspaces. if taskResult.err != nil { @@ -245,25 +211,5 @@ func (c *Coordinator) ExecuteAndBuildSpecs(ctx context.Context, batchSpec *batch specs = append(specs, taskSpecs...) } - return specs, c.logManager.LogFiles(), errs -} - -func (c *Coordinator) doExecute(ctx context.Context, tasks []*Task, ui TaskExecutionUI) (results []taskResult, err error) { - ui.Start(tasks) - - // Run executor - c.exec.Start(ctx, tasks, ui) - results, err = c.exec.Wait(ctx) - - // Write all step cache results for all results. - for _, res := range results { - for _, stepRes := range res.stepResults { - cacheKey := res.task.cacheKey(c.opts.GlobalEnv, c.opts.IsRemote, stepRes.StepIndex) - if err := c.cache.Set(ctx, cacheKey, stepRes); err != nil { - return nil, errors.Wrapf(err, "caching result for step %d", stepRes.StepIndex) - } - } - } - - return results, err + return specs, c.opts.Logger.LogFiles(), errs } diff --git a/internal/batches/executor/coordinator_test.go b/internal/batches/executor/coordinator_test.go index 64c6696bd6..93cb69a4a2 100644 --- a/internal/batches/executor/coordinator_test.go +++ b/internal/batches/executor/coordinator_test.go @@ -276,13 +276,14 @@ func TestCoordinator_Execute(t *testing.T) { } logManager := mock.LogNoOpManager{} - c := newInMemoryExecutionCache() + + tc.opts.Cache = c + tc.opts.Logger = logManager + coord := Coordinator{ - cache: c, - exec: tc.executor, - logManager: logManager, - opts: tc.opts, + exec: tc.executor, + opts: tc.opts, } // execute contains the actual logic for executing the tasks and @@ -375,7 +376,13 @@ func TestCoordinator_Execute_StepCaching(t *testing.T) { }} // Build Coordinator - coord := &Coordinator{cache: cache, exec: executor, logManager: logManager} + coord := &Coordinator{ + opts: NewCoordinatorOpts{ + Cache: cache, + Logger: logManager, + }, + exec: executor, + } batchSpec := &batcheslib.BatchSpec{ChangesetTemplate: testChangesetTemplate} diff --git a/internal/batches/executor/execution_cache.go b/internal/batches/executor/execution_cache.go index 8a96be043a..24b7f91bc0 100644 --- a/internal/batches/executor/execution_cache.go +++ b/internal/batches/executor/execution_cache.go @@ -121,44 +121,3 @@ func (ExecutionNoOpCache) Set(ctx context.Context, key cache.Keyer, result execu func (ExecutionNoOpCache) Get(ctx context.Context, key cache.Keyer) (execution.AfterStepResult, bool, error) { return execution.AfterStepResult{}, false, nil } - -type JSONCacheWriter interface { - WriteAfterStepResult(key string, value execution.AfterStepResult) -} - -type ServerSideCache struct { - CacheDir string - Writer JSONCacheWriter -} - -func (c *ServerSideCache) Set(ctx context.Context, key cache.Keyer, result execution.AfterStepResult) error { - k, err := key.Key() - if err != nil { - return err - } - - c.Writer.WriteAfterStepResult(k, result) - - return nil -} - -func (c *ServerSideCache) Get(ctx context.Context, key cache.Keyer) (result execution.AfterStepResult, found bool, err error) { - rawKey, err := key.Key() - if err != nil { - return result, false, err - } - - file := rawKey + cacheFileExt - path := filepath.Join(c.CacheDir, file) - found, err = readCacheFile(path, &result) - if err != nil { - return result, false, err - } - - return result, found, nil -} - -func (c *ServerSideCache) Clear(ctx context.Context, key cache.Keyer) error { - // noop - return nil -} diff --git a/internal/batches/executor/executor.go b/internal/batches/executor/executor.go index 82ec04145f..069727e82d 100644 --- a/internal/batches/executor/executor.go +++ b/internal/batches/executor/executor.go @@ -3,7 +3,6 @@ package executor import ( "context" "fmt" - "os/exec" "sync" "time" @@ -11,6 +10,7 @@ import ( "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/src-cli/internal/batches/docker" "github.com/sourcegraph/src-cli/internal/batches/log" "github.com/sourcegraph/src-cli/internal/batches/repozip" "github.com/sourcegraph/src-cli/internal/batches/util" @@ -52,7 +52,9 @@ type taskResult struct { err error } -type newExecutorOpts struct { +type imageEnsurer func(ctx context.Context, name string) (docker.Image, error) + +type NewExecutorOpts struct { // Dependencies Creator workspace.Creator RepoArchiveRegistry repozip.ArchiveRegistry @@ -68,7 +70,7 @@ type newExecutorOpts struct { } type executor struct { - opts newExecutorOpts + opts NewExecutorOpts par *parallel.Run doneEnqueuing chan struct{} @@ -77,7 +79,7 @@ type executor struct { resultsMu sync.Mutex } -func newExecutor(opts newExecutorOpts) *executor { +func NewExecutor(opts NewExecutorOpts) *executor { return &executor{ opts: opts, @@ -153,20 +155,10 @@ func (x *executor) do(ctx context.Context, task *Task, ui TaskExecutionUI) (err if err != nil { return errors.Wrap(err, "creating log file") } - defer func() { - if err != nil { - err = TaskExecutionErr{ - Err: err, - Logfile: l.Path(), - Repository: task.Repository.Name, - } - l.MarkErrored() - } - l.Close() - }() + defer l.Close() // Now checkout the archive. - task.RepoArchive = x.opts.RepoArchiveRegistry.Checkout( + repoArchive := x.opts.RepoArchiveRegistry.Checkout( repozip.RepoRevision{ RepoName: task.Repository.Name, Commit: task.Repository.Rev(), @@ -174,35 +166,35 @@ func (x *executor) do(ctx context.Context, task *Task, ui TaskExecutionUI) (err task.ArchivePathToFetch(), ) - // Set up our timeout. - runCtx, cancel := context.WithTimeout(ctx, x.opts.Timeout) - defer cancel() - // Actually execute the steps. - opts := &runStepsOpts{ - task: task, - logger: l, - wc: x.opts.Creator, - ensureImage: x.opts.EnsureImage, - tempDir: x.opts.TempDir, - isRemote: x.opts.IsRemote, - globalEnv: x.opts.GlobalEnv, - - ui: ui.StepsExecutionUI(task), + opts := &RunStepsOpts{ + Task: task, + Logger: l, + WC: x.opts.Creator, + EnsureImage: x.opts.EnsureImage, + TempDir: x.opts.TempDir, + IsRemote: x.opts.IsRemote, + GlobalEnv: x.opts.GlobalEnv, + Timeout: x.opts.Timeout, + RepoArchive: repoArchive, + + UI: ui.StepsExecutionUI(task), } - - stepResults, err := runSteps(runCtx, opts) - x.addResult(task, stepResults, err) - + stepResults, err := RunSteps(ctx, opts) if err != nil { - if reachedTimeout(runCtx, err) { - err = &errTimeoutReached{timeout: x.opts.Timeout} + // Create a more visual error for the UI. + err = TaskExecutionErr{ + Err: err, + Logfile: l.Path(), + Repository: task.Repository.Name, } - return err + l.MarkErrored() } + x.addResult(task, stepResults, err) - return nil + return err } + func (x *executor) addResult(task *Task, stepResults []execution.AfterStepResult, err error) { x.resultsMu.Lock() defer x.resultsMu.Unlock() @@ -213,19 +205,3 @@ func (x *executor) addResult(task *Task, stepResults []execution.AfterStepResult err: err, }) } - -type errTimeoutReached struct{ timeout time.Duration } - -func (e *errTimeoutReached) Error() string { - return fmt.Sprintf("Timeout reached. Execution took longer than %s.", e.timeout) -} - -func reachedTimeout(cmdCtx context.Context, err error) bool { - if ee, ok := errors.Cause(err).(*exec.ExitError); ok { - if ee.String() == "signal: killed" && cmdCtx.Err() == context.DeadlineExceeded { - return true - } - } - - return errors.Is(errors.Cause(err), context.DeadlineExceeded) -} diff --git a/internal/batches/executor/executor_test.go b/internal/batches/executor/executor_test.go index 075fbe8815..9b9167956c 100644 --- a/internal/batches/executor/executor_test.go +++ b/internal/batches/executor/executor_test.go @@ -379,7 +379,7 @@ func TestExecutor_Integration(t *testing.T) { cr, _ := workspace.NewCreator(context.Background(), "bind", testTempDir, testTempDir, images) // Setup executor - opts := newExecutorOpts{ + opts := NewExecutorOpts{ Creator: cr, RepoArchiveRegistry: repozip.NewArchiveRegistry(client, testTempDir, false), Logger: mock.LogNoOpManager{}, @@ -395,7 +395,7 @@ func TestExecutor_Integration(t *testing.T) { } dummyUI := newDummyTaskExecutionUI() - executor := newExecutor(opts) + executor := NewExecutor(opts) // Run executor executor.Start(context.Background(), tc.tasks, dummyUI) @@ -809,7 +809,7 @@ func testExecuteTasks(t *testing.T, tasks []*Task, archives ...mock.RepoArchive) cr, _ := workspace.NewCreator(context.Background(), "bind", testTempDir, testTempDir, images) // Setup executor - executor := newExecutor(newExecutorOpts{ + executor := NewExecutor(NewExecutorOpts{ Creator: cr, RepoArchiveRegistry: repozip.NewArchiveRegistry(client, testTempDir, false), Logger: mock.LogNoOpManager{}, diff --git a/internal/batches/executor/run_steps.go b/internal/batches/executor/run_steps.go index 556c951f66..40f704a13b 100644 --- a/internal/batches/executor/run_steps.go +++ b/internal/batches/executor/run_steps.go @@ -13,10 +13,12 @@ import ( batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/execution" + "github.com/sourcegraph/sourcegraph/lib/batches/git" "github.com/sourcegraph/sourcegraph/lib/batches/template" "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/batches/log" + "github.com/sourcegraph/src-cli/internal/batches/repozip" "github.com/sourcegraph/src-cli/internal/batches/util" "github.com/sourcegraph/src-cli/internal/batches/workspace" @@ -25,47 +27,61 @@ import ( yamlv3 "gopkg.in/yaml.v3" ) -type runStepsOpts struct { - // wc is the workspace creator to use. It will be called at the beginning of +type RunStepsOpts struct { + // WC is the workspace creator to use. It will be called at the beginning of // runSteps to prepare the workspace for execution. - wc workspace.Creator - // ensureImage is called in runSteps to make sure the used image has been + WC workspace.Creator + // EnsureImage is called in runSteps to make sure the used image has been // pulled from the registry. - ensureImage imageEnsurer - // task is the definition of the workspace execution. - task *Task - // tempDir points to where temporary files of the execution should live at. - tempDir string - - logger log.TaskLogger - - ui StepsExecutionUI - - // isRemote toggles server-side execution mode. This disables file mounts using + EnsureImage imageEnsurer + // Task is the definition of the workspace execution. + Task *Task + // TempDir points to where temporary files of the execution should live at. + TempDir string + // Timeout sets the deadline for the execution context. When exceeded, + // execution will stop and an error is returned. + Timeout time.Duration + // RepoArchive is the repo archive to be used for creating the workspace. + RepoArchive repozip.Archive + Logger log.TaskLogger + UI StepsExecutionUI + // IsRemote toggles server-side execution mode. This disables file mounts using // step.mounts. - isRemote bool - - // globalEnv is the os.Environ() for the execution. We don't read from os.Environ() + IsRemote bool + // GlobalEnv is the os.Environ() for the execution. We don't read from os.Environ() // directly to allow injecting variables and hiding others. - globalEnv []string + GlobalEnv []string } -func runSteps(ctx context.Context, opts *runStepsOpts) (stepResults []execution.AfterStepResult, err error) { - opts.ui.ArchiveDownloadStarted() - err = opts.task.RepoArchive.Ensure(ctx) - opts.ui.ArchiveDownloadFinished(err) +func RunSteps(ctx context.Context, opts *RunStepsOpts) (stepResults []execution.AfterStepResult, err error) { + // Set up our timeout. + ctx, cancel := context.WithTimeout(ctx, opts.Timeout) + defer cancel() + + // Return an errTimeoutReached error in case the deadline has been exceeded. + defer func() { + if err != nil { + if reachedTimeout(ctx, err) { + err = &errTimeoutReached{timeout: opts.Timeout} + } + } + }() + + opts.UI.ArchiveDownloadStarted() + err = opts.RepoArchive.Ensure(ctx) + opts.UI.ArchiveDownloadFinished(err) if err != nil { return nil, errors.Wrap(err, "fetching repo") } - defer opts.task.RepoArchive.Close() + defer opts.RepoArchive.Close() - opts.ui.WorkspaceInitializationStarted() - ws, err := opts.wc.Create(ctx, opts.task.Repository, opts.task.Steps, opts.task.RepoArchive) + opts.UI.WorkspaceInitializationStarted() + ws, err := opts.WC.Create(ctx, opts.Task.Repository, opts.Task.Steps, opts.RepoArchive) if err != nil { return nil, errors.Wrap(err, "creating workspace") } defer ws.Close(ctx) - opts.ui.WorkspaceInitializationFinished() + opts.UI.WorkspaceInitializationFinished() var ( // lastOutputs are the step.outputs from the previously run step. @@ -78,11 +94,11 @@ func runSteps(ctx context.Context, opts *runStepsOpts) (stepResults []execution. startStep int ) - if opts.task.CachedStepResultFound { + if opts.Task.CachedStepResultFound { // Set the Outputs to the cached outputs - lastOutputs = opts.task.CachedStepResult.Outputs - previousStepResult = opts.task.CachedStepResult - lastStep := opts.task.CachedStepResult.StepIndex + lastOutputs = opts.Task.CachedStepResult.Outputs + previousStepResult = opts.Task.CachedStepResult + lastStep := opts.Task.CachedStepResult.StepIndex // Add the cached result to the result set. It may be required for building // the changeset specs in the end if we don't need to execute any other steps // due to dynamic skipping. @@ -95,35 +111,35 @@ func runSteps(ctx context.Context, opts *runStepsOpts) (stepResults []execution. // TODO: This doesn't consider skipped steps, but it's not _that_ // bad, we will find out about that further down and correctly finish // execution early. - if lastStep == len(opts.task.Steps)-1 { + if lastStep == len(opts.Task.Steps)-1 { return stepResults, nil } // If the previous steps made any modifications to the workspace yet, // apply them. - if opts.task.CachedStepResult.Diff != "" { - if err := ws.ApplyDiff(ctx, []byte(opts.task.CachedStepResult.Diff)); err != nil { + if opts.Task.CachedStepResult.Diff != "" { + if err := ws.ApplyDiff(ctx, []byte(opts.Task.CachedStepResult.Diff)); err != nil { return nil, errors.Wrap(err, "applying diff of cache result") } } startStep = lastStep + 1 - opts.ui.SkippingStepsUpto( + opts.UI.SkippingStepsUpto( // UI is 1-indexed. startStep + 1, ) } - for i := startStep; i < len(opts.task.Steps); i++ { - step := opts.task.Steps[i] + for i := startStep; i < len(opts.Task.Steps); i++ { + step := opts.Task.Steps[i] stepContext := template.StepContext{ - BatchChange: *opts.task.BatchChangeAttributes, - Repository: util.NewTemplatingRepo(opts.task.Repository.Name, opts.task.Repository.FileMatches), + BatchChange: *opts.Task.BatchChangeAttributes, + Repository: util.NewTemplatingRepo(opts.Task.Repository.Name, opts.Task.Repository.FileMatches), Outputs: lastOutputs, Steps: template.StepsContext{ - Path: opts.task.Path, + Path: opts.Task.Path, Changes: previousStepResult.ChangedFiles, }, PreviousStep: previousStepResult, @@ -135,12 +151,12 @@ func runSteps(ctx context.Context, opts *runStepsOpts) (stepResults []execution. return nil, errors.Wrap(err, "evaluating step condition") } if !cond { - opts.ui.StepSkipped(i + 1) + opts.UI.StepSkipped(i + 1) continue } // We need to grab the digest for the exact image we're using. - img, err := opts.ensureImage(ctx, step.Container) + img, err := opts.EnsureImage(ctx, step.Container) if err != nil { return nil, err } @@ -157,24 +173,25 @@ func runSteps(ctx context.Context, opts *runStepsOpts) (stepResults []execution. if errors.As(err, sfe) { exitCode = sfe.ExitCode } - opts.ui.StepFailed(i+1, err, exitCode) + opts.UI.StepFailed(i+1, err, exitCode) } }() if err != nil { return stepResults, err } - changes, err := ws.Changes(ctx) - if err != nil { - return stepResults, errors.Wrap(err, "getting changed files in step") - } - // Get the current diff and store that away as the per-step result. stepDiff, err := ws.Diff(ctx) if err != nil { return stepResults, errors.Wrap(err, "getting diff produced by step") } + // Next parse the diff to determine which files were changed. + changes, err := git.ChangesInDiff(stepDiff) + if err != nil { + return stepResults, errors.Wrap(err, "getting changed files in step") + } + stepResult := execution.AfterStepResult{ ChangedFiles: changes, Stdout: stdoutBuffer.String(), @@ -197,14 +214,14 @@ func runSteps(ctx context.Context, opts *runStepsOpts) (stepResults []execution. stepResults = append(stepResults, stepResult) previousStepResult = stepResult - opts.ui.StepFinished(i+1, stepResult.Diff, stepResult.ChangedFiles, stepResult.Outputs) + opts.UI.StepFinished(i+1, stepResult.Diff, stepResult.ChangedFiles, stepResult.Outputs) } // If we ended up executing at least one step in addition to the cached step, // we can remove it from the result set. Otherwise we write it to the cache // again which is unnecessary. We only need to return it when we want to build changeset // specs from it. - if len(stepResults) > 1 && opts.task.CachedStepResultFound { + if len(stepResults) > 1 && opts.Task.CachedStepResultFound { stepResults = stepResults[1:] } @@ -215,7 +232,7 @@ const workDir = "/work" func executeSingleStep( ctx context.Context, - opts *runStepsOpts, + opts *RunStepsOpts, workspace workspace.Workspace, stepIdx int, step batcheslib.Step, @@ -225,11 +242,11 @@ func executeSingleStep( // ---------- // PREPARATION // ---------- - opts.ui.StepPreparingStart(stepIdx + 1) + opts.UI.StepPreparingStart(stepIdx + 1) - cidFile, cleanup, err := createCidFile(ctx, opts.tempDir, util.SlugForRepo(opts.task.Repository.Name, opts.task.Repository.Rev())) + cidFile, cleanup, err := createCidFile(ctx, opts.TempDir, util.SlugForRepo(opts.Task.Repository.Name, opts.Task.Repository.Rev())) if err != nil { - opts.ui.StepPreparingFailed(stepIdx+1, err) + opts.UI.StepPreparingFailed(stepIdx+1, err) return bytes.Buffer{}, bytes.Buffer{}, err } defer cleanup() @@ -238,46 +255,47 @@ func executeSingleStep( shell, containerTemp, err := probeImageForShell(ctx, imageDigest) if err != nil { err = errors.Wrapf(err, "probing image %q for shell", step.Container) - opts.ui.StepPreparingFailed(stepIdx+1, err) + opts.UI.StepPreparingFailed(stepIdx+1, err) return bytes.Buffer{}, bytes.Buffer{}, err } - runScriptFile, runScript, cleanup, err := createRunScriptFile(ctx, opts.tempDir, step.Run, stepContext) + runScriptFile, runScript, cleanup, err := createRunScriptFile(ctx, opts.TempDir, step.Run, stepContext) if err != nil { - opts.ui.StepPreparingFailed(stepIdx+1, err) + opts.UI.StepPreparingFailed(stepIdx+1, err) return bytes.Buffer{}, bytes.Buffer{}, err } defer cleanup() // Parse and render the step.Files. - filesToMount, cleanup, err := createFilesToMount(opts.tempDir, step, stepContext) + filesToMount, cleanup, err := createFilesToMount(opts.TempDir, step, stepContext) if err != nil { - opts.ui.StepPreparingFailed(stepIdx+1, err) + opts.UI.StepPreparingFailed(stepIdx+1, err) return bytes.Buffer{}, bytes.Buffer{}, err } defer cleanup() // Resolve step.Env given the current environment. - stepEnv, err := step.Env.Resolve(opts.globalEnv) + stepEnv, err := step.Env.Resolve(opts.GlobalEnv) if err != nil { err = errors.Wrap(err, "resolving step environment") - opts.ui.StepPreparingFailed(stepIdx+1, err) + opts.UI.StepPreparingFailed(stepIdx+1, err) return bytes.Buffer{}, bytes.Buffer{}, err } + // Render the step.Env variables as templates. env, err := template.RenderStepMap(stepEnv, stepContext) if err != nil { err = errors.Wrap(err, "parsing step environment") - opts.ui.StepPreparingFailed(stepIdx+1, err) + opts.UI.StepPreparingFailed(stepIdx+1, err) return bytes.Buffer{}, bytes.Buffer{}, err } - opts.ui.StepPreparingSuccess(stepIdx + 1) + opts.UI.StepPreparingSuccess(stepIdx + 1) // ---------- // EXECUTION // ---------- - opts.ui.StepStarted(stepIdx+1, runScript, env) + opts.UI.StepStarted(stepIdx+1, runScript, env) workspaceOpts, err := workspace.DockerRunOpts(ctx, workDir) if err != nil { @@ -286,8 +304,8 @@ func executeSingleStep( // Where should we execute the steps.run script? scriptWorkDir := workDir - if opts.task.Path != "" { - scriptWorkDir = workDir + "/" + opts.task.Path + if opts.Task.Path != "" { + scriptWorkDir = workDir + "/" + opts.Task.Path } args := append([]string{ @@ -304,7 +322,7 @@ func executeSingleStep( } // Temporarily add a guard to prevent a path to mount path for server-side processing. - if !opts.isRemote { + if !opts.IsRemote { // Mount any paths on the local system to the docker container. The paths have already been validated during parsing. for _, mount := range step.Mount { args = append(args, "--mount", fmt.Sprintf("type=bind,source=%s,target=%s,ro", mount.Path, mount.Mountpoint)) @@ -325,13 +343,13 @@ func executeSingleStep( writerCtx, writerCancel := context.WithCancel(ctx) defer writerCancel() - outputWriter := opts.ui.StepOutputWriter(writerCtx, opts.task, stepIdx+1) + outputWriter := opts.UI.StepOutputWriter(writerCtx, opts.Task, stepIdx+1) defer func() { outputWriter.Close() }() - stdoutWriter := io.MultiWriter(&stdout, outputWriter.StdoutWriter(), opts.logger.PrefixWriter("stdout")) - stderrWriter := io.MultiWriter(&stderr, outputWriter.StderrWriter(), opts.logger.PrefixWriter("stderr")) + stdoutWriter := io.MultiWriter(&stdout, outputWriter.StdoutWriter(), opts.Logger.PrefixWriter("stdout")) + stderrWriter := io.MultiWriter(&stderr, outputWriter.StderrWriter(), opts.Logger.PrefixWriter("stderr")) // Setup readers that pipe the output into the given buffers wg, err := process.PipeOutput(ctx, cmd, stdoutWriter, stderrWriter) @@ -357,13 +375,13 @@ func executeSingleStep( } } - opts.logger.Logf("[Step %d] run: %q, container: %q", stepIdx+1, step.Run, step.Container) - opts.logger.Logf("[Step %d] full command: %q", stepIdx+1, strings.Join(cmd.Args, " ")) + opts.Logger.Logf("[Step %d] run: %q, container: %q", stepIdx+1, step.Run, step.Container) + opts.Logger.Logf("[Step %d] full command: %q", stepIdx+1, strings.Join(cmd.Args, " ")) // Start the command. t0 := time.Now() if err := cmd.Start(); err != nil { - opts.logger.Logf("[Step %d] error starting Docker container: %+v", stepIdx+1, err) + opts.Logger.Logf("[Step %d] error starting Docker container: %+v", stepIdx+1, err) return stdout, stderr, newStepFailedErr(err) } @@ -375,11 +393,11 @@ func executeSingleStep( err = cmd.Wait() elapsed := time.Since(t0).Round(time.Millisecond) if err != nil { - opts.logger.Logf("[Step %d] took %s; error running Docker container: %+v", stepIdx+1, elapsed, err) + opts.Logger.Logf("[Step %d] took %s; error running Docker container: %+v", stepIdx+1, elapsed, err) return stdout, stderr, newStepFailedErr(err) } - opts.logger.Logf("[Step %d] complete in %s", stepIdx+1, elapsed) + opts.Logger.Logf("[Step %d] complete in %s", stepIdx+1, elapsed) return stdout, stderr, nil } @@ -639,3 +657,19 @@ func (e stepFailedErr) SingleLineError() string { return strings.Split(out, "\n")[0] } + +type errTimeoutReached struct{ timeout time.Duration } + +func (e *errTimeoutReached) Error() string { + return fmt.Sprintf("Timeout reached. Execution took longer than %s.", e.timeout) +} + +func reachedTimeout(cmdCtx context.Context, err error) bool { + if ee, ok := errors.Cause(err).(*exec.ExitError); ok { + if ee.String() == "signal: killed" && cmdCtx.Err() == context.DeadlineExceeded { + return true + } + } + + return errors.Is(errors.Cause(err), context.DeadlineExceeded) +} diff --git a/internal/batches/executor/task.go b/internal/batches/executor/task.go index b6b2ee8b04..aba8779004 100644 --- a/internal/batches/executor/task.go +++ b/internal/batches/executor/task.go @@ -11,12 +11,10 @@ import ( "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/batches/graphql" - "github.com/sourcegraph/src-cli/internal/batches/repozip" ) type Task struct { Repository *graphql.Repository - // Path is the folder relative to the repository's root in which the steps // should be executed. "" means root. Path string @@ -24,20 +22,13 @@ type Task struct { // the complete repository or just the files in Path (and additional files, // see RepoFetcher). // If Path is "" then this setting has no effect. - OnlyFetchWorkspace bool - - Steps []batcheslib.Step - - // TODO(mrnugget): this should just be a single BatchSpec field instead, if - // we can make it work with caching - BatchChangeAttributes *template.BatchChangeAttributes `json:"-"` - - RepoArchive repozip.Archive `json:"-"` - + OnlyFetchWorkspace bool + Steps []batcheslib.Step + BatchChangeAttributes *template.BatchChangeAttributes // CachedStepResultFound is true when a partial execution result was found in the cache. // When this field is true, CachedStepResult is also populated. - CachedStepResultFound bool `json:"-"` - CachedStepResult execution.AfterStepResult `json:"-"` + CachedStepResultFound bool + CachedStepResult execution.AfterStepResult } func (t *Task) ArchivePathToFetch() string { @@ -47,7 +38,7 @@ func (t *Task) ArchivePathToFetch() string { return "" } -func (t *Task) cacheKey(globalEnv []string, isRemote bool, stepIndex int) cache.Keyer { +func (t *Task) CacheKey(globalEnv []string, isRemote bool, stepIndex int) cache.Keyer { var metadataRetriever cache.MetadataRetriever // If the task is being run locally, set the metadata retrieve to use the filesystem based implementation. if !isRemote { diff --git a/internal/batches/log/noop_manager.go b/internal/batches/log/noop_manager.go deleted file mode 100644 index b092bd1cf2..0000000000 --- a/internal/batches/log/noop_manager.go +++ /dev/null @@ -1,21 +0,0 @@ -package log - -var _ LogManager = &NoopManager{} - -type NoopManager struct{} - -func NewNoopManager() *NoopManager { - return &NoopManager{} -} - -func (lm *NoopManager) AddTask(string) (TaskLogger, error) { - return &NoopTaskLogger{}, nil -} - -func (lm *NoopManager) Close() error { - return nil -} - -func (lm *NoopManager) LogFiles() []string { - return []string{} -} diff --git a/internal/batches/mock/cache.go b/internal/batches/mock/cache.go index 7f4b6466f6..0e60217933 100644 --- a/internal/batches/mock/cache.go +++ b/internal/batches/mock/cache.go @@ -1,6 +1,10 @@ package mock -import "github.com/sourcegraph/src-cli/internal/batches/docker" +import ( + "context" + + "github.com/sourcegraph/src-cli/internal/batches/docker" +) type ImageCache struct { Images map[string]docker.Image @@ -9,3 +13,7 @@ type ImageCache struct { var _ docker.ImageCache = &ImageCache{} func (c *ImageCache) Get(name string) docker.Image { return c.Images[name] } +func (c *ImageCache) Ensure(ctx context.Context, name string) (docker.Image, error) { + img := c.Images[name] + return img, img.Ensure(ctx) +} diff --git a/internal/batches/repozip/fetcher.go b/internal/batches/repozip/fetcher.go index 85b780b062..dff57bad00 100644 --- a/internal/batches/repozip/fetcher.go +++ b/internal/batches/repozip/fetcher.go @@ -27,7 +27,7 @@ type ArchiveRegistry interface { // Checkout returns an Archive for the given repository and the given // relative path in the repository. The Archive is possibly unfetched. // Users need to call `Ensure()` on the Archive before using it and - // `Close()` once // they're done using it. + // `Close()` once they're done using it. Checkout(repo RepoRevision, path string) Archive } diff --git a/internal/batches/repozip/noop.go b/internal/batches/repozip/noop.go index 2f83e797eb..be7af094a2 100644 --- a/internal/batches/repozip/noop.go +++ b/internal/batches/repozip/noop.go @@ -2,30 +2,17 @@ package repozip import "context" -// NewNoopRegistry returns a registry that returns archives that don't perform -// any operation. This is used in executor mode to disable fetching repo archives -// in favor of cloning. -func NewNoopRegistry() ArchiveRegistry { - return &noopArchiveRegistry{} -} - -type noopArchiveRegistry struct{} - -func (r *noopArchiveRegistry) Checkout(repo RepoRevision, path string) Archive { - return &noopArchive{} -} - -type noopArchive struct{} +type NoopArchive struct{} -func (a *noopArchive) Ensure(context.Context) error { +func (a *NoopArchive) Ensure(context.Context) error { return nil } -func (a *noopArchive) Close() error { +func (a *NoopArchive) Close() error { return nil } -func (a *noopArchive) Path() string { +func (a *NoopArchive) Path() string { return "" } -func (a *noopArchive) AdditionalFilePaths() map[string]string { +func (a *NoopArchive) AdditionalFilePaths() map[string]string { return nil } diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index 93383bc07e..2d86b1d858 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -24,22 +24,15 @@ import ( "github.com/sourcegraph/src-cli/internal/batches/docker" "github.com/sourcegraph/src-cli/internal/batches/executor" "github.com/sourcegraph/src-cli/internal/batches/graphql" - "github.com/sourcegraph/src-cli/internal/batches/log" - "github.com/sourcegraph/src-cli/internal/batches/repozip" ) type Service struct { - allowUnsupported bool - allowIgnored bool - client api.Client - features batches.FeatureFlags - imageCache docker.ImageCache + client api.Client + features batches.FeatureFlags } type Opts struct { - AllowUnsupported bool - AllowIgnored bool - Client api.Client + Client api.Client } var ( @@ -48,10 +41,7 @@ var ( func New(opts *Opts) *Service { return &Service{ - allowUnsupported: opts.AllowUnsupported, - allowIgnored: opts.AllowIgnored, - client: opts.Client, - imageCache: docker.NewImageCache(), + client: opts.Client, } } @@ -96,7 +86,7 @@ func (svc *Service) DetermineFeatureFlags(ctx context.Context) error { return errors.Wrap(err, "failed to query Sourcegraph version to check for available features") } - return svc.features.SetFromVersion(version) + return svc.SetFeatureFlagsForVersion(version) } func (svc *Service) SetFeatureFlagsForVersion(version string) error { @@ -172,6 +162,7 @@ func (svc *Service) CreateChangesetSpec(ctx context.Context, spec *batcheslib.Ch // Progress information is reported back to the given progress function. func (svc *Service) EnsureDockerImages( ctx context.Context, + imageCache docker.ImageCache, steps []batcheslib.Step, parallelism int, progress func(done, total int), @@ -222,7 +213,7 @@ func (svc *Service) EnsureDockerImages( if !more { return } - img, err := svc.EnsureImage(workerCtx, name) + img, err := imageCache.Ensure(workerCtx, name) select { case <-workerCtx.Done(): return @@ -269,16 +260,6 @@ func (svc *Service) EnsureDockerImages( return images, nil } -func (svc *Service) EnsureImage(ctx context.Context, name string) (docker.Image, error) { - img := svc.imageCache.Get(name) - - if err := img.Ensure(ctx); err != nil { - return nil, errors.Wrapf(err, "pulling image %q", name) - } - - return img, nil -} - func (svc *Service) DetermineWorkspaces(ctx context.Context, repos []*graphql.Repository, spec *batcheslib.BatchSpec) ([]RepoWorkspace, error) { return findWorkspaces(ctx, spec, svc, repos) } @@ -287,12 +268,8 @@ func (svc *Service) BuildTasks(ctx context.Context, attributes *templatelib.Batc return buildTasks(ctx, attributes, workspaces) } -func (svc *Service) NewCoordinator(archiveRegistry repozip.ArchiveRegistry, logger log.LogManager, opts executor.NewCoordinatorOpts) *executor.Coordinator { - opts.RepoArchiveRegistry = archiveRegistry - opts.Features = svc.features - opts.EnsureImage = svc.EnsureImage - - return executor.NewCoordinator(opts, logger) +func (svc *Service) Features() batches.FeatureFlags { + return svc.features } func (svc *Service) CreateImportChangesetSpecs(ctx context.Context, batchSpec *batcheslib.BatchSpec) ([]*batcheslib.ChangesetSpec, error) { @@ -588,7 +565,7 @@ func (svc *Service) ResolveNamespace(ctx context.Context, namespace string) (Nam return Namespace{}, fmt.Errorf("failed to resolve namespace %q: no user or organization found", namespace) } -func (svc *Service) ResolveRepositories(ctx context.Context, spec *batcheslib.BatchSpec) ([]*graphql.Repository, error) { +func (svc *Service) ResolveRepositories(ctx context.Context, spec *batcheslib.BatchSpec, allowUnsupported, allowIgnored bool) ([]*graphql.Repository, error) { agg := onlib.NewRepoRevisionAggregator() unsupported := batches.UnsupportedRepoSet{} ignored := batches.IgnoredRepoSet{} @@ -610,7 +587,7 @@ func (svc *Service) ResolveRepositories(ctx context.Context, spec *batcheslib.Ba } var repoBatchIgnores map[*graphql.Repository][]string - if !svc.allowIgnored { + if !allowIgnored { repoBatchIgnores, err = svc.FindDirectoriesInRepos(ctx, ".batchignore", reposWithBranch...) if err != nil { return nil, err @@ -628,12 +605,12 @@ func (svc *Service) ResolveRepositories(ctx context.Context, spec *batcheslib.Ba } fallthrough default: - if !svc.allowUnsupported { + if !allowUnsupported { unsupported.Append(repo) } } - if !svc.allowIgnored { + if !allowIgnored { if locations, ok := repoBatchIgnores[repo]; ok && len(locations) > 0 { ignored.Append(repo) } diff --git a/internal/batches/service/service_test.go b/internal/batches/service/service_test.go index 2a25e7f8be..e407d246df 100644 --- a/internal/batches/service/service_test.go +++ b/internal/batches/service/service_test.go @@ -163,9 +163,9 @@ func TestResolveRepositories_Unsupported(t *testing.T) { } t.Run("allowUnsupported:true", func(t *testing.T) { - svc := &Service{client: client, allowUnsupported: true, allowIgnored: true} + svc := &Service{client: client} - repos, err := svc.ResolveRepositories(context.Background(), spec) + repos, err := svc.ResolveRepositories(context.Background(), spec, true, true) if err != nil { t.Fatalf("unexpected error: %s", err) } @@ -175,9 +175,9 @@ func TestResolveRepositories_Unsupported(t *testing.T) { }) t.Run("allowUnsupported:false", func(t *testing.T) { - svc := &Service{client: client, allowUnsupported: false, allowIgnored: true} + svc := &Service{client: client} - repos, err := svc.ResolveRepositories(context.Background(), spec) + repos, err := svc.ResolveRepositories(context.Background(), spec, false, true) repoSet, ok := err.(batches.UnsupportedRepoSet) if !ok { t.Fatalf("err is not UnsupportedRepoSet") @@ -246,9 +246,9 @@ func TestResolveRepositories_Ignored(t *testing.T) { client, done := mockGraphQLClient(testResolveRepositories, testBatchIgnoreInRepos) defer done() - svc := &Service{client: client, allowIgnored: true} + svc := &Service{client: client} - repos, err := svc.ResolveRepositories(context.Background(), spec) + repos, err := svc.ResolveRepositories(context.Background(), spec, false, true) if err != nil { t.Fatalf("unexpected error: %s", err) } @@ -261,9 +261,9 @@ func TestResolveRepositories_Ignored(t *testing.T) { client, done := mockGraphQLClient(testResolveRepositories, testBatchIgnoreInRepos) defer done() - svc := &Service{client: client, allowIgnored: false} + svc := &Service{client: client} - repos, err := svc.ResolveRepositories(context.Background(), spec) + repos, err := svc.ResolveRepositories(context.Background(), spec, false, false) ignored, ok := err.(batches.IgnoredRepoSet) if !ok { t.Fatalf("err is not IgnoredRepoSet: %s", err) @@ -343,9 +343,9 @@ func TestResolveRepositories_RepoWithoutBranch(t *testing.T) { client, done := mockGraphQLClient(testResolveRepositoriesNoBranch, testBatchIgnoreInReposNoBranch) defer done() - svc := &Service{client: client, allowIgnored: false} + svc := &Service{client: client} - repos, err := svc.ResolveRepositories(context.Background(), spec) + repos, err := svc.ResolveRepositories(context.Background(), spec, false, false) if err != nil { t.Fatalf("unexpected error: %s", err) } @@ -584,11 +584,7 @@ func TestEnsureDockerImages(t *testing.T) { ctx := context.Background() parallelCases := []int{0, 1, 2, 4, 8} - newServiceWithImages := func(images map[string]docker.Image) *Service { - return &Service{ - imageCache: &mock.ImageCache{Images: images}, - } - } + svc := &Service{} t.Run("success", func(t *testing.T) { t.Run("single image", func(t *testing.T) { @@ -605,10 +601,8 @@ func TestEnsureDockerImages(t *testing.T) { t.Run(name, func(t *testing.T) { for _, parallelism := range parallelCases { t.Run(fmt.Sprintf("%d worker(s)", parallelism), func(t *testing.T) { - svc := newServiceWithImages(images) progress := &mock.Progress{} - - have, err := svc.EnsureDockerImages(ctx, steps, parallelism, progress.Callback()) + have, err := svc.EnsureDockerImages(ctx, &mock.ImageCache{Images: images}, steps, parallelism, progress.Callback()) assert.Nil(t, err) assert.Equal(t, images, have) assert.Equal(t, []mock.ProgressCall{ @@ -635,16 +629,21 @@ func TestEnsureDockerImages(t *testing.T) { for _, parallelism := range parallelCases { t.Run(fmt.Sprintf("%d worker(s)", parallelism), func(t *testing.T) { - svc := newServiceWithImages(images) progress := &mock.Progress{} - have, err := svc.EnsureDockerImages(ctx, []batcheslib.Step{ - {Container: "a"}, - {Container: "a"}, - {Container: "a"}, - {Container: "b"}, - {Container: "c"}, - }, parallelism, progress.Callback()) + have, err := svc.EnsureDockerImages( + ctx, + &mock.ImageCache{Images: images}, + []batcheslib.Step{ + {Container: "a"}, + {Container: "a"}, + {Container: "a"}, + {Container: "b"}, + {Container: "c"}, + }, + parallelism, + progress.Callback(), + ) assert.Nil(t, err) assert.Equal(t, images, have) assert.Equal(t, []mock.ProgressCall{ @@ -686,10 +685,9 @@ func TestEnsureDockerImages(t *testing.T) { for _, parallelism := range parallelCases { t.Run(fmt.Sprintf("%d worker(s)", parallelism), func(t *testing.T) { - svc := newServiceWithImages(images) progress := &mock.Progress{} - have, err := svc.EnsureDockerImages(ctx, steps, parallelism, progress.Callback()) + have, err := svc.EnsureDockerImages(ctx, &mock.ImageCache{Images: images}, steps, parallelism, progress.Callback()) assert.ErrorIs(t, err, wantErr) assert.Nil(t, have) diff --git a/internal/batches/ui/json_lines.go b/internal/batches/ui/json_lines.go index 220914f243..ceade9e4c0 100644 --- a/internal/batches/ui/json_lines.go +++ b/internal/batches/ui/json_lines.go @@ -172,8 +172,6 @@ func (ui *JSONLines) ExecutionError(err error) { logOperationFailure(batcheslib.LogEventOperationBatchSpecExecution, &batcheslib.BatchSpecExecutionMetadata{Error: err.Error()}) } -var _ executor.JSONCacheWriter = &JSONLines{} - func (ui *JSONLines) WriteAfterStepResult(key string, value execution.AfterStepResult) { logOperationSuccess(batcheslib.LogEventOperationCacheAfterStepResult, &batcheslib.CacheAfterStepResultMetadata{ Key: key, @@ -195,7 +193,6 @@ func randomID() (string, error) { func (ui *taskExecutionJSONLines) Start(tasks []*executor.Task) { ui.linesTasks = make(map[*executor.Task]batcheslib.JSONLinesTask, len(tasks)) - linesTasks := []batcheslib.JSONLinesTask{} for _, t := range tasks { id, err := randomID() if err != nil { @@ -210,12 +207,7 @@ func (ui *taskExecutionJSONLines) Start(tasks []*executor.Task) { StartStep: t.CachedStepResult.StepIndex, } ui.linesTasks[t] = linesTask - linesTasks = append(linesTasks, linesTask) } - - logOperationStart(batcheslib.LogEventOperationExecutingTasks, &batcheslib.ExecutingTasksMetadata{ - Tasks: linesTasks, - }) } func (ui *taskExecutionJSONLines) Success() { logOperationSuccess(batcheslib.LogEventOperationExecutingTasks, &batcheslib.ExecutingTasksMetadata{}) diff --git a/internal/batches/workspace/bind_workspace.go b/internal/batches/workspace/bind_workspace.go index 6ae4c57c78..55a1e4dcb4 100644 --- a/internal/batches/workspace/bind_workspace.go +++ b/internal/batches/workspace/bind_workspace.go @@ -11,7 +11,6 @@ import ( "strings" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" - "github.com/sourcegraph/sourcegraph/lib/batches/git" "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/batches/graphql" @@ -129,25 +128,11 @@ func (w *dockerBindWorkspace) DockerRunOpts(ctx context.Context, target string) func (w *dockerBindWorkspace) WorkDir() *string { return &w.dir } -func (w *dockerBindWorkspace) Changes(ctx context.Context) (git.Changes, error) { +func (w *dockerBindWorkspace) Diff(ctx context.Context) ([]byte, error) { if _, err := runGitCmd(ctx, w.dir, "add", "--all"); err != nil { - return git.Changes{}, errors.Wrap(err, "git add failed") - } - - statusOut, err := runGitCmd(ctx, w.dir, "status", "--porcelain", "--no-ahead-behind") - if err != nil { - return git.Changes{}, errors.Wrap(err, "git status failed") - } - - changes, err := git.ParseGitStatus(statusOut) - if err != nil { - return git.Changes{}, errors.Wrap(err, "parsing git status output") + return nil, errors.Wrap(err, "git add failed") } - return changes, nil -} - -func (w *dockerBindWorkspace) Diff(ctx context.Context) ([]byte, error) { // As of Sourcegraph 3.14 we only support unified diff format. // That means we need to strip away the `a/` and `/b` prefixes with `--no-prefix`. // See: https://github.com/sourcegraph/sourcegraph/blob/82d5e7e1562fef6be5c0b17f18631040fd330835/enterprise/internal/campaigns/service.go#L324-L329 diff --git a/internal/batches/workspace/volume_workspace.go b/internal/batches/workspace/volume_workspace.go index 9be8ac8c49..5cc8222a2f 100644 --- a/internal/batches/workspace/volume_workspace.go +++ b/internal/batches/workspace/volume_workspace.go @@ -13,7 +13,6 @@ import ( "github.com/sourcegraph/sourcegraph/lib/errors" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" - "github.com/sourcegraph/sourcegraph/lib/batches/git" "github.com/sourcegraph/src-cli/internal/batches/docker" "github.com/sourcegraph/src-cli/internal/batches/graphql" @@ -229,29 +228,6 @@ func (w *dockerVolumeWorkspace) DockerRunOpts(ctx context.Context, target string func (w *dockerVolumeWorkspace) WorkDir() *string { return nil } -func (w *dockerVolumeWorkspace) Changes(ctx context.Context) (git.Changes, error) { - script := `#!/bin/sh - -set -e -# No set -x here, since we're going to parse the git status output. - -git add --all > /dev/null -exec git status --porcelain -` - - out, err := w.runScript(ctx, "/work", script) - if err != nil { - return git.Changes{}, errors.Wrap(err, "running git status") - } - - changes, err := git.ParseGitStatus(out) - if err != nil { - return git.Changes{}, errors.Wrapf(err, "parsing git status output:\n\n%s", string(out)) - } - - return changes, nil -} - func (w *dockerVolumeWorkspace) Diff(ctx context.Context) ([]byte, error) { // As of Sourcegraph 3.14 we only support unified diff format. // That means we need to strip away the `a/` and `/b` prefixes with `--no-prefix`. @@ -262,7 +238,11 @@ func (w *dockerVolumeWorkspace) Diff(ctx context.Context) ([]byte, error) { // ATTENTION: When you change the options here, be sure to also update the // ApplyDiff method accordingly. script := `#!/bin/sh - + +set -e +# No set -x here, since we're going to parse the git status output. + +git add --all > /dev/null exec git diff --cached --no-prefix --binary ` diff --git a/internal/batches/workspace/volume_workspace_test.go b/internal/batches/workspace/volume_workspace_test.go index 9d3526e6e3..559d22aa67 100644 --- a/internal/batches/workspace/volume_workspace_test.go +++ b/internal/batches/workspace/volume_workspace_test.go @@ -1,7 +1,6 @@ package workspace import ( - "bytes" "context" "os" "path/filepath" @@ -12,7 +11,6 @@ import ( "github.com/sourcegraph/sourcegraph/lib/errors" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" - "github.com/sourcegraph/sourcegraph/lib/batches/git" "github.com/sourcegraph/src-cli/internal/batches/docker" "github.com/sourcegraph/src-cli/internal/batches/graphql" @@ -434,91 +432,6 @@ func TestVolumeWorkspace_WorkDir(t *testing.T) { } } -// For the below tests that essentially delegate to runScript, we're not going -// to test the content of the script file: we'll do that as a one off test at -// the bottom of runScript itself, rather than depending on script content that -// may drift over time. - -func TestVolumeWorkspace_Changes(t *testing.T) { - ctx := context.Background() - w := &dockerVolumeWorkspace{volume: volumeID} - - t.Run("success", func(t *testing.T) { - for name, tc := range map[string]struct { - stdout string - want git.Changes - }{ - "empty": { - stdout: "", - want: git.Changes{}, - }, - "valid": { - stdout: ` -M go.mod -M internal/campaigns/volume_workspace.go -M internal/campaigns/volume_workspace_test.go - `, - want: git.Changes{Modified: []string{ - "go.mod", - "internal/campaigns/volume_workspace.go", - "internal/campaigns/volume_workspace_test.go", - }}, - }, - } { - t.Run(name, func(t *testing.T) { - expect.Commands( - t, - expect.NewGlob( - expect.Behaviour{Stdout: bytes.TrimSpace([]byte(tc.stdout))}, - "docker", "run", "--rm", "--init", "--workdir", "/work", - "--mount", "type=bind,source=*,target=/run.sh,ro", - "--user", "0:0", - "--mount", "type=volume,source="+volumeID+",target=/work", - DockerVolumeWorkspaceImage, - "sh", "/run.sh", - ), - ) - - have, err := w.Changes(ctx) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - - if diff := cmp.Diff(have, tc.want); diff != "" { - t.Errorf("unexpected changes (-have +want):\n\n%s", diff) - } - - }) - } - }) - - t.Run("failure", func(t *testing.T) { - for name, behaviour := range map[string]expect.Behaviour{ - "exit code": {ExitCode: 1}, - "malformed status": {Stdout: []byte("Z")}, - } { - t.Run(name, func(t *testing.T) { - expect.Commands( - t, - expect.NewGlob( - behaviour, - "docker", "run", "--rm", "--init", "--workdir", "/work", - "--mount", "type=bind,source=*,target=/run.sh,ro", - "--user", "0:0", - "--mount", "type=volume,source="+volumeID+",target=/work", - DockerVolumeWorkspaceImage, - "sh", "/run.sh", - ), - ) - - if _, err := w.Changes(ctx); err == nil { - t.Error("unexpected nil error") - } - }) - } - }) -} - func TestVolumeWorkspace_Diff(t *testing.T) { ctx := context.Background() w := &dockerVolumeWorkspace{volume: volumeID} diff --git a/internal/batches/workspace/workspace.go b/internal/batches/workspace/workspace.go index 7f173b71b6..b13f0b24dc 100644 --- a/internal/batches/workspace/workspace.go +++ b/internal/batches/workspace/workspace.go @@ -5,7 +5,6 @@ import ( "runtime" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" - "github.com/sourcegraph/sourcegraph/lib/batches/git" "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/batches/docker" @@ -39,15 +38,12 @@ type Workspace interface { // delete the workspace when Close is called. Close(ctx context.Context) error - // Changes is called after each step is executed, and should return the - // cumulative file changes that have occurred since Prepare was called. - Changes(ctx context.Context) (git.Changes, error) - // Diff should return the total diff for the workspace. This may be called // multiple times in the life of a workspace. Diff(ctx context.Context) ([]byte, error) - // ApplyDiff applies the given diff + // ApplyDiff applies the given diff to the current workspace. Used when replaying + // a cache entry onto the workspace. ApplyDiff(ctx context.Context, diff []byte) error } From 87b7685e9b2b3820f0bb9cb1dcbaeaddbe100561 Mon Sep 17 00:00:00 2001 From: Robert Lin Date: Thu, 14 Jul 2022 11:45:22 -0700 Subject: [PATCH 205/647] deps: upgrade sourcegraph/lib (#800) --- go.mod | 6 +++--- go.sum | 11 ++++++----- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/go.mod b/go.mod index 6ad5f49533..44d3c8d743 100644 --- a/go.mod +++ b/go.mod @@ -20,7 +20,7 @@ require ( github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf github.com/sourcegraph/scip v0.1.0 - github.com/sourcegraph/sourcegraph/lib v0.0.0-20220711172327-614bf6eac4e0 + github.com/sourcegraph/sourcegraph/lib v0.0.0-20220713192657-addd1c802a2e github.com/stretchr/testify v1.7.2 golang.org/x/net v0.0.0-20220526153639-5463443f8c37 golang.org/x/sync v0.0.0-20210220032951-036812b2e83c @@ -72,7 +72,7 @@ require ( github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect github.com/muesli/reflow v0.3.0 // indirect - github.com/muesli/termenv v0.9.0 // indirect + github.com/muesli/termenv v0.12.0 // indirect github.com/mwitkow/go-proto-validators v0.0.0-20180403085117-0950a7990007 // indirect github.com/olekukonko/tablewriter v0.0.5 // indirect github.com/pkg/errors v0.9.1 // indirect @@ -98,7 +98,7 @@ require ( go.uber.org/zap v1.21.0 // indirect golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 // indirect golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 // indirect - golang.org/x/sys v0.0.0-20220708085239-5a0f0661e09d // indirect + golang.org/x/sys v0.0.0-20220712014510-0a85c31ab51e // indirect golang.org/x/term v0.0.0-20220411215600-e5f449aeb171 // indirect golang.org/x/text v0.3.7 // indirect golang.org/x/tools v0.1.11 // indirect diff --git a/go.sum b/go.sum index bfe1dd250a..b1d59cfd6c 100644 --- a/go.sum +++ b/go.sum @@ -282,8 +282,9 @@ github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjY github.com/moul/http2curl v1.0.0/go.mod h1:8UbvGypXm98wA/IqH45anm5Y2Z6ep6O31QGOAZ3H0fQ= github.com/muesli/reflow v0.3.0 h1:IFsN6K9NfGtjeggFP+68I4chLZV2yIKsXJFNZ+eWh6s= github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKtnHY/8= -github.com/muesli/termenv v0.9.0 h1:wnbOaGz+LUR3jNT0zOzinPnyDaCZUQRZj9GxK8eRVl8= github.com/muesli/termenv v0.9.0/go.mod h1:R/LzAKf+suGs4IsO95y7+7DpFHO0KABgnZqtlyx2mBw= +github.com/muesli/termenv v0.12.0 h1:KuQRUE3PgxRFWhq4gHvZtPSLCGDqM5q/cYr1pZ39ytc= +github.com/muesli/termenv v0.12.0/go.mod h1:WCCv32tusQ/EEZ5S8oUIIrC/nIuBcxCVqlN4Xfkv+7A= github.com/mwitkow/go-proto-validators v0.0.0-20180403085117-0950a7990007 h1:28i1IjGcx8AofiB4N3q5Yls55VEaitzuEPkFJEVgGkA= github.com/mwitkow/go-proto-validators v0.0.0-20180403085117-0950a7990007/go.mod h1:m2XC9Qq0AlmmVksL6FktJCdTYyLk7V3fKyp0sl1yWQo= github.com/nats-io/jwt v0.3.0/go.mod h1:fRYCDE99xlTsqUzISS1Bi75UBJ6ljOJQOAAu5VglpSg= @@ -351,8 +352,8 @@ github.com/sourcegraph/log v0.0.0-20220707160925-6a936691c838 h1:8wknDSCUVYbaRT6 github.com/sourcegraph/log v0.0.0-20220707160925-6a936691c838/go.mod h1:zWEPlKrWBUVpko/tOgDS+qrp7BmzaCcmUrh9+ver1iQ= github.com/sourcegraph/scip v0.1.0 h1:kTs0CJaLQvcRZjg+HpGrcJPNX2Tx31+d6szWio3ZOkQ= github.com/sourcegraph/scip v0.1.0/go.mod h1:/AZ8RvsnRfeCZy232PJuVZqcl9f82fJnYwdWZeU2JCo= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20220711172327-614bf6eac4e0 h1:sWMGp3Mc3dGvLkGLPPe/qopXbITRi+WVkpUT0vl+DB8= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20220711172327-614bf6eac4e0/go.mod h1:4efRAk7Sv9XaetWwvOxZjiBO3i32jlsmQKpemvCJmMI= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20220713192657-addd1c802a2e h1:lNO4kQ7cxfexFGQvUj1b7csrS5a6BRsU0/XGsr239EQ= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20220713192657-addd1c802a2e/go.mod h1:NOllMVD9zFtTsYX/v/M9/zTIGtzOu3uhlWe2XN2N+hE= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= @@ -503,8 +504,8 @@ golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211007075335-d3039528d8ac/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220708085239-5a0f0661e09d h1:/m5NbqQelATgoSPVC2Z23sR4kVNokFwDDyWh/3rGY+I= -golang.org/x/sys v0.0.0-20220708085239-5a0f0661e09d/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220712014510-0a85c31ab51e h1:NHvCuwuS43lGnYhten69ZWqi2QOj/CiDNcKbVqwVoew= +golang.org/x/sys v0.0.0-20220712014510-0a85c31ab51e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20220411215600-e5f449aeb171 h1:EH1Deb8WZJ0xc0WK//leUHXcX9aLE5SymusoTmMZye8= golang.org/x/term v0.0.0-20220411215600-e5f449aeb171/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= From dab95918c945caef5f4a5dbe54c6af36211193bb Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Tue, 19 Jul 2022 13:58:38 +0200 Subject: [PATCH 206/647] Use new API to resolve workspaces server-side (#801) Makes use of the newly introduced endpoint in src-cli. This is usually faster, and it means we can eventually have just one code path again. --- cmd/src/batch_common.go | 54 +++++++--- cmd/src/batch_repositories.go | 11 +- go.mod | 2 +- go.sum | 4 +- internal/batches/features.go | 22 ++-- internal/batches/service/build_tasks.go | 5 +- internal/batches/service/service.go | 108 +++++++++++++++++++- internal/batches/service/workspaces.go | 2 - internal/batches/service/workspaces_test.go | 46 ++++----- internal/servegit/serve.go | 3 +- 10 files changed, 191 insertions(+), 66 deletions(-) diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index 189867bbff..d4d95ab63c 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -348,26 +348,49 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp ui.DeterminingWorkspaceCreatorTypeSuccess(typ) } - ui.ResolvingRepositories() - repos, err := svc.ResolveRepositories(ctx, batchSpec, opts.flags.allowUnsupported, opts.flags.allowIgnored) - if err != nil { - if repoSet, ok := err.(batches.UnsupportedRepoSet); ok { - ui.ResolvingRepositoriesDone(repos, repoSet, nil) - } else if repoSet, ok := err.(batches.IgnoredRepoSet); ok { - ui.ResolvingRepositoriesDone(repos, nil, repoSet) + var ( + repos []*graphql.Repository + workspaces []service.RepoWorkspace + ) + if svc.Features().ServerSideWorkspaceResolution { + ui.ResolvingRepositories() + workspaces, repos, err = svc.ResolveWorkspacesForBatchSpec(ctx, batchSpec, opts.flags.allowUnsupported, opts.flags.allowIgnored) + if err != nil { + if repoSet, ok := err.(batches.UnsupportedRepoSet); ok { + ui.ResolvingRepositoriesDone(repos, repoSet, nil) + } else if repoSet, ok := err.(batches.IgnoredRepoSet); ok { + ui.ResolvingRepositoriesDone(repos, nil, repoSet) + } else { + return errors.Wrap(err, "resolving repositories server-side") + } } else { - return errors.Wrap(err, "resolving repositories") + ui.ResolvingRepositoriesDone(repos, nil, nil) } + + ui.DeterminingWorkspaces() + ui.DeterminingWorkspacesSuccess(len(workspaces)) } else { - ui.ResolvingRepositoriesDone(repos, nil, nil) - } + ui.ResolvingRepositories() + repos, err := svc.ResolveRepositories(ctx, batchSpec, opts.flags.allowUnsupported, opts.flags.allowIgnored) + if err != nil { + if repoSet, ok := err.(batches.UnsupportedRepoSet); ok { + ui.ResolvingRepositoriesDone(repos, repoSet, nil) + } else if repoSet, ok := err.(batches.IgnoredRepoSet); ok { + ui.ResolvingRepositoriesDone(repos, nil, repoSet) + } else { + return errors.Wrap(err, "resolving repositories") + } + } else { + ui.ResolvingRepositoriesDone(repos, nil, nil) + } - ui.DeterminingWorkspaces() - workspaces, err := svc.DetermineWorkspaces(ctx, repos, batchSpec) - if err != nil { - return err + ui.DeterminingWorkspaces() + workspaces, err := svc.DetermineWorkspaces(ctx, repos, batchSpec) + if err != nil { + return err + } + ui.DeterminingWorkspacesSuccess(len(workspaces)) } - ui.DeterminingWorkspacesSuccess(len(workspaces)) archiveRegistry := repozip.NewArchiveRegistry(opts.client, opts.flags.cacheDir, opts.flags.cleanArchives) logManager := log.NewDiskManager(opts.flags.tempDir, opts.flags.keepLogs) @@ -399,6 +422,7 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp Name: batchSpec.Name, Description: batchSpec.Description, }, + batchSpec.Steps, workspaces, ) var ( diff --git a/cmd/src/batch_repositories.go b/cmd/src/batch_repositories.go index 7346becabf..02d8979cee 100644 --- a/cmd/src/batch_repositories.go +++ b/cmd/src/batch_repositories.go @@ -90,8 +90,7 @@ Examples: return err } - final := []*graphql.Repository{} - finalMax := 0 + repoCount := 0 for _, on := range spec.On { repos, _, err := svc.ResolveRepositoriesOn(ctx, &on) if err != nil { @@ -104,11 +103,7 @@ Examples: max = len(repo.Name) } - final = append(final, repo) - } - - if max > finalMax { - finalMax = max + repoCount++ } if err := execTemplate(queryTmpl, batchRepositoryTemplateInput{ @@ -123,7 +118,7 @@ Examples: } return execTemplate(totalTmpl, batchRepositoryTemplateInput{ - RepoCount: len(final), + RepoCount: repoCount, }) } diff --git a/go.mod b/go.mod index 44d3c8d743..c50a619f8e 100644 --- a/go.mod +++ b/go.mod @@ -20,7 +20,7 @@ require ( github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf github.com/sourcegraph/scip v0.1.0 - github.com/sourcegraph/sourcegraph/lib v0.0.0-20220713192657-addd1c802a2e + github.com/sourcegraph/sourcegraph/lib v0.0.0-20220715132627-cb906941e8b4 github.com/stretchr/testify v1.7.2 golang.org/x/net v0.0.0-20220526153639-5463443f8c37 golang.org/x/sync v0.0.0-20210220032951-036812b2e83c diff --git a/go.sum b/go.sum index b1d59cfd6c..4a0de3ddbd 100644 --- a/go.sum +++ b/go.sum @@ -352,8 +352,8 @@ github.com/sourcegraph/log v0.0.0-20220707160925-6a936691c838 h1:8wknDSCUVYbaRT6 github.com/sourcegraph/log v0.0.0-20220707160925-6a936691c838/go.mod h1:zWEPlKrWBUVpko/tOgDS+qrp7BmzaCcmUrh9+ver1iQ= github.com/sourcegraph/scip v0.1.0 h1:kTs0CJaLQvcRZjg+HpGrcJPNX2Tx31+d6szWio3ZOkQ= github.com/sourcegraph/scip v0.1.0/go.mod h1:/AZ8RvsnRfeCZy232PJuVZqcl9f82fJnYwdWZeU2JCo= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20220713192657-addd1c802a2e h1:lNO4kQ7cxfexFGQvUj1b7csrS5a6BRsU0/XGsr239EQ= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20220713192657-addd1c802a2e/go.mod h1:NOllMVD9zFtTsYX/v/M9/zTIGtzOu3uhlWe2XN2N+hE= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20220715132627-cb906941e8b4 h1:x+66tdk/r6k/t4gxs1g7WE9oY1CA35gHDAGHb0Sa6HI= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20220715132627-cb906941e8b4/go.mod h1:NOllMVD9zFtTsYX/v/M9/zTIGtzOu3uhlWe2XN2N+hE= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= diff --git a/internal/batches/features.go b/internal/batches/features.go index c27e94596f..a2a285fb47 100644 --- a/internal/batches/features.go +++ b/internal/batches/features.go @@ -9,16 +9,17 @@ import ( // FeatureFlags represent features that are only available on certain // Sourcegraph versions and we therefore have to detect at runtime. type FeatureFlags struct { - AllowArrayEnvironments bool - IncludeAutoAuthorDetails bool - UseGzipCompression bool - AllowTransformChanges bool - AllowWorkspaces bool - BatchChanges bool - AllowConditionalExec bool - AllowOptionalPublished bool - ServerSideBatchChanges bool - BitbucketCloud bool + AllowArrayEnvironments bool + IncludeAutoAuthorDetails bool + UseGzipCompression bool + AllowTransformChanges bool + AllowWorkspaces bool + BatchChanges bool + AllowConditionalExec bool + AllowOptionalPublished bool + ServerSideBatchChanges bool + BitbucketCloud bool + ServerSideWorkspaceResolution bool } func (ff *FeatureFlags) SetFromVersion(version string) error { @@ -44,6 +45,7 @@ func (ff *FeatureFlags) SetFromVersion(version string) error { {&ff.AllowOptionalPublished, ">= 3.30.0-0", "2021-06-21"}, {&ff.ServerSideBatchChanges, ">= 3.37.0-0", "2022-02-08"}, {&ff.BitbucketCloud, ">= 3.40.0-0", "2022-04-20"}, + {&ff.ServerSideWorkspaceResolution, ">= 3.42.0-0", "2022-07-19"}, } { value, err := api.CheckSourcegraphVersion(version, feature.constraint, feature.minDate) if err != nil { diff --git a/internal/batches/service/build_tasks.go b/internal/batches/service/build_tasks.go index d81eb4777b..c1eb10c475 100644 --- a/internal/batches/service/build_tasks.go +++ b/internal/batches/service/build_tasks.go @@ -3,20 +3,21 @@ package service import ( "context" + batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/template" "github.com/sourcegraph/src-cli/internal/batches/executor" ) // buildTasks returns *executor.Tasks for all the workspaces determined for the given spec. -func buildTasks(ctx context.Context, attributes *template.BatchChangeAttributes, workspaces []RepoWorkspace) []*executor.Task { +func buildTasks(ctx context.Context, attributes *template.BatchChangeAttributes, steps []batcheslib.Step, workspaces []RepoWorkspace) []*executor.Task { tasks := make([]*executor.Task, 0, len(workspaces)) for _, ws := range workspaces { task := &executor.Task{ Repository: ws.Repo, Path: ws.Path, - Steps: ws.Steps, + Steps: steps, OnlyFetchWorkspace: ws.OnlyFetchWorkspace, BatchChangeAttributes: attributes, diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index 2d86b1d858..d99f0d11b7 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -155,6 +155,110 @@ func (svc *Service) CreateChangesetSpec(ctx context.Context, spec *batcheslib.Ch return graphql.ChangesetSpecID(result.CreateChangesetSpec.ID), nil } +const resolveWorkspacesForBatchSpecQuery = ` +query ResolveWorkspacesForBatchSpec($spec: String!) { + resolveWorkspacesForBatchSpec(batchSpec: $spec) { + onlyFetchWorkspace + ignored + unsupported + repository { + id + name + url + externalRepository { serviceType } + defaultBranch { + name + target { oid } + } + } + branch { + name + target { + oid + } + } + path + searchResultPaths + } +} +` + +func (svc *Service) ResolveWorkspacesForBatchSpec(ctx context.Context, spec *batcheslib.BatchSpec, allowUnsupported, allowIgnored bool) ([]RepoWorkspace, []*graphql.Repository, error) { + raw, err := json.Marshal(spec) + if err != nil { + return nil, nil, errors.Wrap(err, "marshalling changeset spec JSON") + } + + var result struct { + ResolveWorkspacesForBatchSpec []struct { + OnlyFetchWorkspace bool + Ignored bool + Unsupported bool + Repository *graphql.Repository + Branch *graphql.Branch + Path string + SearchResultPaths []string + } + } + if ok, err := svc.newRequest(resolveWorkspacesForBatchSpecQuery, map[string]interface{}{ + "spec": string(raw), + }).Do(ctx, &result); err != nil || !ok { + return nil, nil, err + } + + unsupported := batches.UnsupportedRepoSet{} + ignored := batches.IgnoredRepoSet{} + + repos := make([]*graphql.Repository, 0, len(result.ResolveWorkspacesForBatchSpec)) + seenRepos := make(map[string]struct{}) + workspaces := make([]RepoWorkspace, 0, len(result.ResolveWorkspacesForBatchSpec)) + for _, w := range result.ResolveWorkspacesForBatchSpec { + fileMatches := make(map[string]bool) + for _, path := range w.SearchResultPaths { + fileMatches[path] = true + } + + workspace := RepoWorkspace{ + Repo: &graphql.Repository{ + ID: w.Repository.ID, + Name: w.Repository.Name, + URL: w.Repository.URL, + FileMatches: fileMatches, + ExternalRepository: w.Repository.ExternalRepository, + DefaultBranch: w.Repository.DefaultBranch, + Commit: w.Branch.Target, + Branch: *w.Branch, + }, + Path: w.Path, + OnlyFetchWorkspace: w.OnlyFetchWorkspace, + } + + if !allowIgnored && w.Ignored { + ignored.Append(workspace.Repo) + } else if !allowUnsupported && w.Unsupported { + unsupported.Append(workspace.Repo) + } else { + // Collect the repo, if not seen yet. + if _, ok := seenRepos[workspace.Repo.ID]; !ok { + seenRepos[workspace.Repo.ID] = struct{}{} + repos = append(repos, workspace.Repo) + } + + workspaces = append(workspaces, workspace) + } + } + + if unsupported.HasUnsupported() { + return workspaces, repos, unsupported + } + + if ignored.HasIgnored() { + return workspaces, repos, ignored + } + + return workspaces, repos, nil +} + // EnsureDockerImages iterates over the steps within the batch spec to ensure the // images exist and to determine the exact content digest to be used when running // each step, including any required by the service itself. @@ -264,8 +368,8 @@ func (svc *Service) DetermineWorkspaces(ctx context.Context, repos []*graphql.Re return findWorkspaces(ctx, spec, svc, repos) } -func (svc *Service) BuildTasks(ctx context.Context, attributes *templatelib.BatchChangeAttributes, workspaces []RepoWorkspace) []*executor.Task { - return buildTasks(ctx, attributes, workspaces) +func (svc *Service) BuildTasks(ctx context.Context, attributes *templatelib.BatchChangeAttributes, steps []batcheslib.Step, workspaces []RepoWorkspace) []*executor.Task { + return buildTasks(ctx, attributes, steps, workspaces) } func (svc *Service) Features() batches.FeatureFlags { diff --git a/internal/batches/service/workspaces.go b/internal/batches/service/workspaces.go index f8c73b1181..4c40211852 100644 --- a/internal/batches/service/workspaces.go +++ b/internal/batches/service/workspaces.go @@ -16,7 +16,6 @@ import ( type RepoWorkspace struct { Repo *graphql.Repository Path string - Steps []batcheslib.Step OnlyFetchWorkspace bool } @@ -151,7 +150,6 @@ func findWorkspaces( workspaces = append(workspaces, RepoWorkspace{ Repo: workspace.Repo, Path: path, - Steps: steps, OnlyFetchWorkspace: fetchWorkspace, }) } diff --git a/internal/batches/service/workspaces_test.go b/internal/batches/service/workspaces_test.go index be88d772c5..4eb94e728f 100644 --- a/internal/batches/service/workspaces_test.go +++ b/internal/batches/service/workspaces_test.go @@ -34,9 +34,9 @@ func TestFindWorkspaces(t *testing.T) { spec: &batcheslib.BatchSpec{Steps: steps}, finderResults: finderResults{}, wantWorkspaces: []RepoWorkspace{ - {Repo: repos[0], Steps: steps, Path: ""}, - {Repo: repos[1], Steps: steps, Path: ""}, - {Repo: repos[2], Steps: steps, Path: ""}, + {Repo: repos[0], Path: ""}, + {Repo: repos[1], Path: ""}, + {Repo: repos[2], Path: ""}, }, }, @@ -49,9 +49,9 @@ func TestFindWorkspaces(t *testing.T) { }, finderResults: finderResults{}, wantWorkspaces: []RepoWorkspace{ - {Repo: repos[0], Steps: steps, Path: ""}, - {Repo: repos[1], Steps: steps, Path: ""}, - {Repo: repos[2], Steps: steps, Path: ""}, + {Repo: repos[0], Path: ""}, + {Repo: repos[1], Path: ""}, + {Repo: repos[2], Path: ""}, }, }, @@ -67,7 +67,7 @@ func TestFindWorkspaces(t *testing.T) { repos[2]: []string{}, }, wantWorkspaces: []RepoWorkspace{ - {Repo: repos[1], Steps: steps, Path: ""}, + {Repo: repos[1], Path: ""}, }, }, @@ -83,13 +83,13 @@ func TestFindWorkspaces(t *testing.T) { repos[2]: {"a/b", "a/b/c", "d/e/f"}, }, wantWorkspaces: []RepoWorkspace{ - {Repo: repos[0], Steps: steps, Path: "a/b"}, - {Repo: repos[0], Steps: steps, Path: "a/b/c"}, - {Repo: repos[0], Steps: steps, Path: "d/e/f"}, - {Repo: repos[1], Steps: steps, Path: ""}, - {Repo: repos[2], Steps: steps, Path: "a/b"}, - {Repo: repos[2], Steps: steps, Path: "a/b/c"}, - {Repo: repos[2], Steps: steps, Path: "d/e/f"}, + {Repo: repos[0], Path: "a/b"}, + {Repo: repos[0], Path: "a/b/c"}, + {Repo: repos[0], Path: "d/e/f"}, + {Repo: repos[1], Path: ""}, + {Repo: repos[2], Path: "a/b"}, + {Repo: repos[2], Path: "a/b/c"}, + {Repo: repos[2], Path: "d/e/f"}, }, }, @@ -109,13 +109,13 @@ func TestFindWorkspaces(t *testing.T) { repos[2]: {"a/b", "a/b/c", "d/e/f"}, }, wantWorkspaces: []RepoWorkspace{ - {Repo: repos[0], Steps: steps, Path: "a/b", OnlyFetchWorkspace: true}, - {Repo: repos[0], Steps: steps, Path: "a/b/c", OnlyFetchWorkspace: true}, - {Repo: repos[0], Steps: steps, Path: "d/e/f", OnlyFetchWorkspace: true}, - {Repo: repos[1], Steps: steps, Path: ""}, - {Repo: repos[2], Steps: steps, Path: "a/b", OnlyFetchWorkspace: true}, - {Repo: repos[2], Steps: steps, Path: "a/b/c", OnlyFetchWorkspace: true}, - {Repo: repos[2], Steps: steps, Path: "d/e/f", OnlyFetchWorkspace: true}, + {Repo: repos[0], Path: "a/b", OnlyFetchWorkspace: true}, + {Repo: repos[0], Path: "a/b/c", OnlyFetchWorkspace: true}, + {Repo: repos[0], Path: "d/e/f", OnlyFetchWorkspace: true}, + {Repo: repos[1], Path: ""}, + {Repo: repos[2], Path: "a/b", OnlyFetchWorkspace: true}, + {Repo: repos[2], Path: "a/b/c", OnlyFetchWorkspace: true}, + {Repo: repos[2], Path: "d/e/f", OnlyFetchWorkspace: true}, }, }, "workspace configuration without 'in' matches all": { @@ -132,8 +132,8 @@ func TestFindWorkspaces(t *testing.T) { repos[2]: {"a/b"}, }, wantWorkspaces: []RepoWorkspace{ - {Repo: repos[0], Steps: steps, Path: "a/b"}, - {Repo: repos[2], Steps: steps, Path: "a/b"}, + {Repo: repos[0], Path: "a/b"}, + {Repo: repos[2], Path: "a/b"}, }, }, } diff --git a/internal/servegit/serve.go b/internal/servegit/serve.go index de5b9d17c0..1ee5c13320 100644 --- a/internal/servegit/serve.go +++ b/internal/servegit/serve.go @@ -1,6 +1,7 @@ package servegit import ( + "context" "encoding/json" "fmt" "html/template" @@ -104,7 +105,7 @@ func (s *Serve) handler() http.Handler { Dir: func(name string) string { return filepath.Join(s.Root, filepath.FromSlash(name)) }, - Trace: func(svc, repo, protocol string) func(error) { + Trace: func(ctx context.Context, svc, repo, protocol string) func(error) { start := time.Now() return func(err error) { s.Debug.Printf("git service svc=%s protocol=%s repo=%s duration=%v", svc, protocol, repo, time.Since(start)) From 4d5a398136bf7a42545aa60a8f5916411907c9f7 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Tue, 19 Jul 2022 14:05:40 +0200 Subject: [PATCH 207/647] Add changelog for 3.42.0 (#802) --- CHANGELOG.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index ef8d238b50..923cb6c0cb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,12 @@ All notable changes to `src-cli` are documented in this file. ### Removed +## 3.42.0 + +### Changed + +- Starting with Sourcegraph 3.42, src-cli will be resolving workspaces for Batch Changes server-side which is significantly faster and reduces network utilization. + ## 3.41.1 ### Added From 8db7dd7c030b851b8fa2f52ca277c838e5c12abe Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Wed, 20 Jul 2022 12:09:25 +0200 Subject: [PATCH 208/647] Fix workspace resolution for non-server-side (#803) That's what you get for restructuring. Also thank you go for allowing shadowing so silently :upside_down_face: --- CHANGELOG.md | 6 ++++++ cmd/src/batch_common.go | 4 ++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 923cb6c0cb..298c5854cd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,12 @@ All notable changes to `src-cli` are documented in this file. ### Removed +## 3.42.1 + +### Fixed + +- Fixed an issue where no workspaces would be executed on after successful workspace resolution. + ## 3.42.0 ### Changed diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index d4d95ab63c..553831adbd 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -371,7 +371,7 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp ui.DeterminingWorkspacesSuccess(len(workspaces)) } else { ui.ResolvingRepositories() - repos, err := svc.ResolveRepositories(ctx, batchSpec, opts.flags.allowUnsupported, opts.flags.allowIgnored) + repos, err = svc.ResolveRepositories(ctx, batchSpec, opts.flags.allowUnsupported, opts.flags.allowIgnored) if err != nil { if repoSet, ok := err.(batches.UnsupportedRepoSet); ok { ui.ResolvingRepositoriesDone(repos, repoSet, nil) @@ -385,7 +385,7 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp } ui.DeterminingWorkspaces() - workspaces, err := svc.DetermineWorkspaces(ctx, repos, batchSpec) + workspaces, err = svc.DetermineWorkspaces(ctx, repos, batchSpec) if err != nil { return err } From f02a7139c5e6c312980ec8ed4f21ae7033e7be67 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Thu, 21 Jul 2022 01:36:14 +0200 Subject: [PATCH 209/647] Don't keep unsupported/ignored repos error for server-side resolution (#804) The error was the global error and wasn't unset ever, so the execution would go on and eventually it fails with that error in the end. Also fixes a swallowed error for clear cache. --- CHANGELOG.md | 6 ++++++ cmd/src/batch_common.go | 6 ++++-- internal/batches/service/build_tasks.go | 4 +--- internal/batches/service/service.go | 4 ++-- internal/batches/service/service_test.go | 2 +- 5 files changed, 14 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 298c5854cd..18cca14224 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,12 @@ All notable changes to `src-cli` are documented in this file. ### Removed +## 3.42.2 + +### Fixed + +- Fixed an issue where execution would eventually fail with an error when there were unsupported or ignored workspaces found by server-side execution. + ## 3.42.1 ### Fixed diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index 553831adbd..91554c7850 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -354,6 +354,7 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp ) if svc.Features().ServerSideWorkspaceResolution { ui.ResolvingRepositories() + var err error workspaces, repos, err = svc.ResolveWorkspacesForBatchSpec(ctx, batchSpec, opts.flags.allowUnsupported, opts.flags.allowIgnored) if err != nil { if repoSet, ok := err.(batches.UnsupportedRepoSet); ok { @@ -417,7 +418,6 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp ui.CheckingCache() tasks := svc.BuildTasks( - ctx, &template.BatchChangeAttributes{ Name: batchSpec.Name, Description: batchSpec.Description, @@ -430,7 +430,9 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp uncachedTasks []*executor.Task ) if opts.flags.clearCache { - coord.ClearCache(ctx, tasks) + if err := coord.ClearCache(ctx, tasks); err != nil { + return err + } uncachedTasks = tasks } else { // Check the cache for completely cached executions. diff --git a/internal/batches/service/build_tasks.go b/internal/batches/service/build_tasks.go index c1eb10c475..c7898759ff 100644 --- a/internal/batches/service/build_tasks.go +++ b/internal/batches/service/build_tasks.go @@ -1,8 +1,6 @@ package service import ( - "context" - batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/template" @@ -10,7 +8,7 @@ import ( ) // buildTasks returns *executor.Tasks for all the workspaces determined for the given spec. -func buildTasks(ctx context.Context, attributes *template.BatchChangeAttributes, steps []batcheslib.Step, workspaces []RepoWorkspace) []*executor.Task { +func buildTasks(attributes *template.BatchChangeAttributes, steps []batcheslib.Step, workspaces []RepoWorkspace) []*executor.Task { tasks := make([]*executor.Task, 0, len(workspaces)) for _, ws := range workspaces { diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index d99f0d11b7..44c97843e1 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -368,8 +368,8 @@ func (svc *Service) DetermineWorkspaces(ctx context.Context, repos []*graphql.Re return findWorkspaces(ctx, spec, svc, repos) } -func (svc *Service) BuildTasks(ctx context.Context, attributes *templatelib.BatchChangeAttributes, steps []batcheslib.Step, workspaces []RepoWorkspace) []*executor.Task { - return buildTasks(ctx, attributes, steps, workspaces) +func (svc *Service) BuildTasks(attributes *templatelib.BatchChangeAttributes, steps []batcheslib.Step, workspaces []RepoWorkspace) []*executor.Task { + return buildTasks(attributes, steps, workspaces) } func (svc *Service) Features() batches.FeatureFlags { diff --git a/internal/batches/service/service_test.go b/internal/batches/service/service_test.go index e407d246df..8d2f1b604e 100644 --- a/internal/batches/service/service_test.go +++ b/internal/batches/service/service_test.go @@ -134,7 +134,7 @@ func mockGraphQLClient(responses ...string) (client api.Client, done func()) { mux := http.NewServeMux() var count int - mux.HandleFunc("/.api/graphql", func(w http.ResponseWriter, r *http.Request) { + mux.HandleFunc("/.api/graphql", func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "application/json") _, _ = w.Write([]byte(responses[count])) From 86c548b6976e1568d3cce1e7e1e97ab2e594ed43 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Mon, 25 Jul 2022 16:51:44 +0200 Subject: [PATCH 210/647] Port workspaces path fix to src-cli (#779) --- internal/batches/service/workspaces.go | 17 +++++- internal/batches/service/workspaces_test.go | 61 +++++++++++++++++++-- 2 files changed, 72 insertions(+), 6 deletions(-) diff --git a/internal/batches/service/workspaces.go b/internal/batches/service/workspaces.go index 4c40211852..c5df1005ac 100644 --- a/internal/batches/service/workspaces.go +++ b/internal/batches/service/workspaces.go @@ -3,6 +3,7 @@ package service import ( "context" "sort" + "strings" "github.com/gobwas/glob" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" @@ -137,7 +138,19 @@ func findWorkspaces( fetchWorkspace = false } - steps, err := stepsForRepo(spec, util.NewTemplatingRepo(workspace.Repo.Name, workspace.Repo.FileMatches)) + // Filter file matches by workspace. Only include paths that are + // _within_ the directory. + paths := map[string]bool{} + for probe := range workspace.Repo.FileMatches { + if strings.HasPrefix(probe, path) { + paths[probe] = true + } + } + + repo := *workspace.Repo + repo.FileMatches = paths + + steps, err := stepsForRepo(spec, util.NewTemplatingRepo(repo.Name, repo.FileMatches)) if err != nil { return nil, err } @@ -148,7 +161,7 @@ func findWorkspaces( } workspaces = append(workspaces, RepoWorkspace{ - Repo: workspace.Repo, + Repo: &repo, Path: path, OnlyFetchWorkspace: fetchWorkspace, }) diff --git a/internal/batches/service/workspaces_test.go b/internal/batches/service/workspaces_test.go index 4eb94e728f..06b9be3193 100644 --- a/internal/batches/service/workspaces_test.go +++ b/internal/batches/service/workspaces_test.go @@ -15,9 +15,10 @@ import ( func TestFindWorkspaces(t *testing.T) { repos := []*graphql.Repository{ - {ID: "repo-id-0", Name: "github.com/sourcegraph/automation-testing"}, - {ID: "repo-id-1", Name: "github.com/sourcegraph/sourcegraph"}, - {ID: "repo-id-2", Name: "bitbucket.sgdev.org/SOUR/automation-testing"}, + {ID: "repo-id-0", Name: "github.com/sourcegraph/automation-testing", FileMatches: map[string]bool{}}, + {ID: "repo-id-1", Name: "github.com/sourcegraph/sourcegraph", FileMatches: map[string]bool{}}, + {ID: "repo-id-2", Name: "bitbucket.sgdev.org/SOUR/automation-testing", FileMatches: map[string]bool{}}, + {ID: "repo-id-3", Name: "github.com/sourcegraph/src-cli", FileMatches: map[string]bool{"a/b": true, "a/b/c": true, "d/e/f": true}}, } steps := []batcheslib.Step{{Run: "echo 1"}} @@ -37,6 +38,7 @@ func TestFindWorkspaces(t *testing.T) { {Repo: repos[0], Path: ""}, {Repo: repos[1], Path: ""}, {Repo: repos[2], Path: ""}, + {Repo: repos[3], Path: ""}, }, }, @@ -52,10 +54,11 @@ func TestFindWorkspaces(t *testing.T) { {Repo: repos[0], Path: ""}, {Repo: repos[1], Path: ""}, {Repo: repos[2], Path: ""}, + {Repo: repos[3], Path: ""}, }, }, - "workspace configuration matching 2 repos with no results": { + "workspace configuration matching 3 repos with no results": { spec: &batcheslib.BatchSpec{ Steps: steps, Workspaces: []batcheslib.WorkspaceConfiguration{ @@ -68,6 +71,7 @@ func TestFindWorkspaces(t *testing.T) { }, wantWorkspaces: []RepoWorkspace{ {Repo: repos[1], Path: ""}, + {Repo: repos[3], Path: ""}, }, }, @@ -90,6 +94,7 @@ func TestFindWorkspaces(t *testing.T) { {Repo: repos[2], Path: "a/b"}, {Repo: repos[2], Path: "a/b/c"}, {Repo: repos[2], Path: "d/e/f"}, + {Repo: repos[3], Path: ""}, }, }, @@ -116,6 +121,7 @@ func TestFindWorkspaces(t *testing.T) { {Repo: repos[2], Path: "a/b", OnlyFetchWorkspace: true}, {Repo: repos[2], Path: "a/b/c", OnlyFetchWorkspace: true}, {Repo: repos[2], Path: "d/e/f", OnlyFetchWorkspace: true}, + {Repo: repos[3], Path: ""}, }, }, "workspace configuration without 'in' matches all": { @@ -136,6 +142,53 @@ func TestFindWorkspaces(t *testing.T) { {Repo: repos[2], Path: "a/b"}, }, }, + "workspace gets subset of search_result_paths": { + spec: &batcheslib.BatchSpec{ + Steps: steps, + Workspaces: []batcheslib.WorkspaceConfiguration{ + { + In: "*src-cli", + RootAtLocationOf: "package.json", + }, + }, + }, + finderResults: finderResults{ + repos[3]: {"a/b", "d"}, + }, + wantWorkspaces: []RepoWorkspace{ + {Repo: repos[0], Path: ""}, + {Repo: repos[1], Path: ""}, + {Repo: repos[2], Path: ""}, + { + Repo: &graphql.Repository{ + ID: repos[3].ID, + Name: repos[3].Name, + URL: repos[3].URL, + ExternalRepository: repos[3].ExternalRepository, + DefaultBranch: repos[3].DefaultBranch, + Branch: repos[3].Branch, + Commit: repos[3].Commit, + // Only expect the file matches that are children of a/b. + FileMatches: map[string]bool{"a/b": true, "a/b/c": true}, + }, + Path: "a/b", + }, + { + Repo: &graphql.Repository{ + ID: repos[3].ID, + Name: repos[3].Name, + URL: repos[3].URL, + ExternalRepository: repos[3].ExternalRepository, + DefaultBranch: repos[3].DefaultBranch, + Branch: repos[3].Branch, + Commit: repos[3].Commit, + // Only expect the file matches that are children of d. + FileMatches: map[string]bool{"d/e/f": true}, + }, + Path: "d", + }, + }, + }, } for name, tt := range tests { From 625547b5b37fb61f16d8e9e75457dad500f469bd Mon Sep 17 00:00:00 2001 From: Rijnard van Tonder Date: Tue, 26 Jul 2022 15:30:06 -0700 Subject: [PATCH 211/647] test: use autogold for testdata (#806) --- .gitignore | 4 +- cmd/src/search_stream_test.go | 14 ++----- .../JSON.golden} | 0 .../Text.golden} | 0 go.mod | 6 +++ go.sum | 37 +++++++++++++++++++ 6 files changed, 48 insertions(+), 13 deletions(-) rename cmd/src/testdata/{streaming_search_want.json => TestSearchStream/JSON.golden} (100%) mode change 100755 => 100644 rename cmd/src/testdata/{streaming_search_want.txt => TestSearchStream/Text.golden} (100%) diff --git a/.gitignore b/.gitignore index c4b8f452b8..6b0ad027c3 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,8 @@ ./src -./cmd/src/src +cmd/src/src *.zip release ./vendor .idea .env -.envrc \ No newline at end of file +.envrc diff --git a/cmd/src/search_stream_test.go b/cmd/src/search_stream_test.go index 2eea7589a6..01a4500bd4 100644 --- a/cmd/src/search_stream_test.go +++ b/cmd/src/search_stream_test.go @@ -9,7 +9,7 @@ import ( "os" "testing" - "github.com/google/go-cmp/cmp" + "github.com/hexops/autogold" "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/streaming" @@ -113,19 +113,16 @@ func TestSearchStream(t *testing.T) { cases := []struct { name string opts streaming.Opts - want string }{ { "Text", streaming.Opts{}, - "./testdata/streaming_search_want.txt", }, { "JSON", streaming.Opts{ Json: true, }, - "./testdata/streaming_search_want.json", }, } for _, c := range cases { @@ -151,13 +148,8 @@ func TestSearchStream(t *testing.T) { if err != nil { t.Fatal(err) } - want, err := os.ReadFile(c.want) - if err != nil { - t.Fatal(err) - } - if d := cmp.Diff(want, got); d != "" { - t.Fatalf("(-want +got): %s", d) - } + + autogold.Equal(t, autogold.Raw(got)) }) } diff --git a/cmd/src/testdata/streaming_search_want.json b/cmd/src/testdata/TestSearchStream/JSON.golden old mode 100755 new mode 100644 similarity index 100% rename from cmd/src/testdata/streaming_search_want.json rename to cmd/src/testdata/TestSearchStream/JSON.golden diff --git a/cmd/src/testdata/streaming_search_want.txt b/cmd/src/testdata/TestSearchStream/Text.golden similarity index 100% rename from cmd/src/testdata/streaming_search_want.txt rename to cmd/src/testdata/TestSearchStream/Text.golden diff --git a/go.mod b/go.mod index c50a619f8e..8104a6b9ff 100644 --- a/go.mod +++ b/go.mod @@ -54,6 +54,9 @@ require ( github.com/golang/protobuf v1.5.2 // indirect github.com/google/uuid v1.3.0 // indirect github.com/gorilla/css v1.0.0 // indirect + github.com/hexops/autogold v1.3.0 // indirect + github.com/hexops/gotextdiff v1.0.3 // indirect + github.com/hexops/valast v1.4.1 // indirect github.com/huandu/xstrings v1.0.0 // indirect github.com/imdario/mergo v0.3.4 // indirect github.com/inconshreveable/mousetrap v1.0.0 // indirect @@ -74,6 +77,7 @@ require ( github.com/muesli/reflow v0.3.0 // indirect github.com/muesli/termenv v0.12.0 // indirect github.com/mwitkow/go-proto-validators v0.0.0-20180403085117-0950a7990007 // indirect + github.com/nightlyone/lockfile v1.0.0 // indirect github.com/olekukonko/tablewriter v0.0.5 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/pkg/profile v1.6.0 // indirect @@ -83,6 +87,7 @@ require ( github.com/rivo/uniseg v0.2.0 // indirect github.com/rogpeppe/go-internal v1.8.1 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect + github.com/shurcooL/go-goon v0.0.0-20210110234559-7585751d9a17 // indirect github.com/sourcegraph/log v0.0.0-20220707160925-6a936691c838 // indirect github.com/spf13/cobra v1.4.0 // indirect github.com/spf13/pflag v1.0.5 // indirect @@ -106,6 +111,7 @@ require ( google.golang.org/genproto v0.0.0-20220414192740-2d67ff6cf2b4 // indirect google.golang.org/grpc v1.45.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect + mvdan.cc/gofumpt v0.2.1 // indirect ) // See: https://github.com/ghodss/yaml/pull/65 diff --git a/go.sum b/go.sum index 4a0de3ddbd..5c14b50bd6 100644 --- a/go.sum +++ b/go.sum @@ -94,6 +94,7 @@ github.com/fatih/color v1.13.0 h1:8LOYc1KYPPmyKMuN8QV2DNRWNbLo6LZ0iLs8+mlH53w= github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M= github.com/flosch/pongo2 v0.0.0-20190707114632-bbf5a6c351f4/go.mod h1:T9YF2M40nIgbVgp3rreNmTged+9HrbNTIQf1PsaIiTA= +github.com/frankban/quicktest v1.14.0/go.mod h1:NeW+ay9A/U67EYXNFA1nPE8e/tnQv/09mUdL/ijj8og= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/gavv/httpexpect v2.0.0+incompatible/go.mod h1:x+9tiU1YnrOvnB725RkpoLv1M62hOWzwo5OXotisrKc= @@ -151,7 +152,9 @@ github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.7 h1:81/ik6ipDQS2aGcBfIN5dHDB36BwrStyeAQquSYCV4o= github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE= github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck= @@ -169,6 +172,14 @@ github.com/grafana/regexp v0.0.0-20220202152701-6a046c4caf32/go.mod h1:M5qHK+eWf github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= github.com/hashicorp/go-version v1.2.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= +github.com/hexops/autogold v0.8.1/go.mod h1:97HLDXyG23akzAoRYJh/2OBs3kd80eHyKPvZw0S5ZBY= +github.com/hexops/autogold v1.3.0 h1:IEtGNPxBeBu8RMn8eKWh/Ll9dVNgSnJ7bp/qHgMQ14o= +github.com/hexops/autogold v1.3.0/go.mod h1:d4hwi2rid66Sag+BVuHgwakW/EmaFr8vdTSbWDbrDRI= +github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM= +github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg= +github.com/hexops/valast v1.4.0/go.mod h1:uVjKZ0smVuYlgCSPz9NRi5A04sl7lp6GtFWsROKDgEs= +github.com/hexops/valast v1.4.1 h1:vlB+usah+MLacCyDDqACn2yhAoCDlpHYkpEKtej+RXE= +github.com/hexops/valast v1.4.1/go.mod h1:G+D6TExWuKs5he+hYlPMfYyhQ8w8qbc2vm4gDWwLdDg= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/huandu/xstrings v1.0.0 h1:pO2K/gKgKaat5LdpAhxhluX2GPQMaI3W5FUz/I/UnWk= github.com/huandu/xstrings v1.0.0/go.mod h1:4qWG/gcEcfX4z/mBDHJ++3ReCw9ibxbsNJbcucJdbSo= @@ -297,6 +308,8 @@ github.com/neelance/parallel v0.0.0-20160708114440-4de9ce63d14c h1:NZOii9TDGRAfC github.com/neelance/parallel v0.0.0-20160708114440-4de9ce63d14c/go.mod h1:eTBvSIlRgLo+CNFFQRQTwUGTZOEdvXIKeZS/xG+D2yU= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= +github.com/nightlyone/lockfile v1.0.0 h1:RHep2cFKK4PonZJDdEl4GmkabuhbsRMgk/k3uAmxBiA= +github.com/nightlyone/lockfile v1.0.0/go.mod h1:rywoIealpdNse2r832aiD9jRk8ErCatROs6LzC841CI= github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec= github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY= @@ -329,6 +342,8 @@ github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY= github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= +github.com/rogpeppe/go-internal v1.6.2/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= +github.com/rogpeppe/go-internal v1.8.1-0.20211023094830-115ce09fd6b4/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= github.com/rogpeppe/go-internal v1.8.1 h1:geMPLpDpQOgVyCg5z5GoRwLHepNdb71NXb67XFkP+Eg= github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= @@ -341,6 +356,8 @@ github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAm github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= github.com/shurcooL/go v0.0.0-20180423040247-9e1955d9fb6e/go.mod h1:TDJrrUr11Vxrven61rcy3hJMUqaf/CLWYhHNPmT14Lk= github.com/shurcooL/go-goon v0.0.0-20170922171312-37c2f522c041/go.mod h1:N5mDOmsrJOB+vfqUK+7DmDyjhSLIIBnXo9lvZJj3MWQ= +github.com/shurcooL/go-goon v0.0.0-20210110234559-7585751d9a17 h1:lRAUE0dIvigSSFAmaM2dfg7OH8T+a8zJ5smEh09a/GI= +github.com/shurcooL/go-goon v0.0.0-20210110234559-7585751d9a17/go.mod h1:N5mDOmsrJOB+vfqUK+7DmDyjhSLIIBnXo9lvZJj3MWQ= github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= @@ -402,6 +419,7 @@ github.com/yudai/pp v2.0.1+incompatible/go.mod h1:PuxR/8QJ7cyCkFp/aUDS+JY727OFEZ github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= github.com/yuin/goldmark v1.4.4 h1:zNWRjYUW32G9KirMXYHQHVNFkXvMI7LpgNW2AgYAoIs= github.com/yuin/goldmark v1.4.4/go.mod h1:rmuwmfZ0+bvzB24eSC//bk1R1Zp3hM0OXYv/G2LIilg= github.com/yuin/goldmark-emoji v1.0.1 h1:ctuWEyzGBwiucEqxzwe0SOYDXPAucOrE9NQC18Wa1os= @@ -437,7 +455,10 @@ golang.org/x/lint v0.0.0-20210508222113-6edffad5e616/go.mod h1:3xt1FjdF8hUf6vQPI golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 h1:6zppjxzCulZykYSLyVDYbneBfbaBIQPYMevg0bEwv2s= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -463,6 +484,7 @@ golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/net v0.0.0-20210614182718-04defd469f4e/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211008194852-3b03d305991f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220526153639-5463443f8c37 h1:lUkvobShwKsOesNfWWlCS5q7fnbG1MEliIzwu886fn8= golang.org/x/net v0.0.0-20220526153639-5463443f8c37/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= @@ -493,6 +515,8 @@ golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20200519105757-fe76b779f299/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210218084038-e8e29180ff58/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210403161142-5e06dd20ab57/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -503,6 +527,10 @@ golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211007075335-d3039528d8ac/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211102192858-4dd72447c267/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211117180635-dee7805ff2e1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211213223007-03aa0b5f6827/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220712014510-0a85c31ab51e h1:NHvCuwuS43lGnYhten69ZWqi2QOj/CiDNcKbVqwVoew= golang.org/x/sys v0.0.0-20220712014510-0a85c31ab51e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -531,9 +559,13 @@ golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtn golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200624163319-25775e59acb7/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20210101214203-2dba1e4ea05c/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/tools v0.1.8-0.20211102182255-bb4add04ddef/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= +golang.org/x/tools v0.1.8/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= golang.org/x/tools v0.1.11 h1:loJ25fNOEhSXfHrpoGj91eCUThwdNX6u24rO1xnNteY= golang.org/x/tools v0.1.11/go.mod h1:SgwaegtQh8clINPpECJMqnxLv9I09HLqnW3RMqW0CA4= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -608,3 +640,8 @@ honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWh honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7 h1:mub0MmFLOn8XLikZOAhgLD1kXJq8jgftSrrv7m00xFo= jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7/go.mod h1:OxvTsCwKosqQ1q7B+8FwXqg4rKZ/UG9dUW+g/VL2xH4= +mvdan.cc/gofumpt v0.0.0-20210107193838-d24d34e18d44/go.mod h1:yXG1r1WqZVKWbVRtBWKWX9+CxGYfA51nSomhM0woR48= +mvdan.cc/gofumpt v0.1.0/go.mod h1:yXG1r1WqZVKWbVRtBWKWX9+CxGYfA51nSomhM0woR48= +mvdan.cc/gofumpt v0.2.0/go.mod h1:TiGmrf914DAuT6+hDIxOqoDb4QXIzAuEUSXqEf9hGKY= +mvdan.cc/gofumpt v0.2.1 h1:7jakRGkQcLAJdT+C8Bwc9d0BANkVPSkHZkzNv07pJAs= +mvdan.cc/gofumpt v0.2.1/go.mod h1:a/rvZPhsNaedOJBzqRD9omnwVwHZsBdJirXHa9Gh9Ig= From e043d96c063d289214c959f2872b25c9c1bce061 Mon Sep 17 00:00:00 2001 From: Rijnard van Tonder Date: Thu, 28 Jul 2022 15:09:04 -0700 Subject: [PATCH 212/647] search: use chunk matches to render multiline streamed results (#807) --- CHANGELOG.md | 2 + cmd/src/format.go | 14 +-- cmd/src/search_stream.go | 106 +++++++++--------- cmd/src/search_stream_test.go | 29 ++++- cmd/src/testdata/TestSearchStream/JSON.golden | 2 +- cmd/src/testdata/TestSearchStream/Text.golden | 8 +- internal/streaming/events.go | 26 ++++- internal/streaming/search.go | 7 ++ 8 files changed, 119 insertions(+), 75 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 18cca14224..210e5affe6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,8 @@ All notable changes to `src-cli` are documented in this file. ### Changed +- **IMPORTANT:** Searches using the command `src search -stream` is updated to use a **new and better search result schema**, improving highlighting and accurate result counts for multiline matches. Please see the new JSON schema for results if you use the `src search -stream -json` output: [#807](https://github.com/sourcegraph/src-cli/pull/807) + ### Fixed ### Removed diff --git a/cmd/src/format.go b/cmd/src/format.go index af36ee157b..2c08d4fcc1 100644 --- a/cmd/src/format.go +++ b/cmd/src/format.go @@ -60,9 +60,6 @@ func parseTemplate(text string) (*template.Template, error) { "addFloat": func(x, y float64) float64 { return x + y }, - "addInt32": func(x, y int32) int32 { - return x + y - }, "debug": func(v interface{}) string { data, _ := marshalIndent(v) fmt.Println(string(data)) @@ -95,12 +92,11 @@ func parseTemplate(text string) (*template.Template, error) { "renderResult": searchTemplateFuncs["renderResult"], // Register stream-search specific template functions. - "streamSearchSequentialLineNumber": streamSearchTemplateFuncs["streamSearchSequentialLineNumber"], - "streamSearchHighlightMatch": streamSearchTemplateFuncs["streamSearchHighlightMatch"], - "streamSearchHighlightCommit": streamSearchTemplateFuncs["streamSearchHighlightCommit"], - "streamSearchRenderCommitLabel": streamSearchTemplateFuncs["streamSearchRenderCommitLabel"], - "matchOrMatches": streamSearchTemplateFuncs["matchOrMatches"], - "countMatches": streamSearchTemplateFuncs["countMatches"], + "streamSearchHighlightMatch": streamSearchTemplateFuncs["streamSearchHighlightMatch"], + "streamSearchHighlightCommit": streamSearchTemplateFuncs["streamSearchHighlightCommit"], + "streamSearchRenderCommitLabel": streamSearchTemplateFuncs["streamSearchRenderCommitLabel"], + "matchOrMatches": streamSearchTemplateFuncs["matchOrMatches"], + "countMatches": streamSearchTemplateFuncs["countMatches"], // Alert rendering "searchAlertRender": func(alert searchResultsAlert) string { diff --git a/cmd/src/search_stream.go b/cmd/src/search_stream.go index 68ad43f987..7cdb9cea19 100644 --- a/cmd/src/search_stream.go +++ b/cmd/src/search_stream.go @@ -226,20 +226,16 @@ const streamingTemplate = ` {{- color "search-repository"}}{{.Repository}}{{color "nc" -}} {{- " › " -}} {{- color "search-filename"}}{{.Path}}{{color "nc" -}} - {{- color "success"}}{{matchOrMatches (countMatches .LineMatches)}}{{color "nc" -}} + {{- color "success"}}{{matchOrMatches (countMatches .ChunkMatches)}}{{color "nc" -}} {{- "\n" -}} {{- color "search-border"}}{{"--------------------------------------------------------------------------------\n"}}{{color "nc"}} - - {{- /* Line matches */ -}} - {{- $lineMatches := .LineMatches -}} - {{- range $index, $match := $lineMatches -}} - {{- if not (streamSearchSequentialLineNumber $lineMatches $index) -}} - {{- color "search-border"}}{{" ------------------------------------------------------------------------------\n"}}{{color "nc"}} - {{- end -}} - {{- " "}}{{color "search-line-numbers"}}{{pad (addInt32 $match.LineNumber 1) 6 " "}}{{color "nc" -}} - {{- color "search-border"}}{{" | "}}{{color "nc"}}{{streamSearchHighlightMatch $.Query $match }} + + {{- /* Content matches */ -}} + {{- $chunks := .ChunkMatches -}} + {{- range $index, $chunk := $chunks -}} + {{streamSearchHighlightMatch $chunk }} + {{- color "search-border"}}{{"\n ------------------------------------------------------------------------------\n"}}{{color "nc"}} {{- end -}} - {{- "\n" -}} {{- end -}} {{define "symbol"}} @@ -250,7 +246,7 @@ const streamingTemplate = ` {{- color "success"}}{{matchOrMatches (len .Symbols)}}{{color "nc" -}} {{- "\n" -}} {{- color "search-border"}}{{"--------------------------------------------------------------------------------\n"}}{{color "nc"}} - + {{- /* Symbols */ -}} {{- $symbols := .Symbols -}} {{- range $index, $match := $symbols -}} @@ -278,7 +274,7 @@ const streamingTemplate = ` {{- color "search-link"}}{{$.SourcegraphEndpoint}}{{.URL}}{{color "nc" -}} {{- color "search-border"}}{{")\n"}}{{color "nc" -}} {{- color "nc" -}} - + {{- /* Repository > author name "commit subject" (time ago) */ -}} {{- color "search-commit-subject"}}{{(streamSearchRenderCommitLabel .Label)}}{{color "nc" -}} {{- color "success" -}} @@ -321,25 +317,52 @@ const streamingTemplate = ` ` var streamSearchTemplateFuncs = map[string]interface{}{ - "streamSearchHighlightMatch": func(query string, match streaming.EventLineMatch) string { - var highlights []highlight - if strings.Contains(query, "patterntype:structural") { - highlights = streamConvertMatchToHighlights(match, false) - return applyHighlightsForFile(match.Line, highlights) + "streamSearchHighlightMatch": func(match streaming.ChunkMatch) string { + var result []rune + + addLineColumn := func(n int) []rune { + result = append(result, []rune(" ")...) + result = append(result, []rune(ansiColors["search-line-numbers"])...) + result = append(result, []rune(fmt.Sprintf("% 6d", match.ContentStart.Line+1+n))...) + result = append(result, []rune(ansiColors["nc"])...) + result = append(result, []rune(ansiColors["search-border"])...) + result = append(result, []rune(" | ")...) + result = append(result, []rune(ansiColors["nc"])...) + return result } - highlights = streamConvertMatchToHighlights(match, true) - return applyHighlights(match.Line, highlights, ansiColors["search-match"], ansiColors["nc"]) - }, + // if there are overlapping ranges, use this value to know + // whether to terminate highlighting or not. + highlightingActive := 0 + + lineCount := 0 + addLineColumn(lineCount) + for offset, r := range match.Content { + offset++ + if r == '\n' { + lineCount++ + result = append(result, []rune(ansiColors["nc"])...) + result = append(result, r) + addLineColumn(lineCount) + result = append(result, []rune(ansiColors["search-match"])...) + continue + } + for _, rr := range match.Ranges { + if rr.Start.Offset-match.ContentStart.Offset+1 == offset { + result = append(result, []rune(ansiColors["search-match"])...) + highlightingActive++ + } else if rr.End.Offset-match.ContentStart.Offset+1 == offset { + highlightingActive-- + if highlightingActive <= 0 { + result = append(result, []rune(ansiColors["nc"])...) + } + } + } + result = append(result, r) - "streamSearchSequentialLineNumber": func(lineMatches []streaming.EventLineMatch, index int) bool { - prevIndex := index - 1 - if prevIndex < 0 { - return true } - prevLineNumber := lineMatches[prevIndex].LineNumber - lineNumber := lineMatches[index].LineNumber - return prevLineNumber == lineNumber-1 + result = append(result, []rune(ansiColors["nc"])...) + return string(result) }, "streamSearchHighlightCommit": func(content string, ranges [][3]int32) string { @@ -372,10 +395,10 @@ var streamSearchTemplateFuncs = map[string]interface{}{ return fmt.Sprintf(" (%d matches)", i) }, - "countMatches": func(lineMatches []streaming.EventLineMatch) int { + "countMatches": func(chunks []streaming.ChunkMatch) int { count := 0 - for _, l := range lineMatches { - count += len(l.OffsetAndLengths) + for _, c := range chunks { + count += len(c.Ranges) } return count }, @@ -447,27 +470,6 @@ func stripMarkdownMarkers(content string) string { return strings.TrimSuffix(content, "\n```") } -// convertMatchToHighlights converts a FileMatch m to a highlight data type. -// When isPreview is true, it is assumed that the result to highlight is only on -// one line, and the offsets 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 streamConvertMatchToHighlights(m streaming.EventLineMatch, isPreview bool) (highlights []highlight) { - var line int - for _, offsetAndLength := range m.OffsetAndLengths { - ol := offsetAndLength - offset := int(ol[0]) - length := int(ol[1]) - if isPreview { - line = 1 - } else { - line = int(m.LineNumber) - } - highlights = append(highlights, highlight{line: line, character: offset, length: length}) - } - return highlights -} - func logError(msg string) { _, _ = fmt.Fprint(os.Stderr, msg) } diff --git a/cmd/src/search_stream_test.go b/cmd/src/search_stream_test.go index 01a4500bd4..1653b273ac 100644 --- a/cmd/src/search_stream_test.go +++ b/cmd/src/search_stream_test.go @@ -43,11 +43,32 @@ var event = []streaming.EventMatch{ Repository: "org/repo", Branches: nil, Commit: "", - LineMatches: []streaming.EventLineMatch{ + ChunkMatches: []streaming.ChunkMatch{ { - Line: "foo bar foo", - LineNumber: 4, - OffsetAndLengths: [][2]int32{{0, 3}, {8, 3}}, + Content: "foo bar foo", + ContentStart: streaming.Location{Line: 4}, + Ranges: []streaming.Range{ + { + Start: streaming.Location{Offset: 0}, + End: streaming.Location{Offset: 3}, + }, + { + Start: streaming.Location{Offset: 0}, + End: streaming.Location{Offset: 3}, + }, + { + Start: streaming.Location{Offset: 1}, + End: streaming.Location{Offset: 2}, + }, + { + Start: streaming.Location{Offset: 1}, + End: streaming.Location{Offset: 3}, + }, + { + Start: streaming.Location{Offset: 8}, + End: streaming.Location{Offset: 11}, + }, + }, }, }, }, diff --git a/cmd/src/testdata/TestSearchStream/JSON.golden b/cmd/src/testdata/TestSearchStream/JSON.golden index cd98ef048d..bbc8b0ac9b 100644 --- a/cmd/src/testdata/TestSearchStream/JSON.golden +++ b/cmd/src/testdata/TestSearchStream/JSON.golden @@ -1,4 +1,4 @@ -{"type":"content","path":"path/to/file","repository":"org/repo","lineMatches":[{"line":"foo bar foo","lineNumber":4,"offsetAndLengths":[[0,3],[8,3]]}]} +{"type":"content","path":"path/to/file","repository":"org/repo","chunkMatches":[{"content":"foo bar foo","contentStart":{"offset":0,"line":4,"column":0},"ranges":[{"start":{"offset":0,"line":0,"column":0},"end":{"offset":3,"line":0,"column":0}},{"start":{"offset":0,"line":0,"column":0},"end":{"offset":3,"line":0,"column":0}},{"start":{"offset":1,"line":0,"column":0},"end":{"offset":2,"line":0,"column":0}},{"start":{"offset":1,"line":0,"column":0},"end":{"offset":3,"line":0,"column":0}},{"start":{"offset":8,"line":0,"column":0},"end":{"offset":11,"line":0,"column":0}}]}]} {"type":"repo","repository":"sourcegraph/sourcegraph"} {"type":"symbol","path":"path/to/file","repository":"org/repo","symbols":[{"url":"github.com/sourcegraph/sourcegraph/-/blob/cmd/frontend/graphqlbackend/search_results.go#L1591:26-1591:35","name":"doResults","containerName":"","kind":"FUNCTION"},{"url":"github.com/sourcegraph/sourcegraph/-/blob/cmd/frontend/graphqlbackend/search_results.go#L1591:26-1591:35","name":"Results","containerName":"SearchResultsResolver","kind":"FIELD"}]} {"type":"commit","icon":"","label":"[sourcegraph/sourcegraph-atom](/github.com/sourcegraph/sourcegraph-atom) › [Stephen Gutekanst](/github.com/sourcegraph/sourcegraph-atom/-/commit/5b098d7fed963d88e23057ed99d73d3c7a33ad89): [all: release v1.0.5](/github.com/sourcegraph/sourcegraph-atom/-/commit/5b098d7fed963d88e23057ed99d73d3c7a33ad89)^","url":"","detail":"","content":"```COMMIT_EDITMSG\nfoo bar\n```","ranges":[[1,3,3]]} diff --git a/cmd/src/testdata/TestSearchStream/Text.golden b/cmd/src/testdata/TestSearchStream/Text.golden index 1cc9c8aaeb..65f18b7e66 100644 --- a/cmd/src/testdata/TestSearchStream/Text.golden +++ b/cmd/src/testdata/TestSearchStream/Text.golden @@ -1,8 +1,8 @@ -org/repo › path/to/file (2 matches) +org/repo › path/to/file (5 matches) -------------------------------------------------------------------------------- -  5 | foo bar foo - -sourcegraph/sourcegraph (http://127.0.0.1:55128/sourcegraph/sourcegraph) (1 match) +  5 | foo bar foo + ------------------------------------------------------------------------------ +sourcegraph/sourcegraph (http://127.0.0.1:55128/sourcegraph/sourcegraph) (1 match) org/repo › path/to/file (2 matches) -------------------------------------------------------------------------------- doResults(FUNCTION) (http://127.0.0.1:55128/github.com/sourcegraph/sourcegraph/-/blob/cmd/frontend/graphqlbackend/search_results.go#L1591:26-1591:35) diff --git a/internal/streaming/events.go b/internal/streaming/events.go index 22e69b7ee3..8c33040977 100644 --- a/internal/streaming/events.go +++ b/internal/streaming/events.go @@ -17,12 +17,28 @@ type EventContentMatch struct { // Type is always ContentMatchType. Included here for marshalling. Type MatchType `json:"type"` - Path string `json:"path"` - Repository string `json:"repository"` - Branches []string `json:"branches,omitempty"` - Commit string `json:"commit,omitempty"` + Path string `json:"path"` + Repository string `json:"repository"` + Branches []string `json:"branches,omitempty"` + Commit string `json:"commit,omitempty"` + ChunkMatches []ChunkMatch `json:"chunkMatches"` +} + +type ChunkMatch struct { + Content string `json:"content"` + ContentStart Location `json:"contentStart"` + Ranges []Range `json:"ranges"` +} + +type Location struct { + Offset int `json:"offset"` + Line int `json:"line"` + Column int `json:"column"` +} - LineMatches []EventLineMatch `json:"lineMatches"` +type Range struct { + Start Location `json:"start"` + End Location `json:"end"` } func (e *EventContentMatch) eventMatch() {} diff --git a/internal/streaming/search.go b/internal/streaming/search.go index b4bc3aafa9..56f4c26654 100644 --- a/internal/streaming/search.go +++ b/internal/streaming/search.go @@ -32,6 +32,13 @@ func Search(query string, opts Opts, client api.Client, decoder Decoder) error { req.URL.RawQuery = q.Encode() } + { + // Consume chunk matches for streaming search. + q := req.URL.Query() + q.Add("cm", "t") + req.URL.RawQuery = q.Encode() + } + // Send request. resp, err := client.Do(req) if err != nil { From c0cad1aa5b628f0d88330291387bc20494861178 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 2 Aug 2022 02:12:28 +0000 Subject: [PATCH 213/647] Update dependency @types/tar to v6.1.2 (#808) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- npm-distribution/package.json | 2 +- npm-distribution/yarn.lock | 25 +++++++++---------------- 2 files changed, 10 insertions(+), 17 deletions(-) diff --git a/npm-distribution/package.json b/npm-distribution/package.json index cb1c406770..636eff3b58 100644 --- a/npm-distribution/package.json +++ b/npm-distribution/package.json @@ -20,7 +20,7 @@ "tar": "^6.1.11" }, "devDependencies": { - "@types/tar": "6.1.1" + "@types/tar": "6.1.2" }, "private": false } diff --git a/npm-distribution/yarn.lock b/npm-distribution/yarn.lock index e22e5a78eb..7498cceb63 100644 --- a/npm-distribution/yarn.lock +++ b/npm-distribution/yarn.lock @@ -2,25 +2,18 @@ # yarn lockfile v1 -"@types/minipass@*": - version "3.1.2" - resolved "https://registry.yarnpkg.com/@types/minipass/-/minipass-3.1.2.tgz#e2d7f9df0698aff421dcf145b4fc05b8183b9030" - integrity sha512-foLGjgrJkUjLG/o2t2ymlZGEoBNBa/TfoUZ7oCTkOjP1T43UGBJspovJou/l3ZuHvye2ewR5cZNtp2zyWgILMA== - dependencies: - "@types/node" "*" - "@types/node@*": version "17.0.36" resolved "https://registry.yarnpkg.com/@types/node/-/node-17.0.36.tgz#c0d5f2fe76b47b63e0e0efc3d2049a9970d68794" integrity sha512-V3orv+ggDsWVHP99K3JlwtH20R7J4IhI1Kksgc+64q5VxgfRkQG8Ws3MFm/FZOKDYGy9feGFlZ70/HpCNe9QaA== -"@types/tar@6.1.1": - version "6.1.1" - resolved "https://registry.yarnpkg.com/@types/tar/-/tar-6.1.1.tgz#ab341ec1f149d7eb2a4f4ded56ff85f0d4fe7cb5" - integrity sha512-8mto3YZfVpqB1CHMaYz1TUYIQfZFbh/QbEq5Hsn6D0ilCfqRVCdalmc89B7vi3jhl9UYIk+dWDABShNfOkv5HA== +"@types/tar@6.1.2": + version "6.1.2" + resolved "https://registry.yarnpkg.com/@types/tar/-/tar-6.1.2.tgz#e60108a7d1b08cc91bf2faf1286cc08fdad48bbe" + integrity sha512-bnX3RRm70/n1WMwmevdOAeDU4YP7f5JSubgnuU+yrO+xQQjwDboJj3u2NTJI5ngCQhXihqVVAH5h5J8YpdpEvg== dependencies: - "@types/minipass" "*" "@types/node" "*" + minipass "^3.3.5" chownr@^2.0.0: version "2.0.0" @@ -34,10 +27,10 @@ fs-minipass@^2.0.0: dependencies: minipass "^3.0.0" -minipass@^3.0.0: - version "3.1.6" - resolved "https://registry.yarnpkg.com/minipass/-/minipass-3.1.6.tgz#3b8150aa688a711a1521af5e8779c1d3bb4f45ee" - integrity sha512-rty5kpw9/z8SX9dmxblFA6edItUmwJgMeYDZRrwlIVN27i8gysGbznJwUggw2V/FVqFSDdWy040ZPS811DYAqQ== +minipass@^3.0.0, minipass@^3.3.5: + version "3.3.5" + resolved "https://registry.yarnpkg.com/minipass/-/minipass-3.3.5.tgz#6da7e53a48db8a856eeb9153d85b230a2119e819" + integrity sha512-rQ/p+KfKBkeNwo04U15i+hOwoVBVmekmm/HcfTkTN2t9pbQKCMm4eN5gFeqgrrSp/kH/7BYYhTIHOxGqzbBPaA== dependencies: yallist "^4.0.0" From b400c2d72706fca2a7aaa5e43146fb398e0e53d9 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Tue, 9 Aug 2022 21:02:01 +0200 Subject: [PATCH 214/647] batches: Log error from executeBatchSpecInWorkspaces (#811) --- CHANGELOG.md | 10 +++++++++- cmd/src/batch_exec.go | 2 +- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 210e5affe6..302bdacbd6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,11 +15,19 @@ All notable changes to `src-cli` are documented in this file. ### Changed +### Fixed + +### Removed + +## 3.42.3 + +### Changed + - **IMPORTANT:** Searches using the command `src search -stream` is updated to use a **new and better search result schema**, improving highlighting and accurate result counts for multiline matches. Please see the new JSON schema for results if you use the `src search -stream -json` output: [#807](https://github.com/sourcegraph/src-cli/pull/807) ### Fixed -### Removed +- INTERNAL ONLY: Fixed src batch exec not logging errors. ## 3.42.2 diff --git a/cmd/src/batch_exec.go b/cmd/src/batch_exec.go index c8e0f0ead2..da58dc3ed8 100644 --- a/cmd/src/batch_exec.go +++ b/cmd/src/batch_exec.go @@ -98,7 +98,7 @@ Examples: err := executeBatchSpecInWorkspaces(ctx, flags) if err != nil { - return cmderrors.ExitCode(1, nil) + return cmderrors.ExitCode(1, err) } return nil From da6bd594c84b32b134a4b709bcae32bd881a2b59 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Tue, 9 Aug 2022 21:33:49 +0200 Subject: [PATCH 215/647] Run go mod tidy (#812) --- go.mod | 2 +- go.sum | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/go.mod b/go.mod index 8104a6b9ff..81576aefa0 100644 --- a/go.mod +++ b/go.mod @@ -11,6 +11,7 @@ require ( github.com/gobwas/glob v0.2.3 github.com/google/go-cmp v0.5.7 github.com/grafana/regexp v0.0.0-20220202152701-6a046c4caf32 + github.com/hexops/autogold v1.3.0 github.com/jig/teereadcloser v0.0.0-20181016160506-953720c48e05 github.com/json-iterator/go v1.1.12 github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 @@ -54,7 +55,6 @@ require ( github.com/golang/protobuf v1.5.2 // indirect github.com/google/uuid v1.3.0 // indirect github.com/gorilla/css v1.0.0 // indirect - github.com/hexops/autogold v1.3.0 // indirect github.com/hexops/gotextdiff v1.0.3 // indirect github.com/hexops/valast v1.4.1 // indirect github.com/huandu/xstrings v1.0.0 // indirect diff --git a/go.sum b/go.sum index 5c14b50bd6..97063e427a 100644 --- a/go.sum +++ b/go.sum @@ -94,6 +94,7 @@ github.com/fatih/color v1.13.0 h1:8LOYc1KYPPmyKMuN8QV2DNRWNbLo6LZ0iLs8+mlH53w= github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M= github.com/flosch/pongo2 v0.0.0-20190707114632-bbf5a6c351f4/go.mod h1:T9YF2M40nIgbVgp3rreNmTged+9HrbNTIQf1PsaIiTA= +github.com/frankban/quicktest v1.14.0 h1:+cqqvzZV87b4adx/5ayVOaYZ2CrvM4ejQvUdBzPPUss= github.com/frankban/quicktest v1.14.0/go.mod h1:NeW+ay9A/U67EYXNFA1nPE8e/tnQv/09mUdL/ijj8og= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= From b86c3972baecc6ea53f7a35777af3a7c794d57cb Mon Sep 17 00:00:00 2001 From: Adam Harvey Date: Wed, 10 Aug 2022 08:36:24 -0700 Subject: [PATCH 216/647] batches: fix Docker Desktop for Linux handling (#813) If the default temporary directory is in use _and_ Docker Desktop for Linux is the default Docker context, this changes the temporary directory to be one under `~/.cache/sourcegraph/batch-tmp` instead. Fixes #754. --- CHANGELOG.md | 2 + cmd/src/batch_common.go | 22 +++++++++++ internal/batches/docker/info.go | 25 +++++++++++++ internal/batches/docker/info_test.go | 56 ++++++++++++++++++++++++++++ 4 files changed, 105 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 302bdacbd6..a13e66d9bd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,8 @@ All notable changes to `src-cli` are documented in this file. ### Fixed +- The default directory used to mount files into containers will be automatically changed to a temporary directory within `$HOME` if Docker Desktop for Linux is in use. [#754](https://github.com/sourcegraph/src-cli/issues/754) + ### Removed ## 3.42.3 diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index 91554c7850..58cf4a039a 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -296,6 +296,28 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp return err } + // On Linux only, we also need to figure out if we need to override the + // temporary directory — Docker Desktop restricts file mounts to /home only + // by default. + // + // We could interrogate ~/.docker/desktop/settings.json for extra bonus + // points here, but that feels like overkill. Basically, if it's + // desktop-linux, we'll just assume the user has the default /home mount + // available and go from there. + if runtime.GOOS == "linux" && opts.flags.tempDir == batchDefaultTempDirPrefix() { + context, err := docker.CurrentContext(ctx) + if err != nil { + return err + } + + if context == "desktop-linux" { + opts.flags.tempDir = path.Join(path.Dir(opts.flags.cacheDir), "batch-tmp") + + // Ensure the directory exists and is writable. + os.MkdirAll(opts.flags.tempDir, os.ModePerm) + } + } + // Parse flags and build up our service and executor options. ui.ParsingBatchSpec() batchSpec, rawSpec, err := parseBatchSpec(ctx, opts.file, svc, false) diff --git a/internal/batches/docker/info.go b/internal/batches/docker/info.go index 346163badf..a96397c943 100644 --- a/internal/batches/docker/info.go +++ b/internal/batches/docker/info.go @@ -10,6 +10,31 @@ import ( "github.com/sourcegraph/src-cli/internal/exec" ) +// CurrentContext returns the name of the current Docker context (not to be +// confused with a Go context). +func CurrentContext(ctx context.Context) (string, error) { + dctx, cancel, err := withFastCommandContext(ctx) + if err != nil { + return "", err + } + defer cancel() + + args := []string{"context", "inspect", "--format", "{{ .Name }}"} + out, err := exec.CommandContext(dctx, "docker", args...).CombinedOutput() + if errors.IsDeadlineExceeded(err) || errors.IsDeadlineExceeded(dctx.Err()) { + return "", newFastCommandTimeoutError(dctx, args...) + } else if err != nil { + return "", err + } + + name := string(bytes.TrimSpace(out)) + if name == "" { + return "", errors.New("no context returned from Docker") + } + + return name, nil +} + // NCPU returns the number of CPU cores available to Docker. func NCPU(ctx context.Context) (int, error) { dctx, cancel, err := withFastCommandContext(ctx) diff --git a/internal/batches/docker/info_test.go b/internal/batches/docker/info_test.go index ebc07e89ca..76db6ae91d 100644 --- a/internal/batches/docker/info_test.go +++ b/internal/batches/docker/info_test.go @@ -11,6 +11,62 @@ import ( "github.com/sourcegraph/src-cli/internal/exec/expect" ) +func Test_CurrentContext(t *testing.T) { + ctx := context.Background() + + t.Run("docker fails", func(t *testing.T) { + expect.Commands(t, contextInspectFailure()) + + name, err := CurrentContext(ctx) + assert.Empty(t, name) + assert.Error(t, err) + }) + + t.Run("docker times out", func(t *testing.T) { + tctx, cancel := context.WithTimeout(ctx, -1*time.Second) + t.Cleanup(cancel) + + expect.Commands(t, contextInspectSuccess("desktop-linux")) + + name, err := CurrentContext(tctx) + assert.Zero(t, name) + var terr *fastCommandTimeoutError + assert.ErrorAs(t, err, &terr) + assert.Equal(t, []string{"context", "inspect", "--format", "{{ .Name }}"}, terr.args) + assert.Equal(t, fastCommandTimeoutDefault, terr.timeout) + }) + + t.Run("docker succeeds, but returns nothing", func(t *testing.T) { + expect.Commands(t, contextInspectSuccess("")) + + name, err := CurrentContext(ctx) + assert.Empty(t, name) + assert.Error(t, err) + }) + + t.Run("docker succeeds", func(t *testing.T) { + expect.Commands(t, contextInspectSuccess("desktop-linux")) + + name, err := CurrentContext(ctx) + assert.Equal(t, "desktop-linux", name) + assert.NoError(t, err) + }) +} + +func contextInspectSuccess(ncpu string) *expect.Expectation { + return expect.NewLiteral( + expect.Behaviour{Stdout: []byte(fmt.Sprintf("%s\n", ncpu))}, + "docker", "context", "inspect", "--format", "{{ .Name }}", + ) +} + +func contextInspectFailure() *expect.Expectation { + return expect.NewLiteral( + expect.Behaviour{ExitCode: 1}, + "docker", "context", "inspect", "--format", "{{ .Name }}", + ) +} + func Test_NCPU(t *testing.T) { ctx := context.Background() From abd00f53f073765f6adfee4f624861813fc34013 Mon Sep 17 00:00:00 2001 From: leo Date: Mon, 15 Aug 2022 11:38:15 -0400 Subject: [PATCH 217/647] orgs: update `create` mutation (#815) --- cmd/src/orgs_create.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cmd/src/orgs_create.go b/cmd/src/orgs_create.go index a79d66c5d2..4afd49dabf 100644 --- a/cmd/src/orgs_create.go +++ b/cmd/src/orgs_create.go @@ -26,7 +26,7 @@ Examples: } var ( nameFlag = flagSet.String("name", "", `The new organization's name. (required)`) - displayNameFlag = flagSet.String("display-name", "", `The new organization's display name.`) + displayNameFlag = flagSet.String("display-name", "", `The new organization's display name. Defaults to organization name if unspecified.`) apiFlags = api.NewFlags(flagSet) ) @@ -41,7 +41,7 @@ Examples: $name: String!, $displayName: String!, ) { - createOrg( + createOrganization( name: $name, displayName: $displayName, ) { From d0a443beb1739826f3543d03c06498e6e0d1b276 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Mon, 15 Aug 2022 23:52:23 +0200 Subject: [PATCH 218/647] batches: Make sure no corrupted repozips are used (#817) When the download of a zip was aborted, it could've left behind a corrupted archive zip. This fixes it by first storing it to a temporary location and then creating the actual file atomically by doing os.Rename. --- internal/batches/repozip/fetcher.go | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/internal/batches/repozip/fetcher.go b/internal/batches/repozip/fetcher.go index dff57bad00..8146bcf07b 100644 --- a/internal/batches/repozip/fetcher.go +++ b/internal/batches/repozip/fetcher.go @@ -336,15 +336,27 @@ func fetchRepositoryFile(ctx context.Context, client HTTPClient, repo RepoRevisi return false, fmt.Errorf("unable to fetch archive (HTTP %d from %s)", resp.StatusCode, req.URL.String()) } - f, err := os.Create(dest) + f, err := os.CreateTemp(filepath.Dir(dest), fmt.Sprintf("%s-*.tmp", filepath.Base(dest))) if err != nil { return false, err } - defer f.Close() + // Make sure we clean up the temp file in case something fails. + defer func(path string) { _ = os.Remove(path) }(f.Name()) if _, err := io.Copy(f, resp.Body); err != nil { + // Be a good citizen, attempt to close the file. + _ = f.Close() return false, err } + if err := f.Close(); err != nil { + return false, errors.Wrap(err, "closing temp file") + } + + // Atomically create the actual file, so that there are no artifacts left behind + // when this process is aborted, network errors occur, or some witchcraft goes on. + if err := os.Rename(f.Name(), dest); err != nil { + return false, errors.Wrap(err, "renaming temp file") + } return true, nil } From 7430f1deff82dc27c530ec118abcf54725f34f60 Mon Sep 17 00:00:00 2001 From: Keegan Carruthers-Smith Date: Tue, 16 Aug 2022 08:26:25 +0100 Subject: [PATCH 219/647] gomod: update grafana/regexp (#814) The commit seemed to have gone out of sync with upstream. Ran go get github.com/grafana/regexp@speedup Test Plan: CI --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 81576aefa0..0b9651c397 100644 --- a/go.mod +++ b/go.mod @@ -10,7 +10,7 @@ require ( github.com/dustin/go-humanize v1.0.0 github.com/gobwas/glob v0.2.3 github.com/google/go-cmp v0.5.7 - github.com/grafana/regexp v0.0.0-20220202152701-6a046c4caf32 + github.com/grafana/regexp v0.0.0-20220304100321-149c8afcd6cb github.com/hexops/autogold v1.3.0 github.com/jig/teereadcloser v0.0.0-20181016160506-953720c48e05 github.com/json-iterator/go v1.1.12 diff --git a/go.sum b/go.sum index 97063e427a..0ce580ade2 100644 --- a/go.sum +++ b/go.sum @@ -168,8 +168,8 @@ github.com/gorilla/css v1.0.0 h1:BQqNyPTi50JCFMTw/b67hByjMVXZRwGha6wxVGkeihY= github.com/gorilla/css v1.0.0/go.mod h1:Dn721qIggHpt4+EFCcTLTU/vk5ySda2ReITrtgBl60c= github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= -github.com/grafana/regexp v0.0.0-20220202152701-6a046c4caf32 h1:M3wP8Hwic62qJsiydSgXtev03d4f92uN1I52nVjRgw0= -github.com/grafana/regexp v0.0.0-20220202152701-6a046c4caf32/go.mod h1:M5qHK+eWfAv8VR/265dIuEpL3fNfeC21tXXp9itM24A= +github.com/grafana/regexp v0.0.0-20220304100321-149c8afcd6cb h1:wwzNkyaQwcXCzQuKoWz3lwngetmcyg+EhW0fF5lz73M= +github.com/grafana/regexp v0.0.0-20220304100321-149c8afcd6cb/go.mod h1:M5qHK+eWfAv8VR/265dIuEpL3fNfeC21tXXp9itM24A= github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= github.com/hashicorp/go-version v1.2.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= From ff9a8d7b706c19d768297edfc8fe44b7b5a572f6 Mon Sep 17 00:00:00 2001 From: Varun Gandhi Date: Tue, 16 Aug 2022 18:41:34 +0800 Subject: [PATCH 220/647] chore: Bump scip dependency for bug fixes. (#820) --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 0b9651c397..9043eea507 100644 --- a/go.mod +++ b/go.mod @@ -20,7 +20,7 @@ require ( github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf - github.com/sourcegraph/scip v0.1.0 + github.com/sourcegraph/scip v0.2.0 github.com/sourcegraph/sourcegraph/lib v0.0.0-20220715132627-cb906941e8b4 github.com/stretchr/testify v1.7.2 golang.org/x/net v0.0.0-20220526153639-5463443f8c37 diff --git a/go.sum b/go.sum index 0ce580ade2..596578d5cf 100644 --- a/go.sum +++ b/go.sum @@ -368,8 +368,8 @@ github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWii github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= github.com/sourcegraph/log v0.0.0-20220707160925-6a936691c838 h1:8wknDSCUVYbaRT63OD+Iyv+stwze5kE2FAzbA1HrNMA= github.com/sourcegraph/log v0.0.0-20220707160925-6a936691c838/go.mod h1:zWEPlKrWBUVpko/tOgDS+qrp7BmzaCcmUrh9+ver1iQ= -github.com/sourcegraph/scip v0.1.0 h1:kTs0CJaLQvcRZjg+HpGrcJPNX2Tx31+d6szWio3ZOkQ= -github.com/sourcegraph/scip v0.1.0/go.mod h1:/AZ8RvsnRfeCZy232PJuVZqcl9f82fJnYwdWZeU2JCo= +github.com/sourcegraph/scip v0.2.0 h1:Z9rR9TNONtRhqcpm0JP/yEBUy0fBKaSVbWIZKih5v04= +github.com/sourcegraph/scip v0.2.0/go.mod h1:EYyT39nXdZDNVmgbJAlyIVWbEb1txnAOKpJPSYpvgXk= github.com/sourcegraph/sourcegraph/lib v0.0.0-20220715132627-cb906941e8b4 h1:x+66tdk/r6k/t4gxs1g7WE9oY1CA35gHDAGHb0Sa6HI= github.com/sourcegraph/sourcegraph/lib v0.0.0-20220715132627-cb906941e8b4/go.mod h1:NOllMVD9zFtTsYX/v/M9/zTIGtzOu3uhlWe2XN2N+hE= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= From 854b9c96628edf642ac703805153f29fbf5058c1 Mon Sep 17 00:00:00 2001 From: Noah S-C Date: Tue, 16 Aug 2022 04:37:09 -0700 Subject: [PATCH 221/647] bump sourcegraph/sourcegraph/lib (#821) --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 9043eea507..fa2c21900a 100644 --- a/go.mod +++ b/go.mod @@ -21,7 +21,7 @@ require ( github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf github.com/sourcegraph/scip v0.2.0 - github.com/sourcegraph/sourcegraph/lib v0.0.0-20220715132627-cb906941e8b4 + github.com/sourcegraph/sourcegraph/lib v0.0.0-20220816103048-5fb36f9b800c github.com/stretchr/testify v1.7.2 golang.org/x/net v0.0.0-20220526153639-5463443f8c37 golang.org/x/sync v0.0.0-20210220032951-036812b2e83c diff --git a/go.sum b/go.sum index 596578d5cf..4b56d5fbef 100644 --- a/go.sum +++ b/go.sum @@ -370,8 +370,8 @@ github.com/sourcegraph/log v0.0.0-20220707160925-6a936691c838 h1:8wknDSCUVYbaRT6 github.com/sourcegraph/log v0.0.0-20220707160925-6a936691c838/go.mod h1:zWEPlKrWBUVpko/tOgDS+qrp7BmzaCcmUrh9+ver1iQ= github.com/sourcegraph/scip v0.2.0 h1:Z9rR9TNONtRhqcpm0JP/yEBUy0fBKaSVbWIZKih5v04= github.com/sourcegraph/scip v0.2.0/go.mod h1:EYyT39nXdZDNVmgbJAlyIVWbEb1txnAOKpJPSYpvgXk= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20220715132627-cb906941e8b4 h1:x+66tdk/r6k/t4gxs1g7WE9oY1CA35gHDAGHb0Sa6HI= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20220715132627-cb906941e8b4/go.mod h1:NOllMVD9zFtTsYX/v/M9/zTIGtzOu3uhlWe2XN2N+hE= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20220816103048-5fb36f9b800c h1:KmI6ZEtlP8P4h59rn6s0SSbwkX8Yg7dQBtadOLPYCrc= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20220816103048-5fb36f9b800c/go.mod h1:9wnFUNfpORLAOJn4XAO7ZeWnYkf6/CxlWaTU1vlpuKc= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= From 1aeca049ce11a8500411ca8f464f58bb8c0b7eb3 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Tue, 16 Aug 2022 13:59:21 +0200 Subject: [PATCH 222/647] Prepare changelog for 3.43.0 (#818) --- CHANGELOG.md | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a13e66d9bd..a1ea649adc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,10 +17,19 @@ All notable changes to `src-cli` are documented in this file. ### Fixed -- The default directory used to mount files into containers will be automatically changed to a temporary directory within `$HOME` if Docker Desktop for Linux is in use. [#754](https://github.com/sourcegraph/src-cli/issues/754) - ### Removed +## 3.43.0 + +### Changed + +- `src code-intel upload` now includes an additional header for efficiently tracking the uncompressed size of uploads in the backend. [#39690](https://github.com/sourcegraph/sourcegraph/pull/39690) + +### Fixed + +- The default directory used to mount files into containers will be automatically changed to a temporary directory within `$HOME` if Docker Desktop for Linux is in use. [#754](https://github.com/sourcegraph/src-cli/issues/754) +- src-cli no longer leaves corrupted repo archives behind when interrupted during batch spec execution. [#817](https://github.com/sourcegraph/src-cli/pull/817) + ## 3.42.3 ### Changed From fc87b62c596d6999501f241f3c2c3a818a95b61c Mon Sep 17 00:00:00 2001 From: Varun Gandhi Date: Wed, 17 Aug 2022 17:51:25 +0800 Subject: [PATCH 223/647] docs: Link to usage docs, de-emphasize deprecated command. (#824) --- README.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.markdown b/README.markdown index f26bf9b1ee..c56d24266b 100644 --- a/README.markdown +++ b/README.markdown @@ -111,12 +111,12 @@ Is your Sourcegraph instance behind a custom auth proxy? See [auth proxy configu - `src config` - manage global, org, and user settings - `src extsvc` - manage external services (repository configuration) - `src extensions` - manage extensions - - `src code-intel` - manages Code Intelligence data - - `src lsif` - manages LSIF data (DEPRECATED: use `src code-intel` instead) + - `src code-intel` - manages Code Intelligence data (deprecated alias: `src lsif`) - `src serve-git` - serves your local git repositories over HTTP for Sourcegraph to pull - `src version` - check version and guaranteed-compatible version for your Sourcegraph instance Run `src -h` and `src -h` for more detailed usage information. +You can also read the [usage docs for the latest version of `src-cli`](https://docs.sourcegraph.com/cli/references) online. #### Optional: Renaming `src` From 01648778fd58e6ba497f0c9668f48a69dcb44d25 Mon Sep 17 00:00:00 2001 From: Philipp Spiess Date: Wed, 17 Aug 2022 15:21:48 +0200 Subject: [PATCH 224/647] Prepare CLI for extension sunsetting (#825) --- cmd/src/extensions.go | 3 ++- cmd/src/extensions_list.go | 6 ++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/cmd/src/extensions.go b/cmd/src/extensions.go index 9f2aebbe4c..9c33ab3bc2 100644 --- a/cmd/src/extensions.go +++ b/cmd/src/extensions.go @@ -10,7 +10,8 @@ var extensionsCommands commander func init() { usage := `'src extensions' is a tool that manages extensions in the extension registry on a Sourcegraph instance. -EXPERIMENTAL: Extensions are experimental functionality on Sourcegraph and in the 'src' tool. +DEPRECATED: We're in the process of removing Sourcegraph extensions with our September release. + Learn more: https://docs.sourcegraph.com/extensions/deprecation Usage: diff --git a/cmd/src/extensions_list.go b/cmd/src/extensions_list.go index 291253278a..6aa5bead6c 100644 --- a/cmd/src/extensions_list.go +++ b/cmd/src/extensions_list.go @@ -63,6 +63,7 @@ Examples: nodes { ...RegistryExtensionFields } + error } } }` + registryExtensionFragment @@ -71,6 +72,7 @@ Examples: ExtensionRegistry struct { Extensions struct { Nodes []Extension + Error string } } } @@ -81,6 +83,10 @@ Examples: return err } + if result.ExtensionRegistry.Extensions.Error != "" { + return fmt.Errorf("%s", result.ExtensionRegistry.Extensions.Error) + } + for _, extension := range result.ExtensionRegistry.Extensions.Nodes { if err := execTemplate(tmpl, extension); err != nil { return err From e6e03e850770dd0ba745f0fa4b23127e9d72ad30 Mon Sep 17 00:00:00 2001 From: Adam Harvey Date: Thu, 18 Aug 2022 14:54:26 -0700 Subject: [PATCH 225/647] Update release process until 4.0 stable is released. (#827) --- .goreleaser.yml | 3 ++- DEVELOPMENT.md | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/.goreleaser.yml b/.goreleaser.yml index 4db476ce7d..8d975be529 100644 --- a/.goreleaser.yml +++ b/.goreleaser.yml @@ -50,7 +50,8 @@ dockers: - "sourcegraph/src-cli:{{ .Tag }}" - "sourcegraph/src-cli:{{ .Major }}" - "sourcegraph/src-cli:{{ .Major }}.{{ .Minor }}" - - "sourcegraph/src-cli:latest" + # Disabled until 4.0 stable is released. + #- "sourcegraph/src-cli:latest" changelog: sort: asc filters: diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index ca256d7288..3f45f144a7 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -1,5 +1,23 @@ This file covers things that are good to know if you're developing or maintaining `src`. It is likely incomplete, and contributions would be most welcome! +## Things are a bit weird right now, August-September 2022 edition + +With 3.43 having been released, we now want to remove a bunch of old backward compatibility code before 4.0 is released in late September. However, we also need to be able to fix bugs and make 3.43.x releases in the interim. + +**Until 4.0 is released, `main` is the 4.0 branch.** + +### Releasing a 3.43.x bug fix + +You must merge the fix into **both** the `3.43` and `main` branches. Then [perform the release normally](#releasing), except note that you **must** be on the `3.43` branch when you run `./release.sh`. + +### Releasing a 4.0 pre-release + +[Perform the release normally](#releasing), but be careful to use a version number that is clearly a pre-release, specifically in the format `4.0.0-rc.X`, where `X` is one higher than the previous pre-release. + +### Releasing 4.0 proper + +If you're reading this because you're about to release the stable 4.0.0 release, please merge #828 first to put the release machinery back the way it was. + ## Contents * [Developing `src`](#development) From 8a75c6f8b4cbe2a2f3c8be0f2c50bc766499f498 Mon Sep 17 00:00:00 2001 From: Adam Harvey Date: Thu, 18 Aug 2022 15:09:43 -0700 Subject: [PATCH 226/647] release.sh: allow -rc.X suffixes (#829) --- release.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/release.sh b/release.sh index aa0d4f9706..b868493d40 100755 --- a/release.sh +++ b/release.sh @@ -12,7 +12,7 @@ case "$REPLY" in ;; esac -if ! echo "$VERSION" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+$'; then +if ! echo "$VERSION" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+(-rc\.[0-9]+)?$'; then echo "\$VERSION is not in MAJOR.MINOR.PATCH format" exit 1 fi From 8c0658fe12627f8a5b689743acdb6f0650bf55fd Mon Sep 17 00:00:00 2001 From: Adam Harvey Date: Thu, 18 Aug 2022 15:23:12 -0700 Subject: [PATCH 227/647] goreleaser: force releases to be marked as pre-release (#830) Whatever version string sniffing goreleaser is doing isn't firing, so let's just force it. I'll add a revert to #828 for this as well. --- .goreleaser.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.goreleaser.yml b/.goreleaser.yml index 8d975be529..0b6800ddaa 100644 --- a/.goreleaser.yml +++ b/.goreleaser.yml @@ -58,3 +58,5 @@ changelog: exclude: - '^docs:' - '^test:' +release: + prerelease: true From 8afc4657dccba6a93680f13d4f904b7575327a4b Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Wed, 24 Aug 2022 15:56:21 +0200 Subject: [PATCH 228/647] Remove src-cli workspace resolution (#819) This is available as a faster API from the backend now, so no need to keep this duplicative, slower code. This is a 4.0 deprecation execution. --- cmd/src/batch_common.go | 49 +- cmd/src/batch_repositories.go | 59 +-- go.mod | 12 +- go.sum | 22 +- internal/batches/features.go | 22 +- internal/batches/service/build_tasks.go | 7 + internal/batches/service/main_test.go | 13 - internal/batches/service/service.go | 361 --------------- internal/batches/service/service_test.go | 482 -------------------- internal/batches/service/workspaces.go | 214 --------- internal/batches/service/workspaces_test.go | 345 -------------- internal/batches/ui/exec_ui.go | 5 +- internal/batches/ui/json_lines.go | 20 +- internal/batches/ui/tui.go | 20 +- 14 files changed, 83 insertions(+), 1548 deletions(-) delete mode 100644 internal/batches/service/main_test.go delete mode 100644 internal/batches/service/workspaces.go delete mode 100644 internal/batches/service/workspaces_test.go diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index 58cf4a039a..cbd58b4e72 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -370,49 +370,18 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp ui.DeterminingWorkspaceCreatorTypeSuccess(typ) } - var ( - repos []*graphql.Repository - workspaces []service.RepoWorkspace - ) - if svc.Features().ServerSideWorkspaceResolution { - ui.ResolvingRepositories() - var err error - workspaces, repos, err = svc.ResolveWorkspacesForBatchSpec(ctx, batchSpec, opts.flags.allowUnsupported, opts.flags.allowIgnored) - if err != nil { - if repoSet, ok := err.(batches.UnsupportedRepoSet); ok { - ui.ResolvingRepositoriesDone(repos, repoSet, nil) - } else if repoSet, ok := err.(batches.IgnoredRepoSet); ok { - ui.ResolvingRepositoriesDone(repos, nil, repoSet) - } else { - return errors.Wrap(err, "resolving repositories server-side") - } + ui.DeterminingWorkspaces() + workspaces, repos, err := svc.ResolveWorkspacesForBatchSpec(ctx, batchSpec, opts.flags.allowUnsupported, opts.flags.allowIgnored) + if err != nil { + if repoSet, ok := err.(batches.UnsupportedRepoSet); ok { + ui.DeterminingWorkspacesSuccess(len(workspaces), len(repos), repoSet, nil) + } else if repoSet, ok := err.(batches.IgnoredRepoSet); ok { + ui.DeterminingWorkspacesSuccess(len(workspaces), len(repos), nil, repoSet) } else { - ui.ResolvingRepositoriesDone(repos, nil, nil) + return errors.Wrap(err, "resolving repositories") } - - ui.DeterminingWorkspaces() - ui.DeterminingWorkspacesSuccess(len(workspaces)) } else { - ui.ResolvingRepositories() - repos, err = svc.ResolveRepositories(ctx, batchSpec, opts.flags.allowUnsupported, opts.flags.allowIgnored) - if err != nil { - if repoSet, ok := err.(batches.UnsupportedRepoSet); ok { - ui.ResolvingRepositoriesDone(repos, repoSet, nil) - } else if repoSet, ok := err.(batches.IgnoredRepoSet); ok { - ui.ResolvingRepositoriesDone(repos, nil, repoSet) - } else { - return errors.Wrap(err, "resolving repositories") - } - } else { - ui.ResolvingRepositoriesDone(repos, nil, nil) - } - - ui.DeterminingWorkspaces() - workspaces, err = svc.DetermineWorkspaces(ctx, repos, batchSpec) - if err != nil { - return err - } - ui.DeterminingWorkspacesSuccess(len(workspaces)) + ui.DeterminingWorkspacesSuccess(len(workspaces), len(repos), nil, nil) } archiveRegistry := repozip.NewArchiveRegistry(opts.client, opts.flags.cacheDir, opts.flags.cleanArchives) diff --git a/cmd/src/batch_repositories.go b/cmd/src/batch_repositories.go index 02d8979cee..3d92b578bb 100644 --- a/cmd/src/batch_repositories.go +++ b/cmd/src/batch_repositories.go @@ -9,6 +9,7 @@ import ( "github.com/sourcegraph/sourcegraph/lib/output" "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/graphql" "github.com/sourcegraph/src-cli/internal/batches/service" "github.com/sourcegraph/src-cli/internal/batches/ui" @@ -90,31 +91,34 @@ Examples: return err } - repoCount := 0 - for _, on := range spec.On { - repos, _, err := svc.ResolveRepositoriesOn(ctx, &on) - if err != nil { - return errors.Wrapf(err, "Resolving %q", on.String()) + _, repos, err := svc.ResolveWorkspacesForBatchSpec(ctx, spec, allowUnsupported, allowIgnored) + if err != nil { + if _, ok := err.(batches.UnsupportedRepoSet); ok { + // This is fine, we just ignore those in the output. + } else if _, ok := err.(batches.IgnoredRepoSet); ok { + // This is fine, we just ignore those in the output. + } else { + return errors.Wrap(err, "resolving repositories") } + } - max := 0 - for _, repo := range repos { - if len(repo.Name) > max { - max = len(repo.Name) - } - - repoCount++ + repoCount := 0 + max := 0 + for _, repo := range repos { + if len(repo.Name) > max { + max = len(repo.Name) } - if err := execTemplate(queryTmpl, batchRepositoryTemplateInput{ - Max: max, - Query: on.String(), - RepoCount: len(repos), - Repos: repos, - SourcegraphEndpoint: cfg.Endpoint, - }); err != nil { - return err - } + repoCount++ + } + + if err := execTemplate(queryTmpl, batchRepositoryTemplateInput{ + Max: max, + RepoCount: len(repos), + Repos: repos, + SourcegraphEndpoint: cfg.Endpoint, + }); err != nil { + return err } return execTemplate(totalTmpl, batchRepositoryTemplateInput{ @@ -135,19 +139,6 @@ Examples: } const batchRepositoriesTemplate = ` -{{- color "logo" -}}✱{{- color "nc" -}} -{{- " " -}} -{{- if eq .RepoCount 0 -}} - {{- color "warning" -}} -{{- else -}} - {{- color "success" -}} -{{- end -}} -{{- .RepoCount }} workspace{{ if ne .RepoCount 1 }}s{{ end }}{{- color "nc" -}} -{{- if ne (len .Query) 0 -}} - {{- " for " -}}{{- color "search-query"}}"{{.Query}}"{{ color "nc" -}} -{{- end -}} -{{- "\n" -}} - {{- range .Repos -}} {{- " "}}{{ color "success" }}{{ padRight .Name $.Max " " }}{{ color "nc" -}} {{- if ne (len .Branch.Name) 0 -}}{{ " " }}{{- color "search-branch" -}}{{- .Branch.Name -}}{{ color "nc" -}}{{- end -}} diff --git a/go.mod b/go.mod index fa2c21900a..9d37a66f31 100644 --- a/go.mod +++ b/go.mod @@ -21,10 +21,10 @@ require ( github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf github.com/sourcegraph/scip v0.2.0 - github.com/sourcegraph/sourcegraph/lib v0.0.0-20220816103048-5fb36f9b800c + github.com/sourcegraph/sourcegraph/lib v0.0.0-20220822143138-d621aac70d3d github.com/stretchr/testify v1.7.2 - golang.org/x/net v0.0.0-20220526153639-5463443f8c37 - golang.org/x/sync v0.0.0-20210220032951-036812b2e83c + golang.org/x/net v0.0.0-20220722155237-a158d28d115b + golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4 google.golang.org/protobuf v1.28.0 gopkg.in/yaml.v3 v3.0.1 jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7 @@ -95,7 +95,7 @@ require ( github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect github.com/xeipuuv/gojsonschema v1.2.0 // indirect - github.com/yuin/goldmark v1.4.4 // indirect + github.com/yuin/goldmark v1.4.13 // indirect github.com/yuin/goldmark-emoji v1.0.1 // indirect go.opencensus.io v0.23.0 // indirect go.uber.org/atomic v1.9.0 // indirect @@ -103,10 +103,10 @@ require ( go.uber.org/zap v1.21.0 // indirect golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 // indirect golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 // indirect - golang.org/x/sys v0.0.0-20220712014510-0a85c31ab51e // indirect + golang.org/x/sys v0.0.0-20220818161305-2296e01440c6 // indirect golang.org/x/term v0.0.0-20220411215600-e5f449aeb171 // indirect golang.org/x/text v0.3.7 // indirect - golang.org/x/tools v0.1.11 // indirect + golang.org/x/tools v0.1.12 // indirect golang.org/x/xerrors v0.0.0-20220609144429-65e65417b02f // indirect google.golang.org/genproto v0.0.0-20220414192740-2d67ff6cf2b4 // indirect google.golang.org/grpc v1.45.0 // indirect diff --git a/go.sum b/go.sum index 4b56d5fbef..fe55304b2e 100644 --- a/go.sum +++ b/go.sum @@ -370,8 +370,8 @@ github.com/sourcegraph/log v0.0.0-20220707160925-6a936691c838 h1:8wknDSCUVYbaRT6 github.com/sourcegraph/log v0.0.0-20220707160925-6a936691c838/go.mod h1:zWEPlKrWBUVpko/tOgDS+qrp7BmzaCcmUrh9+ver1iQ= github.com/sourcegraph/scip v0.2.0 h1:Z9rR9TNONtRhqcpm0JP/yEBUy0fBKaSVbWIZKih5v04= github.com/sourcegraph/scip v0.2.0/go.mod h1:EYyT39nXdZDNVmgbJAlyIVWbEb1txnAOKpJPSYpvgXk= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20220816103048-5fb36f9b800c h1:KmI6ZEtlP8P4h59rn6s0SSbwkX8Yg7dQBtadOLPYCrc= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20220816103048-5fb36f9b800c/go.mod h1:9wnFUNfpORLAOJn4XAO7ZeWnYkf6/CxlWaTU1vlpuKc= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20220822143138-d621aac70d3d h1:bUaXAbtXSWbcv8LjDwwYXo0grERhlOJDn2T8ROe/Mmc= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20220822143138-d621aac70d3d/go.mod h1:9wnFUNfpORLAOJn4XAO7ZeWnYkf6/CxlWaTU1vlpuKc= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= @@ -421,8 +421,9 @@ github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9de github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= -github.com/yuin/goldmark v1.4.4 h1:zNWRjYUW32G9KirMXYHQHVNFkXvMI7LpgNW2AgYAoIs= github.com/yuin/goldmark v1.4.4/go.mod h1:rmuwmfZ0+bvzB24eSC//bk1R1Zp3hM0OXYv/G2LIilg= +github.com/yuin/goldmark v1.4.13 h1:fVcFKWvrslecOb/tg+Cc05dkeYx540o0FuFt3nUVDoE= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= github.com/yuin/goldmark-emoji v1.0.1 h1:ctuWEyzGBwiucEqxzwe0SOYDXPAucOrE9NQC18Wa1os= github.com/yuin/goldmark-emoji v1.0.1/go.mod h1:2w1E6FEWLcDQkoTE+7HU6QF1F6SLlNGjRIBbIZQFqkQ= go.opencensus.io v0.23.0 h1:gqCw0LfLxScz8irSi8exQc7fyQ0fKQU/qnC/X8+V/1M= @@ -486,8 +487,8 @@ golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96b golang.org/x/net v0.0.0-20210614182718-04defd469f4e/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211008194852-3b03d305991f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/net v0.0.0-20220526153639-5463443f8c37 h1:lUkvobShwKsOesNfWWlCS5q7fnbG1MEliIzwu886fn8= -golang.org/x/net v0.0.0-20220526153639-5463443f8c37/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b h1:PxfKdU9lEEDYjdIzOtC4qFWgkU2rGHdKlKowJSMN9h0= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -497,8 +498,9 @@ golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20210220032951-036812b2e83c h1:5KslGYwFpkhGh+Q16bwMP3cOontH8FOep7tGV86Y7SQ= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4 h1:uVc8UZUe6tr40fFVnUP5Oj+veunVezqYl9z7DYw9xzw= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -533,8 +535,8 @@ golang.org/x/sys v0.0.0-20211102192858-4dd72447c267/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20211117180635-dee7805ff2e1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211213223007-03aa0b5f6827/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220712014510-0a85c31ab51e h1:NHvCuwuS43lGnYhten69ZWqi2QOj/CiDNcKbVqwVoew= -golang.org/x/sys v0.0.0-20220712014510-0a85c31ab51e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220818161305-2296e01440c6 h1:Sx/u41w+OwrInGdEckYmEuU5gHoGSL4QbDz3S9s6j4U= +golang.org/x/sys v0.0.0-20220818161305-2296e01440c6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20220411215600-e5f449aeb171 h1:EH1Deb8WZJ0xc0WK//leUHXcX9aLE5SymusoTmMZye8= golang.org/x/term v0.0.0-20220411215600-e5f449aeb171/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= @@ -567,8 +569,8 @@ golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.8-0.20211102182255-bb4add04ddef/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= golang.org/x/tools v0.1.8/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= -golang.org/x/tools v0.1.11 h1:loJ25fNOEhSXfHrpoGj91eCUThwdNX6u24rO1xnNteY= -golang.org/x/tools v0.1.11/go.mod h1:SgwaegtQh8clINPpECJMqnxLv9I09HLqnW3RMqW0CA4= +golang.org/x/tools v0.1.12 h1:VveCTK38A2rkS8ZqFY25HIDFscX5X9OoEhJd3quQmXU= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/internal/batches/features.go b/internal/batches/features.go index a2a285fb47..c27e94596f 100644 --- a/internal/batches/features.go +++ b/internal/batches/features.go @@ -9,17 +9,16 @@ import ( // FeatureFlags represent features that are only available on certain // Sourcegraph versions and we therefore have to detect at runtime. type FeatureFlags struct { - AllowArrayEnvironments bool - IncludeAutoAuthorDetails bool - UseGzipCompression bool - AllowTransformChanges bool - AllowWorkspaces bool - BatchChanges bool - AllowConditionalExec bool - AllowOptionalPublished bool - ServerSideBatchChanges bool - BitbucketCloud bool - ServerSideWorkspaceResolution bool + AllowArrayEnvironments bool + IncludeAutoAuthorDetails bool + UseGzipCompression bool + AllowTransformChanges bool + AllowWorkspaces bool + BatchChanges bool + AllowConditionalExec bool + AllowOptionalPublished bool + ServerSideBatchChanges bool + BitbucketCloud bool } func (ff *FeatureFlags) SetFromVersion(version string) error { @@ -45,7 +44,6 @@ func (ff *FeatureFlags) SetFromVersion(version string) error { {&ff.AllowOptionalPublished, ">= 3.30.0-0", "2021-06-21"}, {&ff.ServerSideBatchChanges, ">= 3.37.0-0", "2022-02-08"}, {&ff.BitbucketCloud, ">= 3.40.0-0", "2022-04-20"}, - {&ff.ServerSideWorkspaceResolution, ">= 3.42.0-0", "2022-07-19"}, } { value, err := api.CheckSourcegraphVersion(version, feature.constraint, feature.minDate) if err != nil { diff --git a/internal/batches/service/build_tasks.go b/internal/batches/service/build_tasks.go index c7898759ff..265b090b06 100644 --- a/internal/batches/service/build_tasks.go +++ b/internal/batches/service/build_tasks.go @@ -5,8 +5,15 @@ import ( "github.com/sourcegraph/sourcegraph/lib/batches/template" "github.com/sourcegraph/src-cli/internal/batches/executor" + "github.com/sourcegraph/src-cli/internal/batches/graphql" ) +type RepoWorkspace struct { + Repo *graphql.Repository + Path string + OnlyFetchWorkspace bool +} + // buildTasks returns *executor.Tasks for all the workspaces determined for the given spec. func buildTasks(attributes *template.BatchChangeAttributes, steps []batcheslib.Step, workspaces []RepoWorkspace) []*executor.Task { tasks := make([]*executor.Task, 0, len(workspaces)) diff --git a/internal/batches/service/main_test.go b/internal/batches/service/main_test.go deleted file mode 100644 index 07883000b4..0000000000 --- a/internal/batches/service/main_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package service - -import "github.com/sourcegraph/src-cli/internal/batches/graphql" - -var testRepo1 = &graphql.Repository{ - ID: "src-cli", - Name: "github.com/sourcegraph/src-cli", - DefaultBranch: &graphql.Branch{Name: "main", Target: graphql.Target{OID: "d34db33f"}}, - FileMatches: map[string]bool{ - "README.md": true, - "main.go": true, - }, -} diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index 44c97843e1..7a8287f031 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -6,16 +6,12 @@ import ( "fmt" "os" "os/exec" - "path" "path/filepath" "strings" "sync" "text/template" - "github.com/grafana/regexp" - batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" - onlib "github.com/sourcegraph/sourcegraph/lib/batches/on" templatelib "github.com/sourcegraph/sourcegraph/lib/batches/template" "github.com/sourcegraph/sourcegraph/lib/errors" @@ -364,10 +360,6 @@ func (svc *Service) EnsureDockerImages( return images, nil } -func (svc *Service) DetermineWorkspaces(ctx context.Context, repos []*graphql.Repository, spec *batcheslib.BatchSpec) ([]RepoWorkspace, error) { - return findWorkspaces(ctx, spec, svc, repos) -} - func (svc *Service) BuildTasks(attributes *templatelib.BatchChangeAttributes, steps []batcheslib.Step, workspaces []RepoWorkspace) []*executor.Task { return buildTasks(attributes, steps, workspaces) } @@ -669,114 +661,6 @@ func (svc *Service) ResolveNamespace(ctx context.Context, namespace string) (Nam return Namespace{}, fmt.Errorf("failed to resolve namespace %q: no user or organization found", namespace) } -func (svc *Service) ResolveRepositories(ctx context.Context, spec *batcheslib.BatchSpec, allowUnsupported, allowIgnored bool) ([]*graphql.Repository, error) { - agg := onlib.NewRepoRevisionAggregator() - unsupported := batches.UnsupportedRepoSet{} - ignored := batches.IgnoredRepoSet{} - - // TODO: this could be trivially parallelised in the future. - for _, on := range spec.On { - repos, ruleType, err := svc.ResolveRepositoriesOn(ctx, &on) - if err != nil { - return nil, errors.Wrapf(err, on.String()) - } - - result := agg.NewRuleRevisions(ruleType) - reposWithBranch := make([]*graphql.Repository, 0, len(repos)) - for _, repo := range repos { - if !repo.HasBranch() { - continue - } - reposWithBranch = append(reposWithBranch, repo) - } - - var repoBatchIgnores map[*graphql.Repository][]string - if !allowIgnored { - repoBatchIgnores, err = svc.FindDirectoriesInRepos(ctx, ".batchignore", reposWithBranch...) - if err != nil { - return nil, err - } - } - - for _, repo := range reposWithBranch { - result.AddRepoRevision(repo.ID, repo) - - switch st := strings.ToLower(repo.ExternalRepository.ServiceType); st { - case "github", "gitlab", "bitbucketserver": - case "bitbucketcloud": - if svc.features.BitbucketCloud { - break - } - fallthrough - default: - if !allowUnsupported { - unsupported.Append(repo) - } - } - - if !allowIgnored { - if locations, ok := repoBatchIgnores[repo]; ok && len(locations) > 0 { - ignored.Append(repo) - } - } - } - } - - final := []*graphql.Repository{} - for _, rev := range agg.Revisions() { - repo := rev.(*graphql.Repository) - if !unsupported.Includes(repo) && !ignored.Includes(repo) { - final = append(final, repo) - } - } - - if unsupported.HasUnsupported() { - return final, unsupported - } - - if ignored.HasIgnored() { - return final, ignored - } - - return final, nil -} - -func (svc *Service) ResolveRepositoriesOn(ctx context.Context, on *batcheslib.OnQueryOrRepository) ([]*graphql.Repository, onlib.RepositoryRuleType, error) { - if on.RepositoriesMatchingQuery != "" { - repo, err := svc.resolveRepositorySearch(ctx, on.RepositoriesMatchingQuery) - return repo, onlib.RepositoryRuleTypeQuery, err - } else if on.Repository != "" { - branches, err := on.GetBranches() - if err != nil { - return nil, onlib.RepositoryRuleTypeExplicit, err - } - - if len(branches) > 0 { - repos := make([]*graphql.Repository, len(branches)) - for i, branch := range branches { - repo, err := svc.resolveRepositoryNameAndBranch(ctx, on.Repository, branch) - if err != nil { - return nil, onlib.RepositoryRuleTypeExplicit, err - } - - repos[i] = repo - } - - return repos, onlib.RepositoryRuleTypeExplicit, nil - } else { - repo, err := svc.resolveRepositoryName(ctx, on.Repository) - if err != nil { - return nil, onlib.RepositoryRuleTypeExplicit, err - } - return []*graphql.Repository{repo}, onlib.RepositoryRuleTypeExplicit, nil - } - } - - // This shouldn't happen on any batch spec that has passed validation, but, - // alas, software. - return nil, onlib.RepositoryRuleTypeExplicit, ErrMalformedOnQueryOrRepository -} - const repositoryNameQuery = ` query Repository($name: String!, $queryCommit: Boolean!, $rev: String!) { repository(name: $name) { @@ -800,251 +684,6 @@ func (svc *Service) resolveRepositoryName(ctx context.Context, name string) (*gr return result.Repository, nil } -func (svc *Service) resolveRepositoryNameAndBranch(ctx context.Context, name, branch string) (*graphql.Repository, error) { - var result struct{ Repository *graphql.Repository } - if ok, err := svc.client.NewRequest(repositoryNameQuery, map[string]interface{}{ - "name": name, - "queryCommit": true, - "rev": branch, - }).Do(ctx, &result); err != nil || !ok { - return nil, err - } - if result.Repository == nil { - return nil, errors.New("no repository found") - } - if result.Repository.Commit.OID == "" { - return nil, fmt.Errorf("no branch matching %q found for repository %s", branch, name) - } - - result.Repository.Branch = graphql.Branch{ - Name: branch, - Target: result.Repository.Commit, - } - - return result.Repository, nil -} - -// TODO: search result alerts. -const repositorySearchQuery = ` -query ChangesetRepos( - $query: String!, - $queryCommit: Boolean!, - $rev: String!, -) { - search(query: $query, version: V2) { - results { - results { - __typename - ... on Repository { - ...repositoryFields - } - ... on FileMatch { - file { path } - repository { - ...repositoryFields - } - } - } - } - } -} -` + graphql.RepositoryFieldsFragment - -func (svc *Service) resolveRepositorySearch(ctx context.Context, query string) ([]*graphql.Repository, error) { - var result struct { - Search struct { - Results struct { - Results []searchResult - } - } - } - - if ok, err := svc.client.NewRequest(repositorySearchQuery, map[string]interface{}{ - "query": setDefaultQueryCount(query), - "queryCommit": false, - "rev": "", - }).Do(ctx, &result); err != nil || !ok { - return nil, err - } - - ids := map[string]*graphql.Repository{} - var repos []*graphql.Repository - for _, r := range result.Search.Results.Results { - existing, ok := ids[r.ID] - if !ok { - repo := r.Repository - repos = append(repos, &repo) - ids[r.ID] = &repo - } else { - for file := range r.FileMatches { - existing.FileMatches[file] = true - } - } - } - return repos, nil -} - -// findDirectoriesResult maps the name of the GraphQL query to its results. The -// name is the repository's ID. -type findDirectoriesResult map[string]struct { - Results struct{ Results []searchResult } -} - -const searchQueryTmpl = `%s: search(query: %q, version: V2) { - results { - results { - __typename - ... on FileMatch { - file { path } - } - } - } -} -` - -const findDirectoriesInReposBatchSize = 50 - -// FindDirectoriesInRepos returns a map of repositories and the locations of -// files matching the given file name in the repository. -// The locations are paths relative to the root of the directory. -// No "/" at the beginning. -// A dot (".") represents the root directory. -func (svc *Service) FindDirectoriesInRepos(ctx context.Context, fileName string, repos ...*graphql.Repository) (map[*graphql.Repository][]string, error) { - // Build up unique identifiers that are safe to use as GraphQL query aliases. - reposByQueryID := map[string]*graphql.Repository{} - queryIDByRepo := map[*graphql.Repository]string{} - for i, repo := range repos { - queryID := fmt.Sprintf("repo_%d", i) - reposByQueryID[queryID] = repo - queryIDByRepo[repo] = queryID - } - - findInBatch := func(batch []*graphql.Repository, results map[*graphql.Repository][]string) error { - var a strings.Builder - a.WriteString("query DirectoriesContainingFile {\n") - - for _, repo := range batch { - query := fmt.Sprintf(`file:(^|/)%s$ repo:^%s$@%s type:path count:99999`, regexp.QuoteMeta(fileName), regexp.QuoteMeta(repo.Name), repo.Rev()) - - a.WriteString(fmt.Sprintf(searchQueryTmpl, queryIDByRepo[repo], query)) - } - - a.WriteString("}") - - var result findDirectoriesResult - if ok, err := svc.client.NewQuery(a.String()).Do(ctx, &result); err != nil || !ok { - return err - } - - for queryID, search := range result { - repo, ok := reposByQueryID[queryID] - if !ok { - return fmt.Errorf("result for query %q did not match any repository", queryID) - } - - files := map[string]struct{}{} - - for _, r := range search.Results.Results { - for file := range r.FileMatches { - files[file] = struct{}{} - } - } - - var dirs []string - for f := range files { - dir := path.Dir(f) - // "." means the path is root, but in the executor we use "" to signify root. - if dir == "." { - dir = "" - } - // We use path.Dir and not filepath.Dir here, because while - // src-cli might be executed on Windows, we need the paths to - // be Unix paths, since they will be used inside Docker - // containers. - dirs = append(dirs, dir) - } - - results[repo] = dirs - } - - return nil - } - - results := make(map[*graphql.Repository][]string) - - for start := 0; start < len(repos); start += findDirectoriesInReposBatchSize { - if err := ctx.Err(); err != nil { - return nil, err - } - - end := start + findDirectoriesInReposBatchSize - if end > len(repos) { - end = len(repos) - } - - batch := repos[start:end] - - err := findInBatch(batch, results) - if err != nil { - return results, err - } - } - - return results, nil -} - -var defaultQueryCountRegex = regexp.MustCompile(`\bcount:(\d+|all)\b`) - -const hardCodedCount = " count:999999" - -func setDefaultQueryCount(query string) string { - if defaultQueryCountRegex.MatchString(query) { - return query - } - - return query + hardCodedCount -} - -type searchResult struct { - graphql.Repository -} - -func (sr *searchResult) UnmarshalJSON(data []byte) error { - var tn struct { - Typename string `json:"__typename"` - } - if err := json.Unmarshal(data, &tn); err != nil { - return err - } - - switch tn.Typename { - case "FileMatch": - var result struct { - Repository graphql.Repository - File struct { - Path string - } - } - if err := json.Unmarshal(data, &result); err != nil { - return err - } - - sr.Repository = result.Repository - sr.Repository.FileMatches = map[string]bool{result.File.Path: true} - return nil - - case "Repository": - if err := json.Unmarshal(data, &sr.Repository); err != nil { - return err - } - sr.Repository.FileMatches = map[string]bool{} - return nil - - default: - return errors.Errorf("unknown GraphQL type %q", tn.Typename) - } -} - func getGitConfig(attribute string) (string, error) { cmd := exec.Command("git", "config", "--get", attribute) out, err := cmd.CombinedOutput() diff --git a/internal/batches/service/service_test.go b/internal/batches/service/service_test.go index 8d2f1b604e..70bde9fff8 100644 --- a/internal/batches/service/service_test.go +++ b/internal/batches/service/service_test.go @@ -1,19 +1,14 @@ package service import ( - "bytes" "context" "fmt" - "net/http" - "net/http/httptest" "os" "path/filepath" "strconv" "strings" "testing" - "github.com/google/go-cmp/cmp" - "github.com/google/go-cmp/cmp/cmpopts" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -21,488 +16,11 @@ import ( batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" - "github.com/sourcegraph/src-cli/internal/api" - "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/docker" "github.com/sourcegraph/src-cli/internal/batches/graphql" "github.com/sourcegraph/src-cli/internal/batches/mock" ) -func TestSetDefaultQueryCount(t *testing.T) { - for in, want := range map[string]string{ - "": hardCodedCount, - "count:10": "count:10", - "count:all": "count:all", - "r:foo": "r:foo" + hardCodedCount, - "r:foo count:10": "r:foo count:10", - "r:foo count:10 f:bar": "r:foo count:10 f:bar", - "r:foo count:": "r:foo count:" + hardCodedCount, - "r:foo count:xyz": "r:foo count:xyz" + hardCodedCount, - } { - t.Run(in, func(t *testing.T) { - have := setDefaultQueryCount(in) - if have != want { - t.Errorf("unexpected query: have %q; want %q", have, want) - } - }) - } -} - -func TestResolveRepositorySearch(t *testing.T) { - client, done := mockGraphQLClient(testResolveRepositorySearchResult) - defer done() - - svc := &Service{client: client} - - repos, err := svc.resolveRepositorySearch(context.Background(), "sourcegraph reconciler or src-cli") - if err != nil { - t.Fatalf("unexpected error: %s", err) - } - - // We want multiple FileMatches in the same repository to result in one repository - // and Repository and FileMatches should be folded into the same repository. - if have, want := len(repos), 3; have != want { - t.Fatalf("wrong number of repos. want=%d, have=%d", want, have) - } -} - -const testResolveRepositorySearchResult = `{ - "data": { - "search": { - "results": { - "results": [ - { - "__typename": "FileMatch", - "file": { "path": "website/src/components/PricingTable.tsx" }, - "repository": { - "id": "UmVwb3NpdG9yeTo0MDc=", - "name": "github.com/sd9/about", - "url": "/https/github.com/github.com/sd9/about", - "externalRepository": { "serviceType": "github" }, - "defaultBranch": { "name": "refs/heads/master", "target": { "oid": "1576f235209fbbfc918129db35f3d108347b74cb" } } - } - }, - { - "__typename": "Repository", - "id": "UmVwb3NpdG9yeToxOTM=", - "name": "github.com/sd9/src-cli", - "url": "/https/github.com/github.com/sd9/src-cli", - "externalRepository": { "serviceType": "github" }, - "defaultBranch": { "name": "refs/heads/master", "target": { "oid": "21dd58b08d64620942401b5543f5b0d33498bacb" } } - }, - { - "__typename": "FileMatch", - "file": { "path": "cmd/src/api.go" }, - "repository": { - "id": "UmVwb3NpdG9yeToxOTM=", - "name": "github.com/sd9/src-cli", - "url": "/https/github.com/github.com/sd9/src-cli", - "externalRepository": { "serviceType": "github" }, - "defaultBranch": { "name": "refs/heads/master", "target": { "oid": "21dd58b08d64620942401b5543f5b0d33498bacb" } } - } - }, - { - "__typename": "FileMatch", - "file": { "path": "client/web/src/components/externalServices/externalServices.tsx" }, - "repository": { - "id": "UmVwb3NpdG9yeTo2", - "name": "github.com/sourcegraph/sourcegraph", - "url": "/https/github.com/github.com/sourcegraph/sourcegraph", - "externalRepository": { "serviceType": "github" }, - "defaultBranch": { "name": "refs/heads/main", "target": { "oid": "e612c34f2e27005928ff3dfdd8e5ead5a0cb1526" } } - } - }, - { - "__typename": "FileMatch", - "file": { "path": "cmd/frontend/internal/httpapi/src_cli.go" }, - "repository": { - "id": "UmVwb3NpdG9yeTo2", - "name": "github.com/sourcegraph/sourcegraph", - "url": "/https/github.com/github.com/sourcegraph/sourcegraph", - "externalRepository": { "serviceType": "github" }, - "defaultBranch": { "name": "refs/heads/main", "target": { "oid": "e612c34f2e27005928ff3dfdd8e5ead5a0cb1526" } } - } - } - ] - } - } - } -} -` - -func mockGraphQLClient(responses ...string) (client api.Client, done func()) { - mux := http.NewServeMux() - - var count int - mux.HandleFunc("/.api/graphql", func(w http.ResponseWriter, _ *http.Request) { - w.Header().Set("Content-Type", "application/json") - - _, _ = w.Write([]byte(responses[count])) - - if count < len(responses)-1 { - count += 1 - } - }) - - ts := httptest.NewServer(mux) - - var clientBuffer bytes.Buffer - client = api.NewClient(api.ClientOpts{Endpoint: ts.URL, Out: &clientBuffer}) - - return client, ts.Close -} - -func TestResolveRepositories_Unsupported(t *testing.T) { - client, done := mockGraphQLClient(testResolveRepositoriesUnsupported) - defer done() - - spec := &batcheslib.BatchSpec{ - On: []batcheslib.OnQueryOrRepository{ - {RepositoriesMatchingQuery: "testquery"}, - }, - } - - t.Run("allowUnsupported:true", func(t *testing.T) { - svc := &Service{client: client} - - repos, err := svc.ResolveRepositories(context.Background(), spec, true, true) - if err != nil { - t.Fatalf("unexpected error: %s", err) - } - if len(repos) != 4 { - t.Fatalf("wrong number of repos. want=%d, have=%d", 4, len(repos)) - } - }) - - t.Run("allowUnsupported:false", func(t *testing.T) { - svc := &Service{client: client} - - repos, err := svc.ResolveRepositories(context.Background(), spec, false, true) - repoSet, ok := err.(batches.UnsupportedRepoSet) - if !ok { - t.Fatalf("err is not UnsupportedRepoSet") - } - if len(repoSet) != 1 { - t.Fatalf("wrong number of repos. want=%d, have=%d", 1, len(repoSet)) - } - if len(repos) != 3 { - t.Fatalf("wrong number of repos. want=%d, have=%d", 3, len(repos)) - } - }) -} - -const testResolveRepositoriesUnsupported = `{ - "data": { - "search": { - "results": { - "results": [ - { - "__typename": "Repository", - "id": "UmVwb3NpdG9yeToxMw==", - "name": "bitbucket.sgdev.org/SOUR/automation-testing", - "url": "/https/github.com/bitbucket.sgdev.org/SOUR/automation-testing", - "externalRepository": { "serviceType": "bitbucketserver" }, - "defaultBranch": { "name": "refs/heads/master", "target": { "oid": "b978d56de5578a935ca0bf07b56528acc99d5a61" } } - }, - { - "__typename": "Repository", - "id": "UmVwb3NpdG9yeTo0", - "name": "github.com/sourcegraph/automation-testing", - "url": "/https/github.com/github.com/sourcegraph/automation-testing", - "externalRepository": { "serviceType": "github" }, - "defaultBranch": { "name": "refs/heads/master", "target": { "oid": "6ac8a32ecaf6c4dc5ce050b9af51bce3db8efd63" } } - }, - { - "__typename": "Repository", - "id": "UmVwb3NpdG9yeTo2MQ==", - "name": "gitlab.sgdev.org/sourcegraph/automation-testing", - "url": "/https/github.com/gitlab.sgdev.org/sourcegraph/automation-testing", - "externalRepository": { "serviceType": "gitlab" }, - "defaultBranch": { "name": "refs/heads/master", "target": { "oid": "3b79a5d479d2af9cfe91e0aad4e9dddca7278150" } } - }, - { - "__typename": "Repository", - "id": "UmVwb3NpdG9yeToxNDg=", - "name": "git-codecommit.us-est-1.amazonaws.com/stripe-go", - "url": "/https/github.com/git-codecommit.us-est-1.amazonaws.com/stripe-go", - "externalRepository": { "serviceType": "awscodecommit" }, - "defaultBranch": { "name": "refs/heads/master", "target": { "oid": "3b79a5d479d2af9cfe91e0aad4e9dddca7278150" } } - } - ] - } - } - } -} -` - -func TestResolveRepositories_Ignored(t *testing.T) { - spec := &batcheslib.BatchSpec{ - On: []batcheslib.OnQueryOrRepository{ - {RepositoriesMatchingQuery: "testquery"}, - }, - } - - t.Run("allowIgnored:true", func(t *testing.T) { - client, done := mockGraphQLClient(testResolveRepositories, testBatchIgnoreInRepos) - defer done() - - svc := &Service{client: client} - - repos, err := svc.ResolveRepositories(context.Background(), spec, false, true) - if err != nil { - t.Fatalf("unexpected error: %s", err) - } - if len(repos) != 3 { - t.Fatalf("wrong number of repos. want=%d, have=%d", 3, len(repos)) - } - }) - - t.Run("allowIgnored:false", func(t *testing.T) { - client, done := mockGraphQLClient(testResolveRepositories, testBatchIgnoreInRepos) - defer done() - - svc := &Service{client: client} - - repos, err := svc.ResolveRepositories(context.Background(), spec, false, false) - ignored, ok := err.(batches.IgnoredRepoSet) - if !ok { - t.Fatalf("err is not IgnoredRepoSet: %s", err) - } - if len(ignored) != 1 { - t.Fatalf("wrong number of ignored repos. want=%d, have=%d", 1, len(ignored)) - } - if len(repos) != 2 { - t.Fatalf("wrong number of repos. want=%d, have=%d", 2, len(repos)) - } - }) -} - -const testResolveRepositories = `{ - "data": { - "search": { - "results": { - "results": [ - { - "__typename": "Repository", - "id": "UmVwb3NpdG9yeToxMw==", - "name": "bitbucket.sgdev.org/SOUR/automation-testing", - "url": "/https/github.com/bitbucket.sgdev.org/SOUR/automation-testing", - "externalRepository": { "serviceType": "bitbucketserver" }, - "defaultBranch": { "name": "refs/heads/master", "target": { "oid": "b978d56de5578a935ca0bf07b56528acc99d5a61" } } - }, - { - "__typename": "Repository", - "id": "UmVwb3NpdG9yeTo0", - "name": "github.com/sourcegraph/automation-testing", - "url": "/https/github.com/github.com/sourcegraph/automation-testing", - "externalRepository": { "serviceType": "github" }, - "defaultBranch": { "name": "refs/heads/master", "target": { "oid": "6ac8a32ecaf6c4dc5ce050b9af51bce3db8efd63" } } - }, - { - "__typename": "Repository", - "id": "UmVwb3NpdG9yeTo2MQ==", - "name": "gitlab.sgdev.org/sourcegraph/automation-testing", - "url": "/https/github.com/gitlab.sgdev.org/sourcegraph/automation-testing", - "externalRepository": { "serviceType": "gitlab" }, - "defaultBranch": { "name": "refs/heads/master", "target": { "oid": "3b79a5d479d2af9cfe91e0aad4e9dddca7278150" } } - } - ] - } - } - } -} -` - -const testBatchIgnoreInRepos = `{ - "data": { - "repo_0": { - "results": { - "results": [ - { - "__typename": "FileMatch", - "file": { - "path": ".batchignore" - } - } - ] - } - }, - "repo_1": { "results": { "results": [] } }, - "repo_2": { "results": { "results": [] } } - } -} -` - -func TestResolveRepositories_RepoWithoutBranch(t *testing.T) { - spec := &batcheslib.BatchSpec{ - On: []batcheslib.OnQueryOrRepository{ - {RepositoriesMatchingQuery: "testquery"}, - }, - } - - client, done := mockGraphQLClient(testResolveRepositoriesNoBranch, testBatchIgnoreInReposNoBranch) - defer done() - - svc := &Service{client: client} - - repos, err := svc.ResolveRepositories(context.Background(), spec, false, false) - if err != nil { - t.Fatalf("unexpected error: %s", err) - } - if len(repos) != 1 { - t.Fatalf("wrong number of repos. want=%d, have=%d", 2, len(repos)) - } -} - -const testResolveRepositoriesNoBranch = `{ - "data": { - "search": { - "results": { - "results": [ - { - "__typename": "Repository", - "id": "UmVwb3NpdG9yeToxMw==", - "name": "bitbucket.sgdev.org/SOUR/automation-testing", - "url": "/https/github.com/bitbucket.sgdev.org/SOUR/automation-testing", - "externalRepository": { "serviceType": "bitbucketserver" }, - "defaultBranch": null - }, - { - "__typename": "Repository", - "id": "UmVwb3NpdG9yeTo0", - "name": "github.com/sourcegraph/automation-testing", - "url": "/https/github.com/github.com/sourcegraph/automation-testing", - "externalRepository": { "serviceType": "github" }, - "defaultBranch": null - }, - { - "__typename": "Repository", - "id": "UmVwb3NpdG9yeTo2MQ==", - "name": "gitlab.sgdev.org/sourcegraph/automation-testing", - "url": "/https/github.com/gitlab.sgdev.org/sourcegraph/automation-testing", - "externalRepository": { "serviceType": "gitlab" }, - "defaultBranch": { "name": "refs/heads/master", "target": { "oid": "3b79a5d479d2af9cfe91e0aad4e9dddca7278150" } } - } - ] - } - } - } -} -` - -const testBatchIgnoreInReposNoBranch = `{ - "data": { - "repo_0": { "results": { "results": [] } } - } -} -` - -func TestService_FindDirectoriesInRepos(t *testing.T) { - client, done := mockGraphQLClient(testFindDirectoriesInRepos) - defer done() - - fileName := "package.json" - repos := []*graphql.Repository{ - { - ID: "repo-id-0", - Name: "github.com/sourcegraph/automation-testing", - Branch: graphql.Branch{Name: "dev"}, - DefaultBranch: &graphql.Branch{ - Name: "main", - Target: graphql.Target{ - OID: "d34db33f", - }, - }, - }, - { - ID: "repo-id-1", - Name: "github.com/sourcegraph/sourcegraph", - Branch: graphql.Branch{Name: "dev"}, - DefaultBranch: &graphql.Branch{ - Name: "main", - Target: graphql.Target{ - OID: "d34db33f", - }, - }, - }, - } - - svc := &Service{client: client} - - results, err := svc.FindDirectoriesInRepos(context.Background(), fileName, repos...) - if err != nil { - t.Fatalf("unexpected error: %s", err) - } - if len(results) != len(repos) { - t.Fatalf("wrong number of repos. want=%d, have=%d", 4, len(repos)) - } - - want := map[*graphql.Repository][]string{ - repos[0]: {"examples/project3", "project1", "project2"}, - repos[1]: {"docs/client1", "", "docs/client2/examples"}, - } - - if !cmp.Equal(want, results, cmpopts.SortSlices(sortStrings)) { - t.Errorf("wrong tasks built (-want +got):\n%s", cmp.Diff(want, results)) - } -} - -func sortStrings(a, b string) bool { return a < b } - -const testFindDirectoriesInRepos = `{ - "data": { - "repo_0": { - "results": { - "results": [ - { - "__typename": "FileMatch", - "file": { - "path": "examples/project3/package.json" - } - }, - { - "__typename": "FileMatch", - "file": { - "path": "project1/package.json" - } - }, - { - "__typename": "FileMatch", - "file": { - "path": "project2/package.json" - } - } - ] - } - }, - "repo_1": { - "results": { - "results": [ - { - "__typename": "FileMatch", - "file": { - "path": "docs/client1/package.json" - } - }, - { - "__typename": "FileMatch", - "file": { - "path": "package.json" - } - }, - { - "__typename": "FileMatch", - "file": { - "path": "docs/client2/examples/package.json" - } - } - ] - } - } - } -} -` - func TestService_ValidateChangesetSpecs(t *testing.T) { repo1 := &graphql.Repository{ID: "repo-graphql-id-1", Name: "github.com/sourcegraph/src-cli"} repo2 := &graphql.Repository{ID: "repo-graphql-id-2", Name: "github.com/sourcegraph/sourcegraph"} diff --git a/internal/batches/service/workspaces.go b/internal/batches/service/workspaces.go deleted file mode 100644 index c5df1005ac..0000000000 --- a/internal/batches/service/workspaces.go +++ /dev/null @@ -1,214 +0,0 @@ -package service - -import ( - "context" - "sort" - "strings" - - "github.com/gobwas/glob" - batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" - "github.com/sourcegraph/sourcegraph/lib/batches/template" - "github.com/sourcegraph/sourcegraph/lib/errors" - - "github.com/sourcegraph/src-cli/internal/batches/graphql" - "github.com/sourcegraph/src-cli/internal/batches/util" -) - -type RepoWorkspace struct { - Repo *graphql.Repository - Path string - OnlyFetchWorkspace bool -} - -type directoryFinder interface { - FindDirectoriesInRepos(ctx context.Context, fileName string, repos ...*graphql.Repository) (map[*graphql.Repository][]string, error) -} - -// findWorkspaces matches the given repos to the workspace configs and -// searches, via the Sourcegraph instance, the locations of the workspaces in -// each repository. -// The repositories that were matched by a workspace config and all repos that didn't -// match a config are returned as workspaces. -func findWorkspaces( - ctx context.Context, - spec *batcheslib.BatchSpec, - finder directoryFinder, - repos []*graphql.Repository, -) ([]RepoWorkspace, error) { - // Pre-compile all globs. - workspaceMatchers := make(map[batcheslib.WorkspaceConfiguration]glob.Glob) - for _, conf := range spec.Workspaces { - in := conf.In - // Empty `in` should fall back to matching all, instead of nothing. - if in == "" { - in = "*" - } - g, err := glob.Compile(in) - if err != nil { - return nil, batcheslib.NewValidationError(errors.Errorf("failed to compile glob %q: %v", in, err)) - } - workspaceMatchers[conf] = g - } - - root := []*graphql.Repository{} - - // Maps workspace config indexes to repositories matching them. - matched := map[int][]*graphql.Repository{} - - for _, repo := range repos { - found := false - - // Try to find a workspace configuration matching this repo. - for idx, conf := range spec.Workspaces { - if !workspaceMatchers[conf].Match(repo.Name) { - continue - } - - // Don't allow duplicate matches. - if found { - return nil, batcheslib.NewValidationError(errors.Errorf("repository %s matches multiple workspaces.in globs in the batch spec. glob: %q", repo.Name, conf.In)) - } - - matched[idx] = append(matched[idx], repo) - found = true - } - - if !found { - root = append(root, repo) - } - } - - type repoWorkspaces struct { - Repo *graphql.Repository - Paths []string - OnlyFetchWorkspace bool - } - type workspaceKey struct { - repo string - branch string - } - workspacesByKey := map[workspaceKey]repoWorkspaces{} - for idx, repos := range matched { - conf := spec.Workspaces[idx] - repoDirs, err := finder.FindDirectoriesInRepos(ctx, conf.RootAtLocationOf, repos...) - if err != nil { - return nil, err - } - - for repo, dirs := range repoDirs { - // Don't add repos that don't have any matched workspaces. - if len(dirs) == 0 { - continue - } - key := workspaceKey{ - repo: repo.ID, - branch: repo.Branch.Name, - } - workspacesByKey[key] = repoWorkspaces{ - Repo: repo, - Paths: dirs, - OnlyFetchWorkspace: conf.OnlyFetchWorkspace, - } - } - } - - // And add the root for repos. - for _, repo := range root { - key := workspaceKey{ - repo: repo.ID, - branch: repo.Branch.Name, - } - conf, ok := workspacesByKey[key] - if !ok { - workspacesByKey[key] = repoWorkspaces{ - Repo: repo, - Paths: []string{""}, - OnlyFetchWorkspace: false, - } - continue - } - conf.Paths = append(workspacesByKey[key].Paths, "") - } - - workspaces := make([]RepoWorkspace, 0, len(workspacesByKey)) - for _, workspace := range workspacesByKey { - for _, path := range workspace.Paths { - fetchWorkspace := workspace.OnlyFetchWorkspace - if path == "" { - fetchWorkspace = false - } - - // Filter file matches by workspace. Only include paths that are - // _within_ the directory. - paths := map[string]bool{} - for probe := range workspace.Repo.FileMatches { - if strings.HasPrefix(probe, path) { - paths[probe] = true - } - } - - repo := *workspace.Repo - repo.FileMatches = paths - - steps, err := stepsForRepo(spec, util.NewTemplatingRepo(repo.Name, repo.FileMatches)) - if err != nil { - return nil, err - } - - // If the workspace doesn't have any steps we don't need to include it. - if len(steps) == 0 { - continue - } - - workspaces = append(workspaces, RepoWorkspace{ - Repo: &repo, - Path: path, - OnlyFetchWorkspace: fetchWorkspace, - }) - } - } - - // Stable sorting. - sort.Slice(workspaces, func(i, j int) bool { - if workspaces[i].Repo.Name == workspaces[j].Repo.Name { - return workspaces[i].Path < workspaces[j].Path - } - return workspaces[i].Repo.Name < workspaces[j].Repo.Name - }) - - return workspaces, nil -} - -// stepsForRepo calculates the steps required to run on the given repo. -func stepsForRepo(spec *batcheslib.BatchSpec, repo template.Repository) ([]batcheslib.Step, error) { - taskSteps := []batcheslib.Step{} - for _, step := range spec.Steps { - // If no if condition is given, just go ahead and add the step to the list. - if step.IfCondition() == "" { - taskSteps = append(taskSteps, step) - continue - } - - batchChange := template.BatchChangeAttributes{ - Name: spec.Name, - Description: spec.Description, - } - stepCtx := &template.StepContext{ - Repository: repo, - BatchChange: batchChange, - } - static, boolVal, err := template.IsStaticBool(step.IfCondition(), stepCtx) - if err != nil { - return nil, err - } - - // If we could evaluate the condition statically and the resulting - // boolean is false, we don't add that step. - if !static { - taskSteps = append(taskSteps, step) - } else if boolVal { - taskSteps = append(taskSteps, step) - } - } - return taskSteps, nil -} diff --git a/internal/batches/service/workspaces_test.go b/internal/batches/service/workspaces_test.go deleted file mode 100644 index 06b9be3193..0000000000 --- a/internal/batches/service/workspaces_test.go +++ /dev/null @@ -1,345 +0,0 @@ -package service - -import ( - "context" - "sort" - "testing" - - "github.com/google/go-cmp/cmp" - "github.com/google/go-cmp/cmp/cmpopts" - batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" - - "github.com/sourcegraph/src-cli/internal/batches/graphql" - "github.com/sourcegraph/src-cli/internal/batches/util" -) - -func TestFindWorkspaces(t *testing.T) { - repos := []*graphql.Repository{ - {ID: "repo-id-0", Name: "github.com/sourcegraph/automation-testing", FileMatches: map[string]bool{}}, - {ID: "repo-id-1", Name: "github.com/sourcegraph/sourcegraph", FileMatches: map[string]bool{}}, - {ID: "repo-id-2", Name: "bitbucket.sgdev.org/SOUR/automation-testing", FileMatches: map[string]bool{}}, - {ID: "repo-id-3", Name: "github.com/sourcegraph/src-cli", FileMatches: map[string]bool{"a/b": true, "a/b/c": true, "d/e/f": true}}, - } - steps := []batcheslib.Step{{Run: "echo 1"}} - - type finderResults map[*graphql.Repository][]string - - tests := map[string]struct { - spec *batcheslib.BatchSpec - finderResults map[*graphql.Repository][]string - - // workspaces in which repo/path they are executed - wantWorkspaces []RepoWorkspace - }{ - "no workspace configuration": { - spec: &batcheslib.BatchSpec{Steps: steps}, - finderResults: finderResults{}, - wantWorkspaces: []RepoWorkspace{ - {Repo: repos[0], Path: ""}, - {Repo: repos[1], Path: ""}, - {Repo: repos[2], Path: ""}, - {Repo: repos[3], Path: ""}, - }, - }, - - "workspace configuration matching no repos": { - spec: &batcheslib.BatchSpec{ - Steps: steps, - Workspaces: []batcheslib.WorkspaceConfiguration{ - {In: "this-does-not-match", RootAtLocationOf: "package.json"}, - }, - }, - finderResults: finderResults{}, - wantWorkspaces: []RepoWorkspace{ - {Repo: repos[0], Path: ""}, - {Repo: repos[1], Path: ""}, - {Repo: repos[2], Path: ""}, - {Repo: repos[3], Path: ""}, - }, - }, - - "workspace configuration matching 3 repos with no results": { - spec: &batcheslib.BatchSpec{ - Steps: steps, - Workspaces: []batcheslib.WorkspaceConfiguration{ - {In: "*automation-testing", RootAtLocationOf: "package.json"}, - }, - }, - finderResults: finderResults{ - repos[0]: []string{}, - repos[2]: []string{}, - }, - wantWorkspaces: []RepoWorkspace{ - {Repo: repos[1], Path: ""}, - {Repo: repos[3], Path: ""}, - }, - }, - - "workspace configuration matching 2 repos with 3 results each": { - spec: &batcheslib.BatchSpec{ - Steps: steps, - Workspaces: []batcheslib.WorkspaceConfiguration{ - {In: "*automation-testing", RootAtLocationOf: "package.json"}, - }, - }, - finderResults: finderResults{ - repos[0]: {"a/b", "a/b/c", "d/e/f"}, - repos[2]: {"a/b", "a/b/c", "d/e/f"}, - }, - wantWorkspaces: []RepoWorkspace{ - {Repo: repos[0], Path: "a/b"}, - {Repo: repos[0], Path: "a/b/c"}, - {Repo: repos[0], Path: "d/e/f"}, - {Repo: repos[1], Path: ""}, - {Repo: repos[2], Path: "a/b"}, - {Repo: repos[2], Path: "a/b/c"}, - {Repo: repos[2], Path: "d/e/f"}, - {Repo: repos[3], Path: ""}, - }, - }, - - "workspace configuration matches repo with OnlyFetchWorkspace": { - spec: &batcheslib.BatchSpec{ - Steps: steps, - Workspaces: []batcheslib.WorkspaceConfiguration{ - { - OnlyFetchWorkspace: true, - In: "*automation-testing", - RootAtLocationOf: "package.json", - }, - }, - }, - finderResults: finderResults{ - repos[0]: {"a/b", "a/b/c", "d/e/f"}, - repos[2]: {"a/b", "a/b/c", "d/e/f"}, - }, - wantWorkspaces: []RepoWorkspace{ - {Repo: repos[0], Path: "a/b", OnlyFetchWorkspace: true}, - {Repo: repos[0], Path: "a/b/c", OnlyFetchWorkspace: true}, - {Repo: repos[0], Path: "d/e/f", OnlyFetchWorkspace: true}, - {Repo: repos[1], Path: ""}, - {Repo: repos[2], Path: "a/b", OnlyFetchWorkspace: true}, - {Repo: repos[2], Path: "a/b/c", OnlyFetchWorkspace: true}, - {Repo: repos[2], Path: "d/e/f", OnlyFetchWorkspace: true}, - {Repo: repos[3], Path: ""}, - }, - }, - "workspace configuration without 'in' matches all": { - spec: &batcheslib.BatchSpec{ - Steps: steps, - Workspaces: []batcheslib.WorkspaceConfiguration{ - { - RootAtLocationOf: "package.json", - }, - }, - }, - finderResults: finderResults{ - repos[0]: {"a/b"}, - repos[2]: {"a/b"}, - }, - wantWorkspaces: []RepoWorkspace{ - {Repo: repos[0], Path: "a/b"}, - {Repo: repos[2], Path: "a/b"}, - }, - }, - "workspace gets subset of search_result_paths": { - spec: &batcheslib.BatchSpec{ - Steps: steps, - Workspaces: []batcheslib.WorkspaceConfiguration{ - { - In: "*src-cli", - RootAtLocationOf: "package.json", - }, - }, - }, - finderResults: finderResults{ - repos[3]: {"a/b", "d"}, - }, - wantWorkspaces: []RepoWorkspace{ - {Repo: repos[0], Path: ""}, - {Repo: repos[1], Path: ""}, - {Repo: repos[2], Path: ""}, - { - Repo: &graphql.Repository{ - ID: repos[3].ID, - Name: repos[3].Name, - URL: repos[3].URL, - ExternalRepository: repos[3].ExternalRepository, - DefaultBranch: repos[3].DefaultBranch, - Branch: repos[3].Branch, - Commit: repos[3].Commit, - // Only expect the file matches that are children of a/b. - FileMatches: map[string]bool{"a/b": true, "a/b/c": true}, - }, - Path: "a/b", - }, - { - Repo: &graphql.Repository{ - ID: repos[3].ID, - Name: repos[3].Name, - URL: repos[3].URL, - ExternalRepository: repos[3].ExternalRepository, - DefaultBranch: repos[3].DefaultBranch, - Branch: repos[3].Branch, - Commit: repos[3].Commit, - // Only expect the file matches that are children of d. - FileMatches: map[string]bool{"d/e/f": true}, - }, - Path: "d", - }, - }, - }, - } - - for name, tt := range tests { - t.Run(name, func(t *testing.T) { - finder := &mockDirectoryFinder{results: tt.finderResults} - workspaces, err := findWorkspaces(context.Background(), tt.spec, finder, repos) - if err != nil { - t.Fatalf("unexpected err: %s", err) - } - - // Sort by ID, easier than by name for tests. - sort.Slice(workspaces, func(i, j int) bool { - if workspaces[i].Repo.ID == workspaces[j].Repo.ID { - return workspaces[i].Path < workspaces[j].Path - } - return workspaces[i].Repo.ID < workspaces[j].Repo.ID - }) - - if diff := cmp.Diff(tt.wantWorkspaces, workspaces); diff != "" { - t.Errorf("mismatch (-want +got):\n%s", diff) - } - }) - } -} - -type mockDirectoryFinder struct { - results map[*graphql.Repository][]string -} - -func (m *mockDirectoryFinder) FindDirectoriesInRepos(ctx context.Context, fileName string, repos ...*graphql.Repository) (map[*graphql.Repository][]string, error) { - return m.results, nil -} - -func TestStepsForRepo(t *testing.T) { - tests := map[string]struct { - spec *batcheslib.BatchSpec - - wantSteps []batcheslib.Step - }{ - "no if": { - spec: &batcheslib.BatchSpec{ - Steps: []batcheslib.Step{ - {Run: "echo 1"}, - }, - }, - wantSteps: []batcheslib.Step{ - {Run: "echo 1"}, - }, - }, - - "if has static true value": { - spec: &batcheslib.BatchSpec{ - Steps: []batcheslib.Step{ - {Run: "echo 1", If: "true"}, - }, - }, - wantSteps: []batcheslib.Step{ - {Run: "echo 1", If: "true"}, - }, - }, - - "one of many steps has if with static true value": { - spec: &batcheslib.BatchSpec{ - Steps: []batcheslib.Step{ - {Run: "echo 1"}, - {Run: "echo 2", If: "true"}, - {Run: "echo 3"}, - }, - }, - wantSteps: []batcheslib.Step{ - {Run: "echo 1"}, - {Run: "echo 2", If: "true"}, - {Run: "echo 3"}, - }, - }, - - "if has static non-true value": { - spec: &batcheslib.BatchSpec{ - Steps: []batcheslib.Step{ - {Run: "echo 1", If: "this is not true"}, - }, - }, - wantSteps: []batcheslib.Step{}, - }, - - "one of many steps has if with static non-true value": { - spec: &batcheslib.BatchSpec{ - Steps: []batcheslib.Step{ - {Run: "echo 1"}, - {Run: "echo 2", If: "every type system needs generics"}, - {Run: "echo 3"}, - }, - }, - wantSteps: []batcheslib.Step{ - {Run: "echo 1"}, - {Run: "echo 3"}, - }, - }, - - "if expression that can be partially evaluated to true": { - spec: &batcheslib.BatchSpec{ - Steps: []batcheslib.Step{ - {Run: "echo 1", If: `${{ matches repository.name "github.com/sourcegraph/src*" }}`}, - }, - }, - wantSteps: []batcheslib.Step{ - {Run: "echo 1", If: `${{ matches repository.name "github.com/sourcegraph/src*" }}`}, - }, - }, - - "if expression that can be partially evaluated to false": { - spec: &batcheslib.BatchSpec{ - Steps: []batcheslib.Step{ - {Run: "echo 1", If: `${{ matches repository.name "horse" }}`}, - }, - }, - wantSteps: []batcheslib.Step{}, - }, - - "one of many steps has if expression that can be evaluated to true": { - spec: &batcheslib.BatchSpec{ - Steps: []batcheslib.Step{ - {Run: "echo 1", If: `${{ matches repository.name "horse" }}`}, - }, - }, - wantSteps: []batcheslib.Step{}, - }, - - "if expression that can NOT be partially evaluated": { - spec: &batcheslib.BatchSpec{ - Steps: []batcheslib.Step{ - {Run: "echo 1", If: `${{ eq outputs.value "foobar" }}`}, - }, - }, - wantSteps: []batcheslib.Step{ - {Run: "echo 1", If: `${{ eq outputs.value "foobar" }}`}, - }, - }, - } - - for name, tt := range tests { - t.Run(name, func(t *testing.T) { - haveSteps, err := stepsForRepo(tt.spec, util.NewTemplatingRepo(testRepo1.Name, testRepo1.FileMatches)) - if err != nil { - t.Fatalf("unexpected err: %s", err) - } - - opts := cmpopts.IgnoreUnexported(batcheslib.Step{}) - if diff := cmp.Diff(tt.wantSteps, haveSteps, opts); diff != "" { - t.Errorf("mismatch (-want +got):\n%s", diff) - } - }) - } -} diff --git a/internal/batches/ui/exec_ui.go b/internal/batches/ui/exec_ui.go index 52a5f91637..ecedfcfcac 100644 --- a/internal/batches/ui/exec_ui.go +++ b/internal/batches/ui/exec_ui.go @@ -22,11 +22,8 @@ type ExecUI interface { DeterminingWorkspaceCreatorType() DeterminingWorkspaceCreatorTypeSuccess(wt workspace.CreatorType) - ResolvingRepositories() - ResolvingRepositoriesDone(repos []*graphql.Repository, unsupported batches.UnsupportedRepoSet, ignored batches.IgnoredRepoSet) - DeterminingWorkspaces() - DeterminingWorkspacesSuccess(num int) + DeterminingWorkspacesSuccess(workspacesCount, reposCount int, unsupported batches.UnsupportedRepoSet, ignored batches.IgnoredRepoSet) CheckingCache() CheckingCacheSuccess(cachedSpecsFound int, tasksToExecute int) diff --git a/internal/batches/ui/json_lines.go b/internal/batches/ui/json_lines.go index ceade9e4c0..54795ec6ba 100644 --- a/internal/batches/ui/json_lines.go +++ b/internal/batches/ui/json_lines.go @@ -66,22 +66,16 @@ func (ui *JSONLines) DeterminingWorkspaceCreatorTypeSuccess(wt workspace.Creator logOperationSuccess(batcheslib.LogEventOperationDeterminingWorkspaceType, &batcheslib.DeterminingWorkspaceTypeMetadata{Type: t}) } -func (ui *JSONLines) ResolvingRepositories() { - logOperationStart(batcheslib.LogEventOperationResolvingRepositories, &batcheslib.ResolvingRepositoriesMetadata{}) -} -func (ui *JSONLines) ResolvingRepositoriesDone(repos []*graphql.Repository, unsupported batches.UnsupportedRepoSet, ignored batches.IgnoredRepoSet) { - logOperationSuccess(batcheslib.LogEventOperationResolvingRepositories, &batcheslib.ResolvingRepositoriesMetadata{ - Unsupported: len(unsupported), - Ignored: len(ignored), - Count: len(repos), - }) -} - func (ui *JSONLines) DeterminingWorkspaces() { logOperationStart(batcheslib.LogEventOperationDeterminingWorkspaces, &batcheslib.DeterminingWorkspacesMetadata{}) } -func (ui *JSONLines) DeterminingWorkspacesSuccess(num int) { - logOperationSuccess(batcheslib.LogEventOperationDeterminingWorkspaces, &batcheslib.DeterminingWorkspacesMetadata{Count: num}) +func (ui *JSONLines) DeterminingWorkspacesSuccess(workspacesCount, reposCount int, unsupported batches.UnsupportedRepoSet, ignored batches.IgnoredRepoSet) { + logOperationSuccess(batcheslib.LogEventOperationDeterminingWorkspaces, &batcheslib.DeterminingWorkspacesMetadata{ + Unsupported: len(unsupported), + Ignored: len(ignored), + RepoCount: reposCount, + WorkspaceCount: workspacesCount, + }) } func (ui *JSONLines) CheckingCache() { diff --git a/internal/batches/ui/tui.go b/internal/batches/ui/tui.go index f146ab77fc..bedec35639 100644 --- a/internal/batches/ui/tui.go +++ b/internal/batches/ui/tui.go @@ -93,19 +93,19 @@ func (ui *TUI) DeterminingWorkspaceCreatorTypeSuccess(wt workspace.CreatorType) batchCompletePending(ui.pending, "Set workspace type") } -func (ui *TUI) ResolvingRepositories() { - ui.pending = batchCreatePending(ui.Out, "Resolving repositories") +func (ui *TUI) DeterminingWorkspaces() { + ui.pending = batchCreatePending(ui.Out, "Determining workspaces") } -func (ui *TUI) ResolvingRepositoriesDone(repos []*graphql.Repository, unsupported batches.UnsupportedRepoSet, ignored batches.IgnoredRepoSet) { - batchCompletePending(ui.pending, fmt.Sprintf("Resolved %d repositories", len(repos))) +func (ui *TUI) DeterminingWorkspacesSuccess(workspacesCount, reposCount int, unsupported batches.UnsupportedRepoSet, ignored batches.IgnoredRepoSet) { + batchCompletePending(ui.pending, fmt.Sprintf("Resolved %d workspaces from %d repositories", workspacesCount, reposCount)) - if unsupported != nil && len(unsupported) != 0 { + if len(unsupported) != 0 { block := ui.Out.Block(output.Line(" ", output.StyleWarning, "Some repositories are hosted on unsupported code hosts and will be skipped. Use the -allow-unsupported flag to avoid skipping them.")) for repo := range unsupported { block.Write(repo.Name) } block.Close() - } else if ignored != nil && len(ignored) != 0 { + } else if len(ignored) != 0 { block := ui.Out.Block(output.Line(" ", output.StyleWarning, "The repositories listed below contain .batchignore files and will be skipped. Use the -force-override-ignore flag to avoid skipping them.")) for repo := range ignored { block.Write(repo.Name) @@ -114,14 +114,6 @@ func (ui *TUI) ResolvingRepositoriesDone(repos []*graphql.Repository, unsupporte } } -func (ui *TUI) DeterminingWorkspaces() { - ui.pending = batchCreatePending(ui.Out, "Determining workspaces") -} - -func (ui *TUI) DeterminingWorkspacesSuccess(num int) { - batchCompletePending(ui.pending, fmt.Sprintf("Found %d workspaces with steps to execute", num)) -} - func (ui *TUI) CheckingCache() { ui.pending = batchCreatePending(ui.Out, "Checking cache for changeset specs") } From a415face7d6e31de21590cbb11de637d80300149 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Thu, 25 Aug 2022 20:38:38 +0200 Subject: [PATCH 229/647] Remove old feature gates from pre-4.0 (#822) --- cmd/src/batch_common.go | 42 +++----- cmd/src/batch_new.go | 2 +- cmd/src/batch_remote.go | 2 +- cmd/src/batch_repositories.go | 2 +- cmd/src/batch_validate.go | 2 +- go.mod | 4 +- go.sum | 8 +- internal/api/api.go | 31 +----- internal/batches/executor/coordinator.go | 8 +- internal/batches/executor/coordinator_test.go | 8 +- internal/batches/executor/executor_test.go | 13 --- internal/batches/features.go | 24 +---- internal/batches/graphql/batch_change.go | 5 - internal/batches/graphql/batches.go | 67 ++---------- internal/batches/graphql/campaigns.go | 64 ----------- internal/batches/graphql/common.go | 17 --- internal/batches/graphql/operations.go | 39 ------- internal/batches/service/remote.go | 23 ---- internal/batches/service/service.go | 101 +++++++++--------- internal/batches/ui/tui.go | 2 +- 20 files changed, 99 insertions(+), 365 deletions(-) delete mode 100644 internal/batches/graphql/batch_change.go delete mode 100644 internal/batches/graphql/campaigns.go delete mode 100644 internal/batches/graphql/common.go delete mode 100644 internal/batches/graphql/operations.go diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index cbd58b4e72..ff51ed64d3 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -177,37 +177,17 @@ func batchDefaultCacheDir() string { if err != nil { return "" } - - // Check if there's an old campaigns cache directory but not a new batch - // directory: if so, we should rename the old directory and carry on. - // - // TODO(campaigns-deprecation): we can remove this migration shim after June - // 2021. - old := path.Join(uc, "sourcegraph", "campaigns") dir := path.Join(uc, "sourcegraph", "batch") - if _, err := os.Stat(dir); os.IsNotExist(err) { - if _, err := os.Stat(old); os.IsExist(err) { - // We'll just try to do this without checking for an error: if it - // fails, we'll carry on and let the normal cache directory handling - // logic take care of it. - os.Rename(old, dir) - } - } return dir } // batchDefaultTempDirPrefix returns the prefix to be passed to ioutil.TempFile. -// If one of the environment variables SRC_BATCH_TMP_DIR or -// SRC_CAMPAIGNS_TMP_DIR is set, that is used as the prefix. Otherwise we use -// "/tmp". +// If the environment variable SRC_BATCH_TMP_DIR is set, that is used as the prefix. +// Otherwise we use "/tmp". func batchDefaultTempDirPrefix() string { - // TODO(campaigns-deprecation): we can remove this migration shim in - // Sourcegraph 4.0. - for _, env := range []string{"SRC_BATCH_TMP_DIR", "SRC_CAMPAIGNS_TMP_DIR"} { - if p := os.Getenv(env); p != "" { - return p - } + if p := os.Getenv("SRC_BATCH_TMP_DIR"); p != "" { + return p } // On macOS, we use an explicit prefix for our temp directories, because @@ -280,7 +260,7 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp imageCache := docker.NewImageCache() - if err := svc.DetermineFeatureFlags(ctx); err != nil { + if err := validateSourcegraphVersionConstraint(ctx, svc); err != nil { return err } @@ -399,7 +379,6 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp GlobalEnv: os.Environ(), IsRemote: false, }, - Features: svc.Features(), Logger: logManager, Cache: executor.NewDiskCache(opts.flags.cacheDir), GlobalEnv: os.Environ(), @@ -604,3 +583,14 @@ func getBatchParallelism(ctx context.Context, flag int) (int, error) { return docker.NCPU(ctx) } + +func validateSourcegraphVersionConstraint(ctx context.Context, svc *service.Service) error { + ffs, err := svc.DetermineFeatureFlags(ctx) + if err != nil { + return err + } + if ffs.Sourcegraph40 { + return nil + } + return errors.Newf("\n\n * Warning:\n This version of src-cli requires Sourcegraph version 4.0 or newer. If you're not on Sourcegraph 4.0 or newer, please use the 3.x release of src-cli that corresponds to your Sourcegraph version.\n\n") +} diff --git a/cmd/src/batch_new.go b/cmd/src/batch_new.go index 9d692e00ec..577da8bd4b 100644 --- a/cmd/src/batch_new.go +++ b/cmd/src/batch_new.go @@ -48,7 +48,7 @@ Examples: Client: cfg.apiClient(apiFlags, flagSet.Output()), }) - if err := svc.DetermineFeatureFlags(ctx); err != nil { + if err := validateSourcegraphVersionConstraint(ctx, svc); err != nil { return err } diff --git a/cmd/src/batch_remote.go b/cmd/src/batch_remote.go index 261831c11c..483e6e8db9 100644 --- a/cmd/src/batch_remote.go +++ b/cmd/src/batch_remote.go @@ -52,7 +52,7 @@ Examples: Client: cfg.apiClient(flags.api, flagSet.Output()), }) - if err := svc.DetermineFeatureFlags(ctx); err != nil { + if err := validateSourcegraphVersionConstraint(ctx, svc); err != nil { return err } diff --git a/cmd/src/batch_repositories.go b/cmd/src/batch_repositories.go index 3d92b578bb..31cbbf6d8c 100644 --- a/cmd/src/batch_repositories.go +++ b/cmd/src/batch_repositories.go @@ -64,7 +64,7 @@ Examples: Client: client, }) - if err := svc.DetermineFeatureFlags(ctx); err != nil { + if err := validateSourcegraphVersionConstraint(ctx, svc); err != nil { return err } diff --git a/cmd/src/batch_validate.go b/cmd/src/batch_validate.go index ae5b20e1e4..a9571348e9 100644 --- a/cmd/src/batch_validate.go +++ b/cmd/src/batch_validate.go @@ -63,7 +63,7 @@ Examples: Client: cfg.apiClient(apiFlags, flagSet.Output()), }) - if err := svc.DetermineFeatureFlags(ctx); err != nil { + if err := validateSourcegraphVersionConstraint(ctx, svc); err != nil { ui.ExecutionError(err) return err } diff --git a/go.mod b/go.mod index 9d37a66f31..b7e61b08bd 100644 --- a/go.mod +++ b/go.mod @@ -21,7 +21,7 @@ require ( github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf github.com/sourcegraph/scip v0.2.0 - github.com/sourcegraph/sourcegraph/lib v0.0.0-20220822143138-d621aac70d3d + github.com/sourcegraph/sourcegraph/lib v0.0.0-20220825181731-397a768a5290 github.com/stretchr/testify v1.7.2 golang.org/x/net v0.0.0-20220722155237-a158d28d115b golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4 @@ -103,7 +103,7 @@ require ( go.uber.org/zap v1.21.0 // indirect golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 // indirect golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 // indirect - golang.org/x/sys v0.0.0-20220818161305-2296e01440c6 // indirect + golang.org/x/sys v0.0.0-20220823224334-20c2bfdbfe24 // indirect golang.org/x/term v0.0.0-20220411215600-e5f449aeb171 // indirect golang.org/x/text v0.3.7 // indirect golang.org/x/tools v0.1.12 // indirect diff --git a/go.sum b/go.sum index fe55304b2e..bb2cb1200e 100644 --- a/go.sum +++ b/go.sum @@ -370,8 +370,8 @@ github.com/sourcegraph/log v0.0.0-20220707160925-6a936691c838 h1:8wknDSCUVYbaRT6 github.com/sourcegraph/log v0.0.0-20220707160925-6a936691c838/go.mod h1:zWEPlKrWBUVpko/tOgDS+qrp7BmzaCcmUrh9+ver1iQ= github.com/sourcegraph/scip v0.2.0 h1:Z9rR9TNONtRhqcpm0JP/yEBUy0fBKaSVbWIZKih5v04= github.com/sourcegraph/scip v0.2.0/go.mod h1:EYyT39nXdZDNVmgbJAlyIVWbEb1txnAOKpJPSYpvgXk= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20220822143138-d621aac70d3d h1:bUaXAbtXSWbcv8LjDwwYXo0grERhlOJDn2T8ROe/Mmc= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20220822143138-d621aac70d3d/go.mod h1:9wnFUNfpORLAOJn4XAO7ZeWnYkf6/CxlWaTU1vlpuKc= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20220825181731-397a768a5290 h1:SLCu3Rf1eLZ4sNKl0Bg1oURTgDxEutRCaTQt5dpVqH4= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20220825181731-397a768a5290/go.mod h1:9wnFUNfpORLAOJn4XAO7ZeWnYkf6/CxlWaTU1vlpuKc= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= @@ -535,8 +535,8 @@ golang.org/x/sys v0.0.0-20211102192858-4dd72447c267/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20211117180635-dee7805ff2e1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211213223007-03aa0b5f6827/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220818161305-2296e01440c6 h1:Sx/u41w+OwrInGdEckYmEuU5gHoGSL4QbDz3S9s6j4U= -golang.org/x/sys v0.0.0-20220818161305-2296e01440c6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220823224334-20c2bfdbfe24 h1:TyKJRhyo17yWxOMCTHKWrc5rddHORMlnZ/j57umaUd8= +golang.org/x/sys v0.0.0-20220823224334-20c2bfdbfe24/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20220411215600-e5f449aeb171 h1:EH1Deb8WZJ0xc0WK//leUHXcX9aLE5SymusoTmMZye8= golang.org/x/term v0.0.0-20220411215600-e5f449aeb171/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= diff --git a/internal/api/api.go b/internal/api/api.go index eaa3a39de7..25e87f814e 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -16,6 +16,7 @@ import ( ioaux "github.com/jig/teereadcloser" "github.com/kballard/go-shellquote" "github.com/mattn/go-isatty" + "github.com/sourcegraph/src-cli/internal/version" ) @@ -28,13 +29,6 @@ type Client interface { // NewRequest creates a GraphQL request. NewRequest(query string, vars map[string]interface{}) Request - // NewGzippedRequest creates a GraphQL request with gzip compression turned on. - NewGzippedRequest(query string, vars map[string]interface{}) Request - - // NewGzippedQuery is a convenience wrapper around NewQuery with gzip - // compression turned on. - NewGzippedQuery(query string) Request - // NewHTTPRequest creates an http.Request for the Sourcegraph API. // // path is joined against the API route. For example on Sourcegraph.com this @@ -72,7 +66,6 @@ type request struct { client *client query string vars map[string]interface{} - gzip bool } // ClientOpts encapsulates the options given to NewClient. @@ -132,19 +125,6 @@ func (c *client) NewRequest(query string, vars map[string]interface{}) Request { } } -func (c *client) NewGzippedRequest(query string, vars map[string]interface{}) Request { - return &request{ - client: c, - query: query, - vars: vars, - gzip: true, - } -} - -func (c *client) NewGzippedQuery(query string) Request { - return c.NewGzippedRequest(query, nil) -} - func (c *client) Do(req *http.Request) (*http.Response, error) { return c.httpClient.Do(req) } @@ -216,9 +196,7 @@ func (r *request) do(ctx context.Context, result interface{}) (bool, error) { } var bufBody io.Reader = bytes.NewBuffer(reqBody) - if r.gzip { - bufBody = gzipReader(bufBody) - } + bufBody = gzipReader(bufBody) // Create the HTTP request. req, err := r.client.NewHTTPRequest(ctx, "POST", ".api/graphql", bufBody) @@ -226,9 +204,8 @@ func (r *request) do(ctx context.Context, result interface{}) (bool, error) { return false, err } - if r.gzip { - req.Header.Set("Content-Encoding", "gzip") - } + // Use gzip compression. + req.Header.Set("Content-Encoding", "gzip") // Perform the request. resp, err := r.client.httpClient.Do(req) diff --git a/internal/batches/executor/coordinator.go b/internal/batches/executor/coordinator.go index 970ae6c555..77441f3717 100644 --- a/internal/batches/executor/coordinator.go +++ b/internal/batches/executor/coordinator.go @@ -9,7 +9,6 @@ import ( "github.com/sourcegraph/sourcegraph/lib/batches/execution" "github.com/sourcegraph/sourcegraph/lib/batches/execution/cache" - "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/log" ) @@ -34,8 +33,6 @@ type NewCoordinatorOpts struct { Logger log.LogManager GlobalEnv []string - // Used by batcheslib.BuildChangesetSpecs - Features batches.FeatureFlags IsRemote bool } @@ -124,10 +121,7 @@ func (c Coordinator) buildChangesetSpecs(task *Task, batchSpec *batcheslib.Batch }, } - return batcheslib.BuildChangesetSpecs(input, batcheslib.ChangesetSpecFeatureFlags{ - IncludeAutoAuthorDetails: c.opts.Features.IncludeAutoAuthorDetails, - AllowOptionalPublished: c.opts.Features.AllowOptionalPublished, - }) + return batcheslib.BuildChangesetSpecs(input) } func (c *Coordinator) loadCachedStepResults(ctx context.Context, task *Task, globalEnv []string) error { diff --git a/internal/batches/executor/coordinator_test.go b/internal/batches/executor/coordinator_test.go index 93cb69a4a2..5ac48da62d 100644 --- a/internal/batches/executor/coordinator_test.go +++ b/internal/batches/executor/coordinator_test.go @@ -82,7 +82,7 @@ func TestCoordinator_Execute(t *testing.T) { {task: sourcegraphTask, stepResults: []execution.AfterStepResult{{Diff: `dummydiff2`}}}, }, }, - opts: NewCoordinatorOpts{Features: featuresAllEnabled()}, + opts: NewCoordinatorOpts{}, wantCacheEntries: 2, wantSpecs: []*batcheslib.ChangesetSpec{ @@ -150,7 +150,7 @@ func TestCoordinator_Execute(t *testing.T) { }, }, }, - opts: NewCoordinatorOpts{Features: featuresAllEnabled()}, + opts: NewCoordinatorOpts{}, wantCacheEntries: 1, wantSpecs: []*batcheslib.ChangesetSpec{ @@ -201,7 +201,7 @@ func TestCoordinator_Execute(t *testing.T) { {task: sourcegraphTask, stepResults: []execution.AfterStepResult{{Diff: nestedChangesDiff}}}, }, }, - opts: NewCoordinatorOpts{Features: featuresAllEnabled()}, + opts: NewCoordinatorOpts{}, // TODO: Fix comment. // We have 4 ChangesetSpecs, but we only want 2 cache entries, @@ -249,7 +249,7 @@ func TestCoordinator_Execute(t *testing.T) { {task: sourcegraphTask, stepResults: []execution.AfterStepResult{{Diff: `dummydiff2`, StepIndex: 0}}}, }, }, - opts: NewCoordinatorOpts{Features: featuresAllEnabled()}, + opts: NewCoordinatorOpts{}, wantCacheEntries: 2, wantSpecs: []*batcheslib.ChangesetSpec{ diff --git a/internal/batches/executor/executor_test.go b/internal/batches/executor/executor_test.go index 9b9167956c..2a6040ffdc 100644 --- a/internal/batches/executor/executor_test.go +++ b/internal/batches/executor/executor_test.go @@ -25,7 +25,6 @@ import ( "github.com/sourcegraph/sourcegraph/lib/batches/template" "github.com/sourcegraph/src-cli/internal/api" - "github.com/sourcegraph/src-cli/internal/batches" "github.com/sourcegraph/src-cli/internal/batches/docker" "github.com/sourcegraph/src-cli/internal/batches/mock" "github.com/sourcegraph/src-cli/internal/batches/repozip" @@ -510,18 +509,6 @@ func addToPath(t *testing.T, relPath string) { os.Setenv("PATH", fmt.Sprintf("%s%c%s", dummyDockerPath, os.PathListSeparator, os.Getenv("PATH"))) } -func featuresAllEnabled() batches.FeatureFlags { - return batches.FeatureFlags{ - AllowArrayEnvironments: true, - IncludeAutoAuthorDetails: true, - UseGzipCompression: true, - AllowTransformChanges: true, - AllowWorkspaces: true, - AllowConditionalExec: true, - AllowOptionalPublished: true, - } -} - func TestExecutor_CachedStepResults(t *testing.T) { t.Run("single step cached", func(t *testing.T) { archive := mock.RepoArchive{ diff --git a/internal/batches/features.go b/internal/batches/features.go index c27e94596f..0a020b6bc6 100644 --- a/internal/batches/features.go +++ b/internal/batches/features.go @@ -9,16 +9,7 @@ import ( // FeatureFlags represent features that are only available on certain // Sourcegraph versions and we therefore have to detect at runtime. type FeatureFlags struct { - AllowArrayEnvironments bool - IncludeAutoAuthorDetails bool - UseGzipCompression bool - AllowTransformChanges bool - AllowWorkspaces bool - BatchChanges bool - AllowConditionalExec bool - AllowOptionalPublished bool - ServerSideBatchChanges bool - BitbucketCloud bool + Sourcegraph40 bool } func (ff *FeatureFlags) SetFromVersion(version string) error { @@ -34,16 +25,9 @@ func (ff *FeatureFlags) SetFromVersion(version string) error { // ">= 3.23.0". However, the same version IS considered to satisfy the constraint // "3.23.0-0". See // https://github.com/Masterminds/semver#working-with-prerelease-versions for more. - {&ff.AllowArrayEnvironments, ">= 3.23.0-0", "2020-11-24"}, - {&ff.IncludeAutoAuthorDetails, ">= 3.20.0-0", "2020-09-10"}, - {&ff.UseGzipCompression, ">= 3.21.0-0", "2020-10-12"}, - {&ff.AllowTransformChanges, ">= 3.23.0-0", "2020-12-11"}, - {&ff.AllowWorkspaces, ">= 3.25.0-0", "2021-01-29"}, - {&ff.BatchChanges, ">= 3.26.0-0", "2021-03-07"}, - {&ff.AllowConditionalExec, ">= 3.28.0-0", "2021-05-05"}, - {&ff.AllowOptionalPublished, ">= 3.30.0-0", "2021-06-21"}, - {&ff.ServerSideBatchChanges, ">= 3.37.0-0", "2022-02-08"}, - {&ff.BitbucketCloud, ">= 3.40.0-0", "2022-04-20"}, + // Example usage: + // {&ff.FlagName, ">= 3.23.0-0", "2020-11-24"}, + {&ff.Sourcegraph40, ">= 4.0.0-0", "2022-08-24"}, } { value, err := api.CheckSourcegraphVersion(version, feature.constraint, feature.minDate) if err != nil { diff --git a/internal/batches/graphql/batch_change.go b/internal/batches/graphql/batch_change.go deleted file mode 100644 index d29ee33c2e..0000000000 --- a/internal/batches/graphql/batch_change.go +++ /dev/null @@ -1,5 +0,0 @@ -package graphql - -type BatchChange struct { - URL string -} diff --git a/internal/batches/graphql/batches.go b/internal/batches/graphql/batches.go index 54fd1f26d8..5f8dfa84c8 100644 --- a/internal/batches/graphql/batches.go +++ b/internal/batches/graphql/batches.go @@ -1,66 +1,13 @@ package graphql -import ( - "context" -) +type BatchSpecID string +type ChangesetSpecID string -type batchesBackend struct { - commonBackend +type CreateBatchSpecResponse struct { + ID BatchSpecID + ApplyURL string } -var _ Operations = &batchesBackend{} - -const applyBatchChangeMutation = ` -mutation ApplyBatchChange($batchSpec: ID!) { - applyBatchChange(batchSpec: $batchSpec) { - ...batchChangeFields - } -} - -fragment batchChangeFields on BatchChange { - url -} -` - -func (bb *batchesBackend) ApplyBatchChange(ctx context.Context, batchSpecID BatchSpecID) (*BatchChange, error) { - var result struct { - BatchChange *BatchChange `json:"applyBatchChange"` - } - if ok, err := bb.newRequest(applyBatchChangeMutation, map[string]interface{}{ - "batchSpec": batchSpecID, - }).Do(ctx, &result); err != nil || !ok { - return nil, err - } - return result.BatchChange, nil -} - -const createBatchSpecMutation = ` -mutation CreateBatchSpec( - $namespace: ID!, - $spec: String!, - $changesetSpecs: [ID!]! -) { - createBatchSpec( - namespace: $namespace, - batchSpec: $spec, - changesetSpecs: $changesetSpecs - ) { - id - applyURL - } -} -` - -func (bb *batchesBackend) CreateBatchSpec(ctx context.Context, namespace, spec string, changesetSpecIDs []ChangesetSpecID) (*CreateBatchSpecResponse, error) { - var result struct { - CreateBatchSpec CreateBatchSpecResponse - } - if ok, err := bb.newRequest(createBatchSpecMutation, map[string]interface{}{ - "namespace": namespace, - "spec": spec, - "changesetSpecs": changesetSpecIDs, - }).Do(ctx, &result); err != nil || !ok { - return nil, err - } - return &result.CreateBatchSpec, nil +type BatchChange struct { + URL string } diff --git a/internal/batches/graphql/campaigns.go b/internal/batches/graphql/campaigns.go deleted file mode 100644 index a45abffef4..0000000000 --- a/internal/batches/graphql/campaigns.go +++ /dev/null @@ -1,64 +0,0 @@ -package graphql - -import "context" - -type campaignsBackend struct { - commonBackend -} - -var _ Operations = &campaignsBackend{} - -const applyCampaignMutation = ` -mutation ApplyCampaign($campaignSpec: ID!) { - applyCampaign(campaignSpec: $campaignSpec) { - ...campaignFields - } -} - -fragment campaignFields on Campaign { - url -} -` - -func (cb *campaignsBackend) ApplyBatchChange(ctx context.Context, batchSpecID BatchSpecID) (*BatchChange, error) { - var result struct { - BatchChange *BatchChange `json:"applyCampaign"` - } - if ok, err := cb.newRequest(applyCampaignMutation, map[string]interface{}{ - "campaignSpec": batchSpecID, - }).Do(ctx, &result); err != nil || !ok { - return nil, err - } - return result.BatchChange, nil -} - -const createCampaignSpecMutation = ` -mutation CreateCampaignSpec( - $namespace: ID!, - $spec: String!, - $changesetSpecs: [ID!]! -) { - createCampaignSpec( - namespace: $namespace, - campaignSpec: $spec, - changesetSpecs: $changesetSpecs - ) { - id - applyURL - } -} -` - -func (cb *campaignsBackend) CreateBatchSpec(ctx context.Context, namespace, spec string, changesetSpecIDs []ChangesetSpecID) (*CreateBatchSpecResponse, error) { - var result struct { - CreateCampaignSpec CreateBatchSpecResponse - } - if ok, err := cb.newRequest(createCampaignSpecMutation, map[string]interface{}{ - "namespace": namespace, - "spec": spec, - "changesetSpecs": changesetSpecIDs, - }).Do(ctx, &result); err != nil || !ok { - return nil, err - } - return &result.CreateCampaignSpec, nil -} diff --git a/internal/batches/graphql/common.go b/internal/batches/graphql/common.go deleted file mode 100644 index 1581ac9f53..0000000000 --- a/internal/batches/graphql/common.go +++ /dev/null @@ -1,17 +0,0 @@ -package graphql - -import ( - "github.com/sourcegraph/src-cli/internal/api" -) - -type commonBackend struct { - client api.Client - useGzipCompression bool -} - -func (b *commonBackend) newRequest(query string, vars map[string]interface{}) api.Request { - if b.useGzipCompression { - return b.client.NewGzippedRequest(query, vars) - } - return b.client.NewRequest(query, vars) -} diff --git a/internal/batches/graphql/operations.go b/internal/batches/graphql/operations.go deleted file mode 100644 index fe1b721543..0000000000 --- a/internal/batches/graphql/operations.go +++ /dev/null @@ -1,39 +0,0 @@ -package graphql - -import ( - "context" - - "github.com/sourcegraph/src-cli/internal/api" -) - -// Operations defines queries and mutations that are used by src-cli for Batch -// Change operations, and that vary between the old Campaigns world and the new -// Batch Changes world. -// -// TODO(campaigns-deprecation): this can be removed in Sourcegraph 4.0. -type Operations interface { - ApplyBatchChange(ctx context.Context, batchSpecID BatchSpecID) (*BatchChange, error) - CreateBatchSpec(ctx context.Context, namespace, spec string, changesetSpecIDs []ChangesetSpecID) (*CreateBatchSpecResponse, error) -} - -type BatchSpecID string -type ChangesetSpecID string - -type CreateBatchSpecResponse struct { - ID BatchSpecID - ApplyURL string -} - -func NewOperations(client api.Client, batchChanges, useGzipCompression bool) Operations { - backend := commonBackend{ - client: client, - useGzipCompression: useGzipCompression, - } - - if batchChanges { - return &batchesBackend{backend} - } - - return &campaignsBackend{backend} - -} diff --git a/internal/batches/service/remote.go b/internal/batches/service/remote.go index dc63a47daf..87733240b8 100644 --- a/internal/batches/service/remote.go +++ b/internal/batches/service/remote.go @@ -8,13 +8,6 @@ import ( var ErrServerSideBatchChangesUnsupported = errors.New("server side batch changes are not available on this Sourcegraph instance") -func (svc *Service) areServerSideBatchChangesSupported() error { - if !svc.features.ServerSideBatchChanges { - return ErrServerSideBatchChangesUnsupported - } - return nil -} - const upsertEmptyBatchChangeQuery = ` mutation UpsertEmptyBatchChange( $name: String! @@ -34,10 +27,6 @@ func (svc *Service) UpsertBatchChange( name string, namespaceID string, ) (string, error) { - if err := svc.areServerSideBatchChangesSupported(); err != nil { - return "", err - } - var resp struct { UpsertEmptyBatchChange struct { Name string `json:"name"` @@ -82,10 +71,6 @@ func (svc *Service) CreateBatchSpecFromRaw( allowUnsupported bool, noCache bool, ) (string, error) { - if err := svc.areServerSideBatchChangesSupported(); err != nil { - return "", err - } - var resp struct { CreateBatchSpecFromRaw struct { ID string `json:"id"` @@ -118,10 +103,6 @@ func (svc *Service) ExecuteBatchSpec( batchSpecID string, noCache bool, ) (string, error) { - if err := svc.areServerSideBatchChangesSupported(); err != nil { - return "", err - } - var resp struct { ExecuteBatchSpec struct { ID string `json:"id"` @@ -157,10 +138,6 @@ type BatchSpecWorkspaceResolution struct { } func (svc *Service) GetBatchSpecWorkspaceResolution(ctx context.Context, id string) (*BatchSpecWorkspaceResolution, error) { - if err := svc.areServerSideBatchChangesSupported(); err != nil { - return nil, err - } - var resp struct { Node struct { WorkspaceResolution BatchSpecWorkspaceResolution `json:"workspaceResolution"` diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index 7a8287f031..960de35283 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -23,8 +23,7 @@ import ( ) type Service struct { - client api.Client - features batches.FeatureFlags + client api.Client } type Opts struct { @@ -73,49 +72,70 @@ func (svc *Service) getSourcegraphVersion(ctx context.Context) (string, error) { return result.Site.ProductVersion, err } -// DetermineFeatureFlags fetches the version of the configured Sourcegraph -// instance and then sets flags on the Service itself to use features available -// in that version, e.g. gzip compression. -func (svc *Service) DetermineFeatureFlags(ctx context.Context) error { +// DetermineFeatureFlags fetches the version of the configured Sourcegraph and +// returns the enabled features. +func (svc *Service) DetermineFeatureFlags(ctx context.Context) (*batches.FeatureFlags, error) { version, err := svc.getSourcegraphVersion(ctx) if err != nil { - return errors.Wrap(err, "failed to query Sourcegraph version to check for available features") + return nil, errors.Wrap(err, "failed to query Sourcegraph version to check for available features") } - - return svc.SetFeatureFlagsForVersion(version) + ffs := &batches.FeatureFlags{} + return ffs, ffs.SetFromVersion(version) } -func (svc *Service) SetFeatureFlagsForVersion(version string) error { - return svc.features.SetFromVersion(version) +const applyBatchChangeMutation = ` +mutation ApplyBatchChange($batchSpec: ID!) { + applyBatchChange(batchSpec: $batchSpec) { + ...batchChangeFields + } } -// TODO(campaigns-deprecation): this shim can be removed in Sourcegraph 4.0. -func (svc *Service) newOperations() graphql.Operations { - return graphql.NewOperations( - svc.client, - svc.features.BatchChanges, - svc.features.UseGzipCompression, - ) +fragment batchChangeFields on BatchChange { + url } +` -func (svc *Service) newRequest(query string, vars map[string]interface{}) api.Request { - if svc.features.UseGzipCompression { - return svc.client.NewGzippedRequest(query, vars) +func (svc *Service) ApplyBatchChange(ctx context.Context, spec graphql.BatchSpecID) (*graphql.BatchChange, error) { + var result struct { + BatchChange *graphql.BatchChange `json:"applyBatchChange"` + } + if ok, err := svc.client.NewRequest(applyBatchChangeMutation, map[string]interface{}{ + "batchSpec": spec, + }).Do(ctx, &result); err != nil || !ok { + return nil, err } - return svc.client.NewRequest(query, vars) + return result.BatchChange, nil } -func (svc *Service) ApplyBatchChange(ctx context.Context, spec graphql.BatchSpecID) (*graphql.BatchChange, error) { - return svc.newOperations().ApplyBatchChange(ctx, spec) +const createBatchSpecMutation = ` +mutation CreateBatchSpec( + $namespace: ID!, + $spec: String!, + $changesetSpecs: [ID!]! +) { + createBatchSpec( + namespace: $namespace, + batchSpec: $spec, + changesetSpecs: $changesetSpecs + ) { + id + applyURL + } } +` func (svc *Service) CreateBatchSpec(ctx context.Context, namespace, spec string, ids []graphql.ChangesetSpecID) (graphql.BatchSpecID, string, error) { - result, err := svc.newOperations().CreateBatchSpec(ctx, namespace, spec, ids) - if err != nil { + var result struct { + CreateBatchSpec graphql.CreateBatchSpecResponse + } + if ok, err := svc.client.NewRequest(createBatchSpecMutation, map[string]interface{}{ + "namespace": namespace, + "spec": spec, + "changesetSpecs": ids, + }).Do(ctx, &result); err != nil || !ok { return "", "", err } - - return result.ID, result.ApplyURL, nil + return result.CreateBatchSpec.ID, result.CreateBatchSpec.ApplyURL, nil } const createChangesetSpecMutation = ` @@ -142,7 +162,7 @@ func (svc *Service) CreateChangesetSpec(ctx context.Context, spec *batcheslib.Ch ID string } } - if ok, err := svc.newRequest(createChangesetSpecMutation, map[string]interface{}{ + if ok, err := svc.client.NewRequest(createChangesetSpecMutation, map[string]interface{}{ "spec": string(raw), }).Do(ctx, &result); err != nil || !ok { return "", err @@ -196,7 +216,7 @@ func (svc *Service) ResolveWorkspacesForBatchSpec(ctx context.Context, spec *bat SearchResultPaths []string } } - if ok, err := svc.newRequest(resolveWorkspacesForBatchSpecQuery, map[string]interface{}{ + if ok, err := svc.client.NewRequest(resolveWorkspacesForBatchSpecQuery, map[string]interface{}{ "spec": string(raw), }).Do(ctx, &result); err != nil || !ok { return nil, nil, err @@ -364,10 +384,6 @@ func (svc *Service) BuildTasks(attributes *templatelib.BatchChangeAttributes, st return buildTasks(attributes, steps, workspaces) } -func (svc *Service) Features() batches.FeatureFlags { - return svc.features -} - func (svc *Service) CreateImportChangesetSpecs(ctx context.Context, batchSpec *batcheslib.BatchSpec) ([]*batcheslib.ChangesetSpec, error) { return batcheslib.BuildImportChangesetSpecs(ctx, batchSpec.ImportChangesets, func(ctx context.Context, repoNames []string) (_ map[string]string, errs error) { repoNameIDs := map[string]string{} @@ -451,11 +467,7 @@ func (e *duplicateBranchesErr) Error() string { } func (svc *Service) ParseBatchSpec(dir string, data []byte, isRemote bool) (*batcheslib.BatchSpec, error) { - spec, err := batcheslib.ParseBatchSpec(data, batcheslib.ParseBatchSpecOptions{ - AllowArrayEnvironments: svc.features.AllowArrayEnvironments, - AllowTransformChanges: svc.features.AllowTransformChanges, - AllowConditionalExec: svc.features.AllowConditionalExec, - }) + spec, err := batcheslib.ParseBatchSpec(data) if err != nil { return nil, errors.Wrap(err, "parsing batch spec") } @@ -530,11 +542,6 @@ changesetTemplate: message: Append Hello World to all README.md files ` -const exampleSpecPublishFlagTmpl = ` - # Change published to true once you're ready to create changesets on the code host. - published: false -` - func (svc *Service) GenerateExampleSpec(ctx context.Context, fileName string) error { // Try to create file. Bail out, if it already exists. f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0644) @@ -546,11 +553,7 @@ func (svc *Service) GenerateExampleSpec(ctx context.Context, fileName string) er } defer f.Close() - t := exampleSpecTmpl - if !svc.features.AllowOptionalPublished { - t += exampleSpecPublishFlagTmpl - } - tmpl, err := template.New("").Parse(t) + tmpl, err := template.New("").Parse(exampleSpecTmpl) if err != nil { return err } diff --git a/internal/batches/ui/tui.go b/internal/batches/ui/tui.go index bedec35639..ed3e5e3117 100644 --- a/internal/batches/ui/tui.go +++ b/internal/batches/ui/tui.go @@ -274,7 +274,7 @@ func prettyPrintBatchUnlicensedError(out *output.Output, err error) error { // verbose mode, but let the original error bubble up rather // than this one. out.Verbosef("Unexpected error parsing the GraphQL error: %v", cerr) - } else if code == "ErrCampaignsUnlicensed" || code == "ErrBatchChangesUnlicensed" { + } else if code == "ErrBatchChangesUnlicensed" { // OK, let's print a better message, then return an // exitCodeError to suppress the normal automatic error block. // Note that we have hand wrapped the output at 80 (printable) From 96c8c8cc0fdb23b85f8cad9053423279cb259b68 Mon Sep 17 00:00:00 2001 From: Idan Varsano Date: Thu, 25 Aug 2022 15:03:14 -0400 Subject: [PATCH 230/647] Fix over recursion of git serve (#810) * Fix over recursion of git serve --- CHANGELOG.md | 8 +++- internal/servegit/serve.go | 35 ++++++++------- internal/servegit/serve_test.go | 80 ++++++++------------------------- 3 files changed, 46 insertions(+), 77 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a1ea649adc..eba4031fac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,8 +17,13 @@ All notable changes to `src-cli` are documented in this file. ### Fixed +- Fixed a performance issue when serving git repos where it would take an exponentially large amount of time to list the repos. [#810](https://github.com/sourcegraph/src-cli/pull/810) +- Fixed Bare git repo support when serving git repos. [#810](https://github.com/sourcegraph/src-cli/pull/810) + ### Removed +- Removed git sub-repo support when serving git repos as it introduced a huge performance hit. [#810](https://github.com/sourcegraph/src-cli/pull/810) + ## 3.43.0 ### Changed @@ -40,6 +45,7 @@ All notable changes to `src-cli` are documented in this file. - INTERNAL ONLY: Fixed src batch exec not logging errors. + ## 3.42.2 ### Fixed @@ -833,4 +839,4 @@ Re-release of 3.29.3 for Sourcegraph 3.30. ### Changed - The terminal UI has been replaced by the logger-based UI that was previously only visible in verbose-mode (`-v`). [#228](https://github.com/sourcegraph/src-cli/pull/228) -- Deprecated the `-endpoint` flag. Instead, use the `SRC_ENDPOINT` environment variable. [#235](https://github.com/sourcegraph/src-cli/pull/235) +- Deprecated the `-endpoint` flag. Instead, use the `SRC_ENDPOINT` environment variable. [#235](https://github.com/sourcegraph/src-cli/pull/235) \ No newline at end of file diff --git a/internal/servegit/serve.go b/internal/servegit/serve.go index 1ee5c13320..4e3b99a2f1 100644 --- a/internal/servegit/serve.go +++ b/internal/servegit/serve.go @@ -60,8 +60,9 @@ var indexHTML = template.Must(template.New("").Parse(` `)) type Repo struct { - Name string - URI string + Name string + URI string + ClonePath string } func (s *Serve) handler() http.Handler { @@ -178,8 +179,8 @@ func (s *Serve) Repos() ([]Repo, error) { return nil } - // We recurse into bare repositories to find subprojects. Prevent - // recursing into .git + // Previously we recursed into bare repositories which is why this check was here. + // Now we use this as a sanity check to make sure we didn't somehow stumble into a .git dir. if filepath.Base(path) == ".git" { return filepath.SkipDir } @@ -204,20 +205,24 @@ func (s *Serve) Repos() ([]Repo, error) { name := filepath.ToSlash(subpath) reposRootIsRepo = reposRootIsRepo || name == "." - repos = append(repos, Repo{ - Name: name, - URI: pathpkg.Join("/repos", name), - }) + cloneURI := pathpkg.Join("/repos", name) + clonePath := cloneURI - // Check whether a repository is a bare repository or not. - // - // Bare repositories shouldn't have any further child - // repositories. Only regular git worktrees can have children. - if isBare { - return filepath.SkipDir + // Regular git repos won't clone without the full path to the .git directory. + if isGit { + clonePath += "/.git" } - return nil + repos = append(repos, Repo{ + Name: name, + URI: cloneURI, + ClonePath: clonePath, + }) + + // At this point we know the directory is either a git repo or a bare git repo, + // we don't need to recurse further to save time. + // TODO: Look into whether it is useful to support git submodules + return filepath.SkipDir }) if err != nil { diff --git a/internal/servegit/serve_test.go b/internal/servegit/serve_test.go index df80603666..b314b76de4 100644 --- a/internal/servegit/serve_test.go +++ b/internal/servegit/serve_test.go @@ -32,7 +32,7 @@ func TestReposHandler(t *testing.T) { repos: []string{"project1", "project2"}, }, { name: "nested", - repos: []string{"project1", "project1/subproject", "project2", "dir/project3", "dir/project4.bare"}, + repos: []string{"project1", "project2", "dir/project3", "dir/project4.bare"}, }} for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { @@ -47,65 +47,14 @@ func TestReposHandler(t *testing.T) { var want []Repo for _, name := range tc.repos { - want = append(want, Repo{Name: name, URI: path.Join("/repos", name)}) - } - testReposHandler(t, h, want) - }) - - // Now do the same test, but we root it under a repo we serve. This is - // to test we properly serve up the root repo as something other than - // "." - t.Run("rooted-"+tc.name, func(t *testing.T) { - repos := []string{"project-root"} - for _, name := range tc.repos { - repos = append(repos, filepath.Join("project-root", name)) - } - - root := gitInitRepos(t, repos...) - - // This is the difference to above, we point our root at the git repo - root = filepath.Join(root, "project-root") - - h := (&Serve{ - Info: testLogger(t), - Debug: discardLogger, - Addr: testAddress, - Root: root, - }).handler() - - // project-root is served from /repos, etc - want := []Repo{{Name: "project-root", URI: "/repos"}} - for _, name := range tc.repos { - want = append(want, Repo{Name: path.Join("project-root", name), URI: path.Join("/repos", name)}) - } - testReposHandler(t, h, want) - }) - - // Ensure everything still works if root is a symlink - t.Run("rooted-"+tc.name, func(t *testing.T) { - root := gitInitRepos(t, tc.repos...) - - // This is the difference, we create a symlink for root - { - tmp := t.TempDir() - - symlink := filepath.Join(tmp, "symlink-root") - if err := os.Symlink(root, symlink); err != nil { - t.Fatal(err) + isBare := strings.HasSuffix(name, ".bare") + uri := path.Join("/repos", name) + clonePath := uri + if !isBare { + clonePath += "/.git" } - root = symlink - } + want = append(want, Repo{Name: name, URI: uri, ClonePath: clonePath}) - h := (&Serve{ - Info: testLogger(t), - Debug: discardLogger, - Addr: testAddress, - Root: root, - }).handler() - - var want []Repo - for _, name := range tc.repos { - want = append(want, Repo{Name: name, URI: path.Join("/repos", name)}) } testReposHandler(t, h, want) }) @@ -173,6 +122,14 @@ func gitInitBare(t *testing.T, path string) { } } +func gitInit(t *testing.T, path string) { + cmd := exec.Command("git", "init") + cmd.Dir = path + if err := cmd.Run(); err != nil { + t.Fatal(err) + } +} + func gitInitRepos(t *testing.T, names ...string) string { root := t.TempDir() root = filepath.Join(root, "repos-root") @@ -183,10 +140,11 @@ func gitInitRepos(t *testing.T, names ...string) string { t.Fatal(err) } - if !strings.HasSuffix(p, ".bare") { - p = filepath.Join(p, ".git") + if strings.HasSuffix(p, ".bare") { + gitInitBare(t, p) + } else { + gitInit(t, p) } - gitInitBare(t, p) } return root From 812cde19b17fc6ca631f03c3abc02fd96d2272ce Mon Sep 17 00:00:00 2001 From: Thorsten Ball Date: Fri, 26 Aug 2022 10:16:39 +0200 Subject: [PATCH 231/647] src doc: add code-intel and remove lsif (#831) --- cmd/src/doc.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/src/doc.go b/cmd/src/doc.go index 1fb0254830..dc4e7a222c 100644 --- a/cmd/src/doc.go +++ b/cmd/src/doc.go @@ -58,7 +58,7 @@ Examples: "config": &configCommands, "extensions": &extensionsCommands, "extsvc": &extsvcCommands, - "lsif": &lsifCommands, + "code-intel": &codeintelCommands, "orgs": &orgsCommands, "orgs members": &orgsMembersCommands, "repos": &reposCommands, From 1ef0f08cca3da998bf042acf7a4f721ce92e34c8 Mon Sep 17 00:00:00 2001 From: Robert Lin Date: Thu, 1 Sep 2022 09:54:45 -0700 Subject: [PATCH 232/647] deps: upgrade github.com/sourcegraph/log (#835) --- go.mod | 19 +++++++++---------- go.sum | 44 +++++++++++++++++++++----------------------- 2 files changed, 30 insertions(+), 33 deletions(-) diff --git a/go.mod b/go.mod index b7e61b08bd..4688c68922 100644 --- a/go.mod +++ b/go.mod @@ -9,20 +9,20 @@ require ( github.com/dineshappavoo/basex v0.0.0-20170425072625-481a6f6dc663 github.com/dustin/go-humanize v1.0.0 github.com/gobwas/glob v0.2.3 - github.com/google/go-cmp v0.5.7 + github.com/google/go-cmp v0.5.8 github.com/grafana/regexp v0.0.0-20220304100321-149c8afcd6cb github.com/hexops/autogold v1.3.0 github.com/jig/teereadcloser v0.0.0-20181016160506-953720c48e05 github.com/json-iterator/go v1.1.12 github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 - github.com/mattn/go-isatty v0.0.14 + github.com/mattn/go-isatty v0.0.16 github.com/neelance/parallel v0.0.0-20160708114440-4de9ce63d14c github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf github.com/sourcegraph/scip v0.2.0 github.com/sourcegraph/sourcegraph/lib v0.0.0-20220825181731-397a768a5290 - github.com/stretchr/testify v1.7.2 + github.com/stretchr/testify v1.8.0 golang.org/x/net v0.0.0-20220722155237-a158d28d115b golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4 google.golang.org/protobuf v1.28.0 @@ -68,7 +68,7 @@ require ( github.com/kr/pretty v0.3.0 // indirect github.com/kr/text v0.2.0 // indirect github.com/lucasb-eyer/go-colorful v1.2.0 // indirect - github.com/mattn/go-colorable v0.1.12 // indirect + github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-runewidth v0.0.13 // indirect github.com/microcosm-cc/bluemonday v1.0.17 // indirect github.com/moby/term v0.0.0-20210619224110-3f7ff695adc6 // indirect @@ -85,10 +85,10 @@ require ( github.com/pseudomuto/protoc-gen-doc v1.5.1 // indirect github.com/pseudomuto/protokit v0.2.0 // indirect github.com/rivo/uniseg v0.2.0 // indirect - github.com/rogpeppe/go-internal v1.8.1 // indirect + github.com/rogpeppe/go-internal v1.9.0 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect github.com/shurcooL/go-goon v0.0.0-20210110234559-7585751d9a17 // indirect - github.com/sourcegraph/log v0.0.0-20220707160925-6a936691c838 // indirect + github.com/sourcegraph/log v0.0.0-20220901143117-fc0516a694c9 // indirect github.com/spf13/cobra v1.4.0 // indirect github.com/spf13/pflag v1.0.5 // indirect github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect @@ -98,16 +98,15 @@ require ( github.com/yuin/goldmark v1.4.13 // indirect github.com/yuin/goldmark-emoji v1.0.1 // indirect go.opencensus.io v0.23.0 // indirect - go.uber.org/atomic v1.9.0 // indirect + go.uber.org/atomic v1.10.0 // indirect go.uber.org/multierr v1.8.0 // indirect - go.uber.org/zap v1.21.0 // indirect + go.uber.org/zap v1.23.0 // indirect golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 // indirect golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 // indirect - golang.org/x/sys v0.0.0-20220823224334-20c2bfdbfe24 // indirect + golang.org/x/sys v0.0.0-20220829200755-d48e67d00261 // indirect golang.org/x/term v0.0.0-20220411215600-e5f449aeb171 // indirect golang.org/x/text v0.3.7 // indirect golang.org/x/tools v0.1.12 // indirect - golang.org/x/xerrors v0.0.0-20220609144429-65e65417b02f // indirect google.golang.org/genproto v0.0.0-20220414192740-2d67ff6cf2b4 // indirect google.golang.org/grpc v1.45.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect diff --git a/go.sum b/go.sum index bb2cb1200e..547852d34c 100644 --- a/go.sum +++ b/go.sum @@ -25,7 +25,6 @@ github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5 github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk= github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4= github.com/aymerick/raymond v2.0.3-0.20180322193309-b565731e1464+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g= -github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= github.com/benbjohnson/clock v1.3.0 h1:ip6w0uFQkncKQ979AypyG0ER7mqUSBdKLOgAle/AT8A= github.com/bufbuild/buf v1.4.0 h1:GqE3a8CMmcFvWPzuY3Mahf9Kf3S9XgZ/ORpfYFzO+90= github.com/bufbuild/buf v1.4.0/go.mod h1:mwHG7klTHnX+rM/ym8LXGl7vYpVmnwT96xWoRB4H5QI= @@ -156,8 +155,8 @@ github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.7 h1:81/ik6ipDQS2aGcBfIN5dHDB36BwrStyeAQquSYCV4o= -github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE= +github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg= +github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= @@ -258,15 +257,16 @@ github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVc github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-colorable v0.1.11/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= -github.com/mattn/go-colorable v0.1.12 h1:jF+Du6AlPIjs2BiUiQlKOX0rt3SujHxPnksPKZbaA40= -github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= +github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= +github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= github.com/mattn/go-isatty v0.0.7/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= github.com/mattn/go-isatty v0.0.9/go.mod h1:YNRxwqDuOph6SZLI9vUUz6OYw3QyUt7WiY2yME+cCiQ= github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/mattn/go-isatty v0.0.13/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= -github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9Y= github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= +github.com/mattn/go-isatty v0.0.16 h1:bq3VjFmv/sOjHtdEhmkEV4x1AJtvUvOJ2PFAZ5+peKQ= +github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk= github.com/mattn/go-runewidth v0.0.13 h1:lTGmDsbAYt5DmK6OnoV7EuIF1wEIFAcxld6ypU4OSgU= @@ -345,8 +345,9 @@ github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6L github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.6.2/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.8.1-0.20211023094830-115ce09fd6b4/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= -github.com/rogpeppe/go-internal v1.8.1 h1:geMPLpDpQOgVyCg5z5GoRwLHepNdb71NXb67XFkP+Eg= github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= +github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= +github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= @@ -366,8 +367,8 @@ github.com/sourcegraph/go-diff v0.6.1 h1:hmA1LzxW0n1c3Q4YbrFgg4P99GSnebYa3x8gr0H github.com/sourcegraph/go-diff v0.6.1/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= -github.com/sourcegraph/log v0.0.0-20220707160925-6a936691c838 h1:8wknDSCUVYbaRT63OD+Iyv+stwze5kE2FAzbA1HrNMA= -github.com/sourcegraph/log v0.0.0-20220707160925-6a936691c838/go.mod h1:zWEPlKrWBUVpko/tOgDS+qrp7BmzaCcmUrh9+ver1iQ= +github.com/sourcegraph/log v0.0.0-20220901143117-fc0516a694c9 h1:JjFyvx9hCD5+JpuRV6t+gTQgGFvwkxXMZzOc4sLiPqc= +github.com/sourcegraph/log v0.0.0-20220901143117-fc0516a694c9/go.mod h1:UxiwB6C3xk3xOySJpW1R0MDUyfGuJRFS5Z8C+SA5p2I= github.com/sourcegraph/scip v0.2.0 h1:Z9rR9TNONtRhqcpm0JP/yEBUy0fBKaSVbWIZKih5v04= github.com/sourcegraph/scip v0.2.0/go.mod h1:EYyT39nXdZDNVmgbJAlyIVWbEb1txnAOKpJPSYpvgXk= github.com/sourcegraph/sourcegraph/lib v0.0.0-20220825181731-397a768a5290 h1:SLCu3Rf1eLZ4sNKl0Bg1oURTgDxEutRCaTQt5dpVqH4= @@ -387,14 +388,16 @@ github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DM github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf h1:pvbZ0lM0XWPBqUKqFU8cmavspvIl9nulOYwdy6IFRRo= github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf/go.mod h1:RJID2RhlZKId02nZ62WenDCkgHFerpIOmW0iT7GKmXM= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.7.2 h1:4jaiDzPyXQvSd7D0EjG45355tLlV3VOECpq10pLC+8s= -github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc= github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw= github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= @@ -430,15 +433,13 @@ go.opencensus.io v0.23.0 h1:gqCw0LfLxScz8irSi8exQc7fyQ0fKQU/qnC/X8+V/1M= go.opencensus.io v0.23.0/go.mod h1:XItmlyltB5F7CS4xOC1DcqMoFqwtC6OG2xF7mCv7P7E= go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI= go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= -go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE= -go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= +go.uber.org/atomic v1.10.0 h1:9qC72Qh0+3MqyJbAn8YU5xVq1frD8bn3JtD2oXtafVQ= +go.uber.org/atomic v1.10.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= go.uber.org/goleak v1.1.11 h1:wy28qYRKZgnJTxGxvye5/wgWr1EKjmUDGYox5mGlRlI= -go.uber.org/goleak v1.1.11/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ= -go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= go.uber.org/multierr v1.8.0 h1:dg6GjLku4EH+249NNmoIciG9N/jURbDG+pFlTkhzIC8= go.uber.org/multierr v1.8.0/go.mod h1:7EAYxJLBy9rStEaz58O2t4Uvip6FSURkq8/ppBp95ak= -go.uber.org/zap v1.21.0 h1:WefMeulhovoZ2sYXz7st6K0sLj7bBhpiFaud4r4zST8= -go.uber.org/zap v1.21.0/go.mod h1:wjWOCqI0f2ZZrJF/UufIOkiC8ii6tm1iqIsLo76RfJw= +go.uber.org/zap v1.23.0 h1:OjGQ5KQDEUawVHxNwQgPpiypGHOxo2mNZsOqTak4fFY= +go.uber.org/zap v1.23.0/go.mod h1:D+nX8jyLsMHMYrln8A0rJjFt/T/9/bGgIhAqxv5URuY= golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= @@ -452,7 +453,6 @@ golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/lint v0.0.0-20210508222113-6edffad5e616/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= @@ -535,8 +535,9 @@ golang.org/x/sys v0.0.0-20211102192858-4dd72447c267/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20211117180635-dee7805ff2e1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211213223007-03aa0b5f6827/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220823224334-20c2bfdbfe24 h1:TyKJRhyo17yWxOMCTHKWrc5rddHORMlnZ/j57umaUd8= -golang.org/x/sys v0.0.0-20220823224334-20c2bfdbfe24/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220829200755-d48e67d00261 h1:v6hYoSR9T5oet+pMXwUWkbiVqx/63mlHjefrHmxwfeY= +golang.org/x/sys v0.0.0-20220829200755-d48e67d00261/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20220411215600-e5f449aeb171 h1:EH1Deb8WZJ0xc0WK//leUHXcX9aLE5SymusoTmMZye8= golang.org/x/term v0.0.0-20220411215600-e5f449aeb171/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= @@ -566,7 +567,6 @@ golang.org/x/tools v0.0.0-20210101214203-2dba1e4ea05c/go.mod h1:emZCQorbCU4vsT4f golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= -golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.8-0.20211102182255-bb4add04ddef/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= golang.org/x/tools v0.1.8/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= golang.org/x/tools v0.1.12 h1:VveCTK38A2rkS8ZqFY25HIDFscX5X9OoEhJd3quQmXU= @@ -575,8 +575,6 @@ golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8T golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20220609144429-65e65417b02f h1:uF6paiQQebLeSXkrTqHqz0MXhXXS1KgF41eUdBNvxK0= -golang.org/x/xerrors v0.0.0-20220609144429-65e65417b02f/go.mod h1:K8+ghG5WaK9qNqU5K3HdILfMLy1f3aNYFI/wnl100a8= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/genproto v0.0.0-20180518175338-11a468237815/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= From 6a997c087fffabcf4043eb2ad90c7cc43191bddb Mon Sep 17 00:00:00 2001 From: Keegan Carruthers-Smith Date: Wed, 7 Sep 2022 08:38:13 +0200 Subject: [PATCH 233/647] readme: add instructions for docker (#836) We received feedback that some users prefer using src-cli via docker. We publish an image for the purpose of serve-git, so was only documented there. This includes basic information for those inclined to use docker. --- README.markdown | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/README.markdown b/README.markdown index c56d24266b..e0f01030d4 100644 --- a/README.markdown +++ b/README.markdown @@ -63,6 +63,14 @@ chmod +x /usr/local/bin/src See [Sourcegraph CLI for Windows](WINDOWS.md). +### Installation: Docker + +`sourcegraph/src-cli` is published to Docker Hub. You can use the `latest` tag or a specific version such as `3.43`. To see all versions view [sourcegraph/src-cli tags](https://hub.docker.com/r/sourcegraph/src-cli/tags). + +```bash +docker run --rm=true sourcegraph/src-cli:latest search 'hello world' +``` + ## Log into your Sourcegraph instance Run src login SOURCEGRAPH-URL to authenticate `src` to access your Sourcegraph instance with your user credentials. From 8d1c2479ad8548cc317cd34d9d64ee80fd2b6586 Mon Sep 17 00:00:00 2001 From: Warren Gifford Date: Thu, 8 Sep 2022 13:43:05 -0700 Subject: [PATCH 234/647] Add `src users clean` to src-cli (#826) * register users clean * added usage statistics to User Node type * mark * define worker function for user removal * before implementing time.Parse(time.RFC3339, payload.UsageStatistics.LastActiveTime) * now computes time since last active * added utility function structure * initialize array to store users to be deleted * working query to remove users and flags * added a user verification to command * corrects logic around removeNeverActive flag * better warning messaging * formating warning * add flag to skip verify check * commented out placeholder code and added TODO comments * addressed many review concerns, added lower bound on -days flag, made better table * Update cmd/src/users.go Co-authored-by: Thorsten Ball * Update cmd/src/users_clean.go Co-authored-by: Thorsten Ball * Update cmd/src/users_clean.go Co-authored-by: Thorsten Ball * correct variable naming bug * remove unused params in get users query * Update cmd/src/users.go Co-authored-by: Joe Chen * admins must be explcitly removed * commit dependencies * camel case * ensure clean doesnt clean the user issuing the command Co-authored-by: Thorsten Ball Co-authored-by: Joe Chen --- cmd/src/users.go | 17 +++- cmd/src/users_clean.go | 212 +++++++++++++++++++++++++++++++++++++++++ go.mod | 1 + go.sum | 3 + 4 files changed, 230 insertions(+), 3 deletions(-) create mode 100644 cmd/src/users_clean.go diff --git a/cmd/src/users.go b/cmd/src/users.go index c189ae1b45..38d4cfdc00 100644 --- a/cmd/src/users.go +++ b/cmd/src/users.go @@ -20,6 +20,7 @@ The commands are: get gets a user create creates a user account delete deletes a user account + clean deletes inactive users tag add/remove a tag on a user Use "src users [command] -h" for more information about a command. @@ -57,7 +58,11 @@ fragment UserFields on User { } emails { email - verified + verified + } + usageStatistics { + lastActiveTime + lastActiveCodeHostIntegrationTime } url } @@ -71,11 +76,17 @@ type User struct { Organizations struct { Nodes []Org } - Emails []UserEmail - URL string + Emails []UserEmail + UsageStatistics UserUsageStatistics + URL string } type UserEmail struct { Email string Verified bool } + +type UserUsageStatistics struct { + LastActiveTime string + LastActiveCodeHostIntegrationTime string +} diff --git a/cmd/src/users_clean.go b/cmd/src/users_clean.go new file mode 100644 index 0000000000..adcd5ddbd7 --- /dev/null +++ b/cmd/src/users_clean.go @@ -0,0 +1,212 @@ +package main + +import ( + "context" + "flag" + "fmt" + "os" + "strings" + "time" + + "github.com/jedib0t/go-pretty/v6/table" + + "github.com/sourcegraph/src-cli/internal/api" +) + +func init() { + usage := ` +This command removes users from a Sourcegraph instance who have been inactive for 60 or more days. Admin accounts are omitted by default. + +Examples: + + $ src users clean -days 182 + + $ src users clean -remove-admin -remove-never-active +` + + flagSet := flag.NewFlagSet("clean", flag.ExitOnError) + usageFunc := func() { + fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src users %s':\n", flagSet.Name()) + flagSet.PrintDefaults() + fmt.Println(usage) + } + var ( + daysToDelete = flagSet.Int("days", 60, "Days threshold on which to remove users, must be 60 days or greater and defaults to this value ") + removeAdmin = flagSet.Bool("remove-admin", false, "clean admin accounts") + removeNoLastActive = flagSet.Bool("remove-never-active", false, "removes users with null lastActive value") + skipConfirmation = flagSet.Bool("force", false, "skips user confirmation step allowing programmatic use") + apiFlags = api.NewFlags(flagSet) + ) + + handler := func(args []string) error { + if err := flagSet.Parse(args); err != nil { + return err + } + if *daysToDelete < 60 { + fmt.Println("-days flag must be set to 60 or greater") + return nil + } + + ctx := context.Background() + client := cfg.apiClient(apiFlags, flagSet.Output()) + + currentUserQuery := ` +query { + currentUser { + username + } +} +` + var currentUserResult struct { + Data struct { + CurrentUser struct { + Username string + } + } + } + if ok, err := cfg.apiClient(apiFlags, flagSet.Output()).NewRequest(currentUserQuery, nil).DoRaw(context.Background(), ¤tUserResult); err != nil || !ok { + return err + } + fmt.Println(currentUserResult) + + usersQuery := ` +query Users() { + users() { + nodes { + ...UserFields + } + } +} +` + userFragment + + // get users to delete + var usersResult struct { + Users struct { + Nodes []User + } + } + if ok, err := client.NewRequest(usersQuery, nil).Do(ctx, &usersResult); err != nil || !ok { + return err + } + fmt.Println(usersResult) + + usersToDelete := make([]UserToDelete, 0) + for _, user := range usersResult.Users.Nodes { + daysSinceLastUse, wasLastActive, err := computeDaysSinceLastUse(user) + if err != nil { + return err + } + // never remove user issuing command + if user.Username == currentUserResult.Data.CurrentUser.Username { + continue + } + if !wasLastActive && !*removeNoLastActive { + continue + } + if !*removeAdmin && user.SiteAdmin { + continue + } + if daysSinceLastUse <= *daysToDelete && wasLastActive { + continue + } + deleteUser := UserToDelete{user, daysSinceLastUse} + + usersToDelete = append(usersToDelete, deleteUser) + } + + if *skipConfirmation { + for _, user := range usersToDelete { + if err := removeUser(user.User, client, ctx); err != nil { + return err + } + } + return nil + } + + // confirm and remove users + if confirmed, _ := confirmUserRemoval(usersToDelete); !confirmed { + fmt.Println("Aborting removal") + return nil + } else { + fmt.Println("REMOVING USERS") + for _, user := range usersToDelete { + if err := removeUser(user.User, client, ctx); err != nil { + return err + } + } + } + + return nil + } + + // Register the command. + usersCommands = append(usersCommands, &command{ + flagSet: flagSet, + handler: handler, + usageFunc: usageFunc, + }) +} + +// computes days since last usage from current day and time and UsageStatistics.LastActiveTime, uses time.Parse +func computeDaysSinceLastUse(user User) (timeDiff int, wasLastActive bool, _ error) { + // handle for null lastActiveTime returned from + if user.UsageStatistics.LastActiveTime == "" { + wasLastActive = false + return 0, wasLastActive, nil + } + timeLast, err := time.Parse(time.RFC3339, user.UsageStatistics.LastActiveTime) + if err != nil { + return 0, false, err + } + timeDiff = int(time.Since(timeLast).Hours() / 24) + + return timeDiff, true, err +} + +// Issue graphQL api request to remove user +func removeUser(user User, client api.Client, ctx context.Context) error { + query := `mutation DeleteUser($user: ID!) { + deleteUser(user: $user) { + alwaysNil + } +}` + vars := map[string]interface{}{ + "user": user.ID, + } + if ok, err := client.NewRequest(query, vars).Do(ctx, nil); err != nil || !ok { + return err + } + return nil +} + +type UserToDelete struct { + User User + DaysSinceLastUse int +} + +// Verify user wants to remove users with table of users and a command prompt for [y/N] +func confirmUserRemoval(usersToRemove []UserToDelete) (bool, error) { + fmt.Printf("Users to remove from instance at %s\n", cfg.Endpoint) + t := table.NewWriter() + t.SetOutputMirror(os.Stdout) + t.AppendHeader(table.Row{"Username", "Email", "Days Since Last Active"}) + for _, user := range usersToRemove { + if len(user.User.Emails) > 0 { + t.AppendRow([]interface{}{user.User.Username, user.User.Emails[0].Email, user.DaysSinceLastUse}) + t.AppendSeparator() + } else { + t.AppendRow([]interface{}{user.User.Username, "", user.DaysSinceLastUse}) + t.AppendSeparator() + } + } + t.SetStyle(table.StyleRounded) + t.Render() + input := "" + for strings.ToLower(input) != "y" && strings.ToLower(input) != "n" { + fmt.Printf("Do you wish to proceed with user removal [y/N]: ") + if _, err := fmt.Scanln(&input); err != nil { + return false, err + } + } + return strings.ToLower(input) == "y", nil +} diff --git a/go.mod b/go.mod index 4688c68922..923bcc71fb 100644 --- a/go.mod +++ b/go.mod @@ -12,6 +12,7 @@ require ( github.com/google/go-cmp v0.5.8 github.com/grafana/regexp v0.0.0-20220304100321-149c8afcd6cb github.com/hexops/autogold v1.3.0 + github.com/jedib0t/go-pretty/v6 v6.3.7 github.com/jig/teereadcloser v0.0.0-20181016160506-953720c48e05 github.com/json-iterator/go v1.1.12 github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 diff --git a/go.sum b/go.sum index 547852d34c..25ba1fefe8 100644 --- a/go.sum +++ b/go.sum @@ -198,6 +198,8 @@ github.com/iris-contrib/pongo2 v0.0.1/go.mod h1:Ssh+00+3GAZqSQb30AvBRNxBx7rf0Gqw github.com/iris-contrib/schema v0.0.1/go.mod h1:urYA3uvUNG1TIIjOSCzHr9/LmbQo8LrOcOqfqxa4hXw= github.com/jdxcode/netrc v0.0.0-20210204082910-926c7f70242a h1:d4+I1YEKVmWZrgkt6jpXBnLgV2ZjO0YxEtLDdfIZfH4= github.com/jdxcode/netrc v0.0.0-20210204082910-926c7f70242a/go.mod h1:Zi/ZFkEqFHTm7qkjyNJjaWH4LQA9LQhGJyF0lTYGpxw= +github.com/jedib0t/go-pretty/v6 v6.3.7 h1:H3Ulkf7h6A+p0HgKBGzgDn0bZIupRbKKWF4pO4Bs7iA= +github.com/jedib0t/go-pretty/v6 v6.3.7/go.mod h1:MgmISkTWDSFu0xOqiZ0mKNntMQ2mDgOcwOkwBEkMDJI= github.com/jhump/gopoet v0.0.0-20190322174617-17282ff210b3/go.mod h1:me9yfT6IJSlOL3FCfrg+L6yzUEZ+5jW6WHt4Sk+UPUI= github.com/jhump/gopoet v0.1.0/go.mod h1:me9yfT6IJSlOL3FCfrg+L6yzUEZ+5jW6WHt4Sk+UPUI= github.com/jhump/goprotoc v0.5.0/go.mod h1:VrbvcYrQOrTi3i0Vf+m+oqQWk9l72mjkJCYo7UvLHRQ= @@ -396,6 +398,7 @@ github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5 github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.4/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc= From 70466eb1c74a2af4a875434f8c300f5d180b6a95 Mon Sep 17 00:00:00 2001 From: Warren Gifford Date: Fri, 9 Sep 2022 11:16:41 -0700 Subject: [PATCH 235/647] removed development printlns :facepalm: (#838) --- cmd/src/users_clean.go | 2 -- 1 file changed, 2 deletions(-) diff --git a/cmd/src/users_clean.go b/cmd/src/users_clean.go index adcd5ddbd7..4651383dc4 100644 --- a/cmd/src/users_clean.go +++ b/cmd/src/users_clean.go @@ -67,7 +67,6 @@ query { if ok, err := cfg.apiClient(apiFlags, flagSet.Output()).NewRequest(currentUserQuery, nil).DoRaw(context.Background(), ¤tUserResult); err != nil || !ok { return err } - fmt.Println(currentUserResult) usersQuery := ` query Users() { @@ -88,7 +87,6 @@ query Users() { if ok, err := client.NewRequest(usersQuery, nil).Do(ctx, &usersResult); err != nil || !ok { return err } - fmt.Println(usersResult) usersToDelete := make([]UserToDelete, 0) for _, user := range usersResult.Users.Nodes { From 2e0a0283fcc6842cf96421876caf6bb2ad47f232 Mon Sep 17 00:00:00 2001 From: Adam Harvey Date: Fri, 9 Sep 2022 16:55:30 -0700 Subject: [PATCH 236/647] doc: tinker with the help for -clean-archives for clarity (#839) Fixes sourcegraph/sourcegraph#36304. --- cmd/src/batch_common.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index ff51ed64d3..20691ed2b2 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -137,7 +137,7 @@ func newBatchExecuteFlags(flagSet *flag.FlagSet, cacheDir, tempDir string) *batc flagSet.BoolVar( &caf.cleanArchives, "clean-archives", true, - "If true, deletes downloaded repository archives after executing batch spec steps.", + "If true, deletes downloaded repository archives after executing batch spec steps. Note that only the archives related to the actual repositories matched by the batch spec will be cleaned up, and clean up will not occur if src exits unexpectedly.", ) flagSet.BoolVar( From 756a50e611570bd49a60b0ce7c10dd4cb96fa02c Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Sat, 10 Sep 2022 07:12:28 +0200 Subject: [PATCH 237/647] Add changelog entry for 3.43.2 (#837) ..and 3.43.1 since we seemingly have missed that. --- CHANGELOG.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index eba4031fac..f460f2286f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,18 @@ All notable changes to `src-cli` are documented in this file. - Removed git sub-repo support when serving git repos as it introduced a huge performance hit. [#810](https://github.com/sourcegraph/src-cli/pull/810) +## 3.43.2 + +### Added + +- `src users cleanup` has been added. [#826](https://github.com/sourcegraph/src-cli/pull/826) + +## 3.43.1 + +### Changed + +- `src extensions` subcommands are now deprecated, and will be removed in Sourcegraph 4.0. + ## 3.43.0 ### Changed From 6a43f0c1a1b6450c5848a22c43523d343b3c7d9e Mon Sep 17 00:00:00 2001 From: Randell Callahan Date: Tue, 20 Sep 2022 12:49:50 -0500 Subject: [PATCH 238/647] batches: Fix remote command - Batch Change ID not provided (#842) --- cmd/src/batch_remote.go | 3 +- go.mod | 1 + go.sum | 1 + internal/api/mock/api.go | 78 ++++++++++ internal/batches/service/remote.go | 12 +- internal/batches/service/remote_test.go | 193 ++++++++++++++++++++++++ 6 files changed, 284 insertions(+), 4 deletions(-) create mode 100644 internal/api/mock/api.go create mode 100644 internal/batches/service/remote_test.go diff --git a/cmd/src/batch_remote.go b/cmd/src/batch_remote.go index 483e6e8db9..25768f8052 100644 --- a/cmd/src/batch_remote.go +++ b/cmd/src/batch_remote.go @@ -79,7 +79,7 @@ Examples: ui.ResolvingNamespaceSuccess(namespace.ID) ui.SendingBatchChange() - batchChangeName, err := svc.UpsertBatchChange(ctx, spec.Name, namespace.ID) + batchChangeID, batchChangeName, err := svc.UpsertBatchChange(ctx, spec.Name, namespace.ID) if err != nil { return err } @@ -93,6 +93,7 @@ Examples: flags.allowIgnored, flags.allowUnsupported, flags.clearCache, + batchChangeID, ) if err != nil { return err diff --git a/go.mod b/go.mod index 923bcc71fb..d4a955e26d 100644 --- a/go.mod +++ b/go.mod @@ -93,6 +93,7 @@ require ( github.com/spf13/cobra v1.4.0 // indirect github.com/spf13/pflag v1.0.5 // indirect github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect + github.com/stretchr/objx v0.4.0 // indirect github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect github.com/xeipuuv/gojsonschema v1.2.0 // indirect diff --git a/go.sum b/go.sum index 25ba1fefe8..85775bb7cc 100644 --- a/go.sum +++ b/go.sum @@ -390,6 +390,7 @@ github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DM github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf h1:pvbZ0lM0XWPBqUKqFU8cmavspvIl9nulOYwdy6IFRRo= github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf/go.mod h1:RJID2RhlZKId02nZ62WenDCkgHFerpIOmW0iT7GKmXM= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0 h1:M2gUjqZET1qApGOWNSnZ49BAIMX4F/1plDv3+l31EJ4= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= diff --git a/internal/api/mock/api.go b/internal/api/mock/api.go new file mode 100644 index 0000000000..43e7f795a7 --- /dev/null +++ b/internal/api/mock/api.go @@ -0,0 +1,78 @@ +package mock + +import ( + "context" + "encoding/json" + "io" + "net/http" + + "github.com/sourcegraph/src-cli/internal/api" + "github.com/stretchr/testify/mock" +) + +type Client struct { + mock.Mock +} + +func (m *Client) NewQuery(query string) api.Request { + args := m.Called(query) + return args.Get(0).(api.Request) +} + +func (m *Client) NewRequest(query string, vars map[string]interface{}) 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 { + args := m.Called(query, vars) + return args.Get(0).(api.Request) +} + +func (m *Client) NewGzippedQuery(query string) api.Request { + args := m.Called(query) + return args.Get(0).(api.Request) +} + +func (m *Client) NewHTTPRequest(ctx context.Context, method, path string, body io.Reader) (*http.Request, error) { + args := m.Called(ctx, method, path, body) + var obj *http.Request + if args.Get(0) != nil { + obj = args.Get(0).(*http.Request) + } + return obj, args.Error(1) +} + +func (m *Client) Do(req *http.Request) (*http.Response, error) { + args := m.Called(req) + var obj *http.Response + if args.Get(0) != nil { + obj = args.Get(0).(*http.Response) + } + return obj, args.Error(1) +} + +type Request struct { + mock.Mock + Response string +} + +func (r *Request) Do(ctx context.Context, result interface{}) (bool, error) { + args := r.Called(ctx, result) + if r.Response != "" { + if err := json.Unmarshal([]byte(r.Response), result); err != nil { + return false, err + } + } + return args.Bool(0), args.Error(1) +} + +func (r *Request) DoRaw(ctx context.Context, result interface{}) (bool, error) { + args := r.Called(ctx, result) + if r.Response != "" { + if err := json.Unmarshal([]byte(r.Response), result); err != nil { + return false, err + } + } + return args.Bool(0), args.Error(1) +} diff --git a/internal/batches/service/remote.go b/internal/batches/service/remote.go index 87733240b8..6d4577812b 100644 --- a/internal/batches/service/remote.go +++ b/internal/batches/service/remote.go @@ -17,6 +17,7 @@ mutation UpsertEmptyBatchChange( name: $name, namespace: $namespace ) { + id name } } @@ -26,9 +27,10 @@ func (svc *Service) UpsertBatchChange( ctx context.Context, name string, namespaceID string, -) (string, error) { +) (string, string, error) { var resp struct { UpsertEmptyBatchChange struct { + ID string `json:"id"` Name string `json:"name"` } `json:"upsertEmptyBatchChange"` } @@ -37,10 +39,10 @@ func (svc *Service) UpsertBatchChange( "name": name, "namespace": namespaceID, }).Do(ctx, &resp); err != nil || !ok { - return "", err + return "", "", err } - return resp.UpsertEmptyBatchChange.Name, nil + return resp.UpsertEmptyBatchChange.ID, resp.UpsertEmptyBatchChange.Name, nil } const createBatchSpecFromRawQuery = ` @@ -50,6 +52,7 @@ mutation CreateBatchSpecFromRaw( $allowIgnored: Boolean!, $allowUnsupported: Boolean!, $noCache: Boolean!, + $batchChange: ID!, ) { createBatchSpecFromRaw( batchSpec: $batchSpec, @@ -57,6 +60,7 @@ mutation CreateBatchSpecFromRaw( allowIgnored: $allowIgnored, allowUnsupported: $allowUnsupported, noCache: $noCache, + batchChange: $batchChange, ) { id } @@ -70,6 +74,7 @@ func (svc *Service) CreateBatchSpecFromRaw( allowIgnored bool, allowUnsupported bool, noCache bool, + batchChange string, ) (string, error) { var resp struct { CreateBatchSpecFromRaw struct { @@ -83,6 +88,7 @@ func (svc *Service) CreateBatchSpecFromRaw( "allowIgnored": allowIgnored, "allowUnsupported": allowUnsupported, "noCache": noCache, + "batchChange": batchChange, }).Do(ctx, &resp); err != nil || !ok { return "", err } diff --git a/internal/batches/service/remote_test.go b/internal/batches/service/remote_test.go new file mode 100644 index 0000000000..6cbfecaa2b --- /dev/null +++ b/internal/batches/service/remote_test.go @@ -0,0 +1,193 @@ +package service_test + +import ( + "context" + "encoding/json" + "testing" + + mockclient "github.com/sourcegraph/src-cli/internal/api/mock" + "github.com/sourcegraph/src-cli/internal/batches/service" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +func TestService_UpsertBatchChange(t *testing.T) { + client := new(mockclient.Client) + mockRequest := new(mockclient.Request) + svc := service.New(&service.Opts{Client: client}) + + tests := []struct { + name string + + mockInvokes func() + + requestName string + requestNamespaceID string + + expectedID string + expectedName string + expectedErr error + }{ + { + name: "New Batch Change", + mockInvokes: func() { + client.On("NewRequest", mock.Anything, map[string]interface{}{ + "name": "my-change", + "namespace": "my-namespace", + }). + Return(mockRequest, nil). + Once() + mockRequest.On("Do", mock.Anything, mock.Anything). + Run(func(args mock.Arguments) { + json.Unmarshal([]byte(`{"upsertEmptyBatchChange":{"id":"123", "name":"my-change"}}`), &args[1]) + }). + Return(true, nil). + Once() + }, + requestName: "my-change", + requestNamespaceID: "my-namespace", + expectedID: "123", + expectedName: "my-change", + }, + { + name: "Failed to upsert batch change", + mockInvokes: func() { + client.On("NewRequest", mock.Anything, map[string]interface{}{ + "name": "my-change", + "namespace": "my-namespace", + }). + Return(mockRequest, nil). + Once() + mockRequest.On("Do", mock.Anything, mock.Anything). + Return(false, errors.New("did not get a good response code")). + Once() + }, + requestName: "my-change", + requestNamespaceID: "my-namespace", + expectedErr: errors.New("did not get a good response code"), + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if test.mockInvokes != nil { + test.mockInvokes() + } + + id, name, err := svc.UpsertBatchChange(context.Background(), test.requestName, test.requestNamespaceID) + assert.Equal(t, test.expectedID, id) + assert.Equal(t, test.expectedName, name) + if test.expectedErr != nil { + assert.Error(t, err) + assert.Equal(t, test.expectedErr.Error(), err.Error()) + } else { + assert.NoError(t, err) + } + + client.AssertExpectations(t) + }) + } +} + +func TestService_CreateBatchSpecFromRaw(t *testing.T) { + client := new(mockclient.Client) + mockRequest := new(mockclient.Request) + svc := service.New(&service.Opts{Client: client}) + + tests := []struct { + name string + + mockInvokes func() + + requestBatchSpec string + requestNamespaceID string + requestAllowIgnored bool + requestAllowUnsupported bool + requestNoCache bool + requestBatchChange string + + expectedID string + expectedErr error + }{ + { + name: "Create batch spec", + mockInvokes: func() { + client.On("NewRequest", mock.Anything, map[string]interface{}{ + "batchSpec": "abc", + "namespace": "some-namespace", + "allowIgnored": false, + "allowUnsupported": false, + "noCache": false, + "batchChange": "123", + }). + Return(mockRequest, nil). + Once() + mockRequest.On("Do", mock.Anything, mock.Anything). + Run(func(args mock.Arguments) { + json.Unmarshal([]byte(`{"createBatchSpecFromRaw":{"id":"xyz"}}`), &args[1]) + }). + Return(true, nil). + Once() + }, + requestBatchSpec: "abc", + requestNamespaceID: "some-namespace", + requestAllowIgnored: false, + requestAllowUnsupported: false, + requestNoCache: false, + requestBatchChange: "123", + expectedID: "xyz", + }, + { + name: "Failed to create batch spec", + mockInvokes: func() { + client.On("NewRequest", mock.Anything, map[string]interface{}{ + "batchSpec": "abc", + "namespace": "some-namespace", + "allowIgnored": false, + "allowUnsupported": false, + "noCache": false, + "batchChange": "123", + }). + Return(mockRequest, nil). + Once() + mockRequest.On("Do", mock.Anything, mock.Anything). + Return(false, errors.New("did not get a good response code")). + Once() + }, + requestBatchSpec: "abc", + requestNamespaceID: "some-namespace", + requestAllowIgnored: false, + requestAllowUnsupported: false, + requestNoCache: false, + requestBatchChange: "123", + expectedErr: errors.New("did not get a good response code"), + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if test.mockInvokes != nil { + test.mockInvokes() + } + + id, err := svc.CreateBatchSpecFromRaw( + context.Background(), + test.requestBatchSpec, + test.requestNamespaceID, + test.requestAllowIgnored, + test.requestAllowUnsupported, + test.requestNoCache, + test.requestBatchChange, + ) + assert.Equal(t, test.expectedID, id) + if test.expectedErr != nil { + assert.Error(t, err) + assert.Equal(t, test.expectedErr.Error(), err.Error()) + } else { + assert.NoError(t, err) + } + + client.AssertExpectations(t) + }) + } +} From 692663ed8f82eb56fcc85c10214bdea1f8651dee Mon Sep 17 00:00:00 2001 From: Adam Harvey Date: Tue, 20 Sep 2022 19:37:34 -0500 Subject: [PATCH 239/647] changelog: 4.0.0 (#843) --- CHANGELOG.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index f460f2286f..0669508cfa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,12 @@ All notable changes to `src-cli` are documented in this file. ### Fixed +### Removed + +## 4.0.0 + +### Fixed + - Fixed a performance issue when serving git repos where it would take an exponentially large amount of time to list the repos. [#810](https://github.com/sourcegraph/src-cli/pull/810) - Fixed Bare git repo support when serving git repos. [#810](https://github.com/sourcegraph/src-cli/pull/810) From cb9c49f216b3f8a62ed6db63b9eb19d2127d0388 Mon Sep 17 00:00:00 2001 From: Adam Harvey Date: Tue, 20 Sep 2022 21:12:41 -0500 Subject: [PATCH 240/647] Revert 4.0-pre changes (#828) --- .goreleaser.yml | 5 +---- DEVELOPMENT.md | 18 ------------------ 2 files changed, 1 insertion(+), 22 deletions(-) diff --git a/.goreleaser.yml b/.goreleaser.yml index 0b6800ddaa..4db476ce7d 100644 --- a/.goreleaser.yml +++ b/.goreleaser.yml @@ -50,13 +50,10 @@ dockers: - "sourcegraph/src-cli:{{ .Tag }}" - "sourcegraph/src-cli:{{ .Major }}" - "sourcegraph/src-cli:{{ .Major }}.{{ .Minor }}" - # Disabled until 4.0 stable is released. - #- "sourcegraph/src-cli:latest" + - "sourcegraph/src-cli:latest" changelog: sort: asc filters: exclude: - '^docs:' - '^test:' -release: - prerelease: true diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index 3f45f144a7..ca256d7288 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -1,23 +1,5 @@ This file covers things that are good to know if you're developing or maintaining `src`. It is likely incomplete, and contributions would be most welcome! -## Things are a bit weird right now, August-September 2022 edition - -With 3.43 having been released, we now want to remove a bunch of old backward compatibility code before 4.0 is released in late September. However, we also need to be able to fix bugs and make 3.43.x releases in the interim. - -**Until 4.0 is released, `main` is the 4.0 branch.** - -### Releasing a 3.43.x bug fix - -You must merge the fix into **both** the `3.43` and `main` branches. Then [perform the release normally](#releasing), except note that you **must** be on the `3.43` branch when you run `./release.sh`. - -### Releasing a 4.0 pre-release - -[Perform the release normally](#releasing), but be careful to use a version number that is clearly a pre-release, specifically in the format `4.0.0-rc.X`, where `X` is one higher than the previous pre-release. - -### Releasing 4.0 proper - -If you're reading this because you're about to release the stable 4.0.0 release, please merge #828 first to put the release machinery back the way it was. - ## Contents * [Developing `src`](#development) From 1dab5b2e2bb31adc2930b66b6972253a3d114b4c Mon Sep 17 00:00:00 2001 From: Bolaji Olajide <25608335+BolajiOlajide@users.noreply.github.com> Date: Tue, 27 Sep 2022 22:17:55 +0100 Subject: [PATCH 241/647] batches: check that docker is running when running src batch (#844) * check docker version before batch * remove debug statement * create wrapper for fastcontext * move executeFastCommand into context.go * cleanup --- cmd/src/batch_common.go | 12 ++++++++---- internal/batches/docker/context.go | 18 ++++++++++++++++++ internal/batches/docker/version.go | 21 +++++++++++++++++++++ 3 files changed, 47 insertions(+), 4 deletions(-) create mode 100644 internal/batches/docker/version.go diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index 20691ed2b2..a9706d1fba 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -268,9 +268,13 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp return err } - // In the past, we checked `docker version`, but now we retrieve the number - // of CPUs, since we need that anyway and it performs the same check (is - // Docker working _at all_?). + // In the past, we relied on `getBatchParallelism` to ascertain if docker is running, + // however, we don't always check for the number of CPUs (especially when the -j parallelis) + // flag is passed. This is a more explicit check to confirm docker is working. + if err := docker.CheckVersion(ctx); err != nil { + return err + } + parallelism, err := getBatchParallelism(ctx, opts.flags.parallelism) if err != nil { return err @@ -547,7 +551,7 @@ func parseBatchSpec(ctx context.Context, file string, svc *service.Service, isRe func checkExecutable(cmd string, args ...string) error { if err := exec.Command(cmd, args...).Run(); err != nil { return fmt.Errorf( - "failed to execute \"%s %s\":\n\t%s\n\n'src batch' require %q to be available.", + "failed to execute \"%s %s\":\n\t%s\n\n'src batch' requires %q to be available.", cmd, strings.Join(args, " "), err, diff --git a/internal/batches/docker/context.go b/internal/batches/docker/context.go index c8bd052fc8..5d4a8fdb19 100644 --- a/internal/batches/docker/context.go +++ b/internal/batches/docker/context.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "os" + "os/exec" "sync" "time" @@ -94,3 +95,20 @@ func fastCommandTimeout() (time.Duration, error) { return fastCommandTimeoutData.timeout, fastCommandTimeoutData.err } + +// executeFastCommand creates a fastCommandContext used to execute docker commands +// with a timeout for docker commands that are supposed to be fast (e.g docker info). +func executeFastCommand(ctx context.Context, args ...string) ([]byte, error) { + dctx, cancel, err := withFastCommandContext(ctx) + if err != nil { + return nil, err + } + defer cancel() + + out, err := exec.CommandContext(dctx, "docker", args...).CombinedOutput() + if errors.IsDeadlineExceeded(err) || errors.IsDeadlineExceeded(dctx.Err()) { + return nil, newFastCommandTimeoutError(dctx, args...) + } + + return out, err +} diff --git a/internal/batches/docker/version.go b/internal/batches/docker/version.go new file mode 100644 index 0000000000..84cfdcd1e7 --- /dev/null +++ b/internal/batches/docker/version.go @@ -0,0 +1,21 @@ +package docker + +import ( + "context" + "fmt" +) + +// CheckVersion is used to check if docker is running. We use this method instead of +// checkExecutable (https://sourcegraph.com/github.com/sourcegraph/src-cli@main/-/blob/cmd/src/batch_common.go?L547%3A6=&popover=pinned) +// to prevent a case where docker commands take too long and results in `src-cli` freezing for some users. +func CheckVersion(ctx context.Context) error { + _, err := executeFastCommand(ctx, "version") + if err != nil { + return fmt.Errorf( + "failed to execute \"docker version\":\n\t%s\n\n'src batch' requires \"docker\" to be available.", + err, + ) + } + + return nil +} From 0f2ef91847ddc1b7b927045a8aafe2a13df742b3 Mon Sep 17 00:00:00 2001 From: Varun Gandhi Date: Thu, 29 Sep 2022 21:00:54 +0800 Subject: [PATCH 242/647] code-intel: Don't panic on errors in SCIP code paths. (#847) --- cmd/src/code_intel_upload_flags.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/cmd/src/code_intel_upload_flags.go b/cmd/src/code_intel_upload_flags.go index 528e4293a2..d802835bdb 100644 --- a/cmd/src/code_intel_upload_flags.go +++ b/cmd/src/code_intel_upload_flags.go @@ -229,20 +229,20 @@ func convertSCIPToLSIFGraph(out *output.Output, inputFile, outputFile string) er data, err := os.ReadFile(inputFile) if err != nil { - panic(err) + return errors.Wrapf(err, "failed to read SCIP index '%s'", inputFile) } index := scip.Index{} err = proto.Unmarshal(data, &index) if err != nil { - panic(errors.Wrapf(err, "failed to parse protobuf file '%s'", inputFile)) + return errors.Wrapf(err, "failed to parse protobuf file '%s'", inputFile) } els, err := scip.ConvertSCIPToLSIF(&index) if err != nil { - panic(errors.Wrapf(err, "failed reader.ConvertTypedIndexToGraphIndex")) + return errors.Wrapf(err, "failed to convert SCIP index at '%s' to LSIF", inputFile) } err = scip.WriteNDJSON(scip.ElementsToJsonElements(els), tmp) if err != nil { - panic(err) + return errors.Wrapf(err, "failed to write LSIF JSON output to '%s'", tmp.Name()) } err = tmp.Close() if err != nil { From 5b0298601c16d8f0386305f4d56a666964c7471e Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Sat, 1 Oct 2022 13:06:34 +0000 Subject: [PATCH 243/647] Update dependency @types/tar to v6.1.3 (#850) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- npm-distribution/package.json | 2 +- npm-distribution/yarn.lock | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/npm-distribution/package.json b/npm-distribution/package.json index 636eff3b58..4d90acd9a7 100644 --- a/npm-distribution/package.json +++ b/npm-distribution/package.json @@ -20,7 +20,7 @@ "tar": "^6.1.11" }, "devDependencies": { - "@types/tar": "6.1.2" + "@types/tar": "6.1.3" }, "private": false } diff --git a/npm-distribution/yarn.lock b/npm-distribution/yarn.lock index 7498cceb63..ffeba76eca 100644 --- a/npm-distribution/yarn.lock +++ b/npm-distribution/yarn.lock @@ -7,10 +7,10 @@ resolved "https://registry.yarnpkg.com/@types/node/-/node-17.0.36.tgz#c0d5f2fe76b47b63e0e0efc3d2049a9970d68794" integrity sha512-V3orv+ggDsWVHP99K3JlwtH20R7J4IhI1Kksgc+64q5VxgfRkQG8Ws3MFm/FZOKDYGy9feGFlZ70/HpCNe9QaA== -"@types/tar@6.1.2": - version "6.1.2" - resolved "https://registry.yarnpkg.com/@types/tar/-/tar-6.1.2.tgz#e60108a7d1b08cc91bf2faf1286cc08fdad48bbe" - integrity sha512-bnX3RRm70/n1WMwmevdOAeDU4YP7f5JSubgnuU+yrO+xQQjwDboJj3u2NTJI5ngCQhXihqVVAH5h5J8YpdpEvg== +"@types/tar@6.1.3": + version "6.1.3" + resolved "https://registry.yarnpkg.com/@types/tar/-/tar-6.1.3.tgz#46a2ce7617950c4852dfd7e9cd41aa8161b9d750" + integrity sha512-YzDOr5kdAeqS8dcO6NTTHTMJ44MUCBDoLEIyPtwEn7PssKqUYL49R1iCVJPeiPzPlKi6DbH33eZkpeJ27e4vHg== dependencies: "@types/node" "*" minipass "^3.3.5" From 4e07d074a613885f0c5b7b538ff29fa6cc90f914 Mon Sep 17 00:00:00 2001 From: Varun Gandhi Date: Tue, 4 Oct 2022 19:29:19 +0800 Subject: [PATCH 244/647] chore: Bump scip dependency for Relationship.is_definition. (#854) --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index d4a955e26d..5679c7ee98 100644 --- a/go.mod +++ b/go.mod @@ -21,7 +21,7 @@ require ( github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf - github.com/sourcegraph/scip v0.2.0 + github.com/sourcegraph/scip v0.2.1 github.com/sourcegraph/sourcegraph/lib v0.0.0-20220825181731-397a768a5290 github.com/stretchr/testify v1.8.0 golang.org/x/net v0.0.0-20220722155237-a158d28d115b diff --git a/go.sum b/go.sum index 85775bb7cc..9a7f9524d9 100644 --- a/go.sum +++ b/go.sum @@ -371,8 +371,8 @@ github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWii github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= github.com/sourcegraph/log v0.0.0-20220901143117-fc0516a694c9 h1:JjFyvx9hCD5+JpuRV6t+gTQgGFvwkxXMZzOc4sLiPqc= github.com/sourcegraph/log v0.0.0-20220901143117-fc0516a694c9/go.mod h1:UxiwB6C3xk3xOySJpW1R0MDUyfGuJRFS5Z8C+SA5p2I= -github.com/sourcegraph/scip v0.2.0 h1:Z9rR9TNONtRhqcpm0JP/yEBUy0fBKaSVbWIZKih5v04= -github.com/sourcegraph/scip v0.2.0/go.mod h1:EYyT39nXdZDNVmgbJAlyIVWbEb1txnAOKpJPSYpvgXk= +github.com/sourcegraph/scip v0.2.1 h1:t4cTR8TU81Psfmcj3ZYer67JFzsR/Sc7w5rsuckRo1Y= +github.com/sourcegraph/scip v0.2.1/go.mod h1:EYyT39nXdZDNVmgbJAlyIVWbEb1txnAOKpJPSYpvgXk= github.com/sourcegraph/sourcegraph/lib v0.0.0-20220825181731-397a768a5290 h1:SLCu3Rf1eLZ4sNKl0Bg1oURTgDxEutRCaTQt5dpVqH4= github.com/sourcegraph/sourcegraph/lib v0.0.0-20220825181731-397a768a5290/go.mod h1:9wnFUNfpORLAOJn4XAO7ZeWnYkf6/CxlWaTU1vlpuKc= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= From ad1b36ada775f09561eb708657f447c3c7754433 Mon Sep 17 00:00:00 2001 From: Randell Callahan Date: Thu, 6 Oct 2022 08:24:40 -0600 Subject: [PATCH 245/647] batches: Remote Mount #5 - src-cli (#816) --- CHANGELOG.md | 4 +- cmd/src/batch_common.go | 33 +- cmd/src/batch_exec.go | 45 +- cmd/src/batch_remote.go | 17 +- cmd/src/batch_repositories.go | 2 +- cmd/src/batch_validate.go | 2 +- go.mod | 4 +- go.sum | 8 +- internal/batches/executor/coordinator.go | 8 +- internal/batches/executor/executor.go | 29 +- internal/batches/executor/run_steps.go | 40 +- internal/batches/executor/task.go | 37 +- internal/batches/executor/task_test.go | 30 +- internal/batches/service/remote.go | 147 ++++- internal/batches/service/remote_test.go | 526 ++++++++++++++++++ .../batches/service/remote_windows_test.go | 76 +++ internal/batches/service/service.go | 31 +- internal/batches/service/service_test.go | 35 +- internal/batches/ui/tui.go | 9 + 19 files changed, 930 insertions(+), 153 deletions(-) create mode 100644 internal/batches/service/remote_windows_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 0669508cfa..348162d8e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,8 @@ All notable changes to `src-cli` are documented in this file. ### Added +- Mounting files now works when running batch changes server side. [sourcegraph/src-cli#816](https://github.com/sourcegraph/src-cli/pull/816) + ### Changed ### Fixed @@ -857,4 +859,4 @@ Re-release of 3.29.3 for Sourcegraph 3.30. ### Changed - The terminal UI has been replaced by the logger-based UI that was previously only visible in verbose-mode (`-v`). [#228](https://github.com/sourcegraph/src-cli/pull/228) -- Deprecated the `-endpoint` flag. Instead, use the `SRC_ENDPOINT` environment variable. [#235](https://github.com/sourcegraph/src-cli/pull/235) \ No newline at end of file +- Deprecated the `-endpoint` flag. Instead, use the `SRC_ENDPOINT` environment variable. [#235](https://github.com/sourcegraph/src-cli/pull/235) diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index a9706d1fba..8bfee5a05e 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -304,7 +304,7 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp // Parse flags and build up our service and executor options. ui.ParsingBatchSpec() - batchSpec, rawSpec, err := parseBatchSpec(ctx, opts.file, svc, false) + batchSpec, batchSpecDir, rawSpec, err := parseBatchSpec(ctx, opts.file, svc) if err != nil { var multiErr errors.MultiError if errors.As(err, &multiErr) { @@ -378,15 +378,14 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp Creator: workspaceCreator, EnsureImage: imageCache.Ensure, Parallelism: parallelism, + WorkingDirectory: batchSpecDir, Timeout: opts.flags.timeout, TempDir: opts.flags.tempDir, GlobalEnv: os.Environ(), - IsRemote: false, }, Logger: logManager, Cache: executor.NewDiskCache(opts.flags.cacheDir), GlobalEnv: os.Environ(), - IsRemote: false, }, ) @@ -508,13 +507,10 @@ func setReadDeadlineOnCancel(ctx context.Context, f *os.File) { // parseBatchSpec parses and validates the given batch spec. If the spec has // validation errors, they are returned. -// -// isRemote argument is a temporary argument used to determine if the batch spec is being parsed for remote -// (server-side) processing. Remote processing does not support mounts yet. -func parseBatchSpec(ctx context.Context, file string, svc *service.Service, isRemote bool) (*batcheslib.BatchSpec, string, error) { +func parseBatchSpec(ctx context.Context, file string, svc *service.Service) (*batcheslib.BatchSpec, string, string, error) { f, err := batchOpenFileFlag(file) if err != nil { - return nil, "", err + return nil, "", "", err } defer f.Close() @@ -526,26 +522,35 @@ func parseBatchSpec(ctx context.Context, file string, svc *service.Service, isRe data, err := io.ReadAll(f) if err != nil { - return nil, "", errors.Wrap(err, "reading batch spec") + return nil, "", "", errors.Wrap(err, "reading batch spec") } + dir, err := getBatchSpecDirectory(file) + if err != nil { + return nil, "", "", errors.Wrap(err, "batch spec path") + } + + spec, err := svc.ParseBatchSpec(dir, data) + return spec, dir, string(data), err +} + +func getBatchSpecDirectory(file string) (string, error) { var workingDirectory string + var err error // if the batch spec is being provided via standard input, set the working directory to the current directory if file == "" || file == "-" { workingDirectory, err = os.Getwd() if err != nil { - return nil, "", errors.Wrap(err, "batch spec path") + return "", errors.Wrap(err, "batch spec path") } } else { p, err := filepath.Abs(file) if err != nil { - return nil, "", errors.Wrap(err, "batch spec path") + return "", errors.Wrap(err, "batch spec path") } workingDirectory = filepath.Dir(p) } - - spec, err := svc.ParseBatchSpec(workingDirectory, data, isRemote) - return spec, string(data), err + return workingDirectory, nil } func checkExecutable(cmd string, args ...string) error { diff --git a/cmd/src/batch_exec.go b/cmd/src/batch_exec.go index da58dc3ed8..76cb2bbbe2 100644 --- a/cmd/src/batch_exec.go +++ b/cmd/src/batch_exec.go @@ -10,16 +10,17 @@ import ( "path/filepath" "time" + "github.com/sourcegraph/src-cli/internal/batches/docker" + "github.com/sourcegraph/src-cli/internal/batches/log" + "github.com/sourcegraph/src-cli/internal/batches/repozip" + "github.com/sourcegraph/src-cli/internal/batches/workspace" + "github.com/sourcegraph/sourcegraph/lib/errors" - "github.com/sourcegraph/src-cli/internal/batches/docker" "github.com/sourcegraph/src-cli/internal/batches/executor" "github.com/sourcegraph/src-cli/internal/batches/graphql" - "github.com/sourcegraph/src-cli/internal/batches/log" - "github.com/sourcegraph/src-cli/internal/batches/repozip" "github.com/sourcegraph/src-cli/internal/batches/service" "github.com/sourcegraph/src-cli/internal/batches/ui" - "github.com/sourcegraph/src-cli/internal/batches/workspace" "github.com/sourcegraph/src-cli/internal/cmderrors" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" @@ -30,10 +31,11 @@ const ( ) type executorModeFlags struct { - timeout time.Duration - file string - tempDir string - repoDir string + timeout time.Duration + file string + tempDir string + repoDir string + workspaceFilesDir string } func newExecutorModeFlags(flagSet *flag.FlagSet) (f *executorModeFlags) { @@ -42,6 +44,7 @@ func newExecutorModeFlags(flagSet *flag.FlagSet) (f *executorModeFlags) { flagSet.StringVar(&f.file, "f", "", "The workspace execution input file to read.") flagSet.StringVar(&f.tempDir, "tmp", "", "Directory for storing temporary data.") flagSet.StringVar(&f.repoDir, "repo", "", "Path of the checked out repo on disk.") + flagSet.StringVar(&f.workspaceFilesDir, "workspaceFiles", "", "Path of workspace files on disk.") return f } @@ -69,7 +72,7 @@ github.com/sourcegraph/sourcegraph/lib/batches. Usage: - src batch exec -f FILE -repo DIR [command options] + src batch exec -f FILE -repo DIR -workspaceFiles DIR [command options] Examples: @@ -140,6 +143,12 @@ func executeBatchSpecInWorkspaces(ctx context.Context, flags *executorModeFlags) } } + // Grab the absolute path to the workspace files contents. + workspaceFilesDir, err := filepath.Abs(flags.workspaceFilesDir) + if err != nil { + return errors.Wrap(err, "getting absolute path for workspace files dir") + } + // Test if git is available. if err := checkExecutable("git", "version"); err != nil { return err @@ -177,8 +186,7 @@ func executeBatchSpecInWorkspaces(ctx context.Context, flags *executorModeFlags) ui.PreparingContainerImagesSuccess() // Empty for now until we support secrets or env var settings in SSBC. - globalEnv := []string{} - isRemote := true + var globalEnv []string // Set up the execution UI. taskExecUI := ui.ExecutingTasks(false, 1) @@ -191,19 +199,18 @@ func executeBatchSpecInWorkspaces(ctx context.Context, flags *executorModeFlags) EnsureImage: imageCache.Ensure, Task: task, // TODO: Should be slightly less than the executor timeout. Can we somehow read that? - Timeout: flags.timeout, - TempDir: tempDir, - GlobalEnv: globalEnv, - // Temporarily prevent the ability to sending a batch spec with a mount for server-side processing. - IsRemote: isRemote, - RepoArchive: &repozip.NoopArchive{}, - UI: taskExecUI.StepsExecutionUI(task), + Timeout: flags.timeout, + TempDir: tempDir, + WorkingDirectory: workspaceFilesDir, + GlobalEnv: globalEnv, + RepoArchive: &repozip.NoopArchive{}, + UI: taskExecUI.StepsExecutionUI(task), } results, err := executor.RunSteps(ctx, opts) // Write all step cache results for all results. for _, stepRes := range results { - cacheKey := task.CacheKey(globalEnv, isRemote, stepRes.StepIndex) + cacheKey := task.CacheKey(globalEnv, workspaceFilesDir, stepRes.StepIndex) k, err := cacheKey.Key() if err != nil { return errors.Wrap(err, "calculating step cache key") diff --git a/cmd/src/batch_remote.go b/cmd/src/batch_remote.go index 25768f8052..f83df8f6bb 100644 --- a/cmd/src/batch_remote.go +++ b/cmd/src/batch_remote.go @@ -63,7 +63,7 @@ Examples: // may as well validate it at the same time so we don't even have to go to // the backend if it's invalid. ui.ParsingBatchSpec() - spec, raw, err := parseBatchSpec(ctx, file, svc, true) + spec, batchSpecDir, raw, err := parseBatchSpec(ctx, file, svc) if err != nil { ui.ParsingBatchSpecFailure(err) return err @@ -100,6 +100,21 @@ Examples: } ui.SendingBatchSpecSuccess() + hasWorkspaceFiles := false + for _, step := range spec.Steps { + if len(step.Mount) > 0 { + hasWorkspaceFiles = true + break + } + } + if hasWorkspaceFiles { + ui.UploadingWorkspaceFiles() + if err = svc.UploadBatchSpecWorkspaceFiles(ctx, batchSpecDir, batchSpecID, spec.Steps); err != nil { + return err + } + ui.UploadingWorkspaceFilesSuccess() + } + // Wait for the workspaces to be resolved. ui.ResolvingWorkspaces() ticker := time.NewTicker(1 * time.Second) diff --git a/cmd/src/batch_repositories.go b/cmd/src/batch_repositories.go index 31cbbf6d8c..b3b96d5891 100644 --- a/cmd/src/batch_repositories.go +++ b/cmd/src/batch_repositories.go @@ -74,7 +74,7 @@ Examples: } out := output.NewOutput(flagSet.Output(), output.OutputOpts{Verbose: *verbose}) - spec, _, err := parseBatchSpec(ctx, file, svc, false) + spec, _, _, err := parseBatchSpec(ctx, file, svc) if err != nil { ui := &ui.TUI{Out: out} ui.ParsingBatchSpecFailure(err) diff --git a/cmd/src/batch_validate.go b/cmd/src/batch_validate.go index a9571348e9..e83ac3f553 100644 --- a/cmd/src/batch_validate.go +++ b/cmd/src/batch_validate.go @@ -73,7 +73,7 @@ Examples: return err } - if _, _, err := parseBatchSpec(ctx, file, svc, false); err != nil { + if _, _, _, err := parseBatchSpec(ctx, file, svc); err != nil { ui.ParsingBatchSpecFailure(err) return err } diff --git a/go.mod b/go.mod index 5679c7ee98..9dd450cae6 100644 --- a/go.mod +++ b/go.mod @@ -22,7 +22,7 @@ require ( github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf github.com/sourcegraph/scip v0.2.1 - github.com/sourcegraph/sourcegraph/lib v0.0.0-20220825181731-397a768a5290 + github.com/sourcegraph/sourcegraph/lib v0.0.0-20221004162410-237d5855fa13 github.com/stretchr/testify v1.8.0 golang.org/x/net v0.0.0-20220722155237-a158d28d115b golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4 @@ -105,7 +105,7 @@ require ( go.uber.org/zap v1.23.0 // indirect golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 // indirect golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 // indirect - golang.org/x/sys v0.0.0-20220829200755-d48e67d00261 // indirect + golang.org/x/sys v0.0.0-20220928140112-f11e5e49a4ec // indirect golang.org/x/term v0.0.0-20220411215600-e5f449aeb171 // indirect golang.org/x/text v0.3.7 // indirect golang.org/x/tools v0.1.12 // indirect diff --git a/go.sum b/go.sum index 9a7f9524d9..fbc09ca2a3 100644 --- a/go.sum +++ b/go.sum @@ -373,8 +373,8 @@ github.com/sourcegraph/log v0.0.0-20220901143117-fc0516a694c9 h1:JjFyvx9hCD5+Jpu github.com/sourcegraph/log v0.0.0-20220901143117-fc0516a694c9/go.mod h1:UxiwB6C3xk3xOySJpW1R0MDUyfGuJRFS5Z8C+SA5p2I= github.com/sourcegraph/scip v0.2.1 h1:t4cTR8TU81Psfmcj3ZYer67JFzsR/Sc7w5rsuckRo1Y= github.com/sourcegraph/scip v0.2.1/go.mod h1:EYyT39nXdZDNVmgbJAlyIVWbEb1txnAOKpJPSYpvgXk= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20220825181731-397a768a5290 h1:SLCu3Rf1eLZ4sNKl0Bg1oURTgDxEutRCaTQt5dpVqH4= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20220825181731-397a768a5290/go.mod h1:9wnFUNfpORLAOJn4XAO7ZeWnYkf6/CxlWaTU1vlpuKc= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20221004162410-237d5855fa13 h1:HEj9QVz35nIU4plPb7iJSFjcTA14zVnfAdfYZF5jsKg= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20221004162410-237d5855fa13/go.mod h1:e3v3msUOgthv/QCWUzhFdfR3+hwUSn37rtuw49IVJg4= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= @@ -540,8 +540,8 @@ golang.org/x/sys v0.0.0-20211117180635-dee7805ff2e1/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20211213223007-03aa0b5f6827/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220829200755-d48e67d00261 h1:v6hYoSR9T5oet+pMXwUWkbiVqx/63mlHjefrHmxwfeY= -golang.org/x/sys v0.0.0-20220829200755-d48e67d00261/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220928140112-f11e5e49a4ec h1:BkDtF2Ih9xZ7le9ndzTA7KJow28VbQW3odyk/8drmuI= +golang.org/x/sys v0.0.0-20220928140112-f11e5e49a4ec/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20220411215600-e5f449aeb171 h1:EH1Deb8WZJ0xc0WK//leUHXcX9aLE5SymusoTmMZye8= golang.org/x/term v0.0.0-20220411215600-e5f449aeb171/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= diff --git a/internal/batches/executor/coordinator.go b/internal/batches/executor/coordinator.go index 77441f3717..d1c16e64b6 100644 --- a/internal/batches/executor/coordinator.go +++ b/internal/batches/executor/coordinator.go @@ -67,7 +67,7 @@ func (c *Coordinator) CheckCache(ctx context.Context, batchSpec *batcheslib.Batc func (c *Coordinator) ClearCache(ctx context.Context, tasks []*Task) error { for _, task := range tasks { for i := len(task.Steps) - 1; i > -1; i-- { - key := task.CacheKey(c.opts.GlobalEnv, c.opts.IsRemote, i) + key := task.CacheKey(c.opts.GlobalEnv, c.opts.ExecOpts.WorkingDirectory, i) if err := c.opts.Cache.Clear(ctx, key); err != nil { return errors.Wrapf(err, "clearing cache for step %d in %q", i, task.Repository.Name) } @@ -100,7 +100,7 @@ func (c *Coordinator) checkCacheForTask(ctx context.Context, batchSpec *batchesl return specs, false, nil } -func (c Coordinator) buildChangesetSpecs(task *Task, batchSpec *batcheslib.BatchSpec, result execution.AfterStepResult) ([]*batcheslib.ChangesetSpec, error) { +func (c *Coordinator) buildChangesetSpecs(task *Task, batchSpec *batcheslib.BatchSpec, result execution.AfterStepResult) ([]*batcheslib.ChangesetSpec, error) { input := &batcheslib.ChangesetSpecInput{ Repository: batcheslib.Repository{ ID: task.Repository.ID, @@ -128,7 +128,7 @@ func (c *Coordinator) loadCachedStepResults(ctx context.Context, task *Task, glo // We start at the back so that we can find the _last_ cached step, // then restart execution on the following step. for i := len(task.Steps) - 1; i > -1; i-- { - key := task.CacheKey(globalEnv, c.opts.IsRemote, i) + key := task.CacheKey(globalEnv, c.opts.ExecOpts.WorkingDirectory, i) result, found, err := c.opts.Cache.Get(ctx, key) if err != nil { @@ -181,7 +181,7 @@ func (c *Coordinator) ExecuteAndBuildSpecs(ctx context.Context, batchSpec *batch // Write all step cache results to the cache. for _, res := range results { for _, stepRes := range res.stepResults { - cacheKey := res.task.CacheKey(c.opts.GlobalEnv, c.opts.IsRemote, stepRes.StepIndex) + cacheKey := res.task.CacheKey(c.opts.GlobalEnv, c.opts.ExecOpts.WorkingDirectory, stepRes.StepIndex) if err := c.opts.Cache.Set(ctx, cacheKey, stepRes); err != nil { return nil, nil, errors.Wrapf(err, "caching result for step %d", stepRes.StepIndex) } diff --git a/internal/batches/executor/executor.go b/internal/batches/executor/executor.go index 069727e82d..463f46f8c0 100644 --- a/internal/batches/executor/executor.go +++ b/internal/batches/executor/executor.go @@ -62,11 +62,12 @@ type NewExecutorOpts struct { Logger log.LogManager // Config - Parallelism int - Timeout time.Duration - TempDir string - IsRemote bool - GlobalEnv []string + Parallelism int + Timeout time.Duration + WorkingDirectory string + TempDir string + IsRemote bool + GlobalEnv []string } type executor struct { @@ -168,15 +169,15 @@ func (x *executor) do(ctx context.Context, task *Task, ui TaskExecutionUI) (err // Actually execute the steps. opts := &RunStepsOpts{ - Task: task, - Logger: l, - WC: x.opts.Creator, - EnsureImage: x.opts.EnsureImage, - TempDir: x.opts.TempDir, - IsRemote: x.opts.IsRemote, - GlobalEnv: x.opts.GlobalEnv, - Timeout: x.opts.Timeout, - RepoArchive: repoArchive, + Task: task, + Logger: l, + WC: x.opts.Creator, + EnsureImage: x.opts.EnsureImage, + TempDir: x.opts.TempDir, + GlobalEnv: x.opts.GlobalEnv, + Timeout: x.opts.Timeout, + RepoArchive: repoArchive, + WorkingDirectory: x.opts.WorkingDirectory, UI: ui.StepsExecutionUI(task), } diff --git a/internal/batches/executor/run_steps.go b/internal/batches/executor/run_steps.go index 40f704a13b..7804793e32 100644 --- a/internal/batches/executor/run_steps.go +++ b/internal/batches/executor/run_steps.go @@ -8,6 +8,7 @@ import ( "io" "os" "os/exec" + "path/filepath" "strings" "time" @@ -38,6 +39,8 @@ type RunStepsOpts struct { Task *Task // TempDir points to where temporary files of the execution should live at. TempDir string + // WorkingDirectory points to where the workspace files should live at. + WorkingDirectory string // Timeout sets the deadline for the execution context. When exceeded, // execution will stop and an error is returned. Timeout time.Duration @@ -45,9 +48,6 @@ type RunStepsOpts struct { RepoArchive repozip.Archive Logger log.TaskLogger UI StepsExecutionUI - // IsRemote toggles server-side execution mode. This disables file mounts using - // step.mounts. - IsRemote bool // GlobalEnv is the os.Environ() for the execution. We don't read from os.Environ() // directly to allow injecting variables and hiding others. GlobalEnv []string @@ -321,12 +321,13 @@ func executeSingleStep( args = append(args, "--mount", fmt.Sprintf("type=bind,source=%s,target=%s,ro", source.Name(), target)) } - // Temporarily add a guard to prevent a path to mount path for server-side processing. - if !opts.IsRemote { - // Mount any paths on the local system to the docker container. The paths have already been validated during parsing. - for _, mount := range step.Mount { - args = append(args, "--mount", fmt.Sprintf("type=bind,source=%s,target=%s,ro", mount.Path, mount.Mountpoint)) + // Mount any paths on the local system to the docker container. The paths have already been validated during parsing. + for _, mount := range step.Mount { + workspaceFilePath, err := getAbsoluteMountPath(opts.WorkingDirectory, mount.Path) + if err != nil { + return bytes.Buffer{}, bytes.Buffer{}, err } + args = append(args, "--mount", fmt.Sprintf("type=bind,source=%s,target=%s,ro", workspaceFilePath, mount.Mountpoint)) } for k, v := range env { @@ -591,6 +592,29 @@ func createCidFile(ctx context.Context, tempDir string, repoSlug string) (string return cidFile.Name(), cleanup, nil } +func getAbsoluteMountPath(batchSpecDir string, mountPath string) (string, error) { + p := mountPath + if !filepath.IsAbs(p) { + // Try to build the absolute path since Docker will only mount absolute paths + p = filepath.Join(batchSpecDir, p) + } + pathInfo, err := os.Stat(p) + if os.IsNotExist(err) { + return "", errors.Newf("mount path %s does not exist", p) + } else if err != nil { + return "", errors.Wrap(err, "mount path validation") + } + if !strings.HasPrefix(p, batchSpecDir) { + return "", errors.Newf("mount path %s is not in the same directory or subdirectory as the batch spec", mountPath) + } + // Mounting a directory on Docker must end with the separator. So, append the file separator to make + // users' lives easier. + if pathInfo.IsDir() && !strings.HasSuffix(p, string(filepath.Separator)) { + p += string(filepath.Separator) + } + return p, nil +} + type stepFailedErr struct { Run string Container string diff --git a/internal/batches/executor/task.go b/internal/batches/executor/task.go index aba8779004..ee7f8ad55e 100644 --- a/internal/batches/executor/task.go +++ b/internal/batches/executor/task.go @@ -38,12 +38,7 @@ func (t *Task) ArchivePathToFetch() string { return "" } -func (t *Task) CacheKey(globalEnv []string, isRemote bool, stepIndex int) cache.Keyer { - var metadataRetriever cache.MetadataRetriever - // If the task is being run locally, set the metadata retrieve to use the filesystem based implementation. - if !isRemote { - metadataRetriever = fileMetadataRetriever{} - } +func (t *Task) CacheKey(globalEnv []string, workingDir string, stepIndex int) cache.Keyer { return &cache.CacheKey{ Repository: batcheslib.Repository{ ID: t.Repository.ID, @@ -56,8 +51,7 @@ func (t *Task) CacheKey(globalEnv []string, isRemote bool, stepIndex int) cache. OnlyFetchWorkspace: t.OnlyFetchWorkspace, Steps: t.Steps, BatchChangeAttributes: t.BatchChangeAttributes, - // TODO: This should be cached. - MetadataRetriever: metadataRetriever, + MetadataRetriever: fileMetadataRetriever{workingDirectory: workingDir}, GlobalEnv: globalEnv, @@ -65,14 +59,16 @@ func (t *Task) CacheKey(globalEnv []string, isRemote bool, stepIndex int) cache. } } -type fileMetadataRetriever struct{} +type fileMetadataRetriever struct { + workingDirectory string +} func (f fileMetadataRetriever) Get(steps []batcheslib.Step) ([]cache.MountMetadata, error) { var mountsMetadata []cache.MountMetadata for _, step := range steps { // Build up the metadata for each mount for each step for _, mount := range step.Mount { - metadata, err := getMountMetadata(mount.Path) + metadata, err := f.getMountMetadata(f.workingDirectory, mount.Path) if err != nil { return nil, err } @@ -83,8 +79,12 @@ func (f fileMetadataRetriever) Get(steps []batcheslib.Step) ([]cache.MountMetada return mountsMetadata, nil } -func getMountMetadata(path string) ([]cache.MountMetadata, error) { - info, err := os.Stat(path) +func (f fileMetadataRetriever) getMountMetadata(baseDir string, path string) ([]cache.MountMetadata, error) { + fullPath := path + if !filepath.IsAbs(path) { + fullPath = filepath.Join(baseDir, path) + } + info, err := os.Stat(fullPath) if errors.Is(err, os.ErrNotExist) { return nil, errors.Newf("path %s does not exist", path) } else if err != nil { @@ -92,30 +92,33 @@ func getMountMetadata(path string) ([]cache.MountMetadata, error) { } var metadata []cache.MountMetadata if info.IsDir() { - dirMetadata, err := getDirectoryMountMetadata(path) + dirMetadata, err := f.getDirectoryMountMetadata(fullPath) if err != nil { return nil, err } metadata = append(metadata, dirMetadata...) } else { - metadata = append(metadata, cache.MountMetadata{Path: path, Size: info.Size(), Modified: info.ModTime().UTC()}) + relativePath, err := filepath.Rel(f.workingDirectory, fullPath) + if err != nil { + return nil, err + } + metadata = append(metadata, cache.MountMetadata{Path: relativePath, Size: info.Size(), Modified: info.ModTime().UTC()}) } return metadata, nil } // getDirectoryMountMetadata reads all the files in the directory with the given // path and returns the cache.MountMetadata for all of them. -func getDirectoryMountMetadata(path string) ([]cache.MountMetadata, error) { +func (f fileMetadataRetriever) getDirectoryMountMetadata(path string) ([]cache.MountMetadata, error) { dir, err := os.ReadDir(path) if err != nil { return nil, err } var metadata []cache.MountMetadata for _, dirEntry := range dir { - newPath := filepath.Join(path, dirEntry.Name()) // Go back to the very start. Need to get the FileInfo again for the new path and figure out if it is a // directory or a file. - fileMetadata, err := getMountMetadata(newPath) + fileMetadata, err := f.getMountMetadata(path, dirEntry.Name()) if err != nil { return nil, err } diff --git a/internal/batches/executor/task_test.go b/internal/batches/executor/task_test.go index 423eff5fc7..de7b9a6e3e 100644 --- a/internal/batches/executor/task_test.go +++ b/internal/batches/executor/task_test.go @@ -39,7 +39,9 @@ func TestFileMetadataRetriever_Get(t *testing.T) { err = os.Chtimes(anotherScriptPath, modDate, modDate) require.NoError(t, err) - retriever := fileMetadataRetriever{} + retriever := fileMetadataRetriever{ + workingDirectory: tempDir, + } tests := []struct { name string @@ -53,13 +55,13 @@ func TestFileMetadataRetriever_Get(t *testing.T) { { Run: "foo", Mount: []batches.Mount{{ - Path: sampleScriptPath, + Path: "./sample.sh", Mountpoint: "/tmp/foo.sh", }}, }, }, expectedMetadata: []cache.MountMetadata{ - {Path: sampleScriptPath, Size: 0, Modified: modDate}, + {Path: "sample.sh", Size: 0, Modified: modDate}, }, }, { @@ -69,19 +71,19 @@ func TestFileMetadataRetriever_Get(t *testing.T) { Run: "foo", Mount: []batches.Mount{ { - Path: sampleScriptPath, + Path: "./sample.sh", Mountpoint: "/tmp/foo.sh", }, { - Path: anotherScriptPath, + Path: "./another.sh", Mountpoint: "/tmp/bar.sh", }, }, }, }, expectedMetadata: []cache.MountMetadata{ - {Path: sampleScriptPath, Size: 0, Modified: modDate}, - {Path: anotherScriptPath, Size: 0, Modified: modDate}, + {Path: "sample.sh", Size: 0, Modified: modDate}, + {Path: "another.sh", Size: 0, Modified: modDate}, }, }, { @@ -90,14 +92,14 @@ func TestFileMetadataRetriever_Get(t *testing.T) { { Run: "foo", Mount: []batches.Mount{{ - Path: tempDir, + Path: "./", Mountpoint: "/tmp/scripts", }}, }, }, expectedMetadata: []cache.MountMetadata{ - {Path: anotherScriptPath, Size: 0, Modified: modDate}, - {Path: sampleScriptPath, Size: 0, Modified: modDate}, + {Path: "another.sh", Size: 0, Modified: modDate}, + {Path: "sample.sh", Size: 0, Modified: modDate}, }, }, { @@ -119,21 +121,21 @@ func TestFileMetadataRetriever_Get(t *testing.T) { { Run: "foo", Mount: []batches.Mount{{ - Path: sampleScriptPath, + Path: "./sample.sh", Mountpoint: "/tmp/foo.sh", }}, }, { Run: "foo", Mount: []batches.Mount{{ - Path: sampleScriptPath, + Path: "./sample.sh", Mountpoint: "/tmp/foo.sh", }}, }, }, expectedMetadata: []cache.MountMetadata{ - {Path: sampleScriptPath, Size: 0, Modified: modDate}, - {Path: sampleScriptPath, Size: 0, Modified: modDate}, + {Path: "sample.sh", Size: 0, Modified: modDate}, + {Path: "sample.sh", Size: 0, Modified: modDate}, }, }, } diff --git a/internal/batches/service/remote.go b/internal/batches/service/remote.go index 6d4577812b..b0492560e4 100644 --- a/internal/batches/service/remote.go +++ b/internal/batches/service/remote.go @@ -2,12 +2,18 @@ package service import ( "context" + "fmt" + "io" + "mime/multipart" + "net/http" + "os" + "path/filepath" + "strings" + "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/errors" ) -var ErrServerSideBatchChangesUnsupported = errors.New("server side batch changes are not available on this Sourcegraph instance") - const upsertEmptyBatchChangeQuery = ` mutation UpsertEmptyBatchChange( $name: String! @@ -96,6 +102,143 @@ func (svc *Service) CreateBatchSpecFromRaw( return resp.CreateBatchSpecFromRaw.ID, nil } +// UploadBatchSpecWorkspaceFiles uploads workspace files to the server. +func (svc *Service) UploadBatchSpecWorkspaceFiles(ctx context.Context, workingDir string, batchSpecID string, steps []batches.Step) error { + filePaths := make(map[string]bool) + for _, step := range steps { + for _, mount := range step.Mount { + paths, err := getFilePaths(workingDir, mount.Path) + if err != nil { + return err + } + // Dedupe any files. + for _, path := range paths { + if !filePaths[path] { + filePaths[path] = true + } + } + } + } + + for filePath := range filePaths { + if err := svc.uploadFile(ctx, workingDir, filePath, batchSpecID); err != nil { + return err + } + } + return nil +} + +func getFilePaths(workingDir, filePath string) ([]string, error) { + var filePaths []string + actualFilePath := filepath.Join(workingDir, filePath) + info, err := os.Stat(actualFilePath) + if err != nil { + return nil, err + } + + if info.IsDir() { + dir, err := os.ReadDir(actualFilePath) + if err != nil { + return nil, err + } + for _, dirEntry := range dir { + paths, err := getFilePaths(workingDir, filepath.Join(filePath, dirEntry.Name())) + if err != nil { + return nil, err + } + filePaths = append(filePaths, paths...) + } + } else { + relPath, err := filepath.Rel(workingDir, actualFilePath) + if err != nil { + return nil, err + } + filePaths = append(filePaths, relPath) + } + return filePaths, nil +} + +func (svc *Service) uploadFile(ctx context.Context, workingDir, filePath, batchSpecID string) error { + // Create a pipe so the requests can be chunked to the server + pipeReader, pipeWriter := io.Pipe() + multipartWriter := multipart.NewWriter(pipeWriter) + + // Write in a separate goroutine to properly chunk the file content. Writing to the pipe lets us not have + // to put the whole file in memory. + go func() { + defer pipeWriter.Close() + defer multipartWriter.Close() + + if err := createFormFile(multipartWriter, workingDir, filePath); err != nil { + pipeWriter.CloseWithError(err) + } + }() + + request, err := svc.client.NewHTTPRequest(ctx, http.MethodPost, fmt.Sprintf(".api/files/batch-changes/%s", batchSpecID), pipeReader) + if err != nil { + return err + } + request.Header.Set("Content-Type", multipartWriter.FormDataContentType()) + + resp, err := svc.client.Do(request) + if err != nil { + // Errors passed to pipeWriter.CloseWithError come through here. + return err + } + // 2xx and 3xx are ok + if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusBadRequest { + p, err := io.ReadAll(resp.Body) + if err != nil { + return err + } + return errors.New(string(p)) + } + return nil +} + +const maxFileSize = 10 << 20 // 10MB + +func createFormFile(w *multipart.Writer, workingDir string, mountPath string) error { + f, err := os.Open(filepath.Join(workingDir, mountPath)) + if err != nil { + return err + } + defer f.Close() + + // Limit the size of file to 10MB + fileStat, err := f.Stat() + if err != nil { + return err + } + if fileStat.Size() > maxFileSize { + return errors.New("file exceeds limit of 10MB") + } + + filePath, fileName := filepath.Split(mountPath) + filePath = strings.Trim(strings.TrimSuffix(filePath, string(filepath.Separator)), ".") + // Ensure Windows separators are changed to Unix. + filePath = strings.ReplaceAll(filePath, "\\", "/") + if err = w.WriteField("filepath", filePath); err != nil { + return err + } + fileInfo, err := f.Stat() + if err != nil { + return err + } + if err = w.WriteField("filemod", fileInfo.ModTime().UTC().String()); err != nil { + return err + } + + part, err := w.CreateFormFile("file", fileName) + if err != nil { + return err + } + if _, err = io.Copy(part, f); err != nil { + return err + } + return nil +} + const executeBatchSpecQuery = ` mutation ExecuteBatchSpec($batchSpec: ID!, $noCache: Boolean!) { executeBatchSpec(batchSpec: $batchSpec, noCache: $noCache) { diff --git a/internal/batches/service/remote_test.go b/internal/batches/service/remote_test.go index 6cbfecaa2b..563a862383 100644 --- a/internal/batches/service/remote_test.go +++ b/internal/batches/service/remote_test.go @@ -1,15 +1,26 @@ package service_test import ( + "bytes" "context" "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "regexp" + "strings" "testing" mockclient "github.com/sourcegraph/src-cli/internal/api/mock" "github.com/sourcegraph/src-cli/internal/batches/service" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/errors" ) @@ -191,3 +202,518 @@ func TestService_CreateBatchSpecFromRaw(t *testing.T) { }) } } + +func TestService_UploadBatchSpecWorkspaceFiles(t *testing.T) { + tests := []struct { + name string + steps []batches.Step + + setup func(workingDir string) error + mockInvokes func(client *mockclient.Client) + + expectedError error + }{ + { + name: "Upload single file", + steps: []batches.Step{{ + Mount: []batches.Mount{{ + Path: "./hello.txt", + }}, + }}, + setup: func(workingDir string) error { + return writeTempFile(workingDir, "hello.txt", "hello world!") + }, + mockInvokes: func(client *mockclient.Client) { + // Body will get set with the body argument to NewHTTPRequest + req := httptest.NewRequest(http.MethodPost, "http://fake.com/.api/files/batch-changes/123", nil) + client.On("NewHTTPRequest", mock.Anything, http.MethodPost, ".api/files/batch-changes/123", mock.Anything). + Run(func(args mock.Arguments) { + req.Body = args[3].(*io.PipeReader) + }). + Return(req, nil). + Once() + + resp := &http.Response{ + StatusCode: http.StatusOK, + } + entry := &multipartFormEntry{ + fileName: "hello.txt", + content: "hello world!", + } + requestMatcher := multipartFormRequestMatcher(entry) + client.On("Do", mock.MatchedBy(requestMatcher)). + Return(resp, nil). + Once() + }, + }, + { + name: "Deduplicate files", + steps: []batches.Step{{ + Mount: []batches.Mount{ + { + Path: "./hello.txt", + }, + { + Path: "./hello.txt", + }, + { + Path: "./hello.txt", + }, + }, + }}, + setup: func(workingDir string) error { + return writeTempFile(workingDir, "hello.txt", "hello world!") + }, + mockInvokes: func(client *mockclient.Client) { + // Body will get set with the body argument to NewHTTPRequest + req := httptest.NewRequest(http.MethodPost, "http://fake.com/.api/files/batch-changes/123", nil) + client.On("NewHTTPRequest", mock.Anything, http.MethodPost, ".api/files/batch-changes/123", mock.Anything). + Run(func(args mock.Arguments) { + req.Body = args[3].(*io.PipeReader) + }). + Return(req, nil). + Once() + + resp := &http.Response{ + StatusCode: http.StatusOK, + } + entry := &multipartFormEntry{ + fileName: "hello.txt", + content: "hello world!", + } + requestMatcher := multipartFormRequestMatcher(entry) + client.On("Do", mock.MatchedBy(requestMatcher)). + Return(resp, nil). + Once() + }, + }, + { + name: "Upload multiple files", + steps: []batches.Step{{ + Mount: []batches.Mount{ + { + Path: "./hello.txt", + }, + { + Path: "./world.txt", + }, + }, + }}, + setup: func(workingDir string) error { + if err := writeTempFile(workingDir, "hello.txt", "hello"); err != nil { + return err + } + return writeTempFile(workingDir, "world.txt", "world!") + }, + mockInvokes: func(client *mockclient.Client) { + // Body will get set with the body argument to NewHTTPRequest + req := httptest.NewRequest(http.MethodPost, "http://fake.com/.api/files/batch-changes/123", nil) + client.On("NewHTTPRequest", mock.Anything, http.MethodPost, ".api/files/batch-changes/123", mock.Anything). + Run(func(args mock.Arguments) { + req.Body = args[3].(*io.PipeReader) + }). + Return(req, nil). + Twice() + + resp := &http.Response{ + StatusCode: http.StatusOK, + } + helloEntry := &multipartFormEntry{ + fileName: "hello.txt", + content: "hello", + } + client. + On("Do", mock.MatchedBy(multipartFormRequestMatcher(helloEntry))). + Return(resp, nil). + Once() + + worldEntry := &multipartFormEntry{ + fileName: "world.txt", + content: "world!", + } + client. + On("Do", mock.MatchedBy(multipartFormRequestMatcher(worldEntry))). + Return(resp, nil). + Once() + }, + }, + { + name: "Upload directory", + steps: []batches.Step{{ + Mount: []batches.Mount{ + { + Path: "./", + }, + }, + }}, + setup: func(workingDir string) error { + if err := writeTempFile(workingDir, "hello.txt", "hello"); err != nil { + return err + } + return writeTempFile(workingDir, "world.txt", "world!") + }, + mockInvokes: func(client *mockclient.Client) { + // Body will get set with the body argument to NewHTTPRequest + req := httptest.NewRequest(http.MethodPost, "http://fake.com/.api/files/batch-changes/123", nil) + client.On("NewHTTPRequest", mock.Anything, http.MethodPost, ".api/files/batch-changes/123", mock.Anything). + Run(func(args mock.Arguments) { + req.Body = args[3].(*io.PipeReader) + }). + Return(req, nil). + Twice() + + resp := &http.Response{ + StatusCode: http.StatusOK, + } + helloEntry := &multipartFormEntry{ + fileName: "hello.txt", + content: "hello", + } + client. + On("Do", mock.MatchedBy(multipartFormRequestMatcher(helloEntry))). + Return(resp, nil). + Once() + + worldEntry := &multipartFormEntry{ + fileName: "world.txt", + content: "world!", + } + client. + On("Do", mock.MatchedBy(multipartFormRequestMatcher(worldEntry))). + Return(resp, nil). + Once() + }, + }, + { + name: "Upload subdirectory", + steps: []batches.Step{{ + Mount: []batches.Mount{ + { + Path: "./scripts", + }, + }, + }}, + setup: func(workingDir string) error { + dir := filepath.Join(workingDir, "scripts") + if err := os.Mkdir(dir, os.ModePerm); err != nil { + return err + } + return writeTempFile(dir, "hello.txt", "hello world!") + }, + mockInvokes: func(client *mockclient.Client) { + // Body will get set with the body argument to NewHTTPRequest + req := httptest.NewRequest(http.MethodPost, "http://fake.com/.api/files/batch-changes/123", nil) + client.On("NewHTTPRequest", mock.Anything, http.MethodPost, ".api/files/batch-changes/123", mock.Anything). + Run(func(args mock.Arguments) { + req.Body = args[3].(*io.PipeReader) + }). + Return(req, nil). + Once() + + resp := &http.Response{ + StatusCode: http.StatusOK, + } + entry := &multipartFormEntry{ + path: "scripts", + fileName: "hello.txt", + content: "hello world!", + } + client.On("Do", mock.MatchedBy(multipartFormRequestMatcher(entry))). + Return(resp, nil). + Once() + }, + }, + { + name: "Upload files and directory", + steps: []batches.Step{{ + Mount: []batches.Mount{ + { + Path: "./hello.txt", + }, + { + Path: "./world.txt", + }, + { + Path: "./scripts", + }, + }, + }}, + setup: func(workingDir string) error { + if err := writeTempFile(workingDir, "hello.txt", "hello"); err != nil { + return err + } + if err := writeTempFile(workingDir, "world.txt", "world!"); err != nil { + return err + } + dir := filepath.Join(workingDir, "scripts") + if err := os.Mkdir(dir, os.ModePerm); err != nil { + return err + } + return writeTempFile(dir, "something-else.txt", "this is neat") + }, + mockInvokes: func(client *mockclient.Client) { + // Body will get set with the body argument to NewHTTPRequest + req := httptest.NewRequest(http.MethodPost, "http://fake.com/.api/files/batch-changes/123", nil) + client.On("NewHTTPRequest", mock.Anything, http.MethodPost, ".api/files/batch-changes/123", mock.Anything). + Run(func(args mock.Arguments) { + req.Body = args[3].(*io.PipeReader) + }). + Return(req, nil). + Times(3) + + resp := &http.Response{ + StatusCode: http.StatusOK, + } + helloEntry := &multipartFormEntry{ + fileName: "hello.txt", + content: "hello", + } + client.On("Do", mock.MatchedBy(multipartFormRequestMatcher(helloEntry))). + Return(resp, nil). + Once() + worldEntry := &multipartFormEntry{ + fileName: "world.txt", + content: "world!", + } + client.On("Do", mock.MatchedBy(multipartFormRequestMatcher(worldEntry))). + Return(resp, nil). + Once() + somethingElseEntry := &multipartFormEntry{ + path: "scripts", + fileName: "something-else.txt", + content: "this is neat", + } + client.On("Do", mock.MatchedBy(multipartFormRequestMatcher(somethingElseEntry))). + Return(resp, nil). + Once() + }, + }, + { + name: "Bad status code", + steps: []batches.Step{{ + Mount: []batches.Mount{{ + Path: "./hello.txt", + }}, + }}, + setup: func(workingDir string) error { + return writeTempFile(workingDir, "hello.txt", "hello world!") + }, + mockInvokes: func(client *mockclient.Client) { + req := httptest.NewRequest(http.MethodPost, "http://fake.com/.api/files/batch-changes/123", nil) + client.On("NewHTTPRequest", mock.Anything, http.MethodPost, ".api/files/batch-changes/123", mock.Anything). + Return(req, nil). + Once() + + resp := &http.Response{ + StatusCode: http.StatusInternalServerError, + Body: io.NopCloser(bytes.NewReader([]byte("failed to upload file"))), + } + client.On("Do", mock.Anything). + Return(resp, nil). + Once() + }, + expectedError: errors.New("failed to upload file"), + }, + { + name: "File exceeds limit", + steps: []batches.Step{{ + Mount: []batches.Mount{{ + Path: "./hello.txt", + }}, + }}, + setup: func(workingDir string) error { + f, err := os.Create(filepath.Join(workingDir, "hello.txt")) + if err != nil { + return err + } + defer f.Close() + if _, err = io.Copy(f, io.LimitReader(neverEnding('a'), 11<<20)); err != nil { + return err + } + return nil + }, + mockInvokes: func(client *mockclient.Client) { + req := httptest.NewRequest(http.MethodPost, "http://fake.com/.api/files/batch-changes/123", nil) + client.On("NewHTTPRequest", mock.Anything, http.MethodPost, ".api/files/batch-changes/123", mock.Anything). + Run(func(args mock.Arguments) { + req.Body = args[3].(*io.PipeReader) + }). + Return(req, nil). + Once() + + client.On("Do", mock.Anything). + Return(nil, errors.New("file exceeds limit")). + Once() + }, + expectedError: errors.New("file exceeds limit"), + }, + { + name: "Long mount path", + steps: []batches.Step{{ + Mount: []batches.Mount{{ + Path: "foo/../bar/../baz/../hello.txt", + }}, + }}, + setup: func(workingDir string) error { + dir := filepath.Join(workingDir, "foo") + if err := os.Mkdir(dir, os.ModePerm); err != nil { + return err + } + dir = filepath.Join(workingDir, "bar") + if err := os.Mkdir(dir, os.ModePerm); err != nil { + return err + } + dir = filepath.Join(workingDir, "baz") + if err := os.Mkdir(dir, os.ModePerm); err != nil { + return err + } + return writeTempFile(workingDir, "hello.txt", "hello world!") + }, + mockInvokes: func(client *mockclient.Client) { + // Body will get set with the body argument to NewHTTPRequest + req := httptest.NewRequest(http.MethodPost, "http://fake.com/.api/files/batch-changes/123", nil) + client.On("NewHTTPRequest", mock.Anything, http.MethodPost, ".api/files/batch-changes/123", mock.Anything). + Run(func(args mock.Arguments) { + req.Body = args[3].(*io.PipeReader) + }). + Return(req, nil). + Once() + + resp := &http.Response{ + StatusCode: http.StatusOK, + } + entry := &multipartFormEntry{ + fileName: "hello.txt", + content: "hello world!", + } + requestMatcher := multipartFormRequestMatcher(entry) + client.On("Do", mock.MatchedBy(requestMatcher)). + Return(resp, nil). + Once() + }, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + // TODO: use TempDir when https://github.com/golang/go/issues/51442 is cherry-picked into 1.18 or upgrade to 1.19+ + //tempDir := t.TempDir() + workingDir, err := os.MkdirTemp("", test.name) + require.NoError(t, err) + t.Cleanup(func() { + os.RemoveAll(workingDir) + }) + + if test.setup != nil { + err := test.setup(workingDir) + require.NoError(t, err) + } + + client := new(mockclient.Client) + svc := service.New(&service.Opts{Client: client}) + + if test.mockInvokes != nil { + test.mockInvokes(client) + } + + err = svc.UploadBatchSpecWorkspaceFiles(context.Background(), workingDir, "123", test.steps) + if test.expectedError != nil { + assert.Equal(t, test.expectedError.Error(), err.Error()) + } else { + assert.NoError(t, err) + } + + client.AssertExpectations(t) + }) + } +} + +func writeTempFile(dir string, name string, content string) error { + f, err := os.Create(filepath.Join(dir, name)) + if err != nil { + return err + } + defer f.Close() + if _, err = io.WriteString(f, content); err != nil { + return err + } + return nil +} + +// 2006-01-02 15:04:05.999999999 -0700 MST +var modtimeRegex = regexp.MustCompile("^[0-9]{4}-[0-9]{2}-[0-9]{2}\\s[0-9]{2}:[0-9]{2}:[0-9]{2}.[0-9]{1,9} \\+0000 UTC$") + +func multipartFormRequestMatcher(entry *multipartFormEntry) func(*http.Request) bool { + return func(req *http.Request) bool { + // Prevent parsing the body for the wrong matcher - causes all kinds of havoc. + if entry.calls > 0 { + return false + } + // Clone the request. Running ParseMultipartForm changes the behavior of the request for any additional + // matchers by consuming the request body. + cloneReq, err := cloneRequest(req) + if err != nil { + fmt.Printf("failed to clone request: %s\n", err) + return false + } + contentType := cloneReq.Header.Get("Content-Type") + if !strings.HasPrefix(contentType, "multipart/form-data") { + return false + } + if err := cloneReq.ParseMultipartForm(32 << 20); err != nil { + fmt.Printf("failed to parse multipartform: %s\n", err) + return false + } + if cloneReq.Form.Get("filepath") != entry.path { + return false + } + if !modtimeRegex.MatchString(cloneReq.Form.Get("filemod")) { + return false + } + f, header, err := cloneReq.FormFile("file") + if err != nil { + fmt.Printf("failed to get form file: %s\n", err) + return false + } + if header.Filename != entry.fileName { + return false + } + b, err := io.ReadAll(f) + if err != nil { + fmt.Printf("failed to read file: %s\n", err) + return false + } + if string(b) != entry.content { + return false + } + entry.calls++ + return true + } +} + +type multipartFormEntry struct { + path string + fileName string + content string + // This prevents some weird behavior that causes the request body to get read and throw errors. + calls int +} + +type neverEnding byte + +func (b neverEnding) Read(p []byte) (n int, err error) { + for i := range p { + p[i] = byte(b) + } + return len(p), nil +} + +func cloneRequest(req *http.Request) (*http.Request, error) { + clone := req.Clone(context.TODO()) + var b bytes.Buffer + if _, err := b.ReadFrom(req.Body); err != nil { + return nil, err + } + req.Body = io.NopCloser(&b) + clone.Body = io.NopCloser(bytes.NewReader(b.Bytes())) + return clone, nil +} diff --git a/internal/batches/service/remote_windows_test.go b/internal/batches/service/remote_windows_test.go new file mode 100644 index 0000000000..f8e34a8be4 --- /dev/null +++ b/internal/batches/service/remote_windows_test.go @@ -0,0 +1,76 @@ +package service_test + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + + mockclient "github.com/sourcegraph/src-cli/internal/api/mock" + "github.com/sourcegraph/src-cli/internal/batches/service" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + + "github.com/sourcegraph/sourcegraph/lib/batches" +) + +func TestService_UploadBatchSpecWorkspaceFiles_Windows_Path(t *testing.T) { + // TODO: use TempDir when https://github.com/golang/go/issues/51442 is cherry-picked into 1.18 or upgrade to 1.19+ + //tempDir := t.TempDir() + workingDir, err := os.MkdirTemp("", "windows_path") + require.NoError(t, err) + t.Cleanup(func() { + os.RemoveAll(workingDir) + }) + + // Set up test files and directories + dir := filepath.Join(workingDir, "scripts") + err = os.Mkdir(dir, os.ModePerm) + require.NoError(t, err) + + dir = filepath.Join(dir, "another-dir") + err = os.Mkdir(dir, os.ModePerm) + require.NoError(t, err) + + err = writeTempFile(dir, "hello.txt", "hello world!") + require.NoError(t, err) + + client := new(mockclient.Client) + svc := service.New(&service.Opts{Client: client}) + + // Body will get set with the body argument to NewHTTPRequest + req := httptest.NewRequest(http.MethodPost, "http://fake.com/.api/files/batch-changes/123", nil) + client.On("NewHTTPRequest", mock.Anything, http.MethodPost, ".api/files/batch-changes/123", mock.Anything). + Run(func(args mock.Arguments) { + req.Body = args[3].(*io.PipeReader) + }). + Return(req, nil). + Once() + + resp := &http.Response{ + StatusCode: http.StatusOK, + } + entry := &multipartFormEntry{ + path: "scripts/another-dir", + fileName: "hello.txt", + content: "hello world!", + } + requestMatcher := multipartFormRequestMatcher(entry) + client.On("Do", mock.MatchedBy(requestMatcher)). + Return(resp, nil). + Once() + + steps := []batches.Step{{ + Mount: []batches.Mount{{ + Path: ".\\scripts\\another-dir\\hello.txt", + }}, + }} + err = svc.UploadBatchSpecWorkspaceFiles(context.Background(), workingDir, "123", steps) + assert.NoError(t, err) + + client.AssertExpectations(t) +} diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index 960de35283..4231b945dd 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -466,46 +466,33 @@ func (e *duplicateBranchesErr) Error() string { return out.String() } -func (svc *Service) ParseBatchSpec(dir string, data []byte, isRemote bool) (*batcheslib.BatchSpec, error) { +func (svc *Service) ParseBatchSpec(dir string, data []byte) (*batcheslib.BatchSpec, error) { spec, err := batcheslib.ParseBatchSpec(data) if err != nil { return nil, errors.Wrap(err, "parsing batch spec") } - if err = validateMount(dir, spec, isRemote); err != nil { + if err = validateMount(dir, spec); err != nil { return nil, errors.Wrap(err, "handling mount") } return spec, nil } -func validateMount(batchSpecDir string, spec *batcheslib.BatchSpec, isRemote bool) error { +func validateMount(batchSpecDir string, spec *batcheslib.BatchSpec) error { for i, step := range spec.Steps { - for j, mount := range step.Mount { - if isRemote { - return errors.New("mounts are not supported for server-side processing") - } - p := mount.Path - if !filepath.IsAbs(p) { + for _, mount := range step.Mount { + if !filepath.IsAbs(mount.Path) { // Try to build the absolute path since Docker will only mount absolute paths - p = filepath.Join(batchSpecDir, p) + mount.Path = filepath.Join(batchSpecDir, mount.Path) } - pathInfo, err := os.Stat(p) + _, err := os.Stat(mount.Path) if os.IsNotExist(err) { - return errors.Newf("step %d mount path %s does not exist", i+1, p) + return errors.Newf("step %d mount path %s does not exist", i+1, mount.Path) } else if err != nil { return errors.Wrapf(err, "step %d mount path validation", i+1) } - if !strings.HasPrefix(p, batchSpecDir) { + if !strings.HasPrefix(mount.Path, batchSpecDir) { return errors.Newf("step %d mount path is not in the same directory or subdirectory as the batch spec", i+1) } - // Mounting a directory on Docker must end with the separator. So, append the file separator to make - // users' lives easier. - if pathInfo.IsDir() && !strings.HasSuffix(p, string(filepath.Separator)) { - p += string(filepath.Separator) - } - // Update the mount path to the absolute path so building the absolute path (above) does not need to be - // redone when adding the mount argument to the Docker container. - // TODO: Can this mess with caching? We wouldn't be doing that server-side. - step.Mount[j].Path = p } } return nil diff --git a/internal/batches/service/service_test.go b/internal/batches/service/service_test.go index 70bde9fff8..dc5aa09c48 100644 --- a/internal/batches/service/service_test.go +++ b/internal/batches/service/service_test.go @@ -234,7 +234,6 @@ func TestService_ParseBatchSpec(t *testing.T) { name string batchSpecDir string rawSpec string - isRemote bool expectedSpec *batcheslib.BatchSpec expectedErr error }{ @@ -327,7 +326,7 @@ changesetTemplate: Container: "alpine:3", Mount: []batcheslib.Mount{ { - Path: filepath.Join(tempDir, "sample.sh"), + Path: "./sample.sh", Mountpoint: "/tmp/sample.sh", }, }, @@ -371,7 +370,7 @@ changesetTemplate: Container: "alpine:3", Mount: []batcheslib.Mount{ { - Path: tempDir + string(filepath.Separator), + Path: tempDir, Mountpoint: "/tmp", }, }, @@ -415,7 +414,7 @@ changesetTemplate: Container: "alpine:3", Mount: []batcheslib.Mount{ { - Path: tempDir + string(filepath.Separator), + Path: "./", Mountpoint: "/tmp", }, }, @@ -461,11 +460,11 @@ changesetTemplate: Container: "alpine:3", Mount: []batcheslib.Mount{ { - Path: filepath.Join(tempDir, "sample.sh"), + Path: "./sample.sh", Mountpoint: "/tmp/sample.sh", }, { - Path: filepath.Join(tempDir, "another.sh"), + Path: "./another.sh", Mountpoint: "/tmp/another.sh", }, }, @@ -523,32 +522,10 @@ changesetTemplate: `, tempOutsideDir), expectedErr: errors.New("handling mount: step 1 mount path is not in the same directory or subdirectory as the batch spec"), }, - { - name: "mount remote processing", - batchSpecDir: tempDir, - rawSpec: ` -name: test-spec -description: A test spec -steps: - - run: /tmp/foo/bar/sample.sh - container: alpine:3 - mount: - - path: /valid/sample.sh - mountpoint: /tmp/foo/bar/sample.sh -changesetTemplate: - title: Test Mount - body: Test a mounted path - branch: test - commit: - message: Test -`, - isRemote: true, - expectedErr: errors.New("handling mount: mounts are not supported for server-side processing"), - }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - spec, err := svc.ParseBatchSpec(test.batchSpecDir, []byte(test.rawSpec), test.isRemote) + spec, err := svc.ParseBatchSpec(test.batchSpecDir, []byte(test.rawSpec)) if test.expectedErr != nil { assert.Equal(t, test.expectedErr.Error(), err.Error()) } else { diff --git a/internal/batches/ui/tui.go b/internal/batches/ui/tui.go index ed3e5e3117..ce1c310027 100644 --- a/internal/batches/ui/tui.go +++ b/internal/batches/ui/tui.go @@ -6,6 +6,7 @@ import ( "os/exec" "github.com/neelance/parallel" + "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/sourcegraph/lib/output" @@ -231,6 +232,14 @@ func (ui *TUI) SendingBatchSpecSuccess() { batchCompletePending(ui.pending, "Sending batch spec") } +func (ui *TUI) UploadingWorkspaceFiles() { + ui.pending = batchCreatePending(ui.Out, "Uploading workspace files") +} + +func (ui *TUI) UploadingWorkspaceFilesSuccess() { + batchCompletePending(ui.pending, "Uploading workspace files") +} + func (ui *TUI) ResolvingWorkspaces() { ui.pending = batchCreatePending(ui.Out, "Resolving workspaces") } From 5a9d166efe41ef031272f6df627186e5a2b3aec5 Mon Sep 17 00:00:00 2001 From: Randell Callahan Date: Thu, 6 Oct 2022 11:00:42 -0600 Subject: [PATCH 246/647] Update changelog for next release version (#857) --- CHANGELOG.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 348162d8e3..f5fb7db9c1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,14 +13,18 @@ All notable changes to `src-cli` are documented in this file. ### Added -- Mounting files now works when running batch changes server side. [sourcegraph/src-cli#816](https://github.com/sourcegraph/src-cli/pull/816) - ### Changed ### Fixed ### Removed +## 4.0.1 + +### Added + +- Mounting files now works when running batch changes server side. [sourcegraph/src-cli#816](https://github.com/sourcegraph/src-cli/pull/816) + ## 4.0.0 ### Fixed From ac3c970def0ccb3cb012f35832227380a0dcd504 Mon Sep 17 00:00:00 2001 From: Varun Gandhi Date: Fri, 7 Oct 2022 15:47:32 +0800 Subject: [PATCH 247/647] chore: Bump scip dependency for LSIF conversion fix. (#858) --- go.mod | 4 ++-- go.sum | 7 ++++--- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/go.mod b/go.mod index 9dd450cae6..12e2a9f87d 100644 --- a/go.mod +++ b/go.mod @@ -21,7 +21,7 @@ require ( github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf - github.com/sourcegraph/scip v0.2.1 + github.com/sourcegraph/scip v0.2.3 github.com/sourcegraph/sourcegraph/lib v0.0.0-20221004162410-237d5855fa13 github.com/stretchr/testify v1.8.0 golang.org/x/net v0.0.0-20220722155237-a158d28d115b @@ -42,7 +42,7 @@ require ( github.com/cockroachdb/errors v1.9.0 // indirect github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f // indirect github.com/cockroachdb/redact v1.1.3 // indirect - github.com/cpuguy83/go-md2man/v2 v2.0.1 // indirect + github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/dlclark/regexp2 v1.4.0 // indirect github.com/envoyproxy/protoc-gen-validate v0.3.0-java // indirect diff --git a/go.sum b/go.sum index fbc09ca2a3..3e1e2b3937 100644 --- a/go.sum +++ b/go.sum @@ -56,8 +56,9 @@ github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE= -github.com/cpuguy83/go-md2man/v2 v2.0.1 h1:r/myEWzV9lfsM1tFLgDyu0atFtJ1fXn261LKYj/3DxU= github.com/cpuguy83/go-md2man/v2 v2.0.1/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= +github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w= +github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/creack/goselect v0.1.2 h1:2DNy14+JPjRBgPzAd1thbQp4BSIihxcBf0IXhQXDRa0= github.com/creack/goselect v0.1.2/go.mod h1:a/NhLweNvqIYMuxcMOuWY516Cimucms3DglDzQP3hKY= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= @@ -371,8 +372,8 @@ github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWii github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= github.com/sourcegraph/log v0.0.0-20220901143117-fc0516a694c9 h1:JjFyvx9hCD5+JpuRV6t+gTQgGFvwkxXMZzOc4sLiPqc= github.com/sourcegraph/log v0.0.0-20220901143117-fc0516a694c9/go.mod h1:UxiwB6C3xk3xOySJpW1R0MDUyfGuJRFS5Z8C+SA5p2I= -github.com/sourcegraph/scip v0.2.1 h1:t4cTR8TU81Psfmcj3ZYer67JFzsR/Sc7w5rsuckRo1Y= -github.com/sourcegraph/scip v0.2.1/go.mod h1:EYyT39nXdZDNVmgbJAlyIVWbEb1txnAOKpJPSYpvgXk= +github.com/sourcegraph/scip v0.2.3 h1:6nRsTlNTELn+1V7JxLrDVbBpb9H1gAbUF48N7x5B8Y4= +github.com/sourcegraph/scip v0.2.3/go.mod h1:3D/RLCMvrrSam85RtFmC67SE/jhV9++hpCR5MTDzbA0= github.com/sourcegraph/sourcegraph/lib v0.0.0-20221004162410-237d5855fa13 h1:HEj9QVz35nIU4plPb7iJSFjcTA14zVnfAdfYZF5jsKg= github.com/sourcegraph/sourcegraph/lib v0.0.0-20221004162410-237d5855fa13/go.mod h1:e3v3msUOgthv/QCWUzhFdfR3+hwUSn37rtuw49IVJg4= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= From 23cab1f799db945a2a5186ef0199dd9f1ea0adbc Mon Sep 17 00:00:00 2001 From: Jean-Hadrien Chabran Date: Mon, 10 Oct 2022 17:20:38 +0200 Subject: [PATCH 248/647] Add a add subcommand to extsvc (#856) * Add a add subcommand to extsvc In the context of scaletesting, it's pretty useful to be able to add code hosts on the fly, while toying with a test instance. This PR adds such a command. * fixup * Small fixes --- cmd/src/extsvc.go | 5 ++- cmd/src/extsvc_create.go | 95 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 99 insertions(+), 1 deletion(-) create mode 100644 cmd/src/extsvc_create.go diff --git a/cmd/src/extsvc.go b/cmd/src/extsvc.go index e761dd1714..a716aebc00 100644 --- a/cmd/src/extsvc.go +++ b/cmd/src/extsvc.go @@ -23,6 +23,7 @@ The commands are: list lists the external services on the Sourcegraph instance edit edits external services on the Sourcegraph instance + add add an external service on the Sourcegraph instance Use "src extsvc [command] -h" for more information about a command. ` @@ -52,6 +53,8 @@ type externalService struct { CreatedAt, UpdatedAt string } +var errServiceNotFound = errors.New("no such external service") + func lookupExternalService(ctx context.Context, client api.Client, byID, byName string) (*externalService, error) { var result struct { ExternalServices struct { @@ -72,5 +75,5 @@ func lookupExternalService(ctx context.Context, client api.Client, byID, byName return svc, nil } } - return nil, errors.New("no such external service") + return nil, errServiceNotFound } diff --git a/cmd/src/extsvc_create.go b/cmd/src/extsvc_create.go new file mode 100644 index 0000000000..d79ac48540 --- /dev/null +++ b/cmd/src/extsvc_create.go @@ -0,0 +1,95 @@ +package main + +import ( + "context" + "flag" + "fmt" + "io" + "os" + "strings" + + "github.com/mattn/go-isatty" + "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/src-cli/internal/api" +) + +func init() { + usage := ` + Examples: + + create an external service configuration on the Sourcegraph instance: + + $ cat new-config.json | src extsvc create + $ src extsvc create -name 'My GitHub connection' new-config.json + ` + + flagSet := flag.NewFlagSet("create", flag.ExitOnError) + usageFunc := func() { + fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src extsvc %s':\n", flagSet.Name()) + flagSet.PrintDefaults() + fmt.Println(usage) + } + var ( + nameFlag = flagSet.String("name", "", "exact name of the external service to create") + kindFlag = flagSet.String("kind", "", "kind of the external service to create") + apiFlags = api.NewFlags(flagSet) + ) + + handler := func(args []string) (err error) { + ctx := context.Background() + if err := flagSet.Parse(args); err != nil { + return err + } + if *nameFlag == "" { + return errors.New("-name must be provided") + } + + var createJSON []byte + if len(flagSet.Args()) == 1 { + createJSON, err = os.ReadFile(flagSet.Arg(0)) + if err != nil { + return err + } + } + if !isatty.IsTerminal(os.Stdin.Fd()) { + // stdin is a pipe not a terminal + createJSON, err = io.ReadAll(os.Stdin) + if err != nil { + return err + } + } + + createExternalServiceInput := map[string]interface{}{ + "kind": strings.ToUpper(*kindFlag), + "displayName": *nameFlag, + "config": string(createJSON), + } + queryVars := map[string]interface{}{ + "input": createExternalServiceInput, + } + var result struct{} // TODO: future: allow formatting resulting external service + + client := cfg.apiClient(apiFlags, flagSet.Output()) + if ok, err := client.NewRequest(externalServicesCreateMutation, queryVars).Do(ctx, &result); err != nil { + return err + } else if ok { + fmt.Println("External service created:", *nameFlag) + } + return nil + } + + // Register the command. + extsvcCommands = append(extsvcCommands, &command{ + flagSet: flagSet, + handler: handler, + usageFunc: usageFunc, + }) +} + +const externalServicesCreateMutation = ` + mutation AddExternalService($input: AddExternalServiceInput!) { + addExternalService(input: $input) { + id + warning + } + }` From e0d313657419bc6d516534fa8b972534619433fd Mon Sep 17 00:00:00 2001 From: Anatoli Babenia Date: Tue, 11 Oct 2022 15:31:04 +0300 Subject: [PATCH 249/647] code-intel: Fix double word typo (#851) --- cmd/src/code_intel_upload.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cmd/src/code_intel_upload.go b/cmd/src/code_intel_upload.go index 7035d20383..566010805e 100644 --- a/cmd/src/code_intel_upload.go +++ b/cmd/src/code_intel_upload.go @@ -246,7 +246,7 @@ func filterLSIFUnauthorizedError(out *output.Output, err error) error { ) } else { actionableHints = append(actionableHints, - fmt.Sprintf("Please retry your request with a -github-token=XXX with with collaborator access to %s.", codeintelUploadFlags.repo), + fmt.Sprintf("Please retry your request with a -github-token=XXX with collaborator access to %s.", codeintelUploadFlags.repo), "This token will be used to check with the code host that the uploading user has write access to the target repository.", ) } @@ -258,7 +258,7 @@ func filterLSIFUnauthorizedError(out *output.Output, err error) error { ) } else { actionableHints = append(actionableHints, - fmt.Sprintf("Please retry your request with a -gitlab-token=XXX with with write access to %s.", codeintelUploadFlags.repo), + fmt.Sprintf("Please retry your request with a -gitlab-token=XXX with write access to %s.", codeintelUploadFlags.repo), "This token will be used to check with the code host that the uploading user has write access to the target repository.", ) } From fb189abd50c4e183b7f4ac69d10b6a1c69bef606 Mon Sep 17 00:00:00 2001 From: Adam Harvey Date: Wed, 12 Oct 2022 18:09:47 +0800 Subject: [PATCH 250/647] batches: show warning when batch changes are too large (#860) Closes sourcegraph/sourcegraph#42408. --- cmd/src/batch_remote.go | 5 +++-- internal/batches/service/remote.go | 6 ++++++ internal/batches/ui/tui.go | 30 +++++++++++++++++++++++++++++- 3 files changed, 38 insertions(+), 3 deletions(-) diff --git a/cmd/src/batch_remote.go b/cmd/src/batch_remote.go index f83df8f6bb..a5a1a57e1a 100644 --- a/cmd/src/batch_remote.go +++ b/cmd/src/batch_remote.go @@ -119,8 +119,9 @@ Examples: ui.ResolvingWorkspaces() ticker := time.NewTicker(1 * time.Second) defer ticker.Stop() + var res *service.BatchSpecWorkspaceResolution for range ticker.C { - res, err := svc.GetBatchSpecWorkspaceResolution(ctx, batchSpecID) + res, err = svc.GetBatchSpecWorkspaceResolution(ctx, batchSpecID) if err != nil { return err } @@ -131,7 +132,7 @@ Examples: break } } - ui.ResolvingWorkspacesSuccess() + ui.ResolvingWorkspacesSuccess(res.Workspaces.TotalCount) // We have to enqueue this for execution with a separate operation. // diff --git a/internal/batches/service/remote.go b/internal/batches/service/remote.go index b0492560e4..f671715def 100644 --- a/internal/batches/service/remote.go +++ b/internal/batches/service/remote.go @@ -275,6 +275,9 @@ query BatchSpecWorkspaceResolution($batchSpec: ID!) { workspaceResolution { failureMessage state + workspaces { + totalCount + } } } } @@ -284,6 +287,9 @@ query BatchSpecWorkspaceResolution($batchSpec: ID!) { type BatchSpecWorkspaceResolution struct { FailureMessage string `json:"failureMessage"` State string `json:"state"` + Workspaces struct { + TotalCount int `json:"totalCount"` + } `json:"workspaces"` } func (svc *Service) GetBatchSpecWorkspaceResolution(ctx context.Context, id string) (*BatchSpecWorkspaceResolution, error) { diff --git a/internal/batches/ui/tui.go b/internal/batches/ui/tui.go index ce1c310027..f5a8bade25 100644 --- a/internal/batches/ui/tui.go +++ b/internal/batches/ui/tui.go @@ -3,6 +3,7 @@ package ui import ( "context" "fmt" + "math" "os/exec" "github.com/neelance/parallel" @@ -97,6 +98,7 @@ func (ui *TUI) DeterminingWorkspaceCreatorTypeSuccess(wt workspace.CreatorType) func (ui *TUI) DeterminingWorkspaces() { ui.pending = batchCreatePending(ui.Out, "Determining workspaces") } + func (ui *TUI) DeterminingWorkspacesSuccess(workspacesCount, reposCount int, unsupported batches.UnsupportedRepoSet, ignored batches.IgnoredRepoSet) { batchCompletePending(ui.pending, fmt.Sprintf("Resolved %d workspaces from %d repositories", workspacesCount, reposCount)) @@ -113,6 +115,31 @@ func (ui *TUI) DeterminingWorkspacesSuccess(workspacesCount, reposCount int, uns } block.Close() } + + ui.maybeWorkspaceCountWarning(workspacesCount, 500) +} + +func (ui *TUI) maybeWorkspaceCountWarning(count, limit int) { + if count > limit { + block := ui.Out.Block(output.Linef( + "⚠️", output.StyleWarning, + "Batch changes with more than %d workspaces may be unwieldy to manage.", + limit, + )) + + for _, line := range []string{ + "We're working on providing more filtering options, and you can continue with", + fmt.Sprintf( + "this batch change if you want, but you may want to break it into %d or more", + int(math.Ceil(float64(count)/float64(limit))), + ), + "batch changes if you can.", + } { + block.WriteLine(output.Line("", output.StyleSuggestion, line)) + } + + block.Close() + } } func (ui *TUI) CheckingCache() { @@ -244,8 +271,9 @@ func (ui *TUI) ResolvingWorkspaces() { ui.pending = batchCreatePending(ui.Out, "Resolving workspaces") } -func (ui *TUI) ResolvingWorkspacesSuccess() { +func (ui *TUI) ResolvingWorkspacesSuccess(workspacesCount int) { batchCompletePending(ui.pending, "Resolving workspaces") + ui.maybeWorkspaceCountWarning(workspacesCount, 2000) } func (ui *TUI) ExecutingBatchSpec() { From ecce113297a1388ba482b634be27998c3de0802f Mon Sep 17 00:00:00 2001 From: Kelli Rockwell Date: Mon, 17 Oct 2022 17:11:03 -0700 Subject: [PATCH 251/647] Automate versioned Homebrew formula publishing, fix patch releases (#864) --- .github/workflows/goreleaser.yml | 204 ++++++++++++++++++++++++++++++- .goreleaser-patch.yml | 63 ++++++++++ .goreleaser.yml | 4 + DEVELOPMENT.md | 17 +-- README.markdown => README.md | 34 +++++- 5 files changed, 302 insertions(+), 20 deletions(-) create mode 100644 .goreleaser-patch.yml rename README.markdown => README.md (91%) diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index 1b1f1a4ba1..cc5fd77c8a 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -1,16 +1,166 @@ -name: GoReleaser +name: Build and Release on: push: - tags: + tags: - '*' - - '!latest' +# There are two cases where this GitHub action will run: +# +# 1. We are releasing a new latest version for src-cli, as a major, minor, or patch +# update, for instance 4.0.2 -> 4.1.0, OR +# 2. We are releasing a new minor/patch version for an older major/minor version of +# src-cli, for instance if the latest version is 4.0.2 and we're releasing 3.43.3 +# +# In both cases, we want to run both goreleaser and npm to publish new versions in all the +# places we care about. For goreleaser publishing to Homebrew, we need to publish to +# different formulas depending on if we're case 1. or case 2, and neither goreleaser nor +# Homebrew has a good way of handling this automatically. In the case of the former (a new +# latest release), we must: +# +# 1. Copy the main formula in our Homebrew tap for the previous latest release to a +# versioned formula +# 2. Build and publish the new release to the main formula +# 3. Update the Homebrew symlink alias for the latest version +# +# In the case of the latter (a patch release for an older version), we only need to: +# +# 1. Build and publish the new release to a versioned Homebrew formula +# +# This action contains 5 jobs to accommodate both cases: +# +# release_type [always] - checks tags, determines if we're case 1. or case 2. +# goreleaser_pre [if case 1.] - copies the main formula to a versioned formula +# goreleaser [always] - runs tests, builds + publishes with goreleaser +# goreleaser_post [if case 1.] - updates symlink to latest version +# npm [always] - publishes to npm jobs: + # release_type compares the most recently created tag to the highest versioned tag + # available on the repo to determine if this release is for a new latest version or a + # patch of an older version. + release_type: + name: Determine release type + runs-on: ubuntu-latest + outputs: + is_latest_version: ${{ env.is_latest_version }} + latest_tag: ${{ env.latest_tag }} + second_latest_tag: ${{ env.second_latest_tag }} + steps: + - name: Checkout + uses: actions/checkout@v3 + with: + fetch-depth: 0 + - name: Fetch most recent tag, latest (highest version) tag, and second latest tag + # For latest and second latest tags, we can't use git tag --sort=version:refname + # because git doesn't have a concept of pre-release versions and thus mis-sorts + # versions like 4.0.0-rc.0 *after* 4.0.0. + run: | + echo "most_recent_tag=$(git tag --sort=taggerdate | tail -1)" >> $GITHUB_ENV + echo "latest_tag=$(git tag | tr - \~ | sort --version-sort | tr \~ - | tail -1)" >> $GITHUB_ENV + echo "second_latest_tag=$(git tag | tr - \~ | sort --version-sort | tr \~ - | tail -2 | sed -n 1p)" >> $GITHUB_ENV + - name: Install semver + run: | + wget -O /usr/local/bin/semver https://raw.githubusercontent.com/fsaintjacques/semver-tool/master/src/semver + chmod +x /usr/local/bin/semver + - name: Compare tags + # If the most recent tag is also the latest tag, semver compare returns 0. If it's + # a patch of an older version, semver compare will return -1. + run: | + if [[ $(semver compare ${{ env.latest_tag }} ${{ env.most_recent_tag }}) == 0 ]] + then + echo "is_latest_version=1" >> $GITHUB_ENV + else + echo "is_latest_version=0" >> $GITHUB_ENV + fi + - name: Log variables + run: | + echo "Most recent (current) tag: ${{ env.most_recent_tag }}" + echo "Latest version tag: ${{ env.latest_tag }}" + echo "Building current version as new latest?: ${{ env.is_latest_version }}" + + # goreleaser_pre copies the main formula in our Homebrew tap for the previous latest + # release (second latest tag) to a versioned formula, so that it is preserved when + # goreleaser runs and overwrites the main formula for the latest build. + goreleaser_pre: + name: Copy previous release + runs-on: ubuntu-latest + needs: release_type + # Only run this step if we're releasing a new latest version. Creating a patch release + # does not touch the main formula. + if: needs.release_type.outputs.is_latest_version == 1 + steps: + - name: Set variables + run: | + echo "latest_tag=${{ needs.release_type.outputs.latest_tag }}" >> $GITHUB_ENV + echo "second_latest_tag=${{ needs.release_type.outputs.second_latest_tag }}" >> $GITHUB_ENV + - name: Checkout + uses: actions/checkout@v3 + with: + fetch-depth: 0 + - name: Set versioning variables + run: | + echo "versioned_formula_file=Formula/src-cli@${{ env.second_latest_tag }}.rb" >> $GITHUB_ENV + echo "versioned_classname=SrcCliAT$(echo ${{ env.second_latest_tag }} | sed 's/\.//g')" >> $GITHUB_ENV + - name: Log variables + run: | + echo "Second latest tag: ${{ env.second_latest_tag }}" + echo "Versioned formula file: ${{ env.versioned_formula_file }}" + echo "Versioned classname: ${{ env.versioned_classname }}" + - name: Checkout Homebrew tap + uses: actions/checkout@v3 + with: + repository: sourcegraph/homebrew-src-cli + fetch-depth: 0 + token: ${{ secrets.BOT_CROSS_REPO_PAT }} + - name: Copy main release formula file to versioned formula file + run: cp Formula/src-cli.rb ${{ env.versioned_formula_file }} + # Homebrew expects the name of the class in a versioned formula file to be of the + # format {Formula}AT{Major}{Minor}{Patch}, but the main formula classname is just + # {Formula}, so we manually update the name: SrcCli -> SrcCliAT### + - name: Rename formula classname + run: sed -i 's/class SrcCli/class ${{ env.versioned_classname }}/' ${{ env.versioned_formula_file }} + - name: Commit result + run: | + git config user.name sourcegraph-bot + git config user.email sourcegraph-bot-github@sourcegraph.com + git add . + git commit -m "Copy previous release" + git push + + # goreleaser runs tests before building, then uses goreleaser to publish to Homebrew and + # Docker Hub. goreleaser: - name: release + name: Run goreleaser runs-on: ubuntu-latest + needs: [release_type, goreleaser_pre] + # By default, this job will be skipped if either "needs" job is skipped. This tells + # GitHub actions to always run it, so long as the previous jobs that ran didn't fail. + if: | + always() && + (needs.release_type.result == 'success') && + (needs.goreleaser_pre.result == 'success' || needs.goreleaser_pre.result == 'skipped') + outputs: + # Passthrough from previous jobs so that they're also available in goreleaser_post + second_latest_tag: ${{ needs.release_type.outputs.second_latest_tag }} + latest_tag: ${{ needs.release_type.outputs.latest_tag }} + is_latest_version: ${{ env.is_latest_version }} steps: + - name: Set variables + run: echo "is_latest_version=${{ needs.release_type.outputs.is_latest_version }}" >> $GITHUB_ENV + - name: Set config file + # These goreleaser config files are identical except for the brews.name template. + # Homebrew expects the main formula to be named one way, and versioned formulas to + # be named another, but goreleaser only allows us to specify a single template. + run: | + if [[ ${{ env.is_latest_version }} == 1 ]] + then + echo "config_file=.goreleaser.yml" >> $GITHUB_ENV + else + echo "config_file=.goreleaser-patch.yml" >> $GITHUB_ENV + fi + - name: Log config file + run: | + echo "Goreleaser config file: ${{ env.config_file }}" - name: Checkout uses: actions/checkout@v3 with: @@ -29,10 +179,54 @@ jobs: uses: goreleaser/goreleaser-action@v2 with: version: latest - args: release --rm-dist + # We use a different goreleaser config for releasing a new latest version vs. + # releasing a patch on an older version. For releasing the new latest version, + # we want to update the main (unversioned) Homebrew formula. For releasing a + # patch on an older version, we want to publish a new versioned formula and + # leave the main formula untouched. + args: release --rm-dist --config=${{ env.config_file }} env: # Use separate access token, because we need a scope:repo token to publish the brew formula. GITHUB_TOKEN: ${{ secrets.GH_PAT }} + + # goreleaser_post updates the symlink name to refer to the new release version. The + # symlink enables users to install the latest src-cli with the versioned command: + # $ brew install sourcegraph/src-cli/src-cli@X.Y.Z + # alongside the command to install it via the main formula: + # $ brew install sourcegraph/src-cli/src-cli + goreleaser_post: + name: Create new release version symlink + runs-on: ubuntu-latest + needs: goreleaser + # Only run this step if we're releasing a new latest version. Creating a patch release + # does not require updating the symlink. + if: needs.goreleaser.outputs.is_latest_version == 1 + steps: + - name: Set variables + run: | + echo "old_symlink_name=Aliases/src-cli@${{ needs.goreleaser.outputs.second_latest_tag }}" >> $GITHUB_ENV + echo "new_symlink_name=Aliases/src-cli@${{ needs.goreleaser.outputs.latest_tag }}" >> $GITHUB_ENV + - name: Log variables + run: | + echo "Old symlink: ${{ env.old_symlink_name }}" + echo "New symlink: ${{ env.new_symlink_name }}" + - name: Checkout Homebrew tap + uses: actions/checkout@v3 + with: + repository: sourcegraph/homebrew-src-cli + fetch-depth: 0 + token: ${{ secrets.BOT_CROSS_REPO_PAT }} + - name: Replace symlink + run: mv ${{ env.old_symlink_name }} ${{ env.new_symlink_name }} + - name: Commit result + run: | + git config user.name sourcegraph-bot + git config user.email sourcegraph-bot-github@sourcegraph.com + git add . + git commit -m "Update latest release symlink" + git push + + # npm publishes the new version to the npm package registry npm: runs-on: ubuntu-latest needs: goreleaser diff --git a/.goreleaser-patch.yml b/.goreleaser-patch.yml new file mode 100644 index 0000000000..f7307e5474 --- /dev/null +++ b/.goreleaser-patch.yml @@ -0,0 +1,63 @@ +# This is the patch release configuration for goreleaser, which builds and publishes a new +# patch release for an older version of src-cli. It publishes a new versioned formula in +# the Homebrew tap and does not publish a "latest" image to Docker Hub. It should match +# .goreleaser.yml in every way except for the brews.name template and the +# dockers.image_templates list. +dist: release +env: + - GO111MODULE=on + - CGO_ENABLED=0 +before: + hooks: + - go mod download + - go mod tidy + - go generate ./schema +builds: +- + main: ./cmd/src/ + binary: src + ldflags: + - -X github.com/sourcegraph/src-cli/internal/version.BuildTag={{.Version}} + goos: + - linux + - windows + - darwin + goarch: + - amd64 + - arm64 +archives: +- id: tarball + format: tar.gz +- id: bin + format: binary + wrap_in_directory: false + name_template: "src_{{ .Os }}_{{ .Arch }}" +brews: + - + name: src-cli@{{ .Major }}.{{ .Minor }}.{{ .Patch }} + homepage: "https://sourcegraph.com/" + description: "Sourcegraph CLI" + tap: + owner: sourcegraph + name: homebrew-src-cli + # Folder inside the repository to put the formula. + # Default is the root folder. + folder: Formula + # We need to set this so that goreleaser doesn't think the binary is called + # `src-cli` + install: | + bin.install "src" + ids: + - tarball +dockers: + - dockerfile: Dockerfile.release + image_templates: + - "sourcegraph/src-cli:{{ .Tag }}" + - "sourcegraph/src-cli:{{ .Major }}" + - "sourcegraph/src-cli:{{ .Major }}.{{ .Minor }}" +changelog: + sort: asc + filters: + exclude: + - '^docs:' + - '^test:' diff --git a/.goreleaser.yml b/.goreleaser.yml index 4db476ce7d..a0ca261922 100644 --- a/.goreleaser.yml +++ b/.goreleaser.yml @@ -1,3 +1,7 @@ +# This is the main configuration for goreleaser, which builds and publishes a new latest +# release. It updates the main formula in the Homebrew tap. It should match +# .goreleaser-patch.yml in every way except for the brews.name template and the +# dockers.image_templates list. dist: release env: - GO111MODULE=on diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index ca256d7288..144717ce26 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -59,7 +59,7 @@ We adhere to the [general Sourcegraph principles for testing](https://docs.sourc 1. Find the latest version (either via the releases tab on GitHub or via git tags) to determine which version you are releasing. 2. (optional) If this is a non-patch release, update the changelog. Add a new section `## $MAJOR.MINOR` to [`CHANGELOG.md`](https://github.com/sourcegraph/src-cli/blob/main/CHANGELOG.md#unreleased) immediately under `## Unreleased changes`. Add new empty `Added`, `Changed`, `Fixed`, and `Removed` sections under `## Unreleased changes`. Open a pull request with the new changelog. Get the pull request merged before completing the next step. 3. `VERSION=9.9.9 ./release.sh` (replace `9.9.9` with the version you are releasing) -4. GitHub will automatically perform the release via the [goreleaser action](https://github.com/sourcegraph/src-cli/actions?query=workflow%3AGoreleaser). Once it has finished, **you need to confirm**: +4. GitHub will automatically perform the release via the [Build and Release action](https://github.com/sourcegraph/src-cli/actions?query=workflow%3ABuild+and+Release). Once it has finished, **you need to confirm**: 1. The [curl commands in the README](README.markdown#installation) fetch the latest version above. 2. The [releases section of the repo sidebar](https://github.com/sourcegraph/src-cli) shows the correct version. 5. Make the necessary updates to the main Sourcegraph repo: @@ -69,22 +69,11 @@ We adhere to the [general Sourcegraph principles for testing](https://docs.sourc ### Patch releases -If a backwards-compatible change is made _after_ a backwards-incompatible one, the backwards-compatible one should be re-released to older instances that support it. +If a backwards-compatible change, such as a bug fix, is made _after_ a backwards-incompatible one, the backwards-compatible one should be re-released to older instances that support it. A Sourcegraph instance returns the highest patch version with the same major and minor version as `MinimumVersion` as defined in the instance. Patch versions are reserved solely for non-breaking changes and minor bug fixes. This allows us to dynamically release fixes for older versions of `src-cli` without having to update the instance. -To release a bug fix or a new feature that is backwards compatible with one of the previous two minor version of Sourcegraph, cherry-pick the changes into a patch branch and re-releases with a new patch version. - -For example, suppose we have the the recommended versions. - -| Sourcegraph version | Recommended src-cli version | -| ------------------- | --------------------------- | -| `3.100` | `3.90.5` | -| `3.99` | `3.85.7` | - -If a new feature is added to a new `3.91.6` release of src-cli and this change requires only features available in Sourcegraph `3.99`, then this feature should also be present in a new `3.85.8` release of src-cli. Because a Sourcegraph instance will automatically select the highest patch version, all non-breaking changes should increment only the patch version. - -Note that if instead the recommended src-cli version for Sourcegraph `3.99` was `3.90.4` in the example above, there is no additional step required, and the new patch version of src-cli will be available to both Sourcegraph versions. +To release a bug fix or a new feature that is backwards compatible with one of the previous two minor version of Sourcegraph, cherry-pick the changes into a patch branch, then follow the steps above to release the patch, specifying the appropriate patch `VERSION`. The Build and Release action will automatically create the appropriate versioned release, without overwriting the latest one. ## Docker diff --git a/README.markdown b/README.md similarity index 91% rename from README.markdown rename to README.md index e0f01030d4..3fcdf01bf0 100644 --- a/README.markdown +++ b/README.md @@ -26,12 +26,18 @@ curl -L https://sourcegraph.com/.api/src-cli/src_darwin_amd64 -o /usr/local/bin/ chmod +x /usr/local/bin/src ``` -or +or with Homebrew: ```bash brew install sourcegraph/src-cli/src-cli ``` +or with npm: + +```bash +npm install -g @sourcegraph/src +``` + #### Version compatible with your Sourcegraph instance Replace `sourcegraph.example.com` with your Sourcegraph instance URL: @@ -41,6 +47,20 @@ curl -L https://sourcegraph.example.com/.api/src-cli/src_darwin_amd64 -o /usr/lo chmod +x /usr/local/bin/src ``` +or, if you know the specific version to target, for example 3.43.2: + +```bash +brew install sourcegraph/src-cli/src-cli@3.43.2 +``` + +or with npm/npx: + +```bash +npx @sourcegraph/src@3.43.2 version +``` + +> Note: Versioned formulas are available on Homebrew for Sourcegraph versions 3.43.2 and later. + ### Installation: Linux #### Latest version @@ -50,6 +70,12 @@ curl -L https://sourcegraph.com/.api/src-cli/src_linux_amd64 -o /usr/local/bin/s chmod +x /usr/local/bin/src ``` +or with npm: + +```bash +npm install -g @sourcegraph/src +``` + #### Version compatible with your Sourcegraph instance Replace `sourcegraph.example.com` with your Sourcegraph instance URL: @@ -59,6 +85,12 @@ curl -L https://sourcegraph.example.com/.api/src-cli/src_linux_amd64 -o /usr/loc chmod +x /usr/local/bin/src ``` +or, with npm/npx, if you know the specific version to target, for example 3.43.2: + +```bash +npx @sourcegraph/src@3.43.2 version +``` + ### Installation: Windows See [Sourcegraph CLI for Windows](WINDOWS.md). From ef062719d99112c3645fb1702f72d8c8aa9fce8c Mon Sep 17 00:00:00 2001 From: Kelli Rockwell Date: Mon, 17 Oct 2022 18:35:34 -0700 Subject: [PATCH 252/647] Prepare changelog for 4.1 (#865) --- CHANGELOG.md | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f5fb7db9c1..a3f8a3cc14 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,11 +19,17 @@ All notable changes to `src-cli` are documented in this file. ### Removed +## 4.1.0 + +### Changed + +- All current and future versions of src-cli from version 3.43.2 and up will now be available for installation via Homebrew in addition to the latest version. A specific version can be installed with the command `brew install sourcegraph/src-cli/src-cli@X.Y.Z`. [#864](https://github.com/sourcegraph/src-cli/pull/864) + ## 4.0.1 ### Added -- Mounting files now works when running batch changes server side. [sourcegraph/src-cli#816](https://github.com/sourcegraph/src-cli/pull/816) +- Mounting files now works when running batch changes server side. [#816](https://github.com/sourcegraph/src-cli/pull/816) ## 4.0.0 @@ -139,7 +145,7 @@ All notable changes to `src-cli` are documented in this file. ### Fixed -- Global git email gets inserted as plain text when running `src batch new -f ` and doesn't result in a schema validation failure. [sourcegraph/src-cli#773](https://github.com/sourcegraph/src-cli/pull/773) +- Global git email gets inserted as plain text when running `src batch new -f ` and doesn't result in a schema validation failure. [#773](https://github.com/sourcegraph/src-cli/pull/773) ## 3.40.8 @@ -155,7 +161,7 @@ All notable changes to `src-cli` are documented in this file. ### Added -- It's now possible to install src-cli via `npm install -g @sourcegraph/src`. [sourcegraph/src-cli#760](https://github.com/sourcegraph/src-cli/pull/760) +- It's now possible to install src-cli via `npm install -g @sourcegraph/src`. [#760](https://github.com/sourcegraph/src-cli/pull/760) ## 3.40.3 From 85c118a1ae1ad9b6f58c5f8a22d32651b9b5e1ee Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Thu, 20 Oct 2022 01:54:45 +0200 Subject: [PATCH 253/647] ssbc: Don't drop repo origin (#871) I added this as a stopgap to prevent accidental token leakage to cause upstream pushes to be allowed. This has been fixed on the executor side by using a new clone mechanism for repos, so this is no longer required. --- internal/batches/workspace/executor_workspace.go | 7 ------- 1 file changed, 7 deletions(-) diff --git a/internal/batches/workspace/executor_workspace.go b/internal/batches/workspace/executor_workspace.go index 8d8e9e3faf..d682d46578 100644 --- a/internal/batches/workspace/executor_workspace.go +++ b/internal/batches/workspace/executor_workspace.go @@ -4,7 +4,6 @@ import ( "context" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" - "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/batches/graphql" "github.com/sourcegraph/src-cli/internal/batches/repozip" @@ -25,12 +24,6 @@ type executorWorkspaceCreator struct { var _ Creator = &executorWorkspaceCreator{} func (wc *executorWorkspaceCreator) Create(ctx context.Context, repo *graphql.Repository, steps []batcheslib.Step, archive repozip.Archive) (Workspace, error) { - // Cleanup the repo dir. We don't want any origin to be defined here. This - // reduces risk of accidentally pushing anything from the workspace execution. - if _, err := runGitCmd(ctx, wc.RepoDir, "remote", "rm", "origin"); err != nil { - return nil, errors.Wrap(err, "git init failed") - } - return &dockerBindExecutorWorkspace{ dockerBindWorkspace: dockerBindWorkspace{ tempDir: wc.TempDir, From e4cacfce9197d36bb0659422301cfda37675c1b4 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Thu, 20 Oct 2022 01:54:56 +0200 Subject: [PATCH 254/647] secrets: Allow using secrets from os.Environ (#872) This is a requirement for secrets. The inline comment explains a bit why this is okay. This is all it takes from the src-cli side to implement secrets support :) --- cmd/src/batch_exec.go | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/cmd/src/batch_exec.go b/cmd/src/batch_exec.go index 76cb2bbbe2..700f82d931 100644 --- a/cmd/src/batch_exec.go +++ b/cmd/src/batch_exec.go @@ -185,14 +185,17 @@ func executeBatchSpecInWorkspaces(ctx context.Context, flags *executorModeFlags) } ui.PreparingContainerImagesSuccess() - // Empty for now until we support secrets or env var settings in SSBC. - var globalEnv []string - // Set up the execution UI. taskExecUI := ui.ExecutingTasks(false, 1) taskExecUI.Start([]*executor.Task{task}) taskExecUI.TaskStarted(task) + // Pass the os.Environ to run steps to allow access to the secrets set + // in the executor environment. + // The executor runtime takes care of not forwarding any sensitive secrets + // from the host, so this is safe. + globalEnv := os.Environ() + opts := &executor.RunStepsOpts{ Logger: &log.NoopTaskLogger{}, WC: workspace.NewExecutorWorkspaceCreator(tempDir, repoDir), From 1174f68625716722b0b75cf07a52c6f605692d4c Mon Sep 17 00:00:00 2001 From: Adam Harvey Date: Fri, 21 Oct 2022 12:51:02 -0700 Subject: [PATCH 255/647] batches: fix whitespace problem introduced in #860 (#873) --- internal/batches/service/remote.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/internal/batches/service/remote.go b/internal/batches/service/remote.go index f671715def..f196e6b645 100644 --- a/internal/batches/service/remote.go +++ b/internal/batches/service/remote.go @@ -275,9 +275,9 @@ query BatchSpecWorkspaceResolution($batchSpec: ID!) { workspaceResolution { failureMessage state - workspaces { - totalCount - } + workspaces { + totalCount + } } } } From fc3f13fb02ad353d56b6c6993f6811364c1f308d Mon Sep 17 00:00:00 2001 From: Christine Lovett Date: Tue, 25 Oct 2022 17:03:47 -0700 Subject: [PATCH 256/647] Changed query syntax link to correct page (#874) --- cmd/src/search.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/src/search.go b/cmd/src/search.go index 1a69916019..b4529da7c3 100644 --- a/cmd/src/search.go +++ b/cmd/src/search.go @@ -48,7 +48,7 @@ Other tips: Force color output on (not on by default when piped to other programs) by setting COLOR=t - Query syntax: https://about.sourcegraph.com/docs/search/query-syntax/ + Query syntax: https://docs.sourcegraph.com/code_search/reference/queries Be careful with search strings including negation: a search with an initial negated term may be parsed as a flag rather than as a search string. You can From ee916cd15a7cf77f15ded0bb367dec7d21f53d80 Mon Sep 17 00:00:00 2001 From: JIMMY ZHAO Date: Fri, 4 Nov 2022 13:13:40 -0400 Subject: [PATCH 257/647] Add windows tutorial for cli config (#875) Co-authored-by: Bolaji Olajide <25608335+BolajiOlajide@users.noreply.github.com> --- README.md | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 3fcdf01bf0..a1c954a49c 100644 --- a/README.md +++ b/README.md @@ -120,7 +120,11 @@ Run src login SOURCEGRAPH-URL to authentica - `SRC_ENDPOINT`: the URL to your Sourcegraph instance (such as `https://sourcegraph.example.com`) - `SRC_ACCESS_TOKEN`: your Sourcegraph access token (on your Sourcegraph instance, click your user menu in the top right, then select **Settings > Access tokens** to create one) -For convenience, you can export these environment variables in your shell profile. To configure them as environment variables, add the following to your terminal profile file, typically accessible at `~/.bash_profile` (if using Bash) or `~/.zprofile` (if using Zsh): +For convenience, you can add these environment variables persistently. + +### Configuration: Mac OS / Linux + +Add the following to your terminal profile file, typically accessible at `~/.bash_profile` (if using Bash) or `~/.zprofile` (if using Zsh): ``` export SRC_ACCESS_TOKEN=my-token @@ -135,6 +139,19 @@ You can also inline them in a single command with: SRC_ENDPOINT=https://sourcegraph.example.com SRC_ACCESS_TOKEN=my-token src search 'foo' ``` +### Configuration: Windows + +Type the following on your PowerShell terminal: + +``` +$env.SRC_ENDPOINT = 'https://sourcegraph.example.com' +$env.SRC_ACCESS_TOKEN = 'my-token' +``` + +Replace `my-token` and `https://sourcegraph.example.com` with the appropriate values for your account and instance. + +You can also manually add them via the *System Properties* windows. Check [this post](https://www.computerhope.com/issues/ch000549.htm) for details. + Is your Sourcegraph instance behind a custom auth proxy? See [auth proxy configuration](./AUTH_PROXY.md) docs. ## Usage From 993ee0aaa595a04237ff02528722de182b958441 Mon Sep 17 00:00:00 2001 From: Kelli Rockwell Date: Sun, 6 Nov 2022 21:18:49 -0800 Subject: [PATCH 258/647] Use `GITHUB_REF_NAME` to determine current tag for release workflow (#879) --- .github/workflows/goreleaser.yml | 33 ++++++++++++++++++++------------ 1 file changed, 21 insertions(+), 12 deletions(-) diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index cc5fd77c8a..11acdb772e 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -35,9 +35,9 @@ on: # goreleaser_post [if case 1.] - updates symlink to latest version # npm [always] - publishes to npm jobs: - # release_type compares the most recently created tag to the highest versioned tag - # available on the repo to determine if this release is for a new latest version or a - # patch of an older version. + # release_type compares the current tag to the highest versioned tag available on the + # repo to determine if this release is for a new latest version or a patch of an older + # version. release_type: name: Determine release type runs-on: ubuntu-latest @@ -50,12 +50,12 @@ jobs: uses: actions/checkout@v3 with: fetch-depth: 0 - - name: Fetch most recent tag, latest (highest version) tag, and second latest tag + - name: Set current tag, latest (highest version) tag, and second latest tag # For latest and second latest tags, we can't use git tag --sort=version:refname # because git doesn't have a concept of pre-release versions and thus mis-sorts # versions like 4.0.0-rc.0 *after* 4.0.0. run: | - echo "most_recent_tag=$(git tag --sort=taggerdate | tail -1)" >> $GITHUB_ENV + echo "current_tag=${GITHUB_REF_NAME}" >> $GITHUB_ENV echo "latest_tag=$(git tag | tr - \~ | sort --version-sort | tr \~ - | tail -1)" >> $GITHUB_ENV echo "second_latest_tag=$(git tag | tr - \~ | sort --version-sort | tr \~ - | tail -2 | sed -n 1p)" >> $GITHUB_ENV - name: Install semver @@ -63,10 +63,14 @@ jobs: wget -O /usr/local/bin/semver https://raw.githubusercontent.com/fsaintjacques/semver-tool/master/src/semver chmod +x /usr/local/bin/semver - name: Compare tags - # If the most recent tag is also the latest tag, semver compare returns 0. If it's - # a patch of an older version, semver compare will return -1. + # If the current tag is also the latest (highest-versioned) tag, semver compare + # returns 0. If the current tag is older (i.e. it's a patch for an older version), + # semver compare will return -1. By definition, it should be impossible for the + # current tag to be newer than the latest tag unless somehow the current tag is + # not a real tag, but if for some reason this happens, it will be treated the same + # as if it were the latest. run: | - if [[ $(semver compare ${{ env.latest_tag }} ${{ env.most_recent_tag }}) == 0 ]] + if [ "$(semver compare ${{ env.current_tag }} ${{ env.latest_tag }})" -ge 0 ] then echo "is_latest_version=1" >> $GITHUB_ENV else @@ -74,9 +78,14 @@ jobs: fi - name: Log variables run: | - echo "Most recent (current) tag: ${{ env.most_recent_tag }}" - echo "Latest version tag: ${{ env.latest_tag }}" - echo "Building current version as new latest?: ${{ env.is_latest_version }}" + echo "Version for this release: ${{ env.current_tag }}" + echo "Latest version: ${{ env.latest_tag }}" + if [[ ${{ env.is_latest_version }} == 1 ]] + then + echo "Releasing new latest version." + else + echo "Releasing patch of older version." + fi # goreleaser_pre copies the main formula in our Homebrew tap for the previous latest # release (second latest tag) to a versioned formula, so that it is preserved when @@ -103,7 +112,7 @@ jobs: echo "versioned_classname=SrcCliAT$(echo ${{ env.second_latest_tag }} | sed 's/\.//g')" >> $GITHUB_ENV - name: Log variables run: | - echo "Second latest tag: ${{ env.second_latest_tag }}" + echo "Second latest tag (previous latest release): ${{ env.second_latest_tag }}" echo "Versioned formula file: ${{ env.versioned_formula_file }}" echo "Versioned classname: ${{ env.versioned_classname }}" - name: Checkout Homebrew tap From c908e51b3c5df9c01fbb62b7b88cd093f696d5b7 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Mon, 7 Nov 2022 13:17:39 +0100 Subject: [PATCH 259/647] Improve log output of docker pull errors (#880) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Recently a customer ran into _some_ issue but we weren't able to tell WHAT the issue was. This adds additional log output. *Before* ``` ✅ Parsing batch spec ✅ Resolving namespace ⠸ Preparing container images 0% ❌ Error: pulling image "ubunootu:18.04": pulling image: exit status 1 💡 The troubleshooting documentation can help to narrow down the cause of the errors: https://docs.sourcegraph.com/batch_changes/references/troubleshooting ``` *After* ``` ✅ Parsing batch spec ✅ Resolving namespace ⠏ Preparing container images 0% ❌ Error: pulling image "ubunootu:18.04": failed to pull image: Error response from daemon: failed to resolve reference "docker.io/library/ubunootu:18.04": pull access denied, repository does not exist or may require authorization: server message: insufficient_scope: authorization failed docker pull exited with code 1 💡 The troubleshooting documentation can help to narrow down the cause of the errors: https://docs.sourcegraph.com/batch_changes/references/troubleshooting ``` --- internal/batches/docker/image.go | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/internal/batches/docker/image.go b/internal/batches/docker/image.go index 90fb7e3d89..279ef0b949 100644 --- a/internal/batches/docker/image.go +++ b/internal/batches/docker/image.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "fmt" + goexec "os/exec" "strings" "sync" @@ -87,7 +88,7 @@ func (image *image) Ensure(ctx context.Context) error { defer cancel() args := []string{"image", "inspect", "--format", "{{ .Id }}", image.name} - out, err := exec.CommandContext(dctx, "docker", args...).CombinedOutput() + out, err := exec.CommandContext(dctx, "docker", args...).Output() id := string(bytes.TrimSpace(out)) if errors.IsDeadlineExceeded(err) || errors.IsDeadlineExceeded(dctx.Err()) { @@ -108,7 +109,14 @@ func (image *image) Ensure(ctx context.Context) error { return err } else if err != nil { // Let's try pulling the image. - if err := exec.CommandContext(ctx, "docker", "image", "pull", image.name).Run(); err != nil { + pullCmd := exec.CommandContext(ctx, "docker", "image", "pull", image.name) + var stderr bytes.Buffer + pullCmd.Stderr = &stderr + if err := pullCmd.Run(); err != nil { + exitErr := &goexec.ExitError{} + if errors.As(err, &exitErr) { + return errors.Newf("failed to pull image: %s\ndocker pull exited with code %d", stderr.String(), exitErr.ExitCode()) + } return errors.Wrap(err, "pulling image") } // And try again to get the image digest. From d5778f1df4555cf4b5add6794ed578b64f55c566 Mon Sep 17 00:00:00 2001 From: Philipp Spiess Date: Mon, 7 Nov 2022 14:39:01 +0000 Subject: [PATCH 260/647] Fix broken code-intel link (#882) --- cmd/src/code_intel_upload.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/src/code_intel_upload.go b/cmd/src/code_intel_upload.go index 566010805e..73548289f4 100644 --- a/cmd/src/code_intel_upload.go +++ b/cmd/src/code_intel_upload.go @@ -272,7 +272,7 @@ func filterLSIFUnauthorizedError(out *output.Output, err error) error { return errorWithHint{err: err, hint: strings.Join(mergeStringSlices( []string{"This Sourcegraph instance has enforced auth for LSIF uploads."}, actionableHints, - []string{"For more details, see https://docs.sourcegraph.com/cli/references/lsif/upload."}, + []string{"For more details, see https://docs.sourcegraph.com/cli/references/code-intel/upload."}, ), "\n")} } From 43463887d3693b860f8a2519f43441886e75735b Mon Sep 17 00:00:00 2001 From: Randell Callahan Date: Mon, 7 Nov 2022 08:38:47 -0700 Subject: [PATCH 261/647] batches: Workspace file upload for local runs (#861) --- CHANGELOG.md | 2 ++ cmd/src/batch_common.go | 17 +++++++++++++++++ internal/batches/ui/exec_ui.go | 4 ++++ internal/batches/ui/json_lines.go | 12 ++++++++++++ internal/batches/ui/tui.go | 10 ++++++++++ 5 files changed, 45 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index a3f8a3cc14..d40ca1db83 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,8 @@ All notable changes to `src-cli` are documented in this file. ### Added +- Mounted file are now uploaded to the Sourcegraph instance when running `src batch preview` and `src batch apply`. [#861](https://github.com/sourcegraph/src-cli/pull/861) + ### Changed ### Fixed diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index 8bfee5a05e..c828401a5b 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -481,6 +481,23 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp previewURL := cfg.Endpoint + url ui.CreatingBatchSpecSuccess(previewURL) + hasWorkspaceFiles := false + for _, step := range batchSpec.Steps { + if len(step.Mount) > 0 { + hasWorkspaceFiles = true + break + } + } + if hasWorkspaceFiles { + ui.UploadingWorkspaceFiles() + if err = svc.UploadBatchSpecWorkspaceFiles(ctx, batchSpecDir, string(id), batchSpec.Steps); err != nil { + // Since failing to upload workspace files should not stop processing, just warn + ui.UploadingWorkspaceFilesWarning(errors.Wrap(err, "uploading workspace files")) + } else { + ui.UploadingWorkspaceFilesSuccess() + } + } + if !opts.applyBatchSpec { ui.PreviewBatchSpec(previewURL) return diff --git a/internal/batches/ui/exec_ui.go b/internal/batches/ui/exec_ui.go index ecedfcfcac..e6e8bdeeec 100644 --- a/internal/batches/ui/exec_ui.go +++ b/internal/batches/ui/exec_ui.go @@ -48,4 +48,8 @@ type ExecUI interface { ApplyingBatchSpecSuccess(batchChangeURL string) ExecutionError(error) + + UploadingWorkspaceFiles() + UploadingWorkspaceFilesWarning(error) + UploadingWorkspaceFilesSuccess() } diff --git a/internal/batches/ui/json_lines.go b/internal/batches/ui/json_lines.go index 54795ec6ba..f584a25a51 100644 --- a/internal/batches/ui/json_lines.go +++ b/internal/batches/ui/json_lines.go @@ -335,6 +335,18 @@ func (ui *stepsExecutionJSONLines) StepFailed(step int, err error, exitCode int) ) } +func (ui *JSONLines) UploadingWorkspaceFiles() { + // No workspace file upload required for executor mode. +} + +func (ui *JSONLines) UploadingWorkspaceFilesWarning(err error) { + // No workspace file upload required for executor mode. +} + +func (ui *JSONLines) UploadingWorkspaceFilesSuccess() { + // No workspace file upload required for executor mode. +} + func logOperationStart(op batcheslib.LogEventOperation, metadata interface{}) { logEvent(batcheslib.LogEvent{Operation: op, Status: batcheslib.LogEventStatusStarted, Metadata: metadata}) } diff --git a/internal/batches/ui/tui.go b/internal/batches/ui/tui.go index f5a8bade25..3d4ad1b21d 100644 --- a/internal/batches/ui/tui.go +++ b/internal/batches/ui/tui.go @@ -23,6 +23,8 @@ var ( batchPendingColor = output.StylePending batchSuccessColor = output.StyleSuccess batchSuccessEmoji = output.EmojiSuccess + batchWarningColor = output.StyleWarning + batchWarningEmoji = output.EmojiWarning ) var _ ExecUI = &TUI{} @@ -263,6 +265,10 @@ func (ui *TUI) UploadingWorkspaceFiles() { ui.pending = batchCreatePending(ui.Out, "Uploading workspace files") } +func (ui *TUI) UploadingWorkspaceFilesWarning(err error) { + batchCompleteWarning(ui.pending, err.Error()) +} + func (ui *TUI) UploadingWorkspaceFilesSuccess() { batchCompletePending(ui.pending, "Uploading workspace files") } @@ -439,3 +445,7 @@ func batchCreatePending(out *output.Output, message string) output.Pending { func batchCompletePending(p output.Pending, message string) { p.Complete(output.Line(batchSuccessEmoji, batchSuccessColor, message)) } + +func batchCompleteWarning(p output.Pending, message string) { + p.Complete(output.Line(batchWarningEmoji, batchWarningColor, message)) +} From eaf900bcc0092158c6b7e1e8a6d400745d363597 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Mon, 7 Nov 2022 18:11:47 +0100 Subject: [PATCH 262/647] Add changelog entry for 4.1.1 (#881) --- CHANGELOG.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index d40ca1db83..ecbf1269d8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,12 @@ All notable changes to `src-cli` are documented in this file. ### Removed +## 4.1.1 + +### Changed + +- Improved output for failing docker pulls in batch change execution. [#880](https://github.com/sourcegraph/src-cli/pull/880) + ## 4.1.0 ### Changed From 8424c23429ba06f73177f6fcd17451a87862e454 Mon Sep 17 00:00:00 2001 From: Kelli Rockwell Date: Mon, 7 Nov 2022 09:59:26 -0800 Subject: [PATCH 263/647] Prepare changelog for 4.1.1 (#883) --- CHANGELOG.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ecbf1269d8..59fbf52adb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,8 +13,6 @@ All notable changes to `src-cli` are documented in this file. ### Added -- Mounted file are now uploaded to the Sourcegraph instance when running `src batch preview` and `src batch apply`. [#861](https://github.com/sourcegraph/src-cli/pull/861) - ### Changed ### Fixed @@ -23,6 +21,10 @@ All notable changes to `src-cli` are documented in this file. ## 4.1.1 +### Added + +- Mounted files are now uploaded to the Sourcegraph instance when running `src batch preview` and `src batch apply`. [#861](https://github.com/sourcegraph/src-cli/pull/861) + ### Changed - Improved output for failing docker pulls in batch change execution. [#880](https://github.com/sourcegraph/src-cli/pull/880) From 73964e6b4f39f9be8b6a7247b0cf7fe872cefe5a Mon Sep 17 00:00:00 2001 From: Bolaji Olajide <25608335+BolajiOlajide@users.noreply.github.com> Date: Wed, 16 Nov 2022 18:39:41 +0100 Subject: [PATCH 264/647] update changelog (#884) --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 59fbf52adb..aacda325e0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,10 @@ All notable changes to `src-cli` are documented in this file. ### Removed +## 4.2.0 + +No noteworthy changes, mechanical release to match Sourcegraph release. + ## 4.1.1 ### Added From e77731fd1471d495fbab464b5ce3ccfcaf483723 Mon Sep 17 00:00:00 2001 From: Bolaji Olajide <25608335+BolajiOlajide@users.noreply.github.com> Date: Thu, 17 Nov 2022 13:06:51 +0100 Subject: [PATCH 265/647] update release process (#885) * update release process * Update DEVELOPMENT.md Co-authored-by: Kelli Rockwell Co-authored-by: Kelli Rockwell --- DEVELOPMENT.md | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index 144717ce26..e7f75d1cc3 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -60,12 +60,19 @@ We adhere to the [general Sourcegraph principles for testing](https://docs.sourc 2. (optional) If this is a non-patch release, update the changelog. Add a new section `## $MAJOR.MINOR` to [`CHANGELOG.md`](https://github.com/sourcegraph/src-cli/blob/main/CHANGELOG.md#unreleased) immediately under `## Unreleased changes`. Add new empty `Added`, `Changed`, `Fixed`, and `Removed` sections under `## Unreleased changes`. Open a pull request with the new changelog. Get the pull request merged before completing the next step. 3. `VERSION=9.9.9 ./release.sh` (replace `9.9.9` with the version you are releasing) 4. GitHub will automatically perform the release via the [Build and Release action](https://github.com/sourcegraph/src-cli/actions?query=workflow%3ABuild+and+Release). Once it has finished, **you need to confirm**: - 1. The [curl commands in the README](README.markdown#installation) fetch the latest version above. - 2. The [releases section of the repo sidebar](https://github.com/sourcegraph/src-cli) shows the correct version. + 1. The brew formula shows the correct version. + ```shell + brew info sourcegraph/src-cli/src-cli + ``` + 2. The npm library shows the correct version. + ```shell + npm show @sourcegraph/src version + ``` + 3. The [releases section of the repo sidebar](https://github.com/sourcegraph/src-cli) shows the correct version. 5. Make the necessary updates to the main Sourcegraph repo: 1. Update the `MinimumVersion` constant in the [src-cli package](https://github.com/sourcegraph/sourcegraph/tree/main/internal/src-cli/consts.go). - 2. Update the reference documentation by running `go generate ./doc/cli/references`. - 3. Commit the changes, and open a PR. + 2. Commit the changes, and open a PR. + 6. Once the version bump PR is merged and the commit is live on dotcom, check that the [curl commands in the README](README.markdown#installation) also fetch the new latest version. ### Patch releases From c9902bf2acccadd07cdbddde8652ecda2da86673 Mon Sep 17 00:00:00 2001 From: Adam Harvey Date: Thu, 17 Nov 2022 16:27:22 -0800 Subject: [PATCH 266/647] batches: improve handling of non-root steps (#886) This changes the default for `src batch exec` (used by SSBC) to run all step containers as root, and adds a flag to `src batch apply` and `src batch preview` to optionally do the same thing. Fixes sourcegraph/sourcegraph#41836. --- CHANGELOG.md | 4 ++++ cmd/src/batch_common.go | 7 +++++++ cmd/src/batch_exec.go | 3 +++ internal/batches/executor/executor.go | 2 ++ internal/batches/executor/run_steps.go | 7 +++++++ 5 files changed, 23 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index aacda325e0..1a81623fd5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,8 +13,12 @@ All notable changes to `src-cli` are documented in this file. ### Added +- Batch specs being run locally with `src batch preview` or `src batch apply` can now be run with the `-run-as-root` flag, which will run all step containers as root instead of the default user for the image. This is off by default. [#886](https://github.com/sourcegraph/src-cli/pull/886) + ### Changed +- Batch specs being run from the server using this version of `src-cli` now run all step containers as root, rather than as the default user for the image. [#886](https://github.com/sourcegraph/src-cli/pull/886) + ### Fixed ### Removed diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index c828401a5b..c387c60055 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -85,6 +85,7 @@ type batchExecuteFlags struct { workspace string cleanArchives bool skipErrors bool + runAsRoot bool // EXPERIMENTAL textOnly bool @@ -152,6 +153,11 @@ func newBatchExecuteFlags(flagSet *flag.FlagSet, cacheDir, tempDir string) *batc flagSet.BoolVar(verbose, "v", false, "print verbose output") + flagSet.BoolVar( + &caf.runAsRoot, "run-as-root", false, + "If true, forces all step containers to run as root.", + ) + return caf } @@ -382,6 +388,7 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp Timeout: opts.flags.timeout, TempDir: opts.flags.tempDir, GlobalEnv: os.Environ(), + ForceRoot: opts.flags.runAsRoot, }, Logger: logManager, Cache: executor.NewDiskCache(opts.flags.cacheDir), diff --git a/cmd/src/batch_exec.go b/cmd/src/batch_exec.go index 700f82d931..d4592ce139 100644 --- a/cmd/src/batch_exec.go +++ b/cmd/src/batch_exec.go @@ -33,6 +33,7 @@ const ( type executorModeFlags struct { timeout time.Duration file string + runAsImageUser bool tempDir string repoDir string workspaceFilesDir string @@ -42,6 +43,7 @@ func newExecutorModeFlags(flagSet *flag.FlagSet) (f *executorModeFlags) { f = &executorModeFlags{} flagSet.DurationVar(&f.timeout, "timeout", 60*time.Minute, "The maximum duration a single batch spec step can take.") flagSet.StringVar(&f.file, "f", "", "The workspace execution input file to read.") + flagSet.BoolVar(&f.runAsImageUser, "run-as-image-user", false, "True to run step containers as the default image user; if false or omitted, containers are always run as root.") flagSet.StringVar(&f.tempDir, "tmp", "", "Directory for storing temporary data.") flagSet.StringVar(&f.repoDir, "repo", "", "Path of the checked out repo on disk.") flagSet.StringVar(&f.workspaceFilesDir, "workspaceFiles", "", "Path of workspace files on disk.") @@ -208,6 +210,7 @@ func executeBatchSpecInWorkspaces(ctx context.Context, flags *executorModeFlags) GlobalEnv: globalEnv, RepoArchive: &repozip.NoopArchive{}, UI: taskExecUI.StepsExecutionUI(task), + ForceRoot: !flags.runAsImageUser, } results, err := executor.RunSteps(ctx, opts) diff --git a/internal/batches/executor/executor.go b/internal/batches/executor/executor.go index 463f46f8c0..657e79e7e5 100644 --- a/internal/batches/executor/executor.go +++ b/internal/batches/executor/executor.go @@ -68,6 +68,7 @@ type NewExecutorOpts struct { TempDir string IsRemote bool GlobalEnv []string + ForceRoot bool } type executor struct { @@ -178,6 +179,7 @@ func (x *executor) do(ctx context.Context, task *Task, ui TaskExecutionUI) (err Timeout: x.opts.Timeout, RepoArchive: repoArchive, WorkingDirectory: x.opts.WorkingDirectory, + ForceRoot: x.opts.ForceRoot, UI: ui.StepsExecutionUI(task), } diff --git a/internal/batches/executor/run_steps.go b/internal/batches/executor/run_steps.go index 7804793e32..b4911640f9 100644 --- a/internal/batches/executor/run_steps.go +++ b/internal/batches/executor/run_steps.go @@ -51,6 +51,9 @@ type RunStepsOpts struct { // GlobalEnv is the os.Environ() for the execution. We don't read from os.Environ() // directly to allow injecting variables and hiding others. GlobalEnv []string + // ForceRoot forces Docker containers to be run as root:root, rather than + // whatever the image's default user and group are. + ForceRoot bool } func RunSteps(ctx context.Context, opts *RunStepsOpts) (stepResults []execution.AfterStepResult, err error) { @@ -317,6 +320,10 @@ func executeSingleStep( "--mount", fmt.Sprintf("type=bind,source=%s,target=%s,ro", runScriptFile, containerTemp), }, workspaceOpts...) + if opts.ForceRoot { + args = append(args, "--user", "0:0") + } + for target, source := range filesToMount { args = append(args, "--mount", fmt.Sprintf("type=bind,source=%s,target=%s,ro", source.Name(), target)) } From 4d2957c8ae98d81194ed6bad4500abe8dfc521e0 Mon Sep 17 00:00:00 2001 From: Robert Lin Date: Fri, 25 Nov 2022 14:27:03 -0800 Subject: [PATCH 267/647] snapshot: add 'snapshot summary', 'snapshot test' (#888) --- cmd/src/snapshot.go | 31 ++++ cmd/src/snapshot_summary.go | 106 ++++++++++++ cmd/src/snapshot_testcmd.go | 102 +++++++++++ internal/instancehealth/checks.go | 231 +++++++++++++++++++++++++ internal/instancehealth/checks_test.go | 85 +++++++++ internal/instancehealth/summary.go | 119 +++++++++++++ 6 files changed, 674 insertions(+) create mode 100644 cmd/src/snapshot.go create mode 100644 cmd/src/snapshot_summary.go create mode 100644 cmd/src/snapshot_testcmd.go create mode 100644 internal/instancehealth/checks.go create mode 100644 internal/instancehealth/checks_test.go create mode 100644 internal/instancehealth/summary.go diff --git a/cmd/src/snapshot.go b/cmd/src/snapshot.go new file mode 100644 index 0000000000..0c604ca088 --- /dev/null +++ b/cmd/src/snapshot.go @@ -0,0 +1,31 @@ +package main + +import ( + "flag" + "fmt" +) + +var snapshotCommands commander + +func init() { + usage := `'src snapshot' manages snapshots of Sourcegraph instance data. All subcommands are currently EXPERIMENTAL. + +USAGE + src [-v] snapshot + +COMMANDS + + summary export summary data about an instance for acceptance testing of a restored Sourcegraph instance + test use exported summary data and instance health indicators to validate a restored and upgraded instance +` + flagSet := flag.NewFlagSet("snapshot", flag.ExitOnError) + + commands = append(commands, &command{ + flagSet: flagSet, + handler: func(args []string) error { + snapshotCommands.run(flagSet, "src snapshot", usage, args) + return nil + }, + usageFunc: func() { fmt.Fprint(flag.CommandLine.Output(), usage) }, + }) +} diff --git a/cmd/src/snapshot_summary.go b/cmd/src/snapshot_summary.go new file mode 100644 index 0000000000..56223723f4 --- /dev/null +++ b/cmd/src/snapshot_summary.go @@ -0,0 +1,106 @@ +package main + +import ( + "context" + "encoding/json" + "flag" + "fmt" + "os" + + "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/output" + + "github.com/sourcegraph/src-cli/internal/api" +) + +func init() { + usage := `'src snapshot summary' generates summary data for acceptance testing of a restored Sourcegraph instance with 'src snapshot test'. + +USAGE + src login # site-admin authentication required + src [-v] snapshot summary [-summary-path="./src-snapshot-summary.json"] +` + flagSet := flag.NewFlagSet("summary", flag.ExitOnError) + snapshotPath := flagSet.String("summary-path", "./src-snapshot-summary.json", "path to write snapshot summary to") + apiFlags := api.NewFlags(flagSet) + + snapshotCommands = append(snapshotCommands, &command{ + flagSet: flagSet, + handler: func(args []string) error { + if err := flagSet.Parse(args); err != nil { + return err + } + out := output.NewOutput(flagSet.Output(), output.OutputOpts{Verbose: *verbose}) + + client := cfg.apiClient(apiFlags, flagSet.Output()) + + snapshotResult, err := fetchSnapshotSummary(context.Background(), client) + if err != nil { + return err + } + + f, err := os.OpenFile(*snapshotPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm) + if err != nil { + return errors.Wrap(err, "open snapshot file") + } + enc := json.NewEncoder(f) + enc.SetIndent("", "\t") + if err := enc.Encode(snapshotResult); err != nil { + return errors.Wrap(err, "write snapshot file") + } + + out.WriteLine(output.Emoji(output.EmojiSuccess, "Summary snapshot data generated!")) + return nil + }, + usageFunc: func() { fmt.Fprint(flag.CommandLine.Output(), usage) }, + }) +} + +type snapshotSummary struct { + ExternalServices struct { + TotalCount int + Nodes []struct { + Kind string + ID string + } + } + Site struct { + AuthProviders struct { + TotalCount int + Nodes []struct { + ServiceType string + ServiceID string + } + } + } +} + +func fetchSnapshotSummary(ctx context.Context, client api.Client) (*snapshotSummary, error) { + var snapshotResult snapshotSummary + ok, err := client.NewQuery(` + query GenerateSnapshotAcceptanceData { + externalServices { + totalCount + nodes { + kind + id + } + } + site { + authProviders { + totalCount + nodes { + serviceType + serviceID + } + } + } + } + `).Do(ctx, &snapshotResult) + if err != nil { + return nil, errors.Wrap(err, "generate snapshot") + } else if !ok { + return nil, errors.New("received no data") + } + return &snapshotResult, nil +} diff --git a/cmd/src/snapshot_testcmd.go b/cmd/src/snapshot_testcmd.go new file mode 100644 index 0000000000..1d8fb89d14 --- /dev/null +++ b/cmd/src/snapshot_testcmd.go @@ -0,0 +1,102 @@ +package main + +import ( + "context" + "encoding/json" + "flag" + "fmt" + "os" + "time" + + "github.com/google/go-cmp/cmp" + "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/output" + + "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/instancehealth" +) + +// note that this file is called '_testcmd.go' because '_test.go' cannot be used + +func init() { + usage := `'src snapshot test' uses exported summary data to validate a restored and upgraded instance. + +USAGE + src login # site-admin authentication required + src [-v] snapshot test [-summary-path="./src-snapshot-summary.json"] +` + flagSet := flag.NewFlagSet("test", flag.ExitOnError) + snapshotSummaryPath := flagSet.String("summary-path", "./src-snapshot-summary.json", "path to read snapshot summary from") + since := flagSet.Duration("since", 1*time.Hour, "duration ago to look for healthcheck data") + apiFlags := api.NewFlags(flagSet) + + snapshotCommands = append(snapshotCommands, &command{ + flagSet: flagSet, + handler: func(args []string) error { + if err := flagSet.Parse(args); err != nil { + return err + } + out := output.NewOutput(flagSet.Output(), output.OutputOpts{Verbose: *verbose}) + client := cfg.apiClient(apiFlags, flagSet.Output()) + + // Fetch health data + instanceHealth, err := instancehealth.GetIndicators(context.Background(), client) + if err != nil { + return err + } + + // Optionally validate snapshots + if *snapshotSummaryPath != "" { + f, err := os.OpenFile(*snapshotSummaryPath, os.O_RDONLY, os.ModePerm) + if err != nil { + return errors.Wrap(err, "open snapshot file") + } + var recordedSummary snapshotSummary + if err := json.NewDecoder(f).Decode(&recordedSummary); err != nil { + return errors.Wrap(err, "read snapshot file") + } + // Fetch new snapshot + newSummary, err := fetchSnapshotSummary(context.Background(), client) + if err != nil { + return errors.Wrap(err, "get snapshot") + } + if err := compareSnapshotSummaries(out, recordedSummary, *newSummary); err != nil { + return err + } + } + + // generate checks set + checks := instancehealth.NewChecks(*since, *instanceHealth) + + // Run checks + var validationErrors error + for _, check := range checks { + validationErrors = errors.Append(validationErrors, check(out)) + } + if validationErrors != nil { + out.WriteLine(output.Linef(output.EmojiFailure, output.StyleFailure, + "Critical issues found: %s", err.Error())) + return errors.New("validation failed") + } + out.WriteLine(output.Line(output.EmojiSuccess, output.StyleSuccess, + "No critical issues found!")) + return nil + }, + usageFunc: func() { fmt.Fprint(flag.CommandLine.Output(), usage) }, + }) +} + +func compareSnapshotSummaries(out *output.Output, recordedSummary, newSummary snapshotSummary) error { + b := out.Block(output.Styled(output.StyleBold, "Snapshot contents")) + defer b.Close() + + // Compare + diff := cmp.Diff(recordedSummary, newSummary) + if diff != "" { + b.WriteLine(output.Line(output.EmojiFailure, output.StyleFailure, "Snapshot diff detected:")) + b.WriteCode("diff", diff) + return errors.New("snapshot mismatch") + } + b.WriteLine(output.Emoji(output.EmojiSuccess, "Snapshots match!")) + return nil +} diff --git a/internal/instancehealth/checks.go b/internal/instancehealth/checks.go new file mode 100644 index 0000000000..0c2e2557ce --- /dev/null +++ b/internal/instancehealth/checks.go @@ -0,0 +1,231 @@ +package instancehealth + +import ( + "fmt" + "strings" + "time" + + "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/output" +) + +// NewChecks returns a set of checks against the given inputs to validate the +// health of a Sourcegraph application. It is designed primarily to validate +// information that can be provided via the GraphQL API - see GetSummary for +// more details. +// +// Each test errors with only a brief summary of what went wrong, and only if +// the error is critical. Detailed output should be written to out. +func NewChecks( + since time.Duration, + instanceHealth Indicators, +) []func(out *output.Output) error { + return []func(out *output.Output) error{ + func(out *output.Output) error { + b := out.Block(output.Styled(output.StyleBold, "Site alerts")) + defer b.Close() + return checkSiteAlerts(b, instanceHealth) + }, + func(out *output.Output) error { + b := out.Block(output.Styled(output.StyleBold, "Site configuration")) + defer b.Close() + return checkSiteConfiguration(b, instanceHealth) + }, + func(out *output.Output) error { + b := out.Block(output.Styled(output.StyleBold, "Monitoring alerts")) + defer b.Close() + return checkMonitoringAlerts(b, since, instanceHealth) + }, + func(out *output.Output) error { + b := out.Block(output.Styled(output.StyleBold, "External services")) + defer b.Close() + return checkExternalServices(b, since, instanceHealth) + }, + func(out *output.Output) error { + b := out.Block(output.Styled(output.StyleBold, "Permissions syncing")) + defer b.Close() + return checkPermissionsSyncing(b, since, instanceHealth) + }, + } +} + +// checkSiteAlerts indicates if there are any alerts issued by the application +func checkSiteAlerts( + out output.Writer, + instanceHealth Indicators, +) error { + if len(instanceHealth.Site.Alerts) > 0 { + out.WriteLine(output.Linef(output.EmojiWarning, output.StyleWarning, + "Found site-level alerts:")) + for _, a := range instanceHealth.Site.Alerts { + out.Writef("\t%s: %q", a.Type, a.Message) + } + return errors.New("site-level alerts") + } + out.WriteLine(output.Emoji(output.EmojiSuccess, "No site-level alerts!")) + return nil +} + +// checkSiteAlerts indicates if there are any alerts issued by the application regarding +// configuration validation +func checkSiteConfiguration( + out output.Writer, + instanceHealth Indicators, +) error { + if len(instanceHealth.Site.Configuration.ValidationMessages) > 0 { + out.WriteLine(output.Linef(output.EmojiWarning, output.StyleWarning, + "Found configuration validation alerts:")) + for _, m := range instanceHealth.Site.Configuration.ValidationMessages { + out.Writef("\t%s", m) + } + } else { + out.WriteLine(output.Emoji(output.EmojiSuccess, "No site configuration issues!")) + } + // never error, just issue printed warning, since the application should still work + // even with validation messages + return nil +} + +// checkMonitoringAlerts indicates if there are any alerts issued by monitoring infra +func checkMonitoringAlerts( + out output.Writer, + since time.Duration, + instanceHealth Indicators, +) error { + var criticalAlerts int + for _, a := range instanceHealth.Site.MonitoringStatistics.Alerts { + if a.Average == 0 || !strings.Contains(strings.ToLower(a.Name), "critical") { + continue + } + // average is ratio of 12h windows that alert was active, so we set the threshold + // if it's possible this alert could have been active in this 'since' window. + if a.Average*0.5 >= since.Hours()/12 { + criticalAlerts += 1 + out.WriteLine(output.Linef(output.EmojiWarning, output.StyleWarning, + "Found recently active alert: %q", a.Name)) + } + } + if criticalAlerts == 0 { + out.WriteLine(output.Emoji(output.EmojiSuccess, "No critical monitoring alerts!")) + } + // never error, just issue printed warning, since critical alerts aren't all _that_ + // reliable today, though they provide a potentially useful signal. + return nil +} + +// checkExternalServices checks the health of external service syncing +func checkExternalServices( + out output.Writer, + since time.Duration, + instanceHealth Indicators, +) error { + if len(instanceHealth.ExternalServices.Nodes) == 0 { + out.WriteLine(output.Linef(output.EmojiWarning, output.StyleWarning, + "No external services found")) + return nil + } + + var hasExtsvcIssue bool + for _, extsvc := range instanceHealth.ExternalServices.Nodes { + var jobCount int + for _, job := range extsvc.SyncJobs.Nodes { + if job.FinishedAt.Before(time.Now().Add(-since)) { + continue + } + jobCount++ + } + + if extsvc.LastSyncError != nil { + hasExtsvcIssue = true + out.WriteLine(output.Linef(output.EmojiFailure, output.StyleFailure, + "External service %s %q encountered sync error: %q", + extsvc.Kind, extsvc.ID, *extsvc.LastSyncError)) + } else if jobCount == 0 { + // not critical, this is somewhat normal behaviour + out.WriteLine(output.Linef(output.EmojiInfo, output.StyleSuggestion, + "External service %s %q had no sync jobs in last %s", + extsvc.Kind, extsvc.ID, since.String())) + } else { + out.WriteLine(output.Emojif(output.EmojiSuccess, + "External service %s %q healthy", + extsvc.Kind, extsvc.ID)) + } + } + if hasExtsvcIssue { + return errors.New("encountered external service issues") + } + out.WriteLine(output.Emoji(output.EmojiSuccess, "No external service issues!")) + return nil +} + +// checkPermissionsSyncing checks the health of permissions syncing +func checkPermissionsSyncing( + out output.Writer, + since time.Duration, + instanceHealth Indicators, +) error { + var syncCount int + var syncErrors []string + var seenProviders = make(map[string]map[string]string) // provider : state : message + for _, sync := range instanceHealth.PermissionsSyncJobs.Nodes { + if sync.CompletedAt.Before(time.Now().Add(-since)) { + continue + } + syncCount += 1 + if sync.Status == "ERROR" { + syncErrors = append(syncErrors, sync.Message) + } + for _, p := range sync.Providers { + key := fmt.Sprintf("%s - %s", p.Type, p.ID) + if _, ok := seenProviders[key]; !ok { + seenProviders[key] = make(map[string]string) + } + // Just track one message per state for reference + seenProviders[key][p.Status] = p.Message + } + } + + if syncCount == 0 { + out.WriteLine(output.Linef(output.EmojiWarning, output.StyleWarning, + "No permissions sync jobs since %s ago", since.String())) + return nil // there may be no permissions sync configured + } + + // Summarize results by provider + if len(seenProviders) == 0 { + out.WriteLine(output.Linef(output.EmojiWarning, output.StyleWarning, + "No authz providers running since %s ago", since.String())) + } else { + for key, messages := range seenProviders { + for state := range messages { + switch state { + case "SUCCESS": + out.WriteLine(output.Emojif(output.EmojiSuccess, + "Authz provider %q healthy", key)) + default: + out.WriteLine(output.Linef(output.EmojiWarning, output.StyleWarning, + "Authz provider %q state %s: %q", key, state, messages[state])) + } + } + } + } + + // Note if syncing is failing + if len(syncErrors) > 0 { + out.WriteLine(output.Linef(output.EmojiFailure, output.StyleFailure, + "Encountered permissions sync errors:")) + for i, msg := range syncErrors { + out.Writef("\t%q", msg) + if i > 3 && len(syncErrors)-i > 0 { + out.Writef("\t... %d more", len(syncErrors)-i) + break + } + } + return errors.New("permissions sync errors") + } else if syncCount > 0 { + out.WriteLine(output.Emoji(output.EmojiSuccess, + "Permissions syncing healthy!")) + } + + return nil +} diff --git a/internal/instancehealth/checks_test.go b/internal/instancehealth/checks_test.go new file mode 100644 index 0000000000..a0d9af9696 --- /dev/null +++ b/internal/instancehealth/checks_test.go @@ -0,0 +1,85 @@ +package instancehealth + +import ( + "bytes" + "io" + "os" + "testing" + "time" + + "github.com/sourcegraph/sourcegraph/lib/output" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// run with -v for output +func TestCheckPermissionsSyncing(t *testing.T) { + for _, tt := range []struct { + name string + instanceHealth Indicators + + wantEmojis []string + wantErr string + }{{ + name: "no jobs", + instanceHealth: Indicators{ + PermissionsSyncJobs: struct{ Nodes []permissionsSyncJob }{ + Nodes: nil, + }, + }, + wantEmojis: []string{output.EmojiWarning}, + wantErr: "", + }, { + name: "healthy", + instanceHealth: Indicators{ + PermissionsSyncJobs: struct{ Nodes []permissionsSyncJob }{ + Nodes: []permissionsSyncJob{{ + CompletedAt: time.Now(), + Status: "SUCCESS", + Providers: []permissionsProviderStatus{{ + Type: "github", + ID: "https://github.com/", + Status: "SUCCESS", + }}, + }}, + }, + }, + wantEmojis: []string{output.EmojiSuccess}, + wantErr: "", + }, { + name: "unhealthy", + instanceHealth: Indicators{ + PermissionsSyncJobs: struct{ Nodes []permissionsSyncJob }{ + Nodes: []permissionsSyncJob{{ + CompletedAt: time.Now(), + Status: "ERROR", + Message: "oh no!", + Providers: []permissionsProviderStatus{{ + Type: "github", + ID: "https://github.com/", + Status: "ERROR", + }}, + }}, + }, + }, + wantEmojis: []string{output.EmojiFailure}, + wantErr: "permissions sync errors", + }} { + t.Run(tt.name, func(t *testing.T) { + var out bytes.Buffer + err := checkPermissionsSyncing(output.NewOutput(io.MultiWriter(os.Stderr, &out), output.OutputOpts{}), time.Hour, tt.instanceHealth) + if tt.wantErr == "" { + assert.NoError(t, err) + } else { + require.Error(t, err) + assert.Contains(t, err.Error(), tt.wantErr) + } + if len(tt.wantEmojis) > 0 { + data := out.String() + for _, emoji := range tt.wantEmojis { + assert.Contains(t, data, emoji) + } + } + }) + } +} diff --git a/internal/instancehealth/summary.go b/internal/instancehealth/summary.go new file mode 100644 index 0000000000..e6320ea057 --- /dev/null +++ b/internal/instancehealth/summary.go @@ -0,0 +1,119 @@ +package instancehealth + +import ( + "context" + "time" + + "github.com/sourcegraph/sourcegraph/lib/errors" + + "github.com/sourcegraph/src-cli/internal/api" +) + +// Indicators are values from the Sourcegraph GraphQL API that help indicate the health of +// and instance. +type Indicators struct { + Site struct { + Configuration struct { + ValidationMessages []string + } + Alerts []struct { + Type string + Message string + } + MonitoringStatistics struct { + Alerts []struct { + Name string + Average float64 + } + } + } + ExternalServices struct { + Nodes []struct { + Kind string + ID string + LastSyncError *string + SyncJobs struct { + Nodes []struct { + State string + FinishedAt time.Time + } + } + } + } + PermissionsSyncJobs struct { + Nodes []permissionsSyncJob + } +} + +type permissionsSyncJob struct { + Status string + Message string + CompletedAt time.Time + Providers []permissionsProviderStatus +} + +type permissionsProviderStatus struct { + Type string + ID string + Status string + Message string +} + +// GetIndicators retrieves summary data from a Sourcegraph instance's GraphQL API for +// assessing instance health. +func GetIndicators(ctx context.Context, client api.Client) (*Indicators, error) { + var instanceHealth Indicators + ok, err := client.NewQuery(` + query InstanceHealthSummary { + site { + configuration { + validationMessages + } + alerts { + type + message + } + monitoringStatistics(days:1) { + alerts { + name + average + } + } + } + + externalServices { + nodes { + kind + id + lastSyncError + syncJobs(first:100) { + nodes { + state + finishedAt + } + } + } + } + + permissionsSyncJobs(first:500) { + nodes { + status + completedAt + message + providers { + type + id + status + message + } + } + } + } + `).Do(ctx, &instanceHealth) + if err != nil { + return nil, errors.Wrap(err, "get health data") + } else if !ok { + return nil, errors.New("received no data") + } + return &instanceHealth, nil +} From 5d82eb0496d6ac43d6d83a5ae9ee86bf83070827 Mon Sep 17 00:00:00 2001 From: Robert Lin Date: Mon, 28 Nov 2022 14:48:22 -0800 Subject: [PATCH 268/647] snapshot: add pg_dump command builder with 'snapshot databases' (#889) Add simple utility for generating commands that can then be run/modified to create database dumps. Right now, it's mostly for reference - as we build experience with different setups we can see if this can be made more flexible in the right ways. I believe a templating command like this is important to have, however, since we want to make sure all databases are exported and the correct flags are used with pg_dump, and documentation + manual copy-paste is error-prone. Co-authored-by: Michael Lin --- cmd/src/snapshot_databases.go | 173 ++++++++++++++++++++++++++++++++++ internal/pgdump/pgdump.go | 68 +++++++++++++ 2 files changed, 241 insertions(+) create mode 100644 cmd/src/snapshot_databases.go create mode 100644 internal/pgdump/pgdump.go diff --git a/cmd/src/snapshot_databases.go b/cmd/src/snapshot_databases.go new file mode 100644 index 0000000000..1a0a618315 --- /dev/null +++ b/cmd/src/snapshot_databases.go @@ -0,0 +1,173 @@ +package main + +import ( + "flag" + "fmt" + "os" + "strings" + + "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/output" + "gopkg.in/yaml.v3" + + "github.com/sourcegraph/src-cli/internal/pgdump" +) + +func init() { + usage := `'src snapshot databases' generates commands to export Sourcegraph database dumps. +Note that these commands are intended for use as reference - you may need to adjust the commands for your deployment. + +USAGE + src [-v] snapshot databases [--targets=] + +TARGETS FILES + Predefined targets are available based on default Sourcegraph configurations ('docker', 'k8s'). + Custom targets configuration can be provided in YAML format with '--targets=target.yaml', e.g. + + primary: + target: ... # the DSN of the database deployment, e.g. in docker, the name of the database container + dbname: ... # name of database + username: ... # username for database access + password: ... # password for database access - only include password if it is non-sensitive + codeintel: + # same as above + codeinsights: + # same as above + + See the pgdump.Targets type for more details. +` + flagSet := flag.NewFlagSet("databases", flag.ExitOnError) + targetsKeyFlag := flagSet.String("targets", "auto", "predefined targets ('docker' or 'k8s'), or a custom targets.yaml file") + + snapshotCommands = append(snapshotCommands, &command{ + flagSet: flagSet, + handler: func(args []string) error { + if err := flagSet.Parse(args); err != nil { + return err + } + out := output.NewOutput(flagSet.Output(), output.OutputOpts{Verbose: *verbose}) + + var builder string + if len(args) > 0 { + builder = args[0] + } + + targetKey := "docker" + var commandBuilder pgdump.CommandBuilder + switch builder { + case "pg_dump", "": + targetKey = "local" + commandBuilder = func(t pgdump.Target) (string, error) { + cmd := pgdump.Command(t) + if t.Target != "" { + return fmt.Sprintf("%s --host=%s", cmd, t.Target), nil + } + return cmd, nil + } + case "docker": + commandBuilder = func(t pgdump.Target) (string, error) { + return fmt.Sprintf("docker exec -it %s sh -c '%s'", t.Target, pgdump.Command(t)), nil + } + case "kubectl": + targetKey = "k8s" + commandBuilder = func(t pgdump.Target) (string, error) { + return fmt.Sprintf("kubectl exec -it %s -- bash -c '%s'", t.Target, pgdump.Command(t)), nil + } + default: + return errors.Newf("unknown or invalid template type %q", builder) + } + if *targetsKeyFlag != "auto" { + targetKey = *targetsKeyFlag + } + + targets, ok := predefinedDatabaseDumpTargets[targetKey] + if !ok { + out.WriteLine(output.Emojif(output.EmojiInfo, "Using targets defined in targets file %q", targetKey)) + f, err := os.Open(targetKey) + if err != nil { + return errors.Wrapf(err, "invalid targets file %q", targetKey) + } + if err := yaml.NewDecoder(f).Decode(&targets); err != nil { + return errors.Wrapf(err, "invalid targets file %q", targetKey) + } + } else { + out.WriteLine(output.Emojif(output.EmojiInfo, "Using predefined targets for %s environments", targetKey)) + } + + commands, err := pgdump.BuildCommands(commandBuilder, targets) + if err != nil { + return errors.Wrap(err, "failed to build commands") + } + + b := out.Block(output.Emoji(output.EmojiSuccess, "Commands generated - run them all to generate required database dumps:")) + b.Write("\n" + strings.Join(commands, "\n")) + b.Close() + + out.WriteLine(output.Styledf(output.StyleSuggestion, "Note that you may need to do some additional setup, such as authentication, beforehand.")) + + return nil + }, + usageFunc: func() { fmt.Fprint(flag.CommandLine.Output(), usage) }, + }) +} + +// predefinedDatabaseDumpTargets is based on default Sourcegraph configurations. +var predefinedDatabaseDumpTargets = map[string]pgdump.Targets{ + "local": { + Primary: pgdump.Target{ + DBName: "sg", + Username: "sg", + Password: "sg", + }, + CodeIntel: pgdump.Target{ + DBName: "sg", + Username: "sg", + Password: "sg", + }, + CodeInsights: pgdump.Target{ + DBName: "postgres", + Username: "postgres", + Password: "password", + }, + }, + "docker": { // based on deploy-sourcegraph-managed + Primary: pgdump.Target{ + Target: "pgsql", + DBName: "sg", + Username: "sg", + Password: "sg", + }, + CodeIntel: pgdump.Target{ + Target: "codeintel-db", + DBName: "sg", + Username: "sg", + Password: "sg", + }, + CodeInsights: pgdump.Target{ + Target: "codeinsights-db", + DBName: "postgres", + Username: "postgres", + Password: "password", + }, + }, + "k8s": { // based on deploy-sourcegraph-helm + Primary: pgdump.Target{ + Target: "statefulset/pgsql", + DBName: "sg", + Username: "sg", + Password: "sg", + }, + CodeIntel: pgdump.Target{ + Target: "statefulset/codeintel-db", + DBName: "sg", + Username: "sg", + Password: "sg", + }, + CodeInsights: pgdump.Target{ + Target: "statefulset/codeinsights-db", + DBName: "postgres", + Username: "postgres", + Password: "password", + }, + }, +} diff --git a/internal/pgdump/pgdump.go b/internal/pgdump/pgdump.go new file mode 100644 index 0000000000..60e9bddd58 --- /dev/null +++ b/internal/pgdump/pgdump.go @@ -0,0 +1,68 @@ +package pgdump + +import ( + "fmt" + + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +// Targets represents configuration for each of Sourcegraph's databases. +type Targets struct { + Primary Target `yaml:"primary"` + CodeIntel Target `yaml:"codeintel"` + CodeInsights Target `yaml:"codeinsights"` +} + +// Target represents a database for pg_dump to export. +type Target struct { + // Target is the DSN of the database deployment: + // + // - in docker, the name of the database container, e.g. pgsql, codeintel-db, codeinsights-db + // - in k8s, the name of the deployment or statefulset, e.g. deploy/pgsql, sts/pgsql + // - in plain pg_dump, the server host or socket directory + Target string `yaml:"target"` + + DBName string `yaml:"dbname"` + Username string `yaml:"username"` + + // Only include password if non-sensitive + Password string `yaml:"password"` +} + +// Command generates a pg_dump command that can be used for on-prem-to-Cloud migrations. +func Command(t Target) string { + dump := fmt.Sprintf("pg_dump --no-owner --format=p --no-acl --username=%s --dbname=%s", + t.Username, t.DBName) + if t.Password == "" { + return dump + } + return fmt.Sprintf("PGPASSWORD=%s %s", t.Password, dump) +} + +type CommandBuilder func(Target) (string, error) + +// BuildCommands generates commands that output Postgres dumps and sends them to predefined +// files for each target database. +func BuildCommands(commandBuilder CommandBuilder, targets Targets) ([]string, error) { + var commands []string + for _, t := range []struct { + Output string + Target Target + }{{ + Output: "primary.sql", + Target: targets.Primary, + }, { + Output: "codeintel.sql", + Target: targets.CodeIntel, + }, { + Output: "codeinsights.sql", + Target: targets.CodeInsights, + }} { + c, err := commandBuilder(t.Target) + if err != nil { + return nil, errors.Wrapf(err, "generating command for %q", t.Output) + } + commands = append(commands, fmt.Sprintf("%s > %s", c, t.Output)) + } + return commands, nil +} From fa50cb7b8af8711ac10198e4879793df99212ba6 Mon Sep 17 00:00:00 2001 From: Robert Lin Date: Mon, 28 Nov 2022 15:01:03 -0800 Subject: [PATCH 269/647] snapshot: add snapshot contents uploader (#890) Adds a command, src snapshot upload, that checks that all snapshot resources have been created and initiates parallel uploads for them with native usage of the Cloud Storage client. Co-authored-by: Michael Lin --- .gitignore | 1 + cmd/src/snapshot_databases.go | 2 +- cmd/src/snapshot_summary.go | 5 +- cmd/src/snapshot_upload.go | 162 ++++++++++++++++++++++++++++++++++ go.mod | 41 ++++++--- go.sum | 95 +++++++++++++------- internal/pgdump/pgdump.go | 35 +++++--- 7 files changed, 279 insertions(+), 62 deletions(-) create mode 100644 cmd/src/snapshot_upload.go diff --git a/.gitignore b/.gitignore index 6b0ad027c3..de75d79e40 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,4 @@ release .idea .env .envrc +src-snapshot/ diff --git a/cmd/src/snapshot_databases.go b/cmd/src/snapshot_databases.go index 1a0a618315..e519279229 100644 --- a/cmd/src/snapshot_databases.go +++ b/cmd/src/snapshot_databases.go @@ -94,7 +94,7 @@ TARGETS FILES out.WriteLine(output.Emojif(output.EmojiInfo, "Using predefined targets for %s environments", targetKey)) } - commands, err := pgdump.BuildCommands(commandBuilder, targets) + commands, err := pgdump.BuildCommands(srcSnapshotDir, commandBuilder, targets) if err != nil { return errors.Wrap(err, "failed to build commands") } diff --git a/cmd/src/snapshot_summary.go b/cmd/src/snapshot_summary.go index 56223723f4..ba164e59c8 100644 --- a/cmd/src/snapshot_summary.go +++ b/cmd/src/snapshot_summary.go @@ -18,10 +18,9 @@ func init() { USAGE src login # site-admin authentication required - src [-v] snapshot summary [-summary-path="./src-snapshot-summary.json"] + src [-v] snapshot summary ` flagSet := flag.NewFlagSet("summary", flag.ExitOnError) - snapshotPath := flagSet.String("summary-path", "./src-snapshot-summary.json", "path to write snapshot summary to") apiFlags := api.NewFlags(flagSet) snapshotCommands = append(snapshotCommands, &command{ @@ -39,7 +38,7 @@ USAGE return err } - f, err := os.OpenFile(*snapshotPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm) + f, err := os.OpenFile(snapshotSummaryPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm) if err != nil { return errors.Wrap(err, "open snapshot file") } diff --git a/cmd/src/snapshot_upload.go b/cmd/src/snapshot_upload.go new file mode 100644 index 0000000000..b7e3e2ad97 --- /dev/null +++ b/cmd/src/snapshot_upload.go @@ -0,0 +1,162 @@ +package main + +import ( + "context" + "flag" + "fmt" + "io" + "io/fs" + "os" + "path" + + "cloud.google.com/go/storage" + "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/group" + "github.com/sourcegraph/sourcegraph/lib/output" + "google.golang.org/api/option" + + "github.com/sourcegraph/src-cli/internal/pgdump" +) + +const srcSnapshotDir = "./src-snapshot" + +var snapshotSummaryPath = path.Join(srcSnapshotDir, "summary.json") + +// https://pkg.go.dev/cloud.google.com/go/storage#section-readme + +func init() { + usage := `'src snapshot upload' uploads snapshot contents. + +USAGE + src +` + flagSet := flag.NewFlagSet("upload", flag.ExitOnError) + bucketName := flagSet.String("bucket", "", "destination Cloud Storage bucket name") + credentialsPath := flagSet.String("credentials", "", "JSON credentials file for Google Cloud service account") + + snapshotCommands = append(snapshotCommands, &command{ + flagSet: flagSet, + handler: func(args []string) error { + if err := flagSet.Parse(args); err != nil { + return err + } + + if *bucketName == "" { + return errors.New("-bucket required") + } + if *credentialsPath == "" { + return errors.New("-credentials required") + } + + out := output.NewOutput(flagSet.Output(), output.OutputOpts{Verbose: *verbose}) + ctx := context.Background() + c, err := storage.NewClient(ctx, option.WithCredentialsFile(*credentialsPath)) + if err != nil { + return errors.Wrap(err, "create Cloud Storage client") + } + + type upload struct { + file *os.File + stat os.FileInfo + } + var ( + uploads []upload // index aligned with progressBars + progressBars []output.ProgressBar // index aligned with uploads + ) + + // Open snapshot summary + if f, err := os.Open(snapshotSummaryPath); err != nil { + return errors.Wrap(err, "failed to open snapshot summary - generate one with 'src snapshot summary'") + } else { + stat, err := f.Stat() + if err != nil { + return errors.Wrap(err, "get file size") + } + uploads = append(uploads, upload{ + file: f, + stat: stat, + }) + progressBars = append(progressBars, output.ProgressBar{ + Label: stat.Name(), + Max: float64(stat.Size()), + }) + } + + // Open database dumps + for _, o := range pgdump.Outputs(srcSnapshotDir, pgdump.Targets{}) { + if f, err := os.Open(o.Output); err != nil { + return errors.Wrap(err, "failed to database dump - generate one with 'src snapshot databases'") + } else { + stat, err := f.Stat() + if err != nil { + return errors.Wrap(err, "get file size") + } + uploads = append(uploads, upload{ + file: f, + stat: stat, + }) + progressBars = append(progressBars, output.ProgressBar{ + Label: stat.Name(), + Max: float64(stat.Size()), + }) + } + } + + // Start uploads + progress := out.Progress(progressBars, nil) + progress.WriteLine(output.Emoji(output.EmojiHourglass, "Starting uploads...")) + bucket := c.Bucket(*bucketName) + g := group.New().WithErrors().WithContext(ctx) + for i, u := range uploads { + i := i + u := u + g.Go(func(ctx context.Context) error { + progressFn := func(p int64) { progress.SetValue(i, float64(p)) } + + if err := copyToBucket(ctx, u.file, u.stat, bucket, progressFn); err != nil { + return errors.Wrap(err, u.stat.Name()) + } + + return nil + }) + } + + // Finalize + errs := g.Wait() + progress.Complete() + if errs != nil { + out.WriteLine(output.Line(output.EmojiFailure, output.StyleFailure, "Some snapshot contents failed to upload.")) + return errs + } + + out.WriteLine(output.Emoji(output.EmojiSuccess, "Summary contents uploaded!")) + return nil + }, + usageFunc: func() { fmt.Fprint(flag.CommandLine.Output(), usage) }, + }) +} + +func copyToBucket(ctx context.Context, src io.Reader, stat fs.FileInfo, dst *storage.BucketHandle, progressFn func(int64)) error { + writer := dst.Object(stat.Name()).NewWriter(ctx) + writer.ProgressFunc = progressFn + defer writer.Close() + + // io.Copy is the best way to copy from a reader to writer in Go, and storage.Writer + // has its own chunking mechanisms internally. + written, err := io.Copy(writer, src) + if err != nil { + return err + } + + // Progress is not called on completion, so we call it manually after io.Copy is done + progressFn(written) + + // Validate we have sent all data + size := stat.Size() + if written != size { + return errors.Newf("expected to write %d bytes, but actually wrote %d bytes", + size, written) + } + + return nil +} diff --git a/go.mod b/go.mod index 12e2a9f87d..360787f63b 100644 --- a/go.mod +++ b/go.mod @@ -3,13 +3,14 @@ module github.com/sourcegraph/src-cli go 1.18 require ( + cloud.google.com/go/storage v1.28.0 github.com/Masterminds/semver v1.5.0 github.com/creack/goselect v0.1.2 github.com/derision-test/glock v0.0.0-20210316032053-f5b74334bb29 github.com/dineshappavoo/basex v0.0.0-20170425072625-481a6f6dc663 github.com/dustin/go-humanize v1.0.0 github.com/gobwas/glob v0.2.3 - github.com/google/go-cmp v0.5.8 + github.com/google/go-cmp v0.5.9 github.com/grafana/regexp v0.0.0-20220304100321-149c8afcd6cb github.com/hexops/autogold v1.3.0 github.com/jedib0t/go-pretty/v6 v6.3.7 @@ -22,19 +23,27 @@ require ( github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf github.com/sourcegraph/scip v0.2.3 - github.com/sourcegraph/sourcegraph/lib v0.0.0-20221004162410-237d5855fa13 + github.com/sourcegraph/sourcegraph/lib v0.0.0-20221128221602-4b48d5d69f5d github.com/stretchr/testify v1.8.0 - golang.org/x/net v0.0.0-20220722155237-a158d28d115b - golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4 - google.golang.org/protobuf v1.28.0 + golang.org/x/net v0.2.0 + golang.org/x/sync v0.1.0 + google.golang.org/api v0.102.0 + google.golang.org/protobuf v1.28.1 gopkg.in/yaml.v3 v3.0.1 jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7 ) require ( + cloud.google.com/go v0.104.0 // indirect + cloud.google.com/go/compute v1.12.1 // indirect + cloud.google.com/go/compute/metadata v0.2.1 // indirect + cloud.google.com/go/iam v0.5.0 // indirect github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect github.com/Masterminds/sprig v2.15.0+incompatible // indirect github.com/alecthomas/chroma v0.10.0 // indirect + github.com/alecthomas/kingpin v2.2.6+incompatible // indirect + github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751 // indirect + github.com/alecthomas/units v0.0.0-20211218093645-b94a6e3cc137 // indirect github.com/aokoli/goutils v1.0.1 // indirect github.com/aymerick/douceur v0.2.0 // indirect github.com/bufbuild/buf v1.4.0 // indirect @@ -43,7 +52,9 @@ require ( github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f // indirect github.com/cockroachdb/redact v1.1.3 // indirect github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect + github.com/dave/jennifer v1.6.0 // indirect github.com/davecgh/go-spew v1.1.1 // indirect + github.com/derision-test/go-mockgen v1.3.7 // indirect github.com/dlclark/regexp2 v1.4.0 // indirect github.com/envoyproxy/protoc-gen-validate v0.3.0-java // indirect github.com/fatih/color v1.13.0 // indirect @@ -55,6 +66,8 @@ require ( github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect github.com/golang/protobuf v1.5.2 // indirect github.com/google/uuid v1.3.0 // indirect + github.com/googleapis/enterprise-certificate-proxy v0.2.0 // indirect + github.com/googleapis/gax-go/v2 v2.6.0 // indirect github.com/gorilla/css v1.0.0 // indirect github.com/hexops/gotextdiff v1.0.3 // indirect github.com/hexops/valast v1.4.1 // indirect @@ -72,6 +85,7 @@ require ( github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-runewidth v0.0.13 // indirect github.com/microcosm-cc/bluemonday v1.0.17 // indirect + github.com/mitchellh/go-wordwrap v1.0.1 // indirect github.com/moby/term v0.0.0-20210619224110-3f7ff695adc6 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect @@ -104,13 +118,16 @@ require ( go.uber.org/multierr v1.8.0 // indirect go.uber.org/zap v1.23.0 // indirect golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 // indirect - golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 // indirect - golang.org/x/sys v0.0.0-20220928140112-f11e5e49a4ec // indirect - golang.org/x/term v0.0.0-20220411215600-e5f449aeb171 // indirect - golang.org/x/text v0.3.7 // indirect - golang.org/x/tools v0.1.12 // indirect - google.golang.org/genproto v0.0.0-20220414192740-2d67ff6cf2b4 // indirect - google.golang.org/grpc v1.45.0 // indirect + golang.org/x/mod v0.7.0 // indirect + golang.org/x/oauth2 v0.0.0-20221014153046-6fdb5e3db783 // indirect + golang.org/x/sys v0.2.0 // indirect + golang.org/x/term v0.2.0 // indirect + golang.org/x/text v0.4.0 // indirect + golang.org/x/tools v0.3.0 // indirect + golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 // indirect + google.golang.org/appengine v1.6.7 // indirect + google.golang.org/genproto v0.0.0-20221024183307-1bc688fe9f3e // indirect + google.golang.org/grpc v1.50.1 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect mvdan.cc/gofumpt v0.2.1 // indirect ) diff --git a/go.sum b/go.sum index 3e1e2b3937..ca54f1a641 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,14 @@ cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.104.0 h1:gSmWO7DY1vOm0MVU6DNXM11BWHHsTUmsC5cv1fuW5X8= +cloud.google.com/go v0.104.0/go.mod h1:OO6xxXdJyvuJPcEPBLN9BJPD+jep5G1+2U5B5gkRYtA= +cloud.google.com/go/compute v1.12.1 h1:gKVJMEyqV5c/UnpzjjQbo3Rjvvqpr9B1DFSbJC4OXr0= +cloud.google.com/go/compute v1.12.1/go.mod h1:e8yNOBcBONZU1vJKCvCoDw/4JQsA0dpM4x/6PIIOocU= +cloud.google.com/go/compute/metadata v0.2.1 h1:efOwf5ymceDhK6PKMnnrTHP4pppY5L22mle96M1yP48= +cloud.google.com/go/compute/metadata v0.2.1/go.mod h1:jgHgmJd2RKBGzXqF5LR2EZMGxBkeanZ9wwa75XHJgOM= +cloud.google.com/go/iam v0.5.0 h1:fz9X5zyTWBmamZsqvqZqD7khbifcZF/q+Z1J8pfhIUg= +cloud.google.com/go/iam v0.5.0/go.mod h1:wPU9Vt0P4UmCux7mqtRu6jcpPAb74cP1fh50J3QpkUc= +cloud.google.com/go/storage v1.28.0 h1:DLrIZ6xkeZX6K70fU/boWx5INJumt6f+nwwWSHXzzGY= +cloud.google.com/go/storage v1.28.0/go.mod h1:qlgZML35PXA3zoEnIkiPLY4/TOkUleufRlu6qmcf7sI= github.com/AndreasBriese/bbloom v0.0.0-20190306092124-e2d15f34fcf9/go.mod h1:bOvUY6CB00SOBii9/FifXqc0awNKxLFCL/+pkDPuyl8= github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 h1:UQHMgLO+TxOElx5B5HZ4hJQsoJ/PvUvKRhJHDQXO8P8= github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= @@ -18,7 +27,12 @@ github.com/Shopify/goreferrer v0.0.0-20181106222321-ec9c9a553398/go.mod h1:a1uqR github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY= github.com/alecthomas/chroma v0.10.0 h1:7XDcGkCQopCNKjZHfYrNLraA+M7e0fMiJ/Mfikbfjek= github.com/alecthomas/chroma v0.10.0/go.mod h1:jtJATyUxlIORhUOFNA9NZDWGAQ8wpxQQqNSB4rjA/1s= -github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= +github.com/alecthomas/kingpin v2.2.6+incompatible h1:5svnBTFgJjZvGKyYBtMB0+m5wvrbUHiqye8wRJMlnYI= +github.com/alecthomas/kingpin v2.2.6+incompatible/go.mod h1:59OFYbFVLKQKq+mqrL6Rw5bR0c3ACQaawgXx0QYndlE= +github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751 h1:JYp7IbQjafoB+tBA3gMyHYHrpOtNuDiK/uB5uXxq5wM= +github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/units v0.0.0-20211218093645-b94a6e3cc137 h1:s6gZFSlWYmbqAuRjVTiNNhvNRfY2Wxp9nhfyel4rklc= +github.com/alecthomas/units v0.0.0-20211218093645-b94a6e3cc137/go.mod h1:OMCwj8VM1Kc9e19TLln2VL61YJF0x1XFtfdL4JdbSyE= github.com/aokoli/goutils v1.0.1 h1:7fpzNGoJ3VA8qcrm++XEE1QUe0mIwNeLa02Nwq7RDkg= github.com/aokoli/goutils v1.0.1/go.mod h1:SijmP0QR8LtwsmDs8Yii5Z/S4trXFGFC2oO5g9DP+DQ= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= @@ -29,16 +43,11 @@ github.com/benbjohnson/clock v1.3.0 h1:ip6w0uFQkncKQ979AypyG0ER7mqUSBdKLOgAle/AT github.com/bufbuild/buf v1.4.0 h1:GqE3a8CMmcFvWPzuY3Mahf9Kf3S9XgZ/ORpfYFzO+90= github.com/bufbuild/buf v1.4.0/go.mod h1:mwHG7klTHnX+rM/ym8LXGl7vYpVmnwT96xWoRB4H5QI= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= -github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/charmbracelet/glamour v0.5.0 h1:wu15ykPdB7X6chxugG/NNfDUbyyrCLV9XBalj5wdu3g= github.com/charmbracelet/glamour v0.5.0/go.mod h1:9ZRtG19AUIzcTm7FGLGbq3D5WKQ5UyZBbQsMQN0XIqc= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= -github.com/cncf/udpa/go v0.0.0-20210930031921-04548b0d99d4/go.mod h1:6pvJx4me5XPnfI9Z40ddWsdw2W/uZgQLFXToKeRcDiI= -github.com/cncf/xds/go v0.0.0-20210805033703-aa0b78936158/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= -github.com/cncf/xds/go v0.0.0-20210922020428-25de7278fc84/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= -github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cockroachdb/datadriven v1.0.1-0.20211007161720-b558070c3be0/go.mod h1:5Ib8Meh+jk1RlHIXej6Pzevx/NLlNvQB9pmSBZErGA4= github.com/cockroachdb/datadriven v1.0.1-0.20220214170620-9913f5bc19b7/go.mod h1:hi0MtSY3AYDQNDi83kDkMH5/yqM/CsIrsOITkSoH7KI= github.com/cockroachdb/errors v1.6.1/go.mod h1:tm6FTP5G81vwJ5lC0SizQo374JNCOPrHyXGitRJoDqM= @@ -64,11 +73,15 @@ github.com/creack/goselect v0.1.2/go.mod h1:a/NhLweNvqIYMuxcMOuWY516Cimucms3DglD github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/creack/pty v1.1.11 h1:07n33Z8lZxZ2qwegKbObQohDhXDQxiMMz1NOUGYlesw= github.com/creack/pty v1.1.11/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/dave/jennifer v1.6.0 h1:MQ/6emI2xM7wt0tJzJzyUik2Q3Tcn2eE0vtYgh4GPVI= +github.com/dave/jennifer v1.6.0/go.mod h1:AxTG893FiZKqxy3FP1kL80VMshSMuz2G+EgvszgGRnk= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/derision-test/glock v0.0.0-20210316032053-f5b74334bb29 h1:O07j7ewg0eFHRx+7bxCA/7z86HJexl7HLY9kyVMmPDo= github.com/derision-test/glock v0.0.0-20210316032053-f5b74334bb29/go.mod h1:jKtLdBMrF+XQatqvg46wiWdDfDSSDjdhO4dOM2FX9H4= +github.com/derision-test/go-mockgen v1.3.7 h1:b/DXAXL2FkaRPpnbYK3ODdZzklmJAwox0tkc6yyXx74= +github.com/derision-test/go-mockgen v1.3.7/go.mod h1:/TXUePlhtHmDDCaDAi/a4g6xOHqMDz3Wf0r2NPGskB4= github.com/dgraph-io/badger v1.6.0/go.mod h1:zwt7syl517jmP8s94KqSxTlM6IMsdhYy6psNgSztDR4= github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= @@ -82,9 +95,7 @@ github.com/eknkc/amber v0.0.0-20171010120322-cdade1c07385/go.mod h1:0vRUJqYpeSZi github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= -github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= github.com/envoyproxy/go-control-plane v0.9.9-0.20210217033140-668b12f5399d/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= -github.com/envoyproxy/go-control-plane v0.9.10-0.20210907150352-cf90f659a021/go.mod h1:AFq3mo9L8Lqqiid3OhADV3RfLJnjiw63cSpi+fDTRC0= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/envoyproxy/protoc-gen-validate v0.3.0-java h1:bV5JGEB1ouEzZa0hgVDFFiClrUEuGWRaAc/3mxR2QK0= github.com/envoyproxy/protoc-gen-validate v0.3.0-java/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= @@ -156,13 +167,18 @@ github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg= -github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= +github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/martian/v3 v3.2.1 h1:d8MncMlErDFTwQGBK1xhv026j9kqhvw1Qv9IbWT1VLQ= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/googleapis/enterprise-certificate-proxy v0.2.0 h1:y8Yozv7SZtlU//QXbezB6QkpuE6jMD2/gfzk4AftXjs= +github.com/googleapis/enterprise-certificate-proxy v0.2.0/go.mod h1:8C0jb7/mgJe/9KK8Lm7X9ctZC2t60YyIpYEI16jx0Qg= +github.com/googleapis/gax-go/v2 v2.6.0 h1:SXk3ABtQYDT/OH8jAyvEOQ58mgawq5C4o/4/89qN2ZU= +github.com/googleapis/gax-go/v2 v2.6.0/go.mod h1:1mjbznJAPHFpesgE5ucqfYEscaz5kMdcIDwU/6+DDoY= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gorilla/css v1.0.0 h1:BQqNyPTi50JCFMTw/b67hByjMVXZRwGha6wxVGkeihY= github.com/gorilla/css v1.0.0/go.mod h1:Dn721qIggHpt4+EFCcTLTU/vk5ySda2ReITrtgBl60c= @@ -170,7 +186,6 @@ github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoA github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/grafana/regexp v0.0.0-20220304100321-149c8afcd6cb h1:wwzNkyaQwcXCzQuKoWz3lwngetmcyg+EhW0fF5lz73M= github.com/grafana/regexp v0.0.0-20220304100321-149c8afcd6cb/go.mod h1:M5qHK+eWfAv8VR/265dIuEpL3fNfeC21tXXp9itM24A= -github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= github.com/hashicorp/go-version v1.2.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= github.com/hexops/autogold v0.8.1/go.mod h1:97HLDXyG23akzAoRYJh/2OBs3kd80eHyKPvZw0S5ZBY= @@ -283,6 +298,8 @@ github.com/microcosm-cc/bluemonday v1.0.17 h1:Z1a//hgsQ4yjC+8zEkV8IWySkXnsxmdSY6 github.com/microcosm-cc/bluemonday v1.0.17/go.mod h1:Z0r70sCuXHig8YpBzCc5eGHAap2K7e/u082ZUpDRRqM= github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= +github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0= +github.com/mitchellh/go-wordwrap v1.0.1/go.mod h1:R62XHJLzvMFRBbcrT7m7WgmE1eOyTSsCt+hzestvNj0= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ= github.com/moby/term v0.0.0-20210619224110-3f7ff695adc6 h1:dcztxKSvZ4Id8iPpHERQBbIJfabdt4wUm5qy3wOL2Zc= @@ -344,7 +361,6 @@ github.com/pseudomuto/protokit v0.2.0/go.mod h1:2PdH30hxVHsup8KpBTOXTBeMVhJZVio3 github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY= github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= -github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.6.2/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.8.1-0.20211023094830-115ce09fd6b4/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= @@ -376,6 +392,8 @@ github.com/sourcegraph/scip v0.2.3 h1:6nRsTlNTELn+1V7JxLrDVbBpb9H1gAbUF48N7x5B8Y github.com/sourcegraph/scip v0.2.3/go.mod h1:3D/RLCMvrrSam85RtFmC67SE/jhV9++hpCR5MTDzbA0= github.com/sourcegraph/sourcegraph/lib v0.0.0-20221004162410-237d5855fa13 h1:HEj9QVz35nIU4plPb7iJSFjcTA14zVnfAdfYZF5jsKg= github.com/sourcegraph/sourcegraph/lib v0.0.0-20221004162410-237d5855fa13/go.mod h1:e3v3msUOgthv/QCWUzhFdfR3+hwUSn37rtuw49IVJg4= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20221128221602-4b48d5d69f5d h1:uIvIqhKNSuTH49fZcOh0fhJoKni/5MO3sQ/0zCfj/MM= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20221128221602-4b48d5d69f5d/go.mod h1:tyHfYAVIPq+U6bCOTbIYra4uQ0gC7PQWA8BqmyF//Q0= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= @@ -436,7 +454,6 @@ github.com/yuin/goldmark-emoji v1.0.1 h1:ctuWEyzGBwiucEqxzwe0SOYDXPAucOrE9NQC18W github.com/yuin/goldmark-emoji v1.0.1/go.mod h1:2w1E6FEWLcDQkoTE+7HU6QF1F6SLlNGjRIBbIZQFqkQ= go.opencensus.io v0.23.0 h1:gqCw0LfLxScz8irSi8exQc7fyQ0fKQU/qnC/X8+V/1M= go.opencensus.io v0.23.0/go.mod h1:XItmlyltB5F7CS4xOC1DcqMoFqwtC6OG2xF7mCv7P7E= -go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI= go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= go.uber.org/atomic v1.10.0 h1:9qC72Qh0+3MqyJbAn8YU5xVq1frD8bn3JtD2oXtafVQ= go.uber.org/atomic v1.10.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= @@ -468,23 +485,24 @@ golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 h1:6zppjxzCulZykYSLyVDYbneBfbaBIQPYMevg0bEwv2s= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/mod v0.7.0 h1:LapD9S96VoQRhi/GrNTqeBJFrUjs5UHCAtTlgwA5oZA= +golang.org/x/mod v0.7.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190327091125-710a502c58a2/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190827160401-ba9fcec4b297/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= -golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= @@ -492,20 +510,22 @@ golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96b golang.org/x/net v0.0.0-20210614182718-04defd469f4e/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211008194852-3b03d305991f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/net v0.0.0-20220722155237-a158d28d115b h1:PxfKdU9lEEDYjdIzOtC4qFWgkU2rGHdKlKowJSMN9h0= -golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.0.0-20221014081412-f15817d10f9b h1:tvrvnPFcdzp294diPnrdZZZ8XUt2Tyj7svb7X52iDuU= +golang.org/x/net v0.0.0-20221014081412-f15817d10f9b/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk= +golang.org/x/net v0.2.0 h1:sZfSu1wtKLGlWI4ZZayP0ck9Y73K1ynO6gqzTdBVdPU= +golang.org/x/net v0.2.0/go.mod h1:KqCZLdyyvdV855qA2rE3GC2aiw5xGR5TEjj8smXukLY= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= -golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20221014153046-6fdb5e3db783 h1:nt+Q6cXKz4MosCSpnbMtqiQ8Oz0pxTef2B4Vca2lvfk= +golang.org/x/oauth2 v0.0.0-20221014153046-6fdb5e3db783/go.mod h1:h4gKUeWbJ4rQPri7E0u6Gs4e9Ri2zaLxzw5DI5XGrYg= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4 h1:uVc8UZUe6tr40fFVnUP5Oj+veunVezqYl9z7DYw9xzw= -golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o= +golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -543,16 +563,21 @@ golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220928140112-f11e5e49a4ec h1:BkDtF2Ih9xZ7le9ndzTA7KJow28VbQW3odyk/8drmuI= golang.org/x/sys v0.0.0-20220928140112-f11e5e49a4ec/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.2.0 h1:ljd4t30dBnAvMZaQCevtY0xLLD0A+bRZXbgLMLU1F/A= +golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20220411215600-e5f449aeb171 h1:EH1Deb8WZJ0xc0WK//leUHXcX9aLE5SymusoTmMZye8= golang.org/x/term v0.0.0-20220411215600-e5f449aeb171/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.2.0 h1:z85xZCsEl7bi/KwbNADeBYoOP0++7W1ipu+aGnpwzRM= +golang.org/x/term v0.2.0/go.mod h1:TVmDHMZPmdnySmBfhjOoOdhjzdE1h4u1VwSiw2l1Nuc= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.4.0 h1:BrVqGRd7+k1DiOgtnFvAkoQEWQvBc25ouMJM6429SFg= +golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/time v0.0.0-20201208040808-7e3f01d25324/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -576,32 +601,37 @@ golang.org/x/tools v0.1.8-0.20211102182255-bb4add04ddef/go.mod h1:nABZi5QlRsZVlz golang.org/x/tools v0.1.8/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= golang.org/x/tools v0.1.12 h1:VveCTK38A2rkS8ZqFY25HIDFscX5X9OoEhJd3quQmXU= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/tools v0.3.0 h1:SrNbZl6ECOS1qFzgTdQfWXZM9XBkiA6tkFrH9YSTPHM= +golang.org/x/tools v0.3.0/go.mod h1:/rWhSS2+zyEVwoJf8YAX6L2f0ntZ7Kn/mGgAWcipA5k= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 h1:H2TDz8ibqkAF6YGhCdN3jS9O0/s90v0rJh3X/OLHEUk= +golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2/go.mod h1:K8+ghG5WaK9qNqU5K3HdILfMLy1f3aNYFI/wnl100a8= +google.golang.org/api v0.102.0 h1:JxJl2qQ85fRMPNvlZY/enexbxpCjLwGhZUtgfGeQ51I= +google.golang.org/api v0.102.0/go.mod h1:3VFl6/fzoA+qNuS1N1/VfXY4LjoXN/wzeIp7TweWwGo= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c= +google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= google.golang.org/genproto v0.0.0-20180518175338-11a468237815/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= -google.golang.org/genproto v0.0.0-20200513103714-09dca8ec2884/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= google.golang.org/genproto v0.0.0-20210624195500-8bfb893ecb84/go.mod h1:SzzZ/N+nwJDaO1kznhnlzqS8ocJICar6hYhVyhi++24= -google.golang.org/genproto v0.0.0-20220414192740-2d67ff6cf2b4 h1:myaecH64R0bIEDjNORIel4iXubqzaHU1K2z8ajBwWcM= -google.golang.org/genproto v0.0.0-20220414192740-2d67ff6cf2b4/go.mod h1:8w6bsBMX6yCPbAVTeqQHvzxW0EIFigd5lZyahWgyfDo= +google.golang.org/genproto v0.0.0-20221024183307-1bc688fe9f3e h1:S9GbmC1iCgvbLyAokVCwiO6tVIrU9Y7c5oMx1V/ki/Y= +google.golang.org/genproto v0.0.0-20221024183307-1bc688fe9f3e/go.mod h1:9qHF0xnpdSfF6knlcsnpzUu5y+rpwgbvsyGAZPBMg4s= google.golang.org/grpc v1.12.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= -google.golang.org/grpc v1.33.1/go.mod h1:fr5YgcSWrqhRRxogOsw7RzIpsmvOZ6IcH4kBYTpR3n0= google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= -google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= google.golang.org/grpc v1.38.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= -google.golang.org/grpc v1.45.0 h1:NEpgUqV3Z+ZjkqMsxMg11IaDrXY4RY6CQukSGK0uI1M= -google.golang.org/grpc v1.45.0/go.mod h1:lN7owxKUQEqMfSyQikvvk5tf/6zMPsrK+ONuO11+0rQ= +google.golang.org/grpc v1.50.1 h1:DS/BukOZWp8s6p4Dt/tOaJaTQyPyOoCcrjroHuCeLzY= +google.golang.org/grpc v1.50.1/go.mod h1:ZgQEeidpAuNRZ8iRrlBKXZQP1ghovWIVhdJRyCDK+GI= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= @@ -614,8 +644,8 @@ google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlba google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.27.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -google.golang.org/protobuf v1.28.0 h1:w43yiav+6bVFTBQFZX0r7ipe9JQ1QsbMgHwbBziscLw= -google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +google.golang.org/protobuf v1.28.1 h1:d0NfwRgPtno5B1Wa6L2DAG+KivqkdutMf1UhdNx175w= +google.golang.org/protobuf v1.28.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= @@ -629,7 +659,6 @@ gopkg.in/ini.v1 v1.51.1/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/mgo.v2 v2.0.0-20180705113604-9856a29383ce/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/internal/pgdump/pgdump.go b/internal/pgdump/pgdump.go index 60e9bddd58..c7941ed5ba 100644 --- a/internal/pgdump/pgdump.go +++ b/internal/pgdump/pgdump.go @@ -2,6 +2,7 @@ package pgdump import ( "fmt" + "path/filepath" "github.com/sourcegraph/sourcegraph/lib/errors" ) @@ -39,25 +40,33 @@ func Command(t Target) string { return fmt.Sprintf("PGPASSWORD=%s %s", t.Password, dump) } -type CommandBuilder func(Target) (string, error) +type Output struct { + Output string + Target Target +} -// BuildCommands generates commands that output Postgres dumps and sends them to predefined -// files for each target database. -func BuildCommands(commandBuilder CommandBuilder, targets Targets) ([]string, error) { - var commands []string - for _, t := range []struct { - Output string - Target Target - }{{ - Output: "primary.sql", +// Outputs generates a set of mappings between a pgdump.Target and the desired output +// path. It can be provided a zero-value Targets to just generate the output paths. +func Outputs(dir string, targets Targets) []Output { + return []Output{{ + Output: filepath.Join(dir, "primary.sql"), Target: targets.Primary, }, { - Output: "codeintel.sql", + Output: filepath.Join(dir, "codeintel.sql"), Target: targets.CodeIntel, }, { - Output: "codeinsights.sql", + Output: filepath.Join(dir, "codeinsights.sql"), Target: targets.CodeInsights, - }} { + }} +} + +type CommandBuilder func(Target) (string, error) + +// BuildCommands generates commands that output Postgres dumps and sends them to predefined +// files for each target database. +func BuildCommands(outDir string, commandBuilder CommandBuilder, targets Targets) ([]string, error) { + var commands []string + for _, t := range Outputs(outDir, targets) { c, err := commandBuilder(t.Target) if err != nil { return nil, errors.Wrapf(err, "generating command for %q", t.Output) From e76569759863448dbd9fbf1d823698ba298c2d72 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Tue, 29 Nov 2022 03:32:59 +0100 Subject: [PATCH 270/647] Support binary diffs (#887) Patches can contain non UTF-8 characters (who knew). Since we JSON-encode the patch as a string field, we lose that encoding over the wire to Sourcegraph. This PR adds support for a byte slice encoded (so base64 over the wire) mode from Sourcegraph 4.4 onwards, which retains original encoding. --- .tool-versions | 2 +- CHANGELOG.md | 12 +- cmd/src/batch_apply.go | 13 +-- cmd/src/batch_common.go | 103 ++++++++++------- cmd/src/batch_exec.go | 5 +- cmd/src/batch_new.go | 7 +- cmd/src/batch_preview.go | 13 +-- cmd/src/batch_remote.go | 7 +- cmd/src/batch_repositories.go | 7 +- cmd/src/batch_validate.go | 7 +- go.mod | 10 +- go.sum | 28 +---- internal/api/version_check.go | 46 -------- internal/api/version_check_test.go | 107 ------------------ internal/batches/executor/coordinator.go | 18 ++- internal/batches/executor/coordinator_test.go | 46 ++++---- .../batches/executor/execution_cache_test.go | 7 +- internal/batches/executor/executor.go | 3 + internal/batches/executor/executor_test.go | 23 ++-- internal/batches/executor/run_steps.go | 13 ++- internal/batches/executor/ui.go | 4 +- internal/batches/features.go | 5 +- internal/batches/ui/json_lines.go | 41 +++++-- internal/batches/ui/task_exec_tui.go | 4 +- internal/batches/ui/task_exec_tui_test.go | 5 +- 25 files changed, 215 insertions(+), 321 deletions(-) delete mode 100644 internal/api/version_check.go delete mode 100644 internal/api/version_check_test.go diff --git a/.tool-versions b/.tool-versions index 5521e49283..1fd8168ccb 100644 --- a/.tool-versions +++ b/.tool-versions @@ -1,3 +1,3 @@ -golang 1.18.1 +golang 1.19.3 shfmt 3.2.0 shellcheck 0.7.1 diff --git a/CHANGELOG.md b/CHANGELOG.md index 1a81623fd5..d05ecc14e6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,16 @@ All notable changes to `src-cli` are documented in this file. ### Added +### Changed + +### Fixed + +### Removed + +## 4.2.1 + +### Added + - Batch specs being run locally with `src batch preview` or `src batch apply` can now be run with the `-run-as-root` flag, which will run all step containers as root instead of the default user for the image. This is off by default. [#886](https://github.com/sourcegraph/src-cli/pull/886) ### Changed @@ -21,7 +31,7 @@ All notable changes to `src-cli` are documented in this file. ### Fixed -### Removed +- Batch changes: Git patches are now binary encoded instead of UTF-8 over the wire, fixing support for non-UTF-8 files. [#887](https://github.com/sourcegraph/src-cli/pull/887) ## 4.2.0 diff --git a/cmd/src/batch_apply.go b/cmd/src/batch_apply.go index dcbc061f51..28f715656d 100644 --- a/cmd/src/batch_apply.go +++ b/cmd/src/batch_apply.go @@ -5,10 +5,7 @@ import ( "flag" "fmt" - "github.com/sourcegraph/src-cli/internal/batches/ui" "github.com/sourcegraph/src-cli/internal/cmderrors" - - "github.com/sourcegraph/sourcegraph/lib/output" ) func init() { @@ -47,15 +44,7 @@ Examples: ctx, cancel := contextCancelOnInterrupt(context.Background()) defer cancel() - var execUI ui.ExecUI - if flags.textOnly { - execUI = &ui.JSONLines{} - } else { - out := output.NewOutput(flagSet.Output(), output.OutputOpts{Verbose: *verbose}) - execUI = &ui.TUI{Out: out} - } - - if err = executeBatchSpec(ctx, execUI, executeBatchSpecOpts{ + if err = executeBatchSpec(ctx, executeBatchSpecOpts{ flags: flags, client: cfg.apiClient(flags.api, flagSet.Output()), file: file, diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index c387c60055..8a07076421 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -18,6 +18,7 @@ import ( "github.com/mattn/go-isatty" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/output" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/template" @@ -253,10 +254,18 @@ type executeBatchSpecOpts struct { // executeBatchSpec performs all the steps required to upload the batch spec to // Sourcegraph, including execution as needed and applying the resulting batch // spec if specified. -func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOpts) (err error) { +func executeBatchSpec(ctx context.Context, opts executeBatchSpecOpts) (err error) { + var execUI ui.ExecUI + if opts.flags.textOnly { + execUI = &ui.JSONLines{} + } else { + out := output.NewOutput(os.Stderr, output.OutputOpts{Verbose: *verbose}) + execUI = &ui.TUI{Out: out} + } + defer func() { if err != nil { - ui.ExecutionError(err) + execUI.ExecutionError(err) } }() @@ -264,9 +273,19 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp Client: opts.client, }) + ffs, err := svc.DetermineFeatureFlags(ctx) + if err != nil { + return err + } + + // Once we know about feature flags, reconfigure the UI if needed. + if opts.flags.textOnly && ffs.BinaryDiffs { + execUI = &ui.JSONLines{BinaryDiffs: true} + } + imageCache := docker.NewImageCache() - if err := validateSourcegraphVersionConstraint(ctx, svc); err != nil { + if err := validateSourcegraphVersionConstraint(ctx, ffs); err != nil { return err } @@ -309,12 +328,12 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp } // Parse flags and build up our service and executor options. - ui.ParsingBatchSpec() + execUI.ParsingBatchSpec() batchSpec, batchSpecDir, rawSpec, err := parseBatchSpec(ctx, opts.file, svc) if err != nil { var multiErr errors.MultiError if errors.As(err, &multiErr) { - ui.ParsingBatchSpecFailure(multiErr) + execUI.ParsingBatchSpecFailure(multiErr) return cmderrors.ExitCode(2, nil) } else { // This shouldn't happen; let's just punt and let the normal @@ -322,32 +341,32 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp return err } } - ui.ParsingBatchSpecSuccess() + execUI.ParsingBatchSpecSuccess() - ui.ResolvingNamespace() + execUI.ResolvingNamespace() namespace, err := svc.ResolveNamespace(ctx, opts.flags.namespace) if err != nil { return err } - ui.ResolvingNamespaceSuccess(namespace.ID) + execUI.ResolvingNamespaceSuccess(namespace.ID) var workspaceCreator workspace.Creator if len(batchSpec.Steps) > 0 { - ui.PreparingContainerImages() + execUI.PreparingContainerImages() images, err := svc.EnsureDockerImages( ctx, imageCache, batchSpec.Steps, parallelism, - ui.PreparingContainerImagesProgress, + execUI.PreparingContainerImagesProgress, ) if err != nil { return err } - ui.PreparingContainerImagesSuccess() + execUI.PreparingContainerImagesSuccess() - ui.DeterminingWorkspaceCreatorType() + execUI.DeterminingWorkspaceCreatorType() var typ workspace.CreatorType workspaceCreator, typ = workspace.NewCreator(ctx, opts.flags.workspace, opts.flags.cacheDir, opts.flags.tempDir, images) if typ == workspace.CreatorTypeVolume { @@ -357,21 +376,21 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp return err } } - ui.DeterminingWorkspaceCreatorTypeSuccess(typ) + execUI.DeterminingWorkspaceCreatorTypeSuccess(typ) } - ui.DeterminingWorkspaces() + execUI.DeterminingWorkspaces() workspaces, repos, err := svc.ResolveWorkspacesForBatchSpec(ctx, batchSpec, opts.flags.allowUnsupported, opts.flags.allowIgnored) if err != nil { if repoSet, ok := err.(batches.UnsupportedRepoSet); ok { - ui.DeterminingWorkspacesSuccess(len(workspaces), len(repos), repoSet, nil) + execUI.DeterminingWorkspacesSuccess(len(workspaces), len(repos), repoSet, nil) } else if repoSet, ok := err.(batches.IgnoredRepoSet); ok { - ui.DeterminingWorkspacesSuccess(len(workspaces), len(repos), nil, repoSet) + execUI.DeterminingWorkspacesSuccess(len(workspaces), len(repos), nil, repoSet) } else { return errors.Wrap(err, "resolving repositories") } } else { - ui.DeterminingWorkspacesSuccess(len(workspaces), len(repos), nil, nil) + execUI.DeterminingWorkspacesSuccess(len(workspaces), len(repos), nil, nil) } archiveRegistry := repozip.NewArchiveRegistry(opts.client, opts.flags.cacheDir, opts.flags.cleanArchives) @@ -389,14 +408,16 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp TempDir: opts.flags.tempDir, GlobalEnv: os.Environ(), ForceRoot: opts.flags.runAsRoot, + BinaryDiffs: ffs.BinaryDiffs, }, - Logger: logManager, - Cache: executor.NewDiskCache(opts.flags.cacheDir), - GlobalEnv: os.Environ(), + Logger: logManager, + Cache: executor.NewDiskCache(opts.flags.cacheDir), + BinaryDiffs: ffs.BinaryDiffs, + GlobalEnv: os.Environ(), }, ) - ui.CheckingCache() + execUI.CheckingCache() tasks := svc.BuildTasks( &template.BatchChangeAttributes{ Name: batchSpec.Name, @@ -421,9 +442,9 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp return err } } - ui.CheckingCacheSuccess(len(specs), len(uncachedTasks)) + execUI.CheckingCacheSuccess(len(specs), len(uncachedTasks)) - taskExecUI := ui.ExecutingTasks(*verbose, parallelism) + taskExecUI := execUI.ExecutingTasks(*verbose, parallelism) freshSpecs, logFiles, execErr := coord.ExecuteAndBuildSpecs(ctx, batchSpec, uncachedTasks, taskExecUI) // Add external changeset specs. importedSpecs, importErr := svc.CreateImportChangesetSpecs(ctx, batchSpec) @@ -440,7 +461,7 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp if err == nil { taskExecUI.Success() } else { - ui.ExecutingTasksSkippingErrors(err) + execUI.ExecutingTasksSkippingErrors(err) } } else { if err != nil { @@ -450,7 +471,7 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp } if len(logFiles) > 0 && opts.flags.keepLogs { - ui.LogFilesKept(logFiles) + execUI.LogFilesKept(logFiles) } specs = append(specs, freshSpecs...) @@ -464,7 +485,7 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp ids := make([]graphql.ChangesetSpecID, len(specs)) if len(specs) > 0 { - ui.UploadingChangesetSpecs(len(specs)) + execUI.UploadingChangesetSpecs(len(specs)) for i, spec := range specs { id, err := svc.CreateChangesetSpec(ctx, spec) @@ -472,21 +493,21 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp return err } ids[i] = id - ui.UploadingChangesetSpecsProgress(i+1, len(specs)) + execUI.UploadingChangesetSpecsProgress(i+1, len(specs)) } - ui.UploadingChangesetSpecsSuccess(ids) + execUI.UploadingChangesetSpecsSuccess(ids) } else if len(repos) == 0 { - ui.NoChangesetSpecs() + execUI.NoChangesetSpecs() } - ui.CreatingBatchSpec() + execUI.CreatingBatchSpec() id, url, err := svc.CreateBatchSpec(ctx, namespace.ID, rawSpec, ids) if err != nil { - return ui.CreatingBatchSpecError(err) + return execUI.CreatingBatchSpecError(err) } previewURL := cfg.Endpoint + url - ui.CreatingBatchSpecSuccess(previewURL) + execUI.CreatingBatchSpecSuccess(previewURL) hasWorkspaceFiles := false for _, step := range batchSpec.Steps { @@ -496,26 +517,26 @@ func executeBatchSpec(ctx context.Context, ui ui.ExecUI, opts executeBatchSpecOp } } if hasWorkspaceFiles { - ui.UploadingWorkspaceFiles() + execUI.UploadingWorkspaceFiles() if err = svc.UploadBatchSpecWorkspaceFiles(ctx, batchSpecDir, string(id), batchSpec.Steps); err != nil { // Since failing to upload workspace files should not stop processing, just warn - ui.UploadingWorkspaceFilesWarning(errors.Wrap(err, "uploading workspace files")) + execUI.UploadingWorkspaceFilesWarning(errors.Wrap(err, "uploading workspace files")) } else { - ui.UploadingWorkspaceFilesSuccess() + execUI.UploadingWorkspaceFilesSuccess() } } if !opts.applyBatchSpec { - ui.PreviewBatchSpec(previewURL) + execUI.PreviewBatchSpec(previewURL) return } - ui.ApplyingBatchSpec() + execUI.ApplyingBatchSpec() batch, err := svc.ApplyBatchChange(ctx, id) if err != nil { return err } - ui.ApplyingBatchSpecSuccess(cfg.Endpoint + batch.URL) + execUI.ApplyingBatchSpecSuccess(cfg.Endpoint + batch.URL) return nil } @@ -617,11 +638,7 @@ func getBatchParallelism(ctx context.Context, flag int) (int, error) { return docker.NCPU(ctx) } -func validateSourcegraphVersionConstraint(ctx context.Context, svc *service.Service) error { - ffs, err := svc.DetermineFeatureFlags(ctx) - if err != nil { - return err - } +func validateSourcegraphVersionConstraint(ctx context.Context, ffs *batches.FeatureFlags) error { if ffs.Sourcegraph40 { return nil } diff --git a/cmd/src/batch_exec.go b/cmd/src/batch_exec.go index d4592ce139..11aadf39e3 100644 --- a/cmd/src/batch_exec.go +++ b/cmd/src/batch_exec.go @@ -37,6 +37,7 @@ type executorModeFlags struct { tempDir string repoDir string workspaceFilesDir string + binaryDiffs bool } func newExecutorModeFlags(flagSet *flag.FlagSet) (f *executorModeFlags) { @@ -47,6 +48,7 @@ func newExecutorModeFlags(flagSet *flag.FlagSet) (f *executorModeFlags) { flagSet.StringVar(&f.tempDir, "tmp", "", "Directory for storing temporary data.") flagSet.StringVar(&f.repoDir, "repo", "", "Path of the checked out repo on disk.") flagSet.StringVar(&f.workspaceFilesDir, "workspaceFiles", "", "Path of workspace files on disk.") + flagSet.BoolVar(&f.binaryDiffs, "binaryDiffs", false, "Whether to encode diffs as base64.") return f } @@ -121,7 +123,7 @@ Examples: } func executeBatchSpecInWorkspaces(ctx context.Context, flags *executorModeFlags) (err error) { - ui := &ui.JSONLines{} + ui := &ui.JSONLines{BinaryDiffs: flags.binaryDiffs} // Ensure the temp dir exists. tempDir := flags.tempDir @@ -211,6 +213,7 @@ func executeBatchSpecInWorkspaces(ctx context.Context, flags *executorModeFlags) RepoArchive: &repozip.NoopArchive{}, UI: taskExecUI.StepsExecutionUI(task), ForceRoot: !flags.runAsImageUser, + BinaryDiffs: flags.binaryDiffs, } results, err := executor.RunSteps(ctx, opts) diff --git a/cmd/src/batch_new.go b/cmd/src/batch_new.go index 577da8bd4b..75fe9a8891 100644 --- a/cmd/src/batch_new.go +++ b/cmd/src/batch_new.go @@ -48,7 +48,12 @@ Examples: Client: cfg.apiClient(apiFlags, flagSet.Output()), }) - if err := validateSourcegraphVersionConstraint(ctx, svc); err != nil { + ffs, err := svc.DetermineFeatureFlags(ctx) + if err != nil { + return err + } + + if err := validateSourcegraphVersionConstraint(ctx, ffs); err != nil { return err } diff --git a/cmd/src/batch_preview.go b/cmd/src/batch_preview.go index 088c58046e..8226bb5459 100644 --- a/cmd/src/batch_preview.go +++ b/cmd/src/batch_preview.go @@ -5,10 +5,7 @@ import ( "flag" "fmt" - "github.com/sourcegraph/src-cli/internal/batches/ui" "github.com/sourcegraph/src-cli/internal/cmderrors" - - "github.com/sourcegraph/sourcegraph/lib/output" ) func init() { @@ -45,15 +42,7 @@ Examples: ctx, cancel := contextCancelOnInterrupt(context.Background()) defer cancel() - var execUI ui.ExecUI - if flags.textOnly { - execUI = &ui.JSONLines{} - } else { - out := output.NewOutput(flagSet.Output(), output.OutputOpts{Verbose: *verbose}) - execUI = &ui.TUI{Out: out} - } - - if err = executeBatchSpec(ctx, execUI, executeBatchSpecOpts{ + if err = executeBatchSpec(ctx, executeBatchSpecOpts{ flags: flags, client: cfg.apiClient(flags.api, flagSet.Output()), file: file, diff --git a/cmd/src/batch_remote.go b/cmd/src/batch_remote.go index a5a1a57e1a..dbdcf1c264 100644 --- a/cmd/src/batch_remote.go +++ b/cmd/src/batch_remote.go @@ -52,7 +52,12 @@ Examples: Client: cfg.apiClient(flags.api, flagSet.Output()), }) - if err := validateSourcegraphVersionConstraint(ctx, svc); err != nil { + ffs, err := svc.DetermineFeatureFlags(ctx) + if err != nil { + return err + } + + if err := validateSourcegraphVersionConstraint(ctx, ffs); err != nil { return err } diff --git a/cmd/src/batch_repositories.go b/cmd/src/batch_repositories.go index b3b96d5891..99c64a8688 100644 --- a/cmd/src/batch_repositories.go +++ b/cmd/src/batch_repositories.go @@ -64,7 +64,12 @@ Examples: Client: client, }) - if err := validateSourcegraphVersionConstraint(ctx, svc); err != nil { + ffs, err := svc.DetermineFeatureFlags(ctx) + if err != nil { + return err + } + + if err := validateSourcegraphVersionConstraint(ctx, ffs); err != nil { return err } diff --git a/cmd/src/batch_validate.go b/cmd/src/batch_validate.go index e83ac3f553..b3268ea758 100644 --- a/cmd/src/batch_validate.go +++ b/cmd/src/batch_validate.go @@ -63,7 +63,12 @@ Examples: Client: cfg.apiClient(apiFlags, flagSet.Output()), }) - if err := validateSourcegraphVersionConstraint(ctx, svc); err != nil { + ffs, err := svc.DetermineFeatureFlags(ctx) + if err != nil { + return err + } + + if err := validateSourcegraphVersionConstraint(ctx, ffs); err != nil { ui.ExecutionError(err) return err } diff --git a/go.mod b/go.mod index 360787f63b..ca114bf010 100644 --- a/go.mod +++ b/go.mod @@ -4,7 +4,6 @@ go 1.18 require ( cloud.google.com/go/storage v1.28.0 - github.com/Masterminds/semver v1.5.0 github.com/creack/goselect v0.1.2 github.com/derision-test/glock v0.0.0-20210316032053-f5b74334bb29 github.com/dineshappavoo/basex v0.0.0-20170425072625-481a6f6dc663 @@ -23,7 +22,7 @@ require ( github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf github.com/sourcegraph/scip v0.2.3 - github.com/sourcegraph/sourcegraph/lib v0.0.0-20221128221602-4b48d5d69f5d + github.com/sourcegraph/sourcegraph/lib v0.0.0-20221129022201-2804729b069c github.com/stretchr/testify v1.8.0 golang.org/x/net v0.2.0 golang.org/x/sync v0.1.0 @@ -39,11 +38,9 @@ require ( cloud.google.com/go/compute/metadata v0.2.1 // indirect cloud.google.com/go/iam v0.5.0 // indirect github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect + github.com/Masterminds/semver v1.5.0 // indirect github.com/Masterminds/sprig v2.15.0+incompatible // indirect github.com/alecthomas/chroma v0.10.0 // indirect - github.com/alecthomas/kingpin v2.2.6+incompatible // indirect - github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751 // indirect - github.com/alecthomas/units v0.0.0-20211218093645-b94a6e3cc137 // indirect github.com/aokoli/goutils v1.0.1 // indirect github.com/aymerick/douceur v0.2.0 // indirect github.com/bufbuild/buf v1.4.0 // indirect @@ -52,9 +49,7 @@ require ( github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f // indirect github.com/cockroachdb/redact v1.1.3 // indirect github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect - github.com/dave/jennifer v1.6.0 // indirect github.com/davecgh/go-spew v1.1.1 // indirect - github.com/derision-test/go-mockgen v1.3.7 // indirect github.com/dlclark/regexp2 v1.4.0 // indirect github.com/envoyproxy/protoc-gen-validate v0.3.0-java // indirect github.com/fatih/color v1.13.0 // indirect @@ -85,7 +80,6 @@ require ( github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-runewidth v0.0.13 // indirect github.com/microcosm-cc/bluemonday v1.0.17 // indirect - github.com/mitchellh/go-wordwrap v1.0.1 // indirect github.com/moby/term v0.0.0-20210619224110-3f7ff695adc6 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect diff --git a/go.sum b/go.sum index ca54f1a641..7d93f5e83c 100644 --- a/go.sum +++ b/go.sum @@ -27,12 +27,6 @@ github.com/Shopify/goreferrer v0.0.0-20181106222321-ec9c9a553398/go.mod h1:a1uqR github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY= github.com/alecthomas/chroma v0.10.0 h1:7XDcGkCQopCNKjZHfYrNLraA+M7e0fMiJ/Mfikbfjek= github.com/alecthomas/chroma v0.10.0/go.mod h1:jtJATyUxlIORhUOFNA9NZDWGAQ8wpxQQqNSB4rjA/1s= -github.com/alecthomas/kingpin v2.2.6+incompatible h1:5svnBTFgJjZvGKyYBtMB0+m5wvrbUHiqye8wRJMlnYI= -github.com/alecthomas/kingpin v2.2.6+incompatible/go.mod h1:59OFYbFVLKQKq+mqrL6Rw5bR0c3ACQaawgXx0QYndlE= -github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751 h1:JYp7IbQjafoB+tBA3gMyHYHrpOtNuDiK/uB5uXxq5wM= -github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= -github.com/alecthomas/units v0.0.0-20211218093645-b94a6e3cc137 h1:s6gZFSlWYmbqAuRjVTiNNhvNRfY2Wxp9nhfyel4rklc= -github.com/alecthomas/units v0.0.0-20211218093645-b94a6e3cc137/go.mod h1:OMCwj8VM1Kc9e19TLln2VL61YJF0x1XFtfdL4JdbSyE= github.com/aokoli/goutils v1.0.1 h1:7fpzNGoJ3VA8qcrm++XEE1QUe0mIwNeLa02Nwq7RDkg= github.com/aokoli/goutils v1.0.1/go.mod h1:SijmP0QR8LtwsmDs8Yii5Z/S4trXFGFC2oO5g9DP+DQ= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= @@ -73,15 +67,11 @@ github.com/creack/goselect v0.1.2/go.mod h1:a/NhLweNvqIYMuxcMOuWY516Cimucms3DglD github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/creack/pty v1.1.11 h1:07n33Z8lZxZ2qwegKbObQohDhXDQxiMMz1NOUGYlesw= github.com/creack/pty v1.1.11/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= -github.com/dave/jennifer v1.6.0 h1:MQ/6emI2xM7wt0tJzJzyUik2Q3Tcn2eE0vtYgh4GPVI= -github.com/dave/jennifer v1.6.0/go.mod h1:AxTG893FiZKqxy3FP1kL80VMshSMuz2G+EgvszgGRnk= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/derision-test/glock v0.0.0-20210316032053-f5b74334bb29 h1:O07j7ewg0eFHRx+7bxCA/7z86HJexl7HLY9kyVMmPDo= github.com/derision-test/glock v0.0.0-20210316032053-f5b74334bb29/go.mod h1:jKtLdBMrF+XQatqvg46wiWdDfDSSDjdhO4dOM2FX9H4= -github.com/derision-test/go-mockgen v1.3.7 h1:b/DXAXL2FkaRPpnbYK3ODdZzklmJAwox0tkc6yyXx74= -github.com/derision-test/go-mockgen v1.3.7/go.mod h1:/TXUePlhtHmDDCaDAi/a4g6xOHqMDz3Wf0r2NPGskB4= github.com/dgraph-io/badger v1.6.0/go.mod h1:zwt7syl517jmP8s94KqSxTlM6IMsdhYy6psNgSztDR4= github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= @@ -298,8 +288,6 @@ github.com/microcosm-cc/bluemonday v1.0.17 h1:Z1a//hgsQ4yjC+8zEkV8IWySkXnsxmdSY6 github.com/microcosm-cc/bluemonday v1.0.17/go.mod h1:Z0r70sCuXHig8YpBzCc5eGHAap2K7e/u082ZUpDRRqM= github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= -github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0= -github.com/mitchellh/go-wordwrap v1.0.1/go.mod h1:R62XHJLzvMFRBbcrT7m7WgmE1eOyTSsCt+hzestvNj0= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ= github.com/moby/term v0.0.0-20210619224110-3f7ff695adc6 h1:dcztxKSvZ4Id8iPpHERQBbIJfabdt4wUm5qy3wOL2Zc= @@ -390,10 +378,8 @@ github.com/sourcegraph/log v0.0.0-20220901143117-fc0516a694c9 h1:JjFyvx9hCD5+Jpu github.com/sourcegraph/log v0.0.0-20220901143117-fc0516a694c9/go.mod h1:UxiwB6C3xk3xOySJpW1R0MDUyfGuJRFS5Z8C+SA5p2I= github.com/sourcegraph/scip v0.2.3 h1:6nRsTlNTELn+1V7JxLrDVbBpb9H1gAbUF48N7x5B8Y4= github.com/sourcegraph/scip v0.2.3/go.mod h1:3D/RLCMvrrSam85RtFmC67SE/jhV9++hpCR5MTDzbA0= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20221004162410-237d5855fa13 h1:HEj9QVz35nIU4plPb7iJSFjcTA14zVnfAdfYZF5jsKg= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20221004162410-237d5855fa13/go.mod h1:e3v3msUOgthv/QCWUzhFdfR3+hwUSn37rtuw49IVJg4= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20221128221602-4b48d5d69f5d h1:uIvIqhKNSuTH49fZcOh0fhJoKni/5MO3sQ/0zCfj/MM= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20221128221602-4b48d5d69f5d/go.mod h1:tyHfYAVIPq+U6bCOTbIYra4uQ0gC7PQWA8BqmyF//Q0= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20221129022201-2804729b069c h1:bjTcIdEx6FvUXIbD1Ckjp7SfvV4jTyJ7RozZH/HVj9M= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20221129022201-2804729b069c/go.mod h1:PmWmo2ysXWCHcbtp08cDXKGD+8NQzrkj2UjdRBu9H0k= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= @@ -483,8 +469,6 @@ golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro= -golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 h1:6zppjxzCulZykYSLyVDYbneBfbaBIQPYMevg0bEwv2s= -golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.7.0 h1:LapD9S96VoQRhi/GrNTqeBJFrUjs5UHCAtTlgwA5oZA= golang.org/x/mod v0.7.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -510,8 +494,6 @@ golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96b golang.org/x/net v0.0.0-20210614182718-04defd469f4e/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211008194852-3b03d305991f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/net v0.0.0-20221014081412-f15817d10f9b h1:tvrvnPFcdzp294diPnrdZZZ8XUt2Tyj7svb7X52iDuU= -golang.org/x/net v0.0.0-20221014081412-f15817d10f9b/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk= golang.org/x/net v0.2.0 h1:sZfSu1wtKLGlWI4ZZayP0ck9Y73K1ynO6gqzTdBVdPU= golang.org/x/net v0.2.0/go.mod h1:KqCZLdyyvdV855qA2rE3GC2aiw5xGR5TEjj8smXukLY= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= @@ -561,13 +543,9 @@ golang.org/x/sys v0.0.0-20211117180635-dee7805ff2e1/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20211213223007-03aa0b5f6827/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220928140112-f11e5e49a4ec h1:BkDtF2Ih9xZ7le9ndzTA7KJow28VbQW3odyk/8drmuI= -golang.org/x/sys v0.0.0-20220928140112-f11e5e49a4ec/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.2.0 h1:ljd4t30dBnAvMZaQCevtY0xLLD0A+bRZXbgLMLU1F/A= golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/term v0.0.0-20220411215600-e5f449aeb171 h1:EH1Deb8WZJ0xc0WK//leUHXcX9aLE5SymusoTmMZye8= -golang.org/x/term v0.0.0-20220411215600-e5f449aeb171/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.2.0 h1:z85xZCsEl7bi/KwbNADeBYoOP0++7W1ipu+aGnpwzRM= golang.org/x/term v0.2.0/go.mod h1:TVmDHMZPmdnySmBfhjOoOdhjzdE1h4u1VwSiw2l1Nuc= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -599,8 +577,6 @@ golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.8-0.20211102182255-bb4add04ddef/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= golang.org/x/tools v0.1.8/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= -golang.org/x/tools v0.1.12 h1:VveCTK38A2rkS8ZqFY25HIDFscX5X9OoEhJd3quQmXU= -golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.3.0 h1:SrNbZl6ECOS1qFzgTdQfWXZM9XBkiA6tkFrH9YSTPHM= golang.org/x/tools v0.3.0/go.mod h1:/rWhSS2+zyEVwoJf8YAX6L2f0ntZ7Kn/mGgAWcipA5k= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/internal/api/version_check.go b/internal/api/version_check.go deleted file mode 100644 index dfc8e25f2c..0000000000 --- a/internal/api/version_check.go +++ /dev/null @@ -1,46 +0,0 @@ -package api - -import ( - "github.com/grafana/regexp" - - "github.com/Masterminds/semver" -) - -// NOTE: A version with a prerelease suffix (e.g. the "-rc.3" of "3.35.1-rc.3") is not -// considered by semver to satisfy a constraint without a prerelease suffix, regardless of -// whether or not the major/minor/patch version is greater than or equal to that of the -// constraint. -// -// For example, the version "3.35.1-rc.3" is not considered to satisfy the constraint ">= -// 3.23.0". This is likely not the expected outcome. However, the same version IS -// considered to satisfy the constraint "3.23.0-0". Thus, it is recommended to pass a -// constraint with a minimum prerelease version suffix attached if comparisons to -// prerelease versions are ever expected. See -// https://github.com/Masterminds/semver#working-with-prerelease-versions for more. -func CheckSourcegraphVersion(version, constraint, minDate string) (bool, error) { - if version == "dev" || version == "0.0.0+dev" { - return true, nil - } - - // Since we don't actually care about the abbreviated commit hash at the end of the - // version string, we match on 7 or more characters. Currently, the Sourcegraph version - // is expected to return 12: - // https://sourcegraph.com/github.com/sourcegraph/sourcegraph/-/blob/enterprise/dev/ci/internal/ci/config.go?L96. - buildDate := regexp.MustCompile(`^\d+_(\d{4}-\d{2}-\d{2})_[a-z0-9]{7,}$`) - matches := buildDate.FindStringSubmatch(version) - if len(matches) > 1 { - return matches[1] >= minDate, nil - } - - c, err := semver.NewConstraint(constraint) - if err != nil { - return false, nil - } - - v, err := semver.NewVersion(version) - if err != nil { - return false, err - } - - return c.Check(v), nil -} diff --git a/internal/api/version_check_test.go b/internal/api/version_check_test.go deleted file mode 100644 index fe8e0ee9f7..0000000000 --- a/internal/api/version_check_test.go +++ /dev/null @@ -1,107 +0,0 @@ -package api - -import "testing" - -func TestCheckSourcegraphVersion(t *testing.T) { - for _, tc := range []struct { - currentVersion, constraint, minDate string - expected bool - }{ - { - currentVersion: "3.12.6", - constraint: ">= 3.12.6", - minDate: "2020-01-19", - expected: true, - }, - { - currentVersion: "3.12.6-rc.1", - constraint: ">= 3.12.6-0", - minDate: "2020-01-19", - expected: true, - }, - { - currentVersion: "3.12.6-rc.3", - constraint: ">= 3.10.6-0", - minDate: "2020-01-19", - expected: true, - }, - { - currentVersion: "3.12.6", - constraint: ">= 3.13", - minDate: "2020-01-19", - expected: false, - }, - { - currentVersion: "3.13.0", - constraint: ">= 3.13", - minDate: "2020-01-19", - expected: true, - }, - { - currentVersion: "dev", - constraint: ">= 3.13", - minDate: "2020-01-19", - expected: true, - }, - { - currentVersion: "0.0.0+dev", - constraint: ">= 3.13", - minDate: "2020-01-19", - expected: true, - }, - // 7-character abbreviated hash - { - currentVersion: "54959_2020-01-29_9258595", - minDate: "2020-01-19", - constraint: ">= 999.13", - expected: true, - }, - { - currentVersion: "54959_2020-01-29_9258595", - minDate: "2020-01-30", - constraint: ">= 999.13", - expected: false, - }, - { - currentVersion: "54959_2020-01-29_9258595", - minDate: "2020-01-29", - constraint: ">= 0.0", - expected: true, - }, - // 12-character abbreviated hash - { - currentVersion: "54959_2020-01-29_925859585436", - minDate: "2020-01-19", - constraint: ">= 999.13", - expected: true, - }, - { - currentVersion: "54959_2020-01-29_925859585436", - minDate: "2020-01-30", - constraint: ">= 999.13", - expected: false, - }, - { - currentVersion: "54959_2020-01-29_925859585436", - minDate: "2020-01-29", - constraint: ">= 0.0", - expected: true, - }, - // Full 40-character hash, just for fun - { - currentVersion: "54959_2020-01-29_7db7d396346284fd0f8f79f130f38b16fb1d3d70", - minDate: "2020-01-29", - constraint: ">= 0.0", - expected: true, - }, - } { - actual, err := CheckSourcegraphVersion(tc.currentVersion, tc.constraint, tc.minDate) - if err != nil { - t.Errorf("err: %s", err) - } - - if actual != tc.expected { - t.Errorf("wrong result. want=%t, got=%t (version=%q, constraint=%q)", tc.expected, actual, tc.currentVersion, tc.constraint) - } - } -} diff --git a/internal/batches/executor/coordinator.go b/internal/batches/executor/coordinator.go index d1c16e64b6..921d02ff81 100644 --- a/internal/batches/executor/coordinator.go +++ b/internal/batches/executor/coordinator.go @@ -29,9 +29,10 @@ type Coordinator struct { type NewCoordinatorOpts struct { ExecOpts NewExecutorOpts - Cache cache.Cache - Logger log.LogManager - GlobalEnv []string + Cache cache.Cache + Logger log.LogManager + GlobalEnv []string + BinaryDiffs bool IsRemote bool } @@ -89,7 +90,7 @@ func (c *Coordinator) checkCacheForTask(ctx context.Context, batchSpec *batchesl // add it to the list of specs that are displayed to the user and // send to the server. Instead, we can just report that the task is // complete and move on. - if task.CachedStepResult.Diff == "" { + if len(task.CachedStepResult.Diff) == 0 { return specs, true, nil } @@ -101,6 +102,10 @@ func (c *Coordinator) checkCacheForTask(ctx context.Context, batchSpec *batchesl } func (c *Coordinator) buildChangesetSpecs(task *Task, batchSpec *batcheslib.BatchSpec, result execution.AfterStepResult) ([]*batcheslib.ChangesetSpec, error) { + version := 1 + if c.opts.BinaryDiffs { + version = 2 + } input := &batcheslib.ChangesetSpecInput{ Repository: batcheslib.Repository{ ID: task.Repository.ID, @@ -115,13 +120,14 @@ func (c *Coordinator) buildChangesetSpecs(task *Task, batchSpec *batcheslib.Batc TransformChanges: batchSpec.TransformChanges, Result: execution.AfterStepResult{ + Version: version, Diff: result.Diff, ChangedFiles: result.ChangedFiles, Outputs: result.Outputs, }, } - return batcheslib.BuildChangesetSpecs(input) + return batcheslib.BuildChangesetSpecs(input, c.opts.BinaryDiffs) } func (c *Coordinator) loadCachedStepResults(ctx context.Context, task *Task, globalEnv []string) error { @@ -155,7 +161,7 @@ func (c *Coordinator) buildSpecs(ctx context.Context, batchSpec *batcheslib.Batc // If the steps didn't result in any diff, we don't need to create a // changeset spec that's displayed to the user and send to the server. - if lastStepResult.Diff == "" { + if len(lastStepResult.Diff) == 0 { return nil, nil } diff --git a/internal/batches/executor/coordinator_test.go b/internal/batches/executor/coordinator_test.go index 5ac48da62d..9ce252cda3 100644 --- a/internal/batches/executor/coordinator_test.go +++ b/internal/batches/executor/coordinator_test.go @@ -39,10 +39,11 @@ func TestCoordinator_Execute(t *testing.T) { Body: testChangesetTemplate.Body, Commits: []batcheslib.GitCommitDescription{ { + Version: 2, Message: testChangesetTemplate.Commit.Message, AuthorName: testChangesetTemplate.Commit.Author.Name, AuthorEmail: testChangesetTemplate.Commit.Author.Email, - Diff: `dummydiff1`, + Diff: []byte(`dummydiff1`), }, }, Published: batcheslib.PublishedValue{Val: false}, @@ -78,8 +79,8 @@ func TestCoordinator_Execute(t *testing.T) { executor: &dummyExecutor{ results: []taskResult{ - {task: srcCLITask, stepResults: []execution.AfterStepResult{{Diff: `dummydiff1`}}}, - {task: sourcegraphTask, stepResults: []execution.AfterStepResult{{Diff: `dummydiff2`}}}, + {task: srcCLITask, stepResults: []execution.AfterStepResult{{Version: 2, Diff: []byte(`dummydiff1`)}}}, + {task: sourcegraphTask, stepResults: []execution.AfterStepResult{{Version: 2, Diff: []byte(`dummydiff2`)}}}, }, }, opts: NewCoordinatorOpts{}, @@ -87,10 +88,10 @@ func TestCoordinator_Execute(t *testing.T) { wantCacheEntries: 2, wantSpecs: []*batcheslib.ChangesetSpec{ buildSpecFor(testRepo1, func(spec *batcheslib.ChangesetSpec) { - spec.Commits[0].Diff = `dummydiff1` + spec.Commits[0].Diff = []byte(`dummydiff1`) }), buildSpecFor(testRepo2, func(spec *batcheslib.ChangesetSpec) { - spec.Commits[0].Diff = `dummydiff2` + spec.Commits[0].Diff = []byte(`dummydiff2`) }), }, }, @@ -133,7 +134,8 @@ func TestCoordinator_Execute(t *testing.T) { { task: srcCLITask, stepResults: []execution.AfterStepResult{{ - Diff: `dummydiff1`, + Version: 2, + Diff: []byte(`dummydiff1`), Outputs: map[string]interface{}{ "output1": "myOutputValue1", "output2": map[string]interface{}{ @@ -171,10 +173,11 @@ func TestCoordinator_Execute(t *testing.T) { batch_change_description=the description` spec.Commits = []batcheslib.GitCommitDescription{ { + Version: 2, Message: "output1=myOutputValue1,output2=subFieldValue", AuthorName: "output1=myOutputValue1", AuthorEmail: "output1=myOutputValue1", - Diff: `dummydiff1`, + Diff: []byte(`dummydiff1`), }, } }), @@ -197,8 +200,8 @@ func TestCoordinator_Execute(t *testing.T) { executor: &dummyExecutor{ results: []taskResult{ - {task: srcCLITask, stepResults: []execution.AfterStepResult{{Diff: nestedChangesDiff}}}, - {task: sourcegraphTask, stepResults: []execution.AfterStepResult{{Diff: nestedChangesDiff}}}, + {task: srcCLITask, stepResults: []execution.AfterStepResult{{Version: 2, Diff: nestedChangesDiff}}}, + {task: sourcegraphTask, stepResults: []execution.AfterStepResult{{Version: 2, Diff: nestedChangesDiff}}}, }, }, opts: NewCoordinatorOpts{}, @@ -210,19 +213,19 @@ func TestCoordinator_Execute(t *testing.T) { wantSpecs: []*batcheslib.ChangesetSpec{ buildSpecFor(testRepo1, func(spec *batcheslib.ChangesetSpec) { spec.HeadRef = "refs/heads/" + testChangesetTemplate.Branch - spec.Commits[0].Diff = nestedChangesDiffSubdirA + nestedChangesDiffSubdirB + spec.Commits[0].Diff = []byte(nestedChangesDiffSubdirA + nestedChangesDiffSubdirB) }), buildSpecFor(testRepo2, func(spec *batcheslib.ChangesetSpec) { spec.HeadRef = "refs/heads/in-directory-b" - spec.Commits[0].Diff = nestedChangesDiffSubdirB + nestedChangesDiffSubdirC + spec.Commits[0].Diff = []byte(nestedChangesDiffSubdirB + nestedChangesDiffSubdirC) }), buildSpecFor(testRepo1, func(spec *batcheslib.ChangesetSpec) { spec.HeadRef = "refs/heads/in-directory-c" - spec.Commits[0].Diff = nestedChangesDiffSubdirC + spec.Commits[0].Diff = []byte(nestedChangesDiffSubdirC) }), buildSpecFor(testRepo2, func(spec *batcheslib.ChangesetSpec) { spec.HeadRef = util.EnsureRefPrefix(testChangesetTemplate.Branch) - spec.Commits[0].Diff = nestedChangesDiffSubdirA + spec.Commits[0].Diff = []byte(nestedChangesDiffSubdirA) }), }, }, @@ -245,8 +248,8 @@ func TestCoordinator_Execute(t *testing.T) { executor: &dummyExecutor{ results: []taskResult{ - {task: srcCLITask, stepResults: []execution.AfterStepResult{{Diff: `dummydiff1`, StepIndex: 0}}}, - {task: sourcegraphTask, stepResults: []execution.AfterStepResult{{Diff: `dummydiff2`, StepIndex: 0}}}, + {task: srcCLITask, stepResults: []execution.AfterStepResult{{Version: 2, Diff: []byte(`dummydiff1`), StepIndex: 0}}}, + {task: sourcegraphTask, stepResults: []execution.AfterStepResult{{Version: 2, Diff: []byte(`dummydiff2`), StepIndex: 0}}}, }, }, opts: NewCoordinatorOpts{}, @@ -254,10 +257,10 @@ func TestCoordinator_Execute(t *testing.T) { wantCacheEntries: 2, wantSpecs: []*batcheslib.ChangesetSpec{ buildSpecFor(testRepo1, func(spec *batcheslib.ChangesetSpec) { - spec.Commits[0].Diff = `dummydiff1` + spec.Commits[0].Diff = []byte(`dummydiff1`) }), buildSpecFor(testRepo2, func(spec *batcheslib.ChangesetSpec) { - spec.Commits[0].Diff = `dummydiff2` + spec.Commits[0].Diff = []byte(`dummydiff2`) }), }, }, @@ -280,6 +283,7 @@ func TestCoordinator_Execute(t *testing.T) { tc.opts.Cache = c tc.opts.Logger = logManager + tc.opts.BinaryDiffs = true coord := Coordinator{ exec: tc.executor, @@ -369,9 +373,9 @@ func TestCoordinator_Execute_StepCaching(t *testing.T) { executor.results = []taskResult{{ task: task, stepResults: []execution.AfterStepResult{ - {StepIndex: 0, Diff: `step-0-diff`}, - {StepIndex: 1, Diff: `step-1-diff`}, - {StepIndex: 2, Diff: `step-2-diff`}, + {Version: 2, StepIndex: 0, Diff: []byte(`step-0-diff`)}, + {Version: 2, StepIndex: 1, Diff: []byte(`step-1-diff`)}, + {Version: 2, StepIndex: 2, Diff: []byte(`step-2-diff`)}, }, }} @@ -660,4 +664,4 @@ index 7f96c22..43df362 100644 +var c = 3 ` -const nestedChangesDiff = nestedChangesDiffSubdirA + nestedChangesDiffSubdirB + nestedChangesDiffSubdirC +var nestedChangesDiff = []byte(nestedChangesDiffSubdirA + nestedChangesDiffSubdirB + nestedChangesDiffSubdirC) diff --git a/internal/batches/executor/execution_cache_test.go b/internal/batches/executor/execution_cache_test.go index 0b1ff71877..d5ff754ffc 100644 --- a/internal/batches/executor/execution_cache_test.go +++ b/internal/batches/executor/execution_cache_test.go @@ -29,7 +29,7 @@ var cacheRepo2 = batches.Repository{ FileMatches: []string{"main.go"}, } -const testDiff = `diff --git a/README.md b/README.md +var testDiff = []byte(`diff --git a/README.md b/README.md new file mode 100644 index 0000000..3363c39 --- /dev/null @@ -38,7 +38,7 @@ index 0000000..3363c39 +# README + +This is the readme -` +`) func TestExecutionDiskCache_GetSet(t *testing.T) { ctx := context.Background() @@ -58,7 +58,8 @@ func TestExecutionDiskCache_GetSet(t *testing.T) { } value := execution.AfterStepResult{ - Diff: testDiff, + Version: 2, + Diff: testDiff, ChangedFiles: git.Changes{ Added: []string{"README.md"}, }, diff --git a/internal/batches/executor/executor.go b/internal/batches/executor/executor.go index 657e79e7e5..9ccb94a8fc 100644 --- a/internal/batches/executor/executor.go +++ b/internal/batches/executor/executor.go @@ -69,6 +69,8 @@ type NewExecutorOpts struct { IsRemote bool GlobalEnv []string ForceRoot bool + + BinaryDiffs bool } type executor struct { @@ -180,6 +182,7 @@ func (x *executor) do(ctx context.Context, task *Task, ui TaskExecutionUI) (err RepoArchive: repoArchive, WorkingDirectory: x.opts.WorkingDirectory, ForceRoot: x.opts.ForceRoot, + BinaryDiffs: x.opts.BinaryDiffs, UI: ui.StepsExecutionUI(task), } diff --git a/internal/batches/executor/executor_test.go b/internal/batches/executor/executor_test.go index 2a6040ffdc..c4accc0f87 100644 --- a/internal/batches/executor/executor_test.go +++ b/internal/batches/executor/executor_test.go @@ -455,7 +455,7 @@ func TestExecutor_Integration(t *testing.T) { lastStepResult := taskResult.stepResults[len(taskResult.stepResults)-1] - fileDiffs, err := diff.ParseMultiFileDiff([]byte(lastStepResult.Diff)) + fileDiffs, err := diff.ParseMultiFileDiff(lastStepResult.Diff) if err != nil { t.Fatalf("failed to parse diff: %s", err) } @@ -517,14 +517,14 @@ func TestExecutor_CachedStepResults(t *testing.T) { }, } - cachedDiff := `diff --git README.md README.md + cachedDiff := []byte(`diff --git README.md README.md index 02a19af..c9644dd 100644 --- README.md +++ README.md @@ -1 +1,2 @@ # Welcome to the README +foobar -` +`) task := &Task{ BatchChangeAttributes: &template.BatchChangeAttributes{}, @@ -533,6 +533,7 @@ index 02a19af..c9644dd 100644 }, CachedStepResultFound: true, CachedStepResult: execution.AfterStepResult{ + Version: 2, StepIndex: 0, Diff: cachedDiff, Outputs: map[string]interface{}{}, @@ -579,7 +580,7 @@ This repository is used to test opening and closing pull request with Automation }, } - cachedDiff := `diff --git README.md README.md + cachedDiff := []byte(`diff --git README.md README.md index 1914491..cd2ccbf 100644 --- README.md +++ README.md @@ -598,9 +599,9 @@ index 0000000..888e1ec +++ README.txt @@ -0,0 +1 @@ +this is step 1 -` +`) - wantFinalDiff := `diff --git README.md README.md + wantFinalDiff := []byte(`diff --git README.md README.md index 1914491..d6782d3 100644 --- README.md +++ README.md @@ -628,7 +629,7 @@ index 0000000..257ae8e +++ my-output.txt @@ -0,0 +1 @@ +this is step 5 -` +`) task := &Task{ Repository: testRepo1, @@ -648,6 +649,7 @@ echo "previous_step.modified_files=${{ previous_step.modified_files }}" >> READM }, CachedStepResultFound: true, CachedStepResult: execution.AfterStepResult{ + Version: 2, StepIndex: 2, Diff: cachedDiff, Outputs: map[string]interface{}{ @@ -705,7 +707,7 @@ This repository is used to test opening and closing pull request with Automation }, } - wantFinalDiff := `diff --git README.md README.md + wantFinalDiff := []byte(`diff --git README.md README.md index 3040106..5f2f924 100644 --- README.md +++ README.md @@ -713,7 +715,7 @@ index 3040106..5f2f924 100644 # automation-testing This repository is used to test opening and closing pull request with Automation +hello world -` +`) task := &Task{ Repository: testRepo1, @@ -724,8 +726,9 @@ index 3040106..5f2f924 100644 }, CachedStepResultFound: true, CachedStepResult: execution.AfterStepResult{ + Version: 2, StepIndex: 0, - Diff: "", + Diff: []byte(""), Outputs: map[string]interface{}{}, ChangedFiles: git.Changes{}, Stdout: "hello world", diff --git a/internal/batches/executor/run_steps.go b/internal/batches/executor/run_steps.go index b4911640f9..848362a3b3 100644 --- a/internal/batches/executor/run_steps.go +++ b/internal/batches/executor/run_steps.go @@ -54,6 +54,8 @@ type RunStepsOpts struct { // ForceRoot forces Docker containers to be run as root:root, rather than // whatever the image's default user and group are. ForceRoot bool + + BinaryDiffs bool } func RunSteps(ctx context.Context, opts *RunStepsOpts) (stepResults []execution.AfterStepResult, err error) { @@ -120,8 +122,8 @@ func RunSteps(ctx context.Context, opts *RunStepsOpts) (stepResults []execution. // If the previous steps made any modifications to the workspace yet, // apply them. - if opts.Task.CachedStepResult.Diff != "" { - if err := ws.ApplyDiff(ctx, []byte(opts.Task.CachedStepResult.Diff)); err != nil { + if len(opts.Task.CachedStepResult.Diff) > 0 { + if err := ws.ApplyDiff(ctx, opts.Task.CachedStepResult.Diff); err != nil { return nil, errors.Wrap(err, "applying diff of cache result") } } @@ -195,12 +197,17 @@ func RunSteps(ctx context.Context, opts *RunStepsOpts) (stepResults []execution. return stepResults, errors.Wrap(err, "getting changed files in step") } + version := 1 + if opts.BinaryDiffs { + version = 2 + } stepResult := execution.AfterStepResult{ + Version: version, ChangedFiles: changes, Stdout: stdoutBuffer.String(), Stderr: stderrBuffer.String(), StepIndex: i, - Diff: string(stepDiff), + Diff: stepDiff, // Those will be set below. Outputs: make(map[string]interface{}), } diff --git a/internal/batches/executor/ui.go b/internal/batches/executor/ui.go index 38c24340bb..547a2fb1f1 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 string, changes git.Changes, outputs map[string]interface{}) + StepFinished(idx int, diff []byte, changes git.Changes, outputs map[string]interface{}) 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 string, changes git.Changes, outputs map[string]interface{}) { +func (noop NoopStepsExecUI) StepFinished(idx int, diff []byte, changes git.Changes, outputs map[string]interface{}) { } func (noop NoopStepsExecUI) StepFailed(idx int, err error, exitCode int) { } diff --git a/internal/batches/features.go b/internal/batches/features.go index 0a020b6bc6..ee319709b7 100644 --- a/internal/batches/features.go +++ b/internal/batches/features.go @@ -1,15 +1,15 @@ package batches import ( + "github.com/sourcegraph/sourcegraph/lib/api" "github.com/sourcegraph/sourcegraph/lib/errors" - - "github.com/sourcegraph/src-cli/internal/api" ) // FeatureFlags represent features that are only available on certain // Sourcegraph versions and we therefore have to detect at runtime. type FeatureFlags struct { Sourcegraph40 bool + BinaryDiffs bool } func (ff *FeatureFlags) SetFromVersion(version string) error { @@ -28,6 +28,7 @@ func (ff *FeatureFlags) SetFromVersion(version string) error { // Example usage: // {&ff.FlagName, ">= 3.23.0-0", "2020-11-24"}, {&ff.Sourcegraph40, ">= 4.0.0-0", "2022-08-24"}, + {&ff.BinaryDiffs, ">= 4.3.0-0", "2022-11-29"}, } { value, err := api.CheckSourcegraphVersion(version, feature.constraint, feature.minDate) if err != nil { diff --git a/internal/batches/ui/json_lines.go b/internal/batches/ui/json_lines.go index f584a25a51..dea8e2d0ee 100644 --- a/internal/batches/ui/json_lines.go +++ b/internal/batches/ui/json_lines.go @@ -23,7 +23,9 @@ import ( var _ ExecUI = &JSONLines{} -type JSONLines struct{} +type JSONLines struct { + BinaryDiffs bool +} func (ui *JSONLines) ParsingBatchSpec() { logOperationStart(batcheslib.LogEventOperationParsingBatchSpec, &batcheslib.ParsingBatchSpecMetadata{}) @@ -89,7 +91,9 @@ func (ui *JSONLines) CheckingCacheSuccess(cachedSpecsFound int, tasksToExecute i } func (ui *JSONLines) ExecutingTasks(_ bool, _ int) executor.TaskExecutionUI { - return &taskExecutionJSONLines{} + return &taskExecutionJSONLines{ + binaryDiffs: ui.BinaryDiffs, + } } func (ui *JSONLines) ExecutingTasksSkippingErrors(err error) { @@ -174,7 +178,8 @@ func (ui *JSONLines) WriteAfterStepResult(key string, value execution.AfterStepR } type taskExecutionJSONLines struct { - linesTasks map[*executor.Task]batcheslib.JSONLinesTask + linesTasks map[*executor.Task]batcheslib.JSONLinesTask + binaryDiffs bool } // seededRand is used in randomID() to generate a "random" number. @@ -256,7 +261,8 @@ func (ui *taskExecutionJSONLines) StepsExecutionUI(task *executor.Task) executor } type stepsExecutionJSONLines struct { - linesTask *batcheslib.JSONLinesTask + linesTask *batcheslib.JSONLinesTask + binaryDiffs bool } const stepFlushDuration = 500 * time.Millisecond @@ -294,7 +300,14 @@ func (ui *stepsExecutionJSONLines) StepPreparingFailed(step int, err error) { } func (ui *stepsExecutionJSONLines) StepStarted(step int, runScript string, env map[string]string) { - logOperationStart(batcheslib.LogEventOperationTaskStep, &batcheslib.TaskStepMetadata{TaskID: ui.linesTask.ID, Step: step, Env: env}) + logOperationStart( + batcheslib.LogEventOperationTaskStep, + &batcheslib.TaskStepMetadata{ + Version: version(ui.binaryDiffs), + TaskID: ui.linesTask.ID, + Step: step, + Env: env, + }) } func (ui *stepsExecutionJSONLines) StepOutputWriter(ctx context.Context, task *executor.Task, step int) executor.StepOutputWriter { @@ -302,19 +315,21 @@ func (ui *stepsExecutionJSONLines) StepOutputWriter(ctx context.Context, task *e logOperationProgress( batcheslib.LogEventOperationTaskStep, &batcheslib.TaskStepMetadata{ - TaskID: ui.linesTask.ID, - Step: step, - Out: data, + Version: version(ui.binaryDiffs), + TaskID: ui.linesTask.ID, + Step: step, + Out: data, }, ) } return NewIntervalProcessWriter(ctx, stepFlushDuration, sink) } -func (ui *stepsExecutionJSONLines) StepFinished(step int, diff string, changes git.Changes, outputs map[string]interface{}) { +func (ui *stepsExecutionJSONLines) StepFinished(step int, diff []byte, changes git.Changes, outputs map[string]interface{}) { logOperationSuccess( batcheslib.LogEventOperationTaskStep, &batcheslib.TaskStepMetadata{ + Version: version(ui.binaryDiffs), TaskID: ui.linesTask.ID, Step: step, Diff: diff, @@ -327,6 +342,7 @@ func (ui *stepsExecutionJSONLines) StepFailed(step int, err error, exitCode int) logOperationFailure( batcheslib.LogEventOperationTaskStep, &batcheslib.TaskStepMetadata{ + Version: version(ui.binaryDiffs), TaskID: ui.linesTask.ID, Step: step, Error: err.Error(), @@ -370,3 +386,10 @@ func logEvent(e batcheslib.LogEvent) { fmt.Fprintln(os.Stderr, err) } } + +func version(binaryDiffs bool) int { + if binaryDiffs { + return 2 + } + return 1 +} diff --git a/internal/batches/ui/task_exec_tui.go b/internal/batches/ui/task_exec_tui.go index 606396ef89..43243324ed 100644 --- a/internal/batches/ui/task_exec_tui.go +++ b/internal/batches/ui/task_exec_tui.go @@ -297,7 +297,7 @@ func (ui *taskExecTUI) TaskChangesetSpecsBuilt(task *executor.Task, specs []*bat var fileDiffs []*diff.FileDiff for _, spec := range specs { - fd, err := diff.ParseMultiFileDiff([]byte(spec.Commits[0].Diff)) + fd, err := diff.ParseMultiFileDiff(spec.Commits[0].Diff) if err != nil { ui.progress.Verbosef("%-*s failed to display status: %s", ui.maxRepoName, ts.displayName, err) return @@ -471,7 +471,7 @@ func (ui stepsExecTUI) StepOutputWriter(ctx context.Context, task *executor.Task return executor.NoopStepOutputWriter{} } -func (ui stepsExecTUI) StepFinished(idx int, diff string, changes git.Changes, outputs map[string]interface{}) { +func (ui stepsExecTUI) StepFinished(idx int, diff []byte, changes git.Changes, outputs map[string]interface{}) { // 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 572155f11b..e27c671898 100644 --- a/internal/batches/ui/task_exec_tui_test.go +++ b/internal/batches/ui/task_exec_tui_test.go @@ -14,7 +14,7 @@ import ( "github.com/sourcegraph/src-cli/internal/batches/graphql" ) -const progressPrinterDiff = `diff --git README.md README.md +var progressPrinterDiff = []byte(`diff --git README.md README.md new file mode 100644 index 0000000..3363c39 --- /dev/null @@ -37,7 +37,7 @@ index 627c2ae..88f1836 100644 @@ -1 +1 @@ -this is x +this is x (or is it?) -` +`) func TestTaskExecTUI_Integration(t *testing.T) { if runtime.GOOS == "windows" { @@ -153,6 +153,7 @@ func TestTaskExecTUI_Integration(t *testing.T) { Body: "This is my batch change", Commits: []batcheslib.GitCommitDescription{ { + Version: 2, Message: "This is my batch change", Diff: progressPrinterDiff, }, From c06c567e0078eef8be1ac835e4fe59c042361ce0 Mon Sep 17 00:00:00 2001 From: Robert Lin Date: Tue, 29 Nov 2022 08:06:21 -0800 Subject: [PATCH 271/647] changelog: add mention of new 'src snapshot' commands (#891) --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index d05ecc14e6..786630c939 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,7 @@ All notable changes to `src-cli` are documented in this file. ### Added - Batch specs being run locally with `src batch preview` or `src batch apply` can now be run with the `-run-as-root` flag, which will run all step containers as root instead of the default user for the image. This is off by default. [#886](https://github.com/sourcegraph/src-cli/pull/886) +- An **experimental** set of `src snapshot` commands for generating and sharing snapshots of Sourcegraph instances, as well as testing Sourcegraph instances restored from snapshots. [#888](https://github.com/sourcegraph/src-cli/pull/888), [#889](https://github.com/sourcegraph/src-cli/pull/889), [#890](https://github.com/sourcegraph/src-cli/pull/890) ### Changed From 7462d799377c790250421219545611ce5cd25ed2 Mon Sep 17 00:00:00 2001 From: Robert Lin Date: Tue, 29 Nov 2022 10:20:57 -0800 Subject: [PATCH 272/647] snapshot: improve docstrings (#892) --- cmd/src/snapshot_databases.go | 4 +++- cmd/src/snapshot_summary.go | 13 +++++++++---- cmd/src/snapshot_testcmd.go | 13 ++++++++++++- cmd/src/snapshot_upload.go | 11 +++++++---- 4 files changed, 31 insertions(+), 10 deletions(-) diff --git a/cmd/src/snapshot_databases.go b/cmd/src/snapshot_databases.go index e519279229..7b3583d1d4 100644 --- a/cmd/src/snapshot_databases.go +++ b/cmd/src/snapshot_databases.go @@ -99,7 +99,9 @@ TARGETS FILES return errors.Wrap(err, "failed to build commands") } - b := out.Block(output.Emoji(output.EmojiSuccess, "Commands generated - run them all to generate required database dumps:")) + _ = os.MkdirAll(srcSnapshotDir, os.ModePerm) + + b := out.Block(output.Emoji(output.EmojiSuccess, "Run these commands to generate the required database dumps:")) b.Write("\n" + strings.Join(commands, "\n")) b.Close() diff --git a/cmd/src/snapshot_summary.go b/cmd/src/snapshot_summary.go index ba164e59c8..36f001ba7b 100644 --- a/cmd/src/snapshot_summary.go +++ b/cmd/src/snapshot_summary.go @@ -14,12 +14,15 @@ import ( ) func init() { - usage := `'src snapshot summary' generates summary data for acceptance testing of a restored Sourcegraph instance with 'src snapshot test'. + usage := fmt.Sprintf(`'src snapshot summary' generates summary data for acceptance testing of a restored Sourcegraph instance with 'src snapshot test'. USAGE src login # site-admin authentication required src [-v] snapshot summary -` + +SUMMARY DATA + Use '-dump-requests' to see what data is requested, or open the generated summary at %q. +`, srcSnapshotSummaryPath) flagSet := flag.NewFlagSet("summary", flag.ExitOnError) apiFlags := api.NewFlags(flagSet) @@ -38,7 +41,9 @@ USAGE return err } - f, err := os.OpenFile(snapshotSummaryPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm) + _ = os.MkdirAll(srcSnapshotDir, os.ModePerm) + + f, err := os.OpenFile(srcSnapshotSummaryPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm) if err != nil { return errors.Wrap(err, "open snapshot file") } @@ -48,7 +53,7 @@ USAGE return errors.Wrap(err, "write snapshot file") } - out.WriteLine(output.Emoji(output.EmojiSuccess, "Summary snapshot data generated!")) + out.WriteLine(output.Emojif(output.EmojiSuccess, "Summary snapshot data generated in %q!", srcSnapshotSummaryPath)) return nil }, usageFunc: func() { fmt.Fprint(flag.CommandLine.Output(), usage) }, diff --git a/cmd/src/snapshot_testcmd.go b/cmd/src/snapshot_testcmd.go index 1d8fb89d14..e3d760c741 100644 --- a/cmd/src/snapshot_testcmd.go +++ b/cmd/src/snapshot_testcmd.go @@ -24,9 +24,20 @@ func init() { USAGE src login # site-admin authentication required src [-v] snapshot test [-summary-path="./src-snapshot-summary.json"] + +ASSESSING RESULTS + The outputs of the test is supposed to be used only as a reference indicator of whether or not the instance is in a healthy state. + + It generally does not give a definitive result, though if an issue is found that the test deems may be critical, the command will exit with status 1. + +SNAPSHOT SUMMARY + The snapshot summary to assert against ('-summary-path') should be generated by 'src snapshot summary'. + +TEST DATA + Use '-dump-requests' to see what data is requested to perform tests. ` flagSet := flag.NewFlagSet("test", flag.ExitOnError) - snapshotSummaryPath := flagSet.String("summary-path", "./src-snapshot-summary.json", "path to read snapshot summary from") + snapshotSummaryPath := flagSet.String("summary-path", srcSnapshotSummaryPath, "path to read snapshot summary from") since := flagSet.Duration("since", 1*time.Hour, "duration ago to look for healthcheck data") apiFlags := api.NewFlags(flagSet) diff --git a/cmd/src/snapshot_upload.go b/cmd/src/snapshot_upload.go index b7e3e2ad97..a7ced84ff3 100644 --- a/cmd/src/snapshot_upload.go +++ b/cmd/src/snapshot_upload.go @@ -20,15 +20,18 @@ import ( const srcSnapshotDir = "./src-snapshot" -var snapshotSummaryPath = path.Join(srcSnapshotDir, "summary.json") +var srcSnapshotSummaryPath = path.Join(srcSnapshotDir, "summary.json") // https://pkg.go.dev/cloud.google.com/go/storage#section-readme func init() { - usage := `'src snapshot upload' uploads snapshot contents. + usage := `'src snapshot upload' uploads instance snapshot contents generated by 'src snapshot databases' and 'src snapshot summary' to the designated bucket. USAGE - src + src snapshot upload -bucket=$BUCKET -credentials=$CREDENTIALS_FILE + +BUCKET + In general, a Google Cloud Storage bucket and relevant credentials will be provided by Sourcegraph when using this functionality to share a snapshot with Sourcegraph. ` flagSet := flag.NewFlagSet("upload", flag.ExitOnError) bucketName := flagSet.String("bucket", "", "destination Cloud Storage bucket name") @@ -65,7 +68,7 @@ USAGE ) // Open snapshot summary - if f, err := os.Open(snapshotSummaryPath); err != nil { + if f, err := os.Open(srcSnapshotSummaryPath); err != nil { return errors.Wrap(err, "failed to open snapshot summary - generate one with 'src snapshot summary'") } else { stat, err := f.Stat() From 173d2ad97a0c4a70e33f484bbb92e6ccaeadce19 Mon Sep 17 00:00:00 2001 From: Robert Lin Date: Wed, 30 Nov 2022 08:54:09 -0800 Subject: [PATCH 273/647] snapshot: trim extension statements from pgdump when uploading (#893) When uploading a snapshot, trim extension statements unsupported by Google Cloud SQL. We do this on upload so that the customer's copy of the dump remains unmodified (in case something goes wrong, we still have the original to work with - trimming can be disabled with trim-extensions=false). --- cmd/src/snapshot_upload.go | 59 +++++++++++++++++-------- internal/pgdump/extensions.go | 67 ++++++++++++++++++++++++++++ internal/pgdump/extensions_test.go | 70 ++++++++++++++++++++++++++++++ 3 files changed, 177 insertions(+), 19 deletions(-) create mode 100644 internal/pgdump/extensions.go create mode 100644 internal/pgdump/extensions_test.go diff --git a/cmd/src/snapshot_upload.go b/cmd/src/snapshot_upload.go index a7ced84ff3..eef0d31042 100644 --- a/cmd/src/snapshot_upload.go +++ b/cmd/src/snapshot_upload.go @@ -36,6 +36,7 @@ BUCKET flagSet := flag.NewFlagSet("upload", flag.ExitOnError) bucketName := flagSet.String("bucket", "", "destination Cloud Storage bucket name") credentialsPath := flagSet.String("credentials", "", "JSON credentials file for Google Cloud service account") + trimExtensions := flagSet.Bool("trim-extensions", true, "trim EXTENSION statements from database dumps for import to Google Cloud SQL") snapshotCommands = append(snapshotCommands, &command{ flagSet: flagSet, @@ -59,8 +60,9 @@ BUCKET } type upload struct { - file *os.File - stat os.FileInfo + file *os.File + stat os.FileInfo + trimExtensions bool } var ( uploads []upload // index aligned with progressBars @@ -76,8 +78,9 @@ BUCKET return errors.Wrap(err, "get file size") } uploads = append(uploads, upload{ - file: f, - stat: stat, + file: f, + stat: stat, + trimExtensions: false, // not a database dump }) progressBars = append(progressBars, output.ProgressBar{ Label: stat.Name(), @@ -95,8 +98,9 @@ BUCKET return errors.Wrap(err, "get file size") } uploads = append(uploads, upload{ - file: f, - stat: stat, + file: f, + stat: stat, + trimExtensions: *trimExtensions, }) progressBars = append(progressBars, output.ProgressBar{ Label: stat.Name(), @@ -116,7 +120,7 @@ BUCKET g.Go(func(ctx context.Context) error { progressFn := func(p int64) { progress.SetValue(i, float64(p)) } - if err := copyToBucket(ctx, u.file, u.stat, bucket, progressFn); err != nil { + if err := copyDumpToBucket(ctx, u.file, u.stat, bucket, progressFn, u.trimExtensions); err != nil { return errors.Wrap(err, u.stat.Name()) } @@ -139,26 +143,43 @@ BUCKET }) } -func copyToBucket(ctx context.Context, src io.Reader, stat fs.FileInfo, dst *storage.BucketHandle, progressFn func(int64)) error { - writer := dst.Object(stat.Name()).NewWriter(ctx) - writer.ProgressFunc = progressFn - defer writer.Close() +func copyDumpToBucket(ctx context.Context, src io.ReadSeeker, stat fs.FileInfo, dst *storage.BucketHandle, progressFn func(int64), trimExtensions bool) error { + // Set up object to write to + object := dst.Object(stat.Name()).NewWriter(ctx) + object.ProgressFunc = progressFn + defer object.Close() + + // To assert against actual file size + var totalWritten int64 + + // Do a partial copy that trims out unwanted statements + if trimExtensions { + written, err := pgdump.PartialCopyWithoutExtensions(object, src, progressFn) + if err != nil { + return errors.Wrap(err, "trim extensions and upload") + } + totalWritten += written + } // io.Copy is the best way to copy from a reader to writer in Go, and storage.Writer - // has its own chunking mechanisms internally. - written, err := io.Copy(writer, src) + // has its own chunking mechanisms internally. io.Reader is stateful, so this copy + // will just continue from where we left off if we use copyAndTrimExtensions. + written, err := io.Copy(object, src) if err != nil { - return err + return errors.Wrap(err, "upload") } + totalWritten += written - // Progress is not called on completion, so we call it manually after io.Copy is done + // Progress is not called on completion of io.Copy, so we call it manually after to + // update our pretty progress bars. progressFn(written) - // Validate we have sent all data + // Validate we have sent all data. copyAndTrimExtensions may add some bytes, so the + // check is not a strict equality. size := stat.Size() - if written != size { - return errors.Newf("expected to write %d bytes, but actually wrote %d bytes", - size, written) + if totalWritten < size { + return errors.Newf("expected to write %d bytes, but actually wrote %d bytes (diff: %d bytes)", + size, totalWritten, totalWritten-size) } return nil diff --git a/internal/pgdump/extensions.go b/internal/pgdump/extensions.go new file mode 100644 index 0000000000..70f896a335 --- /dev/null +++ b/internal/pgdump/extensions.go @@ -0,0 +1,67 @@ +package pgdump + +import ( + "bufio" + "bytes" + "io" + + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +// PartialCopyWithoutExtensions will perform a partial copy of a SQL database dump from +// src to dst while commenting out EXTENSIONs-related statements. When it determines there +// are no more EXTENSIONs-related statements, it will return, resetting src to the position +// of the last contents written to dst. +// +// This is needed for import to Google Cloud Storage, which does not like many EXTENSION +// statements. For more details, see https://cloud.google.com/sql/docs/postgres/import-export/import-export-dmp +// +// Filtering requires reading entire lines into memory - this can be a very expensive +// operation, so when filtering is complete the more efficient io.Copy should be used +// to perform the remainder of the copy from src to dst. +func PartialCopyWithoutExtensions(dst io.Writer, src io.ReadSeeker, progressFn func(int64)) (int64, error) { + var ( + reader = bufio.NewReader(src) + // position we have consumed up to, track separately because bufio.Reader may have + // read ahead on src. This allows us to reset src later. + consumed int64 + // number of bytes we have actually written to dst - it should always be returned. + written int64 + // set to true when we have done all our filtering + noMoreExtensions bool + ) + + for !noMoreExtensions { + // Read up to a line, keeping track of our position in src + line, err := reader.ReadBytes('\n') + consumed += int64(len(line)) + if err != nil { + return written, err + } + + // Once we start seeing table creations, we are definitely done with extensions, + // so we can hand off the rest to the superior io.Copy implementation. + if bytes.HasPrefix(line, []byte("CREATE TABLE")) { + // we are done with extensions + noMoreExtensions = true + } else if bytes.HasPrefix(line, []byte("COMMENT ON EXTENSION")) { + // comment out this line + line = append([]byte("-- "), line...) + } + + // Write this line and update our progress before returning on error + lineWritten, err := dst.Write(line) + written += int64(lineWritten) + progressFn(written) + if err != nil { + return written, err + } + } + + // No more extensions - reset src to the last actual consumed position + _, err := src.Seek(consumed, io.SeekStart) + if err != nil { + return written, errors.Wrap(err, "reset src position") + } + return written, nil +} diff --git a/internal/pgdump/extensions_test.go b/internal/pgdump/extensions_test.go new file mode 100644 index 0000000000..d6c3286a84 --- /dev/null +++ b/internal/pgdump/extensions_test.go @@ -0,0 +1,70 @@ +package pgdump + +import ( + "bytes" + "io" + "os" + "path/filepath" + "runtime" + "testing" + + "github.com/hexops/autogold" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestPartialCopyWithoutExtensions(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("Test doesn't work on Windows of weirdness with t.TempDir() handling") + } + + // Create test data - there is no stdlib in-memory io.ReadSeeker implementation + src, err := os.Create(filepath.Join(t.TempDir(), t.Name())) + require.NoError(t, err) + _, err = src.WriteString(`-- Some comment + +CREATE EXTENSION foobar + +COMMENT ON EXTENSION barbaz + +CREATE TYPE asdf + +CREATE TABLE robert ( + ... +) + +CREATE TABLE bobhead ( + ... +)`) + require.NoError(t, err) + _, err = src.Seek(0, io.SeekStart) + require.NoError(t, err) + + // Set up target to assert against + var dst bytes.Buffer + + // Perform partial copy + _, err = PartialCopyWithoutExtensions(&dst, src, func(i int64) {}) + assert.NoError(t, err) + + // Copy rest of contents + _, err = io.Copy(&dst, src) + assert.NoError(t, err) + + // Assert contents (update with -update) + autogold.Want("partial-copy-without-extensions", `-- Some comment + +CREATE EXTENSION foobar + +-- COMMENT ON EXTENSION barbaz + +CREATE TYPE asdf + +CREATE TABLE robert ( + ... +) + +CREATE TABLE bobhead ( + ... +)`).Equal(t, dst.String()) +} From ba6d0bf534bde2b42f73fbfef92616550a4472cd Mon Sep 17 00:00:00 2001 From: Thomas Liu <70350613+tbliu98@users.noreply.github.com> Date: Mon, 5 Dec 2022 17:05:58 -0600 Subject: [PATCH 274/647] add CRUD support for repo key-value pairs (#896) * add CRUD support for repo key-value pairs - Add field KeyValuePairs to the Repository type so it will be part of the response object for repo read requests - Add commands `src repos add-kvp`, `src repos update-kvp`, and `src repos delete-kvp` * go imports * rename added files for consistency --- cmd/src/repos.go | 13 +++++ cmd/src/repos_add_kvp.go | 99 +++++++++++++++++++++++++++++++++++++ cmd/src/repos_delete_kvp.go | 84 +++++++++++++++++++++++++++++++ cmd/src/repos_update_kvp.go | 99 +++++++++++++++++++++++++++++++++++++ 4 files changed, 295 insertions(+) create mode 100644 cmd/src/repos_add_kvp.go create mode 100644 cmd/src/repos_delete_kvp.go create mode 100644 cmd/src/repos_update_kvp.go diff --git a/cmd/src/repos.go b/cmd/src/repos.go index b5c2020344..d58fe0abe0 100644 --- a/cmd/src/repos.go +++ b/cmd/src/repos.go @@ -23,6 +23,9 @@ The commands are: get gets a repository list lists repositories delete deletes repositories + add-kvp adds a key-value pair to a repository + update-kvp updates a key-value pair on a repository + delete-kvp deletes a key-value pair from a repository Use "src repos [command] -h" for more information about a command. ` @@ -63,6 +66,10 @@ fragment RepositoryFields on Repository { displayName } viewerCanAdminister + keyValuePairs { + key + value + } } ` @@ -77,6 +84,12 @@ type Repository struct { ExternalRepository ExternalRepository `json:"externalRepository"` DefaultBranch GitRef `json:"defaultBranch"` ViewerCanAdminister bool `json:"viewerCanAdminister"` + KeyValuePairs []KeyValuePair `json:"keyValuePairs"` +} + +type KeyValuePair struct { + Key string `json:"key"` + Value *string `json:"value"` } type ExternalRepository struct { diff --git a/cmd/src/repos_add_kvp.go b/cmd/src/repos_add_kvp.go new file mode 100644 index 0000000000..d7155c54c1 --- /dev/null +++ b/cmd/src/repos_add_kvp.go @@ -0,0 +1,99 @@ +package main + +import ( + "context" + "flag" + "fmt" + + "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/src-cli/internal/api" +) + +func init() { + usage := ` +Examples: + + Add a key-value pair to a repository: + + $ src repos add-kvp -repo=repoID -key=mykey -value=myvalue + + Omitting -value will create a tag (a key with a null value). +` + + flagSet := flag.NewFlagSet("add-kvp", flag.ExitOnError) + usageFunc := func() { + fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src repos %s':\n", flagSet.Name()) + flagSet.PrintDefaults() + fmt.Println(usage) + } + var ( + repoFlag = flagSet.String("repo", "", `The ID of the repo to add the key-value pair to (required)`) + keyFlag = flagSet.String("key", "", `The name of the key to add (required)`) + valueFlag = flagSet.String("value", "", `The value associated with the key. Defaults to null.`) + apiFlags = api.NewFlags(flagSet) + ) + + handler := func(args []string) error { + if err := flagSet.Parse(args); err != nil { + return err + } + if *repoFlag == "" { + return errors.New("error: repo is required") + } + + keyFlag = nil + valueFlag = nil + flagSet.Visit(func(f *flag.Flag) { + if f.Name == "key" { + key := f.Value.String() + keyFlag = &key + } + + if f.Name == "value" { + value := f.Value.String() + valueFlag = &value + } + }) + if keyFlag == nil { + return errors.New("error: key is required") + } + + client := cfg.apiClient(apiFlags, flagSet.Output()) + + query := `mutation addKVP( + $repo: ID!, + $key: String!, + $value: String, +) { + addRepoKeyValuePair( + repo: $repo, + key: $key, + value: $value, + ) { + alwaysNil + } +}` + + if ok, err := client.NewRequest(query, map[string]interface{}{ + "repo": *repoFlag, + "key": *keyFlag, + "value": valueFlag, + }).Do(context.Background(), nil); err != nil || !ok { + return err + } + + if valueFlag != nil { + fmt.Printf("Key-value pair '%s:%v' created.\n", *keyFlag, *valueFlag) + } else { + fmt.Printf("Key-value pair '%s:' created.\n", *keyFlag) + } + return nil + } + + // Register the command. + reposCommands = append(reposCommands, &command{ + flagSet: flagSet, + handler: handler, + usageFunc: usageFunc, + }) +} diff --git a/cmd/src/repos_delete_kvp.go b/cmd/src/repos_delete_kvp.go new file mode 100644 index 0000000000..4b9612a3a9 --- /dev/null +++ b/cmd/src/repos_delete_kvp.go @@ -0,0 +1,84 @@ +package main + +import ( + "context" + "flag" + "fmt" + + "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/src-cli/internal/api" +) + +func init() { + usage := ` +Examples: + + Delete a key-value pair from a repository: + + $ src repos delete-kvp -repo=repoID -key=mykey + +` + + flagSet := flag.NewFlagSet("delete-kvp", flag.ExitOnError) + usageFunc := func() { + fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src repos %s':\n", flagSet.Name()) + flagSet.PrintDefaults() + fmt.Println(usage) + } + var ( + repoFlag = flagSet.String("repo", "", `The ID of the repo with the key-value pair to be deleted (required)`) + keyFlag = flagSet.String("key", "", `The name of the key to be deleted (required)`) + apiFlags = api.NewFlags(flagSet) + ) + + handler := func(args []string) error { + if err := flagSet.Parse(args); err != nil { + return err + } + if *repoFlag == "" { + return errors.New("error: repo is required") + } + + keyFlag = nil + flagSet.Visit(func(f *flag.Flag) { + if f.Name == "key" { + key := f.Value.String() + keyFlag = &key + } + }) + if keyFlag == nil { + return errors.New("error: key is required") + } + + client := cfg.apiClient(apiFlags, flagSet.Output()) + + query := `mutation deleteKVP( + $repo: ID!, + $key: String!, +) { + deleteRepoKeyValuePair( + repo: $repo, + key: $key, + ) { + alwaysNil + } +}` + + if ok, err := client.NewRequest(query, map[string]interface{}{ + "repo": *repoFlag, + "key": *keyFlag, + }).Do(context.Background(), nil); err != nil || !ok { + return err + } + + fmt.Printf("Key-value pair with key '%s' deleted.\n", *keyFlag) + return nil + } + + // Register the command. + reposCommands = append(reposCommands, &command{ + flagSet: flagSet, + handler: handler, + usageFunc: usageFunc, + }) +} diff --git a/cmd/src/repos_update_kvp.go b/cmd/src/repos_update_kvp.go new file mode 100644 index 0000000000..4e12e9a423 --- /dev/null +++ b/cmd/src/repos_update_kvp.go @@ -0,0 +1,99 @@ +package main + +import ( + "context" + "flag" + "fmt" + + "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/src-cli/internal/api" +) + +func init() { + usage := ` +Examples: + + Update the value for a key on a repository: + + $ src repos update-kvp -repo=repoID -key=my-key -value=new-value + + Omitting -value will set the value of the key to null. +` + + flagSet := flag.NewFlagSet("update-kvp", flag.ExitOnError) + usageFunc := func() { + fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src repos %s':\n", flagSet.Name()) + flagSet.PrintDefaults() + fmt.Println(usage) + } + var ( + repoFlag = flagSet.String("repo", "", `The ID of the repo with the key to be updated (required)`) + keyFlag = flagSet.String("key", "", `The name of the key to be updated (required)`) + valueFlag = flagSet.String("value", "", `The new value of the key to be set. Defaults to null.`) + apiFlags = api.NewFlags(flagSet) + ) + + handler := func(args []string) error { + if err := flagSet.Parse(args); err != nil { + return err + } + if *repoFlag == "" { + return errors.New("error: repo is required") + } + + keyFlag = nil + valueFlag = nil + flagSet.Visit(func(f *flag.Flag) { + if f.Name == "key" { + key := f.Value.String() + keyFlag = &key + } + + if f.Name == "value" { + value := f.Value.String() + valueFlag = &value + } + }) + if keyFlag == nil { + return errors.New("error: key is required") + } + + client := cfg.apiClient(apiFlags, flagSet.Output()) + + query := `mutation updateKVP( + $repo: ID!, + $key: String!, + $value: String, +) { + updateRepoKeyValuePair( + repo: $repo, + key: $key, + value: $value, + ) { + alwaysNil + } +}` + + if ok, err := client.NewRequest(query, map[string]interface{}{ + "repo": *repoFlag, + "key": *keyFlag, + "value": valueFlag, + }).Do(context.Background(), nil); err != nil || !ok { + return err + } + + if valueFlag != nil { + fmt.Printf("Value of key '%s' updated to '%v'\n", *keyFlag, *valueFlag) + } else { + fmt.Printf("Value of key '%s' updated to \n", *keyFlag) + } + return nil + } + + // Register the command. + reposCommands = append(reposCommands, &command{ + flagSet: flagSet, + handler: handler, + usageFunc: usageFunc, + }) +} From cbc5871e9b1df2e839c175d1bbc5cb85685a366a Mon Sep 17 00:00:00 2001 From: Bolaji Olajide <25608335+BolajiOlajide@users.noreply.github.com> Date: Fri, 9 Dec 2022 22:41:02 +0100 Subject: [PATCH 275/647] add watchdog goroutine for docker (#898) --- CHANGELOG.md | 2 ++ cmd/src/batch_common.go | 17 +++++++++ go.mod | 2 +- go.sum | 4 +-- internal/batches/ui/exec_ui.go | 2 ++ internal/batches/ui/json_lines.go | 8 +++++ internal/batches/ui/tui.go | 12 +++++++ internal/batches/watchdog/watchdog.go | 38 ++++++++++++++++++++ internal/batches/watchdog/watchdog_test.go | 40 ++++++++++++++++++++++ 9 files changed, 122 insertions(+), 3 deletions(-) create mode 100644 internal/batches/watchdog/watchdog.go create mode 100644 internal/batches/watchdog/watchdog_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 786630c939..2d95ac8597 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,8 @@ All notable changes to `src-cli` are documented in this file. ### Added +- Batch Changes: Watchdog that checks for docker responsiveness while running commands has been added. [#898](https://github.com/sourcegraph/src-cli/pull/898) + ### Changed ### Fixed diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index 8a07076421..27b4ada60f 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -32,10 +32,14 @@ import ( "github.com/sourcegraph/src-cli/internal/batches/repozip" "github.com/sourcegraph/src-cli/internal/batches/service" "github.com/sourcegraph/src-cli/internal/batches/ui" + "github.com/sourcegraph/src-cli/internal/batches/watchdog" "github.com/sourcegraph/src-cli/internal/batches/workspace" "github.com/sourcegraph/src-cli/internal/cmderrors" ) +// We check for docker responsiveness every minute +const dockerWatchDuration = 1 * time.Minute + // batchExecutionFlags are common to batch changes that are executed both // locally and remotely. type batchExecutionFlags struct { @@ -251,6 +255,15 @@ type executeBatchSpecOpts struct { client api.Client } +func createDockerWatchdog(ctx context.Context, execUI ui.ExecUI) *watchdog.WatchDog { + return watchdog.New(dockerWatchDuration, func() { + _, err := docker.NCPU(ctx) + if err != nil { + execUI.DockerWatchDogWarning(errors.Wrap(err, "docker watchdog")) + } + }) +} + // executeBatchSpec performs all the steps required to upload the batch spec to // Sourcegraph, including execution as needed and applying the resulting batch // spec if specified. @@ -263,7 +276,11 @@ func executeBatchSpec(ctx context.Context, opts executeBatchSpecOpts) (err error execUI = &ui.TUI{Out: out} } + w := createDockerWatchdog(ctx, execUI) + go w.Start() + defer func() { + w.Stop() if err != nil { execUI.ExecutionError(err) } diff --git a/go.mod b/go.mod index ca114bf010..5f637a7613 100644 --- a/go.mod +++ b/go.mod @@ -22,7 +22,7 @@ require ( github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf github.com/sourcegraph/scip v0.2.3 - github.com/sourcegraph/sourcegraph/lib v0.0.0-20221129022201-2804729b069c + github.com/sourcegraph/sourcegraph/lib v0.0.0-20221207201520-eeeaf1f74c51 github.com/stretchr/testify v1.8.0 golang.org/x/net v0.2.0 golang.org/x/sync v0.1.0 diff --git a/go.sum b/go.sum index 7d93f5e83c..9168bd65f1 100644 --- a/go.sum +++ b/go.sum @@ -378,8 +378,8 @@ github.com/sourcegraph/log v0.0.0-20220901143117-fc0516a694c9 h1:JjFyvx9hCD5+Jpu github.com/sourcegraph/log v0.0.0-20220901143117-fc0516a694c9/go.mod h1:UxiwB6C3xk3xOySJpW1R0MDUyfGuJRFS5Z8C+SA5p2I= github.com/sourcegraph/scip v0.2.3 h1:6nRsTlNTELn+1V7JxLrDVbBpb9H1gAbUF48N7x5B8Y4= github.com/sourcegraph/scip v0.2.3/go.mod h1:3D/RLCMvrrSam85RtFmC67SE/jhV9++hpCR5MTDzbA0= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20221129022201-2804729b069c h1:bjTcIdEx6FvUXIbD1Ckjp7SfvV4jTyJ7RozZH/HVj9M= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20221129022201-2804729b069c/go.mod h1:PmWmo2ysXWCHcbtp08cDXKGD+8NQzrkj2UjdRBu9H0k= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20221207201520-eeeaf1f74c51 h1:G9XMyQ0SKC53PP9WPSkQqRFvwkZNYRdMHvdm5K3b8Lw= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20221207201520-eeeaf1f74c51/go.mod h1:pLXoYrwkmERkPVv1dpLcq0Epo21Kh4EgrdZXdnafmyQ= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= diff --git a/internal/batches/ui/exec_ui.go b/internal/batches/ui/exec_ui.go index e6e8bdeeec..e9944c17bc 100644 --- a/internal/batches/ui/exec_ui.go +++ b/internal/batches/ui/exec_ui.go @@ -52,4 +52,6 @@ type ExecUI interface { UploadingWorkspaceFiles() UploadingWorkspaceFilesWarning(error) UploadingWorkspaceFilesSuccess() + + DockerWatchDogWarning(error) } diff --git a/internal/batches/ui/json_lines.go b/internal/batches/ui/json_lines.go index dea8e2d0ee..45475b137e 100644 --- a/internal/batches/ui/json_lines.go +++ b/internal/batches/ui/json_lines.go @@ -177,6 +177,14 @@ func (ui *JSONLines) WriteAfterStepResult(key string, value execution.AfterStepR }) } +func (ui *JSONLines) DockerWatchDogWarning(err error) { + message := fmt.Sprintf(`It seems your Docker engine might be frozen. +If there's no progress in the next couple minutes, you may want to try restarting Docker and running the command again. +Error: %s +`, err.Error()) + logOperationFailure(batcheslib.LogEventOperationDockerWatchDog, &batcheslib.DockerWatchDogMetadata{Error: message}) +} + type taskExecutionJSONLines struct { linesTasks map[*executor.Task]batcheslib.JSONLinesTask binaryDiffs bool diff --git a/internal/batches/ui/tui.go b/internal/batches/ui/tui.go index 3d4ad1b21d..ae74c05ca4 100644 --- a/internal/batches/ui/tui.go +++ b/internal/batches/ui/tui.go @@ -221,6 +221,10 @@ func (ui *TUI) CreatingBatchSpecError(err error) error { return prettyPrintBatchUnlicensedError(ui.Out, err) } +func (ui *TUI) DockerWatchDogWarning(err error) { + dockerWatchDogWarning(ui.Out, err) +} + func (ui *TUI) PreviewBatchSpec(batchSpecURL string) { ui.Out.Write("") block := ui.Out.Block(output.Line(batchSuccessEmoji, batchSuccessColor, "To preview or apply the batch spec, go to:")) @@ -449,3 +453,11 @@ func batchCompletePending(p output.Pending, message string) { func batchCompleteWarning(p output.Pending, message string) { p.Complete(output.Line(batchWarningEmoji, batchWarningColor, message)) } + +func dockerWatchDogWarning(out *output.Output, err error) { + block := out.Block(output.Line("🐳", output.StyleWarning, "It seems your Docker engine might be frozen.")) + block.WriteLine(output.Line("", output.StyleWarning, "If there's no progress in the next couple minutes, you may want to try restarting Docker and running the command again.")) + block.WriteLine(output.Linef("", output.StyleWarning, "Error: %s", err.Error())) + block.Write("") + block.Close() +} diff --git a/internal/batches/watchdog/watchdog.go b/internal/batches/watchdog/watchdog.go new file mode 100644 index 0000000000..757f445350 --- /dev/null +++ b/internal/batches/watchdog/watchdog.go @@ -0,0 +1,38 @@ +package watchdog + +import ( + "time" + + "github.com/derision-test/glock" +) + +type WatchDog struct { + ticker glock.Ticker + callback func() + done chan struct{} +} + +func New(interval time.Duration, callback func()) *WatchDog { + ticker := glock.NewRealTicker(interval) + return &WatchDog{ + ticker: ticker, + callback: callback, + done: make(chan struct{}, 1), + } +} + +func (w *WatchDog) Stop() { + close(w.done) +} + +func (w *WatchDog) Start() { + for { + select { + case <-w.ticker.Chan(): + go w.callback() + case <-w.done: + w.ticker.Stop() + return + } + } +} diff --git a/internal/batches/watchdog/watchdog_test.go b/internal/batches/watchdog/watchdog_test.go new file mode 100644 index 0000000000..49b1574e95 --- /dev/null +++ b/internal/batches/watchdog/watchdog_test.go @@ -0,0 +1,40 @@ +package watchdog + +import ( + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/derision-test/glock" +) + +func TestWatchDog(t *testing.T) { + ticker := glock.NewMockTicker(5 * time.Minute) + var count uint32 + expectedCount := 100 + var wg sync.WaitGroup + + mockCallback := func() { + atomic.AddUint32(&count, 1) + wg.Done() + } + + w := &WatchDog{ + ticker: ticker, + callback: mockCallback, + done: make(chan struct{}, 1), + } + + go w.Start() + for i := 0; i < expectedCount; i++ { + wg.Add(1) + ticker.BlockingAdvance(5 * time.Minute) + } + wg.Wait() + w.Stop() + + if count != uint32(expectedCount) { + t.Errorf("expected mock callback to be called %d times, got %d", expectedCount, count) + } +} From a2de95410724e4c00b7299e3556a6c04023e6c85 Mon Sep 17 00:00:00 2001 From: Bolaji Olajide <25608335+BolajiOlajide@users.noreply.github.com> Date: Mon, 12 Dec 2022 17:24:43 +0100 Subject: [PATCH 276/647] update changelog (#899) --- CHANGELOG.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2d95ac8597..7a99d32e31 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,14 +13,18 @@ All notable changes to `src-cli` are documented in this file. ### Added -- Batch Changes: Watchdog that checks for docker responsiveness while running commands has been added. [#898](https://github.com/sourcegraph/src-cli/pull/898) - ### Changed ### Fixed ### Removed +## 4.3.0 + +### Added + +- Batch Changes: Watchdog that checks for docker responsiveness while running commands has been added. [#898](https://github.com/sourcegraph/src-cli/pull/898) + ## 4.2.1 ### Added From 0476543ba6365385ded4fc189b528c51ec8e2503 Mon Sep 17 00:00:00 2001 From: Warren Gifford Date: Thu, 15 Dec 2022 11:11:37 -0800 Subject: [PATCH 277/647] Rename users clean or prune -- use aggregated user statistics (#901) * added new type to process siteUser grahQL type -- still needing to change in utility functions * code compiling but not registering users to remove correctly * correctly structured json response * remove debugging log * rename command src users clean to src users prune * rename null flag * changelog entry * correct json formating * correct command name in users general help * style correct users.go --- CHANGELOG.md | 4 ++ cmd/src/users.go | 10 ++- cmd/src/{users_clean.go => users_prune.go} | 71 ++++++++++++---------- 3 files changed, 52 insertions(+), 33 deletions(-) rename cmd/src/{users_clean.go => users_prune.go} (75%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7a99d32e31..788350d236 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,8 +15,12 @@ All notable changes to `src-cli` are documented in this file. ### Changed +- Renamed `src users clean` command to `src users prune` [#901](https://github.com/sourcegraph/src-cli/pull/901) + ### Fixed +- Fix network timeout in `src users clean` occuring in instances with many users [#901](https://github.com/sourcegraph/src-cli/pull/901) + ### Removed ## 4.3.0 diff --git a/cmd/src/users.go b/cmd/src/users.go index 38d4cfdc00..20c2810120 100644 --- a/cmd/src/users.go +++ b/cmd/src/users.go @@ -20,7 +20,7 @@ The commands are: get gets a user create creates a user account delete deletes a user account - clean deletes inactive users + prune deletes inactive users tag add/remove a tag on a user Use "src users [command] -h" for more information about a command. @@ -90,3 +90,11 @@ type UserUsageStatistics struct { LastActiveTime string LastActiveCodeHostIntegrationTime string } + +type SiteUser struct { + ID string + Username string + Email string + SiteAdmin bool + LastActiveAt string +} diff --git a/cmd/src/users_clean.go b/cmd/src/users_prune.go similarity index 75% rename from cmd/src/users_clean.go rename to cmd/src/users_prune.go index 4651383dc4..54bd05c87e 100644 --- a/cmd/src/users_clean.go +++ b/cmd/src/users_prune.go @@ -19,12 +19,12 @@ This command removes users from a Sourcegraph instance who have been inactive fo Examples: - $ src users clean -days 182 + $ src users prune -days 182 - $ src users clean -remove-admin -remove-never-active + $ src users prune -remove-admin -remove-null-users ` - flagSet := flag.NewFlagSet("clean", flag.ExitOnError) + flagSet := flag.NewFlagSet("prune", flag.ExitOnError) usageFunc := func() { fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src users %s':\n", flagSet.Name()) flagSet.PrintDefaults() @@ -32,8 +32,8 @@ Examples: } var ( daysToDelete = flagSet.Int("days", 60, "Days threshold on which to remove users, must be 60 days or greater and defaults to this value ") - removeAdmin = flagSet.Bool("remove-admin", false, "clean admin accounts") - removeNoLastActive = flagSet.Bool("remove-never-active", false, "removes users with null lastActive value") + removeAdmin = flagSet.Bool("remove-admin", false, "prune admin accounts") + removeNoLastActive = flagSet.Bool("remove-null-users", false, "removes users with no last active value") skipConfirmation = flagSet.Bool("force", false, "skips user confirmation step allowing programmatic use") apiFlags = api.NewFlags(flagSet) ) @@ -51,7 +51,7 @@ Examples: client := cfg.apiClient(apiFlags, flagSet.Output()) currentUserQuery := ` -query { +query getCurrentUser { currentUser { username } @@ -68,29 +68,36 @@ query { return err } - usersQuery := ` -query Users() { - users() { - nodes { - ...UserFields - } - } + getInactiveUsersQuery := ` +query getInactiveUsers { + site { + users { + nodes { + username + email + siteAdmin + lastActiveAt + } + } + } } -` + userFragment +` - // get users to delete var usersResult struct { - Users struct { - Nodes []User + Site struct { + Users struct { + Nodes []SiteUser + } } } - if ok, err := client.NewRequest(usersQuery, nil).Do(ctx, &usersResult); err != nil || !ok { + + if ok, err := client.NewRequest(getInactiveUsersQuery, nil).Do(ctx, &usersResult); err != nil || !ok { return err } usersToDelete := make([]UserToDelete, 0) - for _, user := range usersResult.Users.Nodes { - daysSinceLastUse, wasLastActive, err := computeDaysSinceLastUse(user) + for _, user := range usersResult.Site.Users.Nodes { + daysSinceLastUse, hasLastActive, err := computeDaysSinceLastUse(user) if err != nil { return err } @@ -98,13 +105,13 @@ query Users() { if user.Username == currentUserResult.Data.CurrentUser.Username { continue } - if !wasLastActive && !*removeNoLastActive { + if !hasLastActive && !*removeNoLastActive { continue } if !*removeAdmin && user.SiteAdmin { continue } - if daysSinceLastUse <= *daysToDelete && wasLastActive { + if daysSinceLastUse <= *daysToDelete && hasLastActive { continue } deleteUser := UserToDelete{user, daysSinceLastUse} @@ -146,13 +153,13 @@ query Users() { } // computes days since last usage from current day and time and UsageStatistics.LastActiveTime, uses time.Parse -func computeDaysSinceLastUse(user User) (timeDiff int, wasLastActive bool, _ error) { - // handle for null lastActiveTime returned from - if user.UsageStatistics.LastActiveTime == "" { - wasLastActive = false - return 0, wasLastActive, nil +func computeDaysSinceLastUse(user SiteUser) (timeDiff int, hasLastActive bool, _ error) { + // handle for null LastActiveAt returned from + if user.LastActiveAt == "" { + hasLastActive = false + return 0, hasLastActive, nil } - timeLast, err := time.Parse(time.RFC3339, user.UsageStatistics.LastActiveTime) + timeLast, err := time.Parse(time.RFC3339, user.LastActiveAt) if err != nil { return 0, false, err } @@ -162,7 +169,7 @@ func computeDaysSinceLastUse(user User) (timeDiff int, wasLastActive bool, _ err } // Issue graphQL api request to remove user -func removeUser(user User, client api.Client, ctx context.Context) error { +func removeUser(user SiteUser, client api.Client, ctx context.Context) error { query := `mutation DeleteUser($user: ID!) { deleteUser(user: $user) { alwaysNil @@ -178,7 +185,7 @@ func removeUser(user User, client api.Client, ctx context.Context) error { } type UserToDelete struct { - User User + User SiteUser DaysSinceLastUse int } @@ -189,8 +196,8 @@ func confirmUserRemoval(usersToRemove []UserToDelete) (bool, error) { t.SetOutputMirror(os.Stdout) t.AppendHeader(table.Row{"Username", "Email", "Days Since Last Active"}) for _, user := range usersToRemove { - if len(user.User.Emails) > 0 { - t.AppendRow([]interface{}{user.User.Username, user.User.Emails[0].Email, user.DaysSinceLastUse}) + if user.User.Email != "" { + t.AppendRow([]interface{}{user.User.Username, user.User.Email, user.DaysSinceLastUse}) t.AppendSeparator() } else { t.AppendRow([]interface{}{user.User.Username, "", user.DaysSinceLastUse}) From 0768bfb988729a082bbb9f6f68b2041692cd7a21 Mon Sep 17 00:00:00 2001 From: Warren Gifford Date: Mon, 19 Dec 2022 00:20:29 -0800 Subject: [PATCH 278/647] correct query formatting (#903) --- cmd/src/users_prune.go | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/cmd/src/users_prune.go b/cmd/src/users_prune.go index 54bd05c87e..7c2d7c3325 100644 --- a/cmd/src/users_prune.go +++ b/cmd/src/users_prune.go @@ -70,16 +70,16 @@ query getCurrentUser { getInactiveUsersQuery := ` query getInactiveUsers { - site { - users { - nodes { - username - email - siteAdmin - lastActiveAt - } - } - } + site { + users { + nodes { + username + email + siteAdmin + lastActiveAt + } + } + } } ` From b5564eaa0a237b282b9d0221cadffa4c6ce156ee Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Mon, 19 Dec 2022 19:45:09 +0100 Subject: [PATCH 279/647] Fixup development docs (#905) That step seems to have gone missing. --- DEVELOPMENT.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index e7f75d1cc3..bd8aa79ae3 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -71,8 +71,9 @@ We adhere to the [general Sourcegraph principles for testing](https://docs.sourc 3. The [releases section of the repo sidebar](https://github.com/sourcegraph/src-cli) shows the correct version. 5. Make the necessary updates to the main Sourcegraph repo: 1. Update the `MinimumVersion` constant in the [src-cli package](https://github.com/sourcegraph/sourcegraph/tree/main/internal/src-cli/consts.go). - 2. Commit the changes, and open a PR. - 6. Once the version bump PR is merged and the commit is live on dotcom, check that the [curl commands in the README](README.markdown#installation) also fetch the new latest version. + 2. Update the reference documentation by running `go generate ./doc/cli/references`. + 3. Commit the changes, and open a PR. + 6. Once the version bump PR is merged and the commit is live on dotcom, check that the [curl commands in the README](README.md#installation) also fetch the new latest version. ### Patch releases From eb68e5f51203d57b1de5d888e2d5909928ac3aa5 Mon Sep 17 00:00:00 2001 From: Jean-Hadrien Chabran Date: Wed, 4 Jan 2023 18:36:59 +0100 Subject: [PATCH 280/647] Return an error when additional headers conflicts (#910) --- cmd/src/main.go | 10 ++++++++-- cmd/src/main_test.go | 7 +++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/cmd/src/main.go b/cmd/src/main.go index 8fc7f1fcec..9e63c49762 100644 --- a/cmd/src/main.go +++ b/cmd/src/main.go @@ -58,6 +58,9 @@ var ( // The following arguments are deprecated which is why they are no longer documented configPath = flag.String("config", "", "") endpoint = flag.String("endpoint", "", "") + + errConfigMerge = errors.New("when using a configuration file, zero or all environment variables must be set") + errConfigAuthorizationConflict = errors.New("when passing an 'Authorization' additional headers, SRC_ACCESS_TOKEN must never be set") ) // commands contains all registered subcommands. @@ -154,6 +157,11 @@ func readConfig() (*config, error) { } cfg.AdditionalHeaders = parseAdditionalHeaders() + // Ensure that we're not clashing additonal headers + _, hasAuthorizationAdditonalHeader := cfg.AdditionalHeaders["authorization"] + if cfg.AccessToken != "" && hasAuthorizationAdditonalHeader { + return nil, errConfigAuthorizationConflict + } // Lastly, apply endpoint flag if set if endpoint != nil && *endpoint != "" { @@ -168,5 +176,3 @@ func readConfig() (*config, error) { func cleanEndpoint(urlStr string) string { return strings.TrimSuffix(urlStr, "/") } - -var errConfigMerge = errors.New("when using a configuration file, zero or all environment variables must be set") diff --git a/cmd/src/main_test.go b/cmd/src/main_test.go index 3fe93eb2a5..6b25654e7f 100644 --- a/cmd/src/main_test.go +++ b/cmd/src/main_test.go @@ -151,6 +151,13 @@ func TestReadConfig(t *testing.T) { AdditionalHeaders: map[string]string{"foo-bar": "bar-baz", "foo": "bar"}, }, }, + { + name: "additional headers SRC_HEADERS_AUTHORIZATION and SRC_ACCESS_TOKEN", + envToken: "abc", + envEndpoint: "https://override.com", + envHeaders: "Authorization:Bearer", + wantErr: errConfigAuthorizationConflict.Error(), + }, } for _, test := range tests { From ed6a481d064d022464d9b8bdf7192722eb0ea536 Mon Sep 17 00:00:00 2001 From: Kelli Rockwell Date: Sat, 7 Jan 2023 18:27:04 -0800 Subject: [PATCH 281/647] batches: update limit in unlicensed alert (#900) --- internal/batches/ui/tui.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/batches/ui/tui.go b/internal/batches/ui/tui.go index ae74c05ca4..af49e98bde 100644 --- a/internal/batches/ui/tui.go +++ b/internal/batches/ui/tui.go @@ -328,7 +328,7 @@ func prettyPrintBatchUnlicensedError(out *output.Output, err error) error { // characters: having automatic wrapping some day would be nice, // but this should be sufficient for now. block := out.Block(output.Line("🪙", output.StyleWarning, "Batch Changes is a paid feature of Sourcegraph. All users can create sample")) - block.WriteLine(output.Linef("", output.StyleWarning, "batch changes with up to 5 changesets without a license. Contact Sourcegraph")) + block.WriteLine(output.Linef("", output.StyleWarning, "batch changes with up to 10 changesets without a license. Contact Sourcegraph")) block.WriteLine(output.Linef("", output.StyleWarning, "sales at %shttps://about.sourcegraph.com/contact/sales/%s to obtain a trial", output.StyleSearchLink, output.StyleWarning)) block.WriteLine(output.Linef("", output.StyleWarning, "license.")) block.Write("") From f1ef4c88e4a3ee7a351121ca964c0ff98ccc3496 Mon Sep 17 00:00:00 2001 From: Manuel Ucles <78464298+mucles@users.noreply.github.com> Date: Mon, 9 Jan 2023 13:53:49 -0700 Subject: [PATCH 282/647] Validate: add ability to check if code insights works on an instance (#912) * wip: add a validation check for being able to create insights * validate: adjust required yaml inputs for creating an Insight * validate: fixed missing common in json * Update CHANGELOG.md Co-authored-by: Bolaji Olajide <25608335+BolajiOlajide@users.noreply.github.com> Co-authored-by: Bolaji Olajide <25608335+BolajiOlajide@users.noreply.github.com> --- CHANGELOG.md | 2 +- cmd/src/validate.go | 84 ++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 84 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 788350d236..cc013abf22 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,7 @@ All notable changes to `src-cli` are documented in this file. ## Unreleased - +* `src validate` has an added check to determine if an instance is able to create a basic code insight. ### Added ### Changed diff --git a/cmd/src/validate.go b/cmd/src/validate.go index 2720518d81..2b5ee3bc9e 100644 --- a/cmd/src/validate.go +++ b/cmd/src/validate.go @@ -42,6 +42,10 @@ type validationSpec struct { Config map[string]interface{} `yaml:"config"` DeleteWhenDone bool `yaml:"deleteWhenDone"` } `yaml:"externalService"` + CreateInsight struct { + Title string `yaml:"title"` + DataSeries []map[string]interface{} `yaml:"dataSeries"` + } `yaml:"createInsight"` } type validator struct { @@ -68,7 +72,28 @@ const defaultVspec = `{ "maxTries": 5, "sleepBetweenTriesSeconds": 5 }, - "searchQuery": ["repo:^github.com/gorilla/mux$ Router", "repo:^github.com/gorilla/mux$@v1.8.0 Router"] + "searchQuery": ["repo:^github.com/gorilla/mux$ Router", "repo:^github.com/gorilla/mux$@v1.8.0 Router"], + "createInsight": { + "title": "test insight", + "dataSeries": [ + { + "query": "lang:javascript", + "label": "javascript", + "repositoryScope": [], + "lineColor": "#6495ED", + "timeScopeUnit": "MONTH", + "timeScopeValue": 1 + }, + { + "query": "lang:typescript", + "label": "typescript", + "lineColor": "#DE3163", + "repositoryScope": [], + "timeScopeUnit": "MONTH", + "timeScopeValue": 1 + } + ] + } }` func init() { @@ -275,6 +300,15 @@ func (vd *validator) validate(script []byte, scriptContext map[string]string, is } } + if vspec.CreateInsight.Title != "" { + id, err := vd.createInsight(vspec.CreateInsight.Title, vspec.CreateInsight.DataSeries) + if err != nil { + return err + } + + fmt.Printf("insight %s(%s) is being added \n", vspec.CreateInsight.Title, id) + } + return nil } @@ -406,6 +440,54 @@ func (vd *validator) waitRepoCloned(repoName string, sleepSeconds int, maxTries return false, nil } +const vdAddCodeInsight = ` +mutation CreateLineChartSearchInsight($input: LineChartSearchInsightInput!) { + createLineChartSearchInsight(input: $input) { + view { + id + } + } +}` + +func (vd *validator) createInsight(title string, dataseries []map[string]interface{}) (string, error) { + var resp struct { + CreateLineChartSearchInsight struct { + View struct { + ID string `json:"id"` + } `json:"view"` + } `json:"createLineChartSearchInsight"` + } + var ds []map[string]interface{} + for _, d := range dataseries { + var series = map[string]interface{}{ + "query": d["query"], + "options": map[string]interface{}{ + "label": d["label"], + "lineColor": d["lineColor"], + }, + "repositoryScope": map[string]interface{}{ + "repositories": d["repositoryScope"], + }, + "timeScope": map[string]interface{}{ + "stepInterval": map[string]interface{}{ + "unit": d["timeScopeUnit"], + "value": d["timeScopeValue"], + }, + }, + } + ds = append(ds, series) + } + err := vd.graphQL(vdAddCodeInsight, + map[string]interface{}{"input": map[string]interface{}{ + "options": map[string]interface{}{"title": title}, + "dataSeries": ds}}, &resp) + if err != nil { + return "", err + } + + return resp.CreateLineChartSearchInsight.View.ID, nil +} + const vdUserQuery = ` query User($username: String) { user(username: $username) { From 4ef7cbae45c89977409642dea950096cade6a0d7 Mon Sep 17 00:00:00 2001 From: Noah S-C Date: Tue, 10 Jan 2023 15:03:33 +0000 Subject: [PATCH 283/647] codeintel: print every error encountered while retrying code-intel upload instead of only final one (#915) --- CHANGELOG.md | 5 ++++- go.mod | 2 +- go.sum | 4 ++-- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cc013abf22..4192528fbe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,12 +10,15 @@ All notable changes to `src-cli` are documented in this file. ## Unreleased -* `src validate` has an added check to determine if an instance is able to create a basic code insight. + ### Added +- `src validate` has an added check to determine if an instance is able to create a basic code insight. [#912](https://github.com/sourcegraph/src-cli/pull/912) + ### Changed - Renamed `src users clean` command to `src users prune` [#901](https://github.com/sourcegraph/src-cli/pull/901) +- Failed code-intel uploads now print every error encountered while retrying instead of only the error encountered in the final retry attempt. [#46281](https://github.com/sourcegraph/sourcegraph/pull/46281) ### Fixed diff --git a/go.mod b/go.mod index 5f637a7613..73b1835a2c 100644 --- a/go.mod +++ b/go.mod @@ -22,7 +22,7 @@ require ( github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf github.com/sourcegraph/scip v0.2.3 - github.com/sourcegraph/sourcegraph/lib v0.0.0-20221207201520-eeeaf1f74c51 + github.com/sourcegraph/sourcegraph/lib v0.0.0-20230110145349-bfa074f6c6d7 github.com/stretchr/testify v1.8.0 golang.org/x/net v0.2.0 golang.org/x/sync v0.1.0 diff --git a/go.sum b/go.sum index 9168bd65f1..167679f29f 100644 --- a/go.sum +++ b/go.sum @@ -378,8 +378,8 @@ github.com/sourcegraph/log v0.0.0-20220901143117-fc0516a694c9 h1:JjFyvx9hCD5+Jpu github.com/sourcegraph/log v0.0.0-20220901143117-fc0516a694c9/go.mod h1:UxiwB6C3xk3xOySJpW1R0MDUyfGuJRFS5Z8C+SA5p2I= github.com/sourcegraph/scip v0.2.3 h1:6nRsTlNTELn+1V7JxLrDVbBpb9H1gAbUF48N7x5B8Y4= github.com/sourcegraph/scip v0.2.3/go.mod h1:3D/RLCMvrrSam85RtFmC67SE/jhV9++hpCR5MTDzbA0= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20221207201520-eeeaf1f74c51 h1:G9XMyQ0SKC53PP9WPSkQqRFvwkZNYRdMHvdm5K3b8Lw= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20221207201520-eeeaf1f74c51/go.mod h1:pLXoYrwkmERkPVv1dpLcq0Epo21Kh4EgrdZXdnafmyQ= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20230110145349-bfa074f6c6d7 h1:fsQV2h0koB8rW96SbLnyvWwl1eWU+Dv4E0Eypml1X2I= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20230110145349-bfa074f6c6d7/go.mod h1:HCz/QYbQD5wiwRFYn5ochsMbw6ZNnSgZckE+EYLSBqw= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= From 6d72b3ff827651f3d8d8eab06b6cf83bc00f1c99 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Thu, 12 Jan 2023 15:40:38 +0100 Subject: [PATCH 284/647] Fix src batch repo file parameter parsing (#919) --- CHANGELOG.md | 1 + cmd/src/batch_repositories.go | 10 +++++----- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4192528fbe..5811752909 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,7 @@ All notable changes to `src-cli` are documented in this file. ### Fixed - Fix network timeout in `src users clean` occuring in instances with many users [#901](https://github.com/sourcegraph/src-cli/pull/901) +- Aligned parsing of spec file parameter of `src batch repos` with other commands. [#919](https://github.com/sourcegraph/src-cli/pull/919) ### Removed diff --git a/cmd/src/batch_repositories.go b/cmd/src/batch_repositories.go index 99c64a8688..f4b3280823 100644 --- a/cmd/src/batch_repositories.go +++ b/cmd/src/batch_repositories.go @@ -57,6 +57,11 @@ Examples: return err } + file, err := getBatchSpecFile(flagSet, fileFlag) + if err != nil { + return err + } + ctx := context.Background() client := cfg.apiClient(apiFlags, flagSet.Output()) @@ -73,11 +78,6 @@ Examples: return err } - var file string - if fileFlag != nil { - file = *fileFlag - } - out := output.NewOutput(flagSet.Output(), output.OutputOpts{Verbose: *verbose}) spec, _, _, err := parseBatchSpec(ctx, file, svc) if err != nil { From 90bd461c9fcf8f9233bc5d0973cb8f48c2dfa44c Mon Sep 17 00:00:00 2001 From: Robert Lin Date: Thu, 12 Jan 2023 08:04:27 -0800 Subject: [PATCH 285/647] instancehealth: remove monitoring check (#920) Removes usage of the endpoint deprecated in https://github.com/sourcegraph/sourcegraph/pull/46299, related to https://github.com/sourcegraph/customer/issues/1525 --- internal/instancehealth/checks.go | 33 ------------------------------- 1 file changed, 33 deletions(-) diff --git a/internal/instancehealth/checks.go b/internal/instancehealth/checks.go index 0c2e2557ce..f78dd57b0e 100644 --- a/internal/instancehealth/checks.go +++ b/internal/instancehealth/checks.go @@ -2,7 +2,6 @@ package instancehealth import ( "fmt" - "strings" "time" "github.com/sourcegraph/sourcegraph/lib/errors" @@ -31,11 +30,6 @@ func NewChecks( defer b.Close() return checkSiteConfiguration(b, instanceHealth) }, - func(out *output.Output) error { - b := out.Block(output.Styled(output.StyleBold, "Monitoring alerts")) - defer b.Close() - return checkMonitoringAlerts(b, since, instanceHealth) - }, func(out *output.Output) error { b := out.Block(output.Styled(output.StyleBold, "External services")) defer b.Close() @@ -86,33 +80,6 @@ func checkSiteConfiguration( return nil } -// checkMonitoringAlerts indicates if there are any alerts issued by monitoring infra -func checkMonitoringAlerts( - out output.Writer, - since time.Duration, - instanceHealth Indicators, -) error { - var criticalAlerts int - for _, a := range instanceHealth.Site.MonitoringStatistics.Alerts { - if a.Average == 0 || !strings.Contains(strings.ToLower(a.Name), "critical") { - continue - } - // average is ratio of 12h windows that alert was active, so we set the threshold - // if it's possible this alert could have been active in this 'since' window. - if a.Average*0.5 >= since.Hours()/12 { - criticalAlerts += 1 - out.WriteLine(output.Linef(output.EmojiWarning, output.StyleWarning, - "Found recently active alert: %q", a.Name)) - } - } - if criticalAlerts == 0 { - out.WriteLine(output.Emoji(output.EmojiSuccess, "No critical monitoring alerts!")) - } - // never error, just issue printed warning, since critical alerts aren't all _that_ - // reliable today, though they provide a potentially useful signal. - return nil -} - // checkExternalServices checks the health of external service syncing func checkExternalServices( out output.Writer, From c84c80a673ecb41b0831653cd5f347191896c306 Mon Sep 17 00:00:00 2001 From: Bolaji Olajide <25608335+BolajiOlajide@users.noreply.github.com> Date: Fri, 13 Jan 2023 14:12:46 +0100 Subject: [PATCH 286/647] batches: skip empty log output (#923) --- CHANGELOG.md | 1 + internal/batches/ui/interval_writer.go | 16 +++++++++------- internal/batches/ui/interval_writer_test.go | 9 +++++++-- 3 files changed, 17 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5811752909..ab983e8299 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,7 @@ All notable changes to `src-cli` are documented in this file. - Fix network timeout in `src users clean` occuring in instances with many users [#901](https://github.com/sourcegraph/src-cli/pull/901) - Aligned parsing of spec file parameter of `src batch repos` with other commands. [#919](https://github.com/sourcegraph/src-cli/pull/919) +- batches: Remove empty log outputs. [#923](https://github.com/sourcegraph/src-cli/pull/923) ### Removed diff --git a/internal/batches/ui/interval_writer.go b/internal/batches/ui/interval_writer.go index 1cc285446f..75fafbe931 100644 --- a/internal/batches/ui/interval_writer.go +++ b/internal/batches/ui/interval_writer.go @@ -116,15 +116,17 @@ type prefixedWriter struct { prefix string } -func (w *prefixedWriter) Write(p []byte) (int, error) { - var prefixedLines []byte - for _, line := range bytes.Split(p, []byte("\n")) { - prefixedLine := append([]byte(w.prefix), line...) - prefixedLine = append(prefixedLine, []byte("\n")...) +var newLineByteSlice = []byte("\n") - prefixedLines = append(prefixedLines, prefixedLine...) +// Write is only ever called with a single line. That line may or may not end with a newline character. +// It then writes the content as a single line to the inner writer, regardless of if the provided line +// had a newline or not. That is, because our encoding requires exactly one line per formatted line. +func (w *prefixedWriter) Write(p []byte) (int, error) { + prefixedLine := append([]byte(w.prefix), p...) + if !bytes.HasSuffix(prefixedLine, newLineByteSlice) { + prefixedLine = append(prefixedLine, newLineByteSlice...) } - w.writes <- prefixedLines + w.writes <- prefixedLine <-w.writesDone return len(p), nil } diff --git a/internal/batches/ui/interval_writer_test.go b/internal/batches/ui/interval_writer_test.go index 1a56eb4288..043aaf4cc7 100644 --- a/internal/batches/ui/interval_writer_test.go +++ b/internal/batches/ui/interval_writer_test.go @@ -50,6 +50,10 @@ func TestIntervalWriter(t *testing.T) { stderrWriter.Write([]byte("4")) stdoutWriter.Write([]byte("5")) stderrWriter.Write([]byte("5")) + stdoutWriter.Write([]byte(`Hello world: 1 +`)) + stderrWriter.Write([]byte(`Hello world: 1 +`)) select { case <-ch: @@ -65,10 +69,11 @@ func TestIntervalWriter(t *testing.T) { want := "stdout: 2\nstderr: 2\n" + "stdout: 3\nstderr: 3\n" + "stdout: 4\nstderr: 4\n" + - "stdout: 5\nstderr: 5\n" + "stdout: 5\nstderr: 5\n" + + "stdout: Hello world: 1\nstderr: Hello world: 1\n" if d != want { - t.Fatalf("wrong data in sink. want") + t.Fatalf("wrong data in sink. want=%q, have=%q", want, d) } case <-time.After(1 * time.Second): t.Fatalf("ch has NO data") From 0ffe3d36167bbd1d1d3f661d173b48b326265870 Mon Sep 17 00:00:00 2001 From: Jacob Pleiness Date: Fri, 13 Jan 2023 13:18:28 -0500 Subject: [PATCH 287/647] Validate: add ability to expand `src validate` commands for future health check functionality (#921) * Refactor validate functionality into pkg To support expansion of the validate command, the current validate functionality will need to be moved to a new subcommand. * Use existing internal api package for graphql requests * Remove create first admin features * Refactor configuration structs to support multiple code hosts in future * Add cool emoji to output * Add insight test cleanup * Add env vars for Github access token Github access token is needed for new validate command. Add token to config. * Add 'src validate install' command * Move 'src validate' functionality into 'srv validate install' commmand to allow for more validate subcommands. * Change validation API to be more specific * Change SRC_GITHUB_TOKEN to only be read if needed for command * Update CHANGELOG.md * Add warning if SRC_GITHUB_TOKEN isn't set * An auth token is required for code hosts when using `src validate install`, warn user and exit if not set. * Remove unused deps * Separate tasks being performed * Add symbol search to default queries * Change default queries to use sourcegraph/src-cli repo instead of gorilla/mux --- CHANGELOG.md | 6 + cmd/src/validate.go | 774 +---------------------------------- cmd/src/validate_install.go | 120 ++++++ go.mod | 2 +- internal/validate/install.go | 487 ++++++++++++++++++++++ 5 files changed, 631 insertions(+), 758 deletions(-) create mode 100644 cmd/src/validate_install.go create mode 100644 internal/validate/install.go diff --git a/CHANGELOG.md b/CHANGELOG.md index ab983e8299..fa21cee809 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,11 +14,15 @@ All notable changes to `src-cli` are documented in this file. ### Added - `src validate` has an added check to determine if an instance is able to create a basic code insight. [#912](https://github.com/sourcegraph/src-cli/pull/912) +- Add visual feedback to `src validate install` CLI [#921](https://github.com/sourcegraph/src-cli/pull/921) +- Add insight cleanup as per [#912](https://github.com/sourcegraph/src-cli/pull/912#issuecomment-1377084768) ### Changed - Renamed `src users clean` command to `src users prune` [#901](https://github.com/sourcegraph/src-cli/pull/901) - Failed code-intel uploads now print every error encountered while retrying instead of only the error encountered in the final retry attempt. [#46281](https://github.com/sourcegraph/sourcegraph/pull/46281) +- `src validate` has been changed to `srv validate install` subcommand [#921](https://github.com/sourcegraph/src-cli/pull/921) +- Move GitHub token for `srv validate` to ENV var [#921](https://github.com/sourcegraph/src-cli/pull/921) ### Fixed @@ -28,6 +32,8 @@ All notable changes to `src-cli` are documented in this file. ### Removed +- Removed __create first admin__ feature from `src validate` [#921](https://github.com/sourcegraph/src-cli/pull/921) + ## 4.3.0 ### Added diff --git a/cmd/src/validate.go b/cmd/src/validate.go index 2b5ee3bc9e..4e097de5ce 100644 --- a/cmd/src/validate.go +++ b/cmd/src/validate.go @@ -1,783 +1,43 @@ package main import ( - "bytes" - "context" - "encoding/json" "flag" "fmt" - "io" - "net/http" - "os" - "strings" - "text/template" - "time" - - "github.com/sourcegraph/sourcegraph/lib/errors" - - jsoniter "github.com/json-iterator/go" - "github.com/mattn/go-isatty" - "gopkg.in/yaml.v3" - - "github.com/sourcegraph/src-cli/internal/api" - "github.com/sourcegraph/src-cli/internal/cmderrors" ) -type validationSpec struct { - FirstAdmin struct { - Email string `yaml:"email"` - Username string `yaml:"username"` - Password string `yaml:"password"` - CreateAccessToken bool `yaml:"createAccessToken"` - } `yaml:"firstAdmin"` - WaitRepoCloned struct { - Repo string `yaml:"repo"` - MaxTries int `yaml:"maxTries"` - SleepBetweenTriesSeconds int `yaml:"sleepBetweenTriesSeconds"` - } `yaml:"waitRepoCloned"` - SearchQuery []string `yaml:"searchQuery"` - ExternalService struct { - Kind string `yaml:"kind"` - DisplayName string `yaml:"displayName"` - Config map[string]interface{} `yaml:"config"` - DeleteWhenDone bool `yaml:"deleteWhenDone"` - } `yaml:"externalService"` - CreateInsight struct { - Title string `yaml:"title"` - DataSeries []map[string]interface{} `yaml:"dataSeries"` - } `yaml:"createInsight"` -} - -type validator struct { - client *vdClient - apiClient api.Client -} - -const defaultVspec = `{ - "externalService": { - "config": { - "url": "https://github.com", - "token": "{{ .github_token }}", - "orgs": [], - "repos": [ - "gorilla/mux" - ] - }, - "kind": "GITHUB", - "displayName": "footest", - "deleteWhenDone": true - }, - "waitRepoCloned": { - "repo": "github.com/gorilla/mux", - "maxTries": 5, - "sleepBetweenTriesSeconds": 5 - }, - "searchQuery": ["repo:^github.com/gorilla/mux$ Router", "repo:^github.com/gorilla/mux$@v1.8.0 Router"], - "createInsight": { - "title": "test insight", - "dataSeries": [ - { - "query": "lang:javascript", - "label": "javascript", - "repositoryScope": [], - "lineColor": "#6495ED", - "timeScopeUnit": "MONTH", - "timeScopeValue": 1 - }, - { - "query": "lang:typescript", - "label": "typescript", - "lineColor": "#DE3163", - "repositoryScope": [], - "timeScopeUnit": "MONTH", - "timeScopeValue": 1 - } - ] - } -}` +var validateCommands commander func init() { usage := `'src validate' is a tool that validates a Sourcegraph instance. EXPERIMENTAL: 'validate' is an experimental command in the 'src' tool. +Please visit https://docs.sourcegraph.com/admin/validation for documentation of the validate command. + Usage: - src validate [options] src-validate.yml -or - cat src-validate.yml | src validate [options] + src validate command [command options] -if user is authenticated, user can also run default checks +The commands are: - src validate [options] + install validates a Sourcegraph installation -Please visit https://docs.sourcegraph.com/admin/validation for documentation of the validate command. +Use "src validate [command] -h" for more information about a command. ` - flagSet := flag.NewFlagSet("validate", flag.ExitOnError) - usageFunc := func() { - _, _ = fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src validate %s':\n", flagSet.Name()) - flagSet.PrintDefaults() - fmt.Println(usage) - } - - var ( - contextFlag = flagSet.String("context", "", `Comma-separated list of key=value pairs to add to the script execution context`) - secretsFlag = flagSet.String("secrets", "", "Path to a file containing key=value lines. The key value pairs will be added to the script context") - apiFlags = api.NewFlags(flagSet) - ) + flagSet := flag.NewFlagSet("validate", flag.ExitOnError) handler := func(args []string) error { - if err := flagSet.Parse(args); err != nil { - return err - } - - client := cfg.apiClient(apiFlags, flagSet.Output()) - - vd := &validator{ - apiClient: client, - } - - var script []byte - var isYaml bool - var isJSON bool - - var err error - if len(flagSet.Args()) == 1 { - filename := flagSet.Arg(0) - script, err = os.ReadFile(filename) - if err != nil { - return err - } - if strings.HasSuffix(filename, ".yaml") || strings.HasSuffix(filename, ".yml") { - isYaml = true - } - if strings.HasSuffix(filename, ".json") { - isJSON = true - } - } - if !isatty.IsTerminal(os.Stdin.Fd()) { - // stdin is a pipe not a terminal - script, err = io.ReadAll(os.Stdin) - if err != nil { - return err - } - isYaml = true - } - - if !isYaml && !isJSON { - script = []byte(defaultVspec) - - } - - ctxm := vd.parseKVPairs(*contextFlag, ",") - - if *secretsFlag != "" { - sm, err := vd.readSecrets(*secretsFlag) - if err != nil { - return err - } - - for k, v := range sm { - ctxm[k] = v - } - } - - return vd.validate(script, ctxm, isYaml) - + validateCommands.run(flagSet, "src validate", usage, args) + return nil } + // Register the command commands = append(commands, &command{ - flagSet: flagSet, - handler: handler, - usageFunc: usageFunc, - }) -} - -func (vd *validator) parseKVPairs(val string, pairSep string) map[string]string { - scriptContext := make(map[string]string) - - pairs := strings.Split(val, pairSep) - for _, pair := range pairs { - kv := strings.Split(pair, "=") - - if len(kv) == 2 { - scriptContext[strings.TrimSpace(kv[0])] = strings.TrimSpace(kv[1]) - } - } - return scriptContext -} - -func (vd *validator) readSecrets(path string) (map[string]string, error) { - bs, err := os.ReadFile(path) - if err != nil { - return nil, err - } - - return vd.parseKVPairs(string(bs), "\n"), nil -} - -func (vd *validator) validate(script []byte, scriptContext map[string]string, isYaml bool) error { - tpl, err := template.New("validate").Parse(string(script)) - if err != nil { - return err - } - var ts bytes.Buffer - err = tpl.Execute(&ts, scriptContext) - if err != nil { - return err - } - - var vspec validationSpec - - if isYaml { - if err := yaml.Unmarshal(ts.Bytes(), &vspec); err != nil { - return err - } - } else { - if err := json.Unmarshal(ts.Bytes(), &vspec); err != nil { - return err - } - } - - if vspec.FirstAdmin.Username != "" { - err = vd.createFirstAdmin(&vspec) - if err != nil { - return err - } - - if vspec.FirstAdmin.CreateAccessToken { - token, err := vd.createAccessToken(vspec.FirstAdmin.Username) - if err != nil { - return err - } - fmt.Println(token) - } - } - - if vspec.ExternalService.DisplayName != "" { - extSvcID, err := vd.addExternalService(&vspec) - if err != nil { - return err - } - fmt.Printf("External Service %s is being added \n", vspec.ExternalService.DisplayName) - - defer func() { - if extSvcID != "" && vspec.ExternalService.DeleteWhenDone { - _ = vd.deleteExternalService(extSvcID) - fmt.Printf("External Service %s has been removed \n", vspec.ExternalService.DisplayName) - fmt.Println("Validation Completed") - - } - }() - } - - if vspec.WaitRepoCloned.Repo != "" { - fmt.Printf("repo %s clonining has began \n", vspec.WaitRepoCloned.Repo) - - cloned, err := vd.waitRepoCloned(vspec.WaitRepoCloned.Repo, vspec.WaitRepoCloned.SleepBetweenTriesSeconds, - vspec.WaitRepoCloned.MaxTries) - if err != nil { - return err - } - if !cloned { - return fmt.Errorf("repo %s didn't clone \n", vspec.WaitRepoCloned.Repo) - } - - fmt.Printf("repo %s clonining was successful \n", vspec.WaitRepoCloned.Repo) - - } - - if vspec.SearchQuery != nil { - for i := 0; i < len(vspec.SearchQuery); i++ { - matchCount, err := vd.searchMatchCount(vspec.SearchQuery[i]) - if err != nil { - return err - } - if matchCount == 0 { - return fmt.Errorf("search query %s returned no results \n", vspec.SearchQuery[i]) - } - fmt.Printf("search query '%s' was successful \n", vspec.SearchQuery[i]) - } - } - - if vspec.CreateInsight.Title != "" { - id, err := vd.createInsight(vspec.CreateInsight.Title, vspec.CreateInsight.DataSeries) - if err != nil { - return err - } - - fmt.Printf("insight %s(%s) is being added \n", vspec.CreateInsight.Title, id) - } - - return nil -} - -const vdAddExternalServiceQuery = ` -mutation AddExternalService($kind: ExternalServiceKind!, $displayName: String!, $config: String!) { - addExternalService(input:{ - kind:$kind, - displayName:$displayName, - config: $config - }) - { - id - } -}` - -func (vd *validator) addExternalService(vspec *validationSpec) (string, error) { - configJson, err := json.Marshal(vspec.ExternalService.Config) - if err != nil { - return "", err - } - var resp struct { - AddExternalService struct { - ID string `json:"id"` - } `json:"addExternalService"` - } - - err = vd.graphQL(vdAddExternalServiceQuery, map[string]interface{}{ - "kind": vspec.ExternalService.Kind, - "displayName": vspec.ExternalService.DisplayName, - "config": string(configJson), - }, &resp) - - return resp.AddExternalService.ID, err -} - -const vdDeleteExternalServiceQuery = ` -mutation DeleteExternalService($id: ID!) { - deleteExternalService(externalService: $id){ - alwaysNil - } -}` - -func (vd *validator) deleteExternalService(id string) error { - var resp struct{} - - return vd.graphQL(vdDeleteExternalServiceQuery, map[string]interface{}{ - "id": id, - }, &resp) -} - -const vdSearchMatchCountQuery = ` -query ($query: String!) { - search(query: $query, version: V2, patternType:literal) { - results { - matchCount - } - } -}` - -func (vd *validator) searchMatchCount(searchStr string) (int, error) { - var resp struct { - Search struct { - Results struct { - MatchCount int `json:"matchCount"` - } `json:"results"` - } `json:"search"` - } - - err := vd.graphQL(vdSearchMatchCountQuery, map[string]interface{}{ - "query": searchStr, - }, &resp) - - return resp.Search.Results.MatchCount, err -} - -const vdListRepos = ` -query ListRepos($names: [String!]) { - repositories( - names: $names - ) { - nodes { - name - mirrorInfo { - cloned - } - } - } -}` - -func (vd *validator) listClonedRepos(fs []string) ([]string, error) { - var resp struct { - Repositories struct { - Nodes []struct { - Name string `json:"name"` - MirrorInfo struct { - Cloned bool `json:"cloned"` - } `json:"mirrorInfo"` - } `json:"nodes"` - } `json:"repositories"` - } - - err := vd.graphQL(vdListRepos, map[string]interface{}{ - "names": fs, - }, &resp) - - names := make([]string, 0, len(resp.Repositories.Nodes)) - for _, node := range resp.Repositories.Nodes { - if node.MirrorInfo.Cloned { - names = append(names, node.Name) - } - } - - return names, err -} - -func (vd *validator) waitRepoCloned(repoName string, sleepSeconds int, maxTries int) (bool, error) { - nameFilter := []string{repoName} - - for i := 0; i < maxTries; i++ { - names, err := vd.listClonedRepos(nameFilter) - if err != nil { - return false, err - } - if len(names) == 1 { - return true, nil - } - time.Sleep(time.Second * time.Duration(sleepSeconds)) - } - return false, nil -} - -const vdAddCodeInsight = ` -mutation CreateLineChartSearchInsight($input: LineChartSearchInsightInput!) { - createLineChartSearchInsight(input: $input) { - view { - id - } - } -}` - -func (vd *validator) createInsight(title string, dataseries []map[string]interface{}) (string, error) { - var resp struct { - CreateLineChartSearchInsight struct { - View struct { - ID string `json:"id"` - } `json:"view"` - } `json:"createLineChartSearchInsight"` - } - var ds []map[string]interface{} - for _, d := range dataseries { - var series = map[string]interface{}{ - "query": d["query"], - "options": map[string]interface{}{ - "label": d["label"], - "lineColor": d["lineColor"], - }, - "repositoryScope": map[string]interface{}{ - "repositories": d["repositoryScope"], - }, - "timeScope": map[string]interface{}{ - "stepInterval": map[string]interface{}{ - "unit": d["timeScopeUnit"], - "value": d["timeScopeValue"], - }, - }, - } - ds = append(ds, series) - } - err := vd.graphQL(vdAddCodeInsight, - map[string]interface{}{"input": map[string]interface{}{ - "options": map[string]interface{}{"title": title}, - "dataSeries": ds}}, &resp) - if err != nil { - return "", err - } - - return resp.CreateLineChartSearchInsight.View.ID, nil -} - -const vdUserQuery = ` -query User($username: String) { - user(username: $username) { - id - } -}` - -func (vd *validator) userID(username string) (string, error) { - var resp struct { - User struct { - ID string `json:"id"` - } `json:"user"` - } - - err := vd.graphQL(vdUserQuery, map[string]interface{}{ - "username": username, - }, &resp) - - return resp.User.ID, err -} - -const vdCreateAccessTokenMutation = ` -mutation CreateAccessToken($user: ID!, $scopes: [String!]!, $note: String!) { - createAccessToken( - user:$user, - scopes:$scopes, - note: $note - ) - { - token - } -}` - -func (vd *validator) createAccessToken(username string) (string, error) { - userID, err := vd.userID(username) - if err != nil { - return "", err - } - - var resp struct { - CreateAccessToken struct { - Token string `json:"token"` - } `json:"createAccessToken"` - } - - err = vd.graphQL(vdCreateAccessTokenMutation, map[string]interface{}{ - "user": userID, - "scopes": []string{"user:all", "site-admin:sudo"}, - "note": "src_cli_validate", - }, &resp) - - return resp.CreateAccessToken.Token, err -} - -// SiteAdminInit initializes the instance with given admin account. -// It returns an authenticated client as the admin for doing e2e testing. -func (vd *validator) siteAdminInit(baseURL, email, username, password string) (*vdClient, error) { - client := vd.newClient(baseURL) - - var request = struct { - Email string `json:"email"` - Username string `json:"username"` - Password string `json:"password"` - }{ - Email: email, - Username: username, - Password: password, - } - err := client.authenticate("/-/site-init", request) - if err != nil { - return nil, err - } - - return client, nil -} - -// SignIn performs the sign in with given user credentials. -// It returns an authenticated client as the user for doing e2e testing. -func (vd *validator) signIn(baseURL string, email, password string) (*vdClient, error) { - client := vd.newClient(baseURL) - - var request = struct { - Email string `json:"email"` - Password string `json:"password"` - }{ - Email: email, - Password: password, - } - err := client.authenticate("/-/sign-in", request) - if err != nil { - return nil, err - } - - return client, nil -} - -// Client is an authenticated client for a Sourcegraph user for doing e2e testing. -// The user may or may not be a site admin depends on how the client is instantiated. -// It works by simulating how the browser would send HTTP requests to the server. -type vdClient struct { - baseURL string - sessionCookie *http.Cookie - - userID string -} - -// newClient instantiates a new client. -func (vd *validator) newClient(baseURL string) *vdClient { - return &vdClient{ - baseURL: baseURL, - } -} - -// authenticate is used to send a HTTP POST request to an URL that is able to authenticate -// a user with given body (marshalled to JSON), e.g. site admin init, sign in. Once the -// client is authenticated, the session cookie will be stored as a proof of authentication. -func (c *vdClient) authenticate(path string, body interface{}) error { - p, err := jsoniter.Marshal(body) - if err != nil { - return err - } - - req, err := http.NewRequest("POST", c.baseURL+path, bytes.NewReader(p)) - if err != nil { - return err - } - req.Header.Set("Content-Type", "application/json") - - resp, err := http.DefaultClient.Do(req) - if err != nil { - return err - } - defer func() { _ = resp.Body.Close() }() - - if resp.StatusCode != http.StatusOK { - p, err := io.ReadAll(resp.Body) - if err != nil { - return err - } - return errors.New(string(p)) - } - - var sessionCookie *http.Cookie - for _, cookie := range resp.Cookies() { - if cookie.Name == "sgs" { - sessionCookie = cookie - break - } - } - if sessionCookie == nil { - return err - } - c.sessionCookie = sessionCookie - - userID, err := c.currentUserID() - if err != nil { - return err - } - c.userID = userID - return nil -} - -// currentUserID returns the current user's GraphQL node ID. -func (c *vdClient) currentUserID() (string, error) { - query := ` - query { - currentUser { - id - } - } -` - var resp struct { - Data struct { - CurrentUser struct { - ID string `json:"id"` - } `json:"currentUser"` - } `json:"data"` - } - err := c.graphQL("", query, nil, &resp) - if err != nil { - return "", err - } - - return resp.Data.CurrentUser.ID, nil -} - -// graphqlError wraps a raw JSON error returned from a GraphQL endpoint. -type graphqlError struct{ v interface{} } - -func (g *graphqlError) Error() string { - j, _ := json.MarshalIndent(g.v, "", " ") - return string(j) -} - -// jsonCopy is a cheaty method of copying an already-decoded JSON (src) -// response into its destination (dst) that would usually be passed to e.g. -// json.Unmarshal. -// -// We could do this with reflection, obviously, but it would be much more -// complex and JSON re-marshaling should be cheap enough anyway. Can improve in -// the future. -func jsonCopy(dst, src interface{}) error { - data, err := json.Marshal(src) - if err != nil { - return err - } - return json.NewDecoder(bytes.NewReader(data)).Decode(dst) -} - -// GraphQL makes a GraphQL request to the server on behalf of the user authenticated by the client. -// An optional token can be passed to impersonate other users. -func (c *vdClient) graphQL(token, query string, variables map[string]interface{}, target interface{}) error { - body, err := jsoniter.Marshal(map[string]interface{}{ - "query": query, - "variables": variables, + flagSet: flagSet, + aliases: []string{"validate"}, + handler: handler, + usageFunc: func() { + fmt.Println(usage) + }, }) - if err != nil { - return err - } - - req, err := http.NewRequest("POST", fmt.Sprintf("%s/.api/graphql", c.baseURL), bytes.NewReader(body)) - if err != nil { - return err - } - if token != "" { - req.Header.Set("Authorization", fmt.Sprintf("token %s", token)) - } else { - // NOTE: We use this header to protect from CSRF attacks of HTTP API, - // see https://sourcegraph.com/github.com/sourcegraph/sourcegraph/-/blob/cmd/frontend/internal/cli/http.go#L41-42 - req.Header.Set("X-Requested-With", "Sourcegraph") - req.AddCookie(c.sessionCookie) - } - - resp, err := http.DefaultClient.Do(req) - if err != nil { - return err - } - defer func() { _ = resp.Body.Close() }() - - if resp.StatusCode != http.StatusOK { - p, err := io.ReadAll(resp.Body) - if err != nil { - return err - } - return errors.New(string(p)) - } - - // Decode the response. - var result struct { - Data interface{} `json:"data,omitempty"` - Errors interface{} `json:"errors,omitempty"` - } - if err := json.NewDecoder(resp.Body).Decode(&result); err != nil { - return err - } - - if result.Errors != nil { - return cmderrors.ExitCode( - cmderrors.GraphqlErrorsExitCode, - fmt.Errorf("GraphQL errors:\n%s", &graphqlError{result.Errors}), - ) - } - if err := jsonCopy(target, result.Data); err != nil { - return err - } - return nil -} - -func (vd *validator) createFirstAdmin(vspec *validationSpec) error { - client, err := vd.signIn(cfg.Endpoint, vspec.FirstAdmin.Email, vspec.FirstAdmin.Password) - if err != nil { - client, err = vd.siteAdminInit(cfg.Endpoint, vspec.FirstAdmin.Email, vspec.FirstAdmin.Username, - vspec.FirstAdmin.Password) - if err != nil { - return err - } - } - - vd.client = client - return nil -} - -func (vd *validator) graphQL(query string, variables map[string]interface{}, target interface{}) error { - if vd.client != nil { - return vd.client.graphQL("", query, variables, target) - } - - _, err := vd.apiClient.NewRequest(query, variables).Do(context.TODO(), target) - if err != nil { - return err - } - return nil } diff --git a/cmd/src/validate_install.go b/cmd/src/validate_install.go new file mode 100644 index 0000000000..0bab7d354a --- /dev/null +++ b/cmd/src/validate_install.go @@ -0,0 +1,120 @@ +package main + +import ( + "context" + "flag" + "fmt" + "io" + "os" + "strings" + + "github.com/mattn/go-isatty" + "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/validate" + + "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/output" +) + +var ( + validateWarningEmoji = output.EmojiWarning +) + +func init() { + usage := `'src validate install' is a tool that validates a Sourcegraph installation. + +Examples: + + Run default checks: + + $ src validate install + + Provide a YAML configuration file: + + $ src validate install config.yml + + Provide a JSON configuration file: + + $ src validate install config.json + +Environmental variables + + SRC_GITHUB_TOKEN GitHub access token for validation features + +` + + flagSet := flag.NewFlagSet("install", flag.ExitOnError) + usageFunc := func() { + fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src validate %s':\n", flagSet.Name()) + flagSet.PrintDefaults() + fmt.Println(usage) + } + var ( + apiFlags = api.NewFlags(flagSet) + ) + + handler := func(args []string) error { + if err := flagSet.Parse(args); err != nil { + return err + } + + client := cfg.apiClient(apiFlags, flagSet.Output()) + + var validationSpec *validate.ValidationSpec + + if len(flagSet.Args()) == 1 { + fileName := flagSet.Arg(0) + f, err := os.ReadFile(fileName) + if err != nil { + return errors.Wrap(err, "failed to read installation validation config from file") + } + + if strings.HasSuffix(fileName, ".yaml") || strings.HasSuffix(fileName, ".yml") { + validationSpec, err = validate.LoadYamlConfig(f) + if err != nil { + return err + } + } + + if strings.HasSuffix(fileName, ".json") { + validationSpec, err = validate.LoadJsonConfig(f) + if err != nil { + return err + } + } + } + + if !isatty.IsTerminal(os.Stdin.Fd()) { + // stdin is a pipe not a terminal + input, err := io.ReadAll(os.Stdin) + if err != nil { + return errors.Wrap(err, "failed to read installation validation config from pipe") + } + validationSpec, err = validate.LoadYamlConfig(input) + if err != nil { + return err + } + } + + if validationSpec == nil { + validationSpec = validate.DefaultConfig() + } + + envGithubToken := os.Getenv("SRC_GITHUB_TOKEN") + + // will work for now with only GitHub supported but will need to be revisited when other code hosts are supported + if envGithubToken == "" { + return errors.Newf("%s failed to read `SRC_GITHUB_TOKEN` environment variable", validateWarningEmoji) + } + + validationSpec.ExternalService.Config.GitHub.Token = envGithubToken + + return validate.Installation(context.Background(), client, validationSpec) + } + + validateCommands = append(validateCommands, &command{ + flagSet: flagSet, + handler: handler, + usageFunc: usageFunc, + }) +} diff --git a/go.mod b/go.mod index 73b1835a2c..4c19f1ab36 100644 --- a/go.mod +++ b/go.mod @@ -14,7 +14,6 @@ require ( github.com/hexops/autogold v1.3.0 github.com/jedib0t/go-pretty/v6 v6.3.7 github.com/jig/teereadcloser v0.0.0-20181016160506-953720c48e05 - github.com/json-iterator/go v1.1.12 github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 github.com/mattn/go-isatty v0.0.16 github.com/neelance/parallel v0.0.0-20160708114440-4de9ce63d14c @@ -72,6 +71,7 @@ require ( github.com/jdxcode/netrc v0.0.0-20210204082910-926c7f70242a // indirect github.com/jhump/protocompile v0.0.0-20220216033700-d705409f108f // indirect github.com/jhump/protoreflect v1.12.1-0.20220417024638-438db461d753 // indirect + github.com/json-iterator/go v1.1.12 // indirect github.com/klauspost/compress v1.15.1 // indirect github.com/klauspost/pgzip v1.2.5 // indirect github.com/kr/pretty v0.3.0 // indirect diff --git a/internal/validate/install.go b/internal/validate/install.go new file mode 100644 index 0000000000..3f6d538448 --- /dev/null +++ b/internal/validate/install.go @@ -0,0 +1,487 @@ +package validate + +import ( + "context" + "encoding/json" + "log" + "strings" + "time" + + "github.com/sourcegraph/src-cli/internal/api" + "gopkg.in/yaml.v3" + + "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/output" +) + +var ( + validateEmojiFingerPointRight = output.EmojiFingerPointRight + validateFailureEmoji = output.EmojiFailure + validateHourglassEmoji = output.EmojiHourglass + validateSuccessEmoji = output.EmojiSuccess +) + +type ExternalService struct { + // Type of code host, e.g. GITHUB. + Kind string `yaml:"kind"` + + // Display name of external service, e.g. sourcegraph-test. + DisplayName string `yaml:"displayName"` + + // Configuration for code host. + Config Config `yaml:"config"` + + // Maximum retry attempts when cloning test repositories. Defaults to 5 retries. + MaxRetries int `yaml:"maxRetries"` + + // Retry timeout in seconds. Defaults to 5 seconds + RetryTimeoutSeconds int `yaml:"retryTimeoutSeconds"` + + // Delete code host when test is done. Defaults to true. + DeleteWhenDone bool `yaml:"deleteWhenDone"` +} + +// Config for different types of code hosts. +type Config struct { + GitHub GitHub `yaml:"gitHub"` +} + +// GitHub configuration parameters. +type GitHub struct { + // URL used to access your GitHub instance, e.g. https://github.com. + URL string `yaml:"url" json:"url"` + + // Auth token used to authenticate to GitHub instance. This should be provided via env var SRC_GITHUB_TOKEN. + Token string `yaml:"token" json:"token"` + + // List of organizations. + Orgs []string `yaml:"orgs" json:"orgs"` + + // List of repositories to pull. + Repos []string `yaml:"repos" json:"repos"` +} + +type Insight struct { + Title string `yaml:"title"` + DataSeries []map[string]any `yaml:"dataSeries"` +} + +type ValidationSpec struct { + // Search queries used for validation testing, e.g. "repo:^github\\.com/gorilla/mux$ Router". + SearchQuery []string `yaml:"searchQuery"` + + // External Service configuration. + ExternalService ExternalService `yaml:"externalService"` + + // Insight used for validation testing. + Insight Insight `yaml:"insight"` +} + +// DefaultConfig returns a default configuration to be used for testing. +func DefaultConfig() *ValidationSpec { + return &ValidationSpec{ + SearchQuery: []string{ + "repo:^github.com/sourcegraph/src-cli$ config", + "repo:^github.com/sourcegraph/src-cli$@4.0.0 config", + "repo:^github.com/sourcegraph/src-cli$ type:symbol config", + }, + ExternalService: ExternalService{ + Kind: "GITHUB", + DisplayName: "sourcegraph-test", + Config: Config{ + GitHub: GitHub{ + URL: "https://github.com", + Token: "", + Orgs: []string{}, + Repos: []string{"sourcegraph/src-cli"}, + }, + }, + MaxRetries: 5, + RetryTimeoutSeconds: 5, + DeleteWhenDone: true, + }, + Insight: Insight{ + Title: "test insight", + DataSeries: []map[string]any{ + { + "query": "lang:javascript", + "label": "javascript", + "repositoryScope": "", + "lineColor": "#6495ED", + "timeScopeUnit": "MONTH", + "timeScopeValue": 1, + }, + { + "query": "lang:typescript", + "label": "typescript", + "lineColor": "#DE3163", + "repositoryScope": "", + "timeScopeUnit": "MONTH", + "timeScopeValue": 1, + }, + }, + }, + } +} + +type jsonVars map[string]interface{} + +type clientQuery struct { + opName string + query string + variables jsonVars +} + +// LoadYamlConfig will unmarshal a YAML configuration file into a ValidationSpec. +func LoadYamlConfig(userConfig []byte) (*ValidationSpec, error) { + var config ValidationSpec + if err := yaml.Unmarshal(userConfig, &config); err != nil { + return nil, err + } + + return &config, nil +} + +// LoadJsonConfig will unmarshal a JSON configuration file into a ValidationSpec. +func LoadJsonConfig(userConfig []byte) (*ValidationSpec, error) { + var config ValidationSpec + if err := json.Unmarshal(userConfig, &config); err != nil { + return nil, err + } + + return &config, nil +} + +// Installation runs a series of validation checks such as cloning a repository, running search queries, and +// creating insights, based on the configuration provided. +func Installation(ctx context.Context, client api.Client, config *ValidationSpec) error { + log.Printf("%s validating external service", validateEmojiFingerPointRight) + + if config.ExternalService.DisplayName != "" { + srvID, err := addExternalService(ctx, client, config.ExternalService) + if err != nil { + return err + } + + log.Printf("%s external service %s is being added", validateHourglassEmoji, config.ExternalService.DisplayName) + + defer func() { + if srvID != "" && config.ExternalService.DeleteWhenDone { + _ = removeExternalService(ctx, client, srvID) + log.Printf("%s external service %s has been removed", validateSuccessEmoji, config.ExternalService.DisplayName) + } + }() + } + + log.Printf("%s cloning repository", validateHourglassEmoji) + + cloned, err := repoCloneTimeout(ctx, client, config.ExternalService) + if err != nil { + return err //TODO make sure errors are wrapped once + } + if !cloned { + return errors.Newf("%s validate failed, repo did not clone\n", validateFailureEmoji) + } + + log.Printf("%s repositry successfully cloned", validateSuccessEmoji) + + log.Printf("%s validating search queries", validateEmojiFingerPointRight) + + if config.SearchQuery != nil { + for i := 0; i < len(config.SearchQuery); i++ { + matchCount, err := searchMatchCount(ctx, client, config.SearchQuery[i]) + if err != nil { + return err + } + if matchCount == 0 { + return errors.Newf("validate failed, search query %s returned no results", config.SearchQuery[i]) + } + log.Printf("%s search query '%s' was successful", validateSuccessEmoji, config.SearchQuery[i]) + } + } + + log.Printf("%s validating code insight", validateEmojiFingerPointRight) + + if config.Insight.Title != "" { + log.Printf("%s insight %s is being added", validateHourglassEmoji, config.Insight.Title) + + insightId, err := createInsight(ctx, client, config.Insight) + if err != nil { + return err + } + + log.Printf("%s insight successfully added", validateSuccessEmoji) + + defer func() { + if insightId != "" { + _ = removeInsight(ctx, client, insightId) + log.Printf("%s insight %s has been removed", validateSuccessEmoji, config.Insight.Title) + + } + }() + } + + return nil +} + +func addExternalService(ctx context.Context, client api.Client, srv ExternalService) (string, error) { + config, err := json.Marshal(srv.Config.GitHub) + if err != nil { + return "", errors.Wrap(err, "addExternalService failed") + } + + q := clientQuery{ + opName: "AddExternalService", + query: `mutation AddExternalService($kind: ExternalServiceKind!, $displayName: String!, $config: String!) { + addExternalService(input:{ + kind:$kind, + displayName:$displayName, + config: $config + }) + { + id + } + }`, + variables: jsonVars{ + "kind": srv.Kind, + "displayName": srv.DisplayName, + "config": string(config), + }, + } + + var result struct { + AddExternalService struct { + ID string `json:"id"` + } `json:"addExternalService"` + } + + ok, err := client.NewRequest(q.query, q.variables).Do(ctx, &result) + if err != nil { + return "", errors.Wrap(err, "addExternalService failed") + } + if !ok { + return "", errors.New("addExternalService failed, no data to unmarshal") + } + + return result.AddExternalService.ID, nil +} + +func removeExternalService(ctx context.Context, client api.Client, id string) error { + q := clientQuery{ + opName: "DeleteExternalService", + query: `mutation DeleteExternalService($id: ID!) { + deleteExternalService(externalService: $id){ + alwaysNil + } + }`, + variables: jsonVars{ + "id": id, + }, + } + + var result struct{} + + ok, err := client.NewRequest(q.query, q.variables).Do(ctx, &result) + if err != nil { + return errors.Wrap(err, "removeExternalService failed") + } + if !ok { + return errors.New("removeExternalService failed, no data to unmarshal") + } + return nil +} + +func searchMatchCount(ctx context.Context, client api.Client, searchExpr string) (int, error) { + q := clientQuery{ + opName: "SearchMatchCount", + query: `query ($query: String!) { + search(query: $query, version: V2, patternType:literal){ + results { + matchCount + } + } + }`, + variables: jsonVars{ + "query": searchExpr, + }, + } + + var result struct { + Search struct { + Results struct { + MatchCount int `json:"matchCount"` + } `json:"results"` + } `json:"search"` + } + + ok, err := client.NewRequest(q.query, q.variables).Do(ctx, &result) + if err != nil { + return 0, errors.Wrap(err, "searchMatchCount failed") + } + if !ok { + return 0, errors.New("searchMatchCount failed, no data to unmarshal") + } + + return result.Search.Results.MatchCount, nil +} + +func repoCloneTimeout(ctx context.Context, client api.Client, srv ExternalService) (bool, error) { + // construct repo string for query + var name strings.Builder + + name.WriteString("github.com/") + name.WriteString(srv.Config.GitHub.Repos[0]) + + for i := 0; i < srv.MaxRetries; i++ { + repos, err := listClonedRepos(ctx, client, []string{name.String()}) + if err != nil { + return false, err + } + if len(repos) >= 1 { + return true, nil + } + time.Sleep(time.Second * time.Duration(srv.RetryTimeoutSeconds)) + } + return false, nil +} + +func listClonedRepos(ctx context.Context, client api.Client, names []string) ([]string, error) { + q := clientQuery{ + opName: "ListRepos", + query: `query ListRepos($names: [String!]) { + repositories( + names: $names + ) { + nodes { + name + mirrorInfo { + cloned + } + } + } + }`, + variables: jsonVars{ + "names": names, + }, + } + + var result struct { + Repositories struct { + Nodes []struct { + Name string `json:"name"` + MirrorInfo struct { + Cloned bool `json:"cloned"` + } `json:"mirrorInfo"` + } `json:"nodes"` + } `json:"repositories"` + } + + ok, err := client.NewRequest(q.query, q.variables).Do(ctx, &result) + if err != nil { + return nil, errors.Wrap(err, "listClonedRepos failed") + } + if !ok { + return nil, errors.New("listClonedRepos failed, no data to unmarshal") + } + + nodeNames := make([]string, 0, len(result.Repositories.Nodes)) + for _, node := range result.Repositories.Nodes { + if node.MirrorInfo.Cloned { + nodeNames = append(nodeNames, node.Name) + } + } + + return nodeNames, nil +} + +func createInsight(ctx context.Context, client api.Client, insight Insight) (string, error) { + var dataSeries []map[string]interface{} + + for _, ds := range insight.DataSeries { + var series = map[string]interface{}{ + "query": ds["query"], + "options": map[string]interface{}{ + "label": ds["label"], + "lineColor": ds["lineColor"], + }, + "repositoryScope": map[string]interface{}{ + "repositories": ds["repositoryScope"], + }, + "timeScope": map[string]interface{}{ + "stepInterval": map[string]interface{}{ + "unit": ds["timeScopeUnit"], + "value": ds["timeScopeValue"], + }, + }, + } + + dataSeries = append(dataSeries, series) + } + + q := clientQuery{ + opName: "CreateLineChartSearchInsight", + query: `mutation CreateLineChartSearchInsight($input: LineChartSearchInsightInput!) { + createLineChartSearchInsight(input: $input) { + view { + id + } + } + }`, + variables: jsonVars{ + "input": map[string]interface{}{ + "options": map[string]interface{}{"title": insight.Title}, + "dataSeries": dataSeries, + }, + }, + } + + var result struct { + CreateLineChartSearchInsight struct { + View struct { + ID string `json:"id"` + } `json:"view"` + } `json:"createLineChartSearchInsight"` + } + + ok, err := client.NewRequest(q.query, q.variables).Do(ctx, &result) + if err != nil { + return "", errors.Wrap(err, "createInsight failed") + } + if !ok { + return "", errors.New("createInsight failed, no data to unmarshal") + } + + return result.CreateLineChartSearchInsight.View.ID, nil +} + +func removeInsight(ctx context.Context, client api.Client, insightId string) error { + q := clientQuery{ + opName: "DeleteInsightView", + query: `mutation DeleteInsightView ($id: ID!) { + deleteInsightView(id: $id){ + alwaysNil + } + }`, + variables: jsonVars{ + "id": insightId, + }, + } + + var result struct { + Data struct { + DeleteInsightView struct { + AlwaysNil string `json:"alwaysNil"` + } `json:"deleteInsightView"` + } `json:"data"` + } + + ok, err := client.NewRequest(q.query, q.variables).Do(ctx, &result) + if err != nil { + return errors.Wrap(err, "removeInsight failed") + } + if !ok { + return errors.New("removeInsight failed, no data to unmarshal") + } + + return nil +} From 2a630332f1b7e147d400dc83d16f2a1ef283e1ca Mon Sep 17 00:00:00 2001 From: Warren Gifford Date: Sun, 15 Jan 2023 18:25:43 -0800 Subject: [PATCH 288/647] `users prune` - Paginate graphql site users - fix bug for soft deleted users (#909) * fixes bug in which request is made to delete users that have already been deleted but exist in the aggregated_user_stats table * implemented some pagination -- totalCount of nodes is always 0 -- needing to fix that for break condition * fixed totalCount issue -- switched DoRaw methods to Do * remove development print statements; hide users table behind flag; improve comments * gofmt * added a few more comments * style improvements * better graphQL querry formatting for single use queries --- cmd/src/users.go | 1 + cmd/src/users_prune.go | 149 +++++++++++++++++++++++++---------------- 2 files changed, 93 insertions(+), 57 deletions(-) diff --git a/cmd/src/users.go b/cmd/src/users.go index 20c2810120..d02304e005 100644 --- a/cmd/src/users.go +++ b/cmd/src/users.go @@ -97,4 +97,5 @@ type SiteUser struct { Email string SiteAdmin bool LastActiveAt string + DeletedAt string } diff --git a/cmd/src/users_prune.go b/cmd/src/users_prune.go index 7c2d7c3325..e35555feb6 100644 --- a/cmd/src/users_prune.go +++ b/cmd/src/users_prune.go @@ -31,11 +31,12 @@ Examples: fmt.Println(usage) } var ( - daysToDelete = flagSet.Int("days", 60, "Days threshold on which to remove users, must be 60 days or greater and defaults to this value ") - removeAdmin = flagSet.Bool("remove-admin", false, "prune admin accounts") - removeNoLastActive = flagSet.Bool("remove-null-users", false, "removes users with no last active value") - skipConfirmation = flagSet.Bool("force", false, "skips user confirmation step allowing programmatic use") - apiFlags = api.NewFlags(flagSet) + daysToDelete = flagSet.Int("days", 60, "Days threshold on which to remove users, must be 60 days or greater and defaults to this value ") + removeAdmin = flagSet.Bool("remove-admin", false, "prune admin accounts") + removeNoLastActive = flagSet.Bool("remove-null-users", false, "removes users with no last active value") + skipConfirmation = flagSet.Bool("force", false, "skips user confirmation step allowing programmatic use") + displayUsersToDelete = flagSet.Bool("display-users", false, "display table of users to be deleted by prune") + apiFlags = api.NewFlags(flagSet) ) handler := func(args []string) error { @@ -50,73 +51,109 @@ Examples: ctx := context.Background() client := cfg.apiClient(apiFlags, flagSet.Output()) - currentUserQuery := ` -query getCurrentUser { - currentUser { - username - } -} -` + // get current user so as not to delete issuer of the prune request + currentUserQuery := `query getCurrentUser { currentUser { username }}` var currentUserResult struct { - Data struct { - CurrentUser struct { - Username string + CurrentUser struct { + Username string + } + } + if ok, err := cfg.apiClient(apiFlags, flagSet.Output()).NewRequest(currentUserQuery, nil).Do(context.Background(), ¤tUserResult); err != nil || !ok { + return err + } + + // get total users to paginate over + totalUsersQuery := `query getTotalUsers { site { users { totalCount }}}` + var totalUsers struct { + Site struct { + Users struct { + TotalCount float64 } } } - if ok, err := cfg.apiClient(apiFlags, flagSet.Output()).NewRequest(currentUserQuery, nil).DoRaw(context.Background(), ¤tUserResult); err != nil || !ok { + if ok, err := cfg.apiClient(apiFlags, flagSet.Output()).NewRequest(totalUsersQuery, nil).Do(context.Background(), &totalUsers); err != nil || !ok { return err } + // get 100 site users getInactiveUsersQuery := ` -query getInactiveUsers { + query getInactiveUsers($limit: Int $offset: Int) { site { users { - nodes { + nodes (limit: $limit offset: $offset) { + id username email siteAdmin lastActiveAt + deletedAt } } } } ` - var usersResult struct { - Site struct { - Users struct { - Nodes []SiteUser - } + // paginate through users + var aggregatedUsers []SiteUser + // pagination variables, limit set to maximum possible users returned per request + offset := 0 + const limit int = 100 + + // 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{}{ + "offset": offset, + "limit": limit, } - } - if ok, err := client.NewRequest(getInactiveUsersQuery, nil).Do(ctx, &usersResult); err != nil || !ok { - return err + var usersResult struct { + Site struct { + Users struct { + Nodes []SiteUser + } + TotalCount float64 + } + } + if ok, err := client.NewRequest(getInactiveUsersQuery, pagVars).Do(ctx, &usersResult); err != nil || !ok { + return err + } + // increment graphql request offset by the length of the last user set returned + offset = offset + len(usersResult.Site.Users.Nodes) + // append graphql user results to aggregated users to be processed against user removal conditions + aggregatedUsers = append(aggregatedUsers, usersResult.Site.Users.Nodes...) } + // filter users for deletion usersToDelete := make([]UserToDelete, 0) - for _, user := range usersResult.Site.Users.Nodes { + for _, user := range aggregatedUsers { + // never remove user issuing command + if user.Username == currentUserResult.CurrentUser.Username { + continue + } + // filter out soft deleted users returned by site graphql endpoint + if user.DeletedAt != "" { + continue + } + //compute days since last use daysSinceLastUse, hasLastActive, err := computeDaysSinceLastUse(user) if err != nil { return err } - // never remove user issuing command - if user.Username == currentUserResult.Data.CurrentUser.Username { - continue - } + // don't remove users with no last active value unless option flag is set if !hasLastActive && !*removeNoLastActive { continue } + // don't remove admins unless option flag is set if !*removeAdmin && user.SiteAdmin { continue } + // remove users who have been inactive for longer than the threshold set by the -days flag if daysSinceLastUse <= *daysToDelete && hasLastActive { continue } - deleteUser := UserToDelete{user, daysSinceLastUse} - - usersToDelete = append(usersToDelete, deleteUser) + // serialize user to print in table as part of confirmUserRemoval, add to delete slice + userToDelete := UserToDelete{user, daysSinceLastUse} + usersToDelete = append(usersToDelete, userToDelete) } if *skipConfirmation { @@ -129,7 +166,7 @@ query getInactiveUsers { } // confirm and remove users - if confirmed, _ := confirmUserRemoval(usersToDelete); !confirmed { + if confirmed, _ := confirmUserRemoval(usersToDelete, int(totalUsers.Site.Users.TotalCount), *daysToDelete, *displayUsersToDelete); !confirmed { fmt.Println("Aborting removal") return nil } else { @@ -152,9 +189,9 @@ query getInactiveUsers { }) } -// computes days since last usage from current day and time and UsageStatistics.LastActiveTime, uses time.Parse +// computes days since last usage from current day and time and aggregated_user_statistics.lastActiveAt, uses time.Parse func computeDaysSinceLastUse(user SiteUser) (timeDiff int, hasLastActive bool, _ error) { - // handle for null LastActiveAt returned from + // handle for null LastActiveAt, users who have never been active if user.LastActiveAt == "" { hasLastActive = false return 0, hasLastActive, nil @@ -170,11 +207,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 - } -}` + query := `mutation DeleteUser($user: ID!) { deleteUser(user: $user) { alwaysNil }}` vars := map[string]interface{}{ "user": user.ID, } @@ -190,25 +223,27 @@ type UserToDelete struct { } // Verify user wants to remove users with table of users and a command prompt for [y/N] -func confirmUserRemoval(usersToRemove []UserToDelete) (bool, error) { - fmt.Printf("Users to remove from instance at %s\n", cfg.Endpoint) - t := table.NewWriter() - t.SetOutputMirror(os.Stdout) - t.AppendHeader(table.Row{"Username", "Email", "Days Since Last Active"}) - for _, user := range usersToRemove { - if user.User.Email != "" { - t.AppendRow([]interface{}{user.User.Username, user.User.Email, user.DaysSinceLastUse}) - t.AppendSeparator() - } else { - t.AppendRow([]interface{}{user.User.Username, "", user.DaysSinceLastUse}) - t.AppendSeparator() +func confirmUserRemoval(usersToDelete []UserToDelete, totalUsers int, daysThreshold int, displayUsers bool) (bool, error) { + if displayUsers { + fmt.Printf("Users to remove from %s\n", cfg.Endpoint) + t := table.NewWriter() + t.SetOutputMirror(os.Stdout) + 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.AppendSeparator() + } else { + t.AppendRow([]interface{}{user.User.Username, "", user.DaysSinceLastUse}) + t.AppendSeparator() + } } + t.SetStyle(table.StyleRounded) + t.Render() } - t.SetStyle(table.StyleRounded) - t.Render() input := "" for strings.ToLower(input) != "y" && strings.ToLower(input) != "n" { - fmt.Printf("Do you wish to proceed with user removal [y/N]: ") + fmt.Printf("%v users were inactive for more than %v days on %v.\nDo you wish to proceed with user removal [y/N]: ", len(usersToDelete), daysThreshold, cfg.Endpoint) if _, err := fmt.Scanln(&input); err != nil { return false, err } From 1e9a0cf4635451107aa870f396fb4ad68ebc511a Mon Sep 17 00:00:00 2001 From: Bolaji Olajide <25608335+BolajiOlajide@users.noreply.github.com> Date: Tue, 17 Jan 2023 04:31:30 +0100 Subject: [PATCH 289/647] update changelog (#924) --- CHANGELOG.md | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fa21cee809..606ebfc291 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,16 @@ All notable changes to `src-cli` are documented in this file. ### Added +### Changed + +### Fixed + +### Removed + +## 4.4.0 + +### Added + - `src validate` has an added check to determine if an instance is able to create a basic code insight. [#912](https://github.com/sourcegraph/src-cli/pull/912) - Add visual feedback to `src validate install` CLI [#921](https://github.com/sourcegraph/src-cli/pull/921) - Add insight cleanup as per [#912](https://github.com/sourcegraph/src-cli/pull/912#issuecomment-1377084768) @@ -28,7 +38,7 @@ All notable changes to `src-cli` are documented in this file. - Fix network timeout in `src users clean` occuring in instances with many users [#901](https://github.com/sourcegraph/src-cli/pull/901) - Aligned parsing of spec file parameter of `src batch repos` with other commands. [#919](https://github.com/sourcegraph/src-cli/pull/919) -- batches: Remove empty log outputs. [#923](https://github.com/sourcegraph/src-cli/pull/923) +- Remove empty log outputs during batch spec execution. [#923](https://github.com/sourcegraph/src-cli/pull/923) ### Removed From 1c70d536b4ab3187b5aed41af8f259f1b8ceba6b Mon Sep 17 00:00:00 2001 From: Cesar Jimenez Date: Tue, 17 Jan 2023 12:54:15 -0700 Subject: [PATCH 290/647] [language-platform] update src-cli to handle scip file upload (#897) --- CHANGELOG.md | 6 +- cmd/src/code_intel_upload.go | 21 +++- cmd/src/code_intel_upload_flags.go | 188 +++++++++++++++++++++++++---- go.mod | 12 +- go.sum | 24 ++-- 5 files changed, 205 insertions(+), 46 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 606ebfc291..b8dd4c5aaa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,8 @@ All notable changes to `src-cli` are documented in this file. ### Added +- `src codeintel upload` will now upload SCIP indexes (over LSIF indexes) when the target instance supports it. [#897](https://github.com/sourcegraph/src-cli/pull/897) + ### Changed ### Fixed @@ -36,7 +38,7 @@ All notable changes to `src-cli` are documented in this file. ### Fixed -- Fix network timeout in `src users clean` occuring in instances with many users [#901](https://github.com/sourcegraph/src-cli/pull/901) +- Fix network timeout in `src users clean` occuring in instances with many users [#901](https://github.com/sourcegraph/src-cli/pull/901) - Aligned parsing of spec file parameter of `src batch repos` with other commands. [#919](https://github.com/sourcegraph/src-cli/pull/919) - Remove empty log outputs during batch spec execution. [#923](https://github.com/sourcegraph/src-cli/pull/923) @@ -135,7 +137,6 @@ No noteworthy changes, mechanical release to match Sourcegraph release. - INTERNAL ONLY: Fixed src batch exec not logging errors. - ## 3.42.2 ### Fixed @@ -179,7 +180,6 @@ No noteworthy changes, mechanical release to match Sourcegraph release. - The preview link shown when running `src batch remote` to create a new batch change no longer 404s. [sourcegraph/src-cli](https://github.com/sourcegraph/src-cli/pull/787) - ## 3.40.11 ### Changed diff --git a/cmd/src/code_intel_upload.go b/cmd/src/code_intel_upload.go index 73548289f4..41520bd47a 100644 --- a/cmd/src/code_intel_upload.go +++ b/cmd/src/code_intel_upload.go @@ -9,6 +9,7 @@ import ( "io" "net/url" "os" + "path/filepath" "strings" "time" @@ -70,7 +71,12 @@ Examples: func handleCodeIntelUpload(args []string) error { ctx := context.Background() - out, err := parseAndValidateCodeIntelUploadFlags(args) + isSCIPAvailable, err := isSCIPAvailable() + if err != nil { + return err + } + + out, err := parseAndValidateCodeIntelUploadFlags(args, isSCIPAvailable) if !codeintelUploadFlags.json { if out != nil { printInferredArguments(out) @@ -88,7 +94,7 @@ func handleCodeIntelUpload(args []string) error { Flags: codeintelUploadFlags.apiFlags, }) - uploadID, err := upload.UploadIndex(ctx, codeintelUploadFlags.file, client, codeintelUploadOptions(out)) + uploadID, err := upload.UploadIndex(ctx, codeintelUploadFlags.file, client, codeintelUploadOptions(out, isSCIPAvailable)) if err != nil { return handleUploadError(out, err) } @@ -132,12 +138,19 @@ func handleCodeIntelUpload(args []string) error { } // codeintelUploadOptions creates a set of upload options given the values in the flags. -func codeintelUploadOptions(out *output.Output) upload.UploadOptions { +func codeintelUploadOptions(out *output.Output, isSCIPAvailable bool) upload.UploadOptions { var associatedIndexID *int if codeintelUploadFlags.associatedIndexID != -1 { associatedIndexID = &codeintelUploadFlags.associatedIndexID } + cfg.AdditionalHeaders["Content-Type"] = "application/x-ndjson+lsif" + path := codeintelUploadFlags.uploadRoute + if isSCIPAvailable && filepath.Ext(codeintelUploadFlags.file) == ".scip" { + cfg.AdditionalHeaders["Content-Type"] = "application/x-protobuf+scip" + path = "/.api/scip/upload" + } + logger := upload.NewRequestLogger( os.Stdout, // Don't need to check upper bounds as we only compare verbosity ranges @@ -162,7 +175,7 @@ func codeintelUploadOptions(out *output.Output) upload.UploadOptions { AdditionalHeaders: cfg.AdditionalHeaders, MaxRetries: 5, RetryInterval: time.Second, - Path: codeintelUploadFlags.uploadRoute, + Path: path, MaxPayloadSizeBytes: codeintelUploadFlags.maxPayloadSizeMb * 1000 * 1000, GitHubToken: codeintelUploadFlags.gitHubToken, GitLabToken: codeintelUploadFlags.gitLabToken, diff --git a/cmd/src/code_intel_upload_flags.go b/cmd/src/code_intel_upload_flags.go index d802835bdb..04de47379e 100644 --- a/cmd/src/code_intel_upload_flags.go +++ b/cmd/src/code_intel_upload_flags.go @@ -1,20 +1,23 @@ package main import ( + "context" "flag" "fmt" + "net/http" "os" "path" "path/filepath" "strings" + "time" + "github.com/sourcegraph/scip/bindings/go/scip" + libscip "github.com/sourcegraph/sourcegraph/lib/codeintel/lsif/scip" + "github.com/sourcegraph/sourcegraph/lib/codeintel/upload" "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/sourcegraph/lib/output" "google.golang.org/protobuf/proto" - "github.com/sourcegraph/scip/bindings/go/scip" - "github.com/sourcegraph/sourcegraph/lib/codeintel/upload" - "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/codeintel" ) @@ -53,10 +56,15 @@ var ( // Used to include the insecure-skip-verify flag in the help output, as we don't use any of the // other api.Client methods, so only the insecureSkipVerify flag is relevant here. dummyflag bool + + // Used to skip the LSIF -> SCIP conversion during the migration. Not expected to be used outside + // of codeintel-qa pipelines and not expected to last much longer than a few releases while we + // deprecate all LSIF code paths. + skipConversionToSCIP bool ) func init() { - codeintelUploadFlagSet.StringVar(&codeintelUploadFlags.file, "file", "./dump.lsif", `The path to the LSIF dump file.`) + codeintelUploadFlagSet.StringVar(&codeintelUploadFlags.file, "file", "", `The path to the LSIF dump file.`) // UploadRecordOptions codeintelUploadFlagSet.StringVar(&codeintelUploadFlags.repo, "repo", "", `The name of the repository (e.g. github.com/gorilla/mux). By default, derived from the origin remote.`) @@ -81,6 +89,9 @@ func init() { codeintelUploadFlagSet.BoolVar(&codeintelUploadFlags.json, "json", false, `Output relevant state in JSON on success.`) codeintelUploadFlagSet.BoolVar(&codeintelUploadFlags.open, "open", false, `Open the LSIF upload page in your browser.`) codeintelUploadFlagSet.BoolVar(&dummyflag, "insecure-skip-verify", false, "Skip validation of TLS certificates against trusted chains") + + // Testing flags + codeintelUploadFlagSet.BoolVar(&skipConversionToSCIP, "skip-scip", false, "Skip converting LSIF index to SCIP if the instance supports it; this option should only used for debugging") } // parseAndValidateCodeIntelUploadFlags calls codeintelUploadFlagset.Parse, then infers values for @@ -89,7 +100,7 @@ func init() { // // On success, the global codeintelUploadFlags object will be populated with valid values. An // error is returned on failure. -func parseAndValidateCodeIntelUploadFlags(args []string) (*output.Output, error) { +func parseAndValidateCodeIntelUploadFlags(args []string, isSCIPAvailable bool) (*output.Output, error) { if err := codeintelUploadFlagSet.Parse(args); err != nil { return nil, err } @@ -112,22 +123,43 @@ func parseAndValidateCodeIntelUploadFlags(args []string) (*output.Output, error) return nil, err } - if err := handleSCIP(out); err != nil { - return nil, err + if !isFlagSet(codeintelUploadFlagSet, "file") { + defaultFile, err := inferDefaultFile() + if err != nil { + return nil, err + } + codeintelUploadFlags.file = defaultFile } - if inferenceErrors := inferMissingCodeIntelUploadFlags(); len(inferenceErrors) > 0 { - return nil, errorWithHint{ - err: inferenceErrors[0].err, hint: strings.Join([]string{ - fmt.Sprintf( - "Unable to determine %s from environment. Check your working directory or supply -%s={value} explicitly", - inferenceErrors[0].argument, - inferenceErrors[0].argument, - ), - }, "\n"), + // Check to see if input file exists + if _, err := os.Stat(codeintelUploadFlags.file); os.IsNotExist(err) { + if !isFlagSet(codeintelUploadFlagSet, "file") { + return nil, formatInferenceError(argumentInferenceError{"file", err}) + } + + return nil, errors.Newf("file %q does not exist", codeintelUploadFlags.file) + } + + if !isSCIPAvailable { + if err := handleSCIP(out); err != nil { + return nil, err + } + } else { + if err := handleLSIF(out); err != nil { + return nil, err } } + // Check for new file existence after transformation + if _, err := os.Stat(codeintelUploadFlags.file); os.IsNotExist(err) { + return nil, errors.Newf("file %q does not exist", codeintelUploadFlags.file) + } + + // Infer the remaining default arguments (may require reading from new file) + if inferenceErrors := inferMissingCodeIntelUploadFlags(); len(inferenceErrors) > 0 { + return nil, formatInferenceError(inferenceErrors[0]) + } + if err := validateCodeIntelUploadFlags(); err != nil { return nil, err } @@ -151,6 +183,22 @@ func codeintelUploadOutput() (out *output.Output) { }) } +func isSCIPAvailable() (bool, error) { + client := cfg.apiClient(codeintelUploadFlags.apiFlags, codeintelUploadFlagSet.Output()) + req, err := client.NewHTTPRequest(context.Background(), "HEAD", "/.api/scip/upload", nil) + if err != nil { + return false, err + } + + resp, err := client.Do(req) + if err != nil { + return false, err + } + defer resp.Body.Close() + + return resp.StatusCode == http.StatusOK, nil +} + type argumentInferenceError struct { argument string err error @@ -174,7 +222,7 @@ func replaceBaseName(oldPath string, newBaseName string) string { func handleSCIP(out *output.Output) error { fileExt := path.Ext(codeintelUploadFlags.file) if len(fileExt) == 0 { - return errors.Newf("missing file extension for %s; expected .scip", codeintelUploadFlags.file) + return errors.Newf("missing file extension for %s; expected .scip or .lsif", codeintelUploadFlags.file) } inputFile := codeintelUploadFlags.file if fileExt == ".scip" || fileExt == ".lsif-typed" { @@ -251,16 +299,114 @@ func convertSCIPToLSIFGraph(out *output.Output, inputFile, outputFile string) er return nil } +func inferDefaultFile() (string, error) { + hasSCIP := true + const scipFilename = "index.scip" + if _, err := os.Stat(scipFilename); err != nil { + if os.IsNotExist(err) { + hasSCIP = false + } else { + return "", err + } + } + + hasLSIF := true + const lsifFilename = "dump.lsif" + if _, err := os.Stat(lsifFilename); err != nil { + if os.IsNotExist(err) { + hasLSIF = false + } else { + return "", err + } + } + + if hasSCIP && hasLSIF { + return "", errors.Newf("both %s and %s exists - cannot determine unambiguous choice", scipFilename, lsifFilename) + } + if !(hasSCIP || hasLSIF) { + return "", formatInferenceError(argumentInferenceError{"file", errors.Newf("neither %s nor %s exists", scipFilename, lsifFilename)}) + } + + if hasSCIP { + return scipFilename, nil + } + + return lsifFilename, nil +} + +func formatInferenceError(inferenceErr argumentInferenceError) error { + return errorWithHint{ + err: inferenceErr.err, hint: strings.Join([]string{ + fmt.Sprintf( + "Unable to determine %s from environment. Check your working directory or supply -%s={value} explicitly", + inferenceErr.argument, + inferenceErr.argument, + ), + }, "\n"), + } +} + +func handleLSIF(out *output.Output) error { + if skipConversionToSCIP { + return nil + } + + fileExt := path.Ext(codeintelUploadFlags.file) + if len(fileExt) == 0 { + return errors.Newf("missing file extension for %s; expected .scip or .lsif", codeintelUploadFlags.file) + } + + if fileExt == ".lsif" || fileExt == ".dump" { + inputFile := codeintelUploadFlags.file + outputFile := replaceExtension(inputFile, ".scip") + codeintelUploadFlags.file = outputFile + return convertLSIFToSCIP(out, inputFile, outputFile) + } + + return nil +} + +// Reads the LSIF encoded input file and writes the corresponding SCIP encoded output file. +func convertLSIFToSCIP(out *output.Output, inputFile, outputFile string) error { + if out != nil { + out.Writef("%s Converting %s into %s", output.EmojiInfo, inputFile, outputFile) + } + + ctx := context.Background() + uploadID := -time.Now().Nanosecond() + root := codeintelUploadFlags.root + + if !isFlagSet(codeintelUploadFlagSet, "root") { + // Best-effort infer the root; we have a strange cyclic init order where we're + // currently trying to determine the filename that determines the root, but we + // need the root when converting from LSIF to SCIP. + root, _ = inferIndexRoot() + } + + rc, err := os.Open(inputFile) + if err != nil { + return err + } + defer rc.Close() + + index, err := libscip.ConvertLSIF(ctx, uploadID, rc, root) + if err != nil { + return err + } + serialized, err := proto.Marshal(index) + if err != nil { + return err + } + + return os.WriteFile(outputFile, serialized, os.ModePerm) +} + // inferMissingCodeIntelUploadFlags updates the flags values which were not explicitly // supplied by the user with default values inferred from the current git state and // filesystem. // // Note: This function must not be called before codeintelUploadFlagset.Parse. func inferMissingCodeIntelUploadFlags() (inferErrors []argumentInferenceError) { - if _, err := os.Stat(codeintelUploadFlags.file); os.IsNotExist(err) { - inferErrors = append(inferErrors, argumentInferenceError{"file", err}) - } - indexerName, indexerVersion, readIndexerNameAndVersionErr := readIndexerNameAndVersion() getIndexerName := func() (string, error) { return indexerName, readIndexerNameAndVersionErr } getIndexerVersion := func() (string, error) { return indexerVersion, readIndexerNameAndVersionErr } diff --git a/go.mod b/go.mod index 4c19f1ab36..7b76510e7c 100644 --- a/go.mod +++ b/go.mod @@ -21,9 +21,9 @@ require ( github.com/sourcegraph/go-diff v0.6.1 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf github.com/sourcegraph/scip v0.2.3 - github.com/sourcegraph/sourcegraph/lib v0.0.0-20230110145349-bfa074f6c6d7 + github.com/sourcegraph/sourcegraph/lib v0.0.0-20230113014457-46187b849239 github.com/stretchr/testify v1.8.0 - golang.org/x/net v0.2.0 + golang.org/x/net v0.5.0 golang.org/x/sync v0.1.0 google.golang.org/api v0.102.0 google.golang.org/protobuf v1.28.1 @@ -114,10 +114,10 @@ require ( golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 // indirect golang.org/x/mod v0.7.0 // indirect golang.org/x/oauth2 v0.0.0-20221014153046-6fdb5e3db783 // indirect - golang.org/x/sys v0.2.0 // indirect - golang.org/x/term v0.2.0 // indirect - golang.org/x/text v0.4.0 // indirect - golang.org/x/tools v0.3.0 // indirect + golang.org/x/sys v0.4.0 // indirect + golang.org/x/term v0.4.0 // indirect + golang.org/x/text v0.6.0 // indirect + golang.org/x/tools v0.5.0 // indirect golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 // indirect google.golang.org/appengine v1.6.7 // indirect google.golang.org/genproto v0.0.0-20221024183307-1bc688fe9f3e // indirect diff --git a/go.sum b/go.sum index 167679f29f..3a302ac8cb 100644 --- a/go.sum +++ b/go.sum @@ -378,8 +378,8 @@ github.com/sourcegraph/log v0.0.0-20220901143117-fc0516a694c9 h1:JjFyvx9hCD5+Jpu github.com/sourcegraph/log v0.0.0-20220901143117-fc0516a694c9/go.mod h1:UxiwB6C3xk3xOySJpW1R0MDUyfGuJRFS5Z8C+SA5p2I= github.com/sourcegraph/scip v0.2.3 h1:6nRsTlNTELn+1V7JxLrDVbBpb9H1gAbUF48N7x5B8Y4= github.com/sourcegraph/scip v0.2.3/go.mod h1:3D/RLCMvrrSam85RtFmC67SE/jhV9++hpCR5MTDzbA0= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20230110145349-bfa074f6c6d7 h1:fsQV2h0koB8rW96SbLnyvWwl1eWU+Dv4E0Eypml1X2I= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20230110145349-bfa074f6c6d7/go.mod h1:HCz/QYbQD5wiwRFYn5ochsMbw6ZNnSgZckE+EYLSBqw= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20230113014457-46187b849239 h1:2yZUA+tBbgRQ6oqjyn0TKHoBMh4UaENMiJIiWmUvKfI= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20230113014457-46187b849239/go.mod h1:HCz/QYbQD5wiwRFYn5ochsMbw6ZNnSgZckE+EYLSBqw= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= @@ -494,8 +494,8 @@ golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96b golang.org/x/net v0.0.0-20210614182718-04defd469f4e/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211008194852-3b03d305991f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/net v0.2.0 h1:sZfSu1wtKLGlWI4ZZayP0ck9Y73K1ynO6gqzTdBVdPU= -golang.org/x/net v0.2.0/go.mod h1:KqCZLdyyvdV855qA2rE3GC2aiw5xGR5TEjj8smXukLY= +golang.org/x/net v0.5.0 h1:GyT4nK/YDHSqa1c4753ouYCDajOYKTja9Xb/OHtgvSw= +golang.org/x/net v0.5.0/go.mod h1:DivGGAXEgPSlEBzxGzZI+ZLohi+xUj054jfeKui00ws= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20221014153046-6fdb5e3db783 h1:nt+Q6cXKz4MosCSpnbMtqiQ8Oz0pxTef2B4Vca2lvfk= golang.org/x/oauth2 v0.0.0-20221014153046-6fdb5e3db783/go.mod h1:h4gKUeWbJ4rQPri7E0u6Gs4e9Ri2zaLxzw5DI5XGrYg= @@ -543,19 +543,19 @@ golang.org/x/sys v0.0.0-20211117180635-dee7805ff2e1/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20211213223007-03aa0b5f6827/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.2.0 h1:ljd4t30dBnAvMZaQCevtY0xLLD0A+bRZXbgLMLU1F/A= -golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.4.0 h1:Zr2JFtRQNX3BCZ8YtxRE9hNJYC8J6I1MVbMg6owUp18= +golang.org/x/sys v0.4.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/term v0.2.0 h1:z85xZCsEl7bi/KwbNADeBYoOP0++7W1ipu+aGnpwzRM= -golang.org/x/term v0.2.0/go.mod h1:TVmDHMZPmdnySmBfhjOoOdhjzdE1h4u1VwSiw2l1Nuc= +golang.org/x/term v0.4.0 h1:O7UWfv5+A2qiuulQk30kVinPoMtoIPeVaKLEgLpVkvg= +golang.org/x/term v0.4.0/go.mod h1:9P2UbLfCdcvo3p/nzKvsmas4TnlujnuoV9hGgYzW1lQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.4.0 h1:BrVqGRd7+k1DiOgtnFvAkoQEWQvBc25ouMJM6429SFg= -golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.6.0 h1:3XmdazWV+ubf7QgHSTWeykHOci5oeekaGJBLkrkaw4k= +golang.org/x/text v0.6.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/time v0.0.0-20201208040808-7e3f01d25324/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -577,8 +577,8 @@ golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.8-0.20211102182255-bb4add04ddef/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= golang.org/x/tools v0.1.8/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= -golang.org/x/tools v0.3.0 h1:SrNbZl6ECOS1qFzgTdQfWXZM9XBkiA6tkFrH9YSTPHM= -golang.org/x/tools v0.3.0/go.mod h1:/rWhSS2+zyEVwoJf8YAX6L2f0ntZ7Kn/mGgAWcipA5k= +golang.org/x/tools v0.5.0 h1:+bSpV5HIeWkuvgaMfI3UmKRThoTA5ODJTUd8T17NO+4= +golang.org/x/tools v0.5.0/go.mod h1:N+Kgy78s5I24c24dU8OfWNEotWjutIs8SnJvn5IDq+k= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= From dd50ea03fd15a16d7c274a1893a5714da94a7d21 Mon Sep 17 00:00:00 2001 From: Jacob Pleiness Date: Mon, 23 Jan 2023 14:08:21 -0500 Subject: [PATCH 291/647] Validate: add support for kubernetes deployment validation with `src validate kube` subcommand (#926) * Refactor out shared vars * Add basic kube validation * Add pod validation * Add skeleton for service and connection validation * Add connection validations * Add go modules files * Fix --kubeconfig flag * Fix line output * Add usage output to cli * Fix path in example * Add quiet flag to suppress output and return exit status only * Fix exit status to be consistent if there are failures * Remove TODOs * Update CHANGELOG.md --- CHANGELOG.md | 2 + cmd/src/validate.go | 1 + cmd/src/validate_install.go | 21 +- cmd/src/validate_kube.go | 90 +++++ go.mod | 24 +- go.sum | 66 +++- internal/validate/README.md | 0 internal/validate/{ => install}/install.go | 42 +-- internal/validate/kube/kube.go | 389 ++++++++++++++++++++ internal/validate/kube/kube_test.go | 395 +++++++++++++++++++++ internal/validate/validate.go | 23 ++ 11 files changed, 1014 insertions(+), 39 deletions(-) create mode 100644 cmd/src/validate_kube.go create mode 100644 internal/validate/README.md rename internal/validate/{ => install}/install.go (88%) create mode 100644 internal/validate/kube/kube.go create mode 100644 internal/validate/kube/kube_test.go create mode 100644 internal/validate/validate.go diff --git a/CHANGELOG.md b/CHANGELOG.md index b8dd4c5aaa..319cbdf502 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,8 @@ All notable changes to `src-cli` are documented in this file. - `src codeintel upload` will now upload SCIP indexes (over LSIF indexes) when the target instance supports it. [#897](https://github.com/sourcegraph/src-cli/pull/897) +- `src validate kube` adds support for validating Sourcegraph deployments on Kubernetes. Validations include Pods, Services, PVCs, and network connectivity. [#926](https://github.com/sourcegraph/src-cli/pull/926) + ### Changed ### Fixed diff --git a/cmd/src/validate.go b/cmd/src/validate.go index 4e097de5ce..ee67f5fa9a 100644 --- a/cmd/src/validate.go +++ b/cmd/src/validate.go @@ -21,6 +21,7 @@ Usage: The commands are: install validates a Sourcegraph installation + kube validates a Sourcegraph deployment on a Kubernetes cluster Use "src validate [command] -h" for more information about a command. ` diff --git a/cmd/src/validate_install.go b/cmd/src/validate_install.go index 0bab7d354a..02a0a26f99 100644 --- a/cmd/src/validate_install.go +++ b/cmd/src/validate_install.go @@ -9,15 +9,12 @@ import ( "strings" "github.com/mattn/go-isatty" + "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/validate" + "github.com/sourcegraph/src-cli/internal/validate/install" "github.com/sourcegraph/sourcegraph/lib/errors" - "github.com/sourcegraph/sourcegraph/lib/output" -) - -var ( - validateWarningEmoji = output.EmojiWarning ) func init() { @@ -60,7 +57,7 @@ Environmental variables client := cfg.apiClient(apiFlags, flagSet.Output()) - var validationSpec *validate.ValidationSpec + var validationSpec *install.ValidationSpec if len(flagSet.Args()) == 1 { fileName := flagSet.Arg(0) @@ -70,14 +67,14 @@ Environmental variables } if strings.HasSuffix(fileName, ".yaml") || strings.HasSuffix(fileName, ".yml") { - validationSpec, err = validate.LoadYamlConfig(f) + validationSpec, err = install.LoadYamlConfig(f) if err != nil { return err } } if strings.HasSuffix(fileName, ".json") { - validationSpec, err = validate.LoadJsonConfig(f) + validationSpec, err = install.LoadJsonConfig(f) if err != nil { return err } @@ -90,26 +87,26 @@ Environmental variables if err != nil { return errors.Wrap(err, "failed to read installation validation config from pipe") } - validationSpec, err = validate.LoadYamlConfig(input) + validationSpec, err = install.LoadYamlConfig(input) if err != nil { return err } } if validationSpec == nil { - validationSpec = validate.DefaultConfig() + validationSpec = install.DefaultConfig() } envGithubToken := os.Getenv("SRC_GITHUB_TOKEN") // will work for now with only GitHub supported but will need to be revisited when other code hosts are supported if envGithubToken == "" { - return errors.Newf("%s failed to read `SRC_GITHUB_TOKEN` environment variable", validateWarningEmoji) + return errors.Newf("%s failed to read `SRC_GITHUB_TOKEN` environment variable", validate.WarningSign) } validationSpec.ExternalService.Config.GitHub.Token = envGithubToken - return validate.Installation(context.Background(), client, validationSpec) + return install.Validate(context.Background(), client, validationSpec) } validateCommands = append(validateCommands, &command{ diff --git a/cmd/src/validate_kube.go b/cmd/src/validate_kube.go new file mode 100644 index 0000000000..2fab5a760a --- /dev/null +++ b/cmd/src/validate_kube.go @@ -0,0 +1,90 @@ +package main + +import ( + "context" + "flag" + "fmt" + "path/filepath" + + "k8s.io/client-go/kubernetes" + "k8s.io/client-go/tools/clientcmd" + "k8s.io/client-go/util/homedir" + + "github.com/sourcegraph/src-cli/internal/validate/kube" + + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +func init() { + usage := `'src validate kube' is a tool that validates a Kubernetes based Sourcegraph deployment + +Examples: + + Run default deployment validation: + $ src validate kube + + Specify Kubernetes namespace: + $ src validate kube --namespace sourcegraph + + Specify the kubeconfig file location: + $ src validate kube --kubeconfig ~/.kube/config + + Suppress output (useful for CI/CD pipelines) + $ src validate kube --quiet +` + + flagSet := flag.NewFlagSet("kube", flag.ExitOnError) + usageFunc := func() { + fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src validate %s':\n", flagSet.Name()) + flagSet.PrintDefaults() + fmt.Println(usage) + } + + var ( + kubeConfig *string + namespace = flagSet.String("namespace", "", "(optional) specify the kubernetes namespace to use") + quiet = flagSet.Bool("quiet", false, "(optional) suppress output and return exit status only") + ) + + if home := homedir.HomeDir(); home != "" { + kubeConfig = flagSet.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file") + } else { + kubeConfig = flagSet.String("kubeconfig", "", "absolute path to the kubeconfig file") + } + + handler := func(args []string) error { + if err := flagSet.Parse(args); err != nil { + return err + } + + // use the current context in kubeConfig + config, err := clientcmd.BuildConfigFromFlags("", *kubeConfig) + if err != nil { + return errors.Wrap(err, "failed to load kubernetes config") + } + + clientSet, err := kubernetes.NewForConfig(config) + if err != nil { + return errors.Wrap(err, "failed to create kubernetes client") + } + + // parse through flag options + var options []kube.Option + + if *namespace != "" { + options = append(options, kube.WithNamespace(*namespace)) + } + + if *quiet { + options = append(options, kube.Quiet()) + } + + return kube.Validate(context.Background(), clientSet, config, options...) + } + + validateCommands = append(validateCommands, &command{ + flagSet: flagSet, + handler: handler, + usageFunc: usageFunc, + }) +} diff --git a/go.mod b/go.mod index 7b76510e7c..e661c3b971 100644 --- a/go.mod +++ b/go.mod @@ -29,6 +29,9 @@ require ( google.golang.org/protobuf v1.28.1 gopkg.in/yaml.v3 v3.0.1 jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7 + k8s.io/api v0.26.1 + k8s.io/apimachinery v0.26.1 + k8s.io/client-go v0.26.1 ) require ( @@ -50,15 +53,22 @@ require ( github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/dlclark/regexp2 v1.4.0 // indirect + github.com/emicklei/go-restful/v3 v3.9.0 // indirect github.com/envoyproxy/protoc-gen-validate v0.3.0-java // indirect github.com/fatih/color v1.13.0 // indirect github.com/getsentry/sentry-go v0.13.0 // indirect github.com/ghodss/yaml v1.0.0 // indirect + github.com/go-logr/logr v1.2.3 // indirect + github.com/go-openapi/jsonpointer v0.19.5 // indirect + github.com/go-openapi/jsonreference v0.20.0 // indirect + github.com/go-openapi/swag v0.19.14 // indirect github.com/gofrs/flock v0.8.1 // indirect github.com/gofrs/uuid v4.2.0+incompatible // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect github.com/golang/protobuf v1.5.2 // indirect + github.com/google/gnostic v0.5.7-v3refs // indirect + github.com/google/gofuzz v1.1.0 // indirect github.com/google/uuid v1.3.0 // indirect github.com/googleapis/enterprise-certificate-proxy v0.2.0 // indirect github.com/googleapis/gax-go/v2 v2.6.0 // indirect @@ -66,25 +76,29 @@ require ( github.com/hexops/gotextdiff v1.0.3 // indirect github.com/hexops/valast v1.4.1 // indirect github.com/huandu/xstrings v1.0.0 // indirect - github.com/imdario/mergo v0.3.4 // indirect + github.com/imdario/mergo v0.3.6 // indirect github.com/inconshreveable/mousetrap v1.0.0 // indirect github.com/jdxcode/netrc v0.0.0-20210204082910-926c7f70242a // indirect github.com/jhump/protocompile v0.0.0-20220216033700-d705409f108f // indirect github.com/jhump/protoreflect v1.12.1-0.20220417024638-438db461d753 // indirect + github.com/josharian/intern v1.0.0 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/klauspost/compress v1.15.1 // indirect github.com/klauspost/pgzip v1.2.5 // indirect github.com/kr/pretty v0.3.0 // indirect github.com/kr/text v0.2.0 // indirect github.com/lucasb-eyer/go-colorful v1.2.0 // indirect + github.com/mailru/easyjson v0.7.6 // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-runewidth v0.0.13 // indirect github.com/microcosm-cc/bluemonday v1.0.17 // indirect + github.com/moby/spdystream v0.2.0 // indirect github.com/moby/term v0.0.0-20210619224110-3f7ff695adc6 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect github.com/muesli/reflow v0.3.0 // indirect github.com/muesli/termenv v0.12.0 // indirect + github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/mwitkow/go-proto-validators v0.0.0-20180403085117-0950a7990007 // indirect github.com/nightlyone/lockfile v1.0.0 // indirect github.com/olekukonko/tablewriter v0.0.5 // indirect @@ -117,13 +131,21 @@ require ( golang.org/x/sys v0.4.0 // indirect golang.org/x/term v0.4.0 // indirect golang.org/x/text v0.6.0 // indirect + golang.org/x/time v0.0.0-20220210224613-90d013bbcef8 // indirect golang.org/x/tools v0.5.0 // indirect golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 // indirect google.golang.org/appengine v1.6.7 // indirect google.golang.org/genproto v0.0.0-20221024183307-1bc688fe9f3e // indirect google.golang.org/grpc v1.50.1 // indirect + gopkg.in/inf.v0 v0.9.1 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect + k8s.io/klog/v2 v2.80.1 // indirect + k8s.io/kube-openapi v0.0.0-20221012153701-172d655c2280 // indirect + k8s.io/utils v0.0.0-20221107191617-1a15be271d1d // indirect mvdan.cc/gofumpt v0.2.1 // indirect + sigs.k8s.io/json v0.0.0-20220713155537-f223a00ba0e2 // indirect + sigs.k8s.io/structured-merge-diff/v4 v4.2.3 // indirect + sigs.k8s.io/yaml v1.3.0 // indirect ) // See: https://github.com/ghodss/yaml/pull/65 diff --git a/go.sum b/go.sum index 3a302ac8cb..65fa4f2f78 100644 --- a/go.sum +++ b/go.sum @@ -30,6 +30,7 @@ github.com/alecthomas/chroma v0.10.0/go.mod h1:jtJATyUxlIORhUOFNA9NZDWGAQ8wpxQQq github.com/aokoli/goutils v1.0.1 h1:7fpzNGoJ3VA8qcrm++XEE1QUe0mIwNeLa02Nwq7RDkg= github.com/aokoli/goutils v1.0.1/go.mod h1:SijmP0QR8LtwsmDs8Yii5Z/S4trXFGFC2oO5g9DP+DQ= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= +github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio= github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk= github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4= github.com/aymerick/raymond v2.0.3-0.20180322193309-b565731e1464+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g= @@ -79,9 +80,13 @@ github.com/dineshappavoo/basex v0.0.0-20170425072625-481a6f6dc663 h1:fctNkSsavbX github.com/dineshappavoo/basex v0.0.0-20170425072625-481a6f6dc663/go.mod h1:Kad2hux31v/IyD4Rf4wAwIyK48995rs3qAl9IUAhc2k= github.com/dlclark/regexp2 v1.4.0 h1:F1rxgk7p4uKjwIQxBs9oAXe5CqrXlCduYEJvrF4u93E= github.com/dlclark/regexp2 v1.4.0/go.mod h1:2pZnwuY/m+8K6iRw6wQdMtk+rH5tNGR1i55kozfMjCc= +github.com/docopt/docopt-go v0.0.0-20180111231733-ee0de3bc6815/go.mod h1:WwZ+bS3ebgob9U8Nd0kOddGdZWjyMGR8Wziv+TBNwSE= github.com/dustin/go-humanize v1.0.0 h1:VSnTsYCnlFHaM2/igO1h6X3HA71jcobQuxemgkq4zYo= github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= github.com/eknkc/amber v0.0.0-20171010120322-cdade1c07385/go.mod h1:0vRUJqYpeSZifjYj7uP3BG/gKcuzL9xWVV/Y+cK33KM= +github.com/elazarl/goproxy v0.0.0-20180725130230-947c36da3153 h1:yUdfgN0XgIJw7foRItutHYUIhlcKzcSf5vDpdhQAKTc= +github.com/emicklei/go-restful/v3 v3.9.0 h1:XwGDlfxEnQZzuopoqxwSEllNcCOM9DhhFyhFIIGKwxE= +github.com/emicklei/go-restful/v3 v3.9.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= @@ -108,7 +113,18 @@ github.com/gin-gonic/gin v1.4.0/go.mod h1:OW2EZn3DO8Ln9oIKOvM++LBO+5UPHJJDH72/q/ github.com/go-check/check v0.0.0-20180628173108-788fd7840127/go.mod h1:9ES+weclKsC9YodN5RgxqK/VD9HM9JsCSh7rNhMZE98= github.com/go-errors/errors v1.0.1 h1:LUHzmkK3GUKUrL/1gfBUxAHzcev3apQlezX/+O7ma6w= github.com/go-errors/errors v1.0.1/go.mod h1:f4zRHt4oKfwPJE5k8C9vpYG+aDHdBFUsgrm6/TyX73Q= +github.com/go-logr/logr v1.2.0/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.2.3 h1:2DntVwHkVopvECVRSlL5PSo9eG+cAkDCuckLubN+rq0= +github.com/go-logr/logr v1.2.3/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-martini/martini v0.0.0-20170121215854-22fa46961aab/go.mod h1:/P9AEU963A2AYjv4d1V5eVL1CQbEJq6aCNHDDjibzu8= +github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= +github.com/go-openapi/jsonpointer v0.19.5 h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUeOFYEICuY= +github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= +github.com/go-openapi/jsonreference v0.20.0 h1:MYlu0sBgChmCfJxxUKZ8g1cPWFOB37YSZqewK7OKeyA= +github.com/go-openapi/jsonreference v0.20.0/go.mod h1:Ag74Ico3lPc+zR+qjn4XBUmXymS4zJbYVCZmcgkasdo= +github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk= +github.com/go-openapi/swag v0.19.14 h1:gm3vOOXfiuw5i9p5N9xJvfjvuofpyvLA9Wr6QfK5Fng= +github.com/go-openapi/swag v0.19.14/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ= github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y= github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8= github.com/gobwas/httphead v0.0.0-20180130184737-2c6c146eadee/go.mod h1:L0fX3K22YWvt/FAX9NnzrNzcI4wNYi9Yku4O0LKYflo= @@ -147,6 +163,8 @@ github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaS github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw= github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/gomodule/redigo v1.7.1-0.20190724094224-574c33c3df38/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4= +github.com/google/gnostic v0.5.7-v3refs h1:FhTMOKj2VhjpouxvWJAV1TL304uMlb9zcDqkl6cEI54= +github.com/google/gnostic v0.5.7-v3refs/go.mod h1:73MKFl6jIHelAJNaBGFzt3SPtZULs9dYrGFt8OiIsHQ= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= @@ -161,6 +179,8 @@ github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/gofuzz v1.1.0 h1:Hsa8mG0dQ46ij8Sl2AYJDUv1oA9/d6Vk+3LG99Oe02g= +github.com/google/gofuzz v1.1.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/martian/v3 v3.2.1 h1:d8MncMlErDFTwQGBK1xhv026j9kqhvw1Qv9IbWT1VLQ= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= @@ -174,6 +194,7 @@ github.com/gorilla/css v1.0.0 h1:BQqNyPTi50JCFMTw/b67hByjMVXZRwGha6wxVGkeihY= github.com/gorilla/css v1.0.0/go.mod h1:Dn721qIggHpt4+EFCcTLTU/vk5ySda2ReITrtgBl60c= github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/grafana/regexp v0.0.0-20220304100321-149c8afcd6cb h1:wwzNkyaQwcXCzQuKoWz3lwngetmcyg+EhW0fF5lz73M= github.com/grafana/regexp v0.0.0-20220304100321-149c8afcd6cb/go.mod h1:M5qHK+eWfAv8VR/265dIuEpL3fNfeC21tXXp9itM24A= github.com/hashicorp/go-version v1.2.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= @@ -191,8 +212,8 @@ github.com/huandu/xstrings v1.0.0 h1:pO2K/gKgKaat5LdpAhxhluX2GPQMaI3W5FUz/I/UnWk github.com/huandu/xstrings v1.0.0/go.mod h1:4qWG/gcEcfX4z/mBDHJ++3ReCw9ibxbsNJbcucJdbSo= github.com/hydrogen18/memlistener v0.0.0-20141126152155-54553eb933fb/go.mod h1:qEIFzExnS6016fRpRfxrExeVn2gbClQA99gQhnIcdhE= github.com/hydrogen18/memlistener v0.0.0-20200120041712-dcc25e7acd91/go.mod h1:qEIFzExnS6016fRpRfxrExeVn2gbClQA99gQhnIcdhE= -github.com/imdario/mergo v0.3.4 h1:mKkfHkZWD8dC7WxKx3N9WCF0Y+dLau45704YQmY6H94= -github.com/imdario/mergo v0.3.4/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= +github.com/imdario/mergo v0.3.6 h1:xTNEAn+kxVO7dTZGu0CegyqKZmoWFI0rF8UxjlB2d28= +github.com/imdario/mergo v0.3.6/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= github.com/imkira/go-interpol v1.1.0/go.mod h1:z0h2/2T3XF8kyEPpRgJ3kmNv+C43p+I/CoI+jC3w2iA= github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= @@ -216,6 +237,8 @@ github.com/jhump/protoreflect v1.12.1-0.20220417024638-438db461d753 h1:uFlcJKZPL github.com/jhump/protoreflect v1.12.1-0.20220417024638-438db461d753/go.mod h1:JytZfP5d0r8pVNLZvai7U/MCuTWITgrI4tTg7puQFKI= github.com/jig/teereadcloser v0.0.0-20181016160506-953720c48e05 h1:dSwwtWuwMyarzsbVWOq4QJ8xVy9wgcNomvWyGtrKe+E= github.com/jig/teereadcloser v0.0.0-20181016160506-953720c48e05/go.mod h1:sRUFlj+HCejvoCRpuhU0EYnNw5FG+YJpz8UFfCf0F2U= +github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= +github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= @@ -248,6 +271,7 @@ github.com/klauspost/cpuid v1.2.1/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgo github.com/klauspost/pgzip v1.2.5 h1:qnWYvvKqedOF2ulHpMG72XQol4ILEJ8k2wwRl/Km8oE= github.com/klauspost/pgzip v1.2.5/go.mod h1:Ch1tH69qFZu15pkjo5kYi6mth2Zzwzt50oCQKQE9RUs= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= @@ -261,6 +285,10 @@ github.com/labstack/gommon v0.3.0/go.mod h1:MULnywXg0yavhxWKc+lOruYdAhDwPK9wf0OL github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= +github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= +github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= +github.com/mailru/easyjson v0.7.6 h1:8yTIVnZgCoiM1TgqoeTl+LfU5Jg6/xL3QhGQnimLYnA= +github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= @@ -290,6 +318,8 @@ github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa1 github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ= +github.com/moby/spdystream v0.2.0 h1:cjW1zVyyoiM0T7b6UoySUFqzXMoqRckQtXwGPiBhOM8= +github.com/moby/spdystream v0.2.0/go.mod h1:f7i0iNDQJ059oMTcWxx8MA/zKFIuD/lY+0GqbN2Wy8c= github.com/moby/term v0.0.0-20210619224110-3f7ff695adc6 h1:dcztxKSvZ4Id8iPpHERQBbIJfabdt4wUm5qy3wOL2Zc= github.com/moby/term v0.0.0-20210619224110-3f7ff695adc6/go.mod h1:E2VnQOmVuvZB6UYnnDB0qG5Nq/1tD9acaOpo6xmt0Kw= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -305,6 +335,8 @@ github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKt github.com/muesli/termenv v0.9.0/go.mod h1:R/LzAKf+suGs4IsO95y7+7DpFHO0KABgnZqtlyx2mBw= github.com/muesli/termenv v0.12.0 h1:KuQRUE3PgxRFWhq4gHvZtPSLCGDqM5q/cYr1pZ39ytc= github.com/muesli/termenv v0.12.0/go.mod h1:WCCv32tusQ/EEZ5S8oUIIrC/nIuBcxCVqlN4Xfkv+7A= +github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= +github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/mwitkow/go-proto-validators v0.0.0-20180403085117-0950a7990007 h1:28i1IjGcx8AofiB4N3q5Yls55VEaitzuEPkFJEVgGkA= github.com/mwitkow/go-proto-validators v0.0.0-20180403085117-0950a7990007/go.mod h1:m2XC9Qq0AlmmVksL6FktJCdTYyLk7V3fKyp0sl1yWQo= github.com/nats-io/jwt v0.3.0/go.mod h1:fRYCDE99xlTsqUzISS1Bi75UBJ6ljOJQOAAu5VglpSg= @@ -325,9 +357,12 @@ github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6 github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.10.3/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= +github.com/onsi/ginkgo v1.13.0 h1:M76yO2HkZASFjXL0HSoZJ1AYEmQxNJmY41Jx1zNUq1Y= github.com/onsi/ginkgo v1.13.0/go.mod h1:+REjRxOmWfHCjfv9TTWB1jD1Frx4XydAD3zm1lskyM0= +github.com/onsi/ginkgo/v2 v2.4.0 h1:+Ig9nvqgS5OBSACXNk15PLdp0U9XPYROt9CFzVdFGIs= github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= +github.com/onsi/gomega v1.23.0 h1:/oxKu9c2HVap+F3PfKort2Hw5DEU+HGlW8n+tguWsys= github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4= github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8= @@ -394,6 +429,7 @@ github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s= github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf h1:pvbZ0lM0XWPBqUKqFU8cmavspvIl9nulOYwdy6IFRRo= github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf/go.mod h1:RJID2RhlZKId02nZ62WenDCkgHFerpIOmW0iT7GKmXM= +github.com/stoewer/go-strcase v1.2.0/go.mod h1:IBiWB2sKIp3wVVQ3Y035++gc+knqhUQag1KpM8ahLw8= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0 h1:M2gUjqZET1qApGOWNSnZ49BAIMX4F/1plDv3+l31EJ4= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= @@ -557,6 +593,8 @@ golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.6.0 h1:3XmdazWV+ubf7QgHSTWeykHOci5oeekaGJBLkrkaw4k= golang.org/x/text v0.6.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/time v0.0.0-20201208040808-7e3f01d25324/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20220210224613-90d013bbcef8 h1:vVKdlvoWBphwdxWKrFZEuM0kGgGLxUOYcY4U/2Vjg44= +golang.org/x/time v0.0.0-20220210224613-90d013bbcef8/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20181221001348-537d06c36207/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -595,6 +633,7 @@ google.golang.org/genproto v0.0.0-20180518175338-11a468237815/go.mod h1:JiN7NxoA google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= +google.golang.org/genproto v0.0.0-20201019141844-1ed22bb0c154/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210624195500-8bfb893ecb84/go.mod h1:SzzZ/N+nwJDaO1kznhnlzqS8ocJICar6hYhVyhi++24= google.golang.org/genproto v0.0.0-20221024183307-1bc688fe9f3e h1:S9GbmC1iCgvbLyAokVCwiO6tVIrU9Y7c5oMx1V/ki/Y= google.golang.org/genproto v0.0.0-20221024183307-1bc688fe9f3e/go.mod h1:9qHF0xnpdSfF6knlcsnpzUu5y+rpwgbvsyGAZPBMg4s= @@ -616,6 +655,7 @@ google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzi google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGjtUeSXeh4= google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= @@ -625,12 +665,15 @@ google.golang.org/protobuf v1.28.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqw gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b h1:QRR6H1YWRnHb4Y/HeNFCTJLFVxaq6wH4YuVdsUOr75U= gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= gopkg.in/go-playground/assert.v1 v1.2.1/go.mod h1:9RXL0bg/zibRAgZUYszZSwO/z8Y/a8bDuhia5mkpMnE= gopkg.in/go-playground/validator.v8 v8.18.2/go.mod h1:RX2a/7Ha8BgOhfk7j780h4/u/RRjR0eouCJSH80/M2Y= +gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc= +gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= gopkg.in/ini.v1 v1.51.1/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/mgo.v2 v2.0.0-20180705113604-9856a29383ce/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= @@ -642,6 +685,7 @@ gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20191120175047-4206685974f2/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= @@ -651,8 +695,26 @@ honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWh honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7 h1:mub0MmFLOn8XLikZOAhgLD1kXJq8jgftSrrv7m00xFo= jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7/go.mod h1:OxvTsCwKosqQ1q7B+8FwXqg4rKZ/UG9dUW+g/VL2xH4= +k8s.io/api v0.26.1 h1:f+SWYiPd/GsiWwVRz+NbFyCgvv75Pk9NK6dlkZgpCRQ= +k8s.io/api v0.26.1/go.mod h1:xd/GBNgR0f707+ATNyPmQ1oyKSgndzXij81FzWGsejg= +k8s.io/apimachinery v0.26.1 h1:8EZ/eGJL+hY/MYCNwhmDzVqq2lPl3N3Bo8rvweJwXUQ= +k8s.io/apimachinery v0.26.1/go.mod h1:tnPmbONNJ7ByJNz9+n9kMjNP8ON+1qoAIIC70lztu74= +k8s.io/client-go v0.26.1 h1:87CXzYJnAMGaa/IDDfRdhTzxk/wzGZ+/HUQpqgVSZXU= +k8s.io/client-go v0.26.1/go.mod h1:IWNSglg+rQ3OcvDkhY6+QLeasV4OYHDjdqeWkDQZwGE= +k8s.io/klog/v2 v2.80.1 h1:atnLQ121W371wYYFawwYx1aEY2eUfs4l3J72wtgAwV4= +k8s.io/klog/v2 v2.80.1/go.mod h1:y1WjHnz7Dj687irZUWR/WLkLc5N1YHtjLdmgWjndZn0= +k8s.io/kube-openapi v0.0.0-20221012153701-172d655c2280 h1:+70TFaan3hfJzs+7VK2o+OGxg8HsuBr/5f6tVAjDu6E= +k8s.io/kube-openapi v0.0.0-20221012153701-172d655c2280/go.mod h1:+Axhij7bCpeqhklhUTe3xmOn6bWxolyZEeyaFpjGtl4= +k8s.io/utils v0.0.0-20221107191617-1a15be271d1d h1:0Smp/HP1OH4Rvhe+4B8nWGERtlqAGSftbSbbmm45oFs= +k8s.io/utils v0.0.0-20221107191617-1a15be271d1d/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= mvdan.cc/gofumpt v0.0.0-20210107193838-d24d34e18d44/go.mod h1:yXG1r1WqZVKWbVRtBWKWX9+CxGYfA51nSomhM0woR48= mvdan.cc/gofumpt v0.1.0/go.mod h1:yXG1r1WqZVKWbVRtBWKWX9+CxGYfA51nSomhM0woR48= mvdan.cc/gofumpt v0.2.0/go.mod h1:TiGmrf914DAuT6+hDIxOqoDb4QXIzAuEUSXqEf9hGKY= mvdan.cc/gofumpt v0.2.1 h1:7jakRGkQcLAJdT+C8Bwc9d0BANkVPSkHZkzNv07pJAs= mvdan.cc/gofumpt v0.2.1/go.mod h1:a/rvZPhsNaedOJBzqRD9omnwVwHZsBdJirXHa9Gh9Ig= +sigs.k8s.io/json v0.0.0-20220713155537-f223a00ba0e2 h1:iXTIw73aPyC+oRdyqqvVJuloN1p0AC/kzH07hu3NE+k= +sigs.k8s.io/json v0.0.0-20220713155537-f223a00ba0e2/go.mod h1:B8JuhiUyNFVKdsE8h686QcCxMaH6HrOAZj4vswFpcB0= +sigs.k8s.io/structured-merge-diff/v4 v4.2.3 h1:PRbqxJClWWYMNV1dhaG4NsibJbArud9kFxnAMREiWFE= +sigs.k8s.io/structured-merge-diff/v4 v4.2.3/go.mod h1:qjx8mGObPmV2aSZepjQjbmb2ihdVs8cGKBraizNC69E= +sigs.k8s.io/yaml v1.3.0 h1:a2VclLzOGrwOHDiV8EfBGhvjHvP46CtW5j6POvhYGGo= +sigs.k8s.io/yaml v1.3.0/go.mod h1:GeOyir5tyXNByN85N/dRIT9es5UQNerPYEKK56eTBm8= diff --git a/internal/validate/README.md b/internal/validate/README.md new file mode 100644 index 0000000000..e69de29bb2 diff --git a/internal/validate/install.go b/internal/validate/install/install.go similarity index 88% rename from internal/validate/install.go rename to internal/validate/install/install.go index 3f6d538448..eb3a6503a2 100644 --- a/internal/validate/install.go +++ b/internal/validate/install/install.go @@ -1,4 +1,4 @@ -package validate +package install import ( "context" @@ -7,18 +7,12 @@ import ( "strings" "time" - "github.com/sourcegraph/src-cli/internal/api" "gopkg.in/yaml.v3" - "github.com/sourcegraph/sourcegraph/lib/errors" - "github.com/sourcegraph/sourcegraph/lib/output" -) + "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/validate" -var ( - validateEmojiFingerPointRight = output.EmojiFingerPointRight - validateFailureEmoji = output.EmojiFailure - validateHourglassEmoji = output.EmojiHourglass - validateSuccessEmoji = output.EmojiSuccess + "github.com/sourcegraph/sourcegraph/lib/errors" ) type ExternalService struct { @@ -152,10 +146,10 @@ func LoadJsonConfig(userConfig []byte) (*ValidationSpec, error) { return &config, nil } -// Installation runs a series of validation checks such as cloning a repository, running search queries, and +// Validate runs a series of validation checks such as cloning a repository, running search queries, and // creating insights, based on the configuration provided. -func Installation(ctx context.Context, client api.Client, config *ValidationSpec) error { - log.Printf("%s validating external service", validateEmojiFingerPointRight) +func Validate(ctx context.Context, client api.Client, config *ValidationSpec) error { + log.Printf("%s validating external service", validate.EmojiFingerPointRight) if config.ExternalService.DisplayName != "" { srvID, err := addExternalService(ctx, client, config.ExternalService) @@ -163,29 +157,29 @@ func Installation(ctx context.Context, client api.Client, config *ValidationSpec return err } - log.Printf("%s external service %s is being added", validateHourglassEmoji, config.ExternalService.DisplayName) + log.Printf("%s external service %s is being added", validate.HourglassEmoji, config.ExternalService.DisplayName) defer func() { if srvID != "" && config.ExternalService.DeleteWhenDone { _ = removeExternalService(ctx, client, srvID) - log.Printf("%s external service %s has been removed", validateSuccessEmoji, config.ExternalService.DisplayName) + log.Printf("%s external service %s has been removed", validate.SuccessEmoji, config.ExternalService.DisplayName) } }() } - log.Printf("%s cloning repository", validateHourglassEmoji) + log.Printf("%s cloning repository", validate.HourglassEmoji) cloned, err := repoCloneTimeout(ctx, client, config.ExternalService) if err != nil { return err //TODO make sure errors are wrapped once } if !cloned { - return errors.Newf("%s validate failed, repo did not clone\n", validateFailureEmoji) + return errors.Newf("%s validate failed, repo did not clone\n", validate.FailureEmoji) } - log.Printf("%s repositry successfully cloned", validateSuccessEmoji) + log.Printf("%s repositry successfully cloned", validate.SuccessEmoji) - log.Printf("%s validating search queries", validateEmojiFingerPointRight) + log.Printf("%s validating search queries", validate.EmojiFingerPointRight) if config.SearchQuery != nil { for i := 0; i < len(config.SearchQuery); i++ { @@ -196,26 +190,26 @@ func Installation(ctx context.Context, client api.Client, config *ValidationSpec if matchCount == 0 { return errors.Newf("validate failed, search query %s returned no results", config.SearchQuery[i]) } - log.Printf("%s search query '%s' was successful", validateSuccessEmoji, config.SearchQuery[i]) + log.Printf("%s search query '%s' was successful", validate.SuccessEmoji, config.SearchQuery[i]) } } - log.Printf("%s validating code insight", validateEmojiFingerPointRight) + log.Printf("%s validating code insight", validate.EmojiFingerPointRight) if config.Insight.Title != "" { - log.Printf("%s insight %s is being added", validateHourglassEmoji, config.Insight.Title) + log.Printf("%s insight %s is being added", validate.HourglassEmoji, config.Insight.Title) insightId, err := createInsight(ctx, client, config.Insight) if err != nil { return err } - log.Printf("%s insight successfully added", validateSuccessEmoji) + log.Printf("%s insight successfully added", validate.SuccessEmoji) defer func() { if insightId != "" { _ = removeInsight(ctx, client, insightId) - log.Printf("%s insight %s has been removed", validateSuccessEmoji, config.Insight.Title) + log.Printf("%s insight %s has been removed", validate.SuccessEmoji, config.Insight.Title) } }() diff --git a/internal/validate/kube/kube.go b/internal/validate/kube/kube.go new file mode 100644 index 0000000000..6a59dd016c --- /dev/null +++ b/internal/validate/kube/kube.go @@ -0,0 +1,389 @@ +package kube + +import ( + "bytes" + "context" + "fmt" + "io" + "log" + "os" + "regexp" + + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/client-go/kubernetes" + "k8s.io/client-go/kubernetes/scheme" + "k8s.io/client-go/rest" + "k8s.io/client-go/tools/remotecommand" + + "github.com/sourcegraph/src-cli/internal/validate" + + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +var ( + sourcegraphFrontend = regexp.MustCompile(`^sourcegraph-frontend-.*`) + sourcegraphRepoUpdater = regexp.MustCompile(`^repo-updater-.*`) + sourcegraphWorker = regexp.MustCompile(`^worker-.*`) +) + +type Option = func(config *Config) + +type Config struct { + namespace string + output io.Writer + exitStatus bool + clientSet *kubernetes.Clientset + restConfig *rest.Config +} + +func WithNamespace(namespace string) Option { + return func(config *Config) { + config.namespace = namespace + } +} + +func Quiet() Option { + return func(config *Config) { + config.output = io.Discard + config.exitStatus = true + } +} + +type validation func(ctx context.Context, config *Config) ([]validate.Result, error) + +// Validate will call a series of validation functions in a table driven tests style. +func Validate(ctx context.Context, clientSet *kubernetes.Clientset, restConfig *rest.Config, opts ...Option) error { + config := &Config{ + namespace: "default", + output: os.Stdout, + exitStatus: false, + clientSet: clientSet, + restConfig: restConfig, + } + + for _, opt := range opts { + opt(config) + } + + log.SetOutput(config.output) + + var validations = []struct { + Validate validation + WaitMsg string + SuccessMsg string + ErrMsg string + }{ + {Pods, "validating pods", "pods validated", "validating pods failed"}, + {Services, "validating services", "services validated", "validating services failed"}, + {PVCs, "validating pvcs", "pvcs validated", "validating pvcs failed"}, + {Connections, "validating connections", "connections validated", "validating connections failed"}, + } + + var totalFailCount int + + for _, v := range validations { + log.Printf("%s %s...", validate.HourglassEmoji, v.WaitMsg) + results, err := v.Validate(ctx, config) + if err != nil { + return errors.Wrapf(err, v.ErrMsg) + } + + var failCount int + var warnCount int + var succCount int + + for _, r := range results { + switch r.Status { + case validate.Failure: + log.Printf(" %s failure: %s", validate.FailureEmoji, r.Message) + failCount++ + case validate.Warning: + log.Printf(" %s warning: %s", validate.WarningSign, r.Message) + warnCount++ + case validate.Success: + succCount++ + } + } + + if failCount > 0 || warnCount > 0 { + log.Printf("\n%s %s", validate.FlashingLightEmoji, v.ErrMsg) + } + + if failCount > 0 { + log.Printf(" %s %d total failure(s)", validate.EmojiFingerPointRight, failCount) + + totalFailCount = totalFailCount + failCount + } + + if warnCount > 0 { + log.Printf(" %s %d total warning(s)", validate.EmojiFingerPointRight, warnCount) + } + + if failCount == 0 && warnCount == 0 { + log.Printf("%s %s!", validate.SuccessEmoji, v.SuccessMsg) + } + } + + if totalFailCount > 0 { + return errors.Newf("validation failed: %d failures", totalFailCount) + } + + return nil +} + +// Pods will validate all pods in a given namespace. +func Pods(ctx context.Context, config *Config) ([]validate.Result, error) { + pods, err := config.clientSet.CoreV1().Pods(config.namespace).List(ctx, metav1.ListOptions{}) + if err != nil { + return nil, err + } + + var results []validate.Result + + for _, pod := range pods.Items { + r := validatePod(&pod) + results = append(results, r...) + } + + return results, nil +} + +func validatePod(pod *corev1.Pod) []validate.Result { + var results []validate.Result + + if pod.Name == "" { + results = append(results, validate.Result{Status: validate.Failure, Message: "pod.Name is empty"}) + } + + if pod.Namespace == "" { + results = append(results, validate.Result{Status: validate.Failure, Message: "pod.Namespace is empty"}) + } + + if len(pod.Spec.Containers) == 0 { + results = append(results, validate.Result{Status: validate.Failure, Message: "spec.Containers is empty"}) + } + + switch pod.Status.Phase { + case corev1.PodPending: + results = append(results, validate.Result{ + Status: validate.Failure, + Message: fmt.Sprintf("pod '%s' has a status 'pending'", pod.Name), + }) + case corev1.PodFailed: + results = append(results, validate.Result{ + Status: validate.Failure, + Message: fmt.Sprintf("pod '%s' has a status 'failed'", pod.Name), + }) + } + + for _, container := range pod.Spec.Containers { + if container.Name == "" { + results = append(results, validate.Result{ + Status: validate.Failure, + Message: fmt.Sprintf("container.Name is empty, pod '%s'", pod.Name), + }) + } + + if container.Image == "" { + results = append(results, validate.Result{ + Status: validate.Failure, + Message: fmt.Sprintf("container.Image is empty, pod '%s'", pod.Name), + }) + } + } + + for _, c := range pod.Status.ContainerStatuses { + if !c.Ready { + results = append(results, validate.Result{ + Status: validate.Failure, + Message: fmt.Sprintf("container '%s' is not ready, pod '%s'", c.ContainerID, pod.Name), + }) + } + + if c.RestartCount > 50 { + results = append(results, validate.Result{ + Status: validate.Warning, + Message: fmt.Sprintf("container '%s' has high restart count: %d restarts", c.ContainerID, c.RestartCount), + }) + } + } + + return results +} + +// Services will validate all services in a given namespace. +func Services(ctx context.Context, config *Config) ([]validate.Result, error) { + services, err := config.clientSet.CoreV1().Services(config.namespace).List(ctx, metav1.ListOptions{}) + if err != nil { + return nil, err + } + + var results []validate.Result + + for _, service := range services.Items { + r := validateService(&service) + results = append(results, r...) + } + + return results, nil +} + +func validateService(service *corev1.Service) []validate.Result { + var results []validate.Result + + if service.Name == "" { + results = append(results, validate.Result{Status: validate.Failure, Message: "service.Name is empty"}) + } + + if service.Namespace == "" { + results = append(results, validate.Result{Status: validate.Failure, Message: "service.Namespace is empty"}) + } + + if len(service.Spec.Ports) == 0 { + results = append(results, validate.Result{Status: validate.Failure, Message: "service.Ports is empty"}) + } + + return results +} + +// PVCs will validate all persistent volume claims on a given namespace +func PVCs(ctx context.Context, config *Config) ([]validate.Result, error) { + pvcs, err := config.clientSet.CoreV1().PersistentVolumeClaims(config.namespace).List(ctx, metav1.ListOptions{}) + if err != nil { + return nil, err + } + + var results []validate.Result + + for _, pvc := range pvcs.Items { + r := validatePVC(&pvc) + results = append(results, r...) + } + + return results, nil +} + +func validatePVC(pvc *corev1.PersistentVolumeClaim) []validate.Result { + var results []validate.Result + + if pvc.Name == "" { + results = append(results, validate.Result{Status: validate.Failure, Message: "pvc.Name is empty"}) + } + + if pvc.Status.Phase != "Bound" { + results = append(results, validate.Result{Status: validate.Failure, Message: "pvc.Status is not bound"}) + } + + return results +} + +type connection struct { + src corev1.Pod + dest []dest +} + +type dest struct { + addr string + port string +} + +// Connections will validate that Sourcegraph services can reach each other over the network. +func Connections(ctx context.Context, config *Config) ([]validate.Result, error) { + var results []validate.Result + var connections []connection + + pods, err := config.clientSet.CoreV1().Pods(config.namespace).List(ctx, metav1.ListOptions{}) + if err != nil { + return nil, err + } + + // iterate through pods looking for specific pod name prefixes, then construct + // a relationship map between pods that should have connectivity with each other + for _, pod := range pods.Items { + switch name := pod.Name; { + case sourcegraphFrontend.MatchString(name): // pod is one of the sourcegraph front-end pods + connections = append(connections, connection{ + src: pod, + dest: []dest{ + { + addr: "pgsql", + port: "5432", + }, + { + addr: "indexed-search", + port: "6070", + }, + { + addr: "repo-updater", + port: "3182", + }, + { + addr: "syntect-server", + port: "9238", + }, + }, + }) + case sourcegraphWorker.MatchString(name): // pod is a worker pod + connections = append(connections, connection{ + src: pod, + dest: []dest{ + { + addr: "pgsql", + port: "5432", + }, + }, + }) + case sourcegraphRepoUpdater.MatchString(name): + connections = append(connections, connection{ + src: pod, + dest: []dest{ + { + addr: "pgsql", + port: "5432", + }, + }, + }) + } + } + + // use network relationships constructed above to test network connection for each relationship + for _, c := range connections { + for _, d := range c.dest { + req := config.clientSet.CoreV1().RESTClient().Post(). + Resource("pods"). + Name(c.src.Name). + Namespace(c.src.Namespace). + SubResource("exec") + + req.VersionedParams(&corev1.PodExecOptions{ + Command: []string{"/usr/bin/nc", "-z", d.addr, d.port}, + Stdin: false, + Stdout: true, + Stderr: true, + TTY: false, + }, scheme.ParameterCodec) + + exec, err := remotecommand.NewSPDYExecutor(config.restConfig, "POST", req.URL()) + if err != nil { + return nil, err + } + + var stdout, stderr bytes.Buffer + + err = exec.StreamWithContext(ctx, remotecommand.StreamOptions{ + Stdout: &stdout, + Stderr: &stderr, + }) + if err != nil { + return nil, err + } + + if stderr.String() != "" { + results = append(results, validate.Result{Status: validate.Failure, Message: stderr.String()}) + } + } + } + + return results, nil +} diff --git a/internal/validate/kube/kube_test.go b/internal/validate/kube/kube_test.go new file mode 100644 index 0000000000..cd8a778cec --- /dev/null +++ b/internal/validate/kube/kube_test.go @@ -0,0 +1,395 @@ +package kube + +import ( + "testing" + + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + "github.com/sourcegraph/src-cli/internal/validate" +) + +func TestValidatePod(t *testing.T) { + cases := []struct { + name string + pod func(pod *corev1.Pod) + result []validate.Result + }{ + { + name: "valid pod", + }, + { + name: "invalid pod: pod name is not set", + pod: func(pod *corev1.Pod) { + pod.Name = "" + }, + result: []validate.Result{ + { + Status: validate.Failure, + Message: "pod.Name is empty", + }, + }, + }, + { + name: "invalid pod: pod namespace is empty", + pod: func(pod *corev1.Pod) { + pod.Namespace = "" + }, + result: []validate.Result{ + { + Status: validate.Failure, + Message: "pod.Namespace is empty", + }, + }, + }, + { + name: "invalid pod: spec containers is empty", + pod: func(pod *corev1.Pod) { + pod.Spec.Containers = nil + }, + result: []validate.Result{ + { + Status: validate.Failure, + Message: "spec.Containers is empty", + }, + }, + }, + { + name: "invalid pod: pod status is pending", + pod: func(pod *corev1.Pod) { + pod.Status.Phase = corev1.PodPending + }, + result: []validate.Result{ + { + Status: validate.Failure, + Message: "pod 'sourcegraph-frontend-' has a status 'pending'", + }, + }, + }, + { + name: "invalid pod: pod status failed", + pod: func(pod *corev1.Pod) { + pod.Status.Phase = corev1.PodFailed + }, + result: []validate.Result{ + { + Status: validate.Failure, + Message: "pod 'sourcegraph-frontend-' has a status 'failed'", + }, + }, + }, + { + name: "invalid pod: container name is empty", + pod: func(pod *corev1.Pod) { + pod.Spec.Containers[0].Name = "" + }, + result: []validate.Result{ + { + Status: validate.Failure, + Message: "container.Name is empty, pod 'sourcegraph-frontend-'", + }, + }, + }, + { + name: "invalid pod: container image is empty", + pod: func(pod *corev1.Pod) { + pod.Spec.Containers[0].Image = "" + }, + result: []validate.Result{ + { + Status: validate.Failure, + Message: "container.Image is empty, pod 'sourcegraph-frontend-'", + }, + }, + }, + { + name: "invalid pod: image is not set", + pod: func(pod *corev1.Pod) { + pod.Spec.Containers[0].Image = "" + }, + result: []validate.Result{ + { + Status: validate.Failure, + Message: "container.Image is empty, pod 'sourcegraph-frontend-'", + }, + }, + }, + { + name: "invalid pod: container status not ready", + pod: func(pod *corev1.Pod) { + pod.Status.ContainerStatuses[0].Ready = false + }, + result: []validate.Result{ + { + Status: validate.Failure, + Message: "container 'sourcegraph-test-id' is not ready, pod 'sourcegraph-frontend-'", + }, + }, + }, + { + name: "invalid pod: container restart count is high", + pod: func(pod *corev1.Pod) { + pod.Status.ContainerStatuses[0].RestartCount = 100 + }, + result: []validate.Result{ + { + Status: validate.Warning, + Message: "container 'sourcegraph-test-id' has high restart count: 100 restarts", + }, + }, + }, + } + + for _, tc := range cases { + tc := tc + t.Run(tc.name, func(t *testing.T) { + pod := testPod() + if tc.pod != nil { + tc.pod(pod) + } + result := validatePod(pod) + + // test should error + if len(tc.result) > 0 { + if result == nil { + t.Fatal("validate should return result") + return + } + if result[0].Status != tc.result[0].Status { + t.Errorf("result status\nwant: %v\n got: %v", tc.result[0].Status, result[0].Status) + } + if result[0].Message != tc.result[0].Message { + t.Errorf("result msg\nwant: %s\n got: %s", tc.result[0].Message, result[0].Message) + } + return + } + + // test should not error + if result != nil { + t.Fatalf("ValidatePod error: %v", result) + } + }) + } +} + +func TestValidateService(t *testing.T) { + cases := []struct { + name string + service func(service *corev1.Service) + result []validate.Result + }{ + { + name: "valid service", + }, + { + name: "invalid service: service name is not set", + service: func(service *corev1.Service) { + service.Name = "" + }, + result: []validate.Result{ + { + Status: validate.Failure, + Message: "service.Name is empty", + }, + }, + }, + { + name: "invalid service: service namespace is not set", + service: func(service *corev1.Service) { + service.Namespace = "" + }, + result: []validate.Result{ + { + Status: validate.Failure, + Message: "service.Namespace is empty", + }, + }, + }, + { + name: "invalid service: service ports is empty", + service: func(service *corev1.Service) { + service.Spec.Ports = nil + }, + result: []validate.Result{ + { + Status: validate.Failure, + Message: "service.Ports is empty", + }, + }, + }, + } + + for _, tc := range cases { + tc := tc + t.Run(tc.name, func(t *testing.T) { + service := testService() + if tc.service != nil { + tc.service(service) + } + result := validateService(service) + + // test should error + if len(tc.result) > 0 { + if result == nil { + t.Fatal("validate should return result") + return + } + if result[0].Status != tc.result[0].Status { + t.Errorf("result status\nwant: %v\n got: %v", tc.result[0].Status, result[0].Status) + } + if result[0].Message != tc.result[0].Message { + t.Errorf("result msg\nwant: %s\n got: %s", tc.result[0].Message, result[0].Message) + } + return + } + + // test should not error + if result != nil { + t.Fatalf("ValidateService error: %v", result) + } + }) + } +} + +func TestValidatePVC(t *testing.T) { + cases := []struct { + name string + pvc func(pvc *corev1.PersistentVolumeClaim) + result []validate.Result + }{ + { + name: "valid pvc", + }, + { + name: "invalid pvc: status not bound", + pvc: func(pvc *corev1.PersistentVolumeClaim) { + pvc.Status.Phase = "Waiting" + }, + result: []validate.Result{ + { + Status: validate.Failure, + Message: "pvc.Status is not bound", + }, + }, + }, + } + + for _, tc := range cases { + tc := tc + t.Run(tc.name, func(t *testing.T) { + pvc := testPVC() + if tc.pvc != nil { + tc.pvc(pvc) + } + result := validatePVC(pvc) + + // test should error + if len(tc.result) > 0 { + if result == nil { + t.Fatal("validate should return result") + return + } + if result[0].Status != tc.result[0].Status { + t.Errorf("result status\nwant: %v\n got: %v", tc.result[0].Status, result[0].Status) + } + if result[0].Message != tc.result[0].Message { + t.Errorf("result msg\nwant: %s\n got: %s", tc.result[0].Message, result[0].Message) + } + return + } + + // test should not error + if result != nil { + t.Fatalf("ValidateService error: %v", result) + } + }) + } +} + +// helper test function to return a valid pod +func testPod() *corev1.Pod { + return &corev1.Pod{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: "default", + Name: "sourcegraph-frontend-", + Labels: map[string]string{ + "deploy": "sourcegraph", + }, + Annotations: map[string]string{ + "kubectl.kubernetes.io/default-container": "frontend", + }, + }, + Spec: corev1.PodSpec{ + Containers: []corev1.Container{ + { + Name: "sourcegraph-frontend", + Image: "sourcegraph/foo:test", + Ports: []corev1.ContainerPort{ + { + ContainerPort: 8800, + Protocol: corev1.ProtocolTCP, + }, + { + ContainerPort: 3090, + Protocol: corev1.ProtocolTCP, + }, + { + ContainerPort: 6060, + Protocol: corev1.ProtocolTCP, + }, + }, + Args: []string{"serve"}, + }, + }, + }, + Status: corev1.PodStatus{ + ContainerStatuses: []corev1.ContainerStatus{ + { + ContainerID: "sourcegraph-test-id", + Ready: true, + RestartCount: 0, + }, + }, + }, + } +} + +// helper test function to return a valid service +func testService() *corev1.Service { + return &corev1.Service{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: "default", + Name: "symbols", + Labels: map[string]string{ + "deploy": "sourcegraph", + }, + }, + Spec: corev1.ServiceSpec{ + Type: corev1.ServiceTypeClusterIP, + Ports: []corev1.ServicePort{ + { + Name: "http", + Port: 3184, + Protocol: corev1.ProtocolTCP, + }, + }, + }, + Status: corev1.ServiceStatus{}, + } +} + +// helper test function to return a valid PVC +func testPVC() *corev1.PersistentVolumeClaim { + return &corev1.PersistentVolumeClaim{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: "default", + Name: "pgsql", + Labels: map[string]string{ + "deploy": "sourcegraph", + }, + }, + Status: corev1.PersistentVolumeClaimStatus{ + Phase: "Bound", + }, + } +} diff --git a/internal/validate/validate.go b/internal/validate/validate.go new file mode 100644 index 0000000000..402d2686ea --- /dev/null +++ b/internal/validate/validate.go @@ -0,0 +1,23 @@ +package validate + +var ( + EmojiFingerPointRight = "👉" + FailureEmoji = "🛑" + FlashingLightEmoji = "🚨" + HourglassEmoji = "⌛" + SuccessEmoji = "✅" + WarningSign = "⚠️ " // why does this need an extra space to align?!?! +) + +type Status string + +const ( + Failure Status = "Failure" + Warning Status = "Warning" + Success Status = "Success" +) + +type Result struct { + Status Status + Message string +} From 79c8fa1421c92041f22141cd64b34571e080d748 Mon Sep 17 00:00:00 2001 From: Jacob Pleiness Date: Tue, 24 Jan 2023 14:43:28 -0500 Subject: [PATCH 292/647] Add deleteWhenDone option to insights (#927) * Insights were automatically deleted, add option to keep insight created during validation --- internal/validate/install/install.go | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/internal/validate/install/install.go b/internal/validate/install/install.go index eb3a6503a2..1dad644610 100644 --- a/internal/validate/install/install.go +++ b/internal/validate/install/install.go @@ -56,8 +56,9 @@ type GitHub struct { } type Insight struct { - Title string `yaml:"title"` - DataSeries []map[string]any `yaml:"dataSeries"` + Title string `yaml:"title"` + DataSeries []map[string]any `yaml:"dataSeries"` + DeleteWhenDone bool `yaml:"deleteWhenDone"` } type ValidationSpec struct { @@ -114,6 +115,7 @@ func DefaultConfig() *ValidationSpec { "timeScopeValue": 1, }, }, + DeleteWhenDone: true, }, } } @@ -171,7 +173,7 @@ func Validate(ctx context.Context, client api.Client, config *ValidationSpec) er cloned, err := repoCloneTimeout(ctx, client, config.ExternalService) if err != nil { - return err //TODO make sure errors are wrapped once + return err } if !cloned { return errors.Newf("%s validate failed, repo did not clone\n", validate.FailureEmoji) @@ -207,7 +209,7 @@ func Validate(ctx context.Context, client api.Client, config *ValidationSpec) er log.Printf("%s insight successfully added", validate.SuccessEmoji) defer func() { - if insightId != "" { + if insightId != "" && config.Insight.DeleteWhenDone { _ = removeInsight(ctx, client, insightId) log.Printf("%s insight %s has been removed", validate.SuccessEmoji, config.Insight.Title) From c967c5ea2df6d7cb07759b4a4d64a6e9e35cb03a Mon Sep 17 00:00:00 2001 From: Jacob Pleiness Date: Fri, 27 Jan 2023 13:46:52 -0500 Subject: [PATCH 293/647] Update CHANGELOG.md for 4.4.1 release (#928) --- CHANGELOG.md | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 319cbdf502..b2d4b84675 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,16 +13,20 @@ All notable changes to `src-cli` are documented in this file. ### Added -- `src codeintel upload` will now upload SCIP indexes (over LSIF indexes) when the target instance supports it. [#897](https://github.com/sourcegraph/src-cli/pull/897) - -- `src validate kube` adds support for validating Sourcegraph deployments on Kubernetes. Validations include Pods, Services, PVCs, and network connectivity. [#926](https://github.com/sourcegraph/src-cli/pull/926) - ### Changed ### Fixed ### Removed +## 4.4.1 + +### Added + +- `src codeintel upload` will now upload SCIP indexes (over LSIF indexes) when the target instance supports it. [#897](https://github.com/sourcegraph/src-cli/pull/897) + +- `src validate kube` adds support for validating Sourcegraph deployments on Kubernetes. Validations include Pods, Services, PVCs, and network connectivity. [#926](https://github.com/sourcegraph/src-cli/pull/926) + ## 4.4.0 ### Added From 715ed433720f890f86c522841648ca2f98edc1c8 Mon Sep 17 00:00:00 2001 From: adeola <67931373+adeola-ak@users.noreply.github.com> Date: Sun, 29 Jan 2023 02:44:19 -0500 Subject: [PATCH 294/647] batches: query max unlicensed changesets count (#929) replace hardcoded permitted unlicensed changesets count by querying maxUnlicensedChangesets --- cmd/src/batch_common.go | 4 ++-- cmd/src/batch_new.go | 2 +- cmd/src/batch_remote.go | 2 +- cmd/src/batch_repositories.go | 2 +- cmd/src/batch_validate.go | 2 +- internal/batches/license.go | 5 ++++ internal/batches/service/service.go | 36 ++++++++++++++++++----------- internal/batches/ui/exec_ui.go | 2 +- internal/batches/ui/json_lines.go | 2 +- internal/batches/ui/tui.go | 14 +++++------ 10 files changed, 42 insertions(+), 29 deletions(-) create mode 100644 internal/batches/license.go diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index 27b4ada60f..e16aa38fcb 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -290,7 +290,7 @@ func executeBatchSpec(ctx context.Context, opts executeBatchSpecOpts) (err error Client: opts.client, }) - ffs, err := svc.DetermineFeatureFlags(ctx) + lr, ffs, err := svc.DetermineLicenseAndFeatureFlags(ctx) if err != nil { return err } @@ -521,7 +521,7 @@ func executeBatchSpec(ctx context.Context, opts executeBatchSpecOpts) (err error execUI.CreatingBatchSpec() id, url, err := svc.CreateBatchSpec(ctx, namespace.ID, rawSpec, ids) if err != nil { - return execUI.CreatingBatchSpecError(err) + return execUI.CreatingBatchSpecError(lr.MaxUnlicensedChangesets, err) } previewURL := cfg.Endpoint + url execUI.CreatingBatchSpecSuccess(previewURL) diff --git a/cmd/src/batch_new.go b/cmd/src/batch_new.go index 75fe9a8891..349b590eff 100644 --- a/cmd/src/batch_new.go +++ b/cmd/src/batch_new.go @@ -48,7 +48,7 @@ Examples: Client: cfg.apiClient(apiFlags, flagSet.Output()), }) - ffs, err := svc.DetermineFeatureFlags(ctx) + _, ffs, err := svc.DetermineLicenseAndFeatureFlags(ctx) if err != nil { return err } diff --git a/cmd/src/batch_remote.go b/cmd/src/batch_remote.go index dbdcf1c264..7817421ab3 100644 --- a/cmd/src/batch_remote.go +++ b/cmd/src/batch_remote.go @@ -52,7 +52,7 @@ Examples: Client: cfg.apiClient(flags.api, flagSet.Output()), }) - ffs, err := svc.DetermineFeatureFlags(ctx) + _, ffs, err := svc.DetermineLicenseAndFeatureFlags(ctx) if err != nil { return err } diff --git a/cmd/src/batch_repositories.go b/cmd/src/batch_repositories.go index f4b3280823..092ae637d2 100644 --- a/cmd/src/batch_repositories.go +++ b/cmd/src/batch_repositories.go @@ -69,7 +69,7 @@ Examples: Client: client, }) - ffs, err := svc.DetermineFeatureFlags(ctx) + _, ffs, err := svc.DetermineLicenseAndFeatureFlags(ctx) if err != nil { return err } diff --git a/cmd/src/batch_validate.go b/cmd/src/batch_validate.go index b3268ea758..e2c77c29bc 100644 --- a/cmd/src/batch_validate.go +++ b/cmd/src/batch_validate.go @@ -63,7 +63,7 @@ Examples: Client: cfg.apiClient(apiFlags, flagSet.Output()), }) - ffs, err := svc.DetermineFeatureFlags(ctx) + _, ffs, err := svc.DetermineLicenseAndFeatureFlags(ctx) if err != nil { return err } diff --git a/internal/batches/license.go b/internal/batches/license.go new file mode 100644 index 0000000000..2a614ae719 --- /dev/null +++ b/internal/batches/license.go @@ -0,0 +1,5 @@ +package batches + +type LicenseRestrictions struct { + MaxUnlicensedChangesets int +} diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index 4231b945dd..99d49a9c21 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -43,10 +43,11 @@ func New(opts *Opts) *Service { // The reason we ask for batchChanges here is to surface errors about trying to use batch // changes in an unsupported environment sooner, since the version check is typically the // first thing we do. -const sourcegraphVersionQuery = `query SourcegraphVersion { +const getInstanceInfo = `query InstanceInfo { site { productVersion } + maxUnlicensedChangesets batchChanges(first: 1) { nodes { id @@ -55,32 +56,39 @@ const sourcegraphVersionQuery = `query SourcegraphVersion { } ` -// getSourcegraphVersion queries the Sourcegraph GraphQL API to get the -// current version of the Sourcegraph instance. -func (svc *Service) getSourcegraphVersion(ctx context.Context) (string, error) { +// getSourcegraphVersionAndMaxChangesetsCount queries the Sourcegraph GraphQL API to get the +// current version and max unlicensed changesets count for the Sourcegraph instance. +func (svc *Service) getSourcegraphVersionAndMaxChangesetsCount(ctx context.Context) (string, int, error) { var result struct { - Site struct { + MaxUnlicensedChangesets int + Site struct { ProductVersion string } } - ok, err := svc.client.NewQuery(sourcegraphVersionQuery).Do(ctx, &result) + ok, err := svc.client.NewQuery(getInstanceInfo).Do(ctx, &result) if err != nil || !ok { - return "", err + return "", 0, err } - return result.Site.ProductVersion, err + return result.Site.ProductVersion, result.MaxUnlicensedChangesets, err } -// DetermineFeatureFlags fetches the version of the configured Sourcegraph and -// returns the enabled features. -func (svc *Service) DetermineFeatureFlags(ctx context.Context) (*batches.FeatureFlags, error) { - version, err := svc.getSourcegraphVersion(ctx) +// DetermineLicenseAndFeatureFlags returns the enabled features and license restrictions +// configured for the Sourcegraph instance. +func (svc *Service) DetermineLicenseAndFeatureFlags(ctx context.Context) (*batches.LicenseRestrictions, *batches.FeatureFlags, error) { + version, mc, err := svc.getSourcegraphVersionAndMaxChangesetsCount(ctx) if err != nil { - return nil, errors.Wrap(err, "failed to query Sourcegraph version to check for available features") + return nil, nil, errors.Wrap(err, "failed to query Sourcegraph version and license info for instance") + } + + lr := &batches.LicenseRestrictions{ + MaxUnlicensedChangesets: mc, } + ffs := &batches.FeatureFlags{} - return ffs, ffs.SetFromVersion(version) + return lr, ffs, ffs.SetFromVersion(version) + } const applyBatchChangeMutation = ` diff --git a/internal/batches/ui/exec_ui.go b/internal/batches/ui/exec_ui.go index e9944c17bc..fd12b84173 100644 --- a/internal/batches/ui/exec_ui.go +++ b/internal/batches/ui/exec_ui.go @@ -40,7 +40,7 @@ type ExecUI interface { CreatingBatchSpec() CreatingBatchSpecSuccess(previewURL string) - CreatingBatchSpecError(err error) error + CreatingBatchSpecError(maxUnlicensedCS int, err error) error PreviewBatchSpec(previewURL string) diff --git a/internal/batches/ui/json_lines.go b/internal/batches/ui/json_lines.go index 45475b137e..36ae989570 100644 --- a/internal/batches/ui/json_lines.go +++ b/internal/batches/ui/json_lines.go @@ -149,7 +149,7 @@ func (ui *JSONLines) CreatingBatchSpecSuccess(batchSpecURL string) { }) } -func (ui *JSONLines) CreatingBatchSpecError(err error) error { +func (ui *JSONLines) CreatingBatchSpecError(_ int, err error) error { logOperationFailure(batcheslib.LogEventOperationCreatingBatchSpec, &batcheslib.CreatingBatchSpecMetadata{}) return err } diff --git a/internal/batches/ui/tui.go b/internal/batches/ui/tui.go index af49e98bde..94724909b1 100644 --- a/internal/batches/ui/tui.go +++ b/internal/batches/ui/tui.go @@ -217,8 +217,8 @@ func (ui *TUI) CreatingBatchSpecSuccess(previewURL string) { batchCompletePending(ui.pending, "Creating batch spec on Sourcegraph") } -func (ui *TUI) CreatingBatchSpecError(err error) error { - return prettyPrintBatchUnlicensedError(ui.Out, err) +func (ui *TUI) CreatingBatchSpecError(maxUnlicensedCS int, err error) error { + return prettyPrintBatchUnlicensedError(ui.Out, maxUnlicensedCS, err) } func (ui *TUI) DockerWatchDogWarning(err error) { @@ -307,7 +307,7 @@ func (ui *TUI) RemoteSuccess(url string) { // is, then a better message is output. Regardless, the return value of this // function should be used to replace the original error passed in to ensure // that the displayed output is sensible. -func prettyPrintBatchUnlicensedError(out *output.Output, err error) error { +func prettyPrintBatchUnlicensedError(out *output.Output, maxUnlicensedCS int, err error) error { // Pull apart the error to see if it's a licensing error: if so, we should // display a friendlier and more actionable message than the usual GraphQL // error output. @@ -321,19 +321,19 @@ func prettyPrintBatchUnlicensedError(out *output.Output, err error) error { // verbose mode, but let the original error bubble up rather // than this one. out.Verbosef("Unexpected error parsing the GraphQL error: %v", cerr) - } else if code == "ErrBatchChangesUnlicensed" { + } else if code == "ErrBatchChangesUnlicensed" || code == "ErrBatchChangesOverLimit" { // OK, let's print a better message, then return an // exitCodeError to suppress the normal automatic error block. // Note that we have hand wrapped the output at 80 (printable) // characters: having automatic wrapping some day would be nice, // but this should be sufficient for now. block := out.Block(output.Line("🪙", output.StyleWarning, "Batch Changes is a paid feature of Sourcegraph. All users can create sample")) - block.WriteLine(output.Linef("", output.StyleWarning, "batch changes with up to 10 changesets without a license. Contact Sourcegraph")) + block.WriteLine(output.Linef("", output.StyleWarning, "batch changes with up to %v changesets without a license. Contact Sourcegraph", maxUnlicensedCS)) block.WriteLine(output.Linef("", output.StyleWarning, "sales at %shttps://about.sourcegraph.com/contact/sales/%s to obtain a trial", output.StyleSearchLink, output.StyleWarning)) block.WriteLine(output.Linef("", output.StyleWarning, "license.")) block.Write("") - block.WriteLine(output.Linef("", output.StyleWarning, "To proceed with this batch change, you will need to create 5 or fewer")) - block.WriteLine(output.Linef("", output.StyleWarning, "changesets. To do so, you could try adding %scount:5%s to your", output.StyleSearchAlertProposedQuery, output.StyleWarning)) + block.WriteLine(output.Linef("", output.StyleWarning, "To proceed with this batch change, you will need to create %v or fewer", maxUnlicensedCS)) + block.WriteLine(output.Linef("", output.StyleWarning, "changesets. To do so, you could try adding %scount:%v%s to your", output.StyleSearchAlertProposedQuery, maxUnlicensedCS, output.StyleWarning)) block.WriteLine(output.Linef("", output.StyleWarning, "%srepositoriesMatchingQuery%s search, or reduce the number of changesets in", output.StyleReset, output.StyleWarning)) block.WriteLine(output.Linef("", output.StyleWarning, "%simportChangesets%s.", output.StyleReset, output.StyleWarning)) block.Close() From e9ce3f62ef47a8ce59928f8db2fd8e39f6a75ab5 Mon Sep 17 00:00:00 2001 From: Robert Lin Date: Thu, 2 Feb 2023 16:28:08 -0800 Subject: [PATCH 295/647] snapshot: fix incorrect ref to validation error (#933) --- cmd/src/snapshot_testcmd.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/src/snapshot_testcmd.go b/cmd/src/snapshot_testcmd.go index e3d760c741..f9a7b624c1 100644 --- a/cmd/src/snapshot_testcmd.go +++ b/cmd/src/snapshot_testcmd.go @@ -86,7 +86,7 @@ TEST DATA } if validationErrors != nil { out.WriteLine(output.Linef(output.EmojiFailure, output.StyleFailure, - "Critical issues found: %s", err.Error())) + "Critical issues found: %s", validationErrors.Error())) return errors.New("validation failed") } out.WriteLine(output.Line(output.EmojiSuccess, output.StyleSuccess, From 8579a58a7dbad07308380c980093cf98c256ed29 Mon Sep 17 00:00:00 2001 From: Eric Fritz Date: Sun, 12 Feb 2023 23:55:09 +0100 Subject: [PATCH 296/647] Do not override executor queue endpoints (#934) --- cmd/src/code_intel_upload.go | 2 +- cmd/src/code_intel_upload_flags.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/cmd/src/code_intel_upload.go b/cmd/src/code_intel_upload.go index 41520bd47a..fe361c3e02 100644 --- a/cmd/src/code_intel_upload.go +++ b/cmd/src/code_intel_upload.go @@ -148,7 +148,7 @@ func codeintelUploadOptions(out *output.Output, isSCIPAvailable bool) upload.Upl path := codeintelUploadFlags.uploadRoute if isSCIPAvailable && filepath.Ext(codeintelUploadFlags.file) == ".scip" { cfg.AdditionalHeaders["Content-Type"] = "application/x-protobuf+scip" - path = "/.api/scip/upload" + path = strings.ReplaceAll(path, "lsif", "scip") } logger := upload.NewRequestLogger( diff --git a/cmd/src/code_intel_upload_flags.go b/cmd/src/code_intel_upload_flags.go index 04de47379e..cd19fbce32 100644 --- a/cmd/src/code_intel_upload_flags.go +++ b/cmd/src/code_intel_upload_flags.go @@ -185,7 +185,7 @@ func codeintelUploadOutput() (out *output.Output) { func isSCIPAvailable() (bool, error) { client := cfg.apiClient(codeintelUploadFlags.apiFlags, codeintelUploadFlagSet.Output()) - req, err := client.NewHTTPRequest(context.Background(), "HEAD", "/.api/scip/upload", nil) + req, err := client.NewHTTPRequest(context.Background(), "HEAD", strings.ReplaceAll(codeintelUploadFlags.uploadRoute, "lsif", "scip"), nil) if err != nil { return false, err } From a1f16e8f0594fd5683cc4fa3e14aacc310e1aa93 Mon Sep 17 00:00:00 2001 From: Eric Fritz Date: Mon, 13 Feb 2023 14:40:05 +0100 Subject: [PATCH 297/647] Prep changelog for 4.4.2 release (#935) --- CHANGELOG.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b2d4b84675..2d8bdc39fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,12 @@ All notable changes to `src-cli` are documented in this file. ### Removed +## 4.4.2 + +### Fixed + +- `src codeintel upload` will no longer overwrite the entire route supplied via `-upload-route` if SCIP data is detected. [#934](https://github.com/sourcegraph/src-cli/pull/934) + ## 4.4.1 ### Added From a84baf7c522b41ea8f0e77721bc9be88686fcd51 Mon Sep 17 00:00:00 2001 From: Bolaji Olajide <25608335+BolajiOlajide@users.noreply.github.com> Date: Wed, 15 Feb 2023 15:46:16 +0100 Subject: [PATCH 298/647] update changelog for 4.5 release (#937) --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2d8bdc39fc..f6744d89e6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,10 @@ All notable changes to `src-cli` are documented in this file. ### Removed +## 4.5.0 + +No noteworthy changes, mechanical release to match Sourcegraph release. + ## 4.4.2 ### Fixed From b7eb62bcb8f1675a167dc5013921f9644aba92d8 Mon Sep 17 00:00:00 2001 From: Alex Ostrikov Date: Tue, 21 Feb 2023 19:14:09 +0100 Subject: [PATCH 299/647] permissions-center: use new `permissionSyncJobs` query. (#942) Test plan: `src snapshot test` runs successfully and fetches perms sync information from a local sg instance. --- cmd/src/cmd.go | 8 +++--- cmd/src/snapshot_testcmd.go | 5 ++-- internal/instancehealth/checks.go | 12 ++++---- internal/instancehealth/checks_test.go | 39 +++++++++++++------------- internal/instancehealth/summary.go | 36 ++++++++++++------------ 5 files changed, 51 insertions(+), 49 deletions(-) diff --git a/cmd/src/cmd.go b/cmd/src/cmd.go index 7d602b2a64..96a6fcec9e 100644 --- a/cmd/src/cmd.go +++ b/cmd/src/cmd.go @@ -23,8 +23,8 @@ type command struct { // handler is the function that is invoked to handle this command. handler func(args []string) error - // flagSet.Usage function to invoke on e.g. -h flag. If nil, a default one - // one is used. + // flagSet.Usage function to invoke on e.g. -h flag. If nil, a default one is + // used. usageFunc func() } @@ -48,7 +48,7 @@ type commander []*command func (c commander) run(flagSet *flag.FlagSet, cmdName, usageText string, args []string) { // Parse flags. flagSet.Usage = func() { - fmt.Fprint(flag.CommandLine.Output(), usageText) + _, _ = fmt.Fprint(flag.CommandLine.Output(), usageText) } if !flagSet.Parsed() { _ = flagSet.Parse(args) @@ -68,7 +68,7 @@ func (c commander) run(flagSet *flag.FlagSet, cmdName, usageText string, args [] continue } cmd.flagSet.Usage = func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of '%s %s':\n", cmdName, cmd.flagSet.Name()) + _, _ = fmt.Fprintf(flag.CommandLine.Output(), "Usage of '%s %s':\n", cmdName, cmd.flagSet.Name()) cmd.flagSet.PrintDefaults() } } diff --git a/cmd/src/snapshot_testcmd.go b/cmd/src/snapshot_testcmd.go index f9a7b624c1..0faf58df03 100644 --- a/cmd/src/snapshot_testcmd.go +++ b/cmd/src/snapshot_testcmd.go @@ -9,6 +9,7 @@ import ( "time" "github.com/google/go-cmp/cmp" + "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/sourcegraph/lib/output" @@ -93,7 +94,7 @@ TEST DATA "No critical issues found!")) return nil }, - usageFunc: func() { fmt.Fprint(flag.CommandLine.Output(), usage) }, + usageFunc: func() { _, _ = fmt.Fprint(flag.CommandLine.Output(), usage) }, }) } @@ -105,7 +106,7 @@ func compareSnapshotSummaries(out *output.Output, recordedSummary, newSummary sn diff := cmp.Diff(recordedSummary, newSummary) if diff != "" { b.WriteLine(output.Line(output.EmojiFailure, output.StyleFailure, "Snapshot diff detected:")) - b.WriteCode("diff", diff) + _ = b.WriteCode("diff", diff) return errors.New("snapshot mismatch") } b.WriteLine(output.Emoji(output.EmojiSuccess, "Snapshots match!")) diff --git a/internal/instancehealth/checks.go b/internal/instancehealth/checks.go index f78dd57b0e..968628ea87 100644 --- a/internal/instancehealth/checks.go +++ b/internal/instancehealth/checks.go @@ -134,16 +134,16 @@ func checkPermissionsSyncing( var syncCount int var syncErrors []string var seenProviders = make(map[string]map[string]string) // provider : state : message - for _, sync := range instanceHealth.PermissionsSyncJobs.Nodes { - if sync.CompletedAt.Before(time.Now().Add(-since)) { + for _, sync := range instanceHealth.PermissionSyncJobs.Nodes { + if sync.FinishedAt.Before(time.Now().Add(-since)) { continue } syncCount += 1 - if sync.Status == "ERROR" { - syncErrors = append(syncErrors, sync.Message) + if sync.State == "ERROR" || sync.State == "FAILED" { + syncErrors = append(syncErrors, sync.FailureMessage) } - for _, p := range sync.Providers { - key := fmt.Sprintf("%s - %s", p.Type, p.ID) + for _, p := range sync.CodeHostStates { + key := fmt.Sprintf("%s - %s", p.ProviderType, p.ProviderID) if _, ok := seenProviders[key]; !ok { seenProviders[key] = make(map[string]string) } diff --git a/internal/instancehealth/checks_test.go b/internal/instancehealth/checks_test.go index a0d9af9696..e57223487c 100644 --- a/internal/instancehealth/checks_test.go +++ b/internal/instancehealth/checks_test.go @@ -7,9 +7,10 @@ import ( "testing" "time" - "github.com/sourcegraph/sourcegraph/lib/output" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + "github.com/sourcegraph/sourcegraph/lib/output" ) // run with -v for output @@ -23,7 +24,7 @@ func TestCheckPermissionsSyncing(t *testing.T) { }{{ name: "no jobs", instanceHealth: Indicators{ - PermissionsSyncJobs: struct{ Nodes []permissionsSyncJob }{ + PermissionSyncJobs: struct{ Nodes []permissionSyncJob }{ Nodes: nil, }, }, @@ -32,14 +33,14 @@ func TestCheckPermissionsSyncing(t *testing.T) { }, { name: "healthy", instanceHealth: Indicators{ - PermissionsSyncJobs: struct{ Nodes []permissionsSyncJob }{ - Nodes: []permissionsSyncJob{{ - CompletedAt: time.Now(), - Status: "SUCCESS", - Providers: []permissionsProviderStatus{{ - Type: "github", - ID: "https://github.com/", - Status: "SUCCESS", + PermissionSyncJobs: struct{ Nodes []permissionSyncJob }{ + Nodes: []permissionSyncJob{{ + FinishedAt: time.Now(), + State: "SUCCESS", + CodeHostStates: []permissionsProviderStatus{{ + ProviderType: "github", + ProviderID: "https://github.com/", + Status: "SUCCESS", }}, }}, }, @@ -49,15 +50,15 @@ func TestCheckPermissionsSyncing(t *testing.T) { }, { name: "unhealthy", instanceHealth: Indicators{ - PermissionsSyncJobs: struct{ Nodes []permissionsSyncJob }{ - Nodes: []permissionsSyncJob{{ - CompletedAt: time.Now(), - Status: "ERROR", - Message: "oh no!", - Providers: []permissionsProviderStatus{{ - Type: "github", - ID: "https://github.com/", - Status: "ERROR", + PermissionSyncJobs: struct{ Nodes []permissionSyncJob }{ + Nodes: []permissionSyncJob{{ + FinishedAt: time.Now(), + State: "ERROR", + FailureMessage: "oh no!", + CodeHostStates: []permissionsProviderStatus{{ + ProviderType: "github", + ProviderID: "https://github.com/", + Status: "ERROR", }}, }}, }, diff --git a/internal/instancehealth/summary.go b/internal/instancehealth/summary.go index e6320ea057..6996e08659 100644 --- a/internal/instancehealth/summary.go +++ b/internal/instancehealth/summary.go @@ -40,23 +40,23 @@ type Indicators struct { } } } - PermissionsSyncJobs struct { - Nodes []permissionsSyncJob + PermissionSyncJobs struct { + Nodes []permissionSyncJob } } -type permissionsSyncJob struct { - Status string - Message string - CompletedAt time.Time - Providers []permissionsProviderStatus +type permissionSyncJob struct { + State string + FailureMessage string + FinishedAt time.Time + CodeHostStates []permissionsProviderStatus } type permissionsProviderStatus struct { - Type string - ID string - Status string - Message string + ProviderType string + ProviderID string + Status string + Message string } // GetIndicators retrieves summary data from a Sourcegraph instance's GraphQL API for @@ -95,14 +95,14 @@ func GetIndicators(ctx context.Context, client api.Client) (*Indicators, error) } } - permissionsSyncJobs(first:500) { + permissionSyncJobs(first:500) { nodes { - status - completedAt - message - providers { - type - id + state + finishedAt + failureMessage + codeHostStates { + providerType + providerID status message } From f5de12db1c508d379eb6fe5895724a478c4b21eb Mon Sep 17 00:00:00 2001 From: Dax McDonald Date: Wed, 22 Feb 2023 21:37:52 +0100 Subject: [PATCH 300/647] ci: update to actions/checkout@v3 (#908) Co-authored-by: Sourcegraph --- .github/workflows/pr-auditor.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/pr-auditor.yml b/.github/workflows/pr-auditor.yml index 3fe4223315..626ebc4a07 100644 --- a/.github/workflows/pr-auditor.yml +++ b/.github/workflows/pr-auditor.yml @@ -8,7 +8,7 @@ jobs: check-pr: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 with: { repository: 'sourcegraph/sourcegraph' } - uses: actions/setup-go@v2 with: { go-version: '1.18' } From f7f5b1df80c3d56644d6ba5a48b5d8edbde1adba Mon Sep 17 00:00:00 2001 From: Keegan Carruthers-Smith Date: Thu, 23 Feb 2023 08:19:43 +0200 Subject: [PATCH 301/647] servegit: use more performant WalkDir (#938) WalkDir was introduced in go1.16 suits our use case while being more efficient. Test Plan: go test --- internal/servegit/serve.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/servegit/serve.go b/internal/servegit/serve.go index 4e3b99a2f1..ec45103bca 100644 --- a/internal/servegit/serve.go +++ b/internal/servegit/serve.go @@ -5,10 +5,10 @@ import ( "encoding/json" "fmt" "html/template" + "io/fs" "log" "net" "net/http" - "os" "os/exec" pathpkg "path" "path/filepath" @@ -170,7 +170,7 @@ func (s *Serve) Repos() ([]Repo, error) { return nil, nil } - err = filepath.Walk(root, func(path string, fi os.FileInfo, fileErr error) error { + err = filepath.WalkDir(root, func(path string, fi fs.DirEntry, fileErr error) error { if fileErr != nil { s.Info.Printf("WARN: ignoring error searching %s: %v", path, fileErr) return nil From cc0ee590c0201b679abb6cba29bb69dd705c305a Mon Sep 17 00:00:00 2001 From: Jason Hawk Harris Date: Fri, 24 Feb 2023 15:49:31 -0600 Subject: [PATCH 302/647] src validation for ebs-csi drivers and VPCs (#939) * validate ebs-csi drivers on EKS clusters * add condition for failed config * add validation for vpcs * Adds tests for validate VPC * formatting, add comment for EksVpc * fix formatting in kube test * add test for ebs-csi validation and refactor * formatting * remove commented out function signature * checks current context when using --eks flag - Before, validation ran regardless of whether current kubectl context was set to an EKS cluster or not - Now, if --eks flag is added to the command, src checks that an EKS cluster is already configured * formatting * fix ineffectual append that linter flagged * refactor * formatting * retab * Adds more robust testing for ebs csi drivers * remove test copies from kube_test * formatting * retab * add tests and refactor * improve naming conventions to be less confusing and more informative * Update internal/validate/kube/kube.go Co-authored-by: James Cotter <35706755+jac@users.noreply.github.com> * retab * more retabbing * Update internal/validate/kube/eks.go Co-authored-by: Jacob Pleiness * Moved/renamed Eks() function to eks file * formatting --------- Co-authored-by: Jean-Hadrien Chabran Co-authored-by: James Cotter <35706755+jac@users.noreply.github.com> Co-authored-by: Jacob Pleiness --- cmd/src/validate_kube.go | 5 + go.mod | 16 ++ go.sum | 41 ++++ internal/validate/kube/eks.go | 377 +++++++++++++++++++++++++++++ internal/validate/kube/eks_test.go | 335 +++++++++++++++++++++++++ internal/validate/kube/kube.go | 52 +++- 6 files changed, 815 insertions(+), 11 deletions(-) create mode 100644 internal/validate/kube/eks.go create mode 100644 internal/validate/kube/eks_test.go diff --git a/cmd/src/validate_kube.go b/cmd/src/validate_kube.go index 2fab5a760a..c6e5e3b04e 100644 --- a/cmd/src/validate_kube.go +++ b/cmd/src/validate_kube.go @@ -44,6 +44,7 @@ Examples: kubeConfig *string namespace = flagSet.String("namespace", "", "(optional) specify the kubernetes namespace to use") quiet = flagSet.Bool("quiet", false, "(optional) suppress output and return exit status only") + eks = flagSet.Bool("eks", false, "(optional) check EKS cluster") ) if home := homedir.HomeDir(); home != "" { @@ -79,6 +80,10 @@ Examples: options = append(options, kube.Quiet()) } + if *eks { + options = append(options, kube.GenerateAWSClients(context.Background())) + } + return kube.Validate(context.Background(), clientSet, config, options...) } diff --git a/go.mod b/go.mod index e661c3b971..f525ddcf65 100644 --- a/go.mod +++ b/go.mod @@ -4,6 +4,8 @@ go 1.18 require ( cloud.google.com/go/storage v1.28.0 + github.com/aws/aws-sdk-go-v2/config v1.18.13 + github.com/aws/aws-sdk-go-v2/service/eks v1.27.3 github.com/creack/goselect v0.1.2 github.com/derision-test/glock v0.0.0-20210316032053-f5b74334bb29 github.com/dineshappavoo/basex v0.0.0-20170425072625-481a6f6dc663 @@ -44,6 +46,19 @@ require ( github.com/Masterminds/sprig v2.15.0+incompatible // indirect github.com/alecthomas/chroma v0.10.0 // indirect github.com/aokoli/goutils v1.0.1 // indirect + github.com/aws/aws-sdk-go-v2 v1.17.5 // indirect + github.com/aws/aws-sdk-go-v2/credentials v1.13.13 // indirect + github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.12.22 // indirect + github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.29 // indirect + github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.23 // indirect + github.com/aws/aws-sdk-go-v2/internal/ini v1.3.29 // indirect + github.com/aws/aws-sdk-go-v2/service/ec2 v1.86.0 // indirect + github.com/aws/aws-sdk-go-v2/service/iam v1.19.3 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.22 // indirect + github.com/aws/aws-sdk-go-v2/service/sso v1.12.2 // indirect + github.com/aws/aws-sdk-go-v2/service/ssooidc v1.14.2 // indirect + github.com/aws/aws-sdk-go-v2/service/sts v1.18.3 // indirect + github.com/aws/smithy-go v1.13.5 // indirect github.com/aymerick/douceur v0.2.0 // indirect github.com/bufbuild/buf v1.4.0 // indirect github.com/charmbracelet/glamour v0.5.0 // indirect @@ -81,6 +96,7 @@ require ( github.com/jdxcode/netrc v0.0.0-20210204082910-926c7f70242a // indirect github.com/jhump/protocompile v0.0.0-20220216033700-d705409f108f // indirect github.com/jhump/protoreflect v1.12.1-0.20220417024638-438db461d753 // indirect + github.com/jmespath/go-jmespath v0.4.0 // indirect github.com/josharian/intern v1.0.0 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/klauspost/compress v1.15.1 // indirect diff --git a/go.sum b/go.sum index 65fa4f2f78..dc6b6d959b 100644 --- a/go.sum +++ b/go.sum @@ -31,6 +31,42 @@ github.com/aokoli/goutils v1.0.1 h1:7fpzNGoJ3VA8qcrm++XEE1QUe0mIwNeLa02Nwq7RDkg= github.com/aokoli/goutils v1.0.1/go.mod h1:SijmP0QR8LtwsmDs8Yii5Z/S4trXFGFC2oO5g9DP+DQ= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio= +github.com/aws/aws-sdk-go-v2 v1.17.4 h1:wyC6p9Yfq6V2y98wfDsj6OnNQa4w2BLGCLIxzNhwOGY= +github.com/aws/aws-sdk-go-v2 v1.17.4/go.mod h1:uzbQtefpm44goOPmdKyAlXSNcwlRgF3ePWVW6EtJvvw= +github.com/aws/aws-sdk-go-v2 v1.17.5 h1:TzCUW1Nq4H8Xscph5M/skINUitxM5UBAyvm2s7XBzL4= +github.com/aws/aws-sdk-go-v2 v1.17.5/go.mod h1:uzbQtefpm44goOPmdKyAlXSNcwlRgF3ePWVW6EtJvvw= +github.com/aws/aws-sdk-go-v2/config v1.18.13 h1:v0xlYqbO6/EVlM8tUn2QEOA7btQxcgidEq2JRDBPTho= +github.com/aws/aws-sdk-go-v2/config v1.18.13/go.mod h1:r39wGSZB7wPDW1i54JyQXUpc5KsWjh5z/3S5D9eCqDg= +github.com/aws/aws-sdk-go-v2/credentials v1.13.13 h1:zw1KAc1kl00NYd3ofVmFrb09qnYlSQMeh+fmlQRAihI= +github.com/aws/aws-sdk-go-v2/credentials v1.13.13/go.mod h1:DW9nbIIF9MrIja0cBQrUpeWYQMSlNmP8fevLUyF9W38= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.12.22 h1:3aMfcTmoXtTZnaT86QlVaYh+BRMbvrrmZwIQ5jWqCZQ= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.12.22/go.mod h1:YGSIJyQ6D6FjKMQh16hVFSIUD54L4F7zTGePqYMYYJU= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.28 h1:r+XwaCLpIvCKjBIYy/HVZujQS9tsz5ohHG3ZIe0wKoE= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.28/go.mod h1:3lwChorpIM/BhImY/hy+Z6jekmN92cXGPI1QJasVPYY= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.29 h1:9/aKwwus0TQxppPXFmf010DFrE+ssSbzroLVYINA+xE= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.29/go.mod h1:Dip3sIGv485+xerzVv24emnjX5Sg88utCL8fwGmCeWg= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.22 h1:7AwGYXDdqRQYsluvKFmWoqpcOQJ4bH634SkYf3FNj/A= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.22/go.mod h1:EqK7gVrIGAHyZItrD1D8B0ilgwMD1GiWAmbU4u/JHNk= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.23 h1:b/Vn141DBuLVgXbhRWIrl9g+ww7G+ScV5SzniWR13jQ= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.23/go.mod h1:mr6c4cHC+S/MMkrjtSlG4QA36kOznDep+0fga5L/fGQ= +github.com/aws/aws-sdk-go-v2/internal/ini v1.3.29 h1:J4xhFd6zHhdF9jPP0FQJ6WknzBboGMBNjKOv4iTuw4A= +github.com/aws/aws-sdk-go-v2/internal/ini v1.3.29/go.mod h1:TwuqRBGzxjQJIwH16/fOZodwXt2Zxa9/cwJC5ke4j7s= +github.com/aws/aws-sdk-go-v2/service/ec2 v1.86.0 h1:4dt0Mg5veHbMLcA2JAR9LDxvqXjtG0ZLQdxZG/2wHy4= +github.com/aws/aws-sdk-go-v2/service/ec2 v1.86.0/go.mod h1:jK4MhMMe6HIe4qnjGaQqQQECcsxRZ0q86oCq06T8IEE= +github.com/aws/aws-sdk-go-v2/service/eks v1.27.3 h1:jlh0AJVhauqSGaiwRJx4j0LNBGEAaGn46sA1XJyTj0E= +github.com/aws/aws-sdk-go-v2/service/eks v1.27.3/go.mod h1:S30WtE6uWErcppqG9Rl03MATEFYsm0vnDyxPUKmmCqU= +github.com/aws/aws-sdk-go-v2/service/iam v1.19.3 h1:vaDXu/p/5RNK++B2pqKS3hwsWGxsVjJJqPaAMg0OkiM= +github.com/aws/aws-sdk-go-v2/service/iam v1.19.3/go.mod h1:F5Xt96+AfAiyMpRXHy9CKafE/KULVwj7MwgZ0a4row4= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.22 h1:LjFQf8hFuMO22HkV5VWGLBvmCLBCLPivUAmpdpnp4Vs= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.22/go.mod h1:xt0Au8yPIwYXf/GYPy/vl4K3CgwhfQMYbrH7DlUUIws= +github.com/aws/aws-sdk-go-v2/service/sso v1.12.2 h1:EN102fWY7hI5u/2FPheTrwwMHkSXfl49RYkeEnJsrCU= +github.com/aws/aws-sdk-go-v2/service/sso v1.12.2/go.mod h1:IgV8l3sj22nQDd5qcAGY0WenwCzCphqdbFOpfktZPrI= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.14.2 h1:f1lmlce7r13CX1BPyPqt9oh/H+uqOWc9367lDoGGwNQ= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.14.2/go.mod h1:O1YSOg3aekZibh2SngvCRRG+cRHKKlYgxf/JBF/Kr/k= +github.com/aws/aws-sdk-go-v2/service/sts v1.18.3 h1:s49mSnsBZEXjfGBkRfmK+nPqzT7Lt3+t2SmAKNyHblw= +github.com/aws/aws-sdk-go-v2/service/sts v1.18.3/go.mod h1:b+psTJn33Q4qGoDaM7ZiOVVG8uVjGI6HaZ8WBHdgDgU= +github.com/aws/smithy-go v1.13.5 h1:hgz0X/DX0dGqTYpGALqXJoRKRj5oQ7150i5FdTePzO8= +github.com/aws/smithy-go v1.13.5/go.mod h1:Tg+OJXh4MB2R/uN61Ko2f6hTZwB/ZYGOtib8J3gBHzA= github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk= github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4= github.com/aymerick/raymond v2.0.3-0.20180322193309-b565731e1464+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g= @@ -175,6 +211,7 @@ github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck= @@ -237,6 +274,10 @@ github.com/jhump/protoreflect v1.12.1-0.20220417024638-438db461d753 h1:uFlcJKZPL github.com/jhump/protoreflect v1.12.1-0.20220417024638-438db461d753/go.mod h1:JytZfP5d0r8pVNLZvai7U/MCuTWITgrI4tTg7puQFKI= github.com/jig/teereadcloser v0.0.0-20181016160506-953720c48e05 h1:dSwwtWuwMyarzsbVWOq4QJ8xVy9wgcNomvWyGtrKe+E= github.com/jig/teereadcloser v0.0.0-20181016160506-953720c48e05/go.mod h1:sRUFlj+HCejvoCRpuhU0EYnNw5FG+YJpz8UFfCf0F2U= +github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg= +github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= +github.com/jmespath/go-jmespath/internal/testify v1.5.1 h1:shLQSRRSCCPj3f2gpwzGwWFoC7ycTf1rcQZHOlsJ6N8= +github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= diff --git a/internal/validate/kube/eks.go b/internal/validate/kube/eks.go new file mode 100644 index 0000000000..9bf102f478 --- /dev/null +++ b/internal/validate/kube/eks.go @@ -0,0 +1,377 @@ +package kube + +import ( + "context" + "fmt" + "log" + "path/filepath" + "reflect" + "strings" + + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/client-go/kubernetes" + "k8s.io/client-go/tools/clientcmd" + "k8s.io/client-go/util/homedir" + + "github.com/aws/aws-sdk-go-v2/config" + "github.com/aws/aws-sdk-go-v2/service/ec2" + "github.com/aws/aws-sdk-go-v2/service/ec2/types" + "github.com/aws/aws-sdk-go-v2/service/eks" + "github.com/aws/aws-sdk-go-v2/service/iam" + "github.com/sourcegraph/src-cli/internal/validate" + + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +type EbsTestObjects struct { + addons []string + serviceAccount *corev1.ServiceAccount + serviceAccountRole string + ebsRolePolicy RolePolicy +} + +type RolePolicy struct { + PolicyName *string + PolicyArn *string +} + +func GenerateAWSClients(ctx context.Context) Option { + eksConfig, err := config.LoadDefaultConfig(ctx) + if err != nil { + log.Printf("error while loading config: %s\n", err) + } + + ec2Config, err := config.LoadDefaultConfig(ctx) + if err != nil { + log.Printf("error while loading config: %s\n", err) + } + + iamConfig, err := config.LoadDefaultConfig(ctx) + if err != nil { + log.Printf("error while loading config: %s\n", err) + } + + return func(config *Config) { + config.eks = true + config.eksClient = eks.NewFromConfig(eksConfig) + config.ec2Client = ec2.NewFromConfig(ec2Config) + config.iamClient = iam.NewFromConfig(iamConfig) + } +} + +func EksVpc(ctx context.Context, config *Config) ([]validate.Result, error) { + var results []validate.Result + if config.ec2Client == nil { + results = append(results, validate.Result{ + Status: validate.Failure, + Message: "EKS: validate VPC failed", + }) + } + + inputs := &ec2.DescribeVpcsInput{} + outputs, err := config.ec2Client.DescribeVpcs(ctx, inputs) + + if err != nil { + results = append(results, validate.Result{ + Status: validate.Failure, + Message: "EKS: Validate VPC failed", + }) + + return results, nil + } + + if len(outputs.Vpcs) == 0 { + results = append(results, validate.Result{ + Status: validate.Failure, + Message: "EKS: Validate VPC failed: No VPC configured", + }) + + return results, nil + } + + for _, vpc := range outputs.Vpcs { + r := validateVpc(&vpc) + results = append(results, r...) + } + + return results, nil +} + +func validateVpc(vpc *types.Vpc) (result []validate.Result) { + state := vpc.State + + if state == "available" { + result = append(result, validate.Result{ + Status: validate.Success, + Message: "VPC is validated", + }) + + return result + } + + result = append(result, validate.Result{ + Status: validate.Failure, + Message: "vpc.State stuck in pending state", + }) + + return result +} + +func EksEbsCsiDrivers(ctx context.Context, config *Config) ([]validate.Result, error) { + var results []validate.Result + var ebsTestParams EbsTestObjects + + addons, err := getAddons(ctx, config.eksClient) + if err != nil { + results = append(results, validate.Result{ + Status: validate.Failure, + Message: "EKS: could not validate ebs in addons", + }) + + return results, err + } + + ebsServiceAccount, err := getEBSServiceAccount(ctx, config.clientSet) + if err != nil { + results = append(results, validate.Result{ + Status: validate.Failure, + Message: "EKS: could not validate ebs service account", + }) + + return results, err + } + + ebsServiceAccountRole, err := getEBSServiceAccountRole(ebsServiceAccount) + if err != nil { + results = append(results, validate.Result{ + Status: validate.Failure, + Message: "EKS: could not validate ebs service account attached to role", + }) + + return results, err + } + + ebsRolePolicy, err := getEBSCSIPolicy(ctx, config.iamClient, ebsServiceAccountRole) + if err != nil { + results = append(results, validate.Result{ + Status: validate.Failure, + Message: "EKS: could not validate ebs role policy", + }) + + return results, err + } + + ebsTestParams.addons = addons + ebsTestParams.serviceAccount = ebsServiceAccount + ebsTestParams.serviceAccountRole = ebsServiceAccountRole + ebsTestParams.ebsRolePolicy = ebsRolePolicy + + result := validateEbsCsiDrivers(ebsTestParams) + results = append(results, result...) + + return results, nil +} + +func validateEbsCsiDrivers(testers EbsTestObjects) (result []validate.Result) { + result = append(result, validateAddons(testers.addons)...) + result = append(result, validateServiceAccount(testers.serviceAccount)...) + result = append(result, validateServiceAccountRole(testers.serviceAccountRole)...) + result = append(result, validateRolePolicy(testers.ebsRolePolicy)...) + + return 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 + } + } + + result = append(result, validate.Result{ + Status: validate.Failure, + Message: "EKS: no 'aws-ebs-csi-driver' present in addons", + }) + + return result +} + +func validateServiceAccount(serviceAccount *corev1.ServiceAccount) (result []validate.Result) { + if serviceAccount.Name == "ebs-csi-controller-sa" { + result = append(result, validate.Result{ + Status: validate.Success, + Message: "EKS: 'ebs-csi-controller-sa' present on cluster", + }) + return result + } + + result = append(result, validate.Result{ + Status: validate.Failure, + Message: "EKS: no 'ebs-csi-controller-sa' present on cluster", + }) + + return result +} + +func validateServiceAccountRole(serviceAccountRole string) (result []validate.Result) { + if serviceAccountRole != "" { + result = append(result, validate.Result{ + Status: validate.Success, + Message: "EKS: role attached to 'ebs-csi-controller-sa' service account", + }) + return result + } + + result = append(result, validate.Result{ + Status: validate.Failure, + Message: "EKS: no role attached to 'ebs-csi-controller-sa' service account", + }) + + return result +} + +func validateRolePolicy(rolePolicy RolePolicy) (result []validate.Result) { + if *rolePolicy.PolicyName == "AmazonEBSCSIDriverPolicy" { + result = append(result, validate.Result{ + Status: validate.Success, + Message: "EKS: 'AmazonEBSCSIDriverPolicy' bound to role", + }) + + return result + } + + result = append(result, validate.Result{ + Status: validate.Failure, + Message: "EKS: no 'AmazonEBSCSIDriverPolicy' bound to role", + }) + + return result +} + +func CurrentContextSetToEKSCluster() error { + home := homedir.HomeDir() + pathToKubeConfig := filepath.Join(home, ".kube", "config") + + config, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig( + &clientcmd.ClientConfigLoadingRules{ExplicitPath: pathToKubeConfig}, + &clientcmd.ConfigOverrides{ + CurrentContext: "", + }).RawConfig() + + if err != nil { + return err + } + + got := strings.Split(config.CurrentContext, ":") + want := []string{"arn", "aws", "eks"} + + if len(got) >= 3 { + got = got[:3] + if reflect.DeepEqual(got, want) { + return nil + } + } + + return errors.New("no eks cluster configured") +} + +func getAddons(ctx context.Context, client *eks.Client) ([]string, error) { + clusterName := getClusterName(ctx, client) + inputs := &eks.ListAddonsInput{ClusterName: clusterName} + outputs, err := client.ListAddons(ctx, inputs) + + if err != nil { + return nil, err + } + + return outputs.Addons, nil +} + +func getEBSServiceAccount(ctx context.Context, client *kubernetes.Clientset) (*corev1.ServiceAccount, error) { + serviceAccounts := client.CoreV1().ServiceAccounts("kube-system") + ebsSA, err := serviceAccounts.Get( + ctx, + "ebs-csi-controller-sa", + metav1.GetOptions{}, + ) + + if err != nil { + return nil, err + } + + return ebsSA, nil +} + +func getEBSServiceAccountRole(sa *corev1.ServiceAccount) (string, error) { + annotations := sa.GetAnnotations() + if _, ok := annotations["eks.amazonaws.com/role-arn"]; !ok { + return "", errors.Newf( + "%s no role attached to service account", + validate.FailureEmoji, + ) + } + + roleArn := strings.Split(annotations["eks.amazonaws.com/role-arn"], "/") + if len(roleArn) != 2 { + return "", errors.Newf( + "%s value of 'eks.amazonaws.com/role-arn' invalid", + validate.FailureEmoji, + ) + } + + ebsControllerSA := roleArn[1] + return ebsControllerSA, nil +} + +// getEbsCSIPolicy +func getEBSCSIPolicy(ctx context.Context, client *iam.Client, sa string) (RolePolicy, error) { + inputs := iam.ListAttachedRolePoliciesInput{RoleName: &sa} + outputs, err := client.ListAttachedRolePolicies(ctx, &inputs) + + if err != nil { + return RolePolicy{}, err + } + + if len(outputs.AttachedPolicies) == 0 { + return RolePolicy{}, nil + } + + var policyName *string + for _, policy := range outputs.AttachedPolicies { + policyName = policy.PolicyName + if *policyName == "AmazonEBSCSIDriverPolicy" { + return RolePolicy{ + PolicyName: policy.PolicyName, + PolicyArn: policy.PolicyArn, + }, nil + } + } + + return RolePolicy{}, nil +} + +func getClusterName(ctx context.Context, client *eks.Client) *string { + home := homedir.HomeDir() + pathToKubeConfig := filepath.Join(home, ".kube", "config") + + config, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig( + &clientcmd.ClientConfigLoadingRules{ExplicitPath: pathToKubeConfig}, + &clientcmd.ConfigOverrides{ + CurrentContext: "", + }).RawConfig() + + if err != nil { + fmt.Printf("error while checking current context: %s\n", err) + return nil + } + + currentContext := strings.Split(config.CurrentContext, "/") + clusterName := currentContext[len(currentContext)-1] + + return &clusterName +} diff --git a/internal/validate/kube/eks_test.go b/internal/validate/kube/eks_test.go new file mode 100644 index 0000000000..f008034669 --- /dev/null +++ b/internal/validate/kube/eks_test.go @@ -0,0 +1,335 @@ +package kube + +import ( + "testing" + + "github.com/aws/aws-sdk-go-v2/service/ec2/types" + "github.com/aws/aws-sdk-go-v2/service/eks" + "github.com/aws/aws-sdk-go-v2/service/iam" + iamTypes "github.com/aws/aws-sdk-go-v2/service/iam/types" + "github.com/sourcegraph/src-cli/internal/validate" + corev1 "k8s.io/api/core/v1" +) + +func TestValidateVpc(t *testing.T) { + cases := []struct { + name string + vpc func(vpc *types.Vpc) + result []validate.Result + }{ + { + name: "valid vpc", + vpc: func(vpc *types.Vpc) { + vpc.State = "available" + }, + result: []validate.Result{ + { + Status: validate.Success, + Message: "VPC is validated", + }, + }, + }, + { + name: "invalid vpc: pending", + vpc: func(vpc *types.Vpc) { + vpc.State = "pending" + }, + result: []validate.Result{ + { + Status: validate.Failure, + Message: "vpc.State stuck in pending state", + }, + }, + }, + } + + for _, tc := range cases { + tc := tc + t.Run(tc.name, func(t *testing.T) { + vpc := testVPC() + if tc.vpc != nil { + tc.vpc(vpc) + } + result := validateVpc(vpc) + + // test should error + if len(tc.result) > 0 { + if result == nil { + t.Fatal("validate should return result") + return + } + if result[0].Status != tc.result[0].Status { + t.Errorf( + "result status\nwant: %v\n got: %v", + tc.result[0].Status, + result[0].Status, + ) + } + if result[0].Message != tc.result[0].Message { + t.Errorf( + "result msg\nwant: %s\n got: %s", + tc.result[0].Message, + result[0].Message, + ) + } + return + } + + // test should not error + if result != nil { + t.Fatalf("ValidateService error: %v", result) + } + }) + } +} + +func TestValidateAddons(t *testing.T) { + cases := []struct { + name string + addons func(addons *eks.ListAddonsOutput) + result []validate.Result + }{ + { + name: "should pass if 'aws-ebs-csi-driver' present in addons", + addons: func(addonsOutput *eks.ListAddonsOutput) { + addonsOutput.Addons = append(addonsOutput.Addons, "aws-ebs-csi-driver") + }, + result: []validate.Result{ + { + Status: validate.Success, + Message: "EKS: 'aws-ebs-csi-driver' present in addons", + }, + }, + }, + { + name: "should fail if 'aws-ebs-csi-driver' not present in addons", + addons: func(addons *eks.ListAddonsOutput) {}, + result: []validate.Result{ + { + Status: validate.Failure, + Message: "EKS: no 'aws-ebs-csi-driver' present in addons", + }, + }, + }, + } + + for _, tc := range cases { + tc := tc + t.Run(tc.name, func(t *testing.T) { + addons := testAddonOutput() + if tc.addons != nil { + tc.addons(addons) + } + result := validateAddons(addons.Addons) + + // test should error + if len(tc.result) > 0 { + if result == nil { + t.Fatal("validate should return result") + return + } + if result[0].Status != tc.result[0].Status { + t.Errorf( + "result status\nwant: %v\n got: %v", + tc.result[0].Status, + result[0].Status, + ) + } + if result[0].Message != tc.result[0].Message { + t.Errorf( + "result msg\nwant: %s\n got: %s", + tc.result[0].Message, + result[0].Message, + ) + } + return + } + + // test should not error + if result != nil { + t.Fatalf("ValidateService error: %v", result) + } + }) + } +} + +func TestValidateServiceAccount(t *testing.T) { + cases := []struct { + name string + sa func(sa *corev1.ServiceAccount) + result []validate.Result + }{ + { + name: "should pass if 'ebs-csi-controller-sa' present on cluster", + sa: func(sa *corev1.ServiceAccount) { + sa.ObjectMeta.Name = "ebs-csi-controller-sa" + sa.ObjectMeta.Namespace = "kube-system" + }, + result: []validate.Result{ + { + Status: validate.Success, + Message: "EKS: 'ebs-csi-controller-sa' present on cluster", + }, + }, + }, + { + name: "should fail if 'ebs-csi-controller-sa' not present on cluster", + sa: func(sa *corev1.ServiceAccount) {}, + result: []validate.Result{ + { + Status: validate.Failure, + Message: "EKS: no 'ebs-csi-controller-sa' present on cluster", + }, + }, + }, + } + + for _, tc := range cases { + tc := tc + t.Run(tc.name, func(t *testing.T) { + sa := testServiceAccount() + if tc.sa != nil { + tc.sa(sa) + } + result := validateServiceAccount(sa) + + // test should error + if len(tc.result) > 0 { + if result == nil { + t.Fatal("validate should return result") + return + } + if result[0].Status != tc.result[0].Status { + t.Errorf( + "result status\nwant: %v\n got: %v", + tc.result[0].Status, + result[0].Status, + ) + } + if result[0].Message != tc.result[0].Message { + t.Errorf( + "result msg\nwant: %s\n got: %s", + tc.result[0].Message, + result[0].Message, + ) + } + return + } + + // test should not error + if result != nil { + t.Fatalf("ValidateService error: %v", result) + } + }) + } +} + +func TestValidateRolePolicy(t *testing.T) { + cases := []struct { + name string + rp func(rp *iam.ListAttachedRolePoliciesOutput) + result []validate.Result + }{ + { + name: "should pass if 'AmazonEBSCSIDriverPolicy' bound to role", + rp: func(rp *iam.ListAttachedRolePoliciesOutput) { + AmazonEBSCSIDriverPolicy := "AmazonEBSCSIDriverPolicy" + rp.AttachedPolicies = append(rp.AttachedPolicies, iamTypes.AttachedPolicy{ + PolicyName: &AmazonEBSCSIDriverPolicy, + }) + }, + result: []validate.Result{ + { + Status: validate.Success, + Message: "EKS: 'AmazonEBSCSIDriverPolicy' bound to role", + }, + }, + }, + { + name: "should fail if 'AmazonEBSCSIDriverPolicy' not bound to role", + rp: func(rp *iam.ListAttachedRolePoliciesOutput) {}, + result: []validate.Result{ + { + Status: validate.Failure, + Message: "EKS: no 'AmazonEBSCSIDriverPolicy' bound to role", + }, + }, + }, + } + + for _, tc := range cases { + tc := tc + t.Run(tc.name, func(t *testing.T) { + rp := testEBSCSIRole() + if tc.rp != nil { + tc.rp(rp) + } + + var result []validate.Result + + if len(rp.AttachedPolicies) == 0 { + shouldFail := "should fail" + result = validateRolePolicy(RolePolicy{ + PolicyName: &shouldFail, + PolicyArn: &shouldFail, + }) + } else { + rolePolicy := RolePolicy{ + PolicyName: rp.AttachedPolicies[0].PolicyName, + PolicyArn: rp.AttachedPolicies[0].PolicyArn, + } + + result = validateRolePolicy(rolePolicy) + } + + // test should error + if len(tc.result) > 0 { + if result == nil { + t.Fatal("validate should return result") + return + } + if result[0].Status != tc.result[0].Status { + t.Errorf( + "result status\nwant: %v\n got: %v", + tc.result[0].Status, + result[0].Status, + ) + } + if result[0].Message != tc.result[0].Message { + t.Errorf( + "result msg\nwant: %s\n got: %s", + tc.result[0].Message, + result[0].Message, + ) + } + return + } + + // test should not error + if result != nil { + t.Fatalf("ValidateService error: %v", result) + } + }) + } +} + +// helpers +func testVPC() *types.Vpc { + return &types.Vpc{ + State: "available", + } +} + +func testAddonOutput() *eks.ListAddonsOutput { + return &eks.ListAddonsOutput{} +} + +func testServiceAccount() *corev1.ServiceAccount { + return &corev1.ServiceAccount{} +} + +func testEBSCSIRole() *iam.ListAttachedRolePoliciesOutput { + return &iam.ListAttachedRolePoliciesOutput{ + AttachedPolicies: []iamTypes.AttachedPolicy{}, + } +} diff --git a/internal/validate/kube/kube.go b/internal/validate/kube/kube.go index 6a59dd016c..2f41a68a4d 100644 --- a/internal/validate/kube/kube.go +++ b/internal/validate/kube/kube.go @@ -16,6 +16,9 @@ import ( "k8s.io/client-go/rest" "k8s.io/client-go/tools/remotecommand" + "github.com/aws/aws-sdk-go-v2/service/ec2" + "github.com/aws/aws-sdk-go-v2/service/eks" + "github.com/aws/aws-sdk-go-v2/service/iam" "github.com/sourcegraph/src-cli/internal/validate" "github.com/sourcegraph/sourcegraph/lib/errors" @@ -35,6 +38,10 @@ type Config struct { exitStatus bool clientSet *kubernetes.Clientset restConfig *rest.Config + eks bool + eksClient *eks.Client + ec2Client *ec2.Client + iamClient *iam.Client } func WithNamespace(namespace string) Option { @@ -50,41 +57,64 @@ func Quiet() Option { } } -type validation func(ctx context.Context, config *Config) ([]validate.Result, error) +type validation struct { + Validate func(ctx context.Context, config *Config) ([]validate.Result, error) + WaitMsg string + SuccessMsg string + ErrMsg string +} // Validate will call a series of validation functions in a table driven tests style. func Validate(ctx context.Context, clientSet *kubernetes.Clientset, restConfig *rest.Config, opts ...Option) error { - config := &Config{ + cfg := &Config{ namespace: "default", output: os.Stdout, exitStatus: false, clientSet: clientSet, restConfig: restConfig, + eks: false, } for _, opt := range opts { - opt(config) + opt(cfg) } - log.SetOutput(config.output) + log.SetOutput(cfg.output) - var validations = []struct { - Validate validation - WaitMsg string - SuccessMsg string - ErrMsg string - }{ + validations := []validation{ {Pods, "validating pods", "pods validated", "validating pods failed"}, {Services, "validating services", "services validated", "validating services failed"}, {PVCs, "validating pvcs", "pvcs validated", "validating pvcs failed"}, {Connections, "validating connections", "connections validated", "validating connections failed"}, } + if cfg.eks { + if err := CurrentContextSetToEKSCluster(); err != nil { + return errors.Newf("%s %s", validate.FailureEmoji, err) + } + + GenerateAWSClients(ctx) + + validations = append(validations, validation{ + Validate: EksEbsCsiDrivers, + WaitMsg: "EKS: validating ebs-csi drivers", + SuccessMsg: "EKS: ebs-csi drivers validated", + ErrMsg: "EKS: validating ebs-csi drivers failed", + }) + + validations = append(validations, validation{ + Validate: EksVpc, + WaitMsg: "EKS: validating vpc", + SuccessMsg: "EKS: vpc validated", + ErrMsg: "EKS: validating vpc failed", + }) + } + var totalFailCount int for _, v := range validations { log.Printf("%s %s...", validate.HourglassEmoji, v.WaitMsg) - results, err := v.Validate(ctx, config) + results, err := v.Validate(ctx, cfg) if err != nil { return errors.Wrapf(err, v.ErrMsg) } From 9a46c5e67360672c843c2440e78629de0064ac71 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Sun, 26 Feb 2023 00:58:43 +0100 Subject: [PATCH 303/647] Teams CLI interface (#922) This implements a CLI interface for managing/ingesting teams into Sourcegraph. --- cmd/src/main.go | 1 + cmd/src/team_members_list.go | 111 +++++++++++++++++++++++++++ cmd/src/teams.go | 59 +++++++++++++++ cmd/src/teams_create.go | 96 +++++++++++++++++++++++ cmd/src/teams_delete.go | 74 ++++++++++++++++++ cmd/src/teams_list.go | 130 ++++++++++++++++++++++++++++++++ cmd/src/teams_members.go | 55 ++++++++++++++ cmd/src/teams_members_add.go | 108 ++++++++++++++++++++++++++ cmd/src/teams_members_remove.go | 108 ++++++++++++++++++++++++++ cmd/src/teams_update.go | 92 ++++++++++++++++++++++ cmd/src/users_get.go | 16 +++- 11 files changed, 847 insertions(+), 3 deletions(-) create mode 100644 cmd/src/team_members_list.go create mode 100644 cmd/src/teams.go create mode 100644 cmd/src/teams_create.go create mode 100644 cmd/src/teams_delete.go create mode 100644 cmd/src/teams_list.go create mode 100644 cmd/src/teams_members.go create mode 100644 cmd/src/teams_members_add.go create mode 100644 cmd/src/teams_members_remove.go create mode 100644 cmd/src/teams_update.go diff --git a/cmd/src/main.go b/cmd/src/main.go index 9e63c49762..177a622672 100644 --- a/cmd/src/main.go +++ b/cmd/src/main.go @@ -41,6 +41,7 @@ The commands are: login authenticate to a Sourcegraph instance with your user credentials lsif manages LSIF data (deprecated: use 'code-intel') orgs,org manages organizations + teams,team manages teams repos,repo manages repositories search search for results on Sourcegraph serve-git serves your local git repositories over HTTP for Sourcegraph to pull diff --git a/cmd/src/team_members_list.go b/cmd/src/team_members_list.go new file mode 100644 index 0000000000..0090c88312 --- /dev/null +++ b/cmd/src/team_members_list.go @@ -0,0 +1,111 @@ +package main + +import ( + "context" + "encoding/json" + "flag" + "fmt" + "os" + + "github.com/sourcegraph/sourcegraph/lib/errors" + + "github.com/sourcegraph/src-cli/internal/api" +) + +func init() { + usage := ` +Examples: + + List team members: + + $ src team members list -name= + + List team members whose names match the query: + + $ src team members list -name= -query='myquery' +` + + flagSet := flag.NewFlagSet("list", flag.ExitOnError) + usageFunc := func() { + fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src team members %s':\n", flagSet.Name()) + flagSet.PrintDefaults() + fmt.Println(usage) + } + var ( + nameFlag = flagSet.String("name", "", "The team of which to return members") + firstFlag = flagSet.Int("first", 1000, "Returns the first n teams from the list") + queryFlag = flagSet.String("query", "", `Returns teams whose name or displayname match the query. (e.g. "engineering")`) + formatFlag = flagSet.String("f", "{{.Username}}", `Format for the output, using the syntax of Go package text/template. (e.g. "{{.Name}}: {{.DisplayName}}" or "{{.|json}}")`) + jsonFlag = flagSet.Bool("json", false, `Format for the output as json`) + apiFlags = api.NewFlags(flagSet) + ) + + handler := func(args []string) error { + if err := flagSet.Parse(args); err != nil { + return err + } + + if *nameFlag == "" { + return errors.New("must provide -name") + } + + tmpl, err := parseTemplate(*formatFlag) + if err != nil { + return err + } + + client := cfg.apiClient(apiFlags, flagSet.Output()) + + query := `query TeamMembers( + $name: String!, + $first: Int, + $search: String +) { + team(name: $name) { + members ( + first: $first, + search: $search + ) { + nodes { + ...TeamMemberFields + } + } + } +} +` + teamMemberFragment + + var result struct { + Team struct { + Members struct { + Nodes []TeamMember + } + } + } + if ok, err := client.NewRequest(query, map[string]interface{}{ + "name": *nameFlag, + "first": api.NullInt(*firstFlag), + "search": api.NullString(*queryFlag), + }).Do(context.Background(), &result); err != nil || !ok { + return err + } + + if jsonFlag != nil && *jsonFlag { + json.NewEncoder(os.Stdout).Encode(result.Team.Members.Nodes) + return nil + } + + for _, t := range result.Team.Members.Nodes { + if err := execTemplate(tmpl, t); err != nil { + return err + } + } + return nil + } + + // Register the command. + teamMembersCommands = append(teamMembersCommands, &command{ + flagSet: flagSet, + handler: handler, + usageFunc: usageFunc, + }) +} diff --git a/cmd/src/teams.go b/cmd/src/teams.go new file mode 100644 index 0000000000..98708dc1ee --- /dev/null +++ b/cmd/src/teams.go @@ -0,0 +1,59 @@ +package main + +import ( + "flag" + "fmt" +) + +var teamsCommands commander + +func init() { + usage := `'src teams' is a tool that manages teams in a Sourcegraph instance. + +Usage: + + src teams command [command options] + +The commands are: + + list lists teams + create create a team + update update a team + delete delete a team + members manage team members, use "src teams members [command] -h" for more information. + +Use "src teams [command] -h" for more information about a command. +` + + flagSet := flag.NewFlagSet("teams", flag.ExitOnError) + handler := func(args []string) error { + teamsCommands.run(flagSet, "src teams", usage, args) + return nil + } + + // Register the command. + commands = append(commands, &command{ + flagSet: flagSet, + aliases: []string{"team"}, + handler: handler, + usageFunc: func() { + fmt.Println(usage) + }, + }) +} + +const teamFragment = ` +fragment TeamFields on Team { + id + name + displayName + readonly +} +` + +type Team struct { + ID string `json:"id"` + Name string `json:"name"` + DisplayName string `json:"displayName"` + Readonly bool `json:"readonly"` +} diff --git a/cmd/src/teams_create.go b/cmd/src/teams_create.go new file mode 100644 index 0000000000..013d204efa --- /dev/null +++ b/cmd/src/teams_create.go @@ -0,0 +1,96 @@ +package main + +import ( + "context" + "flag" + "fmt" + "strings" + + "github.com/sourcegraph/sourcegraph/lib/errors" + + "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/cmderrors" +) + +func init() { + usage := ` +Examples: + + Create a team "engineering": + + $ src teams create -name='engineering' [-display-name='Engineering Team'] [-parent-team='engineering-leadership'] [-read-only] + +` + + flagSet := flag.NewFlagSet("create", flag.ExitOnError) + usageFunc := func() { + fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src teams %s':\n", flagSet.Name()) + flagSet.PrintDefaults() + fmt.Println(usage) + } + var ( + nameFlag = flagSet.String("name", "", "The team name") + displayNameFlag = flagSet.String("display-name", "", "Optional additional display name for a more human-readable UI") + parentTeamFlag = flagSet.String("parent-team", "", "Optional name or ID of the parent team") + readonlyFlag = flagSet.Bool("read-only", false, "Optionally create the team as read-only marking it as externally managed in this UI") + apiFlags = api.NewFlags(flagSet) + ) + + handler := func(args []string) error { + if err := flagSet.Parse(args); err != nil { + return err + } + + if *nameFlag == "" { + return errors.New("provide a name") + } + + client := cfg.apiClient(apiFlags, flagSet.Output()) + + query := `mutation CreateTeam( + $name: String!, + $displayName: String, + $parentTeam: String, + $readonly: Boolean +) { + createTeam( + name: $name, + displayName: $displayName, + parentTeamName: $parentTeam, + readonly: $readonly, + ) { + ...TeamFields + } +} +` + teamFragment + + var result struct { + CreateTeam Team + } + if ok, err := client.NewRequest(query, map[string]interface{}{ + "name": *nameFlag, + "displayName": api.NullString(*displayNameFlag), + "parentTeam": api.NullString(*parentTeamFlag), + "readonly": *readonlyFlag, + }).Do(context.Background(), &result); err != nil || !ok { + var gqlErr api.GraphQlErrors + if errors.As(err, &gqlErr) { + for _, e := range gqlErr { + if strings.Contains(e.Error(), "team name is already taken") { + return cmderrors.ExitCode(3, err) + } + } + } + return err + } + + return nil + } + + // Register the command. + teamsCommands = append(teamsCommands, &command{ + flagSet: flagSet, + handler: handler, + usageFunc: usageFunc, + }) +} diff --git a/cmd/src/teams_delete.go b/cmd/src/teams_delete.go new file mode 100644 index 0000000000..df667204c3 --- /dev/null +++ b/cmd/src/teams_delete.go @@ -0,0 +1,74 @@ +package main + +import ( + "context" + "flag" + "fmt" + + "github.com/sourcegraph/sourcegraph/lib/errors" + + "github.com/sourcegraph/src-cli/internal/api" +) + +func init() { + usage := ` +Examples: + + Delete the team "engineering": + + $ src teams delete -name='engineering' + +` + + flagSet := flag.NewFlagSet("delete", flag.ExitOnError) + usageFunc := func() { + fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src teams %s':\n", flagSet.Name()) + flagSet.PrintDefaults() + fmt.Println(usage) + } + var ( + nameFlag = flagSet.String("name", "", "The team name") + apiFlags = api.NewFlags(flagSet) + ) + + handler := func(args []string) error { + if err := flagSet.Parse(args); err != nil { + return err + } + + if *nameFlag == "" { + return errors.New("provide a name") + } + + client := cfg.apiClient(apiFlags, flagSet.Output()) + + query := `mutation DeleteTeam( + $name: String!, +) { + deleteTeam( + name: $name, + ) { + alwaysNil + } +} +` + + var result struct { + DeleteTeam any + } + if ok, err := client.NewRequest(query, map[string]interface{}{ + "name": *nameFlag, + }).Do(context.Background(), &result); err != nil || !ok { + return err + } + + return nil + } + + // Register the command. + teamsCommands = append(teamsCommands, &command{ + flagSet: flagSet, + handler: handler, + usageFunc: usageFunc, + }) +} diff --git a/cmd/src/teams_list.go b/cmd/src/teams_list.go new file mode 100644 index 0000000000..8ba98a7bd1 --- /dev/null +++ b/cmd/src/teams_list.go @@ -0,0 +1,130 @@ +package main + +import ( + "context" + "encoding/json" + "flag" + "fmt" + "os" + + "github.com/sourcegraph/src-cli/internal/api" +) + +func init() { + usage := ` +Examples: + + List teams: + + $ src teams list + + List teams whose names match the query: + + $ src teams list -query='myquery' +` + + flagSet := flag.NewFlagSet("list", flag.ExitOnError) + usageFunc := func() { + fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src teams %s':\n", flagSet.Name()) + flagSet.PrintDefaults() + fmt.Println(usage) + } + var ( + firstFlag = flagSet.Int("first", 1000, "Returns the first n teams from the list") + parentTeamFlag = flagSet.String("parent-team", "", "Get child teams of the given team") + queryFlag = flagSet.String("query", "", `Returns teams whose name or displayname match the query. (e.g. "engineering")`) + formatFlag = flagSet.String("f", "{{.Name}} {{if .DisplayName}}({{.DisplayName}}){{end}}", `Format for the output, using the syntax of Go package text/template. (e.g. "{{.Name}}: {{.DisplayName}}" or "{{.|json}}")`) + jsonFlag = flagSet.Bool("json", false, `Format for the output as json`) + apiFlags = api.NewFlags(flagSet) + ) + + handler := func(args []string) error { + if err := flagSet.Parse(args); err != nil { + return err + } + + tmpl, err := parseTemplate(*formatFlag) + if err != nil { + return err + } + + client := cfg.apiClient(apiFlags, flagSet.Output()) + + query := `query Teams( + $first: Int, + $search: String +) { + teams( + first: $first, + search: $search + ) { + nodes { + ...TeamFields + } + + } +}` + teamFragment + + if *parentTeamFlag != "" { + query = `query ChildTeams( + $first: Int, + $search: String, + $parentTeamName: String! + ) { + team(name: $parentTeamName) { + childTeams( + first: $first, + search: $search + ) { + nodes { + ...TeamFields + } + + } + } + }` + teamFragment + } + + var result struct { + Teams struct { + Nodes []Team + } + Team struct { + ChildTeams struct { + Nodes []Team + } + } + } + if ok, err := client.NewRequest(query, map[string]interface{}{ + "first": api.NullInt(*firstFlag), + "search": api.NullString(*queryFlag), + "parentTeamName": api.NullString(*parentTeamFlag), + }).Do(context.Background(), &result); err != nil || !ok { + return err + } + + nodes := result.Teams.Nodes + if *parentTeamFlag != "" { + nodes = result.Team.ChildTeams.Nodes + } + + if jsonFlag != nil && *jsonFlag { + json.NewEncoder(os.Stdout).Encode(nodes) + return nil + } + + for _, t := range nodes { + if err := execTemplate(tmpl, t); err != nil { + return err + } + } + return nil + } + + // Register the command. + teamsCommands = append(teamsCommands, &command{ + flagSet: flagSet, + handler: handler, + usageFunc: usageFunc, + }) +} diff --git a/cmd/src/teams_members.go b/cmd/src/teams_members.go new file mode 100644 index 0000000000..15be1b5331 --- /dev/null +++ b/cmd/src/teams_members.go @@ -0,0 +1,55 @@ +package main + +import ( + "flag" + "fmt" +) + +var teamMembersCommands commander + +func init() { + usage := `'src teams members' is a tool that manages team membership in a Sourcegraph instance. + +Usage: + + src team members command [command options] + +The commands are: + + list lists team members + add add team members + remove remove team members + +Use "src team members [command] -h" for more information about a command. +` + + flagSet := flag.NewFlagSet("members", flag.ExitOnError) + handler := func(args []string) error { + teamMembersCommands.run(flagSet, "src teams members", usage, args) + return nil + } + + // Register the command. + teamsCommands = append(teamsCommands, &command{ + flagSet: flagSet, + aliases: []string{"member"}, + handler: handler, + usageFunc: func() { + fmt.Println(usage) + }, + }) +} + +const teamMemberFragment = ` +fragment TeamMemberFields on TeamMember { + ... on User { + id + username + } +} +` + +type TeamMember struct { + ID string `json:"id"` + Username string `json:"username"` +} diff --git a/cmd/src/teams_members_add.go b/cmd/src/teams_members_add.go new file mode 100644 index 0000000000..9f4c3d24d2 --- /dev/null +++ b/cmd/src/teams_members_add.go @@ -0,0 +1,108 @@ +package main + +import ( + "context" + "flag" + "fmt" + + "github.com/sourcegraph/sourcegraph/lib/errors" + + "github.com/sourcegraph/src-cli/internal/api" +) + +func init() { + usage := ` +Examples: + + Add a team member: + + $ src teams members add -team-name='engineering' [-email='alice@sourcegraph.com'] [-username='alice'] [-id='VXNlcjox'] [-external-account-service-id='https://github.com/' -external-account-service-type='github' [-external-account-account-id='123123123'] [-external-account-login='alice']] + +` + + flagSet := flag.NewFlagSet("add", flag.ExitOnError) + usageFunc := func() { + fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src teams %s':\n", flagSet.Name()) + flagSet.PrintDefaults() + fmt.Println(usage) + } + var ( + teamNameFlag = flagSet.String("team-name", "", "The team name") + skipUnmatchedMembersFlag = flagSet.Bool("skip-unmatched-members", false, "If true, members that don't match a Sourcegraph user or team will be silently skipped") + emailFlag = flagSet.String("email", "", "Email to match the user by") + usernameFlag = flagSet.String("username", "", "Username to match the user by") + idFlag = flagSet.String("id", "", "Sourcegraph user ID to match the user by") + externalAccountServiceIDFlag = flagSet.String("external-account-service-id", "", "External account service ID to match the user by, must specify all of externalAccount*") + externalAccountServiceTypeFlag = flagSet.String("external-account-service-type", "", "External account service type to match the user by, must specify all of externalAccount*") + externalAccountAccountIDFlag = flagSet.String("external-account-account-id", "", "External account account ID to match the user by, must specify all of externalAccount*") + externalAccountLoginFlag = flagSet.String("external-account-login", "", "External account login ID to match the user by, must specify all of externalAccount*") + apiFlags = api.NewFlags(flagSet) + ) + + handler := func(args []string) error { + if err := flagSet.Parse(args); err != nil { + return err + } + + if *teamNameFlag == "" { + return errors.New("provide a team name") + } + + client := cfg.apiClient(apiFlags, flagSet.Output()) + + query := `mutation AddTeamMember( + $teamName: String! + $id: ID, + $email: String, + $username: String, + $externalAccountServiceID: String, + $externalAccountServiceType: String, + $externalAccountAccountID: String, + $externalAccountLogin: String, + $skipUnmatchedMembers: Boolean, +) { + addTeamMembers( + teamName: $teamName, + members: [{ + userID: $id, + email: $email, + username: $username, + externalAccountServiceID: $externalAccountServiceID, + externalAccountServiceType: $externalAccountServiceType, + externalAccountAccountID: $externalAccountAccountID, + externalAccountLogin: $externalAccountLogin, + }], + skipUnmatchedMembers: $skipUnmatchedMembers, + ) { + ...TeamFields + } +} +` + teamFragment + + var result struct { + AddTeamMembers Team + } + if ok, err := client.NewRequest(query, map[string]interface{}{ + "teamName": *teamNameFlag, + "skipUnmatchedMembers": *skipUnmatchedMembersFlag, + "id": api.NullString(*idFlag), + "email": api.NullString(*emailFlag), + "username": api.NullString(*usernameFlag), + "externalAccountServiceID": api.NullString(*externalAccountServiceIDFlag), + "externalAccountServiceType": api.NullString(*externalAccountServiceTypeFlag), + "externalAccountAccountID": api.NullString(*externalAccountAccountIDFlag), + "externalAccountLogin": api.NullString(*externalAccountLoginFlag), + }).Do(context.Background(), &result); err != nil || !ok { + return err + } + + return nil + } + + // Register the command. + teamMembersCommands = append(teamMembersCommands, &command{ + flagSet: flagSet, + handler: handler, + usageFunc: usageFunc, + }) +} diff --git a/cmd/src/teams_members_remove.go b/cmd/src/teams_members_remove.go new file mode 100644 index 0000000000..1a5dbbeb4c --- /dev/null +++ b/cmd/src/teams_members_remove.go @@ -0,0 +1,108 @@ +package main + +import ( + "context" + "flag" + "fmt" + + "github.com/sourcegraph/sourcegraph/lib/errors" + + "github.com/sourcegraph/src-cli/internal/api" +) + +func init() { + usage := ` +Examples: + + Remove a team member: + + $ src teams members remove -team-name='engineering' [-email='alice@sourcegraph.com'] [-username='alice'] [-id='VXNlcjox'] [-external-account-service-id='https://github.com/' -external-account-service-type='github' [-external-account-account-id='123123123'] [-external-account-login='alice']] + +` + + flagSet := flag.NewFlagSet("remove", flag.ExitOnError) + usageFunc := func() { + fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src teams %s':\n", flagSet.Name()) + flagSet.PrintDefaults() + fmt.Println(usage) + } + var ( + teamNameFlag = flagSet.String("team-name", "", "The team name") + skipUnmatchedMembersFlag = flagSet.Bool("skip-unmatched-members", false, "If true, members that don't match a Sourcegraph user or team will be silently skipped") + emailFlag = flagSet.String("email", "", "Email to match the user by") + usernameFlag = flagSet.String("username", "", "Username to match the user by") + idFlag = flagSet.String("id", "", "Sourcegraph user ID to match the user by") + externalAccountServiceIDFlag = flagSet.String("external-account-service-id", "", "External account service ID to match the user by, must specify all of externalAccount*") + externalAccountServiceTypeFlag = flagSet.String("external-account-service-type", "", "External account service type to match the user by, must specify all of externalAccount*") + externalAccountAccountIDFlag = flagSet.String("external-account-account-id", "", "External account account ID to match the user by, must specify all of externalAccount*") + externalAccountLoginFlag = flagSet.String("external-account-login", "", "External account login ID to match the user by, must specify all of externalAccount*") + apiFlags = api.NewFlags(flagSet) + ) + + handler := func(args []string) error { + if err := flagSet.Parse(args); err != nil { + return err + } + + if *teamNameFlag == "" { + return errors.New("provide a team name") + } + + client := cfg.apiClient(apiFlags, flagSet.Output()) + + query := `mutation RemoveTeamMember( + $teamName: String! + $id: ID, + $email: String, + $username: String, + $externalAccountServiceID: String, + $externalAccountServiceType: String, + $externalAccountAccountID: String, + $externalAccountLogin: String, + $skipUnmatchedMembers: Boolean, +) { + removeTeamMembers( + teamName: $teamName, + members: [{ + userID: $id, + email: $email, + username: $username, + externalAccountServiceID: $externalAccountServiceID, + externalAccountServiceType: $externalAccountServiceType, + externalAccountAccountID: $externalAccountAccountID, + externalAccountLogin: $externalAccountLogin, + }], + skipUnmatchedMembers: $skipUnmatchedMembers, + ) { + ...TeamFields + } +} +` + teamFragment + + var result struct { + RemoveTeamMembers Team + } + if ok, err := client.NewRequest(query, map[string]interface{}{ + "teamName": *teamNameFlag, + "skipUnmatchedMembers": *skipUnmatchedMembersFlag, + "id": api.NullString(*idFlag), + "email": api.NullString(*emailFlag), + "username": api.NullString(*usernameFlag), + "externalAccountServiceID": api.NullString(*externalAccountServiceIDFlag), + "externalAccountServiceType": api.NullString(*externalAccountServiceTypeFlag), + "externalAccountAccountID": api.NullString(*externalAccountAccountIDFlag), + "externalAccountLogin": api.NullString(*externalAccountLoginFlag), + }).Do(context.Background(), &result); err != nil || !ok { + return err + } + + return nil + } + + // Register the command. + teamMembersCommands = append(teamMembersCommands, &command{ + flagSet: flagSet, + handler: handler, + usageFunc: usageFunc, + }) +} diff --git a/cmd/src/teams_update.go b/cmd/src/teams_update.go new file mode 100644 index 0000000000..549a254a29 --- /dev/null +++ b/cmd/src/teams_update.go @@ -0,0 +1,92 @@ +package main + +import ( + "context" + "flag" + "fmt" + "strings" + + "github.com/sourcegraph/sourcegraph/lib/errors" + + "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/cmderrors" +) + +func init() { + usage := ` +Examples: + + Update the team "engineering": + + $ src teams update -name='engineering' [-display-name='Engineering Team'] [-parent-team='engineering-leadership'] + +` + + flagSet := flag.NewFlagSet("update", flag.ExitOnError) + usageFunc := func() { + fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src teams %s':\n", flagSet.Name()) + flagSet.PrintDefaults() + fmt.Println(usage) + } + var ( + nameFlag = flagSet.String("name", "", "The team name") + displayNameFlag = flagSet.String("display-name", "", "Optional additional display name for a more human-readable UI") + parentTeamFlag = flagSet.String("parent-team", "", "Optional name or ID of the parent team") + apiFlags = api.NewFlags(flagSet) + ) + + handler := func(args []string) error { + if err := flagSet.Parse(args); err != nil { + return err + } + + if *nameFlag == "" { + return errors.New("provide a name") + } + + client := cfg.apiClient(apiFlags, flagSet.Output()) + + query := `mutation UpdateTeam( + $name: String!, + $displayName: String, + $parentTeam: String +) { + updateTeam( + name: $name, + displayName: $displayName, + parentTeamName: $parentTeam, + ) { + ...TeamFields + } +} +` + teamFragment + + var result struct { + UpdateTeam Team + } + if ok, err := client.NewRequest(query, map[string]interface{}{ + "name": *nameFlag, + "displayName": api.NullString(*displayNameFlag), + "parentTeam": api.NullString(*parentTeamFlag), + }).Do(context.Background(), &result); err != nil || !ok { + var gqlErr api.GraphQlErrors + if errors.As(err, &gqlErr) { + for _, e := range gqlErr { + if strings.Contains(e.Error(), "team name is already taken") { + return cmderrors.ExitCode(3, err) + } + } + } + return err + } + + return nil + } + + // Register the command. + teamsCommands = append(teamsCommands, &command{ + flagSet: flagSet, + handler: handler, + usageFunc: usageFunc, + }) +} diff --git a/cmd/src/users_get.go b/cmd/src/users_get.go index 3e20aaabf5..47cebc5309 100644 --- a/cmd/src/users_get.go +++ b/cmd/src/users_get.go @@ -5,6 +5,8 @@ import ( "flag" "fmt" + "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/src-cli/internal/api" ) @@ -26,6 +28,7 @@ Examples: } var ( usernameFlag = flagSet.String("username", "", `Look up user by username. (e.g. "alice")`) + emailFlag = flagSet.String("email", "", `Look up user by email. (e.g. "alice@sourcegraph.com")`) formatFlag = flagSet.String("f", "{{.|json}}", `Format for the output, using the syntax of Go package text/template. (e.g. "{{.ID}}: {{.Username}} ({{.DisplayName}})")`) apiFlags = api.NewFlags(flagSet) ) @@ -37,16 +40,22 @@ Examples: client := cfg.apiClient(apiFlags, flagSet.Output()) + if usernameFlag != nil && *usernameFlag != "" && emailFlag != nil && *emailFlag != "" { + return errors.New("cannot specify both email and username") + } + tmpl, err := parseTemplate(*formatFlag) if err != nil { return err } query := `query User( - $username: String!, + $username: String, + $email: String, ) { user( - username: $username + username: $username, + email: $email, ) { ...UserFields } @@ -56,7 +65,8 @@ Examples: User *User } if ok, err := client.NewRequest(query, map[string]interface{}{ - "username": *usernameFlag, + "username": api.NullString(*usernameFlag), + "email": api.NullString(*emailFlag), }).Do(context.Background(), &result); err != nil || !ok { return err } From 8de09aa54a47ec56a156f21f7625ea6f53f62fe9 Mon Sep 17 00:00:00 2001 From: Jason Hawk Harris Date: Tue, 28 Feb 2023 14:29:20 -0600 Subject: [PATCH 304/647] add side effect imports for azure and gcp auth (#944) * add side effect imports for azure and gcp auth --- cmd/src/validate_kube.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/cmd/src/validate_kube.go b/cmd/src/validate_kube.go index c6e5e3b04e..c7044190fc 100644 --- a/cmd/src/validate_kube.go +++ b/cmd/src/validate_kube.go @@ -7,6 +7,8 @@ import ( "path/filepath" "k8s.io/client-go/kubernetes" + _ "k8s.io/client-go/plugin/pkg/client/auth/azure" + _ "k8s.io/client-go/plugin/pkg/client/auth/gcp" "k8s.io/client-go/tools/clientcmd" "k8s.io/client-go/util/homedir" From df169f1804213b06832a20fe24da9ec50b636202 Mon Sep 17 00:00:00 2001 From: Jason Hawk Harris Date: Thu, 2 Mar 2023 15:25:41 -0600 Subject: [PATCH 305/647] Adds validation of CSI drivers for GKE (#948) * add validate support for gke * set up gke validation flow, add nil validator * checks if storageClass is configured for gce-pd volumes * Adds validation for gke persistent volume drivers * delete commented import and remove unneeded context from gke function --- cmd/src/validate_kube.go | 18 +++++-- go.mod | 50 +++++++++--------- go.sum | 92 +++++++++++++++++----------------- internal/validate/kube/eks.go | 28 ----------- internal/validate/kube/gke.go | 80 +++++++++++++++++++++++++++++ internal/validate/kube/kube.go | 69 ++++++++++++++++++++++++- 6 files changed, 234 insertions(+), 103 deletions(-) create mode 100644 internal/validate/kube/gke.go diff --git a/cmd/src/validate_kube.go b/cmd/src/validate_kube.go index c7044190fc..fa42327372 100644 --- a/cmd/src/validate_kube.go +++ b/cmd/src/validate_kube.go @@ -28,7 +28,7 @@ Examples: Specify Kubernetes namespace: $ src validate kube --namespace sourcegraph - Specify the kubeconfig file location: + Specify the kubeconfig file())) location: $ src validate kube --kubeconfig ~/.kube/config Suppress output (useful for CI/CD pipelines) @@ -46,16 +46,22 @@ Examples: kubeConfig *string namespace = flagSet.String("namespace", "", "(optional) specify the kubernetes namespace to use") quiet = flagSet.Bool("quiet", false, "(optional) suppress output and return exit status only") - eks = flagSet.Bool("eks", false, "(optional) check EKS cluster") + eks = flagSet.Bool("eks", false, "(optional) validate EKS cluster") + gke = flagSet.Bool("gke", false, "(optional) validate GKE cluster") ) if home := homedir.HomeDir(); home != "" { - kubeConfig = flagSet.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file") + kubeConfig = flagSet.String( + "kubeconfig", + filepath.Join(home, ".kube", "config"), + "(optional) absolute path to the kubeconfig file", + ) } else { kubeConfig = flagSet.String("kubeconfig", "", "absolute path to the kubeconfig file") } handler := func(args []string) error { + ctx := context.Background() if err := flagSet.Parse(args); err != nil { return err } @@ -83,7 +89,11 @@ Examples: } if *eks { - options = append(options, kube.GenerateAWSClients(context.Background())) + options = append(options, kube.GenerateAWSClients(ctx)) + } + + if *gke { + options = append(options, kube.Gke()) } return kube.Validate(context.Background(), clientSet, config, options...) diff --git a/go.mod b/go.mod index f525ddcf65..cfb74c15e7 100644 --- a/go.mod +++ b/go.mod @@ -5,7 +5,9 @@ go 1.18 require ( cloud.google.com/go/storage v1.28.0 github.com/aws/aws-sdk-go-v2/config v1.18.13 + github.com/aws/aws-sdk-go-v2/service/ec2 v1.86.0 github.com/aws/aws-sdk-go-v2/service/eks v1.27.3 + github.com/aws/aws-sdk-go-v2/service/iam v1.19.3 github.com/creack/goselect v0.1.2 github.com/derision-test/glock v0.0.0-20210316032053-f5b74334bb29 github.com/dineshappavoo/basex v0.0.0-20170425072625-481a6f6dc663 @@ -24,10 +26,10 @@ require ( github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf github.com/sourcegraph/scip v0.2.3 github.com/sourcegraph/sourcegraph/lib v0.0.0-20230113014457-46187b849239 - github.com/stretchr/testify v1.8.0 - golang.org/x/net v0.5.0 + github.com/stretchr/testify v1.8.1 + golang.org/x/net v0.7.0 golang.org/x/sync v0.1.0 - google.golang.org/api v0.102.0 + google.golang.org/api v0.110.0 google.golang.org/protobuf v1.28.1 gopkg.in/yaml.v3 v3.0.1 jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7 @@ -37,10 +39,10 @@ require ( ) require ( - cloud.google.com/go v0.104.0 // indirect - cloud.google.com/go/compute v1.12.1 // indirect - cloud.google.com/go/compute/metadata v0.2.1 // indirect - cloud.google.com/go/iam v0.5.0 // indirect + cloud.google.com/go v0.107.0 // indirect + cloud.google.com/go/compute v1.18.0 // indirect + cloud.google.com/go/compute/metadata v0.2.3 // indirect + cloud.google.com/go/iam v0.12.0 // indirect github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect github.com/Masterminds/semver v1.5.0 // indirect github.com/Masterminds/sprig v2.15.0+incompatible // indirect @@ -52,8 +54,6 @@ require ( github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.29 // indirect github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.23 // indirect github.com/aws/aws-sdk-go-v2/internal/ini v1.3.29 // indirect - github.com/aws/aws-sdk-go-v2/service/ec2 v1.86.0 // indirect - github.com/aws/aws-sdk-go-v2/service/iam v1.19.3 // indirect github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.22 // indirect github.com/aws/aws-sdk-go-v2/service/sso v1.12.2 // indirect github.com/aws/aws-sdk-go-v2/service/ssooidc v1.14.2 // indirect @@ -69,7 +69,7 @@ require ( github.com/davecgh/go-spew v1.1.1 // indirect github.com/dlclark/regexp2 v1.4.0 // indirect github.com/emicklei/go-restful/v3 v3.9.0 // indirect - github.com/envoyproxy/protoc-gen-validate v0.3.0-java // indirect + github.com/envoyproxy/protoc-gen-validate v0.9.1 // indirect github.com/fatih/color v1.13.0 // indirect github.com/getsentry/sentry-go v0.13.0 // indirect github.com/ghodss/yaml v1.0.0 // indirect @@ -85,14 +85,14 @@ require ( github.com/google/gnostic v0.5.7-v3refs // indirect github.com/google/gofuzz v1.1.0 // indirect github.com/google/uuid v1.3.0 // indirect - github.com/googleapis/enterprise-certificate-proxy v0.2.0 // indirect - github.com/googleapis/gax-go/v2 v2.6.0 // indirect + github.com/googleapis/enterprise-certificate-proxy v0.2.3 // indirect + github.com/googleapis/gax-go/v2 v2.7.0 // indirect github.com/gorilla/css v1.0.0 // indirect github.com/hexops/gotextdiff v1.0.3 // indirect github.com/hexops/valast v1.4.1 // indirect github.com/huandu/xstrings v1.0.0 // indirect github.com/imdario/mergo v0.3.6 // indirect - github.com/inconshreveable/mousetrap v1.0.0 // indirect + github.com/inconshreveable/mousetrap v1.0.1 // indirect github.com/jdxcode/netrc v0.0.0-20210204082910-926c7f70242a // indirect github.com/jhump/protocompile v0.0.0-20220216033700-d705409f108f // indirect github.com/jhump/protoreflect v1.12.1-0.20220417024638-438db461d753 // indirect @@ -107,9 +107,9 @@ require ( github.com/mailru/easyjson v0.7.6 // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-runewidth v0.0.13 // indirect - github.com/microcosm-cc/bluemonday v1.0.17 // indirect + github.com/microcosm-cc/bluemonday v1.0.22 // indirect github.com/moby/spdystream v0.2.0 // indirect - github.com/moby/term v0.0.0-20210619224110-3f7ff695adc6 // indirect + github.com/moby/term v0.0.0-20220808134915-39b0c02b01ae // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect github.com/muesli/reflow v0.3.0 // indirect @@ -128,31 +128,31 @@ require ( github.com/russross/blackfriday/v2 v2.1.0 // indirect github.com/shurcooL/go-goon v0.0.0-20210110234559-7585751d9a17 // indirect github.com/sourcegraph/log v0.0.0-20220901143117-fc0516a694c9 // indirect - github.com/spf13/cobra v1.4.0 // indirect + github.com/spf13/cobra v1.6.0 // indirect github.com/spf13/pflag v1.0.5 // indirect github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect - github.com/stretchr/objx v0.4.0 // indirect + github.com/stretchr/objx v0.5.0 // indirect github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect github.com/xeipuuv/gojsonschema v1.2.0 // indirect github.com/yuin/goldmark v1.4.13 // indirect github.com/yuin/goldmark-emoji v1.0.1 // indirect - go.opencensus.io v0.23.0 // indirect + go.opencensus.io v0.24.0 // indirect go.uber.org/atomic v1.10.0 // indirect go.uber.org/multierr v1.8.0 // indirect go.uber.org/zap v1.23.0 // indirect - golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 // indirect + golang.org/x/crypto v0.1.0 // indirect golang.org/x/mod v0.7.0 // indirect - golang.org/x/oauth2 v0.0.0-20221014153046-6fdb5e3db783 // indirect - golang.org/x/sys v0.4.0 // indirect - golang.org/x/term v0.4.0 // indirect - golang.org/x/text v0.6.0 // indirect + golang.org/x/oauth2 v0.5.0 // indirect + golang.org/x/sys v0.5.0 // indirect + golang.org/x/term v0.5.0 // indirect + golang.org/x/text v0.7.0 // indirect golang.org/x/time v0.0.0-20220210224613-90d013bbcef8 // indirect golang.org/x/tools v0.5.0 // indirect golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 // indirect google.golang.org/appengine v1.6.7 // indirect - google.golang.org/genproto v0.0.0-20221024183307-1bc688fe9f3e // indirect - google.golang.org/grpc v1.50.1 // indirect + google.golang.org/genproto v0.0.0-20230216225411-c8e22ba71e44 // indirect + google.golang.org/grpc v1.53.0 // indirect gopkg.in/inf.v0 v0.9.1 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect k8s.io/klog/v2 v2.80.1 // indirect diff --git a/go.sum b/go.sum index dc6b6d959b..e483eaebdc 100644 --- a/go.sum +++ b/go.sum @@ -1,12 +1,13 @@ cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -cloud.google.com/go v0.104.0 h1:gSmWO7DY1vOm0MVU6DNXM11BWHHsTUmsC5cv1fuW5X8= -cloud.google.com/go v0.104.0/go.mod h1:OO6xxXdJyvuJPcEPBLN9BJPD+jep5G1+2U5B5gkRYtA= -cloud.google.com/go/compute v1.12.1 h1:gKVJMEyqV5c/UnpzjjQbo3Rjvvqpr9B1DFSbJC4OXr0= -cloud.google.com/go/compute v1.12.1/go.mod h1:e8yNOBcBONZU1vJKCvCoDw/4JQsA0dpM4x/6PIIOocU= -cloud.google.com/go/compute/metadata v0.2.1 h1:efOwf5ymceDhK6PKMnnrTHP4pppY5L22mle96M1yP48= -cloud.google.com/go/compute/metadata v0.2.1/go.mod h1:jgHgmJd2RKBGzXqF5LR2EZMGxBkeanZ9wwa75XHJgOM= -cloud.google.com/go/iam v0.5.0 h1:fz9X5zyTWBmamZsqvqZqD7khbifcZF/q+Z1J8pfhIUg= -cloud.google.com/go/iam v0.5.0/go.mod h1:wPU9Vt0P4UmCux7mqtRu6jcpPAb74cP1fh50J3QpkUc= +cloud.google.com/go v0.107.0 h1:qkj22L7bgkl6vIeZDlOY2po43Mx/TIa2Wsa7VR+PEww= +cloud.google.com/go v0.107.0/go.mod h1:wpc2eNrD7hXUTy8EKS10jkxpZBjASrORK7goS+3YX2I= +cloud.google.com/go/compute v1.18.0 h1:FEigFqoDbys2cvFkZ9Fjq4gnHBP55anJ0yQyau2f9oY= +cloud.google.com/go/compute v1.18.0/go.mod h1:1X7yHxec2Ga+Ss6jPyjxRxpu2uu7PLgsOVXvgU0yacs= +cloud.google.com/go/compute/metadata v0.2.3 h1:mg4jlk7mCAj6xXp9UJ4fjI9VUI5rubuGBW5aJ7UnBMY= +cloud.google.com/go/compute/metadata v0.2.3/go.mod h1:VAV5nSsACxMJvgaAuX6Pk2AawlZn8kiOGuCv6gTkwuA= +cloud.google.com/go/iam v0.12.0 h1:DRtTY29b75ciH6Ov1PHb4/iat2CLCvrOm40Q0a6DFpE= +cloud.google.com/go/iam v0.12.0/go.mod h1:knyHGviacl11zrtZUoDuYpDgLjvr28sLQaG0YB2GYAY= +cloud.google.com/go/longrunning v0.3.0 h1:NjljC+FYPV3uh5/OwWT6pVU+doBqMg2x/rZlE+CamDs= cloud.google.com/go/storage v1.28.0 h1:DLrIZ6xkeZX6K70fU/boWx5INJumt6f+nwwWSHXzzGY= cloud.google.com/go/storage v1.28.0/go.mod h1:qlgZML35PXA3zoEnIkiPLY4/TOkUleufRlu6qmcf7sI= github.com/AndreasBriese/bbloom v0.0.0-20190306092124-e2d15f34fcf9/go.mod h1:bOvUY6CB00SOBii9/FifXqc0awNKxLFCL/+pkDPuyl8= @@ -31,7 +32,6 @@ github.com/aokoli/goutils v1.0.1 h1:7fpzNGoJ3VA8qcrm++XEE1QUe0mIwNeLa02Nwq7RDkg= github.com/aokoli/goutils v1.0.1/go.mod h1:SijmP0QR8LtwsmDs8Yii5Z/S4trXFGFC2oO5g9DP+DQ= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio= -github.com/aws/aws-sdk-go-v2 v1.17.4 h1:wyC6p9Yfq6V2y98wfDsj6OnNQa4w2BLGCLIxzNhwOGY= github.com/aws/aws-sdk-go-v2 v1.17.4/go.mod h1:uzbQtefpm44goOPmdKyAlXSNcwlRgF3ePWVW6EtJvvw= github.com/aws/aws-sdk-go-v2 v1.17.5 h1:TzCUW1Nq4H8Xscph5M/skINUitxM5UBAyvm2s7XBzL4= github.com/aws/aws-sdk-go-v2 v1.17.5/go.mod h1:uzbQtefpm44goOPmdKyAlXSNcwlRgF3ePWVW6EtJvvw= @@ -41,11 +41,9 @@ github.com/aws/aws-sdk-go-v2/credentials v1.13.13 h1:zw1KAc1kl00NYd3ofVmFrb09qnY github.com/aws/aws-sdk-go-v2/credentials v1.13.13/go.mod h1:DW9nbIIF9MrIja0cBQrUpeWYQMSlNmP8fevLUyF9W38= github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.12.22 h1:3aMfcTmoXtTZnaT86QlVaYh+BRMbvrrmZwIQ5jWqCZQ= github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.12.22/go.mod h1:YGSIJyQ6D6FjKMQh16hVFSIUD54L4F7zTGePqYMYYJU= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.28 h1:r+XwaCLpIvCKjBIYy/HVZujQS9tsz5ohHG3ZIe0wKoE= github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.28/go.mod h1:3lwChorpIM/BhImY/hy+Z6jekmN92cXGPI1QJasVPYY= github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.29 h1:9/aKwwus0TQxppPXFmf010DFrE+ssSbzroLVYINA+xE= github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.29/go.mod h1:Dip3sIGv485+xerzVv24emnjX5Sg88utCL8fwGmCeWg= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.22 h1:7AwGYXDdqRQYsluvKFmWoqpcOQJ4bH634SkYf3FNj/A= github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.22/go.mod h1:EqK7gVrIGAHyZItrD1D8B0ilgwMD1GiWAmbU4u/JHNk= github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.23 h1:b/Vn141DBuLVgXbhRWIrl9g+ww7G+ScV5SzniWR13jQ= github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.23/go.mod h1:mr6c4cHC+S/MMkrjtSlG4QA36kOznDep+0fga5L/fGQ= @@ -96,7 +94,6 @@ github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE= -github.com/cpuguy83/go-md2man/v2 v2.0.1/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w= github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/creack/goselect v0.1.2 h1:2DNy14+JPjRBgPzAd1thbQp4BSIihxcBf0IXhQXDRa0= @@ -128,8 +125,8 @@ github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.m github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= github.com/envoyproxy/go-control-plane v0.9.9-0.20210217033140-668b12f5399d/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= -github.com/envoyproxy/protoc-gen-validate v0.3.0-java h1:bV5JGEB1ouEzZa0hgVDFFiClrUEuGWRaAc/3mxR2QK0= -github.com/envoyproxy/protoc-gen-validate v0.3.0-java/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/envoyproxy/protoc-gen-validate v0.9.1 h1:PS7VIOgmSVhWUEeZwTe7z7zouA22Cr590PzXKbZHOVY= +github.com/envoyproxy/protoc-gen-validate v0.9.1/go.mod h1:OKNgG7TCp5pF4d6XftA0++PMirau2/yoOwVac3AbF2w= github.com/etcd-io/bbolt v1.3.3/go.mod h1:ZF2nL25h33cCyBtcyWeZ2/I3HQOfTP+0PIEvHjkjCrw= github.com/fasthttp-contrib/websocket v0.0.0-20160511215533-1f3b11f56072/go.mod h1:duJ4Jxv5lDcvg4QuQr0oowTf7dz4/CR8NtyCooz9HL8= github.com/fatih/color v1.13.0 h1:8LOYc1KYPPmyKMuN8QV2DNRWNbLo6LZ0iLs8+mlH53w= @@ -222,10 +219,10 @@ github.com/google/martian/v3 v3.2.1 h1:d8MncMlErDFTwQGBK1xhv026j9kqhvw1Qv9IbWT1V github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/googleapis/enterprise-certificate-proxy v0.2.0 h1:y8Yozv7SZtlU//QXbezB6QkpuE6jMD2/gfzk4AftXjs= -github.com/googleapis/enterprise-certificate-proxy v0.2.0/go.mod h1:8C0jb7/mgJe/9KK8Lm7X9ctZC2t60YyIpYEI16jx0Qg= -github.com/googleapis/gax-go/v2 v2.6.0 h1:SXk3ABtQYDT/OH8jAyvEOQ58mgawq5C4o/4/89qN2ZU= -github.com/googleapis/gax-go/v2 v2.6.0/go.mod h1:1mjbznJAPHFpesgE5ucqfYEscaz5kMdcIDwU/6+DDoY= +github.com/googleapis/enterprise-certificate-proxy v0.2.3 h1:yk9/cqRKtT9wXZSsRH9aurXEpJX+U6FLtpYTdC3R06k= +github.com/googleapis/enterprise-certificate-proxy v0.2.3/go.mod h1:AwSRAtLfXpU5Nm3pW+v7rGDHp09LsPtGY9MduiEsR9k= +github.com/googleapis/gax-go/v2 v2.7.0 h1:IcsPKeInNvYi7eqSaDjiZqDDKu5rsmunY0Y1YupQSSQ= +github.com/googleapis/gax-go/v2 v2.7.0/go.mod h1:TEop28CZZQ2y+c0VxMUmu1lV+fQx57QpBWsYpwqHJx8= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gorilla/css v1.0.0 h1:BQqNyPTi50JCFMTw/b67hByjMVXZRwGha6wxVGkeihY= github.com/gorilla/css v1.0.0/go.mod h1:Dn721qIggHpt4+EFCcTLTU/vk5ySda2ReITrtgBl60c= @@ -252,8 +249,9 @@ github.com/hydrogen18/memlistener v0.0.0-20200120041712-dcc25e7acd91/go.mod h1:q github.com/imdario/mergo v0.3.6 h1:xTNEAn+kxVO7dTZGu0CegyqKZmoWFI0rF8UxjlB2d28= github.com/imdario/mergo v0.3.6/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= github.com/imkira/go-interpol v1.1.0/go.mod h1:z0h2/2T3XF8kyEPpRgJ3kmNv+C43p+I/CoI+jC3w2iA= -github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= +github.com/inconshreveable/mousetrap v1.0.1 h1:U3uMjPSQEBMNp1lFxmllqCPM6P5u/Xq7Pgzkat/bFNc= +github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/iris-contrib/blackfriday v2.0.0+incompatible/go.mod h1:UzZ2bDEoaSGPbkg6SAB4att1aAwTmVIx/5gCVqeyUdI= github.com/iris-contrib/go.uuid v2.0.0+incompatible/go.mod h1:iz2lgM/1UnEf1kP0L/+fafWORmlnuysV2EMP8MW+qe0= github.com/iris-contrib/i18n v0.0.0-20171121225848-987a633949d0/go.mod h1:pMCz62A0xJL6I+umB2YTlFRwWXaDFA0jy+5HzGiJjqI= @@ -353,16 +351,17 @@ github.com/mediocregopher/mediocre-go-lib v0.0.0-20181029021733-cb65787f37ed/go. github.com/mediocregopher/radix/v3 v3.3.0/go.mod h1:EmfVyvspXz1uZEyPBMyGK+kjWiKQGvsUt6O3Pj+LDCQ= github.com/mediocregopher/radix/v3 v3.4.2/go.mod h1:8FL3F6UQRXHXIBSPUs5h0RybMF8i4n7wVopoX3x7Bv8= github.com/microcosm-cc/bluemonday v1.0.2/go.mod h1:iVP4YcDBq+n/5fb23BhYFvIMq/leAFZyRl6bYmGDlGc= -github.com/microcosm-cc/bluemonday v1.0.17 h1:Z1a//hgsQ4yjC+8zEkV8IWySkXnsxmdSY642CTFQb5Y= github.com/microcosm-cc/bluemonday v1.0.17/go.mod h1:Z0r70sCuXHig8YpBzCc5eGHAap2K7e/u082ZUpDRRqM= +github.com/microcosm-cc/bluemonday v1.0.22 h1:p2tT7RNzRdCi0qmwxG+HbqD6ILkmwter1ZwVZn1oTxA= +github.com/microcosm-cc/bluemonday v1.0.22/go.mod h1:ytNkv4RrDrLJ2pqlsSI46O6IVXmZOBBD4SaJyDwwTkM= github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ= github.com/moby/spdystream v0.2.0 h1:cjW1zVyyoiM0T7b6UoySUFqzXMoqRckQtXwGPiBhOM8= github.com/moby/spdystream v0.2.0/go.mod h1:f7i0iNDQJ059oMTcWxx8MA/zKFIuD/lY+0GqbN2Wy8c= -github.com/moby/term v0.0.0-20210619224110-3f7ff695adc6 h1:dcztxKSvZ4Id8iPpHERQBbIJfabdt4wUm5qy3wOL2Zc= -github.com/moby/term v0.0.0-20210619224110-3f7ff695adc6/go.mod h1:E2VnQOmVuvZB6UYnnDB0qG5Nq/1tD9acaOpo6xmt0Kw= +github.com/moby/term v0.0.0-20220808134915-39b0c02b01ae h1:O4SWKdcHVCvYqyDV+9CJA1fcDN2L11Bule0iFy3YlAI= +github.com/moby/term v0.0.0-20220808134915-39b0c02b01ae/go.mod h1:E2VnQOmVuvZB6UYnnDB0qG5Nq/1tD9acaOpo6xmt0Kw= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -461,8 +460,8 @@ github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDI github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU= -github.com/spf13/cobra v1.4.0 h1:y+wJpx64xcgO1V+RcnwW0LEHxTKRi2ZDPSBjWnrg88Q= -github.com/spf13/cobra v1.4.0/go.mod h1:Wo4iy3BUC+X2Fybo0PDqwJIv3dNRiZLHQymsfxlB84g= +github.com/spf13/cobra v1.6.0 h1:42a0n6jwCot1pUmomAp4T7DeMD+20LFv4Q54pxLf2LI= +github.com/spf13/cobra v1.6.0/go.mod h1:IOw/AERYS7UzyrGinqmz6HLUo219MORXGxhbaJUqzrY= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= @@ -472,8 +471,9 @@ github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf h1:pvbZ0lM0XWPBqUKqFU8cma github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf/go.mod h1:RJID2RhlZKId02nZ62WenDCkgHFerpIOmW0iT7GKmXM= github.com/stoewer/go-strcase v1.2.0/go.mod h1:IBiWB2sKIp3wVVQ3Y035++gc+knqhUQag1KpM8ahLw8= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.4.0 h1:M2gUjqZET1qApGOWNSnZ49BAIMX4F/1plDv3+l31EJ4= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0 h1:1zr/of2m5FGMsad5YfcqgdqdWrIhu+EBEJRhR1U7z/c= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= @@ -482,8 +482,9 @@ github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.4/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= -github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc= github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw= github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= @@ -515,8 +516,8 @@ github.com/yuin/goldmark v1.4.13 h1:fVcFKWvrslecOb/tg+Cc05dkeYx540o0FuFt3nUVDoE= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= github.com/yuin/goldmark-emoji v1.0.1 h1:ctuWEyzGBwiucEqxzwe0SOYDXPAucOrE9NQC18Wa1os= github.com/yuin/goldmark-emoji v1.0.1/go.mod h1:2w1E6FEWLcDQkoTE+7HU6QF1F6SLlNGjRIBbIZQFqkQ= -go.opencensus.io v0.23.0 h1:gqCw0LfLxScz8irSi8exQc7fyQ0fKQU/qnC/X8+V/1M= -go.opencensus.io v0.23.0/go.mod h1:XItmlyltB5F7CS4xOC1DcqMoFqwtC6OG2xF7mCv7P7E= +go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0= +go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo= go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= go.uber.org/atomic v1.10.0 h1:9qC72Qh0+3MqyJbAn8YU5xVq1frD8bn3JtD2oXtafVQ= go.uber.org/atomic v1.10.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= @@ -532,8 +533,9 @@ golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8U golang.org/x/crypto v0.0.0-20191227163750-53104e6ec876/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= -golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 h1:7I4JAnoQBe7ZtJcBaYHi5UtiO8tQHbUSXxL+pnGRANg= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.1.0 h1:MDRAIl0xIo9Io2xV565hzXHw3zVseKrJKodhohM5CjU= +golang.org/x/crypto v0.1.0/go.mod h1:RecgLatLF4+eUMCP1PoPZQb+cVrJcOPbHkTkbkB9sbw= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= @@ -571,11 +573,11 @@ golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96b golang.org/x/net v0.0.0-20210614182718-04defd469f4e/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211008194852-3b03d305991f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/net v0.5.0 h1:GyT4nK/YDHSqa1c4753ouYCDajOYKTja9Xb/OHtgvSw= -golang.org/x/net v0.5.0/go.mod h1:DivGGAXEgPSlEBzxGzZI+ZLohi+xUj054jfeKui00ws= +golang.org/x/net v0.7.0 h1:rJrUqqhjsgNp7KqAIc25s9pZnjU7TUcSY7HcVZjdn1g= +golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= -golang.org/x/oauth2 v0.0.0-20221014153046-6fdb5e3db783 h1:nt+Q6cXKz4MosCSpnbMtqiQ8Oz0pxTef2B4Vca2lvfk= -golang.org/x/oauth2 v0.0.0-20221014153046-6fdb5e3db783/go.mod h1:h4gKUeWbJ4rQPri7E0u6Gs4e9Ri2zaLxzw5DI5XGrYg= +golang.org/x/oauth2 v0.5.0 h1:HuArIo48skDwlrvM3sEdHXElYslAMsf3KwRkkW4MC4s= +golang.org/x/oauth2 v0.5.0/go.mod h1:9/XBHVqLaWO3/BRHs5jbpYCnOZVjj5V0ndyaAM7KB4I= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -620,19 +622,19 @@ golang.org/x/sys v0.0.0-20211117180635-dee7805ff2e1/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20211213223007-03aa0b5f6827/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.4.0 h1:Zr2JFtRQNX3BCZ8YtxRE9hNJYC8J6I1MVbMg6owUp18= -golang.org/x/sys v0.4.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0 h1:MUK/U/4lj1t1oPg0HfuXDN/Z1wv31ZJ/YcPiGccS4DU= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/term v0.4.0 h1:O7UWfv5+A2qiuulQk30kVinPoMtoIPeVaKLEgLpVkvg= -golang.org/x/term v0.4.0/go.mod h1:9P2UbLfCdcvo3p/nzKvsmas4TnlujnuoV9hGgYzW1lQ= +golang.org/x/term v0.5.0 h1:n2a8QNdAb0sZNpU9R1ALUXBbY+w51fCQDN+7EdxNBsY= +golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.6.0 h1:3XmdazWV+ubf7QgHSTWeykHOci5oeekaGJBLkrkaw4k= -golang.org/x/text v0.6.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.7.0 h1:4BRB4x83lYWy72KwLD/qYDuTu7q9PjSagHvijDw7cLo= +golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/time v0.0.0-20201208040808-7e3f01d25324/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20220210224613-90d013bbcef8 h1:vVKdlvoWBphwdxWKrFZEuM0kGgGLxUOYcY4U/2Vjg44= golang.org/x/time v0.0.0-20220210224613-90d013bbcef8/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= @@ -664,8 +666,8 @@ golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8T golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 h1:H2TDz8ibqkAF6YGhCdN3jS9O0/s90v0rJh3X/OLHEUk= golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2/go.mod h1:K8+ghG5WaK9qNqU5K3HdILfMLy1f3aNYFI/wnl100a8= -google.golang.org/api v0.102.0 h1:JxJl2qQ85fRMPNvlZY/enexbxpCjLwGhZUtgfGeQ51I= -google.golang.org/api v0.102.0/go.mod h1:3VFl6/fzoA+qNuS1N1/VfXY4LjoXN/wzeIp7TweWwGo= +google.golang.org/api v0.110.0 h1:l+rh0KYUooe9JGbGVx71tbFo4SMbMTXK3I3ia2QSEeU= +google.golang.org/api v0.110.0/go.mod h1:7FC4Vvx1Mooxh8C5HWjzZHcavuS2f6pmJpZx60ca7iI= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c= @@ -676,8 +678,8 @@ google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98 google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= google.golang.org/genproto v0.0.0-20201019141844-1ed22bb0c154/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210624195500-8bfb893ecb84/go.mod h1:SzzZ/N+nwJDaO1kznhnlzqS8ocJICar6hYhVyhi++24= -google.golang.org/genproto v0.0.0-20221024183307-1bc688fe9f3e h1:S9GbmC1iCgvbLyAokVCwiO6tVIrU9Y7c5oMx1V/ki/Y= -google.golang.org/genproto v0.0.0-20221024183307-1bc688fe9f3e/go.mod h1:9qHF0xnpdSfF6knlcsnpzUu5y+rpwgbvsyGAZPBMg4s= +google.golang.org/genproto v0.0.0-20230216225411-c8e22ba71e44 h1:EfLuoKW5WfkgVdDy7dTK8qSbH37AX5mj/MFh+bGPz14= +google.golang.org/genproto v0.0.0-20230216225411-c8e22ba71e44/go.mod h1:8B0gmkoRebU8ukX6HP+4wrVQUY1+6PkQ44BSyIlflHA= google.golang.org/grpc v1.12.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= @@ -686,8 +688,8 @@ google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8 google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= google.golang.org/grpc v1.38.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= -google.golang.org/grpc v1.50.1 h1:DS/BukOZWp8s6p4Dt/tOaJaTQyPyOoCcrjroHuCeLzY= -google.golang.org/grpc v1.50.1/go.mod h1:ZgQEeidpAuNRZ8iRrlBKXZQP1ghovWIVhdJRyCDK+GI= +google.golang.org/grpc v1.53.0 h1:LAv2ds7cmFV/XTS3XG1NneeENYrXGmorPxsBbptIjNc= +google.golang.org/grpc v1.53.0/go.mod h1:OnIrk0ipVdj4N5d9IUoFUx72/VlD7+jUsHwZgwSMQpw= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= diff --git a/internal/validate/kube/eks.go b/internal/validate/kube/eks.go index 9bf102f478..745be69f22 100644 --- a/internal/validate/kube/eks.go +++ b/internal/validate/kube/eks.go @@ -5,7 +5,6 @@ import ( "fmt" "log" "path/filepath" - "reflect" "strings" corev1 "k8s.io/api/core/v1" @@ -253,33 +252,6 @@ func validateRolePolicy(rolePolicy RolePolicy) (result []validate.Result) { return result } -func CurrentContextSetToEKSCluster() error { - home := homedir.HomeDir() - pathToKubeConfig := filepath.Join(home, ".kube", "config") - - config, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig( - &clientcmd.ClientConfigLoadingRules{ExplicitPath: pathToKubeConfig}, - &clientcmd.ConfigOverrides{ - CurrentContext: "", - }).RawConfig() - - if err != nil { - return err - } - - got := strings.Split(config.CurrentContext, ":") - want := []string{"arn", "aws", "eks"} - - if len(got) >= 3 { - got = got[:3] - if reflect.DeepEqual(got, want) { - return nil - } - } - - return errors.New("no eks cluster configured") -} - func getAddons(ctx context.Context, client *eks.Client) ([]string, error) { clusterName := getClusterName(ctx, client) inputs := &eks.ListAddonsInput{ClusterName: clusterName} diff --git a/internal/validate/kube/gke.go b/internal/validate/kube/gke.go new file mode 100644 index 0000000000..3a07c1a782 --- /dev/null +++ b/internal/validate/kube/gke.go @@ -0,0 +1,80 @@ +package kube + +import ( + "context" + + "github.com/sourcegraph/src-cli/internal/validate" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +type ClusterInfo struct { + ServiceType string + ProjectId string + Region string + ClusterName string +} + +func Gke() Option { + return func(config *Config) { + config.gke = true + } +} + +func GkeGcePersistentDiskCSIDrivers(ctx context.Context, config *Config) ([]validate.Result, error) { + var results []validate.Result + + checkStorageClassesResults, err := validateStorageClasses(ctx, config) + if err != nil { + results = append(results, validate.Result{ + Status: validate.Failure, + Message: "GKE: could not check StorageClasses", + }) + return results, nil + } + + results = append(results, checkStorageClassesResults...) + return results, nil +} + +/* + validateStorageClasses checks for GKE specific storageClasses: + + After the compute engine persistent disk CSI driver is enabled, + gke automatically installs the standard-rwo and the premium-rwo + storage classes. This function checks that those storage + classes exist on the cluster. + + Ref: shorturl.at/dnKV0 +*/ +func validateStorageClasses(ctx context.Context, config *Config) ([]validate.Result, error) { + var results []validate.Result + + storageClient := config.clientSet.StorageV1() + storageClasses, err := storageClient.StorageClasses().List(ctx, metav1.ListOptions{}) + if err != nil { + return nil, err + } + + classes := 0 + for _, item := range storageClasses.Items { + if item.Name == "premium-rwo" || item.Name == "standard-rwo" { + classes += 1 + } + } + + if classes == 2 { + results = append(results, validate.Result{ + Status: validate.Success, + Message: "persistent volumes enabled: validated", + }) + + return results, nil + } + + results = append(results, validate.Result{ + Status: validate.Failure, + Message: "validate persistent volumes enabled: failed", + }) + + return results, nil +} diff --git a/internal/validate/kube/kube.go b/internal/validate/kube/kube.go index 2f41a68a4d..f3db17c038 100644 --- a/internal/validate/kube/kube.go +++ b/internal/validate/kube/kube.go @@ -7,14 +7,20 @@ import ( "io" "log" "os" + "path/filepath" + "reflect" "regexp" + "strings" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" "k8s.io/client-go/kubernetes/scheme" "k8s.io/client-go/rest" + "k8s.io/client-go/tools/clientcmd" + "k8s.io/client-go/tools/remotecommand" + "k8s.io/client-go/util/homedir" "github.com/aws/aws-sdk-go-v2/service/ec2" "github.com/aws/aws-sdk-go-v2/service/eks" @@ -39,6 +45,7 @@ type Config struct { clientSet *kubernetes.Clientset restConfig *rest.Config eks bool + gke bool eksClient *eks.Client ec2Client *ec2.Client iamClient *iam.Client @@ -73,6 +80,7 @@ func Validate(ctx context.Context, clientSet *kubernetes.Clientset, restConfig * clientSet: clientSet, restConfig: restConfig, eks: false, + gke: false, } for _, opt := range opts { @@ -89,7 +97,7 @@ func Validate(ctx context.Context, clientSet *kubernetes.Clientset, restConfig * } if cfg.eks { - if err := CurrentContextSetToEKSCluster(); err != nil { + if err := CurrentContextSetTo("eks"); err != nil { return errors.Newf("%s %s", validate.FailureEmoji, err) } @@ -110,6 +118,21 @@ func Validate(ctx context.Context, clientSet *kubernetes.Clientset, restConfig * }) } + if cfg.gke { + if err := CurrentContextSetTo("gke"); err != nil { + return errors.Newf("%s %s", validate.FailureEmoji, err) + } + + Gke() + + validations = append(validations, validation{ + Validate: GkeGcePersistentDiskCSIDrivers, + WaitMsg: "GKE: validating persistent volumes", + SuccessMsg: "GKE: persistent volumes validated", + ErrMsg: "GKE: validating peristent volumes failed", + }) + } + var totalFailCount int for _, v := range validations { @@ -417,3 +440,47 @@ func Connections(ctx context.Context, config *Config) ([]validate.Result, error) return results, nil } + +func CurrentContextSetTo(clusterService string) error { + currentContext, err := GetCurrentContext() + if err != nil { + return err + } + + if clusterService == "gke" { + got := strings.Split(currentContext, "_")[0] + want := clusterService + if got != want { + return errors.New("no gke cluster configured") + } + } else if clusterService == "eks" { + got := strings.Split(currentContext, ":") + want := []string{"arn", "aws", clusterService} + + if len(got) >= 3 { + got = got[:3] + if !reflect.DeepEqual(got, want) { + return errors.New("no eks cluster configured") + } + } + } + + return nil +} + +func GetCurrentContext() (string, error) { + home := homedir.HomeDir() + pathToKubeConfig := filepath.Join(home, ".kube", "config") + + config, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig( + &clientcmd.ClientConfigLoadingRules{ExplicitPath: pathToKubeConfig}, + &clientcmd.ConfigOverrides{ + CurrentContext: "", + }).RawConfig() + + if err != nil { + return "", err + } + + return config.CurrentContext, nil +} From 241050b0c2987166edd6a13f37ba9de465c14446 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Mon, 6 Mar 2023 12:30:51 +0100 Subject: [PATCH 306/647] Implement CLI for ingested codeowners (#943) --- cmd/src/codeowners.go | 67 ++++++++++++++++++++ cmd/src/codeowners_create.go | 118 +++++++++++++++++++++++++++++++++++ cmd/src/codeowners_delete.go | 86 +++++++++++++++++++++++++ cmd/src/codeowners_get.go | 87 ++++++++++++++++++++++++++ cmd/src/codeowners_update.go | 116 ++++++++++++++++++++++++++++++++++ cmd/src/main.go | 1 + 6 files changed, 475 insertions(+) create mode 100644 cmd/src/codeowners.go create mode 100644 cmd/src/codeowners_create.go create mode 100644 cmd/src/codeowners_delete.go create mode 100644 cmd/src/codeowners_get.go create mode 100644 cmd/src/codeowners_update.go diff --git a/cmd/src/codeowners.go b/cmd/src/codeowners.go new file mode 100644 index 0000000000..47b9cee19b --- /dev/null +++ b/cmd/src/codeowners.go @@ -0,0 +1,67 @@ +package main + +import ( + "flag" + "fmt" + "io" + "os" +) + +var codeownersCommands commander + +func init() { + usage := `'src codeowners' is a tool that manages ingested code ownership data in a Sourcegraph instance. + +Usage: + + src codeowners command [command options] + +The commands are: + + get returns the codeowners file for a repository, if exists + create create a codeowners file + update update a codeowners file + delete delete a codeowners file + +Use "src codeowners [command] -h" for more information about a command. +` + + flagSet := flag.NewFlagSet("codeowners", flag.ExitOnError) + handler := func(args []string) error { + codeownersCommands.run(flagSet, "src codeowners", usage, args) + return nil + } + + // Register the command. + commands = append(commands, &command{ + flagSet: flagSet, + aliases: []string{"codeowner"}, + handler: handler, + usageFunc: func() { + fmt.Println(usage) + }, + }) +} + +const codeownersFragment = ` +fragment CodeownersFileFields on CodeownersIngestedFile { + contents + repository { + name + } +} +` + +type CodeownersIngestedFile struct { + Contents string `json:"contents"` + Repository struct { + Name string `json:"name"` + } `json:"repository"` +} + +func readFile(f string) (io.Reader, error) { + if f == "-" { + return os.Stdin, nil + } + return os.Open(f) +} diff --git a/cmd/src/codeowners_create.go b/cmd/src/codeowners_create.go new file mode 100644 index 0000000000..7daf00ba21 --- /dev/null +++ b/cmd/src/codeowners_create.go @@ -0,0 +1,118 @@ +package main + +import ( + "context" + "flag" + "fmt" + "io" + "strings" + + "github.com/sourcegraph/sourcegraph/lib/errors" + + "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/cmderrors" +) + +func init() { + usage := ` +Examples: + + Create a codeowners file for the repository "github.com/sourcegraph/sourcegraph": + + $ src codeowners create -repo='github.com/sourcegraph/sourcegraph' -f CODEOWNERS + + Create a codeowners file for the repository "github.com/sourcegraph/sourcegraph" from stdin: + + $ src codeowners create -repo='github.com/sourcegraph/sourcegraph' -f - +` + + flagSet := flag.NewFlagSet("create", flag.ExitOnError) + usageFunc := func() { + fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src codeowners %s':\n", flagSet.Name()) + flagSet.PrintDefaults() + fmt.Println(usage) + } + var ( + repoFlag = flagSet.String("repo", "", "The repository to attach the data to") + fileFlag = flagSet.String("file", "", "File path to read ownership information from (- for stdin)") + fileShortFlag = flagSet.String("f", "", "File path to read ownership information from (- for stdin). Alias for -file") + + apiFlags = api.NewFlags(flagSet) + ) + + handler := func(args []string) error { + if err := flagSet.Parse(args); err != nil { + return err + } + + if *repoFlag == "" { + return errors.New("provide a repo name using -repo") + } + + if *fileFlag == "" && *fileShortFlag == "" { + return errors.New("provide a file using -file") + } + if *fileFlag != "" && *fileShortFlag != "" { + return errors.New("have to provide either -file or -f") + } + if *fileShortFlag != "" { + *fileFlag = *fileShortFlag + } + + file, err := readFile(*fileFlag) + if err != nil { + return err + } + + content, err := io.ReadAll(file) + if err != nil { + return err + } + + client := cfg.apiClient(apiFlags, flagSet.Output()) + + query := `mutation CreateCodeownersFile( + $repoName: String!, + $content: String! +) { + addCodeownersFile(input: { + repoName: $repoName, + fileContents: $content, + } + ) { + ...CodeownersFileFields + } +} +` + codeownersFragment + + var result struct { + AddCodeownersFile CodeownersIngestedFile + } + if ok, err := client.NewRequest(query, map[string]interface{}{ + "repoName": *repoFlag, + "content": string(content), + }).Do(context.Background(), &result); err != nil || !ok { + var gqlErr api.GraphQlErrors + if errors.As(err, &gqlErr) { + for _, e := range gqlErr { + if strings.Contains(e.Error(), "repo not found:") { + return cmderrors.ExitCode(2, errors.Newf("repository %q not found", *repoFlag)) + } + if strings.Contains(e.Error(), "codeowners file has already been ingested for this repository") { + return cmderrors.ExitCode(2, errors.New("codeowners file has already been ingested for this repository")) + } + } + } + return err + } + + return nil + } + + // Register the command. + codeownersCommands = append(codeownersCommands, &command{ + flagSet: flagSet, + handler: handler, + usageFunc: usageFunc, + }) +} diff --git a/cmd/src/codeowners_delete.go b/cmd/src/codeowners_delete.go new file mode 100644 index 0000000000..00ab581023 --- /dev/null +++ b/cmd/src/codeowners_delete.go @@ -0,0 +1,86 @@ +package main + +import ( + "context" + "flag" + "fmt" + "strings" + + "github.com/sourcegraph/sourcegraph/lib/errors" + + "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/cmderrors" +) + +func init() { + usage := ` +Examples: + + Delete a codeowners file for the repository "github.com/sourcegraph/sourcegraph": + + $ src codeowners delete -repo='github.com/sourcegraph/sourcegraph' +` + + flagSet := flag.NewFlagSet("delete", flag.ExitOnError) + usageFunc := func() { + fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src codeowners %s':\n", flagSet.Name()) + flagSet.PrintDefaults() + fmt.Println(usage) + } + var ( + repoFlag = flagSet.String("repo", "", "The repository to delete the data for") + apiFlags = api.NewFlags(flagSet) + ) + + handler := func(args []string) error { + if err := flagSet.Parse(args); err != nil { + return err + } + + if *repoFlag == "" { + return errors.New("provide a repo name using -repo") + } + + client := cfg.apiClient(apiFlags, flagSet.Output()) + + query := `mutation DeleteCodeownersFile( + $repoName: String!, +) { + deleteCodeownersFiles(repositories: [{ + repoName: $repoName, + }]) { + alwaysNil + } +} +` + + var result struct { + DeleteCodeownersFile CodeownersIngestedFile + } + if ok, err := client.NewRequest(query, map[string]interface{}{ + "repoName": *repoFlag, + }).Do(context.Background(), &result); err != nil || !ok { + var gqlErr api.GraphQlErrors + if errors.As(err, &gqlErr) { + for _, e := range gqlErr { + if strings.Contains(e.Error(), "repo not found:") { + return cmderrors.ExitCode(2, errors.Newf("repository %q not found", *repoFlag)) + } + if strings.Contains(e.Error(), "codeowners file not found:") { + return cmderrors.ExitCode(2, errors.Newf("no data found for repository %q", *repoFlag)) + } + } + } + return err + } + + return nil + } + + // Register the command. + codeownersCommands = append(codeownersCommands, &command{ + flagSet: flagSet, + handler: handler, + usageFunc: usageFunc, + }) +} diff --git a/cmd/src/codeowners_get.go b/cmd/src/codeowners_get.go new file mode 100644 index 0000000000..ce4e78a855 --- /dev/null +++ b/cmd/src/codeowners_get.go @@ -0,0 +1,87 @@ +package main + +import ( + "context" + "flag" + "fmt" + "os" + + "github.com/sourcegraph/sourcegraph/lib/errors" + + "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/cmderrors" +) + +func init() { + usage := ` +Examples: + + Read the current codeowners file for the repository "github.com/sourcegraph/sourcegraph": + + $ src codeowners get -repo='github.com/sourcegraph/sourcegraph' +` + + flagSet := flag.NewFlagSet("get", flag.ExitOnError) + usageFunc := func() { + fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src codeowners %s':\n", flagSet.Name()) + flagSet.PrintDefaults() + fmt.Println(usage) + } + var ( + repoFlag = flagSet.String("repo", "", "The repository to attach the data to") + apiFlags = api.NewFlags(flagSet) + ) + + handler := func(args []string) error { + if err := flagSet.Parse(args); err != nil { + return err + } + + if *repoFlag == "" { + return errors.New("provide a repo name using -repo") + } + + client := cfg.apiClient(apiFlags, flagSet.Output()) + + query := `query GetCodeownersFile( + $repoName: String! +) { + repository(name: $repoName) { + ingestedCodeowners { + ...CodeownersFileFields + } + } +} +` + codeownersFragment + + var result struct { + Repository *struct { + IngestedCodeowners *CodeownersIngestedFile + } + } + if ok, err := client.NewRequest(query, map[string]interface{}{ + "repoName": *repoFlag, + }).Do(context.Background(), &result); err != nil || !ok { + return err + } + + if result.Repository == nil { + return cmderrors.ExitCode(2, errors.Newf("repository %q not found", *repoFlag)) + } + + if result.Repository.IngestedCodeowners == nil { + return cmderrors.ExitCode(2, errors.Newf("no codeowners data found for %q", *repoFlag)) + } + + fmt.Fprintf(os.Stdout, "%s", result.Repository.IngestedCodeowners.Contents) + + return nil + } + + // Register the command. + codeownersCommands = append(codeownersCommands, &command{ + flagSet: flagSet, + handler: handler, + usageFunc: usageFunc, + }) +} diff --git a/cmd/src/codeowners_update.go b/cmd/src/codeowners_update.go new file mode 100644 index 0000000000..d27292cd0c --- /dev/null +++ b/cmd/src/codeowners_update.go @@ -0,0 +1,116 @@ +package main + +import ( + "context" + "flag" + "fmt" + "io" + "strings" + + "github.com/sourcegraph/sourcegraph/lib/errors" + + "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/cmderrors" +) + +func init() { + usage := ` +Examples: + + Update a codeowners file for the repository "github.com/sourcegraph/sourcegraph": + + $ src codeowners update -repo='github.com/sourcegraph/sourcegraph' -f CODEOWNERS + + Update a codeowners file for the repository "github.com/sourcegraph/sourcegraph" from stdin: + + $ src codeowners update -repo='github.com/sourcegraph/sourcegraph' -f - +` + + flagSet := flag.NewFlagSet("update", flag.ExitOnError) + usageFunc := func() { + fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src codeowners %s':\n", flagSet.Name()) + flagSet.PrintDefaults() + fmt.Println(usage) + } + var ( + repoFlag = flagSet.String("repo", "", "The repository to attach the data to") + fileFlag = flagSet.String("file", "", "File path to read ownership information from (- for stdin)") + fileShortFlag = flagSet.String("f", "", "File path to read ownership information from (- for stdin). Alias for -file") + apiFlags = api.NewFlags(flagSet) + ) + + handler := func(args []string) error { + if err := flagSet.Parse(args); err != nil { + return err + } + + if *repoFlag == "" { + return errors.New("provide a repo name using -repo") + } + + if *fileFlag == "" && *fileShortFlag == "" { + return errors.New("provide a file using -file") + } + if *fileFlag != "" && *fileShortFlag != "" { + return errors.New("have to provide either -file or -f") + } + if *fileShortFlag != "" { + *fileFlag = *fileShortFlag + } + + file, err := readFile(*fileFlag) + if err != nil { + return err + } + + content, err := io.ReadAll(file) + if err != nil { + return err + } + + client := cfg.apiClient(apiFlags, flagSet.Output()) + + query := `mutation UpdateCodeownersFile( + $repoName: String!, + $content: String! +) { + updateCodeownersFile(input: { + repoName: $repoName, + fileContents: $content, + }) { + ...CodeownersFileFields + } +} +` + codeownersFragment + + var result struct { + UpdateCodeownersFile CodeownersIngestedFile + } + if ok, err := client.NewRequest(query, map[string]interface{}{ + "repoName": *repoFlag, + "content": string(content), + }).Do(context.Background(), &result); err != nil || !ok { + var gqlErr api.GraphQlErrors + if errors.As(err, &gqlErr) { + for _, e := range gqlErr { + if strings.Contains(e.Error(), "repo not found:") { + return cmderrors.ExitCode(2, errors.Newf("repository %q not found", *repoFlag)) + } + if strings.Contains(e.Error(), "could not update codeowners file: codeowners file not found:") { + return cmderrors.ExitCode(2, errors.New("no codeowners data has been found for this repository")) + } + } + } + return err + } + + return nil + } + + // Register the command. + codeownersCommands = append(codeownersCommands, &command{ + flagSet: flagSet, + handler: handler, + usageFunc: usageFunc, + }) +} diff --git a/cmd/src/main.go b/cmd/src/main.go index 177a622672..269f20b424 100644 --- a/cmd/src/main.go +++ b/cmd/src/main.go @@ -47,6 +47,7 @@ The commands are: serve-git serves your local git repositories over HTTP for Sourcegraph to pull upload upload an index to a Sourcegraph instance users,user manages users + codeowners manages code ownership information version display and compare the src-cli version against the recommended version for your instance Use "src [command] -h" for more information about a command. From 34f3599756da1897c4e7682e33b9dcc211dd7071 Mon Sep 17 00:00:00 2001 From: Jason Hawk Harris Date: Mon, 6 Mar 2023 09:41:30 -0600 Subject: [PATCH 307/647] validate persistent volumes for aks clusters (#950) --- cmd/src/validate_kube.go | 14 ++++++ internal/validate/kube/aks.go | 91 ++++++++++++++++++++++++++++++++++ internal/validate/kube/kube.go | 29 +++++++++++ 3 files changed, 134 insertions(+) create mode 100644 internal/validate/kube/aks.go diff --git a/cmd/src/validate_kube.go b/cmd/src/validate_kube.go index fa42327372..46f9374f42 100644 --- a/cmd/src/validate_kube.go +++ b/cmd/src/validate_kube.go @@ -33,6 +33,15 @@ Examples: Suppress output (useful for CI/CD pipelines) $ src validate kube --quiet + + Validate EKS cluster: + $ src validate kube --eks + + Validate GKE cluster: + $ src validate kube --gke + + Validate AKS cluster: + $ src validate kube --aks ` flagSet := flag.NewFlagSet("kube", flag.ExitOnError) @@ -48,6 +57,7 @@ Examples: quiet = flagSet.Bool("quiet", false, "(optional) suppress output and return exit status only") eks = flagSet.Bool("eks", false, "(optional) validate EKS cluster") gke = flagSet.Bool("gke", false, "(optional) validate GKE cluster") + aks = flagSet.Bool("aks", false, "(optional) validate AKS cluster") ) if home := homedir.HomeDir(); home != "" { @@ -96,6 +106,10 @@ Examples: options = append(options, kube.Gke()) } + if *aks { + options = append(options, kube.Aks()) + } + return kube.Validate(context.Background(), clientSet, config, options...) } diff --git a/internal/validate/kube/aks.go b/internal/validate/kube/aks.go new file mode 100644 index 0000000000..dec8b4f921 --- /dev/null +++ b/internal/validate/kube/aks.go @@ -0,0 +1,91 @@ +package kube + +import ( + "context" + + "github.com/sourcegraph/src-cli/internal/validate" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +func Aks() Option { + return func(config *Config) { + config.aks = true + } +} + +func AksCsiDrivers(ctx context.Context, config *Config) ([]validate.Result, error) { + var results []validate.Result + + storageClassResults, err := validateStorageClass(ctx, config) + if err != nil { + results = append(results, validate.Result{ + Status: validate.Failure, + Message: "AKS: could not validate if persistent volumes are enabled", + }) + + return results, err + } + + results = append(results, storageClassResults...) + + return results, nil +} + +func validateStorageClass(ctx context.Context, config *Config) ([]validate.Result, error) { + var results []validate.Result + + storageClient := config.clientSet.StorageV1() + storageClasses, err := storageClient.StorageClasses().List(ctx, metav1.ListOptions{}) + if err != nil { + return nil, err + } + + for _, item := range storageClasses.Items { + if item.Name == "sourcegraph" { + if item.Provisioner != "disk.csi.azure.com" { + results = append(results, validate.Result{ + Status: validate.Failure, + Message: "provisioner does not enable persistent volumes", + }) + } else { + results = append(results, validate.Result{ + Status: validate.Success, + Message: "persistent volumes enabled", + }) + } + + if string(*item.ReclaimPolicy) != "Retain" { + results = append(results, validate.Result{ + Status: validate.Failure, + Message: "storageclass has a reclaim policy other than 'Retain'", + }) + } else { + results = append(results, validate.Result{ + Status: validate.Success, + Message: "storageclass has correct reclaim policy (Retain)", + }) + } + + if string(*item.VolumeBindingMode) != "WaitForFirstConsumer" { + results = append(results, validate.Result{ + Status: validate.Failure, + Message: "storageclass has a binding mode other than 'WaitForFirstConsumer'", + }) + } else { + results = append(results, validate.Result{ + Status: validate.Success, + Message: "storageclass has correct volumeBindingMode (WaitForFirstConsumer)", + }) + } + } + } + + if len(results) == 0 { + results = append(results, validate.Result{ + Status: validate.Warning, + Message: "you have not yet deployed a sourcegraph instance to this cluster, or you've named your storageclass something other than 'sourcegraph'", + }) + } + + return results, nil +} diff --git a/internal/validate/kube/kube.go b/internal/validate/kube/kube.go index f3db17c038..6a1dc71010 100644 --- a/internal/validate/kube/kube.go +++ b/internal/validate/kube/kube.go @@ -46,6 +46,7 @@ type Config struct { restConfig *rest.Config eks bool gke bool + aks bool eksClient *eks.Client ec2Client *ec2.Client iamClient *iam.Client @@ -81,6 +82,7 @@ func Validate(ctx context.Context, clientSet *kubernetes.Clientset, restConfig * restConfig: restConfig, eks: false, gke: false, + aks: false, } for _, opt := range opts { @@ -133,6 +135,21 @@ func Validate(ctx context.Context, clientSet *kubernetes.Clientset, restConfig * }) } + if cfg.aks { + if err := CurrentContextSetTo("aks"); err != nil { + return errors.Newf("%s %s", validate.FailureEmoji, err) + } + + Aks() + + validations = append(validations, validation{ + Validate: AksCsiDrivers, + WaitMsg: "AKS: validating persistent volumes", + SuccessMsg: "AKS: persistent volumes validated", + ErrMsg: "AKS: validating persistent volumes failed", + }) + } + var totalFailCount int for _, v := range validations { @@ -457,12 +474,24 @@ func CurrentContextSetTo(clusterService string) error { got := strings.Split(currentContext, ":") want := []string{"arn", "aws", clusterService} + if got[0] != "arn" { + return errors.New("no eks cluster configured") + } + if len(got) >= 3 { got = got[:3] if !reflect.DeepEqual(got, want) { return errors.New("no eks cluster configured") } } + } else if clusterService == "aks" { + colons := strings.Split(currentContext, ":") // aws string + underscores := strings.Split(currentContext, "_") // gke string + + // if current context has 'arn' or 'gke' in string, return error + if colons[0] == "arn" || underscores[0] == "gke" { + return errors.New("no aks cluster configured") + } } return nil From 7875b7d45e3f92c1ae1a5788dc9dc50beb3b526f Mon Sep 17 00:00:00 2001 From: Jason Hawk Harris Date: Mon, 6 Mar 2023 10:54:42 -0600 Subject: [PATCH 308/647] Adds conditions for clusters that do not have Sourcegraph installed. (#951) - Before, clusters/namespaces would pass all validations even if no Sourcegraph instance was installed. - Now: pods, services, connections and PVC validations fail with a warning if none exist. --- internal/validate/kube/kube.go | 48 ++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/internal/validate/kube/kube.go b/internal/validate/kube/kube.go index 6a1dc71010..be3288b7d9 100644 --- a/internal/validate/kube/kube.go +++ b/internal/validate/kube/kube.go @@ -211,6 +211,18 @@ func Pods(ctx context.Context, config *Config) ([]validate.Result, error) { var results []validate.Result + if len(pods.Items) == 0 { + results = append(results, validate.Result{ + Status: validate.Warning, + Message: fmt.Sprintf( + "No pods exist on namespace '%s'. check namespace/cluster", + config.namespace, + ), + }) + + return results, nil + } + for _, pod := range pods.Items { r := validatePod(&pod) results = append(results, r...) @@ -291,6 +303,18 @@ func Services(ctx context.Context, config *Config) ([]validate.Result, error) { var results []validate.Result + if len(services.Items) <= 1 { + results = append(results, validate.Result{ + Status: validate.Warning, + Message: fmt.Sprintf( + "unexpected number of services on namespace '%s'; check namespace/cluster", + config.namespace, + ), + }) + + return results, nil + } + for _, service := range services.Items { r := validateService(&service) results = append(results, r...) @@ -326,6 +350,18 @@ func PVCs(ctx context.Context, config *Config) ([]validate.Result, error) { var results []validate.Result + if len(pvcs.Items) == 0 { + results = append(results, validate.Result{ + Status: validate.Warning, + Message: fmt.Sprintf( + "no PVCs exist in namespace '%s'; check namespace/cluster", + config.namespace, + ), + }) + + return results, nil + } + for _, pvc := range pvcs.Items { r := validatePVC(&pvc) results = append(results, r...) @@ -368,6 +404,18 @@ func Connections(ctx context.Context, config *Config) ([]validate.Result, error) return nil, err } + if len(pods.Items) == 0 { + results = append(results, validate.Result{ + Status: validate.Warning, + Message: fmt.Sprintf( + "cannot check connections: zero pods exist in namespace '%s'", + config.namespace, + ), + }) + + return results, nil + } + // iterate through pods looking for specific pod name prefixes, then construct // a relationship map between pods that should have connectivity with each other for _, pod := range pods.Items { From 37ff66ff33cd96212e851ad17853916815867177 Mon Sep 17 00:00:00 2001 From: James Cotter <35706755+jac@users.noreply.github.com> Date: Tue, 7 Mar 2023 22:09:47 +0000 Subject: [PATCH 309/647] Add Snapshot Restore command (#947) Snapshot Restore generates commands to restore dumped snapshots to a Sourcegraph instance --- cmd/src/snapshot_databases.go | 57 ++++++++---------- cmd/src/snapshot_restore.go | 108 ++++++++++++++++++++++++++++++++++ internal/pgdump/pgdump.go | 56 ++++++++++++++++-- 3 files changed, 184 insertions(+), 37 deletions(-) create mode 100644 cmd/src/snapshot_restore.go diff --git a/cmd/src/snapshot_databases.go b/cmd/src/snapshot_databases.go index 7b3583d1d4..648667f6fe 100644 --- a/cmd/src/snapshot_databases.go +++ b/cmd/src/snapshot_databases.go @@ -4,6 +4,7 @@ import ( "flag" "fmt" "os" + "os/exec" "strings" "github.com/sourcegraph/sourcegraph/lib/errors" @@ -18,7 +19,7 @@ func init() { Note that these commands are intended for use as reference - you may need to adjust the commands for your deployment. USAGE - src [-v] snapshot databases [--targets=] + src [-v] snapshot databases [--targets=] [--run] TARGETS FILES Predefined targets are available based on default Sourcegraph configurations ('docker', 'k8s'). @@ -38,6 +39,7 @@ TARGETS FILES ` flagSet := flag.NewFlagSet("databases", flag.ExitOnError) targetsKeyFlag := flagSet.String("targets", "auto", "predefined targets ('docker' or 'k8s'), or a custom targets.yaml file") + run := flagSet.Bool("run", false, "Automatically run the commands") snapshotCommands = append(snapshotCommands, &command{ flagSet: flagSet, @@ -47,35 +49,13 @@ TARGETS FILES } out := output.NewOutput(flagSet.Output(), output.OutputOpts{Verbose: *verbose}) - var builder string - if len(args) > 0 { - builder = args[0] - } + builder := flagSet.Arg(0) - targetKey := "docker" - var commandBuilder pgdump.CommandBuilder - switch builder { - case "pg_dump", "": - targetKey = "local" - commandBuilder = func(t pgdump.Target) (string, error) { - cmd := pgdump.Command(t) - if t.Target != "" { - return fmt.Sprintf("%s --host=%s", cmd, t.Target), nil - } - return cmd, nil - } - case "docker": - commandBuilder = func(t pgdump.Target) (string, error) { - return fmt.Sprintf("docker exec -it %s sh -c '%s'", t.Target, pgdump.Command(t)), nil - } - case "kubectl": - targetKey = "k8s" - commandBuilder = func(t pgdump.Target) (string, error) { - return fmt.Sprintf("kubectl exec -it %s -- bash -c '%s'", t.Target, pgdump.Command(t)), nil - } - default: + commandBuilder, targetKey := pgdump.Builder(builder, pgdump.DumpCommand) + if targetKey == "" { return errors.Newf("unknown or invalid template type %q", builder) } + if *targetsKeyFlag != "auto" { targetKey = *targetsKeyFlag } @@ -94,19 +74,32 @@ TARGETS FILES out.WriteLine(output.Emojif(output.EmojiInfo, "Using predefined targets for %s environments", targetKey)) } - commands, err := pgdump.BuildCommands(srcSnapshotDir, commandBuilder, targets) + commands, err := pgdump.BuildCommands(srcSnapshotDir, commandBuilder, targets, true) if err != nil { return errors.Wrap(err, "failed to build commands") } _ = os.MkdirAll(srcSnapshotDir, os.ModePerm) - b := out.Block(output.Emoji(output.EmojiSuccess, "Run these commands to generate the required database dumps:")) - b.Write("\n" + strings.Join(commands, "\n")) - b.Close() + if *run { + for _, c := range commands { + out.WriteLine(output.Emojif(output.EmojiInfo, "Running command: %q", c)) + command := exec.Command("bash", "-c", c) + output, err := command.CombinedOutput() + out.Write(string(output)) + if err != nil { + return errors.Wrapf(err, "failed to run command: %q", c) + } + } - out.WriteLine(output.Styledf(output.StyleSuggestion, "Note that you may need to do some additional setup, such as authentication, beforehand.")) + out.WriteLine(output.Emoji(output.EmojiSuccess, "Successfully completed dump commands")) + } else { + b := out.Block(output.Emoji(output.EmojiSuccess, "Run these commands to generate the required database dumps:")) + b.Write("\n" + strings.Join(commands, "\n")) + b.Close() + out.WriteLine(output.Styledf(output.StyleSuggestion, "Note that you may need to do some additional setup, such as authentication, beforehand.")) + } return nil }, usageFunc: func() { fmt.Fprint(flag.CommandLine.Output(), usage) }, diff --git a/cmd/src/snapshot_restore.go b/cmd/src/snapshot_restore.go new file mode 100644 index 0000000000..a1d71018fa --- /dev/null +++ b/cmd/src/snapshot_restore.go @@ -0,0 +1,108 @@ +package main + +import ( + "flag" + "fmt" + "os" + "os/exec" + "strings" + + "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/output" + "gopkg.in/yaml.v3" + + "github.com/sourcegraph/src-cli/internal/pgdump" +) + +func init() { + usage := `'src snapshot restore' restores a Sourcegraph instance using Sourcegraph database dumps. +Note that these commands are intended for use as reference - you may need to adjust the commands for your deployment. + +USAGE + src [-v] snapshot restore [--targets] [--run] + +TARGETS FILES + Predefined targets are available based on default Sourcegraph configurations ('docker', 'k8s'). + Custom targets configuration can be provided in YAML format with '--targets=target.yaml', e.g. + + primary: + target: ... # the DSN of the database deployment, e.g. in docker, the name of the database container + dbname: ... # name of database + username: ... # username for database access + password: ... # password for database access - only include password if it is non-sensitive + codeintel: + # same as above + codeinsights: + # same as above + + See the pgdump.Targets type for more details. +` + + flagSet := flag.NewFlagSet("restore", flag.ExitOnError) + targetsKeyFlag := flagSet.String("targets", "auto", "predefined targets ('docker' or 'k8s'), or a custom targets.yaml file") + run := flagSet.Bool("run", false, "Automatically run the commands") + + snapshotCommands = append(snapshotCommands, &command{ + flagSet: flagSet, + handler: func(args []string) error { + if err := flagSet.Parse(args); err != nil { + return err + } + out := output.NewOutput(flagSet.Output(), output.OutputOpts{Verbose: *verbose}) + + builder := flagSet.Arg(0) + + commandBuilder, targetKey := pgdump.Builder(builder, pgdump.RestoreCommand) + if targetKey == "" { + return errors.Newf("unknown or invalid template type %q", builder) + } + + if *targetsKeyFlag != "auto" { + targetKey = *targetsKeyFlag + } + + targets, ok := predefinedDatabaseDumpTargets[targetKey] + if !ok { + out.WriteLine(output.Emojif(output.EmojiInfo, "Using targets defined in targets file %q", targetKey)) + f, err := os.Open(targetKey) + if err != nil { + return errors.Wrapf(err, "invalid targets file %q", targetKey) + } + if err := yaml.NewDecoder(f).Decode(&targets); err != nil { + return errors.Wrapf(err, "invalid targets file %q", targetKey) + } + } else { + out.WriteLine(output.Emojif(output.EmojiInfo, "Using predefined targets for %s environments", targetKey)) + } + + commands, err := pgdump.BuildCommands(srcSnapshotDir, commandBuilder, targets, false) + if err != nil { + return errors.Wrap(err, "failed to build commands") + } + if *run { + for _, c := range commands { + out.WriteLine(output.Emojif(output.EmojiInfo, "Running command: %q", c)) + command := exec.Command("bash", "-c", c) + output, err := command.CombinedOutput() + out.Write(string(output)) + if err != nil { + return errors.Wrapf(err, "failed to run command: %q", c) + } + } + + out.WriteLine(output.Emoji(output.EmojiSuccess, "Successfully completed restore commands")) + out.WriteLine(output.Styledf(output.StyleSuggestion, "It may be necessary to restart your Sourcegraph instance after restoring")) + } else { + b := out.Block(output.Emoji(output.EmojiSuccess, "Run these commands to restore the databases:")) + b.Write("\n" + strings.Join(commands, "\n")) + b.Close() + + out.WriteLine(output.Styledf(output.StyleSuggestion, "Note that you may need to do some additional setup, such as authentication, beforehand.")) + } + + return nil + }, + + usageFunc: func() { fmt.Fprint(flag.CommandLine.Output(), usage) }, + }) +} diff --git a/internal/pgdump/pgdump.go b/internal/pgdump/pgdump.go index c7941ed5ba..6734342bbe 100644 --- a/internal/pgdump/pgdump.go +++ b/internal/pgdump/pgdump.go @@ -30,9 +30,19 @@ type Target struct { Password string `yaml:"password"` } -// Command generates a pg_dump command that can be used for on-prem-to-Cloud migrations. -func Command(t Target) string { - dump := fmt.Sprintf("pg_dump --no-owner --format=p --no-acl --username=%s --dbname=%s", +// RestoreCommand generates a psql command that can be used for migrations. +func RestoreCommand(t Target) string { + dump := fmt.Sprintf("psql --username=%s --dbname=%s 1>/dev/null", + t.Username, t.DBName) + if t.Password == "" { + return dump + } + return fmt.Sprintf("PGPASSWORD=%s %s", t.Password, dump) +} + +// DumpCommand generates a pg_dump command that can be used for on-prem-to-Cloud migrations. +func DumpCommand(t Target) string { + dump := fmt.Sprintf("pg_dump --no-owner --format=p --no-acl --clean --if-exists --username=%s --dbname=%s", t.Username, t.DBName) if t.Password == "" { return dump @@ -61,17 +71,53 @@ func Outputs(dir string, targets Targets) []Output { } type CommandBuilder func(Target) (string, error) +type PGCommand func(Target) string + +// Builder generates the CommandBuilder and targetKey for a given builder and PGCommand +func Builder(builder string, command PGCommand) (commandBuilder CommandBuilder, targetKey string) { + switch builder { + case "pg_dump", "": + targetKey = "local" + commandBuilder = func(t Target) (string, error) { + cmd := command(t) + if t.Target != "" { + return fmt.Sprintf("%s --host=%s", cmd, t.Target), nil + } + return cmd, nil + } + case "docker": + targetKey = "docker" + commandBuilder = func(t Target) (string, error) { + return fmt.Sprintf("docker exec -i %s sh -c '%s'", t.Target, command(t)), nil + } + case "kubectl": + targetKey = "k8s" + commandBuilder = func(t Target) (string, error) { + return fmt.Sprintf("kubectl exec -i %s -- bash -c '%s'", t.Target, command(t)), nil + } + default: + return commandBuilder, targetKey + } + return commandBuilder, targetKey +} // BuildCommands generates commands that output Postgres dumps and sends them to predefined // files for each target database. -func BuildCommands(outDir string, commandBuilder CommandBuilder, targets Targets) ([]string, error) { +func BuildCommands(outDir string, commandBuilder CommandBuilder, targets Targets, dump bool) ([]string, error) { var commands []string for _, t := range Outputs(outDir, targets) { c, err := commandBuilder(t.Target) if err != nil { return nil, errors.Wrapf(err, "generating command for %q", t.Output) } - commands = append(commands, fmt.Sprintf("%s > %s", c, t.Output)) + + if dump { + // When dumping use output redirection to dump command stdout to target file + commands = append(commands, fmt.Sprintf("%s > %s", c, t.Output)) + } else { + // When restoring use input redirection to pass target file to command stdin + commands = append(commands, fmt.Sprintf("%s < %s", c, t.Output)) + } } return commands, nil } From 85115b1a8a2e1bc174075eefacbae6ad9d19af1f Mon Sep 17 00:00:00 2001 From: Jean-Hadrien Chabran Date: Wed, 8 Mar 2023 19:12:07 +0100 Subject: [PATCH 310/647] Update to Go 1.19.6 (#946) * Update asdf to Go 1.19.6 * Also test against go 1.19.x * fixup --- .github/workflows/go-ci.yml | 2 +- .tool-versions | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/go-ci.yml b/.github/workflows/go-ci.yml index 5f5f19d1fa..e22cae2d57 100644 --- a/.github/workflows/go-ci.yml +++ b/.github/workflows/go-ci.yml @@ -7,7 +7,7 @@ jobs: go-test: strategy: matrix: - go-version: [1.18.x] + go-version: [1.18.x,1.19.x] os: [ubuntu-latest, macos-latest, windows-latest] runs-on: ${{ matrix.os }} steps: diff --git a/.tool-versions b/.tool-versions index 1fd8168ccb..7a8f1310f6 100644 --- a/.tool-versions +++ b/.tool-versions @@ -1,3 +1,3 @@ -golang 1.19.3 +golang 1.19.6 shfmt 3.2.0 shellcheck 0.7.1 From 42706ee04205b9d9476ac35536e2a7f932a313d8 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Fri, 10 Mar 2023 01:25:51 +0100 Subject: [PATCH 311/647] version: Clarify origin of error (#953) This could be confusing, it only says server error and prints details on that, so it sounds like src-cli just broke? At least it confused people at Sourcegraph. This prefixes it with some more context to help that. --- cmd/src/version.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/cmd/src/version.go b/cmd/src/version.go index c76e67b235..024ab0600e 100644 --- a/cmd/src/version.go +++ b/cmd/src/version.go @@ -8,6 +8,8 @@ import ( "io" "net/http" + "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/version" ) @@ -37,7 +39,7 @@ Examples: client := cfg.apiClient(apiFlags, flagSet.Output()) recommendedVersion, err := getRecommendedVersion(context.Background(), client) if err != nil { - return err + return errors.Wrap(err, "failed to get recommended version for Sourcegraph deployment") } if recommendedVersion == "" { fmt.Println("Recommended version: ") From 07cb66dad179d6da248ec2d70c1af6dcda2d83aa Mon Sep 17 00:00:00 2001 From: leo Date: Mon, 13 Mar 2023 15:38:38 +0000 Subject: [PATCH 312/647] Add changelog entries for Own-related additions (#954) --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index f6744d89e6..e162c5782b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,9 @@ All notable changes to `src-cli` are documented in this file. ### Added +- `src team` (experimental) has been added to manage teams. [#922](https://github.com/sourcegraph/src-cli/pull/922) +- `src codeowners` (experimental) has been added to manage manually ingested `CODEOWNERS`. [#943](https://github.com/sourcegraph/src-cli/pull/943) + ### Changed ### Fixed From 422a71cb2fabce9cc682ed0b8a194ebcd6439944 Mon Sep 17 00:00:00 2001 From: coury-clark Date: Mon, 13 Mar 2023 12:30:33 -0700 Subject: [PATCH 313/647] changelog: cut sourcegraph@5.0.0 (#955) --- CHANGELOG.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index e162c5782b..b85bd43e7c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,16 @@ All notable changes to `src-cli` are documented in this file. ### Added +### Changed + +### Fixed + +### Removed + +## 5.0.0 + +### Added + - `src team` (experimental) has been added to manage teams. [#922](https://github.com/sourcegraph/src-cli/pull/922) - `src codeowners` (experimental) has been added to manage manually ingested `CODEOWNERS`. [#943](https://github.com/sourcegraph/src-cli/pull/943) From db398d07e2857463a9be96e9fd147ccc5af45bef Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Thu, 16 Mar 2023 16:01:18 +0100 Subject: [PATCH 314/647] Bump sourcegraph dependency to fix version parsing of insiders (#959) For untagged versions, we added the current Sourcegraph version as well, so the parsing didn't work anymore. This fixes it. --- .github/workflows/go-ci.yml | 2 +- .github/workflows/go-lint.yml | 2 +- .github/workflows/goreleaser-check.yml | 2 +- .github/workflows/goreleaser.yml | 2 +- .github/workflows/pr-auditor.yml | 2 +- CHANGELOG.md | 6 + cmd/src/snapshot_upload.go | 4 +- dev/golangci-lint.sh | 2 +- go.mod | 66 +++---- go.sum | 164 ++++++++++-------- internal/batches/docker/context.go | 8 +- internal/batches/executor/coordinator.go | 2 +- internal/batches/log/noop_task_logger.go | 8 +- internal/batches/service/remote.go | 2 + internal/batches/service/remote_test.go | 14 +- .../batches/service/remote_windows_test.go | 2 + internal/validate/kube/gke.go | 21 ++- 17 files changed, 169 insertions(+), 140 deletions(-) diff --git a/.github/workflows/go-ci.yml b/.github/workflows/go-ci.yml index e22cae2d57..b25f3ab262 100644 --- a/.github/workflows/go-ci.yml +++ b/.github/workflows/go-ci.yml @@ -7,7 +7,7 @@ jobs: go-test: strategy: matrix: - go-version: [1.18.x,1.19.x] + go-version: [1.19.x] os: [ubuntu-latest, macos-latest, windows-latest] runs-on: ${{ matrix.os }} steps: diff --git a/.github/workflows/go-lint.yml b/.github/workflows/go-lint.yml index cb1accdbe3..3561c53e88 100644 --- a/.github/workflows/go-lint.yml +++ b/.github/workflows/go-lint.yml @@ -12,5 +12,5 @@ jobs: - name: Set up Go uses: actions/setup-go@v3 with: - go-version: 1.18.x + go-version: 1.19.x - run: ./dev/go-lint.sh diff --git a/.github/workflows/goreleaser-check.yml b/.github/workflows/goreleaser-check.yml index d5723607a0..07801fd96f 100644 --- a/.github/workflows/goreleaser-check.yml +++ b/.github/workflows/goreleaser-check.yml @@ -15,7 +15,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v3 with: - go-version: 1.18 + go-version: 1.19 - name: Check GoReleaser config uses: goreleaser/goreleaser-action@v2 with: diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index 11acdb772e..b344d9012d 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -177,7 +177,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v3 with: - go-version: 1.18 + go-version: 1.19 - run: go get -d -t ./... - run: go test -i ./... - run: go test -race -v ./... diff --git a/.github/workflows/pr-auditor.yml b/.github/workflows/pr-auditor.yml index 626ebc4a07..5c6ba2e0a4 100644 --- a/.github/workflows/pr-auditor.yml +++ b/.github/workflows/pr-auditor.yml @@ -11,7 +11,7 @@ jobs: - uses: actions/checkout@v3 with: { repository: 'sourcegraph/sourcegraph' } - uses: actions/setup-go@v2 - with: { go-version: '1.18' } + with: { go-version: '1.19' } - run: ./dev/pr-auditor/check-pr.sh env: diff --git a/CHANGELOG.md b/CHANGELOG.md index b85bd43e7c..6572b67c18 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,12 @@ All notable changes to `src-cli` are documented in this file. ### Removed +## 5.0.1 + +### Fixed + +- Fixed `failed to check version returned by Sourcegraph: Invalid Semantic Version` error in Batch Changes when running against an insiders version of Sourcegraph. + ## 5.0.0 ### Added diff --git a/cmd/src/snapshot_upload.go b/cmd/src/snapshot_upload.go index eef0d31042..b96df483d9 100644 --- a/cmd/src/snapshot_upload.go +++ b/cmd/src/snapshot_upload.go @@ -10,8 +10,8 @@ import ( "path" "cloud.google.com/go/storage" + "github.com/sourcegraph/conc/pool" "github.com/sourcegraph/sourcegraph/lib/errors" - "github.com/sourcegraph/sourcegraph/lib/group" "github.com/sourcegraph/sourcegraph/lib/output" "google.golang.org/api/option" @@ -113,7 +113,7 @@ BUCKET progress := out.Progress(progressBars, nil) progress.WriteLine(output.Emoji(output.EmojiHourglass, "Starting uploads...")) bucket := c.Bucket(*bucketName) - g := group.New().WithErrors().WithContext(ctx) + g := pool.New().WithErrors().WithContext(ctx) for i, u := range uploads { i := i u := u diff --git a/dev/golangci-lint.sh b/dev/golangci-lint.sh index 97d8d8afcd..9f23e2a9fd 100755 --- a/dev/golangci-lint.sh +++ b/dev/golangci-lint.sh @@ -6,7 +6,7 @@ pushd "$(dirname "${BASH_SOURCE[0]}")/.." >/dev/null mkdir -p dev/.bin -version="1.45.2" +version="1.51.2" suffix="${version}-$(go env GOOS)-$(go env GOARCH)" target="$PWD/dev/.bin/golangci-lint-${suffix}" url="https://github.com/golangci/golangci-lint/releases/download/v${version}/golangci-lint-${suffix}.tar.gz" diff --git a/go.mod b/go.mod index cfb74c15e7..5207edaacd 100644 --- a/go.mod +++ b/go.mod @@ -11,10 +11,10 @@ require ( github.com/creack/goselect v0.1.2 github.com/derision-test/glock v0.0.0-20210316032053-f5b74334bb29 github.com/dineshappavoo/basex v0.0.0-20170425072625-481a6f6dc663 - github.com/dustin/go-humanize v1.0.0 + github.com/dustin/go-humanize v1.0.1 github.com/gobwas/glob v0.2.3 github.com/google/go-cmp v0.5.9 - github.com/grafana/regexp v0.0.0-20220304100321-149c8afcd6cb + github.com/grafana/regexp v0.0.0-20221123153739-15dc172cd2db github.com/hexops/autogold v1.3.0 github.com/jedib0t/go-pretty/v6 v6.3.7 github.com/jig/teereadcloser v0.0.0-20181016160506-953720c48e05 @@ -22,12 +22,13 @@ require ( github.com/mattn/go-isatty v0.0.16 github.com/neelance/parallel v0.0.0-20160708114440-4de9ce63d14c github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 - github.com/sourcegraph/go-diff v0.6.1 + github.com/sourcegraph/conc v0.3.0 + github.com/sourcegraph/go-diff v0.6.2-0.20221123165719-f8cd299c40f3 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf - github.com/sourcegraph/scip v0.2.3 - github.com/sourcegraph/sourcegraph/lib v0.0.0-20230113014457-46187b849239 + github.com/sourcegraph/scip v0.2.4-0.20221213205653-aa0e511dcfef + github.com/sourcegraph/sourcegraph/lib v0.0.0-20230316093010-26299ec302d0 github.com/stretchr/testify v1.8.1 - golang.org/x/net v0.7.0 + golang.org/x/net v0.8.0 golang.org/x/sync v0.1.0 google.golang.org/api v0.110.0 google.golang.org/protobuf v1.28.1 @@ -44,10 +45,10 @@ require ( cloud.google.com/go/compute/metadata v0.2.3 // indirect cloud.google.com/go/iam v0.12.0 // indirect github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect + github.com/Masterminds/goutils v1.1.1 // indirect github.com/Masterminds/semver v1.5.0 // indirect - github.com/Masterminds/sprig v2.15.0+incompatible // indirect + github.com/Masterminds/sprig v2.22.0+incompatible // indirect github.com/alecthomas/chroma v0.10.0 // indirect - github.com/aokoli/goutils v1.0.1 // indirect github.com/aws/aws-sdk-go-v2 v1.17.5 // indirect github.com/aws/aws-sdk-go-v2/credentials v1.13.13 // indirect github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.12.22 // indirect @@ -67,11 +68,11 @@ require ( github.com/cockroachdb/redact v1.1.3 // indirect github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect github.com/davecgh/go-spew v1.1.1 // indirect - github.com/dlclark/regexp2 v1.4.0 // indirect + github.com/dlclark/regexp2 v1.7.0 // indirect github.com/emicklei/go-restful/v3 v3.9.0 // indirect github.com/envoyproxy/protoc-gen-validate v0.9.1 // indirect github.com/fatih/color v1.13.0 // indirect - github.com/getsentry/sentry-go v0.13.0 // indirect + github.com/getsentry/sentry-go v0.15.0 // indirect github.com/ghodss/yaml v1.0.0 // indirect github.com/go-logr/logr v1.2.3 // indirect github.com/go-openapi/jsonpointer v0.19.5 // indirect @@ -89,9 +90,9 @@ require ( github.com/googleapis/gax-go/v2 v2.7.0 // indirect github.com/gorilla/css v1.0.0 // indirect github.com/hexops/gotextdiff v1.0.3 // indirect - github.com/hexops/valast v1.4.1 // indirect - github.com/huandu/xstrings v1.0.0 // indirect - github.com/imdario/mergo v0.3.6 // indirect + github.com/hexops/valast v1.4.3 // indirect + github.com/huandu/xstrings v1.3.2 // indirect + github.com/imdario/mergo v0.3.13 // indirect github.com/inconshreveable/mousetrap v1.0.1 // indirect github.com/jdxcode/netrc v0.0.0-20210204082910-926c7f70242a // indirect github.com/jhump/protocompile v0.0.0-20220216033700-d705409f108f // indirect @@ -99,15 +100,17 @@ require ( github.com/jmespath/go-jmespath v0.4.0 // indirect github.com/josharian/intern v1.0.0 // indirect github.com/json-iterator/go v1.1.12 // indirect - github.com/klauspost/compress v1.15.1 // indirect + github.com/klauspost/compress v1.15.11 // indirect github.com/klauspost/pgzip v1.2.5 // indirect - github.com/kr/pretty v0.3.0 // indirect + github.com/kr/pretty v0.3.1 // indirect github.com/kr/text v0.2.0 // indirect github.com/lucasb-eyer/go-colorful v1.2.0 // indirect - github.com/mailru/easyjson v0.7.6 // indirect + github.com/mailru/easyjson v0.7.7 // indirect github.com/mattn/go-colorable v0.1.13 // indirect - github.com/mattn/go-runewidth v0.0.13 // indirect + github.com/mattn/go-runewidth v0.0.14 // indirect github.com/microcosm-cc/bluemonday v1.0.22 // indirect + github.com/mitchellh/copystructure v1.2.0 // indirect + github.com/mitchellh/reflectwalk v1.0.2 // indirect github.com/moby/spdystream v0.2.0 // indirect github.com/moby/term v0.0.0-20220808134915-39b0c02b01ae // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect @@ -115,7 +118,7 @@ require ( github.com/muesli/reflow v0.3.0 // indirect github.com/muesli/termenv v0.12.0 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect - github.com/mwitkow/go-proto-validators v0.0.0-20180403085117-0950a7990007 // indirect + github.com/mwitkow/go-proto-validators v0.3.2 // indirect github.com/nightlyone/lockfile v1.0.0 // indirect github.com/olekukonko/tablewriter v0.0.5 // indirect github.com/pkg/errors v0.9.1 // indirect @@ -123,11 +126,10 @@ require ( github.com/pmezard/go-difflib v1.0.0 // indirect github.com/pseudomuto/protoc-gen-doc v1.5.1 // indirect github.com/pseudomuto/protokit v0.2.0 // indirect - github.com/rivo/uniseg v0.2.0 // indirect + github.com/rivo/uniseg v0.4.2 // indirect github.com/rogpeppe/go-internal v1.9.0 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect - github.com/shurcooL/go-goon v0.0.0-20210110234559-7585751d9a17 // indirect - github.com/sourcegraph/log v0.0.0-20220901143117-fc0516a694c9 // indirect + github.com/sourcegraph/log v0.0.0-20221206163500-7d93c6ad7037 // indirect github.com/spf13/cobra v1.6.0 // indirect github.com/spf13/pflag v1.0.5 // indirect github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect @@ -135,20 +137,20 @@ require ( github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect github.com/xeipuuv/gojsonschema v1.2.0 // indirect - github.com/yuin/goldmark v1.4.13 // indirect + github.com/yuin/goldmark v1.5.2 // indirect github.com/yuin/goldmark-emoji v1.0.1 // indirect go.opencensus.io v0.24.0 // indirect go.uber.org/atomic v1.10.0 // indirect - go.uber.org/multierr v1.8.0 // indirect - go.uber.org/zap v1.23.0 // indirect - golang.org/x/crypto v0.1.0 // indirect - golang.org/x/mod v0.7.0 // indirect + go.uber.org/multierr v1.9.0 // indirect + go.uber.org/zap v1.24.0 // indirect + golang.org/x/crypto v0.3.0 // indirect + golang.org/x/mod v0.9.0 // indirect golang.org/x/oauth2 v0.5.0 // indirect - golang.org/x/sys v0.5.0 // indirect - golang.org/x/term v0.5.0 // indirect - golang.org/x/text v0.7.0 // indirect - golang.org/x/time v0.0.0-20220210224613-90d013bbcef8 // indirect - golang.org/x/tools v0.5.0 // indirect + golang.org/x/sys v0.6.0 // indirect + golang.org/x/term v0.6.0 // indirect + golang.org/x/text v0.8.0 // indirect + golang.org/x/time v0.0.0-20220922220347-f3bd1da661af // indirect + golang.org/x/tools v0.7.0 // indirect golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 // indirect google.golang.org/appengine v1.6.7 // indirect google.golang.org/genproto v0.0.0-20230216225411-c8e22ba71e44 // indirect @@ -158,7 +160,7 @@ require ( k8s.io/klog/v2 v2.80.1 // indirect k8s.io/kube-openapi v0.0.0-20221012153701-172d655c2280 // indirect k8s.io/utils v0.0.0-20221107191617-1a15be271d1d // indirect - mvdan.cc/gofumpt v0.2.1 // indirect + mvdan.cc/gofumpt v0.4.0 // indirect sigs.k8s.io/json v0.0.0-20220713155537-f223a00ba0e2 // indirect sigs.k8s.io/structured-merge-diff/v4 v4.2.3 // indirect sigs.k8s.io/yaml v1.3.0 // indirect diff --git a/go.sum b/go.sum index e483eaebdc..37e963bd89 100644 --- a/go.sum +++ b/go.sum @@ -20,16 +20,16 @@ github.com/CloudyKit/jet v2.1.3-0.20180809161101-62edd43e4f88+incompatible/go.mo github.com/CloudyKit/jet/v3 v3.0.0/go.mod h1:HKQPgSJmdK8hdoAbKUUWajkHyHo4RaU5rMdUywE7VMo= github.com/Joker/hpp v1.0.0/go.mod h1:8x5n+M1Hp5hC0g8okX3sR3vFQwynaX/UgSOM9MeBKzY= github.com/Joker/jade v1.0.1-0.20190614124447-d475f43051e7/go.mod h1:6E6s8o2AE4KhCrqr6GRJjdC/gNfTdxkIXvuGZZda2VM= +github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI= +github.com/Masterminds/goutils v1.1.1/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU= github.com/Masterminds/semver v1.5.0 h1:H65muMkzWKEuNDnfl9d70GUjFniHKHRbFPGBuZ3QEww= github.com/Masterminds/semver v1.5.0/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y= -github.com/Masterminds/sprig v2.15.0+incompatible h1:0gSxPGWS9PAr7U2NsQ2YQg6juRDINkUyuvbb4b2Xm8w= -github.com/Masterminds/sprig v2.15.0+incompatible/go.mod h1:y6hNFY5UBTIWBxnzTeuNhlNS5hqE0NB0E6fgfo2Br3o= +github.com/Masterminds/sprig v2.22.0+incompatible h1:z4yfnGrZ7netVz+0EDJ0Wi+5VZCSYp4Z0m2dk6cEM60= +github.com/Masterminds/sprig v2.22.0+incompatible/go.mod h1:y6hNFY5UBTIWBxnzTeuNhlNS5hqE0NB0E6fgfo2Br3o= github.com/Shopify/goreferrer v0.0.0-20181106222321-ec9c9a553398/go.mod h1:a1uqRtAwp2Xwc6WNPJEufxJ7fx3npB4UV/JOLmbu5I0= github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY= github.com/alecthomas/chroma v0.10.0 h1:7XDcGkCQopCNKjZHfYrNLraA+M7e0fMiJ/Mfikbfjek= github.com/alecthomas/chroma v0.10.0/go.mod h1:jtJATyUxlIORhUOFNA9NZDWGAQ8wpxQQqNSB4rjA/1s= -github.com/aokoli/goutils v1.0.1 h1:7fpzNGoJ3VA8qcrm++XEE1QUe0mIwNeLa02Nwq7RDkg= -github.com/aokoli/goutils v1.0.1/go.mod h1:SijmP0QR8LtwsmDs8Yii5Z/S4trXFGFC2oO5g9DP+DQ= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio= github.com/aws/aws-sdk-go-v2 v1.17.4/go.mod h1:uzbQtefpm44goOPmdKyAlXSNcwlRgF3ePWVW6EtJvvw= @@ -111,11 +111,13 @@ github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZm github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= github.com/dineshappavoo/basex v0.0.0-20170425072625-481a6f6dc663 h1:fctNkSsavbXpt8geFWZb8n+noCqS8MrOXRJ/YfdZ2dQ= github.com/dineshappavoo/basex v0.0.0-20170425072625-481a6f6dc663/go.mod h1:Kad2hux31v/IyD4Rf4wAwIyK48995rs3qAl9IUAhc2k= -github.com/dlclark/regexp2 v1.4.0 h1:F1rxgk7p4uKjwIQxBs9oAXe5CqrXlCduYEJvrF4u93E= github.com/dlclark/regexp2 v1.4.0/go.mod h1:2pZnwuY/m+8K6iRw6wQdMtk+rH5tNGR1i55kozfMjCc= +github.com/dlclark/regexp2 v1.7.0 h1:7lJfhqlPssTb1WQx4yvTHN0uElPEv52sbaECrAQxjAo= +github.com/dlclark/regexp2 v1.7.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= github.com/docopt/docopt-go v0.0.0-20180111231733-ee0de3bc6815/go.mod h1:WwZ+bS3ebgob9U8Nd0kOddGdZWjyMGR8Wziv+TBNwSE= -github.com/dustin/go-humanize v1.0.0 h1:VSnTsYCnlFHaM2/igO1h6X3HA71jcobQuxemgkq4zYo= github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= +github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/eknkc/amber v0.0.0-20171010120322-cdade1c07385/go.mod h1:0vRUJqYpeSZifjYj7uP3BG/gKcuzL9xWVV/Y+cK33KM= github.com/elazarl/goproxy v0.0.0-20180725130230-947c36da3153 h1:yUdfgN0XgIJw7foRItutHYUIhlcKzcSf5vDpdhQAKTc= github.com/emicklei/go-restful/v3 v3.9.0 h1:XwGDlfxEnQZzuopoqxwSEllNcCOM9DhhFyhFIIGKwxE= @@ -133,19 +135,19 @@ github.com/fatih/color v1.13.0 h1:8LOYc1KYPPmyKMuN8QV2DNRWNbLo6LZ0iLs8+mlH53w= github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M= github.com/flosch/pongo2 v0.0.0-20190707114632-bbf5a6c351f4/go.mod h1:T9YF2M40nIgbVgp3rreNmTged+9HrbNTIQf1PsaIiTA= -github.com/frankban/quicktest v1.14.0 h1:+cqqvzZV87b4adx/5ayVOaYZ2CrvM4ejQvUdBzPPUss= -github.com/frankban/quicktest v1.14.0/go.mod h1:NeW+ay9A/U67EYXNFA1nPE8e/tnQv/09mUdL/ijj8og= +github.com/frankban/quicktest v1.14.3 h1:FJKSZTDHjyhriyC81FLQ0LY93eSai0ZyR/ZIkd3ZUKE= +github.com/frankban/quicktest v1.14.3/go.mod h1:mgiwOwqx65TmIk1wJ6Q7wvnVMocbUorkibMOrVTHZps= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/gavv/httpexpect v2.0.0+incompatible/go.mod h1:x+9tiU1YnrOvnB725RkpoLv1M62hOWzwo5OXotisrKc= github.com/getsentry/sentry-go v0.12.0/go.mod h1:NSap0JBYWzHND8oMbyi0+XZhUalc1TBdRL1M71JZW2c= -github.com/getsentry/sentry-go v0.13.0 h1:20dgTiUSfxRB/EhMPtxcL9ZEbM1ZdR+W/7f7NWD+xWo= -github.com/getsentry/sentry-go v0.13.0/go.mod h1:EOsfu5ZdvKPfeHYV6pTVQnsjfp30+XA7//UooKNumH0= +github.com/getsentry/sentry-go v0.15.0 h1:CP9bmA7pralrVUedYZsmIHWpq/pBtXTSew7xvVpfLaA= +github.com/getsentry/sentry-go v0.15.0/go.mod h1:RZPJKSw+adu8PBNygiri/A98FqVr2HtRckJk9XVxJ9I= github.com/gin-contrib/sse v0.0.0-20190301062529-5545eab6dad3/go.mod h1:VJ0WA2NBN22VlZ2dKZQPAPnyWw5XTlK1KymzLKsr59s= github.com/gin-gonic/gin v1.4.0/go.mod h1:OW2EZn3DO8Ln9oIKOvM++LBO+5UPHJJDH72/q/3rZdM= github.com/go-check/check v0.0.0-20180628173108-788fd7840127/go.mod h1:9ES+weclKsC9YodN5RgxqK/VD9HM9JsCSh7rNhMZE98= -github.com/go-errors/errors v1.0.1 h1:LUHzmkK3GUKUrL/1gfBUxAHzcev3apQlezX/+O7ma6w= github.com/go-errors/errors v1.0.1/go.mod h1:f4zRHt4oKfwPJE5k8C9vpYG+aDHdBFUsgrm6/TyX73Q= +github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA= github.com/go-logr/logr v1.2.0/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.2.3 h1:2DntVwHkVopvECVRSlL5PSo9eG+cAkDCuckLubN+rq0= github.com/go-logr/logr v1.2.3/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= @@ -170,6 +172,7 @@ github.com/gofrs/uuid v4.2.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRx github.com/gogo/googleapis v0.0.0-20180223154316-0cd9801be74a/go.mod h1:gf4bu3Q80BeJ6H1S1vYPm8/ELATdvryBaNFGgqEef3s= github.com/gogo/googleapis v1.4.1/go.mod h1:2lpHqI5OcWCtVElxXnPt+s8oJvMpySlOyM6xDCrzib4= github.com/gogo/protobuf v1.2.0/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= +github.com/gogo/protobuf v1.3.0/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= @@ -207,7 +210,7 @@ github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE= github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= @@ -229,8 +232,8 @@ github.com/gorilla/css v1.0.0/go.mod h1:Dn721qIggHpt4+EFCcTLTU/vk5ySda2ReITrtgBl github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= -github.com/grafana/regexp v0.0.0-20220304100321-149c8afcd6cb h1:wwzNkyaQwcXCzQuKoWz3lwngetmcyg+EhW0fF5lz73M= -github.com/grafana/regexp v0.0.0-20220304100321-149c8afcd6cb/go.mod h1:M5qHK+eWfAv8VR/265dIuEpL3fNfeC21tXXp9itM24A= +github.com/grafana/regexp v0.0.0-20221123153739-15dc172cd2db h1:7aN5cccjIqCLTzedH7MZzRZt5/lsAHch6Z3L2ZGn5FA= +github.com/grafana/regexp v0.0.0-20221123153739-15dc172cd2db/go.mod h1:M5qHK+eWfAv8VR/265dIuEpL3fNfeC21tXXp9itM24A= github.com/hashicorp/go-version v1.2.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= github.com/hexops/autogold v0.8.1/go.mod h1:97HLDXyG23akzAoRYJh/2OBs3kd80eHyKPvZw0S5ZBY= @@ -239,15 +242,15 @@ github.com/hexops/autogold v1.3.0/go.mod h1:d4hwi2rid66Sag+BVuHgwakW/EmaFr8vdTSb github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM= github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg= github.com/hexops/valast v1.4.0/go.mod h1:uVjKZ0smVuYlgCSPz9NRi5A04sl7lp6GtFWsROKDgEs= -github.com/hexops/valast v1.4.1 h1:vlB+usah+MLacCyDDqACn2yhAoCDlpHYkpEKtej+RXE= -github.com/hexops/valast v1.4.1/go.mod h1:G+D6TExWuKs5he+hYlPMfYyhQ8w8qbc2vm4gDWwLdDg= +github.com/hexops/valast v1.4.3 h1:oBoGERMJh6UZdRc6cduE1CTPK+VAdXA59Y1HFgu3sm0= +github.com/hexops/valast v1.4.3/go.mod h1:Iqx2kLj3Jn47wuXpj3wX40xn6F93QNFBHuiKBerkTGA= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= -github.com/huandu/xstrings v1.0.0 h1:pO2K/gKgKaat5LdpAhxhluX2GPQMaI3W5FUz/I/UnWk= -github.com/huandu/xstrings v1.0.0/go.mod h1:4qWG/gcEcfX4z/mBDHJ++3ReCw9ibxbsNJbcucJdbSo= +github.com/huandu/xstrings v1.3.2 h1:L18LIDzqlW6xN2rEkpdV8+oL/IXWJ1APd+vsdYy4Wdw= +github.com/huandu/xstrings v1.3.2/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE= github.com/hydrogen18/memlistener v0.0.0-20141126152155-54553eb933fb/go.mod h1:qEIFzExnS6016fRpRfxrExeVn2gbClQA99gQhnIcdhE= github.com/hydrogen18/memlistener v0.0.0-20200120041712-dcc25e7acd91/go.mod h1:qEIFzExnS6016fRpRfxrExeVn2gbClQA99gQhnIcdhE= -github.com/imdario/mergo v0.3.6 h1:xTNEAn+kxVO7dTZGu0CegyqKZmoWFI0rF8UxjlB2d28= -github.com/imdario/mergo v0.3.6/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= +github.com/imdario/mergo v0.3.13 h1:lFzP57bqS/wsqKssCGmtLAb8A0wKjLGrve2q3PPVcBk= +github.com/imdario/mergo v0.3.13/go.mod h1:4lJ1jqUDcsbIECGy0RUJAXNIhg+6ocWgb1ALK2O4oXg= github.com/imkira/go-interpol v1.1.0/go.mod h1:z0h2/2T3XF8kyEPpRgJ3kmNv+C43p+I/CoI+jC3w2iA= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/inconshreveable/mousetrap v1.0.1 h1:U3uMjPSQEBMNp1lFxmllqCPM6P5u/Xq7Pgzkat/bFNc= @@ -304,16 +307,17 @@ github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+o github.com/klauspost/compress v1.8.2/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= github.com/klauspost/compress v1.9.0/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= github.com/klauspost/compress v1.9.7/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= -github.com/klauspost/compress v1.15.1 h1:y9FcTHGyrebwfP0ZZqFiaxTaiDnUrGkJkI+f583BL1A= -github.com/klauspost/compress v1.15.1/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= +github.com/klauspost/compress v1.15.11 h1:Lcadnb3RKGin4FYM/orgq0qde+nc15E5Cbqg4B9Sx9c= +github.com/klauspost/compress v1.15.11/go.mod h1:QPwzmACJjUTFsnSHH934V6woptycfrDDJnH7hvFVbGM= github.com/klauspost/cpuid v1.2.1/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek= github.com/klauspost/pgzip v1.2.5 h1:qnWYvvKqedOF2ulHpMG72XQol4ILEJ8k2wwRl/Km8oE= github.com/klauspost/pgzip v1.2.5/go.mod h1:Ch1tH69qFZu15pkjo5kYi6mth2Zzwzt50oCQKQE9RUs= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= -github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= @@ -326,8 +330,9 @@ github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= -github.com/mailru/easyjson v0.7.6 h1:8yTIVnZgCoiM1TgqoeTl+LfU5Jg6/xL3QhGQnimLYnA= github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= +github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= +github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= @@ -344,8 +349,9 @@ github.com/mattn/go-isatty v0.0.16 h1:bq3VjFmv/sOjHtdEhmkEV4x1AJtvUvOJ2PFAZ5+peK github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk= -github.com/mattn/go-runewidth v0.0.13 h1:lTGmDsbAYt5DmK6OnoV7EuIF1wEIFAcxld6ypU4OSgU= github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= +github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU= +github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= github.com/mattn/goveralls v0.0.2/go.mod h1:8d1ZMHsd7fW6IRPKQh46F2WRpyib5/X4FOpevwGNQEw= github.com/mediocregopher/mediocre-go-lib v0.0.0-20181029021733-cb65787f37ed/go.mod h1:dSsfyI2zABAdhcbvkXqgxOxrCsbYeHCPgrZkku60dSg= github.com/mediocregopher/radix/v3 v3.3.0/go.mod h1:EmfVyvspXz1uZEyPBMyGK+kjWiKQGvsUt6O3Pj+LDCQ= @@ -355,9 +361,11 @@ github.com/microcosm-cc/bluemonday v1.0.17/go.mod h1:Z0r70sCuXHig8YpBzCc5eGHAap2 github.com/microcosm-cc/bluemonday v1.0.22 h1:p2tT7RNzRdCi0qmwxG+HbqD6ILkmwter1ZwVZn1oTxA= github.com/microcosm-cc/bluemonday v1.0.22/go.mod h1:ytNkv4RrDrLJ2pqlsSI46O6IVXmZOBBD4SaJyDwwTkM= github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw= +github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ= +github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= github.com/moby/spdystream v0.2.0 h1:cjW1zVyyoiM0T7b6UoySUFqzXMoqRckQtXwGPiBhOM8= github.com/moby/spdystream v0.2.0/go.mod h1:f7i0iNDQJ059oMTcWxx8MA/zKFIuD/lY+0GqbN2Wy8c= github.com/moby/term v0.0.0-20220808134915-39b0c02b01ae h1:O4SWKdcHVCvYqyDV+9CJA1fcDN2L11Bule0iFy3YlAI= @@ -377,8 +385,8 @@ github.com/muesli/termenv v0.12.0 h1:KuQRUE3PgxRFWhq4gHvZtPSLCGDqM5q/cYr1pZ39ytc github.com/muesli/termenv v0.12.0/go.mod h1:WCCv32tusQ/EEZ5S8oUIIrC/nIuBcxCVqlN4Xfkv+7A= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= -github.com/mwitkow/go-proto-validators v0.0.0-20180403085117-0950a7990007 h1:28i1IjGcx8AofiB4N3q5Yls55VEaitzuEPkFJEVgGkA= -github.com/mwitkow/go-proto-validators v0.0.0-20180403085117-0950a7990007/go.mod h1:m2XC9Qq0AlmmVksL6FktJCdTYyLk7V3fKyp0sl1yWQo= +github.com/mwitkow/go-proto-validators v0.3.2 h1:qRlmpTzm2pstMKKzTdvwPCF5QfBNURSlAgN/R+qbKos= +github.com/mwitkow/go-proto-validators v0.3.2/go.mod h1:ej0Qp0qMgHN/KtDyUt+Q1/tA7a5VarXUOUxD+oeD30w= github.com/nats-io/jwt v0.3.0/go.mod h1:fRYCDE99xlTsqUzISS1Bi75UBJ6ljOJQOAAu5VglpSg= github.com/nats-io/nats.go v1.8.1/go.mod h1:BrFz9vVn0fU3AcH9Vn4Kd7W0NpJ651tD5omQ3M8LwxM= github.com/nats-io/nats.go v1.9.1/go.mod h1:ZjDU1L/7fJ09jvUSRVBR2e7+RnLiiIQyqyzEE/Zbp4w= @@ -387,7 +395,6 @@ github.com/nats-io/nkeys v0.1.0/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxzi github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c= github.com/neelance/parallel v0.0.0-20160708114440-4de9ce63d14c h1:NZOii9TDGRAfCS5VM16XnF4K7afoLQmIiZX8EkKnxtE= github.com/neelance/parallel v0.0.0-20160708114440-4de9ce63d14c/go.mod h1:eTBvSIlRgLo+CNFFQRQTwUGTZOEdvXIKeZS/xG+D2yU= -github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/nightlyone/lockfile v1.0.0 h1:RHep2cFKK4PonZJDdEl4GmkabuhbsRMgk/k3uAmxBiA= github.com/nightlyone/lockfile v1.0.0/go.mod h1:rywoIealpdNse2r832aiD9jRk8ErCatROs6LzC841CI= @@ -422,11 +429,11 @@ github.com/pseudomuto/protoc-gen-doc v1.5.1/go.mod h1:XpMKYg6zkcpgfpCfQ8GcWBDRtR github.com/pseudomuto/protokit v0.2.0 h1:hlnBDcy3YEDXH7kc9gV+NLaN0cDzhDvD1s7Y6FZ8RpM= github.com/pseudomuto/protokit v0.2.0/go.mod h1:2PdH30hxVHsup8KpBTOXTBeMVhJZVio3Q8ViKSAXT0Q= github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= -github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY= github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= +github.com/rivo/uniseg v0.4.2 h1:YwD0ulJSJytLpiaWua0sBDusfsCZohxjxzVTYjwxfV8= +github.com/rivo/uniseg v0.4.2/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.6.2/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= -github.com/rogpeppe/go-internal v1.8.1-0.20211023094830-115ce09fd6b4/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= @@ -440,21 +447,22 @@ github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAm github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= github.com/shurcooL/go v0.0.0-20180423040247-9e1955d9fb6e/go.mod h1:TDJrrUr11Vxrven61rcy3hJMUqaf/CLWYhHNPmT14Lk= github.com/shurcooL/go-goon v0.0.0-20170922171312-37c2f522c041/go.mod h1:N5mDOmsrJOB+vfqUK+7DmDyjhSLIIBnXo9lvZJj3MWQ= -github.com/shurcooL/go-goon v0.0.0-20210110234559-7585751d9a17 h1:lRAUE0dIvigSSFAmaM2dfg7OH8T+a8zJ5smEh09a/GI= github.com/shurcooL/go-goon v0.0.0-20210110234559-7585751d9a17/go.mod h1:N5mDOmsrJOB+vfqUK+7DmDyjhSLIIBnXo9lvZJj3MWQ= github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= -github.com/sourcegraph/go-diff v0.6.1 h1:hmA1LzxW0n1c3Q4YbrFgg4P99GSnebYa3x8gr0HZqLQ= -github.com/sourcegraph/go-diff v0.6.1/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= +github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo= +github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0= +github.com/sourcegraph/go-diff v0.6.2-0.20221123165719-f8cd299c40f3 h1:11miag7hlORpW7ici5mL7T9PyiEsmVmf+8PFOvJ/ZrA= +github.com/sourcegraph/go-diff v0.6.2-0.20221123165719-f8cd299c40f3/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= -github.com/sourcegraph/log v0.0.0-20220901143117-fc0516a694c9 h1:JjFyvx9hCD5+JpuRV6t+gTQgGFvwkxXMZzOc4sLiPqc= -github.com/sourcegraph/log v0.0.0-20220901143117-fc0516a694c9/go.mod h1:UxiwB6C3xk3xOySJpW1R0MDUyfGuJRFS5Z8C+SA5p2I= -github.com/sourcegraph/scip v0.2.3 h1:6nRsTlNTELn+1V7JxLrDVbBpb9H1gAbUF48N7x5B8Y4= -github.com/sourcegraph/scip v0.2.3/go.mod h1:3D/RLCMvrrSam85RtFmC67SE/jhV9++hpCR5MTDzbA0= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20230113014457-46187b849239 h1:2yZUA+tBbgRQ6oqjyn0TKHoBMh4UaENMiJIiWmUvKfI= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20230113014457-46187b849239/go.mod h1:HCz/QYbQD5wiwRFYn5ochsMbw6ZNnSgZckE+EYLSBqw= +github.com/sourcegraph/log v0.0.0-20221206163500-7d93c6ad7037 h1:hgZHfGYG3KMlDDfACuPgzhMIaEjblCqZ+YltcPgd0tw= +github.com/sourcegraph/log v0.0.0-20221206163500-7d93c6ad7037/go.mod h1:y+sVdVKxHhp489iiiXeZgXIhSpFYijtp/pLD2coj96g= +github.com/sourcegraph/scip v0.2.4-0.20221213205653-aa0e511dcfef h1:fWPxLkDObzzKTGe9vb6wpzK0FYkwcfSxmxUBvAOc8aw= +github.com/sourcegraph/scip v0.2.4-0.20221213205653-aa0e511dcfef/go.mod h1:ymcTuv+6D5OEZB/84TRPQvUpDK7v7zXnWBJl79hb7ns= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20230316093010-26299ec302d0 h1:NJyyvyYU/DNZmNFui8ktnHke3hS/PYLmDUbWNHSHKuQ= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20230316093010-26299ec302d0/go.mod h1:bYQ9cozv3Uhh/pINa5PfDnkAl62YqDoKGNhj3WuZIoo= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= @@ -510,22 +518,21 @@ github.com/yudai/pp v2.0.1+incompatible/go.mod h1:PuxR/8QJ7cyCkFp/aUDS+JY727OFEZ github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= -github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= github.com/yuin/goldmark v1.4.4/go.mod h1:rmuwmfZ0+bvzB24eSC//bk1R1Zp3hM0OXYv/G2LIilg= -github.com/yuin/goldmark v1.4.13 h1:fVcFKWvrslecOb/tg+Cc05dkeYx540o0FuFt3nUVDoE= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +github.com/yuin/goldmark v1.5.2 h1:ALmeCk/px5FSm1MAcFBAsVKZjDuMVj8Tm7FFIlMJnqU= +github.com/yuin/goldmark v1.5.2/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= github.com/yuin/goldmark-emoji v1.0.1 h1:ctuWEyzGBwiucEqxzwe0SOYDXPAucOrE9NQC18Wa1os= github.com/yuin/goldmark-emoji v1.0.1/go.mod h1:2w1E6FEWLcDQkoTE+7HU6QF1F6SLlNGjRIBbIZQFqkQ= go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0= go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo= -go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= go.uber.org/atomic v1.10.0 h1:9qC72Qh0+3MqyJbAn8YU5xVq1frD8bn3JtD2oXtafVQ= go.uber.org/atomic v1.10.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= -go.uber.org/goleak v1.1.11 h1:wy28qYRKZgnJTxGxvye5/wgWr1EKjmUDGYox5mGlRlI= -go.uber.org/multierr v1.8.0 h1:dg6GjLku4EH+249NNmoIciG9N/jURbDG+pFlTkhzIC8= -go.uber.org/multierr v1.8.0/go.mod h1:7EAYxJLBy9rStEaz58O2t4Uvip6FSURkq8/ppBp95ak= -go.uber.org/zap v1.23.0 h1:OjGQ5KQDEUawVHxNwQgPpiypGHOxo2mNZsOqTak4fFY= -go.uber.org/zap v1.23.0/go.mod h1:D+nX8jyLsMHMYrln8A0rJjFt/T/9/bGgIhAqxv5URuY= +go.uber.org/goleak v1.2.0 h1:xqgm/S+aQvhWFTtR0XK3Jvg7z8kGV8P4X14IzwN3Eqk= +go.uber.org/multierr v1.9.0 h1:7fIwc/ZtS0q++VgcfqFDxSBZVv/Xo49/SYnDFupUwlI= +go.uber.org/multierr v1.9.0/go.mod h1:X2jQV1h+kxSjClGpnseKVIxpmcjrj7MNnI0bnlfKTVQ= +go.uber.org/zap v1.24.0 h1:FiJd5l1UOLj0wCgbSE0rwwXHzEdAZS6hiiSnxJN/D60= +go.uber.org/zap v1.24.0/go.mod h1:2kMP+WWQ8aoFoedH3T2sq6iJ2yDWpHbP0f6MQbS9Gkg= golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= @@ -534,8 +541,8 @@ golang.org/x/crypto v0.0.0-20191227163750-53104e6ec876/go.mod h1:LzIPMQfyMNhhGPh golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.1.0 h1:MDRAIl0xIo9Io2xV565hzXHw3zVseKrJKodhohM5CjU= -golang.org/x/crypto v0.1.0/go.mod h1:RecgLatLF4+eUMCP1PoPZQb+cVrJcOPbHkTkbkB9sbw= +golang.org/x/crypto v0.3.0 h1:a06MkbcxBrEFc0w0QIZWXrH/9cCX6KJyWbBOIwAn+7A= +golang.org/x/crypto v0.3.0/go.mod h1:hebNnKkNXi2UzZN1eVRvBB7co0a+JxK6XbPiWVs/3J4= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= @@ -547,9 +554,10 @@ golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro= -golang.org/x/mod v0.7.0 h1:LapD9S96VoQRhi/GrNTqeBJFrUjs5UHCAtTlgwA5oZA= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.7.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/mod v0.9.0 h1:KENHtAZL2y3NLMYZeHY9DW8HW8V+kQyJsY/V9JlKvCs= +golang.org/x/mod v0.9.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -572,9 +580,10 @@ golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/net v0.0.0-20210614182718-04defd469f4e/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211008194852-3b03d305991f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/net v0.7.0 h1:rJrUqqhjsgNp7KqAIc25s9pZnjU7TUcSY7HcVZjdn1g= -golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.3.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE= +golang.org/x/net v0.8.0 h1:Zrh2ngAOFYneWTAIAPethzeaQLuHwhuBkuV6ZiRnUaQ= +golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.5.0 h1:HuArIo48skDwlrvM3sEdHXElYslAMsf3KwRkkW4MC4s= golang.org/x/oauth2 v0.5.0/go.mod h1:9/XBHVqLaWO3/BRHs5jbpYCnOZVjj5V0ndyaAM7KB4I= @@ -585,6 +594,8 @@ golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220819030929-7fc1605a5dde/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -616,28 +627,31 @@ golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211007075335-d3039528d8ac/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20211102192858-4dd72447c267/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20211117180635-dee7805ff2e1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20211213223007-03aa0b5f6827/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.5.0 h1:MUK/U/4lj1t1oPg0HfuXDN/Z1wv31ZJ/YcPiGccS4DU= -golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220829200755-d48e67d00261/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/term v0.5.0 h1:n2a8QNdAb0sZNpU9R1ALUXBbY+w51fCQDN+7EdxNBsY= -golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.3.0/go.mod h1:q750SLmJuPmVoN1blW3UFBPREJfb1KmY3vwxfr+nFDA= +golang.org/x/term v0.6.0 h1:clScbb1cHjoCkyRbWwBEUZ5H/tIFu5TAXIqaZD0Gcjw= +golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.7.0 h1:4BRB4x83lYWy72KwLD/qYDuTu7q9PjSagHvijDw7cLo= -golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.8.0 h1:57P1ETyNKtuIjB4SRd15iJxuhj8Gc416Y78H3qgMh68= +golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/time v0.0.0-20201208040808-7e3f01d25324/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/time v0.0.0-20220210224613-90d013bbcef8 h1:vVKdlvoWBphwdxWKrFZEuM0kGgGLxUOYcY4U/2Vjg44= -golang.org/x/time v0.0.0-20220210224613-90d013bbcef8/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20220922220347-f3bd1da661af h1:Yx9k8YCG3dvF87UAn2tu2HQLf2dt/eR1bXxpLMWeH+Y= +golang.org/x/time v0.0.0-20220922220347-f3bd1da661af/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20181221001348-537d06c36207/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -656,10 +670,10 @@ golang.org/x/tools v0.0.0-20210101214203-2dba1e4ea05c/go.mod h1:emZCQorbCU4vsT4f golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= -golang.org/x/tools v0.1.8-0.20211102182255-bb4add04ddef/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= -golang.org/x/tools v0.1.8/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= -golang.org/x/tools v0.5.0 h1:+bSpV5HIeWkuvgaMfI3UmKRThoTA5ODJTUd8T17NO+4= -golang.org/x/tools v0.5.0/go.mod h1:N+Kgy78s5I24c24dU8OfWNEotWjutIs8SnJvn5IDq+k= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/tools v0.4.0/go.mod h1:UE5sM2OK9E/d67R0ANs2xJizIymRP5gJU295PvKXxjQ= +golang.org/x/tools v0.7.0 h1:W4OVu8VVOaIO0yzWMNdepAulS7YfoS3Zabrm8DOXXU4= +golang.org/x/tools v0.7.0/go.mod h1:4pg6aUX35JBAogB10C9AtvVL+qowtN4pT3CGSQex14s= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -709,8 +723,8 @@ gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8 gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b h1:QRR6H1YWRnHb4Y/HeNFCTJLFVxaq6wH4YuVdsUOr75U= gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= gopkg.in/go-playground/assert.v1 v1.2.1/go.mod h1:9RXL0bg/zibRAgZUYszZSwO/z8Y/a8bDuhia5mkpMnE= @@ -730,10 +744,11 @@ gopkg.in/yaml.v3 v3.0.0-20191120175047-4206685974f2/go.mod h1:K4uyk7z7BCEPqu6E+C gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gotest.tools/v3 v3.0.2 h1:kG1BFyqVHuQoVQiR1bWGnfz/fmHvvuiSPIV7rvl360E= gotest.tools/v3 v3.0.2/go.mod h1:3SzNCllyD9/Y+b5r9JIKQ474KzkZyqLqEfYqMsX94Bk= +gotest.tools/v3 v3.0.3 h1:4AuOwCGf4lLR9u3YOe2awrHygurzhO/HeQ6laiA6Sx0= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7 h1:mub0MmFLOn8XLikZOAhgLD1kXJq8jgftSrrv7m00xFo= @@ -752,9 +767,8 @@ k8s.io/utils v0.0.0-20221107191617-1a15be271d1d h1:0Smp/HP1OH4Rvhe+4B8nWGERtlqAG k8s.io/utils v0.0.0-20221107191617-1a15be271d1d/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= mvdan.cc/gofumpt v0.0.0-20210107193838-d24d34e18d44/go.mod h1:yXG1r1WqZVKWbVRtBWKWX9+CxGYfA51nSomhM0woR48= mvdan.cc/gofumpt v0.1.0/go.mod h1:yXG1r1WqZVKWbVRtBWKWX9+CxGYfA51nSomhM0woR48= -mvdan.cc/gofumpt v0.2.0/go.mod h1:TiGmrf914DAuT6+hDIxOqoDb4QXIzAuEUSXqEf9hGKY= -mvdan.cc/gofumpt v0.2.1 h1:7jakRGkQcLAJdT+C8Bwc9d0BANkVPSkHZkzNv07pJAs= -mvdan.cc/gofumpt v0.2.1/go.mod h1:a/rvZPhsNaedOJBzqRD9omnwVwHZsBdJirXHa9Gh9Ig= +mvdan.cc/gofumpt v0.4.0 h1:JVf4NN1mIpHogBj7ABpgOyZc65/UUOkKQFkoURsz4MM= +mvdan.cc/gofumpt v0.4.0/go.mod h1:PljLOHDeZqgS8opHRKLzp2It2VBuSdteAgqUfzMTxlQ= sigs.k8s.io/json v0.0.0-20220713155537-f223a00ba0e2 h1:iXTIw73aPyC+oRdyqqvVJuloN1p0AC/kzH07hu3NE+k= sigs.k8s.io/json v0.0.0-20220713155537-f223a00ba0e2/go.mod h1:B8JuhiUyNFVKdsE8h686QcCxMaH6HrOAZj4vswFpcB0= sigs.k8s.io/structured-merge-diff/v4 v4.2.3 h1:PRbqxJClWWYMNV1dhaG4NsibJbArud9kFxnAMREiWFE= diff --git a/internal/batches/docker/context.go b/internal/batches/docker/context.go index 5d4a8fdb19..6b405a41da 100644 --- a/internal/batches/docker/context.go +++ b/internal/batches/docker/context.go @@ -67,9 +67,11 @@ func (e *fastCommandTimeoutError) Error() string { func (*fastCommandTimeoutError) Timeout() bool { return true } +type fastCommandTimeoutKey string + const ( - fastCommandTimeoutDefault = 5 * time.Second - fastCommandTimeoutEnv = "SRC_DOCKER_FAST_COMMAND_TIMEOUT" + fastCommandTimeoutDefault = 5 * time.Second + fastCommandTimeoutEnv fastCommandTimeoutKey = "SRC_DOCKER_FAST_COMMAND_TIMEOUT" ) var fastCommandTimeoutData = struct { @@ -83,7 +85,7 @@ var fastCommandTimeoutData = struct { func fastCommandTimeout() (time.Duration, error) { fastCommandTimeoutData.once.Do(func() { - if userTimeout, ok := os.LookupEnv(fastCommandTimeoutEnv); ok { + if userTimeout, ok := os.LookupEnv(string(fastCommandTimeoutEnv)); ok { parsed, err := time.ParseDuration(userTimeout) if err != nil { fastCommandTimeoutData.err = errors.Wrapf(err, "parsing timeout duration from environment variable %s", fastCommandTimeoutEnv) diff --git a/internal/batches/executor/coordinator.go b/internal/batches/executor/coordinator.go index 921d02ff81..15855f5d37 100644 --- a/internal/batches/executor/coordinator.go +++ b/internal/batches/executor/coordinator.go @@ -127,7 +127,7 @@ func (c *Coordinator) buildChangesetSpecs(task *Task, batchSpec *batcheslib.Batc }, } - return batcheslib.BuildChangesetSpecs(input, c.opts.BinaryDiffs) + return batcheslib.BuildChangesetSpecs(input, c.opts.BinaryDiffs, nil) } func (c *Coordinator) loadCachedStepResults(ctx context.Context, task *Task, globalEnv []string) error { diff --git a/internal/batches/log/noop_task_logger.go b/internal/batches/log/noop_task_logger.go index f7aac40da3..114a8bf704 100644 --- a/internal/batches/log/noop_task_logger.go +++ b/internal/batches/log/noop_task_logger.go @@ -2,15 +2,9 @@ package log import ( "io" - "os" ) -type NoopTaskLogger struct { - f *os.File - - errored bool - keep bool -} +type NoopTaskLogger struct{} func (tl *NoopTaskLogger) Close() error { return nil diff --git a/internal/batches/service/remote.go b/internal/batches/service/remote.go index f196e6b645..1e57701f7a 100644 --- a/internal/batches/service/remote.go +++ b/internal/batches/service/remote.go @@ -185,6 +185,8 @@ func (svc *Service) uploadFile(ctx context.Context, workingDir, filePath, batchS // Errors passed to pipeWriter.CloseWithError come through here. return err } + defer resp.Body.Close() + // 2xx and 3xx are ok if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusBadRequest { p, err := io.ReadAll(resp.Body) diff --git a/internal/batches/service/remote_test.go b/internal/batches/service/remote_test.go index 563a862383..75a426c2e3 100644 --- a/internal/batches/service/remote_test.go +++ b/internal/batches/service/remote_test.go @@ -14,12 +14,13 @@ import ( "strings" "testing" - mockclient "github.com/sourcegraph/src-cli/internal/api/mock" - "github.com/sourcegraph/src-cli/internal/batches/service" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + mockclient "github.com/sourcegraph/src-cli/internal/api/mock" + "github.com/sourcegraph/src-cli/internal/batches/service" + "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/errors" ) @@ -235,6 +236,7 @@ func TestService_UploadBatchSpecWorkspaceFiles(t *testing.T) { resp := &http.Response{ StatusCode: http.StatusOK, + Body: io.NopCloser(bytes.NewReader([]byte{})), } entry := &multipartFormEntry{ fileName: "hello.txt", @@ -276,6 +278,7 @@ func TestService_UploadBatchSpecWorkspaceFiles(t *testing.T) { resp := &http.Response{ StatusCode: http.StatusOK, + Body: io.NopCloser(bytes.NewReader([]byte{})), } entry := &multipartFormEntry{ fileName: "hello.txt", @@ -317,6 +320,7 @@ func TestService_UploadBatchSpecWorkspaceFiles(t *testing.T) { resp := &http.Response{ StatusCode: http.StatusOK, + Body: io.NopCloser(bytes.NewReader([]byte{})), } helloEntry := &multipartFormEntry{ fileName: "hello.txt", @@ -364,6 +368,7 @@ func TestService_UploadBatchSpecWorkspaceFiles(t *testing.T) { resp := &http.Response{ StatusCode: http.StatusOK, + Body: io.NopCloser(bytes.NewReader([]byte{})), } helloEntry := &multipartFormEntry{ fileName: "hello.txt", @@ -412,6 +417,7 @@ func TestService_UploadBatchSpecWorkspaceFiles(t *testing.T) { resp := &http.Response{ StatusCode: http.StatusOK, + Body: io.NopCloser(bytes.NewReader([]byte{})), } entry := &multipartFormEntry{ path: "scripts", @@ -463,6 +469,7 @@ func TestService_UploadBatchSpecWorkspaceFiles(t *testing.T) { resp := &http.Response{ StatusCode: http.StatusOK, + Body: io.NopCloser(bytes.NewReader([]byte{})), } helloEntry := &multipartFormEntry{ fileName: "hello.txt", @@ -581,6 +588,7 @@ func TestService_UploadBatchSpecWorkspaceFiles(t *testing.T) { resp := &http.Response{ StatusCode: http.StatusOK, + Body: io.NopCloser(bytes.NewReader([]byte{})), } entry := &multipartFormEntry{ fileName: "hello.txt", @@ -640,7 +648,7 @@ func writeTempFile(dir string, name string, content string) error { } // 2006-01-02 15:04:05.999999999 -0700 MST -var modtimeRegex = regexp.MustCompile("^[0-9]{4}-[0-9]{2}-[0-9]{2}\\s[0-9]{2}:[0-9]{2}:[0-9]{2}.[0-9]{1,9} \\+0000 UTC$") +var modtimeRegex = regexp.MustCompile(`^[0-9]{4}-[0-9]{2}-[0-9]{2}\s[0-9]{2}:[0-9]{2}:[0-9]{2}.[0-9]{1,9} \+0000 UTC$`) func multipartFormRequestMatcher(entry *multipartFormEntry) func(*http.Request) bool { return func(req *http.Request) bool { diff --git a/internal/batches/service/remote_windows_test.go b/internal/batches/service/remote_windows_test.go index f8e34a8be4..9cbdc07182 100644 --- a/internal/batches/service/remote_windows_test.go +++ b/internal/batches/service/remote_windows_test.go @@ -1,6 +1,7 @@ package service_test import ( + "bytes" "context" "io" "net/http" @@ -53,6 +54,7 @@ func TestService_UploadBatchSpecWorkspaceFiles_Windows_Path(t *testing.T) { resp := &http.Response{ StatusCode: http.StatusOK, + Body: io.NopCloser(bytes.NewReader([]byte{})), } entry := &multipartFormEntry{ path: "scripts/another-dir", diff --git a/internal/validate/kube/gke.go b/internal/validate/kube/gke.go index 3a07c1a782..f9ebd7eb20 100644 --- a/internal/validate/kube/gke.go +++ b/internal/validate/kube/gke.go @@ -3,8 +3,9 @@ package kube import ( "context" - "github.com/sourcegraph/src-cli/internal/validate" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + "github.com/sourcegraph/src-cli/internal/validate" ) type ClusterInfo struct { @@ -36,16 +37,14 @@ func GkeGcePersistentDiskCSIDrivers(ctx context.Context, config *Config) ([]vali return results, nil } -/* - validateStorageClasses checks for GKE specific storageClasses: - - After the compute engine persistent disk CSI driver is enabled, - gke automatically installs the standard-rwo and the premium-rwo - storage classes. This function checks that those storage - classes exist on the cluster. - - Ref: shorturl.at/dnKV0 -*/ +// validateStorageClasses checks for GKE specific storageClasses: +// +// After the compute engine persistent disk CSI driver is enabled, +// gke automatically installs the standard-rwo and the premium-rwo +// storage classes. This function checks that those storage +// classes exist on the cluster. +// +// Ref: shorturl.at/dnKV0 func validateStorageClasses(ctx context.Context, config *Config) ([]validate.Result, error) { var results []validate.Result From 97b08ed2a5dc4b3f522dfe8e44abd83377a4c971 Mon Sep 17 00:00:00 2001 From: Jacob Pleiness Date: Thu, 16 Mar 2023 12:57:19 -0400 Subject: [PATCH 315/647] Admin: add `src admin create` command (#957) * Add `src admin create` command * Add command to setup an initial admin account on a new deployment of Sourcegraph. * Add option to use env var for admin pass * Fixing issues pointed out in PR --- cmd/src/admin.go | 38 ++++ cmd/src/admin_create.go | 100 +++++++++ internal/lazyregexp/lazyregexp.go | 128 ++++++++++++ internal/users/admin.go | 330 ++++++++++++++++++++++++++++++ 4 files changed, 596 insertions(+) create mode 100644 cmd/src/admin.go create mode 100644 cmd/src/admin_create.go create mode 100644 internal/lazyregexp/lazyregexp.go create mode 100644 internal/users/admin.go diff --git a/cmd/src/admin.go b/cmd/src/admin.go new file mode 100644 index 0000000000..ac8af95205 --- /dev/null +++ b/cmd/src/admin.go @@ -0,0 +1,38 @@ +package main + +import ( + "flag" + "fmt" +) + +var adminCommands commander + +func init() { + usage := `'src admin' is a tool that manages an initial admin user on a new Sourcegraph instance. + +Usage: + + src admin create [command options] + +The commands are: + + create create an initial admin user + +Use "src admin [command] -h" for more information about a command. +` + + flagSet := flag.NewFlagSet("admin", flag.ExitOnError) + handler := func(args []string) error { + adminCommands.run(flagSet, "srv admin", usage, args) + return nil + } + + commands = append(commands, &command{ + flagSet: flagSet, + aliases: []string{"admin"}, + handler: handler, + usageFunc: func() { + fmt.Println(usage) + }, + }) +} diff --git a/cmd/src/admin_create.go b/cmd/src/admin_create.go new file mode 100644 index 0000000000..5b7bdf9110 --- /dev/null +++ b/cmd/src/admin_create.go @@ -0,0 +1,100 @@ +package main + +import ( + "flag" + "fmt" + "os" + + "github.com/sourcegraph/src-cli/internal/users" + + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +func init() { + usage := ` +Examples: + + Create an initial admin user on a new Sourcegraph deployment: + + $ src admin create -url https://your-sourcegraph-url -username admin -email admin@yourcompany.com -with-token + + Create an initial admin user on a new Sourcegraph deployment using '-password' flag. + WARNING: for security purposes we strongly recommend using the SRC_ADMIN_PASS environment variable when possible. + + $ src admin create -url https://your-sourcegraph-url -username admin -email admin@yourcompany.com -password p@55w0rd -with-token + +Environmental variables + + SRC_ADMIN_PASS The new admin user's password +` + + flagSet := flag.NewFlagSet("create", flag.ExitOnError) + usageFunc := func() { + fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src users %s':\n", flagSet.Name()) + flagSet.PrintDefaults() + fmt.Println(usage) + } + + var ( + urlFlag = flagSet.String("url", "", "The base URL for the Sourcegraph instance.") + usernameFlag = flagSet.String("username", "", "The new admin user's username.") + emailFlag = flagSet.String("email", "", "The new admin user's email address.") + passwordFlag = flagSet.String("password", "", "The new admin user's password.") + tokenFlag = flagSet.Bool("with-token", false, "Optionally create and output an admin access token.") + ) + + handler := func(args []string) error { + if err := flagSet.Parse(args); err != nil { + return err + } + + ok, _, err := users.NeedsSiteInit(*urlFlag) + if err != nil { + return err + } + if !ok { + return errors.New("failed to create admin, site already initialized") + } + + envAdminPass := os.Getenv("SRC_ADMIN_PASS") + + var client *users.Client + + switch { + case envAdminPass != "" && *passwordFlag == "": + client, err = users.SiteAdminInit(*urlFlag, *emailFlag, *usernameFlag, envAdminPass) + if err != nil { + return err + } + case envAdminPass == "" && *passwordFlag != "": + client, err = users.SiteAdminInit(*urlFlag, *emailFlag, *usernameFlag, *passwordFlag) + if err != nil { + return err + } + case envAdminPass != "" && *passwordFlag != "": + return errors.New("failed to read admin password: environment variable and -password flag both set") + case envAdminPass == "" && *passwordFlag == "": + return errors.New("failed to read admin password from 'SRC_ADMIN_PASS' environment variable or -password flag") + } + + if *tokenFlag { + token, err := client.CreateAccessToken("", []string{"user:all", "site-admin:sudo"}, "src-cli") + if err != nil { + return err + } + + _, err = fmt.Fprintf(flag.CommandLine.Output(), "%s\n", token) + if err != nil { + return err + } + } + + return nil + } + + adminCommands = append(adminCommands, &command{ + flagSet: flagSet, + handler: handler, + usageFunc: usageFunc, + }) +} diff --git a/internal/lazyregexp/lazyregexp.go b/internal/lazyregexp/lazyregexp.go new file mode 100644 index 0000000000..dc55d78f1a --- /dev/null +++ b/internal/lazyregexp/lazyregexp.go @@ -0,0 +1,128 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package lazyregexp is a thin wrapper over regexp, allowing the use of global +// regexp variables without forcing them to be compiled at init. +package lazyregexp + +import ( + "os" + "strings" + "sync" + + "github.com/grafana/regexp" +) + +// Regexp is a wrapper around regexp.Regexp, where the underlying regexp will be +// compiled the first time it is needed. +type Regexp struct { + str string + posix bool + once sync.Once + rx *regexp.Regexp +} + +func (r *Regexp) Re() *regexp.Regexp { + r.once.Do(r.build) + return r.rx +} + +func (r *Regexp) build() { + if r.posix { + r.rx = regexp.MustCompilePOSIX(r.str) + } else { + r.rx = regexp.MustCompile(r.str) + } + r.str = "" +} + +func (r *Regexp) FindSubmatch(s []byte) [][]byte { + return r.Re().FindSubmatch(s) +} + +func (r *Regexp) FindStringSubmatch(s string) []string { + return r.Re().FindStringSubmatch(s) +} + +func (r *Regexp) FindStringSubmatchIndex(s string) []int { + return r.Re().FindStringSubmatchIndex(s) +} + +func (r *Regexp) ReplaceAllString(src, repl string) string { + return r.Re().ReplaceAllString(src, repl) +} + +func (r *Regexp) FindString(s string) string { + return r.Re().FindString(s) +} + +func (r *Regexp) FindAllString(s string, n int) []string { + return r.Re().FindAllString(s, n) +} + +func (r *Regexp) MatchString(s string) bool { + return r.Re().MatchString(s) +} + +func (r *Regexp) SubexpNames() []string { + return r.Re().SubexpNames() +} + +func (r *Regexp) FindAllStringSubmatch(s string, n int) [][]string { + return r.Re().FindAllStringSubmatch(s, n) +} + +func (r *Regexp) Split(s string, n int) []string { + return r.Re().Split(s, n) +} + +func (r *Regexp) ReplaceAllLiteralString(src, repl string) string { + return r.Re().ReplaceAllLiteralString(src, repl) +} + +func (r *Regexp) FindAllIndex(b []byte, n int) [][]int { + return r.Re().FindAllIndex(b, n) +} + +func (r *Regexp) Match(b []byte) bool { + return r.Re().Match(b) +} + +func (r *Regexp) ReplaceAllStringFunc(src string, repl func(string) string) string { + return r.Re().ReplaceAllStringFunc(src, repl) +} + +func (r *Regexp) ReplaceAll(src, repl []byte) []byte { + return r.Re().ReplaceAll(src, repl) +} + +func (r *Regexp) SubexpIndex(s string) int { + return r.Re().SubexpIndex(s) +} + +var inTest = len(os.Args) > 0 && strings.HasSuffix(strings.TrimSuffix(os.Args[0], ".exe"), ".test") + +// New creates a new lazy regexp, delaying the compiling work until it is first +// needed. If the code is being run as part of tests, the regexp compiling will +// happen immediately. +func New(str string) *Regexp { + lr := &Regexp{str: str} + if inTest { + // In tests, always compile the regexps early. + lr.Re() + } + return lr +} + +// NewPOSIX creates a new lazy regexp, delaying the compiling work until it is +// first needed. If the code is being run as part of tests, the regexp +// compiling will happen immediately. +func NewPOSIX(str string) *Regexp { + lr := &Regexp{str: str, posix: true} + if inTest { + // In tests, always compile the regexps early. + lr.Re() + } + return lr +} diff --git a/internal/users/admin.go b/internal/users/admin.go new file mode 100644 index 0000000000..dad8584989 --- /dev/null +++ b/internal/users/admin.go @@ -0,0 +1,330 @@ +package users + +import ( + "bytes" + "fmt" + "io" + "net/http" + "strings" + + jsoniter "github.com/json-iterator/go" + "github.com/sourcegraph/src-cli/internal/lazyregexp" + + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +// NeedsSiteInit returns true if the instance hasn't done "Site admin init" step. +func NeedsSiteInit(baseURL string) (bool, string, error) { + resp, err := http.Get(baseURL + "/sign-in") + if err != nil { + return false, "", errors.Wrap(err, "sign-in page") + } + defer func() { _ = resp.Body.Close() }() + + p, err := io.ReadAll(resp.Body) + if err != nil { + return false, "", errors.Wrap(err, "read body") + } + return strings.Contains(string(p), `"needsSiteInit":true`), string(p), nil +} + +// SiteAdminInit initializes the instance with given admin account. +// It returns an authenticated client as the admin for doing testing. +func SiteAdminInit(baseURL, email, username, password string) (*Client, error) { + return authenticate(baseURL, "/-/site-init", map[string]string{ + "email": email, + "username": username, + "password": password, + }) +} + +// authenticate initializes an authenticated client with given request body. +func authenticate(baseURL, path string, body any) (*Client, error) { + c, err := NewClient(baseURL, nil, nil) + if err != nil { + return nil, errors.Wrap(err, "new client") + } + + err = c.authenticate(path, body) + if err != nil { + return nil, errors.Wrap(err, "authenticate") + } + + return c, nil +} + +// Client is an authenticated client for a Sourcegraph user for doing e2e testing. +// The user may or may not be a site admin depends on how the client is instantiated. +// It works by simulating how the browser would send HTTP requests to the server. +type Client struct { + baseURL string + csrfToken string + csrfCookie *http.Cookie + sessionCookie *http.Cookie + + userID string + requestLogger logFunc + responseLogger logFunc +} + +type logFunc func(payload []byte) + +func noopLog(payload []byte) {} + +// NewClient instantiates a new client by performing a GET request then obtains the +// CSRF token and cookie from its response, if there is one (old versions of Sourcegraph only). +// If request- or responseLogger are provided, the request and response bodies, respectively, +// will be written to them for any GraphQL requests only. +func NewClient(baseURL string, requestLogger, responseLogger logFunc) (*Client, error) { + if requestLogger == nil { + requestLogger = noopLog + } + if responseLogger == nil { + responseLogger = noopLog + } + + resp, err := http.Get(baseURL) + if err != nil { + return nil, errors.Wrap(err, "get URL") + } + defer func() { _ = resp.Body.Close() }() + + p, err := io.ReadAll(resp.Body) + if err != nil { + return nil, errors.Wrap(err, "read GET body") + } + + csrfToken := extractCSRFToken(string(p)) + var csrfCookie *http.Cookie + for _, cookie := range resp.Cookies() { + if cookie.Name == "sg_csrf_token" { + csrfCookie = cookie + break + } + } + + return &Client{ + baseURL: baseURL, + csrfToken: csrfToken, + csrfCookie: csrfCookie, + requestLogger: requestLogger, + responseLogger: responseLogger, + }, nil +} + +// authenticate is used to send an HTTP POST request to a URL that is able to authenticate +// a user with given body (marshalled to JSON), e.g. site admin init, sign in. Once the +// client is authenticated, the session cookie will be stored as a proof of authentication. +func (c *Client) authenticate(path string, body any) error { + p, err := jsoniter.Marshal(body) + if err != nil { + return errors.Wrap(err, "marshal body") + } + + req, err := http.NewRequest("POST", c.baseURL+path, bytes.NewReader(p)) + if err != nil { + return errors.Wrap(err, "new request") + } + req.Header.Set("Content-Type", "application/json") + if c.csrfToken != "" { + req.Header.Set("X-Csrf-Token", c.csrfToken) + } + if c.csrfCookie != nil { + req.AddCookie(c.csrfCookie) + } + + resp, err := http.DefaultClient.Do(req) + if err != nil { + return errors.Wrap(err, "do request") + } + defer func() { _ = resp.Body.Close() }() + + if resp.StatusCode != http.StatusOK { + p, err := io.ReadAll(resp.Body) + if err != nil { + return errors.Wrap(err, "read response body") + } + return errors.New(string(p)) + } + + var sessionCookie *http.Cookie + for _, cookie := range resp.Cookies() { + if cookie.Name == "sgs" { + sessionCookie = cookie + break + } + } + if sessionCookie == nil { + return errors.Wrap(err, `"sgs" cookie not found`) + } + c.sessionCookie = sessionCookie + + userID, err := c.CurrentUserID("") + if err != nil { + return errors.Wrap(err, "get current user") + } + c.userID = userID + return nil +} + +// CurrentUserID returns the current authenticated user's GraphQL node ID. +// An optional token can be passed to impersonate other users. +func (c *Client) CurrentUserID(token string) (string, error) { + const query = ` + query { + currentUser { + id + } + } +` + var resp struct { + Data struct { + CurrentUser struct { + ID string `json:"id"` + } `json:"currentUser"` + } `json:"data"` + } + err := c.GraphQL(token, query, nil, &resp) + if err != nil { + return "", errors.Wrap(err, "request GraphQL") + } + + return resp.Data.CurrentUser.ID, nil +} + +// CreateAccessToken creates an access token for the current user. +// An optional token can be passed to impersonate other users. +func (c *Client) CreateAccessToken(token string, scopes []string, note string) (string, error) { + userID, err := c.CurrentUserID("") + if err != nil { + return "", err + } + + const mutation = ` + mutation createAccessToken($user: ID!, $scopes: [String!]!, $note: String!) { + createAccessToken(user: $user, scopes: $scopes, note: $note) { + token + } + } +` + + var resp struct { + Data struct { + CreateAccessToken struct { + Token string `json:"token"` + } `json:"createAccessToken"` + } + } + + err = c.GraphQL(token, mutation, map[string]any{ + "user": userID, + "scopes": scopes, + "note": note, + }, &resp) + + if err != nil { + return "", err + } + + return resp.Data.CreateAccessToken.Token, nil +} + +var graphqlQueryNameRe = lazyregexp.New(`(query|mutation) +(\w)+`) + +// GraphQL makes a GraphQL request to the server on behalf of the user authenticated by the client. +// An optional token can be passed to impersonate other users. A nil target will skip unmarshalling +// the returned JSON response. +func (c *Client) GraphQL(token, query string, variables map[string]any, target any) error { + body, err := jsoniter.Marshal(map[string]any{ + "query": query, + "variables": variables, + }) + if err != nil { + return err + } + + var name string + if matches := graphqlQueryNameRe.FindStringSubmatch(query); len(matches) >= 2 { + name = matches[2] + } + + req, err := http.NewRequest("POST", fmt.Sprintf("%s/.api/graphql?%s", c.baseURL, name), bytes.NewReader(body)) + if err != nil { + return err + } + if token != "" { + req.Header.Set("Authorization", fmt.Sprintf("token %s", token)) + } else { + // NOTE: This header is required to authenticate our session with a session cookie, see: + // https://docs.sourcegraph.com/dev/security/csrf_security_model#authentication-in-api-endpoints + req.Header.Set("X-Requested-With", "Sourcegraph") + req.AddCookie(c.sessionCookie) + + // Older versions of Sourcegraph require a CSRF cookie. + if c.csrfCookie != nil { + req.AddCookie(c.csrfCookie) + } + } + + c.requestLogger(body) + + resp, err := http.DefaultClient.Do(req) + if err != nil { + return err + } + defer func() { _ = resp.Body.Close() }() + + body, err = io.ReadAll(resp.Body) + if err != nil { + return errors.Wrap(err, "read response body") + } + + c.responseLogger(body) + + // Check if the response format should be JSON + if strings.Contains(resp.Header.Get("Content-Type"), "application/json") { + // Try and see unmarshalling to errors + var errResp struct { + Errors []struct { + Message string `json:"message"` + } `json:"errors"` + } + err = jsoniter.Unmarshal(body, &errResp) + if err != nil { + return errors.Wrap(err, "unmarshal response body to errors") + } + if len(errResp.Errors) > 0 { + var errs error + for _, err := range errResp.Errors { + errs = errors.Append(errs, errors.New(err.Message)) + } + return errs + } + } + + if resp.StatusCode != http.StatusOK { + return errors.Errorf("%d: %s", resp.StatusCode, string(body)) + } + + if target == nil { + return nil + } + + return jsoniter.Unmarshal(body, &target) +} + +// extractCSRFToken extracts CSRF token from HTML response body. +func extractCSRFToken(body string) string { + anchor := `X-Csrf-Token":"` + i := strings.Index(body, anchor) + if i == -1 { + return "" + } + + j := strings.Index(body[i+len(anchor):], `","`) + if j == -1 { + return "" + } + + return body[i+len(anchor) : i+len(anchor)+j] +} From 0ce1ae4772737264b3fa826e6c6b114754c87009 Mon Sep 17 00:00:00 2001 From: Jacob Pleiness Date: Thu, 16 Mar 2023 13:24:19 -0400 Subject: [PATCH 316/647] Fix: no longer require SRC_GITHUB_TOKEN to be set (#958) --- cmd/src/validate_install.go | 10 +- internal/validate/install/config.go | 132 ++++++++++++ internal/validate/install/github.go | 95 ++++++++ internal/validate/install/insight.go | 101 +++++++++ internal/validate/install/install.go | 311 +-------------------------- 5 files changed, 340 insertions(+), 309 deletions(-) create mode 100644 internal/validate/install/config.go create mode 100644 internal/validate/install/github.go create mode 100644 internal/validate/install/insight.go diff --git a/cmd/src/validate_install.go b/cmd/src/validate_install.go index 02a0a26f99..b298543f3d 100644 --- a/cmd/src/validate_install.go +++ b/cmd/src/validate_install.go @@ -11,7 +11,6 @@ import ( "github.com/mattn/go-isatty" "github.com/sourcegraph/src-cli/internal/api" - "github.com/sourcegraph/src-cli/internal/validate" "github.com/sourcegraph/src-cli/internal/validate/install" "github.com/sourcegraph/sourcegraph/lib/errors" @@ -97,14 +96,7 @@ Environmental variables validationSpec = install.DefaultConfig() } - envGithubToken := os.Getenv("SRC_GITHUB_TOKEN") - - // will work for now with only GitHub supported but will need to be revisited when other code hosts are supported - if envGithubToken == "" { - return errors.Newf("%s failed to read `SRC_GITHUB_TOKEN` environment variable", validate.WarningSign) - } - - validationSpec.ExternalService.Config.GitHub.Token = envGithubToken + validationSpec.ExternalService.Config.GitHub.Token = os.Getenv("SRC_GITHUB_TOKEN") return install.Validate(context.Background(), client, validationSpec) } diff --git a/internal/validate/install/config.go b/internal/validate/install/config.go new file mode 100644 index 0000000000..39695dbb25 --- /dev/null +++ b/internal/validate/install/config.go @@ -0,0 +1,132 @@ +package install + +import ( + "encoding/json" + + "gopkg.in/yaml.v3" +) + +type ExternalService struct { + // Type of code host, e.g. GITHUB. + Kind string `yaml:"kind"` + + // Display name of external service, e.g. sourcegraph-test. + DisplayName string `yaml:"displayName"` + + // Configuration for code host. + Config Config `yaml:"config"` + + // Maximum retry attempts when cloning test repositories. Defaults to 5 retries. + MaxRetries int `yaml:"maxRetries"` + + // Retry timeout in seconds. Defaults to 5 seconds + RetryTimeoutSeconds int `yaml:"retryTimeoutSeconds"` + + // Delete code host when test is done. Defaults to true. + DeleteWhenDone bool `yaml:"deleteWhenDone"` +} + +// Config for different types of code hosts. +type Config struct { + GitHub GitHub `yaml:"gitHub"` +} + +// GitHub configuration parameters. +type GitHub struct { + // URL used to access your GitHub instance, e.g. https://github.com. + URL string `yaml:"url" json:"url"` + + // Auth token used to authenticate to GitHub instance. This should be provided via env var SRC_GITHUB_TOKEN. + Token string `yaml:"token" json:"token"` + + // List of organizations. + Orgs []string `yaml:"orgs" json:"orgs"` + + // List of repositories to pull. + Repos []string `yaml:"repos" json:"repos"` +} + +type Insight struct { + Title string `yaml:"title"` + DataSeries []map[string]any `yaml:"dataSeries"` + DeleteWhenDone bool `yaml:"deleteWhenDone"` +} + +type ValidationSpec struct { + // Search queries used for validation testing, e.g. "repo:^github\\.com/gorilla/mux$ Router". + SearchQuery []string `yaml:"searchQuery"` + + // External Service configuration. + ExternalService ExternalService `yaml:"externalService"` + + // Insight used for validation testing. + Insight Insight `yaml:"insight"` +} + +// DefaultConfig returns a default configuration to be used for testing. +func DefaultConfig() *ValidationSpec { + return &ValidationSpec{ + SearchQuery: []string{ + "repo:^github.com/sourcegraph/src-cli$ config", + "repo:^github.com/sourcegraph/src-cli$@4.0.0 config", + "repo:^github.com/sourcegraph/src-cli$ type:symbol config", + }, + ExternalService: ExternalService{ + Kind: "GITHUB", + DisplayName: "sourcegraph-test", + Config: Config{ + GitHub: GitHub{ + URL: "https://github.com", + Token: "", + Orgs: []string{}, + Repos: []string{"sourcegraph/src-cli"}, + }, + }, + MaxRetries: 5, + RetryTimeoutSeconds: 5, + DeleteWhenDone: true, + }, + Insight: Insight{ + Title: "test insight", + DataSeries: []map[string]any{ + { + "query": "lang:javascript", + "label": "javascript", + "repositoryScope": "", + "lineColor": "#6495ED", + "timeScopeUnit": "MONTH", + "timeScopeValue": 1, + }, + { + "query": "lang:typescript", + "label": "typescript", + "lineColor": "#DE3163", + "repositoryScope": "", + "timeScopeUnit": "MONTH", + "timeScopeValue": 1, + }, + }, + DeleteWhenDone: true, + }, + } +} + +// LoadYamlConfig will unmarshal a YAML configuration file into a ValidationSpec. +func LoadYamlConfig(userConfig []byte) (*ValidationSpec, error) { + var config ValidationSpec + if err := yaml.Unmarshal(userConfig, &config); err != nil { + return nil, err + } + + return &config, nil +} + +// LoadJsonConfig will unmarshal a JSON configuration file into a ValidationSpec. +func LoadJsonConfig(userConfig []byte) (*ValidationSpec, error) { + var config ValidationSpec + if err := json.Unmarshal(userConfig, &config); err != nil { + return nil, err + } + + return &config, nil +} diff --git a/internal/validate/install/github.go b/internal/validate/install/github.go new file mode 100644 index 0000000000..ec506308c2 --- /dev/null +++ b/internal/validate/install/github.go @@ -0,0 +1,95 @@ +package install + +import ( + "context" + "encoding/json" + "fmt" + "log" + + "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/validate" + + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +const GITHUB = "GITHUB" + +func validateGithub(ctx context.Context, client api.Client, config *ValidationSpec) (func(), error) { + // validate external service + log.Printf("%s validating external service", validate.EmojiFingerPointRight) + + srvId, err := addGithubExternalService(ctx, client, config.ExternalService) + if err != nil { + return nil, err + } + + log.Printf("%s external service %s is being added", validate.HourglassEmoji, config.ExternalService.DisplayName) + + cleanupFunc := func() { + if srvId != "" && config.ExternalService.DeleteWhenDone { + _ = removeExternalService(ctx, client, srvId) + log.Printf("%s external service %s has been removed", validate.SuccessEmoji, config.ExternalService.DisplayName) + } + } + + log.Printf("%s cloning repository", validate.HourglassEmoji) + + repo := fmt.Sprintf("github.com/%s", config.ExternalService.Config.GitHub.Repos[0]) + cloned, err := repoCloneTimeout(ctx, client, repo, config.ExternalService) + if err != nil { + return nil, err + } + if !cloned { + return nil, errors.Newf("%s validate failed, repo did not clone\n", validate.FailureEmoji) + } + + log.Printf("%s repositry successfully cloned", validate.SuccessEmoji) + + return cleanupFunc, nil +} + +func addGithubExternalService(ctx context.Context, client api.Client, srv ExternalService) (string, error) { + if srv.Config.GitHub.Token == "" { + return "", errors.Newf("%s failed to read `SRC_GITHUB_TOKEN` environment variable", validate.WarningSign) + } + + cfg, err := json.Marshal(srv.Config.GitHub) + if err != nil { + return "", errors.Wrap(err, "addExternalService failed") + } + + q := clientQuery{ + opName: "AddExternalService", + query: `mutation AddExternalService($kind: ExternalServiceKind!, $displayName: String!, $config: String!) { + addExternalService(input:{ + kind:$kind, + displayName:$displayName, + config: $config + }) + { + id + } + }`, + variables: jsonVars{ + "kind": GITHUB, + "displayName": srv.DisplayName, + "config": string(cfg), + }, + } + + var result struct { + AddExternalService struct { + ID string `json:"id"` + } `json:"addExternalService"` + } + + ok, err := client.NewRequest(q.query, q.variables).Do(ctx, &result) + if err != nil { + return "", errors.Wrap(err, "addExternalService failed") + } + if !ok { + return "", errors.New("addExternalService failed, no data to unmarshal") + } + + return result.AddExternalService.ID, nil +} diff --git a/internal/validate/install/insight.go b/internal/validate/install/insight.go new file mode 100644 index 0000000000..2b24d03c23 --- /dev/null +++ b/internal/validate/install/insight.go @@ -0,0 +1,101 @@ +package install + +import ( + "context" + + "github.com/sourcegraph/src-cli/internal/api" + + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +func createInsight(ctx context.Context, client api.Client, insight Insight) (string, error) { + var dataSeries []map[string]interface{} + + for _, ds := range insight.DataSeries { + var series = map[string]interface{}{ + "query": ds["query"], + "options": map[string]interface{}{ + "label": ds["label"], + "lineColor": ds["lineColor"], + }, + "repositoryScope": map[string]interface{}{ + "repositories": ds["repositoryScope"], + }, + "timeScope": map[string]interface{}{ + "stepInterval": map[string]interface{}{ + "unit": ds["timeScopeUnit"], + "value": ds["timeScopeValue"], + }, + }, + } + + dataSeries = append(dataSeries, series) + } + + q := clientQuery{ + opName: "CreateLineChartSearchInsight", + query: `mutation CreateLineChartSearchInsight($input: LineChartSearchInsightInput!) { + createLineChartSearchInsight(input: $input) { + view { + id + } + } + }`, + variables: jsonVars{ + "input": map[string]interface{}{ + "options": map[string]interface{}{"title": insight.Title}, + "dataSeries": dataSeries, + }, + }, + } + + var result struct { + CreateLineChartSearchInsight struct { + View struct { + ID string `json:"id"` + } `json:"view"` + } `json:"createLineChartSearchInsight"` + } + + ok, err := client.NewRequest(q.query, q.variables).Do(ctx, &result) + if err != nil { + return "", errors.Wrap(err, "createInsight failed") + } + if !ok { + return "", errors.New("createInsight failed, no data to unmarshal") + } + + return result.CreateLineChartSearchInsight.View.ID, nil +} + +func removeInsight(ctx context.Context, client api.Client, insightId string) error { + q := clientQuery{ + opName: "DeleteInsightView", + query: `mutation DeleteInsightView ($id: ID!) { + deleteInsightView(id: $id){ + alwaysNil + } + }`, + variables: jsonVars{ + "id": insightId, + }, + } + + var result struct { + Data struct { + DeleteInsightView struct { + AlwaysNil string `json:"alwaysNil"` + } `json:"deleteInsightView"` + } `json:"data"` + } + + ok, err := client.NewRequest(q.query, q.variables).Do(ctx, &result) + if err != nil { + return errors.Wrap(err, "removeInsight failed") + } + if !ok { + return errors.New("removeInsight failed, no data to unmarshal") + } + + return nil +} diff --git a/internal/validate/install/install.go b/internal/validate/install/install.go index 1dad644610..d776400a54 100644 --- a/internal/validate/install/install.go +++ b/internal/validate/install/install.go @@ -2,124 +2,15 @@ package install import ( "context" - "encoding/json" "log" - "strings" "time" - "gopkg.in/yaml.v3" - "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/validate" "github.com/sourcegraph/sourcegraph/lib/errors" ) -type ExternalService struct { - // Type of code host, e.g. GITHUB. - Kind string `yaml:"kind"` - - // Display name of external service, e.g. sourcegraph-test. - DisplayName string `yaml:"displayName"` - - // Configuration for code host. - Config Config `yaml:"config"` - - // Maximum retry attempts when cloning test repositories. Defaults to 5 retries. - MaxRetries int `yaml:"maxRetries"` - - // Retry timeout in seconds. Defaults to 5 seconds - RetryTimeoutSeconds int `yaml:"retryTimeoutSeconds"` - - // Delete code host when test is done. Defaults to true. - DeleteWhenDone bool `yaml:"deleteWhenDone"` -} - -// Config for different types of code hosts. -type Config struct { - GitHub GitHub `yaml:"gitHub"` -} - -// GitHub configuration parameters. -type GitHub struct { - // URL used to access your GitHub instance, e.g. https://github.com. - URL string `yaml:"url" json:"url"` - - // Auth token used to authenticate to GitHub instance. This should be provided via env var SRC_GITHUB_TOKEN. - Token string `yaml:"token" json:"token"` - - // List of organizations. - Orgs []string `yaml:"orgs" json:"orgs"` - - // List of repositories to pull. - Repos []string `yaml:"repos" json:"repos"` -} - -type Insight struct { - Title string `yaml:"title"` - DataSeries []map[string]any `yaml:"dataSeries"` - DeleteWhenDone bool `yaml:"deleteWhenDone"` -} - -type ValidationSpec struct { - // Search queries used for validation testing, e.g. "repo:^github\\.com/gorilla/mux$ Router". - SearchQuery []string `yaml:"searchQuery"` - - // External Service configuration. - ExternalService ExternalService `yaml:"externalService"` - - // Insight used for validation testing. - Insight Insight `yaml:"insight"` -} - -// DefaultConfig returns a default configuration to be used for testing. -func DefaultConfig() *ValidationSpec { - return &ValidationSpec{ - SearchQuery: []string{ - "repo:^github.com/sourcegraph/src-cli$ config", - "repo:^github.com/sourcegraph/src-cli$@4.0.0 config", - "repo:^github.com/sourcegraph/src-cli$ type:symbol config", - }, - ExternalService: ExternalService{ - Kind: "GITHUB", - DisplayName: "sourcegraph-test", - Config: Config{ - GitHub: GitHub{ - URL: "https://github.com", - Token: "", - Orgs: []string{}, - Repos: []string{"sourcegraph/src-cli"}, - }, - }, - MaxRetries: 5, - RetryTimeoutSeconds: 5, - DeleteWhenDone: true, - }, - Insight: Insight{ - Title: "test insight", - DataSeries: []map[string]any{ - { - "query": "lang:javascript", - "label": "javascript", - "repositoryScope": "", - "lineColor": "#6495ED", - "timeScopeUnit": "MONTH", - "timeScopeValue": 1, - }, - { - "query": "lang:typescript", - "label": "typescript", - "lineColor": "#DE3163", - "repositoryScope": "", - "timeScopeUnit": "MONTH", - "timeScopeValue": 1, - }, - }, - DeleteWhenDone: true, - }, - } -} - type jsonVars map[string]interface{} type clientQuery struct { @@ -128,62 +19,22 @@ type clientQuery struct { variables jsonVars } -// LoadYamlConfig will unmarshal a YAML configuration file into a ValidationSpec. -func LoadYamlConfig(userConfig []byte) (*ValidationSpec, error) { - var config ValidationSpec - if err := yaml.Unmarshal(userConfig, &config); err != nil { - return nil, err - } - - return &config, nil -} - -// LoadJsonConfig will unmarshal a JSON configuration file into a ValidationSpec. -func LoadJsonConfig(userConfig []byte) (*ValidationSpec, error) { - var config ValidationSpec - if err := json.Unmarshal(userConfig, &config); err != nil { - return nil, err - } - - return &config, nil -} - // Validate runs a series of validation checks such as cloning a repository, running search queries, and // creating insights, based on the configuration provided. func Validate(ctx context.Context, client api.Client, config *ValidationSpec) error { - log.Printf("%s validating external service", validate.EmojiFingerPointRight) - - if config.ExternalService.DisplayName != "" { - srvID, err := addExternalService(ctx, client, config.ExternalService) + switch config.ExternalService.Kind { + case GITHUB: + cleanup, err := validateGithub(ctx, client, config) if err != nil { return err } - - log.Printf("%s external service %s is being added", validate.HourglassEmoji, config.ExternalService.DisplayName) - - defer func() { - if srvID != "" && config.ExternalService.DeleteWhenDone { - _ = removeExternalService(ctx, client, srvID) - log.Printf("%s external service %s has been removed", validate.SuccessEmoji, config.ExternalService.DisplayName) - } - }() - } - - log.Printf("%s cloning repository", validate.HourglassEmoji) - - cloned, err := repoCloneTimeout(ctx, client, config.ExternalService) - if err != nil { - return err - } - if !cloned { - return errors.Newf("%s validate failed, repo did not clone\n", validate.FailureEmoji) + defer cleanup() } - log.Printf("%s repositry successfully cloned", validate.SuccessEmoji) - - log.Printf("%s validating search queries", validate.EmojiFingerPointRight) - + // run search queries if config.SearchQuery != nil { + log.Printf("%s validating search queries", validate.EmojiFingerPointRight) + for i := 0; i < len(config.SearchQuery); i++ { matchCount, err := searchMatchCount(ctx, client, config.SearchQuery[i]) if err != nil { @@ -196,9 +47,9 @@ func Validate(ctx context.Context, client api.Client, config *ValidationSpec) er } } - log.Printf("%s validating code insight", validate.EmojiFingerPointRight) - if config.Insight.Title != "" { + log.Printf("%s validating code insight", validate.EmojiFingerPointRight) + log.Printf("%s insight %s is being added", validate.HourglassEmoji, config.Insight.Title) insightId, err := createInsight(ctx, client, config.Insight) @@ -220,48 +71,6 @@ func Validate(ctx context.Context, client api.Client, config *ValidationSpec) er return nil } -func addExternalService(ctx context.Context, client api.Client, srv ExternalService) (string, error) { - config, err := json.Marshal(srv.Config.GitHub) - if err != nil { - return "", errors.Wrap(err, "addExternalService failed") - } - - q := clientQuery{ - opName: "AddExternalService", - query: `mutation AddExternalService($kind: ExternalServiceKind!, $displayName: String!, $config: String!) { - addExternalService(input:{ - kind:$kind, - displayName:$displayName, - config: $config - }) - { - id - } - }`, - variables: jsonVars{ - "kind": srv.Kind, - "displayName": srv.DisplayName, - "config": string(config), - }, - } - - var result struct { - AddExternalService struct { - ID string `json:"id"` - } `json:"addExternalService"` - } - - ok, err := client.NewRequest(q.query, q.variables).Do(ctx, &result) - if err != nil { - return "", errors.Wrap(err, "addExternalService failed") - } - if !ok { - return "", errors.New("addExternalService failed, no data to unmarshal") - } - - return result.AddExternalService.ID, nil -} - func removeExternalService(ctx context.Context, client api.Client, id string) error { q := clientQuery{ opName: "DeleteExternalService", @@ -321,15 +130,9 @@ func searchMatchCount(ctx context.Context, client api.Client, searchExpr string) return result.Search.Results.MatchCount, nil } -func repoCloneTimeout(ctx context.Context, client api.Client, srv ExternalService) (bool, error) { - // construct repo string for query - var name strings.Builder - - name.WriteString("github.com/") - name.WriteString(srv.Config.GitHub.Repos[0]) - +func repoCloneTimeout(ctx context.Context, client api.Client, repo string, srv ExternalService) (bool, error) { for i := 0; i < srv.MaxRetries; i++ { - repos, err := listClonedRepos(ctx, client, []string{name.String()}) + repos, err := listClonedRepos(ctx, client, []string{repo}) if err != nil { return false, err } @@ -389,95 +192,3 @@ func listClonedRepos(ctx context.Context, client api.Client, names []string) ([] return nodeNames, nil } - -func createInsight(ctx context.Context, client api.Client, insight Insight) (string, error) { - var dataSeries []map[string]interface{} - - for _, ds := range insight.DataSeries { - var series = map[string]interface{}{ - "query": ds["query"], - "options": map[string]interface{}{ - "label": ds["label"], - "lineColor": ds["lineColor"], - }, - "repositoryScope": map[string]interface{}{ - "repositories": ds["repositoryScope"], - }, - "timeScope": map[string]interface{}{ - "stepInterval": map[string]interface{}{ - "unit": ds["timeScopeUnit"], - "value": ds["timeScopeValue"], - }, - }, - } - - dataSeries = append(dataSeries, series) - } - - q := clientQuery{ - opName: "CreateLineChartSearchInsight", - query: `mutation CreateLineChartSearchInsight($input: LineChartSearchInsightInput!) { - createLineChartSearchInsight(input: $input) { - view { - id - } - } - }`, - variables: jsonVars{ - "input": map[string]interface{}{ - "options": map[string]interface{}{"title": insight.Title}, - "dataSeries": dataSeries, - }, - }, - } - - var result struct { - CreateLineChartSearchInsight struct { - View struct { - ID string `json:"id"` - } `json:"view"` - } `json:"createLineChartSearchInsight"` - } - - ok, err := client.NewRequest(q.query, q.variables).Do(ctx, &result) - if err != nil { - return "", errors.Wrap(err, "createInsight failed") - } - if !ok { - return "", errors.New("createInsight failed, no data to unmarshal") - } - - return result.CreateLineChartSearchInsight.View.ID, nil -} - -func removeInsight(ctx context.Context, client api.Client, insightId string) error { - q := clientQuery{ - opName: "DeleteInsightView", - query: `mutation DeleteInsightView ($id: ID!) { - deleteInsightView(id: $id){ - alwaysNil - } - }`, - variables: jsonVars{ - "id": insightId, - }, - } - - var result struct { - Data struct { - DeleteInsightView struct { - AlwaysNil string `json:"alwaysNil"` - } `json:"deleteInsightView"` - } `json:"data"` - } - - ok, err := client.NewRequest(q.query, q.variables).Do(ctx, &result) - if err != nil { - return errors.Wrap(err, "removeInsight failed") - } - if !ok { - return errors.New("removeInsight failed, no data to unmarshal") - } - - return nil -} From 9e8f082aded2561ecb574b735f1f98f7682c3683 Mon Sep 17 00:00:00 2001 From: Jacob Pleiness Date: Mon, 20 Mar 2023 09:55:08 -0400 Subject: [PATCH 317/647] Release: update CHANGELOG.md for release process of 5.0.2 (#960) * Update CHANGELOG.md with changes needed for 5.0.2 release in step with DEVELOPMENT.md instructions. * Update CHANGELOG.md Co-authored-by: Bolaji Olajide <25608335+BolajiOlajide@users.noreply.github.com> --------- Co-authored-by: Bolaji Olajide <25608335+BolajiOlajide@users.noreply.github.com> --- CHANGELOG.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6572b67c18..0729e1abe6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,16 @@ All notable changes to `src-cli` are documented in this file. ### Removed +## 5.0.2 + +### Added + +- `src admin create` has been added to setup initial admin accounts on new Sourcegraph deployments. [957](https://github.com/sourcegraph/src-cli/pull/957) + +### Fixed + +- Fixed `src validate install` requiring `SRC_GITHUB_TOKEN` in all cases. [958](https://github.com/sourcegraph/src-cli/pull/958) + ## 5.0.1 ### Fixed From e0a4d7bcd594c94520ed7a8c0d3519b9d19ba07d Mon Sep 17 00:00:00 2001 From: Jacob Pleiness Date: Mon, 20 Mar 2023 12:30:03 -0400 Subject: [PATCH 318/647] Fix `go.mod` dirty state error in build (#961) --- go.mod | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/go.mod b/go.mod index 5207edaacd..263376a6a4 100644 --- a/go.mod +++ b/go.mod @@ -18,6 +18,7 @@ require ( github.com/hexops/autogold v1.3.0 github.com/jedib0t/go-pretty/v6 v6.3.7 github.com/jig/teereadcloser v0.0.0-20181016160506-953720c48e05 + github.com/json-iterator/go v1.1.12 github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 github.com/mattn/go-isatty v0.0.16 github.com/neelance/parallel v0.0.0-20160708114440-4de9ce63d14c @@ -99,7 +100,6 @@ require ( github.com/jhump/protoreflect v1.12.1-0.20220417024638-438db461d753 // indirect github.com/jmespath/go-jmespath v0.4.0 // indirect github.com/josharian/intern v1.0.0 // indirect - github.com/json-iterator/go v1.1.12 // indirect github.com/klauspost/compress v1.15.11 // indirect github.com/klauspost/pgzip v1.2.5 // indirect github.com/kr/pretty v0.3.1 // indirect From 13f6567ec26e8d72c355706c30e5a1983d1c04d3 Mon Sep 17 00:00:00 2001 From: Kelli Rockwell Date: Mon, 20 Mar 2023 09:42:03 -0700 Subject: [PATCH 319/647] Allow empty commits in copy pre-release step (#962) --- .github/workflows/goreleaser.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index b344d9012d..dfa7dd7aba 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -133,7 +133,7 @@ jobs: git config user.name sourcegraph-bot git config user.email sourcegraph-bot-github@sourcegraph.com git add . - git commit -m "Copy previous release" + git commit --allow-empty -m "Copy previous release" git push # goreleaser runs tests before building, then uses goreleaser to publish to Homebrew and From b869716f2a3bb2c4bb9593cb9cf160c058b8245e Mon Sep 17 00:00:00 2001 From: Jacob Pleiness Date: Tue, 21 Mar 2023 20:26:33 -0400 Subject: [PATCH 320/647] Fix `src admin create` outputing token to stderr instead of stdout (#963) --- CHANGELOG.md | 2 ++ cmd/src/admin_create.go | 5 +---- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0729e1abe6..c632f5df52 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,8 @@ All notable changes to `src-cli` are documented in this file. ### Fixed +- Fixed `src admin create` returning token to stderr instead of stdout. + ### Removed ## 5.0.2 diff --git a/cmd/src/admin_create.go b/cmd/src/admin_create.go index 5b7bdf9110..8fdf719647 100644 --- a/cmd/src/admin_create.go +++ b/cmd/src/admin_create.go @@ -83,10 +83,7 @@ Environmental variables return err } - _, err = fmt.Fprintf(flag.CommandLine.Output(), "%s\n", token) - if err != nil { - return err - } + fmt.Println(token) } return nil From 5295c1f7bf92743e7c9c86d57f4a18cbabd57ce0 Mon Sep 17 00:00:00 2001 From: Jacob Pleiness Date: Tue, 28 Mar 2023 09:23:03 -0400 Subject: [PATCH 321/647] Fix GraphQL query to reflect changes in 5.0 (#964) --- internal/validate/install/install.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/internal/validate/install/install.go b/internal/validate/install/install.go index d776400a54..d9154b1d64 100644 --- a/internal/validate/install/install.go +++ b/internal/validate/install/install.go @@ -147,9 +147,10 @@ func repoCloneTimeout(ctx context.Context, client api.Client, repo string, srv E func listClonedRepos(ctx context.Context, client api.Client, names []string) ([]string, error) { q := clientQuery{ opName: "ListRepos", - query: `query ListRepos($names: [String!]) { + query: `query ListRepos($names: [String!], $first: Int) { repositories( names: $names + first: $first ) { nodes { name @@ -161,6 +162,7 @@ func listClonedRepos(ctx context.Context, client api.Client, names []string) ([] }`, variables: jsonVars{ "names": names, + "first": 5, }, } From 72e805c0c83e586e474ff8fb823a1911b9ecc62a Mon Sep 17 00:00:00 2001 From: Vincent Date: Tue, 4 Apr 2023 12:08:13 +0200 Subject: [PATCH 322/647] Update asdf to Go 1.19.7 (#967) --- .tool-versions | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.tool-versions b/.tool-versions index 7a8f1310f6..69e13fbcc5 100644 --- a/.tool-versions +++ b/.tool-versions @@ -1,3 +1,3 @@ -golang 1.19.6 +golang 1.19.7 shfmt 3.2.0 shellcheck 0.7.1 From 58b3f701691cbdbd10b54161d9bfca88b781480d Mon Sep 17 00:00:00 2001 From: Vincent Date: Wed, 5 Apr 2023 16:34:52 +0200 Subject: [PATCH 323/647] Update to Go 1.19.8 (#968) * Update asdf to Go 1.19.8 * update docker image --- .tool-versions | 2 +- Dockerfile | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.tool-versions b/.tool-versions index 69e13fbcc5..9750f5d6c7 100644 --- a/.tool-versions +++ b/.tool-versions @@ -1,3 +1,3 @@ -golang 1.19.7 +golang 1.19.8 shfmt 3.2.0 shellcheck 0.7.1 diff --git a/Dockerfile b/Dockerfile index 002f58fc45..6f04b05964 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,7 +4,7 @@ # # Nothing fancy here: we copy in the source code and build on the Alpine Go # image. Refer to .dockerignore to get a sense of what we're not going to copy. -FROM golang:1.17-alpine@sha256:1d4c7fcfd0c4c917383755ca3b6f6c1f797ec16b83cdebc672d9b08a79b64644 as builder +FROM golang:1.19.8-alpine@sha256:841c160ed35923d96c95c52403c4e6db5decd9cbce034aa851e412ade5d4b74f as builder COPY . /src WORKDIR /src From f0e8fc23d8de8a3e3cb306da7f8444734ccf9f3b Mon Sep 17 00:00:00 2001 From: Jacob Pleiness Date: Tue, 11 Apr 2023 17:26:28 -0400 Subject: [PATCH 324/647] Update CHANGELOG.md for release (#969) --- CHANGELOG.md | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c632f5df52..bafe534f0f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,10 +17,15 @@ All notable changes to `src-cli` are documented in this file. ### Fixed -- Fixed `src admin create` returning token to stderr instead of stdout. - ### Removed +## 5.0.3 + +### Fixed + +- Fixed `src admin create` returning token to stderr instead of stdout. [963](https://github.com/sourcegraph/src-cli/pull/963) +- Fixed `src validate install` failure with Sourcegraph v5.0.0. [964](https://github.com/sourcegraph/src-cli/pull/964) + ## 5.0.2 ### Added From 3c38e8195faf7f4914f3a56ba5dd52c8edc7aa2a Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Thu, 20 Apr 2023 10:59:20 +0200 Subject: [PATCH 325/647] actions: fix job name conflict (#970) * run go-ci on prs * fix event name * go test on specific pr types * remove pull_request type and rename lint job --- .github/workflows/go-lint.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/go-lint.yml b/.github/workflows/go-lint.yml index 3561c53e88..cc73193d04 100644 --- a/.github/workflows/go-lint.yml +++ b/.github/workflows/go-lint.yml @@ -4,7 +4,7 @@ on: - push jobs: - go-test: + go-lint: runs-on: ubuntu-latest steps: - name: Checkout From f5469f29a7939411f6d9a53d2fb03ad4863d5123 Mon Sep 17 00:00:00 2001 From: Heechul Ryu Date: Mon, 24 Apr 2023 01:19:02 -0700 Subject: [PATCH 326/647] Add nix flake support (#965) * Add nix flake support * Apply suggestions from code review Co-authored-by: Noah S-C * Move nix files to /contrib --------- Co-authored-by: Noah S-C --- contrib/.gitignore | 2 ++ contrib/default.nix | 10 ++++++++ contrib/flake.lock | 59 +++++++++++++++++++++++++++++++++++++++++++++ contrib/flake.nix | 31 ++++++++++++++++++++++++ 4 files changed, 102 insertions(+) create mode 100644 contrib/.gitignore create mode 100644 contrib/default.nix create mode 100644 contrib/flake.lock create mode 100644 contrib/flake.nix diff --git a/contrib/.gitignore b/contrib/.gitignore new file mode 100644 index 0000000000..d9d5722c82 --- /dev/null +++ b/contrib/.gitignore @@ -0,0 +1,2 @@ +# for `nix build` +result diff --git a/contrib/default.nix b/contrib/default.nix new file mode 100644 index 0000000000..2cccff28d5 --- /dev/null +++ b/contrib/default.nix @@ -0,0 +1,10 @@ +(import + ( + let lock = builtins.fromJSON (builtins.readFile ./flake.lock); in + fetchTarball { + url = "https://github.com/edolstra/flake-compat/archive/${lock.nodes.flake-compat.locked.rev}.tar.gz"; + sha256 = lock.nodes.flake-compat.locked.narHash; + } + ) + { src = ./.; } +).defaultNix diff --git a/contrib/flake.lock b/contrib/flake.lock new file mode 100644 index 0000000000..2fd91e57b1 --- /dev/null +++ b/contrib/flake.lock @@ -0,0 +1,59 @@ +{ + "nodes": { + "flake-compat": { + "flake": false, + "locked": { + "lastModified": 1673956053, + "narHash": "sha256-4gtG9iQuiKITOjNQQeQIpoIB6b16fm+504Ch3sNKLd8=", + "owner": "edolstra", + "repo": "flake-compat", + "rev": "35bb57c0c8d8b62bbfd284272c928ceb64ddbde9", + "type": "github" + }, + "original": { + "owner": "edolstra", + "repo": "flake-compat", + "type": "github" + } + }, + "flake-utils": { + "locked": { + "lastModified": 1678901627, + "narHash": "sha256-U02riOqrKKzwjsxc/400XnElV+UtPUQWpANPlyazjH0=", + "owner": "numtide", + "repo": "flake-utils", + "rev": "93a2b84fc4b70d9e089d029deacc3583435c2ed6", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "flake-utils", + "type": "github" + } + }, + "nixpkgs": { + "locked": { + "lastModified": 1680125544, + "narHash": "sha256-mlqo1r+TZUOuypWdrZHluxWL+E5WzXlUXNZ9Y0WLDFU=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "9a6aabc4740790ef3bbb246b86d029ccf6759658", + "type": "github" + }, + "original": { + "id": "nixpkgs", + "ref": "nixos-unstable", + "type": "indirect" + } + }, + "root": { + "inputs": { + "flake-compat": "flake-compat", + "flake-utils": "flake-utils", + "nixpkgs": "nixpkgs" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/contrib/flake.nix b/contrib/flake.nix new file mode 100644 index 0000000000..5c6bef9aa4 --- /dev/null +++ b/contrib/flake.nix @@ -0,0 +1,31 @@ +{ + description = "Sourcegraph CLI"; + + inputs = { + nixpkgs.url = "nixpkgs/nixos-unstable"; + flake-utils.url = "github:numtide/flake-utils"; + flake-compat = { + url = "github:edolstra/flake-compat"; + flake = false; + }; + }; + + outputs = { self, nixpkgs, flake-utils, ... }: + flake-utils.lib.eachDefaultSystem (system: + let + pkgs = import nixpkgs { inherit system; }; + in + rec { + packages.src-cli = with pkgs; buildGoModule.override { go = pkgs.go_1_19; } { + pname = "src-cli"; + version = self.shortRev or "dirty"; + src = ../.; + + subPackages = [ "cmd/src" ]; + + vendorSha256 = "sha256-NMLrBYGscZexnR43I4Ku9aqzJr38z2QAnZo0RouHFrc="; + }; + packages.default = packages.src-cli; + } + ); +} From ea9e5018dc66f1c2e73f0eca9b62c7f13dd722b7 Mon Sep 17 00:00:00 2001 From: Erzhan Torokulov Date: Mon, 24 Apr 2023 14:56:45 +0600 Subject: [PATCH 327/647] (chore) rename "repo {add|update|delete}-kvp" to "repo {add|update|delete}-metadata" (#972) --- CHANGELOG.md | 1 + cmd/src/repos.go | 12 +++++------ ...repos_add_kvp.go => repos_add_metadata.go} | 21 +++++++++++-------- ...delete_kvp.go => repos_delete_metadata.go} | 17 ++++++++------- ...update_kvp.go => repos_update_metadata.go} | 17 ++++++++------- 5 files changed, 39 insertions(+), 29 deletions(-) rename cmd/src/{repos_add_kvp.go => repos_add_metadata.go} (67%) rename cmd/src/{repos_delete_kvp.go => repos_delete_metadata.go} (69%) rename cmd/src/{repos_update_kvp.go => repos_update_metadata.go} (72%) diff --git a/CHANGELOG.md b/CHANGELOG.md index bafe534f0f..ad96502b46 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ All notable changes to `src-cli` are documented in this file. ### Added ### Changed +- Renamed `src repo {add|update|delete}-kvp` to `repo {add|update|delete}-metadata` [#972](https://github.com/sourcegraph/src-cli/pull/972) ### Fixed diff --git a/cmd/src/repos.go b/cmd/src/repos.go index d58fe0abe0..5e935b8f4b 100644 --- a/cmd/src/repos.go +++ b/cmd/src/repos.go @@ -20,12 +20,12 @@ Usage: The commands are: - get gets a repository - list lists repositories - delete deletes repositories - add-kvp adds a key-value pair to a repository - update-kvp updates a key-value pair on a repository - delete-kvp deletes a key-value pair from a repository + get gets a repository + list lists repositories + delete deletes repositories + add-metadata adds a key-value pair metadata to a repository + update-metadata updates a key-value pair metadata on a repository + delete-metadata deletes a key-value pair metadata from a repository Use "src repos [command] -h" for more information about a command. ` diff --git a/cmd/src/repos_add_kvp.go b/cmd/src/repos_add_metadata.go similarity index 67% rename from cmd/src/repos_add_kvp.go rename to cmd/src/repos_add_metadata.go index d7155c54c1..da01650a73 100644 --- a/cmd/src/repos_add_kvp.go +++ b/cmd/src/repos_add_metadata.go @@ -13,23 +13,25 @@ func init() { usage := ` Examples: - Add a key-value pair to a repository: + Add a key-value pair metadata to a repository: - $ src repos add-kvp -repo=repoID -key=mykey -value=myvalue + $ src repos add-metadata -repo=repoID -key=mykey -value=myvalue Omitting -value will create a tag (a key with a null value). + + [DEPRECATED] Note that 'add-kvp' is deprecated and will be removed in future release. Use 'add-metadata' instead. ` - flagSet := flag.NewFlagSet("add-kvp", flag.ExitOnError) + flagSet := flag.NewFlagSet("add-metadata", flag.ExitOnError) usageFunc := func() { fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src repos %s':\n", flagSet.Name()) flagSet.PrintDefaults() fmt.Println(usage) } var ( - repoFlag = flagSet.String("repo", "", `The ID of the repo to add the key-value pair to (required)`) - keyFlag = flagSet.String("key", "", `The name of the key to add (required)`) - valueFlag = flagSet.String("value", "", `The value associated with the key. Defaults to null.`) + repoFlag = flagSet.String("repo", "", `The ID of the repo to add the key-value pair metadata to (required)`) + keyFlag = flagSet.String("key", "", `The name of the metadata key to add (required)`) + valueFlag = flagSet.String("value", "", `The metadata value associated with the metadata key. Defaults to null.`) apiFlags = api.NewFlags(flagSet) ) @@ -60,7 +62,7 @@ Examples: client := cfg.apiClient(apiFlags, flagSet.Output()) - query := `mutation addKVP( + query := `mutation addRepoMetadata( $repo: ID!, $key: String!, $value: String, @@ -83,9 +85,9 @@ Examples: } if valueFlag != nil { - fmt.Printf("Key-value pair '%s:%v' created.\n", *keyFlag, *valueFlag) + fmt.Printf("Key-value pair metadata '%s:%v' created.\n", *keyFlag, *valueFlag) } else { - fmt.Printf("Key-value pair '%s:' created.\n", *keyFlag) + fmt.Printf("Key-value pair metadata '%s:' created.\n", *keyFlag) } return nil } @@ -93,6 +95,7 @@ Examples: // Register the command. reposCommands = append(reposCommands, &command{ flagSet: flagSet, + aliases: []string{"add-kvp"}, handler: handler, usageFunc: usageFunc, }) diff --git a/cmd/src/repos_delete_kvp.go b/cmd/src/repos_delete_metadata.go similarity index 69% rename from cmd/src/repos_delete_kvp.go rename to cmd/src/repos_delete_metadata.go index 4b9612a3a9..178b7ac0c8 100644 --- a/cmd/src/repos_delete_kvp.go +++ b/cmd/src/repos_delete_metadata.go @@ -6,6 +6,7 @@ import ( "fmt" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/src-cli/internal/api" ) @@ -13,21 +14,22 @@ func init() { usage := ` Examples: - Delete a key-value pair from a repository: + Delete a key-value pair metadata from a repository: - $ src repos delete-kvp -repo=repoID -key=mykey + $ src repos delete-metadata -repo=repoID -key=mykey + [DEPRECATED] Note 'delete-kvp' is deprecated and will be removed in future release. Use 'delete-metadata' instead. ` - flagSet := flag.NewFlagSet("delete-kvp", flag.ExitOnError) + flagSet := flag.NewFlagSet("delete-metadata", flag.ExitOnError) usageFunc := func() { fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src repos %s':\n", flagSet.Name()) flagSet.PrintDefaults() fmt.Println(usage) } var ( - repoFlag = flagSet.String("repo", "", `The ID of the repo with the key-value pair to be deleted (required)`) - keyFlag = flagSet.String("key", "", `The name of the key to be deleted (required)`) + repoFlag = flagSet.String("repo", "", `The ID of the repo with the key-value pair metadata to be deleted (required)`) + keyFlag = flagSet.String("key", "", `The name of the metadata key to be deleted (required)`) apiFlags = api.NewFlags(flagSet) ) @@ -52,7 +54,7 @@ Examples: client := cfg.apiClient(apiFlags, flagSet.Output()) - query := `mutation deleteKVP( + query := `mutation deleteRepoMetadata( $repo: ID!, $key: String!, ) { @@ -71,13 +73,14 @@ Examples: return err } - fmt.Printf("Key-value pair with key '%s' deleted.\n", *keyFlag) + fmt.Printf("Key-value pair metadata with key '%s' deleted.\n", *keyFlag) return nil } // Register the command. reposCommands = append(reposCommands, &command{ flagSet: flagSet, + aliases: []string{"delete-kvp"}, handler: handler, usageFunc: usageFunc, }) diff --git a/cmd/src/repos_update_kvp.go b/cmd/src/repos_update_metadata.go similarity index 72% rename from cmd/src/repos_update_kvp.go rename to cmd/src/repos_update_metadata.go index 4e12e9a423..f79922dc70 100644 --- a/cmd/src/repos_update_kvp.go +++ b/cmd/src/repos_update_metadata.go @@ -13,23 +13,25 @@ func init() { usage := ` Examples: - Update the value for a key on a repository: + Update the metadata value for a metadata key on a repository: - $ src repos update-kvp -repo=repoID -key=my-key -value=new-value + $ src repos update-metadata -repo=repoID -key=my-key -value=new-value Omitting -value will set the value of the key to null. + + [DEPRECATED] Note that 'update-kvp' is deprecated and will be removed in future release. Use 'update-metadata' instead. ` - flagSet := flag.NewFlagSet("update-kvp", flag.ExitOnError) + flagSet := flag.NewFlagSet("update-metadata", flag.ExitOnError) usageFunc := func() { fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src repos %s':\n", flagSet.Name()) flagSet.PrintDefaults() fmt.Println(usage) } var ( - repoFlag = flagSet.String("repo", "", `The ID of the repo with the key to be updated (required)`) - keyFlag = flagSet.String("key", "", `The name of the key to be updated (required)`) - valueFlag = flagSet.String("value", "", `The new value of the key to be set. Defaults to null.`) + repoFlag = flagSet.String("repo", "", `The ID of the repo with the metadata key to be updated (required)`) + keyFlag = flagSet.String("key", "", `The name of the metadata key to be updated (required)`) + valueFlag = flagSet.String("value", "", `The new metadata value of the metadata key to be set. Defaults to null.`) apiFlags = api.NewFlags(flagSet) ) @@ -60,7 +62,7 @@ Examples: client := cfg.apiClient(apiFlags, flagSet.Output()) - query := `mutation updateKVP( + query := `mutation updateMetadata( $repo: ID!, $key: String!, $value: String, @@ -93,6 +95,7 @@ Examples: // Register the command. reposCommands = append(reposCommands, &command{ flagSet: flagSet, + aliases: []string{"update-kvp"}, handler: handler, usageFunc: usageFunc, }) From 1ef7956e2de5f0aea295631f98d6f0326c2b6367 Mon Sep 17 00:00:00 2001 From: Sam Johns Date: Mon, 24 Apr 2023 10:56:05 -0400 Subject: [PATCH 328/647] Scj/update/smtp validate (#973) * add config for smtp * add function for smtp * smtp enabled check * lint * change Smtp.Test to Smtp.Enabled --- internal/validate/install/config.go | 12 +++++++++ internal/validate/install/install.go | 38 ++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) diff --git a/internal/validate/install/config.go b/internal/validate/install/config.go index 39695dbb25..7578522f13 100644 --- a/internal/validate/install/config.go +++ b/internal/validate/install/config.go @@ -52,6 +52,11 @@ type Insight struct { DeleteWhenDone bool `yaml:"deleteWhenDone"` } +type Smtp struct { + Enabled bool `yaml:"enabled"` + To string `yaml:"to"` +} + type ValidationSpec struct { // Search queries used for validation testing, e.g. "repo:^github\\.com/gorilla/mux$ Router". SearchQuery []string `yaml:"searchQuery"` @@ -61,6 +66,9 @@ type ValidationSpec struct { // Insight used for validation testing. Insight Insight `yaml:"insight"` + + //Test SMTP configuration + Smtp Smtp `yaml:"smtp"` } // DefaultConfig returns a default configuration to be used for testing. @@ -108,6 +116,10 @@ func DefaultConfig() *ValidationSpec { }, DeleteWhenDone: true, }, + Smtp: Smtp{ + Enabled: false, + To: "example@domain.com", + }, } } diff --git a/internal/validate/install/install.go b/internal/validate/install/install.go index d9154b1d64..a9d905a696 100644 --- a/internal/validate/install/install.go +++ b/internal/validate/install/install.go @@ -47,6 +47,23 @@ func Validate(ctx context.Context, client api.Client, config *ValidationSpec) er } } + if config.Smtp.Enabled { + log.Printf("%s validating smtp connection", validate.EmojiFingerPointRight) + + smtpQuery := `mutation sendTestEmail($to: String!) { + sendTestEmail(to: $to) + }` + smtpVars := map[string]interface{}{ + "to": config.Smtp.To, + } + + result, err := checkSmtp(ctx, client, smtpQuery, smtpVars) + if err != nil { + return err + } + log.Printf("%s '%s'", validate.SuccessEmoji, result) + } + if config.Insight.Title != "" { log.Printf("%s validating code insight", validate.EmojiFingerPointRight) @@ -130,6 +147,27 @@ 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) { + q := clientQuery{ + opName: "CheckSmtpConfig", + query: query, + variables: variables, + } + + var result struct { + SendTestEmail string `json:"sendTestEmail"` + } + + ok, err := client.NewRequest(q.query, q.variables).Do(ctx, &result) + if err != nil { + return "", errors.Wrap(err, "sendTestEmail failed") + } + if !ok { + return "", errors.New("sendTestEmail failed, no data to unmarshal") + } + return result.SendTestEmail, nil +} + func repoCloneTimeout(ctx context.Context, client api.Client, repo string, srv ExternalService) (bool, error) { for i := 0; i < srv.MaxRetries; i++ { repos, err := listClonedRepos(ctx, client, []string{repo}) From 4eff6b729c30efe97f9e88acc8db0889e03577c0 Mon Sep 17 00:00:00 2001 From: Sam Johns Date: Mon, 24 Apr 2023 12:34:37 -0400 Subject: [PATCH 329/647] Scj/update/executor validate (#974) * add executor option for src validate install * remove commented code, remove option * remove binary * lint * update error int to -1 --- internal/validate/install/config.go | 11 ++++++ internal/validate/install/install.go | 52 ++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+) diff --git a/internal/validate/install/config.go b/internal/validate/install/config.go index 7578522f13..930cf2027b 100644 --- a/internal/validate/install/config.go +++ b/internal/validate/install/config.go @@ -52,6 +52,11 @@ type Insight struct { DeleteWhenDone bool `yaml:"deleteWhenDone"` } +type Executor struct { + Enabled bool `yaml:"enabled"` + Count bool `yaml:"count"` +} + type Smtp struct { Enabled bool `yaml:"enabled"` To string `yaml:"to"` @@ -67,6 +72,9 @@ type ValidationSpec struct { // Insight used for validation testing. Insight Insight `yaml:"insight"` + // Executor check configuration + Executor Executor `yaml:"executor"` + //Test SMTP configuration Smtp Smtp `yaml:"smtp"` } @@ -116,6 +124,9 @@ func DefaultConfig() *ValidationSpec { }, DeleteWhenDone: true, }, + Executor: Executor{ + Enabled: false, + }, Smtp: Smtp{ Enabled: false, To: "example@domain.com", diff --git a/internal/validate/install/install.go b/internal/validate/install/install.go index a9d905a696..9b3966190c 100644 --- a/internal/validate/install/install.go +++ b/internal/validate/install/install.go @@ -47,6 +47,34 @@ func Validate(ctx context.Context, client api.Client, config *ValidationSpec) er } } + // run executor queries + if config.Executor.Enabled { + log.Printf("%s validating executor connections", validate.EmojiFingerPointRight) + + executorQuery := `query executors($query: String, $active: Boolean, $first: Int, $after: String) { + executors(query: $query, active: $active, first: $first, after: $after){ + totalCount + } + }` + executorVars := map[string]interface{}{ + "query": "", + "active": true, + "first": 100, + "after": "", + } + + totalCount, err := checkExecutors(ctx, client, executorQuery, executorVars) + if err != nil { + return err + } + if totalCount == 0 { + log.Printf("%s validation failed, 0 executors found", validate.FlashingLightEmoji) + } + if totalCount >= 1 { + log.Printf("%s executors found, %d executor(s) connected to Sourcegraph instance", validate.SuccessEmoji, totalCount) + } + } + if config.Smtp.Enabled { log.Printf("%s validating smtp connection", validate.EmojiFingerPointRight) @@ -88,6 +116,30 @@ 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) { + q := clientQuery{ + opName: "CheckExecutorConnection", + query: query, + variables: variables, + } + + var result struct { + Executor struct { + TotalCount int `json:"totalCount"` + } `json:"executors"` + } + + ok, err := client.NewRequest(q.query, q.variables).Do(ctx, &result) + if err != nil { + return -1, errors.Wrap(err, "checkExecutors failed") + } + if !ok { + return -1, errors.New("checkExecutors failed, no data to unmarshal") + } + + return result.Executor.TotalCount, nil +} + func removeExternalService(ctx context.Context, client api.Client, id string) error { q := clientQuery{ opName: "DeleteExternalService", From ef134fbbe74623d55fe58129df218adc014b1b65 Mon Sep 17 00:00:00 2001 From: Sam Johns Date: Tue, 25 Apr 2023 18:06:18 -0400 Subject: [PATCH 330/647] update changelog (#976) --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index ad96502b46..b062bdb1fe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,8 @@ All notable changes to `src-cli` are documented in this file. ## Unreleased ### Added +- `src validate install` can check executor connections [#974](https://github.com/sourcegraph/src-cli/pull/974) +- `src validate install` can send test SMTP message [#973](https://github.com/sourcegraph/src-cli/pull/973) ### Changed - Renamed `src repo {add|update|delete}-kvp` to `repo {add|update|delete}-metadata` [#972](https://github.com/sourcegraph/src-cli/pull/972) From 3d540ecfa40e8a8ac07baf8379d0302baddb6c19 Mon Sep 17 00:00:00 2001 From: Erzhan Torokulov Date: Thu, 27 Apr 2023 18:15:02 +0600 Subject: [PATCH 331/647] (feat) add "src repos {add|update|delete}-metadata -repo-name" flag support (#977) * chore(vscode): add cody.codebase setting to use with Cody extension * update CHANGELOG.md --- .vscode/settings.json | 3 ++- CHANGELOG.md | 1 + cmd/src/repos.go | 12 ++++++++++++ cmd/src/repos_add_metadata.go | 22 +++++++++++++--------- cmd/src/repos_delete_metadata.go | 19 +++++++++++-------- cmd/src/repos_update_metadata.go | 22 +++++++++++++--------- 6 files changed, 52 insertions(+), 27 deletions(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index 8b2f950a82..5cb6acc364 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -8,5 +8,6 @@ "go.useLanguageServer": true, "gopls": { "local": "github.com/sourcegraph/src-cli" - } + }, + "cody.codebase": "github.com/sourcegraph/src-cli", } diff --git a/CHANGELOG.md b/CHANGELOG.md index b062bdb1fe..ab09244f7b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ All notable changes to `src-cli` are documented in this file. ### Added - `src validate install` can check executor connections [#974](https://github.com/sourcegraph/src-cli/pull/974) - `src validate install` can send test SMTP message [#973](https://github.com/sourcegraph/src-cli/pull/973) +- `src repos {add|update|delete}-metadata -repo-name` flag support [#977](https://github.com/sourcegraph/src-cli/pull/977) ### Changed - Renamed `src repo {add|update|delete}-kvp` to `repo {add|update|delete}-metadata` [#972](https://github.com/sourcegraph/src-cli/pull/972) diff --git a/cmd/src/repos.go b/cmd/src/repos.go index 5e935b8f4b..920327ebe0 100644 --- a/cmd/src/repos.go +++ b/cmd/src/repos.go @@ -6,6 +6,8 @@ import ( "fmt" "time" + "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/src-cli/internal/api" ) @@ -125,3 +127,13 @@ func fetchRepositoryID(ctx context.Context, client api.Client, repoName string) } return result.Repository.ID, nil } + +func getRepoIdOrError(ctx context.Context, client api.Client, id *string, repoName *string) (*string, error) { + if *id != "" { + return id, nil + } else if *repoName != "" { + repoID, err := fetchRepositoryID(ctx, client, *repoName) + return &repoID, err + } + return nil, errors.New("error: repo or repoName is required") +} diff --git a/cmd/src/repos_add_metadata.go b/cmd/src/repos_add_metadata.go index da01650a73..66356880cf 100644 --- a/cmd/src/repos_add_metadata.go +++ b/cmd/src/repos_add_metadata.go @@ -6,6 +6,7 @@ import ( "fmt" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/src-cli/internal/api" ) @@ -29,19 +30,17 @@ Examples: fmt.Println(usage) } var ( - repoFlag = flagSet.String("repo", "", `The ID of the repo to add the key-value pair metadata to (required)`) - keyFlag = flagSet.String("key", "", `The name of the metadata key to add (required)`) - valueFlag = flagSet.String("value", "", `The metadata value associated with the metadata key. Defaults to null.`) - apiFlags = api.NewFlags(flagSet) + repoFlag = flagSet.String("repo", "", `The ID of the repo to add the key-value pair metadata to (required if -repo-name is not specified)`) + repoNameFlag = flagSet.String("repo-name", "", `The name of the repo to add the key-value pair metadata to (required if -repo is not specified)`) + keyFlag = flagSet.String("key", "", `The name of the metadata key to add (required)`) + valueFlag = flagSet.String("value", "", `The metadata value associated with the metadata key. Defaults to null.`) + apiFlags = api.NewFlags(flagSet) ) handler := func(args []string) error { if err := flagSet.Parse(args); err != nil { return err } - if *repoFlag == "" { - return errors.New("error: repo is required") - } keyFlag = nil valueFlag = nil @@ -61,6 +60,11 @@ Examples: } client := cfg.apiClient(apiFlags, flagSet.Output()) + ctx := context.Background() + repoID, err := getRepoIdOrError(ctx, client, repoFlag, repoNameFlag) + if err != nil { + return err + } query := `mutation addRepoMetadata( $repo: ID!, @@ -77,10 +81,10 @@ Examples: }` if ok, err := client.NewRequest(query, map[string]interface{}{ - "repo": *repoFlag, + "repo": *repoID, "key": *keyFlag, "value": valueFlag, - }).Do(context.Background(), nil); err != nil || !ok { + }).Do(ctx, nil); err != nil || !ok { return err } diff --git a/cmd/src/repos_delete_metadata.go b/cmd/src/repos_delete_metadata.go index 178b7ac0c8..612120cff4 100644 --- a/cmd/src/repos_delete_metadata.go +++ b/cmd/src/repos_delete_metadata.go @@ -28,18 +28,16 @@ Examples: fmt.Println(usage) } var ( - repoFlag = flagSet.String("repo", "", `The ID of the repo with the key-value pair metadata to be deleted (required)`) - keyFlag = flagSet.String("key", "", `The name of the metadata key to be deleted (required)`) - apiFlags = api.NewFlags(flagSet) + repoFlag = flagSet.String("repo", "", `The ID of the repo with the key-value pair metadata to be deleted (required if -repo-name is not specified)`) + repoNameFlag = flagSet.String("repo-name", "", `The name of the repo to add the key-value pair metadata to (required if -repo is not specified)`) + keyFlag = flagSet.String("key", "", `The name of the metadata key to be deleted (required)`) + apiFlags = api.NewFlags(flagSet) ) handler := func(args []string) error { if err := flagSet.Parse(args); err != nil { return err } - if *repoFlag == "" { - return errors.New("error: repo is required") - } keyFlag = nil flagSet.Visit(func(f *flag.Flag) { @@ -53,6 +51,11 @@ Examples: } client := cfg.apiClient(apiFlags, flagSet.Output()) + ctx := context.Background() + repoID, err := getRepoIdOrError(ctx, client, repoFlag, repoNameFlag) + if err != nil { + return err + } query := `mutation deleteRepoMetadata( $repo: ID!, @@ -67,9 +70,9 @@ Examples: }` if ok, err := client.NewRequest(query, map[string]interface{}{ - "repo": *repoFlag, + "repo": *repoID, "key": *keyFlag, - }).Do(context.Background(), nil); err != nil || !ok { + }).Do(ctx, nil); err != nil || !ok { return err } diff --git a/cmd/src/repos_update_metadata.go b/cmd/src/repos_update_metadata.go index f79922dc70..75889f9590 100644 --- a/cmd/src/repos_update_metadata.go +++ b/cmd/src/repos_update_metadata.go @@ -6,6 +6,7 @@ import ( "fmt" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/src-cli/internal/api" ) @@ -29,19 +30,17 @@ Examples: fmt.Println(usage) } var ( - repoFlag = flagSet.String("repo", "", `The ID of the repo with the metadata key to be updated (required)`) - keyFlag = flagSet.String("key", "", `The name of the metadata key to be updated (required)`) - valueFlag = flagSet.String("value", "", `The new metadata value of the metadata key to be set. Defaults to null.`) - apiFlags = api.NewFlags(flagSet) + repoFlag = flagSet.String("repo", "", `The ID of the repo with the metadata key to be updated (required if -repo-name is not specified)`) + repoNameFlag = flagSet.String("repo-name", "", `The name of the repo to add the key-value pair metadata to (required if -repo is not specified)`) + keyFlag = flagSet.String("key", "", `The name of the metadata key to be updated (required)`) + valueFlag = flagSet.String("value", "", `The new metadata value of the metadata key to be set. Defaults to null.`) + apiFlags = api.NewFlags(flagSet) ) handler := func(args []string) error { if err := flagSet.Parse(args); err != nil { return err } - if *repoFlag == "" { - return errors.New("error: repo is required") - } keyFlag = nil valueFlag = nil @@ -61,6 +60,11 @@ Examples: } client := cfg.apiClient(apiFlags, flagSet.Output()) + ctx := context.Background() + repoID, err := getRepoIdOrError(ctx, client, repoFlag, repoNameFlag) + if err != nil { + return err + } query := `mutation updateMetadata( $repo: ID!, @@ -77,10 +81,10 @@ Examples: }` if ok, err := client.NewRequest(query, map[string]interface{}{ - "repo": *repoFlag, + "repo": *repoID, "key": *keyFlag, "value": valueFlag, - }).Do(context.Background(), nil); err != nil || !ok { + }).Do(ctx, nil); err != nil || !ok { return err } From b367736ad54ada252144c97430afdb659d88bb47 Mon Sep 17 00:00:00 2001 From: Jason Hawk Harris Date: Tue, 16 May 2023 08:24:19 -0500 Subject: [PATCH 332/647] Adds the `src scout` utility to the CLI (#978) * Adds 'scout' command and 'resources' sub command. - Prints all current resource allocations for each service (CPU, Memory, Storage) to the terminal * This commit changes output pattern from unformatted lines to a table * adds unit test for ResroucesK8s * formatting/retabbing * Adds --docker flag to print resources of docker deployment - Previously, you could only run `scout` on a k8s deployment - Now, by specifying the `--docker` flag, you can run against a docker deployment - Added unit tests for ResourcesK8s and ResourcesDocker * edits docs to reflect which sub commands are currently available to use * refactor * fix build issues * replace hard coded file path with path generated by homedir package * Update cmd/src/scout_resources.go Co-authored-by: Jacob Pleiness * Update cmd/src/scout_resources.go Co-authored-by: Jacob Pleiness * Update internal/scout/resources/resources.go Co-authored-by: Jacob Pleiness * Update internal/scout/resources/resources.go Co-authored-by: Jacob Pleiness * Update internal/scout/resources/resources.go Co-authored-by: Jacob Pleiness * don't capitalize error messages Co-authored-by: Jacob Pleiness * remove capitalization on error message Co-authored-by: Jacob Pleiness * capitalization Co-authored-by: Jacob Pleiness * add defer functions for closing tabwriter * capitalization Co-authored-by: Jacob Pleiness * change function invocations to reflect new function names and retab * reformats output for --docker flag * retab * Requested changes - change package from resources to resource - renamed files accordingly - changed from if statement to switch statement. - deleted empty README.md * test skeleton * test for getMemUnits added * replace 'spy' with 'advise' in command instructions * Add bubbles/bubble tea components to CLI for better UI/UX * remove unnecessary tests. Formatting * formatting and removes placeholder code/comments * remove redundant return statement * fix import order (linter caught) * remove unnecessary integration test * import order --------- Co-authored-by: Jacob Pleiness --- cmd/src/scout.go | 44 +++++ cmd/src/scout_resource.go | 96 ++++++++++ go.mod | 27 ++- go.sum | 71 ++++++- internal/scout/resource/resource.go | 224 +++++++++++++++++++++++ internal/scout/resource/resource_test.go | 68 +++++++ internal/scout/resource/style/Table.go | 130 +++++++++++++ 7 files changed, 655 insertions(+), 5 deletions(-) create mode 100644 cmd/src/scout.go create mode 100644 cmd/src/scout_resource.go create mode 100644 internal/scout/resource/resource.go create mode 100644 internal/scout/resource/resource_test.go create mode 100644 internal/scout/resource/style/Table.go diff --git a/cmd/src/scout.go b/cmd/src/scout.go new file mode 100644 index 0000000000..753012cac8 --- /dev/null +++ b/cmd/src/scout.go @@ -0,0 +1,44 @@ +package main + +import ( + "flag" + "fmt" +) + +var scoutCommands commander + +func init() { + usage := `'src scout' is a tool that provides monitoring for Sourcegraph resource allocations + + EXPERIMENTAL: 'scout' is an experimental command in the 'src' tool. To use, you must + point your .kube config to your Sourcegraph instance. + + Usage: + + src scout command [command options] + + The commands are: + + resource print all known sourcegraph resources and their allocations + estimate (coming soon) recommend resource allocation for one or many services + usage (coming soon) get CPU, memory and current disk usage + advise (coming soon) recommend lowering or raising resource allocations based on actual usage + + Use "src scout [command] -h" for more information about a command. + ` + + flagSet := flag.NewFlagSet("scout", flag.ExitOnError) + handler := func(args []string) error { + scoutCommands.run(flagSet, "src scout", usage, args) + return nil + } + + commands = append(commands, &command{ + flagSet: flagSet, + aliases: []string{"scout"}, + handler: handler, + usageFunc: func() { + fmt.Println(usage) + }, + }) +} diff --git a/cmd/src/scout_resource.go b/cmd/src/scout_resource.go new file mode 100644 index 0000000000..32accda5f6 --- /dev/null +++ b/cmd/src/scout_resource.go @@ -0,0 +1,96 @@ +package main + +import ( + "context" + "flag" + "fmt" + "path/filepath" + + "github.com/docker/docker/client" + "github.com/sourcegraph/sourcegraph/lib/errors" + "k8s.io/client-go/kubernetes" + "k8s.io/client-go/tools/clientcmd" + "k8s.io/client-go/util/homedir" + + "github.com/sourcegraph/src-cli/internal/scout/resource" +) + +func init() { + usage := `'src scout resource' is a tool that provides an overview of resource usage + across an instance of Sourcegraph. Part of the EXPERIMENTAL "src scout" tool. + + Examples + List pods and resource allocations in a Kubernetes deployment: + $ src scout resource + + List containers and resource allocations in a Docker deployment: + $ src scout resource --docker + + Add namespace if using namespace in a Kubernetes cluster + $ src scout resource --namespace sg + ` + + flagSet := flag.NewFlagSet("resource", flag.ExitOnError) + usageFunc := func() { + fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src scout %s':\n", flagSet.Name()) + flagSet.PrintDefaults() + fmt.Println(usage) + } + + var ( + kubeConfig *string + namespace = flagSet.String("namespace", "", "(optional) specify the kubernetes namespace to use") + docker = flagSet.Bool("docker", false, "(optional) using docker deployment") + // TODO: option for getting resource allocation of the Node + // nodes = flagSet.Bool("node", false, "(optional) view resources for node(s)") + ) + + if home := homedir.HomeDir(); home != "" { + kubeConfig = flagSet.String( + "kubeconfig", + filepath.Join(home, ".kube", "config"), + "(optional) absolute path to the kubeconfig file", + ) + } else { + kubeConfig = flagSet.String("kubeconfig", "", "absolute path to the kubeconfig file") + } + + handler := func(args []string) error { + if err := flagSet.Parse(args); err != nil { + return err + } + + config, err := clientcmd.BuildConfigFromFlags("", *kubeConfig) + if err != nil { + return errors.New(fmt.Sprintf("%v: failed to load kubernetes config", err)) + } + + clientSet, err := kubernetes.NewForConfig(config) + if err != nil { + return errors.New(fmt.Sprintf("%v: failed to load kubernetes config", err)) + } + + var options []resource.Option + + if *namespace != "" { + options = append(options, resource.WithNamespace(*namespace)) + } + + if *docker { + dockerClient, err := client.NewClientWithOpts(client.FromEnv) + if err != nil { + return errors.Wrap(err, "error creating docker client: ") + } + + return resource.Docker(context.Background(), *dockerClient) + } + + return resource.K8s(context.Background(), clientSet, config, options...) + } + + scoutCommands = append(scoutCommands, &command{ + flagSet: flagSet, + handler: handler, + usageFunc: usageFunc, + }) +} diff --git a/go.mod b/go.mod index 263376a6a4..c232d6109d 100644 --- a/go.mod +++ b/go.mod @@ -8,9 +8,12 @@ require ( github.com/aws/aws-sdk-go-v2/service/ec2 v1.86.0 github.com/aws/aws-sdk-go-v2/service/eks v1.27.3 github.com/aws/aws-sdk-go-v2/service/iam v1.19.3 + github.com/charmbracelet/bubbles v0.15.0 + github.com/charmbracelet/lipgloss v0.7.1 github.com/creack/goselect v0.1.2 github.com/derision-test/glock v0.0.0-20210316032053-f5b74334bb29 github.com/dineshappavoo/basex v0.0.0-20170425072625-481a6f6dc663 + github.com/docker/docker v23.0.5+incompatible github.com/dustin/go-humanize v1.0.1 github.com/gobwas/glob v0.2.3 github.com/google/go-cmp v0.5.9 @@ -20,7 +23,7 @@ require ( github.com/jig/teereadcloser v0.0.0-20181016160506-953720c48e05 github.com/json-iterator/go v1.1.12 github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 - github.com/mattn/go-isatty v0.0.16 + github.com/mattn/go-isatty v0.0.17 github.com/neelance/parallel v0.0.0-20160708114440-4de9ce63d14c github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 github.com/sourcegraph/conc v0.3.0 @@ -29,6 +32,7 @@ require ( github.com/sourcegraph/scip v0.2.4-0.20221213205653-aa0e511dcfef github.com/sourcegraph/sourcegraph/lib v0.0.0-20230316093010-26299ec302d0 github.com/stretchr/testify v1.8.1 + golang.design/x/clipboard v0.7.0 golang.org/x/net v0.8.0 golang.org/x/sync v0.1.0 google.golang.org/api v0.110.0 @@ -40,6 +44,12 @@ require ( k8s.io/client-go v0.26.1 ) +require ( + golang.org/x/exp v0.0.0-20190731235908-ec7cb31e5a56 // indirect + golang.org/x/image v0.6.0 // indirect + golang.org/x/mobile v0.0.0-20230301163155-e0f57694e12c // indirect +) + require ( cloud.google.com/go v0.107.0 // indirect cloud.google.com/go/compute v1.18.0 // indirect @@ -49,6 +59,7 @@ require ( github.com/Masterminds/goutils v1.1.1 // indirect github.com/Masterminds/semver v1.5.0 // indirect github.com/Masterminds/sprig v2.22.0+incompatible // indirect + github.com/Microsoft/go-winio v0.6.1 // indirect github.com/alecthomas/chroma v0.10.0 // indirect github.com/aws/aws-sdk-go-v2 v1.17.5 // indirect github.com/aws/aws-sdk-go-v2/credentials v1.13.13 // indirect @@ -61,15 +72,21 @@ require ( github.com/aws/aws-sdk-go-v2/service/ssooidc v1.14.2 // indirect github.com/aws/aws-sdk-go-v2/service/sts v1.18.3 // indirect github.com/aws/smithy-go v1.13.5 // indirect + github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect github.com/aymerick/douceur v0.2.0 // indirect github.com/bufbuild/buf v1.4.0 // indirect + github.com/charmbracelet/bubbletea v0.23.1 // direct github.com/charmbracelet/glamour v0.5.0 // indirect github.com/cockroachdb/errors v1.9.0 // indirect github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f // indirect github.com/cockroachdb/redact v1.1.3 // indirect + github.com/containerd/console v1.0.3 // indirect github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/dlclark/regexp2 v1.7.0 // indirect + github.com/docker/distribution v2.8.1+incompatible // indirect + github.com/docker/go-connections v0.4.0 // indirect + github.com/docker/go-units v0.5.0 // indirect github.com/emicklei/go-restful/v3 v3.9.0 // indirect github.com/envoyproxy/protoc-gen-validate v0.9.1 // indirect github.com/fatih/color v1.13.0 // indirect @@ -107,6 +124,7 @@ require ( github.com/lucasb-eyer/go-colorful v1.2.0 // indirect github.com/mailru/easyjson v0.7.7 // indirect github.com/mattn/go-colorable v0.1.13 // indirect + github.com/mattn/go-localereader v0.0.1 // indirect github.com/mattn/go-runewidth v0.0.14 // indirect github.com/microcosm-cc/bluemonday v1.0.22 // indirect github.com/mitchellh/copystructure v1.2.0 // indirect @@ -115,12 +133,17 @@ require ( github.com/moby/term v0.0.0-20220808134915-39b0c02b01ae // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/morikuni/aec v1.0.0 // indirect + github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b // indirect + github.com/muesli/cancelreader v0.2.2 // indirect github.com/muesli/reflow v0.3.0 // indirect - github.com/muesli/termenv v0.12.0 // indirect + github.com/muesli/termenv v0.15.1 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/mwitkow/go-proto-validators v0.3.2 // indirect github.com/nightlyone/lockfile v1.0.0 // indirect github.com/olekukonko/tablewriter v0.0.5 // indirect + github.com/opencontainers/go-digest v1.0.0 // indirect + github.com/opencontainers/image-spec v1.0.2 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/pkg/profile v1.6.0 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect diff --git a/go.sum b/go.sum index 37e963bd89..4c9e9d0f55 100644 --- a/go.sum +++ b/go.sum @@ -14,6 +14,7 @@ github.com/AndreasBriese/bbloom v0.0.0-20190306092124-e2d15f34fcf9/go.mod h1:bOv github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 h1:UQHMgLO+TxOElx5B5HZ4hJQsoJ/PvUvKRhJHDQXO8P8= github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/CloudyKit/fastprinter v0.0.0-20170127035650-74b38d55f37a/go.mod h1:EFZQ978U7x8IRnstaskI3IysnWY5Ao3QgZUKOXlsAdw= github.com/CloudyKit/fastprinter v0.0.0-20200109182630-33d98a066a53/go.mod h1:+3IMCy2vIlbG1XG/0ggNQv0SvxCAIpPM5b1nCz56Xno= github.com/CloudyKit/jet v2.1.3-0.20180809161101-62edd43e4f88+incompatible/go.mod h1:HPYO+50pSWkPoj9Q/eq0aRGByCL6ScRlUmiEX5Zgm+w= @@ -26,12 +27,15 @@ github.com/Masterminds/semver v1.5.0 h1:H65muMkzWKEuNDnfl9d70GUjFniHKHRbFPGBuZ3Q github.com/Masterminds/semver v1.5.0/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y= github.com/Masterminds/sprig v2.22.0+incompatible h1:z4yfnGrZ7netVz+0EDJ0Wi+5VZCSYp4Z0m2dk6cEM60= github.com/Masterminds/sprig v2.22.0+incompatible/go.mod h1:y6hNFY5UBTIWBxnzTeuNhlNS5hqE0NB0E6fgfo2Br3o= +github.com/Microsoft/go-winio v0.6.1 h1:9/kr64B9VUZrLm5YYwbGtUJnMgqWVOdUAXu6Migciow= +github.com/Microsoft/go-winio v0.6.1/go.mod h1:LRdKpFKfdobln8UmuiYcKPot9D2v6svN5+sAH+4kjUM= github.com/Shopify/goreferrer v0.0.0-20181106222321-ec9c9a553398/go.mod h1:a1uqRtAwp2Xwc6WNPJEufxJ7fx3npB4UV/JOLmbu5I0= github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY= github.com/alecthomas/chroma v0.10.0 h1:7XDcGkCQopCNKjZHfYrNLraA+M7e0fMiJ/Mfikbfjek= github.com/alecthomas/chroma v0.10.0/go.mod h1:jtJATyUxlIORhUOFNA9NZDWGAQ8wpxQQqNSB4rjA/1s= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio= +github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI= github.com/aws/aws-sdk-go-v2 v1.17.4/go.mod h1:uzbQtefpm44goOPmdKyAlXSNcwlRgF3ePWVW6EtJvvw= github.com/aws/aws-sdk-go-v2 v1.17.5 h1:TzCUW1Nq4H8Xscph5M/skINUitxM5UBAyvm2s7XBzL4= github.com/aws/aws-sdk-go-v2 v1.17.5/go.mod h1:uzbQtefpm44goOPmdKyAlXSNcwlRgF3ePWVW6EtJvvw= @@ -65,6 +69,9 @@ github.com/aws/aws-sdk-go-v2/service/sts v1.18.3 h1:s49mSnsBZEXjfGBkRfmK+nPqzT7L github.com/aws/aws-sdk-go-v2/service/sts v1.18.3/go.mod h1:b+psTJn33Q4qGoDaM7ZiOVVG8uVjGI6HaZ8WBHdgDgU= github.com/aws/smithy-go v1.13.5 h1:hgz0X/DX0dGqTYpGALqXJoRKRj5oQ7150i5FdTePzO8= github.com/aws/smithy-go v1.13.5/go.mod h1:Tg+OJXh4MB2R/uN61Ko2f6hTZwB/ZYGOtib8J3gBHzA= +github.com/aymanbagabas/go-osc52 v1.0.3/go.mod h1:zT8H+Rk4VSabYN90pWyugflM3ZhpTZNC7cASDfUCdT4= +github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k= +github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8= github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk= github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4= github.com/aymerick/raymond v2.0.3-0.20180322193309-b565731e1464+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g= @@ -72,8 +79,16 @@ github.com/benbjohnson/clock v1.3.0 h1:ip6w0uFQkncKQ979AypyG0ER7mqUSBdKLOgAle/AT github.com/bufbuild/buf v1.4.0 h1:GqE3a8CMmcFvWPzuY3Mahf9Kf3S9XgZ/ORpfYFzO+90= github.com/bufbuild/buf v1.4.0/go.mod h1:mwHG7klTHnX+rM/ym8LXGl7vYpVmnwT96xWoRB4H5QI= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/charmbracelet/bubbles v0.15.0 h1:c5vZ3woHV5W2b8YZI1q7v4ZNQaPetfHuoHzx+56Z6TI= +github.com/charmbracelet/bubbles v0.15.0/go.mod h1:Y7gSFbBzlMpUDR/XM9MhZI374Q+1p1kluf1uLl8iK74= +github.com/charmbracelet/bubbletea v0.23.1 h1:CYdteX1wCiCzKNUlwm25ZHBIc1GXlYFyUIte8WPvhck= +github.com/charmbracelet/bubbletea v0.23.1/go.mod h1:JAfGK/3/pPKHTnAS8JIE2u9f61BjWTQY57RbT25aMXU= github.com/charmbracelet/glamour v0.5.0 h1:wu15ykPdB7X6chxugG/NNfDUbyyrCLV9XBalj5wdu3g= github.com/charmbracelet/glamour v0.5.0/go.mod h1:9ZRtG19AUIzcTm7FGLGbq3D5WKQ5UyZBbQsMQN0XIqc= +github.com/charmbracelet/harmonica v0.2.0/go.mod h1:KSri/1RMQOZLbw7AHqgcBycp8pgJnQMYYT8QZRqZ1Ao= +github.com/charmbracelet/lipgloss v0.6.0/go.mod h1:tHh2wr34xcHjC2HCXIlGSG1jaDF0S0atAUvBMP6Ppuk= +github.com/charmbracelet/lipgloss v0.7.1 h1:17WMwi7N1b1rVWOjMT+rCh7sQkvDU75B2hbZpc5Kc1E= +github.com/charmbracelet/lipgloss v0.7.1/go.mod h1:yG0k3giv8Qj8edTCbbg6AlQ5e8KNWpFujkNawKNhE2c= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= @@ -90,6 +105,8 @@ github.com/cockroachdb/redact v1.1.3 h1:AKZds10rFSIj7qADf0g46UixK8NNLwWTNdCIGS5w github.com/cockroachdb/redact v1.1.3/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= github.com/cockroachdb/sentry-go v0.6.1-cockroachdb.2/go.mod h1:8BT+cPK6xvFOcRlk0R8eg+OTkcqI6baNH4xAkpiYVvQ= github.com/codegangsta/inject v0.0.0-20150114235600-33e0aa1cb7c0/go.mod h1:4Zcjuz89kmFXt9morQgcfYZAYZ5n8WHjt81YYWIwtTM= +github.com/containerd/console v1.0.3 h1:lIr7SlA5PxZyMV30bDW0MGbiOPXwc63yRuCP0ARubLw= +github.com/containerd/console v1.0.3/go.mod h1:7LqA/THxQ86k76b8c/EMSiaJ3h1eZkMkXar0TQ1gf3U= github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= @@ -114,6 +131,14 @@ github.com/dineshappavoo/basex v0.0.0-20170425072625-481a6f6dc663/go.mod h1:Kad2 github.com/dlclark/regexp2 v1.4.0/go.mod h1:2pZnwuY/m+8K6iRw6wQdMtk+rH5tNGR1i55kozfMjCc= github.com/dlclark/regexp2 v1.7.0 h1:7lJfhqlPssTb1WQx4yvTHN0uElPEv52sbaECrAQxjAo= github.com/dlclark/regexp2 v1.7.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= +github.com/docker/distribution v2.8.1+incompatible h1:Q50tZOPR6T/hjNsyc9g8/syEs6bk8XXApsHjKukMl68= +github.com/docker/distribution v2.8.1+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= +github.com/docker/docker v23.0.5+incompatible h1:DaxtlTJjFSnLOXVNUBU1+6kXGz2lpDoEAH6QoxaSg8k= +github.com/docker/docker v23.0.5+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= +github.com/docker/go-connections v0.4.0 h1:El9xVISelRB7BuFusrZozjnkIM5YnzCViNKohAFqRJQ= +github.com/docker/go-connections v0.4.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5XhDvyHbTtUxmeec= +github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4= +github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= github.com/docopt/docopt-go v0.0.0-20180111231733-ee0de3bc6815/go.mod h1:WwZ+bS3ebgob9U8Nd0kOddGdZWjyMGR8Wziv+TBNwSE= github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= @@ -322,6 +347,7 @@ github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= github.com/labstack/echo/v4 v4.1.11/go.mod h1:i541M3Fj6f76NZtHSj7TXnyM8n2gaodfvfxNnFqi74g= github.com/labstack/echo/v4 v4.5.0/go.mod h1:czIriw4a0C1dFun+ObrXp7ok03xON0N1awStJ6ArI7Y= github.com/labstack/gommon v0.3.0/go.mod h1:MULnywXg0yavhxWKc+lOruYdAhDwPK9wf0OL7NoOu+k= @@ -345,9 +371,13 @@ github.com/mattn/go-isatty v0.0.9/go.mod h1:YNRxwqDuOph6SZLI9vUUz6OYw3QyUt7WiY2y github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/mattn/go-isatty v0.0.13/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= -github.com/mattn/go-isatty v0.0.16 h1:bq3VjFmv/sOjHtdEhmkEV4x1AJtvUvOJ2PFAZ5+peKQ= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng= +github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4= +github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88= github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= +github.com/mattn/go-runewidth v0.0.10/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk= github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk= github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU= @@ -377,12 +407,21 @@ github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lN github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A= +github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc= github.com/moul/http2curl v1.0.0/go.mod h1:8UbvGypXm98wA/IqH45anm5Y2Z6ep6O31QGOAZ3H0fQ= +github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b h1:1XF24mVaiu7u+CFywTdcDo2ie1pzzhwjt6RHqzpMU34= +github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b/go.mod h1:fQuZ0gauxyBcmsdE3ZT4NasjaRdxmbCS0jRHsrWu3Ho= +github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA= +github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo= +github.com/muesli/reflow v0.2.1-0.20210115123740-9e1d0d53df68/go.mod h1:Xk+z4oIWdQqJzsxyjgl3P22oYZnHdZ8FFTHAQQt5BMQ= github.com/muesli/reflow v0.3.0 h1:IFsN6K9NfGtjeggFP+68I4chLZV2yIKsXJFNZ+eWh6s= github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKtnHY/8= github.com/muesli/termenv v0.9.0/go.mod h1:R/LzAKf+suGs4IsO95y7+7DpFHO0KABgnZqtlyx2mBw= -github.com/muesli/termenv v0.12.0 h1:KuQRUE3PgxRFWhq4gHvZtPSLCGDqM5q/cYr1pZ39ytc= -github.com/muesli/termenv v0.12.0/go.mod h1:WCCv32tusQ/EEZ5S8oUIIrC/nIuBcxCVqlN4Xfkv+7A= +github.com/muesli/termenv v0.11.1-0.20220204035834-5ac8409525e0/go.mod h1:Bd5NYQ7pd+SrtBSrSNoBBmXlcY8+Xj4BMJgh8qcZrvs= +github.com/muesli/termenv v0.13.0/go.mod h1:sP1+uffeLaEYpyOTb8pLCUctGcGLnoFjSn4YJK5e2bc= +github.com/muesli/termenv v0.15.1 h1:UzuTb/+hhlBugQz28rpzey4ZuKcZ03MeKsoG7IJZIxs= +github.com/muesli/termenv v0.15.1/go.mod h1:HeAQPTzpfs016yGtA4g00CsdYnVLJvxsS4ANqrZs2sQ= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/mwitkow/go-proto-validators v0.3.2 h1:qRlmpTzm2pstMKKzTdvwPCF5QfBNURSlAgN/R+qbKos= @@ -410,6 +449,10 @@ github.com/onsi/ginkgo/v2 v2.4.0 h1:+Ig9nvqgS5OBSACXNk15PLdp0U9XPYROt9CFzVdFGIs= github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= github.com/onsi/gomega v1.23.0 h1:/oxKu9c2HVap+F3PfKort2Hw5DEU+HGlW8n+tguWsys= +github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= +github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= +github.com/opencontainers/image-spec v1.0.2 h1:9yCKha/T5XdGtO0q9Q9a6T5NUCsTn/DrBg0D7ufOcFM= +github.com/opencontainers/image-spec v1.0.2/go.mod h1:BtxoFyWECRxE4U/7sNtV5W15zMzWCbyJoFRP3s7yZA0= github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4= github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8= @@ -441,6 +484,7 @@ github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/ryanuber/columnize v2.1.0+incompatible/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= +github.com/sahilm/fuzzy v0.1.0/go.mod h1:VFvziUEIMCrT6A6tw2RFIXPXXmzXbOsSHF0DOI8ZK9Y= github.com/schollz/closestmatch v2.1.0+incompatible/go.mod h1:RtP1ddjLong6gTkbtmuhtR2uUrrJOpYzYRvbcPAid+g= github.com/sclevine/agouti v3.0.0+incompatible/go.mod h1:b4WX9W9L1sfQKXeJf1mUTLZKJ48R1S7H23Ji7oFO5Bw= github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= @@ -533,8 +577,11 @@ go.uber.org/multierr v1.9.0 h1:7fIwc/ZtS0q++VgcfqFDxSBZVv/Xo49/SYnDFupUwlI= go.uber.org/multierr v1.9.0/go.mod h1:X2jQV1h+kxSjClGpnseKVIxpmcjrj7MNnI0bnlfKTVQ= go.uber.org/zap v1.24.0 h1:FiJd5l1UOLj0wCgbSE0rwwXHzEdAZS6hiiSnxJN/D60= go.uber.org/zap v1.24.0/go.mod h1:2kMP+WWQ8aoFoedH3T2sq6iJ2yDWpHbP0f6MQbS9Gkg= +golang.design/x/clipboard v0.7.0 h1:4Je8M/ys9AJumVnl8m+rZnIvstSnYj1fvzqYrU3TXvo= +golang.design/x/clipboard v0.7.0/go.mod h1:PQIvqYO9GP29yINEfsEn5zSQKAz3UgXmZKzDA6dnq2E= golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191227163750-53104e6ec876/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= @@ -544,10 +591,19 @@ golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5y golang.org/x/crypto v0.3.0 h1:a06MkbcxBrEFc0w0QIZWXrH/9cCX6KJyWbBOIwAn+7A= golang.org/x/crypto v0.3.0/go.mod h1:hebNnKkNXi2UzZN1eVRvBB7co0a+JxK6XbPiWVs/3J4= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190731235908-ec7cb31e5a56 h1:estk1glOnSVeJ9tdEZZc5mAMDZk5lNJNyJ6DvrBkTEU= +golang.org/x/exp v0.0.0-20190731235908-ec7cb31e5a56/go.mod h1:JhuoJpWY28nO4Vef9tZUw9qufEGTyX1+7lmHxV5q5G4= +golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= +golang.org/x/image v0.6.0 h1:bR8b5okrPI3g/gyZakLZHeWxAR8Dn5CyxXv1hLH5g/4= +golang.org/x/image v0.6.0/go.mod h1:MXLdDR43H7cDJq5GEGXEVeeNhPgi+YYEQ2pC1byI1x0= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/lint v0.0.0-20210508222113-6edffad5e616/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= +golang.org/x/mobile v0.0.0-20230301163155-e0f57694e12c h1:Gk61ECugwEHL6IiyyNLXNzmu8XslmRP2dS0xjIYhbb4= +golang.org/x/mobile v0.0.0-20230301163155-e0f57694e12c/go.mod h1:aAjjkJNdrh3PMckS4B10TGS2nag27cbKR1y2BpUxsiY= +golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY= golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= @@ -556,6 +612,7 @@ golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.7.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.9.0 h1:KENHtAZL2y3NLMYZeHY9DW8HW8V+kQyJsY/V9JlKvCs= golang.org/x/mod v0.9.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -582,6 +639,7 @@ golang.org/x/net v0.0.0-20210614182718-04defd469f4e/go.mod h1:9nx3DQGgdP8bBQD5qx golang.org/x/net v0.0.0-20211008194852-3b03d305991f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.3.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE= +golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.8.0 h1:Zrh2ngAOFYneWTAIAPethzeaQLuHwhuBkuV6ZiRnUaQ= golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= @@ -616,6 +674,7 @@ golang.org/x/sys v0.0.0-20200519105757-fe76b779f299/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210218084038-e8e29180ff58/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210403161142-5e06dd20ab57/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -627,17 +686,20 @@ golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211007075335-d3039528d8ac/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220204135822-1c1b9b1eba6a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220829200755-d48e67d00261/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.3.0/go.mod h1:q750SLmJuPmVoN1blW3UFBPREJfb1KmY3vwxfr+nFDA= +golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= golang.org/x/term v0.6.0 h1:clScbb1cHjoCkyRbWwBEUZ5H/tIFu5TAXIqaZD0Gcjw= golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -647,6 +709,7 @@ golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.8.0 h1:57P1ETyNKtuIjB4SRd15iJxuhj8Gc416Y78H3qgMh68= golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/time v0.0.0-20201208040808-7e3f01d25324/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= @@ -658,6 +721,7 @@ golang.org/x/tools v0.0.0-20181221001348-537d06c36207/go.mod h1:n7NCudcB/nEzxVGm golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190327201419-c70d86f8b7cf/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= @@ -672,6 +736,7 @@ golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.4.0/go.mod h1:UE5sM2OK9E/d67R0ANs2xJizIymRP5gJU295PvKXxjQ= +golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/tools v0.7.0 h1:W4OVu8VVOaIO0yzWMNdepAulS7YfoS3Zabrm8DOXXU4= golang.org/x/tools v0.7.0/go.mod h1:4pg6aUX35JBAogB10C9AtvVL+qowtN4pT3CGSQex14s= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/internal/scout/resource/resource.go b/internal/scout/resource/resource.go new file mode 100644 index 0000000000..4a63ef9374 --- /dev/null +++ b/internal/scout/resource/resource.go @@ -0,0 +1,224 @@ +package resource + +import ( + "context" + "fmt" + "os" + + "github.com/charmbracelet/bubbles/table" + "github.com/charmbracelet/lipgloss" + "github.com/docker/docker/api/types" + "github.com/docker/docker/client" + "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/src-cli/internal/scout/resource/style" + v1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/client-go/kubernetes" + "k8s.io/client-go/rest" +) + +type Option = func(config *Config) + +type Config struct { + namespace string + docker bool + k8sClient *kubernetes.Clientset + dockerClient *client.Client +} + +func WithNamespace(namespace string) Option { + return func(config *Config) { + config.namespace = namespace + } +} + +// K8s prints the CPU and memory resource limits and requests for all pods in the given namespace. +func K8s(ctx context.Context, clientSet *kubernetes.Clientset, restConfig *rest.Config, opts ...Option) error { + cfg := &Config{ + namespace: "default", + docker: false, + k8sClient: clientSet, + dockerClient: nil, + } + + for _, opt := range opts { + opt(cfg) + } + + return listPodResources(ctx, cfg) +} + +func listPodResources(ctx context.Context, cfg *Config) error { + podInterface := cfg.k8sClient.CoreV1().Pods(cfg.namespace) + podList, err := podInterface.List(ctx, metav1.ListOptions{}) + if err != nil { + return errors.Wrap(err, "error listing pods: ") + } + + columns := []table.Column{ + {Title: "CONTAINER", Width: 20}, + {Title: "CPU LIMITS", Width: 10}, + {Title: "CPU REQUESTS", Width: 12}, + {Title: "MEM LIMITS", Width: 10}, + {Title: "MEM REQUESTS", Width: 12}, + {Title: "CAPACITY", Width: 8}, + } + + if len(podList.Items) == 0 { + msg := lipgloss.NewStyle().Foreground(lipgloss.Color("#FFA500")) + fmt.Println(msg.Render(` + No pods exist in this namespace. + Did you mean to use the --namespace flag? + + If you are attemptying to check + resources for a docker deployment, you + must use the --docker flag. + See --help for more info. + `)) + os.Exit(1) + } + + var rows []table.Row + for _, pod := range podList.Items { + if pod.GetNamespace() == cfg.namespace { + for _, container := range pod.Spec.Containers { + cpuLimits := container.Resources.Limits.Cpu() + cpuRequests := container.Resources.Requests.Cpu() + memLimits := container.Resources.Limits.Memory() + memRequests := container.Resources.Requests.Memory() + + capacity, err := getPVCCapacity(ctx, cfg, container, pod) + if err != nil { + return err + } + + if capacity == "" { + capacity = "N/A" + } + + row := table.Row{ + container.Name, + cpuLimits.String(), + cpuRequests.String(), + memLimits.String(), + memRequests.String(), + capacity, + } + rows = append(rows, row) + } + } + } + + style.ResourceTable(columns, rows) + return nil +} + +func getPVCCapacity(ctx context.Context, cfg *Config, container v1.Container, pod v1.Pod) (string, error) { + for _, volumeMount := range container.VolumeMounts { + for _, volume := range pod.Spec.Volumes { + if volume.Name == volumeMount.Name && volume.PersistentVolumeClaim != nil { + pvc, err := cfg.k8sClient.CoreV1().PersistentVolumeClaims(cfg.namespace).Get( + ctx, + volume.PersistentVolumeClaim.ClaimName, + metav1.GetOptions{}, + ) + if err != nil { + return "", errors.Wrapf(err, "error getting PVC %s", volume.PersistentVolumeClaim.ClaimName) + } + return pvc.Status.Capacity.Storage().String(), nil + } + } + } + return "", nil +} + +// Docker prints the CPU and memory resource limits and requests for running Docker containers. +func Docker(ctx context.Context, dockerClient client.Client) error { + containers, err := dockerClient.ContainerList(ctx, types.ContainerListOptions{}) + if err != nil { + return fmt.Errorf("error listing docker containers: %v", err) + } + + if len(containers) == 0 { + msg := lipgloss.NewStyle().Foreground(lipgloss.Color("#FFA500")) + fmt.Println(msg.Render(` + There are no containers, or the Docker Daemon is not running + `)) + os.Exit(1) + } + + columns := []table.Column{ + {Title: "Container", Width: 20}, + {Title: "CPU Cores", Width: 15}, + {Title: "CPU Shares", Width: 15}, + {Title: "Mem Limits", Width: 15}, + {Title: "Mem Reservations", Width: 17}, + } + + var rows []table.Row + + for _, container := range containers { + containerInfo, err := dockerClient.ContainerInspect(ctx, container.ID) + if err != nil { + return fmt.Errorf("error inspecting container %s: %v", container.ID, err) + } + + row, err := getResourceInfo(&containerInfo, rows) + if err != nil { + return errors.Wrap(err, "error while getting resource info from container: ") + } + + rows = append(rows, row) + } + + style.ResourceTable(columns, rows) + return nil +} + +func getResourceInfo(container *types.ContainerJSON, rows []table.Row) (table.Row, error) { + cpuCores := container.HostConfig.NanoCPUs + cpuShares := container.HostConfig.CPUShares + memLimits := container.HostConfig.Memory + memReservations := container.HostConfig.MemoryReservation + + reqUnit, reqVal, err := getMemUnits(memReservations) + if err != nil { + return table.Row{}, errors.Wrap(err, "error while getting request units") + } + + limUnit, limVal, err := getMemUnits(memLimits) + if err != nil { + return table.Row{}, errors.Wrap(err, "error while getting limit units") + } + + row := table.Row{ + container.Name, + fmt.Sprintf("%v", float64(cpuCores/1e9)), + fmt.Sprint(cpuShares), + fmt.Sprintf("%d%s", limVal, limUnit), + fmt.Sprintf("%d%s", reqVal, reqUnit), + } + + return row, nil +} + +// getMemUnits converts a byte value to the appropriate memory unit. +func getMemUnits(valToConvert int64) (string, int64, error) { + if valToConvert < 0 { + return "", valToConvert, fmt.Errorf("invalid memory value: %d", valToConvert) + } + + var memUnit string + switch { + case valToConvert < 1000000: + memUnit = "KB" + case valToConvert < 1000000000: + memUnit = "MB" + valToConvert = valToConvert / 1000000 + default: + memUnit = "GB" + valToConvert = valToConvert / 1000000000 + } + + return memUnit, valToConvert, nil +} diff --git a/internal/scout/resource/resource_test.go b/internal/scout/resource/resource_test.go new file mode 100644 index 0000000000..f0cbd74d36 --- /dev/null +++ b/internal/scout/resource/resource_test.go @@ -0,0 +1,68 @@ +package resource + +import ( + "fmt" + "testing" +) + +func TestGetMemUnits(t *testing.T) { + cases := []struct { + name string + param int64 + wantUnit string + wantValue int64 + wantError error + }{ + { + name: "convert bytes below a million to KB", + param: 999999, + wantUnit: "KB", + wantValue: 999999, + wantError: nil, + }, + { + name: "convert bytes below a billion to MB", + param: 999999999, + wantUnit: "MB", + wantValue: 999, + wantError: nil, + }, + { + name: "convert bytes above a billion to GB", + param: 12999999900, + wantUnit: "GB", + wantValue: 12, + wantError: nil, + }, + { + name: "return error for a negative number", + param: -300, + wantUnit: "", + wantValue: -300, + wantError: fmt.Errorf("invalid memory value: %d", -300), + }, + } + + for _, tc := range cases { + tc := tc + t.Run(tc.name, func(t *testing.T) { + gotUnit, gotValue, gotError := getMemUnits(tc.param) + + if gotUnit != tc.wantUnit { + t.Errorf("got %s want %s", gotUnit, tc.wantUnit) + } + + if gotValue != tc.wantValue { + t.Errorf("got %v want %v", gotValue, tc.wantValue) + } + + if gotError == nil && tc.wantError != nil { + t.Error("got nil want error") + } + + if gotError != nil && tc.wantError == nil { + t.Error("got error want nil") + } + }) + } +} diff --git a/internal/scout/resource/style/Table.go b/internal/scout/resource/style/Table.go new file mode 100644 index 0000000000..a24b02cc4a --- /dev/null +++ b/internal/scout/resource/style/Table.go @@ -0,0 +1,130 @@ +package style + +import ( + "fmt" + "os" + + "github.com/charmbracelet/bubbles/table" + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" + "golang.design/x/clipboard" +) + +var baseStyle = lipgloss.NewStyle(). + BorderStyle(lipgloss.NormalBorder()). + BorderForeground(lipgloss.Color("240")) + +type model struct { + table table.Model +} + +func (m model) Init() tea.Cmd { return nil } + +func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + var cmd tea.Cmd + switch msg := msg.(type) { + case tea.KeyMsg: + switch msg.String() { + case "esc", "q", "ctrl+c": + return m, tea.Quit + case "c": + m.copyRowToClipboard(m.table.SelectedRow()) + copiedMessage := lipgloss.NewStyle(). + Foreground(lipgloss.Color("#32CD32")). + Render(fmt.Sprintf( + "Copied resource allocations for %s to clipboard", + m.table.SelectedRow()[0], + )) + return m, tea.Batch( + tea.Printf( + copiedMessage, + ), + ) + } + } + m.table, cmd = m.table.Update(msg) + return m, cmd +} + +func (m model) View() string { + s := "\n > Press 'j' and 'k' to go up and down\n" + s += " > Press 'c' to copy highlighted row to clipboard\n" + s += " > Press 'q' to quit\n\n" + s += baseStyle.Render(m.table.View()) + "\n" + return s +} + +func (m model) copyRowToClipboard(row table.Row) { + var containerInfo string + + // change output based on the length of row + // docker rows will always be length of 5 + // kubernetes rows will always be length of 6 + if len(row) == 5 { + name := row[0] + cpuCores := row[1] + cpuShares := row[2] + memLimits := row[3] + memReservations := row[4] + containerInfo = fmt.Sprintf(`container: %s + cpu cores: %s + cpu shares: %s + mem limits: %s + mem reservations: %s`, + name, + cpuCores, + cpuShares, + memLimits, + memReservations, + ) + } else if len(row) == 6 { + name := row[0] + cpuLimits := row[1] + cpuRequests := row[2] + memLimits := row[3] + memRequests := row[4] + capacity := row[5] + containerInfo = fmt.Sprintf(`container: %s + cpu limits: %s + cpu requests: %s + mem limits: %s + mem requests: %s + disk capacity: %s`, + name, + cpuLimits, + cpuRequests, + memLimits, + memRequests, + capacity, + ) + } + + clipboard.Write(clipboard.FmtText, []byte(containerInfo)) +} + +func ResourceTable(columns []table.Column, rows []table.Row) { + t := table.New( + table.WithColumns(columns), + table.WithRows(rows), + table.WithFocused(true), + table.WithHeight(14), + ) + + s := table.DefaultStyles() + s.Header = s.Header. + BorderStyle(lipgloss.NormalBorder()). + BorderForeground(lipgloss.Color("240")). + BorderBottom(true). + Bold(false) + s.Selected = s.Selected. + Foreground(lipgloss.Color("229")). + Background(lipgloss.Color("57")). + Bold(false) + t.SetStyles(s) + + m := model{t} + if _, err := tea.NewProgram(m).Run(); err != nil { + fmt.Println("Error running program:", err) + os.Exit(1) + } +} From 165b945843dcd2460a8932aec2de21ff100f8856 Mon Sep 17 00:00:00 2001 From: Jason Hawk Harris Date: Tue, 16 May 2023 14:34:46 -0500 Subject: [PATCH 333/647] add ability to dump all resource data to text file (#981) * Adds 'scout' command and 'resources' sub command. - Prints all current resource allocations for each service (CPU, Memory, Storage) to the terminal * This commit changes output pattern from unformatted lines to a table * adds unit test for ResroucesK8s * formatting/retabbing * Adds --docker flag to print resources of docker deployment - Previously, you could only run `scout` on a k8s deployment - Now, by specifying the `--docker` flag, you can run against a docker deployment - Added unit tests for ResourcesK8s and ResourcesDocker * edits docs to reflect which sub commands are currently available to use * refactor * fix build issues * replace hard coded file path with path generated by homedir package * Update cmd/src/scout_resources.go Co-authored-by: Jacob Pleiness * Update cmd/src/scout_resources.go Co-authored-by: Jacob Pleiness * Update internal/scout/resources/resources.go Co-authored-by: Jacob Pleiness * Update internal/scout/resources/resources.go Co-authored-by: Jacob Pleiness * Update internal/scout/resources/resources.go Co-authored-by: Jacob Pleiness * don't capitalize error messages Co-authored-by: Jacob Pleiness * remove capitalization on error message Co-authored-by: Jacob Pleiness * capitalization Co-authored-by: Jacob Pleiness * add defer functions for closing tabwriter * capitalization Co-authored-by: Jacob Pleiness * change function invocations to reflect new function names and retab * reformats output for --docker flag * retab * Requested changes - change package from resources to resource - renamed files accordingly - changed from if statement to switch statement. - deleted empty README.md * test skeleton * test for getMemUnits added * replace 'spy' with 'advise' in command instructions * Add bubbles/bubble tea components to CLI for better UI/UX * remove unnecessary tests. Formatting * formatting and removes placeholder code/comments * remove redundant return statement * export to file now works for docker as well. * refactor * add file export functionality for docker * fix errors linter caught * fix import order (linter caught) * remove unnecessary integration test * import order * add the ability to dump all container resource data txt file --------- Co-authored-by: Jacob Pleiness --- cmd/src/scout.go | 2 +- internal/scout/resource/style/Table.go | 130 +++++++++++++++++-------- 2 files changed, 90 insertions(+), 42 deletions(-) diff --git a/cmd/src/scout.go b/cmd/src/scout.go index 753012cac8..0ad74a33c9 100644 --- a/cmd/src/scout.go +++ b/cmd/src/scout.go @@ -8,7 +8,7 @@ import ( var scoutCommands commander func init() { - usage := `'src scout' is a tool that provides monitoring for Sourcegraph resource allocations + usage := `'src scout' is a tool that provides monitoring for Sourcegraph resources EXPERIMENTAL: 'scout' is an experimental command in the 'src' tool. To use, you must point your .kube config to your Sourcegraph instance. diff --git a/internal/scout/resource/style/Table.go b/internal/scout/resource/style/Table.go index a24b02cc4a..fe5830b9c5 100644 --- a/internal/scout/resource/style/Table.go +++ b/internal/scout/resource/style/Table.go @@ -3,10 +3,14 @@ package style import ( "fmt" "os" + "path/filepath" + "strings" + "text/tabwriter" "github.com/charmbracelet/bubbles/table" tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/lipgloss" + "github.com/sourcegraph/sourcegraph/lib/errors" "golang.design/x/clipboard" ) @@ -32,7 +36,7 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { copiedMessage := lipgloss.NewStyle(). Foreground(lipgloss.Color("#32CD32")). Render(fmt.Sprintf( - "Copied resource allocations for %s to clipboard", + "Copied resource allocations for '%s' to clipboard", m.table.SelectedRow()[0], )) return m, tea.Batch( @@ -40,6 +44,21 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { copiedMessage, ), ) + case "C": + tmpDir := os.TempDir() + filePath := filepath.Join(tmpDir, "resource-dump.txt") + m.dumpResources(m.table.Rows(), filePath) + savedMessage := lipgloss.NewStyle(). + Foreground(lipgloss.Color("#32CD32")). + Render(fmt.Sprintf( + "saved resource allocations to %s", + filePath, + )) + return m, tea.Batch( + tea.Printf( + savedMessage, + ), + ) } } m.table, cmd = m.table.Update(msg) @@ -49,54 +68,83 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { func (m model) View() string { s := "\n > Press 'j' and 'k' to go up and down\n" s += " > Press 'c' to copy highlighted row to clipboard\n" + s += " > Press 'C' to copy all rows to a file\n" s += " > Press 'q' to quit\n\n" s += baseStyle.Render(m.table.View()) + "\n" return s } +func (m model) dumpResources(rows []table.Row, filePath string) error { + dumpFile, err := os.Create(filePath) + if err != nil { + return errors.Wrap(err, "error while creating new file") + } + defer dumpFile.Close() + + tw := tabwriter.NewWriter(dumpFile, 0, 0, 3, ' ', 0) + defer tw.Flush() + + // default to docker terms + headers := []string{ + "NAME", + "CPU CORES", + "CPU SHARES", + "MEM LIMITS", + "MEM RESERVATIONS", + } + + // kubernetes rows will always have 6 items + // change column headers to reflect k8s terms + if len(rows[0]) == 6 { + headers = []string{ + "NAME", + "CPU LIMITS", + "CPU REQUESTS", + "MEM LIMITS", + "MEM REQUESTS", + "CAPACITY", + } + } + + fmt.Fprintf(tw, strings.Join(headers, "\t")+"\n") + + for _, row := range rows { + values := []string{row[0], row[1], row[2], row[3], row[4]} + if len(row) == 6 { + values = append(values, row[5]) + } + fmt.Fprintf(tw, strings.Join(values, "\t")+"\n") + } + return nil +} + func (m model) copyRowToClipboard(row table.Row) { var containerInfo string - // change output based on the length of row - // docker rows will always be length of 5 - // kubernetes rows will always be length of 6 - if len(row) == 5 { - name := row[0] - cpuCores := row[1] - cpuShares := row[2] - memLimits := row[3] - memReservations := row[4] - containerInfo = fmt.Sprintf(`container: %s - cpu cores: %s - cpu shares: %s - mem limits: %s - mem reservations: %s`, - name, - cpuCores, - cpuShares, - memLimits, - memReservations, - ) - } else if len(row) == 6 { - name := row[0] - cpuLimits := row[1] - cpuRequests := row[2] - memLimits := row[3] - memRequests := row[4] - capacity := row[5] - containerInfo = fmt.Sprintf(`container: %s - cpu limits: %s - cpu requests: %s - mem limits: %s - mem requests: %s - disk capacity: %s`, - name, - cpuLimits, - cpuRequests, - memLimits, - memRequests, - capacity, - ) + // default to docker headers + headers := []string{ + "NAME", + "CPU CORES", + "CPU SHARES", + "MEM LIMITS", + "MEM RESERVATIONS", + } + + // kubernetes rows will always have 6 items + // change column headers to reflect k8s terms + if len(row) == 6 { + headers = []string{ + "NAME", + "CPU LIMITS", + "CPU REQUESTS", + "MEM LIMITS", + "MEM REQUESTS", + "CAPACITY", + } + } + + for i, header := range headers { + containerInfo += fmt.Sprintf("%s: %s\n", header, row[i]) } clipboard.Write(clipboard.FmtText, []byte(containerInfo)) From f3812db6157e3f21ca047814a95935d257b41b3f Mon Sep 17 00:00:00 2001 From: Dave Try Date: Wed, 17 May 2023 09:58:45 -0500 Subject: [PATCH 334/647] build src-cli w/ bazel (#979) --- .gitignore | 5 + BUILD.bazel | 16 + WORKSPACE | 62 + cmd/src/BUILD.bazel | 186 ++ deps.bzl | 3301 ++++++++++++++++++++++++ internal/api/BUILD.bazel | 32 + internal/api/mock/BUILD.bazel | 12 + internal/batches/BUILD.bazel | 17 + internal/batches/docker/BUILD.bazel | 35 + internal/batches/executor/BUILD.bazel | 66 + internal/batches/graphql/BUILD.bazel | 12 + internal/batches/log/BUILD.bazel | 14 + internal/batches/mock/BUILD.bazel | 18 + internal/batches/repozip/BUILD.bazel | 28 + internal/batches/service/BUILD.bazel | 43 + internal/batches/ui/BUILD.bazel | 50 + internal/batches/util/BUILD.bazel | 9 + internal/batches/watchdog/BUILD.bazel | 16 + internal/batches/workspace/BUILD.bazel | 47 + internal/cmderrors/BUILD.bazel | 9 + internal/codeintel/BUILD.bazel | 20 + internal/exec/BUILD.bazel | 11 + internal/exec/expect/BUILD.bazel | 14 + internal/instancehealth/BUILD.bazel | 27 + internal/lazyregexp/BUILD.bazel | 9 + internal/pgdump/BUILD.bazel | 23 + internal/servegit/BUILD.bazel | 22 + internal/streaming/BUILD.bazel | 25 + internal/users/BUILD.bazel | 13 + internal/validate/BUILD.bazel | 8 + internal/validate/install/BUILD.bazel | 19 + internal/validate/kube/BUILD.bazel | 48 + internal/version/BUILD.bazel | 8 + 33 files changed, 4225 insertions(+) create mode 100644 BUILD.bazel create mode 100644 WORKSPACE create mode 100644 cmd/src/BUILD.bazel create mode 100644 deps.bzl create mode 100644 internal/api/BUILD.bazel create mode 100644 internal/api/mock/BUILD.bazel create mode 100644 internal/batches/BUILD.bazel create mode 100644 internal/batches/docker/BUILD.bazel create mode 100644 internal/batches/executor/BUILD.bazel create mode 100644 internal/batches/graphql/BUILD.bazel create mode 100644 internal/batches/log/BUILD.bazel create mode 100644 internal/batches/mock/BUILD.bazel create mode 100644 internal/batches/repozip/BUILD.bazel create mode 100644 internal/batches/service/BUILD.bazel create mode 100644 internal/batches/ui/BUILD.bazel create mode 100644 internal/batches/util/BUILD.bazel create mode 100644 internal/batches/watchdog/BUILD.bazel create mode 100644 internal/batches/workspace/BUILD.bazel create mode 100644 internal/cmderrors/BUILD.bazel create mode 100644 internal/codeintel/BUILD.bazel create mode 100644 internal/exec/BUILD.bazel create mode 100644 internal/exec/expect/BUILD.bazel create mode 100644 internal/instancehealth/BUILD.bazel create mode 100644 internal/lazyregexp/BUILD.bazel create mode 100644 internal/pgdump/BUILD.bazel create mode 100644 internal/servegit/BUILD.bazel create mode 100644 internal/streaming/BUILD.bazel create mode 100644 internal/users/BUILD.bazel create mode 100644 internal/validate/BUILD.bazel create mode 100644 internal/validate/install/BUILD.bazel create mode 100644 internal/validate/kube/BUILD.bazel create mode 100644 internal/version/BUILD.bazel diff --git a/.gitignore b/.gitignore index de75d79e40..a32d205f63 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,8 @@ release .env .envrc src-snapshot/ +bazel-bin +bazel-out +bazel-testlogs +bazel-zoekt +bazel-src-cli \ No newline at end of file diff --git a/BUILD.bazel b/BUILD.bazel new file mode 100644 index 0000000000..fada8decbf --- /dev/null +++ b/BUILD.bazel @@ -0,0 +1,16 @@ +# gazelle:prefix github.com/sourcegraph/src-cli +# gazelle:build_file_name BUILD.bazel +load("@bazel_gazelle//:def.bzl", "gazelle") + +gazelle(name = "gazelle") + +gazelle( + name = "gazelle-update-repos", + args = [ + "-from_file=go.mod", + "-to_macro=deps.bzl%go_dependencies", + "-prune", + "-build_file_proto_mode=disable_global", + ], + command = "update-repos", +) diff --git a/WORKSPACE b/WORKSPACE new file mode 100644 index 0000000000..523cb75747 --- /dev/null +++ b/WORKSPACE @@ -0,0 +1,62 @@ +load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") + +http_archive( + name = "bazel_skylib", + sha256 = "74d544d96f4a5bb630d465ca8bbcfe231e3594e5aae57e1edbf17a6eb3ca2506", + urls = [ + "https://mirror.bazel.build/github.com/bazelbuild/bazel-skylib/releases/download/1.3.0/bazel-skylib-1.3.0.tar.gz", + "https://github.com/bazelbuild/bazel-skylib/releases/download/1.3.0/bazel-skylib-1.3.0.tar.gz", + ], +) + +load("@bazel_skylib//:workspace.bzl", "bazel_skylib_workspace") + +bazel_skylib_workspace() + +http_archive( + name = "aspect_bazel_lib", + sha256 = "2518c757715d4f5fc7cc7e0a68742dd1155eaafc78fb9196b8a18e13a738cea2", + strip_prefix = "bazel-lib-1.28.0", + url = "https://github.com/aspect-build/bazel-lib/releases/download/v1.28.0/bazel-lib-v1.28.0.tar.gz", +) + +http_archive( + name = "io_bazel_rules_go", + sha256 = "dd926a88a564a9246713a9c00b35315f54cbd46b31a26d5d8fb264c07045f05d", + urls = [ + "https://mirror.bazel.build/github.com/bazelbuild/rules_go/releases/download/v0.38.1/rules_go-v0.38.1.zip", + "https://github.com/bazelbuild/rules_go/releases/download/v0.38.1/rules_go-v0.38.1.zip", + ], +) + +http_archive( + name = "bazel_gazelle", + sha256 = "ecba0f04f96b4960a5b250c8e8eeec42281035970aa8852dda73098274d14a1d", + urls = [ + "https://mirror.bazel.build/github.com/bazelbuild/bazel-gazelle/releases/download/v0.29.0/bazel-gazelle-v0.29.0.tar.gz", + "https://github.com/bazelbuild/bazel-gazelle/releases/download/v0.29.0/bazel-gazelle-v0.29.0.tar.gz", + ], +) + +# Go toolchain setup +load("@io_bazel_rules_go//go:deps.bzl", "go_register_toolchains", "go_rules_dependencies") +load("@bazel_gazelle//:deps.bzl", "gazelle_dependencies","go_repository") +load("//:deps.bzl", "go_dependencies") + +# gazelle:repository_macro deps.bzl%go_dependencies +go_dependencies() + +go_rules_dependencies() + +go_register_toolchains( + version = "1.19.6", +) + +gazelle_dependencies() + +go_repository( + name = "com_github_aws_aws_sdk_go_v2_service_eks", + importpath = "github.com/aws/aws-sdk-go-v2/service/eks", + version = "v1.27.3", + sum = "h1:jlh0AJVhauqSGaiwRJx4j0LNBGEAaGn46sA1XJyTj0E=", +) \ No newline at end of file diff --git a/cmd/src/BUILD.bazel b/cmd/src/BUILD.bazel new file mode 100644 index 0000000000..fdc0530dee --- /dev/null +++ b/cmd/src/BUILD.bazel @@ -0,0 +1,186 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library", "go_test") + +go_library( + name = "src_lib", + srcs = [ + "admin.go", + "admin_create.go", + "api.go", + "batch.go", + "batch_apply.go", + "batch_common.go", + "batch_exec.go", + "batch_new.go", + "batch_preview.go", + "batch_remote.go", + "batch_repositories.go", + "batch_validate.go", + "cmd.go", + "code_intel.go", + "code_intel_upload.go", + "code_intel_upload_flags.go", + "codeowners.go", + "codeowners_create.go", + "codeowners_delete.go", + "codeowners_get.go", + "codeowners_update.go", + "colors.go", + "config.go", + "config_edit.go", + "config_get.go", + "config_list.go", + "debug.go", + "debug_common.go", + "debug_compose.go", + "debug_kube.go", + "debug_server.go", + "doc.go", + "extensions.go", + "extensions_copy.go", + "extensions_delete.go", + "extensions_get.go", + "extensions_list.go", + "extensions_publish.go", + "extsvc.go", + "extsvc_create.go", + "extsvc_edit.go", + "extsvc_list.go", + "format.go", + "headers.go", + "login.go", + "lsif.go", + "main.go", + "orgs.go", + "orgs_create.go", + "orgs_delete.go", + "orgs_get.go", + "orgs_list.go", + "orgs_members.go", + "orgs_members_add.go", + "orgs_members_remove.go", + "repos.go", + "repos_add_metadata.go", + "repos_delete.go", + "repos_delete_metadata.go", + "repos_get.go", + "repos_list.go", + "repos_update_metadata.go", + "search.go", + "search_alert.go", + "search_stream.go", + "servegit.go", + "snapshot.go", + "snapshot_databases.go", + "snapshot_restore.go", + "snapshot_summary.go", + "snapshot_testcmd.go", + "snapshot_upload.go", + "team_members_list.go", + "teams.go", + "teams_create.go", + "teams_delete.go", + "teams_list.go", + "teams_members.go", + "teams_members_add.go", + "teams_members_remove.go", + "teams_update.go", + "users.go", + "users_create.go", + "users_delete.go", + "users_get.go", + "users_list.go", + "users_prune.go", + "users_tag.go", + "validate.go", + "validate_install.go", + "validate_kube.go", + "version.go", + ], + importpath = "github.com/sourcegraph/src-cli/cmd/src", + visibility = ["//visibility:private"], + deps = [ + "//internal/api", + "//internal/batches", + "//internal/batches/docker", + "//internal/batches/executor", + "//internal/batches/graphql", + "//internal/batches/log", + "//internal/batches/repozip", + "//internal/batches/service", + "//internal/batches/ui", + "//internal/batches/watchdog", + "//internal/batches/workspace", + "//internal/cmderrors", + "//internal/codeintel", + "//internal/exec", + "//internal/instancehealth", + "//internal/pgdump", + "//internal/servegit", + "//internal/streaming", + "//internal/users", + "//internal/validate/install", + "//internal/validate/kube", + "//internal/version", + "@com_github_dustin_go_humanize//:go-humanize", + "@com_github_google_go_cmp//cmp", + "@com_github_grafana_regexp//:regexp", + "@com_github_jedib0t_go_pretty_v6//table", + "@com_github_mattn_go_isatty//:go-isatty", + "@com_github_pkg_browser//:browser", + "@com_github_sourcegraph_conc//pool", + "@com_github_sourcegraph_jsonx//:jsonx", + "@com_github_sourcegraph_scip//bindings/go/scip", + "@com_github_sourcegraph_sourcegraph_lib//batches", + "@com_github_sourcegraph_sourcegraph_lib//batches/template", + "@com_github_sourcegraph_sourcegraph_lib//codeintel/lsif/scip", + "@com_github_sourcegraph_sourcegraph_lib//codeintel/upload", + "@com_github_sourcegraph_sourcegraph_lib//errors", + "@com_github_sourcegraph_sourcegraph_lib//output", + "@com_google_cloud_go_storage//:storage", + "@com_jaytaylor_html2text//:html2text", + "@in_gopkg_yaml_v3//:yaml_v3", + "@io_k8s_client_go//kubernetes", + "@io_k8s_client_go//plugin/pkg/client/auth/azure", + "@io_k8s_client_go//plugin/pkg/client/auth/gcp", + "@io_k8s_client_go//tools/clientcmd", + "@io_k8s_client_go//util/homedir", + "@org_golang_google_api//option", + "@org_golang_google_protobuf//proto", + "@org_golang_x_net//context", + "@org_golang_x_sync//errgroup", + "@org_golang_x_sync//semaphore", + ], +) + +go_binary( + name = "src", + embed = [":src_lib"], + visibility = ["//visibility:public"], +) + +go_test( + name = "src_test", + srcs = [ + "code_intel_upload_flags_test.go", + "extensions_publish_test.go", + "headers_test.go", + "login_test.go", + "main_test.go", + "search_alert_test.go", + "search_stream_test.go", + "search_test.go", + ], + data = glob(["testdata/**"]), + embed = [":src_lib"], + deps = [ + "//internal/api", + "//internal/cmderrors", + "//internal/streaming", + "@com_github_google_go_cmp//cmp", + "@com_github_grafana_regexp//:regexp", + "@com_github_hexops_autogold//:autogold", + "@com_github_sourcegraph_scip//bindings/go/scip", + "@com_github_stretchr_testify//require", + "@org_golang_google_protobuf//proto", + ], +) diff --git a/deps.bzl b/deps.bzl new file mode 100644 index 0000000000..9ac9997928 --- /dev/null +++ b/deps.bzl @@ -0,0 +1,3301 @@ +load("@bazel_gazelle//:deps.bzl", "go_repository") + +def go_dependencies(): + go_repository( + name = "cc_mvdan_gofumpt", + build_file_proto_mode = "disable_global", + importpath = "mvdan.cc/gofumpt", + sum = "h1:JVf4NN1mIpHogBj7ABpgOyZc65/UUOkKQFkoURsz4MM=", + version = "v0.4.0", + ) + go_repository( + name = "co_honnef_go_tools", + build_file_proto_mode = "disable_global", + importpath = "honnef.co/go/tools", + sum = "h1:/hemPrYIhOhy8zYrNj+069zDB68us2sMGsfkFJO0iZs=", + version = "v0.0.0-20190523083050-ea95bdfd59fc", + ) + go_repository( + name = "com_github_ajg_form", + build_file_proto_mode = "disable_global", + importpath = "github.com/ajg/form", + sum = "h1:t9c7v8JUKu/XxOGBU0yjNpaMloxGEJhUkqFRq0ibGeU=", + version = "v1.5.1", + ) + go_repository( + name = "com_github_alecthomas_chroma", + build_file_proto_mode = "disable_global", + importpath = "github.com/alecthomas/chroma", + sum = "h1:7XDcGkCQopCNKjZHfYrNLraA+M7e0fMiJ/Mfikbfjek=", + version = "v0.10.0", + ) + go_repository( + name = "com_github_alecthomas_kingpin", + build_file_proto_mode = "disable_global", + importpath = "github.com/alecthomas/kingpin", + sum = "h1:5svnBTFgJjZvGKyYBtMB0+m5wvrbUHiqye8wRJMlnYI=", + version = "v2.2.6+incompatible", + ) + go_repository( + name = "com_github_alecthomas_template", + build_file_proto_mode = "disable_global", + importpath = "github.com/alecthomas/template", + sum = "h1:JYp7IbQjafoB+tBA3gMyHYHrpOtNuDiK/uB5uXxq5wM=", + version = "v0.0.0-20190718012654-fb15b899a751", + ) + go_repository( + name = "com_github_alecthomas_units", + build_file_proto_mode = "disable_global", + importpath = "github.com/alecthomas/units", + sum = "h1:s6gZFSlWYmbqAuRjVTiNNhvNRfY2Wxp9nhfyel4rklc=", + version = "v0.0.0-20211218093645-b94a6e3cc137", + ) + go_repository( + name = "com_github_andreasbriese_bbloom", + build_file_proto_mode = "disable_global", + importpath = "github.com/AndreasBriese/bbloom", + sum = "h1:HD8gA2tkByhMAwYaFAX9w2l7vxvBQ5NMoxDrkhqhtn4=", + version = "v0.0.0-20190306092124-e2d15f34fcf9", + ) + go_repository( + name = "com_github_andybalholm_brotli", + build_file_proto_mode = "disable_global", + importpath = "github.com/andybalholm/brotli", + sum = "h1:V7DdXeJtZscaqfNuAdSRuRFzuiKlHSC/Zh3zl9qY3JY=", + version = "v1.0.4", + ) + go_repository( + name = "com_github_aokoli_goutils", + build_file_proto_mode = "disable_global", + importpath = "github.com/aokoli/goutils", + sum = "h1:7fpzNGoJ3VA8qcrm++XEE1QUe0mIwNeLa02Nwq7RDkg=", + version = "v1.0.1", + ) + go_repository( + name = "com_github_armon_consul_api", + build_file_proto_mode = "disable_global", + importpath = "github.com/armon/consul-api", + sum = "h1:G1bPvciwNyF7IUmKXNt9Ak3m6u9DE1rF+RmtIkBpVdA=", + version = "v0.0.0-20180202201655-eb2c6b5be1b6", + ) + go_repository( + name = "com_github_armon_go_socks5", + build_file_proto_mode = "disable_global", + importpath = "github.com/armon/go-socks5", + sum = "h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio=", + version = "v0.0.0-20160902184237-e75332964ef5", + ) + go_repository( + name = "com_github_asaskevich_govalidator", + build_file_proto_mode = "disable_global", + importpath = "github.com/asaskevich/govalidator", + sum = "h1:idn718Q4B6AGu/h5Sxe66HYVdqdGu2l9Iebqhi/AEoA=", + version = "v0.0.0-20190424111038-f61b66f89f4a", + ) + go_repository( + name = "com_github_aws_aws_sdk_go_v2", + build_file_proto_mode = "disable_global", + importpath = "github.com/aws/aws-sdk-go-v2", + sum = "h1:TzCUW1Nq4H8Xscph5M/skINUitxM5UBAyvm2s7XBzL4=", + version = "v1.17.5", + ) + go_repository( + name = "com_github_aws_aws_sdk_go_v2_config", + build_file_proto_mode = "disable_global", + importpath = "github.com/aws/aws-sdk-go-v2/config", + sum = "h1:v0xlYqbO6/EVlM8tUn2QEOA7btQxcgidEq2JRDBPTho=", + version = "v1.18.13", + ) + go_repository( + name = "com_github_aws_aws_sdk_go_v2_credentials", + build_file_proto_mode = "disable_global", + importpath = "github.com/aws/aws-sdk-go-v2/credentials", + sum = "h1:zw1KAc1kl00NYd3ofVmFrb09qnYlSQMeh+fmlQRAihI=", + version = "v1.13.13", + ) + go_repository( + name = "com_github_aws_aws_sdk_go_v2_feature_ec2_imds", + build_file_proto_mode = "disable_global", + importpath = "github.com/aws/aws-sdk-go-v2/feature/ec2/imds", + sum = "h1:3aMfcTmoXtTZnaT86QlVaYh+BRMbvrrmZwIQ5jWqCZQ=", + version = "v1.12.22", + ) + go_repository( + name = "com_github_aws_aws_sdk_go_v2_internal_configsources", + build_file_proto_mode = "disable_global", + importpath = "github.com/aws/aws-sdk-go-v2/internal/configsources", + sum = "h1:9/aKwwus0TQxppPXFmf010DFrE+ssSbzroLVYINA+xE=", + version = "v1.1.29", + ) + go_repository( + name = "com_github_aws_aws_sdk_go_v2_internal_endpoints_v2", + build_file_proto_mode = "disable_global", + importpath = "github.com/aws/aws-sdk-go-v2/internal/endpoints/v2", + sum = "h1:b/Vn141DBuLVgXbhRWIrl9g+ww7G+ScV5SzniWR13jQ=", + version = "v2.4.23", + ) + go_repository( + name = "com_github_aws_aws_sdk_go_v2_internal_ini", + build_file_proto_mode = "disable_global", + importpath = "github.com/aws/aws-sdk-go-v2/internal/ini", + sum = "h1:J4xhFd6zHhdF9jPP0FQJ6WknzBboGMBNjKOv4iTuw4A=", + version = "v1.3.29", + ) + go_repository( + name = "com_github_aws_aws_sdk_go_v2_service_ec2", + build_file_proto_mode = "disable_global", + importpath = "github.com/aws/aws-sdk-go-v2/service/ec2", + sum = "h1:4dt0Mg5veHbMLcA2JAR9LDxvqXjtG0ZLQdxZG/2wHy4=", + version = "v1.86.0", + ) + go_repository( + name = "com_github_aws_aws_sdk_go_v2_service_eks", + build_file_proto_mode = "disable_global", + importpath = "github.com/aws/aws-sdk-go-v2/service/eks", + sum = "h1:jlh0AJVhauqSGaiwRJx4j0LNBGEAaGn46sA1XJyTj0E=", + version = "v1.27.3", + ) + go_repository( + name = "com_github_aws_aws_sdk_go_v2_service_iam", + build_file_proto_mode = "disable_global", + importpath = "github.com/aws/aws-sdk-go-v2/service/iam", + sum = "h1:vaDXu/p/5RNK++B2pqKS3hwsWGxsVjJJqPaAMg0OkiM=", + version = "v1.19.3", + ) + go_repository( + name = "com_github_aws_aws_sdk_go_v2_service_internal_presigned_url", + build_file_proto_mode = "disable_global", + importpath = "github.com/aws/aws-sdk-go-v2/service/internal/presigned-url", + sum = "h1:LjFQf8hFuMO22HkV5VWGLBvmCLBCLPivUAmpdpnp4Vs=", + version = "v1.9.22", + ) + go_repository( + name = "com_github_aws_aws_sdk_go_v2_service_sso", + build_file_proto_mode = "disable_global", + importpath = "github.com/aws/aws-sdk-go-v2/service/sso", + sum = "h1:EN102fWY7hI5u/2FPheTrwwMHkSXfl49RYkeEnJsrCU=", + version = "v1.12.2", + ) + go_repository( + name = "com_github_aws_aws_sdk_go_v2_service_ssooidc", + build_file_proto_mode = "disable_global", + importpath = "github.com/aws/aws-sdk-go-v2/service/ssooidc", + sum = "h1:f1lmlce7r13CX1BPyPqt9oh/H+uqOWc9367lDoGGwNQ=", + version = "v1.14.2", + ) + go_repository( + name = "com_github_aws_aws_sdk_go_v2_service_sts", + build_file_proto_mode = "disable_global", + importpath = "github.com/aws/aws-sdk-go-v2/service/sts", + sum = "h1:s49mSnsBZEXjfGBkRfmK+nPqzT7Lt3+t2SmAKNyHblw=", + version = "v1.18.3", + ) + go_repository( + name = "com_github_aws_smithy_go", + build_file_proto_mode = "disable_global", + importpath = "github.com/aws/smithy-go", + sum = "h1:hgz0X/DX0dGqTYpGALqXJoRKRj5oQ7150i5FdTePzO8=", + version = "v1.13.5", + ) + go_repository( + name = "com_github_aymerick_douceur", + build_file_proto_mode = "disable_global", + importpath = "github.com/aymerick/douceur", + sum = "h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk=", + version = "v0.2.0", + ) + go_repository( + name = "com_github_aymerick_raymond", + build_file_proto_mode = "disable_global", + importpath = "github.com/aymerick/raymond", + sum = "h1:Ppm0npCCsmuR9oQaBtRuZcmILVE74aXE+AmrJj8L2ns=", + version = "v2.0.3-0.20180322193309-b565731e1464+incompatible", + ) + go_repository( + name = "com_github_azure_go_ansiterm", + build_file_proto_mode = "disable_global", + importpath = "github.com/Azure/go-ansiterm", + sum = "h1:UQHMgLO+TxOElx5B5HZ4hJQsoJ/PvUvKRhJHDQXO8P8=", + version = "v0.0.0-20210617225240-d185dfc1b5a1", + ) + go_repository( + name = "com_github_benbjohnson_clock", + build_file_proto_mode = "disable_global", + importpath = "github.com/benbjohnson/clock", + sum = "h1:ip6w0uFQkncKQ979AypyG0ER7mqUSBdKLOgAle/AT8A=", + version = "v1.3.0", + ) + go_repository( + name = "com_github_bufbuild_buf", + build_file_proto_mode = "disable_global", + importpath = "github.com/bufbuild/buf", + sum = "h1:GqE3a8CMmcFvWPzuY3Mahf9Kf3S9XgZ/ORpfYFzO+90=", + version = "v1.4.0", + ) + go_repository( + name = "com_github_burntsushi_toml", + build_file_proto_mode = "disable_global", + importpath = "github.com/BurntSushi/toml", + sum = "h1:Rt8g24XnyGTyglgET/PRUNlrUeu9F5L+7FilkXfZgs0=", + version = "v1.2.0", + ) + go_repository( + name = "com_github_census_instrumentation_opencensus_proto", + build_file_proto_mode = "disable_global", + importpath = "github.com/census-instrumentation/opencensus-proto", + sum = "h1:iKLQ0xPNFxR/2hzXZMrBo8f1j86j5WHzznCCQxV/b8g=", + version = "v0.4.1", + ) + go_repository( + name = "com_github_cespare_xxhash_v2", + build_file_proto_mode = "disable_global", + importpath = "github.com/cespare/xxhash/v2", + sum = "h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=", + version = "v2.2.0", + ) + go_repository( + name = "com_github_charmbracelet_glamour", + build_file_proto_mode = "disable_global", + importpath = "github.com/charmbracelet/glamour", + sum = "h1:wu15ykPdB7X6chxugG/NNfDUbyyrCLV9XBalj5wdu3g=", + version = "v0.5.0", + ) + go_repository( + name = "com_github_client9_misspell", + build_file_proto_mode = "disable_global", + importpath = "github.com/client9/misspell", + sum = "h1:ta993UF76GwbvJcIo3Y68y/M3WxlpEHPWIGDkJYwzJI=", + version = "v0.3.4", + ) + go_repository( + name = "com_github_cloudykit_fastprinter", + build_file_proto_mode = "disable_global", + importpath = "github.com/CloudyKit/fastprinter", + sum = "h1:sR+/8Yb4slttB4vD+b9btVEnWgL3Q00OBTzVT8B9C0c=", + version = "v0.0.0-20200109182630-33d98a066a53", + ) + go_repository( + name = "com_github_cloudykit_jet", + build_file_proto_mode = "disable_global", + importpath = "github.com/CloudyKit/jet", + sum = "h1:rZgFj+Gtf3NMi/U5FvCvhzaxzW/TaPYgUYx3bAPz9DE=", + version = "v2.1.3-0.20180809161101-62edd43e4f88+incompatible", + ) + go_repository( + name = "com_github_cloudykit_jet_v3", + build_file_proto_mode = "disable_global", + importpath = "github.com/CloudyKit/jet/v3", + sum = "h1:1PwO5w5VCtlUUl+KTOBsTGZlhjWkcybsGaAau52tOy8=", + version = "v3.0.0", + ) + go_repository( + name = "com_github_cloudykit_jet_v6", + build_file_proto_mode = "disable_global", + importpath = "github.com/CloudyKit/jet/v6", + sum = "h1:hvO96X345XagdH1fAoBjpBYG4a1ghhL/QzalkduPuXk=", + version = "v6.1.0", + ) + go_repository( + name = "com_github_cncf_udpa_go", + build_file_proto_mode = "disable_global", + importpath = "github.com/cncf/udpa/go", + sum = "h1:QQ3GSy+MqSHxm/d8nCtnAiZdYFd45cYZPs8vOOIYKfk=", + version = "v0.0.0-20220112060539-c52dc94e7fbe", + ) + go_repository( + name = "com_github_cncf_xds_go", + build_file_proto_mode = "disable_global", + importpath = "github.com/cncf/xds/go", + sum = "h1:ACGZRIr7HsgBKHsueQ1yM4WaVaXh21ynwqsF8M8tXhA=", + version = "v0.0.0-20230105202645-06c439db220b", + ) + go_repository( + name = "com_github_cockroachdb_datadriven", + build_file_proto_mode = "disable_global", + importpath = "github.com/cockroachdb/datadriven", + sum = "h1:GCR5egmFNSTyGOv9IvMh636aELybEhZOlpPlW2NtuiU=", + version = "v1.0.1-0.20220214170620-9913f5bc19b7", + ) + go_repository( + name = "com_github_cockroachdb_errors", + build_file_proto_mode = "disable_global", + importpath = "github.com/cockroachdb/errors", + sum = "h1:B48dYem5SlAY7iU8AKsgedb4gH6mo+bDkbtLIvM/a88=", + version = "v1.9.0", + ) + go_repository( + name = "com_github_cockroachdb_logtags", + build_file_proto_mode = "disable_global", + importpath = "github.com/cockroachdb/logtags", + sum = "h1:6jduT9Hfc0njg5jJ1DdKCFPdMBrp/mdZfCpa5h+WM74=", + version = "v0.0.0-20211118104740-dabe8e521a4f", + ) + go_repository( + name = "com_github_cockroachdb_redact", + build_file_proto_mode = "disable_global", + importpath = "github.com/cockroachdb/redact", + sum = "h1:AKZds10rFSIj7qADf0g46UixK8NNLwWTNdCIGS5wfSQ=", + version = "v1.1.3", + ) + go_repository( + name = "com_github_cockroachdb_sentry_go", + build_file_proto_mode = "disable_global", + importpath = "github.com/cockroachdb/sentry-go", + sum = "h1:IKgmqgMQlVJIZj19CdocBeSfSaiCbEBZGKODaixqtHM=", + version = "v0.6.1-cockroachdb.2", + ) + go_repository( + name = "com_github_codegangsta_inject", + build_file_proto_mode = "disable_global", + importpath = "github.com/codegangsta/inject", + sum = "h1:sDMmm+q/3+BukdIpxwO365v/Rbspp2Nt5XntgQRXq8Q=", + version = "v0.0.0-20150114235600-33e0aa1cb7c0", + ) + go_repository( + name = "com_github_coreos_etcd", + build_file_proto_mode = "disable_global", + importpath = "github.com/coreos/etcd", + sum = "h1:jFneRYjIvLMLhDLCzuTuU4rSJUjRplcJQ7pD7MnhC04=", + version = "v3.3.10+incompatible", + ) + go_repository( + name = "com_github_coreos_go_etcd", + build_file_proto_mode = "disable_global", + importpath = "github.com/coreos/go-etcd", + sum = "h1:bXhRBIXoTm9BYHS3gE0TtQuyNZyeEMux2sDi4oo5YOo=", + version = "v2.0.0+incompatible", + ) + go_repository( + name = "com_github_coreos_go_semver", + build_file_proto_mode = "disable_global", + importpath = "github.com/coreos/go-semver", + sum = "h1:3Jm3tLmsgAYcjC+4Up7hJrFBPr+n7rAqYeSw/SZazuY=", + version = "v0.2.0", + ) + go_repository( + name = "com_github_cpuguy83_go_md2man", + build_file_proto_mode = "disable_global", + importpath = "github.com/cpuguy83/go-md2man", + sum = "h1:BSKMNlYxDvnunlTymqtgONjNnaRV1sTpcovwwjF22jk=", + version = "v1.0.10", + ) + go_repository( + name = "com_github_cpuguy83_go_md2man_v2", + build_file_proto_mode = "disable_global", + importpath = "github.com/cpuguy83/go-md2man/v2", + sum = "h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w=", + version = "v2.0.2", + ) + go_repository( + name = "com_github_creack_goselect", + build_file_proto_mode = "disable_global", + importpath = "github.com/creack/goselect", + sum = "h1:2DNy14+JPjRBgPzAd1thbQp4BSIihxcBf0IXhQXDRa0=", + version = "v0.1.2", + ) + go_repository( + name = "com_github_creack_pty", + build_file_proto_mode = "disable_global", + importpath = "github.com/creack/pty", + sum = "h1:07n33Z8lZxZ2qwegKbObQohDhXDQxiMMz1NOUGYlesw=", + version = "v1.1.11", + ) + go_repository( + name = "com_github_dave_jennifer", + build_file_proto_mode = "disable_global", + importpath = "github.com/dave/jennifer", + sum = "h1:HmgPN93bVDpkQyYbqhCHj5QlgvUkvEOzMyEvKLgCRrg=", + version = "v1.5.0", + ) + go_repository( + name = "com_github_davecgh_go_spew", + build_file_proto_mode = "disable_global", + importpath = "github.com/davecgh/go-spew", + sum = "h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=", + version = "v1.1.1", + ) + go_repository( + name = "com_github_derision_test_glock", + build_file_proto_mode = "disable_global", + importpath = "github.com/derision-test/glock", + sum = "h1:O07j7ewg0eFHRx+7bxCA/7z86HJexl7HLY9kyVMmPDo=", + version = "v0.0.0-20210316032053-f5b74334bb29", + ) + go_repository( + name = "com_github_derision_test_go_mockgen", + build_file_proto_mode = "disable_global", + importpath = "github.com/derision-test/go-mockgen", + sum = "h1:b/DXAXL2FkaRPpnbYK3ODdZzklmJAwox0tkc6yyXx74=", + version = "v1.3.7", + ) + go_repository( + name = "com_github_dgraph_io_badger", + build_file_proto_mode = "disable_global", + importpath = "github.com/dgraph-io/badger", + sum = "h1:DshxFxZWXUcO0xX476VJC07Xsr6ZCBVRHKZ93Oh7Evo=", + version = "v1.6.0", + ) + go_repository( + name = "com_github_dgrijalva_jwt_go", + build_file_proto_mode = "disable_global", + importpath = "github.com/dgrijalva/jwt-go", + sum = "h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=", + version = "v3.2.0+incompatible", + ) + go_repository( + name = "com_github_dgryski_go_farm", + build_file_proto_mode = "disable_global", + importpath = "github.com/dgryski/go-farm", + sum = "h1:tdlZCpZ/P9DhczCTSixgIKmwPv6+wP5DGjqLYw5SUiA=", + version = "v0.0.0-20190423205320-6a90982ecee2", + ) + go_repository( + name = "com_github_dineshappavoo_basex", + build_file_proto_mode = "disable_global", + importpath = "github.com/dineshappavoo/basex", + sum = "h1:fctNkSsavbXpt8geFWZb8n+noCqS8MrOXRJ/YfdZ2dQ=", + version = "v0.0.0-20170425072625-481a6f6dc663", + ) + go_repository( + name = "com_github_dlclark_regexp2", + build_file_proto_mode = "disable_global", + importpath = "github.com/dlclark/regexp2", + sum = "h1:7lJfhqlPssTb1WQx4yvTHN0uElPEv52sbaECrAQxjAo=", + version = "v1.7.0", + ) + go_repository( + name = "com_github_docopt_docopt_go", + build_file_proto_mode = "disable_global", + importpath = "github.com/docopt/docopt-go", + sum = "h1:bWDMxwH3px2JBh6AyO7hdCn/PkvCZXii8TGj7sbtEbQ=", + version = "v0.0.0-20180111231733-ee0de3bc6815", + ) + go_repository( + name = "com_github_dustin_go_humanize", + build_file_proto_mode = "disable_global", + importpath = "github.com/dustin/go-humanize", + sum = "h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=", + version = "v1.0.1", + ) + go_repository( + name = "com_github_eknkc_amber", + build_file_proto_mode = "disable_global", + importpath = "github.com/eknkc/amber", + sum = "h1:clC1lXBpe2kTj2VHdaIu9ajZQe4kcEY9j0NsnDDBZ3o=", + version = "v0.0.0-20171010120322-cdade1c07385", + ) + go_repository( + name = "com_github_elazarl_goproxy", + build_file_proto_mode = "disable_global", + importpath = "github.com/elazarl/goproxy", + sum = "h1:yUdfgN0XgIJw7foRItutHYUIhlcKzcSf5vDpdhQAKTc=", + version = "v0.0.0-20180725130230-947c36da3153", + ) + go_repository( + name = "com_github_emicklei_go_restful_v3", + build_file_proto_mode = "disable_global", + importpath = "github.com/emicklei/go-restful/v3", + sum = "h1:XwGDlfxEnQZzuopoqxwSEllNcCOM9DhhFyhFIIGKwxE=", + version = "v3.9.0", + ) + go_repository( + name = "com_github_envoyproxy_go_control_plane", + build_file_proto_mode = "disable_global", + importpath = "github.com/envoyproxy/go-control-plane", + sum = "h1:xdCVXxEe0Y3FQith+0cj2irwZudqGYvecuLB1HtdexY=", + version = "v0.10.3", + ) + go_repository( + name = "com_github_envoyproxy_protoc_gen_validate", + build_file_proto_mode = "disable_global", + importpath = "github.com/envoyproxy/protoc-gen-validate", + sum = "h1:PS7VIOgmSVhWUEeZwTe7z7zouA22Cr590PzXKbZHOVY=", + version = "v0.9.1", + ) + go_repository( + name = "com_github_etcd_io_bbolt", + build_file_proto_mode = "disable_global", + importpath = "github.com/etcd-io/bbolt", + sum = "h1:gSJmxrs37LgTqR/oyJBWok6k6SvXEUerFTbltIhXkBM=", + version = "v1.3.3", + ) + go_repository( + name = "com_github_evanphx_json_patch", + build_file_proto_mode = "disable_global", + importpath = "github.com/evanphx/json-patch", + sum = "h1:4onqiflcdA9EOZ4RxV643DvftH5pOlLGNtQ5lPWQu84=", + version = "v4.12.0+incompatible", + ) + go_repository( + name = "com_github_fasthttp_contrib_websocket", + build_file_proto_mode = "disable_global", + importpath = "github.com/fasthttp-contrib/websocket", + sum = "h1:DddqAaWDpywytcG8w/qoQ5sAN8X12d3Z3koB0C3Rxsc=", + version = "v0.0.0-20160511215533-1f3b11f56072", + ) + go_repository( + name = "com_github_fatih_color", + build_file_proto_mode = "disable_global", + importpath = "github.com/fatih/color", + sum = "h1:8LOYc1KYPPmyKMuN8QV2DNRWNbLo6LZ0iLs8+mlH53w=", + version = "v1.13.0", + ) + go_repository( + name = "com_github_fatih_structs", + build_file_proto_mode = "disable_global", + importpath = "github.com/fatih/structs", + sum = "h1:Q7juDM0QtcnhCpeyLGQKyg4TOIghuNXrkL32pHAUMxo=", + version = "v1.1.0", + ) + go_repository( + name = "com_github_flosch_pongo2", + build_file_proto_mode = "disable_global", + importpath = "github.com/flosch/pongo2", + sum = "h1:GY1+t5Dr9OKADM64SYnQjw/w99HMYvQ0A8/JoUkxVmc=", + version = "v0.0.0-20190707114632-bbf5a6c351f4", + ) + go_repository( + name = "com_github_flosch_pongo2_v4", + build_file_proto_mode = "disable_global", + importpath = "github.com/flosch/pongo2/v4", + sum = "h1:gv+5Pe3vaSVmiJvh/BZa82b7/00YUGm0PIyVVLop0Hw=", + version = "v4.0.2", + ) + go_repository( + name = "com_github_frankban_quicktest", + build_file_proto_mode = "disable_global", + importpath = "github.com/frankban/quicktest", + sum = "h1:FJKSZTDHjyhriyC81FLQ0LY93eSai0ZyR/ZIkd3ZUKE=", + version = "v1.14.3", + ) + go_repository( + name = "com_github_fsnotify_fsnotify", + build_file_proto_mode = "disable_global", + importpath = "github.com/fsnotify/fsnotify", + sum = "h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4=", + version = "v1.4.9", + ) + go_repository( + name = "com_github_gavv_httpexpect", + build_file_proto_mode = "disable_global", + importpath = "github.com/gavv/httpexpect", + sum = "h1:1X9kcRshkSKEjNJJxX9Y9mQ5BRfbxU5kORdjhlA1yX8=", + version = "v2.0.0+incompatible", + ) + go_repository( + name = "com_github_getsentry_sentry_go", + build_file_proto_mode = "disable_global", + importpath = "github.com/getsentry/sentry-go", + sum = "h1:CP9bmA7pralrVUedYZsmIHWpq/pBtXTSew7xvVpfLaA=", + version = "v0.15.0", + ) + go_repository( + name = "com_github_ghodss_yaml", + build_file_proto_mode = "disable_global", + importpath = "github.com/ghodss/yaml", + replace = "github.com/sourcegraph/yaml", + sum = "h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o=", + version = "v1.0.1-0.20200714132230-56936252f152", + ) + go_repository( + name = "com_github_gin_contrib_sse", + build_file_proto_mode = "disable_global", + importpath = "github.com/gin-contrib/sse", + sum = "h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=", + version = "v0.1.0", + ) + go_repository( + name = "com_github_gin_gonic_gin", + build_file_proto_mode = "disable_global", + importpath = "github.com/gin-gonic/gin", + sum = "h1:4+fr/el88TOO3ewCmQr8cx/CtZ/umlIRIs5M4NTNjf8=", + version = "v1.8.1", + ) + go_repository( + name = "com_github_go_check_check", + build_file_proto_mode = "disable_global", + importpath = "github.com/go-check/check", + sum = "h1:0gkP6mzaMqkmpcJYCFOLkIBwI7xFExG03bbkOkCvUPI=", + version = "v0.0.0-20180628173108-788fd7840127", + ) + go_repository( + name = "com_github_go_enry_go_enry_v2", + build_file_proto_mode = "disable_global", + importpath = "github.com/go-enry/go-enry/v2", + sum = "h1:IBtFo783PgL7oyd/TL1/8HQFMNzOAl4NaLPbzNOvbwM=", + version = "v2.7.2", + ) + go_repository( + name = "com_github_go_enry_go_oniguruma", + build_file_proto_mode = "disable_global", + importpath = "github.com/go-enry/go-oniguruma", + sum = "h1:k8aAMuJfMrqm/56SG2lV9Cfti6tC4x8673aHCcBk+eo=", + version = "v1.2.1", + ) + go_repository( + name = "com_github_go_errors_errors", + build_file_proto_mode = "disable_global", + importpath = "github.com/go-errors/errors", + sum = "h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA=", + version = "v1.4.2", + ) + go_repository( + name = "com_github_go_logr_logr", + build_file_proto_mode = "disable_global", + importpath = "github.com/go-logr/logr", + sum = "h1:2DntVwHkVopvECVRSlL5PSo9eG+cAkDCuckLubN+rq0=", + version = "v1.2.3", + ) + go_repository( + name = "com_github_go_martini_martini", + build_file_proto_mode = "disable_global", + importpath = "github.com/go-martini/martini", + sum = "h1:xveKWz2iaueeTaUgdetzel+U7exyigDYBryyVfV/rZk=", + version = "v0.0.0-20170121215854-22fa46961aab", + ) + go_repository( + name = "com_github_go_openapi_jsonpointer", + build_file_proto_mode = "disable_global", + importpath = "github.com/go-openapi/jsonpointer", + sum = "h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUeOFYEICuY=", + version = "v0.19.5", + ) + go_repository( + name = "com_github_go_openapi_jsonreference", + build_file_proto_mode = "disable_global", + importpath = "github.com/go-openapi/jsonreference", + sum = "h1:MYlu0sBgChmCfJxxUKZ8g1cPWFOB37YSZqewK7OKeyA=", + version = "v0.20.0", + ) + go_repository( + name = "com_github_go_openapi_swag", + build_file_proto_mode = "disable_global", + importpath = "github.com/go-openapi/swag", + sum = "h1:gm3vOOXfiuw5i9p5N9xJvfjvuofpyvLA9Wr6QfK5Fng=", + version = "v0.19.14", + ) + go_repository( + name = "com_github_go_playground_locales", + build_file_proto_mode = "disable_global", + importpath = "github.com/go-playground/locales", + sum = "h1:u50s323jtVGugKlcYeyzC0etD1HifMjqmJqb8WugfUU=", + version = "v0.14.0", + ) + go_repository( + name = "com_github_go_playground_universal_translator", + build_file_proto_mode = "disable_global", + importpath = "github.com/go-playground/universal-translator", + sum = "h1:82dyy6p4OuJq4/CByFNOn/jYrnRPArHwAcmLoJZxyho=", + version = "v0.18.0", + ) + go_repository( + name = "com_github_go_playground_validator_v10", + build_file_proto_mode = "disable_global", + importpath = "github.com/go-playground/validator/v10", + sum = "h1:prmOlTVv+YjZjmRmNSF3VmspqJIxJWXmqUsHwfTRRkQ=", + version = "v10.11.1", + ) + go_repository( + name = "com_github_gobwas_glob", + build_file_proto_mode = "disable_global", + importpath = "github.com/gobwas/glob", + sum = "h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=", + version = "v0.2.3", + ) + go_repository( + name = "com_github_gobwas_httphead", + build_file_proto_mode = "disable_global", + importpath = "github.com/gobwas/httphead", + sum = "h1:s+21KNqlpePfkah2I+gwHF8xmJWRjooY+5248k6m4A0=", + version = "v0.0.0-20180130184737-2c6c146eadee", + ) + go_repository( + name = "com_github_gobwas_pool", + build_file_proto_mode = "disable_global", + importpath = "github.com/gobwas/pool", + sum = "h1:QEmUOlnSjWtnpRGHF3SauEiOsy82Cup83Vf2LcMlnc8=", + version = "v0.2.0", + ) + go_repository( + name = "com_github_gobwas_ws", + build_file_proto_mode = "disable_global", + importpath = "github.com/gobwas/ws", + sum = "h1:CoAavW/wd/kulfZmSIBt6p24n4j7tHgNVCjsfHVNUbo=", + version = "v1.0.2", + ) + go_repository( + name = "com_github_goccy_go_json", + build_file_proto_mode = "disable_global", + importpath = "github.com/goccy/go-json", + sum = "h1:/pAaQDLHEoCq/5FFmSKBswWmK6H0e8g4159Kc/X/nqk=", + version = "v0.9.11", + ) + go_repository( + name = "com_github_gofrs_flock", + build_file_proto_mode = "disable_global", + importpath = "github.com/gofrs/flock", + sum = "h1:+gYjHKf32LDeiEEFhQaotPbLuUXjY5ZqxKgXy7n59aw=", + version = "v0.8.1", + ) + go_repository( + name = "com_github_gofrs_uuid", + build_file_proto_mode = "disable_global", + importpath = "github.com/gofrs/uuid", + sum = "h1:yyYWMnhkhrKwwr8gAOcOCYxOOscHgDS9yZgBrnJfGa0=", + version = "v4.2.0+incompatible", + ) + go_repository( + name = "com_github_gogo_googleapis", + build_file_proto_mode = "disable_global", + importpath = "github.com/gogo/googleapis", + sum = "h1:1Yx4Myt7BxzvUr5ldGSbwYiZG6t9wGBZ+8/fX3Wvtq0=", + version = "v1.4.1", + ) + go_repository( + name = "com_github_gogo_protobuf", + build_file_proto_mode = "disable_global", + importpath = "github.com/gogo/protobuf", + sum = "h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=", + version = "v1.3.2", + ) + go_repository( + name = "com_github_gogo_status", + build_file_proto_mode = "disable_global", + importpath = "github.com/gogo/status", + sum = "h1:+eIkrewn5q6b30y+g/BJINVVdi2xH7je5MPJ3ZPK3JA=", + version = "v1.1.0", + ) + go_repository( + name = "com_github_golang_glog", + build_file_proto_mode = "disable_global", + importpath = "github.com/golang/glog", + sum = "h1:nfP3RFugxnNRyKgeWd4oI1nYvXpxrx8ck8ZrcizshdQ=", + version = "v1.0.0", + ) + go_repository( + name = "com_github_golang_groupcache", + build_file_proto_mode = "disable_global", + importpath = "github.com/golang/groupcache", + sum = "h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE=", + version = "v0.0.0-20210331224755-41bb18bfe9da", + ) + go_repository( + name = "com_github_golang_jwt_jwt", + build_file_proto_mode = "disable_global", + importpath = "github.com/golang-jwt/jwt", + sum = "h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY=", + version = "v3.2.2+incompatible", + ) + go_repository( + name = "com_github_golang_mock", + build_file_proto_mode = "disable_global", + importpath = "github.com/golang/mock", + sum = "h1:G5FRp8JnTd7RQH5kemVNlMeyXQAztQ3mOWV95KxsXH8=", + version = "v1.1.1", + ) + go_repository( + name = "com_github_golang_protobuf", + build_file_proto_mode = "disable_global", + importpath = "github.com/golang/protobuf", + sum = "h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw=", + version = "v1.5.2", + ) + go_repository( + name = "com_github_golang_snappy", + build_file_proto_mode = "disable_global", + importpath = "github.com/golang/snappy", + sum = "h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM=", + version = "v0.0.4", + ) + go_repository( + name = "com_github_gomodule_redigo", + build_file_proto_mode = "disable_global", + importpath = "github.com/gomodule/redigo", + sum = "h1:y0Wmhvml7cGnzPa9nocn/fMraMH/lMDdeG+rkx4VgYY=", + version = "v1.7.1-0.20190724094224-574c33c3df38", + ) + go_repository( + name = "com_github_google_btree", + build_file_proto_mode = "disable_global", + importpath = "github.com/google/btree", + sum = "h1:gK4Kx5IaGY9CD5sPJ36FHiBJ6ZXl0kilRiiCj+jdYp4=", + version = "v1.0.1", + ) + go_repository( + name = "com_github_google_gnostic", + build_file_proto_mode = "disable_global", + importpath = "github.com/google/gnostic", + sum = "h1:FhTMOKj2VhjpouxvWJAV1TL304uMlb9zcDqkl6cEI54=", + version = "v0.5.7-v3refs", + ) + go_repository( + name = "com_github_google_go_cmp", + build_file_proto_mode = "disable_global", + importpath = "github.com/google/go-cmp", + sum = "h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=", + version = "v0.5.9", + ) + go_repository( + name = "com_github_google_go_querystring", + build_file_proto_mode = "disable_global", + importpath = "github.com/google/go-querystring", + sum = "h1:Xkwi/a1rcvNg1PPYe5vI8GbeBY/jrVuDX5ASuANWTrk=", + version = "v1.0.0", + ) + go_repository( + name = "com_github_google_gofuzz", + build_file_proto_mode = "disable_global", + importpath = "github.com/google/gofuzz", + sum = "h1:Hsa8mG0dQ46ij8Sl2AYJDUv1oA9/d6Vk+3LG99Oe02g=", + version = "v1.1.0", + ) + go_repository( + name = "com_github_google_martian_v3", + build_file_proto_mode = "disable_global", + importpath = "github.com/google/martian/v3", + sum = "h1:d8MncMlErDFTwQGBK1xhv026j9kqhvw1Qv9IbWT1VLQ=", + version = "v3.2.1", + ) + go_repository( + name = "com_github_google_uuid", + build_file_proto_mode = "disable_global", + importpath = "github.com/google/uuid", + sum = "h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=", + version = "v1.3.0", + ) + go_repository( + name = "com_github_googleapis_enterprise_certificate_proxy", + build_file_proto_mode = "disable_global", + importpath = "github.com/googleapis/enterprise-certificate-proxy", + sum = "h1:yk9/cqRKtT9wXZSsRH9aurXEpJX+U6FLtpYTdC3R06k=", + version = "v0.2.3", + ) + go_repository( + name = "com_github_googleapis_gax_go_v2", + build_file_proto_mode = "disable_global", + importpath = "github.com/googleapis/gax-go/v2", + sum = "h1:IcsPKeInNvYi7eqSaDjiZqDDKu5rsmunY0Y1YupQSSQ=", + version = "v2.7.0", + ) + go_repository( + name = "com_github_gopherjs_gopherjs", + build_file_proto_mode = "disable_global", + importpath = "github.com/gopherjs/gopherjs", + sum = "h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8=", + version = "v0.0.0-20181017120253-0766667cb4d1", + ) + go_repository( + name = "com_github_gorilla_css", + build_file_proto_mode = "disable_global", + importpath = "github.com/gorilla/css", + sum = "h1:BQqNyPTi50JCFMTw/b67hByjMVXZRwGha6wxVGkeihY=", + version = "v1.0.0", + ) + go_repository( + name = "com_github_gorilla_websocket", + build_file_proto_mode = "disable_global", + importpath = "github.com/gorilla/websocket", + sum = "h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc=", + version = "v1.4.2", + ) + go_repository( + name = "com_github_grafana_regexp", + build_file_proto_mode = "disable_global", + importpath = "github.com/grafana/regexp", + sum = "h1:7aN5cccjIqCLTzedH7MZzRZt5/lsAHch6Z3L2ZGn5FA=", + version = "v0.0.0-20221123153739-15dc172cd2db", + ) + go_repository( + name = "com_github_gregjones_httpcache", + build_file_proto_mode = "disable_global", + importpath = "github.com/gregjones/httpcache", + sum = "h1:pdN6V1QBWetyv/0+wjACpqVH+eVULgEjkurDLq3goeM=", + version = "v0.0.0-20180305231024-9cad4c3443a7", + ) + go_repository( + name = "com_github_hashicorp_go_version", + build_file_proto_mode = "disable_global", + importpath = "github.com/hashicorp/go-version", + sum = "h1:3vNe/fWF5CBgRIguda1meWhsZHy3m8gCJ5wx+dIzX/E=", + version = "v1.2.0", + ) + go_repository( + name = "com_github_hashicorp_hcl", + build_file_proto_mode = "disable_global", + importpath = "github.com/hashicorp/hcl", + sum = "h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=", + version = "v1.0.0", + ) + go_repository( + name = "com_github_hexops_autogold", + build_file_proto_mode = "disable_global", + importpath = "github.com/hexops/autogold", + sum = "h1:IEtGNPxBeBu8RMn8eKWh/Ll9dVNgSnJ7bp/qHgMQ14o=", + version = "v1.3.0", + ) + go_repository( + name = "com_github_hexops_autogold_v2", + build_file_proto_mode = "disable_global", + importpath = "github.com/hexops/autogold/v2", + sum = "h1:zyrfTlNfyxLpX/zuk8wjTeTYP5AXaFeeRYFEZfHPwao=", + version = "v2.0.3", + ) + go_repository( + name = "com_github_hexops_gotextdiff", + build_file_proto_mode = "disable_global", + importpath = "github.com/hexops/gotextdiff", + sum = "h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM=", + version = "v1.0.3", + ) + go_repository( + name = "com_github_hexops_valast", + build_file_proto_mode = "disable_global", + importpath = "github.com/hexops/valast", + sum = "h1:oBoGERMJh6UZdRc6cduE1CTPK+VAdXA59Y1HFgu3sm0=", + version = "v1.4.3", + ) + go_repository( + name = "com_github_hhatto_gocloc", + build_file_proto_mode = "disable_global", + importpath = "github.com/hhatto/gocloc", + sum = "h1:deh3Xb1uqiySNgOccMNYb3HbKsUoQDzsZRpfQmbTIhs=", + version = "v0.4.2", + ) + go_repository( + name = "com_github_hpcloud_tail", + build_file_proto_mode = "disable_global", + importpath = "github.com/hpcloud/tail", + sum = "h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI=", + version = "v1.0.0", + ) + go_repository( + name = "com_github_huandu_xstrings", + build_file_proto_mode = "disable_global", + importpath = "github.com/huandu/xstrings", + sum = "h1:L18LIDzqlW6xN2rEkpdV8+oL/IXWJ1APd+vsdYy4Wdw=", + version = "v1.3.2", + ) + go_repository( + name = "com_github_hydrogen18_memlistener", + build_file_proto_mode = "disable_global", + importpath = "github.com/hydrogen18/memlistener", + sum = "h1:KyZDvZ/GGn+r+Y3DKZ7UOQ/TP4xV6HNkrwiVMB1GnNY=", + version = "v0.0.0-20200120041712-dcc25e7acd91", + ) + go_repository( + name = "com_github_iancoleman_strcase", + build_file_proto_mode = "disable_global", + importpath = "github.com/iancoleman/strcase", + sum = "h1:05I4QRnGpI0m37iZQRuskXh+w77mr6Z41lwQzuHLwW0=", + version = "v0.2.0", + ) + go_repository( + name = "com_github_imdario_mergo", + build_file_proto_mode = "disable_global", + importpath = "github.com/imdario/mergo", + sum = "h1:lFzP57bqS/wsqKssCGmtLAb8A0wKjLGrve2q3PPVcBk=", + version = "v0.3.13", + ) + go_repository( + name = "com_github_imkira_go_interpol", + build_file_proto_mode = "disable_global", + importpath = "github.com/imkira/go-interpol", + sum = "h1:KIiKr0VSG2CUW1hl1jpiyuzuJeKUUpC8iM1AIE7N1Vk=", + version = "v1.1.0", + ) + go_repository( + name = "com_github_inconshreveable_mousetrap", + build_file_proto_mode = "disable_global", + importpath = "github.com/inconshreveable/mousetrap", + sum = "h1:U3uMjPSQEBMNp1lFxmllqCPM6P5u/Xq7Pgzkat/bFNc=", + version = "v1.0.1", + ) + go_repository( + name = "com_github_iris_contrib_blackfriday", + build_file_proto_mode = "disable_global", + importpath = "github.com/iris-contrib/blackfriday", + sum = "h1:o5sHQHHm0ToHUlAJSTjW9UWicjJSDDauOOQ2AHuIVp4=", + version = "v2.0.0+incompatible", + ) + go_repository( + name = "com_github_iris_contrib_go_uuid", + build_file_proto_mode = "disable_global", + importpath = "github.com/iris-contrib/go.uuid", + sum = "h1:XZubAYg61/JwnJNbZilGjf3b3pB80+OQg2qf6c8BfWE=", + version = "v2.0.0+incompatible", + ) + go_repository( + name = "com_github_iris_contrib_i18n", + build_file_proto_mode = "disable_global", + importpath = "github.com/iris-contrib/i18n", + sum = "h1:Kyp9KiXwsyZRTeoNjgVCrWks7D8ht9+kg6yCjh8K97o=", + version = "v0.0.0-20171121225848-987a633949d0", + ) + go_repository( + name = "com_github_iris_contrib_jade", + build_file_proto_mode = "disable_global", + importpath = "github.com/iris-contrib/jade", + sum = "h1:WoYdfyJFfZIUgqNAeOyRfTNQZOksSlZ6+FnXR3AEpX0=", + version = "v1.1.4", + ) + go_repository( + name = "com_github_iris_contrib_pongo2", + build_file_proto_mode = "disable_global", + importpath = "github.com/iris-contrib/pongo2", + sum = "h1:zGP7pW51oi5eQZMIlGA3I+FHY9/HOQWDB+572yin0to=", + version = "v0.0.1", + ) + go_repository( + name = "com_github_iris_contrib_schema", + build_file_proto_mode = "disable_global", + importpath = "github.com/iris-contrib/schema", + sum = "h1:CPSBLyx2e91H2yJzPuhGuifVRnZBBJ3pCOMbOvPZaTw=", + version = "v0.0.6", + ) + go_repository( + name = "com_github_jdxcode_netrc", + build_file_proto_mode = "disable_global", + importpath = "github.com/jdxcode/netrc", + sum = "h1:d4+I1YEKVmWZrgkt6jpXBnLgV2ZjO0YxEtLDdfIZfH4=", + version = "v0.0.0-20210204082910-926c7f70242a", + ) + go_repository( + name = "com_github_jedib0t_go_pretty_v6", + build_file_proto_mode = "disable_global", + importpath = "github.com/jedib0t/go-pretty/v6", + sum = "h1:H3Ulkf7h6A+p0HgKBGzgDn0bZIupRbKKWF4pO4Bs7iA=", + version = "v6.3.7", + ) + go_repository( + name = "com_github_jhump_gopoet", + build_file_proto_mode = "disable_global", + importpath = "github.com/jhump/gopoet", + sum = "h1:gYjOPnzHd2nzB37xYQZxj4EIQNpBrBskRqQQ3q4ZgSg=", + version = "v0.1.0", + ) + go_repository( + name = "com_github_jhump_goprotoc", + build_file_proto_mode = "disable_global", + importpath = "github.com/jhump/goprotoc", + sum = "h1:Y1UgUX+txUznfqcGdDef8ZOVlyQvnV0pKWZH08RmZuo=", + version = "v0.5.0", + ) + go_repository( + name = "com_github_jhump_protocompile", + build_file_proto_mode = "disable_global", + importpath = "github.com/jhump/protocompile", + sum = "h1:BNuUg9k2EiJmlMwjoef3e8vZLHplbVw6DrjGFjLL+Yo=", + version = "v0.0.0-20220216033700-d705409f108f", + ) + go_repository( + name = "com_github_jhump_protoreflect", + build_file_proto_mode = "disable_global", + importpath = "github.com/jhump/protoreflect", + sum = "h1:uFlcJKZPLQd7rmOY/RrvBuUaYmAFnlFHKLivhO6cOy8=", + version = "v1.12.1-0.20220417024638-438db461d753", + ) + go_repository( + name = "com_github_jig_teereadcloser", + build_file_proto_mode = "disable_global", + importpath = "github.com/jig/teereadcloser", + sum = "h1:dSwwtWuwMyarzsbVWOq4QJ8xVy9wgcNomvWyGtrKe+E=", + version = "v0.0.0-20181016160506-953720c48e05", + ) + go_repository( + name = "com_github_jmespath_go_jmespath", + build_file_proto_mode = "disable_global", + importpath = "github.com/jmespath/go-jmespath", + sum = "h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg=", + version = "v0.4.0", + ) + go_repository( + name = "com_github_jmespath_go_jmespath_internal_testify", + build_file_proto_mode = "disable_global", + importpath = "github.com/jmespath/go-jmespath/internal/testify", + sum = "h1:shLQSRRSCCPj3f2gpwzGwWFoC7ycTf1rcQZHOlsJ6N8=", + version = "v1.5.1", + ) + go_repository( + name = "com_github_joker_hpp", + build_file_proto_mode = "disable_global", + importpath = "github.com/Joker/hpp", + sum = "h1:65+iuJYdRXv/XyN62C1uEmmOx3432rNG/rKlX6V7Kkc=", + version = "v1.0.0", + ) + go_repository( + name = "com_github_joker_jade", + build_file_proto_mode = "disable_global", + importpath = "github.com/Joker/jade", + sum = "h1:mreN1m/5VJ/Zc3b4pzj9qU6D9SRQ6Vm+3KfI328t3S8=", + version = "v1.0.1-0.20190614124447-d475f43051e7", + ) + go_repository( + name = "com_github_josharian_intern", + build_file_proto_mode = "disable_global", + importpath = "github.com/josharian/intern", + sum = "h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=", + version = "v1.0.0", + ) + go_repository( + name = "com_github_json_iterator_go", + build_file_proto_mode = "disable_global", + importpath = "github.com/json-iterator/go", + sum = "h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=", + version = "v1.1.12", + ) + go_repository( + name = "com_github_jtolds_gls", + build_file_proto_mode = "disable_global", + importpath = "github.com/jtolds/gls", + sum = "h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo=", + version = "v4.20.0+incompatible", + ) + go_repository( + name = "com_github_juju_errors", + build_file_proto_mode = "disable_global", + importpath = "github.com/juju/errors", + sum = "h1:rhqTjzJlm7EbkELJDKMTU7udov+Se0xZkWmugr6zGok=", + version = "v0.0.0-20181118221551-089d3ea4e4d5", + ) + go_repository( + name = "com_github_juju_loggo", + build_file_proto_mode = "disable_global", + importpath = "github.com/juju/loggo", + sum = "h1:MK144iBQF9hTSwBW/9eJm034bVoG30IshVm688T2hi8=", + version = "v0.0.0-20180524022052-584905176618", + ) + go_repository( + name = "com_github_juju_testing", + build_file_proto_mode = "disable_global", + importpath = "github.com/juju/testing", + sum = "h1:WQM1NildKThwdP7qWrNAFGzp4ijNLw8RlgENkaI4MJs=", + version = "v0.0.0-20180920084828-472a3e8b2073", + ) + go_repository( + name = "com_github_k0kubun_colorstring", + build_file_proto_mode = "disable_global", + importpath = "github.com/k0kubun/colorstring", + sum = "h1:uC1QfSlInpQF+M0ao65imhwqKnz3Q2z/d8PWZRMQvDM=", + version = "v0.0.0-20150214042306-9440f1994b88", + ) + go_repository( + name = "com_github_k0kubun_pp_v3", + build_file_proto_mode = "disable_global", + importpath = "github.com/k0kubun/pp/v3", + sum = "h1:ifxtqJkRZhw3h554/z/8zm6AAbyO4LLKDlA5eV+9O8Q=", + version = "v3.1.0", + ) + go_repository( + name = "com_github_kataras_blocks", + build_file_proto_mode = "disable_global", + importpath = "github.com/kataras/blocks", + sum = "h1:cF3RDY/vxnSRezc7vLFlQFTYXG/yAr1o7WImJuZbzC4=", + version = "v0.0.7", + ) + go_repository( + name = "com_github_kataras_golog", + build_file_proto_mode = "disable_global", + importpath = "github.com/kataras/golog", + sum = "h1:0TY5tHn5L5DlRIikepcaRR/6oInIr9AiWsxzt0vvlBE=", + version = "v0.1.7", + ) + go_repository( + name = "com_github_kataras_iris_v12", + build_file_proto_mode = "disable_global", + importpath = "github.com/kataras/iris/v12", + sum = "h1:grB/oCf5baZhmYIeDMfgN3LYrtEcmK8pbxlRvEZ2pgw=", + version = "v12.2.0-beta5", + ) + go_repository( + name = "com_github_kataras_neffos", + build_file_proto_mode = "disable_global", + importpath = "github.com/kataras/neffos", + sum = "h1:pdJaTvUG3NQfeMbbVCI8JT2T5goPldyyfUB2PJfh1Bs=", + version = "v0.0.14", + ) + go_repository( + name = "com_github_kataras_pio", + build_file_proto_mode = "disable_global", + importpath = "github.com/kataras/pio", + sum = "h1:kqreJ5KOEXGMwHAWHDwIl+mjfNCPhAwZPa8gK7MKlyw=", + version = "v0.0.11", + ) + go_repository( + name = "com_github_kataras_sitemap", + build_file_proto_mode = "disable_global", + importpath = "github.com/kataras/sitemap", + sum = "h1:w71CRMMKYMJh6LR2wTgnk5hSgjVNB9KL60n5e2KHvLY=", + version = "v0.0.6", + ) + go_repository( + name = "com_github_kataras_tunnel", + build_file_proto_mode = "disable_global", + importpath = "github.com/kataras/tunnel", + sum = "h1:sCAqWuJV7nPzGrlb0os3j49lk2JhILT0rID38NHNLpA=", + version = "v0.0.4", + ) + go_repository( + name = "com_github_kballard_go_shellquote", + build_file_proto_mode = "disable_global", + importpath = "github.com/kballard/go-shellquote", + sum = "h1:Z9n2FFNUXsshfwJMBgNA0RU6/i7WVaAegv3PtuIHPMs=", + version = "v0.0.0-20180428030007-95032a82bc51", + ) + go_repository( + name = "com_github_kisielk_errcheck", + build_file_proto_mode = "disable_global", + importpath = "github.com/kisielk/errcheck", + sum = "h1:e8esj/e4R+SAOwFwN+n3zr0nYeCyeweozKfO23MvHzY=", + version = "v1.5.0", + ) + go_repository( + name = "com_github_kisielk_gotool", + build_file_proto_mode = "disable_global", + importpath = "github.com/kisielk/gotool", + sum = "h1:AV2c/EiW3KqPNT9ZKl07ehoAGi4C5/01Cfbblndcapg=", + version = "v1.0.0", + ) + go_repository( + name = "com_github_klauspost_compress", + build_file_proto_mode = "disable_global", + importpath = "github.com/klauspost/compress", + sum = "h1:Lcadnb3RKGin4FYM/orgq0qde+nc15E5Cbqg4B9Sx9c=", + version = "v1.15.11", + ) + go_repository( + name = "com_github_klauspost_cpuid", + build_file_proto_mode = "disable_global", + importpath = "github.com/klauspost/cpuid", + sum = "h1:vJi+O/nMdFt0vqm8NZBI6wzALWdA2X+egi0ogNyrC/w=", + version = "v1.2.1", + ) + go_repository( + name = "com_github_klauspost_pgzip", + build_file_proto_mode = "disable_global", + importpath = "github.com/klauspost/pgzip", + sum = "h1:qnWYvvKqedOF2ulHpMG72XQol4ILEJ8k2wwRl/Km8oE=", + version = "v1.2.5", + ) + go_repository( + name = "com_github_kr_pretty", + build_file_proto_mode = "disable_global", + importpath = "github.com/kr/pretty", + sum = "h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=", + version = "v0.3.1", + ) + go_repository( + name = "com_github_kr_pty", + build_file_proto_mode = "disable_global", + importpath = "github.com/kr/pty", + sum = "h1:VkoXIwSboBpnk99O/KFauAEILuNHv5DVFKZMBN/gUgw=", + version = "v1.1.1", + ) + go_repository( + name = "com_github_kr_text", + build_file_proto_mode = "disable_global", + importpath = "github.com/kr/text", + sum = "h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=", + version = "v0.2.0", + ) + go_repository( + name = "com_github_labstack_echo_v4", + build_file_proto_mode = "disable_global", + importpath = "github.com/labstack/echo/v4", + sum = "h1:wPOF1CE6gvt/kmbMR4dGzWvHMPT+sAEUJOwOTtvITVY=", + version = "v4.9.0", + ) + go_repository( + name = "com_github_labstack_gommon", + build_file_proto_mode = "disable_global", + importpath = "github.com/labstack/gommon", + sum = "h1:OomWaJXm7xR6L1HmEtGyQf26TEn7V6X88mktX9kee9o=", + version = "v0.3.1", + ) + go_repository( + name = "com_github_leodido_go_urn", + build_file_proto_mode = "disable_global", + importpath = "github.com/leodido/go-urn", + sum = "h1:BqpAaACuzVSgi/VLzGZIobT2z4v53pjosyNd9Yv6n/w=", + version = "v1.2.1", + ) + go_repository( + name = "com_github_lucasb_eyer_go_colorful", + build_file_proto_mode = "disable_global", + importpath = "github.com/lucasb-eyer/go-colorful", + sum = "h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=", + version = "v1.2.0", + ) + go_repository( + name = "com_github_lyft_protoc_gen_star", + build_file_proto_mode = "disable_global", + importpath = "github.com/lyft/protoc-gen-star", + sum = "h1:erE0rdztuaDq3bpGifD95wfoPrSZc95nGA6tbiNYh6M=", + version = "v0.6.1", + ) + go_repository( + name = "com_github_magiconair_properties", + build_file_proto_mode = "disable_global", + importpath = "github.com/magiconair/properties", + sum = "h1:LLgXmsheXeRoUOBOjtwPQCWIYqM/LU1ayDtDePerRcY=", + version = "v1.8.0", + ) + go_repository( + name = "com_github_mailgun_raymond_v2", + build_file_proto_mode = "disable_global", + importpath = "github.com/mailgun/raymond/v2", + sum = "h1:aOYHhvTpF5USySJ0o7cpPno/Uh2I5qg2115K25A+Ft4=", + version = "v2.0.46", + ) + go_repository( + name = "com_github_mailru_easyjson", + build_file_proto_mode = "disable_global", + importpath = "github.com/mailru/easyjson", + sum = "h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=", + version = "v0.7.7", + ) + go_repository( + name = "com_github_masterminds_goutils", + build_file_proto_mode = "disable_global", + importpath = "github.com/Masterminds/goutils", + sum = "h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI=", + version = "v1.1.1", + ) + go_repository( + name = "com_github_masterminds_semver", + build_file_proto_mode = "disable_global", + importpath = "github.com/Masterminds/semver", + sum = "h1:H65muMkzWKEuNDnfl9d70GUjFniHKHRbFPGBuZ3QEww=", + version = "v1.5.0", + ) + go_repository( + name = "com_github_masterminds_sprig", + build_file_proto_mode = "disable_global", + importpath = "github.com/Masterminds/sprig", + sum = "h1:z4yfnGrZ7netVz+0EDJ0Wi+5VZCSYp4Z0m2dk6cEM60=", + version = "v2.22.0+incompatible", + ) + go_repository( + name = "com_github_mattn_go_colorable", + build_file_proto_mode = "disable_global", + importpath = "github.com/mattn/go-colorable", + sum = "h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=", + version = "v0.1.13", + ) + go_repository( + name = "com_github_mattn_go_isatty", + build_file_proto_mode = "disable_global", + importpath = "github.com/mattn/go-isatty", + sum = "h1:bq3VjFmv/sOjHtdEhmkEV4x1AJtvUvOJ2PFAZ5+peKQ=", + version = "v0.0.16", + ) + go_repository( + name = "com_github_mattn_go_runewidth", + build_file_proto_mode = "disable_global", + importpath = "github.com/mattn/go-runewidth", + sum = "h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU=", + version = "v0.0.14", + ) + go_repository( + name = "com_github_mattn_goveralls", + build_file_proto_mode = "disable_global", + importpath = "github.com/mattn/goveralls", + sum = "h1:7eJB6EqsPhRVxvwEXGnqdO2sJI0PTsrWoTMXEk9/OQc=", + version = "v0.0.2", + ) + go_repository( + name = "com_github_mediocregopher_mediocre_go_lib", + build_file_proto_mode = "disable_global", + importpath = "github.com/mediocregopher/mediocre-go-lib", + sum = "h1:3dQJqqDouawQgl3gBE1PNHKFkJYGEuFb1DbSlaxdosE=", + version = "v0.0.0-20181029021733-cb65787f37ed", + ) + go_repository( + name = "com_github_mediocregopher_radix_v3", + build_file_proto_mode = "disable_global", + importpath = "github.com/mediocregopher/radix/v3", + sum = "h1:galbPBjIwmyREgwGCfQEN4X8lxbJnKBYurgz+VfcStA=", + version = "v3.4.2", + ) + go_repository( + name = "com_github_microcosm_cc_bluemonday", + build_file_proto_mode = "disable_global", + importpath = "github.com/microcosm-cc/bluemonday", + sum = "h1:p2tT7RNzRdCi0qmwxG+HbqD6ILkmwter1ZwVZn1oTxA=", + version = "v1.0.22", + ) + go_repository( + name = "com_github_mitchellh_copystructure", + build_file_proto_mode = "disable_global", + importpath = "github.com/mitchellh/copystructure", + sum = "h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=", + version = "v1.2.0", + ) + go_repository( + name = "com_github_mitchellh_go_homedir", + build_file_proto_mode = "disable_global", + importpath = "github.com/mitchellh/go-homedir", + sum = "h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y=", + version = "v1.1.0", + ) + go_repository( + name = "com_github_mitchellh_go_wordwrap", + build_file_proto_mode = "disable_global", + importpath = "github.com/mitchellh/go-wordwrap", + sum = "h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0=", + version = "v1.0.1", + ) + go_repository( + name = "com_github_mitchellh_mapstructure", + build_file_proto_mode = "disable_global", + importpath = "github.com/mitchellh/mapstructure", + sum = "h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE=", + version = "v1.1.2", + ) + go_repository( + name = "com_github_mitchellh_reflectwalk", + build_file_proto_mode = "disable_global", + importpath = "github.com/mitchellh/reflectwalk", + sum = "h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=", + version = "v1.0.2", + ) + go_repository( + name = "com_github_moby_spdystream", + build_file_proto_mode = "disable_global", + importpath = "github.com/moby/spdystream", + sum = "h1:cjW1zVyyoiM0T7b6UoySUFqzXMoqRckQtXwGPiBhOM8=", + version = "v0.2.0", + ) + go_repository( + name = "com_github_moby_term", + build_file_proto_mode = "disable_global", + importpath = "github.com/moby/term", + sum = "h1:O4SWKdcHVCvYqyDV+9CJA1fcDN2L11Bule0iFy3YlAI=", + version = "v0.0.0-20220808134915-39b0c02b01ae", + ) + go_repository( + name = "com_github_modern_go_concurrent", + build_file_proto_mode = "disable_global", + importpath = "github.com/modern-go/concurrent", + sum = "h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=", + version = "v0.0.0-20180306012644-bacd9c7ef1dd", + ) + go_repository( + name = "com_github_modern_go_reflect2", + build_file_proto_mode = "disable_global", + importpath = "github.com/modern-go/reflect2", + sum = "h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=", + version = "v1.0.2", + ) + go_repository( + name = "com_github_moul_http2curl", + build_file_proto_mode = "disable_global", + importpath = "github.com/moul/http2curl", + sum = "h1:dRMWoAtb+ePxMlLkrCbAqh4TlPHXvoGUSQ323/9Zahs=", + version = "v1.0.0", + ) + go_repository( + name = "com_github_muesli_reflow", + build_file_proto_mode = "disable_global", + importpath = "github.com/muesli/reflow", + sum = "h1:IFsN6K9NfGtjeggFP+68I4chLZV2yIKsXJFNZ+eWh6s=", + version = "v0.3.0", + ) + go_repository( + name = "com_github_muesli_termenv", + build_file_proto_mode = "disable_global", + importpath = "github.com/muesli/termenv", + sum = "h1:KuQRUE3PgxRFWhq4gHvZtPSLCGDqM5q/cYr1pZ39ytc=", + version = "v0.12.0", + ) + go_repository( + name = "com_github_munnerz_goautoneg", + build_file_proto_mode = "disable_global", + importpath = "github.com/munnerz/goautoneg", + sum = "h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=", + version = "v0.0.0-20191010083416-a7dc8b61c822", + ) + go_repository( + name = "com_github_mwitkow_go_proto_validators", + build_file_proto_mode = "disable_global", + importpath = "github.com/mwitkow/go-proto-validators", + sum = "h1:qRlmpTzm2pstMKKzTdvwPCF5QfBNURSlAgN/R+qbKos=", + version = "v0.3.2", + ) + go_repository( + name = "com_github_mxk_go_flowrate", + build_file_proto_mode = "disable_global", + importpath = "github.com/mxk/go-flowrate", + sum = "h1:y5//uYreIhSUg3J1GEMiLbxo1LJaP8RfCpH6pymGZus=", + version = "v0.0.0-20140419014527-cca7078d478f", + ) + go_repository( + name = "com_github_nats_io_jwt", + build_file_proto_mode = "disable_global", + importpath = "github.com/nats-io/jwt", + sum = "h1:xdnzwFETV++jNc4W1mw//qFyJGb2ABOombmZJQS4+Qo=", + version = "v0.3.0", + ) + go_repository( + name = "com_github_nats_io_nats_go", + build_file_proto_mode = "disable_global", + importpath = "github.com/nats-io/nats.go", + sum = "h1:ik3HbLhZ0YABLto7iX80pZLPw/6dx3T+++MZJwLnMrQ=", + version = "v1.9.1", + ) + go_repository( + name = "com_github_nats_io_nkeys", + build_file_proto_mode = "disable_global", + importpath = "github.com/nats-io/nkeys", + sum = "h1:qMd4+pRHgdr1nAClu+2h/2a5F2TmKcCzjCDazVgRoX4=", + version = "v0.1.0", + ) + go_repository( + name = "com_github_nats_io_nuid", + build_file_proto_mode = "disable_global", + importpath = "github.com/nats-io/nuid", + sum = "h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw=", + version = "v1.0.1", + ) + go_repository( + name = "com_github_neelance_parallel", + build_file_proto_mode = "disable_global", + importpath = "github.com/neelance/parallel", + sum = "h1:NZOii9TDGRAfCS5VM16XnF4K7afoLQmIiZX8EkKnxtE=", + version = "v0.0.0-20160708114440-4de9ce63d14c", + ) + go_repository( + name = "com_github_niemeyer_pretty", + build_file_proto_mode = "disable_global", + importpath = "github.com/niemeyer/pretty", + sum = "h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=", + version = "v0.0.0-20200227124842-a10e7caefd8e", + ) + go_repository( + name = "com_github_nightlyone_lockfile", + build_file_proto_mode = "disable_global", + importpath = "github.com/nightlyone/lockfile", + sum = "h1:RHep2cFKK4PonZJDdEl4GmkabuhbsRMgk/k3uAmxBiA=", + version = "v1.0.0", + ) + go_repository( + name = "com_github_nxadm_tail", + build_file_proto_mode = "disable_global", + importpath = "github.com/nxadm/tail", + sum = "h1:DQuhQpB1tVlglWS2hLQ5OV6B5r8aGxSrPc5Qo6uTN78=", + version = "v1.4.4", + ) + go_repository( + name = "com_github_nytimes_gziphandler", + build_file_proto_mode = "disable_global", + importpath = "github.com/NYTimes/gziphandler", + sum = "h1:lsxEuwrXEAokXB9qhlbKWPpo3KMLZQ5WB5WLQRW1uq0=", + version = "v0.0.0-20170623195520-56545f4a5d46", + ) + go_repository( + name = "com_github_oklog_ulid_v2", + build_file_proto_mode = "disable_global", + importpath = "github.com/oklog/ulid/v2", + sum = "h1:r4fFzBm+bv0wNKNh5eXTwU7i85y5x+uwkxCUTNVQqLc=", + version = "v2.0.2", + ) + go_repository( + name = "com_github_olekukonko_tablewriter", + build_file_proto_mode = "disable_global", + importpath = "github.com/olekukonko/tablewriter", + sum = "h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec=", + version = "v0.0.5", + ) + go_repository( + name = "com_github_onsi_ginkgo", + build_file_proto_mode = "disable_global", + importpath = "github.com/onsi/ginkgo", + sum = "h1:M76yO2HkZASFjXL0HSoZJ1AYEmQxNJmY41Jx1zNUq1Y=", + version = "v1.13.0", + ) + go_repository( + name = "com_github_onsi_ginkgo_v2", + build_file_proto_mode = "disable_global", + importpath = "github.com/onsi/ginkgo/v2", + sum = "h1:+Ig9nvqgS5OBSACXNk15PLdp0U9XPYROt9CFzVdFGIs=", + version = "v2.4.0", + ) + go_repository( + name = "com_github_onsi_gomega", + build_file_proto_mode = "disable_global", + importpath = "github.com/onsi/gomega", + sum = "h1:/oxKu9c2HVap+F3PfKort2Hw5DEU+HGlW8n+tguWsys=", + version = "v1.23.0", + ) + go_repository( + name = "com_github_pelletier_go_toml", + build_file_proto_mode = "disable_global", + importpath = "github.com/pelletier/go-toml", + sum = "h1:T5zMGML61Wp+FlcbWjRDT7yAxhJNAiPPLOFECq181zc=", + version = "v1.2.0", + ) + go_repository( + name = "com_github_pelletier_go_toml_v2", + build_file_proto_mode = "disable_global", + importpath = "github.com/pelletier/go-toml/v2", + sum = "h1:ipoSadvV8oGUjnUbMub59IDPPwfxF694nG/jwbMiyQg=", + version = "v2.0.5", + ) + go_repository( + name = "com_github_peterbourgon_diskv", + build_file_proto_mode = "disable_global", + importpath = "github.com/peterbourgon/diskv", + sum = "h1:UBdAOUP5p4RWqPBg048CAvpKN+vxiaj6gdUUzhl4XmI=", + version = "v2.0.1+incompatible", + ) + go_repository( + name = "com_github_pingcap_errors", + build_file_proto_mode = "disable_global", + importpath = "github.com/pingcap/errors", + sum = "h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4=", + version = "v0.11.4", + ) + go_repository( + name = "com_github_pkg_browser", + build_file_proto_mode = "disable_global", + importpath = "github.com/pkg/browser", + sum = "h1:KoWmjvw+nsYOo29YJK9vDA65RGE3NrOnUtO7a+RF9HU=", + version = "v0.0.0-20210911075715-681adbf594b8", + ) + go_repository( + name = "com_github_pkg_diff", + build_file_proto_mode = "disable_global", + importpath = "github.com/pkg/diff", + sum = "h1:aoZm08cpOy4WuID//EZDgcC4zIxODThtZNPirFr42+A=", + version = "v0.0.0-20210226163009-20ebb0f2a09e", + ) + go_repository( + name = "com_github_pkg_errors", + build_file_proto_mode = "disable_global", + importpath = "github.com/pkg/errors", + sum = "h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=", + version = "v0.9.1", + ) + go_repository( + name = "com_github_pkg_profile", + build_file_proto_mode = "disable_global", + importpath = "github.com/pkg/profile", + sum = "h1:hUDfIISABYI59DyeB3OTay/HxSRwTQ8rB/H83k6r5dM=", + version = "v1.6.0", + ) + go_repository( + name = "com_github_pmezard_go_difflib", + build_file_proto_mode = "disable_global", + importpath = "github.com/pmezard/go-difflib", + sum = "h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=", + version = "v1.0.0", + ) + go_repository( + name = "com_github_prometheus_client_model", + build_file_proto_mode = "disable_global", + importpath = "github.com/prometheus/client_model", + sum = "h1:gQz4mCbXsO+nc9n1hCxHcGA3Zx3Eo+UHZoInFGUIXNM=", + version = "v0.0.0-20190812154241-14fe0d1b01d4", + ) + go_repository( + name = "com_github_pseudomuto_protoc_gen_doc", + build_file_proto_mode = "disable_global", + importpath = "github.com/pseudomuto/protoc-gen-doc", + sum = "h1:Ah259kcrio7Ix1Rhb6u8FCaOkzf9qRBqXnvAufg061w=", + version = "v1.5.1", + ) + go_repository( + name = "com_github_pseudomuto_protokit", + build_file_proto_mode = "disable_global", + importpath = "github.com/pseudomuto/protokit", + sum = "h1:hlnBDcy3YEDXH7kc9gV+NLaN0cDzhDvD1s7Y6FZ8RpM=", + version = "v0.2.0", + ) + go_repository( + name = "com_github_puerkitobio_purell", + build_file_proto_mode = "disable_global", + importpath = "github.com/PuerkitoBio/purell", + sum = "h1:WEQqlqaGbrPkxLJWfBwQmfEAE1Z7ONdDLqrN38tNFfI=", + version = "v1.1.1", + ) + go_repository( + name = "com_github_puerkitobio_urlesc", + build_file_proto_mode = "disable_global", + importpath = "github.com/PuerkitoBio/urlesc", + sum = "h1:d+Bc7a5rLufV/sSk/8dngufqelfh6jnri85riMAaF/M=", + version = "v0.0.0-20170810143723-de5bf2ad4578", + ) + go_repository( + name = "com_github_rivo_uniseg", + build_file_proto_mode = "disable_global", + importpath = "github.com/rivo/uniseg", + sum = "h1:YwD0ulJSJytLpiaWua0sBDusfsCZohxjxzVTYjwxfV8=", + version = "v0.4.2", + ) + go_repository( + name = "com_github_rogpeppe_go_internal", + build_file_proto_mode = "disable_global", + importpath = "github.com/rogpeppe/go-internal", + sum = "h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=", + version = "v1.9.0", + ) + go_repository( + name = "com_github_russross_blackfriday", + build_file_proto_mode = "disable_global", + importpath = "github.com/russross/blackfriday", + sum = "h1:HyvC0ARfnZBqnXwABFeSZHpKvJHJJfPz81GNueLj0oo=", + version = "v1.5.2", + ) + go_repository( + name = "com_github_russross_blackfriday_v2", + build_file_proto_mode = "disable_global", + importpath = "github.com/russross/blackfriday/v2", + sum = "h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=", + version = "v2.1.0", + ) + go_repository( + name = "com_github_ryanuber_columnize", + build_file_proto_mode = "disable_global", + importpath = "github.com/ryanuber/columnize", + sum = "h1:j1Wcmh8OrK4Q7GXY+V7SVSY8nUWQxHW5TkBe7YUl+2s=", + version = "v2.1.0+incompatible", + ) + go_repository( + name = "com_github_schollz_closestmatch", + build_file_proto_mode = "disable_global", + importpath = "github.com/schollz/closestmatch", + sum = "h1:Uel2GXEpJqOWBrlyI+oY9LTiyyjYS17cCYRqP13/SHk=", + version = "v2.1.0+incompatible", + ) + go_repository( + name = "com_github_sclevine_agouti", + build_file_proto_mode = "disable_global", + importpath = "github.com/sclevine/agouti", + sum = "h1:8IBJS6PWz3uTlMP3YBIR5f+KAldcGuOeFkFbUWfBgK4=", + version = "v3.0.0+incompatible", + ) + go_repository( + name = "com_github_sergi_go_diff", + build_file_proto_mode = "disable_global", + importpath = "github.com/sergi/go-diff", + sum = "h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0=", + version = "v1.1.0", + ) + go_repository( + name = "com_github_shopify_goreferrer", + build_file_proto_mode = "disable_global", + importpath = "github.com/Shopify/goreferrer", + sum = "h1:KkH3I3sJuOLP3TjA/dfr4NAY8bghDwnXiU7cTKxQqo0=", + version = "v0.0.0-20220729165902-8cddb4f5de06", + ) + go_repository( + name = "com_github_shurcool_go", + build_file_proto_mode = "disable_global", + importpath = "github.com/shurcooL/go", + sum = "h1:MZM7FHLqUHYI0Y/mQAt3d2aYa0SiNms/hFqC9qJYolM=", + version = "v0.0.0-20180423040247-9e1955d9fb6e", + ) + go_repository( + name = "com_github_shurcool_go_goon", + build_file_proto_mode = "disable_global", + importpath = "github.com/shurcooL/go-goon", + sum = "h1:lRAUE0dIvigSSFAmaM2dfg7OH8T+a8zJ5smEh09a/GI=", + version = "v0.0.0-20210110234559-7585751d9a17", + ) + go_repository( + name = "com_github_shurcool_sanitized_anchor_name", + build_file_proto_mode = "disable_global", + importpath = "github.com/shurcooL/sanitized_anchor_name", + sum = "h1:PdmoCO6wvbs+7yrJyMORt4/BmY5IYyJwS/kOiWx8mHo=", + version = "v1.0.0", + ) + go_repository( + name = "com_github_sirupsen_logrus", + build_file_proto_mode = "disable_global", + importpath = "github.com/sirupsen/logrus", + sum = "h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0=", + version = "v1.9.0", + ) + go_repository( + name = "com_github_smacker_go_tree_sitter", + build_file_proto_mode = "disable_global", + importpath = "github.com/smacker/go-tree-sitter", + sum = "h1:WrsSqod9T70HFyq8hjL6wambOKb4ISUXzFUuNTJHDwo=", + version = "v0.0.0-20220209044044-0d3022e933c3", + ) + go_repository( + name = "com_github_smartystreets_assertions", + build_file_proto_mode = "disable_global", + importpath = "github.com/smartystreets/assertions", + sum = "h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM=", + version = "v0.0.0-20180927180507-b2de0cb4f26d", + ) + go_repository( + name = "com_github_smartystreets_goconvey", + build_file_proto_mode = "disable_global", + importpath = "github.com/smartystreets/goconvey", + sum = "h1:fv0U8FUIMPNf1L9lnHLvLhgicrIVChEkdzIKYqbNC9s=", + version = "v1.6.4", + ) + go_repository( + name = "com_github_sourcegraph_conc", + build_file_proto_mode = "disable_global", + importpath = "github.com/sourcegraph/conc", + sum = "h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo=", + version = "v0.3.0", + ) + go_repository( + name = "com_github_sourcegraph_go_diff", + build_file_proto_mode = "disable_global", + importpath = "github.com/sourcegraph/go-diff", + sum = "h1:11miag7hlORpW7ici5mL7T9PyiEsmVmf+8PFOvJ/ZrA=", + version = "v0.6.2-0.20221123165719-f8cd299c40f3", + ) + go_repository( + name = "com_github_sourcegraph_jsonx", + build_file_proto_mode = "disable_global", + importpath = "github.com/sourcegraph/jsonx", + sum = "h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI=", + version = "v0.0.0-20200629203448-1a936bd500cf", + ) + go_repository( + name = "com_github_sourcegraph_log", + build_file_proto_mode = "disable_global", + importpath = "github.com/sourcegraph/log", + sum = "h1:hgZHfGYG3KMlDDfACuPgzhMIaEjblCqZ+YltcPgd0tw=", + version = "v0.0.0-20221206163500-7d93c6ad7037", + ) + go_repository( + name = "com_github_sourcegraph_scip", + build_file_proto_mode = "disable_global", + importpath = "github.com/sourcegraph/scip", + sum = "h1:fWPxLkDObzzKTGe9vb6wpzK0FYkwcfSxmxUBvAOc8aw=", + version = "v0.2.4-0.20221213205653-aa0e511dcfef", + ) + go_repository( + name = "com_github_sourcegraph_sourcegraph_lib", + build_file_proto_mode = "disable_global", + importpath = "github.com/sourcegraph/sourcegraph/lib", + sum = "h1:NJyyvyYU/DNZmNFui8ktnHke3hS/PYLmDUbWNHSHKuQ=", + version = "v0.0.0-20230316093010-26299ec302d0", + ) + go_repository( + name = "com_github_spf13_afero", + build_file_proto_mode = "disable_global", + importpath = "github.com/spf13/afero", + sum = "h1:j49Hj62F0n+DaZ1dDCvhABaPNSGNkt32oRFxI33IEMw=", + version = "v1.9.2", + ) + go_repository( + name = "com_github_spf13_cast", + build_file_proto_mode = "disable_global", + importpath = "github.com/spf13/cast", + sum = "h1:oget//CVOEoFewqQxwr0Ej5yjygnqGkvggSE/gB35Q8=", + version = "v1.3.0", + ) + go_repository( + name = "com_github_spf13_cobra", + build_file_proto_mode = "disable_global", + importpath = "github.com/spf13/cobra", + sum = "h1:42a0n6jwCot1pUmomAp4T7DeMD+20LFv4Q54pxLf2LI=", + version = "v1.6.0", + ) + go_repository( + name = "com_github_spf13_jwalterweatherman", + build_file_proto_mode = "disable_global", + importpath = "github.com/spf13/jwalterweatherman", + sum = "h1:XHEdyB+EcvlqZamSM4ZOMGlc93t6AcsBEu9Gc1vn7yk=", + version = "v1.0.0", + ) + go_repository( + name = "com_github_spf13_pflag", + build_file_proto_mode = "disable_global", + importpath = "github.com/spf13/pflag", + sum = "h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=", + version = "v1.0.5", + ) + go_repository( + name = "com_github_spf13_viper", + build_file_proto_mode = "disable_global", + importpath = "github.com/spf13/viper", + sum = "h1:VUFqw5KcqRf7i70GOzW7N+Q7+gxVBkSSqiXB12+JQ4M=", + version = "v1.3.2", + ) + go_repository( + name = "com_github_ssor_bom", + build_file_proto_mode = "disable_global", + importpath = "github.com/ssor/bom", + sum = "h1:pvbZ0lM0XWPBqUKqFU8cmavspvIl9nulOYwdy6IFRRo=", + version = "v0.0.0-20170718123548-6386211fdfcf", + ) + go_repository( + name = "com_github_stoewer_go_strcase", + build_file_proto_mode = "disable_global", + importpath = "github.com/stoewer/go-strcase", + sum = "h1:Z2iHWqGXH00XYgqDmNgQbIBxf3wrNq0F3feEy0ainaU=", + version = "v1.2.0", + ) + go_repository( + name = "com_github_stretchr_objx", + build_file_proto_mode = "disable_global", + importpath = "github.com/stretchr/objx", + sum = "h1:1zr/of2m5FGMsad5YfcqgdqdWrIhu+EBEJRhR1U7z/c=", + version = "v0.5.0", + ) + go_repository( + name = "com_github_stretchr_testify", + build_file_proto_mode = "disable_global", + importpath = "github.com/stretchr/testify", + sum = "h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=", + version = "v1.8.1", + ) + go_repository( + name = "com_github_tdewolff_minify_v2", + build_file_proto_mode = "disable_global", + importpath = "github.com/tdewolff/minify/v2", + sum = "h1:kejsHQMM17n6/gwdw53qsi6lg0TGddZADVyQOz1KMdE=", + version = "v2.12.4", + ) + go_repository( + name = "com_github_tdewolff_parse_v2", + build_file_proto_mode = "disable_global", + importpath = "github.com/tdewolff/parse/v2", + sum = "h1:KCkDvNUMof10e3QExio9OPZJT8SbdKojLBumw8YZycQ=", + version = "v2.6.4", + ) + go_repository( + name = "com_github_ugorji_go", + build_file_proto_mode = "disable_global", + importpath = "github.com/ugorji/go", + sum = "h1:/68gy2h+1mWMrwZFeD1kQialdSzAb432dtpeJ42ovdo=", + version = "v1.1.7", + ) + go_repository( + name = "com_github_ugorji_go_codec", + build_file_proto_mode = "disable_global", + importpath = "github.com/ugorji/go/codec", + sum = "h1:YPXUKf7fYbp/y8xloBqZOw2qaVggbfwMlI8WM3wZUJ0=", + version = "v1.2.7", + ) + go_repository( + name = "com_github_urfave_cli_v2", + build_file_proto_mode = "disable_global", + importpath = "github.com/urfave/cli/v2", + sum = "h1:YHDQ46s3VghFHFf1DdF+Sh7H4RqhcM+t0TmZRJx4oJY=", + version = "v2.23.7", + ) + go_repository( + name = "com_github_urfave_negroni", + build_file_proto_mode = "disable_global", + importpath = "github.com/urfave/negroni", + sum = "h1:kIimOitoypq34K7TG7DUaJ9kq/N4Ofuwi1sjz0KipXc=", + version = "v1.0.0", + ) + go_repository( + name = "com_github_valyala_bytebufferpool", + build_file_proto_mode = "disable_global", + importpath = "github.com/valyala/bytebufferpool", + sum = "h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=", + version = "v1.0.0", + ) + go_repository( + name = "com_github_valyala_fasthttp", + build_file_proto_mode = "disable_global", + importpath = "github.com/valyala/fasthttp", + sum = "h1:CRq/00MfruPGFLTQKY8b+8SfdK60TxNztjRMnH0t1Yc=", + version = "v1.40.0", + ) + go_repository( + name = "com_github_valyala_fasttemplate", + build_file_proto_mode = "disable_global", + importpath = "github.com/valyala/fasttemplate", + sum = "h1:TVEnxayobAdVkhQfrfes2IzOB6o+z4roRkPF52WA1u4=", + version = "v1.2.1", + ) + go_repository( + name = "com_github_valyala_tcplisten", + build_file_proto_mode = "disable_global", + importpath = "github.com/valyala/tcplisten", + sum = "h1:0R4NLDRDZX6JcmhJgXi5E4b8Wg84ihbmUKp/GvSPEzc=", + version = "v0.0.0-20161114210144-ceec8f93295a", + ) + go_repository( + name = "com_github_vmihailenco_msgpack_v5", + build_file_proto_mode = "disable_global", + importpath = "github.com/vmihailenco/msgpack/v5", + sum = "h1:5gO0H1iULLWGhs2H5tbAHIZTV8/cYafcFOr9znI5mJU=", + version = "v5.3.5", + ) + go_repository( + name = "com_github_vmihailenco_tagparser_v2", + build_file_proto_mode = "disable_global", + importpath = "github.com/vmihailenco/tagparser/v2", + sum = "h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g=", + version = "v2.0.0", + ) + go_repository( + name = "com_github_xeipuuv_gojsonpointer", + build_file_proto_mode = "disable_global", + importpath = "github.com/xeipuuv/gojsonpointer", + sum = "h1:zGWFAtiMcyryUHoUjUJX0/lt1H2+i2Ka2n+D3DImSNo=", + version = "v0.0.0-20190905194746-02993c407bfb", + ) + go_repository( + name = "com_github_xeipuuv_gojsonreference", + build_file_proto_mode = "disable_global", + importpath = "github.com/xeipuuv/gojsonreference", + sum = "h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0=", + version = "v0.0.0-20180127040603-bd5ef7bd5415", + ) + go_repository( + name = "com_github_xeipuuv_gojsonschema", + build_file_proto_mode = "disable_global", + importpath = "github.com/xeipuuv/gojsonschema", + sum = "h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74=", + version = "v1.2.0", + ) + go_repository( + name = "com_github_xordataexchange_crypt", + build_file_proto_mode = "disable_global", + importpath = "github.com/xordataexchange/crypt", + sum = "h1:ESFSdwYZvkeru3RtdrYueztKhOBCSAAzS4Gf+k0tEow=", + version = "v0.0.3-0.20170626215501-b2862e3d0a77", + ) + go_repository( + name = "com_github_xrash_smetrics", + build_file_proto_mode = "disable_global", + importpath = "github.com/xrash/smetrics", + sum = "h1:bAn7/zixMGCfxrRTfdpNzjtPYqr8smhKouy9mxVdGPU=", + version = "v0.0.0-20201216005158-039620a65673", + ) + go_repository( + name = "com_github_yalp_jsonpath", + build_file_proto_mode = "disable_global", + importpath = "github.com/yalp/jsonpath", + sum = "h1:6fRhSjgLCkTD3JnJxvaJ4Sj+TYblw757bqYgZaOq5ZY=", + version = "v0.0.0-20180802001716-5cc68e5049a0", + ) + go_repository( + name = "com_github_yosssi_ace", + build_file_proto_mode = "disable_global", + importpath = "github.com/yosssi/ace", + sum = "h1:tUkIP/BLdKqrlrPwcmH0shwEEhTRHoGnc1wFIWmaBUA=", + version = "v0.0.5", + ) + go_repository( + name = "com_github_yudai_gojsondiff", + build_file_proto_mode = "disable_global", + importpath = "github.com/yudai/gojsondiff", + sum = "h1:27cbfqXLVEJ1o8I6v3y9lg8Ydm53EKqHXAOMxEGlCOA=", + version = "v1.0.0", + ) + go_repository( + name = "com_github_yudai_golcs", + build_file_proto_mode = "disable_global", + importpath = "github.com/yudai/golcs", + sum = "h1:BHyfKlQyqbsFN5p3IfnEUduWvb9is428/nNb5L3U01M=", + version = "v0.0.0-20170316035057-ecda9a501e82", + ) + go_repository( + name = "com_github_yudai_pp", + build_file_proto_mode = "disable_global", + importpath = "github.com/yudai/pp", + sum = "h1:Q4//iY4pNF6yPLZIigmvcl7k/bPgrcTPIFIcmawg5bI=", + version = "v2.0.1+incompatible", + ) + go_repository( + name = "com_github_yuin_goldmark", + build_file_proto_mode = "disable_global", + importpath = "github.com/yuin/goldmark", + sum = "h1:ALmeCk/px5FSm1MAcFBAsVKZjDuMVj8Tm7FFIlMJnqU=", + version = "v1.5.2", + ) + go_repository( + name = "com_github_yuin_goldmark_emoji", + build_file_proto_mode = "disable_global", + importpath = "github.com/yuin/goldmark-emoji", + sum = "h1:ctuWEyzGBwiucEqxzwe0SOYDXPAucOrE9NQC18Wa1os=", + version = "v1.0.1", + ) + go_repository( + name = "com_google_cloud_go", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go", + sum = "h1:qkj22L7bgkl6vIeZDlOY2po43Mx/TIa2Wsa7VR+PEww=", + version = "v0.107.0", + ) + go_repository( + name = "com_google_cloud_go_accessapproval", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/accessapproval", + sum = "h1:/nTivgnV/n1CaAeo+ekGexTYUsKEU9jUVkoY5359+3Q=", + version = "v1.5.0", + ) + go_repository( + name = "com_google_cloud_go_accesscontextmanager", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/accesscontextmanager", + sum = "h1:CFhNhU7pcD11cuDkQdrE6PQJgv0EXNKNv06jIzbLlCU=", + version = "v1.4.0", + ) + go_repository( + name = "com_google_cloud_go_aiplatform", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/aiplatform", + sum = "h1:DBi3Jk9XjCJ4pkkLM4NqKgj3ozUL1wq4l+d3/jTGXAI=", + version = "v1.27.0", + ) + go_repository( + name = "com_google_cloud_go_analytics", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/analytics", + sum = "h1:NKw6PpQi6V1O+KsjuTd+bhip9d0REYu4NevC45vtGp8=", + version = "v0.12.0", + ) + go_repository( + name = "com_google_cloud_go_apigateway", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/apigateway", + sum = "h1:IIoXKR7FKrEAQhMTz5hK2wiDz2WNFHS7eVr/L1lE/rM=", + version = "v1.4.0", + ) + go_repository( + name = "com_google_cloud_go_apigeeconnect", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/apigeeconnect", + sum = "h1:AONoTYJviyv1vS4IkvWzq69gEVdvHx35wKXc+e6wjZQ=", + version = "v1.4.0", + ) + go_repository( + name = "com_google_cloud_go_apigeeregistry", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/apigeeregistry", + sum = "h1:Av+wedLP6pM8NsLruknv/RFCE/5VVavOhZ8j722vBxg=", + version = "v0.4.0", + ) + go_repository( + name = "com_google_cloud_go_apikeys", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/apikeys", + sum = "h1:d+t1B9U1Ze3LmiRYdSVhNrcRlU6coLvPzNDkqYVuHoc=", + version = "v0.4.0", + ) + go_repository( + name = "com_google_cloud_go_appengine", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/appengine", + sum = "h1:lmG+O5oaR9xNwaRBwE2XoMhwQHsHql5IoiGr1ptdDwU=", + version = "v1.5.0", + ) + go_repository( + name = "com_google_cloud_go_area120", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/area120", + sum = "h1:TCMhwWEWhCn8d44/Zs7UCICTWje9j3HuV6nVGMjdpYw=", + version = "v0.6.0", + ) + go_repository( + name = "com_google_cloud_go_artifactregistry", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/artifactregistry", + sum = "h1:3d0LRAU1K6vfqCahhl9fx2oGHcq+s5gftdix4v8Ibrc=", + version = "v1.9.0", + ) + go_repository( + name = "com_google_cloud_go_asset", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/asset", + sum = "h1:aCrlaLGJWTODJX4G56ZYzJefITKEWNfbjjtHSzWpxW0=", + version = "v1.10.0", + ) + go_repository( + name = "com_google_cloud_go_assuredworkloads", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/assuredworkloads", + sum = "h1:hhIdCOowsT1GG5eMCIA0OwK6USRuYTou/1ZeNxCSRtA=", + version = "v1.9.0", + ) + go_repository( + name = "com_google_cloud_go_automl", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/automl", + sum = "h1:BMioyXSbg7d7xLibn47cs0elW6RT780IUWr42W8rp2Q=", + version = "v1.8.0", + ) + go_repository( + name = "com_google_cloud_go_baremetalsolution", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/baremetalsolution", + sum = "h1:g9KO6SkakcYPcc/XjAzeuUrEOXlYPnMpuiaywYaGrmQ=", + version = "v0.4.0", + ) + go_repository( + name = "com_google_cloud_go_batch", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/batch", + sum = "h1:1jvEBY55OH4Sd2FxEXQfxGExFWov1A/IaRe+Z5Z71Fw=", + version = "v0.4.0", + ) + go_repository( + name = "com_google_cloud_go_beyondcorp", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/beyondcorp", + sum = "h1:w+4kThysgl0JiKshi2MKDCg2NZgOyqOI0wq2eBZyrzA=", + version = "v0.3.0", + ) + go_repository( + name = "com_google_cloud_go_bigquery", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/bigquery", + sum = "h1:Wi4dITi+cf9VYp4VH2T9O41w0kCW0uQTELq2Z6tukN0=", + version = "v1.44.0", + ) + go_repository( + name = "com_google_cloud_go_billing", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/billing", + sum = "h1:Xkii76HWELHwBtkQVZvqmSo9GTr0O+tIbRNnMcGdlg4=", + version = "v1.7.0", + ) + go_repository( + name = "com_google_cloud_go_binaryauthorization", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/binaryauthorization", + sum = "h1:pL70vXWn9TitQYXBWTK2abHl2JHLwkFRjYw6VflRqEA=", + version = "v1.4.0", + ) + go_repository( + name = "com_google_cloud_go_certificatemanager", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/certificatemanager", + sum = "h1:tzbR4UHBbgsewMWUD93JHi8EBi/gHBoSAcY1/sThFGk=", + version = "v1.4.0", + ) + go_repository( + name = "com_google_cloud_go_channel", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/channel", + sum = "h1:pNuUlZx0Jb0Ts9P312bmNMuH5IiFWIR4RUtLb70Ke5s=", + version = "v1.9.0", + ) + go_repository( + name = "com_google_cloud_go_cloudbuild", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/cloudbuild", + sum = "h1:TAAmCmAlOJ4uNBu6zwAjwhyl/7fLHHxIEazVhr3QBbQ=", + version = "v1.4.0", + ) + go_repository( + name = "com_google_cloud_go_clouddms", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/clouddms", + sum = "h1:UhzHIlgFfMr6luVYVNydw/pl9/U5kgtjCMJHnSvoVws=", + version = "v1.4.0", + ) + go_repository( + name = "com_google_cloud_go_cloudtasks", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/cloudtasks", + sum = "h1:faUiUgXjW8yVZ7XMnKHKm1WE4OldPBUWWfIRN/3z1dc=", + version = "v1.8.0", + ) + go_repository( + name = "com_google_cloud_go_compute", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/compute", + sum = "h1:FEigFqoDbys2cvFkZ9Fjq4gnHBP55anJ0yQyau2f9oY=", + version = "v1.18.0", + ) + go_repository( + name = "com_google_cloud_go_compute_metadata", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/compute/metadata", + sum = "h1:mg4jlk7mCAj6xXp9UJ4fjI9VUI5rubuGBW5aJ7UnBMY=", + version = "v0.2.3", + ) + go_repository( + name = "com_google_cloud_go_contactcenterinsights", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/contactcenterinsights", + sum = "h1:tTQLI/ZvguUf9Hv+36BkG2+/PeC8Ol1q4pBW+tgCx0A=", + version = "v1.4.0", + ) + go_repository( + name = "com_google_cloud_go_container", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/container", + sum = "h1:nbEK/59GyDRKKlo1SqpohY1TK8LmJ2XNcvS9Gyom2A0=", + version = "v1.7.0", + ) + go_repository( + name = "com_google_cloud_go_containeranalysis", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/containeranalysis", + sum = "h1:2824iym832ljKdVpCBnpqm5K94YT/uHTVhNF+dRTXPI=", + version = "v0.6.0", + ) + go_repository( + name = "com_google_cloud_go_datacatalog", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/datacatalog", + sum = "h1:6kZ4RIOW/uT7QWC5SfPfq/G8sYzr/v+UOmOAxy4Z1TE=", + version = "v1.8.0", + ) + go_repository( + name = "com_google_cloud_go_dataflow", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/dataflow", + sum = "h1:CW3541Fm7KPTyZjJdnX6NtaGXYFn5XbFC5UcjgALKvU=", + version = "v0.7.0", + ) + go_repository( + name = "com_google_cloud_go_dataform", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/dataform", + sum = "h1:vLwowLF2ZB5J5gqiZCzv076lDI/Rd7zYQQFu5XO1PSg=", + version = "v0.5.0", + ) + go_repository( + name = "com_google_cloud_go_datafusion", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/datafusion", + sum = "h1:j5m2hjWovTZDTQak4MJeXAR9yN7O+zMfULnjGw/OOLg=", + version = "v1.5.0", + ) + go_repository( + name = "com_google_cloud_go_datalabeling", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/datalabeling", + sum = "h1:dp8jOF21n/7jwgo/uuA0RN8hvLcKO4q6s/yvwevs2ZM=", + version = "v0.6.0", + ) + go_repository( + name = "com_google_cloud_go_dataplex", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/dataplex", + sum = "h1:cNxeA2DiWliQGi21kPRqnVeQ5xFhNoEjPRt1400Pm8Y=", + version = "v1.4.0", + ) + go_repository( + name = "com_google_cloud_go_dataproc", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/dataproc", + sum = "h1:gVOqNmElfa6n/ccG/QDlfurMWwrK3ezvy2b2eDoCmS0=", + version = "v1.8.0", + ) + go_repository( + name = "com_google_cloud_go_dataqna", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/dataqna", + sum = "h1:gx9jr41ytcA3dXkbbd409euEaWtofCVXYBvJz3iYm18=", + version = "v0.6.0", + ) + go_repository( + name = "com_google_cloud_go_datastore", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/datastore", + sum = "h1:4siQRf4zTiAVt/oeH4GureGkApgb2vtPQAtOmhpqQwE=", + version = "v1.10.0", + ) + go_repository( + name = "com_google_cloud_go_datastream", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/datastream", + sum = "h1:PgIgbhedBtYBU6POGXFMn2uSl9vpqubc3ewTNdcU8Mk=", + version = "v1.5.0", + ) + go_repository( + name = "com_google_cloud_go_deploy", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/deploy", + sum = "h1:kI6dxt8Ml0is/x7YZjLveTvR7YPzXAUD/8wQZ2nH5zA=", + version = "v1.5.0", + ) + go_repository( + name = "com_google_cloud_go_dialogflow", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/dialogflow", + sum = "h1:Opy6fM2IV9ecQOXkce0JByjBVg8+4X+1AbTAQLbgrCg=", + version = "v1.29.0", + ) + go_repository( + name = "com_google_cloud_go_dlp", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/dlp", + sum = "h1:9I4BYeJSVKoSKgjr70fLdRDumqcUeVmHV4fd5f9LR6Y=", + version = "v1.7.0", + ) + go_repository( + name = "com_google_cloud_go_documentai", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/documentai", + sum = "h1:jfq09Fdjtnpnmt/MLyf6A3DM3ynb8B2na0K+vSXvpFM=", + version = "v1.10.0", + ) + go_repository( + name = "com_google_cloud_go_domains", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/domains", + sum = "h1:pu3JIgC1rswIqi5romW0JgNO6CTUydLYX8zyjiAvO1c=", + version = "v0.7.0", + ) + go_repository( + name = "com_google_cloud_go_edgecontainer", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/edgecontainer", + sum = "h1:hd6J2n5dBBRuAqnNUEsKWrp6XNPKsaxwwIyzOPZTokk=", + version = "v0.2.0", + ) + go_repository( + name = "com_google_cloud_go_errorreporting", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/errorreporting", + sum = "h1:kj1XEWMu8P0qlLhm3FwcaFsUvXChV/OraZwA70trRR0=", + version = "v0.3.0", + ) + go_repository( + name = "com_google_cloud_go_essentialcontacts", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/essentialcontacts", + sum = "h1:b6csrQXCHKQmfo9h3dG/pHyoEh+fQG1Yg78a53LAviY=", + version = "v1.4.0", + ) + go_repository( + name = "com_google_cloud_go_eventarc", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/eventarc", + sum = "h1:AgCqrmMMIcel5WWKkzz5EkCUKC3Rl5LNMMYsS+LvsI0=", + version = "v1.8.0", + ) + go_repository( + name = "com_google_cloud_go_filestore", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/filestore", + sum = "h1:yjKOpzvqtDmL5AXbKttLc8j0hL20kuC1qPdy5HPcxp0=", + version = "v1.4.0", + ) + go_repository( + name = "com_google_cloud_go_firestore", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/firestore", + sum = "h1:IBlRyxgGySXu5VuW0RgGFlTtLukSnNkpDiEOMkQkmpA=", + version = "v1.9.0", + ) + go_repository( + name = "com_google_cloud_go_functions", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/functions", + sum = "h1:35tgv1fQOtvKqH/uxJMzX3w6usneJ0zXpsFr9KAVhNE=", + version = "v1.9.0", + ) + go_repository( + name = "com_google_cloud_go_gaming", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/gaming", + sum = "h1:97OAEQtDazAJD7yh/kvQdSCQuTKdR0O+qWAJBZJ4xiA=", + version = "v1.8.0", + ) + go_repository( + name = "com_google_cloud_go_gkebackup", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/gkebackup", + sum = "h1:4K+jiv4ocqt1niN8q5Imd8imRoXBHTrdnJVt/uFFxF4=", + version = "v0.3.0", + ) + go_repository( + name = "com_google_cloud_go_gkeconnect", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/gkeconnect", + sum = "h1:zAcvDa04tTnGdu6TEZewaLN2tdMtUOJJ7fEceULjguA=", + version = "v0.6.0", + ) + go_repository( + name = "com_google_cloud_go_gkehub", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/gkehub", + sum = "h1:JTcTaYQRGsVm+qkah7WzHb6e9sf1C0laYdRPn9aN+vg=", + version = "v0.10.0", + ) + go_repository( + name = "com_google_cloud_go_gkemulticloud", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/gkemulticloud", + sum = "h1:8F1NhJj8ucNj7lK51UZMtAjSWTgP1zO18XF6vkfiPPU=", + version = "v0.4.0", + ) + go_repository( + name = "com_google_cloud_go_gsuiteaddons", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/gsuiteaddons", + sum = "h1:TGT2oGmO5q3VH6SjcrlgPUWI0njhYv4kywLm6jag0to=", + version = "v1.4.0", + ) + go_repository( + name = "com_google_cloud_go_iam", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/iam", + sum = "h1:DRtTY29b75ciH6Ov1PHb4/iat2CLCvrOm40Q0a6DFpE=", + version = "v0.12.0", + ) + go_repository( + name = "com_google_cloud_go_iap", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/iap", + sum = "h1:BGEXovwejOCt1zDk8hXq0bOhhRu9haXKWXXXp2B4wBM=", + version = "v1.5.0", + ) + go_repository( + name = "com_google_cloud_go_ids", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/ids", + sum = "h1:LncHK4HHucb5Du310X8XH9/ICtMwZ2PCfK0ScjWiJoY=", + version = "v1.2.0", + ) + go_repository( + name = "com_google_cloud_go_iot", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/iot", + sum = "h1:Y9+oZT9jD4GUZzORXTU45XsnQrhxmDT+TFbPil6pRVQ=", + version = "v1.4.0", + ) + go_repository( + name = "com_google_cloud_go_kms", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/kms", + sum = "h1:OWRZzrPmOZUzurjI2FBGtgY2mB1WaJkqhw6oIwSj0Yg=", + version = "v1.6.0", + ) + go_repository( + name = "com_google_cloud_go_language", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/language", + sum = "h1:3Wa+IUMamL4JH3Zd3cDZUHpwyqplTACt6UZKRD2eCL4=", + version = "v1.8.0", + ) + go_repository( + name = "com_google_cloud_go_lifesciences", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/lifesciences", + sum = "h1:tIqhivE2LMVYkX0BLgG7xL64oNpDaFFI7teunglt1tI=", + version = "v0.6.0", + ) + go_repository( + name = "com_google_cloud_go_logging", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/logging", + sum = "h1:ZBsZK+JG+oCDT+vaxwqF2egKNRjz8soXiS6Xv79benI=", + version = "v1.6.1", + ) + go_repository( + name = "com_google_cloud_go_longrunning", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/longrunning", + sum = "h1:NjljC+FYPV3uh5/OwWT6pVU+doBqMg2x/rZlE+CamDs=", + version = "v0.3.0", + ) + go_repository( + name = "com_google_cloud_go_managedidentities", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/managedidentities", + sum = "h1:3Kdajn6X25yWQFhFCErmKSYTSvkEd3chJROny//F1A0=", + version = "v1.4.0", + ) + go_repository( + name = "com_google_cloud_go_maps", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/maps", + sum = "h1:kLReRbclTgJefw2fcCbdLPLhPj0U6UUWN10ldG8sdOU=", + version = "v0.1.0", + ) + go_repository( + name = "com_google_cloud_go_mediatranslation", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/mediatranslation", + sum = "h1:qAJzpxmEX+SeND10Y/4868L5wfZpo4Y3BIEnIieP4dk=", + version = "v0.6.0", + ) + go_repository( + name = "com_google_cloud_go_memcache", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/memcache", + sum = "h1:yLxUzJkZVSH2kPaHut7k+7sbIBFpvSh1LW9qjM2JDjA=", + version = "v1.7.0", + ) + go_repository( + name = "com_google_cloud_go_metastore", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/metastore", + sum = "h1:3KcShzqWdqxrDEXIBWpYJpOOrgpDj+HlBi07Grot49Y=", + version = "v1.8.0", + ) + go_repository( + name = "com_google_cloud_go_monitoring", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/monitoring", + sum = "h1:c9riaGSPQ4dUKWB+M1Fl0N+iLxstMbCktdEwYSPGDvA=", + version = "v1.8.0", + ) + go_repository( + name = "com_google_cloud_go_networkconnectivity", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/networkconnectivity", + sum = "h1:BVdIKaI68bihnXGdCVL89Jsg9kq2kg+II30fjVqo62E=", + version = "v1.7.0", + ) + go_repository( + name = "com_google_cloud_go_networkmanagement", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/networkmanagement", + sum = "h1:mDHA3CDW00imTvC5RW6aMGsD1bH+FtKwZm/52BxaiMg=", + version = "v1.5.0", + ) + go_repository( + name = "com_google_cloud_go_networksecurity", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/networksecurity", + sum = "h1:qDEX/3sipg9dS5JYsAY+YvgTjPR63cozzAWop8oZS94=", + version = "v0.6.0", + ) + go_repository( + name = "com_google_cloud_go_notebooks", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/notebooks", + sum = "h1:AC8RPjNvel3ExgXjO1YOAz+teg9+j+89TNxa7pIZfww=", + version = "v1.5.0", + ) + go_repository( + name = "com_google_cloud_go_optimization", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/optimization", + sum = "h1:7PxOq9VTT7TMib/6dMoWpMvWS2E4dJEvtYzjvBreaec=", + version = "v1.2.0", + ) + go_repository( + name = "com_google_cloud_go_orchestration", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/orchestration", + sum = "h1:39d6tqvNjd/wsSub1Bn4cEmrYcet5Ur6xpaN+SxOxtY=", + version = "v1.4.0", + ) + go_repository( + name = "com_google_cloud_go_orgpolicy", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/orgpolicy", + sum = "h1:erF5PHqDZb6FeFrUHiYj2JK2BMhsk8CyAg4V4amJ3rE=", + version = "v1.5.0", + ) + go_repository( + name = "com_google_cloud_go_osconfig", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/osconfig", + sum = "h1:NO0RouqCOM7M2S85Eal6urMSSipWwHU8evzwS+siqUI=", + version = "v1.10.0", + ) + go_repository( + name = "com_google_cloud_go_oslogin", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/oslogin", + sum = "h1:pKGDPfeZHDybtw48WsnVLjoIPMi9Kw62kUE5TXCLCN4=", + version = "v1.7.0", + ) + go_repository( + name = "com_google_cloud_go_phishingprotection", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/phishingprotection", + sum = "h1:OrwHLSRSZyaiOt3tnY33dsKSedxbMzsXvqB21okItNQ=", + version = "v0.6.0", + ) + go_repository( + name = "com_google_cloud_go_policytroubleshooter", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/policytroubleshooter", + sum = "h1:NQklJuOUoz1BPP+Epjw81COx7IISWslkZubz/1i0UN8=", + version = "v1.4.0", + ) + go_repository( + name = "com_google_cloud_go_privatecatalog", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/privatecatalog", + sum = "h1:Vz86uiHCtNGm1DeC32HeG2VXmOq5JRYA3VRPf8ZEcSg=", + version = "v0.6.0", + ) + go_repository( + name = "com_google_cloud_go_pubsub", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/pubsub", + sum = "h1:q+J/Nfr6Qx4RQeu3rJcnN48SNC0qzlYzSeqkPq93VHs=", + version = "v1.27.1", + ) + go_repository( + name = "com_google_cloud_go_pubsublite", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/pubsublite", + sum = "h1:iqrD8vp3giTb7hI1q4TQQGj77cj8zzgmMPsTZtLnprM=", + version = "v1.5.0", + ) + go_repository( + name = "com_google_cloud_go_recaptchaenterprise_v2", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/recaptchaenterprise/v2", + sum = "h1:UqzFfb/WvhwXGDF1eQtdHLrmni+iByZXY4h3w9Kdyv8=", + version = "v2.5.0", + ) + go_repository( + name = "com_google_cloud_go_recommendationengine", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/recommendationengine", + sum = "h1:6w+WxPf2LmUEqX0YyvfCoYb8aBYOcbIV25Vg6R0FLGw=", + version = "v0.6.0", + ) + go_repository( + name = "com_google_cloud_go_recommender", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/recommender", + sum = "h1:9kMZQGeYfcOD/RtZfcNKGKtoex3DdoB4zRgYU/WaIwE=", + version = "v1.8.0", + ) + go_repository( + name = "com_google_cloud_go_redis", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/redis", + sum = "h1:/zTwwBKIAD2DEWTrXZp8WD9yD/gntReF/HkPssVYd0U=", + version = "v1.10.0", + ) + go_repository( + name = "com_google_cloud_go_resourcemanager", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/resourcemanager", + sum = "h1:NDao6CHMwEZIaNsdWy+tuvHaavNeGP06o1tgrR0kLvU=", + version = "v1.4.0", + ) + go_repository( + name = "com_google_cloud_go_resourcesettings", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/resourcesettings", + sum = "h1:eTzOwB13WrfF0kuzG2ZXCfB3TLunSHBur4s+HFU6uSM=", + version = "v1.4.0", + ) + go_repository( + name = "com_google_cloud_go_retail", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/retail", + sum = "h1:N9fa//ecFUOEPsW/6mJHfcapPV0wBSwIUwpVZB7MQ3o=", + version = "v1.11.0", + ) + go_repository( + name = "com_google_cloud_go_run", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/run", + sum = "h1:AWPuzU7Xtaj3Jf+QarDWIs6AJ5hM1VFQ+F6Q+VZ6OT4=", + version = "v0.3.0", + ) + go_repository( + name = "com_google_cloud_go_scheduler", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/scheduler", + sum = "h1:K/mxOewgHGeKuATUJNGylT75Mhtjmx1TOkKukATqMT8=", + version = "v1.7.0", + ) + go_repository( + name = "com_google_cloud_go_secretmanager", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/secretmanager", + sum = "h1:xE6uXljAC1kCR8iadt9+/blg1fvSbmenlsDN4fT9gqw=", + version = "v1.9.0", + ) + go_repository( + name = "com_google_cloud_go_security", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/security", + sum = "h1:KSKzzJMyUoMRQzcz7azIgqAUqxo7rmQ5rYvimMhikqg=", + version = "v1.10.0", + ) + go_repository( + name = "com_google_cloud_go_securitycenter", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/securitycenter", + sum = "h1:QTVtk/Reqnx2bVIZtJKm1+mpfmwRwymmNvlaFez7fQY=", + version = "v1.16.0", + ) + go_repository( + name = "com_google_cloud_go_servicecontrol", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/servicecontrol", + sum = "h1:ImIzbOu6y4jL6ob65I++QzvqgFaoAKgHOG+RU9/c4y8=", + version = "v1.5.0", + ) + go_repository( + name = "com_google_cloud_go_servicedirectory", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/servicedirectory", + sum = "h1:f7M8IMcVzO3T425AqlZbP3yLzeipsBHtRza8vVFYMhQ=", + version = "v1.7.0", + ) + go_repository( + name = "com_google_cloud_go_servicemanagement", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/servicemanagement", + sum = "h1:TpkCO5M7dhKSy1bKUD9o/sSEW/U1Gtx7opA1fsiMx0c=", + version = "v1.5.0", + ) + go_repository( + name = "com_google_cloud_go_serviceusage", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/serviceusage", + sum = "h1:b0EwJxPJLpavSljMQh0RcdHsUrr5DQ+Nelt/3BAs5ro=", + version = "v1.4.0", + ) + go_repository( + name = "com_google_cloud_go_shell", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/shell", + sum = "h1:b1LFhFBgKsG252inyhtmsUUZwchqSz3WTvAIf3JFo4g=", + version = "v1.4.0", + ) + go_repository( + name = "com_google_cloud_go_spanner", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/spanner", + sum = "h1:NvdTpRwf7DTegbfFdPjAWyD7bOVu0VeMqcvR9aCQCAc=", + version = "v1.41.0", + ) + go_repository( + name = "com_google_cloud_go_speech", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/speech", + sum = "h1:yK0ocnFH4Wsf0cMdUyndJQ/hPv02oTJOxzi6AgpBy4s=", + version = "v1.9.0", + ) + go_repository( + name = "com_google_cloud_go_storage", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/storage", + sum = "h1:DLrIZ6xkeZX6K70fU/boWx5INJumt6f+nwwWSHXzzGY=", + version = "v1.28.0", + ) + go_repository( + name = "com_google_cloud_go_storagetransfer", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/storagetransfer", + sum = "h1:fUe3OydbbvHcAYp07xY+2UpH4AermGbmnm7qdEj3tGE=", + version = "v1.6.0", + ) + go_repository( + name = "com_google_cloud_go_talent", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/talent", + sum = "h1:MrekAGxLqAeAol4Sc0allOVqUGO8j+Iim8NMvpiD7tM=", + version = "v1.4.0", + ) + go_repository( + name = "com_google_cloud_go_texttospeech", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/texttospeech", + sum = "h1:ccPiHgTewxgyAeCWgQWvZvrLmbfQSFABTMAfrSPLPyY=", + version = "v1.5.0", + ) + go_repository( + name = "com_google_cloud_go_tpu", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/tpu", + sum = "h1:ztIdKoma1Xob2qm6QwNh4Xi9/e7N3IfvtwG5AcNsj1g=", + version = "v1.4.0", + ) + go_repository( + name = "com_google_cloud_go_trace", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/trace", + sum = "h1:qO9eLn2esajC9sxpqp1YKX37nXC3L4BfGnPS0Cx9dYo=", + version = "v1.4.0", + ) + go_repository( + name = "com_google_cloud_go_translate", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/translate", + sum = "h1:AOYOH3MspzJ/bH1YXzB+xTE8fMpn3mwhLjugwGXvMPI=", + version = "v1.4.0", + ) + go_repository( + name = "com_google_cloud_go_video", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/video", + sum = "h1:ttlvO4J5c1VGq6FkHqWPD/aH6PfdxujHt+muTJlW1Zk=", + version = "v1.9.0", + ) + go_repository( + name = "com_google_cloud_go_videointelligence", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/videointelligence", + sum = "h1:RPFgVVXbI2b5vnrciZjtsUgpNKVtHO/WIyXUhEfuMhA=", + version = "v1.9.0", + ) + go_repository( + name = "com_google_cloud_go_vision_v2", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/vision/v2", + sum = "h1:TQHxRqvLMi19azwm3qYuDbEzZWmiKJNTpGbkNsfRCik=", + version = "v2.5.0", + ) + go_repository( + name = "com_google_cloud_go_vmmigration", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/vmmigration", + sum = "h1:A2Tl2ZmwMRpvEmhV2ibISY85fmQR+Y5w9a0PlRz5P3s=", + version = "v1.3.0", + ) + go_repository( + name = "com_google_cloud_go_vmwareengine", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/vmwareengine", + sum = "h1:JMPZaOT/gIUxVlTqSl/QQ32Y2k+r0stNeM1NSqhVP9o=", + version = "v0.1.0", + ) + go_repository( + name = "com_google_cloud_go_vpcaccess", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/vpcaccess", + sum = "h1:woHXXtnW8b9gLFdWO9HLPalAddBQ9V4LT+1vjKwR3W8=", + version = "v1.5.0", + ) + go_repository( + name = "com_google_cloud_go_webrisk", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/webrisk", + sum = "h1:ypSnpGlJnZSXbN9a13PDmAYvVekBLnGKxQ3Q9SMwnYY=", + version = "v1.7.0", + ) + go_repository( + name = "com_google_cloud_go_websecurityscanner", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/websecurityscanner", + sum = "h1:y7yIFg/h/mO+5Y5aCOtVAnpGUOgqCH5rXQ2Oc8Oq2+g=", + version = "v1.4.0", + ) + go_repository( + name = "com_google_cloud_go_workflows", + build_file_proto_mode = "disable_global", + importpath = "cloud.google.com/go/workflows", + sum = "h1:7Chpin9p50NTU8Tb7qk+I11U/IwVXmDhEoSsdccvInE=", + version = "v1.9.0", + ) + go_repository( + name = "com_jaytaylor_html2text", + build_file_proto_mode = "disable_global", + importpath = "jaytaylor.com/html2text", + sum = "h1:mub0MmFLOn8XLikZOAhgLD1kXJq8jgftSrrv7m00xFo=", + version = "v0.0.0-20200412013138-3577fbdbcff7", + ) + go_repository( + name = "in_gopkg_check_v1", + build_file_proto_mode = "disable_global", + importpath = "gopkg.in/check.v1", + sum = "h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=", + version = "v1.0.0-20201130134442-10cb98267c6c", + ) + go_repository( + name = "in_gopkg_errgo_v2", + build_file_proto_mode = "disable_global", + importpath = "gopkg.in/errgo.v2", + sum = "h1:0vLT13EuvQ0hNvakwLuFZ/jYrLp5F3kcWHXdRggjCE8=", + version = "v2.1.0", + ) + go_repository( + name = "in_gopkg_fsnotify_v1", + build_file_proto_mode = "disable_global", + importpath = "gopkg.in/fsnotify.v1", + sum = "h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4=", + version = "v1.4.7", + ) + go_repository( + name = "in_gopkg_go_playground_assert_v1", + build_file_proto_mode = "disable_global", + importpath = "gopkg.in/go-playground/assert.v1", + sum = "h1:xoYuJVE7KT85PYWrN730RguIQO0ePzVRfFMXadIrXTM=", + version = "v1.2.1", + ) + go_repository( + name = "in_gopkg_go_playground_validator_v8", + build_file_proto_mode = "disable_global", + importpath = "gopkg.in/go-playground/validator.v8", + sum = "h1:lFB4DoMU6B626w8ny76MV7VX6W2VHct2GVOI3xgiMrQ=", + version = "v8.18.2", + ) + go_repository( + name = "in_gopkg_inf_v0", + build_file_proto_mode = "disable_global", + importpath = "gopkg.in/inf.v0", + sum = "h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc=", + version = "v0.9.1", + ) + go_repository( + name = "in_gopkg_ini_v1", + build_file_proto_mode = "disable_global", + importpath = "gopkg.in/ini.v1", + sum = "h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA=", + version = "v1.67.0", + ) + go_repository( + name = "in_gopkg_mgo_v2", + build_file_proto_mode = "disable_global", + importpath = "gopkg.in/mgo.v2", + sum = "h1:xcEWjVhvbDy+nHP67nPDDpbYrY+ILlfndk4bRioVHaU=", + version = "v2.0.0-20180705113604-9856a29383ce", + ) + go_repository( + name = "in_gopkg_tomb_v1", + build_file_proto_mode = "disable_global", + importpath = "gopkg.in/tomb.v1", + sum = "h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=", + version = "v1.0.0-20141024135613-dd632973f1e7", + ) + go_repository( + name = "in_gopkg_yaml_v2", + build_file_proto_mode = "disable_global", + importpath = "gopkg.in/yaml.v2", + sum = "h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=", + version = "v2.4.0", + ) + go_repository( + name = "in_gopkg_yaml_v3", + build_file_proto_mode = "disable_global", + importpath = "gopkg.in/yaml.v3", + sum = "h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=", + version = "v3.0.1", + ) + go_repository( + name = "io_k8s_api", + build_file_proto_mode = "disable_global", + importpath = "k8s.io/api", + sum = "h1:f+SWYiPd/GsiWwVRz+NbFyCgvv75Pk9NK6dlkZgpCRQ=", + version = "v0.26.1", + ) + go_repository( + name = "io_k8s_apimachinery", + build_file_proto_mode = "disable_global", + importpath = "k8s.io/apimachinery", + sum = "h1:8EZ/eGJL+hY/MYCNwhmDzVqq2lPl3N3Bo8rvweJwXUQ=", + version = "v0.26.1", + ) + go_repository( + name = "io_k8s_client_go", + build_file_proto_mode = "disable_global", + importpath = "k8s.io/client-go", + sum = "h1:87CXzYJnAMGaa/IDDfRdhTzxk/wzGZ+/HUQpqgVSZXU=", + version = "v0.26.1", + ) + go_repository( + name = "io_k8s_gengo", + build_file_proto_mode = "disable_global", + importpath = "k8s.io/gengo", + sum = "h1:GohjlNKauSai7gN4wsJkeZ3WAJx4Sh+oT/b5IYn5suA=", + version = "v0.0.0-20210813121822-485abfe95c7c", + ) + go_repository( + name = "io_k8s_klog_v2", + build_file_proto_mode = "disable_global", + importpath = "k8s.io/klog/v2", + sum = "h1:atnLQ121W371wYYFawwYx1aEY2eUfs4l3J72wtgAwV4=", + version = "v2.80.1", + ) + go_repository( + name = "io_k8s_kube_openapi", + build_file_proto_mode = "disable_global", + importpath = "k8s.io/kube-openapi", + sum = "h1:+70TFaan3hfJzs+7VK2o+OGxg8HsuBr/5f6tVAjDu6E=", + version = "v0.0.0-20221012153701-172d655c2280", + ) + go_repository( + name = "io_k8s_sigs_json", + build_file_proto_mode = "disable_global", + importpath = "sigs.k8s.io/json", + sum = "h1:iXTIw73aPyC+oRdyqqvVJuloN1p0AC/kzH07hu3NE+k=", + version = "v0.0.0-20220713155537-f223a00ba0e2", + ) + go_repository( + name = "io_k8s_sigs_structured_merge_diff_v4", + build_file_proto_mode = "disable_global", + importpath = "sigs.k8s.io/structured-merge-diff/v4", + sum = "h1:PRbqxJClWWYMNV1dhaG4NsibJbArud9kFxnAMREiWFE=", + version = "v4.2.3", + ) + go_repository( + name = "io_k8s_sigs_yaml", + build_file_proto_mode = "disable_global", + importpath = "sigs.k8s.io/yaml", + sum = "h1:a2VclLzOGrwOHDiV8EfBGhvjHvP46CtW5j6POvhYGGo=", + version = "v1.3.0", + ) + go_repository( + name = "io_k8s_utils", + build_file_proto_mode = "disable_global", + importpath = "k8s.io/utils", + sum = "h1:0Smp/HP1OH4Rvhe+4B8nWGERtlqAGSftbSbbmm45oFs=", + version = "v0.0.0-20221107191617-1a15be271d1d", + ) + go_repository( + name = "io_opencensus_go", + build_file_proto_mode = "disable_global", + importpath = "go.opencensus.io", + sum = "h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0=", + version = "v0.24.0", + ) + go_repository( + name = "org_golang_google_api", + build_file_proto_mode = "disable_global", + importpath = "google.golang.org/api", + sum = "h1:l+rh0KYUooe9JGbGVx71tbFo4SMbMTXK3I3ia2QSEeU=", + version = "v0.110.0", + ) + go_repository( + name = "org_golang_google_appengine", + build_file_proto_mode = "disable_global", + importpath = "google.golang.org/appengine", + sum = "h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c=", + version = "v1.6.7", + ) + go_repository( + name = "org_golang_google_genproto", + build_file_proto_mode = "disable_global", + importpath = "google.golang.org/genproto", + sum = "h1:EfLuoKW5WfkgVdDy7dTK8qSbH37AX5mj/MFh+bGPz14=", + version = "v0.0.0-20230216225411-c8e22ba71e44", + ) + go_repository( + name = "org_golang_google_grpc", + build_file_proto_mode = "disable_global", + importpath = "google.golang.org/grpc", + sum = "h1:LAv2ds7cmFV/XTS3XG1NneeENYrXGmorPxsBbptIjNc=", + version = "v1.53.0", + ) + go_repository( + name = "org_golang_google_protobuf", + build_file_proto_mode = "disable_global", + importpath = "google.golang.org/protobuf", + sum = "h1:d0NfwRgPtno5B1Wa6L2DAG+KivqkdutMf1UhdNx175w=", + version = "v1.28.1", + ) + go_repository( + name = "org_golang_x_crypto", + build_file_proto_mode = "disable_global", + importpath = "golang.org/x/crypto", + sum = "h1:a06MkbcxBrEFc0w0QIZWXrH/9cCX6KJyWbBOIwAn+7A=", + version = "v0.3.0", + ) + go_repository( + name = "org_golang_x_exp", + build_file_proto_mode = "disable_global", + importpath = "golang.org/x/exp", + sum = "h1:c2HOrn5iMezYjSlGPncknSEr/8x5LELb/ilJbXi9DEA=", + version = "v0.0.0-20190121172915-509febef88a4", + ) + go_repository( + name = "org_golang_x_lint", + build_file_proto_mode = "disable_global", + importpath = "golang.org/x/lint", + sum = "h1:VLliZ0d+/avPrXXH+OakdXhpJuEoBZuwh1m2j7U6Iug=", + version = "v0.0.0-20210508222113-6edffad5e616", + ) + go_repository( + name = "org_golang_x_mod", + build_file_proto_mode = "disable_global", + importpath = "golang.org/x/mod", + sum = "h1:KENHtAZL2y3NLMYZeHY9DW8HW8V+kQyJsY/V9JlKvCs=", + version = "v0.9.0", + ) + go_repository( + name = "org_golang_x_net", + build_file_proto_mode = "disable_global", + importpath = "golang.org/x/net", + sum = "h1:Zrh2ngAOFYneWTAIAPethzeaQLuHwhuBkuV6ZiRnUaQ=", + version = "v0.8.0", + ) + go_repository( + name = "org_golang_x_oauth2", + build_file_proto_mode = "disable_global", + importpath = "golang.org/x/oauth2", + sum = "h1:HuArIo48skDwlrvM3sEdHXElYslAMsf3KwRkkW4MC4s=", + version = "v0.5.0", + ) + go_repository( + name = "org_golang_x_sync", + build_file_proto_mode = "disable_global", + importpath = "golang.org/x/sync", + sum = "h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=", + version = "v0.1.0", + ) + go_repository( + name = "org_golang_x_sys", + build_file_proto_mode = "disable_global", + importpath = "golang.org/x/sys", + sum = "h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ=", + version = "v0.6.0", + ) + go_repository( + name = "org_golang_x_term", + build_file_proto_mode = "disable_global", + importpath = "golang.org/x/term", + sum = "h1:clScbb1cHjoCkyRbWwBEUZ5H/tIFu5TAXIqaZD0Gcjw=", + version = "v0.6.0", + ) + go_repository( + name = "org_golang_x_text", + build_file_proto_mode = "disable_global", + importpath = "golang.org/x/text", + sum = "h1:57P1ETyNKtuIjB4SRd15iJxuhj8Gc416Y78H3qgMh68=", + version = "v0.8.0", + ) + go_repository( + name = "org_golang_x_time", + build_file_proto_mode = "disable_global", + importpath = "golang.org/x/time", + sum = "h1:Yx9k8YCG3dvF87UAn2tu2HQLf2dt/eR1bXxpLMWeH+Y=", + version = "v0.0.0-20220922220347-f3bd1da661af", + ) + go_repository( + name = "org_golang_x_tools", + build_file_proto_mode = "disable_global", + importpath = "golang.org/x/tools", + sum = "h1:W4OVu8VVOaIO0yzWMNdepAulS7YfoS3Zabrm8DOXXU4=", + version = "v0.7.0", + ) + go_repository( + name = "org_golang_x_xerrors", + build_file_proto_mode = "disable_global", + importpath = "golang.org/x/xerrors", + sum = "h1:H2TDz8ibqkAF6YGhCdN3jS9O0/s90v0rJh3X/OLHEUk=", + version = "v0.0.0-20220907171357-04be3eba64a2", + ) + go_repository( + name = "org_uber_go_atomic", + build_file_proto_mode = "disable_global", + importpath = "go.uber.org/atomic", + sum = "h1:9qC72Qh0+3MqyJbAn8YU5xVq1frD8bn3JtD2oXtafVQ=", + version = "v1.10.0", + ) + go_repository( + name = "org_uber_go_goleak", + build_file_proto_mode = "disable_global", + importpath = "go.uber.org/goleak", + sum = "h1:xqgm/S+aQvhWFTtR0XK3Jvg7z8kGV8P4X14IzwN3Eqk=", + version = "v1.2.0", + ) + go_repository( + name = "org_uber_go_multierr", + build_file_proto_mode = "disable_global", + importpath = "go.uber.org/multierr", + sum = "h1:7fIwc/ZtS0q++VgcfqFDxSBZVv/Xo49/SYnDFupUwlI=", + version = "v1.9.0", + ) + go_repository( + name = "org_uber_go_zap", + build_file_proto_mode = "disable_global", + importpath = "go.uber.org/zap", + sum = "h1:FiJd5l1UOLj0wCgbSE0rwwXHzEdAZS6hiiSnxJN/D60=", + version = "v1.24.0", + ) + go_repository( + name = "tools_gotest_v3", + build_file_proto_mode = "disable_global", + importpath = "gotest.tools/v3", + sum = "h1:4AuOwCGf4lLR9u3YOe2awrHygurzhO/HeQ6laiA6Sx0=", + version = "v3.0.3", + ) diff --git a/internal/api/BUILD.bazel b/internal/api/BUILD.bazel new file mode 100644 index 0000000000..a292172e57 --- /dev/null +++ b/internal/api/BUILD.bazel @@ -0,0 +1,32 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") + +go_library( + name = "api", + srcs = [ + "api.go", + "errors.go", + "flags.go", + "gzip.go", + "nullable.go", + ], + importpath = "github.com/sourcegraph/src-cli/internal/api", + visibility = ["//:__subpackages__"], + deps = [ + "//internal/version", + "@com_github_jig_teereadcloser//:teereadcloser", + "@com_github_kballard_go_shellquote//:go-shellquote", + "@com_github_mattn_go_isatty//:go-isatty", + "@com_github_sourcegraph_sourcegraph_lib//errors", + ], +) + +go_test( + name = "api_test", + srcs = [ + "api_test.go", + "errors_test.go", + "gzip_test.go", + ], + embed = [":api"], + deps = ["@com_github_google_go_cmp//cmp"], +) diff --git a/internal/api/mock/BUILD.bazel b/internal/api/mock/BUILD.bazel new file mode 100644 index 0000000000..01c5399f8d --- /dev/null +++ b/internal/api/mock/BUILD.bazel @@ -0,0 +1,12 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library") + +go_library( + name = "mock", + srcs = ["api.go"], + importpath = "github.com/sourcegraph/src-cli/internal/api/mock", + visibility = ["//:__subpackages__"], + deps = [ + "//internal/api", + "@com_github_stretchr_testify//mock", + ], +) diff --git a/internal/batches/BUILD.bazel b/internal/batches/BUILD.bazel new file mode 100644 index 0000000000..96699bf327 --- /dev/null +++ b/internal/batches/BUILD.bazel @@ -0,0 +1,17 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library") + +go_library( + name = "batches", + srcs = [ + "errors.go", + "features.go", + "license.go", + ], + importpath = "github.com/sourcegraph/src-cli/internal/batches", + visibility = ["//:__subpackages__"], + deps = [ + "//internal/batches/graphql", + "@com_github_sourcegraph_sourcegraph_lib//api", + "@com_github_sourcegraph_sourcegraph_lib//errors", + ], +) diff --git a/internal/batches/docker/BUILD.bazel b/internal/batches/docker/BUILD.bazel new file mode 100644 index 0000000000..21a8ee5c92 --- /dev/null +++ b/internal/batches/docker/BUILD.bazel @@ -0,0 +1,35 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") + +go_library( + name = "docker", + srcs = [ + "cache.go", + "context.go", + "image.go", + "info.go", + "version.go", + ], + importpath = "github.com/sourcegraph/src-cli/internal/batches/docker", + visibility = ["//:__subpackages__"], + deps = [ + "//internal/exec", + "@com_github_kballard_go_shellquote//:go-shellquote", + "@com_github_sourcegraph_sourcegraph_lib//errors", + ], +) + +go_test( + name = "docker_test", + srcs = [ + "cache_test.go", + "image_test.go", + "info_test.go", + "main_test.go", + ], + embed = [":docker"], + deps = [ + "//internal/exec/expect", + "@com_github_google_go_cmp//cmp", + "@com_github_stretchr_testify//assert", + ], +) diff --git a/internal/batches/executor/BUILD.bazel b/internal/batches/executor/BUILD.bazel new file mode 100644 index 0000000000..5ffd119911 --- /dev/null +++ b/internal/batches/executor/BUILD.bazel @@ -0,0 +1,66 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") + +go_library( + name = "executor", + srcs = [ + "coordinator.go", + "execution_cache.go", + "executor.go", + "run_steps.go", + "task.go", + "ui.go", + ], + importpath = "github.com/sourcegraph/src-cli/internal/batches/executor", + visibility = ["//:__subpackages__"], + deps = [ + "//internal/batches/docker", + "//internal/batches/graphql", + "//internal/batches/log", + "//internal/batches/repozip", + "//internal/batches/util", + "//internal/batches/workspace", + "@com_github_neelance_parallel//:parallel", + "@com_github_sourcegraph_sourcegraph_lib//batches", + "@com_github_sourcegraph_sourcegraph_lib//batches/execution", + "@com_github_sourcegraph_sourcegraph_lib//batches/execution/cache", + "@com_github_sourcegraph_sourcegraph_lib//batches/git", + "@com_github_sourcegraph_sourcegraph_lib//batches/template", + "@com_github_sourcegraph_sourcegraph_lib//errors", + "@com_github_sourcegraph_sourcegraph_lib//process", + "@in_gopkg_yaml_v3//:yaml_v3", + ], +) + +go_test( + name = "executor_test", + srcs = [ + "coordinator_test.go", + "execution_cache_test.go", + "executor_test.go", + "main_test.go", + "task_test.go", + ], + data = glob(["testdata/**"]), + embed = [":executor"], + deps = [ + "//internal/api", + "//internal/batches/docker", + "//internal/batches/graphql", + "//internal/batches/mock", + "//internal/batches/repozip", + "//internal/batches/util", + "//internal/batches/workspace", + "@com_github_google_go_cmp//cmp", + "@com_github_google_go_cmp//cmp/cmpopts", + "@com_github_sourcegraph_go_diff//diff", + "@com_github_sourcegraph_sourcegraph_lib//batches", + "@com_github_sourcegraph_sourcegraph_lib//batches/execution", + "@com_github_sourcegraph_sourcegraph_lib//batches/execution/cache", + "@com_github_sourcegraph_sourcegraph_lib//batches/git", + "@com_github_sourcegraph_sourcegraph_lib//batches/overridable", + "@com_github_sourcegraph_sourcegraph_lib//batches/template", + "@com_github_sourcegraph_sourcegraph_lib//errors", + "@com_github_stretchr_testify//assert", + "@com_github_stretchr_testify//require", + ], +) diff --git a/internal/batches/graphql/BUILD.bazel b/internal/batches/graphql/BUILD.bazel new file mode 100644 index 0000000000..0c61ae53d1 --- /dev/null +++ b/internal/batches/graphql/BUILD.bazel @@ -0,0 +1,12 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library") + +go_library( + name = "graphql", + srcs = [ + "batches.go", + "repository.go", + ], + importpath = "github.com/sourcegraph/src-cli/internal/batches/graphql", + visibility = ["//:__subpackages__"], + deps = ["//internal/batches/util"], +) diff --git a/internal/batches/log/BUILD.bazel b/internal/batches/log/BUILD.bazel new file mode 100644 index 0000000000..b287a96e24 --- /dev/null +++ b/internal/batches/log/BUILD.bazel @@ -0,0 +1,14 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library") + +go_library( + name = "log", + srcs = [ + "disk_manager.go", + "disk_task_logger.go", + "logger.go", + "noop_task_logger.go", + ], + importpath = "github.com/sourcegraph/src-cli/internal/batches/log", + visibility = ["//:__subpackages__"], + deps = ["@com_github_sourcegraph_sourcegraph_lib//errors"], +) diff --git a/internal/batches/mock/BUILD.bazel b/internal/batches/mock/BUILD.bazel new file mode 100644 index 0000000000..f45dc39723 --- /dev/null +++ b/internal/batches/mock/BUILD.bazel @@ -0,0 +1,18 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library") + +go_library( + name = "mock", + srcs = [ + "cache.go", + "docker_image_progress.go", + "image.go", + "logger.go", + "repo_archive.go", + ], + importpath = "github.com/sourcegraph/src-cli/internal/batches/mock", + visibility = ["//:__subpackages__"], + deps = [ + "//internal/batches/docker", + "//internal/batches/log", + ], +) diff --git a/internal/batches/repozip/BUILD.bazel b/internal/batches/repozip/BUILD.bazel new file mode 100644 index 0000000000..1d03d70fbb --- /dev/null +++ b/internal/batches/repozip/BUILD.bazel @@ -0,0 +1,28 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") + +go_library( + name = "repozip", + srcs = [ + "fetcher.go", + "noop.go", + ], + importpath = "github.com/sourcegraph/src-cli/internal/batches/repozip", + visibility = ["//:__subpackages__"], + deps = [ + "//internal/batches/util", + "@com_github_sourcegraph_sourcegraph_lib//errors", + ], +) + +go_test( + name = "repozip_test", + srcs = ["fetcher_test.go"], + embed = [":repozip"], + deps = [ + "//internal/api", + "//internal/batches/mock", + "//internal/batches/util", + "@com_github_google_go_cmp//cmp", + "@com_github_google_go_cmp//cmp/cmpopts", + ], +) diff --git a/internal/batches/service/BUILD.bazel b/internal/batches/service/BUILD.bazel new file mode 100644 index 0000000000..8b20ccb96a --- /dev/null +++ b/internal/batches/service/BUILD.bazel @@ -0,0 +1,43 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") + +go_library( + name = "service", + srcs = [ + "build_tasks.go", + "remote.go", + "service.go", + ], + importpath = "github.com/sourcegraph/src-cli/internal/batches/service", + visibility = ["//:__subpackages__"], + deps = [ + "//internal/api", + "//internal/batches", + "//internal/batches/docker", + "//internal/batches/executor", + "//internal/batches/graphql", + "@com_github_sourcegraph_sourcegraph_lib//batches", + "@com_github_sourcegraph_sourcegraph_lib//batches/template", + "@com_github_sourcegraph_sourcegraph_lib//errors", + ], +) + +go_test( + name = "service_test", + srcs = [ + "remote_test.go", + "remote_windows_test.go", + "service_test.go", + ], + embed = [":service"], + deps = [ + "//internal/api/mock", + "//internal/batches/docker", + "//internal/batches/graphql", + "//internal/batches/mock", + "@com_github_sourcegraph_sourcegraph_lib//batches", + "@com_github_sourcegraph_sourcegraph_lib//errors", + "@com_github_stretchr_testify//assert", + "@com_github_stretchr_testify//mock", + "@com_github_stretchr_testify//require", + ], +) diff --git a/internal/batches/ui/BUILD.bazel b/internal/batches/ui/BUILD.bazel new file mode 100644 index 0000000000..c267ca1777 --- /dev/null +++ b/internal/batches/ui/BUILD.bazel @@ -0,0 +1,50 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") + +go_library( + name = "ui", + srcs = [ + "exec_ui.go", + "interval_writer.go", + "json_lines.go", + "task_exec_tui.go", + "tty.go", + "tui.go", + ], + importpath = "github.com/sourcegraph/src-cli/internal/batches/ui", + visibility = ["//:__subpackages__"], + deps = [ + "//internal/api", + "//internal/batches", + "//internal/batches/executor", + "//internal/batches/graphql", + "//internal/batches/workspace", + "//internal/cmderrors", + "@com_github_creack_goselect//:goselect", + "@com_github_derision_test_glock//:glock", + "@com_github_dineshappavoo_basex//:basex", + "@com_github_neelance_parallel//:parallel", + "@com_github_sourcegraph_go_diff//diff", + "@com_github_sourcegraph_sourcegraph_lib//batches", + "@com_github_sourcegraph_sourcegraph_lib//batches/execution", + "@com_github_sourcegraph_sourcegraph_lib//batches/git", + "@com_github_sourcegraph_sourcegraph_lib//errors", + "@com_github_sourcegraph_sourcegraph_lib//output", + ], +) + +go_test( + name = "ui_test", + srcs = [ + "interval_writer_test.go", + "task_exec_tui_test.go", + ], + embed = [":ui"], + deps = [ + "//internal/batches/executor", + "//internal/batches/graphql", + "@com_github_derision_test_glock//:glock", + "@com_github_google_go_cmp//cmp", + "@com_github_sourcegraph_sourcegraph_lib//batches", + "@com_github_sourcegraph_sourcegraph_lib//output", + ], +) diff --git a/internal/batches/util/BUILD.bazel b/internal/batches/util/BUILD.bazel new file mode 100644 index 0000000000..c59ade842e --- /dev/null +++ b/internal/batches/util/BUILD.bazel @@ -0,0 +1,9 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library") + +go_library( + name = "util", + srcs = ["repo.go"], + importpath = "github.com/sourcegraph/src-cli/internal/batches/util", + visibility = ["//:__subpackages__"], + deps = ["@com_github_sourcegraph_sourcegraph_lib//batches/template"], +) diff --git a/internal/batches/watchdog/BUILD.bazel b/internal/batches/watchdog/BUILD.bazel new file mode 100644 index 0000000000..5ac56539aa --- /dev/null +++ b/internal/batches/watchdog/BUILD.bazel @@ -0,0 +1,16 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") + +go_library( + name = "watchdog", + srcs = ["watchdog.go"], + importpath = "github.com/sourcegraph/src-cli/internal/batches/watchdog", + visibility = ["//:__subpackages__"], + deps = ["@com_github_derision_test_glock//:glock"], +) + +go_test( + name = "watchdog_test", + srcs = ["watchdog_test.go"], + embed = [":watchdog"], + deps = ["@com_github_derision_test_glock//:glock"], +) diff --git a/internal/batches/workspace/BUILD.bazel b/internal/batches/workspace/BUILD.bazel new file mode 100644 index 0000000000..dc56ef0575 --- /dev/null +++ b/internal/batches/workspace/BUILD.bazel @@ -0,0 +1,47 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") + +go_library( + name = "workspace", + srcs = [ + "bind_workspace.go", + "executor_workspace.go", + "git.go", + "volume_workspace.go", + "workspace.go", + ], + importpath = "github.com/sourcegraph/src-cli/internal/batches/workspace", + visibility = ["//:__subpackages__"], + deps = [ + "//internal/batches/docker", + "//internal/batches/graphql", + "//internal/batches/repozip", + "//internal/batches/util", + "//internal/exec", + "//internal/version", + "@com_github_sourcegraph_sourcegraph_lib//batches", + "@com_github_sourcegraph_sourcegraph_lib//errors", + ], +) + +go_test( + name = "workspace_test", + srcs = [ + "bind_workspace_nonwin_test.go", + "bind_workspace_test.go", + "bind_workspace_windows_test.go", + "main_test.go", + "volume_workspace_test.go", + "workspace_test.go", + ], + embed = [":workspace"], + deps = [ + "//internal/batches/docker", + "//internal/batches/graphql", + "//internal/batches/mock", + "//internal/batches/repozip", + "//internal/exec/expect", + "@com_github_google_go_cmp//cmp", + "@com_github_sourcegraph_sourcegraph_lib//batches", + "@com_github_sourcegraph_sourcegraph_lib//errors", + ], +) diff --git a/internal/cmderrors/BUILD.bazel b/internal/cmderrors/BUILD.bazel new file mode 100644 index 0000000000..8cea3ca98a --- /dev/null +++ b/internal/cmderrors/BUILD.bazel @@ -0,0 +1,9 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library") + +go_library( + name = "cmderrors", + srcs = ["errors.go"], + importpath = "github.com/sourcegraph/src-cli/internal/cmderrors", + visibility = ["//:__subpackages__"], + deps = ["@com_github_sourcegraph_sourcegraph_lib//errors"], +) diff --git a/internal/codeintel/BUILD.bazel b/internal/codeintel/BUILD.bazel new file mode 100644 index 0000000000..981a0b59fa --- /dev/null +++ b/internal/codeintel/BUILD.bazel @@ -0,0 +1,20 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") + +go_library( + name = "codeintel", + srcs = [ + "gitutil.go", + "sanitation.go", + ], + importpath = "github.com/sourcegraph/src-cli/internal/codeintel", + visibility = ["//:__subpackages__"], +) + +go_test( + name = "codeintel_test", + srcs = [ + "gitutil_test.go", + "sanitation_test.go", + ], + embed = [":codeintel"], +) diff --git a/internal/exec/BUILD.bazel b/internal/exec/BUILD.bazel new file mode 100644 index 0000000000..fa0ed3a7d7 --- /dev/null +++ b/internal/exec/BUILD.bazel @@ -0,0 +1,11 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library") + +go_library( + name = "exec", + srcs = [ + "exec.go", + "middleware.go", + ], + importpath = "github.com/sourcegraph/src-cli/internal/exec", + visibility = ["//:__subpackages__"], +) diff --git a/internal/exec/expect/BUILD.bazel b/internal/exec/expect/BUILD.bazel new file mode 100644 index 0000000000..bb299fe90d --- /dev/null +++ b/internal/exec/expect/BUILD.bazel @@ -0,0 +1,14 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library") + +go_library( + name = "expect", + srcs = ["expect.go"], + importpath = "github.com/sourcegraph/src-cli/internal/exec/expect", + visibility = ["//:__subpackages__"], + deps = [ + "//internal/exec", + "@com_github_gobwas_glob//:glob", + "@com_github_google_go_cmp//cmp", + "@com_github_sourcegraph_sourcegraph_lib//errors", + ], +) diff --git a/internal/instancehealth/BUILD.bazel b/internal/instancehealth/BUILD.bazel new file mode 100644 index 0000000000..146bb95192 --- /dev/null +++ b/internal/instancehealth/BUILD.bazel @@ -0,0 +1,27 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") + +go_library( + name = "instancehealth", + srcs = [ + "checks.go", + "summary.go", + ], + importpath = "github.com/sourcegraph/src-cli/internal/instancehealth", + visibility = ["//:__subpackages__"], + deps = [ + "//internal/api", + "@com_github_sourcegraph_sourcegraph_lib//errors", + "@com_github_sourcegraph_sourcegraph_lib//output", + ], +) + +go_test( + name = "instancehealth_test", + srcs = ["checks_test.go"], + embed = [":instancehealth"], + deps = [ + "@com_github_sourcegraph_sourcegraph_lib//output", + "@com_github_stretchr_testify//assert", + "@com_github_stretchr_testify//require", + ], +) diff --git a/internal/lazyregexp/BUILD.bazel b/internal/lazyregexp/BUILD.bazel new file mode 100644 index 0000000000..e0638b595f --- /dev/null +++ b/internal/lazyregexp/BUILD.bazel @@ -0,0 +1,9 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library") + +go_library( + name = "lazyregexp", + srcs = ["lazyregexp.go"], + importpath = "github.com/sourcegraph/src-cli/internal/lazyregexp", + visibility = ["//:__subpackages__"], + deps = ["@com_github_grafana_regexp//:regexp"], +) diff --git a/internal/pgdump/BUILD.bazel b/internal/pgdump/BUILD.bazel new file mode 100644 index 0000000000..3ae1599e86 --- /dev/null +++ b/internal/pgdump/BUILD.bazel @@ -0,0 +1,23 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") + +go_library( + name = "pgdump", + srcs = [ + "extensions.go", + "pgdump.go", + ], + importpath = "github.com/sourcegraph/src-cli/internal/pgdump", + visibility = ["//:__subpackages__"], + deps = ["@com_github_sourcegraph_sourcegraph_lib//errors"], +) + +go_test( + name = "pgdump_test", + srcs = ["extensions_test.go"], + embed = [":pgdump"], + deps = [ + "@com_github_hexops_autogold//:autogold", + "@com_github_stretchr_testify//assert", + "@com_github_stretchr_testify//require", + ], +) diff --git a/internal/servegit/BUILD.bazel b/internal/servegit/BUILD.bazel new file mode 100644 index 0000000000..f99e9a1bfc --- /dev/null +++ b/internal/servegit/BUILD.bazel @@ -0,0 +1,22 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") + +go_library( + name = "servegit", + srcs = ["serve.go"], + importpath = "github.com/sourcegraph/src-cli/internal/servegit", + visibility = ["//:__subpackages__"], + deps = [ + "@com_github_sourcegraph_sourcegraph_lib//errors", + "@com_github_sourcegraph_sourcegraph_lib//gitservice", + ], +) + +go_test( + name = "servegit_test", + srcs = ["serve_test.go"], + embed = [":servegit"], + deps = [ + "@com_github_google_go_cmp//cmp", + "@com_github_google_go_cmp//cmp/cmpopts", + ], +) diff --git a/internal/streaming/BUILD.bazel b/internal/streaming/BUILD.bazel new file mode 100644 index 0000000000..2963b75ad3 --- /dev/null +++ b/internal/streaming/BUILD.bazel @@ -0,0 +1,25 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") + +go_library( + name = "streaming", + srcs = [ + "api.go", + "client.go", + "events.go", + "search.go", + "writer.go", + ], + importpath = "github.com/sourcegraph/src-cli/internal/streaming", + visibility = ["//:__subpackages__"], + deps = [ + "//internal/api", + "@com_github_sourcegraph_sourcegraph_lib//errors", + ], +) + +go_test( + name = "streaming_test", + srcs = ["client_test.go"], + embed = [":streaming"], + deps = ["@com_github_google_go_cmp//cmp"], +) diff --git a/internal/users/BUILD.bazel b/internal/users/BUILD.bazel new file mode 100644 index 0000000000..3897cade1f --- /dev/null +++ b/internal/users/BUILD.bazel @@ -0,0 +1,13 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library") + +go_library( + name = "users", + srcs = ["admin.go"], + importpath = "github.com/sourcegraph/src-cli/internal/users", + visibility = ["//:__subpackages__"], + deps = [ + "//internal/lazyregexp", + "@com_github_json_iterator_go//:go", + "@com_github_sourcegraph_sourcegraph_lib//errors", + ], +) diff --git a/internal/validate/BUILD.bazel b/internal/validate/BUILD.bazel new file mode 100644 index 0000000000..19190edb10 --- /dev/null +++ b/internal/validate/BUILD.bazel @@ -0,0 +1,8 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library") + +go_library( + name = "validate", + srcs = ["validate.go"], + importpath = "github.com/sourcegraph/src-cli/internal/validate", + visibility = ["//:__subpackages__"], +) diff --git a/internal/validate/install/BUILD.bazel b/internal/validate/install/BUILD.bazel new file mode 100644 index 0000000000..dc5ef4fb35 --- /dev/null +++ b/internal/validate/install/BUILD.bazel @@ -0,0 +1,19 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library") + +go_library( + name = "install", + srcs = [ + "config.go", + "github.go", + "insight.go", + "install.go", + ], + importpath = "github.com/sourcegraph/src-cli/internal/validate/install", + visibility = ["//:__subpackages__"], + deps = [ + "//internal/api", + "//internal/validate", + "@com_github_sourcegraph_sourcegraph_lib//errors", + "@in_gopkg_yaml_v3//:yaml_v3", + ], +) diff --git a/internal/validate/kube/BUILD.bazel b/internal/validate/kube/BUILD.bazel new file mode 100644 index 0000000000..61325ae23f --- /dev/null +++ b/internal/validate/kube/BUILD.bazel @@ -0,0 +1,48 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") + +go_library( + name = "kube", + srcs = [ + "aks.go", + "eks.go", + "gke.go", + "kube.go", + ], + importpath = "github.com/sourcegraph/src-cli/internal/validate/kube", + visibility = ["//:__subpackages__"], + deps = [ + "//internal/validate", + "@com_github_aws_aws_sdk_go_v2_config//:config", + "@com_github_aws_aws_sdk_go_v2_service_ec2//:ec2", + "@com_github_aws_aws_sdk_go_v2_service_ec2//types", + "@com_github_aws_aws_sdk_go_v2_service_eks//:eks", + "@com_github_aws_aws_sdk_go_v2_service_iam//:iam", + "@com_github_sourcegraph_sourcegraph_lib//errors", + "@io_k8s_api//core/v1:core", + "@io_k8s_apimachinery//pkg/apis/meta/v1:meta", + "@io_k8s_client_go//kubernetes", + "@io_k8s_client_go//kubernetes/scheme", + "@io_k8s_client_go//rest", + "@io_k8s_client_go//tools/clientcmd", + "@io_k8s_client_go//tools/remotecommand", + "@io_k8s_client_go//util/homedir", + ], +) + +go_test( + name = "kube_test", + srcs = [ + "eks_test.go", + "kube_test.go", + ], + embed = [":kube"], + deps = [ + "//internal/validate", + "@com_github_aws_aws_sdk_go_v2_service_ec2//types", + "@com_github_aws_aws_sdk_go_v2_service_eks//:eks", + "@com_github_aws_aws_sdk_go_v2_service_iam//:iam", + "@com_github_aws_aws_sdk_go_v2_service_iam//types", + "@io_k8s_api//core/v1:core", + "@io_k8s_apimachinery//pkg/apis/meta/v1:meta", + ], +) diff --git a/internal/version/BUILD.bazel b/internal/version/BUILD.bazel new file mode 100644 index 0000000000..df7ba5c8fc --- /dev/null +++ b/internal/version/BUILD.bazel @@ -0,0 +1,8 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library") + +go_library( + name = "version", + srcs = ["version.go"], + importpath = "github.com/sourcegraph/src-cli/internal/version", + visibility = ["//:__subpackages__"], +) From 08909290b9fa24b740003421e29d525dbd3105e6 Mon Sep 17 00:00:00 2001 From: Dave Try Date: Wed, 17 May 2023 10:13:56 -0500 Subject: [PATCH 335/647] fix new line (#982) * new line --- .gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index a32d205f63..382e2d10fd 100644 --- a/.gitignore +++ b/.gitignore @@ -11,4 +11,4 @@ bazel-bin bazel-out bazel-testlogs bazel-zoekt -bazel-src-cli \ No newline at end of file +bazel-src-cli From 4766869eb6ae93643ad45fcc8282a79cc5846227 Mon Sep 17 00:00:00 2001 From: Jason Hawk Harris Date: Tue, 23 May 2023 09:41:01 -0500 Subject: [PATCH 336/647] add usage command to 'src scout' (#983) * move style folder out of resources directory and into scout directory for ease of reuse * adds metrics api client * refactor * connect metrics api * borked percentages * WIP - incorrect usage percentages for some containers * fixes bug that was causing certain containers to return bad usage percentages * adds percentage of storage capacity used column * add tests and use remotecommand package instead of exec * delete stray line * add line breaks for readability * fix incorrect flag name * refactor to ensure all functions are doing one thing * formatting * formatting * remove duplicate import, remove todo --------- Co-authored-by: Jacob Pleiness --- cmd/src/scout_usage.go | 120 ++++++ go.mod | 31 +- go.sum | 88 ++-- internal/scout/resource/resource.go | 2 +- internal/scout/{resource => }/style/Table.go | 0 internal/scout/usage/docker.go | 28 ++ internal/scout/usage/k8s.go | 398 +++++++++++++++++++ internal/scout/usage/usage.go | 68 ++++ internal/scout/usage/usage_test.go | 191 +++++++++ 9 files changed, 867 insertions(+), 59 deletions(-) create mode 100644 cmd/src/scout_usage.go rename internal/scout/{resource => }/style/Table.go (100%) create mode 100644 internal/scout/usage/docker.go create mode 100644 internal/scout/usage/k8s.go create mode 100644 internal/scout/usage/usage.go create mode 100644 internal/scout/usage/usage_test.go diff --git a/cmd/src/scout_usage.go b/cmd/src/scout_usage.go new file mode 100644 index 0000000000..1158223f88 --- /dev/null +++ b/cmd/src/scout_usage.go @@ -0,0 +1,120 @@ +package main + +import ( + "context" + "flag" + "fmt" + "path/filepath" + + "github.com/docker/docker/client" + "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/src-cli/internal/scout/usage" + "k8s.io/client-go/kubernetes" + "k8s.io/client-go/tools/clientcmd" + "k8s.io/client-go/util/homedir" + metricsv "k8s.io/metrics/pkg/client/clientset/versioned" +) + +func init() { + cmdUsage := `'src scout usage' is a tool that tracks resource usage for Sourcegraph instances. + Part of the EXPERIMENTAL "src scout" tool. + + Examples + List pods and resource usage in a Kubernetes deployment: + $ src scout usage + + List containers and resource usage in a Docker deployment: + $ src scout usage --docker + + Check usage for specific pod + $ src scout usage --pod + + Add namespace if using namespace in a Kubernetes cluster + $ src scout usage --namespace + + Watch usage in real time + $ src scout usage --spy + ` + + flagSet := flag.NewFlagSet("usage", flag.ExitOnError) + usageFunc := func() { + fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src scout %s':\n", flagSet.Name()) + flagSet.PrintDefaults() + fmt.Println(cmdUsage) + } + + var ( + kubeConfig *string + namespace = flagSet.String("namespace", "", "(optional) specify the kubernetes namespace to use") + pod = flagSet.String("pod", "", "(optional) specify a single pod") + docker = flagSet.Bool("docker", false, "(optional) using docker deployment") + spy = flagSet.Bool("spy", false, "(optional) see resource usage in real time") + ) + + if home := homedir.HomeDir(); home != "" { + kubeConfig = flagSet.String( + "kubeconfig", + filepath.Join(home, ".kube", "config"), + "(optional) absolute path to the kubeconfig file", + ) + } else { + kubeConfig = flagSet.String("kubeconfig", "", "absolute path to the kubeconfig file") + } + + handler := func(args []string) error { + if err := flagSet.Parse(args); err != nil { + return err + } + + config, err := clientcmd.BuildConfigFromFlags("", *kubeConfig) + if err != nil { + return errors.Wrap(err, "failed to load .kube config: ") + } + + clientSet, err := kubernetes.NewForConfig(config) + if err != nil { + return errors.Wrap(err, "failed to initiate kubernetes client: ") + } + + metricsClient, err := metricsv.NewForConfig(config) + if err != nil { + return errors.Wrap(err, "failed to initiate metrics client") + } + + var options []usage.Option + + if *namespace != "" { + options = append(options, usage.WithNamespace(*namespace)) + } + if *spy { + options = append(options, usage.WithSpy(true)) + } + if *pod != "" { + options = append(options, usage.WithPod(*pod)) + } + + if *docker { + dockerClient, err := client.NewClientWithOpts(client.FromEnv) + if err != nil { + return errors.Wrap(err, "error creating docker client: ") + } + + return usage.Docker(context.Background(), *dockerClient) + } + + return usage.K8s( + context.Background(), + clientSet, + metricsClient, + config, + options..., + ) + } + + scoutCommands = append(scoutCommands, &command{ + flagSet: flagSet, + handler: handler, + usageFunc: usageFunc, + }) + +} diff --git a/go.mod b/go.mod index c232d6109d..15e9617bf5 100644 --- a/go.mod +++ b/go.mod @@ -39,13 +39,14 @@ require ( google.golang.org/protobuf v1.28.1 gopkg.in/yaml.v3 v3.0.1 jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7 - k8s.io/api v0.26.1 - k8s.io/apimachinery v0.26.1 - k8s.io/client-go v0.26.1 + k8s.io/api v0.27.1 + k8s.io/apimachinery v0.27.1 + k8s.io/client-go v0.27.1 + k8s.io/metrics v0.27.1 ) require ( - golang.org/x/exp v0.0.0-20190731235908-ec7cb31e5a56 // indirect + golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6 // indirect golang.org/x/image v0.6.0 // indirect golang.org/x/mobile v0.0.0-20230301163155-e0f57694e12c // indirect ) @@ -93,14 +94,14 @@ require ( github.com/getsentry/sentry-go v0.15.0 // indirect github.com/ghodss/yaml v1.0.0 // indirect github.com/go-logr/logr v1.2.3 // indirect - github.com/go-openapi/jsonpointer v0.19.5 // indirect - github.com/go-openapi/jsonreference v0.20.0 // indirect - github.com/go-openapi/swag v0.19.14 // indirect + github.com/go-openapi/jsonpointer v0.19.6 // indirect + github.com/go-openapi/jsonreference v0.20.1 // indirect + github.com/go-openapi/swag v0.22.3 // indirect github.com/gofrs/flock v0.8.1 // indirect github.com/gofrs/uuid v4.2.0+incompatible // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect - github.com/golang/protobuf v1.5.2 // indirect + github.com/golang/protobuf v1.5.3 // indirect github.com/google/gnostic v0.5.7-v3refs // indirect github.com/google/gofuzz v1.1.0 // indirect github.com/google/uuid v1.3.0 // indirect @@ -130,7 +131,7 @@ require ( github.com/mitchellh/copystructure v1.2.0 // indirect github.com/mitchellh/reflectwalk v1.0.2 // indirect github.com/moby/spdystream v0.2.0 // indirect - github.com/moby/term v0.0.0-20220808134915-39b0c02b01ae // indirect + github.com/moby/term v0.0.0-20221205130635-1aeaba878587 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect github.com/morikuni/aec v1.0.0 // indirect @@ -150,7 +151,7 @@ require ( github.com/pseudomuto/protoc-gen-doc v1.5.1 // indirect github.com/pseudomuto/protokit v0.2.0 // indirect github.com/rivo/uniseg v0.4.2 // indirect - github.com/rogpeppe/go-internal v1.9.0 // indirect + github.com/rogpeppe/go-internal v1.10.0 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect github.com/sourcegraph/log v0.0.0-20221206163500-7d93c6ad7037 // indirect github.com/spf13/cobra v1.6.0 // indirect @@ -178,13 +179,13 @@ require ( google.golang.org/appengine v1.6.7 // indirect google.golang.org/genproto v0.0.0-20230216225411-c8e22ba71e44 // indirect google.golang.org/grpc v1.53.0 // indirect - gopkg.in/inf.v0 v0.9.1 // indirect + gopkg.in/inf.v0 v0.9.1 // direct gopkg.in/yaml.v2 v2.4.0 // indirect - k8s.io/klog/v2 v2.80.1 // indirect - k8s.io/kube-openapi v0.0.0-20221012153701-172d655c2280 // indirect - k8s.io/utils v0.0.0-20221107191617-1a15be271d1d // indirect + k8s.io/klog/v2 v2.90.1 // indirect + k8s.io/kube-openapi v0.0.0-20230308215209-15aac26d736a // indirect + k8s.io/utils v0.0.0-20230209194617-a36077c30491 // indirect mvdan.cc/gofumpt v0.4.0 // indirect - sigs.k8s.io/json v0.0.0-20220713155537-f223a00ba0e2 // indirect + sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd // indirect sigs.k8s.io/structured-merge-diff/v4 v4.2.3 // indirect sigs.k8s.io/yaml v1.3.0 // indirect ) diff --git a/go.sum b/go.sum index 4c9e9d0f55..cb2ad81c22 100644 --- a/go.sum +++ b/go.sum @@ -10,6 +10,7 @@ cloud.google.com/go/iam v0.12.0/go.mod h1:knyHGviacl11zrtZUoDuYpDgLjvr28sLQaG0YB cloud.google.com/go/longrunning v0.3.0 h1:NjljC+FYPV3uh5/OwWT6pVU+doBqMg2x/rZlE+CamDs= cloud.google.com/go/storage v1.28.0 h1:DLrIZ6xkeZX6K70fU/boWx5INJumt6f+nwwWSHXzzGY= cloud.google.com/go/storage v1.28.0/go.mod h1:qlgZML35PXA3zoEnIkiPLY4/TOkUleufRlu6qmcf7sI= +dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= github.com/AndreasBriese/bbloom v0.0.0-20190306092124-e2d15f34fcf9/go.mod h1:bOvUY6CB00SOBii9/FifXqc0awNKxLFCL/+pkDPuyl8= github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 h1:UQHMgLO+TxOElx5B5HZ4hJQsoJ/PvUvKRhJHDQXO8P8= github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= @@ -116,8 +117,7 @@ github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46t github.com/creack/goselect v0.1.2 h1:2DNy14+JPjRBgPzAd1thbQp4BSIihxcBf0IXhQXDRa0= github.com/creack/goselect v0.1.2/go.mod h1:a/NhLweNvqIYMuxcMOuWY516Cimucms3DglDzQP3hKY= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= -github.com/creack/pty v1.1.11 h1:07n33Z8lZxZ2qwegKbObQohDhXDQxiMMz1NOUGYlesw= -github.com/creack/pty v1.1.11/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/creack/pty v1.1.18 h1:n56/Zwd5o6whRC5PMGretI4IdRLlmBXYNjScPaBgsbY= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -144,7 +144,6 @@ github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25Kn github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/eknkc/amber v0.0.0-20171010120322-cdade1c07385/go.mod h1:0vRUJqYpeSZifjYj7uP3BG/gKcuzL9xWVV/Y+cK33KM= -github.com/elazarl/goproxy v0.0.0-20180725130230-947c36da3153 h1:yUdfgN0XgIJw7foRItutHYUIhlcKzcSf5vDpdhQAKTc= github.com/emicklei/go-restful/v3 v3.9.0 h1:XwGDlfxEnQZzuopoqxwSEllNcCOM9DhhFyhFIIGKwxE= github.com/emicklei/go-restful/v3 v3.9.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= @@ -173,18 +172,18 @@ github.com/gin-gonic/gin v1.4.0/go.mod h1:OW2EZn3DO8Ln9oIKOvM++LBO+5UPHJJDH72/q/ github.com/go-check/check v0.0.0-20180628173108-788fd7840127/go.mod h1:9ES+weclKsC9YodN5RgxqK/VD9HM9JsCSh7rNhMZE98= github.com/go-errors/errors v1.0.1/go.mod h1:f4zRHt4oKfwPJE5k8C9vpYG+aDHdBFUsgrm6/TyX73Q= github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA= +github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= github.com/go-logr/logr v1.2.0/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.2.3 h1:2DntVwHkVopvECVRSlL5PSo9eG+cAkDCuckLubN+rq0= github.com/go-logr/logr v1.2.3/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-martini/martini v0.0.0-20170121215854-22fa46961aab/go.mod h1:/P9AEU963A2AYjv4d1V5eVL1CQbEJq6aCNHDDjibzu8= -github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= -github.com/go-openapi/jsonpointer v0.19.5 h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUeOFYEICuY= -github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= -github.com/go-openapi/jsonreference v0.20.0 h1:MYlu0sBgChmCfJxxUKZ8g1cPWFOB37YSZqewK7OKeyA= -github.com/go-openapi/jsonreference v0.20.0/go.mod h1:Ag74Ico3lPc+zR+qjn4XBUmXymS4zJbYVCZmcgkasdo= -github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk= -github.com/go-openapi/swag v0.19.14 h1:gm3vOOXfiuw5i9p5N9xJvfjvuofpyvLA9Wr6QfK5Fng= -github.com/go-openapi/swag v0.19.14/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ= +github.com/go-openapi/jsonpointer v0.19.6 h1:eCs3fxoIi3Wh6vtgmLTOjdhSpiqphQ+DaPn38N2ZdrE= +github.com/go-openapi/jsonpointer v0.19.6/go.mod h1:osyAmYz/mB/C3I+WsTTSgw1ONzaLJoLCyoi6/zppojs= +github.com/go-openapi/jsonreference v0.20.1 h1:FBLnyygC4/IZZr893oiomc9XaghoveYTrLC1F86HID8= +github.com/go-openapi/jsonreference v0.20.1/go.mod h1:Bl1zwGIM8/wsvqjsOQLJ/SH+En5Ap4rVB5KVcIDZG2k= +github.com/go-openapi/swag v0.22.3 h1:yMBqmnQ0gyZvEb/+KzuWZOXgllrXT4SADYbvDaXHv/g= +github.com/go-openapi/swag v0.22.3/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14= +github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0 h1:p104kn46Q8WdvHunIJ9dAyjPVtrBPhSr3KT2yUst43I= github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y= github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8= github.com/gobwas/httphead v0.0.0-20180130184737-2c6c146eadee/go.mod h1:L0fX3K22YWvt/FAX9NnzrNzcI4wNYi9Yku4O0LKYflo= @@ -221,8 +220,9 @@ github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QD github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= -github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw= github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= +github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= +github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/gomodule/redigo v1.7.1-0.20190724094224-574c33c3df38/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4= github.com/google/gnostic v0.5.7-v3refs h1:FhTMOKj2VhjpouxvWJAV1TL304uMlb9zcDqkl6cEI54= github.com/google/gnostic v0.5.7-v3refs/go.mod h1:73MKFl6jIHelAJNaBGFzt3SPtZULs9dYrGFt8OiIsHQ= @@ -244,6 +244,7 @@ github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/ github.com/google/gofuzz v1.1.0 h1:Hsa8mG0dQ46ij8Sl2AYJDUv1oA9/d6Vk+3LG99Oe02g= github.com/google/gofuzz v1.1.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/martian/v3 v3.2.1 h1:d8MncMlErDFTwQGBK1xhv026j9kqhvw1Qv9IbWT1VLQ= +github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1 h1:K6RDEckDVWvDI9JAJYCmNdQXq6neHJOYx3V6jnqNEec= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= @@ -354,9 +355,6 @@ github.com/labstack/gommon v0.3.0/go.mod h1:MULnywXg0yavhxWKc+lOruYdAhDwPK9wf0OL github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= -github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= -github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= -github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= @@ -398,8 +396,8 @@ github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zx github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= github.com/moby/spdystream v0.2.0 h1:cjW1zVyyoiM0T7b6UoySUFqzXMoqRckQtXwGPiBhOM8= github.com/moby/spdystream v0.2.0/go.mod h1:f7i0iNDQJ059oMTcWxx8MA/zKFIuD/lY+0GqbN2Wy8c= -github.com/moby/term v0.0.0-20220808134915-39b0c02b01ae h1:O4SWKdcHVCvYqyDV+9CJA1fcDN2L11Bule0iFy3YlAI= -github.com/moby/term v0.0.0-20220808134915-39b0c02b01ae/go.mod h1:E2VnQOmVuvZB6UYnnDB0qG5Nq/1tD9acaOpo6xmt0Kw= +github.com/moby/term v0.0.0-20221205130635-1aeaba878587 h1:HfkjXDfhgVaN5rmueG8cL8KKeFNecRCXFhaJ2qZ5SKA= +github.com/moby/term v0.0.0-20221205130635-1aeaba878587/go.mod h1:8FzsFHVUBGZdbDsJw/ot+X+d5HLUbvklYLJ9uGfcI3Y= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -445,10 +443,10 @@ github.com/onsi/ginkgo v1.10.3/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+ github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= github.com/onsi/ginkgo v1.13.0 h1:M76yO2HkZASFjXL0HSoZJ1AYEmQxNJmY41Jx1zNUq1Y= github.com/onsi/ginkgo v1.13.0/go.mod h1:+REjRxOmWfHCjfv9TTWB1jD1Frx4XydAD3zm1lskyM0= -github.com/onsi/ginkgo/v2 v2.4.0 h1:+Ig9nvqgS5OBSACXNk15PLdp0U9XPYROt9CFzVdFGIs= +github.com/onsi/ginkgo/v2 v2.9.1 h1:zie5Ly042PD3bsCvsSOPvRnFwyo3rKe64TJlD6nu0mk= github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= -github.com/onsi/gomega v1.23.0 h1:/oxKu9c2HVap+F3PfKort2Hw5DEU+HGlW8n+tguWsys= +github.com/onsi/gomega v1.27.4 h1:Z2AnStgsdSayCMDiCU42qIz+HLqEPcgiOCXjAU/w+8E= github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= github.com/opencontainers/image-spec v1.0.2 h1:9yCKha/T5XdGtO0q9Q9a6T5NUCsTn/DrBg0D7ufOcFM= @@ -478,8 +476,9 @@ github.com/rivo/uniseg v0.4.2/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUc github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.6.2/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= -github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= +github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= +github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= @@ -581,7 +580,6 @@ golang.design/x/clipboard v0.7.0 h1:4Je8M/ys9AJumVnl8m+rZnIvstSnYj1fvzqYrU3TXvo= golang.design/x/clipboard v0.7.0/go.mod h1:PQIvqYO9GP29yINEfsEn5zSQKAz3UgXmZKzDA6dnq2E= golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191227163750-53104e6ec876/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= @@ -591,20 +589,22 @@ golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5y golang.org/x/crypto v0.3.0 h1:a06MkbcxBrEFc0w0QIZWXrH/9cCX6KJyWbBOIwAn+7A= golang.org/x/crypto v0.3.0/go.mod h1:hebNnKkNXi2UzZN1eVRvBB7co0a+JxK6XbPiWVs/3J4= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= -golang.org/x/exp v0.0.0-20190731235908-ec7cb31e5a56 h1:estk1glOnSVeJ9tdEZZc5mAMDZk5lNJNyJ6DvrBkTEU= -golang.org/x/exp v0.0.0-20190731235908-ec7cb31e5a56/go.mod h1:JhuoJpWY28nO4Vef9tZUw9qufEGTyX1+7lmHxV5q5G4= +golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6 h1:QE6XYQK6naiK1EPAe1g/ILLxN5RBoH5xkJk3CqlMI/Y= +golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= +golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= golang.org/x/image v0.6.0 h1:bR8b5okrPI3g/gyZakLZHeWxAR8Dn5CyxXv1hLH5g/4= golang.org/x/image v0.6.0/go.mod h1:MXLdDR43H7cDJq5GEGXEVeeNhPgi+YYEQ2pC1byI1x0= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/lint v0.0.0-20210508222113-6edffad5e616/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= -golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= +golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= golang.org/x/mobile v0.0.0-20230301163155-e0f57694e12c h1:Gk61ECugwEHL6IiyyNLXNzmu8XslmRP2dS0xjIYhbb4= golang.org/x/mobile v0.0.0-20230301163155-e0f57694e12c/go.mod h1:aAjjkJNdrh3PMckS4B10TGS2nag27cbKR1y2BpUxsiY= -golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY= golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= @@ -661,10 +661,12 @@ golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5h golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190626221950-04f50cda93cb/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -721,13 +723,12 @@ golang.org/x/tools v0.0.0-20181221001348-537d06c36207/go.mod h1:n7NCudcB/nEzxVGm golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190327201419-c70d86f8b7cf/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.0.0-20190624222133-a101b041ded4/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200207183749-b753a1ba74fa/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200624163319-25775e59acb7/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20210101214203-2dba1e4ea05c/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= @@ -787,9 +788,9 @@ google.golang.org/protobuf v1.28.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqw gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= gopkg.in/go-playground/assert.v1 v1.2.1/go.mod h1:9RXL0bg/zibRAgZUYszZSwO/z8Y/a8bDuhia5mkpMnE= @@ -812,30 +813,31 @@ gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C gopkg.in/yaml.v3 v3.0.0/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gotest.tools/v3 v3.0.2/go.mod h1:3SzNCllyD9/Y+b5r9JIKQ474KzkZyqLqEfYqMsX94Bk= gotest.tools/v3 v3.0.3 h1:4AuOwCGf4lLR9u3YOe2awrHygurzhO/HeQ6laiA6Sx0= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7 h1:mub0MmFLOn8XLikZOAhgLD1kXJq8jgftSrrv7m00xFo= jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7/go.mod h1:OxvTsCwKosqQ1q7B+8FwXqg4rKZ/UG9dUW+g/VL2xH4= -k8s.io/api v0.26.1 h1:f+SWYiPd/GsiWwVRz+NbFyCgvv75Pk9NK6dlkZgpCRQ= -k8s.io/api v0.26.1/go.mod h1:xd/GBNgR0f707+ATNyPmQ1oyKSgndzXij81FzWGsejg= -k8s.io/apimachinery v0.26.1 h1:8EZ/eGJL+hY/MYCNwhmDzVqq2lPl3N3Bo8rvweJwXUQ= -k8s.io/apimachinery v0.26.1/go.mod h1:tnPmbONNJ7ByJNz9+n9kMjNP8ON+1qoAIIC70lztu74= -k8s.io/client-go v0.26.1 h1:87CXzYJnAMGaa/IDDfRdhTzxk/wzGZ+/HUQpqgVSZXU= -k8s.io/client-go v0.26.1/go.mod h1:IWNSglg+rQ3OcvDkhY6+QLeasV4OYHDjdqeWkDQZwGE= -k8s.io/klog/v2 v2.80.1 h1:atnLQ121W371wYYFawwYx1aEY2eUfs4l3J72wtgAwV4= -k8s.io/klog/v2 v2.80.1/go.mod h1:y1WjHnz7Dj687irZUWR/WLkLc5N1YHtjLdmgWjndZn0= -k8s.io/kube-openapi v0.0.0-20221012153701-172d655c2280 h1:+70TFaan3hfJzs+7VK2o+OGxg8HsuBr/5f6tVAjDu6E= -k8s.io/kube-openapi v0.0.0-20221012153701-172d655c2280/go.mod h1:+Axhij7bCpeqhklhUTe3xmOn6bWxolyZEeyaFpjGtl4= -k8s.io/utils v0.0.0-20221107191617-1a15be271d1d h1:0Smp/HP1OH4Rvhe+4B8nWGERtlqAGSftbSbbmm45oFs= -k8s.io/utils v0.0.0-20221107191617-1a15be271d1d/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= +k8s.io/api v0.27.1 h1:Z6zUGQ1Vd10tJ+gHcNNNgkV5emCyW+v2XTmn+CLjSd0= +k8s.io/api v0.27.1/go.mod h1:z5g/BpAiD+f6AArpqNjkY+cji8ueZDU/WV1jcj5Jk4E= +k8s.io/apimachinery v0.27.1 h1:EGuZiLI95UQQcClhanryclaQE6xjg1Bts6/L3cD7zyc= +k8s.io/apimachinery v0.27.1/go.mod h1:5ikh59fK3AJ287GUvpUsryoMFtH9zj/ARfWCo3AyXTM= +k8s.io/client-go v0.27.1 h1:oXsfhW/qncM1wDmWBIuDzRHNS2tLhK3BZv512Nc59W8= +k8s.io/client-go v0.27.1/go.mod h1:f8LHMUkVb3b9N8bWturc+EDtVVVwZ7ueTVquFAJb2vA= +k8s.io/klog/v2 v2.90.1 h1:m4bYOKall2MmOiRaR1J+We67Do7vm9KiQVlT96lnHUw= +k8s.io/klog/v2 v2.90.1/go.mod h1:y1WjHnz7Dj687irZUWR/WLkLc5N1YHtjLdmgWjndZn0= +k8s.io/kube-openapi v0.0.0-20230308215209-15aac26d736a h1:gmovKNur38vgoWfGtP5QOGNOA7ki4n6qNYoFAgMlNvg= +k8s.io/kube-openapi v0.0.0-20230308215209-15aac26d736a/go.mod h1:y5VtZWM9sHHc2ZodIH/6SHzXj+TPU5USoA8lcIeKEKY= +k8s.io/metrics v0.27.1 h1:qIASSok+9dhKPrfAZmFreIdpgBgKTfXwkM9CQ+tNM90= +k8s.io/metrics v0.27.1/go.mod h1:5sYmQTC3aeL/24kkJ5fYECVuIz0xhO6oipfGJ81JC1Y= +k8s.io/utils v0.0.0-20230209194617-a36077c30491 h1:r0BAOLElQnnFhE/ApUsg3iHdVYYPBjNSSOMowRZxxsY= +k8s.io/utils v0.0.0-20230209194617-a36077c30491/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= mvdan.cc/gofumpt v0.0.0-20210107193838-d24d34e18d44/go.mod h1:yXG1r1WqZVKWbVRtBWKWX9+CxGYfA51nSomhM0woR48= mvdan.cc/gofumpt v0.1.0/go.mod h1:yXG1r1WqZVKWbVRtBWKWX9+CxGYfA51nSomhM0woR48= mvdan.cc/gofumpt v0.4.0 h1:JVf4NN1mIpHogBj7ABpgOyZc65/UUOkKQFkoURsz4MM= mvdan.cc/gofumpt v0.4.0/go.mod h1:PljLOHDeZqgS8opHRKLzp2It2VBuSdteAgqUfzMTxlQ= -sigs.k8s.io/json v0.0.0-20220713155537-f223a00ba0e2 h1:iXTIw73aPyC+oRdyqqvVJuloN1p0AC/kzH07hu3NE+k= -sigs.k8s.io/json v0.0.0-20220713155537-f223a00ba0e2/go.mod h1:B8JuhiUyNFVKdsE8h686QcCxMaH6HrOAZj4vswFpcB0= +sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd h1:EDPBXCAspyGV4jQlpZSudPeMmr1bNJefnuqLsRAsHZo= +sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd/go.mod h1:B8JuhiUyNFVKdsE8h686QcCxMaH6HrOAZj4vswFpcB0= sigs.k8s.io/structured-merge-diff/v4 v4.2.3 h1:PRbqxJClWWYMNV1dhaG4NsibJbArud9kFxnAMREiWFE= sigs.k8s.io/structured-merge-diff/v4 v4.2.3/go.mod h1:qjx8mGObPmV2aSZepjQjbmb2ihdVs8cGKBraizNC69E= sigs.k8s.io/yaml v1.3.0 h1:a2VclLzOGrwOHDiV8EfBGhvjHvP46CtW5j6POvhYGGo= diff --git a/internal/scout/resource/resource.go b/internal/scout/resource/resource.go index 4a63ef9374..6ad128abd7 100644 --- a/internal/scout/resource/resource.go +++ b/internal/scout/resource/resource.go @@ -10,7 +10,7 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/client" "github.com/sourcegraph/sourcegraph/lib/errors" - "github.com/sourcegraph/src-cli/internal/scout/resource/style" + "github.com/sourcegraph/src-cli/internal/scout/style" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" diff --git a/internal/scout/resource/style/Table.go b/internal/scout/style/Table.go similarity index 100% rename from internal/scout/resource/style/Table.go rename to internal/scout/style/Table.go diff --git a/internal/scout/usage/docker.go b/internal/scout/usage/docker.go new file mode 100644 index 0000000000..1a455e6f2a --- /dev/null +++ b/internal/scout/usage/docker.go @@ -0,0 +1,28 @@ +package usage + +import ( + "context" + "fmt" + + "github.com/docker/docker/client" +) + +func Docker(ctx context.Context, client client.Client, opts ...Option) error { + cfg := &Config{ + namespace: "default", + docker: true, + pod: "", + container: "", + spy: false, + k8sClient: nil, + dockerClient: &client, + metricsClient: nil, + } + + for _, opt := range opts { + opt(cfg) + } + + fmt.Println("Command is routed, but not yet fixed.") + return nil +} diff --git a/internal/scout/usage/k8s.go b/internal/scout/usage/k8s.go new file mode 100644 index 0000000000..e94d32e9a9 --- /dev/null +++ b/internal/scout/usage/k8s.go @@ -0,0 +1,398 @@ +package usage + +import ( + "bytes" + "context" + "fmt" + "os" + "regexp" + "strconv" + "strings" + + "github.com/charmbracelet/bubbles/table" + "github.com/charmbracelet/lipgloss" + "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/src-cli/internal/scout/style" + + "gopkg.in/inf.v0" + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/resource" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/client-go/kubernetes" + "k8s.io/client-go/kubernetes/scheme" + restclient "k8s.io/client-go/rest" + "k8s.io/client-go/tools/remotecommand" + metav1beta1 "k8s.io/metrics/pkg/apis/metrics/v1beta1" + metricsv "k8s.io/metrics/pkg/client/clientset/versioned" +) + +type ContainerMetrics struct { + podName string + limits map[string]Resources +} + +type Resources struct { + cpu *resource.Quantity + memory *resource.Quantity + storage *resource.Quantity +} + +const ( + ABillion float64 = 1000000000 +) + +func K8s( + ctx context.Context, + clientSet *kubernetes.Clientset, + metricsClient *metricsv.Clientset, + restConfig *restclient.Config, + opts ...Option, +) error { + cfg := &Config{ + namespace: "default", + docker: false, + pod: "", + container: "", + spy: false, + restConfig: restConfig, + k8sClient: clientSet, + dockerClient: nil, + metricsClient: metricsClient, + } + + for _, opt := range opts { + opt(cfg) + } + + return renderUsageTable(ctx, cfg) +} + +// renderUsageTable renders a table displaying resource usage for pods. + +// It returns: +// - Any error that occurred while rendering the table +func renderUsageTable(ctx context.Context, cfg *Config) error { + pods, err := getPods(ctx, cfg) + if err != nil { + return errors.Wrap(err, "could not get list of pods") + } + + columns := []table.Column{ + {Title: "Container", Width: 20}, + {Title: "Cores", Width: 10}, + {Title: "Usage(%)", Width: 10}, + {Title: "Memory", Width: 10}, + {Title: "Usage(%)", Width: 10}, + {Title: "Storage", Width: 10}, + {Title: "Usage(%)", Width: 10}, + } + var rows []table.Row + + for _, pod := range pods { + containerMetrics := &ContainerMetrics{pod.Name, map[string]Resources{}} + podMetrics, err := getPodMetrics(ctx, cfg, pod) + if err != nil { + return errors.Wrap(err, "while attempting to fetch pod metrics") + } + + if err = getLimits(ctx, cfg, &pod, containerMetrics); err != nil { + return errors.Wrap(err, "failed to get get container metrics") + } + + for _, container := range podMetrics.Containers { + row, err := makeUsageRow(ctx, cfg, *containerMetrics, pod, container) + if err != nil { + return errors.Wrap(err, "could not compile usage data for row") + } + rows = append(rows, row) + } + } + + style.ResourceTable(columns, rows) + return nil +} + +// getPods returns a list of pods in the given namespace. +// It returns: +// - []v1.Pod: A list of pods in the given namespace +// - error: Any error that occurred while listing the pods +// +// If no pods are found in the given namespace, it will print an error message and exit. +func getPods(ctx context.Context, cfg *Config) ([]corev1.Pod, error) { + podInterface := cfg.k8sClient.CoreV1().Pods(cfg.namespace) + podList, err := podInterface.List(ctx, metav1.ListOptions{}) + if err != nil { + return []corev1.Pod{}, errors.Wrap(err, "could not list pods") + } + + if len(podList.Items) == 0 { + msg := lipgloss.NewStyle().Foreground(lipgloss.Color("#FFA500")) + fmt.Println(msg.Render(` + No pods exist in this namespace. + Did you mean to use the --namespace flag? + + If you are attempting to check + resources for a docker deployment, you + must use the --docker flag. + See --help for more info. + `)) + os.Exit(1) + } + + return podList.Items, nil +} + +// makeUsageRow generates a table row containing resource usage data for a container. +// +// It returns: +// - A table.Row containing the resource usage information +// - An error if there was an issue generating the row +func makeUsageRow( + ctx context.Context, + cfg *Config, + metrics ContainerMetrics, + pod corev1.Pod, + container metav1beta1.ContainerMetrics, +) (table.Row, error) { + cpuUsage, err := getRawUsage(container.Usage, "cpu") + if err != nil { + return table.Row{}, errors.Wrap(err, "failed to get raw CPU usage") + } + + memUsage, err := getRawUsage(container.Usage, "memory") + if err != nil { + return table.Row{}, errors.Wrap(err, "failed to get raw memory usage") + } + + limits := metrics.limits[container.Name] + + cpuUsagePercent := getPercentage( + cpuUsage, + limits.cpu.AsApproximateFloat64()*ABillion, + ) + + memUsagePercent := getPercentage( + memUsage, + limits.memory.AsApproximateFloat64(), + ) + + storageVal := limits.storage.String() + if metrics.limits[container.Name].storage == nil { + storageVal = "-" + } + + stateless := []string{ + "cadvisor", + "pgsql-exporter", + "executor", + "dind", + "github-proxy", + "jaeger", + "node-exporter", + "otel-agent", + "otel-collector", + "precise-code-intel-worker", + "redis-exporter", + "repo-updater", + "frontend", + "syntect-server", + "worker", + } + + var storageUsagePercent string + if contains(stateless, container.Name) { + storageUsagePercent = "-" + } else { + storageUsagePercent, err = getStorageUsage(ctx, cfg, pod.Name, container.Name) + if err != nil { + return table.Row{}, errors.Wrap(err, "failed to get storage usage") + } + } + + row := table.Row{ + container.Name, + metrics.limits[container.Name].cpu.String(), + fmt.Sprintf("%.2f%%", cpuUsagePercent), + metrics.limits[container.Name].memory.String(), + fmt.Sprintf("%.2f%%", memUsagePercent), + storageVal, + storageUsagePercent, + } + + return row, nil +} + +// getPodMetrics retrieves metrics for a given pod. +// +// It returns: +// - podMetrics: The PodMetrics object containing metrics for the pod +// - err: Any error that occurred while getting the pod metrics +func getPodMetrics( + ctx context.Context, + cfg *Config, + pod corev1.Pod, +) (*metav1beta1.PodMetrics, error) { + podMetrics, err := cfg.metricsClient. + MetricsV1beta1(). + PodMetricses(cfg.namespace). + Get(ctx, pod.Name, metav1.GetOptions{}) + if err != nil { + return nil, errors.Wrap(err, "failed to get pod metrics") + } + + return podMetrics, nil +} + +// getLimits extracts resource limits for containers in a pod and stores +// them in a ContainerMetrics struct. +// +// It populates the containerMetrics struct with: +// - The name of each container +// - The CPU, memory, ephemeral storage, and storage resource limits for each container +// - A print method to print the resource limits for each container +func getLimits( + ctx context.Context, + cfg *Config, + pod *corev1.Pod, + containerMetrics *ContainerMetrics, +) error { + for _, container := range pod.Spec.Containers { + containerName := container.Name + capacity, err := getPvcCapacity(ctx, cfg, container, pod) + if err != nil { + return errors.Wrap(err, "while getting storage capacity of PV") + } + + rsrcs := Resources{ + cpu: container.Resources.Limits.Cpu().ToDec(), + memory: container.Resources.Limits.Memory().ToDec(), + storage: capacity, + } + containerMetrics.limits[containerName] = rsrcs + } + return nil +} + +// getRawUsage converts a Kubernetes ResourceList (map[ResourceName]Quantity) +// into a raw float64 usage value for a given resource. +// +// It returns: +// - The raw float64 usage value for the target resource +// - Any error that occurred during conversion +func getRawUsage(usages corev1.ResourceList, targetKey string) (float64, error) { + var usage *inf.Dec + + for key, val := range usages { + if key.String() == targetKey { + usage = val.AsDec().SetScale(0) + } + } + + toFloat, err := strconv.ParseFloat(usage.String(), 64) + if err != nil { + return 0, errors.Wrap(err, "failed to convert inf.Dec type to float") + } + + return toFloat, nil +} + +// getPvcCapacity retrieves the storage capacity of a PersistentVolumeClaim +// mounted as a volume by a container. +// +// It returns: +// - The capacity Quantity of the PVC if a matching PVC mount is found +// - nil if no PVC mount is found +// - Any error that occurred while getting the PVC +func getPvcCapacity( + ctx context.Context, + cfg *Config, container corev1.Container, + pod *corev1.Pod, +) (*resource.Quantity, error) { + for _, volumeMount := range container.VolumeMounts { + for _, volume := range pod.Spec.Volumes { + if volume.Name == volumeMount.Name && volume.PersistentVolumeClaim != nil { + pvc, err := cfg.k8sClient. + CoreV1(). + PersistentVolumeClaims(cfg.namespace). + Get( + ctx, + volume.PersistentVolumeClaim.ClaimName, + metav1.GetOptions{}, + ) + if err != nil { + return nil, errors.Wrapf( + err, + "failed to get PVC %s", + volume.PersistentVolumeClaim.ClaimName, + ) + } + return pvc.Status.Capacity.Storage().ToDec(), nil + } + } + } + return nil, nil +} + +// getStorageUsage executes the df -h command in a container and parses the +// output to get the storage usage percentage for ephemeral storage volumes. +// +// It returns: +// - The storage usage percentage for storage volumes +// - "-" if no storage volumes are found +// - Any error that occurred while executing the df -h command or parsing the output +func getStorageUsage( + ctx context.Context, + cfg *Config, podName, + containerName string, +) (string, error) { + req := cfg.k8sClient.CoreV1().RESTClient().Post(). + Resource("pods"). + Name(podName). + Namespace(cfg.namespace). + SubResource("exec") + + req.VersionedParams(&corev1.PodExecOptions{ + Container: containerName, + Command: []string{"df", "-h"}, + Stdin: false, + Stdout: true, + Stderr: true, + TTY: false, + }, scheme.ParameterCodec) + + exec, err := remotecommand.NewSPDYExecutor(cfg.restConfig, "POST", req.URL()) + if err != nil { + return "", err + } + + var stdout, stderr bytes.Buffer + err = exec.StreamWithContext(ctx, remotecommand.StreamOptions{ + Stdout: &stdout, + Stderr: &stderr, + }) + if err != nil { + return "", err + } + + lines := strings.Split(stdout.String(), "\n") + for _, line := range lines[1 : len(lines)-1] { + fields := strings.Fields(line) + + if acceptedFileSystem(fields[0]) { + return fields[4], nil + } + } + + return "-", nil +} + +// acceptedFileSystem checks if a given file system, represented +// as a string, is an accepted system. +// +// It returns: +// - True if the file system matches the pattern '/dev/sd[a-z]$' +// - False otherwise +func acceptedFileSystem(fileSystem string) bool { + matched, _ := regexp.MatchString(`/dev/sd[a-z]$`, fileSystem) + return matched +} diff --git a/internal/scout/usage/usage.go b/internal/scout/usage/usage.go new file mode 100644 index 0000000000..58cd2e848e --- /dev/null +++ b/internal/scout/usage/usage.go @@ -0,0 +1,68 @@ +package usage + +import ( + "github.com/docker/docker/client" + "k8s.io/client-go/kubernetes" + "k8s.io/client-go/rest" + metricsv "k8s.io/metrics/pkg/client/clientset/versioned" +) + +type Option = func(config *Config) +type Config struct { + namespace string + pod string + container string + spy bool + docker bool + restConfig *rest.Config + k8sClient *kubernetes.Clientset + dockerClient *client.Client + metricsClient *metricsv.Clientset +} + +func WithNamespace(namespace string) Option { + return func(config *Config) { + config.namespace = namespace + } +} + +func WithPod(podname string) Option { + return func(config *Config) { + config.pod = podname + } +} + +func WithContainer(containerName string) Option { + return func(config *Config) { + config.container = containerName + } +} + +func WithSpy(spy bool) Option { + return func(config *Config) { + config.spy = true + } +} + +// contains checks if a string slice contains a given value. +func contains(slice []string, value string) bool { + for _, v := range slice { + if v == value { + return true + } + } + return false +} + +// getPercentage calculates the percentage of x in relation to y. +func getPercentage(x, y float64) float64 { + if x == 0 { + return 0 + } + + if y == 0 { + return 0 + } + + return x * 100 / y +} diff --git a/internal/scout/usage/usage_test.go b/internal/scout/usage/usage_test.go new file mode 100644 index 0000000000..71e7731ac4 --- /dev/null +++ b/internal/scout/usage/usage_test.go @@ -0,0 +1,191 @@ +package usage + +import ( + "testing" + + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/resource" +) + +func TestGetPercentage(t *testing.T) { + cases := []struct { + name string + x float64 + y float64 + want float64 + shouldError bool + }{ + { + name: "should return 0 if x is 0", + x: 0, + y: 1, + want: 0, + shouldError: false, + }, + { + name: "should return correct percentage", + x: 36, + y: 72, + want: 50, + shouldError: false, + }, + { + name: "should return correct percentage", + x: 75, + y: 100, + want: 75, + shouldError: false, + }, + { + name: "should return correct percentages over 100%", + x: 3800, + y: 2000, + want: 190, + shouldError: false, + }, + { + name: "should return 0 if y is 0", + x: 75, + y: 0, + want: 0, + shouldError: true, + }, + } + + for _, tc := range cases { + tc := tc + t.Run(tc.name, func(t *testing.T) { + got := getPercentage(tc.x, tc.y) + + if got != tc.want { + t.Errorf("got %.2f want %.2f", tc.want, got) + } + }) + } +} + +func TestGetRawUsage(t *testing.T) { + cases := []struct { + name string + cpu *resource.Quantity + mem *resource.Quantity + targetKey string + want float64 + shouldError bool + }{ + { + name: "return cpu usage in nanocores", + cpu: resource.NewQuantity(2756053, resource.Format("BinarySI")), + mem: resource.NewQuantity(838374, resource.Format("BinarySI")), + targetKey: "cpu", + want: 2756053, + shouldError: false, + }, + { + name: "return memory usage in KiB", + cpu: resource.NewQuantity(8926483, resource.Format("BinarySI")), + mem: resource.NewQuantity(2332343, resource.Format("BinarySI")), + targetKey: "memory", + want: 2332343, + shouldError: false, + }, + { + name: "should error with non-existant targetKey", + cpu: resource.NewQuantity(8, resource.Format("BinarySI")), + mem: resource.NewQuantity(2, resource.Format("BinarySI")), + targetKey: "mem", + want: 0, + shouldError: true, + }, + } + + for _, tc := range cases { + tc := tc + t.Run(tc.name, func(t *testing.T) { + resourceList := resourceListHelper(tc.cpu, tc.mem) + got, err := getRawUsage(resourceList, tc.targetKey) + if !tc.shouldError && err != nil { + t.Errorf("unexpected error: %v", err) + } + + want := tc.want + if got != want { + t.Errorf("got %v, want %v", got, want) + } + }) + } +} + +func TestContains(t *testing.T) { + cases := []struct { + name string + s []string + val string + want bool + }{ + { + name: "should return true if given slice contains given value", + s: []string{"this", "is", "a", "unit", "test"}, + val: "unit", + want: true, + }, + { + name: "should return false if given slice does not contains given value", + s: []string{"this", "is", "a", "unit", "test"}, + val: "foobar", + want: false, + }, + { + name: "should return true if given slice contains for than one instance of the given value", + s: []string{"this", "is", "a", "unit", "unit", "test", "unit"}, + val: "unit", + want: true, + }, + } + + for _, tc := range cases { + tc := tc + t.Run(tc.name, func(t *testing.T) { + got := contains(tc.s, tc.val) + if got != tc.want { + t.Errorf("got %v, want %v", got, tc.want) + } + }) + } +} + +func TestAcceptedFileSystem(t *testing.T) { + cases := []struct { + name string + filesystem string + want bool + }{ + { + name: "should return true if filesystem matches 'matched' regular expression", + filesystem: "/dev/sda", + want: true, + }, + { + name: "should return false if filesystem doesn't match 'matched' regular expression", + filesystem: "/dev/sda1", + want: false, + }, + } + + for _, tc := range cases { + tc := tc + t.Run(tc.name, func(t *testing.T) { + got := acceptedFileSystem(tc.filesystem) + if got != tc.want { + t.Errorf("got %v want %v", got, tc.want) + } + }) + } +} + +func resourceListHelper(cpu *resource.Quantity, mem *resource.Quantity) corev1.ResourceList { + return corev1.ResourceList{ + corev1.ResourceCPU: *cpu, + corev1.ResourceMemory: *mem, + } +} From 4effedaaa3efd4a70c830eae3dbf31d4f48bd1a1 Mon Sep 17 00:00:00 2001 From: Jason Hawk Harris Date: Wed, 24 May 2023 13:57:01 -0500 Subject: [PATCH 337/647] Adds the `--pod` flag to `scout usage` (#984) * add functionality for getting usage for single pod * refactor for clarity and smaller function bodies * add better mechanism for getting storage capacity and usage --- internal/scout/usage/k8s.go | 308 ++++++++++++++++++++++++------------ 1 file changed, 204 insertions(+), 104 deletions(-) diff --git a/internal/scout/usage/k8s.go b/internal/scout/usage/k8s.go index e94d32e9a9..5380cca98e 100644 --- a/internal/scout/usage/k8s.go +++ b/internal/scout/usage/k8s.go @@ -37,6 +37,16 @@ type Resources struct { storage *resource.Quantity } +type UsageStats struct { + containerName string + cpuCores *resource.Quantity + memory *resource.Quantity + storage *resource.Quantity + cpuUsage float64 + memoryUsage float64 + storageUsage float64 +} + const ( ABillion float64 = 1000000000 ) @@ -64,19 +74,121 @@ func K8s( opt(cfg) } - return renderUsageTable(ctx, cfg) + pods, err := getPods(ctx, cfg) + if err != nil { + return errors.Wrap(err, "could not get list of pods") + } + + if cfg.pod != "" { + return renderSinglePodUsageTable(ctx, cfg, pods) + } + + return renderUsageTable(ctx, cfg, pods) } -// renderUsageTable renders a table displaying resource usage for pods. +// renderSinglePodUsageStats prints resource usage statistics for a single pod. +func renderSinglePodUsageTable(ctx context.Context, cfg *Config, pods []corev1.Pod) error { + pod, err := getPod(cfg, pods) + if err != nil { + return errors.Wrapf(err, "could not get pod with name %s", cfg.pod) + } + + podMetrics, err := getPodMetrics(ctx, cfg, pod) + if err != nil { + return errors.Wrap(err, "while attempting to fetch pod metrics") + } + + containerMetrics := &ContainerMetrics{cfg.pod, map[string]Resources{}} + if err = getLimits(ctx, cfg, &pod, containerMetrics); err != nil { + return errors.Wrap(err, "failed to get get container metrics") + } + columns := []table.Column{ + {Title: "Container", Width: 20}, + {Title: "Cores", Width: 10}, + {Title: "Usage(%)", Width: 10}, + {Title: "Memory", Width: 10}, + {Title: "Usage(%)", Width: 10}, + {Title: "Storage", Width: 10}, + {Title: "Usage(%)", Width: 10}, + } + var rows []table.Row + + for _, container := range podMetrics.Containers { + stats, err := getContainerUsageStats(ctx, cfg, *containerMetrics, pod, container) + if err != nil { + return errors.Wrapf(err, "could not compile usage data for row: %s\n", container.Name) + } + + row := makeRow(stats) + rows = append(rows, row) + } + + style.ResourceTable(columns, rows) + return nil +} + +// getPod returns a Pod object with the given name. +// +// If a Pod with the given name exists in pods, it is returned. +// Otherwise, an error is returned indicating no Pod with that name exists. +func getPod(cfg *Config, pods []corev1.Pod) (corev1.Pod, error) { + for _, p := range pods { + if p.Name == cfg.pod { + return p, nil + } + } + return corev1.Pod{}, errors.New("no pod with this name exists in this namespace") +} + +// getPodMetrics retrieves metrics for a given pod. +// // It returns: -// - Any error that occurred while rendering the table -func renderUsageTable(ctx context.Context, cfg *Config) error { - pods, err := getPods(ctx, cfg) +// - podMetrics: The PodMetrics object containing metrics for the pod +// - err: Any error that occurred while getting the pod metrics +func getPodMetrics(ctx context.Context, cfg *Config, pod corev1.Pod) (*metav1beta1.PodMetrics, error) { + podMetrics, err := cfg.metricsClient. + MetricsV1beta1(). + PodMetricses(cfg.namespace). + Get(ctx, pod.Name, metav1.GetOptions{}) if err != nil { - return errors.Wrap(err, "could not get list of pods") + return nil, errors.Wrap(err, "failed to get pod metrics") } + return podMetrics, nil +} + +// getLimits extracts resource limits for containers in a pod and stores +// them in a ContainerMetrics struct. +// +// It populates the containerMetrics struct with: +// - The name of each container +// - The CPU, memory, ephemeral storage, and storage resource limits for each container +// - A print method to print the resource limits for each container +func getLimits(ctx context.Context, cfg *Config, pod *corev1.Pod, containerMetrics *ContainerMetrics) error { + for _, container := range pod.Spec.Containers { + containerName := container.Name + capacity, err := getPvcCapacity(ctx, cfg, container, pod) + if err != nil { + return errors.Wrap(err, "while getting storage capacity of PV") + } + + rsrcs := Resources{ + cpu: container.Resources.Limits.Cpu().ToDec(), + memory: container.Resources.Limits.Memory().ToDec(), + storage: capacity, + } + containerMetrics.limits[containerName] = rsrcs + } + + return nil +} + +// renderUsageTable renders a table displaying resource usage for pods. + +// It returns: +// - Any error that occurred while rendering the table +func renderUsageTable(ctx context.Context, cfg *Config, pods []corev1.Pod) error { columns := []table.Column{ {Title: "Container", Width: 20}, {Title: "Cores", Width: 10}, @@ -100,10 +212,12 @@ func renderUsageTable(ctx context.Context, cfg *Config) error { } for _, container := range podMetrics.Containers { - row, err := makeUsageRow(ctx, cfg, *containerMetrics, pod, container) + stats, err := getContainerUsageStats(ctx, cfg, *containerMetrics, pod, container) if err != nil { - return errors.Wrap(err, "could not compile usage data for row") + return errors.Wrapf(err, "could not compile usage data for row %s\n", container.Name) } + + row := makeRow(stats) rows = append(rows, row) } } @@ -112,6 +226,34 @@ func renderUsageTable(ctx context.Context, cfg *Config) error { return nil } +// makeRow generates a table row containing resource usage data for a container. +// It returns: +// - A table.Row containing the resource usage information +// - An error if there was an issue generating the row +func makeRow(usageStats UsageStats) table.Row { + if usageStats.storage == nil { + return table.Row{ + usageStats.containerName, + usageStats.cpuCores.String(), + fmt.Sprintf("%.2f%%", usageStats.cpuUsage), + usageStats.memory.String(), + fmt.Sprintf("%.2f%%", usageStats.memoryUsage), + "-", + "-", + } + } + + return table.Row{ + usageStats.containerName, + usageStats.cpuCores.String(), + fmt.Sprintf("%.2f%%", usageStats.cpuUsage), + usageStats.memory.String(), + fmt.Sprintf("%.2f%%", usageStats.memoryUsage), + usageStats.storage.String(), + fmt.Sprintf("%.2f%%", usageStats.storageUsage), + } +} + // getPods returns a list of pods in the given namespace. // It returns: // - []v1.Pod: A list of pods in the given namespace @@ -147,40 +289,28 @@ func getPods(ctx context.Context, cfg *Config) ([]corev1.Pod, error) { // It returns: // - A table.Row containing the resource usage information // - An error if there was an issue generating the row -func makeUsageRow( +func getContainerUsageStats( ctx context.Context, cfg *Config, metrics ContainerMetrics, pod corev1.Pod, container metav1beta1.ContainerMetrics, -) (table.Row, error) { +) (UsageStats, error) { + var usageStats UsageStats + usageStats.containerName = container.Name + cpuUsage, err := getRawUsage(container.Usage, "cpu") if err != nil { - return table.Row{}, errors.Wrap(err, "failed to get raw CPU usage") + return UsageStats{}, errors.Wrap(err, "failed to get raw CPU usage") } memUsage, err := getRawUsage(container.Usage, "memory") if err != nil { - return table.Row{}, errors.Wrap(err, "failed to get raw memory usage") - } - - limits := metrics.limits[container.Name] - - cpuUsagePercent := getPercentage( - cpuUsage, - limits.cpu.AsApproximateFloat64()*ABillion, - ) - - memUsagePercent := getPercentage( - memUsage, - limits.memory.AsApproximateFloat64(), - ) - - storageVal := limits.storage.String() - if metrics.limits[container.Name].storage == nil { - storageVal = "-" + return UsageStats{}, errors.Wrap(err, "failed to get raw memory usage") } + var storageCapacity float64 + var storageUsage float64 stateless := []string{ "cadvisor", "pgsql-exporter", @@ -199,78 +329,47 @@ func makeUsageRow( "worker", } - var storageUsagePercent string if contains(stateless, container.Name) { - storageUsagePercent = "-" + storageUsage = 0 + storageCapacity = 0 } else { - storageUsagePercent, err = getStorageUsage(ctx, cfg, pod.Name, container.Name) + storageCapacity, storageUsage, err = getStorageUsage(ctx, cfg, pod.Name, container.Name) if err != nil { - return table.Row{}, errors.Wrap(err, "failed to get storage usage") + return UsageStats{}, errors.Wrap(err, "failed to get storage usage") } } - row := table.Row{ - container.Name, - metrics.limits[container.Name].cpu.String(), - fmt.Sprintf("%.2f%%", cpuUsagePercent), - metrics.limits[container.Name].memory.String(), - fmt.Sprintf("%.2f%%", memUsagePercent), - storageVal, - storageUsagePercent, - } + limits := metrics.limits[container.Name] - return row, nil -} + usageStats.cpuCores = limits.cpu + usageStats.cpuUsage = getPercentage( + cpuUsage, + limits.cpu.AsApproximateFloat64()*ABillion, + ) -// getPodMetrics retrieves metrics for a given pod. -// -// It returns: -// - podMetrics: The PodMetrics object containing metrics for the pod -// - err: Any error that occurred while getting the pod metrics -func getPodMetrics( - ctx context.Context, - cfg *Config, - pod corev1.Pod, -) (*metav1beta1.PodMetrics, error) { - podMetrics, err := cfg.metricsClient. - MetricsV1beta1(). - PodMetricses(cfg.namespace). - Get(ctx, pod.Name, metav1.GetOptions{}) - if err != nil { - return nil, errors.Wrap(err, "failed to get pod metrics") - } + usageStats.memory = limits.memory + usageStats.memoryUsage = getPercentage( + memUsage, + limits.memory.AsApproximateFloat64(), + ) - return podMetrics, nil -} + if limits.storage == nil { + storageDec := *inf.NewDec(0, 0) + usageStats.storage = resource.NewDecimalQuantity(storageDec, resource.Format("DecimalSI")) + } else { + usageStats.storage = limits.storage + } -// getLimits extracts resource limits for containers in a pod and stores -// them in a ContainerMetrics struct. -// -// It populates the containerMetrics struct with: -// - The name of each container -// - The CPU, memory, ephemeral storage, and storage resource limits for each container -// - A print method to print the resource limits for each container -func getLimits( - ctx context.Context, - cfg *Config, - pod *corev1.Pod, - containerMetrics *ContainerMetrics, -) error { - for _, container := range pod.Spec.Containers { - containerName := container.Name - capacity, err := getPvcCapacity(ctx, cfg, container, pod) - if err != nil { - return errors.Wrap(err, "while getting storage capacity of PV") - } + usageStats.storageUsage = getPercentage( + storageUsage, + storageCapacity, + ) - rsrcs := Resources{ - cpu: container.Resources.Limits.Cpu().ToDec(), - memory: container.Resources.Limits.Memory().ToDec(), - storage: capacity, - } - containerMetrics.limits[containerName] = rsrcs + if metrics.limits[container.Name].storage == nil { + usageStats.storage = nil } - return nil + + return usageStats, nil } // getRawUsage converts a Kubernetes ResourceList (map[ResourceName]Quantity) @@ -303,11 +402,7 @@ func getRawUsage(usages corev1.ResourceList, targetKey string) (float64, error) // - The capacity Quantity of the PVC if a matching PVC mount is found // - nil if no PVC mount is found // - Any error that occurred while getting the PVC -func getPvcCapacity( - ctx context.Context, - cfg *Config, container corev1.Container, - pod *corev1.Pod, -) (*resource.Quantity, error) { +func getPvcCapacity(ctx context.Context, cfg *Config, container corev1.Container, pod *corev1.Pod) (*resource.Quantity, error) { for _, volumeMount := range container.VolumeMounts { for _, volume := range pod.Spec.Volumes { if volume.Name == volumeMount.Name && volume.PersistentVolumeClaim != nil { @@ -340,11 +435,7 @@ func getPvcCapacity( // - The storage usage percentage for storage volumes // - "-" if no storage volumes are found // - Any error that occurred while executing the df -h command or parsing the output -func getStorageUsage( - ctx context.Context, - cfg *Config, podName, - containerName string, -) (string, error) { +func getStorageUsage(ctx context.Context, cfg *Config, podName, containerName string) (float64, float64, error) { req := cfg.k8sClient.CoreV1().RESTClient().Post(). Resource("pods"). Name(podName). @@ -353,7 +444,7 @@ func getStorageUsage( req.VersionedParams(&corev1.PodExecOptions{ Container: containerName, - Command: []string{"df", "-h"}, + Command: []string{"df"}, Stdin: false, Stdout: true, Stderr: true, @@ -362,7 +453,7 @@ func getStorageUsage( exec, err := remotecommand.NewSPDYExecutor(cfg.restConfig, "POST", req.URL()) if err != nil { - return "", err + return 0, 0, err } var stdout, stderr bytes.Buffer @@ -371,7 +462,7 @@ func getStorageUsage( Stderr: &stderr, }) if err != nil { - return "", err + return 0, 0, err } lines := strings.Split(stdout.String(), "\n") @@ -379,11 +470,20 @@ func getStorageUsage( fields := strings.Fields(line) if acceptedFileSystem(fields[0]) { - return fields[4], nil + capacityFloat, err := strconv.ParseFloat(fields[1], 64) + if err != nil { + return 0, 0, errors.Wrap(err, "could not convert string to float64") + } + + usageFloat, err := strconv.ParseFloat(fields[2], 64) + if err != nil { + return 0, 0, errors.Wrap(err, "could not convert string to float64") + } + return capacityFloat, usageFloat, nil } } - return "-", nil + return 0, 0, nil } // acceptedFileSystem checks if a given file system, represented From d9d8ca6836753e793b8ed5444d1d42708c8efe60 Mon Sep 17 00:00:00 2001 From: Jason Hawk Harris Date: Thu, 25 May 2023 14:39:57 -0500 Subject: [PATCH 338/647] scout/usage: add `--docker` flag to `scout usage` tool (#985) prints CPU and Memory usage for each running container in a docker deployment of sourcegraph --- internal/scout/usage/docker.go | 77 ++++++++++++++++++++++++++++++---- 1 file changed, 68 insertions(+), 9 deletions(-) diff --git a/internal/scout/usage/docker.go b/internal/scout/usage/docker.go index 1a455e6f2a..7e953fe2fe 100644 --- a/internal/scout/usage/docker.go +++ b/internal/scout/usage/docker.go @@ -2,27 +2,86 @@ package usage import ( "context" + "encoding/json" "fmt" + "github.com/charmbracelet/bubbles/table" + "github.com/docker/docker/api/types" "github.com/docker/docker/client" + "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/src-cli/internal/scout/style" ) func Docker(ctx context.Context, client client.Client, opts ...Option) error { cfg := &Config{ - namespace: "default", - docker: true, - pod: "", - container: "", - spy: false, - k8sClient: nil, - dockerClient: &client, - metricsClient: nil, + namespace: "default", + docker: true, + pod: "", + container: "", + spy: false, + dockerClient: &client, } for _, opt := range opts { opt(cfg) } - fmt.Println("Command is routed, but not yet fixed.") + containers, err := cfg.dockerClient.ContainerList(ctx, types.ContainerListOptions{}) + if err != nil { + return errors.Wrap(err, "could not get list of containers") + } + + return renderDockerUsageTable(ctx, cfg, containers) +} + +// renderDockerUsageTable renders a table displaying CPU and memory usage for Docker containers. +func renderDockerUsageTable(ctx context.Context, cfg *Config, containers []types.Container) error { + columns := []table.Column{ + {Title: "Container", Width: 20}, + {Title: "Cores", Width: 10}, + {Title: "Usage", Width: 10}, + {Title: "Memory", Width: 10}, + {Title: "Usage", Width: 10}, + } + rows := []table.Row{} + + for _, container := range containers { + containerInfo, err := cfg.dockerClient.ContainerInspect(ctx, container.ID) + if err != nil { + return errors.Wrap(err, "failed to get container info") + } + + stats, err := cfg.dockerClient.ContainerStats(ctx, container.ID, false) + if err != nil { + return errors.Wrap(err, "could not get container stats") + } + defer stats.Body.Close() + + var usage types.StatsJSON + if err := json.NewDecoder(stats.Body).Decode(&usage); err != nil { + return errors.Wrap(err, "could not decode container stats") + } + + row := makeDockerUsageRow(usage, containerInfo) + rows = append(rows, row) + } + + style.ResourceTable(columns, rows) return nil } + +// makeDockerUsageRow generates a table row displaying CPU and memory usage for a Docker container. +func makeDockerUsageRow(containerUsage types.StatsJSON, containerInfo types.ContainerJSON) table.Row { + cpuCores := float64(containerInfo.HostConfig.NanoCPUs) + memory := float64(containerInfo.HostConfig.Memory) + cpuUsage := float64(containerUsage.CPUStats.CPUUsage.TotalUsage) + memoryUsage := float64(containerUsage.MemoryStats.Usage) + + return table.Row{ + containerInfo.Name, + fmt.Sprintf("%.2f", cpuCores/1_000_000_000), + fmt.Sprintf("%.2f%%", getPercentage(cpuUsage, cpuCores)), + fmt.Sprintf("%.2fG", memory/1_000_000_000), + fmt.Sprintf("%.2f%%", getPercentage(memoryUsage, memory)), + } +} From 391d9162ba832304263efbd99a149700afacd335 Mon Sep 17 00:00:00 2001 From: Jason Hawk Harris Date: Fri, 26 May 2023 10:29:22 -0500 Subject: [PATCH 339/647] scout/usage: add `--container` flag to `src scout usage` (#986) --- cmd/src/scout_usage.go | 11 +++++-- internal/scout/usage/docker.go | 58 ++++++++++++++++++++++++---------- 2 files changed, 51 insertions(+), 18 deletions(-) diff --git a/cmd/src/scout_usage.go b/cmd/src/scout_usage.go index 1158223f88..1ac7fc4257 100644 --- a/cmd/src/scout_usage.go +++ b/cmd/src/scout_usage.go @@ -29,6 +29,9 @@ func init() { Check usage for specific pod $ src scout usage --pod + Check usage for specific container (docker only) + $ src scout usage --container + Add namespace if using namespace in a Kubernetes cluster $ src scout usage --namespace @@ -47,6 +50,7 @@ func init() { kubeConfig *string namespace = flagSet.String("namespace", "", "(optional) specify the kubernetes namespace to use") pod = flagSet.String("pod", "", "(optional) specify a single pod") + container = flagSet.String("container", "", "(optional) specify a single container") docker = flagSet.Bool("docker", false, "(optional) using docker deployment") spy = flagSet.Bool("spy", false, "(optional) see resource usage in real time") ) @@ -92,14 +96,17 @@ func init() { if *pod != "" { options = append(options, usage.WithPod(*pod)) } + if *container != "" || *docker { + if *container != "" { + options = append(options, usage.WithContainer(*container)) + } - if *docker { dockerClient, err := client.NewClientWithOpts(client.FromEnv) if err != nil { return errors.Wrap(err, "error creating docker client: ") } - return usage.Docker(context.Background(), *dockerClient) + return usage.Docker(context.Background(), *dockerClient, options...) } return usage.K8s( diff --git a/internal/scout/usage/docker.go b/internal/scout/usage/docker.go index 7e953fe2fe..5bb96f672d 100644 --- a/internal/scout/usage/docker.go +++ b/internal/scout/usage/docker.go @@ -4,8 +4,10 @@ import ( "context" "encoding/json" "fmt" + "os" "github.com/charmbracelet/bubbles/table" + "github.com/charmbracelet/lipgloss" "github.com/docker/docker/api/types" "github.com/docker/docker/client" "github.com/sourcegraph/sourcegraph/lib/errors" @@ -51,34 +53,58 @@ func renderDockerUsageTable(ctx context.Context, cfg *Config, containers []types return errors.Wrap(err, "failed to get container info") } - stats, err := cfg.dockerClient.ContainerStats(ctx, container.ID, false) - if err != nil { - return errors.Wrap(err, "could not get container stats") - } - defer stats.Body.Close() - - var usage types.StatsJSON - if err := json.NewDecoder(stats.Body).Decode(&usage); err != nil { - return errors.Wrap(err, "could not decode container stats") + if cfg.container != "" { + if containerInfo.Name == cfg.container { + row := makeDockerUsageRow(ctx, cfg, containerInfo) + rows = append(rows, row) + break + } else { + continue + } } - row := makeDockerUsageRow(usage, containerInfo) + row := makeDockerUsageRow(ctx, cfg, containerInfo) rows = append(rows, row) } + if len(rows) == 0 { + msg := lipgloss.NewStyle().Foreground(lipgloss.Color("#FFA500")) + if cfg.container == "" { + fmt.Println(msg.Render(`No docker containers are running.`)) + os.Exit(1) + } + fmt.Println(msg.Render( + fmt.Sprintf(`No container with name '%s' running.`, cfg.container), + )) + os.Exit(1) + } + style.ResourceTable(columns, rows) return nil } // makeDockerUsageRow generates a table row displaying CPU and memory usage for a Docker container. -func makeDockerUsageRow(containerUsage types.StatsJSON, containerInfo types.ContainerJSON) table.Row { - cpuCores := float64(containerInfo.HostConfig.NanoCPUs) - memory := float64(containerInfo.HostConfig.Memory) - cpuUsage := float64(containerUsage.CPUStats.CPUUsage.TotalUsage) - memoryUsage := float64(containerUsage.MemoryStats.Usage) +func makeDockerUsageRow(ctx context.Context, cfg *Config, container types.ContainerJSON) table.Row { + stats, err := cfg.dockerClient.ContainerStats(ctx, container.ID, false) + if err != nil { + errors.Wrap(err, "could not get container stats") + os.Exit(1) + } + defer func() { _ = stats.Body.Close() }() + + var usage types.StatsJSON + if err := json.NewDecoder(stats.Body).Decode(&usage); err != nil { + errors.Wrap(err, "could not get container stats") + os.Exit(1) + } + + cpuCores := float64(container.HostConfig.NanoCPUs) + memory := float64(container.HostConfig.Memory) + cpuUsage := float64(usage.CPUStats.CPUUsage.TotalUsage) + memoryUsage := float64(usage.MemoryStats.Usage) return table.Row{ - containerInfo.Name, + container.Name, fmt.Sprintf("%.2f", cpuCores/1_000_000_000), fmt.Sprintf("%.2f%%", getPercentage(cpuUsage, cpuCores)), fmt.Sprintf("%.2fG", memory/1_000_000_000), From 7fc662748f8813cd6b66f0f3ed0d79dcefba9f90 Mon Sep 17 00:00:00 2001 From: Jason Hawk Harris Date: Wed, 31 May 2023 14:04:45 -0500 Subject: [PATCH 340/647] correct headers for exporting usage data to file (#987) * correct headers for exporting usage data to file * remove print statement --- .../style/{Table.go => resource_table.go} | 20 +- internal/scout/style/usage_table.go | 180 ++++++++++++++++++ internal/scout/usage/docker.go | 2 +- internal/scout/usage/k8s.go | 2 +- 4 files changed, 192 insertions(+), 12 deletions(-) rename internal/scout/style/{Table.go => resource_table.go} (87%) create mode 100644 internal/scout/style/usage_table.go diff --git a/internal/scout/style/Table.go b/internal/scout/style/resource_table.go similarity index 87% rename from internal/scout/style/Table.go rename to internal/scout/style/resource_table.go index fe5830b9c5..218579e1a9 100644 --- a/internal/scout/style/Table.go +++ b/internal/scout/style/resource_table.go @@ -14,17 +14,17 @@ import ( "golang.design/x/clipboard" ) -var baseStyle = lipgloss.NewStyle(). +var resourceTableStyle = lipgloss.NewStyle(). BorderStyle(lipgloss.NormalBorder()). BorderForeground(lipgloss.Color("240")) -type model struct { +type resourceTableModel struct { table table.Model } -func (m model) Init() tea.Cmd { return nil } +func (m resourceTableModel) Init() tea.Cmd { return nil } -func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { +func (m resourceTableModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { var cmd tea.Cmd switch msg := msg.(type) { case tea.KeyMsg: @@ -47,7 +47,7 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { case "C": tmpDir := os.TempDir() filePath := filepath.Join(tmpDir, "resource-dump.txt") - m.dumpResources(m.table.Rows(), filePath) + m.dump(m.table.Rows(), filePath) savedMessage := lipgloss.NewStyle(). Foreground(lipgloss.Color("#32CD32")). Render(fmt.Sprintf( @@ -65,16 +65,16 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return m, cmd } -func (m model) View() string { +func (m resourceTableModel) View() string { s := "\n > Press 'j' and 'k' to go up and down\n" s += " > Press 'c' to copy highlighted row to clipboard\n" s += " > Press 'C' to copy all rows to a file\n" s += " > Press 'q' to quit\n\n" - s += baseStyle.Render(m.table.View()) + "\n" + s += resourceTableStyle.Render(m.table.View()) + "\n" return s } -func (m model) dumpResources(rows []table.Row, filePath string) error { +func (m resourceTableModel) dump(rows []table.Row, filePath string) error { dumpFile, err := os.Create(filePath) if err != nil { return errors.Wrap(err, "error while creating new file") @@ -118,7 +118,7 @@ func (m model) dumpResources(rows []table.Row, filePath string) error { return nil } -func (m model) copyRowToClipboard(row table.Row) { +func (m resourceTableModel) copyRowToClipboard(row table.Row) { var containerInfo string // default to docker headers @@ -170,7 +170,7 @@ func ResourceTable(columns []table.Column, rows []table.Row) { Bold(false) t.SetStyles(s) - m := model{t} + m := resourceTableModel{t} if _, err := tea.NewProgram(m).Run(); err != nil { fmt.Println("Error running program:", err) os.Exit(1) diff --git a/internal/scout/style/usage_table.go b/internal/scout/style/usage_table.go new file mode 100644 index 0000000000..1851e1081b --- /dev/null +++ b/internal/scout/style/usage_table.go @@ -0,0 +1,180 @@ +package style + +import ( + "fmt" + "os" + "path/filepath" + "strings" + "text/tabwriter" + + "github.com/charmbracelet/bubbles/table" + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" + "github.com/sourcegraph/sourcegraph/lib/errors" + "golang.design/x/clipboard" +) + +var usageTableStyle = lipgloss.NewStyle(). + BorderStyle(lipgloss.NormalBorder()). + BorderForeground(lipgloss.Color("240")) + +type usageTableModel struct { + table table.Model +} + +func (m usageTableModel) Init() tea.Cmd { return nil } + +func (m usageTableModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + var cmd tea.Cmd + switch msg := msg.(type) { + case tea.KeyMsg: + switch msg.String() { + case "esc", "q", "ctrl+c": + return m, tea.Quit + case "c": + m.copyRowToClipboard(m.table.SelectedRow()) + copiedMessage := lipgloss.NewStyle(). + Foreground(lipgloss.Color("#32CD32")). + Render(fmt.Sprintf( + "Copied usage data for '%s' to clipboard", + m.table.SelectedRow()[0], + )) + return m, tea.Batch( + tea.Printf( + copiedMessage, + ), + ) + case "C": + tmpDir := os.TempDir() + filePath := filepath.Join(tmpDir, "usage-dump.txt") + m.dump(m.table.Rows(), filePath) + savedMessage := lipgloss.NewStyle(). + Foreground(lipgloss.Color("#32CD32")). + Render(fmt.Sprintf( + "saved usage data to %s", + filePath, + )) + return m, tea.Batch( + tea.Printf( + savedMessage, + ), + ) + } + } + m.table, cmd = m.table.Update(msg) + return m, cmd +} + +func (m usageTableModel) View() string { + s := "\n > Press 'j' and 'k' to go up and down\n" + s += " > Press 'c' to copy highlighted row to clipboard\n" + s += " > Press 'C' to copy all rows to a file\n" + s += " > Press 'q' to quit\n\n" + s += usageTableStyle.Render(m.table.View()) + "\n" + return s +} + +func (m usageTableModel) dump(rows []table.Row, filePath string) error { + dumpFile, err := os.Create(filePath) + if err != nil { + return errors.Wrap(err, "error while creating new file") + } + defer dumpFile.Close() + + tw := tabwriter.NewWriter(dumpFile, 5, 0, 3, ' ', 0) + defer tw.Flush() + + // default to docker terms + headers := []string{ + "Name", + "Cores", + "Usage", + "Memory", + "Usage", + } + + // kubernetes rows will always have 6 items + // change column headers to reflect k8s terms + if len(rows[0]) == 7 { + headers = []string{ + "Name", + "Cores", + "Usage", + "Memory", + "Usage", + "Storage", + "Usage", + } + } + + fmt.Fprintf(tw, strings.Join(headers, "\t")+"\n") + for _, row := range rows { + values := []string{row[0], row[1], row[2], row[3], row[4]} + if len(row) == 7 { + values = append(values, row[5]) + values = append(values, row[6]) + } + fmt.Fprintf(tw, strings.Join(values, "\t")+"\n") + } + return nil +} + +func (m usageTableModel) copyRowToClipboard(row table.Row) { + var containerInfo string + + // default to docker headers + headers := []string{ + "Name", + "Cores", + "Usage", + "Memory", + "Usage", + } + + // kubernetes rows will always have 6 items + // change column headers to reflect k8s terms + if len(row) == 7 { + headers = []string{ + "Name", + "Cores", + "Usage", + "Memory", + "Usage", + "Storage", + "Usage", + } + } + + for i, header := range headers { + containerInfo += fmt.Sprintf("%s: %s\n", header, row[i]) + } + + clipboard.Write(clipboard.FmtText, []byte(containerInfo)) +} + +func UsageTable(columns []table.Column, rows []table.Row) { + t := table.New( + table.WithColumns(columns), + table.WithRows(rows), + table.WithFocused(true), + table.WithHeight(14), + ) + + s := table.DefaultStyles() + s.Header = s.Header. + BorderStyle(lipgloss.NormalBorder()). + BorderForeground(lipgloss.Color("240")). + BorderBottom(true). + Bold(false) + s.Selected = s.Selected. + Foreground(lipgloss.Color("229")). + Background(lipgloss.Color("57")). + Bold(false) + t.SetStyles(s) + + m := usageTableModel{t} + if _, err := tea.NewProgram(m).Run(); err != nil { + fmt.Println("Error running program:", err) + os.Exit(1) + } +} diff --git a/internal/scout/usage/docker.go b/internal/scout/usage/docker.go index 5bb96f672d..47b2b49034 100644 --- a/internal/scout/usage/docker.go +++ b/internal/scout/usage/docker.go @@ -79,7 +79,7 @@ func renderDockerUsageTable(ctx context.Context, cfg *Config, containers []types os.Exit(1) } - style.ResourceTable(columns, rows) + style.UsageTable(columns, rows) return nil } diff --git a/internal/scout/usage/k8s.go b/internal/scout/usage/k8s.go index 5380cca98e..b73f9e92bb 100644 --- a/internal/scout/usage/k8s.go +++ b/internal/scout/usage/k8s.go @@ -222,7 +222,7 @@ func renderUsageTable(ctx context.Context, cfg *Config, pods []corev1.Pod) error } } - style.ResourceTable(columns, rows) + style.UsageTable(columns, rows) return nil } From 23e8eb2a303e82e90ab72293bd41194228bfdd52 Mon Sep 17 00:00:00 2001 From: Jason Hawk Harris Date: Tue, 6 Jun 2023 11:47:32 -0500 Subject: [PATCH 341/647] scout/advise: first iteration of the `src scout advise` subcommand (#988) --- cmd/src/scout_advise.go | 120 ++++++++ internal/scout/advise/advise.go | 30 ++ internal/scout/advise/docker.go | 40 +++ internal/scout/advise/k8s.go | 164 +++++++++++ internal/scout/constants.go | 9 + internal/scout/helpers.go | 24 ++ internal/scout/kube/kube.go | 353 ++++++++++++++++++++++ internal/scout/kube/kube_test.go | 32 ++ internal/scout/resource/resource.go | 72 ++--- internal/scout/types.go | 42 +++ internal/scout/usage/docker.go | 37 +-- internal/scout/usage/k8s.go | 436 ++++------------------------ internal/scout/usage/usage.go | 57 +--- internal/scout/usage/usage_test.go | 37 +-- 14 files changed, 924 insertions(+), 529 deletions(-) create mode 100644 cmd/src/scout_advise.go create mode 100644 internal/scout/advise/advise.go create mode 100644 internal/scout/advise/docker.go create mode 100644 internal/scout/advise/k8s.go create mode 100644 internal/scout/constants.go create mode 100644 internal/scout/helpers.go create mode 100644 internal/scout/kube/kube.go create mode 100644 internal/scout/kube/kube_test.go create mode 100644 internal/scout/types.go diff --git a/cmd/src/scout_advise.go b/cmd/src/scout_advise.go new file mode 100644 index 0000000000..7ea1bb646e --- /dev/null +++ b/cmd/src/scout_advise.go @@ -0,0 +1,120 @@ +package main + +import ( + "context" + "flag" + "fmt" + "path/filepath" + + "github.com/docker/docker/client" + "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/src-cli/internal/scout/advise" + "k8s.io/client-go/kubernetes" + "k8s.io/client-go/tools/clientcmd" + "k8s.io/client-go/util/homedir" + metricsv "k8s.io/metrics/pkg/client/clientset/versioned" +) + +func init() { + cmdUsage := `'src scout advise' is a tool that makes resource allocation recommendations. Based on current usage. + Part of the EXPERIMENTAL "src scout" tool. + + Examples + Make recommendations for all pods in a kubernetes deployment of Sourcegraph. + $ src scout advise + + Make recommendations for all containers in a Docker deployment of Sourcegraph. + $ src scout advise + + Make recommendations for specific pod: + $ src scout advise --pod + + Make recommendations for specific container: + $ src scout advise --container + + Add namespace if using namespace in a Kubernetes cluster + $ src scout advise --namespace + ` + + flagSet := flag.NewFlagSet("advise", flag.ExitOnError) + usage := func() { + fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src scout %s':\n", flagSet.Name()) + flagSet.PrintDefaults() + fmt.Println(cmdUsage) + } + + var ( + kubeConfig *string + namespace = flagSet.String("namespace", "", "(optional) specify the kubernetes namespace to use") + pod = flagSet.String("pod", "", "(optional) specify a single pod") + container = flagSet.String("container", "", "(optional) specify a single container") + docker = flagSet.Bool("docker", false, "(optional) using docker deployment") + ) + + if home := homedir.HomeDir(); home != "" { + kubeConfig = flagSet.String( + "kubeconfig", + filepath.Join(home, ".kube", "config"), + "(optional) absolute path to the kubeconfig file", + ) + } else { + kubeConfig = flagSet.String("kubeconfig", "", "absolute path to the kubeconfig file") + } + + handler := func(args []string) error { + if err := flagSet.Parse(args); err != nil { + return err + } + + config, err := clientcmd.BuildConfigFromFlags("", *kubeConfig) + if err != nil { + return errors.Wrap(err, "failed to load .kube config: ") + } + + clientSet, err := kubernetes.NewForConfig(config) + if err != nil { + return errors.Wrap(err, "failed to initiate kubernetes client: ") + } + + metricsClient, err := metricsv.NewForConfig(config) + if err != nil { + return errors.Wrap(err, "failed to initiate metrics client") + } + + var options []advise.Option + + if *namespace != "" { + options = append(options, advise.WithNamespace(*namespace)) + } + if *pod != "" { + options = append(options, advise.WithPod(*pod)) + } + if *container != "" || *docker { + if *container != "" { + options = append(options, advise.WithContainer(*container)) + } + + dockerClient, err := client.NewClientWithOpts(client.FromEnv) + if err != nil { + return errors.Wrap(err, "error creating docker client: ") + } + + return advise.Docker(context.Background(), *dockerClient, options...) + } + + return advise.K8s( + context.Background(), + clientSet, + metricsClient, + config, + options..., + ) + } + + scoutCommands = append(scoutCommands, &command{ + flagSet: flagSet, + handler: handler, + usageFunc: usage, + }) + +} diff --git a/internal/scout/advise/advise.go b/internal/scout/advise/advise.go new file mode 100644 index 0000000000..7df40c13ee --- /dev/null +++ b/internal/scout/advise/advise.go @@ -0,0 +1,30 @@ +package advise + +import "github.com/sourcegraph/src-cli/internal/scout" + +type Option = func(config *scout.Config) + +const ( + OVER_100 = "\t%s %s: Your %s usage is over 100%% (%.2f%%). Add more %s." + OVER_80 = "\t%s %s: Your %s usage is over 80%% (%.2f%%). Consider raising limits." + OVER_40 = "\t%s %s: Your %s usage is under 80%% (%.2f%%). Keep %s allocation the same." + UNDER_40 = "\t%s %s: Your %s usage is under 40%% (%.2f%%). Consider lowering limits." +) + +func WithNamespace(namespace string) Option { + return func(config *scout.Config) { + config.Namespace = namespace + } +} + +func WithPod(podname string) Option { + return func(config *scout.Config) { + config.Pod = podname + } +} + +func WithContainer(containerName string) Option { + return func(config *scout.Config) { + config.Container = containerName + } +} diff --git a/internal/scout/advise/docker.go b/internal/scout/advise/docker.go new file mode 100644 index 0000000000..319a5ceb4e --- /dev/null +++ b/internal/scout/advise/docker.go @@ -0,0 +1,40 @@ +package advise + +import ( + "context" + "fmt" + + "github.com/docker/docker/api/types" + "github.com/docker/docker/client" + "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/src-cli/internal/scout" +) + +func Docker(ctx context.Context, client client.Client, opts ...Option) error { + cfg := &scout.Config{ + Namespace: "default", + Docker: true, + Pod: "", + Container: "", + Spy: false, + DockerClient: &client, + } + + for _, opt := range opts { + opt(cfg) + } + + containers, err := client.ContainerList(ctx, types.ContainerListOptions{}) + if err != nil { + return errors.Wrap(err, "could not get list of containers") + } + + PrintContainers(containers) + return nil +} + +func PrintContainers(containers []types.Container) { + for _, c := range containers { + fmt.Println(c.Image) + } +} diff --git a/internal/scout/advise/k8s.go b/internal/scout/advise/k8s.go new file mode 100644 index 0000000000..f540f63160 --- /dev/null +++ b/internal/scout/advise/k8s.go @@ -0,0 +1,164 @@ +package advise + +import ( + "context" + "fmt" + + "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/src-cli/internal/scout" + "github.com/sourcegraph/src-cli/internal/scout/kube" + v1 "k8s.io/api/core/v1" + "k8s.io/client-go/kubernetes" + "k8s.io/client-go/rest" + metricsv "k8s.io/metrics/pkg/client/clientset/versioned" +) + +func K8s( + ctx context.Context, + k8sClient *kubernetes.Clientset, + metricsClient *metricsv.Clientset, + restConfig *rest.Config, + opts ...Option, +) error { + cfg := &scout.Config{ + Namespace: "default", + Pod: "", + Container: "", + Spy: false, + Docker: false, + RestConfig: restConfig, + K8sClient: k8sClient, + DockerClient: nil, + MetricsClient: metricsClient, + } + + for _, opt := range opts { + opt(cfg) + } + + pods, err := kube.GetPods(ctx, cfg) + if err != nil { + return errors.Wrap(err, "could not get list of pods") + } + + if cfg.Pod != "" { + pod, err := kube.GetPod(cfg.Pod, pods) + if err != nil { + return errors.Wrap(err, "could not get pod") + } + + err = Advise(ctx, cfg, pod) + if err != nil { + return errors.Wrap(err, "could not advise") + } + return nil + } + + for _, pod := range pods { + err = Advise(ctx, cfg, pod) + if err != nil { + return errors.Wrap(err, "could not advise") + } + } + + return nil +} + +func Advise(ctx context.Context, cfg *scout.Config, pod v1.Pod) error { + var advice []string + usageMetrics, err := getUsageMetrics(ctx, cfg, pod) + if err != nil { + return errors.Wrap(err, "could not get usage metrics") + } + + for _, metrics := range usageMetrics { + cpuAdvice := checkUsage(metrics.CpuUsage, "CPU", metrics.ContainerName, pod.Name) + advice = append(advice, cpuAdvice) + + memoryAdvice := checkUsage(metrics.MemoryUsage, "memory", metrics.ContainerName, pod.Name) + advice = append(advice, memoryAdvice) + + if metrics.Storage != nil { + storageAdvice := checkUsage(metrics.StorageUsage, "storage", metrics.ContainerName, pod.Name) + advice = append(advice, storageAdvice) + } + + fmt.Println(scout.EmojiFingerPointRight, pod.Name) + for _, msg := range advice { + fmt.Println(msg) + } + } + + return nil +} + +func getUsageMetrics(ctx context.Context, cfg *scout.Config, pod v1.Pod) ([]scout.UsageStats, error) { + var usages []scout.UsageStats + var usage scout.UsageStats + podMetrics, err := kube.GetPodMetrics(ctx, cfg, pod) + if err != nil { + return usages, errors.Wrap(err, "while attempting to fetch pod metrics") + } + + containerMetrics := &scout.ContainerMetrics{ + PodName: cfg.Pod, + Limits: map[string]scout.Resources{}, + } + + if err = kube.AddLimits(ctx, cfg, &pod, containerMetrics); err != nil { + return usages, errors.Wrap(err, "failed to get get container metrics") + } + + for _, container := range podMetrics.Containers { + usage, err = kube.GetUsage(ctx, cfg, *containerMetrics, pod, container) + if err != nil { + return usages, errors.Wrapf(err, "could not compile usages data for row: %s\n", container.Name) + } + usages = append(usages, usage) + } + + return usages, nil +} + +func checkUsage(usage float64, resourceType, container, pod string) string { + var message string + + switch { + case usage >= 100: + message = fmt.Sprintf( + OVER_100, + scout.FlashingLightEmoji, + container, + resourceType, + usage, + resourceType, + ) + case usage >= 80 && usage < 100: + message = fmt.Sprintf( + OVER_80, + scout.WarningSign, + container, + resourceType, + usage, + ) + case usage >= 40 && usage < 80: + message = fmt.Sprintf( + OVER_40, + scout.SuccessEmoji, + container, + resourceType, + usage, + resourceType, + ) + default: + message = fmt.Sprintf( + UNDER_40, + scout.WarningSign, + container, + resourceType, + usage, + ) + } + + return message +} diff --git a/internal/scout/constants.go b/internal/scout/constants.go new file mode 100644 index 0000000000..4153df9766 --- /dev/null +++ b/internal/scout/constants.go @@ -0,0 +1,9 @@ +package scout + +const ( + ABillion float64 = 1_000_000_000 + EmojiFingerPointRight = "👉" + FlashingLightEmoji = "🚨" + SuccessEmoji = "✅" + WarningSign = "⚠️ " // why does this need an extra space to align?!?! +) diff --git a/internal/scout/helpers.go b/internal/scout/helpers.go new file mode 100644 index 0000000000..1c917d3b94 --- /dev/null +++ b/internal/scout/helpers.go @@ -0,0 +1,24 @@ +package scout + +// contains checks if a string slice contains a given value. +func Contains(slice []string, value string) bool { + for _, v := range slice { + if v == value { + return true + } + } + return false +} + +// getPercentage calculates the percentage of x in relation to y. +func GetPercentage(x, y float64) float64 { + if x == 0 { + return 0 + } + + if y == 0 { + return 0 + } + + return x * 100 / y +} diff --git a/internal/scout/kube/kube.go b/internal/scout/kube/kube.go new file mode 100644 index 0000000000..5e5523266d --- /dev/null +++ b/internal/scout/kube/kube.go @@ -0,0 +1,353 @@ +package kube + +import ( + "bytes" + "context" + "fmt" + "os" + "regexp" + "strconv" + "strings" + + "github.com/charmbracelet/lipgloss" + "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/src-cli/internal/scout" + "gopkg.in/inf.v0" + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/resource" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/client-go/kubernetes/scheme" + "k8s.io/client-go/tools/remotecommand" + metav1beta1 "k8s.io/metrics/pkg/apis/metrics/v1beta1" +) + +// GetPods fetches all pods in a given namespace. +func GetPods(ctx context.Context, cfg *scout.Config) ([]corev1.Pod, error) { + podInterface := cfg.K8sClient.CoreV1().Pods(cfg.Namespace) + podList, err := podInterface.List(ctx, metav1.ListOptions{}) + if err != nil { + return []corev1.Pod{}, errors.Wrap(err, "could not list pods") + } + + if len(podList.Items) == 0 { + msg := lipgloss.NewStyle().Foreground(lipgloss.Color("#FFA500")) + fmt.Println(msg.Render(` + No pods exist in this namespace. + Did you mean to use the --namespace flag? + + If you are attempting to check + resources for a docker deployment, you + must use the --docker flag. + See --help for more info. + `)) + os.Exit(1) + } + + return podList.Items, nil +} + +// GetPod returns a pod object with the given name from a list of pods. +func GetPod(podName string, pods []corev1.Pod) (corev1.Pod, error) { + for _, p := range pods { + if p.Name == podName { + return p, nil + } + } + return corev1.Pod{}, errors.New("no pod with this name exists in this namespace") +} + +// GetPodMetrics fetches metrics for a given pod from the Kubernetes Metrics API. +// It accepts: +// - ctx: The context for the request +// - cfg: The scout config containing Kubernetes clientsets +// - pod: The pod specification +// +// It returns: +// - podMetrics: The PodMetrics object containing metrics for the pod +// - Any error that occurred while fetching the metrics +func GetPodMetrics(ctx context.Context, cfg *scout.Config, pod corev1.Pod) (*metav1beta1.PodMetrics, error) { + podMetrics, err := cfg.MetricsClient. + MetricsV1beta1(). + PodMetricses(cfg.Namespace). + Get(ctx, pod.Name, metav1.GetOptions{}) + if err != nil { + return nil, errors.Wrap(err, "failed to get pod metrics") + } + + return podMetrics, nil +} + +// GetLimits generates resource limits for containers in a pod. +// +// It accepts: +// - ctx: The context for the request +// - cfg: The scout config containing Kubernetes clientsets +// - pod: The pod specification +// - containerMetrics: A pointer to a ContainerMetrics struct to populate +// +// It populates the containerMetrics.Limits field with a map of container names +// to resource limits (CPU, memory, storage) for each container in the pod. +// +// It returns: +// - Any error that occurred while fetching resource limits +func AddLimits(ctx context.Context, cfg *scout.Config, pod *corev1.Pod, containerMetrics *scout.ContainerMetrics) error { + for _, container := range pod.Spec.Containers { + containerName := container.Name + capacity, err := GetPvcCapacity(ctx, cfg, container, pod) + if err != nil { + return errors.Wrap(err, "while getting storage capacity of PV") + } + + rsrcs := scout.Resources{ + Cpu: container.Resources.Limits.Cpu().ToDec(), + Memory: container.Resources.Limits.Memory().ToDec(), + Storage: capacity, + } + containerMetrics.Limits[containerName] = rsrcs + } + + return nil +} + +// GetUsage generates resource usage statistics for a Kubernetes container. +// +// It accepts: +// - ctx: The context for the request +// - cfg: The scout config containing Kubernetes clientsets +// - metrics: Container resource limits +// - pod: The pod specification +// - container: Container metrics from the Metrics API +// +// It returns: +// - usageStats: A UsageStats struct containing the resource usage info +// - Any error that occurred while generating the usage stats +func GetUsage( + ctx context.Context, + cfg *scout.Config, + metrics scout.ContainerMetrics, + pod corev1.Pod, + container metav1beta1.ContainerMetrics, +) (scout.UsageStats, error) { + var usageStats scout.UsageStats + usageStats.ContainerName = container.Name + + cpuUsage, err := GetRawUsage(container.Usage, "cpu") + if err != nil { + return usageStats, errors.Wrap(err, "failed to get raw CPU usage") + } + + memUsage, err := GetRawUsage(container.Usage, "memory") + if err != nil { + return usageStats, errors.Wrap(err, "failed to get raw memory usage") + } + + limits := metrics.Limits[container.Name] + + var storageCapacity float64 + var storageUsage float64 + if limits.Storage != nil { + storageCapacity, storageUsage, err = GetStorageUsage(ctx, cfg, pod.Name, container.Name) + if err != nil { + return usageStats, errors.Wrap(err, "failed to get storage usage") + } + } + + usageStats.CpuCores = limits.Cpu + usageStats.CpuUsage = scout.GetPercentage( + cpuUsage, + limits.Cpu.AsApproximateFloat64()*scout.ABillion, + ) + + usageStats.Memory = limits.Memory + usageStats.MemoryUsage = scout.GetPercentage( + memUsage, + limits.Memory.AsApproximateFloat64(), + ) + + if limits.Storage == nil { + storageDec := *inf.NewDec(0, 0) + usageStats.Storage = resource.NewDecimalQuantity(storageDec, resource.Format("DecimalSI")) + } else { + usageStats.Storage = limits.Storage + } + + usageStats.StorageUsage = scout.GetPercentage( + storageUsage, + storageCapacity, + ) + + if metrics.Limits[container.Name].Storage == nil { + usageStats.Storage = nil + } + + return usageStats, nil +} + +// GetRawUsage returns the raw usage value for a given resource type from a Kubernetes ResourceList. +// +// It accepts: +// - usages: A Kubernetes ResourceList containing usage values +// - targetKey: The resource type to get the usage for (e.g. "cpu" or "memory") +// +// It returns: +// - The raw usage value for the target resource type +// - Any error that occurred while parsing the usage value +func GetRawUsage(usages corev1.ResourceList, targetKey string) (float64, error) { + var usage *inf.Dec + + for key, val := range usages { + if key.String() == targetKey { + usage = val.AsDec().SetScale(0) + } + } + + toFloat, err := strconv.ParseFloat(usage.String(), 64) + if err != nil { + return 0, errors.Wrap(err, "failed to convert inf.Dec type to float") + } + + return toFloat, nil +} + +// GetPvcCapacity returns the storage capacity of a PersistentVolumeClaim mounted to a container. +// +// It accepts: +// - ctx: The context for the request +// - cfg: The scout config containing Kubernetes clientsets +// - container: The container specification +// - pod: The pod specification +// +// It returns: +// - The storage capacity of the PVC in bytes +// - Any error that occurred while fetching the PVC +// +// If no PVC is mounted to the container, nil is returned for the capacity and no error. +func GetPvcCapacity(ctx context.Context, cfg *scout.Config, container corev1.Container, pod *corev1.Pod) (*resource.Quantity, error) { + for _, vm := range container.VolumeMounts { + for _, v := range pod.Spec.Volumes { + if v.Name == vm.Name && v.PersistentVolumeClaim != nil { + pvc, err := cfg.K8sClient. + CoreV1(). + PersistentVolumeClaims(cfg.Namespace). + Get( + ctx, + v.PersistentVolumeClaim.ClaimName, + metav1.GetOptions{}, + ) + if err != nil { + return nil, errors.Wrapf( + err, + "failed to get PVC %s", + v.PersistentVolumeClaim.ClaimName, + ) + } + return pvc.Status.Capacity.Storage().ToDec(), nil + } + } + } + return nil, nil +} + +// GetStorageUsage returns the storage capacity and usage for a given pod and container. +// +// It accepts: +// - ctx: The context for the request +// - cfg: The scout config containing Kubernetes clientsets +// - podName: The name of the pod +// - containerName: The name of the container +// +// It returns: +// - storageCapacity: The total storage capacity for the container in bytes +// - storageUsage: The used storage for the container in bytes +// - Any error that occurred while fetching the storage usage +func GetStorageUsage( + ctx context.Context, + cfg *scout.Config, + podName string, + containerName string, +) (float64, float64, error) { + var storageCapacity float64 + var storageUsage float64 + + stateless := []string{ + "cadvisor", + "pgsql-exporter", + "executor", + "dind", + "github-proxy", + "jaeger", + "node-exporter", + "otel-agent", + "otel-collector", + "precise-code-intel-worker", + "redis-exporter", + "repo-updater", + "frontend", + "syntect-server", + "worker", + } + + if scout.Contains(stateless, containerName) { + return storageCapacity, storageUsage, nil + } + + req := cfg.K8sClient.CoreV1().RESTClient().Post(). + Resource("pods"). + Name(podName). + Namespace(cfg.Namespace). + SubResource("exec") + + req.VersionedParams(&corev1.PodExecOptions{ + Container: containerName, + Command: []string{"df"}, + Stdin: false, + Stdout: true, + Stderr: true, + TTY: false, + }, scheme.ParameterCodec) + + exec, err := remotecommand.NewSPDYExecutor(cfg.RestConfig, "POST", req.URL()) + if err != nil { + return 0, 0, err + } + + var stdout, stderr bytes.Buffer + err = exec.StreamWithContext(ctx, remotecommand.StreamOptions{ + Stdout: &stdout, + Stderr: &stderr, + }) + if err != nil { + return 0, 0, err + } + + lines := strings.Split(stdout.String(), "\n") + for _, line := range lines[1 : len(lines)-1] { + fields := strings.Fields(line) + + if acceptedFileSystem(fields[0]) { + capacityFloat, err := strconv.ParseFloat(fields[1], 64) + if err != nil { + return 0, 0, errors.Wrap(err, "could not convert string to float64") + } + + usageFloat, err := strconv.ParseFloat(fields[2], 64) + if err != nil { + return 0, 0, errors.Wrap(err, "could not convert string to float64") + } + return capacityFloat, usageFloat, nil + } + } + + return 0, 0, nil +} + +// acceptedFileSystem checks if a given file system, represented +// as a string, is an accepted system. +// +// It returns: +// - True if the file system matches the pattern '/dev/sd[a-z]$' +// - False otherwise +func acceptedFileSystem(fileSystem string) bool { + matched, _ := regexp.MatchString(`/dev/sd[a-z]$`, fileSystem) + return matched +} diff --git a/internal/scout/kube/kube_test.go b/internal/scout/kube/kube_test.go new file mode 100644 index 0000000000..787e894234 --- /dev/null +++ b/internal/scout/kube/kube_test.go @@ -0,0 +1,32 @@ +package kube + +import "testing" + +func TestAcceptedFileSystem(t *testing.T) { + cases := []struct { + name string + filesystem string + want bool + }{ + { + name: "should return true if filesystem matches 'matched' regular expression", + filesystem: "/dev/sda", + want: true, + }, + { + name: "should return false if filesystem doesn't match 'matched' regular expression", + filesystem: "/dev/sda1", + want: false, + }, + } + + for _, tc := range cases { + tc := tc + t.Run(tc.name, func(t *testing.T) { + got := acceptedFileSystem(tc.filesystem) + if got != tc.want { + t.Errorf("got %v want %v", got, tc.want) + } + }) + } +} diff --git a/internal/scout/resource/resource.go b/internal/scout/resource/resource.go index 6ad128abd7..ddfd99da8a 100644 --- a/internal/scout/resource/resource.go +++ b/internal/scout/resource/resource.go @@ -10,35 +10,33 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/client" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/src-cli/internal/scout" + kube "github.com/sourcegraph/src-cli/internal/scout/kube" "github.com/sourcegraph/src-cli/internal/scout/style" - v1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" ) -type Option = func(config *Config) - -type Config struct { - namespace string - docker bool - k8sClient *kubernetes.Clientset - dockerClient *client.Client -} +type Option = func(config *scout.Config) func WithNamespace(namespace string) Option { - return func(config *Config) { - config.namespace = namespace + return func(config *scout.Config) { + config.Namespace = namespace } } // K8s prints the CPU and memory resource limits and requests for all pods in the given namespace. func K8s(ctx context.Context, clientSet *kubernetes.Clientset, restConfig *rest.Config, opts ...Option) error { - cfg := &Config{ - namespace: "default", - docker: false, - k8sClient: clientSet, - dockerClient: nil, + cfg := &scout.Config{ + Namespace: "default", + Docker: false, + Pod: "", + Container: "", + Spy: false, + RestConfig: restConfig, + K8sClient: clientSet, + DockerClient: nil, + MetricsClient: nil, } for _, opt := range opts { @@ -48,11 +46,10 @@ func K8s(ctx context.Context, clientSet *kubernetes.Clientset, restConfig *rest. return listPodResources(ctx, cfg) } -func listPodResources(ctx context.Context, cfg *Config) error { - podInterface := cfg.k8sClient.CoreV1().Pods(cfg.namespace) - podList, err := podInterface.List(ctx, metav1.ListOptions{}) +func listPodResources(ctx context.Context, cfg *scout.Config) error { + pods, err := kube.GetPods(ctx, cfg) if err != nil { - return errors.Wrap(err, "error listing pods: ") + return errors.Wrap(err, "could not get pods") } columns := []table.Column{ @@ -64,7 +61,7 @@ func listPodResources(ctx context.Context, cfg *Config) error { {Title: "CAPACITY", Width: 8}, } - if len(podList.Items) == 0 { + if len(pods) == 0 { msg := lipgloss.NewStyle().Foreground(lipgloss.Color("#FFA500")) fmt.Println(msg.Render(` No pods exist in this namespace. @@ -79,30 +76,26 @@ func listPodResources(ctx context.Context, cfg *Config) error { } var rows []table.Row - for _, pod := range podList.Items { - if pod.GetNamespace() == cfg.namespace { + for _, pod := range pods { + if pod.GetNamespace() == cfg.Namespace { for _, container := range pod.Spec.Containers { cpuLimits := container.Resources.Limits.Cpu() cpuRequests := container.Resources.Requests.Cpu() memLimits := container.Resources.Limits.Memory() memRequests := container.Resources.Requests.Memory() - capacity, err := getPVCCapacity(ctx, cfg, container, pod) + capacity, err := kube.GetPvcCapacity(ctx, cfg, container, &pod) if err != nil { return err } - if capacity == "" { - capacity = "N/A" - } - row := table.Row{ container.Name, cpuLimits.String(), cpuRequests.String(), memLimits.String(), memRequests.String(), - capacity, + capacity.String(), } rows = append(rows, row) } @@ -113,25 +106,6 @@ func listPodResources(ctx context.Context, cfg *Config) error { return nil } -func getPVCCapacity(ctx context.Context, cfg *Config, container v1.Container, pod v1.Pod) (string, error) { - for _, volumeMount := range container.VolumeMounts { - for _, volume := range pod.Spec.Volumes { - if volume.Name == volumeMount.Name && volume.PersistentVolumeClaim != nil { - pvc, err := cfg.k8sClient.CoreV1().PersistentVolumeClaims(cfg.namespace).Get( - ctx, - volume.PersistentVolumeClaim.ClaimName, - metav1.GetOptions{}, - ) - if err != nil { - return "", errors.Wrapf(err, "error getting PVC %s", volume.PersistentVolumeClaim.ClaimName) - } - return pvc.Status.Capacity.Storage().String(), nil - } - } - } - return "", nil -} - // Docker prints the CPU and memory resource limits and requests for running Docker containers. func Docker(ctx context.Context, dockerClient client.Client) error { containers, err := dockerClient.ContainerList(ctx, types.ContainerListOptions{}) diff --git a/internal/scout/types.go b/internal/scout/types.go new file mode 100644 index 0000000000..13d327036a --- /dev/null +++ b/internal/scout/types.go @@ -0,0 +1,42 @@ +package scout + +import ( + "github.com/docker/docker/client" + "k8s.io/apimachinery/pkg/api/resource" + "k8s.io/client-go/kubernetes" + "k8s.io/client-go/rest" + metricsv "k8s.io/metrics/pkg/client/clientset/versioned" +) + +type Config struct { + Namespace string + Pod string + Container string + Spy bool + Docker bool + RestConfig *rest.Config + K8sClient *kubernetes.Clientset + DockerClient *client.Client + MetricsClient *metricsv.Clientset +} + +type ContainerMetrics struct { + PodName string + Limits map[string]Resources +} + +type Resources struct { + Cpu *resource.Quantity + Memory *resource.Quantity + Storage *resource.Quantity +} + +type UsageStats struct { + ContainerName string + CpuCores *resource.Quantity + Memory *resource.Quantity + Storage *resource.Quantity + CpuUsage float64 + MemoryUsage float64 + StorageUsage float64 +} diff --git a/internal/scout/usage/docker.go b/internal/scout/usage/docker.go index 47b2b49034..c46cded08e 100644 --- a/internal/scout/usage/docker.go +++ b/internal/scout/usage/docker.go @@ -11,24 +11,25 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/client" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/src-cli/internal/scout" "github.com/sourcegraph/src-cli/internal/scout/style" ) func Docker(ctx context.Context, client client.Client, opts ...Option) error { - cfg := &Config{ - namespace: "default", - docker: true, - pod: "", - container: "", - spy: false, - dockerClient: &client, + cfg := &scout.Config{ + Namespace: "default", + Docker: true, + Pod: "", + Container: "", + Spy: false, + DockerClient: &client, } for _, opt := range opts { opt(cfg) } - containers, err := cfg.dockerClient.ContainerList(ctx, types.ContainerListOptions{}) + containers, err := cfg.DockerClient.ContainerList(ctx, types.ContainerListOptions{}) if err != nil { return errors.Wrap(err, "could not get list of containers") } @@ -37,7 +38,7 @@ func Docker(ctx context.Context, client client.Client, opts ...Option) error { } // renderDockerUsageTable renders a table displaying CPU and memory usage for Docker containers. -func renderDockerUsageTable(ctx context.Context, cfg *Config, containers []types.Container) error { +func renderDockerUsageTable(ctx context.Context, cfg *scout.Config, containers []types.Container) error { columns := []table.Column{ {Title: "Container", Width: 20}, {Title: "Cores", Width: 10}, @@ -48,13 +49,13 @@ func renderDockerUsageTable(ctx context.Context, cfg *Config, containers []types rows := []table.Row{} for _, container := range containers { - containerInfo, err := cfg.dockerClient.ContainerInspect(ctx, container.ID) + containerInfo, err := cfg.DockerClient.ContainerInspect(ctx, container.ID) if err != nil { return errors.Wrap(err, "failed to get container info") } - if cfg.container != "" { - if containerInfo.Name == cfg.container { + if cfg.Container != "" { + if containerInfo.Name == cfg.Container { row := makeDockerUsageRow(ctx, cfg, containerInfo) rows = append(rows, row) break @@ -69,12 +70,12 @@ func renderDockerUsageTable(ctx context.Context, cfg *Config, containers []types if len(rows) == 0 { msg := lipgloss.NewStyle().Foreground(lipgloss.Color("#FFA500")) - if cfg.container == "" { + if cfg.Container == "" { fmt.Println(msg.Render(`No docker containers are running.`)) os.Exit(1) } fmt.Println(msg.Render( - fmt.Sprintf(`No container with name '%s' running.`, cfg.container), + fmt.Sprintf(`No container with name '%s' running.`, cfg.Container), )) os.Exit(1) } @@ -84,8 +85,8 @@ func renderDockerUsageTable(ctx context.Context, cfg *Config, containers []types } // makeDockerUsageRow generates a table row displaying CPU and memory usage for a Docker container. -func makeDockerUsageRow(ctx context.Context, cfg *Config, container types.ContainerJSON) table.Row { - stats, err := cfg.dockerClient.ContainerStats(ctx, container.ID, false) +func makeDockerUsageRow(ctx context.Context, cfg *scout.Config, container types.ContainerJSON) table.Row { + stats, err := cfg.DockerClient.ContainerStats(ctx, container.ID, false) if err != nil { errors.Wrap(err, "could not get container stats") os.Exit(1) @@ -106,8 +107,8 @@ func makeDockerUsageRow(ctx context.Context, cfg *Config, container types.Contai return table.Row{ container.Name, fmt.Sprintf("%.2f", cpuCores/1_000_000_000), - fmt.Sprintf("%.2f%%", getPercentage(cpuUsage, cpuCores)), + fmt.Sprintf("%.2f%%", scout.GetPercentage(cpuUsage, cpuCores)), fmt.Sprintf("%.2fG", memory/1_000_000_000), - fmt.Sprintf("%.2f%%", getPercentage(memoryUsage, memory)), + fmt.Sprintf("%.2f%%", scout.GetPercentage(memoryUsage, memory)), } } diff --git a/internal/scout/usage/k8s.go b/internal/scout/usage/k8s.go index b73f9e92bb..1ca9977eba 100644 --- a/internal/scout/usage/k8s.go +++ b/internal/scout/usage/k8s.go @@ -1,56 +1,21 @@ package usage import ( - "bytes" "context" "fmt" - "os" - "regexp" - "strconv" - "strings" "github.com/charmbracelet/bubbles/table" - "github.com/charmbracelet/lipgloss" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/src-cli/internal/scout" + "github.com/sourcegraph/src-cli/internal/scout/kube" "github.com/sourcegraph/src-cli/internal/scout/style" - "gopkg.in/inf.v0" corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/resource" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" - "k8s.io/client-go/kubernetes/scheme" restclient "k8s.io/client-go/rest" - "k8s.io/client-go/tools/remotecommand" - metav1beta1 "k8s.io/metrics/pkg/apis/metrics/v1beta1" metricsv "k8s.io/metrics/pkg/client/clientset/versioned" ) -type ContainerMetrics struct { - podName string - limits map[string]Resources -} - -type Resources struct { - cpu *resource.Quantity - memory *resource.Quantity - storage *resource.Quantity -} - -type UsageStats struct { - containerName string - cpuCores *resource.Quantity - memory *resource.Quantity - storage *resource.Quantity - cpuUsage float64 - memoryUsage float64 - storageUsage float64 -} - -const ( - ABillion float64 = 1000000000 -) - func K8s( ctx context.Context, clientSet *kubernetes.Clientset, @@ -58,28 +23,28 @@ func K8s( restConfig *restclient.Config, opts ...Option, ) error { - cfg := &Config{ - namespace: "default", - docker: false, - pod: "", - container: "", - spy: false, - restConfig: restConfig, - k8sClient: clientSet, - dockerClient: nil, - metricsClient: metricsClient, + cfg := &scout.Config{ + Namespace: "default", + Docker: false, + Pod: "", + Container: "", + Spy: false, + RestConfig: restConfig, + K8sClient: clientSet, + DockerClient: nil, + MetricsClient: metricsClient, } for _, opt := range opts { opt(cfg) } - pods, err := getPods(ctx, cfg) + pods, err := kube.GetPods(ctx, cfg) if err != nil { return errors.Wrap(err, "could not get list of pods") } - if cfg.pod != "" { + if cfg.Pod != "" { return renderSinglePodUsageTable(ctx, cfg, pods) } @@ -87,20 +52,18 @@ func K8s( } // renderSinglePodUsageStats prints resource usage statistics for a single pod. -func renderSinglePodUsageTable(ctx context.Context, cfg *Config, pods []corev1.Pod) error { - pod, err := getPod(cfg, pods) +func renderSinglePodUsageTable(ctx context.Context, cfg *scout.Config, pods []corev1.Pod) error { + pod, err := kube.GetPod(cfg.Pod, pods) if err != nil { - return errors.Wrapf(err, "could not get pod with name %s", cfg.pod) + return errors.Wrapf(err, "could not get pod with name %s", cfg.Pod) } - podMetrics, err := getPodMetrics(ctx, cfg, pod) - if err != nil { - return errors.Wrap(err, "while attempting to fetch pod metrics") + containerMetrics := &scout.ContainerMetrics{ + PodName: cfg.Pod, + Limits: map[string]scout.Resources{}, } - - containerMetrics := &ContainerMetrics{cfg.pod, map[string]Resources{}} - if err = getLimits(ctx, cfg, &pod, containerMetrics); err != nil { - return errors.Wrap(err, "failed to get get container metrics") + if err = kube.AddLimits(ctx, cfg, &pod, containerMetrics); err != nil { + return errors.Wrap(err, "failed to add limits to container metrics") } columns := []table.Column{ @@ -114,8 +77,13 @@ func renderSinglePodUsageTable(ctx context.Context, cfg *Config, pods []corev1.P } var rows []table.Row + podMetrics, err := kube.GetPodMetrics(ctx, cfg, pod) + if err != nil { + return errors.Wrap(err, "while attempting to fetch pod metrics") + } + for _, container := range podMetrics.Containers { - stats, err := getContainerUsageStats(ctx, cfg, *containerMetrics, pod, container) + stats, err := kube.GetUsage(ctx, cfg, *containerMetrics, pod, container) if err != nil { return errors.Wrapf(err, "could not compile usage data for row: %s\n", container.Name) } @@ -128,67 +96,8 @@ func renderSinglePodUsageTable(ctx context.Context, cfg *Config, pods []corev1.P return nil } -// getPod returns a Pod object with the given name. -// -// If a Pod with the given name exists in pods, it is returned. -// Otherwise, an error is returned indicating no Pod with that name exists. -func getPod(cfg *Config, pods []corev1.Pod) (corev1.Pod, error) { - for _, p := range pods { - if p.Name == cfg.pod { - return p, nil - } - } - return corev1.Pod{}, errors.New("no pod with this name exists in this namespace") -} - -// getPodMetrics retrieves metrics for a given pod. -// -// It returns: -// - podMetrics: The PodMetrics object containing metrics for the pod -// - err: Any error that occurred while getting the pod metrics -func getPodMetrics(ctx context.Context, cfg *Config, pod corev1.Pod) (*metav1beta1.PodMetrics, error) { - podMetrics, err := cfg.metricsClient. - MetricsV1beta1(). - PodMetricses(cfg.namespace). - Get(ctx, pod.Name, metav1.GetOptions{}) - if err != nil { - return nil, errors.Wrap(err, "failed to get pod metrics") - } - - return podMetrics, nil -} - -// getLimits extracts resource limits for containers in a pod and stores -// them in a ContainerMetrics struct. -// -// It populates the containerMetrics struct with: -// - The name of each container -// - The CPU, memory, ephemeral storage, and storage resource limits for each container -// - A print method to print the resource limits for each container -func getLimits(ctx context.Context, cfg *Config, pod *corev1.Pod, containerMetrics *ContainerMetrics) error { - for _, container := range pod.Spec.Containers { - containerName := container.Name - capacity, err := getPvcCapacity(ctx, cfg, container, pod) - if err != nil { - return errors.Wrap(err, "while getting storage capacity of PV") - } - - rsrcs := Resources{ - cpu: container.Resources.Limits.Cpu().ToDec(), - memory: container.Resources.Limits.Memory().ToDec(), - storage: capacity, - } - containerMetrics.limits[containerName] = rsrcs - } - - return nil -} - // renderUsageTable renders a table displaying resource usage for pods. - -// It returns: -// - Any error that occurred while rendering the table -func renderUsageTable(ctx context.Context, cfg *Config, pods []corev1.Pod) error { +func renderUsageTable(ctx context.Context, cfg *scout.Config, pods []corev1.Pod) error { columns := []table.Column{ {Title: "Container", Width: 20}, {Title: "Cores", Width: 10}, @@ -201,18 +110,22 @@ func renderUsageTable(ctx context.Context, cfg *Config, pods []corev1.Pod) error var rows []table.Row for _, pod := range pods { - containerMetrics := &ContainerMetrics{pod.Name, map[string]Resources{}} - podMetrics, err := getPodMetrics(ctx, cfg, pod) - if err != nil { - return errors.Wrap(err, "while attempting to fetch pod metrics") + containerMetrics := &scout.ContainerMetrics{ + PodName: pod.Name, + Limits: map[string]scout.Resources{}, } - if err = getLimits(ctx, cfg, &pod, containerMetrics); err != nil { + if err := kube.AddLimits(ctx, cfg, &pod, containerMetrics); err != nil { return errors.Wrap(err, "failed to get get container metrics") } + podMetrics, err := kube.GetPodMetrics(ctx, cfg, pod) + if err != nil { + return errors.Wrap(err, "while attempting to fetch pod metrics") + } + for _, container := range podMetrics.Containers { - stats, err := getContainerUsageStats(ctx, cfg, *containerMetrics, pod, container) + stats, err := kube.GetUsage(ctx, cfg, *containerMetrics, pod, container) if err != nil { return errors.Wrapf(err, "could not compile usage data for row %s\n", container.Name) } @@ -230,269 +143,26 @@ func renderUsageTable(ctx context.Context, cfg *Config, pods []corev1.Pod) error // It returns: // - A table.Row containing the resource usage information // - An error if there was an issue generating the row -func makeRow(usageStats UsageStats) table.Row { - if usageStats.storage == nil { +func makeRow(usageStats scout.UsageStats) table.Row { + if usageStats.Storage == nil { return table.Row{ - usageStats.containerName, - usageStats.cpuCores.String(), - fmt.Sprintf("%.2f%%", usageStats.cpuUsage), - usageStats.memory.String(), - fmt.Sprintf("%.2f%%", usageStats.memoryUsage), + usageStats.ContainerName, + usageStats.CpuCores.String(), + fmt.Sprintf("%.2f%%", usageStats.CpuUsage), + usageStats.Memory.String(), + fmt.Sprintf("%.2f%%", usageStats.MemoryUsage), "-", "-", } } return table.Row{ - usageStats.containerName, - usageStats.cpuCores.String(), - fmt.Sprintf("%.2f%%", usageStats.cpuUsage), - usageStats.memory.String(), - fmt.Sprintf("%.2f%%", usageStats.memoryUsage), - usageStats.storage.String(), - fmt.Sprintf("%.2f%%", usageStats.storageUsage), + usageStats.ContainerName, + usageStats.CpuCores.String(), + fmt.Sprintf("%.2f%%", usageStats.CpuUsage), + usageStats.Memory.String(), + fmt.Sprintf("%.2f%%", usageStats.MemoryUsage), + usageStats.Storage.String(), + fmt.Sprintf("%.2f%%", usageStats.StorageUsage), } } - -// getPods returns a list of pods in the given namespace. -// It returns: -// - []v1.Pod: A list of pods in the given namespace -// - error: Any error that occurred while listing the pods -// -// If no pods are found in the given namespace, it will print an error message and exit. -func getPods(ctx context.Context, cfg *Config) ([]corev1.Pod, error) { - podInterface := cfg.k8sClient.CoreV1().Pods(cfg.namespace) - podList, err := podInterface.List(ctx, metav1.ListOptions{}) - if err != nil { - return []corev1.Pod{}, errors.Wrap(err, "could not list pods") - } - - if len(podList.Items) == 0 { - msg := lipgloss.NewStyle().Foreground(lipgloss.Color("#FFA500")) - fmt.Println(msg.Render(` - No pods exist in this namespace. - Did you mean to use the --namespace flag? - - If you are attempting to check - resources for a docker deployment, you - must use the --docker flag. - See --help for more info. - `)) - os.Exit(1) - } - - return podList.Items, nil -} - -// makeUsageRow generates a table row containing resource usage data for a container. -// -// It returns: -// - A table.Row containing the resource usage information -// - An error if there was an issue generating the row -func getContainerUsageStats( - ctx context.Context, - cfg *Config, - metrics ContainerMetrics, - pod corev1.Pod, - container metav1beta1.ContainerMetrics, -) (UsageStats, error) { - var usageStats UsageStats - usageStats.containerName = container.Name - - cpuUsage, err := getRawUsage(container.Usage, "cpu") - if err != nil { - return UsageStats{}, errors.Wrap(err, "failed to get raw CPU usage") - } - - memUsage, err := getRawUsage(container.Usage, "memory") - if err != nil { - return UsageStats{}, errors.Wrap(err, "failed to get raw memory usage") - } - - var storageCapacity float64 - var storageUsage float64 - stateless := []string{ - "cadvisor", - "pgsql-exporter", - "executor", - "dind", - "github-proxy", - "jaeger", - "node-exporter", - "otel-agent", - "otel-collector", - "precise-code-intel-worker", - "redis-exporter", - "repo-updater", - "frontend", - "syntect-server", - "worker", - } - - if contains(stateless, container.Name) { - storageUsage = 0 - storageCapacity = 0 - } else { - storageCapacity, storageUsage, err = getStorageUsage(ctx, cfg, pod.Name, container.Name) - if err != nil { - return UsageStats{}, errors.Wrap(err, "failed to get storage usage") - } - } - - limits := metrics.limits[container.Name] - - usageStats.cpuCores = limits.cpu - usageStats.cpuUsage = getPercentage( - cpuUsage, - limits.cpu.AsApproximateFloat64()*ABillion, - ) - - usageStats.memory = limits.memory - usageStats.memoryUsage = getPercentage( - memUsage, - limits.memory.AsApproximateFloat64(), - ) - - if limits.storage == nil { - storageDec := *inf.NewDec(0, 0) - usageStats.storage = resource.NewDecimalQuantity(storageDec, resource.Format("DecimalSI")) - } else { - usageStats.storage = limits.storage - } - - usageStats.storageUsage = getPercentage( - storageUsage, - storageCapacity, - ) - - if metrics.limits[container.Name].storage == nil { - usageStats.storage = nil - } - - return usageStats, nil -} - -// getRawUsage converts a Kubernetes ResourceList (map[ResourceName]Quantity) -// into a raw float64 usage value for a given resource. -// -// It returns: -// - The raw float64 usage value for the target resource -// - Any error that occurred during conversion -func getRawUsage(usages corev1.ResourceList, targetKey string) (float64, error) { - var usage *inf.Dec - - for key, val := range usages { - if key.String() == targetKey { - usage = val.AsDec().SetScale(0) - } - } - - toFloat, err := strconv.ParseFloat(usage.String(), 64) - if err != nil { - return 0, errors.Wrap(err, "failed to convert inf.Dec type to float") - } - - return toFloat, nil -} - -// getPvcCapacity retrieves the storage capacity of a PersistentVolumeClaim -// mounted as a volume by a container. -// -// It returns: -// - The capacity Quantity of the PVC if a matching PVC mount is found -// - nil if no PVC mount is found -// - Any error that occurred while getting the PVC -func getPvcCapacity(ctx context.Context, cfg *Config, container corev1.Container, pod *corev1.Pod) (*resource.Quantity, error) { - for _, volumeMount := range container.VolumeMounts { - for _, volume := range pod.Spec.Volumes { - if volume.Name == volumeMount.Name && volume.PersistentVolumeClaim != nil { - pvc, err := cfg.k8sClient. - CoreV1(). - PersistentVolumeClaims(cfg.namespace). - Get( - ctx, - volume.PersistentVolumeClaim.ClaimName, - metav1.GetOptions{}, - ) - if err != nil { - return nil, errors.Wrapf( - err, - "failed to get PVC %s", - volume.PersistentVolumeClaim.ClaimName, - ) - } - return pvc.Status.Capacity.Storage().ToDec(), nil - } - } - } - return nil, nil -} - -// getStorageUsage executes the df -h command in a container and parses the -// output to get the storage usage percentage for ephemeral storage volumes. -// -// It returns: -// - The storage usage percentage for storage volumes -// - "-" if no storage volumes are found -// - Any error that occurred while executing the df -h command or parsing the output -func getStorageUsage(ctx context.Context, cfg *Config, podName, containerName string) (float64, float64, error) { - req := cfg.k8sClient.CoreV1().RESTClient().Post(). - Resource("pods"). - Name(podName). - Namespace(cfg.namespace). - SubResource("exec") - - req.VersionedParams(&corev1.PodExecOptions{ - Container: containerName, - Command: []string{"df"}, - Stdin: false, - Stdout: true, - Stderr: true, - TTY: false, - }, scheme.ParameterCodec) - - exec, err := remotecommand.NewSPDYExecutor(cfg.restConfig, "POST", req.URL()) - if err != nil { - return 0, 0, err - } - - var stdout, stderr bytes.Buffer - err = exec.StreamWithContext(ctx, remotecommand.StreamOptions{ - Stdout: &stdout, - Stderr: &stderr, - }) - if err != nil { - return 0, 0, err - } - - lines := strings.Split(stdout.String(), "\n") - for _, line := range lines[1 : len(lines)-1] { - fields := strings.Fields(line) - - if acceptedFileSystem(fields[0]) { - capacityFloat, err := strconv.ParseFloat(fields[1], 64) - if err != nil { - return 0, 0, errors.Wrap(err, "could not convert string to float64") - } - - usageFloat, err := strconv.ParseFloat(fields[2], 64) - if err != nil { - return 0, 0, errors.Wrap(err, "could not convert string to float64") - } - return capacityFloat, usageFloat, nil - } - } - - return 0, 0, nil -} - -// acceptedFileSystem checks if a given file system, represented -// as a string, is an accepted system. -// -// It returns: -// - True if the file system matches the pattern '/dev/sd[a-z]$' -// - False otherwise -func acceptedFileSystem(fileSystem string) bool { - matched, _ := regexp.MatchString(`/dev/sd[a-z]$`, fileSystem) - return matched -} diff --git a/internal/scout/usage/usage.go b/internal/scout/usage/usage.go index 58cd2e848e..fbdaad3a72 100644 --- a/internal/scout/usage/usage.go +++ b/internal/scout/usage/usage.go @@ -1,68 +1,31 @@ package usage import ( - "github.com/docker/docker/client" - "k8s.io/client-go/kubernetes" - "k8s.io/client-go/rest" - metricsv "k8s.io/metrics/pkg/client/clientset/versioned" + "github.com/sourcegraph/src-cli/internal/scout" ) -type Option = func(config *Config) -type Config struct { - namespace string - pod string - container string - spy bool - docker bool - restConfig *rest.Config - k8sClient *kubernetes.Clientset - dockerClient *client.Client - metricsClient *metricsv.Clientset -} +type Option = func(config *scout.Config) func WithNamespace(namespace string) Option { - return func(config *Config) { - config.namespace = namespace + return func(config *scout.Config) { + config.Namespace = namespace } } func WithPod(podname string) Option { - return func(config *Config) { - config.pod = podname + return func(config *scout.Config) { + config.Pod = podname } } func WithContainer(containerName string) Option { - return func(config *Config) { - config.container = containerName + return func(config *scout.Config) { + config.Container = containerName } } func WithSpy(spy bool) Option { - return func(config *Config) { - config.spy = true - } -} - -// contains checks if a string slice contains a given value. -func contains(slice []string, value string) bool { - for _, v := range slice { - if v == value { - return true - } - } - return false -} - -// getPercentage calculates the percentage of x in relation to y. -func getPercentage(x, y float64) float64 { - if x == 0 { - return 0 + return func(config *scout.Config) { + config.Spy = true } - - if y == 0 { - return 0 - } - - return x * 100 / y } diff --git a/internal/scout/usage/usage_test.go b/internal/scout/usage/usage_test.go index 71e7731ac4..14cc444b28 100644 --- a/internal/scout/usage/usage_test.go +++ b/internal/scout/usage/usage_test.go @@ -3,6 +3,8 @@ package usage import ( "testing" + "github.com/sourcegraph/src-cli/internal/scout" + "github.com/sourcegraph/src-cli/internal/scout/kube" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" ) @@ -55,7 +57,7 @@ func TestGetPercentage(t *testing.T) { for _, tc := range cases { tc := tc t.Run(tc.name, func(t *testing.T) { - got := getPercentage(tc.x, tc.y) + got := scout.GetPercentage(tc.x, tc.y) if got != tc.want { t.Errorf("got %.2f want %.2f", tc.want, got) @@ -103,7 +105,7 @@ func TestGetRawUsage(t *testing.T) { tc := tc t.Run(tc.name, func(t *testing.T) { resourceList := resourceListHelper(tc.cpu, tc.mem) - got, err := getRawUsage(resourceList, tc.targetKey) + got, err := kube.GetRawUsage(resourceList, tc.targetKey) if !tc.shouldError && err != nil { t.Errorf("unexpected error: %v", err) } @@ -146,7 +148,7 @@ func TestContains(t *testing.T) { for _, tc := range cases { tc := tc t.Run(tc.name, func(t *testing.T) { - got := contains(tc.s, tc.val) + got := scout.Contains(tc.s, tc.val) if got != tc.want { t.Errorf("got %v, want %v", got, tc.want) } @@ -154,35 +156,6 @@ func TestContains(t *testing.T) { } } -func TestAcceptedFileSystem(t *testing.T) { - cases := []struct { - name string - filesystem string - want bool - }{ - { - name: "should return true if filesystem matches 'matched' regular expression", - filesystem: "/dev/sda", - want: true, - }, - { - name: "should return false if filesystem doesn't match 'matched' regular expression", - filesystem: "/dev/sda1", - want: false, - }, - } - - for _, tc := range cases { - tc := tc - t.Run(tc.name, func(t *testing.T) { - got := acceptedFileSystem(tc.filesystem) - if got != tc.want { - t.Errorf("got %v want %v", got, tc.want) - } - }) - } -} - func resourceListHelper(cpu *resource.Quantity, mem *resource.Quantity) corev1.ResourceList { return corev1.ResourceList{ corev1.ResourceCPU: *cpu, From 5a99c9bb73eed8c68da4c3fb8cba2584c780b6dd Mon Sep 17 00:00:00 2001 From: Jason Hawk Harris Date: Wed, 7 Jun 2023 13:13:07 -0500 Subject: [PATCH 342/647] add output flag for advise (#990) --- cmd/src/scout_advise.go | 16 ++++++++------ internal/scout/advise/advise.go | 6 ++++++ internal/scout/advise/k8s.go | 38 ++++++++++++++++++++++++++++++--- internal/scout/types.go | 1 + 4 files changed, 51 insertions(+), 10 deletions(-) diff --git a/cmd/src/scout_advise.go b/cmd/src/scout_advise.go index 7ea1bb646e..d58294511b 100644 --- a/cmd/src/scout_advise.go +++ b/cmd/src/scout_advise.go @@ -7,12 +7,13 @@ import ( "path/filepath" "github.com/docker/docker/client" - "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/scout/advise" "k8s.io/client-go/kubernetes" "k8s.io/client-go/tools/clientcmd" "k8s.io/client-go/util/homedir" metricsv "k8s.io/metrics/pkg/client/clientset/versioned" + + "github.com/sourcegraph/sourcegraph/lib/errors" ) func init() { @@ -23,17 +24,14 @@ func init() { Make recommendations for all pods in a kubernetes deployment of Sourcegraph. $ src scout advise - Make recommendations for all containers in a Docker deployment of Sourcegraph. - $ src scout advise - Make recommendations for specific pod: $ src scout advise --pod - Make recommendations for specific container: - $ src scout advise --container - Add namespace if using namespace in a Kubernetes cluster $ src scout advise --namespace + + Output advice to file + $ src scout advise --o path/to/file ` flagSet := flag.NewFlagSet("advise", flag.ExitOnError) @@ -48,6 +46,7 @@ func init() { namespace = flagSet.String("namespace", "", "(optional) specify the kubernetes namespace to use") pod = flagSet.String("pod", "", "(optional) specify a single pod") container = flagSet.String("container", "", "(optional) specify a single container") + output = flagSet.String("o", "", "(optional) output advice to file") docker = flagSet.Bool("docker", false, "(optional) using docker deployment") ) @@ -89,6 +88,9 @@ func init() { if *pod != "" { options = append(options, advise.WithPod(*pod)) } + if *output != "" { + options = append(options, advise.WithOutput(*output)) + } if *container != "" || *docker { if *container != "" { options = append(options, advise.WithContainer(*container)) diff --git a/internal/scout/advise/advise.go b/internal/scout/advise/advise.go index 7df40c13ee..ac08b73ee5 100644 --- a/internal/scout/advise/advise.go +++ b/internal/scout/advise/advise.go @@ -28,3 +28,9 @@ func WithContainer(containerName string) Option { config.Container = containerName } } + +func WithOutput(pathToFile string) Option { + return func(config *scout.Config) { + config.Output = pathToFile + } +} diff --git a/internal/scout/advise/k8s.go b/internal/scout/advise/k8s.go index f540f63160..eb0b505c70 100644 --- a/internal/scout/advise/k8s.go +++ b/internal/scout/advise/k8s.go @@ -3,6 +3,8 @@ package advise import ( "context" "fmt" + "os" + "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/scout" @@ -24,6 +26,7 @@ func K8s( Namespace: "default", Pod: "", Container: "", + Output: "", Spy: false, Docker: false, RestConfig: restConfig, @@ -64,6 +67,11 @@ func K8s( return nil } +// Advise generates resource allocation advice for a Kubernetes pod. +// The function fetches usage metrics for each container in the pod. It then +// checks the usage percentages against thresholds to determine if more or less +// of a resource is needed. Advice is generated and either printed to the console +// or output to a file depending on the cfg.Output field. func Advise(ctx context.Context, cfg *scout.Config, pod v1.Pod) error { var advice []string usageMetrics, err := getUsageMetrics(ctx, cfg, pod) @@ -83,15 +91,39 @@ func Advise(ctx context.Context, cfg *scout.Config, pod v1.Pod) error { advice = append(advice, storageAdvice) } - fmt.Println(scout.EmojiFingerPointRight, pod.Name) - for _, msg := range advice { - fmt.Println(msg) + if cfg.Output != "" { + outputToFile(ctx, cfg, pod, advice) + } else { + for _, msg := range advice { + fmt.Println(msg) + } } } return nil } +// outputToFile writes resource allocation advice for a Kubernetes pod to a file. +func outputToFile(ctx context.Context, cfg *scout.Config, pod v1.Pod, advice []string) error { + file, err := os.OpenFile(cfg.Output, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) + if err != nil { + return errors.Wrap(err, "failed to open file") + } + defer file.Close() + + if _, err := fmt.Fprintf(file, "- %s\n", pod.Name); err != nil { + return errors.Wrap(err, "failed to write pod name to file") + } + + for _, msg := range advice { + if _, err := fmt.Fprintf(file, "%s\n", msg); err != nil { + return errors.Wrap(err, "failed to write container advice to file") + } + } + return nil +} + +// getUsageMetrics generates resource usage statistics for containers in a Kubernetes pod. func getUsageMetrics(ctx context.Context, cfg *scout.Config, pod v1.Pod) ([]scout.UsageStats, error) { var usages []scout.UsageStats var usage scout.UsageStats diff --git a/internal/scout/types.go b/internal/scout/types.go index 13d327036a..5934f8804b 100644 --- a/internal/scout/types.go +++ b/internal/scout/types.go @@ -12,6 +12,7 @@ type Config struct { Namespace string Pod string Container string + Output string Spy bool Docker bool RestConfig *rest.Config From 81cb1c9fb1d9e8cc7ddb001443e2878735cb227b Mon Sep 17 00:00:00 2001 From: Jason Hawk Harris Date: Fri, 16 Jun 2023 09:19:50 -0500 Subject: [PATCH 343/647] remove docker flag from all scout sub-commands (#999) --- cmd/src/scout.go | 5 +- cmd/src/scout_advise.go | 15 ---- cmd/src/scout_resource.go | 14 ---- cmd/src/scout_usage.go | 29 ------- go.mod | 8 -- go.sum | 17 ----- internal/scout/advise/advise.go | 6 -- internal/scout/advise/docker.go | 40 ---------- internal/scout/advise/k8s.go | 7 +- internal/scout/kube/kube.go | 2 +- internal/scout/resource/resource.go | 78 +------------------ internal/scout/types.go | 5 -- internal/scout/usage/docker.go | 114 ---------------------------- internal/scout/usage/k8s.go | 4 - internal/scout/usage/usage.go | 12 --- 15 files changed, 5 insertions(+), 351 deletions(-) delete mode 100644 internal/scout/advise/docker.go delete mode 100644 internal/scout/usage/docker.go diff --git a/cmd/src/scout.go b/cmd/src/scout.go index 0ad74a33c9..d5df574a80 100644 --- a/cmd/src/scout.go +++ b/cmd/src/scout.go @@ -20,9 +20,8 @@ func init() { The commands are: resource print all known sourcegraph resources and their allocations - estimate (coming soon) recommend resource allocation for one or many services - usage (coming soon) get CPU, memory and current disk usage - advise (coming soon) recommend lowering or raising resource allocations based on actual usage + usage get CPU, memory and current disk usage + advise recommend lowering or raising resource allocations based on actual usage Use "src scout [command] -h" for more information about a command. ` diff --git a/cmd/src/scout_advise.go b/cmd/src/scout_advise.go index d58294511b..8deef42a8c 100644 --- a/cmd/src/scout_advise.go +++ b/cmd/src/scout_advise.go @@ -6,7 +6,6 @@ import ( "fmt" "path/filepath" - "github.com/docker/docker/client" "github.com/sourcegraph/src-cli/internal/scout/advise" "k8s.io/client-go/kubernetes" "k8s.io/client-go/tools/clientcmd" @@ -45,9 +44,7 @@ func init() { kubeConfig *string namespace = flagSet.String("namespace", "", "(optional) specify the kubernetes namespace to use") pod = flagSet.String("pod", "", "(optional) specify a single pod") - container = flagSet.String("container", "", "(optional) specify a single container") output = flagSet.String("o", "", "(optional) output advice to file") - docker = flagSet.Bool("docker", false, "(optional) using docker deployment") ) if home := homedir.HomeDir(); home != "" { @@ -91,18 +88,6 @@ func init() { if *output != "" { options = append(options, advise.WithOutput(*output)) } - if *container != "" || *docker { - if *container != "" { - options = append(options, advise.WithContainer(*container)) - } - - dockerClient, err := client.NewClientWithOpts(client.FromEnv) - if err != nil { - return errors.Wrap(err, "error creating docker client: ") - } - - return advise.Docker(context.Background(), *dockerClient, options...) - } return advise.K8s( context.Background(), diff --git a/cmd/src/scout_resource.go b/cmd/src/scout_resource.go index 32accda5f6..f4c8cf2b5b 100644 --- a/cmd/src/scout_resource.go +++ b/cmd/src/scout_resource.go @@ -6,7 +6,6 @@ import ( "fmt" "path/filepath" - "github.com/docker/docker/client" "github.com/sourcegraph/sourcegraph/lib/errors" "k8s.io/client-go/kubernetes" "k8s.io/client-go/tools/clientcmd" @@ -23,9 +22,6 @@ func init() { List pods and resource allocations in a Kubernetes deployment: $ src scout resource - List containers and resource allocations in a Docker deployment: - $ src scout resource --docker - Add namespace if using namespace in a Kubernetes cluster $ src scout resource --namespace sg ` @@ -40,7 +36,6 @@ func init() { var ( kubeConfig *string namespace = flagSet.String("namespace", "", "(optional) specify the kubernetes namespace to use") - docker = flagSet.Bool("docker", false, "(optional) using docker deployment") // TODO: option for getting resource allocation of the Node // nodes = flagSet.Bool("node", false, "(optional) view resources for node(s)") ) @@ -76,15 +71,6 @@ func init() { options = append(options, resource.WithNamespace(*namespace)) } - if *docker { - dockerClient, err := client.NewClientWithOpts(client.FromEnv) - if err != nil { - return errors.Wrap(err, "error creating docker client: ") - } - - return resource.Docker(context.Background(), *dockerClient) - } - return resource.K8s(context.Background(), clientSet, config, options...) } diff --git a/cmd/src/scout_usage.go b/cmd/src/scout_usage.go index 1ac7fc4257..ba12fd6c11 100644 --- a/cmd/src/scout_usage.go +++ b/cmd/src/scout_usage.go @@ -6,7 +6,6 @@ import ( "fmt" "path/filepath" - "github.com/docker/docker/client" "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/scout/usage" "k8s.io/client-go/kubernetes" @@ -23,20 +22,11 @@ func init() { List pods and resource usage in a Kubernetes deployment: $ src scout usage - List containers and resource usage in a Docker deployment: - $ src scout usage --docker - Check usage for specific pod $ src scout usage --pod - Check usage for specific container (docker only) - $ src scout usage --container - Add namespace if using namespace in a Kubernetes cluster $ src scout usage --namespace - - Watch usage in real time - $ src scout usage --spy ` flagSet := flag.NewFlagSet("usage", flag.ExitOnError) @@ -50,9 +40,6 @@ func init() { kubeConfig *string namespace = flagSet.String("namespace", "", "(optional) specify the kubernetes namespace to use") pod = flagSet.String("pod", "", "(optional) specify a single pod") - container = flagSet.String("container", "", "(optional) specify a single container") - docker = flagSet.Bool("docker", false, "(optional) using docker deployment") - spy = flagSet.Bool("spy", false, "(optional) see resource usage in real time") ) if home := homedir.HomeDir(); home != "" { @@ -86,28 +73,12 @@ func init() { } var options []usage.Option - if *namespace != "" { options = append(options, usage.WithNamespace(*namespace)) } - if *spy { - options = append(options, usage.WithSpy(true)) - } if *pod != "" { options = append(options, usage.WithPod(*pod)) } - if *container != "" || *docker { - if *container != "" { - options = append(options, usage.WithContainer(*container)) - } - - dockerClient, err := client.NewClientWithOpts(client.FromEnv) - if err != nil { - return errors.Wrap(err, "error creating docker client: ") - } - - return usage.Docker(context.Background(), *dockerClient, options...) - } return usage.K8s( context.Background(), diff --git a/go.mod b/go.mod index 15e9617bf5..c617b7e784 100644 --- a/go.mod +++ b/go.mod @@ -13,7 +13,6 @@ require ( github.com/creack/goselect v0.1.2 github.com/derision-test/glock v0.0.0-20210316032053-f5b74334bb29 github.com/dineshappavoo/basex v0.0.0-20170425072625-481a6f6dc663 - github.com/docker/docker v23.0.5+incompatible github.com/dustin/go-humanize v1.0.1 github.com/gobwas/glob v0.2.3 github.com/google/go-cmp v0.5.9 @@ -60,7 +59,6 @@ require ( github.com/Masterminds/goutils v1.1.1 // indirect github.com/Masterminds/semver v1.5.0 // indirect github.com/Masterminds/sprig v2.22.0+incompatible // indirect - github.com/Microsoft/go-winio v0.6.1 // indirect github.com/alecthomas/chroma v0.10.0 // indirect github.com/aws/aws-sdk-go-v2 v1.17.5 // indirect github.com/aws/aws-sdk-go-v2/credentials v1.13.13 // indirect @@ -85,9 +83,6 @@ require ( github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/dlclark/regexp2 v1.7.0 // indirect - github.com/docker/distribution v2.8.1+incompatible // indirect - github.com/docker/go-connections v0.4.0 // indirect - github.com/docker/go-units v0.5.0 // indirect github.com/emicklei/go-restful/v3 v3.9.0 // indirect github.com/envoyproxy/protoc-gen-validate v0.9.1 // indirect github.com/fatih/color v1.13.0 // indirect @@ -134,7 +129,6 @@ require ( github.com/moby/term v0.0.0-20221205130635-1aeaba878587 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect - github.com/morikuni/aec v1.0.0 // indirect github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b // indirect github.com/muesli/cancelreader v0.2.2 // indirect github.com/muesli/reflow v0.3.0 // indirect @@ -143,8 +137,6 @@ require ( github.com/mwitkow/go-proto-validators v0.3.2 // indirect github.com/nightlyone/lockfile v1.0.0 // indirect github.com/olekukonko/tablewriter v0.0.5 // indirect - github.com/opencontainers/go-digest v1.0.0 // indirect - github.com/opencontainers/image-spec v1.0.2 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/pkg/profile v1.6.0 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect diff --git a/go.sum b/go.sum index cb2ad81c22..e6721f4ea6 100644 --- a/go.sum +++ b/go.sum @@ -28,8 +28,6 @@ github.com/Masterminds/semver v1.5.0 h1:H65muMkzWKEuNDnfl9d70GUjFniHKHRbFPGBuZ3Q github.com/Masterminds/semver v1.5.0/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y= github.com/Masterminds/sprig v2.22.0+incompatible h1:z4yfnGrZ7netVz+0EDJ0Wi+5VZCSYp4Z0m2dk6cEM60= github.com/Masterminds/sprig v2.22.0+incompatible/go.mod h1:y6hNFY5UBTIWBxnzTeuNhlNS5hqE0NB0E6fgfo2Br3o= -github.com/Microsoft/go-winio v0.6.1 h1:9/kr64B9VUZrLm5YYwbGtUJnMgqWVOdUAXu6Migciow= -github.com/Microsoft/go-winio v0.6.1/go.mod h1:LRdKpFKfdobln8UmuiYcKPot9D2v6svN5+sAH+4kjUM= github.com/Shopify/goreferrer v0.0.0-20181106222321-ec9c9a553398/go.mod h1:a1uqRtAwp2Xwc6WNPJEufxJ7fx3npB4UV/JOLmbu5I0= github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY= github.com/alecthomas/chroma v0.10.0 h1:7XDcGkCQopCNKjZHfYrNLraA+M7e0fMiJ/Mfikbfjek= @@ -131,14 +129,6 @@ github.com/dineshappavoo/basex v0.0.0-20170425072625-481a6f6dc663/go.mod h1:Kad2 github.com/dlclark/regexp2 v1.4.0/go.mod h1:2pZnwuY/m+8K6iRw6wQdMtk+rH5tNGR1i55kozfMjCc= github.com/dlclark/regexp2 v1.7.0 h1:7lJfhqlPssTb1WQx4yvTHN0uElPEv52sbaECrAQxjAo= github.com/dlclark/regexp2 v1.7.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= -github.com/docker/distribution v2.8.1+incompatible h1:Q50tZOPR6T/hjNsyc9g8/syEs6bk8XXApsHjKukMl68= -github.com/docker/distribution v2.8.1+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= -github.com/docker/docker v23.0.5+incompatible h1:DaxtlTJjFSnLOXVNUBU1+6kXGz2lpDoEAH6QoxaSg8k= -github.com/docker/docker v23.0.5+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= -github.com/docker/go-connections v0.4.0 h1:El9xVISelRB7BuFusrZozjnkIM5YnzCViNKohAFqRJQ= -github.com/docker/go-connections v0.4.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5XhDvyHbTtUxmeec= -github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4= -github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= github.com/docopt/docopt-go v0.0.0-20180111231733-ee0de3bc6815/go.mod h1:WwZ+bS3ebgob9U8Nd0kOddGdZWjyMGR8Wziv+TBNwSE= github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= @@ -405,8 +395,6 @@ github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lN github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= -github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A= -github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc= github.com/moul/http2curl v1.0.0/go.mod h1:8UbvGypXm98wA/IqH45anm5Y2Z6ep6O31QGOAZ3H0fQ= github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b h1:1XF24mVaiu7u+CFywTdcDo2ie1pzzhwjt6RHqzpMU34= github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b/go.mod h1:fQuZ0gauxyBcmsdE3ZT4NasjaRdxmbCS0jRHsrWu3Ho= @@ -447,10 +435,6 @@ github.com/onsi/ginkgo/v2 v2.9.1 h1:zie5Ly042PD3bsCvsSOPvRnFwyo3rKe64TJlD6nu0mk= github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= github.com/onsi/gomega v1.27.4 h1:Z2AnStgsdSayCMDiCU42qIz+HLqEPcgiOCXjAU/w+8E= -github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= -github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= -github.com/opencontainers/image-spec v1.0.2 h1:9yCKha/T5XdGtO0q9Q9a6T5NUCsTn/DrBg0D7ufOcFM= -github.com/opencontainers/image-spec v1.0.2/go.mod h1:BtxoFyWECRxE4U/7sNtV5W15zMzWCbyJoFRP3s7yZA0= github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4= github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8= @@ -813,7 +797,6 @@ gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C gopkg.in/yaml.v3 v3.0.0/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gotest.tools/v3 v3.0.3 h1:4AuOwCGf4lLR9u3YOe2awrHygurzhO/HeQ6laiA6Sx0= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7 h1:mub0MmFLOn8XLikZOAhgLD1kXJq8jgftSrrv7m00xFo= diff --git a/internal/scout/advise/advise.go b/internal/scout/advise/advise.go index ac08b73ee5..bdcd977acc 100644 --- a/internal/scout/advise/advise.go +++ b/internal/scout/advise/advise.go @@ -23,12 +23,6 @@ func WithPod(podname string) Option { } } -func WithContainer(containerName string) Option { - return func(config *scout.Config) { - config.Container = containerName - } -} - func WithOutput(pathToFile string) Option { return func(config *scout.Config) { config.Output = pathToFile diff --git a/internal/scout/advise/docker.go b/internal/scout/advise/docker.go deleted file mode 100644 index 319a5ceb4e..0000000000 --- a/internal/scout/advise/docker.go +++ /dev/null @@ -1,40 +0,0 @@ -package advise - -import ( - "context" - "fmt" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/client" - "github.com/sourcegraph/sourcegraph/lib/errors" - "github.com/sourcegraph/src-cli/internal/scout" -) - -func Docker(ctx context.Context, client client.Client, opts ...Option) error { - cfg := &scout.Config{ - Namespace: "default", - Docker: true, - Pod: "", - Container: "", - Spy: false, - DockerClient: &client, - } - - for _, opt := range opts { - opt(cfg) - } - - containers, err := client.ContainerList(ctx, types.ContainerListOptions{}) - if err != nil { - return errors.Wrap(err, "could not get list of containers") - } - - PrintContainers(containers) - return nil -} - -func PrintContainers(containers []types.Container) { - for _, c := range containers { - fmt.Println(c.Image) - } -} diff --git a/internal/scout/advise/k8s.go b/internal/scout/advise/k8s.go index eb0b505c70..f10e58924f 100644 --- a/internal/scout/advise/k8s.go +++ b/internal/scout/advise/k8s.go @@ -5,7 +5,6 @@ import ( "fmt" "os" - "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/scout" "github.com/sourcegraph/src-cli/internal/scout/kube" @@ -25,13 +24,9 @@ func K8s( cfg := &scout.Config{ Namespace: "default", Pod: "", - Container: "", Output: "", - Spy: false, - Docker: false, RestConfig: restConfig, K8sClient: k8sClient, - DockerClient: nil, MetricsClient: metricsClient, } @@ -94,7 +89,7 @@ func Advise(ctx context.Context, cfg *scout.Config, pod v1.Pod) error { if cfg.Output != "" { outputToFile(ctx, cfg, pod, advice) } else { - for _, msg := range advice { + for _, msg := range advice { fmt.Println(msg) } } diff --git a/internal/scout/kube/kube.go b/internal/scout/kube/kube.go index 5e5523266d..7dc0a6f0e0 100644 --- a/internal/scout/kube/kube.go +++ b/internal/scout/kube/kube.go @@ -105,7 +105,6 @@ func AddLimits(ctx context.Context, cfg *scout.Config, pod *corev1.Pod, containe } containerMetrics.Limits[containerName] = rsrcs } - return nil } @@ -287,6 +286,7 @@ func GetStorageUsage( "worker", } + // if pod is stateless, return 0 for capacity and usage if scout.Contains(stateless, containerName) { return storageCapacity, storageUsage, nil } diff --git a/internal/scout/resource/resource.go b/internal/scout/resource/resource.go index ddfd99da8a..6be8a873e0 100644 --- a/internal/scout/resource/resource.go +++ b/internal/scout/resource/resource.go @@ -7,11 +7,9 @@ import ( "github.com/charmbracelet/bubbles/table" "github.com/charmbracelet/lipgloss" - "github.com/docker/docker/api/types" - "github.com/docker/docker/client" "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/scout" - kube "github.com/sourcegraph/src-cli/internal/scout/kube" + "github.com/sourcegraph/src-cli/internal/scout/kube" "github.com/sourcegraph/src-cli/internal/scout/style" "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" @@ -29,13 +27,9 @@ func WithNamespace(namespace string) Option { func K8s(ctx context.Context, clientSet *kubernetes.Clientset, restConfig *rest.Config, opts ...Option) error { cfg := &scout.Config{ Namespace: "default", - Docker: false, Pod: "", - Container: "", - Spy: false, RestConfig: restConfig, K8sClient: clientSet, - DockerClient: nil, MetricsClient: nil, } @@ -106,76 +100,6 @@ func listPodResources(ctx context.Context, cfg *scout.Config) error { return nil } -// Docker prints the CPU and memory resource limits and requests for running Docker containers. -func Docker(ctx context.Context, dockerClient client.Client) error { - containers, err := dockerClient.ContainerList(ctx, types.ContainerListOptions{}) - if err != nil { - return fmt.Errorf("error listing docker containers: %v", err) - } - - if len(containers) == 0 { - msg := lipgloss.NewStyle().Foreground(lipgloss.Color("#FFA500")) - fmt.Println(msg.Render(` - There are no containers, or the Docker Daemon is not running - `)) - os.Exit(1) - } - - columns := []table.Column{ - {Title: "Container", Width: 20}, - {Title: "CPU Cores", Width: 15}, - {Title: "CPU Shares", Width: 15}, - {Title: "Mem Limits", Width: 15}, - {Title: "Mem Reservations", Width: 17}, - } - - var rows []table.Row - - for _, container := range containers { - containerInfo, err := dockerClient.ContainerInspect(ctx, container.ID) - if err != nil { - return fmt.Errorf("error inspecting container %s: %v", container.ID, err) - } - - row, err := getResourceInfo(&containerInfo, rows) - if err != nil { - return errors.Wrap(err, "error while getting resource info from container: ") - } - - rows = append(rows, row) - } - - style.ResourceTable(columns, rows) - return nil -} - -func getResourceInfo(container *types.ContainerJSON, rows []table.Row) (table.Row, error) { - cpuCores := container.HostConfig.NanoCPUs - cpuShares := container.HostConfig.CPUShares - memLimits := container.HostConfig.Memory - memReservations := container.HostConfig.MemoryReservation - - reqUnit, reqVal, err := getMemUnits(memReservations) - if err != nil { - return table.Row{}, errors.Wrap(err, "error while getting request units") - } - - limUnit, limVal, err := getMemUnits(memLimits) - if err != nil { - return table.Row{}, errors.Wrap(err, "error while getting limit units") - } - - row := table.Row{ - container.Name, - fmt.Sprintf("%v", float64(cpuCores/1e9)), - fmt.Sprint(cpuShares), - fmt.Sprintf("%d%s", limVal, limUnit), - fmt.Sprintf("%d%s", reqVal, reqUnit), - } - - return row, nil -} - // getMemUnits converts a byte value to the appropriate memory unit. func getMemUnits(valToConvert int64) (string, int64, error) { if valToConvert < 0 { diff --git a/internal/scout/types.go b/internal/scout/types.go index 5934f8804b..9703fac20c 100644 --- a/internal/scout/types.go +++ b/internal/scout/types.go @@ -1,7 +1,6 @@ package scout import ( - "github.com/docker/docker/client" "k8s.io/apimachinery/pkg/api/resource" "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" @@ -11,13 +10,9 @@ import ( type Config struct { Namespace string Pod string - Container string Output string - Spy bool - Docker bool RestConfig *rest.Config K8sClient *kubernetes.Clientset - DockerClient *client.Client MetricsClient *metricsv.Clientset } diff --git a/internal/scout/usage/docker.go b/internal/scout/usage/docker.go deleted file mode 100644 index c46cded08e..0000000000 --- a/internal/scout/usage/docker.go +++ /dev/null @@ -1,114 +0,0 @@ -package usage - -import ( - "context" - "encoding/json" - "fmt" - "os" - - "github.com/charmbracelet/bubbles/table" - "github.com/charmbracelet/lipgloss" - "github.com/docker/docker/api/types" - "github.com/docker/docker/client" - "github.com/sourcegraph/sourcegraph/lib/errors" - "github.com/sourcegraph/src-cli/internal/scout" - "github.com/sourcegraph/src-cli/internal/scout/style" -) - -func Docker(ctx context.Context, client client.Client, opts ...Option) error { - cfg := &scout.Config{ - Namespace: "default", - Docker: true, - Pod: "", - Container: "", - Spy: false, - DockerClient: &client, - } - - for _, opt := range opts { - opt(cfg) - } - - containers, err := cfg.DockerClient.ContainerList(ctx, types.ContainerListOptions{}) - if err != nil { - return errors.Wrap(err, "could not get list of containers") - } - - return renderDockerUsageTable(ctx, cfg, containers) -} - -// renderDockerUsageTable renders a table displaying CPU and memory usage for Docker containers. -func renderDockerUsageTable(ctx context.Context, cfg *scout.Config, containers []types.Container) error { - columns := []table.Column{ - {Title: "Container", Width: 20}, - {Title: "Cores", Width: 10}, - {Title: "Usage", Width: 10}, - {Title: "Memory", Width: 10}, - {Title: "Usage", Width: 10}, - } - rows := []table.Row{} - - for _, container := range containers { - containerInfo, err := cfg.DockerClient.ContainerInspect(ctx, container.ID) - if err != nil { - return errors.Wrap(err, "failed to get container info") - } - - if cfg.Container != "" { - if containerInfo.Name == cfg.Container { - row := makeDockerUsageRow(ctx, cfg, containerInfo) - rows = append(rows, row) - break - } else { - continue - } - } - - row := makeDockerUsageRow(ctx, cfg, containerInfo) - rows = append(rows, row) - } - - if len(rows) == 0 { - msg := lipgloss.NewStyle().Foreground(lipgloss.Color("#FFA500")) - if cfg.Container == "" { - fmt.Println(msg.Render(`No docker containers are running.`)) - os.Exit(1) - } - fmt.Println(msg.Render( - fmt.Sprintf(`No container with name '%s' running.`, cfg.Container), - )) - os.Exit(1) - } - - style.UsageTable(columns, rows) - return nil -} - -// makeDockerUsageRow generates a table row displaying CPU and memory usage for a Docker container. -func makeDockerUsageRow(ctx context.Context, cfg *scout.Config, container types.ContainerJSON) table.Row { - stats, err := cfg.DockerClient.ContainerStats(ctx, container.ID, false) - if err != nil { - errors.Wrap(err, "could not get container stats") - os.Exit(1) - } - defer func() { _ = stats.Body.Close() }() - - var usage types.StatsJSON - if err := json.NewDecoder(stats.Body).Decode(&usage); err != nil { - errors.Wrap(err, "could not get container stats") - os.Exit(1) - } - - cpuCores := float64(container.HostConfig.NanoCPUs) - memory := float64(container.HostConfig.Memory) - cpuUsage := float64(usage.CPUStats.CPUUsage.TotalUsage) - memoryUsage := float64(usage.MemoryStats.Usage) - - return table.Row{ - container.Name, - fmt.Sprintf("%.2f", cpuCores/1_000_000_000), - fmt.Sprintf("%.2f%%", scout.GetPercentage(cpuUsage, cpuCores)), - fmt.Sprintf("%.2fG", memory/1_000_000_000), - fmt.Sprintf("%.2f%%", scout.GetPercentage(memoryUsage, memory)), - } -} diff --git a/internal/scout/usage/k8s.go b/internal/scout/usage/k8s.go index 1ca9977eba..c3805938a0 100644 --- a/internal/scout/usage/k8s.go +++ b/internal/scout/usage/k8s.go @@ -25,13 +25,9 @@ func K8s( ) error { cfg := &scout.Config{ Namespace: "default", - Docker: false, Pod: "", - Container: "", - Spy: false, RestConfig: restConfig, K8sClient: clientSet, - DockerClient: nil, MetricsClient: metricsClient, } diff --git a/internal/scout/usage/usage.go b/internal/scout/usage/usage.go index fbdaad3a72..df4cb31b7a 100644 --- a/internal/scout/usage/usage.go +++ b/internal/scout/usage/usage.go @@ -17,15 +17,3 @@ func WithPod(podname string) Option { config.Pod = podname } } - -func WithContainer(containerName string) Option { - return func(config *scout.Config) { - config.Container = containerName - } -} - -func WithSpy(spy bool) Option { - return func(config *scout.Config) { - config.Spy = true - } -} From 25f9e0f5da19428536ff2c04cd3932755fae360d Mon Sep 17 00:00:00 2001 From: Jason Hawk Harris Date: Fri, 16 Jun 2023 09:57:21 -0500 Subject: [PATCH 344/647] test advise package and more tests for kube package (#1000) * test advise package and more tests for kube package * Make OutputToFile function compatible with Windows --- internal/scout/advise/advise.go | 71 ++++++++++++++- internal/scout/advise/advise_test.go | 128 +++++++++++++++++++++++++++ internal/scout/advise/k8s.go | 72 +-------------- internal/scout/kube/kube_test.go | 54 ++++++++++- 4 files changed, 255 insertions(+), 70 deletions(-) create mode 100644 internal/scout/advise/advise_test.go diff --git a/internal/scout/advise/advise.go b/internal/scout/advise/advise.go index bdcd977acc..b42e3446cf 100644 --- a/internal/scout/advise/advise.go +++ b/internal/scout/advise/advise.go @@ -1,6 +1,13 @@ package advise -import "github.com/sourcegraph/src-cli/internal/scout" +import ( + "context" + "fmt" + "os" + + "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/src-cli/internal/scout" +) type Option = func(config *scout.Config) @@ -28,3 +35,65 @@ func WithOutput(pathToFile string) Option { config.Output = pathToFile } } + +func CheckUsage(usage float64, resourceType string, container string) string { + var message string + switch { + case usage >= 100: + message = fmt.Sprintf( + OVER_100, + scout.FlashingLightEmoji, + container, + resourceType, + usage, + resourceType, + ) + case usage >= 80 && usage < 100: + message = fmt.Sprintf( + OVER_80, + scout.WarningSign, + container, + resourceType, + usage, + ) + case usage >= 40 && usage < 80: + message = fmt.Sprintf( + OVER_40, + scout.SuccessEmoji, + container, + resourceType, + usage, + resourceType, + ) + default: + message = fmt.Sprintf( + UNDER_40, + scout.WarningSign, + container, + resourceType, + usage, + ) + } + + return message +} + +// outputToFile writes resource allocation advice for a Kubernetes pod to a file. +func OutputToFile(ctx context.Context, cfg *scout.Config, name string, advice []string) error { + file, err := os.OpenFile(cfg.Output, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) + if err != nil { + return errors.Wrap(err, "failed to open file") + } + defer file.Close() + + if _, err := fmt.Fprintf(file, "- %s\n", name); err != nil { + return errors.Wrap(err, "failed to write service name to file") + } + + for _, msg := range advice { + if _, err := fmt.Fprintf(file, "%s\n", msg); err != nil { + return errors.Wrap(err, "failed to write container advice to file") + } + } + return nil +} diff --git a/internal/scout/advise/advise_test.go b/internal/scout/advise/advise_test.go new file mode 100644 index 0000000000..9d5a7a0196 --- /dev/null +++ b/internal/scout/advise/advise_test.go @@ -0,0 +1,128 @@ +package advise + +import ( + "bufio" + "context" + "os" + "testing" + "time" + + "github.com/sourcegraph/src-cli/internal/scout" +) + +func TestCheckUsage(t *testing.T) { + cases := []struct { + name string + usage float64 + resourceType string + container string + want string + }{ + { + name: "should return correct message for usage over 100", + usage: 110, + resourceType: "cpu", + container: "gitserver-0", + want: "\t🚨 gitserver-0: Your cpu usage is over 100% (110.00%). Add more cpu.", + }, + { + name: "should return correct message for usage over 80 and under 100", + usage: 87, + resourceType: "memory", + container: "gitserver-0", + want: "\t⚠️ gitserver-0: Your memory usage is over 80% (87.00%). Consider raising limits.", + }, + { + name: "should return correct message for usage over 40 and under 80", + usage: 63.4, + resourceType: "memory", + container: "gitserver-0", + want: "\t✅ gitserver-0: Your memory usage is under 80% (63.40%). Keep memory allocation the same.", + }, + { + name: "should return correct message for usage under 40", + usage: 22.33, + resourceType: "memory", + container: "gitserver-0", + want: "\t⚠️ gitserver-0: Your memory usage is under 40% (22.33%). Consider lowering limits.", + }, + } + + for _, tc := range cases { + tc := tc + t.Run(tc.name, func(t *testing.T) { + got := CheckUsage(tc.usage, tc.resourceType, tc.container) + + if got != tc.want { + t.Errorf("got: '%s' want '%s'", got, tc.want) + } + }) + } +} + +func TestOutputToFile(t *testing.T) { + cfg := &scout.Config{ + Output: os.TempDir() + string(os.PathSeparator) + "test.txt", + } + name := "gitserver-0" + advice := []string{ + "Add more CPU", + "Add more memory", + } + + err := OutputToFile(context.Background(), cfg, name, advice) + if err != nil { + t.Fatal(err) + } + + lines := readOutputFile(t, cfg) + + cases := []struct { + lineNum int + want string + }{ + {1, "- gitserver-0"}, + {2, "Add more CPU"}, + {3, "Add more memory"}, + } + + for _, tc := range cases { + tc := tc + if lines[tc.lineNum-1] != tc.want { + t.Errorf("Expected %q, got %q", tc.want, lines[tc.lineNum-1]) + } + } + + if len(lines) > 3 { + t.Error("Expected only 3 lines, got more") + } + + if err != nil { + t.Fatal(err) + } +} + +func readOutputFile(t *testing.T, cfg *scout.Config) []string { + file, err := os.Open(cfg.Output) + if err != nil { + t.Fatal(err) + } + + var lines []string + scanner := bufio.NewScanner(file) + for scanner.Scan() { + lines = append(lines, scanner.Text()) + } + + file.Close() + err = os.Remove(cfg.Output) + if err != nil { + // try again after waiting a bit + time.Sleep(100 * time.Millisecond) + err = os.Remove(cfg.Output) + if err != nil { + t.Fatal(err) + } + } + return lines +} diff --git a/internal/scout/advise/k8s.go b/internal/scout/advise/k8s.go index f10e58924f..e95e887b9f 100644 --- a/internal/scout/advise/k8s.go +++ b/internal/scout/advise/k8s.go @@ -3,7 +3,6 @@ package advise import ( "context" "fmt" - "os" "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/scout" @@ -75,19 +74,19 @@ func Advise(ctx context.Context, cfg *scout.Config, pod v1.Pod) error { } for _, metrics := range usageMetrics { - cpuAdvice := checkUsage(metrics.CpuUsage, "CPU", metrics.ContainerName, pod.Name) + cpuAdvice := CheckUsage(metrics.CpuUsage, "CPU", metrics.ContainerName) advice = append(advice, cpuAdvice) - memoryAdvice := checkUsage(metrics.MemoryUsage, "memory", metrics.ContainerName, pod.Name) + memoryAdvice := CheckUsage(metrics.MemoryUsage, "memory", metrics.ContainerName) advice = append(advice, memoryAdvice) if metrics.Storage != nil { - storageAdvice := checkUsage(metrics.StorageUsage, "storage", metrics.ContainerName, pod.Name) + storageAdvice := CheckUsage(metrics.StorageUsage, "storage", metrics.ContainerName) advice = append(advice, storageAdvice) } if cfg.Output != "" { - outputToFile(ctx, cfg, pod, advice) + OutputToFile(ctx, cfg, pod.Name, advice) } else { for _, msg := range advice { fmt.Println(msg) @@ -98,26 +97,6 @@ func Advise(ctx context.Context, cfg *scout.Config, pod v1.Pod) error { return nil } -// outputToFile writes resource allocation advice for a Kubernetes pod to a file. -func outputToFile(ctx context.Context, cfg *scout.Config, pod v1.Pod, advice []string) error { - file, err := os.OpenFile(cfg.Output, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) - if err != nil { - return errors.Wrap(err, "failed to open file") - } - defer file.Close() - - if _, err := fmt.Fprintf(file, "- %s\n", pod.Name); err != nil { - return errors.Wrap(err, "failed to write pod name to file") - } - - for _, msg := range advice { - if _, err := fmt.Fprintf(file, "%s\n", msg); err != nil { - return errors.Wrap(err, "failed to write container advice to file") - } - } - return nil -} - // getUsageMetrics generates resource usage statistics for containers in a Kubernetes pod. func getUsageMetrics(ctx context.Context, cfg *scout.Config, pod v1.Pod) ([]scout.UsageStats, error) { var usages []scout.UsageStats @@ -146,46 +125,3 @@ func getUsageMetrics(ctx context.Context, cfg *scout.Config, pod v1.Pod) ([]scou return usages, nil } - -func checkUsage(usage float64, resourceType, container, pod string) string { - var message string - - switch { - case usage >= 100: - message = fmt.Sprintf( - OVER_100, - scout.FlashingLightEmoji, - container, - resourceType, - usage, - resourceType, - ) - case usage >= 80 && usage < 100: - message = fmt.Sprintf( - OVER_80, - scout.WarningSign, - container, - resourceType, - usage, - ) - case usage >= 40 && usage < 80: - message = fmt.Sprintf( - OVER_40, - scout.SuccessEmoji, - container, - resourceType, - usage, - resourceType, - ) - default: - message = fmt.Sprintf( - UNDER_40, - scout.WarningSign, - container, - resourceType, - usage, - ) - } - - return message -} diff --git a/internal/scout/kube/kube_test.go b/internal/scout/kube/kube_test.go index 787e894234..c45080dced 100644 --- a/internal/scout/kube/kube_test.go +++ b/internal/scout/kube/kube_test.go @@ -1,6 +1,11 @@ package kube -import "testing" +import ( + "testing" + + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) func TestAcceptedFileSystem(t *testing.T) { cases := []struct { @@ -30,3 +35,50 @@ func TestAcceptedFileSystem(t *testing.T) { }) } } + +func TestGetPod(t *testing.T) { + cases := []struct { + name string + podList []corev1.Pod + wantPod string + }{ + { + name: "should return correct pod", + podList: []corev1.Pod{ + *testPod("sg", "soucegraph-frontend-0", "sourcegraph-frontend"), + *testPod("sg", "gitserver-0", "gitserver"), + *testPod("sg", "indexed-search-0", "indexed-search"), + }, + wantPod: "gitserver-0", + }, + { + name: "should return empty pod if pod not found", + podList: []corev1.Pod{ + *testPod("sg", "soucegraph-frontend-0", "sourcegraph-frontend"), + *testPod("sg", "indexed-search-0", "indexed-search"), + }, + wantPod: "", + }, + } + + for _, tc := range cases { + tc := tc + t.Run(tc.name, func(t *testing.T) { + got, _ := GetPod("gitserver-0", tc.podList) + gotPod := got.Name + + if gotPod != tc.wantPod { + t.Errorf("want pod %s, got pod %s", tc.wantPod, gotPod) + } + }) + } +} + +func testPod(namespace, podName, containerName string) *corev1.Pod { + return &corev1.Pod{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: namespace, + Name: podName, + }, + } +} From 1cd7ede33be51a0552537c9b4bee205993451048 Mon Sep 17 00:00:00 2001 From: Jason Hawk Harris Date: Fri, 16 Jun 2023 12:45:01 -0500 Subject: [PATCH 345/647] print warnings with `--warnings` flag (#1001) * warnings flag supresses warning messages * formatting fixes * fix tests --- cmd/src/scout_advise.go | 8 ++++- internal/scout/advise/advise.go | 54 ++++++++++++++-------------- internal/scout/advise/advise_test.go | 43 +++++++++++++++------- internal/scout/advise/k8s.go | 33 +++++++++++++---- internal/scout/constants.go | 3 ++ internal/scout/types.go | 6 ++++ 6 files changed, 99 insertions(+), 48 deletions(-) diff --git a/cmd/src/scout_advise.go b/cmd/src/scout_advise.go index 8deef42a8c..129a13c660 100644 --- a/cmd/src/scout_advise.go +++ b/cmd/src/scout_advise.go @@ -31,6 +31,9 @@ func init() { Output advice to file $ src scout advise --o path/to/file + + Output with warnings + $ src scout advise --warnings ` flagSet := flag.NewFlagSet("advise", flag.ExitOnError) @@ -45,6 +48,7 @@ func init() { namespace = flagSet.String("namespace", "", "(optional) specify the kubernetes namespace to use") pod = flagSet.String("pod", "", "(optional) specify a single pod") output = flagSet.String("o", "", "(optional) output advice to file") + warnings = flagSet.Bool("warnings", false, "(optional) output advice with warnings") ) if home := homedir.HomeDir(); home != "" { @@ -88,6 +92,9 @@ func init() { if *output != "" { options = append(options, advise.WithOutput(*output)) } + if *warnings { + options = append(options, advise.WithWarnings(true)) + } return advise.K8s( context.Background(), @@ -103,5 +110,4 @@ func init() { handler: handler, usageFunc: usage, }) - } diff --git a/internal/scout/advise/advise.go b/internal/scout/advise/advise.go index b42e3446cf..c1cefe90c0 100644 --- a/internal/scout/advise/advise.go +++ b/internal/scout/advise/advise.go @@ -12,10 +12,9 @@ import ( type Option = func(config *scout.Config) const ( - OVER_100 = "\t%s %s: Your %s usage is over 100%% (%.2f%%). Add more %s." - OVER_80 = "\t%s %s: Your %s usage is over 80%% (%.2f%%). Consider raising limits." - OVER_40 = "\t%s %s: Your %s usage is under 80%% (%.2f%%). Keep %s allocation the same." - UNDER_40 = "\t%s %s: Your %s usage is under 40%% (%.2f%%). Consider lowering limits." + UNDER_PROVISIONED = "%s %s: %s is under-provisioned (%.2f%% usage). Add resources." + WELL_PROVISIONED = "%s %s: %s is well-provisioned (%.2f%% usage). No action needed." + OVER_PROVISIONED = "%s %s: %s is over-provisioned (%.2f%% usage). Trim resources." ) func WithNamespace(namespace string) Option { @@ -36,38 +35,37 @@ func WithOutput(pathToFile string) Option { } } -func CheckUsage(usage float64, resourceType string, container string) string { - var message string +func WithWarnings(includeWarnings bool) Option { + return func(config *scout.Config) { + config.Warnings = includeWarnings + } +} + +func CheckUsage(usage float64, resourceType string, container string) scout.Advice { + var advice scout.Advice switch { - case usage >= 100: - message = fmt.Sprintf( - OVER_100, + case usage >= 80: + advice.Kind = scout.DANGER + advice.Msg = fmt.Sprintf( + UNDER_PROVISIONED, scout.FlashingLightEmoji, container, resourceType, usage, - resourceType, ) - case usage >= 80 && usage < 100: - message = fmt.Sprintf( - OVER_80, - scout.WarningSign, - container, - resourceType, - usage, - ) - case usage >= 40 && usage < 80: - message = fmt.Sprintf( - OVER_40, + case usage >= 20 && usage < 80: + advice.Kind = scout.HEALTHY + advice.Msg = fmt.Sprintf( + WELL_PROVISIONED, scout.SuccessEmoji, container, resourceType, usage, - resourceType, ) default: - message = fmt.Sprintf( - UNDER_40, + advice.Kind = scout.WARNING + advice.Msg = fmt.Sprintf( + OVER_PROVISIONED, scout.WarningSign, container, resourceType, @@ -75,11 +73,11 @@ func CheckUsage(usage float64, resourceType string, container string) string { ) } - return message + return advice } // outputToFile writes resource allocation advice for a Kubernetes pod to a file. -func OutputToFile(ctx context.Context, cfg *scout.Config, name string, advice []string) error { +func OutputToFile(ctx context.Context, cfg *scout.Config, name string, advice []scout.Advice) error { file, err := os.OpenFile(cfg.Output, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) if err != nil { return errors.Wrap(err, "failed to open file") @@ -90,8 +88,8 @@ func OutputToFile(ctx context.Context, cfg *scout.Config, name string, advice [] return errors.Wrap(err, "failed to write service name to file") } - for _, msg := range advice { - if _, err := fmt.Fprintf(file, "%s\n", msg); err != nil { + for _, adv := range advice { + if _, err := fmt.Fprintf(file, "%s\n", adv.Msg); err != nil { return errors.Wrap(err, "failed to write container advice to file") } } diff --git a/internal/scout/advise/advise_test.go b/internal/scout/advise/advise_test.go index 9d5a7a0196..c93696c20f 100644 --- a/internal/scout/advise/advise_test.go +++ b/internal/scout/advise/advise_test.go @@ -16,35 +16,47 @@ func TestCheckUsage(t *testing.T) { usage float64 resourceType string container string - want string + want scout.Advice }{ { name: "should return correct message for usage over 100", usage: 110, resourceType: "cpu", container: "gitserver-0", - want: "\t🚨 gitserver-0: Your cpu usage is over 100% (110.00%). Add more cpu.", + want: scout.Advice{ + Kind: scout.DANGER, + Msg: "🚨 gitserver-0: cpu is under-provisioned (110.00% usage). Add resources.", + }, }, { name: "should return correct message for usage over 80 and under 100", usage: 87, resourceType: "memory", container: "gitserver-0", - want: "\t⚠️ gitserver-0: Your memory usage is over 80% (87.00%). Consider raising limits.", + want: scout.Advice{ + Kind: scout.DANGER, + Msg: "🚨 gitserver-0: memory is under-provisioned (87.00% usage). Add resources.", + }, }, { name: "should return correct message for usage over 40 and under 80", usage: 63.4, resourceType: "memory", container: "gitserver-0", - want: "\t✅ gitserver-0: Your memory usage is under 80% (63.40%). Keep memory allocation the same.", + want: scout.Advice{ + Kind: scout.HEALTHY, + Msg: "✅ gitserver-0: memory is well-provisioned (63.40% usage). No action needed.", + }, }, { name: "should return correct message for usage under 40", - usage: 22.33, + usage: 12.33, resourceType: "memory", container: "gitserver-0", - want: "\t⚠️ gitserver-0: Your memory usage is under 40% (22.33%). Consider lowering limits.", + want: scout.Advice{ + Kind: scout.WARNING, + Msg: "⚠️ gitserver-0: memory is over-provisioned (12.33% usage). Trim resources.", + }, }, } @@ -65,9 +77,15 @@ func TestOutputToFile(t *testing.T) { Output: os.TempDir() + string(os.PathSeparator) + "test.txt", } name := "gitserver-0" - advice := []string{ - "Add more CPU", - "Add more memory", + advice := []scout.Advice{ + { + Kind: scout.WARNING, + Msg: "Add more CPU", + }, + { + Kind: scout.WARNING, + Msg: "Add more memory", + }, } err := OutputToFile(context.Background(), cfg, name, advice) @@ -82,13 +100,14 @@ func TestOutputToFile(t *testing.T) { want string }{ {1, "- gitserver-0"}, - {2, "Add more CPU"}, - {3, "Add more memory"}, + {2, advice[0].Msg}, + {3, advice[1].Msg}, } for _, tc := range cases { tc := tc - if lines[tc.lineNum-1] != tc.want { + got := lines[tc.lineNum-1] + if got != tc.want { t.Errorf("Expected %q, got %q", tc.want, lines[tc.lineNum-1]) } } diff --git a/internal/scout/advise/k8s.go b/internal/scout/advise/k8s.go index e95e887b9f..4226762730 100644 --- a/internal/scout/advise/k8s.go +++ b/internal/scout/advise/k8s.go @@ -3,6 +3,7 @@ package advise import ( "context" "fmt" + "time" "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/scout" @@ -24,6 +25,7 @@ func K8s( Namespace: "default", Pod: "", Output: "", + Warnings: false, RestConfig: restConfig, K8sClient: k8sClient, MetricsClient: metricsClient, @@ -51,6 +53,10 @@ func K8s( return nil } + if cfg.Output != "" { + fmt.Printf("writing to %s. This can take a few minutes...", cfg.Output) + } + for _, pod := range pods { err = Advise(ctx, cfg, pod) if err != nil { @@ -67,29 +73,42 @@ func K8s( // of a resource is needed. Advice is generated and either printed to the console // or output to a file depending on the cfg.Output field. func Advise(ctx context.Context, cfg *scout.Config, pod v1.Pod) error { - var advice []string + var advice []scout.Advice usageMetrics, err := getUsageMetrics(ctx, cfg, pod) if err != nil { return errors.Wrap(err, "could not get usage metrics") } - for _, metrics := range usageMetrics { cpuAdvice := CheckUsage(metrics.CpuUsage, "CPU", metrics.ContainerName) - advice = append(advice, cpuAdvice) + if cfg.Warnings { + advice = append(advice, cpuAdvice) + } else if !cfg.Warnings && cpuAdvice.Kind != scout.WARNING { + advice = append(advice, cpuAdvice) + } memoryAdvice := CheckUsage(metrics.MemoryUsage, "memory", metrics.ContainerName) - advice = append(advice, memoryAdvice) + if cfg.Warnings { + advice = append(advice, memoryAdvice) + } else if !cfg.Warnings && memoryAdvice.Kind != scout.WARNING { + advice = append(advice, memoryAdvice) + } if metrics.Storage != nil { storageAdvice := CheckUsage(metrics.StorageUsage, "storage", metrics.ContainerName) - advice = append(advice, storageAdvice) + if cfg.Warnings { + advice = append(advice, storageAdvice) + } else if !cfg.Warnings && storageAdvice.Kind != scout.WARNING { + advice = append(advice, storageAdvice) + } } if cfg.Output != "" { OutputToFile(ctx, cfg, pod.Name, advice) } else { - for _, msg := range advice { - fmt.Println(msg) + fmt.Printf("%s %s: advising...\n", scout.EmojiFingerPointRight, pod.Name) + time.Sleep(time.Millisecond * 300) + for _, adv := range advice { + fmt.Printf("\t%s\n", adv.Msg) } } } diff --git a/internal/scout/constants.go b/internal/scout/constants.go index 4153df9766..3549ceabd6 100644 --- a/internal/scout/constants.go +++ b/internal/scout/constants.go @@ -6,4 +6,7 @@ const ( FlashingLightEmoji = "🚨" SuccessEmoji = "✅" WarningSign = "⚠️ " // why does this need an extra space to align?!?! + HEALTHY = "HEALTHY" + WARNING = "WARNING" + DANGER = "DANGER" ) diff --git a/internal/scout/types.go b/internal/scout/types.go index 9703fac20c..09bf11d2c9 100644 --- a/internal/scout/types.go +++ b/internal/scout/types.go @@ -11,6 +11,7 @@ type Config struct { Namespace string Pod string Output string + Warnings bool RestConfig *rest.Config K8sClient *kubernetes.Clientset MetricsClient *metricsv.Clientset @@ -36,3 +37,8 @@ type UsageStats struct { MemoryUsage float64 StorageUsage float64 } + +type Advice struct { + Kind string + Msg string +} From ec92b2ae3797c6a8707fff8b3ca5a0f283fb9365 Mon Sep 17 00:00:00 2001 From: coury-clark Date: Wed, 21 Jun 2023 10:49:43 -0700 Subject: [PATCH 346/647] reference docker user from environment (#1003) --- .github/workflows/docker.yml | 2 +- .github/workflows/goreleaser.yml | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index a729e36a94..3e5462220a 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -31,4 +31,4 @@ jobs: - run: ./docker/batch-change-volume-workspace/push.py -d ./docker/batch-change-volume-workspace/Dockerfile -i sourcegraph/src-batch-change-volume-workspace -p linux/amd64,linux/arm64,linux/386 --readme ./docker/batch-change-volume-workspace/README.md env: DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }} - DOCKER_USERNAME: sourcegraphci + DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }} diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index dfa7dd7aba..d0aa004d7b 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -181,9 +181,10 @@ jobs: - run: go get -d -t ./... - run: go test -i ./... - run: go test -race -v ./... - - run: echo "${DOCKER_PASSWORD}" | docker login -u=sourcegraphci --password-stdin + - run: echo "${DOCKER_PASSWORD}" | docker login -u=$DOCKER_USERNAME --password-stdin env: DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }} + DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }} - name: Run GoReleaser uses: goreleaser/goreleaser-action@v2 with: From 9449056c540f2f3d91add155f0c6b23a1a47230a Mon Sep 17 00:00:00 2001 From: coury-clark Date: Wed, 21 Jun 2023 11:24:17 -0700 Subject: [PATCH 347/647] use --clean instead of --rm-dist in goreleaser (#1004) --- .github/workflows/goreleaser.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index d0aa004d7b..faa7c52534 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -194,7 +194,7 @@ jobs: # we want to update the main (unversioned) Homebrew formula. For releasing a # patch on an older version, we want to publish a new versioned formula and # leave the main formula untouched. - args: release --rm-dist --config=${{ env.config_file }} + args: release --clean --config=${{ env.config_file }} env: # Use separate access token, because we need a scope:repo token to publish the brew formula. GITHUB_TOKEN: ${{ secrets.GH_PAT }} From 7128a287b4f76079d8c98edddfecf6042a0837e3 Mon Sep 17 00:00:00 2001 From: coury-clark Date: Wed, 21 Jun 2023 12:57:15 -0700 Subject: [PATCH 348/647] remove go get from releaser (#1005) --- .github/workflows/goreleaser.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index faa7c52534..793c7402a7 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -178,7 +178,6 @@ jobs: uses: actions/setup-go@v3 with: go-version: 1.19 - - run: go get -d -t ./... - run: go test -i ./... - run: go test -race -v ./... - run: echo "${DOCKER_PASSWORD}" | docker login -u=$DOCKER_USERNAME --password-stdin From ef0516b63046e9fe1cde67dfc35a30fd713d368b Mon Sep 17 00:00:00 2001 From: Thorsten Ball Date: Thu, 13 Jul 2023 11:24:56 +0200 Subject: [PATCH 349/647] help text: remove 'upload' command that does not exist (#1006) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit There is no `src upload` command. So let's remove it from the help text. Test Plan: ``` φ go run ./cmd/src upload src: unknown subcommand "upload" Run 'src help' for usage. exit status 1 ``` --- cmd/src/main.go | 1 - 1 file changed, 1 deletion(-) diff --git a/cmd/src/main.go b/cmd/src/main.go index 269f20b424..b9b748934c 100644 --- a/cmd/src/main.go +++ b/cmd/src/main.go @@ -45,7 +45,6 @@ The commands are: repos,repo manages repositories search search for results on Sourcegraph serve-git serves your local git repositories over HTTP for Sourcegraph to pull - upload upload an index to a Sourcegraph instance users,user manages users codeowners manages code ownership information version display and compare the src-cli version against the recommended version for your instance From 31f7c451a8c3c043aa553a18a642c177af936e0c Mon Sep 17 00:00:00 2001 From: Joe Chen Date: Fri, 14 Jul 2023 11:57:47 -0400 Subject: [PATCH 350/647] changelog: cut sourcegraph@5.1.0 (#1002) --- CHANGELOG.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index ab09244f7b..632ab214dd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,16 @@ All notable changes to `src-cli` are documented in this file. ## Unreleased +### Added + +### Changed + +### Fixed + +### Removed + +## 5.1.0 + ### Added - `src validate install` can check executor connections [#974](https://github.com/sourcegraph/src-cli/pull/974) - `src validate install` can send test SMTP message [#973](https://github.com/sourcegraph/src-cli/pull/973) From 12b8e239b95fc20980fd6c73ec0b45ffb3147aa9 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Tue, 18 Jul 2023 15:56:18 +0200 Subject: [PATCH 351/647] "update pr-auditor workflow" (#1007) --- .github/workflows/pr-auditor.yml | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/.github/workflows/pr-auditor.yml b/.github/workflows/pr-auditor.yml index 5c6ba2e0a4..bdc06f3bbf 100644 --- a/.github/workflows/pr-auditor.yml +++ b/.github/workflows/pr-auditor.yml @@ -9,12 +9,13 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - with: { repository: 'sourcegraph/sourcegraph' } - - uses: actions/setup-go@v2 - with: { go-version: '1.19' } + with: + repository: 'sourcegraph/pr-auditor' + - uses: actions/setup-go@v4 + with: { go-version: '1.20' } - - run: ./dev/pr-auditor/check-pr.sh + - run: './check-pr.sh' env: GITHUB_EVENT_PATH: ${{ env.GITHUB_EVENT_PATH }} - GITHUB_TOKEN: ${{ secrets.CODENOTIFY_GITHUB_TOKEN }} + GITHUB_TOKEN: ${{ github.token }} GITHUB_RUN_URL: https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }} From 35689b478cdf29d241c4de016dd4cd0ec79efe98 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Wed, 26 Jul 2023 13:41:59 +0200 Subject: [PATCH 352/647] go-releaser: upgrade workflow (#1013) * upgrade workflow * user repository instead of tap --- .github/workflows/goreleaser-check.yml | 7 ++++--- .goreleaser.yml | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/.github/workflows/goreleaser-check.yml b/.github/workflows/goreleaser-check.yml index 07801fd96f..0a15a41611 100644 --- a/.github/workflows/goreleaser-check.yml +++ b/.github/workflows/goreleaser-check.yml @@ -1,7 +1,8 @@ name: GoReleaser check on: - - push + push: + workflow_dispatch: jobs: goreleaser: @@ -15,9 +16,9 @@ jobs: - name: Set up Go uses: actions/setup-go@v3 with: - go-version: 1.19 + go-version: 1.20 - name: Check GoReleaser config - uses: goreleaser/goreleaser-action@v2 + uses: goreleaser/goreleaser-action@v4 with: version: latest args: check diff --git a/.goreleaser.yml b/.goreleaser.yml index a0ca261922..e452ee7d01 100644 --- a/.goreleaser.yml +++ b/.goreleaser.yml @@ -36,7 +36,7 @@ brews: name: src-cli homepage: "https://sourcegraph.com/" description: "Sourcegraph CLI" - tap: + repository: owner: sourcegraph name: homebrew-src-cli # Folder inside the repository to put the formula. From c0e74d1d9a8a384fc5367e02744076abe057be96 Mon Sep 17 00:00:00 2001 From: Noah S-C Date: Wed, 26 Jul 2023 13:36:24 +0100 Subject: [PATCH 353/647] codeintel: handle -insecure-skip-verify in SCIP endpoint detection (#1012) * codeintel: handle -insecure-skip-verify in SCIP endpoint detection * changelog entry --- CHANGELOG.md | 2 ++ cmd/src/code_intel_upload.go | 7 +------ cmd/src/code_intel_upload_flags.go | 29 +++++++++++++++++------------ 3 files changed, 20 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 632ab214dd..0bd9df1260 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,8 @@ All notable changes to `src-cli` are documented in this file. ### Fixed +- Fixed `src code-intel upload` not respecting `-insecure-skip-verify`. [#1012](https://github.com/sourcegraph/src-cli/pull/1012) + ### Removed ## 5.1.0 diff --git a/cmd/src/code_intel_upload.go b/cmd/src/code_intel_upload.go index fe361c3e02..b6b52380ef 100644 --- a/cmd/src/code_intel_upload.go +++ b/cmd/src/code_intel_upload.go @@ -71,12 +71,7 @@ Examples: func handleCodeIntelUpload(args []string) error { ctx := context.Background() - isSCIPAvailable, err := isSCIPAvailable() - if err != nil { - return err - } - - out, err := parseAndValidateCodeIntelUploadFlags(args, isSCIPAvailable) + out, isSCIPAvailable, err := parseAndValidateCodeIntelUploadFlags(args) if !codeintelUploadFlags.json { if out != nil { printInferredArguments(out) diff --git a/cmd/src/code_intel_upload_flags.go b/cmd/src/code_intel_upload_flags.go index cd19fbce32..00c04c2f59 100644 --- a/cmd/src/code_intel_upload_flags.go +++ b/cmd/src/code_intel_upload_flags.go @@ -100,9 +100,9 @@ func init() { // // On success, the global codeintelUploadFlags object will be populated with valid values. An // error is returned on failure. -func parseAndValidateCodeIntelUploadFlags(args []string, isSCIPAvailable bool) (*output.Output, error) { +func parseAndValidateCodeIntelUploadFlags(args []string) (*output.Output, bool, error) { if err := codeintelUploadFlagSet.Parse(args); err != nil { - return nil, err + return nil, false, err } out := codeintelUploadOutput() @@ -120,13 +120,13 @@ func parseAndValidateCodeIntelUploadFlags(args []string, isSCIPAvailable bool) ( // and maybe we'll use some in the future codeintelUploadFlags.apiFlags = api.NewFlags(apiClientFlagSet) if err := apiClientFlagSet.Parse(insecureSkipVerifyFlag); err != nil { - return nil, err + return nil, false, err } if !isFlagSet(codeintelUploadFlagSet, "file") { defaultFile, err := inferDefaultFile() if err != nil { - return nil, err + return nil, false, err } codeintelUploadFlags.file = defaultFile } @@ -134,37 +134,42 @@ func parseAndValidateCodeIntelUploadFlags(args []string, isSCIPAvailable bool) ( // Check to see if input file exists if _, err := os.Stat(codeintelUploadFlags.file); os.IsNotExist(err) { if !isFlagSet(codeintelUploadFlagSet, "file") { - return nil, formatInferenceError(argumentInferenceError{"file", err}) + return nil, false, formatInferenceError(argumentInferenceError{"file", err}) } - return nil, errors.Newf("file %q does not exist", codeintelUploadFlags.file) + return nil, false, errors.Newf("file %q does not exist", codeintelUploadFlags.file) + } + + isSCIPAvailable, err := isSCIPAvailable() + if err != nil { + return nil, false, err } if !isSCIPAvailable { if err := handleSCIP(out); err != nil { - return nil, err + return nil, false, err } } else { if err := handleLSIF(out); err != nil { - return nil, err + return nil, false, err } } // Check for new file existence after transformation if _, err := os.Stat(codeintelUploadFlags.file); os.IsNotExist(err) { - return nil, errors.Newf("file %q does not exist", codeintelUploadFlags.file) + return nil, false, errors.Newf("file %q does not exist", codeintelUploadFlags.file) } // Infer the remaining default arguments (may require reading from new file) if inferenceErrors := inferMissingCodeIntelUploadFlags(); len(inferenceErrors) > 0 { - return nil, formatInferenceError(inferenceErrors[0]) + return nil, false, formatInferenceError(inferenceErrors[0]) } if err := validateCodeIntelUploadFlags(); err != nil { - return nil, err + return nil, false, err } - return out, nil + return out, isSCIPAvailable, nil } // codeintelUploadOutput returns an output object that should be used to print the progres From b388f85aaf217442dc04507830212355aabaf3ae Mon Sep 17 00:00:00 2001 From: Robert Lin Date: Wed, 2 Aug 2023 08:33:15 -0700 Subject: [PATCH 354/647] instancehealth: permissionSyncJobs -> permissionsSyncJobs (#1010) * instancehealth: permissionSyncJobs -> permissionsSyncJobs * fixup --- CHANGELOG.md | 1 + internal/instancehealth/checks.go | 2 +- internal/instancehealth/checks_test.go | 6 +++--- internal/instancehealth/summary.go | 4 ++-- 4 files changed, 7 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0bd9df1260..c65b13ee49 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,7 @@ All notable changes to `src-cli` are documented in this file. ### Fixed +- Fixed `src snapshot validate`. [#1010](https://github.com/sourcegraph/src-cli/pull/1010) - Fixed `src code-intel upload` not respecting `-insecure-skip-verify`. [#1012](https://github.com/sourcegraph/src-cli/pull/1012) ### Removed diff --git a/internal/instancehealth/checks.go b/internal/instancehealth/checks.go index 968628ea87..b943e52dec 100644 --- a/internal/instancehealth/checks.go +++ b/internal/instancehealth/checks.go @@ -134,7 +134,7 @@ func checkPermissionsSyncing( var syncCount int var syncErrors []string var seenProviders = make(map[string]map[string]string) // provider : state : message - for _, sync := range instanceHealth.PermissionSyncJobs.Nodes { + for _, sync := range instanceHealth.PermissionsSyncJobs.Nodes { if sync.FinishedAt.Before(time.Now().Add(-since)) { continue } diff --git a/internal/instancehealth/checks_test.go b/internal/instancehealth/checks_test.go index e57223487c..a5df185507 100644 --- a/internal/instancehealth/checks_test.go +++ b/internal/instancehealth/checks_test.go @@ -24,7 +24,7 @@ func TestCheckPermissionsSyncing(t *testing.T) { }{{ name: "no jobs", instanceHealth: Indicators{ - PermissionSyncJobs: struct{ Nodes []permissionSyncJob }{ + PermissionsSyncJobs: struct{ Nodes []permissionSyncJob }{ Nodes: nil, }, }, @@ -33,7 +33,7 @@ func TestCheckPermissionsSyncing(t *testing.T) { }, { name: "healthy", instanceHealth: Indicators{ - PermissionSyncJobs: struct{ Nodes []permissionSyncJob }{ + PermissionsSyncJobs: struct{ Nodes []permissionSyncJob }{ Nodes: []permissionSyncJob{{ FinishedAt: time.Now(), State: "SUCCESS", @@ -50,7 +50,7 @@ func TestCheckPermissionsSyncing(t *testing.T) { }, { name: "unhealthy", instanceHealth: Indicators{ - PermissionSyncJobs: struct{ Nodes []permissionSyncJob }{ + PermissionsSyncJobs: struct{ Nodes []permissionSyncJob }{ Nodes: []permissionSyncJob{{ FinishedAt: time.Now(), State: "ERROR", diff --git a/internal/instancehealth/summary.go b/internal/instancehealth/summary.go index 6996e08659..e556278f07 100644 --- a/internal/instancehealth/summary.go +++ b/internal/instancehealth/summary.go @@ -40,7 +40,7 @@ type Indicators struct { } } } - PermissionSyncJobs struct { + PermissionsSyncJobs struct { Nodes []permissionSyncJob } } @@ -95,7 +95,7 @@ func GetIndicators(ctx context.Context, client api.Client) (*Indicators, error) } } - permissionSyncJobs(first:500) { + permissionsSyncJobs(first:500) { nodes { state finishedAt From 7c5da8ea985dd9397ddfb1cc1117ecb08452c6ec Mon Sep 17 00:00:00 2001 From: Randell Callahan Date: Mon, 7 Aug 2023 14:34:33 -0600 Subject: [PATCH 355/647] batches: File upload error handling (#1015) * Add the filename to the error to help determine which file is erroring * Shadow the error to prevent the error being returned later on --- cmd/src/batch_common.go | 2 +- internal/batches/service/remote.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index e16aa38fcb..57b248cf06 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -535,7 +535,7 @@ func executeBatchSpec(ctx context.Context, opts executeBatchSpecOpts) (err error } if hasWorkspaceFiles { execUI.UploadingWorkspaceFiles() - if err = svc.UploadBatchSpecWorkspaceFiles(ctx, batchSpecDir, string(id), batchSpec.Steps); err != nil { + if err := svc.UploadBatchSpecWorkspaceFiles(ctx, batchSpecDir, string(id), batchSpec.Steps); err != nil { // Since failing to upload workspace files should not stop processing, just warn execUI.UploadingWorkspaceFilesWarning(errors.Wrap(err, "uploading workspace files")) } else { diff --git a/internal/batches/service/remote.go b/internal/batches/service/remote.go index 1e57701f7a..8db0e09e45 100644 --- a/internal/batches/service/remote.go +++ b/internal/batches/service/remote.go @@ -213,7 +213,7 @@ func createFormFile(w *multipart.Writer, workingDir string, mountPath string) er return err } if fileStat.Size() > maxFileSize { - return errors.New("file exceeds limit of 10MB") + return errors.Newf("file %q exceeds limit of 10MB", mountPath) } filePath, fileName := filepath.Split(mountPath) From b9e783af438b060a13cf8400078df15bb8626fbd Mon Sep 17 00:00:00 2001 From: Bolaji Olajide <25608335+BolajiOlajide@users.noreply.github.com> Date: Fri, 11 Aug 2023 18:02:51 +0100 Subject: [PATCH 356/647] changelog update 5.1.1. (#1017) --- CHANGELOG.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c65b13ee49..9d605e73fd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,11 +17,15 @@ All notable changes to `src-cli` are documented in this file. ### Fixed +### Removed + +## 5.1.1 + +### Fixed + - Fixed `src snapshot validate`. [#1010](https://github.com/sourcegraph/src-cli/pull/1010) - Fixed `src code-intel upload` not respecting `-insecure-skip-verify`. [#1012](https://github.com/sourcegraph/src-cli/pull/1012) -### Removed - ## 5.1.0 ### Added From 14059616f9abbb49a281ebf3e2ac65ff7f996930 Mon Sep 17 00:00:00 2001 From: Jason Hawk Harris Date: Thu, 17 Aug 2023 12:35:37 -0500 Subject: [PATCH 357/647] switch to attoto/clipboard package (#1022) * switch to attoto/clipboard package * add changelog entry --- CHANGELOG.md | 2 ++ go.mod | 8 +------- go.sum | 26 +------------------------- internal/scout/style/resource_table.go | 4 ++-- internal/scout/style/usage_table.go | 4 ++-- 5 files changed, 8 insertions(+), 36 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9d605e73fd..f755bda277 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,8 @@ All notable changes to `src-cli` are documented in this file. ### Changed +- Changed to attoto/clipboard library from x11 clipboard libary + ### Fixed ### Removed diff --git a/go.mod b/go.mod index c617b7e784..08f6cfd845 100644 --- a/go.mod +++ b/go.mod @@ -4,6 +4,7 @@ go 1.18 require ( cloud.google.com/go/storage v1.28.0 + github.com/atotto/clipboard v0.1.4 github.com/aws/aws-sdk-go-v2/config v1.18.13 github.com/aws/aws-sdk-go-v2/service/ec2 v1.86.0 github.com/aws/aws-sdk-go-v2/service/eks v1.27.3 @@ -31,7 +32,6 @@ require ( github.com/sourcegraph/scip v0.2.4-0.20221213205653-aa0e511dcfef github.com/sourcegraph/sourcegraph/lib v0.0.0-20230316093010-26299ec302d0 github.com/stretchr/testify v1.8.1 - golang.design/x/clipboard v0.7.0 golang.org/x/net v0.8.0 golang.org/x/sync v0.1.0 google.golang.org/api v0.110.0 @@ -44,12 +44,6 @@ require ( k8s.io/metrics v0.27.1 ) -require ( - golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6 // indirect - golang.org/x/image v0.6.0 // indirect - golang.org/x/mobile v0.0.0-20230301163155-e0f57694e12c // indirect -) - require ( cloud.google.com/go v0.107.0 // indirect cloud.google.com/go/compute v1.18.0 // indirect diff --git a/go.sum b/go.sum index e6721f4ea6..496eee800c 100644 --- a/go.sum +++ b/go.sum @@ -10,12 +10,10 @@ cloud.google.com/go/iam v0.12.0/go.mod h1:knyHGviacl11zrtZUoDuYpDgLjvr28sLQaG0YB cloud.google.com/go/longrunning v0.3.0 h1:NjljC+FYPV3uh5/OwWT6pVU+doBqMg2x/rZlE+CamDs= cloud.google.com/go/storage v1.28.0 h1:DLrIZ6xkeZX6K70fU/boWx5INJumt6f+nwwWSHXzzGY= cloud.google.com/go/storage v1.28.0/go.mod h1:qlgZML35PXA3zoEnIkiPLY4/TOkUleufRlu6qmcf7sI= -dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= github.com/AndreasBriese/bbloom v0.0.0-20190306092124-e2d15f34fcf9/go.mod h1:bOvUY6CB00SOBii9/FifXqc0awNKxLFCL/+pkDPuyl8= github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 h1:UQHMgLO+TxOElx5B5HZ4hJQsoJ/PvUvKRhJHDQXO8P8= github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= -github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/CloudyKit/fastprinter v0.0.0-20170127035650-74b38d55f37a/go.mod h1:EFZQ978U7x8IRnstaskI3IysnWY5Ao3QgZUKOXlsAdw= github.com/CloudyKit/fastprinter v0.0.0-20200109182630-33d98a066a53/go.mod h1:+3IMCy2vIlbG1XG/0ggNQv0SvxCAIpPM5b1nCz56Xno= github.com/CloudyKit/jet v2.1.3-0.20180809161101-62edd43e4f88+incompatible/go.mod h1:HPYO+50pSWkPoj9Q/eq0aRGByCL6ScRlUmiEX5Zgm+w= @@ -34,6 +32,7 @@ github.com/alecthomas/chroma v0.10.0 h1:7XDcGkCQopCNKjZHfYrNLraA+M7e0fMiJ/Mfikbf github.com/alecthomas/chroma v0.10.0/go.mod h1:jtJATyUxlIORhUOFNA9NZDWGAQ8wpxQQqNSB4rjA/1s= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio= +github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4= github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI= github.com/aws/aws-sdk-go-v2 v1.17.4/go.mod h1:uzbQtefpm44goOPmdKyAlXSNcwlRgF3ePWVW6EtJvvw= github.com/aws/aws-sdk-go-v2 v1.17.5 h1:TzCUW1Nq4H8Xscph5M/skINUitxM5UBAyvm2s7XBzL4= @@ -162,7 +161,6 @@ github.com/gin-gonic/gin v1.4.0/go.mod h1:OW2EZn3DO8Ln9oIKOvM++LBO+5UPHJJDH72/q/ github.com/go-check/check v0.0.0-20180628173108-788fd7840127/go.mod h1:9ES+weclKsC9YodN5RgxqK/VD9HM9JsCSh7rNhMZE98= github.com/go-errors/errors v1.0.1/go.mod h1:f4zRHt4oKfwPJE5k8C9vpYG+aDHdBFUsgrm6/TyX73Q= github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA= -github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= github.com/go-logr/logr v1.2.0/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.2.3 h1:2DntVwHkVopvECVRSlL5PSo9eG+cAkDCuckLubN+rq0= github.com/go-logr/logr v1.2.3/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= @@ -560,8 +558,6 @@ go.uber.org/multierr v1.9.0 h1:7fIwc/ZtS0q++VgcfqFDxSBZVv/Xo49/SYnDFupUwlI= go.uber.org/multierr v1.9.0/go.mod h1:X2jQV1h+kxSjClGpnseKVIxpmcjrj7MNnI0bnlfKTVQ= go.uber.org/zap v1.24.0 h1:FiJd5l1UOLj0wCgbSE0rwwXHzEdAZS6hiiSnxJN/D60= go.uber.org/zap v1.24.0/go.mod h1:2kMP+WWQ8aoFoedH3T2sq6iJ2yDWpHbP0f6MQbS9Gkg= -golang.design/x/clipboard v0.7.0 h1:4Je8M/ys9AJumVnl8m+rZnIvstSnYj1fvzqYrU3TXvo= -golang.design/x/clipboard v0.7.0/go.mod h1:PQIvqYO9GP29yINEfsEn5zSQKAz3UgXmZKzDA6dnq2E= golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= @@ -573,22 +569,11 @@ golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5y golang.org/x/crypto v0.3.0 h1:a06MkbcxBrEFc0w0QIZWXrH/9cCX6KJyWbBOIwAn+7A= golang.org/x/crypto v0.3.0/go.mod h1:hebNnKkNXi2UzZN1eVRvBB7co0a+JxK6XbPiWVs/3J4= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= -golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= -golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6 h1:QE6XYQK6naiK1EPAe1g/ILLxN5RBoH5xkJk3CqlMI/Y= -golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= -golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= -golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= -golang.org/x/image v0.6.0 h1:bR8b5okrPI3g/gyZakLZHeWxAR8Dn5CyxXv1hLH5g/4= -golang.org/x/image v0.6.0/go.mod h1:MXLdDR43H7cDJq5GEGXEVeeNhPgi+YYEQ2pC1byI1x0= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/lint v0.0.0-20210508222113-6edffad5e616/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= -golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= -golang.org/x/mobile v0.0.0-20230301163155-e0f57694e12c h1:Gk61ECugwEHL6IiyyNLXNzmu8XslmRP2dS0xjIYhbb4= -golang.org/x/mobile v0.0.0-20230301163155-e0f57694e12c/go.mod h1:aAjjkJNdrh3PMckS4B10TGS2nag27cbKR1y2BpUxsiY= golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= -golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= @@ -596,7 +581,6 @@ golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.7.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.9.0 h1:KENHtAZL2y3NLMYZeHY9DW8HW8V+kQyJsY/V9JlKvCs= golang.org/x/mod v0.9.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -623,7 +607,6 @@ golang.org/x/net v0.0.0-20210614182718-04defd469f4e/go.mod h1:9nx3DQGgdP8bBQD5qx golang.org/x/net v0.0.0-20211008194852-3b03d305991f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.3.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE= -golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.8.0 h1:Zrh2ngAOFYneWTAIAPethzeaQLuHwhuBkuV6ZiRnUaQ= golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= @@ -645,12 +628,10 @@ golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5h golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190626221950-04f50cda93cb/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -679,13 +660,11 @@ golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220829200755-d48e67d00261/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.3.0/go.mod h1:q750SLmJuPmVoN1blW3UFBPREJfb1KmY3vwxfr+nFDA= -golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= golang.org/x/term v0.6.0 h1:clScbb1cHjoCkyRbWwBEUZ5H/tIFu5TAXIqaZD0Gcjw= golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -695,7 +674,6 @@ golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.8.0 h1:57P1ETyNKtuIjB4SRd15iJxuhj8Gc416Y78H3qgMh68= golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/time v0.0.0-20201208040808-7e3f01d25324/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= @@ -712,7 +690,6 @@ golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3 golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200207183749-b753a1ba74fa/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200624163319-25775e59acb7/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20210101214203-2dba1e4ea05c/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= @@ -721,7 +698,6 @@ golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.4.0/go.mod h1:UE5sM2OK9E/d67R0ANs2xJizIymRP5gJU295PvKXxjQ= -golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/tools v0.7.0 h1:W4OVu8VVOaIO0yzWMNdepAulS7YfoS3Zabrm8DOXXU4= golang.org/x/tools v0.7.0/go.mod h1:4pg6aUX35JBAogB10C9AtvVL+qowtN4pT3CGSQex14s= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/internal/scout/style/resource_table.go b/internal/scout/style/resource_table.go index 218579e1a9..86f9482bb3 100644 --- a/internal/scout/style/resource_table.go +++ b/internal/scout/style/resource_table.go @@ -7,11 +7,11 @@ import ( "strings" "text/tabwriter" + "github.com/atotto/clipboard" "github.com/charmbracelet/bubbles/table" tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/lipgloss" "github.com/sourcegraph/sourcegraph/lib/errors" - "golang.design/x/clipboard" ) var resourceTableStyle = lipgloss.NewStyle(). @@ -147,7 +147,7 @@ func (m resourceTableModel) copyRowToClipboard(row table.Row) { containerInfo += fmt.Sprintf("%s: %s\n", header, row[i]) } - clipboard.Write(clipboard.FmtText, []byte(containerInfo)) + clipboard.WriteAll(containerInfo) } func ResourceTable(columns []table.Column, rows []table.Row) { diff --git a/internal/scout/style/usage_table.go b/internal/scout/style/usage_table.go index 1851e1081b..533cf6864e 100644 --- a/internal/scout/style/usage_table.go +++ b/internal/scout/style/usage_table.go @@ -7,11 +7,11 @@ import ( "strings" "text/tabwriter" + "github.com/atotto/clipboard" "github.com/charmbracelet/bubbles/table" tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/lipgloss" "github.com/sourcegraph/sourcegraph/lib/errors" - "golang.design/x/clipboard" ) var usageTableStyle = lipgloss.NewStyle(). @@ -149,7 +149,7 @@ func (m usageTableModel) copyRowToClipboard(row table.Row) { containerInfo += fmt.Sprintf("%s: %s\n", header, row[i]) } - clipboard.Write(clipboard.FmtText, []byte(containerInfo)) + clipboard.WriteAll(containerInfo) } func UsageTable(columns []table.Column, rows []table.Row) { From ee449a7168bc7aa08aba16f45ef0659b77825147 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20Miku=C5=A1?= Date: Mon, 21 Aug 2023 17:10:57 +0200 Subject: [PATCH 358/647] docker/info use format JSON (#1008) - use host CPU from Host property if available - this allows to use podman --- internal/batches/docker/info.go | 24 ++++++++++++++++-------- internal/batches/docker/info_test.go | 17 +++++++++++++---- 2 files changed, 29 insertions(+), 12 deletions(-) diff --git a/internal/batches/docker/info.go b/internal/batches/docker/info.go index a96397c943..994e406f8b 100644 --- a/internal/batches/docker/info.go +++ b/internal/batches/docker/info.go @@ -3,8 +3,7 @@ package docker import ( "bytes" "context" - "strconv" - + "encoding/json" "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/exec" @@ -35,6 +34,13 @@ func CurrentContext(ctx context.Context) (string, error) { return name, nil } +type Info struct { + Host struct { + CPUs int `json:"cpus"` + } `json:"host"` // Podman engine + NCPU int `json:"NCPU"` // Docker Engine +} + // NCPU returns the number of CPU cores available to Docker. func NCPU(ctx context.Context) (int, error) { dctx, cancel, err := withFastCommandContext(ctx) @@ -43,7 +49,7 @@ func NCPU(ctx context.Context) (int, error) { } defer cancel() - args := []string{"info", "--format", "{{ .NCPU }}"} + args := []string{"info", "--format", "{{ json .}}"} out, err := exec.CommandContext(dctx, "docker", args...).CombinedOutput() if errors.IsDeadlineExceeded(err) || errors.IsDeadlineExceeded(dctx.Err()) { return 0, newFastCommandTimeoutError(dctx, args...) @@ -51,10 +57,12 @@ func NCPU(ctx context.Context) (int, error) { return 0, err } - dcpu, err := strconv.Atoi(string(bytes.TrimSpace(out))) - if err != nil { - return 0, errors.Wrap(err, "parsing docker cpu count") + var info Info + if err := json.Unmarshal(out, &info); err != nil { + return 0, err } - - return dcpu, nil + if info.NCPU > 0 { + return info.NCPU, nil + } + return info.Host.CPUs, nil } diff --git a/internal/batches/docker/info_test.go b/internal/batches/docker/info_test.go index 76db6ae91d..7e674dd555 100644 --- a/internal/batches/docker/info_test.go +++ b/internal/batches/docker/info_test.go @@ -2,7 +2,9 @@ package docker import ( "context" + "encoding/json" "fmt" + "strconv" "testing" "time" @@ -88,7 +90,7 @@ func Test_NCPU(t *testing.T) { assert.Zero(t, ncpu) var terr *fastCommandTimeoutError assert.ErrorAs(t, err, &terr) - assert.Equal(t, []string{"info", "--format", "{{ .NCPU }}"}, terr.args) + assert.Equal(t, []string{"info", "--format", "{{ json .}}"}, terr.args) assert.Equal(t, fastCommandTimeoutDefault, terr.timeout) }) @@ -118,15 +120,22 @@ func Test_NCPU(t *testing.T) { } func infoSuccess(ncpu string) *expect.Expectation { + var b []byte + n, err := strconv.Atoi(ncpu) + if err == nil { + b, _ = json.Marshal(Info{NCPU: n}) + } else { + b = []byte(ncpu) + } return expect.NewLiteral( - expect.Behaviour{Stdout: []byte(fmt.Sprintf("%s\n", ncpu))}, - "docker", "info", "--format", "{{ .NCPU }}", + expect.Behaviour{Stdout: b}, + "docker", "info", "--format", "{{ json .}}", ) } func infoFailure() *expect.Expectation { return expect.NewLiteral( expect.Behaviour{ExitCode: 1}, - "docker", "info", "--format", "{{ .NCPU }}", + "docker", "info", "--format", "{{ json .}}", ) } From 77abad86e45b911cf034e35f71a1b7428eb20713 Mon Sep 17 00:00:00 2001 From: Thorsten Ball Date: Wed, 23 Aug 2023 09:48:35 +0200 Subject: [PATCH 359/647] README: fix PowerShell env var instructions (#1025) This fixes #1024. --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index a1c954a49c..4a1f744404 100644 --- a/README.md +++ b/README.md @@ -144,8 +144,8 @@ SRC_ENDPOINT=https://sourcegraph.example.com SRC_ACCESS_TOKEN=my-token src searc Type the following on your PowerShell terminal: ``` -$env.SRC_ENDPOINT = 'https://sourcegraph.example.com' -$env.SRC_ACCESS_TOKEN = 'my-token' +$env:SRC_ENDPOINT = 'https://sourcegraph.example.com' +$env:SRC_ACCESS_TOKEN = 'my-token' ``` Replace `my-token` and `https://sourcegraph.example.com` with the appropriate values for your account and instance. From 0ba39d426455b383058ba466f6097c7a3049690d Mon Sep 17 00:00:00 2001 From: Thorsten Ball Date: Wed, 23 Aug 2023 10:36:42 +0200 Subject: [PATCH 360/647] ci: fix goimports lint (#1026) See error here: https://github.com/sourcegraph/src-cli/actions/runs/5948515857/job/16132445754#step:4:21 --- internal/batches/docker/info.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/internal/batches/docker/info.go b/internal/batches/docker/info.go index 994e406f8b..75bdebbd01 100644 --- a/internal/batches/docker/info.go +++ b/internal/batches/docker/info.go @@ -4,9 +4,10 @@ import ( "bytes" "context" "encoding/json" - "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/exec" + + "github.com/sourcegraph/sourcegraph/lib/errors" ) // CurrentContext returns the name of the current Docker context (not to be From 84ffc3e1b8dac88c2b3b1841a795e5a571ca782b Mon Sep 17 00:00:00 2001 From: Joel Low Date: Wed, 23 Aug 2023 21:36:51 +0800 Subject: [PATCH 361/647] Clean up volumes if workspace preparation fails (#1021) --- internal/batches/workspace/volume_workspace.go | 16 +++++++++++++--- .../batches/workspace/volume_workspace_test.go | 12 ++++++++++++ 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/internal/batches/workspace/volume_workspace.go b/internal/batches/workspace/volume_workspace.go index 5cc8222a2f..b161090b77 100644 --- a/internal/batches/workspace/volume_workspace.go +++ b/internal/batches/workspace/volume_workspace.go @@ -30,16 +30,22 @@ type dockerVolumeWorkspaceCreator struct { var _ Creator = &dockerVolumeWorkspaceCreator{} -func (wc *dockerVolumeWorkspaceCreator) Create(ctx context.Context, repo *graphql.Repository, steps []batcheslib.Step, archive repozip.Archive) (Workspace, error) { +func (wc *dockerVolumeWorkspaceCreator) Create(ctx context.Context, repo *graphql.Repository, + steps []batcheslib.Step, archive repozip.Archive) (ws Workspace, err error) { volume, err := wc.createVolume(ctx) if err != nil { return nil, errors.Wrap(err, "creating Docker volume") } + defer func() { + if err != nil { + deleteVolume(ctx, volume) + } + }() + // Figure out the user that containers will be run as. ug := docker.UIDGID{} if len(steps) > 0 { - var err error img, err := wc.EnsureImage(ctx, steps[0].Container) if err != nil { return nil, err @@ -74,6 +80,10 @@ func (*dockerVolumeWorkspaceCreator) createVolume(ctx context.Context) (string, return string(bytes.TrimSpace(out)), nil } +func deleteVolume(ctx context.Context, volume string) error { + return exec.CommandContext(ctx, "docker", "volume", "rm", volume).Run() +} + func (*dockerVolumeWorkspaceCreator) prepareGitRepo(ctx context.Context, w *dockerVolumeWorkspace) error { script := `#!/bin/sh @@ -219,7 +229,7 @@ var _ Workspace = &dockerVolumeWorkspace{} func (w *dockerVolumeWorkspace) Close(ctx context.Context) error { // Cleanup here is easy: we just get rid of the Docker volume. - return exec.CommandContext(ctx, "docker", "volume", "rm", w.volume).Run() + return deleteVolume(ctx, w.volume) } func (w *dockerVolumeWorkspace) DockerRunOpts(ctx context.Context, target string) ([]string, error) { diff --git a/internal/batches/workspace/volume_workspace_test.go b/internal/batches/workspace/volume_workspace_test.go index 559d22aa67..9f6706741c 100644 --- a/internal/batches/workspace/volume_workspace_test.go +++ b/internal/batches/workspace/volume_workspace_test.go @@ -211,6 +211,10 @@ func TestVolumeWorkspaceCreator(t *testing.T) { DockerVolumeWorkspaceImage, "sh", "-c", "touch /work/*; chown -R 0:0 /work", ), + expect.NewGlob( + expect.Behaviour{ExitCode: 0}, + "docker", "volume", "rm", volumeID, + ), }, steps: []batcheslib.Step{ {}, @@ -253,6 +257,10 @@ func TestVolumeWorkspaceCreator(t *testing.T) { DockerVolumeWorkspaceImage, "sh", "/run.sh", ), + expect.NewGlob( + expect.Behaviour{ExitCode: 0}, + "docker", "volume", "rm", volumeID, + ), }, steps: []batcheslib.Step{ {}, @@ -286,6 +294,10 @@ func TestVolumeWorkspaceCreator(t *testing.T) { DockerVolumeWorkspaceImage, "sh", "-c", "unzip /tmp/zip; rm /work/*", ), + expect.NewGlob( + expect.Behaviour{ExitCode: 0}, + "docker", "volume", "rm", volumeID, + ), }, steps: []batcheslib.Step{ {}, From 4c4256830a97e9e8c11040d013b0efa65ca625d9 Mon Sep 17 00:00:00 2001 From: Bolaji Olajide <25608335+BolajiOlajide@users.noreply.github.com> Date: Thu, 24 Aug 2023 10:04:27 +0100 Subject: [PATCH 362/647] changelog update (#1027) --- CHANGELOG.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f755bda277..b818814464 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,10 +15,12 @@ All notable changes to `src-cli` are documented in this file. ### Changed -- Changed to attoto/clipboard library from x11 clipboard libary +- Replace `x11` clipboard library with `attoto/clipboard` to support more platforms. [#1022](https://github.com/sourcegraph/src-cli/pull/1022) ### Fixed +- The temporary docker volume created during workspace preparation is now cleaned up when failure occurs. [#1021](https://github.com/sourcegraph/src-cli/pull/1021). + ### Removed ## 5.1.1 From 511ebf8962ac8ff069cfde63719d4339ff347298 Mon Sep 17 00:00:00 2001 From: Bolaji Olajide <25608335+BolajiOlajide@users.noreply.github.com> Date: Thu, 24 Aug 2023 14:35:53 +0100 Subject: [PATCH 363/647] 5.1.2 changelog update (#1028) --- CHANGELOG.md | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b818814464..7a474da782 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,14 +15,20 @@ All notable changes to `src-cli` are documented in this file. ### Changed +### Fixed + +### Removed + +## 5.1.2 + +### Changed + - Replace `x11` clipboard library with `attoto/clipboard` to support more platforms. [#1022](https://github.com/sourcegraph/src-cli/pull/1022) ### Fixed - The temporary docker volume created during workspace preparation is now cleaned up when failure occurs. [#1021](https://github.com/sourcegraph/src-cli/pull/1021). -### Removed - ## 5.1.1 ### Fixed From c0d85ecd37a8ff9b02b4d190e559050fa159ae07 Mon Sep 17 00:00:00 2001 From: Noah S-C Date: Mon, 28 Aug 2023 22:32:51 +0100 Subject: [PATCH 364/647] codeintel: allow configuring max concurrency in uploads (#1023) * codeintel: allow configuring max concurrency in uploads * pin to main --- cmd/src/code_intel_upload.go | 1 + cmd/src/code_intel_upload_flags.go | 2 + go.mod | 106 +++--- go.sum | 523 ++++++++++++----------------- 4 files changed, 277 insertions(+), 355 deletions(-) diff --git a/cmd/src/code_intel_upload.go b/cmd/src/code_intel_upload.go index b6b52380ef..a3afd2dfe4 100644 --- a/cmd/src/code_intel_upload.go +++ b/cmd/src/code_intel_upload.go @@ -172,6 +172,7 @@ func codeintelUploadOptions(out *output.Output, isSCIPAvailable bool) upload.Upl RetryInterval: time.Second, Path: path, MaxPayloadSizeBytes: codeintelUploadFlags.maxPayloadSizeMb * 1000 * 1000, + MaxConcurrency: codeintelUploadFlags.maxConcurrency, GitHubToken: codeintelUploadFlags.gitHubToken, GitLabToken: codeintelUploadFlags.gitLabToken, }, diff --git a/cmd/src/code_intel_upload_flags.go b/cmd/src/code_intel_upload_flags.go index 00c04c2f59..2e76d8d445 100644 --- a/cmd/src/code_intel_upload_flags.go +++ b/cmd/src/code_intel_upload_flags.go @@ -36,6 +36,7 @@ var codeintelUploadFlags struct { // SourcegraphInstanceOptions uploadRoute string maxPayloadSizeMb int64 + maxConcurrency int // Codehost authorization secrets gitHubToken string @@ -77,6 +78,7 @@ func init() { // SourcegraphInstanceOptions codeintelUploadFlagSet.StringVar(&codeintelUploadFlags.uploadRoute, "upload-route", "/.api/lsif/upload", "The path of the upload route. For internal use only.") codeintelUploadFlagSet.Int64Var(&codeintelUploadFlags.maxPayloadSizeMb, "max-payload-size", 100, `The maximum upload size (in megabytes). Indexes exceeding this limit will be uploaded over multiple HTTP requests.`) + codeintelUploadFlagSet.IntVar(&codeintelUploadFlags.maxConcurrency, "max-concurrency", -1, "The maximum number of concurrent uploads. Only relevant for multipart uploads. Defaults to all parts concurrently.") // Codehost authorization secrets codeintelUploadFlagSet.StringVar(&codeintelUploadFlags.gitHubToken, "github-token", "", `A GitHub access token with 'public_repo' scope that Sourcegraph uses to verify you have access to the repository.`) diff --git a/go.mod b/go.mod index 08f6cfd845..23edb3c76d 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module github.com/sourcegraph/src-cli go 1.18 require ( - cloud.google.com/go/storage v1.28.0 + cloud.google.com/go/storage v1.30.1 github.com/atotto/clipboard v0.1.4 github.com/aws/aws-sdk-go-v2/config v1.18.13 github.com/aws/aws-sdk-go-v2/service/ec2 v1.86.0 @@ -12,30 +12,30 @@ require ( github.com/charmbracelet/bubbles v0.15.0 github.com/charmbracelet/lipgloss v0.7.1 github.com/creack/goselect v0.1.2 - github.com/derision-test/glock v0.0.0-20210316032053-f5b74334bb29 + github.com/derision-test/glock v1.0.0 github.com/dineshappavoo/basex v0.0.0-20170425072625-481a6f6dc663 github.com/dustin/go-humanize v1.0.1 github.com/gobwas/glob v0.2.3 github.com/google/go-cmp v0.5.9 github.com/grafana/regexp v0.0.0-20221123153739-15dc172cd2db - github.com/hexops/autogold v1.3.0 + github.com/hexops/autogold v1.3.1 github.com/jedib0t/go-pretty/v6 v6.3.7 github.com/jig/teereadcloser v0.0.0-20181016160506-953720c48e05 github.com/json-iterator/go v1.1.12 github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 - github.com/mattn/go-isatty v0.0.17 + github.com/mattn/go-isatty v0.0.19 github.com/neelance/parallel v0.0.0-20160708114440-4de9ce63d14c github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 github.com/sourcegraph/conc v0.3.0 github.com/sourcegraph/go-diff v0.6.2-0.20221123165719-f8cd299c40f3 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf - github.com/sourcegraph/scip v0.2.4-0.20221213205653-aa0e511dcfef - github.com/sourcegraph/sourcegraph/lib v0.0.0-20230316093010-26299ec302d0 - github.com/stretchr/testify v1.8.1 - golang.org/x/net v0.8.0 - golang.org/x/sync v0.1.0 - google.golang.org/api v0.110.0 - google.golang.org/protobuf v1.28.1 + github.com/sourcegraph/scip v0.3.1-0.20230627154934-45df7f6d33fc + github.com/sourcegraph/sourcegraph/lib v0.0.0-20230822113036-acc34d9b2e95 + github.com/stretchr/testify v1.8.4 + golang.org/x/net v0.12.0 + golang.org/x/sync v0.3.0 + google.golang.org/api v0.132.0 + google.golang.org/protobuf v1.31.0 gopkg.in/yaml.v3 v3.0.1 jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7 k8s.io/api v0.27.1 @@ -45,10 +45,26 @@ require ( ) require ( - cloud.google.com/go v0.107.0 // indirect - cloud.google.com/go/compute v1.18.0 // indirect - cloud.google.com/go/compute/metadata v0.2.3 // indirect - cloud.google.com/go/iam v0.12.0 // indirect + github.com/google/pprof v0.0.0-20230602150820-91b7bce49751 // indirect + github.com/google/s2a-go v0.1.4 // indirect + github.com/jackc/chunkreader/v2 v2.0.1 // indirect + github.com/jackc/pgconn v1.12.1 // indirect + github.com/jackc/pgio v1.0.0 // indirect + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgproto3/v2 v2.3.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20200714003250-2b9c44734f2b // indirect + github.com/onsi/ginkgo/v2 v2.9.7 // indirect + github.com/onsi/gomega v1.27.8 // indirect + go.uber.org/goleak v1.2.1 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20230717213848-3f92550aa753 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20230717213848-3f92550aa753 // indirect +) + +require ( + cloud.google.com/go v0.110.4 // indirect + cloud.google.com/go/compute v1.22.0 // indirect + cloud.google.com/go/compute/metadata v0.2.4-0.20230617002413-005d2dfb6b68 // indirect + cloud.google.com/go/iam v1.1.1 // indirect github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect github.com/Masterminds/goutils v1.1.1 // indirect github.com/Masterminds/semver v1.5.0 // indirect @@ -70,19 +86,19 @@ require ( github.com/bufbuild/buf v1.4.0 // indirect github.com/charmbracelet/bubbletea v0.23.1 // direct github.com/charmbracelet/glamour v0.5.0 // indirect - github.com/cockroachdb/errors v1.9.0 // indirect - github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f // indirect - github.com/cockroachdb/redact v1.1.3 // indirect + github.com/cockroachdb/errors v1.10.0 // indirect + github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect + github.com/cockroachdb/redact v1.1.5 // indirect github.com/containerd/console v1.0.3 // indirect github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect github.com/davecgh/go-spew v1.1.1 // indirect - github.com/dlclark/regexp2 v1.7.0 // indirect + github.com/dlclark/regexp2 v1.8.0 // indirect github.com/emicklei/go-restful/v3 v3.9.0 // indirect - github.com/envoyproxy/protoc-gen-validate v0.9.1 // indirect - github.com/fatih/color v1.13.0 // indirect - github.com/getsentry/sentry-go v0.15.0 // indirect + github.com/envoyproxy/protoc-gen-validate v0.10.1 // indirect + github.com/fatih/color v1.15.0 // indirect + github.com/getsentry/sentry-go v0.22.0 // indirect github.com/ghodss/yaml v1.0.0 // indirect - github.com/go-logr/logr v1.2.3 // indirect + github.com/go-logr/logr v1.2.4 // indirect github.com/go-openapi/jsonpointer v0.19.6 // indirect github.com/go-openapi/jsonreference v0.20.1 // indirect github.com/go-openapi/swag v0.22.3 // indirect @@ -92,22 +108,22 @@ require ( github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect github.com/golang/protobuf v1.5.3 // indirect github.com/google/gnostic v0.5.7-v3refs // indirect - github.com/google/gofuzz v1.1.0 // indirect + github.com/google/gofuzz v1.2.0 // indirect github.com/google/uuid v1.3.0 // indirect - github.com/googleapis/enterprise-certificate-proxy v0.2.3 // indirect - github.com/googleapis/gax-go/v2 v2.7.0 // indirect + github.com/googleapis/enterprise-certificate-proxy v0.2.5 // indirect + github.com/googleapis/gax-go/v2 v2.12.0 // indirect github.com/gorilla/css v1.0.0 // indirect github.com/hexops/gotextdiff v1.0.3 // indirect github.com/hexops/valast v1.4.3 // indirect github.com/huandu/xstrings v1.3.2 // indirect - github.com/imdario/mergo v0.3.13 // indirect - github.com/inconshreveable/mousetrap v1.0.1 // indirect + github.com/imdario/mergo v0.3.16 // indirect + github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/jdxcode/netrc v0.0.0-20210204082910-926c7f70242a // indirect github.com/jhump/protocompile v0.0.0-20220216033700-d705409f108f // indirect github.com/jhump/protoreflect v1.12.1-0.20220417024638-438db461d753 // indirect github.com/jmespath/go-jmespath v0.4.0 // indirect github.com/josharian/intern v1.0.0 // indirect - github.com/klauspost/compress v1.15.11 // indirect + github.com/klauspost/compress v1.16.7 // indirect github.com/klauspost/pgzip v1.2.5 // indirect github.com/kr/pretty v0.3.1 // indirect github.com/kr/text v0.2.0 // indirect @@ -116,7 +132,7 @@ require ( github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-localereader v0.0.1 // indirect github.com/mattn/go-runewidth v0.0.14 // indirect - github.com/microcosm-cc/bluemonday v1.0.22 // indirect + github.com/microcosm-cc/bluemonday v1.0.23 // indirect github.com/mitchellh/copystructure v1.2.0 // indirect github.com/mitchellh/reflectwalk v1.0.2 // indirect github.com/moby/spdystream v0.2.0 // indirect @@ -136,11 +152,11 @@ require ( github.com/pmezard/go-difflib v1.0.0 // indirect github.com/pseudomuto/protoc-gen-doc v1.5.1 // indirect github.com/pseudomuto/protokit v0.2.0 // indirect - github.com/rivo/uniseg v0.4.2 // indirect + github.com/rivo/uniseg v0.4.3 // indirect github.com/rogpeppe/go-internal v1.10.0 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect - github.com/sourcegraph/log v0.0.0-20221206163500-7d93c6ad7037 // indirect - github.com/spf13/cobra v1.6.0 // indirect + github.com/sourcegraph/log v0.0.0-20230711093019-40c57b632cca // indirect + github.com/spf13/cobra v1.7.0 // indirect github.com/spf13/pflag v1.0.5 // indirect github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect github.com/stretchr/objx v0.5.0 // indirect @@ -150,21 +166,21 @@ require ( github.com/yuin/goldmark v1.5.2 // indirect github.com/yuin/goldmark-emoji v1.0.1 // indirect go.opencensus.io v0.24.0 // indirect - go.uber.org/atomic v1.10.0 // indirect - go.uber.org/multierr v1.9.0 // indirect + go.uber.org/atomic v1.11.0 // indirect + go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.24.0 // indirect - golang.org/x/crypto v0.3.0 // indirect - golang.org/x/mod v0.9.0 // indirect - golang.org/x/oauth2 v0.5.0 // indirect - golang.org/x/sys v0.6.0 // indirect - golang.org/x/term v0.6.0 // indirect - golang.org/x/text v0.8.0 // indirect - golang.org/x/time v0.0.0-20220922220347-f3bd1da661af // indirect - golang.org/x/tools v0.7.0 // indirect + golang.org/x/crypto v0.11.0 // indirect + golang.org/x/mod v0.11.0 // indirect + golang.org/x/oauth2 v0.10.0 // indirect + golang.org/x/sys v0.10.0 // indirect + golang.org/x/term v0.10.0 // indirect + golang.org/x/text v0.11.0 // indirect + golang.org/x/time v0.3.0 // indirect + golang.org/x/tools v0.10.0 // indirect golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 // indirect google.golang.org/appengine v1.6.7 // indirect - google.golang.org/genproto v0.0.0-20230216225411-c8e22ba71e44 // indirect - google.golang.org/grpc v1.53.0 // indirect + google.golang.org/genproto v0.0.0-20230717213848-3f92550aa753 // indirect + google.golang.org/grpc v1.56.2 // indirect gopkg.in/inf.v0 v0.9.1 // direct gopkg.in/yaml.v2 v2.4.0 // indirect k8s.io/klog/v2 v2.90.1 // indirect diff --git a/go.sum b/go.sum index 496eee800c..16f28ca957 100644 --- a/go.sum +++ b/go.sum @@ -1,36 +1,27 @@ cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -cloud.google.com/go v0.107.0 h1:qkj22L7bgkl6vIeZDlOY2po43Mx/TIa2Wsa7VR+PEww= -cloud.google.com/go v0.107.0/go.mod h1:wpc2eNrD7hXUTy8EKS10jkxpZBjASrORK7goS+3YX2I= -cloud.google.com/go/compute v1.18.0 h1:FEigFqoDbys2cvFkZ9Fjq4gnHBP55anJ0yQyau2f9oY= -cloud.google.com/go/compute v1.18.0/go.mod h1:1X7yHxec2Ga+Ss6jPyjxRxpu2uu7PLgsOVXvgU0yacs= -cloud.google.com/go/compute/metadata v0.2.3 h1:mg4jlk7mCAj6xXp9UJ4fjI9VUI5rubuGBW5aJ7UnBMY= -cloud.google.com/go/compute/metadata v0.2.3/go.mod h1:VAV5nSsACxMJvgaAuX6Pk2AawlZn8kiOGuCv6gTkwuA= -cloud.google.com/go/iam v0.12.0 h1:DRtTY29b75ciH6Ov1PHb4/iat2CLCvrOm40Q0a6DFpE= -cloud.google.com/go/iam v0.12.0/go.mod h1:knyHGviacl11zrtZUoDuYpDgLjvr28sLQaG0YB2GYAY= -cloud.google.com/go/longrunning v0.3.0 h1:NjljC+FYPV3uh5/OwWT6pVU+doBqMg2x/rZlE+CamDs= -cloud.google.com/go/storage v1.28.0 h1:DLrIZ6xkeZX6K70fU/boWx5INJumt6f+nwwWSHXzzGY= -cloud.google.com/go/storage v1.28.0/go.mod h1:qlgZML35PXA3zoEnIkiPLY4/TOkUleufRlu6qmcf7sI= -github.com/AndreasBriese/bbloom v0.0.0-20190306092124-e2d15f34fcf9/go.mod h1:bOvUY6CB00SOBii9/FifXqc0awNKxLFCL/+pkDPuyl8= +cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.110.4 h1:1JYyxKMN9hd5dR2MYTPWkGUgcoxVVhg0LKNKEo0qvmk= +cloud.google.com/go v0.110.4/go.mod h1:+EYjdK8e5RME/VY/qLCAtuyALQ9q67dvuum8i+H5xsI= +cloud.google.com/go/compute v1.22.0 h1:cB8R6FtUtT1TYGl5R3xuxnW6OUIc/DrT2aiR16TTG7Y= +cloud.google.com/go/compute v1.22.0/go.mod h1:4tCnrn48xsqlwSAiLf1HXMQk8CONslYbdiEZc9FEIbM= +cloud.google.com/go/compute/metadata v0.2.4-0.20230617002413-005d2dfb6b68 h1:aRVqY1p2IJaBGStWMsQMpkAa83cPkCDLl80eOj0Rbz4= +cloud.google.com/go/compute/metadata v0.2.4-0.20230617002413-005d2dfb6b68/go.mod h1:1a3eRNYX12fs5UABBIXS8HXVvQbX9hRB/RkEBPORpe8= +cloud.google.com/go/iam v1.1.1 h1:lW7fzj15aVIXYHREOqjRBV9PsH0Z6u8Y46a1YGvQP4Y= +cloud.google.com/go/iam v1.1.1/go.mod h1:A5avdyVL2tCppe4unb0951eI9jreack+RJ0/d+KUZOU= +cloud.google.com/go/storage v1.30.1 h1:uOdMxAs8HExqBlnLtnQyP0YkvbiDpdGShGKtx6U/oNM= +cloud.google.com/go/storage v1.30.1/go.mod h1:NfxhC0UJE1aXSx7CIIbCf7y9HKT7BiccwkR7+P7gN8E= github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 h1:UQHMgLO+TxOElx5B5HZ4hJQsoJ/PvUvKRhJHDQXO8P8= github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= -github.com/CloudyKit/fastprinter v0.0.0-20170127035650-74b38d55f37a/go.mod h1:EFZQ978U7x8IRnstaskI3IysnWY5Ao3QgZUKOXlsAdw= -github.com/CloudyKit/fastprinter v0.0.0-20200109182630-33d98a066a53/go.mod h1:+3IMCy2vIlbG1XG/0ggNQv0SvxCAIpPM5b1nCz56Xno= -github.com/CloudyKit/jet v2.1.3-0.20180809161101-62edd43e4f88+incompatible/go.mod h1:HPYO+50pSWkPoj9Q/eq0aRGByCL6ScRlUmiEX5Zgm+w= -github.com/CloudyKit/jet/v3 v3.0.0/go.mod h1:HKQPgSJmdK8hdoAbKUUWajkHyHo4RaU5rMdUywE7VMo= -github.com/Joker/hpp v1.0.0/go.mod h1:8x5n+M1Hp5hC0g8okX3sR3vFQwynaX/UgSOM9MeBKzY= -github.com/Joker/jade v1.0.1-0.20190614124447-d475f43051e7/go.mod h1:6E6s8o2AE4KhCrqr6GRJjdC/gNfTdxkIXvuGZZda2VM= github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI= github.com/Masterminds/goutils v1.1.1/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU= github.com/Masterminds/semver v1.5.0 h1:H65muMkzWKEuNDnfl9d70GUjFniHKHRbFPGBuZ3QEww= github.com/Masterminds/semver v1.5.0/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y= github.com/Masterminds/sprig v2.22.0+incompatible h1:z4yfnGrZ7netVz+0EDJ0Wi+5VZCSYp4Z0m2dk6cEM60= github.com/Masterminds/sprig v2.22.0+incompatible/go.mod h1:y6hNFY5UBTIWBxnzTeuNhlNS5hqE0NB0E6fgfo2Br3o= -github.com/Shopify/goreferrer v0.0.0-20181106222321-ec9c9a553398/go.mod h1:a1uqRtAwp2Xwc6WNPJEufxJ7fx3npB4UV/JOLmbu5I0= -github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY= github.com/alecthomas/chroma v0.10.0 h1:7XDcGkCQopCNKjZHfYrNLraA+M7e0fMiJ/Mfikbfjek= github.com/alecthomas/chroma v0.10.0/go.mod h1:jtJATyUxlIORhUOFNA9NZDWGAQ8wpxQQqNSB4rjA/1s= -github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= +github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio= github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4= github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI= @@ -72,11 +63,11 @@ github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiE github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8= github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk= github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4= -github.com/aymerick/raymond v2.0.3-0.20180322193309-b565731e1464+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g= github.com/benbjohnson/clock v1.3.0 h1:ip6w0uFQkncKQ979AypyG0ER7mqUSBdKLOgAle/AT8A= github.com/bufbuild/buf v1.4.0 h1:GqE3a8CMmcFvWPzuY3Mahf9Kf3S9XgZ/ORpfYFzO+90= github.com/bufbuild/buf v1.4.0/go.mod h1:mwHG7klTHnX+rM/ym8LXGl7vYpVmnwT96xWoRB4H5QI= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/charmbracelet/bubbles v0.15.0 h1:c5vZ3woHV5W2b8YZI1q7v4ZNQaPetfHuoHzx+56Z6TI= github.com/charmbracelet/bubbles v0.15.0/go.mod h1:Y7gSFbBzlMpUDR/XM9MhZI374Q+1p1kluf1uLl8iK74= github.com/charmbracelet/bubbletea v0.23.1 h1:CYdteX1wCiCzKNUlwm25ZHBIc1GXlYFyUIte8WPvhck= @@ -90,106 +81,80 @@ github.com/charmbracelet/lipgloss v0.7.1/go.mod h1:yG0k3giv8Qj8edTCbbg6AlQ5e8KNW github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= -github.com/cockroachdb/datadriven v1.0.1-0.20211007161720-b558070c3be0/go.mod h1:5Ib8Meh+jk1RlHIXej6Pzevx/NLlNvQB9pmSBZErGA4= -github.com/cockroachdb/datadriven v1.0.1-0.20220214170620-9913f5bc19b7/go.mod h1:hi0MtSY3AYDQNDi83kDkMH5/yqM/CsIrsOITkSoH7KI= -github.com/cockroachdb/errors v1.6.1/go.mod h1:tm6FTP5G81vwJ5lC0SizQo374JNCOPrHyXGitRJoDqM= -github.com/cockroachdb/errors v1.8.8/go.mod h1:z6VnEL3hZ/2ONZEvG7S5Ym0bU2AqPcEKnIiA1wbsSu0= -github.com/cockroachdb/errors v1.9.0 h1:B48dYem5SlAY7iU8AKsgedb4gH6mo+bDkbtLIvM/a88= -github.com/cockroachdb/errors v1.9.0/go.mod h1:vaNcEYYqbIqB5JhKBhFV9CneUqeuEbB2OYJBK4GBNYQ= -github.com/cockroachdb/logtags v0.0.0-20190617123548-eb05cc24525f/go.mod h1:i/u985jwjWRlyHXQbwatDASoW0RMlZ/3i9yJHE2xLkI= -github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f h1:6jduT9Hfc0njg5jJ1DdKCFPdMBrp/mdZfCpa5h+WM74= -github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= -github.com/cockroachdb/redact v1.1.3 h1:AKZds10rFSIj7qADf0g46UixK8NNLwWTNdCIGS5wfSQ= -github.com/cockroachdb/redact v1.1.3/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= -github.com/cockroachdb/sentry-go v0.6.1-cockroachdb.2/go.mod h1:8BT+cPK6xvFOcRlk0R8eg+OTkcqI6baNH4xAkpiYVvQ= -github.com/codegangsta/inject v0.0.0-20150114235600-33e0aa1cb7c0/go.mod h1:4Zcjuz89kmFXt9morQgcfYZAYZ5n8WHjt81YYWIwtTM= +github.com/cncf/udpa/go v0.0.0-20210930031921-04548b0d99d4/go.mod h1:6pvJx4me5XPnfI9Z40ddWsdw2W/uZgQLFXToKeRcDiI= +github.com/cncf/xds/go v0.0.0-20210805033703-aa0b78936158/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/xds/go v0.0.0-20210922020428-25de7278fc84/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cockroachdb/apd v1.1.0/go.mod h1:8Sl8LxpKi29FqWXR16WEFZRNSz3SoPzUzeMeY4+DwBQ= +github.com/cockroachdb/errors v1.10.0 h1:lfxS8zZz1+OjtV4MtNWgboi/W5tyLEB6VQZBXN+0VUU= +github.com/cockroachdb/errors v1.10.0/go.mod h1:lknhIsEVQ9Ss/qKDBQS/UqFSvPQjOwNq2qyKAxtHRqE= +github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b h1:r6VH0faHjZeQy818SGhaone5OnYfxFR/+AzdY3sf5aE= +github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= +github.com/cockroachdb/redact v1.1.5 h1:u1PMllDkdFfPWaNGMyLD1+so+aq3uUItthCFqzwPJ30= +github.com/cockroachdb/redact v1.1.5/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= github.com/containerd/console v1.0.3 h1:lIr7SlA5PxZyMV30bDW0MGbiOPXwc63yRuCP0ARubLw= github.com/containerd/console v1.0.3/go.mod h1:7LqA/THxQ86k76b8c/EMSiaJ3h1eZkMkXar0TQ1gf3U= -github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= -github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= -github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= -github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE= +github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= +github.com/coreos/go-systemd v0.0.0-20190719114852-fd7a80b32e1f/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w= github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/creack/goselect v0.1.2 h1:2DNy14+JPjRBgPzAd1thbQp4BSIihxcBf0IXhQXDRa0= github.com/creack/goselect v0.1.2/go.mod h1:a/NhLweNvqIYMuxcMOuWY516Cimucms3DglDzQP3hKY= +github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/creack/pty v1.1.18 h1:n56/Zwd5o6whRC5PMGretI4IdRLlmBXYNjScPaBgsbY= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/derision-test/glock v0.0.0-20210316032053-f5b74334bb29 h1:O07j7ewg0eFHRx+7bxCA/7z86HJexl7HLY9kyVMmPDo= -github.com/derision-test/glock v0.0.0-20210316032053-f5b74334bb29/go.mod h1:jKtLdBMrF+XQatqvg46wiWdDfDSSDjdhO4dOM2FX9H4= -github.com/dgraph-io/badger v1.6.0/go.mod h1:zwt7syl517jmP8s94KqSxTlM6IMsdhYy6psNgSztDR4= -github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= -github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= +github.com/derision-test/glock v1.0.0 h1:b6sViZG+Cm6QtdpqbfWEjaBVbzNPntIS4GzsxpS+CmM= +github.com/derision-test/glock v1.0.0/go.mod h1:jKtLdBMrF+XQatqvg46wiWdDfDSSDjdhO4dOM2FX9H4= github.com/dineshappavoo/basex v0.0.0-20170425072625-481a6f6dc663 h1:fctNkSsavbXpt8geFWZb8n+noCqS8MrOXRJ/YfdZ2dQ= github.com/dineshappavoo/basex v0.0.0-20170425072625-481a6f6dc663/go.mod h1:Kad2hux31v/IyD4Rf4wAwIyK48995rs3qAl9IUAhc2k= github.com/dlclark/regexp2 v1.4.0/go.mod h1:2pZnwuY/m+8K6iRw6wQdMtk+rH5tNGR1i55kozfMjCc= -github.com/dlclark/regexp2 v1.7.0 h1:7lJfhqlPssTb1WQx4yvTHN0uElPEv52sbaECrAQxjAo= -github.com/dlclark/regexp2 v1.7.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= +github.com/dlclark/regexp2 v1.8.0 h1:rJD5HeGIT/2b5CDk63FVCwZA3qgYElfg+oQK7uH5pfE= +github.com/dlclark/regexp2 v1.8.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= github.com/docopt/docopt-go v0.0.0-20180111231733-ee0de3bc6815/go.mod h1:WwZ+bS3ebgob9U8Nd0kOddGdZWjyMGR8Wziv+TBNwSE= -github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= -github.com/eknkc/amber v0.0.0-20171010120322-cdade1c07385/go.mod h1:0vRUJqYpeSZifjYj7uP3BG/gKcuzL9xWVV/Y+cK33KM= github.com/emicklei/go-restful/v3 v3.9.0 h1:XwGDlfxEnQZzuopoqxwSEllNcCOM9DhhFyhFIIGKwxE= github.com/emicklei/go-restful/v3 v3.9.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= +github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= github.com/envoyproxy/go-control-plane v0.9.9-0.20210217033140-668b12f5399d/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= +github.com/envoyproxy/go-control-plane v0.9.10-0.20210907150352-cf90f659a021/go.mod h1:AFq3mo9L8Lqqiid3OhADV3RfLJnjiw63cSpi+fDTRC0= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= -github.com/envoyproxy/protoc-gen-validate v0.9.1 h1:PS7VIOgmSVhWUEeZwTe7z7zouA22Cr590PzXKbZHOVY= -github.com/envoyproxy/protoc-gen-validate v0.9.1/go.mod h1:OKNgG7TCp5pF4d6XftA0++PMirau2/yoOwVac3AbF2w= -github.com/etcd-io/bbolt v1.3.3/go.mod h1:ZF2nL25h33cCyBtcyWeZ2/I3HQOfTP+0PIEvHjkjCrw= -github.com/fasthttp-contrib/websocket v0.0.0-20160511215533-1f3b11f56072/go.mod h1:duJ4Jxv5lDcvg4QuQr0oowTf7dz4/CR8NtyCooz9HL8= -github.com/fatih/color v1.13.0 h1:8LOYc1KYPPmyKMuN8QV2DNRWNbLo6LZ0iLs8+mlH53w= +github.com/envoyproxy/protoc-gen-validate v0.10.1 h1:c0g45+xCJhdgFGw7a5QAfdS4byAbud7miNWJ1WwEVf8= +github.com/envoyproxy/protoc-gen-validate v0.10.1/go.mod h1:DRjgyB0I43LtJapqN6NiRwroiAU2PaFuvk/vjgh61ss= github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= -github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M= -github.com/flosch/pongo2 v0.0.0-20190707114632-bbf5a6c351f4/go.mod h1:T9YF2M40nIgbVgp3rreNmTged+9HrbNTIQf1PsaIiTA= +github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs= +github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw= github.com/frankban/quicktest v1.14.3 h1:FJKSZTDHjyhriyC81FLQ0LY93eSai0ZyR/ZIkd3ZUKE= github.com/frankban/quicktest v1.14.3/go.mod h1:mgiwOwqx65TmIk1wJ6Q7wvnVMocbUorkibMOrVTHZps= -github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= -github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= -github.com/gavv/httpexpect v2.0.0+incompatible/go.mod h1:x+9tiU1YnrOvnB725RkpoLv1M62hOWzwo5OXotisrKc= -github.com/getsentry/sentry-go v0.12.0/go.mod h1:NSap0JBYWzHND8oMbyi0+XZhUalc1TBdRL1M71JZW2c= -github.com/getsentry/sentry-go v0.15.0 h1:CP9bmA7pralrVUedYZsmIHWpq/pBtXTSew7xvVpfLaA= -github.com/getsentry/sentry-go v0.15.0/go.mod h1:RZPJKSw+adu8PBNygiri/A98FqVr2HtRckJk9XVxJ9I= -github.com/gin-contrib/sse v0.0.0-20190301062529-5545eab6dad3/go.mod h1:VJ0WA2NBN22VlZ2dKZQPAPnyWw5XTlK1KymzLKsr59s= -github.com/gin-gonic/gin v1.4.0/go.mod h1:OW2EZn3DO8Ln9oIKOvM++LBO+5UPHJJDH72/q/3rZdM= -github.com/go-check/check v0.0.0-20180628173108-788fd7840127/go.mod h1:9ES+weclKsC9YodN5RgxqK/VD9HM9JsCSh7rNhMZE98= -github.com/go-errors/errors v1.0.1/go.mod h1:f4zRHt4oKfwPJE5k8C9vpYG+aDHdBFUsgrm6/TyX73Q= +github.com/getsentry/sentry-go v0.22.0 h1:XNX9zKbv7baSEI65l+H1GEJgSeIC1c7EN5kluWaP6dM= +github.com/getsentry/sentry-go v0.22.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA= github.com/go-logr/logr v1.2.0/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -github.com/go-logr/logr v1.2.3 h1:2DntVwHkVopvECVRSlL5PSo9eG+cAkDCuckLubN+rq0= -github.com/go-logr/logr v1.2.3/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -github.com/go-martini/martini v0.0.0-20170121215854-22fa46961aab/go.mod h1:/P9AEU963A2AYjv4d1V5eVL1CQbEJq6aCNHDDjibzu8= +github.com/go-logr/logr v1.2.4 h1:g01GSCwiDw2xSZfjJ2/T9M+S6pFdcNtFYsp+Y43HYDQ= +github.com/go-logr/logr v1.2.4/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-openapi/jsonpointer v0.19.6 h1:eCs3fxoIi3Wh6vtgmLTOjdhSpiqphQ+DaPn38N2ZdrE= github.com/go-openapi/jsonpointer v0.19.6/go.mod h1:osyAmYz/mB/C3I+WsTTSgw1ONzaLJoLCyoi6/zppojs= github.com/go-openapi/jsonreference v0.20.1 h1:FBLnyygC4/IZZr893oiomc9XaghoveYTrLC1F86HID8= github.com/go-openapi/jsonreference v0.20.1/go.mod h1:Bl1zwGIM8/wsvqjsOQLJ/SH+En5Ap4rVB5KVcIDZG2k= github.com/go-openapi/swag v0.22.3 h1:yMBqmnQ0gyZvEb/+KzuWZOXgllrXT4SADYbvDaXHv/g= github.com/go-openapi/swag v0.22.3/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14= -github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0 h1:p104kn46Q8WdvHunIJ9dAyjPVtrBPhSr3KT2yUst43I= +github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 h1:tfuBGBXKqDEevZMzYi5KSi8KkcZtzBcTgAUUtapy0OI= github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y= github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8= -github.com/gobwas/httphead v0.0.0-20180130184737-2c6c146eadee/go.mod h1:L0fX3K22YWvt/FAX9NnzrNzcI4wNYi9Yku4O0LKYflo= -github.com/gobwas/pool v0.2.0/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw= -github.com/gobwas/ws v1.0.2/go.mod h1:szmBTxLgaFppYjEmNtny/v3w89xOydFnnZMcgRRu/EM= github.com/gofrs/flock v0.8.1 h1:+gYjHKf32LDeiEEFhQaotPbLuUXjY5ZqxKgXy7n59aw= github.com/gofrs/flock v0.8.1/go.mod h1:F1TvTiK9OcQqauNUHlbJvyl9Qa1QvF/gOUDKA14jxHU= github.com/gofrs/uuid v4.2.0+incompatible h1:yyYWMnhkhrKwwr8gAOcOCYxOOscHgDS9yZgBrnJfGa0= github.com/gofrs/uuid v4.2.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= -github.com/gogo/googleapis v0.0.0-20180223154316-0cd9801be74a/go.mod h1:gf4bu3Q80BeJ6H1S1vYPm8/ELATdvryBaNFGgqEef3s= -github.com/gogo/googleapis v1.4.1/go.mod h1:2lpHqI5OcWCtVElxXnPt+s8oJvMpySlOyM6xDCrzib4= -github.com/gogo/protobuf v1.2.0/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= github.com/gogo/protobuf v1.3.0/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= -github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= -github.com/gogo/status v1.1.0/go.mod h1:BFv9nrluPLmrS0EmGVvLaPNmRosr9KapBYd5/hpY1WM= -github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE= @@ -211,7 +176,6 @@ github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaS github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= -github.com/gomodule/redigo v1.7.1-0.20190724094224-574c33c3df38/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4= github.com/google/gnostic v0.5.7-v3refs h1:FhTMOKj2VhjpouxvWJAV1TL304uMlb9zcDqkl6cEI54= github.com/google/gnostic v0.5.7-v3refs/go.mod h1:73MKFl6jIHelAJNaBGFzt3SPtZULs9dYrGFt8OiIsHQ= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= @@ -227,54 +191,78 @@ github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8 github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= -github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/google/gofuzz v1.1.0 h1:Hsa8mG0dQ46ij8Sl2AYJDUv1oA9/d6Vk+3LG99Oe02g= -github.com/google/gofuzz v1.1.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/google/martian/v3 v3.2.1 h1:d8MncMlErDFTwQGBK1xhv026j9kqhvw1Qv9IbWT1VLQ= -github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1 h1:K6RDEckDVWvDI9JAJYCmNdQXq6neHJOYx3V6jnqNEec= +github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= +github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/martian/v3 v3.3.2 h1:IqNFLAmvJOgVlpdEBiQbDc2EwKW77amAycfTuWKdfvw= +github.com/google/pprof v0.0.0-20230602150820-91b7bce49751 h1:hR7/MlvK23p6+lIw9SN1TigNLn9ZnF3W4SYRKq2gAHs= +github.com/google/pprof v0.0.0-20230602150820-91b7bce49751/go.mod h1:Jh3hGz2jkYak8qXPD19ryItVnUgpgeqzdkY/D0EaeuA= +github.com/google/s2a-go v0.1.4 h1:1kZ/sQM3srePvKs3tXAvQzo66XfcReoqFpIpIccE7Oc= +github.com/google/s2a-go v0.1.4/go.mod h1:Ej+mSEMGRnqRzjc7VtF+jdBwYG5fuJfiZ8ELkjEwM0A= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/googleapis/enterprise-certificate-proxy v0.2.3 h1:yk9/cqRKtT9wXZSsRH9aurXEpJX+U6FLtpYTdC3R06k= -github.com/googleapis/enterprise-certificate-proxy v0.2.3/go.mod h1:AwSRAtLfXpU5Nm3pW+v7rGDHp09LsPtGY9MduiEsR9k= -github.com/googleapis/gax-go/v2 v2.7.0 h1:IcsPKeInNvYi7eqSaDjiZqDDKu5rsmunY0Y1YupQSSQ= -github.com/googleapis/gax-go/v2 v2.7.0/go.mod h1:TEop28CZZQ2y+c0VxMUmu1lV+fQx57QpBWsYpwqHJx8= -github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= +github.com/googleapis/enterprise-certificate-proxy v0.2.5 h1:UR4rDjcgpgEnqpIEvkiqTYKBCKLNmlge2eVjoZfySzM= +github.com/googleapis/enterprise-certificate-proxy v0.2.5/go.mod h1:RxW0N9901Cko1VOCW3SXCpWP+mlIEkk2tP7jnHy9a3w= +github.com/googleapis/gax-go/v2 v2.12.0 h1:A+gCJKdRfqXkr+BIRGtZLibNXf0m1f9E4HG56etFpas= +github.com/googleapis/gax-go/v2 v2.12.0/go.mod h1:y+aIqrI5eb1YGMVJfuV3185Ts/D7qKpsEkdD5+I6QGU= github.com/gorilla/css v1.0.0 h1:BQqNyPTi50JCFMTw/b67hByjMVXZRwGha6wxVGkeihY= github.com/gorilla/css v1.0.0/go.mod h1:Dn721qIggHpt4+EFCcTLTU/vk5ySda2ReITrtgBl60c= -github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= -github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/grafana/regexp v0.0.0-20221123153739-15dc172cd2db h1:7aN5cccjIqCLTzedH7MZzRZt5/lsAHch6Z3L2ZGn5FA= github.com/grafana/regexp v0.0.0-20221123153739-15dc172cd2db/go.mod h1:M5qHK+eWfAv8VR/265dIuEpL3fNfeC21tXXp9itM24A= -github.com/hashicorp/go-version v1.2.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= -github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= +github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= github.com/hexops/autogold v0.8.1/go.mod h1:97HLDXyG23akzAoRYJh/2OBs3kd80eHyKPvZw0S5ZBY= -github.com/hexops/autogold v1.3.0 h1:IEtGNPxBeBu8RMn8eKWh/Ll9dVNgSnJ7bp/qHgMQ14o= -github.com/hexops/autogold v1.3.0/go.mod h1:d4hwi2rid66Sag+BVuHgwakW/EmaFr8vdTSbWDbrDRI= +github.com/hexops/autogold v1.3.1 h1:YgxF9OHWbEIUjhDbpnLhgVsjUDsiHDTyDfy2lrfdlzo= +github.com/hexops/autogold v1.3.1/go.mod h1:sQO+mQUCVfxOKPht+ipDSkJ2SCJ7BNJVHZexsXqWMx4= github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM= github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg= -github.com/hexops/valast v1.4.0/go.mod h1:uVjKZ0smVuYlgCSPz9NRi5A04sl7lp6GtFWsROKDgEs= github.com/hexops/valast v1.4.3 h1:oBoGERMJh6UZdRc6cduE1CTPK+VAdXA59Y1HFgu3sm0= github.com/hexops/valast v1.4.3/go.mod h1:Iqx2kLj3Jn47wuXpj3wX40xn6F93QNFBHuiKBerkTGA= -github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/huandu/xstrings v1.3.2 h1:L18LIDzqlW6xN2rEkpdV8+oL/IXWJ1APd+vsdYy4Wdw= github.com/huandu/xstrings v1.3.2/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE= -github.com/hydrogen18/memlistener v0.0.0-20141126152155-54553eb933fb/go.mod h1:qEIFzExnS6016fRpRfxrExeVn2gbClQA99gQhnIcdhE= -github.com/hydrogen18/memlistener v0.0.0-20200120041712-dcc25e7acd91/go.mod h1:qEIFzExnS6016fRpRfxrExeVn2gbClQA99gQhnIcdhE= -github.com/imdario/mergo v0.3.13 h1:lFzP57bqS/wsqKssCGmtLAb8A0wKjLGrve2q3PPVcBk= -github.com/imdario/mergo v0.3.13/go.mod h1:4lJ1jqUDcsbIECGy0RUJAXNIhg+6ocWgb1ALK2O4oXg= -github.com/imkira/go-interpol v1.1.0/go.mod h1:z0h2/2T3XF8kyEPpRgJ3kmNv+C43p+I/CoI+jC3w2iA= -github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= -github.com/inconshreveable/mousetrap v1.0.1 h1:U3uMjPSQEBMNp1lFxmllqCPM6P5u/Xq7Pgzkat/bFNc= -github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= -github.com/iris-contrib/blackfriday v2.0.0+incompatible/go.mod h1:UzZ2bDEoaSGPbkg6SAB4att1aAwTmVIx/5gCVqeyUdI= -github.com/iris-contrib/go.uuid v2.0.0+incompatible/go.mod h1:iz2lgM/1UnEf1kP0L/+fafWORmlnuysV2EMP8MW+qe0= -github.com/iris-contrib/i18n v0.0.0-20171121225848-987a633949d0/go.mod h1:pMCz62A0xJL6I+umB2YTlFRwWXaDFA0jy+5HzGiJjqI= -github.com/iris-contrib/jade v1.1.3/go.mod h1:H/geBymxJhShH5kecoiOCSssPX7QWYH7UaeZTSWddIk= -github.com/iris-contrib/pongo2 v0.0.1/go.mod h1:Ssh+00+3GAZqSQb30AvBRNxBx7rf0GqwkjqxNd0u65g= -github.com/iris-contrib/schema v0.0.1/go.mod h1:urYA3uvUNG1TIIjOSCzHr9/LmbQo8LrOcOqfqxa4hXw= +github.com/imdario/mergo v0.3.16 h1:wwQJbIsHYGMUyLSPrEq1CT16AhnhNJQ51+4fdHUnCl4= +github.com/imdario/mergo v0.3.16/go.mod h1:WBLT9ZmE3lPoWsEzCh9LPo3TiwVN+ZKEjmz+hD27ysY= +github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= +github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= +github.com/jackc/chunkreader v1.0.0/go.mod h1:RT6O25fNZIuasFJRyZ4R/Y2BbhasbmZXF9QQ7T3kePo= +github.com/jackc/chunkreader/v2 v2.0.0/go.mod h1:odVSm741yZoC3dpHEUXIqA9tQRhFrgOHwnPIn9lDKlk= +github.com/jackc/chunkreader/v2 v2.0.1 h1:i+RDz65UE+mmpjTfyz0MoVTnzeYxroil2G82ki7MGG8= +github.com/jackc/chunkreader/v2 v2.0.1/go.mod h1:odVSm741yZoC3dpHEUXIqA9tQRhFrgOHwnPIn9lDKlk= +github.com/jackc/pgconn v0.0.0-20190420214824-7e0022ef6ba3/go.mod h1:jkELnwuX+w9qN5YIfX0fl88Ehu4XC3keFuOJJk9pcnA= +github.com/jackc/pgconn v0.0.0-20190824142844-760dd75542eb/go.mod h1:lLjNuW/+OfW9/pnVKPazfWOgNfH2aPem8YQ7ilXGvJE= +github.com/jackc/pgconn v0.0.0-20190831204454-2fabfa3c18b7/go.mod h1:ZJKsE/KZfsUgOEh9hBm+xYTstcNHg7UPMVJqRfQxq4s= +github.com/jackc/pgconn v1.8.0/go.mod h1:1C2Pb36bGIP9QHGBYCjnyhqu7Rv3sGshaQUvmfGIB/o= +github.com/jackc/pgconn v1.9.0/go.mod h1:YctiPyvzfU11JFxoXokUOOKQXQmDMoJL9vJzHH8/2JY= +github.com/jackc/pgconn v1.12.1 h1:rsDFzIpRk7xT4B8FufgpCCeyjdNpKyghZeSefViE5W8= +github.com/jackc/pgconn v1.12.1/go.mod h1:ZkhRC59Llhrq3oSfrikvwQ5NaxYExr6twkdkMLaKono= +github.com/jackc/pgio v1.0.0 h1:g12B9UwVnzGhueNavwioyEEpAmqMe1E/BN9ES+8ovkE= +github.com/jackc/pgio v1.0.0/go.mod h1:oP+2QK2wFfUWgr+gxjoBH9KGBb31Eio69xUb0w5bYf8= +github.com/jackc/pgmock v0.0.0-20190831213851-13a1b77aafa2/go.mod h1:fGZlG77KXmcq05nJLRkk0+p82V8B8Dw8KN2/V9c/OAE= +github.com/jackc/pgmock v0.0.0-20201204152224-4fe30f7445fd/go.mod h1:hrBW0Enj2AZTNpt/7Y5rr2xe/9Mn757Wtb2xeBzPv2c= +github.com/jackc/pgmock v0.0.0-20210724152146-4ad1a8207f65 h1:DadwsjnMwFjfWc9y5Wi/+Zz7xoE5ALHsRQlOctkOiHc= +github.com/jackc/pgmock v0.0.0-20210724152146-4ad1a8207f65/go.mod h1:5R2h2EEX+qri8jOWMbJCtaPWkrrNc7OHwsp2TCqp7ak= +github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgproto3 v1.1.0/go.mod h1:eR5FA3leWg7p9aeAqi37XOTgTIbkABlvcPB3E5rlc78= +github.com/jackc/pgproto3/v2 v2.0.0-alpha1.0.20190420180111-c116219b62db/go.mod h1:bhq50y+xrl9n5mRYyCBFKkpRVTLYJVWeCc+mEAI3yXA= +github.com/jackc/pgproto3/v2 v2.0.0-alpha1.0.20190609003834-432c2951c711/go.mod h1:uH0AWtUmuShn0bcesswc4aBTWGvw0cAxIJp+6OB//Wg= +github.com/jackc/pgproto3/v2 v2.0.0-rc3/go.mod h1:ryONWYqW6dqSg1Lw6vXNMXoBJhpzvWKnT95C46ckYeM= +github.com/jackc/pgproto3/v2 v2.0.0-rc3.0.20190831210041-4c03ce451f29/go.mod h1:ryONWYqW6dqSg1Lw6vXNMXoBJhpzvWKnT95C46ckYeM= +github.com/jackc/pgproto3/v2 v2.0.6/go.mod h1:WfJCnwN3HIg9Ish/j3sgWXnAfK8A9Y0bwXYU5xKaEdA= +github.com/jackc/pgproto3/v2 v2.1.1/go.mod h1:WfJCnwN3HIg9Ish/j3sgWXnAfK8A9Y0bwXYU5xKaEdA= +github.com/jackc/pgproto3/v2 v2.3.0 h1:brH0pCGBDkBW07HWlN/oSBXrmo3WB0UvZd1pIuDcL8Y= +github.com/jackc/pgproto3/v2 v2.3.0/go.mod h1:WfJCnwN3HIg9Ish/j3sgWXnAfK8A9Y0bwXYU5xKaEdA= +github.com/jackc/pgservicefile v0.0.0-20200714003250-2b9c44734f2b h1:C8S2+VttkHFdOOCXJe+YGfa4vHYwlt4Zx+IVXQ97jYg= +github.com/jackc/pgservicefile v0.0.0-20200714003250-2b9c44734f2b/go.mod h1:vsD4gTJCa9TptPL8sPkXrLZ+hDuNrZCnj29CQpr4X1E= +github.com/jackc/pgtype v0.0.0-20190421001408-4ed0de4755e0/go.mod h1:hdSHsc1V01CGwFsrv11mJRHWJ6aifDLfdV3aVjFF0zg= +github.com/jackc/pgtype v0.0.0-20190824184912-ab885b375b90/go.mod h1:KcahbBH1nCMSo2DXpzsoWOAfFkdEtEJpPbVLq8eE+mc= +github.com/jackc/pgtype v0.0.0-20190828014616-a8802b16cc59/go.mod h1:MWlu30kVJrUS8lot6TQqcg7mtthZ9T0EoIBFiJcmcyw= +github.com/jackc/pgx/v4 v4.0.0-20190420224344-cc3461e65d96/go.mod h1:mdxmSJJuR08CZQyj1PVQBHy9XOp5p8/SHH6a0psbY9Y= +github.com/jackc/pgx/v4 v4.0.0-20190421002000-1b8f0016e912/go.mod h1:no/Y67Jkk/9WuGR0JG/JseM9irFbnEPbuWV2EELPNuM= +github.com/jackc/pgx/v4 v4.0.0-pre1.0.20190824185557-6972a5742186/go.mod h1:X+GQnOEnf1dqHGpw7JmHqHc1NxDoalibchSk9/RWuDc= +github.com/jackc/puddle v0.0.0-20190413234325-e4ced69a3a2b/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk= +github.com/jackc/puddle v0.0.0-20190608224051-11cab39313c9/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk= github.com/jdxcode/netrc v0.0.0-20210204082910-926c7f70242a h1:d4+I1YEKVmWZrgkt6jpXBnLgV2ZjO0YxEtLDdfIZfH4= github.com/jdxcode/netrc v0.0.0-20210204082910-926c7f70242a/go.mod h1:Zi/ZFkEqFHTm7qkjyNJjaWH4LQA9LQhGJyF0lTYGpxw= github.com/jedib0t/go-pretty/v6 v6.3.7 h1:H3Ulkf7h6A+p0HgKBGzgDn0bZIupRbKKWF4pO4Bs7iA= @@ -295,37 +283,19 @@ github.com/jmespath/go-jmespath/internal/testify v1.5.1 h1:shLQSRRSCCPj3f2gpwzGw github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= -github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= -github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= -github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= -github.com/juju/errors v0.0.0-20181118221551-089d3ea4e4d5/go.mod h1:W54LbzXuIE0boCoNJfwqpmkKJ1O4TCTZMetAt6jGk7Q= -github.com/juju/loggo v0.0.0-20180524022052-584905176618/go.mod h1:vgyd7OREkbtVEN/8IXZe5Ooef3LQePvuBm9UWj6ZL8U= -github.com/juju/testing v0.0.0-20180920084828-472a3e8b2073/go.mod h1:63prj8cnj0tU0S9OHjGJn+b1h0ZghCndfnbQolrYTwA= -github.com/k0kubun/colorstring v0.0.0-20150214042306-9440f1994b88/go.mod h1:3w7q1U84EfirKl04SVQ/s7nPm1ZPhiXd34z40TNz36k= -github.com/kataras/golog v0.0.9/go.mod h1:12HJgwBIZFNGL0EJnMRhmvGA0PQGx8VFwrZtM4CqbAk= -github.com/kataras/golog v0.0.10/go.mod h1:yJ8YKCmyL+nWjERB90Qwn+bdyBZsaQwU3bTVFgkFIp8= -github.com/kataras/iris/v12 v12.0.1/go.mod h1:udK4vLQKkdDqMGJJVd/msuMtN6hpYJhg/lSzuxjhO+U= -github.com/kataras/iris/v12 v12.1.8/go.mod h1:LMYy4VlP67TQ3Zgriz8RE2h2kMZV2SgMYbq3UhfoFmE= -github.com/kataras/neffos v0.0.10/go.mod h1:ZYmJC07hQPW67eKuzlfY7SO3bC0mw83A3j6im82hfqw= -github.com/kataras/neffos v0.0.14/go.mod h1:8lqADm8PnbeFfL7CLXh1WHw53dG27MC3pgi2R1rmoTE= -github.com/kataras/pio v0.0.0-20190103105442-ea782b38602d/go.mod h1:NV88laa9UiiDuX9AhMbDPkGYSPugBOV6yTZB1l2K9Z0= -github.com/kataras/pio v0.0.2/go.mod h1:hAoW0t9UmXi4R5Oyq5Z4irTbaTsOemSrDGUtaTl7Dro= -github.com/kataras/sitemap v0.0.5/go.mod h1:KY2eugMKiPwsJgx7+U103YZehfvNGOXURubcGyk0Bz8= github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 h1:Z9n2FFNUXsshfwJMBgNA0RU6/i7WVaAegv3PtuIHPMs= github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51/go.mod h1:CzGEWj7cYgsdH8dAjBGEr58BoE7ScuLd+fwFZ44+/x8= github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= -github.com/klauspost/compress v1.8.2/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= -github.com/klauspost/compress v1.9.0/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= -github.com/klauspost/compress v1.9.7/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= -github.com/klauspost/compress v1.15.11 h1:Lcadnb3RKGin4FYM/orgq0qde+nc15E5Cbqg4B9Sx9c= -github.com/klauspost/compress v1.15.11/go.mod h1:QPwzmACJjUTFsnSHH934V6woptycfrDDJnH7hvFVbGM= -github.com/klauspost/cpuid v1.2.1/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek= +github.com/klauspost/compress v1.16.7 h1:2mk3MPGNzKyxErAw8YaohYh69+pa4sIQSC0fPGCFR9I= +github.com/klauspost/compress v1.16.7/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= github.com/klauspost/pgzip v1.2.5 h1:qnWYvvKqedOF2ulHpMG72XQol4ILEJ8k2wwRl/Km8oE= github.com/klauspost/pgzip v1.2.5/go.mod h1:Ch1tH69qFZu15pkjo5kYi6mth2Zzwzt50oCQKQE9RUs= +github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= @@ -333,33 +303,30 @@ github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NB github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/pty v1.1.8/go.mod h1:O1sed60cT9XZ5uDucP5qwvh+TE3NnUj51EiZO/lmSfw= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= -github.com/labstack/echo/v4 v4.1.11/go.mod h1:i541M3Fj6f76NZtHSj7TXnyM8n2gaodfvfxNnFqi74g= -github.com/labstack/echo/v4 v4.5.0/go.mod h1:czIriw4a0C1dFun+ObrXp7ok03xON0N1awStJ6ArI7Y= -github.com/labstack/gommon v0.3.0/go.mod h1:MULnywXg0yavhxWKc+lOruYdAhDwPK9wf0OL7NoOu+k= +github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= +github.com/lib/pq v1.1.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= +github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= -github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= -github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= -github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= +github.com/mattn/go-colorable v0.1.1/go.mod h1:FuOcm+DKB9mbwrcAfNl7/TZVBZ6rcnceauSikq3lYCQ= github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= -github.com/mattn/go-colorable v0.1.11/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= +github.com/mattn/go-isatty v0.0.5/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= github.com/mattn/go-isatty v0.0.7/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= -github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= -github.com/mattn/go-isatty v0.0.9/go.mod h1:YNRxwqDuOph6SZLI9vUUz6OYw3QyUt7WiY2yME+cCiQ= github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/mattn/go-isatty v0.0.13/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= -github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng= -github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= +github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4= github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88= github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= @@ -368,18 +335,11 @@ github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRC github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU= github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= -github.com/mattn/goveralls v0.0.2/go.mod h1:8d1ZMHsd7fW6IRPKQh46F2WRpyib5/X4FOpevwGNQEw= -github.com/mediocregopher/mediocre-go-lib v0.0.0-20181029021733-cb65787f37ed/go.mod h1:dSsfyI2zABAdhcbvkXqgxOxrCsbYeHCPgrZkku60dSg= -github.com/mediocregopher/radix/v3 v3.3.0/go.mod h1:EmfVyvspXz1uZEyPBMyGK+kjWiKQGvsUt6O3Pj+LDCQ= -github.com/mediocregopher/radix/v3 v3.4.2/go.mod h1:8FL3F6UQRXHXIBSPUs5h0RybMF8i4n7wVopoX3x7Bv8= -github.com/microcosm-cc/bluemonday v1.0.2/go.mod h1:iVP4YcDBq+n/5fb23BhYFvIMq/leAFZyRl6bYmGDlGc= github.com/microcosm-cc/bluemonday v1.0.17/go.mod h1:Z0r70sCuXHig8YpBzCc5eGHAap2K7e/u082ZUpDRRqM= -github.com/microcosm-cc/bluemonday v1.0.22 h1:p2tT7RNzRdCi0qmwxG+HbqD6ILkmwter1ZwVZn1oTxA= -github.com/microcosm-cc/bluemonday v1.0.22/go.mod h1:ytNkv4RrDrLJ2pqlsSI46O6IVXmZOBBD4SaJyDwwTkM= +github.com/microcosm-cc/bluemonday v1.0.23 h1:SMZe2IGa0NuHvnVNAZ+6B38gsTbi5e4sViiWJyDDqFY= +github.com/microcosm-cc/bluemonday v1.0.23/go.mod h1:mN70sk7UkkF8TUr2IGBpNN0jAgStuPzlK76QuruE/z4= github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw= github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s= -github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= -github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ= github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= github.com/moby/spdystream v0.2.0 h1:cjW1zVyyoiM0T7b6UoySUFqzXMoqRckQtXwGPiBhOM8= @@ -389,11 +349,8 @@ github.com/moby/term v0.0.0-20221205130635-1aeaba878587/go.mod h1:8FzsFHVUBGZdbD github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= -github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= -github.com/moul/http2curl v1.0.0/go.mod h1:8UbvGypXm98wA/IqH45anm5Y2Z6ep6O31QGOAZ3H0fQ= github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b h1:1XF24mVaiu7u+CFywTdcDo2ie1pzzhwjt6RHqzpMU34= github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b/go.mod h1:fQuZ0gauxyBcmsdE3ZT4NasjaRdxmbCS0jRHsrWu3Ho= github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA= @@ -410,32 +367,18 @@ github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/mwitkow/go-proto-validators v0.3.2 h1:qRlmpTzm2pstMKKzTdvwPCF5QfBNURSlAgN/R+qbKos= github.com/mwitkow/go-proto-validators v0.3.2/go.mod h1:ej0Qp0qMgHN/KtDyUt+Q1/tA7a5VarXUOUxD+oeD30w= -github.com/nats-io/jwt v0.3.0/go.mod h1:fRYCDE99xlTsqUzISS1Bi75UBJ6ljOJQOAAu5VglpSg= -github.com/nats-io/nats.go v1.8.1/go.mod h1:BrFz9vVn0fU3AcH9Vn4Kd7W0NpJ651tD5omQ3M8LwxM= -github.com/nats-io/nats.go v1.9.1/go.mod h1:ZjDU1L/7fJ09jvUSRVBR2e7+RnLiiIQyqyzEE/Zbp4w= -github.com/nats-io/nkeys v0.0.2/go.mod h1:dab7URMsZm6Z/jp9Z5UGa87Uutgc2mVpXLC4B7TDb/4= -github.com/nats-io/nkeys v0.1.0/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w= -github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c= github.com/neelance/parallel v0.0.0-20160708114440-4de9ce63d14c h1:NZOii9TDGRAfCS5VM16XnF4K7afoLQmIiZX8EkKnxtE= github.com/neelance/parallel v0.0.0-20160708114440-4de9ce63d14c/go.mod h1:eTBvSIlRgLo+CNFFQRQTwUGTZOEdvXIKeZS/xG+D2yU= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/nightlyone/lockfile v1.0.0 h1:RHep2cFKK4PonZJDdEl4GmkabuhbsRMgk/k3uAmxBiA= github.com/nightlyone/lockfile v1.0.0/go.mod h1:rywoIealpdNse2r832aiD9jRk8ErCatROs6LzC841CI= -github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec= github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY= -github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= -github.com/onsi/ginkgo v1.10.3/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= -github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= -github.com/onsi/ginkgo v1.13.0 h1:M76yO2HkZASFjXL0HSoZJ1AYEmQxNJmY41Jx1zNUq1Y= -github.com/onsi/ginkgo v1.13.0/go.mod h1:+REjRxOmWfHCjfv9TTWB1jD1Frx4XydAD3zm1lskyM0= -github.com/onsi/ginkgo/v2 v2.9.1 h1:zie5Ly042PD3bsCvsSOPvRnFwyo3rKe64TJlD6nu0mk= -github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= -github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= -github.com/onsi/gomega v1.27.4 h1:Z2AnStgsdSayCMDiCU42qIz+HLqEPcgiOCXjAU/w+8E= -github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= +github.com/onsi/ginkgo/v2 v2.9.7 h1:06xGQy5www2oN160RtEZoTvnP2sPhEfePYmCDc2szss= +github.com/onsi/ginkgo/v2 v2.9.7/go.mod h1:cxrmXWykAwTwhQsJOPfdIDiJ+l2RYq7U8hFU+M/1uw0= +github.com/onsi/gomega v1.27.8 h1:gegWiwZjBsf2DgiSbf5hpokZ98JVDMcWkUiigk6/KXc= +github.com/onsi/gomega v1.27.8/go.mod h1:2J8vzI/s+2shY9XHRApDkdgPo1TKT7P2u6fXeJKFnNQ= github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4= -github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8= github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 h1:KoWmjvw+nsYOo29YJK9vDA65RGE3NrOnUtO7a+RF9HU= github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8/go.mod h1:HKlIX3XHQyzLZPlr7++PzdhaXEj94dEiJgZDTsxEqUI= github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= @@ -453,57 +396,49 @@ github.com/pseudomuto/protokit v0.2.0 h1:hlnBDcy3YEDXH7kc9gV+NLaN0cDzhDvD1s7Y6FZ github.com/pseudomuto/protokit v0.2.0/go.mod h1:2PdH30hxVHsup8KpBTOXTBeMVhJZVio3Q8ViKSAXT0Q= github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= -github.com/rivo/uniseg v0.4.2 h1:YwD0ulJSJytLpiaWua0sBDusfsCZohxjxzVTYjwxfV8= -github.com/rivo/uniseg v0.4.2/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= +github.com/rivo/uniseg v0.4.3 h1:utMvzDsuh3suAEnhH0RdHmoPbU648o6CvXxTx4SBMOw= +github.com/rivo/uniseg v0.4.3/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= +github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= -github.com/rogpeppe/go-internal v1.6.2/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= -github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= -github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= +github.com/rs/xid v1.2.1/go.mod h1:+uKXf+4Djp6Md1KODXJxgGQPKngRmWyn10oCKFzNHOQ= +github.com/rs/zerolog v1.13.0/go.mod h1:YbFCdg8HfsridGWAh22vktObvhZbQsZXe4/zB0OKkWU= +github.com/rs/zerolog v1.15.0/go.mod h1:xYTKnLHcpfU2225ny5qZjxnj9NvkumZYjJHlAThCjNc= github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= -github.com/ryanuber/columnize v2.1.0+incompatible/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= github.com/sahilm/fuzzy v0.1.0/go.mod h1:VFvziUEIMCrT6A6tw2RFIXPXXmzXbOsSHF0DOI8ZK9Y= -github.com/schollz/closestmatch v2.1.0+incompatible/go.mod h1:RtP1ddjLong6gTkbtmuhtR2uUrrJOpYzYRvbcPAid+g= -github.com/sclevine/agouti v3.0.0+incompatible/go.mod h1:b4WX9W9L1sfQKXeJf1mUTLZKJ48R1S7H23Ji7oFO5Bw= -github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= -github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= +github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= +github.com/shopspring/decimal v0.0.0-20180709203117-cd690d0c9e24/go.mod h1:M+9NzErvs504Cn4c5DxATwIqPbtswREoFCre64PpcG4= github.com/shurcooL/go v0.0.0-20180423040247-9e1955d9fb6e/go.mod h1:TDJrrUr11Vxrven61rcy3hJMUqaf/CLWYhHNPmT14Lk= github.com/shurcooL/go-goon v0.0.0-20170922171312-37c2f522c041/go.mod h1:N5mDOmsrJOB+vfqUK+7DmDyjhSLIIBnXo9lvZJj3MWQ= -github.com/shurcooL/go-goon v0.0.0-20210110234559-7585751d9a17/go.mod h1:N5mDOmsrJOB+vfqUK+7DmDyjhSLIIBnXo9lvZJj3MWQ= -github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= -github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= -github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= +github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q= +github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo= github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0= github.com/sourcegraph/go-diff v0.6.2-0.20221123165719-f8cd299c40f3 h1:11miag7hlORpW7ici5mL7T9PyiEsmVmf+8PFOvJ/ZrA= github.com/sourcegraph/go-diff v0.6.2-0.20221123165719-f8cd299c40f3/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= -github.com/sourcegraph/log v0.0.0-20221206163500-7d93c6ad7037 h1:hgZHfGYG3KMlDDfACuPgzhMIaEjblCqZ+YltcPgd0tw= -github.com/sourcegraph/log v0.0.0-20221206163500-7d93c6ad7037/go.mod h1:y+sVdVKxHhp489iiiXeZgXIhSpFYijtp/pLD2coj96g= -github.com/sourcegraph/scip v0.2.4-0.20221213205653-aa0e511dcfef h1:fWPxLkDObzzKTGe9vb6wpzK0FYkwcfSxmxUBvAOc8aw= -github.com/sourcegraph/scip v0.2.4-0.20221213205653-aa0e511dcfef/go.mod h1:ymcTuv+6D5OEZB/84TRPQvUpDK7v7zXnWBJl79hb7ns= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20230316093010-26299ec302d0 h1:NJyyvyYU/DNZmNFui8ktnHke3hS/PYLmDUbWNHSHKuQ= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20230316093010-26299ec302d0/go.mod h1:bYQ9cozv3Uhh/pINa5PfDnkAl62YqDoKGNhj3WuZIoo= +github.com/sourcegraph/log v0.0.0-20230711093019-40c57b632cca h1:VwYrG1+YNyOD3nSb0M84ISMQiOOS/5Js05HqU1iNFSU= +github.com/sourcegraph/log v0.0.0-20230711093019-40c57b632cca/go.mod h1:IDp09QkoqS8Z3CyN2RW6vXjgABkNpDbyjLIHNQwQ8P8= +github.com/sourcegraph/scip v0.3.1-0.20230627154934-45df7f6d33fc h1:o+eq0cjVV3B5ngIBF04Lv3GwttKOuYFF5NTcfXWXzfA= +github.com/sourcegraph/scip v0.3.1-0.20230627154934-45df7f6d33fc/go.mod h1:7ZKAtLIUmiMvOIgG5LMcBxdtBXVa0v2GWC4Hm1ASYQ0= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20230822113036-acc34d9b2e95 h1:xkoH/Vn4HMAga75N1YgTdv8nhjCXtbkw0BLY7+M3oyk= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20230822113036-acc34d9b2e95/go.mod h1:hhrNfT3eDxsAsjaWEn8vWjmrEFDa9v238tDf9TyEAHc= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= -github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= -github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= -github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU= -github.com/spf13/cobra v1.6.0 h1:42a0n6jwCot1pUmomAp4T7DeMD+20LFv4Q54pxLf2LI= -github.com/spf13/cobra v1.6.0/go.mod h1:IOw/AERYS7UzyrGinqmz6HLUo219MORXGxhbaJUqzrY= -github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= -github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= +github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I= +github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= -github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s= github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf h1:pvbZ0lM0XWPBqUKqFU8cmavspvIl9nulOYwdy6IFRRo= github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf/go.mod h1:RJID2RhlZKId02nZ62WenDCkgHFerpIOmW0iT7GKmXM= github.com/stoewer/go-strcase v1.2.0/go.mod h1:IBiWB2sKIp3wVVQ3Y035++gc+knqhUQag1KpM8ahLw8= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0 h1:1zr/of2m5FGMsad5YfcqgdqdWrIhu+EBEJRhR1U7z/c= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= @@ -516,18 +451,9 @@ github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.4/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= -github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= -github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc= -github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw= -github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= -github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY= -github.com/urfave/negroni v1.0.0/go.mod h1:Meg73S6kFm/4PpbYdq35yYWoCZ9mS/YSx+lKnmiohz4= -github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= -github.com/valyala/fasthttp v1.6.0/go.mod h1:FstJa9V+Pj9vQ7OJie2qMHdwemEDaDiSdBnvPM1Su9w= -github.com/valyala/fasttemplate v1.0.1/go.mod h1:UQGH1tvbgY+Nz5t2n7tXsz52dQxojPUpymEIMZ47gx8= -github.com/valyala/fasttemplate v1.2.1/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ= -github.com/valyala/tcplisten v0.0.0-20161114210144-ceec8f93295a/go.mod h1:v3UYOV9WzVtRmSR+PDvWpU/qWl4Wa5LApYYX4ZtKbio= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb h1:zGWFAtiMcyryUHoUjUJX0/lt1H2+i2Ka2n+D3DImSNo= github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= @@ -535,201 +461,189 @@ github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHo github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74= github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y= -github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= -github.com/yalp/jsonpath v0.0.0-20180802001716-5cc68e5049a0/go.mod h1:/LWChgwKmvncFJFHJ7Gvn9wZArjbV5/FppcK2fKk/tI= -github.com/yudai/gojsondiff v1.0.0/go.mod h1:AY32+k2cwILAkW1fbgxQ5mUmMiZFgLIV+FBNExI05xg= -github.com/yudai/golcs v0.0.0-20170316035057-ecda9a501e82/go.mod h1:lgjkn3NuSvDfVJdfcVVdX+jpBxNmX4rDAzaS45IcYoM= -github.com/yudai/pp v2.0.1+incompatible/go.mod h1:PuxR/8QJ7cyCkFp/aUDS+JY727OFEZkTdatxwunjIkc= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= github.com/yuin/goldmark v1.4.4/go.mod h1:rmuwmfZ0+bvzB24eSC//bk1R1Zp3hM0OXYv/G2LIilg= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= github.com/yuin/goldmark v1.5.2 h1:ALmeCk/px5FSm1MAcFBAsVKZjDuMVj8Tm7FFIlMJnqU= github.com/yuin/goldmark v1.5.2/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= github.com/yuin/goldmark-emoji v1.0.1 h1:ctuWEyzGBwiucEqxzwe0SOYDXPAucOrE9NQC18Wa1os= github.com/yuin/goldmark-emoji v1.0.1/go.mod h1:2w1E6FEWLcDQkoTE+7HU6QF1F6SLlNGjRIBbIZQFqkQ= +github.com/zenazn/goji v0.9.0/go.mod h1:7S9M489iMyHBNxwZnk9/EHS098H4/F6TATF2mIxtB1Q= go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0= go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo= -go.uber.org/atomic v1.10.0 h1:9qC72Qh0+3MqyJbAn8YU5xVq1frD8bn3JtD2oXtafVQ= -go.uber.org/atomic v1.10.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= -go.uber.org/goleak v1.2.0 h1:xqgm/S+aQvhWFTtR0XK3Jvg7z8kGV8P4X14IzwN3Eqk= -go.uber.org/multierr v1.9.0 h1:7fIwc/ZtS0q++VgcfqFDxSBZVv/Xo49/SYnDFupUwlI= -go.uber.org/multierr v1.9.0/go.mod h1:X2jQV1h+kxSjClGpnseKVIxpmcjrj7MNnI0bnlfKTVQ= +go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI= +go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= +go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= +go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= +go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= +go.uber.org/goleak v1.2.1 h1:NBol2c7O1ZokfZ0LEU9K6Whx/KnwvepVetCUhtKja4A= +go.uber.org/goleak v1.2.1/go.mod h1:qlT2yGI9QafXHhZZLxlSuNsMw3FFLxBr+tBRlmO1xH4= +go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= +go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= +go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= +go.uber.org/zap v1.9.1/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= +go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= go.uber.org/zap v1.24.0 h1:FiJd5l1UOLj0wCgbSE0rwwXHzEdAZS6hiiSnxJN/D60= go.uber.org/zap v1.24.0/go.mod h1:2kMP+WWQ8aoFoedH3T2sq6iJ2yDWpHbP0f6MQbS9Gkg= -golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20190411191339-88737f569e3a/go.mod h1:WFFai1msRO1wXaEeE5yQxYXgSfI8pQAWXbQop6sCtWE= +golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20191227163750-53104e6ec876/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= +golang.org/x/crypto v0.0.0-20201203163018-be400aefbc4c/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= +golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.3.0 h1:a06MkbcxBrEFc0w0QIZWXrH/9cCX6KJyWbBOIwAn+7A= -golang.org/x/crypto v0.3.0/go.mod h1:hebNnKkNXi2UzZN1eVRvBB7co0a+JxK6XbPiWVs/3J4= +golang.org/x/crypto v0.0.0-20220314234659-1baeb1ce4c0b/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= +golang.org/x/crypto v0.11.0 h1:6Ewdq3tDic1mg5xRO4milcWCfMVQhI4NkqWWvqejpuA= +golang.org/x/crypto v0.11.0/go.mod h1:xgJhtzW8F9jGdVFWZESrid1U1bjeNy4zgy5cRr/CIio= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20210508222113-6edffad5e616/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= -golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.7.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/mod v0.9.0 h1:KENHtAZL2y3NLMYZeHY9DW8HW8V+kQyJsY/V9JlKvCs= -golang.org/x/mod v0.9.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/mod v0.11.0 h1:bUO06HqtnRcc/7l71XBe4WcqTZ+3AH1J59zWDDwLKgU= +golang.org/x/mod v0.11.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190327091125-710a502c58a2/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20190827160401-ba9fcec4b297/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190813141303-74dc4d7220e7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/net v0.0.0-20210614182718-04defd469f4e/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/net v0.0.0-20211008194852-3b03d305991f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.3.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE= -golang.org/x/net v0.8.0 h1:Zrh2ngAOFYneWTAIAPethzeaQLuHwhuBkuV6ZiRnUaQ= -golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= +golang.org/x/net v0.12.0 h1:cfawfvKITfUsFCeJIHJrbSxpeu/E81khclypR0GVT50= +golang.org/x/net v0.12.0/go.mod h1:zEVYFnQC7m/vmpQFELhcD1EWkZlX69l4oqgmer6hfKA= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= -golang.org/x/oauth2 v0.5.0 h1:HuArIo48skDwlrvM3sEdHXElYslAMsf3KwRkkW4MC4s= -golang.org/x/oauth2 v0.5.0/go.mod h1:9/XBHVqLaWO3/BRHs5jbpYCnOZVjj5V0ndyaAM7KB4I= +golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.10.0 h1:zHCpF2Khkwy4mMB4bv0U37YtJdTGW8jI0glAApi0Kh8= +golang.org/x/oauth2 v0.10.0/go.mod h1:kTpgurOux7LqtuxjuyZa4Gj2gdezIt/jQtGnNFfypQI= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220819030929-7fc1605a5dde/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.3.0 h1:ftCYgMx6zT/asHUrPw8BLLscYtGznsLAnjq5RH9P66E= +golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190403152447-81d4e9dc473e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190626221950-04f50cda93cb/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200519105757-fe76b779f299/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210218084038-e8e29180ff58/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210403161142-5e06dd20ab57/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210616045830-e2b7044e8c71/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20211007075335-d3039528d8ac/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220204135822-1c1b9b1eba6a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220829200755-d48e67d00261/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.10.0 h1:SqMFp9UcQJZa+pmYuAKjd9xq1f0j5rLcDIk0mj4qAsA= +golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.3.0/go.mod h1:q750SLmJuPmVoN1blW3UFBPREJfb1KmY3vwxfr+nFDA= -golang.org/x/term v0.6.0 h1:clScbb1cHjoCkyRbWwBEUZ5H/tIFu5TAXIqaZD0Gcjw= -golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U= +golang.org/x/term v0.10.0 h1:3R7pNqamzBraeqj/Tj8qt1aQ2HpmlC+Cx/qL/7hn4/c= +golang.org/x/term v0.10.0/go.mod h1:lpqdcUyK/oCiQxvxVrppt5ggO2KCZ5QblwqPnfZ6d5o= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.8.0 h1:57P1ETyNKtuIjB4SRd15iJxuhj8Gc416Y78H3qgMh68= -golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= -golang.org/x/time v0.0.0-20201208040808-7e3f01d25324/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/time v0.0.0-20220922220347-f3bd1da661af h1:Yx9k8YCG3dvF87UAn2tu2HQLf2dt/eR1bXxpLMWeH+Y= -golang.org/x/time v0.0.0-20220922220347-f3bd1da661af/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/text v0.11.0 h1:LAntKIrcmeSKERyiOh0XMV39LXS8IE9UL2yP7+f5ij4= +golang.org/x/text v0.11.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= +golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4= +golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20181221001348-537d06c36207/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190327201419-c70d86f8b7cf/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190425163242-31fd60d6bfdc/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190823170909-c4a336ef6a2f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200624163319-25775e59acb7/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20210101214203-2dba1e4ea05c/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= -golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.4.0/go.mod h1:UE5sM2OK9E/d67R0ANs2xJizIymRP5gJU295PvKXxjQ= -golang.org/x/tools v0.7.0 h1:W4OVu8VVOaIO0yzWMNdepAulS7YfoS3Zabrm8DOXXU4= -golang.org/x/tools v0.7.0/go.mod h1:4pg6aUX35JBAogB10C9AtvVL+qowtN4pT3CGSQex14s= +golang.org/x/tools v0.10.0 h1:tvDr/iQoUqNdohiYm0LmmKcBk+q86lb9EprIUFhHHGg= +golang.org/x/tools v0.10.0/go.mod h1:UJwyiVBsOA2uwvK/e5OY3GTpDUJriEd+/YlqAwLPmyM= +golang.org/x/xerrors v0.0.0-20190410155217-1f06c39b4373/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20190513163551-3ee3066db522/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 h1:H2TDz8ibqkAF6YGhCdN3jS9O0/s90v0rJh3X/OLHEUk= golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2/go.mod h1:K8+ghG5WaK9qNqU5K3HdILfMLy1f3aNYFI/wnl100a8= -google.golang.org/api v0.110.0 h1:l+rh0KYUooe9JGbGVx71tbFo4SMbMTXK3I3ia2QSEeU= -google.golang.org/api v0.110.0/go.mod h1:7FC4Vvx1Mooxh8C5HWjzZHcavuS2f6pmJpZx60ca7iI= +google.golang.org/api v0.132.0 h1:8t2/+qZ26kAOGSmOiHwVycqVaDg7q3JDILrNi/Z6rvc= +google.golang.org/api v0.132.0/go.mod h1:AeTBC6GpJnJSRJjktDcPX0QwtS8pGYZOV6MSuSCusw0= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c= google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= -google.golang.org/genproto v0.0.0-20180518175338-11a468237815/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20200513103714-09dca8ec2884/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= google.golang.org/genproto v0.0.0-20201019141844-1ed22bb0c154/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20210624195500-8bfb893ecb84/go.mod h1:SzzZ/N+nwJDaO1kznhnlzqS8ocJICar6hYhVyhi++24= -google.golang.org/genproto v0.0.0-20230216225411-c8e22ba71e44 h1:EfLuoKW5WfkgVdDy7dTK8qSbH37AX5mj/MFh+bGPz14= -google.golang.org/genproto v0.0.0-20230216225411-c8e22ba71e44/go.mod h1:8B0gmkoRebU8ukX6HP+4wrVQUY1+6PkQ44BSyIlflHA= -google.golang.org/grpc v1.12.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= +google.golang.org/genproto v0.0.0-20230717213848-3f92550aa753 h1:+VoAg+OKmWaommL56xmZSE2sUK8A7m6SUO7X89F2tbw= +google.golang.org/genproto v0.0.0-20230717213848-3f92550aa753/go.mod h1:iqkVr8IRpZ53gx1dEnWlCUIEwDWqWARWrbzpasaTNYM= +google.golang.org/genproto/googleapis/api v0.0.0-20230717213848-3f92550aa753 h1:lCbbUxUDD+DiXx9Q6F/ttL0aAu7N2pz8XnmMm8ZW4NE= +google.golang.org/genproto/googleapis/api v0.0.0-20230717213848-3f92550aa753/go.mod h1:rsr7RhLuwsDKL7RmgDDCUc6yaGr1iqceVb5Wv6f6YvQ= +google.golang.org/genproto/googleapis/rpc v0.0.0-20230717213848-3f92550aa753 h1:XUODHrpzJEUeWmVo/jfNTLj0YyVveOo28oE6vkFbkO4= +google.golang.org/genproto/googleapis/rpc v0.0.0-20230717213848-3f92550aa753/go.mod h1:TUfxEVdsvPg18p6AslUXFoLdpED4oBnGwyqk3dV1XzM= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= -google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= +google.golang.org/grpc v1.33.1/go.mod h1:fr5YgcSWrqhRRxogOsw7RzIpsmvOZ6IcH4kBYTpR3n0= google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= +google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= google.golang.org/grpc v1.38.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= -google.golang.org/grpc v1.53.0 h1:LAv2ds7cmFV/XTS3XG1NneeENYrXGmorPxsBbptIjNc= -google.golang.org/grpc v1.53.0/go.mod h1:OnIrk0ipVdj4N5d9IUoFUx72/VlD7+jUsHwZgwSMQpw= +google.golang.org/grpc v1.45.0/go.mod h1:lN7owxKUQEqMfSyQikvvk5tf/6zMPsrK+ONuO11+0rQ= +google.golang.org/grpc v1.56.2 h1:fVRFRnXvU+x6C4IlHZewvJOVHoOv1TUuQyoRsYnB4bI= +google.golang.org/grpc v1.56.2/go.mod h1:I9bI3vqKfayGqPUAwGdOSu7kt6oIJLixfffKrpXqQ9s= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= @@ -743,8 +657,8 @@ google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlba google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.27.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -google.golang.org/protobuf v1.28.1 h1:d0NfwRgPtno5B1Wa6L2DAG+KivqkdutMf1UhdNx175w= -google.golang.org/protobuf v1.28.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8= +google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= @@ -752,25 +666,16 @@ gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b/go.mod h1:Co6ibVJAznAaIkqp8 gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= -gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= -gopkg.in/go-playground/assert.v1 v1.2.1/go.mod h1:9RXL0bg/zibRAgZUYszZSwO/z8Y/a8bDuhia5mkpMnE= -gopkg.in/go-playground/validator.v8 v8.18.2/go.mod h1:RX2a/7Ha8BgOhfk7j780h4/u/RRjR0eouCJSH80/M2Y= +gopkg.in/inconshreveable/log15.v2 v2.0.0-20180818164646-67afb5ed74ec/go.mod h1:aPpfJ7XW+gOuirDoZ8gHhLh3kZ1B08FtV2bbmy7Jv3s= gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc= gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= -gopkg.in/ini.v1 v1.51.1/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= -gopkg.in/mgo.v2 v2.0.0-20180705113604-9856a29383ce/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA= -gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= -gopkg.in/yaml.v3 v3.0.0-20191120175047-4206685974f2/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.0/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= @@ -791,8 +696,6 @@ k8s.io/metrics v0.27.1 h1:qIASSok+9dhKPrfAZmFreIdpgBgKTfXwkM9CQ+tNM90= k8s.io/metrics v0.27.1/go.mod h1:5sYmQTC3aeL/24kkJ5fYECVuIz0xhO6oipfGJ81JC1Y= k8s.io/utils v0.0.0-20230209194617-a36077c30491 h1:r0BAOLElQnnFhE/ApUsg3iHdVYYPBjNSSOMowRZxxsY= k8s.io/utils v0.0.0-20230209194617-a36077c30491/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= -mvdan.cc/gofumpt v0.0.0-20210107193838-d24d34e18d44/go.mod h1:yXG1r1WqZVKWbVRtBWKWX9+CxGYfA51nSomhM0woR48= -mvdan.cc/gofumpt v0.1.0/go.mod h1:yXG1r1WqZVKWbVRtBWKWX9+CxGYfA51nSomhM0woR48= mvdan.cc/gofumpt v0.4.0 h1:JVf4NN1mIpHogBj7ABpgOyZc65/UUOkKQFkoURsz4MM= mvdan.cc/gofumpt v0.4.0/go.mod h1:PljLOHDeZqgS8opHRKLzp2It2VBuSdteAgqUfzMTxlQ= sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd h1:EDPBXCAspyGV4jQlpZSudPeMmr1bNJefnuqLsRAsHZo= From 4c76e1957f1ecaf14ea5b84ed2669156f5ab2934 Mon Sep 17 00:00:00 2001 From: Noah S-C Date: Mon, 28 Aug 2023 22:39:18 +0100 Subject: [PATCH 365/647] changelog entry for codeintel upload concurrency flag (#1029) --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7a474da782..771deadd3b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,8 @@ All notable changes to `src-cli` are documented in this file. ### Added +- Added flag to configure the concurrency of uploading multipart code-intel indexes, for when limited upload bandwidth causes individual parts to timeout. [#1023](https://github.com/sourcegraph/src-cli/pull/1023) + ### Changed ### Fixed From f3a1963edf78b6e1aae82571d19df79b89a616b1 Mon Sep 17 00:00:00 2001 From: Varun Gandhi Date: Sun, 3 Sep 2023 19:20:15 -0500 Subject: [PATCH 366/647] docs: Tweak examples for src code-intel upload (#1019) --- cmd/src/code_intel_upload.go | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/cmd/src/code_intel_upload.go b/cmd/src/code_intel_upload.go index a3afd2dfe4..a23f9963b7 100644 --- a/cmd/src/code_intel_upload.go +++ b/cmd/src/code_intel_upload.go @@ -24,24 +24,29 @@ import ( func init() { usage := ` Examples: + Before running any of these, first use src auth to authenticate. + Alternately, use the SRC_ACCESS_TOKEN environment variable for + individual src-cli invocations. - Upload a SCIP index with explicit repo, commit, and upload files: + If run from within the project itself, src-cli will infer various + flags based on git metadata. - $ src code-intel upload -repo=FOO -commit=BAR -file=index.scip + $ src code-intel upload # uploads ./index.scip + + If src-cli is invoked outside the project root, or if you're using + a version control system other than git, specify flags explicitly: + + $ src code-intel upload -root='' -repo=FOO -commit=BAR -file=index.scip Upload a SCIP index for a subproject: $ src code-intel upload -root=cmd/ - Upload a SCIP index when lsifEnforceAuth is enabled: + Upload a SCIP index when lsif.enforceAuth is enabled in site settings: $ src code-intel upload -github-token=BAZ, or $ src code-intel upload -gitlab-token=BAZ - Upload an LSIF index when the LSIF indexer does not not declare a tool name. - - $ src code-intel upload -indexer=lsif-elixir - For any of these commands, an LSIF index (default name: dump.lsif) can be used instead of a SCIP index (default name: index.scip). ` From 573ddf8c7a56697488f60e73cdfc4cf50bdacb27 Mon Sep 17 00:00:00 2001 From: Varun Gandhi Date: Sun, 3 Sep 2023 19:34:37 -0500 Subject: [PATCH 367/647] codeintel: Fail fast on 401 failure in SCIP detection (#1034) Don't convert SCIP to LSIF, don't attempt to upload the index --- cmd/src/code_intel_upload_flags.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/cmd/src/code_intel_upload_flags.go b/cmd/src/code_intel_upload_flags.go index 2e76d8d445..a724806a90 100644 --- a/cmd/src/code_intel_upload_flags.go +++ b/cmd/src/code_intel_upload_flags.go @@ -202,6 +202,9 @@ func isSCIPAvailable() (bool, error) { return false, err } defer resp.Body.Close() + if resp.StatusCode == http.StatusUnauthorized { + return false, upload.ErrUnauthorized + } return resp.StatusCode == http.StatusOK, nil } From 998d0876306081183092a42429ec054432ff7657 Mon Sep 17 00:00:00 2001 From: Varun Gandhi Date: Sun, 3 Sep 2023 22:00:52 -0500 Subject: [PATCH 368/647] docs: Mention SCIP not just LSIF (#1033) --- cmd/src/code_intel.go | 2 +- cmd/src/code_intel_upload.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/cmd/src/code_intel.go b/cmd/src/code_intel.go index e75ac73f8c..af9f48795e 100644 --- a/cmd/src/code_intel.go +++ b/cmd/src/code_intel.go @@ -16,7 +16,7 @@ Usage: The commands are: - upload uploads an LSIF dump file + upload uploads a SCIP or LSIF index Use "src code-intel [command] -h" for more information about a command. ` diff --git a/cmd/src/code_intel_upload.go b/cmd/src/code_intel_upload.go index a23f9963b7..1eedd1dd5b 100644 --- a/cmd/src/code_intel_upload.go +++ b/cmd/src/code_intel_upload.go @@ -284,7 +284,7 @@ func filterLSIFUnauthorizedError(out *output.Output, err error) error { } return errorWithHint{err: err, hint: strings.Join(mergeStringSlices( - []string{"This Sourcegraph instance has enforced auth for LSIF uploads."}, + []string{"This Sourcegraph instance has enforced auth for SCIP/LSIF uploads."}, actionableHints, []string{"For more details, see https://docs.sourcegraph.com/cli/references/code-intel/upload."}, ), "\n")} From bdc0413494d67b44f79306a27be74425702a3da0 Mon Sep 17 00:00:00 2001 From: Keegan Carruthers-Smith Date: Thu, 14 Sep 2023 14:40:07 +0200 Subject: [PATCH 369/647] servegit: use error hook (#1037) Before this if the git command failed we would nil panic since the Logger on gitservice.Handler was not set. This commit updates us to the latest version of lib which instead takes in an error hook so we can use the attached stdlib logger. Test Plan: go test --- deps.bzl | 4 ++-- go.mod | 2 +- go.sum | 4 ++-- internal/servegit/serve.go | 3 +++ 4 files changed, 8 insertions(+), 5 deletions(-) diff --git a/deps.bzl b/deps.bzl index 9ac9997928..2c5cf55adc 100644 --- a/deps.bzl +++ b/deps.bzl @@ -1875,8 +1875,8 @@ def go_dependencies(): name = "com_github_sourcegraph_sourcegraph_lib", build_file_proto_mode = "disable_global", importpath = "github.com/sourcegraph/sourcegraph/lib", - sum = "h1:NJyyvyYU/DNZmNFui8ktnHke3hS/PYLmDUbWNHSHKuQ=", - version = "v0.0.0-20230316093010-26299ec302d0", + sum = "h1:0hAo7bbfcF3uujbq2eNl2DpN6zUrjacWAK3iSan5Q0k=", + version = "v0.0.0-20230914103605-e3a8bc516ddc", ) go_repository( name = "com_github_spf13_afero", diff --git a/go.mod b/go.mod index 23edb3c76d..b7f4ec8af1 100644 --- a/go.mod +++ b/go.mod @@ -30,7 +30,7 @@ require ( github.com/sourcegraph/go-diff v0.6.2-0.20221123165719-f8cd299c40f3 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf github.com/sourcegraph/scip v0.3.1-0.20230627154934-45df7f6d33fc - github.com/sourcegraph/sourcegraph/lib v0.0.0-20230822113036-acc34d9b2e95 + github.com/sourcegraph/sourcegraph/lib v0.0.0-20230914103605-e3a8bc516ddc github.com/stretchr/testify v1.8.4 golang.org/x/net v0.12.0 golang.org/x/sync v0.3.0 diff --git a/go.sum b/go.sum index 16f28ca957..401ff44d00 100644 --- a/go.sum +++ b/go.sum @@ -425,8 +425,8 @@ github.com/sourcegraph/log v0.0.0-20230711093019-40c57b632cca h1:VwYrG1+YNyOD3nS github.com/sourcegraph/log v0.0.0-20230711093019-40c57b632cca/go.mod h1:IDp09QkoqS8Z3CyN2RW6vXjgABkNpDbyjLIHNQwQ8P8= github.com/sourcegraph/scip v0.3.1-0.20230627154934-45df7f6d33fc h1:o+eq0cjVV3B5ngIBF04Lv3GwttKOuYFF5NTcfXWXzfA= github.com/sourcegraph/scip v0.3.1-0.20230627154934-45df7f6d33fc/go.mod h1:7ZKAtLIUmiMvOIgG5LMcBxdtBXVa0v2GWC4Hm1ASYQ0= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20230822113036-acc34d9b2e95 h1:xkoH/Vn4HMAga75N1YgTdv8nhjCXtbkw0BLY7+M3oyk= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20230822113036-acc34d9b2e95/go.mod h1:hhrNfT3eDxsAsjaWEn8vWjmrEFDa9v238tDf9TyEAHc= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20230914103605-e3a8bc516ddc h1:0hAo7bbfcF3uujbq2eNl2DpN6zUrjacWAK3iSan5Q0k= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20230914103605-e3a8bc516ddc/go.mod h1:r5UrJ7GztZRFu/LlF5lNS5XzAsnYdGphS4CJEm4Lnts= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I= diff --git a/internal/servegit/serve.go b/internal/servegit/serve.go index ec45103bca..aa845dbe04 100644 --- a/internal/servegit/serve.go +++ b/internal/servegit/serve.go @@ -106,6 +106,9 @@ func (s *Serve) handler() http.Handler { Dir: func(name string) string { return filepath.Join(s.Root, filepath.FromSlash(name)) }, + ErrorHook: func(err error, stderr string) { + s.Info.Printf("git-service error: %s\nstderr:\n%s", err.Error(), stderr) + }, Trace: func(ctx context.Context, svc, repo, protocol string) func(error) { start := time.Now() return func(err error) { From 93218faf53d719e7425428544180cfcdfe311b8b Mon Sep 17 00:00:00 2001 From: Joe Chen Date: Tue, 3 Oct 2023 15:51:44 -0400 Subject: [PATCH 370/647] changelog: cut sourcegraph@5.2.0 (#1038) --- CHANGELOG.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 771deadd3b..27604a4063 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,16 @@ All notable changes to `src-cli` are documented in this file. ### Added +### Changed + +### Fixed + +### Removed + +## 5.2.0 + +### Added + - Added flag to configure the concurrency of uploading multipart code-intel indexes, for when limited upload bandwidth causes individual parts to timeout. [#1023](https://github.com/sourcegraph/src-cli/pull/1023) ### Changed From e58f6a8f59e0fde638d3f342042295a62d90d3b4 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Fri, 6 Oct 2023 18:16:11 +0200 Subject: [PATCH 371/647] update go in workflows to be 1.20 (#1043) * update go in workflows to be 1.20 * remove -i ... it is the default? --- .github/workflows/go-ci.yml | 3 +-- .github/workflows/go-lint.yml | 2 +- .github/workflows/goreleaser.yml | 4 ++-- .tool-versions | 2 +- 4 files changed, 5 insertions(+), 6 deletions(-) diff --git a/.github/workflows/go-ci.yml b/.github/workflows/go-ci.yml index b25f3ab262..43a586f5cc 100644 --- a/.github/workflows/go-ci.yml +++ b/.github/workflows/go-ci.yml @@ -7,7 +7,7 @@ jobs: go-test: strategy: matrix: - go-version: [1.19.x] + go-version: [1.20.x] os: [ubuntu-latest, macos-latest, windows-latest] runs-on: ${{ matrix.os }} steps: @@ -17,5 +17,4 @@ jobs: uses: actions/setup-go@v3 with: go-version: ${{ matrix.go-version }} - - run: go test -i ./... - run: go test -race -v ./... diff --git a/.github/workflows/go-lint.yml b/.github/workflows/go-lint.yml index cc73193d04..58addc04fb 100644 --- a/.github/workflows/go-lint.yml +++ b/.github/workflows/go-lint.yml @@ -12,5 +12,5 @@ jobs: - name: Set up Go uses: actions/setup-go@v3 with: - go-version: 1.19.x + go-version: 1.20.x - run: ./dev/go-lint.sh diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index 793c7402a7..7781883d55 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -2,7 +2,7 @@ name: Build and Release on: push: - tags: + tags: - '*' # There are two cases where this GitHub action will run: @@ -177,7 +177,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v3 with: - go-version: 1.19 + go-version: 1.20 - run: go test -i ./... - run: go test -race -v ./... - run: echo "${DOCKER_PASSWORD}" | docker login -u=$DOCKER_USERNAME --password-stdin diff --git a/.tool-versions b/.tool-versions index 9750f5d6c7..ce1252fd18 100644 --- a/.tool-versions +++ b/.tool-versions @@ -1,3 +1,3 @@ -golang 1.19.8 +golang 1.20.8 shfmt 3.2.0 shellcheck 0.7.1 From e12882d6d956c60c51accde2cc50cd58d858c13e Mon Sep 17 00:00:00 2001 From: Bolaji Olajide <25608335+BolajiOlajide@users.noreply.github.com> Date: Wed, 8 Nov 2023 12:09:38 +0100 Subject: [PATCH 372/647] code-search: fix fork attribute for src-cli batch changes (#1045) * fix fork attribute for src-cli batch changes * changelog update * remove debug statements * update lib * go mod tidy --- .gitignore | 2 ++ CHANGELOG.md | 18 ++---------------- go.mod | 16 ++++++++-------- go.sum | 31 ++++++++++++++++--------------- 4 files changed, 28 insertions(+), 39 deletions(-) diff --git a/.gitignore b/.gitignore index 382e2d10fd..64b187f296 100644 --- a/.gitignore +++ b/.gitignore @@ -12,3 +12,5 @@ bazel-out bazel-testlogs bazel-zoekt bazel-src-cli +.DS_Store +samples \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 27604a4063..0815ac1714 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,8 @@ All notable changes to `src-cli` are documented in this file. ### Fixed +- The fork attribute in changesetTemplate is now acknowleged when creating a batch change via `src-cli`. [#58156](https://github.com/sourcegraph/sourcegraph/pull/58156) + ### Removed ## 5.2.0 @@ -25,12 +27,6 @@ All notable changes to `src-cli` are documented in this file. - Added flag to configure the concurrency of uploading multipart code-intel indexes, for when limited upload bandwidth causes individual parts to timeout. [#1023](https://github.com/sourcegraph/src-cli/pull/1023) -### Changed - -### Fixed - -### Removed - ## 5.1.2 ### Changed @@ -58,10 +54,6 @@ All notable changes to `src-cli` are documented in this file. ### Changed - Renamed `src repo {add|update|delete}-kvp` to `repo {add|update|delete}-metadata` [#972](https://github.com/sourcegraph/src-cli/pull/972) -### Fixed - -### Removed - ## 5.0.3 ### Fixed @@ -92,12 +84,6 @@ All notable changes to `src-cli` are documented in this file. - `src team` (experimental) has been added to manage teams. [#922](https://github.com/sourcegraph/src-cli/pull/922) - `src codeowners` (experimental) has been added to manage manually ingested `CODEOWNERS`. [#943](https://github.com/sourcegraph/src-cli/pull/943) -### Changed - -### Fixed - -### Removed - ## 4.5.0 No noteworthy changes, mechanical release to match Sourcegraph release. diff --git a/go.mod b/go.mod index b7f4ec8af1..16fb454228 100644 --- a/go.mod +++ b/go.mod @@ -16,7 +16,7 @@ require ( github.com/dineshappavoo/basex v0.0.0-20170425072625-481a6f6dc663 github.com/dustin/go-humanize v1.0.1 github.com/gobwas/glob v0.2.3 - github.com/google/go-cmp v0.5.9 + github.com/google/go-cmp v0.6.0 github.com/grafana/regexp v0.0.0-20221123153739-15dc172cd2db github.com/hexops/autogold v1.3.1 github.com/jedib0t/go-pretty/v6 v6.3.7 @@ -30,7 +30,7 @@ require ( github.com/sourcegraph/go-diff v0.6.2-0.20221123165719-f8cd299c40f3 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf github.com/sourcegraph/scip v0.3.1-0.20230627154934-45df7f6d33fc - github.com/sourcegraph/sourcegraph/lib v0.0.0-20230914103605-e3a8bc516ddc + github.com/sourcegraph/sourcegraph/lib v0.0.0-20231108085505-01324538d7f0 github.com/stretchr/testify v1.8.4 golang.org/x/net v0.12.0 golang.org/x/sync v0.3.0 @@ -86,7 +86,7 @@ require ( github.com/bufbuild/buf v1.4.0 // indirect github.com/charmbracelet/bubbletea v0.23.1 // direct github.com/charmbracelet/glamour v0.5.0 // indirect - github.com/cockroachdb/errors v1.10.0 // indirect + github.com/cockroachdb/errors v1.11.1 // indirect github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect github.com/cockroachdb/redact v1.1.5 // indirect github.com/containerd/console v1.0.3 // indirect @@ -96,7 +96,7 @@ require ( github.com/emicklei/go-restful/v3 v3.9.0 // indirect github.com/envoyproxy/protoc-gen-validate v0.10.1 // indirect github.com/fatih/color v1.15.0 // indirect - github.com/getsentry/sentry-go v0.22.0 // indirect + github.com/getsentry/sentry-go v0.25.0 // indirect github.com/ghodss/yaml v1.0.0 // indirect github.com/go-logr/logr v1.2.4 // indirect github.com/go-openapi/jsonpointer v0.19.6 // indirect @@ -109,7 +109,7 @@ require ( github.com/golang/protobuf v1.5.3 // indirect github.com/google/gnostic v0.5.7-v3refs // indirect github.com/google/gofuzz v1.2.0 // indirect - github.com/google/uuid v1.3.0 // indirect + github.com/google/uuid v1.3.1 // indirect github.com/googleapis/enterprise-certificate-proxy v0.2.5 // indirect github.com/googleapis/gax-go/v2 v2.12.0 // indirect github.com/gorilla/css v1.0.0 // indirect @@ -153,9 +153,9 @@ require ( github.com/pseudomuto/protoc-gen-doc v1.5.1 // indirect github.com/pseudomuto/protokit v0.2.0 // indirect github.com/rivo/uniseg v0.4.3 // indirect - github.com/rogpeppe/go-internal v1.10.0 // indirect + github.com/rogpeppe/go-internal v1.11.0 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect - github.com/sourcegraph/log v0.0.0-20230711093019-40c57b632cca // indirect + github.com/sourcegraph/log v0.0.0-20231018134238-fbadff7458bb // indirect github.com/spf13/cobra v1.7.0 // indirect github.com/spf13/pflag v1.0.5 // indirect github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect @@ -174,7 +174,7 @@ require ( golang.org/x/oauth2 v0.10.0 // indirect golang.org/x/sys v0.10.0 // indirect golang.org/x/term v0.10.0 // indirect - golang.org/x/text v0.11.0 // indirect + golang.org/x/text v0.13.0 // indirect golang.org/x/time v0.3.0 // indirect golang.org/x/tools v0.10.0 // indirect golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 // indirect diff --git a/go.sum b/go.sum index 401ff44d00..ce79356d40 100644 --- a/go.sum +++ b/go.sum @@ -86,8 +86,8 @@ github.com/cncf/xds/go v0.0.0-20210805033703-aa0b78936158/go.mod h1:eXthEFrGJvWH github.com/cncf/xds/go v0.0.0-20210922020428-25de7278fc84/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cockroachdb/apd v1.1.0/go.mod h1:8Sl8LxpKi29FqWXR16WEFZRNSz3SoPzUzeMeY4+DwBQ= -github.com/cockroachdb/errors v1.10.0 h1:lfxS8zZz1+OjtV4MtNWgboi/W5tyLEB6VQZBXN+0VUU= -github.com/cockroachdb/errors v1.10.0/go.mod h1:lknhIsEVQ9Ss/qKDBQS/UqFSvPQjOwNq2qyKAxtHRqE= +github.com/cockroachdb/errors v1.11.1 h1:xSEW75zKaKCWzR3OfxXUxgrk/NtT4G1MiOv5lWZazG8= +github.com/cockroachdb/errors v1.11.1/go.mod h1:8MUxA3Gi6b25tYlFEBGLf+D8aISL+M4MIpiWMSNRfxw= github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b h1:r6VH0faHjZeQy818SGhaone5OnYfxFR/+AzdY3sf5aE= github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= github.com/cockroachdb/redact v1.1.5 h1:u1PMllDkdFfPWaNGMyLD1+so+aq3uUItthCFqzwPJ30= @@ -132,8 +132,8 @@ github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs= github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw= github.com/frankban/quicktest v1.14.3 h1:FJKSZTDHjyhriyC81FLQ0LY93eSai0ZyR/ZIkd3ZUKE= github.com/frankban/quicktest v1.14.3/go.mod h1:mgiwOwqx65TmIk1wJ6Q7wvnVMocbUorkibMOrVTHZps= -github.com/getsentry/sentry-go v0.22.0 h1:XNX9zKbv7baSEI65l+H1GEJgSeIC1c7EN5kluWaP6dM= -github.com/getsentry/sentry-go v0.22.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= +github.com/getsentry/sentry-go v0.25.0 h1:q6Eo+hS+yoJlTO3uu/azhQadsD8V+jQn2D8VvX1eOyI= +github.com/getsentry/sentry-go v0.25.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA= github.com/go-logr/logr v1.2.0/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.2.4 h1:g01GSCwiDw2xSZfjJ2/T9M+S6pFdcNtFYsp+Y43HYDQ= @@ -189,8 +189,9 @@ github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE= github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= -github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= @@ -200,8 +201,8 @@ github.com/google/pprof v0.0.0-20230602150820-91b7bce49751/go.mod h1:Jh3hGz2jkYa github.com/google/s2a-go v0.1.4 h1:1kZ/sQM3srePvKs3tXAvQzo66XfcReoqFpIpIccE7Oc= github.com/google/s2a-go v0.1.4/go.mod h1:Ej+mSEMGRnqRzjc7VtF+jdBwYG5fuJfiZ8ELkjEwM0A= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= -github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.3.1 h1:KjJaJ9iWZ3jOFZIf1Lqf4laDRCasjl0BCmnEGxkdLb4= +github.com/google/uuid v1.3.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/googleapis/enterprise-certificate-proxy v0.2.5 h1:UR4rDjcgpgEnqpIEvkiqTYKBCKLNmlge2eVjoZfySzM= github.com/googleapis/enterprise-certificate-proxy v0.2.5/go.mod h1:RxW0N9901Cko1VOCW3SXCpWP+mlIEkk2tP7jnHy9a3w= github.com/googleapis/gax-go/v2 v2.12.0 h1:A+gCJKdRfqXkr+BIRGtZLibNXf0m1f9E4HG56etFpas= @@ -401,8 +402,8 @@ github.com/rivo/uniseg v0.4.3/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUc github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= -github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= -github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= +github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= +github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA= github.com/rs/xid v1.2.1/go.mod h1:+uKXf+4Djp6Md1KODXJxgGQPKngRmWyn10oCKFzNHOQ= github.com/rs/zerolog v1.13.0/go.mod h1:YbFCdg8HfsridGWAh22vktObvhZbQsZXe4/zB0OKkWU= github.com/rs/zerolog v1.15.0/go.mod h1:xYTKnLHcpfU2225ny5qZjxnj9NvkumZYjJHlAThCjNc= @@ -421,12 +422,12 @@ github.com/sourcegraph/go-diff v0.6.2-0.20221123165719-f8cd299c40f3 h1:11miag7hl github.com/sourcegraph/go-diff v0.6.2-0.20221123165719-f8cd299c40f3/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= -github.com/sourcegraph/log v0.0.0-20230711093019-40c57b632cca h1:VwYrG1+YNyOD3nSb0M84ISMQiOOS/5Js05HqU1iNFSU= -github.com/sourcegraph/log v0.0.0-20230711093019-40c57b632cca/go.mod h1:IDp09QkoqS8Z3CyN2RW6vXjgABkNpDbyjLIHNQwQ8P8= +github.com/sourcegraph/log v0.0.0-20231018134238-fbadff7458bb h1:tHKdC+bXxxGJ0cy/R06kg6Z0zqwVGOWMx8uWsIwsaoY= +github.com/sourcegraph/log v0.0.0-20231018134238-fbadff7458bb/go.mod h1:IDp09QkoqS8Z3CyN2RW6vXjgABkNpDbyjLIHNQwQ8P8= github.com/sourcegraph/scip v0.3.1-0.20230627154934-45df7f6d33fc h1:o+eq0cjVV3B5ngIBF04Lv3GwttKOuYFF5NTcfXWXzfA= github.com/sourcegraph/scip v0.3.1-0.20230627154934-45df7f6d33fc/go.mod h1:7ZKAtLIUmiMvOIgG5LMcBxdtBXVa0v2GWC4Hm1ASYQ0= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20230914103605-e3a8bc516ddc h1:0hAo7bbfcF3uujbq2eNl2DpN6zUrjacWAK3iSan5Q0k= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20230914103605-e3a8bc516ddc/go.mod h1:r5UrJ7GztZRFu/LlF5lNS5XzAsnYdGphS4CJEm4Lnts= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20231108085505-01324538d7f0 h1:LZdpNzUvaOw9GaQ59cGRvvuXE8rzNy4I2hL2Z9zZ6WI= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20231108085505-01324538d7f0/go.mod h1:VvoU1TLgHCyaEvFb2plbV14RqAqigTEebR20oapEsJc= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I= @@ -588,8 +589,8 @@ golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.11.0 h1:LAntKIrcmeSKERyiOh0XMV39LXS8IE9UL2yP7+f5ij4= -golang.org/x/text v0.11.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= +golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k= +golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4= golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= From 437d0ec6768aa9d0fee988c594a6eb931eda9287 Mon Sep 17 00:00:00 2001 From: Bolaji Olajide <25608335+BolajiOlajide@users.noreply.github.com> Date: Wed, 8 Nov 2023 12:59:36 +0100 Subject: [PATCH 373/647] changelog update 5.2.1 (#1046) --- CHANGELOG.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0815ac1714..86234db393 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,10 +17,14 @@ All notable changes to `src-cli` are documented in this file. ### Fixed -- The fork attribute in changesetTemplate is now acknowleged when creating a batch change via `src-cli`. [#58156](https://github.com/sourcegraph/sourcegraph/pull/58156) - ### Removed +## 5.2.1 + +### Fixed + +- The fork attribute in changesetTemplate is now acknowleged when creating a batch change via `src-cli`. [#58156](https://github.com/sourcegraph/sourcegraph/pull/58156) + ## 5.2.0 ### Added From 8df54900deaa1c3395a1f3d57061b1dc4bc14fe8 Mon Sep 17 00:00:00 2001 From: Bolaji Olajide <25608335+BolajiOlajide@users.noreply.github.com> Date: Wed, 8 Nov 2023 19:02:01 +0100 Subject: [PATCH 374/647] code-search: remove -i flag (#1047) --- .github/workflows/goreleaser.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index 7781883d55..e5f13c93e6 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -178,7 +178,7 @@ jobs: uses: actions/setup-go@v3 with: go-version: 1.20 - - run: go test -i ./... + - run: go test ./... - run: go test -race -v ./... - run: echo "${DOCKER_PASSWORD}" | docker login -u=$DOCKER_USERNAME --password-stdin env: From f2f0948063d89d82e4dc8d1a7032b9506a265e98 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Wed, 8 Nov 2023 19:27:03 +0000 Subject: [PATCH 375/647] goreleaser: quote go version number (#1048) * quote go version number * set version to 1.20.x string --- .github/workflows/goreleaser-check.yml | 2 +- .github/workflows/goreleaser.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/goreleaser-check.yml b/.github/workflows/goreleaser-check.yml index 0a15a41611..b7032400be 100644 --- a/.github/workflows/goreleaser-check.yml +++ b/.github/workflows/goreleaser-check.yml @@ -16,7 +16,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v3 with: - go-version: 1.20 + go-version: 1.20.x - name: Check GoReleaser config uses: goreleaser/goreleaser-action@v4 with: diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index e5f13c93e6..1ad737ceac 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -177,7 +177,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v3 with: - go-version: 1.20 + go-version: 1.20.x - run: go test ./... - run: go test -race -v ./... - run: echo "${DOCKER_PASSWORD}" | docker login -u=$DOCKER_USERNAME --password-stdin From d53e95f98b1961444cf61baa11645a3ccc2e0416 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Wed, 13 Dec 2023 15:17:14 +0200 Subject: [PATCH 376/647] pr-auditor: use new token (#1053) --- .github/workflows/pr-auditor.yml | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/.github/workflows/pr-auditor.yml b/.github/workflows/pr-auditor.yml index bdc06f3bbf..e7ec2d483b 100644 --- a/.github/workflows/pr-auditor.yml +++ b/.github/workflows/pr-auditor.yml @@ -3,19 +3,20 @@ name: pr-auditor on: pull_request_target: types: [ closed, edited, opened, synchronize, ready_for_review ] + workflow_dispatch: jobs: check-pr: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: repository: 'sourcegraph/pr-auditor' - uses: actions/setup-go@v4 - with: { go-version: '1.20' } + with: { go-version: '1.21' } - run: './check-pr.sh' env: GITHUB_EVENT_PATH: ${{ env.GITHUB_EVENT_PATH }} - GITHUB_TOKEN: ${{ github.token }} + GITHUB_TOKEN: ${{ secrets.PR_AUDITOR_TOKEN }} GITHUB_RUN_URL: https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }} From 0621a6386f97c78991f71f879e3e9ba4300d98c7 Mon Sep 17 00:00:00 2001 From: Camden Cheek Date: Mon, 1 Jan 2024 14:40:18 -0700 Subject: [PATCH 377/647] populate branch name during template resolution (#1054) --- internal/batches/executor/run_steps.go | 8 ++++++-- internal/batches/util/repo.go | 3 ++- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/internal/batches/executor/run_steps.go b/internal/batches/executor/run_steps.go index 848362a3b3..3d3bbd9d60 100644 --- a/internal/batches/executor/run_steps.go +++ b/internal/batches/executor/run_steps.go @@ -141,8 +141,12 @@ func RunSteps(ctx context.Context, opts *RunStepsOpts) (stepResults []execution. stepContext := template.StepContext{ BatchChange: *opts.Task.BatchChangeAttributes, - Repository: util.NewTemplatingRepo(opts.Task.Repository.Name, opts.Task.Repository.FileMatches), - Outputs: lastOutputs, + Repository: util.NewTemplatingRepo( + opts.Task.Repository.Name, + opts.Task.Repository.Branch.Name, + opts.Task.Repository.FileMatches, + ), + Outputs: lastOutputs, Steps: template.StepsContext{ Path: opts.Task.Path, Changes: previousStepResult.ChangedFiles, diff --git a/internal/batches/util/repo.go b/internal/batches/util/repo.go index 705784a972..cdd6cc7271 100644 --- a/internal/batches/util/repo.go +++ b/internal/batches/util/repo.go @@ -10,13 +10,14 @@ import ( // NewTemplatingRepo transforms a given *graphql.Repository into a // template.Repository. -func NewTemplatingRepo(repoName string, fileMatches map[string]bool) template.Repository { +func NewTemplatingRepo(repoName string, branch string, fileMatches map[string]bool) template.Repository { matches := make([]string, 0, len(fileMatches)) for path := range fileMatches { matches = append(matches, path) } return template.Repository{ Name: repoName, + Branch: branch, FileMatches: matches, } } From 1798cc33178b9f40c0d76e2703c39d5dd9336f54 Mon Sep 17 00:00:00 2001 From: Will Dollman Date: Fri, 2 Feb 2024 11:44:13 +0000 Subject: [PATCH 378/647] Update go.mod to fix several vulnerabilities (#1057) * go get golang.org/x/crypto@v0.17.0 * go get golang.org/x/net@v0.17.0 * go get google.golang.org/grpc@v1.56.3 * go mod tidy * Update changelog --- CHANGELOG.md | 2 ++ go.mod | 12 ++++++------ go.sum | 24 ++++++++++++------------ 3 files changed, 20 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 86234db393..ee6bedb8be 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,8 @@ All notable changes to `src-cli` are documented in this file. ### Fixed +- Updated dependencies to address CVE-2023-39325 and GHSA-m425-mq94-257g + ### Removed ## 5.2.1 diff --git a/go.mod b/go.mod index 16fb454228..f69c6704a6 100644 --- a/go.mod +++ b/go.mod @@ -32,7 +32,7 @@ require ( github.com/sourcegraph/scip v0.3.1-0.20230627154934-45df7f6d33fc github.com/sourcegraph/sourcegraph/lib v0.0.0-20231108085505-01324538d7f0 github.com/stretchr/testify v1.8.4 - golang.org/x/net v0.12.0 + golang.org/x/net v0.17.0 golang.org/x/sync v0.3.0 google.golang.org/api v0.132.0 google.golang.org/protobuf v1.31.0 @@ -169,18 +169,18 @@ require ( go.uber.org/atomic v1.11.0 // indirect go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.24.0 // indirect - golang.org/x/crypto v0.11.0 // indirect + golang.org/x/crypto v0.17.0 // indirect golang.org/x/mod v0.11.0 // indirect golang.org/x/oauth2 v0.10.0 // indirect - golang.org/x/sys v0.10.0 // indirect - golang.org/x/term v0.10.0 // indirect - golang.org/x/text v0.13.0 // indirect + golang.org/x/sys v0.15.0 // indirect + golang.org/x/term v0.15.0 // indirect + golang.org/x/text v0.14.0 // indirect golang.org/x/time v0.3.0 // indirect golang.org/x/tools v0.10.0 // indirect golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 // indirect google.golang.org/appengine v1.6.7 // indirect google.golang.org/genproto v0.0.0-20230717213848-3f92550aa753 // indirect - google.golang.org/grpc v1.56.2 // indirect + google.golang.org/grpc v1.56.3 // indirect gopkg.in/inf.v0 v0.9.1 // direct gopkg.in/yaml.v2 v2.4.0 // indirect k8s.io/klog/v2 v2.90.1 // indirect diff --git a/go.sum b/go.sum index ce79356d40..0feb340c2d 100644 --- a/go.sum +++ b/go.sum @@ -497,8 +497,8 @@ golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e/go.mod h1:GvvjBRRGRdwPK5y golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20220314234659-1baeb1ce4c0b/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= -golang.org/x/crypto v0.11.0 h1:6Ewdq3tDic1mg5xRO4milcWCfMVQhI4NkqWWvqejpuA= -golang.org/x/crypto v0.11.0/go.mod h1:xgJhtzW8F9jGdVFWZESrid1U1bjeNy4zgy5cRr/CIio= +golang.org/x/crypto v0.17.0 h1:r8bRNjWL3GshPW3gkd+RpvzWrZAwPS49OmTGZ/uhM4k= +golang.org/x/crypto v0.17.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= @@ -528,8 +528,8 @@ golang.org/x/net v0.0.0-20210614182718-04defd469f4e/go.mod h1:9nx3DQGgdP8bBQD5qx golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.3.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE= -golang.org/x/net v0.12.0 h1:cfawfvKITfUsFCeJIHJrbSxpeu/E81khclypR0GVT50= -golang.org/x/net v0.12.0/go.mod h1:zEVYFnQC7m/vmpQFELhcD1EWkZlX69l4oqgmer6hfKA= +golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM= +golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.10.0 h1:zHCpF2Khkwy4mMB4bv0U37YtJdTGW8jI0glAApi0Kh8= @@ -573,14 +573,14 @@ golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220829200755-d48e67d00261/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.10.0 h1:SqMFp9UcQJZa+pmYuAKjd9xq1f0j5rLcDIk0mj4qAsA= -golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc= +golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.3.0/go.mod h1:q750SLmJuPmVoN1blW3UFBPREJfb1KmY3vwxfr+nFDA= -golang.org/x/term v0.10.0 h1:3R7pNqamzBraeqj/Tj8qt1aQ2HpmlC+Cx/qL/7hn4/c= -golang.org/x/term v0.10.0/go.mod h1:lpqdcUyK/oCiQxvxVrppt5ggO2KCZ5QblwqPnfZ6d5o= +golang.org/x/term v0.15.0 h1:y/Oo/a/q3IXu26lQgl04j/gjuBDOBlx7X6Om1j2CPW4= +golang.org/x/term v0.15.0/go.mod h1:BDl952bC7+uMoWR75FIrCDx79TPU9oHkTZ9yRbYOrX0= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= @@ -589,8 +589,8 @@ golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k= -golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= +golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= +golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4= golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -643,8 +643,8 @@ google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= google.golang.org/grpc v1.38.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= google.golang.org/grpc v1.45.0/go.mod h1:lN7owxKUQEqMfSyQikvvk5tf/6zMPsrK+ONuO11+0rQ= -google.golang.org/grpc v1.56.2 h1:fVRFRnXvU+x6C4IlHZewvJOVHoOv1TUuQyoRsYnB4bI= -google.golang.org/grpc v1.56.2/go.mod h1:I9bI3vqKfayGqPUAwGdOSu7kt6oIJLixfffKrpXqQ9s= +google.golang.org/grpc v1.56.3 h1:8I4C0Yq1EjstUzUJzpcRVbuYA2mODtEmpWiQoN/b2nc= +google.golang.org/grpc v1.56.3/go.mod h1:I9bI3vqKfayGqPUAwGdOSu7kt6oIJLixfffKrpXqQ9s= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= From 180d4e089567537abee759780ab9978f821fbbdb Mon Sep 17 00:00:00 2001 From: Keegan Carruthers-Smith Date: Wed, 7 Feb 2024 13:06:43 +0200 Subject: [PATCH 379/647] changelog: cut sourcegraph@5.3.0 (#1058) --- CHANGELOG.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index ee6bedb8be..1e6d8b71dd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,16 @@ All notable changes to `src-cli` are documented in this file. ### Fixed +### Removed + +## 5.3.0 + +### Added + +### Changed + +### Fixed + - Updated dependencies to address CVE-2023-39325 and GHSA-m425-mq94-257g ### Removed From d29ee42bcbd5c3106cb999908aa0f76d4a39a8d8 Mon Sep 17 00:00:00 2001 From: Noah S-C Date: Fri, 23 Feb 2024 16:32:49 +0000 Subject: [PATCH 380/647] chore: use scip-go instead of lsif-go for precise indexing in CI (#1060) --- .github/workflows/lsif.yml | 13 ------------- .github/workflows/scip.yml | 18 ++++++++++++++++++ 2 files changed, 18 insertions(+), 13 deletions(-) delete mode 100644 .github/workflows/lsif.yml create mode 100644 .github/workflows/scip.yml diff --git a/.github/workflows/lsif.yml b/.github/workflows/lsif.yml deleted file mode 100644 index 62db1f0b9d..0000000000 --- a/.github/workflows/lsif.yml +++ /dev/null @@ -1,13 +0,0 @@ -name: LSIF -on: - - push -jobs: - lsif-go: - runs-on: ubuntu-latest - container: sourcegraph/lsif-go - steps: - - uses: actions/checkout@a12a3943b4bdde767164f792f33f40b04645d846 # tag=v3 - - name: Generate LSIF data - run: lsif-go - - name: Upload LSIF data - run: src lsif upload -github-token=${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/scip.yml b/.github/workflows/scip.yml new file mode 100644 index 0000000000..3330441dd8 --- /dev/null +++ b/.github/workflows/scip.yml @@ -0,0 +1,18 @@ +name: SCIP +'on': + - push +jobs: + scip-go: + runs-on: ubuntu-latest + container: sourcegraph/scip-go + steps: + - uses: actions/checkout@v3 + - name: Get src-cli + run: curl -L https://sourcegraph.com/.api/src-cli/src_linux_amd64 -o /usr/local/bin/src; + chmod +x /usr/local/bin/src + - name: Set directory to safe for git + run: git config --global --add safe.directory $GITHUB_WORKSPACE + - name: Generate SCIP data + run: scip-go + - name: Upload SCIP data + run: src code-intel upload -github-token=${{ secrets.GITHUB_TOKEN }} From 43ca41b5b171293802416f83be629fbc05464494 Mon Sep 17 00:00:00 2001 From: Bolaji Olajide <25608335+BolajiOlajide@users.noreply.github.com> Date: Fri, 8 Mar 2024 17:48:09 -0600 Subject: [PATCH 381/647] npm: add readme when prepacking (#1059) --- npm-distribution/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/npm-distribution/package.json b/npm-distribution/package.json index 4d90acd9a7..73a51436c5 100644 --- a/npm-distribution/package.json +++ b/npm-distribution/package.json @@ -7,7 +7,7 @@ "license": "Apache-2.0", "scripts": { "install": "node install.js", - "prepack": "cp ../LICENSE ." + "prepack": "cp ../LICENSE . && cp ../README.md ." }, "main": "src.js", "bin": { From 5db13a9b5671a687401263434bcee16d8a73d63c Mon Sep 17 00:00:00 2001 From: Varun Gandhi Date: Thu, 28 Mar 2024 23:44:47 +0800 Subject: [PATCH 382/647] Add CODEOWNERS file (#1061) Based on prior discussion in [Slack](https://sourcegraph.slack.com/archives/C05EA9KQUTA/p1709599076169619). --- CODEOWNERS | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 CODEOWNERS diff --git a/CODEOWNERS b/CODEOWNERS new file mode 100644 index 0000000000..71c2c03ab9 --- /dev/null +++ b/CODEOWNERS @@ -0,0 +1,13 @@ +cmd/src/lsif* @sourcegraph/team-graph +cmd/src/code_intel* @sourcegraph/team-graph + +cmd/src/search* @sourcegraph/search-platform + +cmd/src/extsvc* @sourcegraph/source +cmd/src/servegit* @sourcegraph/source +cmd/src/users* @sourcegraph/source + +cmd/src/batch* @sourcegraph/code-search + +# Shepherd team for everything else +* @sourcegraph/code-search From 9a8dee79321931fec56a5f12a67506c270e0e1d5 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Thu, 28 Mar 2024 10:00:55 -0600 Subject: [PATCH 383/647] Update dependency aspect_bazel_lib to v1.42.1 (#995) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- WORKSPACE | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/WORKSPACE b/WORKSPACE index 523cb75747..3a8ed3cb17 100644 --- a/WORKSPACE +++ b/WORKSPACE @@ -15,9 +15,9 @@ bazel_skylib_workspace() http_archive( name = "aspect_bazel_lib", - sha256 = "2518c757715d4f5fc7cc7e0a68742dd1155eaafc78fb9196b8a18e13a738cea2", - strip_prefix = "bazel-lib-1.28.0", - url = "https://github.com/aspect-build/bazel-lib/releases/download/v1.28.0/bazel-lib-v1.28.0.tar.gz", + sha256 = "d0203b032a26086729ade48c46bc6159fb4aa825d9a5bdf2d972449bcbefe967", + strip_prefix = "bazel-lib-1.42.1", + url = "https://github.com/aspect-build/bazel-lib/releases/download/v1.42.1/bazel-lib-v1.42.1.tar.gz", ) http_archive( From a136d961379c775280dd8505a7a5829b8b71a363 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 1 Apr 2024 07:32:10 -0600 Subject: [PATCH 384/647] Update dependency aspect_bazel_lib to v1.42.2 (#1062) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- WORKSPACE | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/WORKSPACE b/WORKSPACE index 3a8ed3cb17..da9035d973 100644 --- a/WORKSPACE +++ b/WORKSPACE @@ -15,9 +15,9 @@ bazel_skylib_workspace() http_archive( name = "aspect_bazel_lib", - sha256 = "d0203b032a26086729ade48c46bc6159fb4aa825d9a5bdf2d972449bcbefe967", - strip_prefix = "bazel-lib-1.42.1", - url = "https://github.com/aspect-build/bazel-lib/releases/download/v1.42.1/bazel-lib-v1.42.1.tar.gz", + sha256 = "f9a0bb072aef719859aae5ad37722e97812ffffb263fd56a36cd8614a2e5d199", + strip_prefix = "bazel-lib-1.42.2", + url = "https://github.com/aspect-build/bazel-lib/releases/download/v1.42.2/bazel-lib-v1.42.2.tar.gz", ) http_archive( From f07c2e90eefc836766fb4e571b6ff2c6be7e6f15 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 1 Apr 2024 07:32:41 -0600 Subject: [PATCH 385/647] Update golang Docker tag to v1.22.1 (#723) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .tool-versions | 2 +- Dockerfile | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.tool-versions b/.tool-versions index ce1252fd18..939554bd1b 100644 --- a/.tool-versions +++ b/.tool-versions @@ -1,3 +1,3 @@ -golang 1.20.8 +golang 1.22.1 shfmt 3.2.0 shellcheck 0.7.1 diff --git a/Dockerfile b/Dockerfile index 6f04b05964..b8b6c61fa0 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,7 +4,7 @@ # # Nothing fancy here: we copy in the source code and build on the Alpine Go # image. Refer to .dockerignore to get a sense of what we're not going to copy. -FROM golang:1.19.8-alpine@sha256:841c160ed35923d96c95c52403c4e6db5decd9cbce034aa851e412ade5d4b74f as builder +FROM golang:1.22.1-alpine@sha256:89c315d402dcae8b1b25daa52379d5bac33610acf0389f163321572983da95e9 as builder COPY . /src WORKDIR /src From 3096fd4d895f017a2eb343d3e7496267f8736328 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 1 Apr 2024 07:45:29 -0600 Subject: [PATCH 386/647] Update dependency bazel_gazelle to v0.35.0 (#996) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- WORKSPACE | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/WORKSPACE b/WORKSPACE index da9035d973..53aa85bc8d 100644 --- a/WORKSPACE +++ b/WORKSPACE @@ -31,10 +31,10 @@ http_archive( http_archive( name = "bazel_gazelle", - sha256 = "ecba0f04f96b4960a5b250c8e8eeec42281035970aa8852dda73098274d14a1d", + sha256 = "32938bda16e6700063035479063d9d24c60eda8d79fd4739563f50d331cb3209", urls = [ - "https://mirror.bazel.build/github.com/bazelbuild/bazel-gazelle/releases/download/v0.29.0/bazel-gazelle-v0.29.0.tar.gz", - "https://github.com/bazelbuild/bazel-gazelle/releases/download/v0.29.0/bazel-gazelle-v0.29.0.tar.gz", + "https://mirror.bazel.build/github.com/bazelbuild/bazel-gazelle/releases/download/v0.35.0/bazel-gazelle-v0.35.0.tar.gz", + "https://github.com/bazelbuild/bazel-gazelle/releases/download/v0.35.0/bazel-gazelle-v0.35.0.tar.gz", ], ) From 9e50e22fd7e95ced10fb86a3dfe68717b82f7ff5 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 1 Apr 2024 07:45:46 -0600 Subject: [PATCH 387/647] Update dependency bazel_skylib to v1.5.0 (#997) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- WORKSPACE | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/WORKSPACE b/WORKSPACE index 53aa85bc8d..14e4ab6779 100644 --- a/WORKSPACE +++ b/WORKSPACE @@ -2,10 +2,10 @@ load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") http_archive( name = "bazel_skylib", - sha256 = "74d544d96f4a5bb630d465ca8bbcfe231e3594e5aae57e1edbf17a6eb3ca2506", + sha256 = "cd55a062e763b9349921f0f5db8c3933288dc8ba4f76dd9416aac68acee3cb94", urls = [ - "https://mirror.bazel.build/github.com/bazelbuild/bazel-skylib/releases/download/1.3.0/bazel-skylib-1.3.0.tar.gz", - "https://github.com/bazelbuild/bazel-skylib/releases/download/1.3.0/bazel-skylib-1.3.0.tar.gz", + "https://mirror.bazel.build/github.com/bazelbuild/bazel-skylib/releases/download/1.5.0/bazel-skylib-1.5.0.tar.gz", + "https://github.com/bazelbuild/bazel-skylib/releases/download/1.5.0/bazel-skylib-1.5.0.tar.gz", ], ) From 2352d0a183df2b294bde21e20138188558f4775e Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 1 Apr 2024 07:46:07 -0600 Subject: [PATCH 388/647] Update dependency io_bazel_rules_go to v0.46.0 (#998) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- WORKSPACE | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/WORKSPACE b/WORKSPACE index 14e4ab6779..ee77c61b90 100644 --- a/WORKSPACE +++ b/WORKSPACE @@ -22,10 +22,10 @@ http_archive( http_archive( name = "io_bazel_rules_go", - sha256 = "dd926a88a564a9246713a9c00b35315f54cbd46b31a26d5d8fb264c07045f05d", + sha256 = "80a98277ad1311dacd837f9b16db62887702e9f1d1c4c9f796d0121a46c8e184", urls = [ - "https://mirror.bazel.build/github.com/bazelbuild/rules_go/releases/download/v0.38.1/rules_go-v0.38.1.zip", - "https://github.com/bazelbuild/rules_go/releases/download/v0.38.1/rules_go-v0.38.1.zip", + "https://mirror.bazel.build/github.com/bazelbuild/rules_go/releases/download/v0.46.0/rules_go-v0.46.0.zip", + "https://github.com/bazelbuild/rules_go/releases/download/v0.46.0/rules_go-v0.46.0.zip", ], ) From e1741274b5e51d335d14ec59262f298d78d46d8d Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 1 Apr 2024 08:20:01 -0600 Subject: [PATCH 389/647] Update dependency tar to ^6.2.1 (#877) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- npm-distribution/package.json | 4 ++-- npm-distribution/yarn.lock | 32 +++++++++++++++++++++----------- 2 files changed, 23 insertions(+), 13 deletions(-) diff --git a/npm-distribution/package.json b/npm-distribution/package.json index 73a51436c5..2be7e822d2 100644 --- a/npm-distribution/package.json +++ b/npm-distribution/package.json @@ -17,10 +17,10 @@ "sourcegraph" ], "dependencies": { - "tar": "^6.1.11" + "tar": "^6.2.1" }, "devDependencies": { - "@types/tar": "6.1.3" + "@types/tar": "6.1.11" }, "private": false } diff --git a/npm-distribution/yarn.lock b/npm-distribution/yarn.lock index ffeba76eca..078133553b 100644 --- a/npm-distribution/yarn.lock +++ b/npm-distribution/yarn.lock @@ -7,13 +7,13 @@ resolved "https://registry.yarnpkg.com/@types/node/-/node-17.0.36.tgz#c0d5f2fe76b47b63e0e0efc3d2049a9970d68794" integrity sha512-V3orv+ggDsWVHP99K3JlwtH20R7J4IhI1Kksgc+64q5VxgfRkQG8Ws3MFm/FZOKDYGy9feGFlZ70/HpCNe9QaA== -"@types/tar@6.1.3": - version "6.1.3" - resolved "https://registry.yarnpkg.com/@types/tar/-/tar-6.1.3.tgz#46a2ce7617950c4852dfd7e9cd41aa8161b9d750" - integrity sha512-YzDOr5kdAeqS8dcO6NTTHTMJ44MUCBDoLEIyPtwEn7PssKqUYL49R1iCVJPeiPzPlKi6DbH33eZkpeJ27e4vHg== +"@types/tar@6.1.11": + version "6.1.11" + resolved "https://registry.yarnpkg.com/@types/tar/-/tar-6.1.11.tgz#48de9ccee8db37efb0d5a9f288567fc0378cb734" + integrity sha512-ThA1WD8aDdVU4VLuyq5NEqriwXErF5gEIJeyT6gHBWU7JtSmW2a5qjNv3/vR82O20mW+1vhmeZJfBQPT3HCugg== dependencies: "@types/node" "*" - minipass "^3.3.5" + minipass "^4.0.0" chownr@^2.0.0: version "2.0.0" @@ -27,13 +27,23 @@ fs-minipass@^2.0.0: dependencies: minipass "^3.0.0" -minipass@^3.0.0, minipass@^3.3.5: +minipass@^3.0.0: version "3.3.5" resolved "https://registry.yarnpkg.com/minipass/-/minipass-3.3.5.tgz#6da7e53a48db8a856eeb9153d85b230a2119e819" integrity sha512-rQ/p+KfKBkeNwo04U15i+hOwoVBVmekmm/HcfTkTN2t9pbQKCMm4eN5gFeqgrrSp/kH/7BYYhTIHOxGqzbBPaA== dependencies: yallist "^4.0.0" +minipass@^4.0.0: + version "4.2.8" + resolved "https://registry.yarnpkg.com/minipass/-/minipass-4.2.8.tgz#f0010f64393ecfc1d1ccb5f582bcaf45f48e1a3a" + integrity sha512-fNzuVyifolSLFL4NzpF+wEF4qrgqaaKX0haXPQEdQ7NKAN+WecoKMHV09YcuL/DHxrUsYQOK3MiuDf7Ip2OXfQ== + +minipass@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/minipass/-/minipass-5.0.0.tgz#3e9788ffb90b694a5d0ec94479a45b5d8738133d" + integrity sha512-3FnjYuehv9k6ovOEbyOswadCDPX1piCfhV8ncmYtHOjuPwylVWsghTLo7rabjC3Rx5xD4HDx8Wm1xnMF7S5qFQ== + minizlib@^2.1.1: version "2.1.2" resolved "https://registry.yarnpkg.com/minizlib/-/minizlib-2.1.2.tgz#e90d3466ba209b932451508a11ce3d3632145931" @@ -47,14 +57,14 @@ mkdirp@^1.0.3: resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-1.0.4.tgz#3eb5ed62622756d79a5f0e2a221dfebad75c2f7e" integrity sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw== -tar@^6.1.11: - version "6.1.11" - resolved "https://registry.yarnpkg.com/tar/-/tar-6.1.11.tgz#6760a38f003afa1b2ffd0ffe9e9abbd0eab3d621" - integrity sha512-an/KZQzQUkZCkuoAA64hM92X0Urb6VpRhAFllDzz44U2mcD5scmT3zBc4VgVpkugF580+DQn8eAFSyoQt0tznA== +tar@^6.2.1: + version "6.2.1" + resolved "https://registry.yarnpkg.com/tar/-/tar-6.2.1.tgz#717549c541bc3c2af15751bea94b1dd068d4b03a" + integrity sha512-DZ4yORTwrbTj/7MZYq2w+/ZFdI6OZ/f9SFHR+71gIVUZhOQPHzVCLpvRnPgyaMpfWxxk/4ONva3GQSyNIKRv6A== dependencies: chownr "^2.0.0" fs-minipass "^2.0.0" - minipass "^3.0.0" + minipass "^5.0.0" minizlib "^2.1.1" mkdirp "^1.0.3" yallist "^4.0.0" From b1f6221058bc517d32a83000aee3e2e6a6fff210 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 1 Apr 2024 08:20:24 -0600 Subject: [PATCH 390/647] Update actions/setup-node action to v4 (#1044) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .github/workflows/goreleaser.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index 1ad737ceac..806883d1aa 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -244,7 +244,7 @@ jobs: uses: actions/checkout@v3 with: fetch-depth: 0 - - uses: actions/setup-node@v3 + - uses: actions/setup-node@v4 with: node-version: 16 registry-url: 'https://registry.npmjs.org' From eabf75d054567a42606351ba36e68599799045fe Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 1 Apr 2024 09:14:43 -0600 Subject: [PATCH 391/647] Update actions/checkout action to v4 (#1036) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .github/workflows/docker.yml | 2 +- .github/workflows/go-ci.yml | 2 +- .github/workflows/go-lint.yml | 2 +- .github/workflows/goreleaser-check.yml | 2 +- .github/workflows/goreleaser.yml | 12 ++++++------ .github/workflows/scip.yml | 2 +- 6 files changed, 11 insertions(+), 11 deletions(-) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 3e5462220a..4ec074b189 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -15,7 +15,7 @@ jobs: runs-on: ubuntu-20.04 steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 # We need buildx to be able to build a multi-architecture image. - name: Set up Docker buildx diff --git a/.github/workflows/go-ci.yml b/.github/workflows/go-ci.yml index 43a586f5cc..4851f27656 100644 --- a/.github/workflows/go-ci.yml +++ b/.github/workflows/go-ci.yml @@ -12,7 +12,7 @@ jobs: runs-on: ${{ matrix.os }} steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Set up Go uses: actions/setup-go@v3 with: diff --git a/.github/workflows/go-lint.yml b/.github/workflows/go-lint.yml index 58addc04fb..068ef0e510 100644 --- a/.github/workflows/go-lint.yml +++ b/.github/workflows/go-lint.yml @@ -8,7 +8,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Set up Go uses: actions/setup-go@v3 with: diff --git a/.github/workflows/goreleaser-check.yml b/.github/workflows/goreleaser-check.yml index b7032400be..20e1ac5075 100644 --- a/.github/workflows/goreleaser-check.yml +++ b/.github/workflows/goreleaser-check.yml @@ -10,7 +10,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: fetch-depth: 0 - name: Set up Go diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index 806883d1aa..0bb4dbbbe2 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -47,7 +47,7 @@ jobs: second_latest_tag: ${{ env.second_latest_tag }} steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: fetch-depth: 0 - name: Set current tag, latest (highest version) tag, and second latest tag @@ -103,7 +103,7 @@ jobs: echo "latest_tag=${{ needs.release_type.outputs.latest_tag }}" >> $GITHUB_ENV echo "second_latest_tag=${{ needs.release_type.outputs.second_latest_tag }}" >> $GITHUB_ENV - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: fetch-depth: 0 - name: Set versioning variables @@ -116,7 +116,7 @@ jobs: echo "Versioned formula file: ${{ env.versioned_formula_file }}" echo "Versioned classname: ${{ env.versioned_classname }}" - name: Checkout Homebrew tap - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: repository: sourcegraph/homebrew-src-cli fetch-depth: 0 @@ -171,7 +171,7 @@ jobs: run: | echo "Goreleaser config file: ${{ env.config_file }}" - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: fetch-depth: 0 - name: Set up Go @@ -220,7 +220,7 @@ jobs: echo "Old symlink: ${{ env.old_symlink_name }}" echo "New symlink: ${{ env.new_symlink_name }}" - name: Checkout Homebrew tap - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: repository: sourcegraph/homebrew-src-cli fetch-depth: 0 @@ -241,7 +241,7 @@ jobs: needs: goreleaser steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: fetch-depth: 0 - uses: actions/setup-node@v4 diff --git a/.github/workflows/scip.yml b/.github/workflows/scip.yml index 3330441dd8..fa2a5655de 100644 --- a/.github/workflows/scip.yml +++ b/.github/workflows/scip.yml @@ -6,7 +6,7 @@ jobs: runs-on: ubuntu-latest container: sourcegraph/scip-go steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Get src-cli run: curl -L https://sourcegraph.com/.api/src-cli/src_linux_amd64 -o /usr/local/bin/src; chmod +x /usr/local/bin/src From 612873dba9ff59f4d5b494b505788cfc94cb6591 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 1 Apr 2024 11:54:15 -0600 Subject: [PATCH 392/647] Update dependency shfmt to v3.8.0 (#895) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .tool-versions | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.tool-versions b/.tool-versions index 939554bd1b..0779ef3d61 100644 --- a/.tool-versions +++ b/.tool-versions @@ -1,3 +1,3 @@ golang 1.22.1 -shfmt 3.2.0 +shfmt 3.8.0 shellcheck 0.7.1 From 00d702f23564615f9aa80107b2ba4c577e03bf94 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 1 Apr 2024 12:00:02 -0600 Subject: [PATCH 393/647] Update actions/setup-go action to v5 (#1052) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .github/workflows/go-ci.yml | 2 +- .github/workflows/go-lint.yml | 2 +- .github/workflows/goreleaser-check.yml | 2 +- .github/workflows/goreleaser.yml | 2 +- .github/workflows/pr-auditor.yml | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/go-ci.yml b/.github/workflows/go-ci.yml index 4851f27656..dfe8d1b909 100644 --- a/.github/workflows/go-ci.yml +++ b/.github/workflows/go-ci.yml @@ -14,7 +14,7 @@ jobs: - name: Checkout uses: actions/checkout@v4 - name: Set up Go - uses: actions/setup-go@v3 + uses: actions/setup-go@v5 with: go-version: ${{ matrix.go-version }} - run: go test -race -v ./... diff --git a/.github/workflows/go-lint.yml b/.github/workflows/go-lint.yml index 068ef0e510..3126381565 100644 --- a/.github/workflows/go-lint.yml +++ b/.github/workflows/go-lint.yml @@ -10,7 +10,7 @@ jobs: - name: Checkout uses: actions/checkout@v4 - name: Set up Go - uses: actions/setup-go@v3 + uses: actions/setup-go@v5 with: go-version: 1.20.x - run: ./dev/go-lint.sh diff --git a/.github/workflows/goreleaser-check.yml b/.github/workflows/goreleaser-check.yml index 20e1ac5075..1355e8c60b 100644 --- a/.github/workflows/goreleaser-check.yml +++ b/.github/workflows/goreleaser-check.yml @@ -14,7 +14,7 @@ jobs: with: fetch-depth: 0 - name: Set up Go - uses: actions/setup-go@v3 + uses: actions/setup-go@v5 with: go-version: 1.20.x - name: Check GoReleaser config diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index 0bb4dbbbe2..2356092d25 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -175,7 +175,7 @@ jobs: with: fetch-depth: 0 - name: Set up Go - uses: actions/setup-go@v3 + uses: actions/setup-go@v5 with: go-version: 1.20.x - run: go test ./... diff --git a/.github/workflows/pr-auditor.yml b/.github/workflows/pr-auditor.yml index e7ec2d483b..0ca5277757 100644 --- a/.github/workflows/pr-auditor.yml +++ b/.github/workflows/pr-auditor.yml @@ -12,7 +12,7 @@ jobs: - uses: actions/checkout@v4 with: repository: 'sourcegraph/pr-auditor' - - uses: actions/setup-go@v4 + - uses: actions/setup-go@v5 with: { go-version: '1.21' } - run: './check-pr.sh' From 0428303f205df169eb46a22722ab2836dae4023e Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 1 Apr 2024 12:00:21 -0600 Subject: [PATCH 394/647] Update goreleaser/goreleaser-action action to v5 (#1041) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .github/workflows/goreleaser-check.yml | 2 +- .github/workflows/goreleaser.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/goreleaser-check.yml b/.github/workflows/goreleaser-check.yml index 1355e8c60b..3bb0aa0191 100644 --- a/.github/workflows/goreleaser-check.yml +++ b/.github/workflows/goreleaser-check.yml @@ -18,7 +18,7 @@ jobs: with: go-version: 1.20.x - name: Check GoReleaser config - uses: goreleaser/goreleaser-action@v4 + uses: goreleaser/goreleaser-action@v5 with: version: latest args: check diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index 2356092d25..4836f1e69f 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -185,7 +185,7 @@ jobs: DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }} DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }} - name: Run GoReleaser - uses: goreleaser/goreleaser-action@v2 + uses: goreleaser/goreleaser-action@v5 with: version: latest # We use a different goreleaser config for releasing a new latest version vs. From 0c3159fcfbf5bd8d51169ac533784bc4cd3d62c3 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 1 Apr 2024 12:00:37 -0600 Subject: [PATCH 395/647] Update dependency aspect_bazel_lib to v2 (#1051) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- WORKSPACE | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/WORKSPACE b/WORKSPACE index ee77c61b90..3e39c662d2 100644 --- a/WORKSPACE +++ b/WORKSPACE @@ -15,9 +15,9 @@ bazel_skylib_workspace() http_archive( name = "aspect_bazel_lib", - sha256 = "f9a0bb072aef719859aae5ad37722e97812ffffb263fd56a36cd8614a2e5d199", - strip_prefix = "bazel-lib-1.42.2", - url = "https://github.com/aspect-build/bazel-lib/releases/download/v1.42.2/bazel-lib-v1.42.2.tar.gz", + sha256 = "ac6392cbe5e1cc7701bbd81caf94016bae6f248780e12af4485d4a7127b4cb2b", + strip_prefix = "bazel-lib-2.6.1", + url = "https://github.com/aspect-build/bazel-lib/releases/download/v2.6.1/bazel-lib-v2.6.1.tar.gz", ) http_archive( From 19302e465efaa251cc0f89812e477bf3102c52b9 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 1 Apr 2024 12:01:09 -0600 Subject: [PATCH 396/647] Update dependency shellcheck to v0.10.0 (#894) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .tool-versions | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.tool-versions b/.tool-versions index 0779ef3d61..334a0bc8ce 100644 --- a/.tool-versions +++ b/.tool-versions @@ -1,3 +1,3 @@ golang 1.22.1 shfmt 3.8.0 -shellcheck 0.7.1 +shellcheck 0.10.0 From b6164a0118397b45014672604370046bf6e4a644 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 1 Apr 2024 12:01:28 -0600 Subject: [PATCH 397/647] Update docker/setup-qemu-action action to v3 (#1040) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .github/workflows/docker.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 4ec074b189..e6f44e271e 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -24,7 +24,7 @@ jobs: # We also need QEMU, since this is running on an AMD64 host and we want to # build ARM64 images. - name: Set up QEMU - uses: docker/setup-qemu-action@v1 + uses: docker/setup-qemu-action@v3 with: platforms: arm64 From 7c4dac6140b2595701b75ba663dc0d8db55d1e14 Mon Sep 17 00:00:00 2001 From: Camden Cheek Date: Wed, 3 Apr 2024 10:49:37 -0600 Subject: [PATCH 398/647] fix deprecated field (#1066) --- .goreleaser.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.goreleaser.yml b/.goreleaser.yml index e452ee7d01..392fb61caf 100644 --- a/.goreleaser.yml +++ b/.goreleaser.yml @@ -41,7 +41,7 @@ brews: name: homebrew-src-cli # Folder inside the repository to put the formula. # Default is the root folder. - folder: Formula + directory: Formula # We need to set this so that goreleaser doesn't think the binary is called # `src-cli` install: | From f468496571825a8a921e788f368aa2d42b8377c9 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 3 Apr 2024 23:27:14 +0000 Subject: [PATCH 399/647] Update dependency @types/tar to v6.1.12 (#1067) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- npm-distribution/package.json | 2 +- npm-distribution/yarn.lock | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/npm-distribution/package.json b/npm-distribution/package.json index 2be7e822d2..2c9a3a3f36 100644 --- a/npm-distribution/package.json +++ b/npm-distribution/package.json @@ -20,7 +20,7 @@ "tar": "^6.2.1" }, "devDependencies": { - "@types/tar": "6.1.11" + "@types/tar": "6.1.12" }, "private": false } diff --git a/npm-distribution/yarn.lock b/npm-distribution/yarn.lock index 078133553b..9c00c43be3 100644 --- a/npm-distribution/yarn.lock +++ b/npm-distribution/yarn.lock @@ -7,10 +7,10 @@ resolved "https://registry.yarnpkg.com/@types/node/-/node-17.0.36.tgz#c0d5f2fe76b47b63e0e0efc3d2049a9970d68794" integrity sha512-V3orv+ggDsWVHP99K3JlwtH20R7J4IhI1Kksgc+64q5VxgfRkQG8Ws3MFm/FZOKDYGy9feGFlZ70/HpCNe9QaA== -"@types/tar@6.1.11": - version "6.1.11" - resolved "https://registry.yarnpkg.com/@types/tar/-/tar-6.1.11.tgz#48de9ccee8db37efb0d5a9f288567fc0378cb734" - integrity sha512-ThA1WD8aDdVU4VLuyq5NEqriwXErF5gEIJeyT6gHBWU7JtSmW2a5qjNv3/vR82O20mW+1vhmeZJfBQPT3HCugg== +"@types/tar@6.1.12": + version "6.1.12" + resolved "https://registry.yarnpkg.com/@types/tar/-/tar-6.1.12.tgz#5cf74254687180e617156e0f22f9b2c7a5cd60a1" + integrity sha512-FwbJPi9YuovB6ilnHrz8Y4pb0Fh6N7guFkbnlCl39ua893Qi5gkXui7LSDpTQMJCmA4z5f6SeSrTPQEWLdtFVw== dependencies: "@types/node" "*" minipass "^4.0.0" From 612c233d8f6ff517e48ccf2ff41417b3fd32a863 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 3 Apr 2024 21:40:20 -0600 Subject: [PATCH 400/647] Update docker/setup-buildx-action action to v3 (#1039) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .github/workflows/docker.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index e6f44e271e..acbca14307 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -19,7 +19,7 @@ jobs: # We need buildx to be able to build a multi-architecture image. - name: Set up Docker buildx - uses: docker/setup-buildx-action@v1 + uses: docker/setup-buildx-action@v3 # We also need QEMU, since this is running on an AMD64 host and we want to # build ARM64 images. From 73444ec6374035aba570db00aa3833acd5d608ed Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 3 Apr 2024 21:40:35 -0600 Subject: [PATCH 401/647] Update dependency ubuntu to v22 (#1030) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .github/workflows/docker.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index acbca14307..f778e52620 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -12,7 +12,7 @@ on: jobs: publish: - runs-on: ubuntu-20.04 + runs-on: ubuntu-22.04 steps: - name: Checkout uses: actions/checkout@v4 From 2d15ea97aa36482c327cddf51778448fdf05ecc7 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 3 Apr 2024 21:40:51 -0600 Subject: [PATCH 402/647] Update dependency bazel_gazelle to v0.36.0 (#1065) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- WORKSPACE | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/WORKSPACE b/WORKSPACE index 3e39c662d2..a859fe33f4 100644 --- a/WORKSPACE +++ b/WORKSPACE @@ -31,10 +31,10 @@ http_archive( http_archive( name = "bazel_gazelle", - sha256 = "32938bda16e6700063035479063d9d24c60eda8d79fd4739563f50d331cb3209", + sha256 = "75df288c4b31c81eb50f51e2e14f4763cb7548daae126817247064637fd9ea62", urls = [ - "https://mirror.bazel.build/github.com/bazelbuild/bazel-gazelle/releases/download/v0.35.0/bazel-gazelle-v0.35.0.tar.gz", - "https://github.com/bazelbuild/bazel-gazelle/releases/download/v0.35.0/bazel-gazelle-v0.35.0.tar.gz", + "https://mirror.bazel.build/github.com/bazelbuild/bazel-gazelle/releases/download/v0.36.0/bazel-gazelle-v0.36.0.tar.gz", + "https://github.com/bazelbuild/bazel-gazelle/releases/download/v0.36.0/bazel-gazelle-v0.36.0.tar.gz", ], ) From 1e92fa8b3bbb0225bcb0d6f6e95bd326a832ee7d Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Thu, 4 Apr 2024 11:35:56 +0200 Subject: [PATCH 403/647] Update dependency aspect_bazel_lib to v2.7.0 (#1068) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- WORKSPACE | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/WORKSPACE b/WORKSPACE index a859fe33f4..9d274704e8 100644 --- a/WORKSPACE +++ b/WORKSPACE @@ -15,9 +15,9 @@ bazel_skylib_workspace() http_archive( name = "aspect_bazel_lib", - sha256 = "ac6392cbe5e1cc7701bbd81caf94016bae6f248780e12af4485d4a7127b4cb2b", - strip_prefix = "bazel-lib-2.6.1", - url = "https://github.com/aspect-build/bazel-lib/releases/download/v2.6.1/bazel-lib-v2.6.1.tar.gz", + sha256 = "357dad9d212327c35d9244190ef010aad315e73ffa1bed1a29e20c372f9ca346", + strip_prefix = "bazel-lib-2.7.0", + url = "https://github.com/aspect-build/bazel-lib/releases/download/v2.7.0/bazel-lib-v2.7.0.tar.gz", ) http_archive( From 8d0899a4052f43ffbc427a98491324815cb926e0 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Thu, 4 Apr 2024 09:09:20 -0600 Subject: [PATCH 404/647] Update alpine Docker tag to v3.19.1 (#722) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- docker/batch-change-volume-workspace/Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docker/batch-change-volume-workspace/Dockerfile b/docker/batch-change-volume-workspace/Dockerfile index 0dc4340f64..42002273fb 100644 --- a/docker/batch-change-volume-workspace/Dockerfile +++ b/docker/batch-change-volume-workspace/Dockerfile @@ -2,6 +2,6 @@ # image that we use to run curl, git, and unzip against a Docker volume when # using the volume workspace. -FROM alpine:3.15.0@sha256:21a3deaa0d32a8057914f36584b5288d2e5ecc984380bc0118285c70fa8c9300 +FROM alpine:3.19.1@sha256:c5b1261d6d3e43071626931fc004f70149baeba2c8ec672bd4f27761f8e1ad6b RUN apk add --update git unzip From f5cd681908a024e8d1a954e8a28cea233a3d677b Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Thu, 4 Apr 2024 09:12:41 -0600 Subject: [PATCH 405/647] Update golang Docker tag to v1.22.2 (#1064) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .tool-versions | 2 +- Dockerfile | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.tool-versions b/.tool-versions index 334a0bc8ce..2de72235ac 100644 --- a/.tool-versions +++ b/.tool-versions @@ -1,3 +1,3 @@ -golang 1.22.1 +golang 1.22.2 shfmt 3.8.0 shellcheck 0.10.0 diff --git a/Dockerfile b/Dockerfile index b8b6c61fa0..1ab5953aec 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,7 +4,7 @@ # # Nothing fancy here: we copy in the source code and build on the Alpine Go # image. Refer to .dockerignore to get a sense of what we're not going to copy. -FROM golang:1.22.1-alpine@sha256:89c315d402dcae8b1b25daa52379d5bac33610acf0389f163321572983da95e9 as builder +FROM golang:1.22.2-alpine@sha256:963da5f97ab931c0df6906e8c0ebc7db28c88d013735ae020f9558c3e6cf0580 as builder COPY . /src WORKDIR /src From efd12d571bb3a0a59e4c517317d88f91fd693050 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Thu, 4 Apr 2024 15:35:52 -0600 Subject: [PATCH 406/647] Update golang:1.22.2-alpine Docker digest to cdc86d9 (#1069) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index 1ab5953aec..cd271f13b4 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,7 +4,7 @@ # # Nothing fancy here: we copy in the source code and build on the Alpine Go # image. Refer to .dockerignore to get a sense of what we're not going to copy. -FROM golang:1.22.2-alpine@sha256:963da5f97ab931c0df6906e8c0ebc7db28c88d013735ae020f9558c3e6cf0580 as builder +FROM golang:1.22.2-alpine@sha256:cdc86d9f363e8786845bea2040312b4efa321b828acdeb26f393faa864d887b0 as builder COPY . /src WORKDIR /src From f1c34e1cf9cdab238f39069f437ab651a8d4297a Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 1 May 2024 07:33:39 +0000 Subject: [PATCH 407/647] Update dependency @types/tar to v6.1.13 (#1070) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- npm-distribution/package.json | 2 +- npm-distribution/yarn.lock | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/npm-distribution/package.json b/npm-distribution/package.json index 2c9a3a3f36..f5992fb124 100644 --- a/npm-distribution/package.json +++ b/npm-distribution/package.json @@ -20,7 +20,7 @@ "tar": "^6.2.1" }, "devDependencies": { - "@types/tar": "6.1.12" + "@types/tar": "6.1.13" }, "private": false } diff --git a/npm-distribution/yarn.lock b/npm-distribution/yarn.lock index 9c00c43be3..aba642fe29 100644 --- a/npm-distribution/yarn.lock +++ b/npm-distribution/yarn.lock @@ -7,10 +7,10 @@ resolved "https://registry.yarnpkg.com/@types/node/-/node-17.0.36.tgz#c0d5f2fe76b47b63e0e0efc3d2049a9970d68794" integrity sha512-V3orv+ggDsWVHP99K3JlwtH20R7J4IhI1Kksgc+64q5VxgfRkQG8Ws3MFm/FZOKDYGy9feGFlZ70/HpCNe9QaA== -"@types/tar@6.1.12": - version "6.1.12" - resolved "https://registry.yarnpkg.com/@types/tar/-/tar-6.1.12.tgz#5cf74254687180e617156e0f22f9b2c7a5cd60a1" - integrity sha512-FwbJPi9YuovB6ilnHrz8Y4pb0Fh6N7guFkbnlCl39ua893Qi5gkXui7LSDpTQMJCmA4z5f6SeSrTPQEWLdtFVw== +"@types/tar@6.1.13": + version "6.1.13" + resolved "https://registry.yarnpkg.com/@types/tar/-/tar-6.1.13.tgz#9b5801c02175344101b4b91086ab2bbc8e93a9b6" + integrity sha512-IznnlmU5f4WcGTh2ltRu/Ijpmk8wiWXfF0VA4s+HPjHZgvFggk1YaIkbo5krX/zUCzWF8N/l4+W/LNxnvAJ8nw== dependencies: "@types/node" "*" minipass "^4.0.0" From e8e79e031169cd4fc3ad0872c7ca0c724a2ac9f7 Mon Sep 17 00:00:00 2001 From: Varun Gandhi Date: Fri, 10 May 2024 20:33:00 +0800 Subject: [PATCH 408/647] chore: Bump to Go 1.22.2 (#1077) Needed for using updated libraries from monorepo --- .github/workflows/go-ci.yml | 2 +- .github/workflows/go-lint.yml | 2 +- .github/workflows/goreleaser-check.yml | 2 +- .github/workflows/goreleaser.yml | 2 +- .github/workflows/pr-auditor.yml | 2 +- go.mod | 2 +- go.sum | 7 +++++++ 7 files changed, 13 insertions(+), 6 deletions(-) diff --git a/.github/workflows/go-ci.yml b/.github/workflows/go-ci.yml index dfe8d1b909..69e853bb26 100644 --- a/.github/workflows/go-ci.yml +++ b/.github/workflows/go-ci.yml @@ -7,7 +7,7 @@ jobs: go-test: strategy: matrix: - go-version: [1.20.x] + go-version: [1.22.2] os: [ubuntu-latest, macos-latest, windows-latest] runs-on: ${{ matrix.os }} steps: diff --git a/.github/workflows/go-lint.yml b/.github/workflows/go-lint.yml index 3126381565..4397d120a0 100644 --- a/.github/workflows/go-lint.yml +++ b/.github/workflows/go-lint.yml @@ -12,5 +12,5 @@ jobs: - name: Set up Go uses: actions/setup-go@v5 with: - go-version: 1.20.x + go-version: 1.22.2 - run: ./dev/go-lint.sh diff --git a/.github/workflows/goreleaser-check.yml b/.github/workflows/goreleaser-check.yml index 3bb0aa0191..10557bb790 100644 --- a/.github/workflows/goreleaser-check.yml +++ b/.github/workflows/goreleaser-check.yml @@ -16,7 +16,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v5 with: - go-version: 1.20.x + go-version: 1.22.2 - name: Check GoReleaser config uses: goreleaser/goreleaser-action@v5 with: diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index 4836f1e69f..95c9c24d24 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -177,7 +177,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v5 with: - go-version: 1.20.x + go-version: 1.22 - run: go test ./... - run: go test -race -v ./... - run: echo "${DOCKER_PASSWORD}" | docker login -u=$DOCKER_USERNAME --password-stdin diff --git a/.github/workflows/pr-auditor.yml b/.github/workflows/pr-auditor.yml index 0ca5277757..0edd201a24 100644 --- a/.github/workflows/pr-auditor.yml +++ b/.github/workflows/pr-auditor.yml @@ -13,7 +13,7 @@ jobs: with: repository: 'sourcegraph/pr-auditor' - uses: actions/setup-go@v5 - with: { go-version: '1.21' } + with: { go-version: '1.22.2' } - run: './check-pr.sh' env: diff --git a/go.mod b/go.mod index f69c6704a6..2190a0a79b 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/sourcegraph/src-cli -go 1.18 +go 1.22 require ( cloud.google.com/go/storage v1.30.1 diff --git a/go.sum b/go.sum index 0feb340c2d..26dc8b69d3 100644 --- a/go.sum +++ b/go.sum @@ -23,6 +23,7 @@ github.com/alecthomas/chroma v0.10.0 h1:7XDcGkCQopCNKjZHfYrNLraA+M7e0fMiJ/Mfikbf github.com/alecthomas/chroma v0.10.0/go.mod h1:jtJATyUxlIORhUOFNA9NZDWGAQ8wpxQQqNSB4rjA/1s= github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio= +github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs= github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4= github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI= github.com/aws/aws-sdk-go-v2 v1.17.4/go.mod h1:uzbQtefpm44goOPmdKyAlXSNcwlRgF3ePWVW6EtJvvw= @@ -64,6 +65,7 @@ github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk= github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4= github.com/benbjohnson/clock v1.3.0 h1:ip6w0uFQkncKQ979AypyG0ER7mqUSBdKLOgAle/AT8A= +github.com/benbjohnson/clock v1.3.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= github.com/bufbuild/buf v1.4.0 h1:GqE3a8CMmcFvWPzuY3Mahf9Kf3S9XgZ/ORpfYFzO+90= github.com/bufbuild/buf v1.4.0/go.mod h1:mwHG7klTHnX+rM/ym8LXGl7vYpVmnwT96xWoRB4H5QI= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= @@ -103,6 +105,7 @@ github.com/creack/goselect v0.1.2/go.mod h1:a/NhLweNvqIYMuxcMOuWY516Cimucms3DglD github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/creack/pty v1.1.18 h1:n56/Zwd5o6whRC5PMGretI4IdRLlmBXYNjScPaBgsbY= +github.com/creack/pty v1.1.18/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -135,6 +138,7 @@ github.com/frankban/quicktest v1.14.3/go.mod h1:mgiwOwqx65TmIk1wJ6Q7wvnVMocbUork github.com/getsentry/sentry-go v0.25.0 h1:q6Eo+hS+yoJlTO3uu/azhQadsD8V+jQn2D8VvX1eOyI= github.com/getsentry/sentry-go v0.25.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA= +github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og= github.com/go-logr/logr v1.2.0/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.2.4 h1:g01GSCwiDw2xSZfjJ2/T9M+S6pFdcNtFYsp+Y43HYDQ= github.com/go-logr/logr v1.2.4/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= @@ -146,6 +150,7 @@ github.com/go-openapi/swag v0.22.3 h1:yMBqmnQ0gyZvEb/+KzuWZOXgllrXT4SADYbvDaXHv/ github.com/go-openapi/swag v0.22.3/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 h1:tfuBGBXKqDEevZMzYi5KSi8KkcZtzBcTgAUUtapy0OI= +github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572/go.mod h1:9Pwr4B2jHnOSGXyyzV8ROjYa2ojvAY6HCGYYfMoC3Ls= github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y= github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8= github.com/gofrs/flock v0.8.1 h1:+gYjHKf32LDeiEEFhQaotPbLuUXjY5ZqxKgXy7n59aw= @@ -196,6 +201,7 @@ github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/ github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/martian/v3 v3.3.2 h1:IqNFLAmvJOgVlpdEBiQbDc2EwKW77amAycfTuWKdfvw= +github.com/google/martian/v3 v3.3.2/go.mod h1:oBOf6HBosgwRXnUGWUB05QECsc6uvmMiJ3+6W4l/CUk= github.com/google/pprof v0.0.0-20230602150820-91b7bce49751 h1:hR7/MlvK23p6+lIw9SN1TigNLn9ZnF3W4SYRKq2gAHs= github.com/google/pprof v0.0.0-20230602150820-91b7bce49751/go.mod h1:Jh3hGz2jkYak8qXPD19ryItVnUgpgeqzdkY/D0EaeuA= github.com/google/s2a-go v0.1.4 h1:1kZ/sQM3srePvKs3tXAvQzo66XfcReoqFpIpIccE7Oc= @@ -380,6 +386,7 @@ github.com/onsi/ginkgo/v2 v2.9.7/go.mod h1:cxrmXWykAwTwhQsJOPfdIDiJ+l2RYq7U8hFU+ github.com/onsi/gomega v1.27.8 h1:gegWiwZjBsf2DgiSbf5hpokZ98JVDMcWkUiigk6/KXc= github.com/onsi/gomega v1.27.8/go.mod h1:2J8vzI/s+2shY9XHRApDkdgPo1TKT7P2u6fXeJKFnNQ= github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4= +github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8= github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 h1:KoWmjvw+nsYOo29YJK9vDA65RGE3NrOnUtO7a+RF9HU= github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8/go.mod h1:HKlIX3XHQyzLZPlr7++PzdhaXEj94dEiJgZDTsxEqUI= github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= From b24f883ebc37e1b97c73065d9ff792a3ef4e0c4d Mon Sep 17 00:00:00 2001 From: Varun Gandhi Date: Fri, 10 May 2024 21:03:43 +0800 Subject: [PATCH 409/647] codeintel: Provide hint on auth error (#1079) --- cmd/src/code_intel_upload.go | 34 ++++- go.mod | 52 +++---- go.sum | 173 +++++++--------------- internal/batches/ui/task_exec_tui_test.go | 6 +- 4 files changed, 108 insertions(+), 157 deletions(-) diff --git a/cmd/src/code_intel_upload.go b/cmd/src/code_intel_upload.go index 1eedd1dd5b..acfd58104f 100644 --- a/cmd/src/code_intel_upload.go +++ b/cmd/src/code_intel_upload.go @@ -15,7 +15,9 @@ import ( "github.com/pkg/browser" + "github.com/sourcegraph/sourcegraph/lib/accesstoken" "github.com/sourcegraph/sourcegraph/lib/codeintel/upload" + "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/sourcegraph/lib/output" "github.com/sourcegraph/src-cli/internal/api" @@ -86,7 +88,7 @@ func handleCodeIntelUpload(args []string) error { } } if err != nil { - return handleUploadError(nil, err) + return handleUploadError(cfg.AccessToken, err) } client := api.NewClient(api.ClientOpts{ @@ -94,9 +96,10 @@ func handleCodeIntelUpload(args []string) error { Flags: codeintelUploadFlags.apiFlags, }) - uploadID, err := upload.UploadIndex(ctx, codeintelUploadFlags.file, client, codeintelUploadOptions(out, isSCIPAvailable)) + uploadOptions := codeintelUploadOptions(out, isSCIPAvailable) + uploadID, err := upload.UploadIndex(ctx, codeintelUploadFlags.file, client, uploadOptions) if err != nil { - return handleUploadError(out, err) + return handleUploadError(uploadOptions.SourcegraphInstanceOptions.AccessToken, err) } uploadURL, err := makeCodeIntelUploadURL(uploadID) @@ -233,9 +236,9 @@ func (e errorWithHint) Error() string { // given output object is nil then the error will be written to standard out. // // This method returns the error that should be passed back up to the runner. -func handleUploadError(out *output.Output, err error) error { - if err == upload.ErrUnauthorized { - err = filterLSIFUnauthorizedError(out, err) +func handleUploadError(accessToken string, err error) error { + if errors.Is(err, upload.ErrUnauthorized) { + err = attachHintsForAuthorizationError(accessToken, err) } if codeintelUploadFlags.ignoreUploadFailures { @@ -247,8 +250,25 @@ func handleUploadError(out *output.Output, err error) error { return err } -func filterLSIFUnauthorizedError(out *output.Output, err error) error { +func attachHintsForAuthorizationError(accessToken string, err error) error { var actionableHints []string + + likelyTokenError := accessToken == "" + if _, err = accesstoken.ParsePersonalAccessToken(accessToken); accessToken != "" && err != nil { + likelyTokenError = true + actionableHints = append(actionableHints, + "However, the provided access token does not match expected format; was it truncated?", + "Typically the access token looks like sgp_<40 hex chars> or sgp__<40 hex chars>.") + } + + if likelyTokenError { + return errorWithHint{err: err, hint: strings.Join(mergeStringSlices( + []string{"A Sourcegraph access token must be provided via SRC_ACCESS_TOKEN for uploading SCIP/LSIF data."}, + actionableHints, + []string{"For more details, see https://sourcegraph.com/docs/cli/how-tos/creating_an_access_token."}, + ), "\n")} + } + needsGitHubToken := strings.HasPrefix(codeintelUploadFlags.repo, "github.com") needsGitLabToken := strings.HasPrefix(codeintelUploadFlags.repo, "gitlab.com") diff --git a/go.mod b/go.mod index 2190a0a79b..6aaf4a0714 100644 --- a/go.mod +++ b/go.mod @@ -2,6 +2,8 @@ module github.com/sourcegraph/src-cli go 1.22 +toolchain go1.22.2 + require ( cloud.google.com/go/storage v1.30.1 github.com/atotto/clipboard v0.1.4 @@ -26,14 +28,14 @@ require ( github.com/mattn/go-isatty v0.0.19 github.com/neelance/parallel v0.0.0-20160708114440-4de9ce63d14c github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 - github.com/sourcegraph/conc v0.3.0 + github.com/sourcegraph/conc v0.3.1-0.20240108182409-4afefce20f9b github.com/sourcegraph/go-diff v0.6.2-0.20221123165719-f8cd299c40f3 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf github.com/sourcegraph/scip v0.3.1-0.20230627154934-45df7f6d33fc - github.com/sourcegraph/sourcegraph/lib v0.0.0-20231108085505-01324538d7f0 + github.com/sourcegraph/sourcegraph/lib v0.0.0-20240510113214-3a8666b99a37 github.com/stretchr/testify v1.8.4 - golang.org/x/net v0.17.0 - golang.org/x/sync v0.3.0 + golang.org/x/net v0.21.0 + golang.org/x/sync v0.6.0 google.golang.org/api v0.132.0 google.golang.org/protobuf v1.31.0 gopkg.in/yaml.v3 v3.0.1 @@ -48,23 +50,23 @@ require ( github.com/google/pprof v0.0.0-20230602150820-91b7bce49751 // indirect github.com/google/s2a-go v0.1.4 // indirect github.com/jackc/chunkreader/v2 v2.0.1 // indirect - github.com/jackc/pgconn v1.12.1 // indirect + github.com/jackc/pgconn v1.14.3 // indirect github.com/jackc/pgio v1.0.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect - github.com/jackc/pgproto3/v2 v2.3.0 // indirect - github.com/jackc/pgservicefile v0.0.0-20200714003250-2b9c44734f2b // indirect + github.com/jackc/pgproto3/v2 v2.3.3 // indirect + github.com/jackc/pgservicefile v0.0.0-20231201235250-de7065d80cb9 // indirect github.com/onsi/ginkgo/v2 v2.9.7 // indirect github.com/onsi/gomega v1.27.8 // indirect go.uber.org/goleak v1.2.1 // indirect - google.golang.org/genproto/googleapis/api v0.0.0-20230717213848-3f92550aa753 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20230717213848-3f92550aa753 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20231016165738-49dd2c1f3d0b // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20231106174013-bbf56f31fb17 // indirect ) require ( - cloud.google.com/go v0.110.4 // indirect - cloud.google.com/go/compute v1.22.0 // indirect + cloud.google.com/go v0.110.9 // indirect + cloud.google.com/go/compute v1.23.2 // indirect cloud.google.com/go/compute/metadata v0.2.4-0.20230617002413-005d2dfb6b68 // indirect - cloud.google.com/go/iam v1.1.1 // indirect + cloud.google.com/go/iam v1.1.4 // indirect github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect github.com/Masterminds/goutils v1.1.1 // indirect github.com/Masterminds/semver v1.5.0 // indirect @@ -94,9 +96,9 @@ require ( github.com/davecgh/go-spew v1.1.1 // indirect github.com/dlclark/regexp2 v1.8.0 // indirect github.com/emicklei/go-restful/v3 v3.9.0 // indirect - github.com/envoyproxy/protoc-gen-validate v0.10.1 // indirect + github.com/envoyproxy/protoc-gen-validate v1.0.2 // indirect github.com/fatih/color v1.15.0 // indirect - github.com/getsentry/sentry-go v0.25.0 // indirect + github.com/getsentry/sentry-go v0.27.0 // indirect github.com/ghodss/yaml v1.0.0 // indirect github.com/go-logr/logr v1.2.4 // indirect github.com/go-openapi/jsonpointer v0.19.6 // indirect @@ -109,7 +111,7 @@ require ( github.com/golang/protobuf v1.5.3 // indirect github.com/google/gnostic v0.5.7-v3refs // indirect github.com/google/gofuzz v1.2.0 // indirect - github.com/google/uuid v1.3.1 // indirect + github.com/google/uuid v1.6.0 // indirect github.com/googleapis/enterprise-certificate-proxy v0.2.5 // indirect github.com/googleapis/gax-go/v2 v2.12.0 // indirect github.com/gorilla/css v1.0.0 // indirect @@ -153,7 +155,7 @@ require ( github.com/pseudomuto/protoc-gen-doc v1.5.1 // indirect github.com/pseudomuto/protokit v0.2.0 // indirect github.com/rivo/uniseg v0.4.3 // indirect - github.com/rogpeppe/go-internal v1.11.0 // indirect + github.com/rogpeppe/go-internal v1.12.0 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect github.com/sourcegraph/log v0.0.0-20231018134238-fbadff7458bb // indirect github.com/spf13/cobra v1.7.0 // indirect @@ -169,18 +171,18 @@ require ( go.uber.org/atomic v1.11.0 // indirect go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.24.0 // indirect - golang.org/x/crypto v0.17.0 // indirect - golang.org/x/mod v0.11.0 // indirect - golang.org/x/oauth2 v0.10.0 // indirect - golang.org/x/sys v0.15.0 // indirect - golang.org/x/term v0.15.0 // indirect - golang.org/x/text v0.14.0 // indirect + golang.org/x/crypto v0.23.0 // indirect + golang.org/x/mod v0.15.0 // indirect + golang.org/x/oauth2 v0.11.0 // indirect + golang.org/x/sys v0.20.0 // indirect + golang.org/x/term v0.20.0 // indirect + golang.org/x/text v0.15.0 // indirect golang.org/x/time v0.3.0 // indirect - golang.org/x/tools v0.10.0 // indirect + golang.org/x/tools v0.18.0 // indirect golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 // indirect google.golang.org/appengine v1.6.7 // indirect - google.golang.org/genproto v0.0.0-20230717213848-3f92550aa753 // indirect - google.golang.org/grpc v1.56.3 // indirect + google.golang.org/genproto v0.0.0-20231030173426-d783a09b4405 // indirect + google.golang.org/grpc v1.59.0 // indirect gopkg.in/inf.v0 v0.9.1 // direct gopkg.in/yaml.v2 v2.4.0 // indirect k8s.io/klog/v2 v2.90.1 // indirect diff --git a/go.sum b/go.sum index 26dc8b69d3..bead6e6a16 100644 --- a/go.sum +++ b/go.sum @@ -1,13 +1,13 @@ cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -cloud.google.com/go v0.110.4 h1:1JYyxKMN9hd5dR2MYTPWkGUgcoxVVhg0LKNKEo0qvmk= -cloud.google.com/go v0.110.4/go.mod h1:+EYjdK8e5RME/VY/qLCAtuyALQ9q67dvuum8i+H5xsI= -cloud.google.com/go/compute v1.22.0 h1:cB8R6FtUtT1TYGl5R3xuxnW6OUIc/DrT2aiR16TTG7Y= -cloud.google.com/go/compute v1.22.0/go.mod h1:4tCnrn48xsqlwSAiLf1HXMQk8CONslYbdiEZc9FEIbM= +cloud.google.com/go v0.110.9 h1:e7ITSqGFFk4rbz/JFIqZh3G4VEHguhAL4BQcFlWtU68= +cloud.google.com/go v0.110.9/go.mod h1:rpxevX/0Lqvlbc88b7Sc1SPNdyK1riNBTUU6JXhYNpM= +cloud.google.com/go/compute v1.23.2 h1:nWEMDhgbBkBJjfpVySqU4jgWdc22PLR0o4vEexZHers= +cloud.google.com/go/compute v1.23.2/go.mod h1:JJ0atRC0J/oWYiiVBmsSsrRnh92DhZPG4hFDcR04Rns= cloud.google.com/go/compute/metadata v0.2.4-0.20230617002413-005d2dfb6b68 h1:aRVqY1p2IJaBGStWMsQMpkAa83cPkCDLl80eOj0Rbz4= cloud.google.com/go/compute/metadata v0.2.4-0.20230617002413-005d2dfb6b68/go.mod h1:1a3eRNYX12fs5UABBIXS8HXVvQbX9hRB/RkEBPORpe8= -cloud.google.com/go/iam v1.1.1 h1:lW7fzj15aVIXYHREOqjRBV9PsH0Z6u8Y46a1YGvQP4Y= -cloud.google.com/go/iam v1.1.1/go.mod h1:A5avdyVL2tCppe4unb0951eI9jreack+RJ0/d+KUZOU= +cloud.google.com/go/iam v1.1.4 h1:K6n/GZHFTtEoKT5aUG3l9diPi0VduZNQ1PfdnpkkIFk= +cloud.google.com/go/iam v1.1.4/go.mod h1:l/rg8l1AaA+VFMho/HYx2Vv6xinPSLMF8qfhRPIZ0L8= cloud.google.com/go/storage v1.30.1 h1:uOdMxAs8HExqBlnLtnQyP0YkvbiDpdGShGKtx6U/oNM= cloud.google.com/go/storage v1.30.1/go.mod h1:NfxhC0UJE1aXSx7CIIbCf7y9HKT7BiccwkR7+P7gN8E= github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 h1:UQHMgLO+TxOElx5B5HZ4hJQsoJ/PvUvKRhJHDQXO8P8= @@ -87,7 +87,6 @@ github.com/cncf/udpa/go v0.0.0-20210930031921-04548b0d99d4/go.mod h1:6pvJx4me5XP github.com/cncf/xds/go v0.0.0-20210805033703-aa0b78936158/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cncf/xds/go v0.0.0-20210922020428-25de7278fc84/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= -github.com/cockroachdb/apd v1.1.0/go.mod h1:8Sl8LxpKi29FqWXR16WEFZRNSz3SoPzUzeMeY4+DwBQ= github.com/cockroachdb/errors v1.11.1 h1:xSEW75zKaKCWzR3OfxXUxgrk/NtT4G1MiOv5lWZazG8= github.com/cockroachdb/errors v1.11.1/go.mod h1:8MUxA3Gi6b25tYlFEBGLf+D8aISL+M4MIpiWMSNRfxw= github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b h1:r6VH0faHjZeQy818SGhaone5OnYfxFR/+AzdY3sf5aE= @@ -96,13 +95,10 @@ github.com/cockroachdb/redact v1.1.5 h1:u1PMllDkdFfPWaNGMyLD1+so+aq3uUItthCFqzwP github.com/cockroachdb/redact v1.1.5/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= github.com/containerd/console v1.0.3 h1:lIr7SlA5PxZyMV30bDW0MGbiOPXwc63yRuCP0ARubLw= github.com/containerd/console v1.0.3/go.mod h1:7LqA/THxQ86k76b8c/EMSiaJ3h1eZkMkXar0TQ1gf3U= -github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= -github.com/coreos/go-systemd v0.0.0-20190719114852-fd7a80b32e1f/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w= github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/creack/goselect v0.1.2 h1:2DNy14+JPjRBgPzAd1thbQp4BSIihxcBf0IXhQXDRa0= github.com/creack/goselect v0.1.2/go.mod h1:a/NhLweNvqIYMuxcMOuWY516Cimucms3DglDzQP3hKY= -github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/creack/pty v1.1.18 h1:n56/Zwd5o6whRC5PMGretI4IdRLlmBXYNjScPaBgsbY= github.com/creack/pty v1.1.18/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4= @@ -128,15 +124,15 @@ github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.m github.com/envoyproxy/go-control-plane v0.9.9-0.20210217033140-668b12f5399d/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= github.com/envoyproxy/go-control-plane v0.9.10-0.20210907150352-cf90f659a021/go.mod h1:AFq3mo9L8Lqqiid3OhADV3RfLJnjiw63cSpi+fDTRC0= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= -github.com/envoyproxy/protoc-gen-validate v0.10.1 h1:c0g45+xCJhdgFGw7a5QAfdS4byAbud7miNWJ1WwEVf8= -github.com/envoyproxy/protoc-gen-validate v0.10.1/go.mod h1:DRjgyB0I43LtJapqN6NiRwroiAU2PaFuvk/vjgh61ss= +github.com/envoyproxy/protoc-gen-validate v1.0.2 h1:QkIBuU5k+x7/QXPvPPnWXWlCdaBFApVqftFV6k087DA= +github.com/envoyproxy/protoc-gen-validate v1.0.2/go.mod h1:GpiZQP3dDbg4JouG/NNS7QWXpgx6x8QiMKdmN72jogE= github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs= github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw= github.com/frankban/quicktest v1.14.3 h1:FJKSZTDHjyhriyC81FLQ0LY93eSai0ZyR/ZIkd3ZUKE= github.com/frankban/quicktest v1.14.3/go.mod h1:mgiwOwqx65TmIk1wJ6Q7wvnVMocbUorkibMOrVTHZps= -github.com/getsentry/sentry-go v0.25.0 h1:q6Eo+hS+yoJlTO3uu/azhQadsD8V+jQn2D8VvX1eOyI= -github.com/getsentry/sentry-go v0.25.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= +github.com/getsentry/sentry-go v0.27.0 h1:Pv98CIbtB3LkMWmXi4Joa5OOcwbmnX88sF5qbK3r3Ps= +github.com/getsentry/sentry-go v0.27.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA= github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og= github.com/go-logr/logr v1.2.0/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= @@ -148,7 +144,6 @@ github.com/go-openapi/jsonreference v0.20.1 h1:FBLnyygC4/IZZr893oiomc9XaghoveYTr github.com/go-openapi/jsonreference v0.20.1/go.mod h1:Bl1zwGIM8/wsvqjsOQLJ/SH+En5Ap4rVB5KVcIDZG2k= github.com/go-openapi/swag v0.22.3 h1:yMBqmnQ0gyZvEb/+KzuWZOXgllrXT4SADYbvDaXHv/g= github.com/go-openapi/swag v0.22.3/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14= -github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 h1:tfuBGBXKqDEevZMzYi5KSi8KkcZtzBcTgAUUtapy0OI= github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572/go.mod h1:9Pwr4B2jHnOSGXyyzV8ROjYa2ojvAY6HCGYYfMoC3Ls= github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y= @@ -207,8 +202,8 @@ github.com/google/pprof v0.0.0-20230602150820-91b7bce49751/go.mod h1:Jh3hGz2jkYa github.com/google/s2a-go v0.1.4 h1:1kZ/sQM3srePvKs3tXAvQzo66XfcReoqFpIpIccE7Oc= github.com/google/s2a-go v0.1.4/go.mod h1:Ej+mSEMGRnqRzjc7VtF+jdBwYG5fuJfiZ8ELkjEwM0A= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/google/uuid v1.3.1 h1:KjJaJ9iWZ3jOFZIf1Lqf4laDRCasjl0BCmnEGxkdLb4= -github.com/google/uuid v1.3.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/googleapis/enterprise-certificate-proxy v0.2.5 h1:UR4rDjcgpgEnqpIEvkiqTYKBCKLNmlge2eVjoZfySzM= github.com/googleapis/enterprise-certificate-proxy v0.2.5/go.mod h1:RxW0N9901Cko1VOCW3SXCpWP+mlIEkk2tP7jnHy9a3w= github.com/googleapis/gax-go/v2 v2.12.0 h1:A+gCJKdRfqXkr+BIRGtZLibNXf0m1f9E4HG56etFpas= @@ -232,44 +227,21 @@ github.com/imdario/mergo v0.3.16 h1:wwQJbIsHYGMUyLSPrEq1CT16AhnhNJQ51+4fdHUnCl4= github.com/imdario/mergo v0.3.16/go.mod h1:WBLT9ZmE3lPoWsEzCh9LPo3TiwVN+ZKEjmz+hD27ysY= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= -github.com/jackc/chunkreader v1.0.0/go.mod h1:RT6O25fNZIuasFJRyZ4R/Y2BbhasbmZXF9QQ7T3kePo= github.com/jackc/chunkreader/v2 v2.0.0/go.mod h1:odVSm741yZoC3dpHEUXIqA9tQRhFrgOHwnPIn9lDKlk= github.com/jackc/chunkreader/v2 v2.0.1 h1:i+RDz65UE+mmpjTfyz0MoVTnzeYxroil2G82ki7MGG8= github.com/jackc/chunkreader/v2 v2.0.1/go.mod h1:odVSm741yZoC3dpHEUXIqA9tQRhFrgOHwnPIn9lDKlk= -github.com/jackc/pgconn v0.0.0-20190420214824-7e0022ef6ba3/go.mod h1:jkELnwuX+w9qN5YIfX0fl88Ehu4XC3keFuOJJk9pcnA= -github.com/jackc/pgconn v0.0.0-20190824142844-760dd75542eb/go.mod h1:lLjNuW/+OfW9/pnVKPazfWOgNfH2aPem8YQ7ilXGvJE= -github.com/jackc/pgconn v0.0.0-20190831204454-2fabfa3c18b7/go.mod h1:ZJKsE/KZfsUgOEh9hBm+xYTstcNHg7UPMVJqRfQxq4s= -github.com/jackc/pgconn v1.8.0/go.mod h1:1C2Pb36bGIP9QHGBYCjnyhqu7Rv3sGshaQUvmfGIB/o= -github.com/jackc/pgconn v1.9.0/go.mod h1:YctiPyvzfU11JFxoXokUOOKQXQmDMoJL9vJzHH8/2JY= -github.com/jackc/pgconn v1.12.1 h1:rsDFzIpRk7xT4B8FufgpCCeyjdNpKyghZeSefViE5W8= -github.com/jackc/pgconn v1.12.1/go.mod h1:ZkhRC59Llhrq3oSfrikvwQ5NaxYExr6twkdkMLaKono= +github.com/jackc/pgconn v1.14.3 h1:bVoTr12EGANZz66nZPkMInAV/KHD2TxH9npjXXgiB3w= +github.com/jackc/pgconn v1.14.3/go.mod h1:RZbme4uasqzybK2RK5c65VsHxoyaml09lx3tXOcO/VM= github.com/jackc/pgio v1.0.0 h1:g12B9UwVnzGhueNavwioyEEpAmqMe1E/BN9ES+8ovkE= github.com/jackc/pgio v1.0.0/go.mod h1:oP+2QK2wFfUWgr+gxjoBH9KGBb31Eio69xUb0w5bYf8= -github.com/jackc/pgmock v0.0.0-20190831213851-13a1b77aafa2/go.mod h1:fGZlG77KXmcq05nJLRkk0+p82V8B8Dw8KN2/V9c/OAE= -github.com/jackc/pgmock v0.0.0-20201204152224-4fe30f7445fd/go.mod h1:hrBW0Enj2AZTNpt/7Y5rr2xe/9Mn757Wtb2xeBzPv2c= github.com/jackc/pgmock v0.0.0-20210724152146-4ad1a8207f65 h1:DadwsjnMwFjfWc9y5Wi/+Zz7xoE5ALHsRQlOctkOiHc= github.com/jackc/pgmock v0.0.0-20210724152146-4ad1a8207f65/go.mod h1:5R2h2EEX+qri8jOWMbJCtaPWkrrNc7OHwsp2TCqp7ak= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= -github.com/jackc/pgproto3 v1.1.0/go.mod h1:eR5FA3leWg7p9aeAqi37XOTgTIbkABlvcPB3E5rlc78= -github.com/jackc/pgproto3/v2 v2.0.0-alpha1.0.20190420180111-c116219b62db/go.mod h1:bhq50y+xrl9n5mRYyCBFKkpRVTLYJVWeCc+mEAI3yXA= -github.com/jackc/pgproto3/v2 v2.0.0-alpha1.0.20190609003834-432c2951c711/go.mod h1:uH0AWtUmuShn0bcesswc4aBTWGvw0cAxIJp+6OB//Wg= -github.com/jackc/pgproto3/v2 v2.0.0-rc3/go.mod h1:ryONWYqW6dqSg1Lw6vXNMXoBJhpzvWKnT95C46ckYeM= -github.com/jackc/pgproto3/v2 v2.0.0-rc3.0.20190831210041-4c03ce451f29/go.mod h1:ryONWYqW6dqSg1Lw6vXNMXoBJhpzvWKnT95C46ckYeM= -github.com/jackc/pgproto3/v2 v2.0.6/go.mod h1:WfJCnwN3HIg9Ish/j3sgWXnAfK8A9Y0bwXYU5xKaEdA= -github.com/jackc/pgproto3/v2 v2.1.1/go.mod h1:WfJCnwN3HIg9Ish/j3sgWXnAfK8A9Y0bwXYU5xKaEdA= -github.com/jackc/pgproto3/v2 v2.3.0 h1:brH0pCGBDkBW07HWlN/oSBXrmo3WB0UvZd1pIuDcL8Y= -github.com/jackc/pgproto3/v2 v2.3.0/go.mod h1:WfJCnwN3HIg9Ish/j3sgWXnAfK8A9Y0bwXYU5xKaEdA= -github.com/jackc/pgservicefile v0.0.0-20200714003250-2b9c44734f2b h1:C8S2+VttkHFdOOCXJe+YGfa4vHYwlt4Zx+IVXQ97jYg= -github.com/jackc/pgservicefile v0.0.0-20200714003250-2b9c44734f2b/go.mod h1:vsD4gTJCa9TptPL8sPkXrLZ+hDuNrZCnj29CQpr4X1E= -github.com/jackc/pgtype v0.0.0-20190421001408-4ed0de4755e0/go.mod h1:hdSHsc1V01CGwFsrv11mJRHWJ6aifDLfdV3aVjFF0zg= -github.com/jackc/pgtype v0.0.0-20190824184912-ab885b375b90/go.mod h1:KcahbBH1nCMSo2DXpzsoWOAfFkdEtEJpPbVLq8eE+mc= -github.com/jackc/pgtype v0.0.0-20190828014616-a8802b16cc59/go.mod h1:MWlu30kVJrUS8lot6TQqcg7mtthZ9T0EoIBFiJcmcyw= -github.com/jackc/pgx/v4 v4.0.0-20190420224344-cc3461e65d96/go.mod h1:mdxmSJJuR08CZQyj1PVQBHy9XOp5p8/SHH6a0psbY9Y= -github.com/jackc/pgx/v4 v4.0.0-20190421002000-1b8f0016e912/go.mod h1:no/Y67Jkk/9WuGR0JG/JseM9irFbnEPbuWV2EELPNuM= -github.com/jackc/pgx/v4 v4.0.0-pre1.0.20190824185557-6972a5742186/go.mod h1:X+GQnOEnf1dqHGpw7JmHqHc1NxDoalibchSk9/RWuDc= -github.com/jackc/puddle v0.0.0-20190413234325-e4ced69a3a2b/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk= -github.com/jackc/puddle v0.0.0-20190608224051-11cab39313c9/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk= +github.com/jackc/pgproto3/v2 v2.3.3 h1:1HLSx5H+tXR9pW3in3zaztoEwQYRC9SQaYUHjTSUOag= +github.com/jackc/pgproto3/v2 v2.3.3/go.mod h1:WfJCnwN3HIg9Ish/j3sgWXnAfK8A9Y0bwXYU5xKaEdA= +github.com/jackc/pgservicefile v0.0.0-20231201235250-de7065d80cb9 h1:L0QtFUgDarD7Fpv9jeVMgy/+Ec0mtnmYuImjTz6dtDA= +github.com/jackc/pgservicefile v0.0.0-20231201235250-de7065d80cb9/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= github.com/jdxcode/netrc v0.0.0-20210204082910-926c7f70242a h1:d4+I1YEKVmWZrgkt6jpXBnLgV2ZjO0YxEtLDdfIZfH4= github.com/jdxcode/netrc v0.0.0-20210204082910-926c7f70242a/go.mod h1:Zi/ZFkEqFHTm7qkjyNJjaWH4LQA9LQhGJyF0lTYGpxw= github.com/jedib0t/go-pretty/v6 v6.3.7 h1:H3Ulkf7h6A+p0HgKBGzgDn0bZIupRbKKWF4pO4Bs7iA= @@ -301,8 +273,6 @@ github.com/klauspost/compress v1.16.7 h1:2mk3MPGNzKyxErAw8YaohYh69+pa4sIQSC0fPGC github.com/klauspost/compress v1.16.7/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= github.com/klauspost/pgzip v1.2.5 h1:qnWYvvKqedOF2ulHpMG72XQol4ILEJ8k2wwRl/Km8oE= github.com/klauspost/pgzip v1.2.5/go.mod h1:Ch1tH69qFZu15pkjo5kYi6mth2Zzwzt50oCQKQE9RUs= -github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= -github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= @@ -310,24 +280,17 @@ github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NB github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/pty v1.1.8/go.mod h1:O1sed60cT9XZ5uDucP5qwvh+TE3NnUj51EiZO/lmSfw= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= -github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= -github.com/lib/pq v1.1.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= -github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= -github.com/mattn/go-colorable v0.1.1/go.mod h1:FuOcm+DKB9mbwrcAfNl7/TZVBZ6rcnceauSikq3lYCQ= github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= -github.com/mattn/go-isatty v0.0.5/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= -github.com/mattn/go-isatty v0.0.7/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/mattn/go-isatty v0.0.13/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= @@ -390,7 +353,6 @@ github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTw github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 h1:KoWmjvw+nsYOo29YJK9vDA65RGE3NrOnUtO7a+RF9HU= github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8/go.mod h1:HKlIX3XHQyzLZPlr7++PzdhaXEj94dEiJgZDTsxEqUI= github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= -github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/profile v1.6.0 h1:hUDfIISABYI59DyeB3OTay/HxSRwTQ8rB/H83k6r5dM= @@ -409,22 +371,15 @@ github.com/rivo/uniseg v0.4.3/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUc github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= -github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= -github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA= -github.com/rs/xid v1.2.1/go.mod h1:+uKXf+4Djp6Md1KODXJxgGQPKngRmWyn10oCKFzNHOQ= -github.com/rs/zerolog v1.13.0/go.mod h1:YbFCdg8HfsridGWAh22vktObvhZbQsZXe4/zB0OKkWU= -github.com/rs/zerolog v1.15.0/go.mod h1:xYTKnLHcpfU2225ny5qZjxnj9NvkumZYjJHlAThCjNc= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/sahilm/fuzzy v0.1.0/go.mod h1:VFvziUEIMCrT6A6tw2RFIXPXXmzXbOsSHF0DOI8ZK9Y= -github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= -github.com/shopspring/decimal v0.0.0-20180709203117-cd690d0c9e24/go.mod h1:M+9NzErvs504Cn4c5DxATwIqPbtswREoFCre64PpcG4= github.com/shurcooL/go v0.0.0-20180423040247-9e1955d9fb6e/go.mod h1:TDJrrUr11Vxrven61rcy3hJMUqaf/CLWYhHNPmT14Lk= github.com/shurcooL/go-goon v0.0.0-20170922171312-37c2f522c041/go.mod h1:N5mDOmsrJOB+vfqUK+7DmDyjhSLIIBnXo9lvZJj3MWQ= -github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q= -github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= -github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo= -github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0= +github.com/sourcegraph/conc v0.3.1-0.20240108182409-4afefce20f9b h1:0FsjN+u9fNXTS2C1JnJ6G/gkgcUg8dscyyfu3PwHWUQ= +github.com/sourcegraph/conc v0.3.1-0.20240108182409-4afefce20f9b/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0= github.com/sourcegraph/go-diff v0.6.2-0.20221123165719-f8cd299c40f3 h1:11miag7hlORpW7ici5mL7T9PyiEsmVmf+8PFOvJ/ZrA= github.com/sourcegraph/go-diff v0.6.2-0.20221123165719-f8cd299c40f3/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= @@ -433,8 +388,8 @@ github.com/sourcegraph/log v0.0.0-20231018134238-fbadff7458bb h1:tHKdC+bXxxGJ0cy github.com/sourcegraph/log v0.0.0-20231018134238-fbadff7458bb/go.mod h1:IDp09QkoqS8Z3CyN2RW6vXjgABkNpDbyjLIHNQwQ8P8= github.com/sourcegraph/scip v0.3.1-0.20230627154934-45df7f6d33fc h1:o+eq0cjVV3B5ngIBF04Lv3GwttKOuYFF5NTcfXWXzfA= github.com/sourcegraph/scip v0.3.1-0.20230627154934-45df7f6d33fc/go.mod h1:7ZKAtLIUmiMvOIgG5LMcBxdtBXVa0v2GWC4Hm1ASYQ0= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20231108085505-01324538d7f0 h1:LZdpNzUvaOw9GaQ59cGRvvuXE8rzNy4I2hL2Z9zZ6WI= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20231108085505-01324538d7f0/go.mod h1:VvoU1TLgHCyaEvFb2plbV14RqAqigTEebR20oapEsJc= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20240510113214-3a8666b99a37 h1:Wdv909oSQbZUGLkmMSlk5b/h48wqfZtrQFofCQ9ELgw= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20240510113214-3a8666b99a37/go.mod h1:JmV9/kgbRQBTGT/72JExxg0tnyJDBDK+fKDVPtkRhrY= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I= @@ -445,12 +400,9 @@ github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf h1:pvbZ0lM0XWPBqUKqFU8cma github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf/go.mod h1:RJID2RhlZKId02nZ62WenDCkgHFerpIOmW0iT7GKmXM= github.com/stoewer/go-strcase v1.2.0/go.mod h1:IBiWB2sKIp3wVVQ3Y035++gc+knqhUQag1KpM8ahLw8= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0 h1:1zr/of2m5FGMsad5YfcqgdqdWrIhu+EBEJRhR1U7z/c= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= -github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= @@ -477,35 +429,24 @@ github.com/yuin/goldmark v1.5.2 h1:ALmeCk/px5FSm1MAcFBAsVKZjDuMVj8Tm7FFIlMJnqU= github.com/yuin/goldmark v1.5.2/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= github.com/yuin/goldmark-emoji v1.0.1 h1:ctuWEyzGBwiucEqxzwe0SOYDXPAucOrE9NQC18Wa1os= github.com/yuin/goldmark-emoji v1.0.1/go.mod h1:2w1E6FEWLcDQkoTE+7HU6QF1F6SLlNGjRIBbIZQFqkQ= -github.com/zenazn/goji v0.9.0/go.mod h1:7S9M489iMyHBNxwZnk9/EHS098H4/F6TATF2mIxtB1Q= go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0= go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo= go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI= -go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= -go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= go.uber.org/goleak v1.2.1 h1:NBol2c7O1ZokfZ0LEU9K6Whx/KnwvepVetCUhtKja4A= go.uber.org/goleak v1.2.1/go.mod h1:qlT2yGI9QafXHhZZLxlSuNsMw3FFLxBr+tBRlmO1xH4= -go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= -go.uber.org/zap v1.9.1/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= -go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= go.uber.org/zap v1.24.0 h1:FiJd5l1UOLj0wCgbSE0rwwXHzEdAZS6hiiSnxJN/D60= go.uber.org/zap v1.24.0/go.mod h1:2kMP+WWQ8aoFoedH3T2sq6iJ2yDWpHbP0f6MQbS9Gkg= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20190411191339-88737f569e3a/go.mod h1:WFFai1msRO1wXaEeE5yQxYXgSfI8pQAWXbQop6sCtWE= -golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20201203163018-be400aefbc4c/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= -golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20220314234659-1baeb1ce4c0b/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= -golang.org/x/crypto v0.17.0 h1:r8bRNjWL3GshPW3gkd+RpvzWrZAwPS49OmTGZ/uhM4k= -golang.org/x/crypto v0.17.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4= +golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI= +golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= @@ -514,8 +455,8 @@ golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.7.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/mod v0.11.0 h1:bUO06HqtnRcc/7l71XBe4WcqTZ+3AH1J59zWDDwLKgU= -golang.org/x/mod v0.11.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/mod v0.15.0 h1:SernR4v+D55NyBH2QiEQrlBAnj1ECL6AGrA5+dPaMY8= +golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -524,7 +465,6 @@ golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20190813141303-74dc4d7220e7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= @@ -535,12 +475,12 @@ golang.org/x/net v0.0.0-20210614182718-04defd469f4e/go.mod h1:9nx3DQGgdP8bBQD5qx golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.3.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE= -golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM= -golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE= +golang.org/x/net v0.21.0 h1:AQyQV4dYCvJ7vGmJyKki9+PBdyvhkSd8EIx/qb0AYv4= +golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.10.0 h1:zHCpF2Khkwy4mMB4bv0U37YtJdTGW8jI0glAApi0Kh8= -golang.org/x/oauth2 v0.10.0/go.mod h1:kTpgurOux7LqtuxjuyZa4Gj2gdezIt/jQtGnNFfypQI= +golang.org/x/oauth2 v0.11.0 h1:vPL4xzxBM4niKCW6g9whtaWVXTJf1U5e4aZxxFx/gbU= +golang.org/x/oauth2 v0.11.0/go.mod h1:LdF7O/8bLR/qWK9DrpXmbHLTouvRHK0SgJl0GmDBchk= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -551,17 +491,11 @@ golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220819030929-7fc1605a5dde/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.3.0 h1:ftCYgMx6zT/asHUrPw8BLLscYtGznsLAnjq5RH9P66E= -golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y= +golang.org/x/sync v0.6.0 h1:5BMeUDZ7vkXGfEr1x9B4bRcTH4lpkTkpdh0T/J+qjbQ= +golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190403152447-81d4e9dc473e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -580,24 +514,22 @@ golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220829200755-d48e67d00261/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc= -golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= +golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y= +golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.3.0/go.mod h1:q750SLmJuPmVoN1blW3UFBPREJfb1KmY3vwxfr+nFDA= -golang.org/x/term v0.15.0 h1:y/Oo/a/q3IXu26lQgl04j/gjuBDOBlx7X6Om1j2CPW4= -golang.org/x/term v0.15.0/go.mod h1:BDl952bC7+uMoWR75FIrCDx79TPU9oHkTZ9yRbYOrX0= +golang.org/x/term v0.20.0 h1:VnkxpohqXaOBYJtBmEppKUG6mXpi+4O6purfc2+sMhw= +golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= -golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk= +golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4= golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -605,19 +537,15 @@ golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGm golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190425163242-31fd60d6bfdc/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.0.0-20190823170909-c4a336ef6a2f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200624163319-25775e59acb7/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.4.0/go.mod h1:UE5sM2OK9E/d67R0ANs2xJizIymRP5gJU295PvKXxjQ= -golang.org/x/tools v0.10.0 h1:tvDr/iQoUqNdohiYm0LmmKcBk+q86lb9EprIUFhHHGg= -golang.org/x/tools v0.10.0/go.mod h1:UJwyiVBsOA2uwvK/e5OY3GTpDUJriEd+/YlqAwLPmyM= -golang.org/x/xerrors v0.0.0-20190410155217-1f06c39b4373/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20190513163551-3ee3066db522/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/tools v0.18.0 h1:k8NLag8AGHnn+PHbl7g43CtqZAwG60vZkLqgyZgIHgQ= +golang.org/x/tools v0.18.0/go.mod h1:GL7B4CwcLLeo59yx/9UWWuNOW1n3VZ4f5axWfML7Lcg= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -635,12 +563,12 @@ google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98 google.golang.org/genproto v0.0.0-20200513103714-09dca8ec2884/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= google.golang.org/genproto v0.0.0-20201019141844-1ed22bb0c154/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20230717213848-3f92550aa753 h1:+VoAg+OKmWaommL56xmZSE2sUK8A7m6SUO7X89F2tbw= -google.golang.org/genproto v0.0.0-20230717213848-3f92550aa753/go.mod h1:iqkVr8IRpZ53gx1dEnWlCUIEwDWqWARWrbzpasaTNYM= -google.golang.org/genproto/googleapis/api v0.0.0-20230717213848-3f92550aa753 h1:lCbbUxUDD+DiXx9Q6F/ttL0aAu7N2pz8XnmMm8ZW4NE= -google.golang.org/genproto/googleapis/api v0.0.0-20230717213848-3f92550aa753/go.mod h1:rsr7RhLuwsDKL7RmgDDCUc6yaGr1iqceVb5Wv6f6YvQ= -google.golang.org/genproto/googleapis/rpc v0.0.0-20230717213848-3f92550aa753 h1:XUODHrpzJEUeWmVo/jfNTLj0YyVveOo28oE6vkFbkO4= -google.golang.org/genproto/googleapis/rpc v0.0.0-20230717213848-3f92550aa753/go.mod h1:TUfxEVdsvPg18p6AslUXFoLdpED4oBnGwyqk3dV1XzM= +google.golang.org/genproto v0.0.0-20231030173426-d783a09b4405 h1:I6WNifs6pF9tNdSob2W24JtyxIYjzFB9qDlpUC76q+U= +google.golang.org/genproto v0.0.0-20231030173426-d783a09b4405/go.mod h1:3WDQMjmJk36UQhjQ89emUzb1mdaHcPeeAh4SCBKznB4= +google.golang.org/genproto/googleapis/api v0.0.0-20231016165738-49dd2c1f3d0b h1:CIC2YMXmIhYw6evmhPxBKJ4fmLbOFtXQN/GV3XOZR8k= +google.golang.org/genproto/googleapis/api v0.0.0-20231016165738-49dd2c1f3d0b/go.mod h1:IBQ646DjkDkvUIsVq/cc03FUFQ9wbZu7yE396YcL870= +google.golang.org/genproto/googleapis/rpc v0.0.0-20231106174013-bbf56f31fb17 h1:Jyp0Hsi0bmHXG6k9eATXoYtjd6e2UzZ1SCn/wIupY14= +google.golang.org/genproto/googleapis/rpc v0.0.0-20231106174013-bbf56f31fb17/go.mod h1:oQ5rr10WTTMvP4A36n8JpR1OrO1BEiV4f78CneXZxkA= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= @@ -650,8 +578,8 @@ google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= google.golang.org/grpc v1.38.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= google.golang.org/grpc v1.45.0/go.mod h1:lN7owxKUQEqMfSyQikvvk5tf/6zMPsrK+ONuO11+0rQ= -google.golang.org/grpc v1.56.3 h1:8I4C0Yq1EjstUzUJzpcRVbuYA2mODtEmpWiQoN/b2nc= -google.golang.org/grpc v1.56.3/go.mod h1:I9bI3vqKfayGqPUAwGdOSu7kt6oIJLixfffKrpXqQ9s= +google.golang.org/grpc v1.59.0 h1:Z5Iec2pjwb+LEOqzpB2MR12/eKFhDPhuqW91O+4bwUk= +google.golang.org/grpc v1.59.0/go.mod h1:aUPDwccQo6OTjy7Hct4AfBPD1GptF4fyUjIkQ9YtF98= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= @@ -674,7 +602,6 @@ gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b/go.mod h1:Co6ibVJAznAaIkqp8 gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= -gopkg.in/inconshreveable/log15.v2 v2.0.0-20180818164646-67afb5ed74ec/go.mod h1:aPpfJ7XW+gOuirDoZ8gHhLh3kZ1B08FtV2bbmy7Jv3s= gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc= gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/internal/batches/ui/task_exec_tui_test.go b/internal/batches/ui/task_exec_tui_test.go index e27c671898..ff23fe8ee6 100644 --- a/internal/batches/ui/task_exec_tui_test.go +++ b/internal/batches/ui/task_exec_tui_test.go @@ -50,8 +50,9 @@ func TestTaskExecTUI_Integration(t *testing.T) { buf := &ttyBuf{} + true_ := true out := output.NewOutput(buf, output.OutputOpts{ - ForceTTY: true, + ForceTTY: &true_, ForceColor: true, ForceHeight: 25, ForceWidth: 80, @@ -209,8 +210,9 @@ func TestProgressUpdateAfterComplete(t *testing.T) { now := time.Now() clock := func() time.Time { return now.UTC().Truncate(time.Millisecond) } + true_ := true out := output.NewOutput(buf, output.OutputOpts{ - ForceTTY: true, + ForceTTY: &true_, ForceColor: true, ForceHeight: 25, ForceWidth: 80, From aaf7b1a91e120779bf0be0918beb9071a8537991 Mon Sep 17 00:00:00 2001 From: Varun Gandhi Date: Wed, 15 May 2024 19:47:42 +0800 Subject: [PATCH 410/647] Turn off race detection for upload test (#1082) This patch can be reverted after the upstream testify library fixes the code which causes a race condition when mocking. I couldn't quite figure out how to run the single test without race detection while running others with race detection, so I've temporarily added two test commands in the go-ci.yml file. --- .github/workflows/go-ci.yml | 4 +- .../batches/service/remote_norace_test.go | 455 ++++++++++++++++++ internal/batches/service/remote_test.go | 439 +---------------- 3 files changed, 460 insertions(+), 438 deletions(-) create mode 100644 internal/batches/service/remote_norace_test.go diff --git a/.github/workflows/go-ci.yml b/.github/workflows/go-ci.yml index 69e853bb26..801eb2603e 100644 --- a/.github/workflows/go-ci.yml +++ b/.github/workflows/go-ci.yml @@ -17,4 +17,6 @@ jobs: uses: actions/setup-go@v5 with: go-version: ${{ matrix.go-version }} - - run: go test -race -v ./... + - run: | + go test -race -v ./... + go test -v ./... diff --git a/internal/batches/service/remote_norace_test.go b/internal/batches/service/remote_norace_test.go new file mode 100644 index 0000000000..c397175135 --- /dev/null +++ b/internal/batches/service/remote_norace_test.go @@ -0,0 +1,455 @@ +//go:build !race + +package service_test + +import ( + "bytes" + "context" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + + "github.com/sourcegraph/sourcegraph/lib/batches" + "github.com/sourcegraph/sourcegraph/lib/errors" + + mockclient "github.com/sourcegraph/src-cli/internal/api/mock" + "github.com/sourcegraph/src-cli/internal/batches/service" +) + +func TestService_UploadBatchSpecWorkspaceFiles(t *testing.T) { + tests := []struct { + name string + steps []batches.Step + + setup func(workingDir string) error + mockInvokes func(client *mockclient.Client) + + expectedError error + }{ + { + name: "Upload single file", + steps: []batches.Step{{ + Mount: []batches.Mount{{ + Path: "./hello.txt", + }}, + }}, + setup: func(workingDir string) error { + return writeTempFile(workingDir, "hello.txt", "hello world!") + }, + mockInvokes: func(client *mockclient.Client) { + // Body will get set with the body argument to NewHTTPRequest + req := httptest.NewRequest(http.MethodPost, "http://fake.com/.api/files/batch-changes/123", nil) + client.On("NewHTTPRequest", mock.Anything, http.MethodPost, ".api/files/batch-changes/123", mock.Anything). + Run(func(args mock.Arguments) { + req.Body = args[3].(*io.PipeReader) + }). + Return(req, nil). + Once() + + resp := &http.Response{ + StatusCode: http.StatusOK, + Body: io.NopCloser(bytes.NewReader([]byte{})), + } + entry := &multipartFormEntry{ + fileName: "hello.txt", + content: "hello world!", + } + requestMatcher := multipartFormRequestMatcher(entry) + client.On("Do", mock.MatchedBy(requestMatcher)). + Return(resp, nil). + Once() + }, + }, + { + name: "Deduplicate files", + steps: []batches.Step{{ + Mount: []batches.Mount{ + { + Path: "./hello.txt", + }, + { + Path: "./hello.txt", + }, + { + Path: "./hello.txt", + }, + }, + }}, + setup: func(workingDir string) error { + return writeTempFile(workingDir, "hello.txt", "hello world!") + }, + mockInvokes: func(client *mockclient.Client) { + // Body will get set with the body argument to NewHTTPRequest + req := httptest.NewRequest(http.MethodPost, "http://fake.com/.api/files/batch-changes/123", nil) + client.On("NewHTTPRequest", mock.Anything, http.MethodPost, ".api/files/batch-changes/123", mock.Anything). + Run(func(args mock.Arguments) { + req.Body = args[3].(*io.PipeReader) + }). + Return(req, nil). + Once() + + resp := &http.Response{ + StatusCode: http.StatusOK, + Body: io.NopCloser(bytes.NewReader([]byte{})), + } + entry := &multipartFormEntry{ + fileName: "hello.txt", + content: "hello world!", + } + requestMatcher := multipartFormRequestMatcher(entry) + client.On("Do", mock.MatchedBy(requestMatcher)). + Return(resp, nil). + Once() + }, + }, + { + name: "Upload multiple files", + steps: []batches.Step{{ + Mount: []batches.Mount{ + { + Path: "./hello.txt", + }, + { + Path: "./world.txt", + }, + }, + }}, + setup: func(workingDir string) error { + if err := writeTempFile(workingDir, "hello.txt", "hello"); err != nil { + return err + } + return writeTempFile(workingDir, "world.txt", "world!") + }, + mockInvokes: func(client *mockclient.Client) { + // Body will get set with the body argument to NewHTTPRequest + req := httptest.NewRequest(http.MethodPost, "http://fake.com/.api/files/batch-changes/123", nil) + client.On("NewHTTPRequest", mock.Anything, http.MethodPost, ".api/files/batch-changes/123", mock.Anything). + Run(func(args mock.Arguments) { + req.Body = args[3].(*io.PipeReader) + }). + Return(req, nil). + Twice() + + resp := &http.Response{ + StatusCode: http.StatusOK, + Body: io.NopCloser(bytes.NewReader([]byte{})), + } + helloEntry := &multipartFormEntry{ + fileName: "hello.txt", + content: "hello", + } + client. + On("Do", mock.MatchedBy(multipartFormRequestMatcher(helloEntry))). + Return(resp, nil). + Once() + + worldEntry := &multipartFormEntry{ + fileName: "world.txt", + content: "world!", + } + client. + On("Do", mock.MatchedBy(multipartFormRequestMatcher(worldEntry))). + Return(resp, nil). + Once() + }, + }, + { + name: "Upload directory", + steps: []batches.Step{{ + Mount: []batches.Mount{ + { + Path: "./", + }, + }, + }}, + setup: func(workingDir string) error { + if err := writeTempFile(workingDir, "hello.txt", "hello"); err != nil { + return err + } + return writeTempFile(workingDir, "world.txt", "world!") + }, + mockInvokes: func(client *mockclient.Client) { + // Body will get set with the body argument to NewHTTPRequest + req := httptest.NewRequest(http.MethodPost, "http://fake.com/.api/files/batch-changes/123", nil) + client.On("NewHTTPRequest", mock.Anything, http.MethodPost, ".api/files/batch-changes/123", mock.Anything). + Run(func(args mock.Arguments) { + req.Body = args[3].(*io.PipeReader) + }). + Return(req, nil). + Twice() + + resp := &http.Response{ + StatusCode: http.StatusOK, + Body: io.NopCloser(bytes.NewReader([]byte{})), + } + helloEntry := &multipartFormEntry{ + fileName: "hello.txt", + content: "hello", + } + client. + On("Do", mock.MatchedBy(multipartFormRequestMatcher(helloEntry))). + Return(resp, nil). + Once() + + worldEntry := &multipartFormEntry{ + fileName: "world.txt", + content: "world!", + } + client. + On("Do", mock.MatchedBy(multipartFormRequestMatcher(worldEntry))). + Return(resp, nil). + Once() + }, + }, + { + name: "Upload subdirectory", + steps: []batches.Step{{ + Mount: []batches.Mount{ + { + Path: "./scripts", + }, + }, + }}, + setup: func(workingDir string) error { + dir := filepath.Join(workingDir, "scripts") + if err := os.Mkdir(dir, os.ModePerm); err != nil { + return err + } + return writeTempFile(dir, "hello.txt", "hello world!") + }, + mockInvokes: func(client *mockclient.Client) { + // Body will get set with the body argument to NewHTTPRequest + req := httptest.NewRequest(http.MethodPost, "http://fake.com/.api/files/batch-changes/123", nil) + client.On("NewHTTPRequest", mock.Anything, http.MethodPost, ".api/files/batch-changes/123", mock.Anything). + Run(func(args mock.Arguments) { + req.Body = args[3].(*io.PipeReader) + }). + Return(req, nil). + Once() + + resp := &http.Response{ + StatusCode: http.StatusOK, + Body: io.NopCloser(bytes.NewReader([]byte{})), + } + entry := &multipartFormEntry{ + path: "scripts", + fileName: "hello.txt", + content: "hello world!", + } + client.On("Do", mock.MatchedBy(multipartFormRequestMatcher(entry))). + Return(resp, nil). + Once() + }, + }, + { + name: "Upload files and directory", + steps: []batches.Step{{ + Mount: []batches.Mount{ + { + Path: "./hello.txt", + }, + { + Path: "./world.txt", + }, + { + Path: "./scripts", + }, + }, + }}, + setup: func(workingDir string) error { + if err := writeTempFile(workingDir, "hello.txt", "hello"); err != nil { + return err + } + if err := writeTempFile(workingDir, "world.txt", "world!"); err != nil { + return err + } + dir := filepath.Join(workingDir, "scripts") + if err := os.Mkdir(dir, os.ModePerm); err != nil { + return err + } + return writeTempFile(dir, "something-else.txt", "this is neat") + }, + mockInvokes: func(client *mockclient.Client) { + // Body will get set with the body argument to NewHTTPRequest + req := httptest.NewRequest(http.MethodPost, "http://fake.com/.api/files/batch-changes/123", nil) + client.On("NewHTTPRequest", mock.Anything, http.MethodPost, ".api/files/batch-changes/123", mock.Anything). + Run(func(args mock.Arguments) { + req.Body = args[3].(*io.PipeReader) + }). + Return(req, nil). + Times(3) + + resp := &http.Response{ + StatusCode: http.StatusOK, + Body: io.NopCloser(bytes.NewReader([]byte{})), + } + helloEntry := &multipartFormEntry{ + fileName: "hello.txt", + content: "hello", + } + client.On("Do", mock.MatchedBy(multipartFormRequestMatcher(helloEntry))). + Return(resp, nil). + Once() + worldEntry := &multipartFormEntry{ + fileName: "world.txt", + content: "world!", + } + client.On("Do", mock.MatchedBy(multipartFormRequestMatcher(worldEntry))). + Return(resp, nil). + Once() + somethingElseEntry := &multipartFormEntry{ + path: "scripts", + fileName: "something-else.txt", + content: "this is neat", + } + client.On("Do", mock.MatchedBy(multipartFormRequestMatcher(somethingElseEntry))). + Return(resp, nil). + Once() + }, + }, + { + name: "Bad status code", + steps: []batches.Step{{ + Mount: []batches.Mount{{ + Path: "./hello.txt", + }}, + }}, + setup: func(workingDir string) error { + return writeTempFile(workingDir, "hello.txt", "hello world!") + }, + mockInvokes: func(client *mockclient.Client) { + req := httptest.NewRequest(http.MethodPost, "http://fake.com/.api/files/batch-changes/123", nil) + client.On("NewHTTPRequest", mock.Anything, http.MethodPost, ".api/files/batch-changes/123", mock.Anything). + Return(req, nil). + Once() + + resp := &http.Response{ + StatusCode: http.StatusInternalServerError, + Body: io.NopCloser(bytes.NewReader([]byte("failed to upload file"))), + } + client.On("Do", mock.Anything). + Return(resp, nil). + Once() + }, + expectedError: errors.New("failed to upload file"), + }, + { + name: "File exceeds limit", + steps: []batches.Step{{ + Mount: []batches.Mount{{ + Path: "./hello.txt", + }}, + }}, + setup: func(workingDir string) error { + f, err := os.Create(filepath.Join(workingDir, "hello.txt")) + if err != nil { + return err + } + defer f.Close() + if _, err = io.Copy(f, io.LimitReader(neverEnding('a'), 11<<20)); err != nil { + return err + } + return nil + }, + mockInvokes: func(client *mockclient.Client) { + req := httptest.NewRequest(http.MethodPost, "http://fake.com/.api/files/batch-changes/123", nil) + client.On("NewHTTPRequest", mock.Anything, http.MethodPost, ".api/files/batch-changes/123", mock.Anything). + Run(func(args mock.Arguments) { + req.Body = args[3].(*io.PipeReader) + }). + Return(req, nil). + Once() + + client.On("Do", mock.Anything). + Return(nil, errors.New("file exceeds limit")). + Once() + }, + expectedError: errors.New("file exceeds limit"), + }, + { + name: "Long mount path", + steps: []batches.Step{{ + Mount: []batches.Mount{{ + Path: "foo/../bar/../baz/../hello.txt", + }}, + }}, + setup: func(workingDir string) error { + dir := filepath.Join(workingDir, "foo") + if err := os.Mkdir(dir, os.ModePerm); err != nil { + return err + } + dir = filepath.Join(workingDir, "bar") + if err := os.Mkdir(dir, os.ModePerm); err != nil { + return err + } + dir = filepath.Join(workingDir, "baz") + if err := os.Mkdir(dir, os.ModePerm); err != nil { + return err + } + return writeTempFile(workingDir, "hello.txt", "hello world!") + }, + mockInvokes: func(client *mockclient.Client) { + // Body will get set with the body argument to NewHTTPRequest + req := httptest.NewRequest(http.MethodPost, "http://fake.com/.api/files/batch-changes/123", nil) + client.On("NewHTTPRequest", mock.Anything, http.MethodPost, ".api/files/batch-changes/123", mock.Anything). + Run(func(args mock.Arguments) { + req.Body = args[3].(*io.PipeReader) + }). + Return(req, nil). + Once() + + resp := &http.Response{ + StatusCode: http.StatusOK, + Body: io.NopCloser(bytes.NewReader([]byte{})), + } + entry := &multipartFormEntry{ + fileName: "hello.txt", + content: "hello world!", + } + requestMatcher := multipartFormRequestMatcher(entry) + client.On("Do", mock.MatchedBy(requestMatcher)). + Return(resp, nil). + Once() + }, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + // TODO: use TempDir when https://github.com/golang/go/issues/51442 is cherry-picked into 1.18 or upgrade to 1.19+ + //tempDir := t.TempDir() + workingDir, err := os.MkdirTemp("", test.name) + require.NoError(t, err) + t.Cleanup(func() { + os.RemoveAll(workingDir) + }) + + if test.setup != nil { + err := test.setup(workingDir) + require.NoError(t, err) + } + + client := new(mockclient.Client) + svc := service.New(&service.Opts{Client: client}) + + if test.mockInvokes != nil { + test.mockInvokes(client) + } + + err = svc.UploadBatchSpecWorkspaceFiles(context.Background(), workingDir, "123", test.steps) + if test.expectedError != nil { + assert.Equal(t, test.expectedError.Error(), err.Error()) + } else { + assert.NoError(t, err) + } + + client.AssertExpectations(t) + }) + } +} diff --git a/internal/batches/service/remote_test.go b/internal/batches/service/remote_test.go index 75a426c2e3..5e18b5e847 100644 --- a/internal/batches/service/remote_test.go +++ b/internal/batches/service/remote_test.go @@ -7,21 +7,17 @@ import ( "fmt" "io" "net/http" - "net/http/httptest" "os" "path/filepath" "regexp" "strings" "testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/require" - mockclient "github.com/sourcegraph/src-cli/internal/api/mock" "github.com/sourcegraph/src-cli/internal/batches/service" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" - "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/errors" ) @@ -204,437 +200,6 @@ func TestService_CreateBatchSpecFromRaw(t *testing.T) { } } -func TestService_UploadBatchSpecWorkspaceFiles(t *testing.T) { - tests := []struct { - name string - steps []batches.Step - - setup func(workingDir string) error - mockInvokes func(client *mockclient.Client) - - expectedError error - }{ - { - name: "Upload single file", - steps: []batches.Step{{ - Mount: []batches.Mount{{ - Path: "./hello.txt", - }}, - }}, - setup: func(workingDir string) error { - return writeTempFile(workingDir, "hello.txt", "hello world!") - }, - mockInvokes: func(client *mockclient.Client) { - // Body will get set with the body argument to NewHTTPRequest - req := httptest.NewRequest(http.MethodPost, "http://fake.com/.api/files/batch-changes/123", nil) - client.On("NewHTTPRequest", mock.Anything, http.MethodPost, ".api/files/batch-changes/123", mock.Anything). - Run(func(args mock.Arguments) { - req.Body = args[3].(*io.PipeReader) - }). - Return(req, nil). - Once() - - resp := &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader([]byte{})), - } - entry := &multipartFormEntry{ - fileName: "hello.txt", - content: "hello world!", - } - requestMatcher := multipartFormRequestMatcher(entry) - client.On("Do", mock.MatchedBy(requestMatcher)). - Return(resp, nil). - Once() - }, - }, - { - name: "Deduplicate files", - steps: []batches.Step{{ - Mount: []batches.Mount{ - { - Path: "./hello.txt", - }, - { - Path: "./hello.txt", - }, - { - Path: "./hello.txt", - }, - }, - }}, - setup: func(workingDir string) error { - return writeTempFile(workingDir, "hello.txt", "hello world!") - }, - mockInvokes: func(client *mockclient.Client) { - // Body will get set with the body argument to NewHTTPRequest - req := httptest.NewRequest(http.MethodPost, "http://fake.com/.api/files/batch-changes/123", nil) - client.On("NewHTTPRequest", mock.Anything, http.MethodPost, ".api/files/batch-changes/123", mock.Anything). - Run(func(args mock.Arguments) { - req.Body = args[3].(*io.PipeReader) - }). - Return(req, nil). - Once() - - resp := &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader([]byte{})), - } - entry := &multipartFormEntry{ - fileName: "hello.txt", - content: "hello world!", - } - requestMatcher := multipartFormRequestMatcher(entry) - client.On("Do", mock.MatchedBy(requestMatcher)). - Return(resp, nil). - Once() - }, - }, - { - name: "Upload multiple files", - steps: []batches.Step{{ - Mount: []batches.Mount{ - { - Path: "./hello.txt", - }, - { - Path: "./world.txt", - }, - }, - }}, - setup: func(workingDir string) error { - if err := writeTempFile(workingDir, "hello.txt", "hello"); err != nil { - return err - } - return writeTempFile(workingDir, "world.txt", "world!") - }, - mockInvokes: func(client *mockclient.Client) { - // Body will get set with the body argument to NewHTTPRequest - req := httptest.NewRequest(http.MethodPost, "http://fake.com/.api/files/batch-changes/123", nil) - client.On("NewHTTPRequest", mock.Anything, http.MethodPost, ".api/files/batch-changes/123", mock.Anything). - Run(func(args mock.Arguments) { - req.Body = args[3].(*io.PipeReader) - }). - Return(req, nil). - Twice() - - resp := &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader([]byte{})), - } - helloEntry := &multipartFormEntry{ - fileName: "hello.txt", - content: "hello", - } - client. - On("Do", mock.MatchedBy(multipartFormRequestMatcher(helloEntry))). - Return(resp, nil). - Once() - - worldEntry := &multipartFormEntry{ - fileName: "world.txt", - content: "world!", - } - client. - On("Do", mock.MatchedBy(multipartFormRequestMatcher(worldEntry))). - Return(resp, nil). - Once() - }, - }, - { - name: "Upload directory", - steps: []batches.Step{{ - Mount: []batches.Mount{ - { - Path: "./", - }, - }, - }}, - setup: func(workingDir string) error { - if err := writeTempFile(workingDir, "hello.txt", "hello"); err != nil { - return err - } - return writeTempFile(workingDir, "world.txt", "world!") - }, - mockInvokes: func(client *mockclient.Client) { - // Body will get set with the body argument to NewHTTPRequest - req := httptest.NewRequest(http.MethodPost, "http://fake.com/.api/files/batch-changes/123", nil) - client.On("NewHTTPRequest", mock.Anything, http.MethodPost, ".api/files/batch-changes/123", mock.Anything). - Run(func(args mock.Arguments) { - req.Body = args[3].(*io.PipeReader) - }). - Return(req, nil). - Twice() - - resp := &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader([]byte{})), - } - helloEntry := &multipartFormEntry{ - fileName: "hello.txt", - content: "hello", - } - client. - On("Do", mock.MatchedBy(multipartFormRequestMatcher(helloEntry))). - Return(resp, nil). - Once() - - worldEntry := &multipartFormEntry{ - fileName: "world.txt", - content: "world!", - } - client. - On("Do", mock.MatchedBy(multipartFormRequestMatcher(worldEntry))). - Return(resp, nil). - Once() - }, - }, - { - name: "Upload subdirectory", - steps: []batches.Step{{ - Mount: []batches.Mount{ - { - Path: "./scripts", - }, - }, - }}, - setup: func(workingDir string) error { - dir := filepath.Join(workingDir, "scripts") - if err := os.Mkdir(dir, os.ModePerm); err != nil { - return err - } - return writeTempFile(dir, "hello.txt", "hello world!") - }, - mockInvokes: func(client *mockclient.Client) { - // Body will get set with the body argument to NewHTTPRequest - req := httptest.NewRequest(http.MethodPost, "http://fake.com/.api/files/batch-changes/123", nil) - client.On("NewHTTPRequest", mock.Anything, http.MethodPost, ".api/files/batch-changes/123", mock.Anything). - Run(func(args mock.Arguments) { - req.Body = args[3].(*io.PipeReader) - }). - Return(req, nil). - Once() - - resp := &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader([]byte{})), - } - entry := &multipartFormEntry{ - path: "scripts", - fileName: "hello.txt", - content: "hello world!", - } - client.On("Do", mock.MatchedBy(multipartFormRequestMatcher(entry))). - Return(resp, nil). - Once() - }, - }, - { - name: "Upload files and directory", - steps: []batches.Step{{ - Mount: []batches.Mount{ - { - Path: "./hello.txt", - }, - { - Path: "./world.txt", - }, - { - Path: "./scripts", - }, - }, - }}, - setup: func(workingDir string) error { - if err := writeTempFile(workingDir, "hello.txt", "hello"); err != nil { - return err - } - if err := writeTempFile(workingDir, "world.txt", "world!"); err != nil { - return err - } - dir := filepath.Join(workingDir, "scripts") - if err := os.Mkdir(dir, os.ModePerm); err != nil { - return err - } - return writeTempFile(dir, "something-else.txt", "this is neat") - }, - mockInvokes: func(client *mockclient.Client) { - // Body will get set with the body argument to NewHTTPRequest - req := httptest.NewRequest(http.MethodPost, "http://fake.com/.api/files/batch-changes/123", nil) - client.On("NewHTTPRequest", mock.Anything, http.MethodPost, ".api/files/batch-changes/123", mock.Anything). - Run(func(args mock.Arguments) { - req.Body = args[3].(*io.PipeReader) - }). - Return(req, nil). - Times(3) - - resp := &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader([]byte{})), - } - helloEntry := &multipartFormEntry{ - fileName: "hello.txt", - content: "hello", - } - client.On("Do", mock.MatchedBy(multipartFormRequestMatcher(helloEntry))). - Return(resp, nil). - Once() - worldEntry := &multipartFormEntry{ - fileName: "world.txt", - content: "world!", - } - client.On("Do", mock.MatchedBy(multipartFormRequestMatcher(worldEntry))). - Return(resp, nil). - Once() - somethingElseEntry := &multipartFormEntry{ - path: "scripts", - fileName: "something-else.txt", - content: "this is neat", - } - client.On("Do", mock.MatchedBy(multipartFormRequestMatcher(somethingElseEntry))). - Return(resp, nil). - Once() - }, - }, - { - name: "Bad status code", - steps: []batches.Step{{ - Mount: []batches.Mount{{ - Path: "./hello.txt", - }}, - }}, - setup: func(workingDir string) error { - return writeTempFile(workingDir, "hello.txt", "hello world!") - }, - mockInvokes: func(client *mockclient.Client) { - req := httptest.NewRequest(http.MethodPost, "http://fake.com/.api/files/batch-changes/123", nil) - client.On("NewHTTPRequest", mock.Anything, http.MethodPost, ".api/files/batch-changes/123", mock.Anything). - Return(req, nil). - Once() - - resp := &http.Response{ - StatusCode: http.StatusInternalServerError, - Body: io.NopCloser(bytes.NewReader([]byte("failed to upload file"))), - } - client.On("Do", mock.Anything). - Return(resp, nil). - Once() - }, - expectedError: errors.New("failed to upload file"), - }, - { - name: "File exceeds limit", - steps: []batches.Step{{ - Mount: []batches.Mount{{ - Path: "./hello.txt", - }}, - }}, - setup: func(workingDir string) error { - f, err := os.Create(filepath.Join(workingDir, "hello.txt")) - if err != nil { - return err - } - defer f.Close() - if _, err = io.Copy(f, io.LimitReader(neverEnding('a'), 11<<20)); err != nil { - return err - } - return nil - }, - mockInvokes: func(client *mockclient.Client) { - req := httptest.NewRequest(http.MethodPost, "http://fake.com/.api/files/batch-changes/123", nil) - client.On("NewHTTPRequest", mock.Anything, http.MethodPost, ".api/files/batch-changes/123", mock.Anything). - Run(func(args mock.Arguments) { - req.Body = args[3].(*io.PipeReader) - }). - Return(req, nil). - Once() - - client.On("Do", mock.Anything). - Return(nil, errors.New("file exceeds limit")). - Once() - }, - expectedError: errors.New("file exceeds limit"), - }, - { - name: "Long mount path", - steps: []batches.Step{{ - Mount: []batches.Mount{{ - Path: "foo/../bar/../baz/../hello.txt", - }}, - }}, - setup: func(workingDir string) error { - dir := filepath.Join(workingDir, "foo") - if err := os.Mkdir(dir, os.ModePerm); err != nil { - return err - } - dir = filepath.Join(workingDir, "bar") - if err := os.Mkdir(dir, os.ModePerm); err != nil { - return err - } - dir = filepath.Join(workingDir, "baz") - if err := os.Mkdir(dir, os.ModePerm); err != nil { - return err - } - return writeTempFile(workingDir, "hello.txt", "hello world!") - }, - mockInvokes: func(client *mockclient.Client) { - // Body will get set with the body argument to NewHTTPRequest - req := httptest.NewRequest(http.MethodPost, "http://fake.com/.api/files/batch-changes/123", nil) - client.On("NewHTTPRequest", mock.Anything, http.MethodPost, ".api/files/batch-changes/123", mock.Anything). - Run(func(args mock.Arguments) { - req.Body = args[3].(*io.PipeReader) - }). - Return(req, nil). - Once() - - resp := &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader([]byte{})), - } - entry := &multipartFormEntry{ - fileName: "hello.txt", - content: "hello world!", - } - requestMatcher := multipartFormRequestMatcher(entry) - client.On("Do", mock.MatchedBy(requestMatcher)). - Return(resp, nil). - Once() - }, - }, - } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - // TODO: use TempDir when https://github.com/golang/go/issues/51442 is cherry-picked into 1.18 or upgrade to 1.19+ - //tempDir := t.TempDir() - workingDir, err := os.MkdirTemp("", test.name) - require.NoError(t, err) - t.Cleanup(func() { - os.RemoveAll(workingDir) - }) - - if test.setup != nil { - err := test.setup(workingDir) - require.NoError(t, err) - } - - client := new(mockclient.Client) - svc := service.New(&service.Opts{Client: client}) - - if test.mockInvokes != nil { - test.mockInvokes(client) - } - - err = svc.UploadBatchSpecWorkspaceFiles(context.Background(), workingDir, "123", test.steps) - if test.expectedError != nil { - assert.Equal(t, test.expectedError.Error(), err.Error()) - } else { - assert.NoError(t, err) - } - - client.AssertExpectations(t) - }) - } -} - func writeTempFile(dir string, name string, content string) error { f, err := os.Create(filepath.Join(dir, name)) if err != nil { From 03b18dd89d1e1a76b272ae9a27468e2522dbef5d Mon Sep 17 00:00:00 2001 From: Varun Gandhi Date: Wed, 15 May 2024 19:51:47 +0800 Subject: [PATCH 411/647] Fix SCIP uploads in CI (#1083) --- .github/workflows/scip.yml | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/.github/workflows/scip.yml b/.github/workflows/scip.yml index fa2a5655de..d2bbd16208 100644 --- a/.github/workflows/scip.yml +++ b/.github/workflows/scip.yml @@ -14,5 +14,15 @@ jobs: run: git config --global --add safe.directory $GITHUB_WORKSPACE - name: Generate SCIP data run: scip-go - - name: Upload SCIP data - run: src code-intel upload -github-token=${{ secrets.GITHUB_TOKEN }} + + - name: Upload SCIP to Cloud + run: src code-intel upload -github-token='${{ secrets.GITHUB_TOKEN }}' -no-progress + env: + SRC_ENDPOINT: https://sourcegraph.com/ + SRC_ACCESS_TOKEN: ${{ secrets.SRC_ACCESS_TOKEN_DOTCOM }} + + - name: Upload SCIP to S2 + run: src code-intel upload -github-token='${{ secrets.GITHUB_TOKEN }}' -no-progress + env: + SRC_ENDPOINT: https://sourcegraph.sourcegraph.com/ + SRC_ACCESS_TOKEN: ${{ secrets.SRC_ACCESS_TOKEN_S2 }} From 849335b67193d220194a6ccddc3b31ad7a3aaf45 Mon Sep 17 00:00:00 2001 From: Craig Furman Date: Wed, 15 May 2024 14:23:45 +0100 Subject: [PATCH 412/647] validate: add context to connection error (#1081) * validate: add context to connection error When src-validate fails to connect to a service, name that service in the error message. * Bump golangci-lint To avoid memory leak / timeout. Fix up depguard config. Fix a formatting error. Leave one linter error in place for now, it'll be fixed in a subsequent commit, as it's a bit more complex. --- .golangci.yml | 21 +++++++++++++-------- dev/golangci-lint.sh | 2 +- internal/batches/ui/task_exec_tui_test.go | 4 ++-- internal/validate/kube/kube.go | 2 +- 4 files changed, 17 insertions(+), 12 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 70b873a074..961158d5e1 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -17,14 +17,19 @@ linters: linters-settings: depguard: - list-type: blacklist - include-go-root: true - packages-with-error-message: - - errors: 'Use github.com/sourcegraph/sourcegraph/lib/errors instead' - - github.com/pkg/errors: 'Use github.com/sourcegraph/sourcegraph/lib/errors instead' - - github.com/cockroachdb/errors: 'Use github.com/sourcegraph/sourcegraph/lib/errors instead' - - github.com/hashicorp/go-multierror: 'Use github.com/sourcegraph/sourcegraph/lib/errors instead' - - io/ioutil: 'The ioutil package has been deprecated' + rules: + main: + deny: + - pkg: "errors" + desc: "Use github.com/sourcegraph/sourcegraph/lib/errors instead" + - pkg: "github.com/pkg/errors" + desc: "Use github.com/sourcegraph/sourcegraph/lib/errors instead" + - pkg: "github.com/cockroachdb/errors" + desc: "Use github.com/sourcegraph/sourcegraph/lib/errors instead" + - pkg: "github.com/hashicorp/go-multierror" + desc: "Use github.com/sourcegraph/sourcegraph/lib/errors instead" + - pkg: "io/ioutil" + desc: "The ioutil package has been deprecated" gocritic: disabled-checks: - appendAssign # Too many false positives diff --git a/dev/golangci-lint.sh b/dev/golangci-lint.sh index 9f23e2a9fd..80c94bf299 100755 --- a/dev/golangci-lint.sh +++ b/dev/golangci-lint.sh @@ -6,7 +6,7 @@ pushd "$(dirname "${BASH_SOURCE[0]}")/.." >/dev/null mkdir -p dev/.bin -version="1.51.2" +version="1.58.1" suffix="${version}-$(go env GOOS)-$(go env GOARCH)" target="$PWD/dev/.bin/golangci-lint-${suffix}" url="https://github.com/golangci/golangci-lint/releases/download/v${version}/golangci-lint-${suffix}.tar.gz" diff --git a/internal/batches/ui/task_exec_tui_test.go b/internal/batches/ui/task_exec_tui_test.go index ff23fe8ee6..f368cb7993 100644 --- a/internal/batches/ui/task_exec_tui_test.go +++ b/internal/batches/ui/task_exec_tui_test.go @@ -50,7 +50,7 @@ func TestTaskExecTUI_Integration(t *testing.T) { buf := &ttyBuf{} - true_ := true + true_ := true out := output.NewOutput(buf, output.OutputOpts{ ForceTTY: &true_, ForceColor: true, @@ -210,7 +210,7 @@ func TestProgressUpdateAfterComplete(t *testing.T) { now := time.Now() clock := func() time.Time { return now.UTC().Truncate(time.Millisecond) } - true_ := true + true_ := true out := output.NewOutput(buf, output.OutputOpts{ ForceTTY: &true_, ForceColor: true, diff --git a/internal/validate/kube/kube.go b/internal/validate/kube/kube.go index be3288b7d9..dd1db3d510 100644 --- a/internal/validate/kube/kube.go +++ b/internal/validate/kube/kube.go @@ -494,7 +494,7 @@ func Connections(ctx context.Context, config *Config) ([]validate.Result, error) Stderr: &stderr, }) if err != nil { - return nil, err + return nil, errors.Wrapf(err, "connecting to %s", c.src.Name) } if stderr.String() != "" { From 448c1ae509fe5463a91200b62edf5ccc3478faa8 Mon Sep 17 00:00:00 2001 From: Varun Gandhi Date: Wed, 15 May 2024 21:42:05 +0800 Subject: [PATCH 413/647] Fix lint error due to variable name mixup (#1084) --- cmd/src/code_intel_upload.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/cmd/src/code_intel_upload.go b/cmd/src/code_intel_upload.go index acfd58104f..71d62116c6 100644 --- a/cmd/src/code_intel_upload.go +++ b/cmd/src/code_intel_upload.go @@ -250,11 +250,11 @@ func handleUploadError(accessToken string, err error) error { return err } -func attachHintsForAuthorizationError(accessToken string, err error) error { +func attachHintsForAuthorizationError(accessToken string, originalError error) error { var actionableHints []string likelyTokenError := accessToken == "" - if _, err = accesstoken.ParsePersonalAccessToken(accessToken); accessToken != "" && err != nil { + if _, parseErr := accesstoken.ParsePersonalAccessToken(accessToken); accessToken != "" && parseErr != nil { likelyTokenError = true actionableHints = append(actionableHints, "However, the provided access token does not match expected format; was it truncated?", @@ -262,7 +262,7 @@ func attachHintsForAuthorizationError(accessToken string, err error) error { } if likelyTokenError { - return errorWithHint{err: err, hint: strings.Join(mergeStringSlices( + return errorWithHint{err: originalError, hint: strings.Join(mergeStringSlices( []string{"A Sourcegraph access token must be provided via SRC_ACCESS_TOKEN for uploading SCIP/LSIF data."}, actionableHints, []string{"For more details, see https://sourcegraph.com/docs/cli/how-tos/creating_an_access_token."}, @@ -303,7 +303,7 @@ func attachHintsForAuthorizationError(accessToken string, err error) error { ) } - return errorWithHint{err: err, hint: strings.Join(mergeStringSlices( + return errorWithHint{err: originalError, hint: strings.Join(mergeStringSlices( []string{"This Sourcegraph instance has enforced auth for SCIP/LSIF uploads."}, actionableHints, []string{"For more details, see https://docs.sourcegraph.com/cli/references/code-intel/upload."}, From 3f5a593f44ea0584851b378cee613dc502a83d45 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 15 May 2024 08:49:20 -0500 Subject: [PATCH 414/647] Update dependency tar to v7 (#1074) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- npm-distribution/package.json | 2 +- npm-distribution/yarn.lock | 326 +++++++++++++++++++++++++++++----- 2 files changed, 284 insertions(+), 44 deletions(-) diff --git a/npm-distribution/package.json b/npm-distribution/package.json index f5992fb124..a40365a444 100644 --- a/npm-distribution/package.json +++ b/npm-distribution/package.json @@ -17,7 +17,7 @@ "sourcegraph" ], "dependencies": { - "tar": "^6.2.1" + "tar": "^7.1.0" }, "devDependencies": { "@types/tar": "6.1.13" diff --git a/npm-distribution/yarn.lock b/npm-distribution/yarn.lock index aba642fe29..2061882caf 100644 --- a/npm-distribution/yarn.lock +++ b/npm-distribution/yarn.lock @@ -2,6 +2,30 @@ # yarn lockfile v1 +"@isaacs/cliui@^8.0.2": + version "8.0.2" + resolved "https://registry.yarnpkg.com/@isaacs/cliui/-/cliui-8.0.2.tgz#b37667b7bc181c168782259bab42474fbf52b550" + integrity sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA== + dependencies: + string-width "^5.1.2" + string-width-cjs "npm:string-width@^4.2.0" + strip-ansi "^7.0.1" + strip-ansi-cjs "npm:strip-ansi@^6.0.1" + wrap-ansi "^8.1.0" + wrap-ansi-cjs "npm:wrap-ansi@^7.0.0" + +"@isaacs/fs-minipass@^4.0.0": + version "4.0.1" + resolved "https://registry.yarnpkg.com/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz#2d59ae3ab4b38fb4270bfa23d30f8e2e86c7fe32" + integrity sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w== + dependencies: + minipass "^7.0.4" + +"@pkgjs/parseargs@^0.11.0": + version "0.11.0" + resolved "https://registry.yarnpkg.com/@pkgjs/parseargs/-/parseargs-0.11.0.tgz#a77ea742fab25775145434eb1d2328cf5013ac33" + integrity sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg== + "@types/node@*": version "17.0.36" resolved "https://registry.yarnpkg.com/@types/node/-/node-17.0.36.tgz#c0d5f2fe76b47b63e0e0efc3d2049a9970d68794" @@ -15,61 +39,277 @@ "@types/node" "*" minipass "^4.0.0" -chownr@^2.0.0: +ansi-regex@^5.0.1: + version "5.0.1" + resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-5.0.1.tgz#082cb2c89c9fe8659a311a53bd6a4dc5301db304" + integrity sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ== + +ansi-regex@^6.0.1: + version "6.0.1" + resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-6.0.1.tgz#3183e38fae9a65d7cb5e53945cd5897d0260a06a" + integrity sha512-n5M855fKb2SsfMIiFFoVrABHJC8QtHwVx+mHWP3QcEqBHYienj5dHSgjbxtC0WEZXYt4wcD6zrQElDPhFuZgfA== + +ansi-styles@^4.0.0: + version "4.3.0" + resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-4.3.0.tgz#edd803628ae71c04c85ae7a0906edad34b648937" + integrity sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg== + dependencies: + color-convert "^2.0.1" + +ansi-styles@^6.1.0: + version "6.2.1" + resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-6.2.1.tgz#0e62320cf99c21afff3b3012192546aacbfb05c5" + integrity sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug== + +balanced-match@^1.0.0: + version "1.0.2" + resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.2.tgz#e83e3a7e3f300b34cb9d87f615fa0cbf357690ee" + integrity sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw== + +brace-expansion@^2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-2.0.1.tgz#1edc459e0f0c548486ecf9fc99f2221364b9a0ae" + integrity sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA== + dependencies: + balanced-match "^1.0.0" + +chownr@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/chownr/-/chownr-3.0.0.tgz#9855e64ecd240a9cc4267ce8a4aa5d24a1da15e4" + integrity sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g== + +color-convert@^2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/color-convert/-/color-convert-2.0.1.tgz#72d3a68d598c9bdb3af2ad1e84f21d896abd4de3" + integrity sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ== + dependencies: + color-name "~1.1.4" + +color-name@~1.1.4: + version "1.1.4" + resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.4.tgz#c2a09a87acbde69543de6f63fa3995c826c536a2" + integrity sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA== + +cross-spawn@^7.0.0: + version "7.0.3" + resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-7.0.3.tgz#f73a85b9d5d41d045551c177e2882d4ac85728a6" + integrity sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w== + dependencies: + path-key "^3.1.0" + shebang-command "^2.0.0" + which "^2.0.1" + +eastasianwidth@^0.2.0: + version "0.2.0" + resolved "https://registry.yarnpkg.com/eastasianwidth/-/eastasianwidth-0.2.0.tgz#696ce2ec0aa0e6ea93a397ffcf24aa7840c827cb" + integrity sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA== + +emoji-regex@^8.0.0: + version "8.0.0" + resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-8.0.0.tgz#e818fd69ce5ccfcb404594f842963bf53164cc37" + integrity sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A== + +emoji-regex@^9.2.2: + version "9.2.2" + resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-9.2.2.tgz#840c8803b0d8047f4ff0cf963176b32d4ef3ed72" + integrity sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg== + +foreground-child@^3.1.0: + version "3.1.1" + resolved "https://registry.yarnpkg.com/foreground-child/-/foreground-child-3.1.1.tgz#1d173e776d75d2772fed08efe4a0de1ea1b12d0d" + integrity sha512-TMKDUnIte6bfb5nWv7V/caI169OHgvwjb7V4WkeUvbQQdjr5rWKqHFiKWb/fcOwB+CzBT+qbWjvj+DVwRskpIg== + dependencies: + cross-spawn "^7.0.0" + signal-exit "^4.0.1" + +glob@^10.3.7: + version "10.3.15" + resolved "https://registry.yarnpkg.com/glob/-/glob-10.3.15.tgz#e72bc61bc3038c90605f5dd48543dc67aaf3b50d" + integrity sha512-0c6RlJt1TICLyvJYIApxb8GsXoai0KUP7AxKKAtsYXdgJR1mGEUa7DgwShbdk1nly0PYoZj01xd4hzbq3fsjpw== + dependencies: + foreground-child "^3.1.0" + jackspeak "^2.3.6" + minimatch "^9.0.1" + minipass "^7.0.4" + path-scurry "^1.11.0" + +is-fullwidth-code-point@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz#f116f8064fe90b3f7844a38997c0b75051269f1d" + integrity sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg== + +isexe@^2.0.0: version "2.0.0" - resolved "https://registry.yarnpkg.com/chownr/-/chownr-2.0.0.tgz#15bfbe53d2eab4cf70f18a8cd68ebe5b3cb1dece" - integrity sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ== + resolved "https://registry.yarnpkg.com/isexe/-/isexe-2.0.0.tgz#e8fbf374dc556ff8947a10dcb0572d633f2cfa10" + integrity sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw== -fs-minipass@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/fs-minipass/-/fs-minipass-2.1.0.tgz#7f5036fdbf12c63c169190cbe4199c852271f9fb" - integrity sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg== +jackspeak@^2.3.6: + version "2.3.6" + resolved "https://registry.yarnpkg.com/jackspeak/-/jackspeak-2.3.6.tgz#647ecc472238aee4b06ac0e461acc21a8c505ca8" + integrity sha512-N3yCS/NegsOBokc8GAdM8UcmfsKiSS8cipheD/nivzr700H+nsMOxJjQnvwOcRYVuFkdH0wGUvW2WbXGmrZGbQ== dependencies: - minipass "^3.0.0" + "@isaacs/cliui" "^8.0.2" + optionalDependencies: + "@pkgjs/parseargs" "^0.11.0" -minipass@^3.0.0: - version "3.3.5" - resolved "https://registry.yarnpkg.com/minipass/-/minipass-3.3.5.tgz#6da7e53a48db8a856eeb9153d85b230a2119e819" - integrity sha512-rQ/p+KfKBkeNwo04U15i+hOwoVBVmekmm/HcfTkTN2t9pbQKCMm4eN5gFeqgrrSp/kH/7BYYhTIHOxGqzbBPaA== +lru-cache@^10.2.0: + version "10.2.2" + resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-10.2.2.tgz#48206bc114c1252940c41b25b41af5b545aca878" + integrity sha512-9hp3Vp2/hFQUiIwKo8XCeFVnrg8Pk3TYNPIR7tJADKi5YfcF7vEaK7avFHTlSy3kOKYaJQaalfEo6YuXdceBOQ== + +minimatch@^9.0.1: + version "9.0.4" + resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-9.0.4.tgz#8e49c731d1749cbec05050ee5145147b32496a51" + integrity sha512-KqWh+VchfxcMNRAJjj2tnsSJdNbHsVgnkBhTNrW7AjVo6OvLtxw8zfT9oLw1JSohlFzJ8jCoTgaoXvJ+kHt6fw== dependencies: - yallist "^4.0.0" + brace-expansion "^2.0.1" minipass@^4.0.0: version "4.2.8" resolved "https://registry.yarnpkg.com/minipass/-/minipass-4.2.8.tgz#f0010f64393ecfc1d1ccb5f582bcaf45f48e1a3a" integrity sha512-fNzuVyifolSLFL4NzpF+wEF4qrgqaaKX0haXPQEdQ7NKAN+WecoKMHV09YcuL/DHxrUsYQOK3MiuDf7Ip2OXfQ== -minipass@^5.0.0: - version "5.0.0" - resolved "https://registry.yarnpkg.com/minipass/-/minipass-5.0.0.tgz#3e9788ffb90b694a5d0ec94479a45b5d8738133d" - integrity sha512-3FnjYuehv9k6ovOEbyOswadCDPX1piCfhV8ncmYtHOjuPwylVWsghTLo7rabjC3Rx5xD4HDx8Wm1xnMF7S5qFQ== +"minipass@^5.0.0 || ^6.0.2 || ^7.0.0", minipass@^7.0.4, minipass@^7.1.0: + version "7.1.1" + resolved "https://registry.yarnpkg.com/minipass/-/minipass-7.1.1.tgz#f7f85aff59aa22f110b20e27692465cf3bf89481" + integrity sha512-UZ7eQ+h8ywIRAW1hIEl2AqdwzJucU/Kp59+8kkZeSvafXhZjul247BvIJjEVFVeON6d7lM46XX1HXCduKAS8VA== -minizlib@^2.1.1: - version "2.1.2" - resolved "https://registry.yarnpkg.com/minizlib/-/minizlib-2.1.2.tgz#e90d3466ba209b932451508a11ce3d3632145931" - integrity sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg== +minizlib@^3.0.1: + version "3.0.1" + resolved "https://registry.yarnpkg.com/minizlib/-/minizlib-3.0.1.tgz#46d5329d1eb3c83924eff1d3b858ca0a31581012" + integrity sha512-umcy022ILvb5/3Djuu8LWeqUa8D68JaBzlttKeMWen48SjabqS3iY5w/vzeMzMUNhLDifyhbOwKDSznB1vvrwg== dependencies: - minipass "^3.0.0" - yallist "^4.0.0" + minipass "^7.0.4" + rimraf "^5.0.5" -mkdirp@^1.0.3: - version "1.0.4" - resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-1.0.4.tgz#3eb5ed62622756d79a5f0e2a221dfebad75c2f7e" - integrity sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw== +mkdirp@^3.0.1: + version "3.0.1" + resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-3.0.1.tgz#e44e4c5607fb279c168241713cc6e0fea9adcb50" + integrity sha512-+NsyUUAZDmo6YVHzL/stxSu3t9YS1iljliy3BSDrXJ/dkn1KYdmtZODGGjLcc9XLgVVpH4KshHB8XmZgMhaBXg== -tar@^6.2.1: - version "6.2.1" - resolved "https://registry.yarnpkg.com/tar/-/tar-6.2.1.tgz#717549c541bc3c2af15751bea94b1dd068d4b03a" - integrity sha512-DZ4yORTwrbTj/7MZYq2w+/ZFdI6OZ/f9SFHR+71gIVUZhOQPHzVCLpvRnPgyaMpfWxxk/4ONva3GQSyNIKRv6A== - dependencies: - chownr "^2.0.0" - fs-minipass "^2.0.0" - minipass "^5.0.0" - minizlib "^2.1.1" - mkdirp "^1.0.3" - yallist "^4.0.0" - -yallist@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/yallist/-/yallist-4.0.0.tgz#9bb92790d9c0effec63be73519e11a35019a3a72" - integrity sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A== +path-key@^3.1.0: + version "3.1.1" + resolved "https://registry.yarnpkg.com/path-key/-/path-key-3.1.1.tgz#581f6ade658cbba65a0d3380de7753295054f375" + integrity sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q== + +path-scurry@^1.11.0: + version "1.11.1" + resolved "https://registry.yarnpkg.com/path-scurry/-/path-scurry-1.11.1.tgz#7960a668888594a0720b12a911d1a742ab9f11d2" + integrity sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA== + dependencies: + lru-cache "^10.2.0" + minipass "^5.0.0 || ^6.0.2 || ^7.0.0" + +rimraf@^5.0.5: + version "5.0.7" + resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-5.0.7.tgz#27bddf202e7d89cb2e0381656380d1734a854a74" + integrity sha512-nV6YcJo5wbLW77m+8KjH8aB/7/rxQy9SZ0HY5shnwULfS+9nmTtVXAJET5NdZmCzA4fPI/Hm1wo/Po/4mopOdg== + dependencies: + glob "^10.3.7" + +shebang-command@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/shebang-command/-/shebang-command-2.0.0.tgz#ccd0af4f8835fbdc265b82461aaf0c36663f34ea" + integrity sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA== + dependencies: + shebang-regex "^3.0.0" + +shebang-regex@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/shebang-regex/-/shebang-regex-3.0.0.tgz#ae16f1644d873ecad843b0307b143362d4c42172" + integrity sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A== + +signal-exit@^4.0.1: + version "4.1.0" + resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-4.1.0.tgz#952188c1cbd546070e2dd20d0f41c0ae0530cb04" + integrity sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw== + +"string-width-cjs@npm:string-width@^4.2.0": + version "4.2.3" + resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010" + integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g== + dependencies: + emoji-regex "^8.0.0" + is-fullwidth-code-point "^3.0.0" + strip-ansi "^6.0.1" + +string-width@^4.1.0: + version "4.2.3" + resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010" + integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g== + dependencies: + emoji-regex "^8.0.0" + is-fullwidth-code-point "^3.0.0" + strip-ansi "^6.0.1" + +string-width@^5.0.1, string-width@^5.1.2: + version "5.1.2" + resolved "https://registry.yarnpkg.com/string-width/-/string-width-5.1.2.tgz#14f8daec6d81e7221d2a357e668cab73bdbca794" + integrity sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA== + dependencies: + eastasianwidth "^0.2.0" + emoji-regex "^9.2.2" + strip-ansi "^7.0.1" + +"strip-ansi-cjs@npm:strip-ansi@^6.0.1": + version "6.0.1" + resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9" + integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A== + dependencies: + ansi-regex "^5.0.1" + +strip-ansi@^6.0.0, strip-ansi@^6.0.1: + version "6.0.1" + resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9" + integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A== + dependencies: + ansi-regex "^5.0.1" + +strip-ansi@^7.0.1: + version "7.1.0" + resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-7.1.0.tgz#d5b6568ca689d8561370b0707685d22434faff45" + integrity sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ== + dependencies: + ansi-regex "^6.0.1" + +tar@^7.1.0: + version "7.1.0" + resolved "https://registry.yarnpkg.com/tar/-/tar-7.1.0.tgz#c6d4ec5b10ccdffe8bc412b206eaeaf5181f3098" + integrity sha512-ENhg4W6BmjYxl8GTaE7/h99f0aXiSWv4kikRZ9n2/JRxypZniE84ILZqimAhxxX7Zb8Px6pFdheW3EeHfhnXQQ== + dependencies: + "@isaacs/fs-minipass" "^4.0.0" + chownr "^3.0.0" + minipass "^7.1.0" + minizlib "^3.0.1" + mkdirp "^3.0.1" + yallist "^5.0.0" + +which@^2.0.1: + version "2.0.2" + resolved "https://registry.yarnpkg.com/which/-/which-2.0.2.tgz#7c6a8dd0a636a0327e10b59c9286eee93f3f51b1" + integrity sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA== + dependencies: + isexe "^2.0.0" + +"wrap-ansi-cjs@npm:wrap-ansi@^7.0.0": + version "7.0.0" + resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-7.0.0.tgz#67e145cff510a6a6984bdf1152911d69d2eb9e43" + integrity sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q== + dependencies: + ansi-styles "^4.0.0" + string-width "^4.1.0" + strip-ansi "^6.0.0" + +wrap-ansi@^8.1.0: + version "8.1.0" + resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-8.1.0.tgz#56dc22368ee570face1b49819975d9b9a5ead214" + integrity sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ== + dependencies: + ansi-styles "^6.1.0" + string-width "^5.0.1" + strip-ansi "^7.0.1" + +yallist@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/yallist/-/yallist-5.0.0.tgz#00e2de443639ed0d78fd87de0d27469fbcffb533" + integrity sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw== From 6158b6e9fe9729832a08e140bd47e890a87b6f28 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 15 May 2024 08:50:20 -0500 Subject: [PATCH 415/647] Update dependency io_bazel_rules_go to v0.47.1 (#1073) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- WORKSPACE | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/WORKSPACE b/WORKSPACE index 9d274704e8..48f5d167b5 100644 --- a/WORKSPACE +++ b/WORKSPACE @@ -22,10 +22,10 @@ http_archive( http_archive( name = "io_bazel_rules_go", - sha256 = "80a98277ad1311dacd837f9b16db62887702e9f1d1c4c9f796d0121a46c8e184", + sha256 = "f74c98d6df55217a36859c74b460e774abc0410a47cc100d822be34d5f990f16", urls = [ - "https://mirror.bazel.build/github.com/bazelbuild/rules_go/releases/download/v0.46.0/rules_go-v0.46.0.zip", - "https://github.com/bazelbuild/rules_go/releases/download/v0.46.0/rules_go-v0.46.0.zip", + "https://mirror.bazel.build/github.com/bazelbuild/rules_go/releases/download/v0.47.1/rules_go-v0.47.1.zip", + "https://github.com/bazelbuild/rules_go/releases/download/v0.47.1/rules_go-v0.47.1.zip", ], ) From f29ca46a44e795a4826124cd18b9c41485a783c8 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 15 May 2024 08:53:16 -0500 Subject: [PATCH 416/647] Update golang Docker tag to v1.22.3 (#1075) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .tool-versions | 2 +- Dockerfile | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.tool-versions b/.tool-versions index 2de72235ac..1f701cea04 100644 --- a/.tool-versions +++ b/.tool-versions @@ -1,3 +1,3 @@ -golang 1.22.2 +golang 1.22.3 shfmt 3.8.0 shellcheck 0.10.0 diff --git a/Dockerfile b/Dockerfile index cd271f13b4..7f9143688a 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,7 +4,7 @@ # # Nothing fancy here: we copy in the source code and build on the Alpine Go # image. Refer to .dockerignore to get a sense of what we're not going to copy. -FROM golang:1.22.2-alpine@sha256:cdc86d9f363e8786845bea2040312b4efa321b828acdeb26f393faa864d887b0 as builder +FROM golang:1.22.3-alpine@sha256:df479aa7d1298917c7de7fd56c7231ec450149f1e63d960ea96aebf9ff9240c5 as builder COPY . /src WORKDIR /src From f8ab44741d523a58cb1aef4155808d640369f998 Mon Sep 17 00:00:00 2001 From: Craig Furman Date: Wed, 15 May 2024 15:48:55 +0100 Subject: [PATCH 417/647] fix go-generate command in goreleaser config (#1085) https://github.com/golang/go/issues/60079 changed the behavior of go-generate when the target package does not exist. It used to silently succeeed, now it errors. The schema package was removed in 2021. --- .goreleaser.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.goreleaser.yml b/.goreleaser.yml index 392fb61caf..e82823cf09 100644 --- a/.goreleaser.yml +++ b/.goreleaser.yml @@ -10,7 +10,7 @@ before: hooks: - go mod download - go mod tidy - - go generate ./schema + - go generate ./... builds: - main: ./cmd/src/ From ca1948c600e208b50066e60becf855df1e9b3b57 Mon Sep 17 00:00:00 2001 From: Craig Furman Date: Wed, 15 May 2024 16:13:06 +0100 Subject: [PATCH 418/647] fix .goreleaser-patch.yml (#1086) Same go command regression as previous commit. We just forgot a goreleaser file. --- .goreleaser-patch.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.goreleaser-patch.yml b/.goreleaser-patch.yml index f7307e5474..5650e19d6b 100644 --- a/.goreleaser-patch.yml +++ b/.goreleaser-patch.yml @@ -11,7 +11,7 @@ before: hooks: - go mod download - go mod tidy - - go generate ./schema + - go generate ./... builds: - main: ./cmd/src/ From d16db0a6714fb03ba54cd1cfbec90f6dc21101b0 Mon Sep 17 00:00:00 2001 From: Varun Gandhi Date: Thu, 16 May 2024 17:21:19 +0800 Subject: [PATCH 419/647] docs: Add CHANGELOG entry for v5.4.0 (#1087) --- CHANGELOG.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1e6d8b71dd..8f90f49387 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,17 @@ All notable changes to `src-cli` are documented in this file. ### Removed +## 5.4.0 + +### Added + +### Changed + +- Improved error message when `src code-intel upload` runs into an authorization error. Sourcegraph versions after 5.4.0 require an access token to be passed via the `SRC_ACCESS_TOKEN` environment variable for SCIP uploads. [#1079](https://github.com/sourcegraph/src-cli/pull/1079) +- Improved error message when `src validate` runs into a connection error. [#1081](https://github.com/sourcegraph/src-cli/pull/1081) + +### Fixed + ## 5.3.0 ### Added From 3ce717fe9ce315d69473191df8a033c5dc8a4a34 Mon Sep 17 00:00:00 2001 From: Craig Furman Date: Tue, 21 May 2024 17:03:16 +0100 Subject: [PATCH 420/647] validate subcommand: various changes (#1088) Remove "connections" validation. This checked that various services were TCP-reachable (and resolvable by kube-dns), from various pods. For example, it checked that pgsql was reachable from frontend. This particular validation wouldn't always be useful, e.g. when external postgres clusters were used. It was also failing due to the removal of `nc` from base images. This upstream health-checking _could_ be replaced by doing this check in the readiness probe handler. For example: frontend pods could check the availability of a pgsql connection, and fail their readiness probe if that is unavailable. This is a contentious topic however and should be approached with caution: mean-time-to-recovery can actually substantially increase under some configurations due to cascading failing readiness probes. This commit conservatively aims to restore utility of src-validate by removing the always-failing connections check, and there are no immediate plans to add upstream readiness probing. This commit also changes src-validate to exit with non-zero status when there are no pods and/or services. This white-box check does have some utility, as a sanity check that we've deployed anything at all. The "no PVCs" case is left as a warning, in case the user is using external DBs everywhere, and might legitimately have no PVCs in their namespace. This closes https://linear.app/sourcegraph/issue/REL-42/src-validate-should-not-exit-with-zero-when-no-pods-are-available-at and https://linear.app/sourcegraph/issue/REL-40/fix-src-validate-now-that-nc-is-not-available, assuming we agree with https://linear.app/sourcegraph/issue/REL-40/fix-src-validate-now-that-nc-is-not-available#comment-7b40beee. It will be followed-up with an implementation of https://linear.app/sourcegraph/issue/REL-43/src-validate-should-perform-black-box-validations-of-core-flows. --- CHANGELOG.md | 4 + internal/validate/kube/kube.go | 141 +-------------------------------- 2 files changed, 8 insertions(+), 137 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8f90f49387..fc021464ee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,10 @@ All notable changes to `src-cli` are documented in this file. ### Fixed +- validate kube: connections check removed. +- validate kube: exits non-zero when there are no pods or services in the target + namespace. + ### Removed ## 5.4.0 diff --git a/internal/validate/kube/kube.go b/internal/validate/kube/kube.go index dd1db3d510..a1382e9116 100644 --- a/internal/validate/kube/kube.go +++ b/internal/validate/kube/kube.go @@ -1,7 +1,6 @@ package kube import ( - "bytes" "context" "fmt" "io" @@ -9,17 +8,14 @@ import ( "os" "path/filepath" "reflect" - "regexp" "strings" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" - "k8s.io/client-go/kubernetes/scheme" "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" - "k8s.io/client-go/tools/remotecommand" "k8s.io/client-go/util/homedir" "github.com/aws/aws-sdk-go-v2/service/ec2" @@ -30,12 +26,6 @@ import ( "github.com/sourcegraph/sourcegraph/lib/errors" ) -var ( - sourcegraphFrontend = regexp.MustCompile(`^sourcegraph-frontend-.*`) - sourcegraphRepoUpdater = regexp.MustCompile(`^repo-updater-.*`) - sourcegraphWorker = regexp.MustCompile(`^worker-.*`) -) - type Option = func(config *Config) type Config struct { @@ -95,7 +85,6 @@ func Validate(ctx context.Context, clientSet *kubernetes.Clientset, restConfig * {Pods, "validating pods", "pods validated", "validating pods failed"}, {Services, "validating services", "services validated", "validating services failed"}, {PVCs, "validating pvcs", "pvcs validated", "validating pvcs failed"}, - {Connections, "validating connections", "connections validated", "validating connections failed"}, } if cfg.eks { @@ -213,9 +202,9 @@ func Pods(ctx context.Context, config *Config) ([]validate.Result, error) { if len(pods.Items) == 0 { results = append(results, validate.Result{ - Status: validate.Warning, + Status: validate.Failure, Message: fmt.Sprintf( - "No pods exist on namespace '%s'. check namespace/cluster", + "no pods exist in namespace '%s'. check namespace/cluster", config.namespace, ), }) @@ -305,9 +294,9 @@ func Services(ctx context.Context, config *Config) ([]validate.Result, error) { if len(services.Items) <= 1 { results = append(results, validate.Result{ - Status: validate.Warning, + Status: validate.Failure, Message: fmt.Sprintf( - "unexpected number of services on namespace '%s'; check namespace/cluster", + "no services in namespace '%s'; check namespace/cluster", config.namespace, ), }) @@ -384,128 +373,6 @@ func validatePVC(pvc *corev1.PersistentVolumeClaim) []validate.Result { return results } -type connection struct { - src corev1.Pod - dest []dest -} - -type dest struct { - addr string - port string -} - -// Connections will validate that Sourcegraph services can reach each other over the network. -func Connections(ctx context.Context, config *Config) ([]validate.Result, error) { - var results []validate.Result - var connections []connection - - pods, err := config.clientSet.CoreV1().Pods(config.namespace).List(ctx, metav1.ListOptions{}) - if err != nil { - return nil, err - } - - if len(pods.Items) == 0 { - results = append(results, validate.Result{ - Status: validate.Warning, - Message: fmt.Sprintf( - "cannot check connections: zero pods exist in namespace '%s'", - config.namespace, - ), - }) - - return results, nil - } - - // iterate through pods looking for specific pod name prefixes, then construct - // a relationship map between pods that should have connectivity with each other - for _, pod := range pods.Items { - switch name := pod.Name; { - case sourcegraphFrontend.MatchString(name): // pod is one of the sourcegraph front-end pods - connections = append(connections, connection{ - src: pod, - dest: []dest{ - { - addr: "pgsql", - port: "5432", - }, - { - addr: "indexed-search", - port: "6070", - }, - { - addr: "repo-updater", - port: "3182", - }, - { - addr: "syntect-server", - port: "9238", - }, - }, - }) - case sourcegraphWorker.MatchString(name): // pod is a worker pod - connections = append(connections, connection{ - src: pod, - dest: []dest{ - { - addr: "pgsql", - port: "5432", - }, - }, - }) - case sourcegraphRepoUpdater.MatchString(name): - connections = append(connections, connection{ - src: pod, - dest: []dest{ - { - addr: "pgsql", - port: "5432", - }, - }, - }) - } - } - - // use network relationships constructed above to test network connection for each relationship - for _, c := range connections { - for _, d := range c.dest { - req := config.clientSet.CoreV1().RESTClient().Post(). - Resource("pods"). - Name(c.src.Name). - Namespace(c.src.Namespace). - SubResource("exec") - - req.VersionedParams(&corev1.PodExecOptions{ - Command: []string{"/usr/bin/nc", "-z", d.addr, d.port}, - Stdin: false, - Stdout: true, - Stderr: true, - TTY: false, - }, scheme.ParameterCodec) - - exec, err := remotecommand.NewSPDYExecutor(config.restConfig, "POST", req.URL()) - if err != nil { - return nil, err - } - - var stdout, stderr bytes.Buffer - - err = exec.StreamWithContext(ctx, remotecommand.StreamOptions{ - Stdout: &stdout, - Stderr: &stderr, - }) - if err != nil { - return nil, errors.Wrapf(err, "connecting to %s", c.src.Name) - } - - if stderr.String() != "" { - results = append(results, validate.Result{Status: validate.Failure, Message: stderr.String()}) - } - } - } - - return results, nil -} - func CurrentContextSetTo(clusterService string) error { currentContext, err := GetCurrentContext() if err != nil { From dcc02b220e1097c352d66b78305a0040c68f1fcd Mon Sep 17 00:00:00 2001 From: Matthew Manela Date: Mon, 17 Jun 2024 13:01:48 -0400 Subject: [PATCH 421/647] fix(Source): Fix broken code host doc links (#1096) --- CHANGELOG.md | 2 +- cmd/src/servegit.go | 2 +- internal/servegit/serve.go | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fc021464ee..df998a6cf5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1016,7 +1016,7 @@ Re-release of 3.29.3 for Sourcegraph 3.30. ### Added -- New command `src serve-git` which can serve local repositories for Sourcegraph to clone. This was previously in a command called `src-expose`. See [serving local repositories](https://docs.sourcegraph.com/admin/external_service/src_serve_git) in our documentation to find out more. [#12363](https://github.com/sourcegraph/sourcegraph/issues/12363) +- New command `src serve-git` which can serve local repositories for Sourcegraph to clone. This was previously in a command called `src-expose`. See [serving local repositories](https://sourcegraph.com/docs/admin/code_hosts/src_serve_git) in our documentation to find out more. [#12363](https://github.com/sourcegraph/sourcegraph/issues/12363) - When used with Sourcegraph 3.18 or later, campaigns can now be created on GitLab. [#231](https://github.com/sourcegraph/src-cli/pull/231) ## 3.16.1 diff --git a/cmd/src/servegit.go b/cmd/src/servegit.go index 99d46ddb30..8a9e96d1ec 100644 --- a/cmd/src/servegit.go +++ b/cmd/src/servegit.go @@ -24,7 +24,7 @@ By default 'src serve-git' will recursively serve your current directory on the 'src serve-git -list' will not start up the server. Instead it will write to stdout a list of repository names it would serve. -Documentation at https://docs.sourcegraph.com/admin/external_service/src_serve_git +Documentation at https://sourcegraph.com/docs/admin/code_hosts/src_serve_git `) } var ( diff --git a/internal/servegit/serve.go b/internal/servegit/serve.go index aa845dbe04..306bc67aa4 100644 --- a/internal/servegit/serve.go +++ b/internal/servegit/serve.go @@ -253,7 +253,7 @@ func (s *Serve) Repos() ([]Repo, error) { func explainAddr(addr string) string { return fmt.Sprintf(`Serving the repositories at http://%s. -See https://docs.sourcegraph.com/admin/external_service/src_serve_git for +See https://sourcegraph.com/docs/admin/code_hosts/src_serve_git for instructions to configure in Sourcegraph. `, addr) } From 1a448323be88b97b225a48da65b9dc1013c308df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=93lafur=20P=C3=A1ll=20Geirsson?= Date: Wed, 3 Jul 2024 14:50:55 +0200 Subject: [PATCH 422/647] Fix windows installation (#1098) Fixes #1050. Previously, it was not possible to install src-cli via npm on Windows. It was also not possible to publish the npm package on Windows. This PR fixes both problems. The second problem had to be solved so I could manually test the fix for this PR.: --- npm-distribution/.gitignore | 1 + npm-distribution/copy-files.js | 8 ++++++++ npm-distribution/install.js | 9 ++++++--- npm-distribution/package.json | 2 +- 4 files changed, 16 insertions(+), 4 deletions(-) create mode 100644 npm-distribution/copy-files.js diff --git a/npm-distribution/.gitignore b/npm-distribution/.gitignore index b1738c9bda..9117026fc7 100644 --- a/npm-distribution/.gitignore +++ b/npm-distribution/.gitignore @@ -1,3 +1,4 @@ node_modules/ src LICENSE +README.md diff --git a/npm-distribution/copy-files.js b/npm-distribution/copy-files.js new file mode 100644 index 0000000000..17b2fe14a2 --- /dev/null +++ b/npm-distribution/copy-files.js @@ -0,0 +1,8 @@ +const fs = require('fs') +const path = require('path') + +const licensePath = path.join(__dirname, '..', 'LICENSE') +const readmePath = path.join(__dirname, '..', 'README.md') + +fs.copyFileSync(licensePath, path.join(__dirname, 'LICENSE')) +fs.copyFileSync(readmePath, path.join(__dirname, 'README.md')) diff --git a/npm-distribution/install.js b/npm-distribution/install.js index 5601449779..178c2759ec 100644 --- a/npm-distribution/install.js +++ b/npm-distribution/install.js @@ -56,9 +56,12 @@ get(assetURL, (response) => { } response .pipe(zlib.createGunzip()) - .pipe(tar.x({ filter: (x) => x === "src" })) - .addListener("close", () => fs.chmodSync(executableName, "755")); -}); + .pipe(tar.x({ filter: (x) => x === executableName })) + .addListener("close", () => { + if (process.platform !== 'win32') { + fs.chmodSync(executableName, "755"); + } + });}); // Follow redirects. function get(url, callback) { diff --git a/npm-distribution/package.json b/npm-distribution/package.json index a40365a444..f0e44a82bf 100644 --- a/npm-distribution/package.json +++ b/npm-distribution/package.json @@ -7,7 +7,7 @@ "license": "Apache-2.0", "scripts": { "install": "node install.js", - "prepack": "cp ../LICENSE . && cp ../README.md ." + "prepack": "node copy-files.js" }, "main": "src.js", "bin": { From 3e384c440ff97b5a85a89cd1b191476e7edc4453 Mon Sep 17 00:00:00 2001 From: Stefan Hengl Date: Wed, 10 Jul 2024 09:29:16 +0200 Subject: [PATCH 423/647] batches: support new version field (#1100) This bumps sourcegraph/sourcegraph/lib to pull in the latest changes from https://github.com/sourcegraph/sourcegraph/pull/63613 to support the new `version` field for batch specs. Notes: - To resolve repos, batches calls the GraphQL endpoint `resolveWorkspacesForBatchSpec`, which takes the serialized spec. This means all the logic to resolve repos is outsourced to Sourcegraph. This is great news for this PR because we don't have to worry how `on.RepositoriesMatchingQuery` is interpreted. The code path in which src-cli itself resolves the workspaces was removed in #819. ### Test plan - New unit tests - Manual testing. I tested the following workflow - `src batch new -f test.spec.yaml` (-> spec contains `version: 2`) - `src batch apply -f test.spec.yaml` (-> validation passes, batch spec shows up in Sourcegraph db) - `src batch validate -f test.spec.yaml` (-> validation passes or fails if I change the version to an unsupported value) - `src batch repos -f test.spec.yaml` (-> checked that returned repos match with expected pattern type) Closes SPLF-126 --- CHANGELOG.md | 2 ++ go.mod | 20 +++++------ go.sum | 42 +++++++++++++----------- internal/batches/docker/image.go | 2 +- internal/batches/service/service.go | 3 +- internal/batches/service/service_test.go | 19 +++++++++++ 6 files changed, 56 insertions(+), 32 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index df998a6cf5..c10d6b622f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,8 @@ All notable changes to `src-cli` are documented in this file. ### Added +- Batch Changes: Added support for batch spec versions. Batch specs with `version: 2` will default to keyword search to resolve workspaces if the pattern type is not specified explicitly. (https://github.com/sourcegraph/sourcegraph/pull/63613) + ### Changed ### Fixed diff --git a/go.mod b/go.mod index 6aaf4a0714..cb3b36b057 100644 --- a/go.mod +++ b/go.mod @@ -32,12 +32,12 @@ require ( github.com/sourcegraph/go-diff v0.6.2-0.20221123165719-f8cd299c40f3 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf github.com/sourcegraph/scip v0.3.1-0.20230627154934-45df7f6d33fc - github.com/sourcegraph/sourcegraph/lib v0.0.0-20240510113214-3a8666b99a37 + github.com/sourcegraph/sourcegraph/lib v0.0.0-20240709083501-1af563b61442 github.com/stretchr/testify v1.8.4 - golang.org/x/net v0.21.0 - golang.org/x/sync v0.6.0 + golang.org/x/net v0.26.0 + golang.org/x/sync v0.7.0 google.golang.org/api v0.132.0 - google.golang.org/protobuf v1.31.0 + google.golang.org/protobuf v1.33.0 gopkg.in/yaml.v3 v3.0.1 jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7 k8s.io/api v0.27.1 @@ -171,14 +171,14 @@ require ( go.uber.org/atomic v1.11.0 // indirect go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.24.0 // indirect - golang.org/x/crypto v0.23.0 // indirect - golang.org/x/mod v0.15.0 // indirect + golang.org/x/crypto v0.24.0 // indirect + golang.org/x/mod v0.17.0 // indirect golang.org/x/oauth2 v0.11.0 // indirect - golang.org/x/sys v0.20.0 // indirect - golang.org/x/term v0.20.0 // indirect - golang.org/x/text v0.15.0 // indirect + golang.org/x/sys v0.21.0 // indirect + golang.org/x/term v0.21.0 // indirect + golang.org/x/text v0.16.0 // indirect golang.org/x/time v0.3.0 // indirect - golang.org/x/tools v0.18.0 // indirect + golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d // indirect golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 // indirect google.golang.org/appengine v1.6.7 // indirect google.golang.org/genproto v0.0.0-20231030173426-d783a09b4405 // indirect diff --git a/go.sum b/go.sum index bead6e6a16..6127dde105 100644 --- a/go.sum +++ b/go.sum @@ -388,8 +388,8 @@ github.com/sourcegraph/log v0.0.0-20231018134238-fbadff7458bb h1:tHKdC+bXxxGJ0cy github.com/sourcegraph/log v0.0.0-20231018134238-fbadff7458bb/go.mod h1:IDp09QkoqS8Z3CyN2RW6vXjgABkNpDbyjLIHNQwQ8P8= github.com/sourcegraph/scip v0.3.1-0.20230627154934-45df7f6d33fc h1:o+eq0cjVV3B5ngIBF04Lv3GwttKOuYFF5NTcfXWXzfA= github.com/sourcegraph/scip v0.3.1-0.20230627154934-45df7f6d33fc/go.mod h1:7ZKAtLIUmiMvOIgG5LMcBxdtBXVa0v2GWC4Hm1ASYQ0= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20240510113214-3a8666b99a37 h1:Wdv909oSQbZUGLkmMSlk5b/h48wqfZtrQFofCQ9ELgw= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20240510113214-3a8666b99a37/go.mod h1:JmV9/kgbRQBTGT/72JExxg0tnyJDBDK+fKDVPtkRhrY= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20240709083501-1af563b61442 h1:n3HZCz5fJRtxCzjcUHZwrfJb96xU0+s2L4/+Da2kD3A= +github.com/sourcegraph/sourcegraph/lib v0.0.0-20240709083501-1af563b61442/go.mod h1:RBdAauod1tGL33L1Izr2YymwN8uWQV++fL6orhD4aqc= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I= @@ -445,8 +445,8 @@ golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8U golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20220314234659-1baeb1ce4c0b/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= -golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI= -golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8= +golang.org/x/crypto v0.24.0 h1:mnl8DM0o513X8fdIkmyFE/5hTYxbwYOjDS/+rK6qpRI= +golang.org/x/crypto v0.24.0/go.mod h1:Z1PMYSOR5nyMcyAVAIQSKCDwalqy85Aqn1x3Ws4L5DM= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= @@ -455,8 +455,8 @@ golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.7.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/mod v0.15.0 h1:SernR4v+D55NyBH2QiEQrlBAnj1ECL6AGrA5+dPaMY8= -golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/mod v0.17.0 h1:zY54UmvipHiNd+pm+m0x9KhZ9hl1/7QNMyxXbc6ICqA= +golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -475,8 +475,8 @@ golang.org/x/net v0.0.0-20210614182718-04defd469f4e/go.mod h1:9nx3DQGgdP8bBQD5qx golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.3.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE= -golang.org/x/net v0.21.0 h1:AQyQV4dYCvJ7vGmJyKki9+PBdyvhkSd8EIx/qb0AYv4= -golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44= +golang.org/x/net v0.26.0 h1:soB7SVo0PWrY4vPW/+ay0jKDNScG2X9wFeYlXIvJsOQ= +golang.org/x/net v0.26.0/go.mod h1:5YKkiSynbBIh3p6iOc/vibscux0x38BZDkn8sCUPxHE= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.11.0 h1:vPL4xzxBM4niKCW6g9whtaWVXTJf1U5e4aZxxFx/gbU= @@ -491,8 +491,8 @@ golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220819030929-7fc1605a5dde/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.6.0 h1:5BMeUDZ7vkXGfEr1x9B4bRcTH4lpkTkpdh0T/J+qjbQ= -golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M= +golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -514,13 +514,13 @@ golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220829200755-d48e67d00261/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y= -golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.21.0 h1:rF+pYz3DAGSQAxAu1CbC7catZg4ebC4UIeIhKxBZvws= +golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.3.0/go.mod h1:q750SLmJuPmVoN1blW3UFBPREJfb1KmY3vwxfr+nFDA= -golang.org/x/term v0.20.0 h1:VnkxpohqXaOBYJtBmEppKUG6mXpi+4O6purfc2+sMhw= -golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY= +golang.org/x/term v0.21.0 h1:WVXCp+/EBEHOj53Rvu+7KiT/iElMrO8ACK16SMZ3jaA= +golang.org/x/term v0.21.0/go.mod h1:ooXLefLobQVslOqselCNF4SxFAaoS6KujMbsGzSDmX0= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= @@ -528,8 +528,8 @@ golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk= -golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4= +golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI= golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4= golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -544,8 +544,8 @@ golang.org/x/tools v0.0.0-20200624163319-25775e59acb7/go.mod h1:EkVYQZoAsY45+roY golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.4.0/go.mod h1:UE5sM2OK9E/d67R0ANs2xJizIymRP5gJU295PvKXxjQ= -golang.org/x/tools v0.18.0 h1:k8NLag8AGHnn+PHbl7g43CtqZAwG60vZkLqgyZgIHgQ= -golang.org/x/tools v0.18.0/go.mod h1:GL7B4CwcLLeo59yx/9UWWuNOW1n3VZ4f5axWfML7Lcg= +golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d h1:vU5i/LfpvrRCpgM/VPfJLg5KjxD3E+hfT1SH+d9zLwg= +golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -593,8 +593,8 @@ google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlba google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.27.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8= -google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI= +google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= @@ -633,6 +633,8 @@ k8s.io/utils v0.0.0-20230209194617-a36077c30491 h1:r0BAOLElQnnFhE/ApUsg3iHdVYYPB k8s.io/utils v0.0.0-20230209194617-a36077c30491/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= mvdan.cc/gofumpt v0.4.0 h1:JVf4NN1mIpHogBj7ABpgOyZc65/UUOkKQFkoURsz4MM= mvdan.cc/gofumpt v0.4.0/go.mod h1:PljLOHDeZqgS8opHRKLzp2It2VBuSdteAgqUfzMTxlQ= +pgregory.net/rapid v1.1.0 h1:CMa0sjHSru3puNx+J0MIAuiiEV4N0qj8/cMWGBBCsjw= +pgregory.net/rapid v1.1.0/go.mod h1:PY5XlDGj0+V1FCq0o192FdRhpKHGTRIWBgqjDBTrq04= sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd h1:EDPBXCAspyGV4jQlpZSudPeMmr1bNJefnuqLsRAsHZo= sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd/go.mod h1:B8JuhiUyNFVKdsE8h686QcCxMaH6HrOAZj4vswFpcB0= sigs.k8s.io/structured-merge-diff/v4 v4.2.3 h1:PRbqxJClWWYMNV1dhaG4NsibJbArud9kFxnAMREiWFE= diff --git a/internal/batches/docker/image.go b/internal/batches/docker/image.go index 279ef0b949..8a31d61042 100644 --- a/internal/batches/docker/image.go +++ b/internal/batches/docker/image.go @@ -103,7 +103,7 @@ func (image *image) Ensure(ctx context.Context) error { // docker image inspect will return a non-zero exit code if the image and // tag don't exist locally, regardless of the format. var digest string - if digest, err = inspectDigest(); errors.HasType(err, &fastCommandTimeoutError{}) { + if digest, err = inspectDigest(); errors.HasType[*fastCommandTimeoutError](err) { // Ensure we immediately propagate a timeout up, rather than // trying to tell an unresponsive Docker to pull. return err diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index 99d49a9c21..8fb1116d1f 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -506,7 +506,8 @@ func validateMount(batchSpecDir string, spec *batcheslib.BatchSpec) error { return nil } -const exampleSpecTmpl = `name: NAME-OF-YOUR-BATCH-CHANGE +const exampleSpecTmpl = `version: 2 # Use the latest schema version +name: NAME-OF-YOUR-BATCH-CHANGE description: DESCRIPTION-OF-YOUR-BATCH-CHANGE # "on" specifies on which repositories to execute the "steps". diff --git a/internal/batches/service/service_test.go b/internal/batches/service/service_test.go index dc5aa09c48..33030b5f18 100644 --- a/internal/batches/service/service_test.go +++ b/internal/batches/service/service_test.go @@ -254,6 +254,25 @@ some-new-field: Foo bar `, expectedErr: errors.New("parsing batch spec: Additional property some-new-field is not allowed"), }, + { + name: "supported version", + rawSpec: ` +version: 2 +name: test-spec +description: A test spec +`, + + expectedSpec: &batcheslib.BatchSpec{Version: 2, Name: "test-spec", Description: "A test spec"}, + }, + { + name: "unsupported version", + rawSpec: ` +version: 99 +name: test-spec +description: A test spec +`, + expectedErr: errors.New("parsing batch spec: version: version must be one of the following: 1, 2"), + }, { name: "mount absolute file", batchSpecDir: tempDir, From f17af31256696027cf7beef764693d7403dcde04 Mon Sep 17 00:00:00 2001 From: Shivasurya Date: Fri, 12 Jul 2024 10:07:08 -0400 Subject: [PATCH 424/647] chore(security) : upgrade golang to 1.22.5 to fix CVE (#1102) * upgrade golang to 1.22.5 to fix CVE * upgrade golang to 1.22.5 to fix CVE --- .github/workflows/go-ci.yml | 2 +- .github/workflows/go-lint.yml | 2 +- .github/workflows/goreleaser-check.yml | 2 +- .github/workflows/goreleaser.yml | 2 +- .github/workflows/pr-auditor.yml | 2 +- .tool-versions | 2 +- Dockerfile | 2 +- go.mod | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/.github/workflows/go-ci.yml b/.github/workflows/go-ci.yml index 801eb2603e..fc0fe69ad0 100644 --- a/.github/workflows/go-ci.yml +++ b/.github/workflows/go-ci.yml @@ -7,7 +7,7 @@ jobs: go-test: strategy: matrix: - go-version: [1.22.2] + go-version: [1.22.5] os: [ubuntu-latest, macos-latest, windows-latest] runs-on: ${{ matrix.os }} steps: diff --git a/.github/workflows/go-lint.yml b/.github/workflows/go-lint.yml index 4397d120a0..ab0f04b8b0 100644 --- a/.github/workflows/go-lint.yml +++ b/.github/workflows/go-lint.yml @@ -12,5 +12,5 @@ jobs: - name: Set up Go uses: actions/setup-go@v5 with: - go-version: 1.22.2 + go-version: 1.22.5 - run: ./dev/go-lint.sh diff --git a/.github/workflows/goreleaser-check.yml b/.github/workflows/goreleaser-check.yml index 10557bb790..cd8e72d671 100644 --- a/.github/workflows/goreleaser-check.yml +++ b/.github/workflows/goreleaser-check.yml @@ -16,7 +16,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v5 with: - go-version: 1.22.2 + go-version: 1.22.5 - name: Check GoReleaser config uses: goreleaser/goreleaser-action@v5 with: diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index 95c9c24d24..1924ffcd94 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -177,7 +177,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v5 with: - go-version: 1.22 + go-version: 1.22.5 - run: go test ./... - run: go test -race -v ./... - run: echo "${DOCKER_PASSWORD}" | docker login -u=$DOCKER_USERNAME --password-stdin diff --git a/.github/workflows/pr-auditor.yml b/.github/workflows/pr-auditor.yml index 0edd201a24..ecf7f55ab7 100644 --- a/.github/workflows/pr-auditor.yml +++ b/.github/workflows/pr-auditor.yml @@ -13,7 +13,7 @@ jobs: with: repository: 'sourcegraph/pr-auditor' - uses: actions/setup-go@v5 - with: { go-version: '1.22.2' } + with: { go-version: '1.22.5' } - run: './check-pr.sh' env: diff --git a/.tool-versions b/.tool-versions index 1f701cea04..97a30a5525 100644 --- a/.tool-versions +++ b/.tool-versions @@ -1,3 +1,3 @@ -golang 1.22.3 +golang 1.22.5 shfmt 3.8.0 shellcheck 0.10.0 diff --git a/Dockerfile b/Dockerfile index 7f9143688a..7143b733c2 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,7 +4,7 @@ # # Nothing fancy here: we copy in the source code and build on the Alpine Go # image. Refer to .dockerignore to get a sense of what we're not going to copy. -FROM golang:1.22.3-alpine@sha256:df479aa7d1298917c7de7fd56c7231ec450149f1e63d960ea96aebf9ff9240c5 as builder +FROM golang:1.22.3-alpine@sha256:4707c052e5bd90c1c6ae16d1825e3ea5076ec1b06de30e34596b1e6f6b9916cf as builder COPY . /src WORKDIR /src diff --git a/go.mod b/go.mod index cb3b36b057..0dedbd61c9 100644 --- a/go.mod +++ b/go.mod @@ -2,7 +2,7 @@ module github.com/sourcegraph/src-cli go 1.22 -toolchain go1.22.2 +toolchain go1.22.5 require ( cloud.google.com/go/storage v1.30.1 From d711d0effe57c4a9a8c5c61e1d3d3d2e9962ea29 Mon Sep 17 00:00:00 2001 From: Bolaji Olajide <25608335+BolajiOlajide@users.noreply.github.com> Date: Tue, 16 Jul 2024 12:22:48 +0100 Subject: [PATCH 425/647] workflows: update pr-auditor workflow (#1097) --- .github/workflows/pr-auditor.yml | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/.github/workflows/pr-auditor.yml b/.github/workflows/pr-auditor.yml index ecf7f55ab7..4a0fc2d708 100644 --- a/.github/workflows/pr-auditor.yml +++ b/.github/workflows/pr-auditor.yml @@ -3,7 +3,7 @@ name: pr-auditor on: pull_request_target: types: [ closed, edited, opened, synchronize, ready_for_review ] - workflow_dispatch: + jobs: check-pr: @@ -11,11 +11,12 @@ jobs: steps: - uses: actions/checkout@v4 with: - repository: 'sourcegraph/pr-auditor' + repository: 'sourcegraph/devx-service' + token: ${{ secrets.PR_AUDITOR_TOKEN }} - uses: actions/setup-go@v5 - with: { go-version: '1.22.5' } + with: { go-version: '1.22' } - - run: './check-pr.sh' + - run: 'go run ./cmd/pr-auditor' env: GITHUB_EVENT_PATH: ${{ env.GITHUB_EVENT_PATH }} GITHUB_TOKEN: ${{ secrets.PR_AUDITOR_TOKEN }} From ffb972710454ca51480f7cfe214f90dad865c78d Mon Sep 17 00:00:00 2001 From: Anish Lakhwara Date: Sat, 3 Aug 2024 06:01:20 +1000 Subject: [PATCH 426/647] misc(changelog): prepare for 5.5.0 release (#1104) --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index c10d6b622f..2515ae7b58 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ All notable changes to `src-cli` are documented in this file. ## Unreleased +## 5.5.0 + ### Added - Batch Changes: Added support for batch spec versions. Batch specs with `version: 2` will default to keyword search to resolve workspaces if the pattern type is not specified explicitly. (https://github.com/sourcegraph/sourcegraph/pull/63613) From 919e777f2f8397885e946e9e39b62619f0109ea6 Mon Sep 17 00:00:00 2001 From: Peter Guy Date: Fri, 30 Aug 2024 09:26:47 -0700 Subject: [PATCH 427/647] Fix PR link - 312 --> 317 (#1106) --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2515ae7b58..efa29b3a4b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -970,7 +970,7 @@ Re-release of 3.29.3 for Sourcegraph 3.30. ### Added -- The new `src login` subcommand helps you authenticate `src` to access your Sourcegraph instance with your user credentials. [#317](https://github.com/sourcegraph/src-cli/pull/312) +- The new `src login` subcommand helps you authenticate `src` to access your Sourcegraph instance with your user credentials. [#317](https://github.com/sourcegraph/src-cli/pull/317) ## 3.20.0 From 95b585445cb1899e72f42b9e7f7392f4e47eee03 Mon Sep 17 00:00:00 2001 From: Harish Navnit Date: Sat, 31 Aug 2024 12:54:20 +0800 Subject: [PATCH 428/647] Consistently redirect usage examples to stdout (#1105) * direct help texts to stdout * set usage output for subcommands --- cmd/src/cmd.go | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/cmd/src/cmd.go b/cmd/src/cmd.go index 96a6fcec9e..3ffe235d7d 100644 --- a/cmd/src/cmd.go +++ b/cmd/src/cmd.go @@ -5,6 +5,7 @@ import ( "fmt" "log" "os" + "slices" "strings" "github.com/sourcegraph/sourcegraph/lib/errors" @@ -56,6 +57,7 @@ func (c commander) run(flagSet *flag.FlagSet, cmdName, usageText string, args [] // Print usage if the command is "help". if flagSet.Arg(0) == "help" || flagSet.NArg() == 0 { + flagSet.SetOutput(os.Stdout) flagSet.Usage() os.Exit(0) } @@ -93,10 +95,22 @@ func (c commander) run(flagSet *flag.FlagSet, cmdName, usageText string, args [] panic(fmt.Sprintf("all registered commands should use flag.ExitOnError: error: %s", err)) } + // Show usage examples for subcommand + if len(args) == 0 || slices.IndexFunc(args, func(s string) bool { + return s == "help" || s == "--help" + }) >= 0 { + cmd.flagSet.SetOutput(os.Stdout) + flag.CommandLine.SetOutput(os.Stdout) + cmd.flagSet.Usage() + os.Exit(0) + } + // Execute the subcommand. if err := cmd.handler(flagSet.Args()[1:]); err != nil { if _, ok := err.(*cmderrors.UsageError); ok { log.Printf("error: %s\n\n", err) + cmd.flagSet.SetOutput(os.Stderr) + flag.CommandLine.SetOutput(os.Stderr) cmd.flagSet.Usage() os.Exit(2) } From f51f817fdd22edd9a2969a89b69c2bbdaad2fd9f Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Wed, 2 Oct 2024 14:57:45 +0200 Subject: [PATCH 429/647] update github actions to be able to access private sg/sg (#1112) * update github actions to be able to access private sg/sg * add workflow_dispatch to actions to be able to test actions --- .github/workflows/docker.yml | 1 + .github/workflows/go-ci.yml | 6 +++++- .github/workflows/go-lint.yml | 6 +++++- .github/workflows/goreleaser-check.yml | 3 +++ .github/workflows/goreleaser.yml | 4 ++++ .github/workflows/scip.yml | 8 ++++++-- 6 files changed, 24 insertions(+), 4 deletions(-) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index f778e52620..fcbc016b4c 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -5,6 +5,7 @@ name: Publish Docker image dependencies # We only want to build on releases; this condition is 100% stolen from the # goreleaser action. on: + workflow_dispatch: push: tags: - "*" diff --git a/.github/workflows/go-ci.yml b/.github/workflows/go-ci.yml index fc0fe69ad0..fafe948376 100644 --- a/.github/workflows/go-ci.yml +++ b/.github/workflows/go-ci.yml @@ -1,7 +1,11 @@ name: Go CI on: - - push + workflow_dispatch: + push: +env: + GOPRIVATE: "github.com/sourcegraph/*" + PRIVATE_TOKEN: "${{ secrets.PRIVATE_SG_ACCESS_TOKEN }}" jobs: go-test: diff --git a/.github/workflows/go-lint.yml b/.github/workflows/go-lint.yml index ab0f04b8b0..c394ce0f97 100644 --- a/.github/workflows/go-lint.yml +++ b/.github/workflows/go-lint.yml @@ -1,7 +1,11 @@ name: Go Lint on: - - push + workflow_dispatch: + push: +env: + GOPRIVATE: "github.com/sourcegraph/*" + PRIVATE_TOKEN: "${{ secrets.PRIVATE_SG_ACCESS_TOKEN }}" jobs: go-lint: diff --git a/.github/workflows/goreleaser-check.yml b/.github/workflows/goreleaser-check.yml index cd8e72d671..080a9dc320 100644 --- a/.github/workflows/goreleaser-check.yml +++ b/.github/workflows/goreleaser-check.yml @@ -3,6 +3,9 @@ name: GoReleaser check on: push: workflow_dispatch: +env: + GOPRIVATE: "github.com/sourcegraph/*" + PRIVATE_TOKEN: "${{ secrets.PRIVATE_SG_ACCESS_TOKEN }}" jobs: goreleaser: diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index 1924ffcd94..75ef436158 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -1,9 +1,13 @@ name: Build and Release on: + workflow_dispatch: push: tags: - '*' +env: + GOPRIVATE: "github.com/sourcegraph/*" + PRIVATE_TOKEN: "${{ secrets.PRIVATE_SG_ACCESS_TOKEN }}" # There are two cases where this GitHub action will run: # diff --git a/.github/workflows/scip.yml b/.github/workflows/scip.yml index d2bbd16208..c7a01d2342 100644 --- a/.github/workflows/scip.yml +++ b/.github/workflows/scip.yml @@ -1,6 +1,10 @@ name: SCIP -'on': - - push +on: + workflow_dispatch: + push: +env: + GOPRIVATE: "github.com/sourcegraph/*" + PRIVATE_TOKEN: "${{ secrets.PRIVATE_SG_ACCESS_TOKEN }}" jobs: scip-go: runs-on: ubuntu-latest From 554b80523d8316b50d97e66ec670f085beeccc1a Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Wed, 2 Oct 2024 15:52:03 +0200 Subject: [PATCH 430/647] add required github config (#1113) * add required github config * set no username in git cfg * use different syntax on windows --- .github/workflows/go-ci.yml | 6 ++++++ .github/workflows/go-lint.yml | 2 ++ .github/workflows/goreleaser-check.yml | 2 ++ .github/workflows/goreleaser.yml | 2 ++ .github/workflows/scip.yml | 2 ++ 5 files changed, 14 insertions(+) diff --git a/.github/workflows/go-ci.yml b/.github/workflows/go-ci.yml index fafe948376..7c44620926 100644 --- a/.github/workflows/go-ci.yml +++ b/.github/workflows/go-ci.yml @@ -21,6 +21,12 @@ jobs: uses: actions/setup-go@v5 with: go-version: ${{ matrix.go-version }} + - name: (Windows) Enable pulling Go modules from private sourcegraph/sourcegraph + if: runner.os == 'Windows' + run: git config --global url."https://$env:PRIVATE_TOKEN@github.com/sourcegraph/".insteadOf "https://github.com/sourcegraph/" + - name: (Default) Enable pulling Go modules from private sourcegraph/sourcegraph + if: runner.os != 'Windows' + run: git config --global url."https://${PRIVATE_TOKEN}@github.com/sourcegraph/".insteadOf "https://github.com/sourcegraph/" - run: | go test -race -v ./... go test -v ./... diff --git a/.github/workflows/go-lint.yml b/.github/workflows/go-lint.yml index c394ce0f97..f15416750a 100644 --- a/.github/workflows/go-lint.yml +++ b/.github/workflows/go-lint.yml @@ -17,4 +17,6 @@ jobs: uses: actions/setup-go@v5 with: go-version: 1.22.5 + - name: Enable pulling Go modules from private sourcegraph/sourcegraph + run: git config --global url."https://${PRIVATE_TOKEN}@github.com/sourcegraph/".insteadOf "https://github.com/sourcegraph/" - run: ./dev/go-lint.sh diff --git a/.github/workflows/goreleaser-check.yml b/.github/workflows/goreleaser-check.yml index 080a9dc320..d48d84b75a 100644 --- a/.github/workflows/goreleaser-check.yml +++ b/.github/workflows/goreleaser-check.yml @@ -20,6 +20,8 @@ jobs: uses: actions/setup-go@v5 with: go-version: 1.22.5 + - name: Enable pulling Go modules from private sourcegraph/sourcegraph + run: git config --global url."https://${PRIVATE_TOKEN}@github.com/sourcegraph/".insteadOf "https://github.com/sourcegraph/" - name: Check GoReleaser config uses: goreleaser/goreleaser-action@v5 with: diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index 75ef436158..1bb3523927 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -182,6 +182,8 @@ jobs: uses: actions/setup-go@v5 with: go-version: 1.22.5 + - name: Enable pulling Go modules from private sourcegraph/sourcegraph + run: git config --global url."https://${PRIVATE_TOKEN}@github.com/sourcegraph/".insteadOf "https://github.com/sourcegraph/" - run: go test ./... - run: go test -race -v ./... - run: echo "${DOCKER_PASSWORD}" | docker login -u=$DOCKER_USERNAME --password-stdin diff --git a/.github/workflows/scip.yml b/.github/workflows/scip.yml index c7a01d2342..a1969f7f6f 100644 --- a/.github/workflows/scip.yml +++ b/.github/workflows/scip.yml @@ -16,6 +16,8 @@ jobs: chmod +x /usr/local/bin/src - name: Set directory to safe for git run: git config --global --add safe.directory $GITHUB_WORKSPACE + - name: Enable pulling Go modules from private sourcegraph/sourcegraph + run: git config --global url."https://${PRIVATE_TOKEN}@github.com/sourcegraph/".insteadOf "https://github.com/sourcegraph/" - name: Generate SCIP data run: scip-go From 099c8c0ee7062651bd577694f6bcbf59ff3bb08e Mon Sep 17 00:00:00 2001 From: Will Dollman Date: Thu, 10 Oct 2024 09:01:25 +0100 Subject: [PATCH 431/647] chore(security): Update go version to 1.22.8 (#1110) * Update go version to 1.22.8 * Update changelog --------- Co-authored-by: William Bezuidenhout --- .github/workflows/go-ci.yml | 2 +- .github/workflows/go-lint.yml | 2 +- .github/workflows/goreleaser-check.yml | 2 +- .github/workflows/goreleaser.yml | 2 +- .tool-versions | 2 +- CHANGELOG.md | 6 ++++++ Dockerfile | 2 +- go.mod | 2 +- 8 files changed, 13 insertions(+), 7 deletions(-) diff --git a/.github/workflows/go-ci.yml b/.github/workflows/go-ci.yml index 7c44620926..cae55fa06a 100644 --- a/.github/workflows/go-ci.yml +++ b/.github/workflows/go-ci.yml @@ -11,7 +11,7 @@ jobs: go-test: strategy: matrix: - go-version: [1.22.5] + go-version: [1.22.8] os: [ubuntu-latest, macos-latest, windows-latest] runs-on: ${{ matrix.os }} steps: diff --git a/.github/workflows/go-lint.yml b/.github/workflows/go-lint.yml index f15416750a..542cc84383 100644 --- a/.github/workflows/go-lint.yml +++ b/.github/workflows/go-lint.yml @@ -16,7 +16,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v5 with: - go-version: 1.22.5 + go-version: 1.22.8 - name: Enable pulling Go modules from private sourcegraph/sourcegraph run: git config --global url."https://${PRIVATE_TOKEN}@github.com/sourcegraph/".insteadOf "https://github.com/sourcegraph/" - run: ./dev/go-lint.sh diff --git a/.github/workflows/goreleaser-check.yml b/.github/workflows/goreleaser-check.yml index d48d84b75a..762b1f9cef 100644 --- a/.github/workflows/goreleaser-check.yml +++ b/.github/workflows/goreleaser-check.yml @@ -19,7 +19,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v5 with: - go-version: 1.22.5 + go-version: 1.22.8 - name: Enable pulling Go modules from private sourcegraph/sourcegraph run: git config --global url."https://${PRIVATE_TOKEN}@github.com/sourcegraph/".insteadOf "https://github.com/sourcegraph/" - name: Check GoReleaser config diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index 1bb3523927..90ca689e81 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -181,7 +181,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v5 with: - go-version: 1.22.5 + go-version: 1.22.8 - name: Enable pulling Go modules from private sourcegraph/sourcegraph run: git config --global url."https://${PRIVATE_TOKEN}@github.com/sourcegraph/".insteadOf "https://github.com/sourcegraph/" - run: go test ./... diff --git a/.tool-versions b/.tool-versions index 97a30a5525..9e1c90413a 100644 --- a/.tool-versions +++ b/.tool-versions @@ -1,3 +1,3 @@ -golang 1.22.5 +golang 1.22.8 shfmt 3.8.0 shellcheck 0.10.0 diff --git a/CHANGELOG.md b/CHANGELOG.md index efa29b3a4b..c3e791393d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,12 @@ All notable changes to `src-cli` are documented in this file. ## Unreleased +## 5.8.0 + +### Changed + +- Update Go to 1.22.8 + ## 5.5.0 ### Added diff --git a/Dockerfile b/Dockerfile index 7143b733c2..27daef0b70 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,7 +4,7 @@ # # Nothing fancy here: we copy in the source code and build on the Alpine Go # image. Refer to .dockerignore to get a sense of what we're not going to copy. -FROM golang:1.22.3-alpine@sha256:4707c052e5bd90c1c6ae16d1825e3ea5076ec1b06de30e34596b1e6f6b9916cf as builder +FROM golang:1.22.8-alpine@sha256:f56a8a4a1aea41bc4694728b69c219af1523aea15690cbbed82dc9bac81e6603 as builder COPY . /src WORKDIR /src diff --git a/go.mod b/go.mod index 0dedbd61c9..58a587e36d 100644 --- a/go.mod +++ b/go.mod @@ -2,7 +2,7 @@ module github.com/sourcegraph/src-cli go 1.22 -toolchain go1.22.5 +toolchain go1.22.8 require ( cloud.google.com/go/storage v1.30.1 From ffe09136746e78b71914373f97c2b52a4f0c3201 Mon Sep 17 00:00:00 2001 From: Will Dollman Date: Mon, 14 Oct 2024 10:01:53 +0100 Subject: [PATCH 432/647] Add SBOM command (#1115) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Rough initial scaffolding for sbom command * Implement SBOM fetching and validation for all images in a given release * Improve output * Make final status emoji consistent + remove debugging * Add a spinner 😵‍💫 * Newline * Enable transparency log verification and provide an override * Fix alignment * Remove comment * Remove comment * Remove unreachable code * Fix getImageDigestDockerHub * Use out.Write consistently * Add sourcegraph-sboms/ dir to gitignore * Fix typo * Use http.DefaultClient * Tweak tlog warning * Remove hardcoded list --- .gitignore | 3 +- cmd/src/main.go | 1 + cmd/src/sbom.go | 36 +++++ cmd/src/sbom_fetch.go | 312 ++++++++++++++++++++++++++++++++++++++++++ cmd/src/sbom_utils.go | 192 ++++++++++++++++++++++++++ 5 files changed, 543 insertions(+), 1 deletion(-) create mode 100644 cmd/src/sbom.go create mode 100644 cmd/src/sbom_fetch.go create mode 100644 cmd/src/sbom_utils.go diff --git a/.gitignore b/.gitignore index 64b187f296..5a3d0f8b09 100644 --- a/.gitignore +++ b/.gitignore @@ -13,4 +13,5 @@ bazel-testlogs bazel-zoekt bazel-src-cli .DS_Store -samples \ No newline at end of file +samples +sourcegraph-sboms/ diff --git a/cmd/src/main.go b/cmd/src/main.go index b9b748934c..c646824e38 100644 --- a/cmd/src/main.go +++ b/cmd/src/main.go @@ -43,6 +43,7 @@ The commands are: orgs,org manages organizations teams,team manages teams repos,repo manages repositories + sbom manages SBOM (Software Bill of Materials) data search search for results on Sourcegraph serve-git serves your local git repositories over HTTP for Sourcegraph to pull users,user manages users diff --git a/cmd/src/sbom.go b/cmd/src/sbom.go new file mode 100644 index 0000000000..5002aa6e9b --- /dev/null +++ b/cmd/src/sbom.go @@ -0,0 +1,36 @@ +package main + +import ( + "flag" + "fmt" +) + +var sbomCommands commander + +func init() { + usage := `'src sbom' fetches and verified SBOM (Software Bill of Materials) data for Sourcegraph containers. + +Usage: + + src sbom command [command options] + +The commands are: + + fetch fetch SBOMs for a released version of Sourcegraph +` + flagSet := flag.NewFlagSet("sbom", flag.ExitOnError) + handler := func(args []string) error { + sbomCommands.run(flagSet, "src sbom", usage, args) + return nil + } + + // Register the command. + commands = append(commands, &command{ + flagSet: flagSet, + aliases: []string{"sbom"}, + handler: handler, + usageFunc: func() { + fmt.Println(usage) + }, + }) +} diff --git a/cmd/src/sbom_fetch.go b/cmd/src/sbom_fetch.go new file mode 100644 index 0000000000..71ae2808e3 --- /dev/null +++ b/cmd/src/sbom_fetch.go @@ -0,0 +1,312 @@ +package main + +import ( + "bufio" + "encoding/base64" + "encoding/json" + "flag" + "fmt" + "net/http" + "os" + "os/exec" + "path" + "path/filepath" + "strings" + "unicode" + + "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/output" + + "github.com/sourcegraph/src-cli/internal/cmderrors" +) + +type sbomConfig struct { + publicKey string + outputDir string + version string + internalRelease bool + insecureIgnoreTransparencyLog bool +} + +const publicKey = "https://storage.googleapis.com/sourcegraph-release-sboms/keys/cosign_keyring-cosign-1.pub" +const imageListBaseURL = "https://storage.googleapis.com/sourcegraph-release-sboms" +const imageListFilename = "release-image-list.txt" + +func init() { + usage := ` +'src sbom fetch' fetches and verifies SBOMs for the given release version of Sourcegraph. + +Usage: + + src sbom fetch -v + +Examples: + + $ src sbom fetch -v 5.8.0 # Fetch all SBOMs for the 5.8.0 release + + $ src sbom fetch -v 5.8.123 -internal -d /tmp/sboms # Fetch all SBOMs for the internal 5.8.123 release and store them in /tmp/sboms +` + + flagSet := flag.NewFlagSet("fetch", flag.ExitOnError) + versionFlag := flagSet.String("v", "", "The version of Sourcegraph to fetch SBOMs for.") + outputDirFlag := flagSet.String("d", "sourcegraph-sboms", "The directory to store validated SBOMs in.") + internalReleaseFlag := flagSet.Bool("internal", false, "Fetch SBOMs for an internal release. Defaults to false.") + insecureIgnoreTransparencyLogFlag := flagSet.Bool("insecure-ignore-tlog", false, "Disable transparency log verification. Defaults to false.") + + handler := func(args []string) error { + c := sbomConfig{ + publicKey: publicKey, + } + + if err := flagSet.Parse(args); err != nil { + return err + } + + if len(flagSet.Args()) != 0 { + return cmderrors.Usage("additional arguments not allowed") + } + + if versionFlag == nil || *versionFlag == "" { + return cmderrors.Usage("version is required") + } + c.version = *versionFlag + + if outputDirFlag == nil || *outputDirFlag == "" { + return cmderrors.Usage("output directory is required") + } + c.outputDir = getOutputDir(*outputDirFlag, *versionFlag) + + if internalReleaseFlag == nil || !*internalReleaseFlag { + c.internalRelease = false + } else { + c.internalRelease = true + } + + if insecureIgnoreTransparencyLogFlag != nil && *insecureIgnoreTransparencyLogFlag { + c.insecureIgnoreTransparencyLog = true + } + + out := output.NewOutput(flagSet.Output(), output.OutputOpts{Verbose: *verbose}) + + if err := verifyCosign(); err != nil { + return cmderrors.ExitCode(1, err) + } + + images, err := c.getImageList() + if err != nil { + return err + } + + out.Writef("Fetching SBOMs and validating signatures for all %d images in the Sourcegraph %s release...\n", len(images), c.version) + + if c.insecureIgnoreTransparencyLog { + out.WriteLine(output.Line("⚠️", output.StyleWarning, "WARNING: Transparency log verification is disabled, increasing the risk that SBOMs may have been tampered with.")) + out.WriteLine(output.Line("️", output.StyleWarning, " This setting should only be used for testing or under explicit instruction from Sourcegraph.\n")) + } + + var successCount, failureCount int + for _, image := range images { + stopSpinner := make(chan bool) + go spinner(image, stopSpinner) + + _, err = c.getSBOMForImageVersion(image, c.version) + + stopSpinner <- true + + if err != nil { + out.WriteLine(output.Line(output.EmojiFailure, output.StyleWarning, + fmt.Sprintf("\r%s: error fetching and validating SBOM:\n %v", image, err))) + failureCount += 1 + } else { + out.WriteLine(output.Line("\r\u2705", output.StyleSuccess, image)) + successCount += 1 + } + } + + out.Write("") + if failureCount == 0 && successCount == 0 { + out.WriteLine(output.Line("🔴", output.StyleWarning, "Failed to fetch SBOMs for any images")) + } + if failureCount > 0 { + out.WriteLine(output.Line("🟠", output.StyleOrange, fmt.Sprintf("Fetched verified SBOMs for %d images, but failed to fetch SBOMs for %d images", successCount, failureCount))) + } else if successCount > 0 { + out.WriteLine(output.Line("🟢", output.StyleSuccess, fmt.Sprintf("Fetched verified SBOMs for %d images", successCount))) + } + + out.Writef("\nFetched and validated SBOMs have been written to `%s`.\n", c.outputDir) + out.WriteLine(output.Linef("", output.StyleBold, "Your Sourcegraph deployment may not use all of these images. Please check your deployment to confirm which images are used.\n")) + + if failureCount > 0 || successCount == 0 { + return cmderrors.ExitCode1 + } + + return nil + } + + sbomCommands = append(sbomCommands, &command{ + flagSet: flagSet, + handler: handler, + usageFunc: func() { + fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src sbom %s':\n", flagSet.Name()) + flagSet.PrintDefaults() + fmt.Println(usage) + }, + }) +} + +func (c sbomConfig) getSBOMForImageVersion(image string, version string) (string, error) { + hash, err := getImageDigest(image, version) + if err != nil { + return "", err + } + + sbom, err := c.getSBOMForImageHash(image, hash) + if err != nil { + return "", err + } + + return sbom, nil +} + +func verifyCosign() error { + _, err := exec.LookPath("cosign") + if err != nil { + return errors.New("SBOM verification requires 'cosign' to be installed and available in $PATH. See https://docs.sigstore.dev/cosign/system_config/installation/") + } + return nil +} + +func (c sbomConfig) getImageList() ([]string, error) { + imageReleaseListURL := c.getImageReleaseListURL() + + resp, err := http.Get(imageReleaseListURL) + if err != nil { + return nil, fmt.Errorf("failed to fetch image list: %w", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("failed to fetch list of images - check that %s is a valid Sourcegraph release: HTTP status %d", c.version, resp.StatusCode) + } + + scanner := bufio.NewScanner(resp.Body) + var images []string + for scanner.Scan() { + image := strings.TrimSpace(scanner.Text()) + if image != "" { + // Strip off a version suffix if present + parts := strings.SplitN(image, ":", 2) + images = append(images, parts[0]) + } + } + + if err := scanner.Err(); err != nil { + return nil, fmt.Errorf("error reading image list: %w", err) + } + + return images, nil +} + +func (c sbomConfig) getSBOMForImageHash(image string, hash string) (string, error) { + tempDir, err := os.MkdirTemp("", "sbom-") + if err != nil { + return "", fmt.Errorf("failed to create temporary directory: %w", err) + } + defer os.RemoveAll(tempDir) + + outputFile := filepath.Join(tempDir, "attestation.json") + + cosignArgs := []string{ + "verify-attestation", + "--key", publicKey, + "--type", "cyclonedx", + fmt.Sprintf("%s@%s", image, hash), + "--output-file", outputFile, + } + + if c.insecureIgnoreTransparencyLog { + cosignArgs = append(cosignArgs, "--insecure-ignore-tlog") + } + + cmd := exec.Command("cosign", cosignArgs...) + + output, err := cmd.CombinedOutput() + if err != nil { + return "", fmt.Errorf("SBOM fetching or validation failed: %w\nOutput: %s", err, output) + } + + attestation, err := os.ReadFile(outputFile) + if err != nil { + return "", fmt.Errorf("failed to read SBOM file: %w", err) + } + + sbom, err := extractSBOM(attestation) + if err != nil { + return "", fmt.Errorf("failed to extract SBOM from attestation: %w", err) + } + + c.storeSBOM(sbom, image) + + return sbom, nil +} + +type attestation struct { + PayloadType string `json:"payloadType"` + Base64Payload string `json:"payload"` +} + +func extractSBOM(attestationBytes []byte) (string, error) { + var a attestation + if err := json.Unmarshal(attestationBytes, &a); err != nil { + return "", fmt.Errorf("failed to unmarshal attestation: %w", err) + } + + if a.PayloadType != "application/vnd.in-toto+json" { + return "", fmt.Errorf("unexpected payload type: %s", a.PayloadType) + } + + decodedPayload, err := base64.StdEncoding.DecodeString(a.Base64Payload) + if err != nil { + return "", fmt.Errorf("failed to decode payload: %w", err) + } + + return string(decodedPayload), nil +} + +func (c sbomConfig) storeSBOM(sbom string, image string) error { + // Make the image name safe for use as a filename + safeImageName := strings.Map(func(r rune) rune { + if unicode.IsLetter(r) || unicode.IsDigit(r) || r == '-' || r == '_' { + return r + } + return '_' + }, image) + + // Create the output file path + outputFile := filepath.Join(c.outputDir, safeImageName+".json") + + // Ensure the output directory exists + if err := os.MkdirAll(c.outputDir, 0755); err != nil { + return fmt.Errorf("failed to create output directory: %w", err) + } + + // Write the SBOM to the file + if err := os.WriteFile(outputFile, []byte(sbom), 0644); err != nil { + return fmt.Errorf("failed to write SBOM file: %w", err) + } + + return nil +} + +func getOutputDir(parentDir, version string) string { + return path.Join(parentDir, "sourcegraph-"+version) +} + +// getImageReleaseListURL returns the URL for the list of images in a release, based on the version and whether it's an internal release. +func (c *sbomConfig) getImageReleaseListURL() string { + if c.internalRelease { + return fmt.Sprintf("%s/release-internal/%s/%s", imageListBaseURL, c.version, imageListFilename) + } else { + return fmt.Sprintf("%s/release/%s/%s", imageListBaseURL, c.version, imageListFilename) + } +} diff --git a/cmd/src/sbom_utils.go b/cmd/src/sbom_utils.go new file mode 100644 index 0000000000..ff223bcb74 --- /dev/null +++ b/cmd/src/sbom_utils.go @@ -0,0 +1,192 @@ +package main + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "os/exec" + "strings" + "time" +) + +// TokenResponse represents the JSON response from dockerHub's token service +type dockerHubTokenResponse struct { + Token string `json:"token"` +} + +// getImageDigest returns the sha256 hash for the given image and tag +// It supports multiple registries +func getImageDigest(image string, tag string) (string, error) { + if strings.HasPrefix(image, "sourcegraph/") { + return getImageDigestDockerHub(image, tag) + } else if strings.HasPrefix(image, "us-central1-docker.pkg.dev/") { + return getImageDigestGcloud(image, tag) + } else { + return "", fmt.Errorf("unsupported image registry: %s", image) + } +} + +// +// Implement functionality for Docker Hub + +// getImageDigestDockerHub returns the sha256 digest for the given image and tag from DockerHub +func getImageDigestDockerHub(image string, tag string) (string, error) { + // Construct the DockerHub manifest URL + url := fmt.Sprintf("https://registry-1.docker.io/v2/%s/manifests/%s", image, tag) + + token, err := getDockerHubAuthToken(image) + if err != nil { + return "", err + } + + // Create a new HTTP request with the authorization header + req, err := http.NewRequest("GET", url, nil) + if err != nil { + return "", err + } + req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token)) + req.Header.Add("Accept", "Accept: application/vnd.docker.distribution.manifest.v2+json, application/vnd.oci.image.manifest.v1+json") + + // Make the HTTP request + resp, err := http.DefaultClient.Do(req) + if err != nil { + return "", fmt.Errorf("failed to fetch image manifest: %v", err) + } + defer resp.Body.Close() + + // Check for a successful response + if resp.StatusCode != http.StatusOK { + return "", fmt.Errorf("failed to get manifest - check %s is a valid Sourcegraph release, status code: %d", tag, resp.StatusCode) + } + + // Get the image digest from the `Docker-Content-Digest` header + digest := resp.Header.Get("Docker-Content-Digest") + if digest == "" { + return "", fmt.Errorf("digest not found in response headers") + } + // Return the image's digest (hash) + return digest, nil +} + +// getDockerHubAuthToken returns an auth token with scope to pull the given image +// Note that the token has a short validity so it should be used immediately +func getDockerHubAuthToken(image string) (string, error) { + // Set the DockerHub authentication URL + url := fmt.Sprintf("https://auth.docker.io/token?service=registry.docker.io&scope=repository:%s:pull", image) + + // Create a new HTTP request + resp, err := http.Get(url) + if err != nil { + return "", fmt.Errorf("failed to get token: %v", err) + } + defer resp.Body.Close() + + // Check if the response status is 200 OK + if resp.StatusCode != http.StatusOK { + return "", fmt.Errorf("failed to get token, status code: %d", resp.StatusCode) + } + + // Read the response body + body, err := io.ReadAll(resp.Body) + if err != nil { + return "", fmt.Errorf("failed to read response body: %v", err) + } + + // Unmarshal the JSON response + var tokenResponse dockerHubTokenResponse + if err := json.Unmarshal(body, &tokenResponse); err != nil { + return "", fmt.Errorf("failed to parse token response: %v", err) + } + + // Return the token + return tokenResponse.Token, nil +} + +// +// Implement functionality for GCP Artifact Registry + +// getImageDigestGcloud fetches the OCI image manifest from GCP Artifact Registry and returns the image digest +func getImageDigestGcloud(image string, tag string) (string, error) { + // Validate image path to ensure it's a valid GCP Artifact Registry image + if !strings.HasPrefix(image, "us-central1-docker.pkg.dev/") { + return "", fmt.Errorf("invalid image format: %s", image) + } + + // Get the GCP access token + token, err := getGcloudAccessToken() + if err != nil { + return "", fmt.Errorf("error getting access token: %v", err) + } + + parts := strings.SplitN(image, "/", 2) + if len(parts) != 2 { + return "", fmt.Errorf("invalid image format: %s", image) + } + domain := parts[0] + repositoryPath := parts[1] + + // Create the URL to fetch the manifest for the specific image and tag + url := fmt.Sprintf("https://%s/v2/%s/manifests/%s", domain, repositoryPath, tag) + + // Create a new HTTP GET request + req, err := http.NewRequest("GET", url, nil) + if err != nil { + return "", fmt.Errorf("failed to create HTTP request: %v", err) + } + + // Add the Authorization and Accept headers + req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token)) + req.Header.Add("Accept", "application/vnd.docker.distribution.manifest.v2+json, application/vnd.oci.image.manifest.v1+json") + + // Perform the HTTP request + resp, err := http.DefaultClient.Do(req) + if err != nil { + return "", fmt.Errorf("failed to fetch manifest: %v", err) + } + defer resp.Body.Close() + + // Check if the request was successful + if resp.StatusCode != http.StatusOK { + body, _ := io.ReadAll(resp.Body) + return "", fmt.Errorf("failed to get manifest, status code: %d, response: %s", resp.StatusCode, string(body)) + } + + // Get the image digest from the `Docker-Content-Digest` header + digest := resp.Header.Get("Docker-Content-Digest") + if digest == "" { + return "", fmt.Errorf("digest not found in response headers") + } + + return digest, nil +} + +// getGcloudAccessToken runs 'gcloud auth print-access-token' and returns the access token +func getGcloudAccessToken() (string, error) { + // Execute the gcloud command to get the access token + cmd := exec.Command("gcloud", "auth", "print-access-token") + out, err := cmd.Output() + if err != nil { + return "", fmt.Errorf("failed to retrieve access token using `gcloud auth`. Ensure that gcloud is installed and you have authenticated: %v", err) + } + + // Trim any extra whitespace or newlines + token := strings.TrimSpace(string(out)) + return token, nil +} + +var spinnerChars = []rune{'⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'} + +func spinner(name string, stop chan bool) { + i := 0 + for { + select { + case <-stop: + return + default: + fmt.Printf("\r%s %s", string(spinnerChars[i%len(spinnerChars)]), name) + i++ + time.Sleep(100 * time.Millisecond) + } + } +} From 847a89944628d048600f1cff04d2ea0b1150d1bd Mon Sep 17 00:00:00 2001 From: Will Dollman Date: Mon, 14 Oct 2024 11:30:03 +0100 Subject: [PATCH 433/647] sboms: Update changelog and improve error message (#1116) * Update changelog + improve error message * Remove newline --- CHANGELOG.md | 4 ++++ cmd/src/sbom_fetch.go | 6 ++++++ 2 files changed, 10 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index c3e791393d..52962df8bf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,10 @@ All notable changes to `src-cli` are documented in this file. ## 5.8.0 +### Added + +- SBOM support: Software Bill of Materials (SBOMs) can now be fetched for Sourcegraph releases after 5.8.0 using `src sbom fetch -v `. [#1115](https://github.com/sourcegraph/src-cli/pull/1115) + ### Changed - Update Go to 1.22.8 diff --git a/cmd/src/sbom_fetch.go b/cmd/src/sbom_fetch.go index 71ae2808e3..6cee467780 100644 --- a/cmd/src/sbom_fetch.go +++ b/cmd/src/sbom_fetch.go @@ -14,6 +14,7 @@ import ( "strings" "unicode" + "github.com/grafana/regexp" "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/sourcegraph/lib/output" @@ -186,6 +187,11 @@ func (c sbomConfig) getImageList() ([]string, error) { defer resp.Body.Close() if resp.StatusCode != http.StatusOK { + // Compare version number against a regex that matches versions up to and including 5.8.0 + versionRegex := regexp.MustCompile(`^v?[0-5]\.([0-7]\.[0-9]+|8\.0)$`) + if versionRegex.MatchString(c.version) { + return nil, fmt.Errorf("unsupported version %s: SBOMs are only available for Sourcegraph releases after 5.8.0", c.version) + } return nil, fmt.Errorf("failed to fetch list of images - check that %s is a valid Sourcegraph release: HTTP status %d", c.version, resp.StatusCode) } From a9118d50fb0092999082a5987f84a8cfe642ee1a Mon Sep 17 00:00:00 2001 From: Will Dollman Date: Tue, 15 Oct 2024 11:04:27 +0100 Subject: [PATCH 434/647] Fix #1105: Execute commands with zero arguments correctly (#1117) * Don't return help for commands with no arguments * Standarise --help flag across different commands * Update changelog --- CHANGELOG.md | 6 ++++++ cmd/src/cmd.go | 19 ++++++++++--------- 2 files changed, 16 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 52962df8bf..ef1ec46a4b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,12 @@ All notable changes to `src-cli` are documented in this file. ## Unreleased +## 5.8.1 + +### Fixed + +- Fixed an issue preventing some commands from executing correctly when no arguments are passed [#1117](https://github.com/sourcegraph/src-cli/pull/1117) + ## 5.8.0 ### Added diff --git a/cmd/src/cmd.go b/cmd/src/cmd.go index 3ffe235d7d..35cc240fac 100644 --- a/cmd/src/cmd.go +++ b/cmd/src/cmd.go @@ -89,15 +89,9 @@ func (c commander) run(flagSet *flag.FlagSet, cmdName, usageText string, args [] log.Fatal("reading config: ", err) } - // Parse subcommand flags. - args := flagSet.Args()[1:] - if err := cmd.flagSet.Parse(args); err != nil { - panic(fmt.Sprintf("all registered commands should use flag.ExitOnError: error: %s", err)) - } - - // Show usage examples for subcommand - if len(args) == 0 || slices.IndexFunc(args, func(s string) bool { - return s == "help" || s == "--help" + // Print help to stdout if requested + if slices.IndexFunc(args, func(s string) bool { + return s == "--help" }) >= 0 { cmd.flagSet.SetOutput(os.Stdout) flag.CommandLine.SetOutput(os.Stdout) @@ -105,6 +99,13 @@ func (c commander) run(flagSet *flag.FlagSet, cmdName, usageText string, args [] os.Exit(0) } + // Parse subcommand flags. + args := flagSet.Args()[1:] + if err := cmd.flagSet.Parse(args); err != nil { + fmt.Printf("Error parsing subcommand flags: %s\n", err) + panic(fmt.Sprintf("all registered commands should use flag.ExitOnError: error: %s", err)) + } + // Execute the subcommand. if err := cmd.handler(flagSet.Args()[1:]); err != nil { if _, ok := err.(*cmderrors.UsageError); ok { From bca0a8b398de1ca8c8957eecba3f42e622ca5d2a Mon Sep 17 00:00:00 2001 From: Will Dollman Date: Mon, 21 Oct 2024 10:02:26 +0100 Subject: [PATCH 435/647] Update development docs to include bazel update instructions (#1118) * Update development docs to include bazel update instructions * Tidy up shell output * Multiline command * Tweak * sg generate is required! * Tweak sg generate instruction --- DEVELOPMENT.md | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index bd8aa79ae3..51b9b39d40 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -71,8 +71,20 @@ We adhere to the [general Sourcegraph principles for testing](https://docs.sourc 3. The [releases section of the repo sidebar](https://github.com/sourcegraph/src-cli) shows the correct version. 5. Make the necessary updates to the main Sourcegraph repo: 1. Update the `MinimumVersion` constant in the [src-cli package](https://github.com/sourcegraph/sourcegraph/tree/main/internal/src-cli/consts.go). - 2. Update the reference documentation by running `go generate ./doc/cli/references`. - 3. Commit the changes, and open a PR. + 2. Update the `SRC_CLI_VERSION` in [tool_deps.bzl](https://sourcegraph.sourcegraph.com/github.com/sourcegraph/sourcegraph@f88ee515885e1761f002f8adcc73560bcb2573ee/-/blob/dev/tool_deps.bzl?L6) + 3. Update the sha256 hashes for the three `src-cli-*` targets in [tool_deps.bzl](https://sourcegraph.sourcegraph.com/github.com/sourcegraph/sourcegraph@f88ee515885e1761f002f8adcc73560bcb2573ee/-/blob/dev/tool_deps.bzl?L113-133). The easiest way to do this is to run the following command after updating `SRC_CLI_VERSION`, and extract the correct checksums for each target from the error message: + ```shell + $ bazel build @src-cli-linux-amd64//:src-cli-linux-amd64 \ + @src-cli-darwin-amd64//:src-cli-darwin-amd64 \ + @src-cli-darwin-arm64//:src-cli-darwin-arm64 + + ERROR: java.io.IOException: Error downloading [...]_linux-amd64.tar.gz [...] Checksum was + + [...] + ``` + After updating the checksums, rerun the command to verify that the values are correct. + 4. Run `sg generate bazel` (this may not result in any changes) + 4. Commit the changes, and open a PR. 6. Once the version bump PR is merged and the commit is live on dotcom, check that the [curl commands in the README](README.md#installation) also fetch the new latest version. ### Patch releases From f86f75d653c2b6e2283becc1c8d2f210e6096248 Mon Sep 17 00:00:00 2001 From: Peter Guy Date: Thu, 24 Oct 2024 16:01:10 -0700 Subject: [PATCH 436/647] Add proxy support (#1120) * - Read proxy env variables and config settings - Define a function to test that a given path is an active UDS * Expand paths to the OS user's home directory if they start with "~/" or "%USERPROFILE%\". * Switch from using "os/user" and `user.Current()` for finding the OS user's home dir, to using "os" and `os.UserHomeDir()`. It requires Go 1.12+. * Use the UNIX Domain Socket when making connections * Add SRC_PROXY_SOCKET to the usage output, and remove config settings for a proxy URL. * Document expandHomeDir function * Add support for HTTP(S) and SOCKS5 proxies * Mollify tests * Add tests * Refactor: move the proxy handling to a separate file. * Add tests for a UNIX Domain Socket. * Fix analysis of url schemes * Ad tests for socks proxies in the config * SOCKS proxies work OOTB, so remove the manual dialing for them. * Use `tls.HandshakeContext` * - add a proxy test script - remove "endpoint" from all of the proxy names. The environment variable is now "SRC_PROXY" - clean up the http(s) proxy dialing code. Experiemented with using http.Request instead of spelling out the CONNECT request manually, but it had enough quircks that I went back to spelling it out manually. - Add more desriptive messages to the socket config test. * fix socket test by shortening the length of the file path - UNIX socket paths need to be less than 108-ish characters. * Fix parameter capitalization * Add comment about th UDS path length to main_test.go * Fix formatting in usage message * Whoops; meant to use `w` instead of `v`! Thanks for catching that. Co-authored-by: Camden Cheek * Whoops; meant to use `w` instead of `v`! Thanks for catching that. Co-authored-by: Camden Cheek * Update comment about InsecureSkipVerify * Make CHANGELOG entry --------- Co-authored-by: Camden Cheek --- CHANGELOG.md | 4 + cmd/src/login.go | 2 +- cmd/src/login_test.go | 2 +- cmd/src/main.go | 168 +++++++++++++++++++++--- cmd/src/main_test.go | 138 ++++++++++++++++++- dev/test-proxies.sh | 94 +++++++++++++ internal/api/BUILD.bazel | 2 + internal/api/api.go | 24 +++- internal/api/proxy.go | 138 +++++++++++++++++++ internal/api/test_unix_socket_server.go | 109 +++++++++++++++ 10 files changed, 651 insertions(+), 30 deletions(-) create mode 100755 dev/test-proxies.sh create mode 100644 internal/api/proxy.go create mode 100644 internal/api/test_unix_socket_server.go diff --git a/CHANGELOG.md b/CHANGELOG.md index ef1ec46a4b..c96941788b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,10 @@ All notable changes to `src-cli` are documented in this file. ## Unreleased +### Added + +- Support HTTP(S), SOCKS5, and UNIX Domain Socket proxies via SRC_PROXY environment variable. [#1120](https://github.com/sourcegraph/src-cli/pull/1120) + ## 5.8.1 ### Fixed diff --git a/cmd/src/login.go b/cmd/src/login.go index 5fec84b593..6915cada7f 100644 --- a/cmd/src/login.go +++ b/cmd/src/login.go @@ -81,7 +81,7 @@ func loginCmd(ctx context.Context, cfg *config, client api.Client, endpointArg s if cfg.ConfigFilePath != "" { fmt.Fprintln(out) - fmt.Fprintf(out, "⚠️ Warning: Configuring src with a JSON file is deprecated. Please migrate to using the env vars SRC_ENDPOINT and SRC_ACCESS_TOKEN instead, and then remove %s. See https://github.com/sourcegraph/src-cli#readme for more information.\n", cfg.ConfigFilePath) + fmt.Fprintf(out, "⚠️ Warning: Configuring src with a JSON file is deprecated. Please migrate to using the env vars SRC_ENDPOINT, SRC_ACCESS_TOKEN, and SRC_PROXY instead, and then remove %s. See https://github.com/sourcegraph/src-cli#readme for more information.\n", cfg.ConfigFilePath) } noToken := cfg.AccessToken == "" diff --git a/cmd/src/login_test.go b/cmd/src/login_test.go index 4423d335d8..45403e293b 100644 --- a/cmd/src/login_test.go +++ b/cmd/src/login_test.go @@ -49,7 +49,7 @@ func TestLogin(t *testing.T) { if err != cmderrors.ExitCode1 { t.Fatal(err) } - wantOut := "⚠️ Warning: Configuring src with a JSON file is deprecated. Please migrate to using the env vars SRC_ENDPOINT and SRC_ACCESS_TOKEN instead, and then remove f. See https://github.com/sourcegraph/src-cli#readme for more information.\n\n❌ Problem: No access token is configured.\n\n🛠 To fix: Create an access token at https://example.com/user/settings/tokens, then set the following environment variables:\n\n SRC_ENDPOINT=https://example.com\n SRC_ACCESS_TOKEN=(the access token you just created)\n\n To verify that it's working, run this command again." + wantOut := "⚠️ Warning: Configuring src with a JSON file is deprecated. Please migrate to using the env vars SRC_ENDPOINT, SRC_ACCESS_TOKEN, and SRC_PROXY instead, and then remove f. See https://github.com/sourcegraph/src-cli#readme for more information.\n\n❌ Problem: No access token is configured.\n\n🛠 To fix: Create an access token at https://example.com/user/settings/tokens, then set the following environment variables:\n\n SRC_ENDPOINT=https://example.com\n SRC_ACCESS_TOKEN=(the access token you just created)\n\n To verify that it's working, run this command again." if out != wantOut { t.Errorf("got output %q, want %q", out, wantOut) } diff --git a/cmd/src/main.go b/cmd/src/main.go index c646824e38..f2dfe270e4 100644 --- a/cmd/src/main.go +++ b/cmd/src/main.go @@ -5,8 +5,9 @@ import ( "flag" "io" "log" + "net" + "net/url" "os" - "os/user" "path/filepath" "strings" @@ -25,6 +26,20 @@ Usage: Environment variables SRC_ACCESS_TOKEN Sourcegraph access token SRC_ENDPOINT endpoint to use, if unset will default to "https://sourcegraph.com" + SRC_PROXY A proxy to use for proxying requests to the Sourcegraph endpoint. + Supports HTTP(S), SOCKS5/5h, and UNIX Domain Socket proxies. + If a UNIX Domain Socket, the path can be either an absolute path, + or can start with ~/ or %USERPROFILE%\ for a path in the user's home directory. + Examples: + - https://localhost:3080 + - https://:localhost:8080 + - socks5h://localhost:1080 + - socks5://:@localhost:1080 + - unix://~/src-proxy.sock + - unix://%USERPROFILE%\src-proxy.sock + - ~/src-proxy.sock + - %USERPROFILE%\src-proxy.sock + - C:\some\path\src-proxy.sock The options are: @@ -83,8 +98,10 @@ type config struct { Endpoint string `json:"endpoint"` AccessToken string `json:"accessToken"` AdditionalHeaders map[string]string `json:"additionalHeaders"` - - ConfigFilePath string + Proxy string `json:"proxy"` + ProxyURL *url.URL + ProxyPath string + ConfigFilePath string } // apiClient returns an api.Client built from the configuration. @@ -95,32 +112,25 @@ func (c *config) apiClient(flags *api.Flags, out io.Writer) api.Client { AdditionalHeaders: c.AdditionalHeaders, Flags: flags, Out: out, + ProxyURL: c.ProxyURL, + ProxyPath: c.ProxyPath, }) } -var testHomeDir string // used by tests to mock the user's $HOME - // readConfig reads the config file from the given path. func readConfig() (*config, error) { - cfgPath := *configPath + cfgFile := *configPath userSpecified := *configPath != "" - var homeDir string - if testHomeDir != "" { - homeDir = testHomeDir - } else { - u, err := user.Current() - if err != nil { - return nil, err - } - homeDir = u.HomeDir + if !userSpecified { + cfgFile = "~/src-config.json" } - if !userSpecified { - cfgPath = filepath.Join(homeDir, "src-config.json") - } else if strings.HasPrefix(cfgPath, "~/") { - cfgPath = filepath.Join(homeDir, cfgPath[2:]) + cfgPath, err := expandHomeDir(cfgFile) + if err != nil { + return nil, err } + data, err := os.ReadFile(os.ExpandEnv(cfgPath)) if err != nil && (!os.IsNotExist(err) || userSpecified) { return nil, err @@ -135,10 +145,12 @@ func readConfig() (*config, error) { envToken := os.Getenv("SRC_ACCESS_TOKEN") envEndpoint := os.Getenv("SRC_ENDPOINT") + envProxy := os.Getenv("SRC_PROXY") if userSpecified { - // If a config file is present, either zero or both environment variables must be present. + // If a config file is present, either zero or both required environment variables must be present. // We don't want to partially apply environment variables. + // Note that SRC_PROXY is optional so we don't test for it. if envToken == "" && envEndpoint != "" { return nil, errConfigMerge } @@ -157,6 +169,60 @@ func readConfig() (*config, error) { if cfg.Endpoint == "" { cfg.Endpoint = "https://sourcegraph.com" } + if envProxy != "" { + cfg.Proxy = envProxy + } + + if cfg.Proxy != "" { + + parseEndpoint := func(endpoint string) (scheme string, address string) { + parts := strings.SplitN(endpoint, "://", 2) + if len(parts) == 2 { + return parts[0], parts[1] + } + return "", endpoint + } + + urlSchemes := []string{"http", "https", "socks", "socks5", "socks5h"} + + isURLScheme := func(scheme string) bool { + for _, s := range urlSchemes { + if scheme == s { + return true + } + } + return false + } + + scheme, address := parseEndpoint(cfg.Proxy) + + if isURLScheme(scheme) { + endpoint := cfg.Proxy + // assume socks means socks5, because that's all we support + if scheme == "socks" { + endpoint = "socks5://" + address + } + cfg.ProxyURL, err = url.Parse(endpoint) + if err != nil { + return nil, err + } + } else if scheme == "" || scheme == "unix" { + path, err := expandHomeDir(address) + if err != nil { + return nil, err + } + isValidUDS, err := isValidUnixSocket(path) + if err != nil { + return nil, errors.Newf("Invalid proxy configuration: %w", err) + } + if !isValidUDS { + return nil, errors.Newf("invalid proxy socket: %s", path) + } + cfg.ProxyPath = path + } else { + return nil, errors.Newf("invalid proxy endpoint: %s", cfg.Proxy) + } + } cfg.AdditionalHeaders = parseAdditionalHeaders() // Ensure that we're not clashing additonal headers @@ -178,3 +244,65 @@ func readConfig() (*config, error) { func cleanEndpoint(urlStr string) string { return strings.TrimSuffix(urlStr, "/") } + +// isValidUnixSocket checks if the given path is a valid Unix socket. +// +// Parameters: +// - path: A string representing the file path to check. +// +// Returns: +// - bool: true if the path is a valid Unix socket, false otherwise. +// - error: nil if the check was successful, or an error if an unexpected issue occurred. +// +// The function attempts to establish a connection to the Unix socket at the given path. +// If the connection succeeds, it's considered a valid Unix socket. +// If the file doesn't exist, it returns false without an error. +// For any other errors, it returns false and the encountered error. +func isValidUnixSocket(path string) (bool, error) { + conn, err := net.Dial("unix", path) + if err != nil { + if os.IsNotExist(err) { + return false, nil + } + return false, errors.Newf("Not a UNIX Domain Socket: %v: %w", path, err) + } + defer conn.Close() + + return true, nil +} + +var testHomeDir string // used by tests to mock the user's $HOME + +// expandHomeDir expands to the user's home directory a tilde (~) or %USERPROFILE% at the beginning of a file path. +// +// Parameters: +// - filePath: A string representing the file path that may start with "~/" or "%USERPROFILE%\". +// +// Returns: +// - string: The expanded file path with the home directory resolved. +// - error: An error if the user's home directory cannot be determined. +// +// The function handles both Unix-style paths starting with "~/" and Windows-style paths starting with "%USERPROFILE%\". +// It uses the testHomeDir variable for testing purposes if set, otherwise it uses os.UserHomeDir() to get the user's home directory. +// If the input path doesn't start with either prefix, it returns the original path unchanged. +func expandHomeDir(filePath string) (string, error) { + if strings.HasPrefix(filePath, "~/") || strings.HasPrefix(filePath, "%USERPROFILE%\\") { + var homeDir string + if testHomeDir != "" { + homeDir = testHomeDir + } else { + hd, err := os.UserHomeDir() + if err != nil { + return "", err + } + homeDir = hd + } + + if strings.HasPrefix(filePath, "~/") { + return filepath.Join(homeDir, filePath[2:]), nil + } + return filepath.Join(homeDir, filePath[14:]), nil + } + + return filePath, nil +} diff --git a/cmd/src/main_test.go b/cmd/src/main_test.go index 6b25654e7f..c37c36792a 100644 --- a/cmd/src/main_test.go +++ b/cmd/src/main_test.go @@ -2,14 +2,31 @@ package main import ( "encoding/json" + "net/url" "os" "path/filepath" "testing" "github.com/google/go-cmp/cmp" + + "github.com/sourcegraph/src-cli/internal/api" ) func TestReadConfig(t *testing.T) { + // UNIX Domain Sockets have a max path length: 104 on BSD/macOS, 108 on Linux. + // Including a prefix and suffix was causing the path to be too long + // with t.TempDir() (os.TempDir() is a shorter path) so we don't use them. + socketPath, err := api.CreateTempFile(t.TempDir(), "", "") + if err != nil { + t.Fatal(err) + } + socketServer, err := api.StartUnixSocketServer(socketPath) + if err != nil { + t.Fatal(err) + } + defer socketServer.Stop() + defer os.Remove(socketPath) + tests := []struct { name string fileContents *config @@ -17,6 +34,7 @@ func TestReadConfig(t *testing.T) { envFooHeader string envHeaders string envEndpoint string + envProxy string flagEndpoint string want *config wantErr string @@ -33,11 +51,18 @@ func TestReadConfig(t *testing.T) { fileContents: &config{ Endpoint: "https://example.com/", AccessToken: "deadbeef", + Proxy: "https://proxy.com:8080", }, want: &config{ Endpoint: "https://example.com", AccessToken: "deadbeef", AdditionalHeaders: map[string]string{}, + Proxy: "https://proxy.com:8080", + ProxyPath: "", + ProxyURL: &url.URL{ + Scheme: "https", + Host: "proxy.com:8080", + }, }, }, { @@ -61,16 +86,44 @@ func TestReadConfig(t *testing.T) { wantErr: errConfigMerge.Error(), }, { - name: "config file, both override", + name: "config file, proxy override only (allow)", fileContents: &config{ Endpoint: "https://example.com/", AccessToken: "deadbeef", + Proxy: "https://proxy.com:8080", + }, + envProxy: "socks5://other.proxy.com:9999", + want: &config{ + Endpoint: "https://example.com", + AccessToken: "deadbeef", + Proxy: "socks5://other.proxy.com:9999", + ProxyPath: "", + ProxyURL: &url.URL{ + Scheme: "socks5", + Host: "other.proxy.com:9999", + }, + AdditionalHeaders: map[string]string{}, + }, + }, + { + name: "config file, all override", + fileContents: &config{ + Endpoint: "https://example.com/", + AccessToken: "deadbeef", + Proxy: "https://proxy.com:8080", }, envToken: "abc", envEndpoint: "https://override.com", + envProxy: "socks5://other.proxy.com:9999", want: &config{ - Endpoint: "https://override.com", - AccessToken: "abc", + Endpoint: "https://override.com", + AccessToken: "abc", + Proxy: "socks5://other.proxy.com:9999", + ProxyPath: "", + ProxyURL: &url.URL{ + Scheme: "socks5", + Host: "other.proxy.com:9999", + }, AdditionalHeaders: map[string]string{}, }, }, @@ -93,12 +146,84 @@ func TestReadConfig(t *testing.T) { }, }, { - name: "no config file, both variables", + name: "no config file, proxy from environment", + envProxy: "https://proxy.com:8080", + want: &config{ + Endpoint: "https://sourcegraph.com", + AccessToken: "", + Proxy: "https://proxy.com:8080", + ProxyPath: "", + ProxyURL: &url.URL{ + Scheme: "https", + Host: "proxy.com:8080", + }, + AdditionalHeaders: map[string]string{}, + }, + }, + { + name: "no config file, all variables", envEndpoint: "https://example.com", envToken: "abc", + envProxy: "https://proxy.com:8080", want: &config{ - Endpoint: "https://example.com", - AccessToken: "abc", + Endpoint: "https://example.com", + AccessToken: "abc", + Proxy: "https://proxy.com:8080", + ProxyPath: "", + ProxyURL: &url.URL{ + Scheme: "https", + Host: "proxy.com:8080", + }, + AdditionalHeaders: map[string]string{}, + }, + }, + { + name: "UNIX Domain Socket proxy using scheme and absolute path", + envProxy: "unix://" + socketPath, + want: &config{ + Endpoint: "https://sourcegraph.com", + Proxy: "unix://" + socketPath, + ProxyPath: socketPath, + ProxyURL: nil, + AdditionalHeaders: map[string]string{}, + }, + }, + { + name: "UNIX Domain Socket proxy with absolute path", + envProxy: socketPath, + want: &config{ + Endpoint: "https://sourcegraph.com", + Proxy: socketPath, + ProxyPath: socketPath, + ProxyURL: nil, + AdditionalHeaders: map[string]string{}, + }, + }, + { + name: "socks --> socks5", + envProxy: "socks://localhost:1080", + want: &config{ + Endpoint: "https://sourcegraph.com", + Proxy: "socks://localhost:1080", + ProxyPath: "", + ProxyURL: &url.URL{ + Scheme: "socks5", + Host: "localhost:1080", + }, + AdditionalHeaders: map[string]string{}, + }, + }, + { + name: "socks5h", + envProxy: "socks5h://localhost:1080", + want: &config{ + Endpoint: "https://sourcegraph.com", + Proxy: "socks5h://localhost:1080", + ProxyPath: "", + ProxyURL: &url.URL{ + Scheme: "socks5h", + Host: "localhost:1080", + }, AdditionalHeaders: map[string]string{}, }, }, @@ -171,6 +296,7 @@ func TestReadConfig(t *testing.T) { } setEnv("SRC_ACCESS_TOKEN", test.envToken) setEnv("SRC_ENDPOINT", test.envEndpoint) + setEnv("SRC_PROXY", test.envProxy) tmpDir := t.TempDir() testHomeDir = tmpDir diff --git a/dev/test-proxies.sh b/dev/test-proxies.sh new file mode 100755 index 0000000000..0241f4e0c6 --- /dev/null +++ b/dev/test-proxies.sh @@ -0,0 +1,94 @@ +#!/usr/bin/env bash + +# A test script to help manually test permutations of the proxy settings. +# Before running this script,you'll need five terminal windows: +# One for `socat`, two for `mitmproxy` (non-auth and auth), +# and two for a socks proxy (none-auth and auth). +# If you're on macOS, run `brew install socat mitmproxy`. +# To avoid the need to use insecure TLS settings, import mitmproxy's CA certificate into your keychain. +# On macOS: `sudo security add-trusted-cert -d -p ssl -p basic -k /Library/Keychains/System.keychain ~/.mitmproxy/mitmproxy-ca-cert.pem` +# For a socks proxy, I use the Docker image serjs/go-socks5-proxy. +# Note that `mitmproxy` is not a tunneling proxy - it uses a self-signed certificate +# to authenticate clients, which is good and bad. Good because we can inspect requests coming through +# if we want, and bad because we need to use insecure TLS settings to use it. +# It also works with `socat`, where `tinyproxy` and even `devproxy.sgdev.org` don't. +# Terminal 1: +# `socat -d -d unix-listen:${HOME}/socat-proxy.sock,fork tcp:localhost:8080` +# Terminal 2: +# `mitmproxy -v -p 8080` +# Terminal 3: +# `mitmproxy -v -p 8081 --proxyauth user:pass` +# Terminal 4: +# `docker run --rm -p 1080:1080 serjs/go-socks5-proxy` +# Terminal 5: +# `docker run --rm -p 1081:1080 -e PROXY_USER=user -e PROXY_PASSWORD=pass serjs/go-socks5-proxy` +# when you kick off this script, keep all of the windows in view so you can see that the output +# shows successful connections being made. + +SRC_PATH=${SRC_PATH:-~/go/bin/src} + +export SRC_ENDPOINT=${SRC_ENDPOINT:-https://sourcegraph.com} +export SRC_ACCESS_TOKEN=${SRC_ACCESS_TOKEN} + +socket=~/socat-proxy.sock + +# UNIX Domain Socket test +# You should see connection output in both the `socat` and `mitmproxy` terminals. +echo "UNIX Domain Socket test" +SRC_PROXY=${socket} \ +${SRC_PATH} login + +# HTTP test +# You should see connection output in the `mitmproxy` terminal. +echo "HTTP proxy test" +SRC_PROXY=http://localhost:8080 \ +${SRC_PATH} login + +# HTTPS with auth test +# You should see connection output in the `mitmproxy` with auth terminal. +echo "HTTP proxy with auth test" +SRC_PROXY=http://user:pass@localhost:8081 \ +${SRC_PATH} login + +# HTTPS test +# You should see connection output in the `mitmproxy` terminal. +echo "HTTPS proxy test" +SRC_PROXY=https://localhost:8080 \ +${SRC_PATH} login + +# HTTPS with auth test +# You should see connection output in the `mitmproxy` with auth terminal. +echo "HTTPS proxy with auth test" +SRC_PROXY=https://user:pass@localhost:8081 \ +${SRC_PATH} login + +# SOCKS test +# You should see connection output in the socks terminal. +echo "SOCKS proxy test" +SRC_PROXY=socks5://localhost:1080 \ +${SRC_PATH} login + +# SOCKS with auth test +# You should see connection output in the socks terminal. +echo "SOCKS proxy with auth test" +SRC_PROXY=socks5://user:pass@localhost:1081 \ +${SRC_PATH} login + +# HTTPS using insecure TLS code path +# You should see connection output in the `mitmproxy` terminal. +echo "HTTPS proxy insecure TLS path test" +SRC_PROXY=https://localhost:8080 \ +${SRC_PATH} login --insecure-skip-verify=true + + +# test a search using a proxy +echo "Search test" +SRC_PROXY=https://localhost:8080 \ +${SRC_PATH} search -json 'repo:github.com/sourcegraph/src-cli foobar' + + +# test with the system proxy set to something else +echo "Ignoring system proxy test" +https_proxy=http://localhost:12345 \ +SRC_PROXY=https://localhost:8080 \ +${SRC_PATH} login diff --git a/internal/api/BUILD.bazel b/internal/api/BUILD.bazel index a292172e57..4441a7b3ba 100644 --- a/internal/api/BUILD.bazel +++ b/internal/api/BUILD.bazel @@ -8,6 +8,8 @@ go_library( "flags.go", "gzip.go", "nullable.go", + "proxy.go", + "test_unix_socket_server.go", ], importpath = "github.com/sourcegraph/src-cli/internal/api", visibility = ["//:__subpackages__"], diff --git a/internal/api/api.go b/internal/api/api.go index 25e87f814e..63cef92b50 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -9,6 +9,7 @@ import ( "fmt" "io" "net/http" + "net/url" "os" "runtime" "strings" @@ -81,6 +82,9 @@ type ClientOpts struct { // Out is the writer that will be used when outputting diagnostics, such as // curl commands when -get-curl is enabled. Out io.Writer + + ProxyURL *url.URL + ProxyPath string } // NewClient creates a new API client. @@ -95,9 +99,26 @@ func NewClient(opts ClientOpts) Client { } httpClient := http.DefaultClient + + transport := http.DefaultTransport.(*http.Transport).Clone() + customTransport := false + if flags.insecureSkipVerify != nil && *flags.insecureSkipVerify { + customTransport = true + transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} + } + + if transport.TLSClientConfig == nil { + transport.TLSClientConfig = &tls.Config{} + } + + if applyProxy(transport, opts.ProxyURL, opts.ProxyPath) { + customTransport = true + } + + if customTransport { httpClient = &http.Client{ - Transport: &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}, + Transport: transport, } } @@ -112,7 +133,6 @@ func NewClient(opts ClientOpts) Client { httpClient: httpClient, } } - func (c *client) NewQuery(query string) Request { return c.NewRequest(query, nil) } diff --git a/internal/api/proxy.go b/internal/api/proxy.go new file mode 100644 index 0000000000..5e5fbf30ef --- /dev/null +++ b/internal/api/proxy.go @@ -0,0 +1,138 @@ +package api + +import ( + "bufio" + "context" + "crypto/tls" + "encoding/base64" + "fmt" + "net" + "net/http" + "net/url" +) + +func applyProxy(transport *http.Transport, proxyURL *url.URL, proxyPath string) (applied bool) { + if proxyURL == nil && proxyPath == "" { + return false + } + + handshakeTLS := func(ctx context.Context, conn net.Conn, addr string) (net.Conn, error) { + // Extract the hostname (without the port) for TLS SNI + host, _, err := net.SplitHostPort(addr) + if err != nil { + return nil, err + } + tlsConn := tls.Client(conn, &tls.Config{ + ServerName: host, + // Pull InsecureSkipVerify from the target host transport + // so that insecure-skip-verify flag settings are honored for the proxy server + InsecureSkipVerify: transport.TLSClientConfig.InsecureSkipVerify, + }) + if err := tlsConn.HandshakeContext(ctx); err != nil { + return nil, err + } + return tlsConn, nil + } + + proxyApplied := false + + if proxyPath != "" { + dial := func(ctx context.Context, _, _ string) (net.Conn, error) { + d := net.Dialer{} + return d.DialContext(ctx, "unix", proxyPath) + } + dialTLS := func(ctx context.Context, network, addr string) (net.Conn, error) { + conn, err := dial(ctx, network, addr) + if err != nil { + return nil, err + } + return handshakeTLS(ctx, conn, addr) + } + transport.DialContext = dial + transport.DialTLSContext = dialTLS + // clear out any system proxy settings + transport.Proxy = nil + proxyApplied = true + } else if proxyURL != nil { + if proxyURL.Scheme == "socks5" || + proxyURL.Scheme == "socks5h" { + // SOCKS proxies work out of the box - no need to manually dial + transport.Proxy = http.ProxyURL(proxyURL) + proxyApplied = true + } else if proxyURL.Scheme == "http" || proxyURL.Scheme == "https" { + dial := func(ctx context.Context, network, addr string) (net.Conn, error) { + // Dial the proxy + d := net.Dialer{} + conn, err := d.DialContext(ctx, "tcp", proxyURL.Host) + if err != nil { + return nil, err + } + + // this is the whole point of manually dialing the HTTP(S) proxy: + // being able to force HTTP/1. + // When relying on Transport.Proxy, the protocol is always HTTP/2, + // but many proxy servers don't support HTTP/2. + // We don't want to disable HTTP/2 in general because we want to use it when + // connecting to the Sourcegraph API, using HTTP/1 for the proxy connection only. + protocol := "HTTP/1.1" + + // CONNECT is the HTTP method used to set up a tunneling connection with a proxy + method := "CONNECT" + + // Manually writing out the HTTP commands because it's not complicated, + // and http.Request has some janky behavior: + // - ignores the Proto field and hard-codes the protocol to HTTP/1.1 + // - ignores the Host Header (Header.Set("Host", host)) and uses URL.Host instead. + // - When the Host field is set, overrides the URL field + connectReq := fmt.Sprintf("%s %s %s\r\n", method, addr, protocol) + + // A Host header is required per RFC 2616, section 14.23 + connectReq += fmt.Sprintf("Host: %s\r\n", addr) + + // use authentication if proxy credentials are present + if proxyURL.User != nil { + password, _ := proxyURL.User.Password() + auth := base64.StdEncoding.EncodeToString([]byte(proxyURL.User.Username() + ":" + password)) + connectReq += fmt.Sprintf("Proxy-Authorization: Basic %s\r\n", auth) + } + + // finish up with an extra carriage return + newline, as per RFC 7230, section 3 + connectReq += "\r\n" + + // Send the CONNECT request to the proxy to establish the tunnel + if _, err := conn.Write([]byte(connectReq)); err != nil { + conn.Close() + return nil, err + } + + // Read and check the response from the proxy + resp, err := http.ReadResponse(bufio.NewReader(conn), nil) + if err != nil { + conn.Close() + return nil, err + } + if resp.StatusCode != http.StatusOK { + conn.Close() + return nil, fmt.Errorf("failed to connect to proxy %v: %v", proxyURL, resp.Status) + } + resp.Body.Close() + return conn, nil + } + dialTLS := func(ctx context.Context, network, addr string) (net.Conn, error) { + // Dial the underlying connection through the proxy + conn, err := dial(ctx, network, addr) + if err != nil { + return nil, err + } + return handshakeTLS(ctx, conn, addr) + } + transport.DialContext = dial + transport.DialTLSContext = dialTLS + // clear out any system proxy settings + transport.Proxy = nil + proxyApplied = true + } + } + + return proxyApplied +} diff --git a/internal/api/test_unix_socket_server.go b/internal/api/test_unix_socket_server.go new file mode 100644 index 0000000000..c637aed0b9 --- /dev/null +++ b/internal/api/test_unix_socket_server.go @@ -0,0 +1,109 @@ +package api + +import ( + "fmt" + "net" + "os" + "sync" +) + +type Server struct { + Listener net.Listener + StopChan chan struct{} + Wg sync.WaitGroup +} + +func CreateTempFile(dir, prefix, suffix string) (string, error) { + // Get the default temporary directory for the OS + if dir == "" { + dir = os.TempDir() + } + + // Create a temporary file with the specified prefix and suffix + tempFile, err := os.CreateTemp(dir, prefix+"*"+suffix) + if err != nil { + return "", fmt.Errorf("failed to create temp file: %w", err) + } + + // Close the file to release the file descriptor + tempFile.Close() + + // Return the name of the created file + return tempFile.Name(), nil +} + +func createUnixSocket(socketPath string) (net.Listener, error) { + // Clean up the socket file if it already exists + _ = os.Remove(socketPath) + + // Create a Unix domain socket + listener, err := net.Listen("unix", socketPath) + if err != nil { + return nil, fmt.Errorf("failed to create Unix domain socket: %w", err) + } + + return listener, nil +} + +// StartServer starts the server in a goroutine and returns a stop function +func StartUnixSocketServer(socketPath string) (*Server, error) { + listener, err := createUnixSocket(socketPath) + if err != nil { + return nil, err + } + + server := &Server{ + Listener: listener, + StopChan: make(chan struct{}), + } + + server.Wg.Add(1) + go func() { + defer server.Wg.Done() + for { + conn, err := server.Listener.Accept() + if err != nil { + select { + case <-server.StopChan: + return + default: + fmt.Println("Error accepting connection:", err) + continue + } + } + + // Handle each connection in a separate goroutine + server.Wg.Add(1) + go func(conn net.Conn) { + defer server.Wg.Done() + defer conn.Close() + + // Handle incoming data from the connection + buf := make([]byte, 1024) + n, err := conn.Read(buf) + if err != nil { + fmt.Println("Error reading from connection:", err) + return + } + + fmt.Printf("Received: %s\n", string(buf[:n])) + + // Example: Write a response back + _, err = conn.Write([]byte("Hello from server\n")) + if err != nil { + fmt.Println("Error writing to connection:", err) + return + } + }(conn) + } + }() + + return server, nil +} + +// StopServer stops the server and waits for all goroutines to finish +func (s *Server) Stop() { + close(s.StopChan) + s.Listener.Close() + s.Wg.Wait() +} From a404f176b725939277cde2dfe572e636664c8d40 Mon Sep 17 00:00:00 2001 From: Will Dollman Date: Wed, 30 Oct 2024 16:15:02 +0000 Subject: [PATCH 437/647] Fix issue preventing some SBOMs being fetched from Docker Hub (#1119) * Fix typo'd accept header * Ensure we only parse the first line of the attestation * Changelog --- CHANGELOG.md | 6 ++++++ cmd/src/sbom_fetch.go | 9 ++++++++- cmd/src/sbom_utils.go | 2 +- 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c96941788b..89bb4a1799 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,10 +11,16 @@ All notable changes to `src-cli` are documented in this file. ## Unreleased +## 5.8.2 + ### Added - Support HTTP(S), SOCKS5, and UNIX Domain Socket proxies via SRC_PROXY environment variable. [#1120](https://github.com/sourcegraph/src-cli/pull/1120) +### Fixed + +- Fixed a compatibility issue that prevented `src sbom fetch` from fetching some SBOMs [#1119](https://github.com/sourcegraph/src-cli/pull/1119) + ## 5.8.1 ### Fixed diff --git a/cmd/src/sbom_fetch.go b/cmd/src/sbom_fetch.go index 6cee467780..894e34658d 100644 --- a/cmd/src/sbom_fetch.go +++ b/cmd/src/sbom_fetch.go @@ -2,6 +2,7 @@ package main import ( "bufio" + "bytes" "encoding/base64" "encoding/json" "flag" @@ -262,8 +263,14 @@ type attestation struct { } func extractSBOM(attestationBytes []byte) (string, error) { + // Ensure we only use the first line - occasionally Cosign includes multiple lines + lines := bytes.Split(attestationBytes, []byte("\n")) + if len(lines) == 0 { + return "", fmt.Errorf("attestation is empty") + } + var a attestation - if err := json.Unmarshal(attestationBytes, &a); err != nil { + if err := json.Unmarshal(lines[0], &a); err != nil { return "", fmt.Errorf("failed to unmarshal attestation: %w", err) } diff --git a/cmd/src/sbom_utils.go b/cmd/src/sbom_utils.go index ff223bcb74..9bce46e748 100644 --- a/cmd/src/sbom_utils.go +++ b/cmd/src/sbom_utils.go @@ -46,7 +46,7 @@ func getImageDigestDockerHub(image string, tag string) (string, error) { return "", err } req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token)) - req.Header.Add("Accept", "Accept: application/vnd.docker.distribution.manifest.v2+json, application/vnd.oci.image.manifest.v1+json") + req.Header.Add("Accept", "application/vnd.docker.distribution.manifest.v2+json, application/vnd.oci.image.manifest.v1+json") // Make the HTTP request resp, err := http.DefaultClient.Do(req) From 3eb07f49399647a9f47096139a5416f0c76c86ec Mon Sep 17 00:00:00 2001 From: Jacob Pleiness Date: Mon, 4 Nov 2024 19:03:06 -0500 Subject: [PATCH 438/647] chore(rel): 5.9.0: Update changelog (#1122) * chore(rel): 5.9.0 * Fix auto-fmt --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 89bb4a1799..1840d10e07 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ All notable changes to `src-cli` are documented in this file. ## Unreleased +## 5.9.0 + ## 5.8.2 ### Added From b9d5d30c00db384bfe6420ab2bb6b5f2e7d25dba Mon Sep 17 00:00:00 2001 From: Will Dollman Date: Mon, 11 Nov 2024 16:33:33 +0000 Subject: [PATCH 439/647] Update SBOM file format and extract different payload (#1123) * Update SBOM file format and extract different payload * Update changelog * Strip any leading v from version string --- CHANGELOG.md | 5 +++++ cmd/src/sbom_fetch.go | 25 ++++++++++++++++--------- cmd/src/sbom_utils.go | 10 ++++++++++ 3 files changed, 31 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1840d10e07..ea5ea301b0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,11 @@ All notable changes to `src-cli` are documented in this file. ## Unreleased +## 5.9.1 + +- Update SBOM output file extension from `.json` to `.cdx.json` [#1123](https://github.com/sourcegraph/src-cli/pull/1123) +- Improve SBOM compatibility with scanning tools [#1123](https://github.com/sourcegraph/src-cli/pull/1123) + ## 5.9.0 ## 5.8.2 diff --git a/cmd/src/sbom_fetch.go b/cmd/src/sbom_fetch.go index 894e34658d..4f82e3f222 100644 --- a/cmd/src/sbom_fetch.go +++ b/cmd/src/sbom_fetch.go @@ -10,7 +10,6 @@ import ( "net/http" "os" "os/exec" - "path" "path/filepath" "strings" "unicode" @@ -71,12 +70,12 @@ Examples: if versionFlag == nil || *versionFlag == "" { return cmderrors.Usage("version is required") } - c.version = *versionFlag + c.version = sanitizeVersion(*versionFlag) if outputDirFlag == nil || *outputDirFlag == "" { return cmderrors.Usage("output directory is required") } - c.outputDir = getOutputDir(*outputDirFlag, *versionFlag) + c.outputDir = getOutputDir(*outputDirFlag, c.version) if internalReleaseFlag == nil || !*internalReleaseFlag { c.internalRelease = false @@ -283,7 +282,19 @@ func extractSBOM(attestationBytes []byte) (string, error) { return "", fmt.Errorf("failed to decode payload: %w", err) } - return string(decodedPayload), nil + // Unmarshal the decoded payload to extract predicate + var payload map[string]json.RawMessage + if err := json.Unmarshal(decodedPayload, &payload); err != nil { + return "", fmt.Errorf("failed to unmarshal decoded payload: %w", err) + } + + // Extract just the predicate field + predicate, ok := payload["predicate"] + if !ok { + return "", fmt.Errorf("no predicate field found in payload") + } + + return string(predicate), nil } func (c sbomConfig) storeSBOM(sbom string, image string) error { @@ -296,7 +307,7 @@ func (c sbomConfig) storeSBOM(sbom string, image string) error { }, image) // Create the output file path - outputFile := filepath.Join(c.outputDir, safeImageName+".json") + outputFile := filepath.Join(c.outputDir, safeImageName+".cdx.json") // Ensure the output directory exists if err := os.MkdirAll(c.outputDir, 0755); err != nil { @@ -311,10 +322,6 @@ func (c sbomConfig) storeSBOM(sbom string, image string) error { return nil } -func getOutputDir(parentDir, version string) string { - return path.Join(parentDir, "sourcegraph-"+version) -} - // getImageReleaseListURL returns the URL for the list of images in a release, based on the version and whether it's an internal release. func (c *sbomConfig) getImageReleaseListURL() string { if c.internalRelease { diff --git a/cmd/src/sbom_utils.go b/cmd/src/sbom_utils.go index 9bce46e748..17f12f7e7c 100644 --- a/cmd/src/sbom_utils.go +++ b/cmd/src/sbom_utils.go @@ -6,6 +6,7 @@ import ( "io" "net/http" "os/exec" + "path" "strings" "time" ) @@ -190,3 +191,12 @@ func spinner(name string, stop chan bool) { } } } + +func getOutputDir(parentDir, version string) string { + return path.Join(parentDir, "sourcegraph-"+version) +} + +// sanitizeVersion removes any leading "v" from the version string +func sanitizeVersion(version string) string { + return strings.TrimPrefix(version, "v") +} From 177b25b230125397190810d657d49a75c763272f Mon Sep 17 00:00:00 2001 From: David Veszelovszki Date: Fri, 15 Nov 2024 00:29:13 +0100 Subject: [PATCH 440/647] feat/gateway: Add `src gateway benchmark` command (#1124) --- cmd/src/colors.go | 9 +- cmd/src/gateway.go | 38 ++++ cmd/src/gateway_benchmark.go | 331 +++++++++++++++++++++++++++++++++++ cmd/src/main.go | 1 + 4 files changed, 378 insertions(+), 1 deletion(-) create mode 100644 cmd/src/gateway.go create mode 100644 cmd/src/gateway_benchmark.go diff --git a/cmd/src/colors.go b/cmd/src/colors.go index 8d671e97f4..162a3842e1 100644 --- a/cmd/src/colors.go +++ b/cmd/src/colors.go @@ -22,7 +22,14 @@ func bg256Color(code int) string { // See https://i.stack.imgur.com/KTSQa.png or https://jonasjacek.github.io/colors/ var ansiColors = map[string]string{ - "nc": "\033[0m", + // Simple colors. + "blue": "\033[34m", + "green": "\033[32m", + "yellow": "\033[33m", + "red": "\033[31m", + "nc": "\033[0m", // reset + + // Custom colors. "logo": fg256Color(57), "warning": fg256Color(124), "success": fg256Color(2), diff --git a/cmd/src/gateway.go b/cmd/src/gateway.go new file mode 100644 index 0000000000..c84340df48 --- /dev/null +++ b/cmd/src/gateway.go @@ -0,0 +1,38 @@ +package main + +import ( + "flag" + "fmt" +) + +var gatewayCommands commander + +func init() { + usage := `'src gateway' interacts with Cody Gateway (directly or through a Sourcegraph instance). + +Usage: + + src gateway command [command options] + +The commands are: + + benchmark runs benchmarks against Cody Gateway + +Use "src gateway [command] -h" for more information about a command. + +` + + flagSet := flag.NewFlagSet("gateway", flag.ExitOnError) + handler := func(args []string) error { + gatewayCommands.run(flagSet, "src gateway", usage, args) + return nil + } + + // Register the command. + commands = append(commands, &command{ + flagSet: flagSet, + aliases: []string{}, // No aliases for gateway command + handler: handler, + usageFunc: func() { fmt.Println(usage) }, + }) +} diff --git a/cmd/src/gateway_benchmark.go b/cmd/src/gateway_benchmark.go new file mode 100644 index 0000000000..0b577fab93 --- /dev/null +++ b/cmd/src/gateway_benchmark.go @@ -0,0 +1,331 @@ +package main + +import ( + "encoding/csv" + "flag" + "fmt" + "io" + "net/http" + "os" + "sort" + "strings" + "time" + + "github.com/sourcegraph/src-cli/internal/cmderrors" +) + +type Stats struct { + Avg time.Duration + P5 time.Duration + P75 time.Duration + P80 time.Duration + P95 time.Duration + Median time.Duration + Total time.Duration +} + +func init() { + usage := ` +'src gateway benchmark' runs performance benchmarks against Cody Gateway endpoints. + +Usage: + + src gateway benchmark [flags] + +Examples: + + $ src gateway benchmark + $ src gateway benchmark --requests 50 + $ src gateway benchmark --requests 50 --csv results.csv +` + + flagSet := flag.NewFlagSet("benchmark", flag.ExitOnError) + + var ( + requestCount = flagSet.Int("requests", 1000, "Number of requests to make per endpoint") + csvOutput = flagSet.String("csv", "", "Export results to CSV file (provide filename)") + ) + + handler := func(args []string) error { + if err := flagSet.Parse(args); err != nil { + return err + } + + if len(flagSet.Args()) != 0 { + return cmderrors.Usage("additional arguments not allowed") + } + + // Create HTTP client with TLS skip verify + client := &http.Client{Transport: &http.Transport{}} + + endpoints := map[string]string{ + "HTTP": fmt.Sprintf("%s/gateway", cfg.Endpoint), + "HTTP then WebSocket": fmt.Sprintf("%s/gateway/http-then-websocket", cfg.Endpoint), + } + + fmt.Printf("Starting benchmark with %d requests per endpoint...\n", *requestCount) + + var results []endpointResult + + for name, url := range endpoints { + durations := make([]time.Duration, 0, *requestCount) + fmt.Printf("\nTesting %s...", name) + + for i := 0; i < *requestCount; i++ { + duration := benchmarkEndpoint(client, url) + if duration > 0 { + durations = append(durations, duration) + } + } + fmt.Println() + + stats := calculateStats(durations) + + results = append(results, endpointResult{ + name: name, + avg: stats.Avg, + median: stats.Median, + p5: stats.P5, + p75: stats.P75, + p80: stats.P80, + p95: stats.P95, + total: stats.Total, + successful: len(durations), + }) + } + + printResults(results, requestCount) + + if *csvOutput != "" { + if err := writeResultsToCSV(*csvOutput, results, requestCount); err != nil { + return fmt.Errorf("failed to export CSV: %v", err) + } + fmt.Printf("\nResults exported to %s\n", *csvOutput) + } + + return nil + } + + gatewayCommands = append(gatewayCommands, &command{ + flagSet: flagSet, + aliases: []string{}, + handler: handler, + usageFunc: func() { + _, err := fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src gateway %s':\n", flagSet.Name()) + if err != nil { + return + } + flagSet.PrintDefaults() + fmt.Println(usage) + }, + }) +} + +type endpointResult struct { + name string + avg time.Duration + median time.Duration + p5 time.Duration + p75 time.Duration + p80 time.Duration + p95 time.Duration + total time.Duration + successful int +} + +func benchmarkEndpoint(client *http.Client, url string) time.Duration { + start := time.Now() + resp, err := client.Get(url) + if err != nil { + fmt.Printf("Error calling %s: %v\n", url, err) + return 0 + } + defer func(Body io.ReadCloser) { + err := Body.Close() + if err != nil { + fmt.Printf("Error closing response body: %v\n", err) + } + }(resp.Body) + + _, err = io.ReadAll(resp.Body) + if err != nil { + fmt.Printf("Error reading response body: %v\n", err) + return 0 + } + + return time.Since(start) +} + +func calculateStats(durations []time.Duration) Stats { + if len(durations) == 0 { + return Stats{0, 0, 0, 0, 0, 0, 0} + } + + // Sort durations in ascending order + sort.Slice(durations, func(i, j int) bool { + return durations[i] < durations[j] + }) + + var sum time.Duration + for _, d := range durations { + sum += d + } + avg := sum / time.Duration(len(durations)) + + return Stats{ + Avg: avg, + P5: durations[int(float64(len(durations))*0.05)], + P75: durations[int(float64(len(durations))*0.75)], + P80: durations[int(float64(len(durations))*0.80)], + P95: durations[int(float64(len(durations))*0.95)], + Median: durations[(len(durations) / 2)], + Total: sum, + } +} + +func formatDuration(d time.Duration, best bool, worst bool) string { + value := fmt.Sprintf("%.2fms", float64(d.Microseconds())/1000) + if best { + return ansiColors["green"] + value + ansiColors["nc"] + } + if worst { + return ansiColors["red"] + value + ansiColors["nc"] + } + return ansiColors["yellow"] + value + ansiColors["nc"] +} + +func formatSuccessRate(successful, total int, best bool, worst bool) string { + value := fmt.Sprintf("%d/%d", successful, total) + if best { + return ansiColors["green"] + value + ansiColors["nc"] + } + if worst { + return ansiColors["red"] + value + ansiColors["nc"] + } + return ansiColors["yellow"] + value + ansiColors["nc"] +} + +func printResults(results []endpointResult, requestCount *int) { + // Print header + headerFmt := ansiColors["blue"] + "%-20s | %-10s | %-10s | %-10s | %-10s | %-10s | %-10s | %-10s | %-10s" + ansiColors["nc"] + "\n" + fmt.Printf("\n"+headerFmt, + "Endpoint ", "Average", "Median", "P5", "P75", "P80", "P95", "Total", "Success") + fmt.Println(ansiColors["blue"] + strings.Repeat("-", 121) + ansiColors["nc"]) + + // Find best/worst values for each metric + var bestAvg, worstAvg time.Duration + var bestMedian, worstMedian time.Duration + var bestP5, worstP5 time.Duration + var bestP75, worstP75 time.Duration + var bestP80, worstP80 time.Duration + var bestP95, worstP95 time.Duration + var bestTotal, worstTotal time.Duration + var bestSuccess, worstSuccess int + + for i, r := range results { + if i == 0 || r.avg < bestAvg { + bestAvg = r.avg + } + if i == 0 || r.avg > worstAvg { + worstAvg = r.avg + } + if i == 0 || r.median < bestMedian { + bestMedian = r.median + } + if i == 0 || r.median > worstMedian { + worstMedian = r.median + } + if i == 0 || r.p5 < bestP5 { + bestP5 = r.p5 + } + if i == 0 || r.p5 > worstP5 { + worstP5 = r.p5 + } + if i == 0 || r.p75 < bestP75 { + bestP75 = r.p75 + } + if i == 0 || r.p75 > worstP75 { + worstP75 = r.p75 + } + if i == 0 || r.p80 < bestP80 { + bestP80 = r.p80 + } + if i == 0 || r.p80 > worstP80 { + worstP80 = r.p80 + } + if i == 0 || r.p95 < bestP95 { + bestP95 = r.p95 + } + if i == 0 || r.p95 > worstP95 { + worstP95 = r.p95 + } + if i == 0 || r.total < bestTotal { + bestTotal = r.total + } + if i == 0 || r.total > worstTotal { + worstTotal = r.total + } + if i == 0 || r.successful > bestSuccess { + bestSuccess = r.successful + } + if i == 0 || r.successful < worstSuccess { + worstSuccess = r.successful + } + } + + // Print each row + for _, r := range results { + fmt.Printf("%-20s | %-19s | %-19s | %-19s | %-19s | %-19s | %-19s | %-19s | %s\n", + r.name, + formatDuration(r.avg, r.avg == bestAvg, r.avg == worstAvg), + formatDuration(r.median, r.median == bestMedian, r.median == worstMedian), + formatDuration(r.p5, r.p5 == bestP5, r.p5 == worstP5), + formatDuration(r.p75, r.p75 == bestP75, r.p75 == worstP75), + formatDuration(r.p80, r.p80 == bestP80, r.p80 == worstP80), + formatDuration(r.p95, r.p95 == bestP95, r.p95 == worstP95), + formatDuration(r.total, r.total == bestTotal, r.total == worstTotal), + formatSuccessRate(r.successful, *requestCount, r.successful == bestSuccess, r.successful == worstSuccess)) + } +} + +func writeResultsToCSV(filename string, results []endpointResult, requestCount *int) error { + file, err := os.Create(filename) + if err != nil { + return fmt.Errorf("failed to create CSV file: %v", err) + } + defer func() { + err := file.Close() + if err != nil { + return + } + }() + + writer := csv.NewWriter(file) + defer writer.Flush() + + // Write header + header := []string{"Endpoint", "Average (ms)", "Median (ms)", "P5 (ms)", "P75 (ms)", "P80 (ms)", "P95 (ms)", "Total (ms)", "Success Rate"} + if err := writer.Write(header); err != nil { + return fmt.Errorf("failed to write CSV header: %v", err) + } + + // Write data rows + for _, r := range results { + row := []string{ + r.name, + fmt.Sprintf("%.2f", float64(r.avg.Microseconds())/1000), + fmt.Sprintf("%.2f", float64(r.median.Microseconds())/1000), + fmt.Sprintf("%.2f", float64(r.p5.Microseconds())/1000), + fmt.Sprintf("%.2f", float64(r.p75.Microseconds())/1000), + fmt.Sprintf("%.2f", float64(r.p80.Microseconds())/1000), + fmt.Sprintf("%.2f", float64(r.p95.Microseconds())/1000), + fmt.Sprintf("%.2f", float64(r.total.Microseconds())/1000), + fmt.Sprintf("%d/%d", r.successful, *requestCount), + } + if err := writer.Write(row); err != nil { + return fmt.Errorf("failed to write CSV row: %v", err) + } + } + + return nil +} diff --git a/cmd/src/main.go b/cmd/src/main.go index f2dfe270e4..d8d32b7983 100644 --- a/cmd/src/main.go +++ b/cmd/src/main.go @@ -53,6 +53,7 @@ The commands are: config manages global, org, and user settings extensions,ext manages extensions (experimental) extsvc manages external services + gateway interacts with Cody Gateway login authenticate to a Sourcegraph instance with your user credentials lsif manages LSIF data (deprecated: use 'code-intel') orgs,org manages organizations From ab6791e5fe4be5e23b2f3d442c21bc9d53820b06 Mon Sep 17 00:00:00 2001 From: Pururva Lakkad Date: Fri, 15 Nov 2024 01:59:48 -0500 Subject: [PATCH 441/647] Access token err msg (#1121) * Bugfix: Improved access token error msg * Bugfix: Added replace directive for sourcegraph-public-snapshot in go.mod * Updated login tests. --- cmd/src/login.go | 8 ++++---- cmd/src/login_test.go | 8 ++++---- go.mod | 1 + go.sum | 4 ++-- 4 files changed, 11 insertions(+), 10 deletions(-) diff --git a/cmd/src/login.go b/cmd/src/login.go index 6915cada7f..b368f617e2 100644 --- a/cmd/src/login.go +++ b/cmd/src/login.go @@ -71,12 +71,12 @@ func loginCmd(ctx context.Context, cfg *config, client api.Client, endpointArg s fmt.Fprintf(out, "❌ Problem: %s\n", problem) } - createAccessTokenMessage := fmt.Sprintf("\n"+`🛠 To fix: Create an access token at %s/user/settings/tokens, then set the following environment variables: + createAccessTokenMessage := fmt.Sprintf("\n"+`🛠 To fix: Create an access token by going to %s/user/settings/tokens, then set the following environment variables in your terminal: - SRC_ENDPOINT=%s - SRC_ACCESS_TOKEN=(the access token you just created) + export SRC_ENDPOINT=%s + export SRC_ACCESS_TOKEN=(your access token) - To verify that it's working, run this command again. + To verify that it's working, run the login command again. `, endpointArg, endpointArg) if cfg.ConfigFilePath != "" { diff --git a/cmd/src/login_test.go b/cmd/src/login_test.go index 45403e293b..ce23343fce 100644 --- a/cmd/src/login_test.go +++ b/cmd/src/login_test.go @@ -27,7 +27,7 @@ func TestLogin(t *testing.T) { if err != cmderrors.ExitCode1 { t.Fatal(err) } - wantOut := "❌ Problem: No access token is configured.\n\n🛠 To fix: Create an access token at https://sourcegraph.example.com/user/settings/tokens, then set the following environment variables:\n\n SRC_ENDPOINT=https://sourcegraph.example.com\n SRC_ACCESS_TOKEN=(the access token you just created)\n\n To verify that it's working, run this command again." + wantOut := "❌ Problem: No access token is configured.\n\n🛠 To fix: Create an access token by going to https://sourcegraph.example.com/user/settings/tokens, then set the following environment variables in your terminal:\n\n export SRC_ENDPOINT=https://sourcegraph.example.com\n export SRC_ACCESS_TOKEN=(your access token)\n\n To verify that it's working, run the login command again." if out != wantOut { t.Errorf("got output %q, want %q", out, wantOut) } @@ -38,7 +38,7 @@ func TestLogin(t *testing.T) { if err != cmderrors.ExitCode1 { t.Fatal(err) } - wantOut := "❌ Problem: No access token is configured.\n\n🛠 To fix: Create an access token at https://sourcegraph.example.com/user/settings/tokens, then set the following environment variables:\n\n SRC_ENDPOINT=https://sourcegraph.example.com\n SRC_ACCESS_TOKEN=(the access token you just created)\n\n To verify that it's working, run this command again." + wantOut := "❌ Problem: No access token is configured.\n\n🛠 To fix: Create an access token by going to https://sourcegraph.example.com/user/settings/tokens, then set the following environment variables in your terminal:\n\n export SRC_ENDPOINT=https://sourcegraph.example.com\n export SRC_ACCESS_TOKEN=(your access token)\n\n To verify that it's working, run the login command again." if out != wantOut { t.Errorf("got output %q, want %q", out, wantOut) } @@ -49,7 +49,7 @@ func TestLogin(t *testing.T) { if err != cmderrors.ExitCode1 { t.Fatal(err) } - wantOut := "⚠️ Warning: Configuring src with a JSON file is deprecated. Please migrate to using the env vars SRC_ENDPOINT, SRC_ACCESS_TOKEN, and SRC_PROXY instead, and then remove f. See https://github.com/sourcegraph/src-cli#readme for more information.\n\n❌ Problem: No access token is configured.\n\n🛠 To fix: Create an access token at https://example.com/user/settings/tokens, then set the following environment variables:\n\n SRC_ENDPOINT=https://example.com\n SRC_ACCESS_TOKEN=(the access token you just created)\n\n To verify that it's working, run this command again." + wantOut := "⚠️ Warning: Configuring src with a JSON file is deprecated. Please migrate to using the env vars SRC_ENDPOINT, SRC_ACCESS_TOKEN, and SRC_PROXY instead, and then remove f. See https://github.com/sourcegraph/src-cli#readme for more information.\n\n❌ Problem: No access token is configured.\n\n🛠 To fix: Create an access token by going to https://example.com/user/settings/tokens, then set the following environment variables in your terminal:\n\n export SRC_ENDPOINT=https://example.com\n export SRC_ACCESS_TOKEN=(your access token)\n\n To verify that it's working, run the login command again." if out != wantOut { t.Errorf("got output %q, want %q", out, wantOut) } @@ -67,7 +67,7 @@ func TestLogin(t *testing.T) { if err != cmderrors.ExitCode1 { t.Fatal(err) } - wantOut := "❌ Problem: Invalid access token.\n\n🛠 To fix: Create an access token at $ENDPOINT/user/settings/tokens, then set the following environment variables:\n\n SRC_ENDPOINT=$ENDPOINT\n SRC_ACCESS_TOKEN=(the access token you just created)\n\n To verify that it's working, run this command again.\n\n (If you need to supply custom HTTP request headers, see information about SRC_HEADER_* and SRC_HEADERS env vars at https://github.com/sourcegraph/src-cli/blob/main/AUTH_PROXY.md.)" + wantOut := "❌ Problem: Invalid access token.\n\n🛠 To fix: Create an access token by going to $ENDPOINT/user/settings/tokens, then set the following environment variables in your terminal:\n\n export SRC_ENDPOINT=$ENDPOINT\n export SRC_ACCESS_TOKEN=(your access token)\n\n To verify that it's working, run the login command again.\n\n (If you need to supply custom HTTP request headers, see information about SRC_HEADER_* and SRC_HEADERS env vars at https://github.com/sourcegraph/src-cli/blob/main/AUTH_PROXY.md.)" wantOut = strings.ReplaceAll(wantOut, "$ENDPOINT", endpoint) if out != wantOut { t.Errorf("got output %q, want %q", out, wantOut) diff --git a/go.mod b/go.mod index 58a587e36d..2fd2d21e4a 100644 --- a/go.mod +++ b/go.mod @@ -196,3 +196,4 @@ require ( // See: https://github.com/ghodss/yaml/pull/65 replace github.com/ghodss/yaml => github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 +replace github.com/sourcegraph/sourcegraph/lib => github.com/sourcegraph/sourcegraph-public-snapshot/lib v0.0.0-20240709083501-1af563b61442 diff --git a/go.sum b/go.sum index 6127dde105..203aab9ee8 100644 --- a/go.sum +++ b/go.sum @@ -388,8 +388,8 @@ github.com/sourcegraph/log v0.0.0-20231018134238-fbadff7458bb h1:tHKdC+bXxxGJ0cy github.com/sourcegraph/log v0.0.0-20231018134238-fbadff7458bb/go.mod h1:IDp09QkoqS8Z3CyN2RW6vXjgABkNpDbyjLIHNQwQ8P8= github.com/sourcegraph/scip v0.3.1-0.20230627154934-45df7f6d33fc h1:o+eq0cjVV3B5ngIBF04Lv3GwttKOuYFF5NTcfXWXzfA= github.com/sourcegraph/scip v0.3.1-0.20230627154934-45df7f6d33fc/go.mod h1:7ZKAtLIUmiMvOIgG5LMcBxdtBXVa0v2GWC4Hm1ASYQ0= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20240709083501-1af563b61442 h1:n3HZCz5fJRtxCzjcUHZwrfJb96xU0+s2L4/+Da2kD3A= -github.com/sourcegraph/sourcegraph/lib v0.0.0-20240709083501-1af563b61442/go.mod h1:RBdAauod1tGL33L1Izr2YymwN8uWQV++fL6orhD4aqc= +github.com/sourcegraph/sourcegraph-public-snapshot/lib v0.0.0-20240709083501-1af563b61442 h1:M/jSgKSzeYbfrE/C6H8b8zu07c59taz4fIQcOGh1vqY= +github.com/sourcegraph/sourcegraph-public-snapshot/lib v0.0.0-20240709083501-1af563b61442/go.mod h1:RBdAauod1tGL33L1Izr2YymwN8uWQV++fL6orhD4aqc= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I= From 2bcd4001ed5c1cb233e452eb92f6f4f55fd3a655 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Wed, 20 Nov 2024 11:17:23 +0200 Subject: [PATCH 442/647] update golang tools version (#1126) --- .github/workflows/go-ci.yml | 2 +- .github/workflows/go-lint.yml | 2 +- .github/workflows/goreleaser-check.yml | 2 +- .github/workflows/goreleaser.yml | 2 +- .github/workflows/pr-auditor.yml | 2 +- .tool-versions | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/go-ci.yml b/.github/workflows/go-ci.yml index cae55fa06a..5e467bcc65 100644 --- a/.github/workflows/go-ci.yml +++ b/.github/workflows/go-ci.yml @@ -11,7 +11,7 @@ jobs: go-test: strategy: matrix: - go-version: [1.22.8] + go-version: [1.23.2] os: [ubuntu-latest, macos-latest, windows-latest] runs-on: ${{ matrix.os }} steps: diff --git a/.github/workflows/go-lint.yml b/.github/workflows/go-lint.yml index 542cc84383..0af8fa22b4 100644 --- a/.github/workflows/go-lint.yml +++ b/.github/workflows/go-lint.yml @@ -16,7 +16,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v5 with: - go-version: 1.22.8 + go-version: 1.23.2 - name: Enable pulling Go modules from private sourcegraph/sourcegraph run: git config --global url."https://${PRIVATE_TOKEN}@github.com/sourcegraph/".insteadOf "https://github.com/sourcegraph/" - run: ./dev/go-lint.sh diff --git a/.github/workflows/goreleaser-check.yml b/.github/workflows/goreleaser-check.yml index 762b1f9cef..59179af2e6 100644 --- a/.github/workflows/goreleaser-check.yml +++ b/.github/workflows/goreleaser-check.yml @@ -19,7 +19,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v5 with: - go-version: 1.22.8 + go-version: 1.23.2 - name: Enable pulling Go modules from private sourcegraph/sourcegraph run: git config --global url."https://${PRIVATE_TOKEN}@github.com/sourcegraph/".insteadOf "https://github.com/sourcegraph/" - name: Check GoReleaser config diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index 90ca689e81..46af514805 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -181,7 +181,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v5 with: - go-version: 1.22.8 + go-version: 1.23.2 - name: Enable pulling Go modules from private sourcegraph/sourcegraph run: git config --global url."https://${PRIVATE_TOKEN}@github.com/sourcegraph/".insteadOf "https://github.com/sourcegraph/" - run: go test ./... diff --git a/.github/workflows/pr-auditor.yml b/.github/workflows/pr-auditor.yml index 4a0fc2d708..fe0862e021 100644 --- a/.github/workflows/pr-auditor.yml +++ b/.github/workflows/pr-auditor.yml @@ -14,7 +14,7 @@ jobs: repository: 'sourcegraph/devx-service' token: ${{ secrets.PR_AUDITOR_TOKEN }} - uses: actions/setup-go@v5 - with: { go-version: '1.22' } + with: { go-version: '1.23' } - run: 'go run ./cmd/pr-auditor' env: diff --git a/.tool-versions b/.tool-versions index 9e1c90413a..a184b8990c 100644 --- a/.tool-versions +++ b/.tool-versions @@ -1,3 +1,3 @@ -golang 1.22.8 +golang 1.23.2 shfmt 3.8.0 shellcheck 0.10.0 From ae7a9c04a270876b17e233fcf01be26a698ef798 Mon Sep 17 00:00:00 2001 From: Emi Gutekanst Date: Tue, 3 Dec 2024 18:53:34 -0700 Subject: [PATCH 443/647] update Go version; add websocket / correct endpoints to 'src gateway benchmark' (#1125) * gateway: benchmark: check HTTP status code * gateway: benchmark: add websocket testing; fix endpoint handling * go get github.com/gorilla/websocket * address PR feedback --------- Signed-off-by: Stephen Gutekanst --- cmd/src/gateway_benchmark.go | 90 +++++++++++++++++++++++++++++------- go.mod | 2 + go.sum | 2 + 3 files changed, 78 insertions(+), 16 deletions(-) diff --git a/cmd/src/gateway_benchmark.go b/cmd/src/gateway_benchmark.go index 0b577fab93..ef3749fb8f 100644 --- a/cmd/src/gateway_benchmark.go +++ b/cmd/src/gateway_benchmark.go @@ -11,6 +11,8 @@ import ( "strings" "time" + "github.com/gorilla/websocket" + "github.com/sourcegraph/src-cli/internal/cmderrors" ) @@ -42,8 +44,9 @@ Examples: flagSet := flag.NewFlagSet("benchmark", flag.ExitOnError) var ( - requestCount = flagSet.Int("requests", 1000, "Number of requests to make per endpoint") - csvOutput = flagSet.String("csv", "", "Export results to CSV file (provide filename)") + requestCount = flagSet.Int("requests", 1000, "Number of requests to make per endpoint") + csvOutput = flagSet.String("csv", "", "Export results to CSV file (provide filename)") + gatewayEndpoint = flagSet.String("gateway", "https://cody-gateway.sourcegraph.com", "Cody Gateway endpoint") ) handler := func(args []string) error { @@ -55,26 +58,49 @@ Examples: return cmderrors.Usage("additional arguments not allowed") } - // Create HTTP client with TLS skip verify - client := &http.Client{Transport: &http.Transport{}} - - endpoints := map[string]string{ - "HTTP": fmt.Sprintf("%s/gateway", cfg.Endpoint), - "HTTP then WebSocket": fmt.Sprintf("%s/gateway/http-then-websocket", cfg.Endpoint), + var ( + gatewayWebsocket, sourcegraphWebsocket *websocket.Conn + err error + httpClient = &http.Client{} + endpoints = map[string]any{} // Values: URL `string`s or `*websocket.Conn`s + ) + if *gatewayEndpoint != "" { + wsURL := strings.Replace(fmt.Sprint(*gatewayEndpoint, "/v2/websocket"), "http", "ws", 1) + gatewayWebsocket, _, err = websocket.DefaultDialer.Dial(wsURL, nil) + if err != nil { + return fmt.Errorf("WebSocket dial(%s): %v", wsURL, err) + } + endpoints["ws(s): gateway"] = gatewayWebsocket + endpoints["http(s): gateway"] = fmt.Sprint(*gatewayEndpoint, "/v2") + } + if cfg.Endpoint != "" { + wsURL := strings.Replace(fmt.Sprint(cfg.Endpoint, "/.api/gateway/websocket"), "http", "ws", 1) + sourcegraphWebsocket, _, err = websocket.DefaultDialer.Dial(wsURL, nil) + if err != nil { + return fmt.Errorf("WebSocket dial(%s): %v", wsURL, err) + } + endpoints["ws(s): sourcegraph"] = sourcegraphWebsocket + endpoints["http(s): sourcegraph"] = fmt.Sprint(*gatewayEndpoint, "/.api/gateway") } fmt.Printf("Starting benchmark with %d requests per endpoint...\n", *requestCount) var results []endpointResult - - for name, url := range endpoints { + for name, clientOrURL := range endpoints { durations := make([]time.Duration, 0, *requestCount) fmt.Printf("\nTesting %s...", name) for i := 0; i < *requestCount; i++ { - duration := benchmarkEndpoint(client, url) - if duration > 0 { - durations = append(durations, duration) + if ws, ok := clientOrURL.(*websocket.Conn); ok { + duration := benchmarkEndpointWebSocket(ws) + if duration > 0 { + durations = append(durations, duration) + } + } else if url, ok := clientOrURL.(string); ok { + duration := benchmarkEndpointHTTP(httpClient, url) + if duration > 0 { + durations = append(durations, duration) + } } } fmt.Println() @@ -133,15 +159,15 @@ type endpointResult struct { successful int } -func benchmarkEndpoint(client *http.Client, url string) time.Duration { +func benchmarkEndpointHTTP(client *http.Client, url string) time.Duration { start := time.Now() resp, err := client.Get(url) if err != nil { fmt.Printf("Error calling %s: %v\n", url, err) return 0 } - defer func(Body io.ReadCloser) { - err := Body.Close() + defer func(body io.ReadCloser) { + err := body.Close() if err != nil { fmt.Printf("Error closing response body: %v\n", err) } @@ -152,10 +178,42 @@ func benchmarkEndpoint(client *http.Client, url string) time.Duration { fmt.Printf("Error reading response body: %v\n", err) return 0 } + if resp.StatusCode != http.StatusOK { + fmt.Printf("non-200 response: %v\n", resp.Status) + return 0 + } + body, err := io.ReadAll(resp.Body) + if err != nil { + fmt.Printf("Error reading response body: %v\n", err) + return 0 + } + if string(body) != "pong" { + fmt.Printf("Expected 'pong' response, got: %q\n", string(body)) + return 0 + } return time.Since(start) } +func benchmarkEndpointWebSocket(conn *websocket.Conn) time.Duration { + start := time.Now() + err := conn.WriteMessage(websocket.TextMessage, []byte("ping")) + if err != nil { + fmt.Printf("WebSocket write error: %v\n", err) + return 0 + } + _, message, err := conn.ReadMessage() + if err != nil { + fmt.Printf("WebSocket read error: %v\n", err) + return 0 + } + if string(message) != "pong" { + fmt.Printf("Expected 'pong' response, got: %q\n", string(message)) + return 0 + } + return time.Since(start) +} + func calculateStats(durations []time.Duration) Stats { if len(durations) == 0 { return Stats{0, 0, 0, 0, 0, 0, 0} diff --git a/go.mod b/go.mod index 2fd2d21e4a..aeb1de58a3 100644 --- a/go.mod +++ b/go.mod @@ -49,6 +49,7 @@ require ( require ( github.com/google/pprof v0.0.0-20230602150820-91b7bce49751 // indirect github.com/google/s2a-go v0.1.4 // indirect + github.com/gorilla/websocket v1.5.3 // indirect github.com/jackc/chunkreader/v2 v2.0.1 // indirect github.com/jackc/pgconn v1.14.3 // indirect github.com/jackc/pgio v1.0.0 // indirect @@ -196,4 +197,5 @@ require ( // See: https://github.com/ghodss/yaml/pull/65 replace github.com/ghodss/yaml => github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 + replace github.com/sourcegraph/sourcegraph/lib => github.com/sourcegraph/sourcegraph-public-snapshot/lib v0.0.0-20240709083501-1af563b61442 diff --git a/go.sum b/go.sum index 203aab9ee8..8dcd3114dd 100644 --- a/go.sum +++ b/go.sum @@ -211,6 +211,8 @@ github.com/googleapis/gax-go/v2 v2.12.0/go.mod h1:y+aIqrI5eb1YGMVJfuV3185Ts/D7qK github.com/gorilla/css v1.0.0 h1:BQqNyPTi50JCFMTw/b67hByjMVXZRwGha6wxVGkeihY= github.com/gorilla/css v1.0.0/go.mod h1:Dn721qIggHpt4+EFCcTLTU/vk5ySda2ReITrtgBl60c= github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= +github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/grafana/regexp v0.0.0-20221123153739-15dc172cd2db h1:7aN5cccjIqCLTzedH7MZzRZt5/lsAHch6Z3L2ZGn5FA= github.com/grafana/regexp v0.0.0-20221123153739-15dc172cd2db/go.mod h1:M5qHK+eWfAv8VR/265dIuEpL3fNfeC21tXXp9itM24A= github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= From 4fdbf718f3b5a934b01b9637dd1b0a415ac24a9d Mon Sep 17 00:00:00 2001 From: David Veszelovszki Date: Wed, 4 Dec 2024 20:15:48 +0100 Subject: [PATCH 444/647] Fix body closing format for CI (#1128) --- cmd/src/gateway_benchmark.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cmd/src/gateway_benchmark.go b/cmd/src/gateway_benchmark.go index ef3749fb8f..93d6f99ea1 100644 --- a/cmd/src/gateway_benchmark.go +++ b/cmd/src/gateway_benchmark.go @@ -166,12 +166,12 @@ func benchmarkEndpointHTTP(client *http.Client, url string) time.Duration { fmt.Printf("Error calling %s: %v\n", url, err) return 0 } - defer func(body io.ReadCloser) { - err := body.Close() + defer func() { + err := resp.Body.Close() if err != nil { fmt.Printf("Error closing response body: %v\n", err) } - }(resp.Body) + }() _, err = io.ReadAll(resp.Body) if err != nil { From a4410218ab48cc1b1c43c99f913ecc43079c87cb Mon Sep 17 00:00:00 2001 From: David Veszelovszki Date: Wed, 4 Dec 2024 20:16:59 +0100 Subject: [PATCH 445/647] Use the new URLs and local port for WebSocket (#1127) * Use the new URLs * Add new CLI flag to work with local Sourcegraph --------- Co-authored-by: Emi Gutekanst --- cmd/src/gateway_benchmark.go | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/cmd/src/gateway_benchmark.go b/cmd/src/gateway_benchmark.go index 93d6f99ea1..6e22d8a924 100644 --- a/cmd/src/gateway_benchmark.go +++ b/cmd/src/gateway_benchmark.go @@ -38,6 +38,7 @@ Examples: $ src gateway benchmark $ src gateway benchmark --requests 50 + $ src gateway benchmark --gateway http://localhost:9992 --sourcegraph http://localhost:3082 $ src gateway benchmark --requests 50 --csv results.csv ` @@ -47,6 +48,7 @@ Examples: requestCount = flagSet.Int("requests", 1000, "Number of requests to make per endpoint") csvOutput = flagSet.String("csv", "", "Export results to CSV file (provide filename)") gatewayEndpoint = flagSet.String("gateway", "https://cody-gateway.sourcegraph.com", "Cody Gateway endpoint") + sgEndpoint = flagSet.String("sourcegraph", "https://sourcegraph.com", "Sourcegraph endpoint") ) handler := func(args []string) error { @@ -71,16 +73,16 @@ Examples: return fmt.Errorf("WebSocket dial(%s): %v", wsURL, err) } endpoints["ws(s): gateway"] = gatewayWebsocket - endpoints["http(s): gateway"] = fmt.Sprint(*gatewayEndpoint, "/v2") + endpoints["http(s): gateway"] = fmt.Sprint(*gatewayEndpoint, "/v2/http") } - if cfg.Endpoint != "" { - wsURL := strings.Replace(fmt.Sprint(cfg.Endpoint, "/.api/gateway/websocket"), "http", "ws", 1) + if *sgEndpoint != "" { + wsURL := strings.Replace(fmt.Sprint(*sgEndpoint, "/.api/gateway/websocket"), "http", "ws", 1) sourcegraphWebsocket, _, err = websocket.DefaultDialer.Dial(wsURL, nil) if err != nil { return fmt.Errorf("WebSocket dial(%s): %v", wsURL, err) } endpoints["ws(s): sourcegraph"] = sourcegraphWebsocket - endpoints["http(s): sourcegraph"] = fmt.Sprint(*gatewayEndpoint, "/.api/gateway") + endpoints["http(s): sourcegraph"] = fmt.Sprint(*sgEndpoint, "/.api/gateway/http") } fmt.Printf("Starting benchmark with %d requests per endpoint...\n", *requestCount) From 947f4b2682be8e384da9287e0087a5d893033dc9 Mon Sep 17 00:00:00 2001 From: Emi Gutekanst Date: Thu, 5 Dec 2024 04:41:01 -0700 Subject: [PATCH 446/647] gateway: benchmark: use POST, improve logging slightly (#1129) * gateway: benchmark: use POST, improve logging slightly Signed-off-by: Stephen Gutekanst * Add Authorization header --------- Signed-off-by: Stephen Gutekanst Co-authored-by: David Veszelovszki --- cmd/src/gateway_benchmark.go | 83 +++++++++++++++++++++++++++--------- 1 file changed, 64 insertions(+), 19 deletions(-) diff --git a/cmd/src/gateway_benchmark.go b/cmd/src/gateway_benchmark.go index 6e22d8a924..910f4e0c87 100644 --- a/cmd/src/gateway_benchmark.go +++ b/cmd/src/gateway_benchmark.go @@ -26,6 +26,23 @@ type Stats struct { Total time.Duration } +// httpEndpointConfig represents the configuration for an HTTP endpoint. +type httpEndpointConfig struct { + client *http.Client + url string +} + +// sgAuthTransport is an http.RoundTripper that adds an Authorization header to requests. +// It is used to add the Sourcegraph access token to requests to Sourcegraph endpoints. +type sgAuthTransport struct { + token string + base http.RoundTripper +} +func (t *sgAuthTransport) RoundTrip(req *http.Request) (*http.Response, error) { + req.Header.Add("Authorization", "token "+t.token) + return t.base.RoundTrip(req) +} + func init() { usage := ` 'src gateway benchmark' runs performance benchmarks against Cody Gateway endpoints. @@ -38,7 +55,7 @@ Examples: $ src gateway benchmark $ src gateway benchmark --requests 50 - $ src gateway benchmark --gateway http://localhost:9992 --sourcegraph http://localhost:3082 + $ src gateway benchmark --gateway http://localhost:9992 --sourcegraph http://localhost:3082 --sgp sgp_***** --requests 50 $ src gateway benchmark --requests 50 --csv results.csv ` @@ -49,6 +66,7 @@ Examples: csvOutput = flagSet.String("csv", "", "Export results to CSV file (provide filename)") gatewayEndpoint = flagSet.String("gateway", "https://cody-gateway.sourcegraph.com", "Cody Gateway endpoint") sgEndpoint = flagSet.String("sourcegraph", "https://sourcegraph.com", "Sourcegraph endpoint") + sgpToken = flagSet.String("sgp", "sgp_*****", "Sourcegraph personal access token for the called instance") ) handler := func(args []string) error { @@ -63,43 +81,76 @@ Examples: var ( gatewayWebsocket, sourcegraphWebsocket *websocket.Conn err error - httpClient = &http.Client{} + gatewayClient = &http.Client{} + sourcegraphClient = &http.Client{} endpoints = map[string]any{} // Values: URL `string`s or `*websocket.Conn`s ) + + // Connect to endpoints if *gatewayEndpoint != "" { + fmt.Println("Benchmarking Cody Gateway instance:", *gatewayEndpoint) wsURL := strings.Replace(fmt.Sprint(*gatewayEndpoint, "/v2/websocket"), "http", "ws", 1) + fmt.Println("Connecting to Cody Gateway via WebSocket..", wsURL) gatewayWebsocket, _, err = websocket.DefaultDialer.Dial(wsURL, nil) if err != nil { return fmt.Errorf("WebSocket dial(%s): %v", wsURL, err) } + fmt.Println("Connected!") endpoints["ws(s): gateway"] = gatewayWebsocket - endpoints["http(s): gateway"] = fmt.Sprint(*gatewayEndpoint, "/v2/http") + endpoints["http(s): gateway"] = &httpEndpointConfig{ + client: gatewayClient, + url: fmt.Sprint(*gatewayEndpoint, "/v2/http"), + } + } else { + fmt.Println("warning: not benchmarking Cody Gateway (-gateway endpoint not provided)") } if *sgEndpoint != "" { + // Add auth header to sourcegraphClient transport + if *sgpToken != "" { + sourcegraphClient.Transport = &sgAuthTransport{ + token: *sgpToken, + base: http.DefaultTransport, + } + } + fmt.Println("Benchmarking Sourcegraph instance:", *sgEndpoint) wsURL := strings.Replace(fmt.Sprint(*sgEndpoint, "/.api/gateway/websocket"), "http", "ws", 1) - sourcegraphWebsocket, _, err = websocket.DefaultDialer.Dial(wsURL, nil) + header := http.Header{} + header.Add("Authorization", "token "+*sgpToken) + fmt.Println("Connecting to Sourcegraph instance via WebSocket..", wsURL) + sourcegraphWebsocket, _, err = websocket.DefaultDialer.Dial(wsURL, header) if err != nil { return fmt.Errorf("WebSocket dial(%s): %v", wsURL, err) } + fmt.Println("Connected!") + endpoints["ws(s): sourcegraph"] = sourcegraphWebsocket - endpoints["http(s): sourcegraph"] = fmt.Sprint(*sgEndpoint, "/.api/gateway/http") + endpoints["http(s): sourcegraph"] = &httpEndpointConfig{ + client: sourcegraphClient, + url: fmt.Sprint(*sgEndpoint, "/.api/gateway/http"), + } + endpoints["http(s): http-then-ws"] = &httpEndpointConfig{ + client: sourcegraphClient, + url: fmt.Sprint(*sgEndpoint, "/.api/gateway/http-then-websocket"), + } + } else { + fmt.Println("warning: not benchmarking Sourcegraph instance (-sourcegraph endpoint not provided)") } fmt.Printf("Starting benchmark with %d requests per endpoint...\n", *requestCount) var results []endpointResult - for name, clientOrURL := range endpoints { + for name, clientOrEndpointConfig := range endpoints { durations := make([]time.Duration, 0, *requestCount) fmt.Printf("\nTesting %s...", name) for i := 0; i < *requestCount; i++ { - if ws, ok := clientOrURL.(*websocket.Conn); ok { + if ws, ok := clientOrEndpointConfig.(*websocket.Conn); ok { duration := benchmarkEndpointWebSocket(ws) if duration > 0 { durations = append(durations, duration) } - } else if url, ok := clientOrURL.(string); ok { - duration := benchmarkEndpointHTTP(httpClient, url) + } else if epConf, ok := clientOrEndpointConfig.(httpEndpointConfig); ok { + duration := benchmarkEndpointHTTP(epConf) if duration > 0 { durations = append(durations, duration) } @@ -161,11 +212,11 @@ type endpointResult struct { successful int } -func benchmarkEndpointHTTP(client *http.Client, url string) time.Duration { +func benchmarkEndpointHTTP(epConfig httpEndpointConfig) time.Duration { start := time.Now() - resp, err := client.Get(url) + resp, err := epConfig.client.Post(epConfig.url, "application/json", strings.NewReader("ping")) if err != nil { - fmt.Printf("Error calling %s: %v\n", url, err) + fmt.Printf("Error calling %s: %v\n", epConfig.url, err) return 0 } defer func() { @@ -174,12 +225,6 @@ func benchmarkEndpointHTTP(client *http.Client, url string) time.Duration { fmt.Printf("Error closing response body: %v\n", err) } }() - - _, err = io.ReadAll(resp.Body) - if err != nil { - fmt.Printf("Error reading response body: %v\n", err) - return 0 - } if resp.StatusCode != http.StatusOK { fmt.Printf("non-200 response: %v\n", resp.Status) return 0 @@ -267,7 +312,7 @@ func formatSuccessRate(successful, total int, best bool, worst bool) string { func printResults(results []endpointResult, requestCount *int) { // Print header - headerFmt := ansiColors["blue"] + "%-20s | %-10s | %-10s | %-10s | %-10s | %-10s | %-10s | %-10s | %-10s" + ansiColors["nc"] + "\n" + headerFmt := ansiColors["blue"] + "%-25s | %-10s | %-10s | %-10s | %-10s | %-10s | %-10s | %-10s | %-10s" + ansiColors["nc"] + "\n" fmt.Printf("\n"+headerFmt, "Endpoint ", "Average", "Median", "P5", "P75", "P80", "P95", "Total", "Success") fmt.Println(ansiColors["blue"] + strings.Repeat("-", 121) + ansiColors["nc"]) From 7a2b7899b070f7211e89b05151447ba84b638038 Mon Sep 17 00:00:00 2001 From: David Veszelovszki Date: Fri, 6 Dec 2024 14:07:04 +0100 Subject: [PATCH 447/647] Fix httpEndpointConfig pointer type issue (#1130) --- cmd/src/gateway_benchmark.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cmd/src/gateway_benchmark.go b/cmd/src/gateway_benchmark.go index 910f4e0c87..93a6c952dc 100644 --- a/cmd/src/gateway_benchmark.go +++ b/cmd/src/gateway_benchmark.go @@ -149,7 +149,7 @@ Examples: if duration > 0 { durations = append(durations, duration) } - } else if epConf, ok := clientOrEndpointConfig.(httpEndpointConfig); ok { + } else if epConf, ok := clientOrEndpointConfig.(*httpEndpointConfig); ok { duration := benchmarkEndpointHTTP(epConf) if duration > 0 { durations = append(durations, duration) @@ -212,7 +212,7 @@ type endpointResult struct { successful int } -func benchmarkEndpointHTTP(epConfig httpEndpointConfig) time.Duration { +func benchmarkEndpointHTTP(epConfig *httpEndpointConfig) time.Duration { start := time.Now() resp, err := epConfig.client.Post(epConfig.url, "application/json", strings.NewReader("ping")) if err != nil { From 28df8389f4bc3bb7964f01ffa593d81f16cc483e Mon Sep 17 00:00:00 2001 From: Emi Gutekanst Date: Fri, 6 Dec 2024 07:28:46 -0700 Subject: [PATCH 448/647] gateway: benchmark: fix 'all websocket requests fail' case (#1131) * gateway: benchmark: fix authentication Signed-off-by: Stephen Gutekanst * gateway: benchmark: only connect to websocket once ready, add reconnect logic Signed-off-by: Stephen Gutekanst --------- Signed-off-by: Stephen Gutekanst --- cmd/src/gateway_benchmark.go | 148 +++++++++++++++++------------------ 1 file changed, 74 insertions(+), 74 deletions(-) diff --git a/cmd/src/gateway_benchmark.go b/cmd/src/gateway_benchmark.go index 93a6c952dc..fd11daff92 100644 --- a/cmd/src/gateway_benchmark.go +++ b/cmd/src/gateway_benchmark.go @@ -26,23 +26,6 @@ type Stats struct { Total time.Duration } -// httpEndpointConfig represents the configuration for an HTTP endpoint. -type httpEndpointConfig struct { - client *http.Client - url string -} - -// sgAuthTransport is an http.RoundTripper that adds an Authorization header to requests. -// It is used to add the Sourcegraph access token to requests to Sourcegraph endpoints. -type sgAuthTransport struct { - token string - base http.RoundTripper -} -func (t *sgAuthTransport) RoundTrip(req *http.Request) (*http.Response, error) { - req.Header.Add("Authorization", "token "+t.token) - return t.base.RoundTrip(req) -} - func init() { usage := ` 'src gateway benchmark' runs performance benchmarks against Cody Gateway endpoints. @@ -53,10 +36,10 @@ Usage: Examples: - $ src gateway benchmark - $ src gateway benchmark --requests 50 - $ src gateway benchmark --gateway http://localhost:9992 --sourcegraph http://localhost:3082 --sgp sgp_***** --requests 50 - $ src gateway benchmark --requests 50 --csv results.csv + $ src gateway benchmark --sgp + $ src gateway benchmark --requests 50 --sgp + $ src gateway benchmark --gateway http://localhost:9992 --sourcegraph http://localhost:3082 --sgp + $ src gateway benchmark --requests 50 --csv results.csv --sgp ` flagSet := flag.NewFlagSet("benchmark", flag.ExitOnError) @@ -66,7 +49,7 @@ Examples: csvOutput = flagSet.String("csv", "", "Export results to CSV file (provide filename)") gatewayEndpoint = flagSet.String("gateway", "https://cody-gateway.sourcegraph.com", "Cody Gateway endpoint") sgEndpoint = flagSet.String("sourcegraph", "https://sourcegraph.com", "Sourcegraph endpoint") - sgpToken = flagSet.String("sgp", "sgp_*****", "Sourcegraph personal access token for the called instance") + sgpToken = flagSet.String("sgp", "", "Sourcegraph personal access token for the called instance") ) handler := func(args []string) error { @@ -79,59 +62,30 @@ Examples: } var ( - gatewayWebsocket, sourcegraphWebsocket *websocket.Conn - err error - gatewayClient = &http.Client{} - sourcegraphClient = &http.Client{} - endpoints = map[string]any{} // Values: URL `string`s or `*websocket.Conn`s + httpClient = &http.Client{} + endpoints = map[string]any{} // Values: URL `string`s or `*webSocketClient`s ) - - // Connect to endpoints if *gatewayEndpoint != "" { fmt.Println("Benchmarking Cody Gateway instance:", *gatewayEndpoint) - wsURL := strings.Replace(fmt.Sprint(*gatewayEndpoint, "/v2/websocket"), "http", "ws", 1) - fmt.Println("Connecting to Cody Gateway via WebSocket..", wsURL) - gatewayWebsocket, _, err = websocket.DefaultDialer.Dial(wsURL, nil) - if err != nil { - return fmt.Errorf("WebSocket dial(%s): %v", wsURL, err) - } - fmt.Println("Connected!") - endpoints["ws(s): gateway"] = gatewayWebsocket - endpoints["http(s): gateway"] = &httpEndpointConfig{ - client: gatewayClient, - url: fmt.Sprint(*gatewayEndpoint, "/v2/http"), + endpoints["ws(s): gateway"] = &webSocketClient{ + conn: nil, + URL: strings.Replace(fmt.Sprint(*gatewayEndpoint, "/v2/websocket"), "http", "ws", 1), } + endpoints["http(s): gateway"] = fmt.Sprint(*gatewayEndpoint, "/v2/http") } else { fmt.Println("warning: not benchmarking Cody Gateway (-gateway endpoint not provided)") } if *sgEndpoint != "" { - // Add auth header to sourcegraphClient transport - if *sgpToken != "" { - sourcegraphClient.Transport = &sgAuthTransport{ - token: *sgpToken, - base: http.DefaultTransport, - } + if *sgpToken == "" { + return cmderrors.Usage("must specify --sgp ") } fmt.Println("Benchmarking Sourcegraph instance:", *sgEndpoint) - wsURL := strings.Replace(fmt.Sprint(*sgEndpoint, "/.api/gateway/websocket"), "http", "ws", 1) - header := http.Header{} - header.Add("Authorization", "token "+*sgpToken) - fmt.Println("Connecting to Sourcegraph instance via WebSocket..", wsURL) - sourcegraphWebsocket, _, err = websocket.DefaultDialer.Dial(wsURL, header) - if err != nil { - return fmt.Errorf("WebSocket dial(%s): %v", wsURL, err) - } - fmt.Println("Connected!") - - endpoints["ws(s): sourcegraph"] = sourcegraphWebsocket - endpoints["http(s): sourcegraph"] = &httpEndpointConfig{ - client: sourcegraphClient, - url: fmt.Sprint(*sgEndpoint, "/.api/gateway/http"), - } - endpoints["http(s): http-then-ws"] = &httpEndpointConfig{ - client: sourcegraphClient, - url: fmt.Sprint(*sgEndpoint, "/.api/gateway/http-then-websocket"), + endpoints["ws(s): sourcegraph"] = &webSocketClient{ + conn: nil, + URL: strings.Replace(fmt.Sprint(*sgEndpoint, "/.api/gateway/websocket"), "http", "ws", 1), } + endpoints["http(s): sourcegraph"] = fmt.Sprint(*sgEndpoint, "/.api/gateway/http") + endpoints["http(s): http-then-ws"] = fmt.Sprint(*sgEndpoint, "/.api/gateway/http-then-websocket") } else { fmt.Println("warning: not benchmarking Sourcegraph instance (-sourcegraph endpoint not provided)") } @@ -139,18 +93,18 @@ Examples: fmt.Printf("Starting benchmark with %d requests per endpoint...\n", *requestCount) var results []endpointResult - for name, clientOrEndpointConfig := range endpoints { + for name, clientOrURL := range endpoints { durations := make([]time.Duration, 0, *requestCount) fmt.Printf("\nTesting %s...", name) for i := 0; i < *requestCount; i++ { - if ws, ok := clientOrEndpointConfig.(*websocket.Conn); ok { + if ws, ok := clientOrURL.(*webSocketClient); ok { duration := benchmarkEndpointWebSocket(ws) if duration > 0 { durations = append(durations, duration) } - } else if epConf, ok := clientOrEndpointConfig.(*httpEndpointConfig); ok { - duration := benchmarkEndpointHTTP(epConf) + } else if url, ok := clientOrURL.(string); ok { + duration := benchmarkEndpointHTTP(httpClient, url, *sgpToken) if duration > 0 { durations = append(durations, duration) } @@ -200,6 +154,26 @@ Examples: }) } +type webSocketClient struct { + conn *websocket.Conn + URL string +} + +func (c *webSocketClient) reconnect() error { + if c.conn != nil { + c.conn.Close() // don't leak connections + } + fmt.Println("Connecting to WebSocket..", c.URL) + var err error + c.conn, _, err = websocket.DefaultDialer.Dial(c.URL, nil) + if err != nil { + c.conn = nil // retry again later + return fmt.Errorf("WebSocket dial(%s): %v", c.URL, err) + } + fmt.Println("Connected!") + return nil +} + type endpointResult struct { name string avg time.Duration @@ -212,11 +186,18 @@ type endpointResult struct { successful int } -func benchmarkEndpointHTTP(epConfig *httpEndpointConfig) time.Duration { +func benchmarkEndpointHTTP(client *http.Client, url, accessToken string) time.Duration { start := time.Now() - resp, err := epConfig.client.Post(epConfig.url, "application/json", strings.NewReader("ping")) + req, err := http.NewRequest("POST", url, strings.NewReader("ping")) + if err != nil { + fmt.Printf("Error creating request: %v\n", err) + return 0 + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Authorization", "token "+accessToken) + resp, err := client.Do(req) if err != nil { - fmt.Printf("Error calling %s: %v\n", epConfig.url, err) + fmt.Printf("Error calling %s: %v\n", url, err) return 0 } defer func() { @@ -242,20 +223,39 @@ func benchmarkEndpointHTTP(epConfig *httpEndpointConfig) time.Duration { return time.Since(start) } -func benchmarkEndpointWebSocket(conn *websocket.Conn) time.Duration { +func benchmarkEndpointWebSocket(client *webSocketClient) time.Duration { + // Perform initial websocket connection, if needed. + if client.conn == nil { + if err := client.reconnect(); err != nil { + fmt.Printf("Error reconnecting: %v\n", err) + return 0 + } + } + + // Perform the benchmarked request using the websocket. start := time.Now() - err := conn.WriteMessage(websocket.TextMessage, []byte("ping")) + err := client.conn.WriteMessage(websocket.TextMessage, []byte("ping")) if err != nil { fmt.Printf("WebSocket write error: %v\n", err) + if err := client.reconnect(); err != nil { + fmt.Printf("Error reconnecting: %v\n", err) + } return 0 } - _, message, err := conn.ReadMessage() + _, message, err := client.conn.ReadMessage() + if err != nil { fmt.Printf("WebSocket read error: %v\n", err) + if err := client.reconnect(); err != nil { + fmt.Printf("Error reconnecting: %v\n", err) + } return 0 } if string(message) != "pong" { fmt.Printf("Expected 'pong' response, got: %q\n", string(message)) + if err := client.reconnect(); err != nil { + fmt.Printf("Error reconnecting: %v\n", err) + } return 0 } return time.Since(start) From 20c534fc9f2c34dfcf02391be9d2836de29e03a7 Mon Sep 17 00:00:00 2001 From: Emi Gutekanst Date: Fri, 6 Dec 2024 08:23:22 -0700 Subject: [PATCH 449/647] gateway: benchmark: fix websocket auth (#1132) Signed-off-by: Stephen Gutekanst --- cmd/src/gateway_benchmark.go | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/cmd/src/gateway_benchmark.go b/cmd/src/gateway_benchmark.go index fd11daff92..e6cc679d14 100644 --- a/cmd/src/gateway_benchmark.go +++ b/cmd/src/gateway_benchmark.go @@ -83,6 +83,9 @@ Examples: endpoints["ws(s): sourcegraph"] = &webSocketClient{ conn: nil, URL: strings.Replace(fmt.Sprint(*sgEndpoint, "/.api/gateway/websocket"), "http", "ws", 1), + headers: http.Header{ + "Authorization": []string{"token " + *sgpToken}, + }, } endpoints["http(s): sourcegraph"] = fmt.Sprint(*sgEndpoint, "/.api/gateway/http") endpoints["http(s): http-then-ws"] = fmt.Sprint(*sgEndpoint, "/.api/gateway/http-then-websocket") @@ -155,8 +158,9 @@ Examples: } type webSocketClient struct { - conn *websocket.Conn - URL string + conn *websocket.Conn + URL string + headers http.Header } func (c *webSocketClient) reconnect() error { @@ -165,7 +169,7 @@ func (c *webSocketClient) reconnect() error { } fmt.Println("Connecting to WebSocket..", c.URL) var err error - c.conn, _, err = websocket.DefaultDialer.Dial(c.URL, nil) + c.conn, _, err = websocket.DefaultDialer.Dial(c.URL, c.headers) if err != nil { c.conn = nil // retry again later return fmt.Errorf("WebSocket dial(%s): %v", c.URL, err) From 4f198d08d056304ae5f20a692cca70c77c515fef Mon Sep 17 00:00:00 2001 From: Keegan Carruthers-Smith Date: Mon, 9 Dec 2024 13:42:32 +0200 Subject: [PATCH 450/647] gateway: benchmark has same alignment for header and rows (#1133) Minor formatting issue which caused the table to not be aligned. Test Plan: Ran the shared incantation with "--requests 1" and the table looked good. --- cmd/src/gateway_benchmark.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/src/gateway_benchmark.go b/cmd/src/gateway_benchmark.go index e6cc679d14..0c1c78570d 100644 --- a/cmd/src/gateway_benchmark.go +++ b/cmd/src/gateway_benchmark.go @@ -384,7 +384,7 @@ func printResults(results []endpointResult, requestCount *int) { // Print each row for _, r := range results { - fmt.Printf("%-20s | %-19s | %-19s | %-19s | %-19s | %-19s | %-19s | %-19s | %s\n", + fmt.Printf("%-25s | %-19s | %-19s | %-19s | %-19s | %-19s | %-19s | %-19s | %s\n", r.name, formatDuration(r.avg, r.avg == bestAvg, r.avg == worstAvg), formatDuration(r.median, r.median == bestMedian, r.median == worstMedian), From 20a3a02c6593d5061dba8ebf27568c76d4431e49 Mon Sep 17 00:00:00 2001 From: Warren Gifford Date: Mon, 9 Dec 2024 15:46:45 -0800 Subject: [PATCH 451/647] 5.10 changelong entry (#1134) --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index ea5ea301b0..3d318f0c4b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,10 @@ All notable changes to `src-cli` are documented in this file. ## Unreleased +## 5.10.0 +- cody gateway benchmark changes +- fix local builds for non sourcegraph team [1121](https://github.com/sourcegraph/src-cli/pull/1121) + ## 5.9.1 - Update SBOM output file extension from `.json` to `.cdx.json` [#1123](https://github.com/sourcegraph/src-cli/pull/1123) From 175628eb174eb3183d047bd166cbb6a3b1836b82 Mon Sep 17 00:00:00 2001 From: Marc <7050295+marcleblanc2@users.noreply.github.com> Date: Tue, 10 Dec 2024 05:14:41 -0700 Subject: [PATCH 452/647] fix: batches now respects skip-errors for version check (#1135) * fix: batches now respects skip-errors for version check Co-authored-by: Michael Bahr --- cmd/src/batch_common.go | 23 ++++++++++++++--------- cmd/src/batch_new.go | 18 ++++++++++++++---- cmd/src/batch_remote.go | 11 ++++++++--- cmd/src/batch_repositories.go | 16 +++++++++++++--- cmd/src/batch_validate.go | 18 ++++++++++++++---- internal/batches/features.go | 11 +++++++++-- internal/batches/service/service.go | 4 ++-- 7 files changed, 74 insertions(+), 27 deletions(-) diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index 57b248cf06..8171156675 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -5,6 +5,7 @@ import ( "flag" "fmt" "io" + cliLog "log" "os" "os/exec" "os/signal" @@ -48,6 +49,7 @@ type batchExecutionFlags struct { api *api.Flags clearCache bool namespace string + skipErrors bool } func newBatchExecutionFlags(flagSet *flag.FlagSet) *batchExecutionFlags { @@ -63,6 +65,10 @@ func newBatchExecutionFlags(flagSet *flag.FlagSet) *batchExecutionFlags { &bef.clearCache, "clear-cache", false, "If true, clears the execution cache and executes all steps anew.", ) + flagSet.BoolVar( + &bef.skipErrors, "skip-errors", false, + "If true, errors encountered won't stop the program, but only log them.", + ) flagSet.BoolVar( &bef.allowIgnored, "force-override-ignore", false, "Do not ignore repositories that have a .batchignore file.", @@ -146,11 +152,6 @@ func newBatchExecuteFlags(flagSet *flag.FlagSet, cacheDir, tempDir string) *batc "If true, deletes downloaded repository archives after executing batch spec steps. Note that only the archives related to the actual repositories matched by the batch spec will be cleaned up, and clean up will not occur if src exits unexpectedly.", ) - flagSet.BoolVar( - &caf.skipErrors, "skip-errors", false, - "If true, errors encountered while executing steps in a repository won't stop the execution of the batch spec but only cause that repository to be skipped.", - ) - flagSet.StringVar( &caf.workspace, "workspace", "auto", `Workspace mode to use ("auto", "bind", or "volume")`, @@ -290,7 +291,7 @@ func executeBatchSpec(ctx context.Context, opts executeBatchSpecOpts) (err error Client: opts.client, }) - lr, ffs, err := svc.DetermineLicenseAndFeatureFlags(ctx) + lr, ffs, err := svc.DetermineLicenseAndFeatureFlags(ctx, opts.flags.skipErrors) if err != nil { return err } @@ -302,8 +303,12 @@ func executeBatchSpec(ctx context.Context, opts executeBatchSpecOpts) (err error imageCache := docker.NewImageCache() - if err := validateSourcegraphVersionConstraint(ctx, ffs); err != nil { - return err + if err := validateSourcegraphVersionConstraint(ffs); err != nil { + if !opts.flags.skipErrors { + return err + } else { + cliLog.Printf("WARNING: %s", err) + } } if err := checkExecutable("git", "version"); err != nil { @@ -655,7 +660,7 @@ func getBatchParallelism(ctx context.Context, flag int) (int, error) { return docker.NCPU(ctx) } -func validateSourcegraphVersionConstraint(ctx context.Context, ffs *batches.FeatureFlags) error { +func validateSourcegraphVersionConstraint(ffs *batches.FeatureFlags) error { if ffs.Sourcegraph40 { return nil } diff --git a/cmd/src/batch_new.go b/cmd/src/batch_new.go index 349b590eff..2dc4b7a5e5 100644 --- a/cmd/src/batch_new.go +++ b/cmd/src/batch_new.go @@ -4,6 +4,7 @@ import ( "context" "flag" "fmt" + cliLog "log" "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/batches/service" @@ -30,7 +31,12 @@ Examples: apiFlags := api.NewFlags(flagSet) var ( - fileFlag = flagSet.String("f", "batch.yaml", "The name of the batch spec file to create.") + fileFlag = flagSet.String("f", "batch.yaml", "The name of the batch spec file to create.") + skipErrors bool + ) + flagSet.BoolVar( + &skipErrors, "skip-errors", false, + "If true, errors encountered won't stop the program, but only log them.", ) handler := func(args []string) error { @@ -48,13 +54,17 @@ Examples: Client: cfg.apiClient(apiFlags, flagSet.Output()), }) - _, ffs, err := svc.DetermineLicenseAndFeatureFlags(ctx) + _, ffs, err := svc.DetermineLicenseAndFeatureFlags(ctx, skipErrors) if err != nil { return err } - if err := validateSourcegraphVersionConstraint(ctx, ffs); err != nil { - return err + if err := validateSourcegraphVersionConstraint(ffs); err != nil { + if !skipErrors { + return err + } else { + cliLog.Printf("WARNING: %s", err) + } } if err := svc.GenerateExampleSpec(ctx, *fileFlag); err != nil { diff --git a/cmd/src/batch_remote.go b/cmd/src/batch_remote.go index 7817421ab3..7dd7628c03 100644 --- a/cmd/src/batch_remote.go +++ b/cmd/src/batch_remote.go @@ -4,6 +4,7 @@ import ( "context" "flag" "fmt" + cliLog "log" "strings" "time" @@ -52,13 +53,17 @@ Examples: Client: cfg.apiClient(flags.api, flagSet.Output()), }) - _, ffs, err := svc.DetermineLicenseAndFeatureFlags(ctx) + _, ffs, err := svc.DetermineLicenseAndFeatureFlags(ctx, flags.skipErrors) if err != nil { return err } - if err := validateSourcegraphVersionConstraint(ctx, ffs); err != nil { - return err + if err := validateSourcegraphVersionConstraint(ffs); err != nil { + if !flags.skipErrors { + return err + } else { + cliLog.Printf("WARNING: %s", err) + } } out := output.NewOutput(flagSet.Output(), output.OutputOpts{Verbose: *verbose}) diff --git a/cmd/src/batch_repositories.go b/cmd/src/batch_repositories.go index 092ae637d2..b02a4f5e58 100644 --- a/cmd/src/batch_repositories.go +++ b/cmd/src/batch_repositories.go @@ -4,6 +4,7 @@ import ( "context" "flag" "fmt" + cliLog "log" "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/sourcegraph/lib/output" @@ -42,6 +43,7 @@ Examples: var ( allowUnsupported bool allowIgnored bool + skipErrors bool ) flagSet.BoolVar( &allowUnsupported, "allow-unsupported", false, @@ -51,6 +53,10 @@ Examples: &allowIgnored, "force-override-ignore", false, "Do not ignore repositories that have a .batchignore file.", ) + flagSet.BoolVar( + &skipErrors, "skip-errors", false, + "If true, errors encountered won't stop the program, but only log them.", + ) handler := func(args []string) error { if err := flagSet.Parse(args); err != nil { @@ -69,13 +75,17 @@ Examples: Client: client, }) - _, ffs, err := svc.DetermineLicenseAndFeatureFlags(ctx) + _, ffs, err := svc.DetermineLicenseAndFeatureFlags(ctx, skipErrors) if err != nil { return err } - if err := validateSourcegraphVersionConstraint(ctx, ffs); err != nil { - return err + if err := validateSourcegraphVersionConstraint(ffs); err != nil { + if !skipErrors { + return err + } else { + cliLog.Printf("WARNING: %s", err) + } } out := output.NewOutput(flagSet.Output(), output.OutputOpts{Verbose: *verbose}) diff --git a/cmd/src/batch_validate.go b/cmd/src/batch_validate.go index e2c77c29bc..5f09caeebc 100644 --- a/cmd/src/batch_validate.go +++ b/cmd/src/batch_validate.go @@ -4,6 +4,7 @@ import ( "context" "flag" "fmt" + cliLog "log" "github.com/sourcegraph/sourcegraph/lib/output" @@ -36,6 +37,7 @@ Examples: var ( allowUnsupported bool allowIgnored bool + skipErrors bool ) flagSet.BoolVar( &allowUnsupported, "allow-unsupported", false, @@ -45,6 +47,10 @@ Examples: &allowIgnored, "force-override-ignore", false, "Do not ignore repositories that have a .batchignore file.", ) + flagSet.BoolVar( + &skipErrors, "skip-errors", false, + "If true, errors encountered won't stop the program, but only log them.", + ) handler := func(args []string) error { ctx := context.Background() @@ -63,14 +69,18 @@ Examples: Client: cfg.apiClient(apiFlags, flagSet.Output()), }) - _, ffs, err := svc.DetermineLicenseAndFeatureFlags(ctx) + _, ffs, err := svc.DetermineLicenseAndFeatureFlags(ctx, skipErrors) if err != nil { return err } - if err := validateSourcegraphVersionConstraint(ctx, ffs); err != nil { - ui.ExecutionError(err) - return err + if err := validateSourcegraphVersionConstraint(ffs); err != nil { + if !skipErrors { + ui.ExecutionError(err) + return err + } else { + cliLog.Printf("WARNING: %s", err) + } } file, err := getBatchSpecFile(flagSet, fileFlag) diff --git a/internal/batches/features.go b/internal/batches/features.go index ee319709b7..228775f66a 100644 --- a/internal/batches/features.go +++ b/internal/batches/features.go @@ -1,6 +1,9 @@ package batches import ( + "fmt" + "log" + "github.com/sourcegraph/sourcegraph/lib/api" "github.com/sourcegraph/sourcegraph/lib/errors" ) @@ -12,7 +15,7 @@ type FeatureFlags struct { BinaryDiffs bool } -func (ff *FeatureFlags) SetFromVersion(version string) error { +func (ff *FeatureFlags) SetFromVersion(version string, skipErrors bool) error { for _, feature := range []struct { flag *bool constraint string @@ -32,7 +35,11 @@ func (ff *FeatureFlags) SetFromVersion(version string) error { } { value, err := api.CheckSourcegraphVersion(version, feature.constraint, feature.minDate) if err != nil { - return errors.Wrap(err, "failed to check version returned by Sourcegraph") + if skipErrors { + log.Printf("failed to check version returned by Sourcegraph: %s. Assuming no feature flags.", version) + } else { + return errors.Wrap(err, fmt.Sprintf("failed to check version returned by Sourcegraph: %s", version)) + } } *feature.flag = value } diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index 8fb1116d1f..9c8339e3c3 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -76,7 +76,7 @@ func (svc *Service) getSourcegraphVersionAndMaxChangesetsCount(ctx context.Conte // DetermineLicenseAndFeatureFlags returns the enabled features and license restrictions // configured for the Sourcegraph instance. -func (svc *Service) DetermineLicenseAndFeatureFlags(ctx context.Context) (*batches.LicenseRestrictions, *batches.FeatureFlags, error) { +func (svc *Service) DetermineLicenseAndFeatureFlags(ctx context.Context, skipErrors bool) (*batches.LicenseRestrictions, *batches.FeatureFlags, error) { version, mc, err := svc.getSourcegraphVersionAndMaxChangesetsCount(ctx) if err != nil { return nil, nil, errors.Wrap(err, "failed to query Sourcegraph version and license info for instance") @@ -87,7 +87,7 @@ func (svc *Service) DetermineLicenseAndFeatureFlags(ctx context.Context) (*batch } ffs := &batches.FeatureFlags{} - return lr, ffs, ffs.SetFromVersion(version) + return lr, ffs, ffs.SetFromVersion(version, skipErrors) } From 2746a8bb6df391d54f0849221cc9d057b0f1dd44 Mon Sep 17 00:00:00 2001 From: Will Dollman Date: Tue, 17 Dec 2024 11:59:34 +0000 Subject: [PATCH 453/647] chore/security: Update x/crypto to latest version (#1139) * Update x/crypto to latest version * Bump changelog --- CHANGELOG.md | 4 ++++ go.mod | 12 ++++++------ go.sum | 20 ++++++++++---------- 3 files changed, 20 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3d318f0c4b..32823d2959 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,10 @@ All notable changes to `src-cli` are documented in this file. ## Unreleased +## 5.11.0 + +- Update x/crypto to fix reported CVE-2024-45337 + ## 5.10.0 - cody gateway benchmark changes - fix local builds for non sourcegraph team [1121](https://github.com/sourcegraph/src-cli/pull/1121) diff --git a/go.mod b/go.mod index aeb1de58a3..88dce5245d 100644 --- a/go.mod +++ b/go.mod @@ -19,6 +19,7 @@ require ( github.com/dustin/go-humanize v1.0.1 github.com/gobwas/glob v0.2.3 github.com/google/go-cmp v0.6.0 + github.com/gorilla/websocket v1.5.3 github.com/grafana/regexp v0.0.0-20221123153739-15dc172cd2db github.com/hexops/autogold v1.3.1 github.com/jedib0t/go-pretty/v6 v6.3.7 @@ -35,7 +36,7 @@ require ( github.com/sourcegraph/sourcegraph/lib v0.0.0-20240709083501-1af563b61442 github.com/stretchr/testify v1.8.4 golang.org/x/net v0.26.0 - golang.org/x/sync v0.7.0 + golang.org/x/sync v0.10.0 google.golang.org/api v0.132.0 google.golang.org/protobuf v1.33.0 gopkg.in/yaml.v3 v3.0.1 @@ -49,7 +50,6 @@ require ( require ( github.com/google/pprof v0.0.0-20230602150820-91b7bce49751 // indirect github.com/google/s2a-go v0.1.4 // indirect - github.com/gorilla/websocket v1.5.3 // indirect github.com/jackc/chunkreader/v2 v2.0.1 // indirect github.com/jackc/pgconn v1.14.3 // indirect github.com/jackc/pgio v1.0.0 // indirect @@ -172,12 +172,12 @@ require ( go.uber.org/atomic v1.11.0 // indirect go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.24.0 // indirect - golang.org/x/crypto v0.24.0 // indirect + golang.org/x/crypto v0.31.0 // indirect golang.org/x/mod v0.17.0 // indirect golang.org/x/oauth2 v0.11.0 // indirect - golang.org/x/sys v0.21.0 // indirect - golang.org/x/term v0.21.0 // indirect - golang.org/x/text v0.16.0 // indirect + golang.org/x/sys v0.28.0 // indirect + golang.org/x/term v0.27.0 // indirect + golang.org/x/text v0.21.0 // indirect golang.org/x/time v0.3.0 // indirect golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d // indirect golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 // indirect diff --git a/go.sum b/go.sum index 8dcd3114dd..76618aa376 100644 --- a/go.sum +++ b/go.sum @@ -447,8 +447,8 @@ golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8U golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20220314234659-1baeb1ce4c0b/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= -golang.org/x/crypto v0.24.0 h1:mnl8DM0o513X8fdIkmyFE/5hTYxbwYOjDS/+rK6qpRI= -golang.org/x/crypto v0.24.0/go.mod h1:Z1PMYSOR5nyMcyAVAIQSKCDwalqy85Aqn1x3Ws4L5DM= +golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U= +golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= @@ -493,8 +493,8 @@ golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220819030929-7fc1605a5dde/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M= -golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ= +golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -516,13 +516,13 @@ golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220829200755-d48e67d00261/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.21.0 h1:rF+pYz3DAGSQAxAu1CbC7catZg4ebC4UIeIhKxBZvws= -golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA= +golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.3.0/go.mod h1:q750SLmJuPmVoN1blW3UFBPREJfb1KmY3vwxfr+nFDA= -golang.org/x/term v0.21.0 h1:WVXCp+/EBEHOj53Rvu+7KiT/iElMrO8ACK16SMZ3jaA= -golang.org/x/term v0.21.0/go.mod h1:ooXLefLobQVslOqselCNF4SxFAaoS6KujMbsGzSDmX0= +golang.org/x/term v0.27.0 h1:WP60Sv1nlK1T6SupCHbXzSaN0b9wUmsPoRS9b61A23Q= +golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= @@ -530,8 +530,8 @@ golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4= -golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI= +golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo= +golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ= golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4= golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= From 5812ab7358527351aac17a12b74cb34726da2dc5 Mon Sep 17 00:00:00 2001 From: Will Dollman Date: Thu, 19 Dec 2024 10:04:32 +0000 Subject: [PATCH 454/647] chore/security: Update x/net to latest version (#1140) * Upgrade x/net to latest --- CHANGELOG.md | 4 ++++ go.mod | 2 +- go.sum | 2 ++ 3 files changed, 7 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 32823d2959..bdb93bd5b1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,10 @@ All notable changes to `src-cli` are documented in this file. ## Unreleased +## 5.11.1 + +- Update x/net to fix CVE-2024-45338 + ## 5.11.0 - Update x/crypto to fix reported CVE-2024-45337 diff --git a/go.mod b/go.mod index 88dce5245d..b43384406e 100644 --- a/go.mod +++ b/go.mod @@ -35,7 +35,7 @@ require ( github.com/sourcegraph/scip v0.3.1-0.20230627154934-45df7f6d33fc github.com/sourcegraph/sourcegraph/lib v0.0.0-20240709083501-1af563b61442 github.com/stretchr/testify v1.8.4 - golang.org/x/net v0.26.0 + golang.org/x/net v0.33.0 golang.org/x/sync v0.10.0 google.golang.org/api v0.132.0 google.golang.org/protobuf v1.33.0 diff --git a/go.sum b/go.sum index 76618aa376..7e918c201e 100644 --- a/go.sum +++ b/go.sum @@ -479,6 +479,8 @@ golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug golang.org/x/net v0.3.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE= golang.org/x/net v0.26.0 h1:soB7SVo0PWrY4vPW/+ay0jKDNScG2X9wFeYlXIvJsOQ= golang.org/x/net v0.26.0/go.mod h1:5YKkiSynbBIh3p6iOc/vibscux0x38BZDkn8sCUPxHE= +golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I= +golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.11.0 h1:vPL4xzxBM4niKCW6g9whtaWVXTJf1U5e4aZxxFx/gbU= From b2e0f1d18e5be9d16354e9ff010abdce9710a090 Mon Sep 17 00:00:00 2001 From: David Veszelovszki Date: Fri, 20 Dec 2024 12:35:39 +0100 Subject: [PATCH 455/647] Add "gateway benchmark-stream"(PRIME-655) (#1138) * Add gateway benchmark-stream endpoint to let us benchmark real completion endpoints on CG and SG instances * Add `--use-special-header` and optional request CSV output to the "benchmark gateway" command --- cmd/src/gateway.go | 1 + cmd/src/gateway_benchmark.go | 164 ++++++++++++---- cmd/src/gateway_benchmark_stream.go | 283 ++++++++++++++++++++++++++++ 3 files changed, 407 insertions(+), 41 deletions(-) create mode 100644 cmd/src/gateway_benchmark_stream.go diff --git a/cmd/src/gateway.go b/cmd/src/gateway.go index c84340df48..0540d694e3 100644 --- a/cmd/src/gateway.go +++ b/cmd/src/gateway.go @@ -17,6 +17,7 @@ Usage: The commands are: benchmark runs benchmarks against Cody Gateway + benchmark-stream runs benchmarks against Cody Gateway code completion streaming endpoints Use "src gateway [command] -h" for more information about a command. diff --git a/cmd/src/gateway_benchmark.go b/cmd/src/gateway_benchmark.go index 0c1c78570d..2988dfb9db 100644 --- a/cmd/src/gateway_benchmark.go +++ b/cmd/src/gateway_benchmark.go @@ -26,9 +26,14 @@ type Stats struct { Total time.Duration } +type requestResult struct { + duration time.Duration + traceID string // X-Trace header value +} + func init() { usage := ` -'src gateway benchmark' runs performance benchmarks against Cody Gateway endpoints. +'src gateway benchmark' runs performance benchmarks against Cody Gateway and Sourcegraph test endpoints. Usage: @@ -39,17 +44,20 @@ Examples: $ src gateway benchmark --sgp $ src gateway benchmark --requests 50 --sgp $ src gateway benchmark --gateway http://localhost:9992 --sourcegraph http://localhost:3082 --sgp - $ src gateway benchmark --requests 50 --csv results.csv --sgp + $ src gateway benchmark --requests 50 --csv results.csv --request-csv requests.csv --sgp + $ src gateway benchmark --gateway https://cody-gateway.sourcegraph.com --sourcegraph https://sourcegraph.com --sgp --use-special-header ` flagSet := flag.NewFlagSet("benchmark", flag.ExitOnError) var ( - requestCount = flagSet.Int("requests", 1000, "Number of requests to make per endpoint") - csvOutput = flagSet.String("csv", "", "Export results to CSV file (provide filename)") - gatewayEndpoint = flagSet.String("gateway", "https://cody-gateway.sourcegraph.com", "Cody Gateway endpoint") - sgEndpoint = flagSet.String("sourcegraph", "https://sourcegraph.com", "Sourcegraph endpoint") - sgpToken = flagSet.String("sgp", "", "Sourcegraph personal access token for the called instance") + requestCount = flagSet.Int("requests", 1000, "Number of requests to make per endpoint") + csvOutput = flagSet.String("csv", "", "Export results to CSV file (provide filename)") + requestLevelCsvOutput = flagSet.String("request-csv", "", "Export request results to CSV file (provide filename)") + gatewayEndpoint = flagSet.String("gateway", "", "Cody Gateway endpoint") + sgEndpoint = flagSet.String("sourcegraph", "", "Sourcegraph endpoint") + sgpToken = flagSet.String("sgp", "", "Sourcegraph personal access token for the called instance") + useSpecialHeader = flagSet.Bool("use-special-header", false, "Use special header to test the gateway") ) handler := func(args []string) error { @@ -61,15 +69,23 @@ Examples: return cmderrors.Usage("additional arguments not allowed") } + if *useSpecialHeader { + fmt.Println("Using special header 'cody-core-gc-test'") + } + var ( httpClient = &http.Client{} endpoints = map[string]any{} // Values: URL `string`s or `*webSocketClient`s ) if *gatewayEndpoint != "" { fmt.Println("Benchmarking Cody Gateway instance:", *gatewayEndpoint) + headers := http.Header{ + "X-Sourcegraph-Should-Trace": []string{"true"}, + } endpoints["ws(s): gateway"] = &webSocketClient{ - conn: nil, - URL: strings.Replace(fmt.Sprint(*gatewayEndpoint, "/v2/websocket"), "http", "ws", 1), + conn: nil, + URL: strings.Replace(fmt.Sprint(*gatewayEndpoint, "/v2/websocket"), "http", "ws", 1), + reqHeaders: headers, } endpoints["http(s): gateway"] = fmt.Sprint(*gatewayEndpoint, "/v2/http") } else { @@ -80,12 +96,18 @@ Examples: return cmderrors.Usage("must specify --sgp ") } fmt.Println("Benchmarking Sourcegraph instance:", *sgEndpoint) + headers := http.Header{ + "Authorization": []string{"token " + *sgpToken}, + "X-Sourcegraph-Should-Trace": []string{"true"}, + } + if *useSpecialHeader { + headers.Set("cody-core-gc-test", "M2R{+6VI?1,M3n&") + } + endpoints["ws(s): sourcegraph"] = &webSocketClient{ - conn: nil, - URL: strings.Replace(fmt.Sprint(*sgEndpoint, "/.api/gateway/websocket"), "http", "ws", 1), - headers: http.Header{ - "Authorization": []string{"token " + *sgpToken}, - }, + conn: nil, + URL: strings.Replace(fmt.Sprint(*sgEndpoint, "/.api/gateway/websocket"), "http", "ws", 1), + reqHeaders: headers, } endpoints["http(s): sourcegraph"] = fmt.Sprint(*sgEndpoint, "/.api/gateway/http") endpoints["http(s): http-then-ws"] = fmt.Sprint(*sgEndpoint, "/.api/gateway/http-then-websocket") @@ -95,21 +117,25 @@ Examples: fmt.Printf("Starting benchmark with %d requests per endpoint...\n", *requestCount) - var results []endpointResult + var eResults []endpointResult + rResults := map[string][]requestResult{} for name, clientOrURL := range endpoints { durations := make([]time.Duration, 0, *requestCount) + rResults[name] = make([]requestResult, 0, *requestCount) fmt.Printf("\nTesting %s...", name) for i := 0; i < *requestCount; i++ { if ws, ok := clientOrURL.(*webSocketClient); ok { - duration := benchmarkEndpointWebSocket(ws) - if duration > 0 { - durations = append(durations, duration) + result := benchmarkEndpointWebSocket(ws) + if result.duration > 0 { + durations = append(durations, result.duration) + rResults[name] = append(rResults[name], result) } } else if url, ok := clientOrURL.(string); ok { - duration := benchmarkEndpointHTTP(httpClient, url, *sgpToken) - if duration > 0 { - durations = append(durations, duration) + result := benchmarkEndpointHTTP(httpClient, url, *sgpToken, *useSpecialHeader) + if result.duration > 0 { + durations = append(durations, result.duration) + rResults[name] = append(rResults[name], result) } } } @@ -117,7 +143,7 @@ Examples: stats := calculateStats(durations) - results = append(results, endpointResult{ + eResults = append(eResults, endpointResult{ name: name, avg: stats.Avg, median: stats.Median, @@ -130,14 +156,20 @@ Examples: }) } - printResults(results, requestCount) + printResults(eResults, requestCount) if *csvOutput != "" { - if err := writeResultsToCSV(*csvOutput, results, requestCount); err != nil { + if err := writeResultsToCSV(*csvOutput, eResults, requestCount); err != nil { return fmt.Errorf("failed to export CSV: %v", err) } fmt.Printf("\nResults exported to %s\n", *csvOutput) } + if *requestLevelCsvOutput != "" { + if err := writeRequestResultsToCSV(*requestLevelCsvOutput, rResults); err != nil { + return fmt.Errorf("failed to export request-level CSV: %v", err) + } + fmt.Printf("\nRequest-level results exported to %s\n", *requestLevelCsvOutput) + } return nil } @@ -158,9 +190,10 @@ Examples: } type webSocketClient struct { - conn *websocket.Conn - URL string - headers http.Header + conn *websocket.Conn + URL string + reqHeaders http.Header + respHeaders http.Header } func (c *webSocketClient) reconnect() error { @@ -169,11 +202,13 @@ func (c *webSocketClient) reconnect() error { } fmt.Println("Connecting to WebSocket..", c.URL) var err error - c.conn, _, err = websocket.DefaultDialer.Dial(c.URL, c.headers) + var resp *http.Response + c.conn, resp, err = websocket.DefaultDialer.Dial(c.URL, c.reqHeaders) if err != nil { c.conn = nil // retry again later return fmt.Errorf("WebSocket dial(%s): %v", c.URL, err) } + c.respHeaders = resp.Header fmt.Println("Connected!") return nil } @@ -190,19 +225,23 @@ type endpointResult struct { successful int } -func benchmarkEndpointHTTP(client *http.Client, url, accessToken string) time.Duration { +func benchmarkEndpointHTTP(client *http.Client, url, accessToken string, useSpecialHeader bool) requestResult { start := time.Now() req, err := http.NewRequest("POST", url, strings.NewReader("ping")) if err != nil { fmt.Printf("Error creating request: %v\n", err) - return 0 + return requestResult{} } req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", "token "+accessToken) + req.Header.Set("X-Sourcegraph-Should-Trace", "true") + if useSpecialHeader { + req.Header.Set("cody-core-gc-test", "M2R{+6VI?1,M3n&") + } resp, err := client.Do(req) if err != nil { fmt.Printf("Error calling %s: %v\n", url, err) - return 0 + return requestResult{} } defer func() { err := resp.Body.Close() @@ -212,27 +251,30 @@ func benchmarkEndpointHTTP(client *http.Client, url, accessToken string) time.Du }() if resp.StatusCode != http.StatusOK { fmt.Printf("non-200 response: %v\n", resp.Status) - return 0 + return requestResult{} } body, err := io.ReadAll(resp.Body) if err != nil { fmt.Printf("Error reading response body: %v\n", err) - return 0 + return requestResult{} } if string(body) != "pong" { fmt.Printf("Expected 'pong' response, got: %q\n", string(body)) - return 0 + return requestResult{} } - return time.Since(start) + return requestResult{ + duration: time.Since(start), + traceID: resp.Header.Get("X-Trace"), + } } -func benchmarkEndpointWebSocket(client *webSocketClient) time.Duration { +func benchmarkEndpointWebSocket(client *webSocketClient) requestResult { // Perform initial websocket connection, if needed. if client.conn == nil { if err := client.reconnect(); err != nil { fmt.Printf("Error reconnecting: %v\n", err) - return 0 + return requestResult{} } } @@ -244,7 +286,7 @@ func benchmarkEndpointWebSocket(client *webSocketClient) time.Duration { if err := client.reconnect(); err != nil { fmt.Printf("Error reconnecting: %v\n", err) } - return 0 + return requestResult{} } _, message, err := client.conn.ReadMessage() @@ -253,16 +295,19 @@ func benchmarkEndpointWebSocket(client *webSocketClient) time.Duration { if err := client.reconnect(); err != nil { fmt.Printf("Error reconnecting: %v\n", err) } - return 0 + return requestResult{} } if string(message) != "pong" { fmt.Printf("Expected 'pong' response, got: %q\n", string(message)) if err := client.reconnect(); err != nil { fmt.Printf("Error reconnecting: %v\n", err) } - return 0 + return requestResult{} + } + return requestResult{ + duration: time.Since(start), + traceID: client.respHeaders.Get("Content-Type"), } - return time.Since(start) } func calculateStats(durations []time.Duration) Stats { @@ -438,3 +483,40 @@ func writeResultsToCSV(filename string, results []endpointResult, requestCount * return nil } + +func writeRequestResultsToCSV(filename string, results map[string][]requestResult) error { + file, err := os.Create(filename) + if err != nil { + return fmt.Errorf("failed to create CSV file: %v", err) + } + defer func() { + err := file.Close() + if err != nil { + return + } + }() + + writer := csv.NewWriter(file) + defer writer.Flush() + + // Write header + header := []string{"Endpoint", "Duration (ms)", "Trace ID"} + if err := writer.Write(header); err != nil { + return fmt.Errorf("failed to write CSV header: %v", err) + } + + for endpoint, requestResults := range results { + for _, result := range requestResults { + row := []string{ + endpoint, + fmt.Sprintf("%.2f", float64(result.duration.Microseconds())/1000), + result.traceID, + } + if err := writer.Write(row); err != nil { + return fmt.Errorf("failed to write CSV row: %v", err) + } + } + } + + return nil +} diff --git a/cmd/src/gateway_benchmark_stream.go b/cmd/src/gateway_benchmark_stream.go new file mode 100644 index 0000000000..66154a5c8b --- /dev/null +++ b/cmd/src/gateway_benchmark_stream.go @@ -0,0 +1,283 @@ +package main + +import ( + "flag" + "fmt" + "io" + "net/http" + "strings" + "time" + + "github.com/sourcegraph/src-cli/internal/cmderrors" +) + +type httpEndpoint struct { + url string + authHeader string + body string +} + +func init() { + usage := ` +'src gateway benchmark-stream' runs performance benchmarks against Cody Gateway and Sourcegraph +code completion streaming endpoints. + +Usage: + + src gateway benchmark-stream [flags] + +Examples: + + $ src gateway benchmark-stream --requests 50 --csv results.csv --sgd --sgp + $ src gateway benchmark-stream --gateway http://localhost:9992 --sourcegraph http://localhost:3082 --sgd --sgp + $ src gateway benchmark-stream --requests 250 --gateway http://localhost:9992 --sourcegraph http://localhost:3082 --sgd --sgp --max-tokens 50 --provider fireworks --stream +` + + flagSet := flag.NewFlagSet("benchmark-stream", flag.ExitOnError) + + var ( + requestCount = flagSet.Int("requests", 1000, "Number of requests to make per endpoint") + csvOutput = flagSet.String("csv", "", "Export results to CSV file (provide filename)") + requestLevelCsvOutput = flagSet.String("request-csv", "", "Export request results to CSV file (provide filename)") + gatewayEndpoint = flagSet.String("gateway", "", "Cody Gateway endpoint") + sgEndpoint = flagSet.String("sourcegraph", "", "Sourcegraph endpoint") + sgdToken = flagSet.String("sgd", "", "Sourcegraph Dotcom user key for Cody Gateway") + sgpToken = flagSet.String("sgp", "", "Sourcegraph personal access token for the called instance") + maxTokens = flagSet.Int("max-tokens", 256, "Maximum number of tokens to generate") + provider = flagSet.String("provider", "anthropic", "Provider to use for completion. Supported values: 'anthropic', 'fireworks'") + stream = flagSet.Bool("stream", false, "Whether to stream completions. Default: false") + ) + + handler := func(args []string) error { + // Parse the flags. + if err := flagSet.Parse(args); err != nil { + return err + } + if len(flagSet.Args()) != 0 { + return cmderrors.Usage("additional arguments not allowed") + } + if *gatewayEndpoint != "" && *sgdToken == "" { + return cmderrors.Usage("must specify --sgp ") + } + if *sgEndpoint != "" && *sgpToken == "" { + return cmderrors.Usage("must specify --sgp ") + } + + var httpClient = &http.Client{} + var cgResult, sgResult endpointResult + var cgRequestResults, sgRequestResults []requestResult + + // Do the benchmarking. + fmt.Printf("Starting benchmark with %d requests per endpoint...\n", *requestCount) + if *gatewayEndpoint != "" { + fmt.Println("Benchmarking Cody Gateway instance:", *gatewayEndpoint) + endpoint := buildGatewayHttpEndpoint(*gatewayEndpoint, *sgdToken, *maxTokens, *provider, *stream) + cgResult, cgRequestResults = benchmarkCodeCompletions("gateway", httpClient, endpoint, *requestCount) + fmt.Println() + } else { + fmt.Println("warning: not benchmarking Cody Gateway (-gateway endpoint not provided)") + } + if *sgEndpoint != "" { + fmt.Println("Benchmarking Sourcegraph instance:", *sgEndpoint) + endpoint := buildSourcegraphHttpEndpoint(*sgEndpoint, *sgpToken, *maxTokens, *provider, *stream) + sgResult, sgRequestResults = benchmarkCodeCompletions("sourcegraph", httpClient, endpoint, *requestCount) + fmt.Println() + } else { + fmt.Println("warning: not benchmarking Sourcegraph instance (-sourcegraph endpoint not provided)") + } + + // Output the results. + endpointResults := []endpointResult{cgResult, sgResult} + printResults(endpointResults, requestCount) + if *csvOutput != "" { + if err := writeResultsToCSV(*csvOutput, endpointResults, requestCount); err != nil { + return fmt.Errorf("failed to export CSV: %v", err) + } + fmt.Printf("\nAggregate results exported to %s\n", *csvOutput) + } + if *requestLevelCsvOutput != "" { + if err := writeRequestResultsToCSV(*requestLevelCsvOutput, map[string][]requestResult{"gateway": cgRequestResults, "sourcegraph": sgRequestResults}); err != nil { + return fmt.Errorf("failed to export CSV: %v", err) + } + fmt.Printf("\nRequest-level results exported to %s\n", *requestLevelCsvOutput) + } + + return nil + } + gatewayCommands = append(gatewayCommands, &command{ + flagSet: flagSet, + aliases: []string{}, + handler: handler, + usageFunc: func() { + _, err := fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src gateway %s':\n", flagSet.Name()) + if err != nil { + return + } + flagSet.PrintDefaults() + fmt.Println(usage) + }, + }) +} + +func buildGatewayHttpEndpoint(gatewayEndpoint string, sgdToken string, maxTokens int, provider string, stream bool) httpEndpoint { + s := "true" + if !stream { + s = "false" + } + if provider == "anthropic" { + return httpEndpoint{ + url: fmt.Sprint(gatewayEndpoint, "/v1/completions/anthropic-messages"), + authHeader: fmt.Sprintf("Bearer %s", sgdToken), + body: fmt.Sprintf(`{ + "model": "claude-3-haiku-20240307", + "messages": [ + {"role": "user", "content": "def bubble_sort(arr):"}, + {"role": "assistant", "content": "Here is a bubble sort:"} + ], + "max_tokens": %d, + "temperature": 0.0, + "stream": %s +}`, maxTokens, s), + } + } else if provider == "fireworks" { + return httpEndpoint{ + url: fmt.Sprint(gatewayEndpoint, "/v1/completions/fireworks"), + authHeader: fmt.Sprintf("Bearer %s", sgdToken), + body: fmt.Sprintf(`{ + "model": "starcoder", + "prompt": "#hello.ts<|fim▁begin|>const sayHello = () => <|fim▁hole|><|fim▁end|>", + "max_tokens": %d, + "stop": [ + "\n\n", + "\n\r\n", + "<|fim▁begin|>", + "<|fim▁hole|>", + "<|fim▁end|>, <|eos_token|>" + ], + "temperature": 0.2, + "topK": 0, + "topP": 0, + "stream": %s +}`, maxTokens, s), + } + } + + return httpEndpoint{} +} + +func buildSourcegraphHttpEndpoint(sgEndpoint string, sgpToken string, maxTokens int, provider string, stream bool) httpEndpoint { + s := "true" + if !stream { + s = "false" + } + if provider == "anthropic" { + return httpEndpoint{ + url: fmt.Sprint(sgEndpoint, "/.api/completions/stream"), + authHeader: fmt.Sprintf("token %s", sgpToken), + body: fmt.Sprintf(`{ + "model": "anthropic::2023-06-01::claude-3-haiku", + "messages": [ + {"speaker": "human", "text": "def bubble_sort(arr):"}, + {"speaker": "assistant", "text": "Here is a bubble sort:"} + ], + "maxTokensToSample": %d, + "temperature": 0.0, + "stream": %s +}`, maxTokens, s), + } + } else if provider == "fireworks" { + return httpEndpoint{ + url: fmt.Sprint(sgEndpoint, "/.api/completions/code"), + authHeader: fmt.Sprintf("token %s", sgpToken), + body: fmt.Sprintf(`{ + "model": "fireworks::v1::starcoder", + "messages": [ + {"speaker": "human", "text": "#hello.ts<|fim▁begin|>const sayHello = () => <|fim▁hole|><|fim▁end|>"} + ], + "maxTokensToSample": %d, + "stopSequences": [ + "\n\n", + "\n\r\n", + "<|fim▁begin|>", + "<|fim▁hole|>", + "<|fim▁end|>, <|eos_token|>" + ], + "temperature": 0.2, + "topK": 0, + "topP": 0, + "stream": %s +}`, maxTokens, s), + } + } + + return httpEndpoint{} +} + +func benchmarkCodeCompletions(benchmarkName string, client *http.Client, endpoint httpEndpoint, requestCount int) (endpointResult, []requestResult) { + results := make([]requestResult, 0, requestCount) + durations := make([]time.Duration, 0, requestCount) + + for i := 0; i < requestCount; i++ { + result := benchmarkCodeCompletion(client, endpoint) + if result.duration > 0 { + results = append(results, result) + durations = append(durations, result.duration) + } + } + stats := calculateStats(durations) + + return toEndpointResult(benchmarkName, stats, len(durations)), results +} + +func benchmarkCodeCompletion(client *http.Client, endpoint httpEndpoint) requestResult { + start := time.Now() + req, err := http.NewRequest("POST", endpoint.url, strings.NewReader(endpoint.body)) + if err != nil { + fmt.Printf("Error creating request: %v\n", err) + return requestResult{0, ""} + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Authorization", endpoint.authHeader) + req.Header.Set("X-Sourcegraph-Should-Trace", "true") + req.Header.Set("X-Sourcegraph-Feature", "code_completions") + resp, err := client.Do(req) + if err != nil { + fmt.Printf("Error calling %s: %v\n", endpoint.url, err) + return requestResult{0, ""} + } + defer func() { + err := resp.Body.Close() + if err != nil { + fmt.Printf("Error closing response body: %v\n", err) + } + }() + if resp.StatusCode != http.StatusOK { + body, _ := io.ReadAll(resp.Body) + fmt.Printf("non-200 response: %v - %s\n", resp.Status, body) + return requestResult{0, ""} + } + _, err = io.ReadAll(resp.Body) + if err != nil { + fmt.Printf("Error reading response body: %v\n", err) + return requestResult{0, ""} + } + + return requestResult{ + duration: time.Since(start), + traceID: resp.Header.Get("X-Trace"), + } +} + +func toEndpointResult(name string, stats Stats, requestCount int) endpointResult { + return endpointResult{ + name: name, + avg: stats.Avg, + median: stats.Median, + p5: stats.P5, + p75: stats.P75, + p80: stats.P80, + p95: stats.P95, + successful: requestCount, + total: stats.Total, + } +} From 436da916751ad5b785537a235c06fa317373969e Mon Sep 17 00:00:00 2001 From: Will Dollman Date: Fri, 31 Jan 2025 17:18:49 +0000 Subject: [PATCH 456/647] feature/security: Implement image signature verification (#1143) --- CHANGELOG.md | 4 + cmd/src/sbom.go | 2 +- cmd/src/sbom_fetch.go | 81 ++------------- cmd/src/sbom_utils.go | 70 +++++++++++++ cmd/src/signature.go | 36 +++++++ cmd/src/signature_fetch.go | 202 +++++++++++++++++++++++++++++++++++++ 6 files changed, 320 insertions(+), 75 deletions(-) create mode 100644 cmd/src/signature.go create mode 100644 cmd/src/signature_fetch.go diff --git a/CHANGELOG.md b/CHANGELOG.md index bdb93bd5b1..d9b345603c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,10 @@ All notable changes to `src-cli` are documented in this file. ## Unreleased +## 6.0.1 + +- Container signature verification support: Container signatures can now be verified for Sourcegraph releases after 5.11.4013 using `src signature verify -v ` [#1143](https://github.com/sourcegraph/src-cli/pull/1143) + ## 5.11.1 - Update x/net to fix CVE-2024-45338 diff --git a/cmd/src/sbom.go b/cmd/src/sbom.go index 5002aa6e9b..ff1a0a5c33 100644 --- a/cmd/src/sbom.go +++ b/cmd/src/sbom.go @@ -8,7 +8,7 @@ import ( var sbomCommands commander func init() { - usage := `'src sbom' fetches and verified SBOM (Software Bill of Materials) data for Sourcegraph containers. + usage := `'src sbom' fetches and verifies SBOM (Software Bill of Materials) data for Sourcegraph containers. Usage: diff --git a/cmd/src/sbom_fetch.go b/cmd/src/sbom_fetch.go index 4f82e3f222..d6fa90f79a 100644 --- a/cmd/src/sbom_fetch.go +++ b/cmd/src/sbom_fetch.go @@ -1,37 +1,23 @@ package main import ( - "bufio" "bytes" "encoding/base64" "encoding/json" "flag" "fmt" - "net/http" "os" "os/exec" "path/filepath" "strings" "unicode" - "github.com/grafana/regexp" - "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/sourcegraph/lib/output" "github.com/sourcegraph/src-cli/internal/cmderrors" ) -type sbomConfig struct { - publicKey string - outputDir string - version string - internalRelease bool - insecureIgnoreTransparencyLog bool -} - -const publicKey = "https://storage.googleapis.com/sourcegraph-release-sboms/keys/cosign_keyring-cosign-1.pub" -const imageListBaseURL = "https://storage.googleapis.com/sourcegraph-release-sboms" -const imageListFilename = "release-image-list.txt" +const sbomPublicKey = "https://storage.googleapis.com/sourcegraph-release-sboms/keys/cosign_keyring-cosign-1.pub" func init() { usage := ` @@ -55,8 +41,8 @@ Examples: insecureIgnoreTransparencyLogFlag := flagSet.Bool("insecure-ignore-tlog", false, "Disable transparency log verification. Defaults to false.") handler := func(args []string) error { - c := sbomConfig{ - publicKey: publicKey, + c := cosignConfig{ + publicKey: sbomPublicKey, } if err := flagSet.Parse(args); err != nil { @@ -155,7 +141,7 @@ Examples: }) } -func (c sbomConfig) getSBOMForImageVersion(image string, version string) (string, error) { +func (c cosignConfig) getSBOMForImageVersion(image string, version string) (string, error) { hash, err := getImageDigest(image, version) if err != nil { return "", err @@ -169,51 +155,7 @@ func (c sbomConfig) getSBOMForImageVersion(image string, version string) (string return sbom, nil } -func verifyCosign() error { - _, err := exec.LookPath("cosign") - if err != nil { - return errors.New("SBOM verification requires 'cosign' to be installed and available in $PATH. See https://docs.sigstore.dev/cosign/system_config/installation/") - } - return nil -} - -func (c sbomConfig) getImageList() ([]string, error) { - imageReleaseListURL := c.getImageReleaseListURL() - - resp, err := http.Get(imageReleaseListURL) - if err != nil { - return nil, fmt.Errorf("failed to fetch image list: %w", err) - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - // Compare version number against a regex that matches versions up to and including 5.8.0 - versionRegex := regexp.MustCompile(`^v?[0-5]\.([0-7]\.[0-9]+|8\.0)$`) - if versionRegex.MatchString(c.version) { - return nil, fmt.Errorf("unsupported version %s: SBOMs are only available for Sourcegraph releases after 5.8.0", c.version) - } - return nil, fmt.Errorf("failed to fetch list of images - check that %s is a valid Sourcegraph release: HTTP status %d", c.version, resp.StatusCode) - } - - scanner := bufio.NewScanner(resp.Body) - var images []string - for scanner.Scan() { - image := strings.TrimSpace(scanner.Text()) - if image != "" { - // Strip off a version suffix if present - parts := strings.SplitN(image, ":", 2) - images = append(images, parts[0]) - } - } - - if err := scanner.Err(); err != nil { - return nil, fmt.Errorf("error reading image list: %w", err) - } - - return images, nil -} - -func (c sbomConfig) getSBOMForImageHash(image string, hash string) (string, error) { +func (c cosignConfig) getSBOMForImageHash(image string, hash string) (string, error) { tempDir, err := os.MkdirTemp("", "sbom-") if err != nil { return "", fmt.Errorf("failed to create temporary directory: %w", err) @@ -224,7 +166,7 @@ func (c sbomConfig) getSBOMForImageHash(image string, hash string) (string, erro cosignArgs := []string{ "verify-attestation", - "--key", publicKey, + "--key", c.publicKey, "--type", "cyclonedx", fmt.Sprintf("%s@%s", image, hash), "--output-file", outputFile, @@ -297,7 +239,7 @@ func extractSBOM(attestationBytes []byte) (string, error) { return string(predicate), nil } -func (c sbomConfig) storeSBOM(sbom string, image string) error { +func (c cosignConfig) storeSBOM(sbom string, image string) error { // Make the image name safe for use as a filename safeImageName := strings.Map(func(r rune) rune { if unicode.IsLetter(r) || unicode.IsDigit(r) || r == '-' || r == '_' { @@ -321,12 +263,3 @@ func (c sbomConfig) storeSBOM(sbom string, image string) error { return nil } - -// getImageReleaseListURL returns the URL for the list of images in a release, based on the version and whether it's an internal release. -func (c *sbomConfig) getImageReleaseListURL() string { - if c.internalRelease { - return fmt.Sprintf("%s/release-internal/%s/%s", imageListBaseURL, c.version, imageListFilename) - } else { - return fmt.Sprintf("%s/release/%s/%s", imageListBaseURL, c.version, imageListFilename) - } -} diff --git a/cmd/src/sbom_utils.go b/cmd/src/sbom_utils.go index 17f12f7e7c..44e46279fa 100644 --- a/cmd/src/sbom_utils.go +++ b/cmd/src/sbom_utils.go @@ -1,16 +1,33 @@ package main +// Utility functions used by the SBOM and Signature commands. + import ( + "bufio" "encoding/json" "fmt" "io" "net/http" "os/exec" "path" + "regexp" "strings" "time" + + "github.com/sourcegraph/sourcegraph/lib/errors" ) +const imageListBaseURL = "https://storage.googleapis.com/sourcegraph-release-sboms" +const imageListFilename = "release-image-list.txt" + +type cosignConfig struct { + publicKey string + outputDir string + version string + internalRelease bool + insecureIgnoreTransparencyLog bool +} + // TokenResponse represents the JSON response from dockerHub's token service type dockerHubTokenResponse struct { Token string `json:"token"` @@ -200,3 +217,56 @@ func getOutputDir(parentDir, version string) string { func sanitizeVersion(version string) string { return strings.TrimPrefix(version, "v") } + +func verifyCosign() error { + _, err := exec.LookPath("cosign") + if err != nil { + return errors.New("SBOM verification requires 'cosign' to be installed and available in $PATH. See https://docs.sigstore.dev/cosign/system_config/installation/") + } + return nil +} + +func (c cosignConfig) getImageList() ([]string, error) { + imageReleaseListURL := c.getImageReleaseListURL() + + resp, err := http.Get(imageReleaseListURL) + if err != nil { + return nil, fmt.Errorf("failed to fetch image list: %w", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + // Compare version number against a regex that matches versions up to and including 5.8.0 + versionRegex := regexp.MustCompile(`^v?[0-5]\.([0-7]\.[0-9]+|8\.0)$`) + if versionRegex.MatchString(c.version) { + return nil, fmt.Errorf("unsupported version %s: SBOMs are only available for Sourcegraph releases after 5.8.0", c.version) + } + return nil, fmt.Errorf("failed to fetch list of images - check that %s is a valid Sourcegraph release: HTTP status %d", c.version, resp.StatusCode) + } + + scanner := bufio.NewScanner(resp.Body) + var images []string + for scanner.Scan() { + image := strings.TrimSpace(scanner.Text()) + if image != "" { + // Strip off a version suffix if present + parts := strings.SplitN(image, ":", 2) + images = append(images, parts[0]) + } + } + + if err := scanner.Err(); err != nil { + return nil, fmt.Errorf("error reading image list: %w", err) + } + + return images, nil +} + +// getImageReleaseListURL returns the URL for the list of images in a release, based on the version and whether it's an internal release. +func (c *cosignConfig) getImageReleaseListURL() string { + if c.internalRelease { + return fmt.Sprintf("%s/release-internal/%s/%s", imageListBaseURL, c.version, imageListFilename) + } else { + return fmt.Sprintf("%s/release/%s/%s", imageListBaseURL, c.version, imageListFilename) + } +} diff --git a/cmd/src/signature.go b/cmd/src/signature.go new file mode 100644 index 0000000000..0d61014aec --- /dev/null +++ b/cmd/src/signature.go @@ -0,0 +1,36 @@ +package main + +import ( + "flag" + "fmt" +) + +var signatureCommands commander + +func init() { + usage := `'src signature' verifies published signatures for Sourcegraph containers. + +Usage: + + src signature command [command options] + +The commands are: + + verify verify signatures for a Sourcegraph release +` + flagSet := flag.NewFlagSet("signature", flag.ExitOnError) + handler := func(args []string) error { + signatureCommands.run(flagSet, "src signature", usage, args) + return nil + } + + // Register the command. + commands = append(commands, &command{ + flagSet: flagSet, + aliases: []string{"signature", "sig"}, + handler: handler, + usageFunc: func() { + fmt.Println(usage) + }, + }) +} diff --git a/cmd/src/signature_fetch.go b/cmd/src/signature_fetch.go new file mode 100644 index 0000000000..e0bfa34e9f --- /dev/null +++ b/cmd/src/signature_fetch.go @@ -0,0 +1,202 @@ +package main + +import ( + "flag" + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" + + "github.com/sourcegraph/sourcegraph/lib/output" + + "github.com/sourcegraph/src-cli/internal/cmderrors" +) + +const signaturePublicKey = "https://storage.googleapis.com/sourcegraph-release-sboms/keys/cosign_keyring-cosign_image_signing_key-1.pub" + +func init() { + usage := ` +'src signature verify' verifies signatures for the given release version of Sourcegraph. + +Usage: + + src signature verify -v + +Examples: + + $ src signature verify -v 5.11.4013 # Verify all signatures for the 5.11.4013 release + + $ src signature verify -v 6.0.0 -d /tmp/signatures # Verify all signatures for the 6.0.0 release and write verified image digests under /tmp/signatures +` + + flagSet := flag.NewFlagSet("verify", flag.ExitOnError) + versionFlag := flagSet.String("v", "", "The version of Sourcegraph to verify signatures for.") + outputDirFlag := flagSet.String("d", "", "The directory to store verified image digests in.") + insecureIgnoreTransparencyLogFlag := flagSet.Bool("insecure-ignore-tlog", false, "Disable transparency log verification. Defaults to false.") + + handler := func(args []string) error { + c := cosignConfig{ + publicKey: signaturePublicKey, + internalRelease: false, + } + + if err := flagSet.Parse(args); err != nil { + return err + } + + if len(flagSet.Args()) != 0 { + return cmderrors.Usage("additional arguments not allowed") + } + + if versionFlag == nil || *versionFlag == "" { + return cmderrors.Usage("version is required") + } + c.version = sanitizeVersion(*versionFlag) + + if outputDirFlag != nil && *outputDirFlag != "" { + c.outputDir = getOutputDir(*outputDirFlag, c.version) + } + + if insecureIgnoreTransparencyLogFlag != nil && *insecureIgnoreTransparencyLogFlag { + c.insecureIgnoreTransparencyLog = true + } + + out := output.NewOutput(flagSet.Output(), output.OutputOpts{Verbose: *verbose}) + + if err := verifyCosign(); err != nil { + return cmderrors.ExitCode(1, err) + } + + images, err := c.getImageList() + if err != nil { + return err + } + + out.Writef("Verifying signatures for all %d images in the Sourcegraph %s release...\n", len(images), c.version) + + if c.insecureIgnoreTransparencyLog { + out.WriteLine(output.Line("⚠️", output.StyleWarning, "WARNING: Transparency log verification is disabled, increasing the risk that images may have been tampered with.")) + out.WriteLine(output.Line("️", output.StyleWarning, " This setting should only be used for testing or under explicit instruction from Sourcegraph.\n")) + } + + var successCount, failureCount int + var verifiedDigests []string + for _, image := range images { + stopSpinner := make(chan bool) + go spinner(image, stopSpinner) + + verifiedDigest, err := c.verifySignatureForImageVersion(image, c.version) + verifiedDigests = append(verifiedDigests, image+"@"+verifiedDigest) + + stopSpinner <- true + + if err != nil { + out.WriteLine(output.Line(output.EmojiFailure, output.StyleWarning, + fmt.Sprintf("\r%s: error verifying signature:\n %v", image, err))) + failureCount += 1 + } else { + out.WriteLine(output.Line("\r\u2705", output.StyleSuccess, image+"@"+verifiedDigest)) + successCount += 1 + } + } + + out.Write("") + if successCount > 0 && failureCount > 0 { + out.WriteLine(output.Line("🟠", output.StyleOrange, fmt.Sprintf("Verified signatures and digests for %d images, but failed to verify signatures for %d images", successCount, failureCount))) + } else if successCount > 0 && failureCount == 0 { + out.WriteLine(output.Line("🟢", output.StyleSuccess, fmt.Sprintf("Verified signatures and digests for %d images", successCount))) + } else { + out.WriteLine(output.Line("🔴", output.StyleWarning, "Failed to verify signatures for any images")) + + } + + if c.outputDir != "" { + if err = c.writeVerifiedDigests(verifiedDigests); err != nil { + out.WriteLine(output.Line("🔴", output.StyleWarning, err.Error())) + return cmderrors.ExitCode1 + } + out.Writef("\nVerified digests have been written to `%s`.\n", c.getOutputFilepath()) + } + out.WriteLine(output.Linef("", output.StyleBold, "Your Sourcegraph deployment may not use all of these images. Please check your deployment to confirm which images are used.\n")) + + if failureCount > 0 || successCount == 0 { + return cmderrors.ExitCode1 + } + + return nil + } + + signatureCommands = append(signatureCommands, &command{ + flagSet: flagSet, + handler: handler, + usageFunc: func() { + fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src signature %s':\n", flagSet.Name()) + flagSet.PrintDefaults() + fmt.Println(usage) + }, + }) +} + +func (c cosignConfig) verifySignatureForImageVersion(image string, version string) (string, error) { + digest, err := getImageDigest(image, version) + if err != nil { + return "", err + } + + err = c.verifySignatureForImageHash(image, digest) + if err != nil { + return "", err + } + + // Only return the digest if the signature is verified + return digest, nil +} + +func (c cosignConfig) verifySignatureForImageHash(image string, hash string) error { + tempDir, err := os.MkdirTemp("", "signature-") + if err != nil { + return fmt.Errorf("failed to create temporary directory: %w", err) + } + defer os.RemoveAll(tempDir) + + cosignArgs := []string{ + "verify", + "--key", c.publicKey, + fmt.Sprintf("%s@%s", image, hash), + } + + if c.insecureIgnoreTransparencyLog { + cosignArgs = append(cosignArgs, "--insecure-ignore-tlog") + } + + cmd := exec.Command("cosign", cosignArgs...) + + output, err := cmd.CombinedOutput() + if err != nil { + return fmt.Errorf("Signature verification failed: %w\nOutput: %s", err, output) + } + + return nil +} + +func (c cosignConfig) writeVerifiedDigests(verifiedDigests []string) error { + // Create the output file + outputFile := c.getOutputFilepath() + err := os.MkdirAll(c.outputDir, 0755) + if err != nil { + return fmt.Errorf("failed to create output directory: %w", err) + } + + // Write the verified digests to the file, one per line + err = os.WriteFile(outputFile, []byte(strings.Join(verifiedDigests, "\n")+"\n"), 0644) + if err != nil { + return fmt.Errorf("failed to write verified digests to file: %w", err) + } + + return nil +} + +func (c cosignConfig) getOutputFilepath() string { + return filepath.Join(c.outputDir, "verified-digests.txt") +} From 7b196a988531c7685d0ce84aaa1295d7694d671c Mon Sep 17 00:00:00 2001 From: Keegan Carruthers-Smith Date: Thu, 20 Feb 2025 18:31:15 +0200 Subject: [PATCH 457/647] Update ubuntu in Github Actions to latest LTS (24.04) (#1142) --- .github/workflows/docker.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index fcbc016b4c..c74ad5ab64 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -13,7 +13,7 @@ on: jobs: publish: - runs-on: ubuntu-22.04 + runs-on: ubuntu-24.04 steps: - name: Checkout uses: actions/checkout@v4 From 284b2b1ff0a42013bbc357fc3f452e8a065773e1 Mon Sep 17 00:00:00 2001 From: Keegan Carruthers-Smith Date: Fri, 21 Feb 2025 14:03:59 +0200 Subject: [PATCH 458/647] chore/ci: upgrade golanglint-ci to 1.64.5 (#1148) Hopefully solves a potential OOM we are seeing on CI. Test Plan: CI --- cmd/src/gateway_benchmark.go | 1 + dev/golangci-lint.sh | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/cmd/src/gateway_benchmark.go b/cmd/src/gateway_benchmark.go index 2988dfb9db..cc354bc625 100644 --- a/cmd/src/gateway_benchmark.go +++ b/cmd/src/gateway_benchmark.go @@ -203,6 +203,7 @@ func (c *webSocketClient) reconnect() error { fmt.Println("Connecting to WebSocket..", c.URL) var err error var resp *http.Response + //nolint:bodyclose // closed as part of webSocketClient c.conn, resp, err = websocket.DefaultDialer.Dial(c.URL, c.reqHeaders) if err != nil { c.conn = nil // retry again later diff --git a/dev/golangci-lint.sh b/dev/golangci-lint.sh index 80c94bf299..c4663dc8ec 100755 --- a/dev/golangci-lint.sh +++ b/dev/golangci-lint.sh @@ -6,7 +6,7 @@ pushd "$(dirname "${BASH_SOURCE[0]}")/.." >/dev/null mkdir -p dev/.bin -version="1.58.1" +version="1.64.5" suffix="${version}-$(go env GOOS)-$(go env GOARCH)" target="$PWD/dev/.bin/golangci-lint-${suffix}" url="https://github.com/golangci/golangci-lint/releases/download/v${version}/golangci-lint-${suffix}.tar.gz" @@ -18,6 +18,7 @@ if [ ! -f "${target}" ]; then mv "golangci-lint-${suffix}/golangci-lint" "${target}" rm -f "${target}.tar.gz" rm -rf "golangci-lint-${suffix}" + echo "downloaded" 1>&2 fi chmod +x "${target}" From 98d8cd4673c272ee9076382cb33fe960820c492a Mon Sep 17 00:00:00 2001 From: Anton Sviridov Date: Fri, 21 Feb 2025 14:53:44 +0000 Subject: [PATCH 459/647] Remove LSIF support from src-cli (#1147) --- cmd/src/code_intel.go | 4 +- cmd/src/code_intel_upload.go | 36 +-- cmd/src/code_intel_upload_flags.go | 289 ++++-------------------- cmd/src/code_intel_upload_flags_test.go | 71 +----- cmd/src/lsif.go | 30 --- cmd/src/main.go | 3 +- internal/codeintel/gitutil_test.go | 6 +- 7 files changed, 67 insertions(+), 372 deletions(-) delete mode 100644 cmd/src/lsif.go diff --git a/cmd/src/code_intel.go b/cmd/src/code_intel.go index af9f48795e..3dc3f28d8c 100644 --- a/cmd/src/code_intel.go +++ b/cmd/src/code_intel.go @@ -16,13 +16,13 @@ Usage: The commands are: - upload uploads a SCIP or LSIF index + upload uploads a SCIP index Use "src code-intel [command] -h" for more information about a command. ` flagSet := flag.NewFlagSet("code-intel", flag.ExitOnError) handler := func(args []string) error { - lsifCommands.run(flagSet, "src code-intel", usage, args) + codeintelCommands.run(flagSet, "src code-intel", usage, args) return nil } diff --git a/cmd/src/code_intel_upload.go b/cmd/src/code_intel_upload.go index 71d62116c6..dfe761939e 100644 --- a/cmd/src/code_intel_upload.go +++ b/cmd/src/code_intel_upload.go @@ -9,7 +9,6 @@ import ( "io" "net/url" "os" - "path/filepath" "strings" "time" @@ -28,7 +27,7 @@ func init() { Examples: Before running any of these, first use src auth to authenticate. Alternately, use the SRC_ACCESS_TOKEN environment variable for - individual src-cli invocations. + individual src-cli invocations. If run from within the project itself, src-cli will infer various flags based on git metadata. @@ -48,9 +47,6 @@ Examples: $ src code-intel upload -github-token=BAZ, or $ src code-intel upload -gitlab-token=BAZ - - For any of these commands, an LSIF index (default name: dump.lsif) can be - used instead of a SCIP index (default name: index.scip). ` codeintelCommands = append(codeintelCommands, &command{ flagSet: codeintelUploadFlagSet, @@ -61,24 +57,13 @@ Examples: fmt.Println(usage) }, }) - - // Make 'upload' available under 'src lsif' for backwards compatibility. - lsifCommands = append(lsifCommands, &command{ - flagSet: codeintelUploadFlagSet, - handler: handleCodeIntelUpload, - usageFunc: func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src lsif %s':\n", codeintelUploadFlagSet.Name()) - codeintelUploadFlagSet.PrintDefaults() - fmt.Println(usage) - }, - }) } // handleCodeIntelUpload is the handler for `src code-intel upload`. func handleCodeIntelUpload(args []string) error { ctx := context.Background() - out, isSCIPAvailable, err := parseAndValidateCodeIntelUploadFlags(args) + out, err := parseAndValidateCodeIntelUploadFlags(args) if !codeintelUploadFlags.json { if out != nil { printInferredArguments(out) @@ -96,7 +81,7 @@ func handleCodeIntelUpload(args []string) error { Flags: codeintelUploadFlags.apiFlags, }) - uploadOptions := codeintelUploadOptions(out, isSCIPAvailable) + uploadOptions := codeintelUploadOptions(out) uploadID, err := upload.UploadIndex(ctx, codeintelUploadFlags.file, client, uploadOptions) if err != nil { return handleUploadError(uploadOptions.SourcegraphInstanceOptions.AccessToken, err) @@ -141,18 +126,13 @@ func handleCodeIntelUpload(args []string) error { } // codeintelUploadOptions creates a set of upload options given the values in the flags. -func codeintelUploadOptions(out *output.Output, isSCIPAvailable bool) upload.UploadOptions { +func codeintelUploadOptions(out *output.Output) upload.UploadOptions { var associatedIndexID *int if codeintelUploadFlags.associatedIndexID != -1 { associatedIndexID = &codeintelUploadFlags.associatedIndexID } - cfg.AdditionalHeaders["Content-Type"] = "application/x-ndjson+lsif" - path := codeintelUploadFlags.uploadRoute - if isSCIPAvailable && filepath.Ext(codeintelUploadFlags.file) == ".scip" { - cfg.AdditionalHeaders["Content-Type"] = "application/x-protobuf+scip" - path = strings.ReplaceAll(path, "lsif", "scip") - } + cfg.AdditionalHeaders["Content-Type"] = "application/x-protobuf+scip" logger := upload.NewRequestLogger( os.Stdout, @@ -178,7 +158,7 @@ func codeintelUploadOptions(out *output.Output, isSCIPAvailable bool) upload.Upl AdditionalHeaders: cfg.AdditionalHeaders, MaxRetries: 5, RetryInterval: time.Second, - Path: path, + Path: codeintelUploadFlags.uploadRoute, MaxPayloadSizeBytes: codeintelUploadFlags.maxPayloadSizeMb * 1000 * 1000, MaxConcurrency: codeintelUploadFlags.maxConcurrency, GitHubToken: codeintelUploadFlags.gitHubToken, @@ -263,7 +243,7 @@ func attachHintsForAuthorizationError(accessToken string, originalError error) e if likelyTokenError { return errorWithHint{err: originalError, hint: strings.Join(mergeStringSlices( - []string{"A Sourcegraph access token must be provided via SRC_ACCESS_TOKEN for uploading SCIP/LSIF data."}, + []string{"A Sourcegraph access token must be provided via SRC_ACCESS_TOKEN for uploading SCIP data."}, actionableHints, []string{"For more details, see https://sourcegraph.com/docs/cli/how-tos/creating_an_access_token."}, ), "\n")} @@ -304,7 +284,7 @@ func attachHintsForAuthorizationError(accessToken string, originalError error) e } return errorWithHint{err: originalError, hint: strings.Join(mergeStringSlices( - []string{"This Sourcegraph instance has enforced auth for SCIP/LSIF uploads."}, + []string{"This Sourcegraph instance has enforced auth for SCIP uploads."}, actionableHints, []string{"For more details, see https://docs.sourcegraph.com/cli/references/code-intel/upload."}, ), "\n")} diff --git a/cmd/src/code_intel_upload_flags.go b/cmd/src/code_intel_upload_flags.go index a724806a90..b63735944a 100644 --- a/cmd/src/code_intel_upload_flags.go +++ b/cmd/src/code_intel_upload_flags.go @@ -1,22 +1,14 @@ package main import ( - "context" "flag" "fmt" - "net/http" "os" - "path" - "path/filepath" "strings" - "time" "github.com/sourcegraph/scip/bindings/go/scip" - libscip "github.com/sourcegraph/sourcegraph/lib/codeintel/lsif/scip" - "github.com/sourcegraph/sourcegraph/lib/codeintel/upload" "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/sourcegraph/lib/output" - "google.golang.org/protobuf/proto" "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/codeintel" @@ -57,26 +49,21 @@ var ( // Used to include the insecure-skip-verify flag in the help output, as we don't use any of the // other api.Client methods, so only the insecureSkipVerify flag is relevant here. dummyflag bool - - // Used to skip the LSIF -> SCIP conversion during the migration. Not expected to be used outside - // of codeintel-qa pipelines and not expected to last much longer than a few releases while we - // deprecate all LSIF code paths. - skipConversionToSCIP bool ) func init() { - codeintelUploadFlagSet.StringVar(&codeintelUploadFlags.file, "file", "", `The path to the LSIF dump file.`) + codeintelUploadFlagSet.StringVar(&codeintelUploadFlags.file, "file", "", `The path to the SCIP index file.`) // UploadRecordOptions codeintelUploadFlagSet.StringVar(&codeintelUploadFlags.repo, "repo", "", `The name of the repository (e.g. github.com/gorilla/mux). By default, derived from the origin remote.`) codeintelUploadFlagSet.StringVar(&codeintelUploadFlags.commit, "commit", "", `The 40-character hash of the commit. Defaults to the currently checked-out commit.`) - codeintelUploadFlagSet.StringVar(&codeintelUploadFlags.root, "root", "", `The path in the repository that matches the LSIF projectRoot (e.g. cmd/project1). Defaults to the directory where the dump file is located.`) - codeintelUploadFlagSet.StringVar(&codeintelUploadFlags.indexer, "indexer", "", `The name of the indexer that generated the dump. This will override the 'toolInfo.name' field in the metadata vertex of the LSIF dump file. This must be supplied if the indexer does not set this field (in which case the upload will fail with an explicit message).`) - codeintelUploadFlagSet.StringVar(&codeintelUploadFlags.indexerVersion, "indexerVersion", "", `The version of the indexer that generated the dump. This will override the 'toolInfo.version' field in the metadata vertex of the LSIF dump file. This must be supplied if the indexer does not set this field (in which case the upload will fail with an explicit message).`) + codeintelUploadFlagSet.StringVar(&codeintelUploadFlags.root, "root", "", `The path in the repository that matches the SCIP projectRoot (e.g. cmd/project1). Defaults to the directory where the SCIP index file is located.`) + codeintelUploadFlagSet.StringVar(&codeintelUploadFlags.indexer, "indexer", "", `The name of the indexer that generated the dump. This will override the 'toolInfo.name' field in the metadata section of SCIP index. This must be supplied if the indexer does not set this field (in which case the upload will fail with an explicit message).`) + codeintelUploadFlagSet.StringVar(&codeintelUploadFlags.indexerVersion, "indexerVersion", "", `The version of the indexer that generated the dump. This will override the 'toolInfo.version' field in the metadata section of SCIP index. This must be supplied if the indexer does not set this field (in which case the upload will fail with an explicit message).`) codeintelUploadFlagSet.IntVar(&codeintelUploadFlags.associatedIndexID, "associated-index-id", -1, "ID of the associated index record for this upload. For internal use only.") // SourcegraphInstanceOptions - codeintelUploadFlagSet.StringVar(&codeintelUploadFlags.uploadRoute, "upload-route", "/.api/lsif/upload", "The path of the upload route. For internal use only.") + codeintelUploadFlagSet.StringVar(&codeintelUploadFlags.uploadRoute, "upload-route", "/.api/scip/upload", "The path of the upload route. For internal use only.") codeintelUploadFlagSet.Int64Var(&codeintelUploadFlags.maxPayloadSizeMb, "max-payload-size", 100, `The maximum upload size (in megabytes). Indexes exceeding this limit will be uploaded over multiple HTTP requests.`) codeintelUploadFlagSet.IntVar(&codeintelUploadFlags.maxConcurrency, "max-concurrency", -1, "The maximum number of concurrent uploads. Only relevant for multipart uploads. Defaults to all parts concurrently.") @@ -89,11 +76,8 @@ func init() { codeintelUploadFlagSet.BoolVar(&codeintelUploadFlags.noProgress, "no-progress", false, `Do not display progress updates.`) codeintelUploadFlagSet.IntVar(&codeintelUploadFlags.verbosity, "trace", 0, "-trace=0 shows no logs; -trace=1 shows requests and response metadata; -trace=2 shows headers, -trace=3 shows response body") codeintelUploadFlagSet.BoolVar(&codeintelUploadFlags.json, "json", false, `Output relevant state in JSON on success.`) - codeintelUploadFlagSet.BoolVar(&codeintelUploadFlags.open, "open", false, `Open the LSIF upload page in your browser.`) + codeintelUploadFlagSet.BoolVar(&codeintelUploadFlags.open, "open", false, `Open the SCIP upload page in your browser.`) codeintelUploadFlagSet.BoolVar(&dummyflag, "insecure-skip-verify", false, "Skip validation of TLS certificates against trusted chains") - - // Testing flags - codeintelUploadFlagSet.BoolVar(&skipConversionToSCIP, "skip-scip", false, "Skip converting LSIF index to SCIP if the instance supports it; this option should only used for debugging") } // parseAndValidateCodeIntelUploadFlags calls codeintelUploadFlagset.Parse, then infers values for @@ -102,9 +86,9 @@ func init() { // // On success, the global codeintelUploadFlags object will be populated with valid values. An // error is returned on failure. -func parseAndValidateCodeIntelUploadFlags(args []string) (*output.Output, bool, error) { +func parseAndValidateCodeIntelUploadFlags(args []string) (*output.Output, error) { if err := codeintelUploadFlagSet.Parse(args); err != nil { - return nil, false, err + return nil, err } out := codeintelUploadOutput() @@ -122,13 +106,13 @@ func parseAndValidateCodeIntelUploadFlags(args []string) (*output.Output, bool, // and maybe we'll use some in the future codeintelUploadFlags.apiFlags = api.NewFlags(apiClientFlagSet) if err := apiClientFlagSet.Parse(insecureSkipVerifyFlag); err != nil { - return nil, false, err + return nil, err } if !isFlagSet(codeintelUploadFlagSet, "file") { defaultFile, err := inferDefaultFile() if err != nil { - return nil, false, err + return nil, err } codeintelUploadFlags.file = defaultFile } @@ -136,42 +120,27 @@ func parseAndValidateCodeIntelUploadFlags(args []string) (*output.Output, bool, // Check to see if input file exists if _, err := os.Stat(codeintelUploadFlags.file); os.IsNotExist(err) { if !isFlagSet(codeintelUploadFlagSet, "file") { - return nil, false, formatInferenceError(argumentInferenceError{"file", err}) + return nil, formatInferenceError(argumentInferenceError{"file", err}) } - return nil, false, errors.Newf("file %q does not exist", codeintelUploadFlags.file) - } - - isSCIPAvailable, err := isSCIPAvailable() - if err != nil { - return nil, false, err - } - - if !isSCIPAvailable { - if err := handleSCIP(out); err != nil { - return nil, false, err - } - } else { - if err := handleLSIF(out); err != nil { - return nil, false, err - } + return nil, errors.Newf("file %q does not exist", codeintelUploadFlags.file) } // Check for new file existence after transformation if _, err := os.Stat(codeintelUploadFlags.file); os.IsNotExist(err) { - return nil, false, errors.Newf("file %q does not exist", codeintelUploadFlags.file) + return nil, errors.Newf("file %q does not exist", codeintelUploadFlags.file) } // Infer the remaining default arguments (may require reading from new file) if inferenceErrors := inferMissingCodeIntelUploadFlags(); len(inferenceErrors) > 0 { - return nil, false, formatInferenceError(inferenceErrors[0]) + return nil, formatInferenceError(inferenceErrors[0]) } if err := validateCodeIntelUploadFlags(); err != nil { - return nil, false, err + return nil, err } - return out, isSCIPAvailable, nil + return out, nil } // codeintelUploadOutput returns an output object that should be used to print the progres @@ -190,158 +159,24 @@ func codeintelUploadOutput() (out *output.Output) { }) } -func isSCIPAvailable() (bool, error) { - client := cfg.apiClient(codeintelUploadFlags.apiFlags, codeintelUploadFlagSet.Output()) - req, err := client.NewHTTPRequest(context.Background(), "HEAD", strings.ReplaceAll(codeintelUploadFlags.uploadRoute, "lsif", "scip"), nil) - if err != nil { - return false, err - } - - resp, err := client.Do(req) - if err != nil { - return false, err - } - defer resp.Body.Close() - if resp.StatusCode == http.StatusUnauthorized { - return false, upload.ErrUnauthorized - } - - return resp.StatusCode == http.StatusOK, nil -} - type argumentInferenceError struct { argument string err error } -func replaceExtension(oldPath string, newExtension string) string { - oldExtLen := len(path.Ext(oldPath)) - if oldExtLen == 0 { - panic(fmt.Sprintf("Expected path %s to have an extension", oldPath)) - } - return oldPath[:len(oldPath)-oldExtLen] + newExtension -} - -func replaceBaseName(oldPath string, newBaseName string) string { - if filepath.Dir(newBaseName) != "." { - panic(fmt.Sprintf("Expected bare file name but found %s", newBaseName)) - } - return filepath.Join(filepath.Dir(oldPath), newBaseName) -} - -func handleSCIP(out *output.Output) error { - fileExt := path.Ext(codeintelUploadFlags.file) - if len(fileExt) == 0 { - return errors.Newf("missing file extension for %s; expected .scip or .lsif", codeintelUploadFlags.file) - } - inputFile := codeintelUploadFlags.file - if fileExt == ".scip" || fileExt == ".lsif-typed" { - // The user explicitly passed in a -file flag that points to an SCIP index. - outputFile := replaceExtension(inputFile, ".lsif") - if filepath.Base(inputFile) == "index.scip" { - outputFile = replaceBaseName(inputFile, "dump.lsif") - } - // HACK: Modify the flags to point to the output file, because - // that field of the flags is read when performing the upload. - codeintelUploadFlags.file = outputFile - return convertSCIPToLSIFGraph(out, inputFile, outputFile) - } - - if _, err := os.Stat(inputFile); err == nil { - // Do nothing, the provided -flag flag points to an existing - // file that does not have the file extension `.lsif-typed` or `.scip`. - return nil - } - - scipFile := replaceExtension(inputFile, ".scip") - if _, err := os.Stat(scipFile); os.IsNotExist(err) { - // The input may be named 'dump.lsif', but the default name for SCIP - // indexes is 'index.scip', not 'dump.scip'. - scipFile = replaceBaseName(inputFile, "index.scip") - if _, err := os.Stat(scipFile); os.IsNotExist(err) { - lsifTypedFile := replaceExtension(inputFile, ".lsif-typed") - if _, err := os.Stat(lsifTypedFile); os.IsNotExist(err) { - // There is no `*.scip` or `*.lsif-typed` file for the inferred path. - return nil - } - scipFile = lsifTypedFile - } - } - - // The provided -file flag points to an `*.lsif` file that doesn't exist - // so we convert the sibling file (which we confirmed exists). - return convertSCIPToLSIFGraph(out, scipFile, codeintelUploadFlags.file) -} - -// Reads the SCIP encoded input file and writes the corresponding LSIF -// Graph encoded output file. -func convertSCIPToLSIFGraph(out *output.Output, inputFile, outputFile string) error { - if out != nil { - out.Writef("%s Converting %s into %s", output.EmojiInfo, inputFile, outputFile) - } - tmp, err := os.Create(outputFile) - if err != nil { - return err - } - defer tmp.Close() - - data, err := os.ReadFile(inputFile) - if err != nil { - return errors.Wrapf(err, "failed to read SCIP index '%s'", inputFile) - } - index := scip.Index{} - err = proto.Unmarshal(data, &index) - if err != nil { - return errors.Wrapf(err, "failed to parse protobuf file '%s'", inputFile) - } - els, err := scip.ConvertSCIPToLSIF(&index) - if err != nil { - return errors.Wrapf(err, "failed to convert SCIP index at '%s' to LSIF", inputFile) - } - err = scip.WriteNDJSON(scip.ElementsToJsonElements(els), tmp) - if err != nil { - return errors.Wrapf(err, "failed to write LSIF JSON output to '%s'", tmp.Name()) - } - err = tmp.Close() - if err != nil { - return err - } - return nil -} - func inferDefaultFile() (string, error) { - hasSCIP := true const scipFilename = "index.scip" - if _, err := os.Stat(scipFilename); err != nil { - if os.IsNotExist(err) { - hasSCIP = false - } else { - return "", err - } - } - - hasLSIF := true - const lsifFilename = "dump.lsif" - if _, err := os.Stat(lsifFilename); err != nil { - if os.IsNotExist(err) { - hasLSIF = false - } else { - return "", err - } - } + _, err := os.Stat(scipFilename) - if hasSCIP && hasLSIF { - return "", errors.Newf("both %s and %s exists - cannot determine unambiguous choice", scipFilename, lsifFilename) - } - if !(hasSCIP || hasLSIF) { - return "", formatInferenceError(argumentInferenceError{"file", errors.Newf("neither %s nor %s exists", scipFilename, lsifFilename)}) + if err == nil { + return scipFilename, nil } - if hasSCIP { - return scipFilename, nil + if os.IsNotExist(err) { + return "", formatInferenceError(argumentInferenceError{"file", errors.Newf("%s does not exist", scipFilename)}) } - return lsifFilename, nil + return "", err } func formatInferenceError(inferenceErr argumentInferenceError) error { @@ -356,68 +191,13 @@ func formatInferenceError(inferenceErr argumentInferenceError) error { } } -func handleLSIF(out *output.Output) error { - if skipConversionToSCIP { - return nil - } - - fileExt := path.Ext(codeintelUploadFlags.file) - if len(fileExt) == 0 { - return errors.Newf("missing file extension for %s; expected .scip or .lsif", codeintelUploadFlags.file) - } - - if fileExt == ".lsif" || fileExt == ".dump" { - inputFile := codeintelUploadFlags.file - outputFile := replaceExtension(inputFile, ".scip") - codeintelUploadFlags.file = outputFile - return convertLSIFToSCIP(out, inputFile, outputFile) - } - - return nil -} - -// Reads the LSIF encoded input file and writes the corresponding SCIP encoded output file. -func convertLSIFToSCIP(out *output.Output, inputFile, outputFile string) error { - if out != nil { - out.Writef("%s Converting %s into %s", output.EmojiInfo, inputFile, outputFile) - } - - ctx := context.Background() - uploadID := -time.Now().Nanosecond() - root := codeintelUploadFlags.root - - if !isFlagSet(codeintelUploadFlagSet, "root") { - // Best-effort infer the root; we have a strange cyclic init order where we're - // currently trying to determine the filename that determines the root, but we - // need the root when converting from LSIF to SCIP. - root, _ = inferIndexRoot() - } - - rc, err := os.Open(inputFile) - if err != nil { - return err - } - defer rc.Close() - - index, err := libscip.ConvertLSIF(ctx, uploadID, rc, root) - if err != nil { - return err - } - serialized, err := proto.Marshal(index) - if err != nil { - return err - } - - return os.WriteFile(outputFile, serialized, os.ModePerm) -} - // inferMissingCodeIntelUploadFlags updates the flags values which were not explicitly // supplied by the user with default values inferred from the current git state and // filesystem. // // Note: This function must not be called before codeintelUploadFlagset.Parse. func inferMissingCodeIntelUploadFlags() (inferErrors []argumentInferenceError) { - indexerName, indexerVersion, readIndexerNameAndVersionErr := readIndexerNameAndVersion() + indexerName, indexerVersion, readIndexerNameAndVersionErr := readIndexerNameAndVersion(codeintelUploadFlags.file) getIndexerName := func() (string, error) { return indexerName, readIndexerNameAndVersionErr } getIndexerVersion := func() (string, error) { return indexerVersion, readIndexerNameAndVersionErr } @@ -484,14 +264,31 @@ func inferIndexRoot() (string, error) { // toolInfo value in the configured index file. // // Note: This function must not be called before codeintelUploadFlagset.Parse. -func readIndexerNameAndVersion() (string, string, error) { - file, err := os.Open(codeintelUploadFlags.file) +func readIndexerNameAndVersion(indexFile string) (string, string, error) { + file, err := os.Open(indexFile) if err != nil { return "", "", err } defer file.Close() - return upload.ReadIndexerNameAndVersion(file) + var metadata *scip.Metadata + + visitor := scip.IndexVisitor{ + VisitMetadata: func(m *scip.Metadata) { + metadata = m + }, + } + + // convert file to io.Reader + if err := visitor.ParseStreaming(file); err != nil { + return "", "", err + } + + if metadata == nil || metadata.ToolInfo == nil { + return "", "", errors.New("index file does not contain valid metadata") + } + + return metadata.ToolInfo.Name, metadata.ToolInfo.Version, nil } // validateCodeIntelUploadFlags returns an error if any of the parsed flag values are illegal. diff --git a/cmd/src/code_intel_upload_flags_test.go b/cmd/src/code_intel_upload_flags_test.go index 9725a45f42..cf675ddeb2 100644 --- a/cmd/src/code_intel_upload_flags_test.go +++ b/cmd/src/code_intel_upload_flags_test.go @@ -21,9 +21,6 @@ var exampleSCIPIndex = scip.Index{ }, } -var exampleLSIFString = `{"id":1,"version":"0.4.3","positionEncoding":"utf-8","toolInfo":{"name":"hello","version":"1.0.0"},"type":"vertex","label":"metaData"} -` - func exampleSCIPBytes(t *testing.T) []byte { bytes, err := proto.Marshal(&exampleSCIPIndex) if err != nil { @@ -32,67 +29,19 @@ func exampleSCIPBytes(t *testing.T) []byte { return bytes } -func createTempSCIPFile(t *testing.T, scipFileName string) (scipFilePath string, lsifFilePath string) { +func createTempSCIPFile(t *testing.T, scipFileName string) string { + t.Helper() dir := t.TempDir() require.NotEqual(t, "", scipFileName) - scipFilePath = filepath.Join(dir, scipFileName) - lsifFilePath = filepath.Join(dir, "dump.lsif") + scipFilePath := filepath.Join(dir, scipFileName) err := os.WriteFile(scipFilePath, exampleSCIPBytes(t), 0755) - if err != nil { - t.Fatal(err) - } - return scipFilePath, lsifFilePath -} - -func assertLSIFOutput(t *testing.T, lsifFile, expectedLSIFString string) { - out := codeintelUploadOutput() - handleSCIP(out) - lsif, err := os.ReadFile(lsifFile) - if err != nil { - t.Fatal(err) - } - obtained := string(lsif) - if obtained != expectedLSIFString { - t.Fatalf("unexpected LSIF output %s", obtained) - } - if lsifFile != codeintelUploadFlags.file { - t.Fatalf("unexpected codeintelUploadFlag.file value %s, expected %s", codeintelUploadFlags.file, lsifFile) - } + require.NoError(t, err) + return scipFilePath } -func TestImplicitlyConvertSCIPIntoLSIF(t *testing.T) { - for _, filename := range []string{"index.scip", "dump.scip", "dump.lsif-typed"} { - _, lsifFile := createTempSCIPFile(t, filename) - codeintelUploadFlags.file = lsifFile - assertLSIFOutput(t, lsifFile, exampleLSIFString) - } -} - -func TestImplicitlyIgnoreSCIP(t *testing.T) { - for _, filename := range []string{"index.scip", "dump.scip", "dump.lsif-typed"} { - _, lsifFile := createTempSCIPFile(t, filename) - codeintelUploadFlags.file = lsifFile - os.WriteFile(lsifFile, []byte("hello world"), 0755) - assertLSIFOutput(t, lsifFile, "hello world") - } -} - -func TestExplicitlyConvertSCIPIntoGraph(t *testing.T) { - for _, filename := range []string{"index.scip", "dump.scip", "dump.lsif-typed"} { - scipFile, lsifFile := createTempSCIPFile(t, filename) - codeintelUploadFlags.file = scipFile - assertLSIFOutput(t, lsifFile, exampleLSIFString) - } -} - -func TestReplaceExtension(t *testing.T) { - require.Panics(t, func() { replaceExtension("foo", ".xyz") }) - require.Equal(t, "foo.xyz", replaceExtension("foo.abc", ".xyz")) -} - -func TestReplaceBaseName(t *testing.T) { - require.Panics(t, func() { replaceBaseName("mydir", filepath.Join("dir", "file")) }) - - require.Equal(t, filepath.Join("a", "d.e"), - replaceBaseName(filepath.Join("a", "b.c"), "d.e")) +func TestInferIndexerNameAndVersion(t *testing.T) { + name, version, err := readIndexerNameAndVersion(createTempSCIPFile(t, "index.scip")) + require.NoError(t, err) + require.Equal(t, "hello", name) + require.Equal(t, "1.0.0", version) } diff --git a/cmd/src/lsif.go b/cmd/src/lsif.go deleted file mode 100644 index 7b5939569c..0000000000 --- a/cmd/src/lsif.go +++ /dev/null @@ -1,30 +0,0 @@ -package main - -import ( - "flag" - "fmt" -) - -var lsifCommands commander - -func init() { - usage := `[DEPRECATED] 'src lsif' is a tool that manages LSIF data on a Sourcegraph instance. - -Use 'src code-intel' instead. -` - flagSet := flag.NewFlagSet("lsif", flag.ExitOnError) - handler := func(args []string) error { - lsifCommands.run(flagSet, "src lsif", usage, args) - return nil - } - - // Register the command. - commands = append(commands, &command{ - flagSet: flagSet, - aliases: []string{"lsif"}, - handler: handler, - usageFunc: func() { - fmt.Println(usage) - }, - }) -} diff --git a/cmd/src/main.go b/cmd/src/main.go index d8d32b7983..06feaa5ac0 100644 --- a/cmd/src/main.go +++ b/cmd/src/main.go @@ -28,7 +28,7 @@ Environment variables SRC_ENDPOINT endpoint to use, if unset will default to "https://sourcegraph.com" SRC_PROXY A proxy to use for proxying requests to the Sourcegraph endpoint. Supports HTTP(S), SOCKS5/5h, and UNIX Domain Socket proxies. - If a UNIX Domain Socket, the path can be either an absolute path, + If a UNIX Domain Socket, the path can be either an absolute path, or can start with ~/ or %USERPROFILE%\ for a path in the user's home directory. Examples: - https://localhost:3080 @@ -55,7 +55,6 @@ The commands are: extsvc manages external services gateway interacts with Cody Gateway login authenticate to a Sourcegraph instance with your user credentials - lsif manages LSIF data (deprecated: use 'code-intel') orgs,org manages organizations teams,team manages teams repos,repo manages repositories diff --git a/internal/codeintel/gitutil_test.go b/internal/codeintel/gitutil_test.go index 893f790a2a..29dde13d85 100644 --- a/internal/codeintel/gitutil_test.go +++ b/internal/codeintel/gitutil_test.go @@ -63,9 +63,9 @@ func TestParseRemote(t *testing.T) { func TestInferRoot(t *testing.T) { testCases := map[string]string{ - "gitutil.go": filepath.Join("internal", "codeintel"), - "../../cmd/src/lsif.go": filepath.Join("cmd", "src"), - "../../README.md": ".", + "gitutil.go": filepath.Join("internal", "codeintel"), + "../../cmd/src/code_intel_upload.go": filepath.Join("cmd", "src"), + "../../README.md": ".", } for input, expectedOutput := range testCases { From 53e36ab82c9d499440c5c882b6f599a7ff886203 Mon Sep 17 00:00:00 2001 From: Anton Sviridov Date: Thu, 27 Feb 2025 11:05:31 +0000 Subject: [PATCH 460/647] Support pre-compressed uploads in code-intel upload (#1146) --- .github/workflows/scip.yml | 32 +- CHANGELOG.md | 4 +- cmd/src/code_intel_upload.go | 7 +- cmd/src/code_intel_upload_flags.go | 83 +++- cmd/src/code_intel_upload_transfer.go | 82 ++++ cmd/src/code_intel_upload_vendored.go | 627 ++++++++++++++++++++++++++ 6 files changed, 819 insertions(+), 16 deletions(-) create mode 100644 cmd/src/code_intel_upload_transfer.go create mode 100644 cmd/src/code_intel_upload_vendored.go diff --git a/.github/workflows/scip.yml b/.github/workflows/scip.yml index a1969f7f6f..24463d7dbe 100644 --- a/.github/workflows/scip.yml +++ b/.github/workflows/scip.yml @@ -11,24 +11,46 @@ jobs: container: sourcegraph/scip-go steps: - uses: actions/checkout@v4 - - name: Get src-cli - run: curl -L https://sourcegraph.com/.api/src-cli/src_linux_amd64 -o /usr/local/bin/src; - chmod +x /usr/local/bin/src + - name: Set up Go + uses: actions/setup-go@v5 + with: + go-version: 1.23.2 + - name: Set directory to safe for git run: git config --global --add safe.directory $GITHUB_WORKSPACE + + - name: Build src-cli + run: go build -o ./src-cli ./cmd/src + - name: Enable pulling Go modules from private sourcegraph/sourcegraph run: git config --global url."https://${PRIVATE_TOKEN}@github.com/sourcegraph/".insteadOf "https://github.com/sourcegraph/" + - name: Generate SCIP data run: scip-go - name: Upload SCIP to Cloud - run: src code-intel upload -github-token='${{ secrets.GITHUB_TOKEN }}' -no-progress + run: ./src-cli code-intel upload -github-token='${{ secrets.GITHUB_TOKEN }}' -no-progress env: SRC_ENDPOINT: https://sourcegraph.com/ SRC_ACCESS_TOKEN: ${{ secrets.SRC_ACCESS_TOKEN_DOTCOM }} - name: Upload SCIP to S2 - run: src code-intel upload -github-token='${{ secrets.GITHUB_TOKEN }}' -no-progress + run: ./src-cli code-intel upload -github-token='${{ secrets.GITHUB_TOKEN }}' -no-progress + env: + SRC_ENDPOINT: https://sourcegraph.sourcegraph.com/ + SRC_ACCESS_TOKEN: ${{ secrets.SRC_ACCESS_TOKEN_S2 }} + + - name: Compress SCIP file + run: gzip index.scip + + - name: Upload compressed SCIP to Cloud + run: ./src-cli code-intel upload -github-token='${{ secrets.GITHUB_TOKEN }}' -no-progress + env: + SRC_ENDPOINT: https://sourcegraph.com/ + SRC_ACCESS_TOKEN: ${{ secrets.SRC_ACCESS_TOKEN_DOTCOM }} + + - name: Upload compressed SCIP to S2 + run: ./src-cli code-intel upload -github-token='${{ secrets.GITHUB_TOKEN }}' -no-progress env: SRC_ENDPOINT: https://sourcegraph.sourcegraph.com/ SRC_ACCESS_TOKEN: ${{ secrets.SRC_ACCESS_TOKEN_S2 }} diff --git a/CHANGELOG.md b/CHANGELOG.md index d9b345603c..f596554e7f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ All notable changes to `src-cli` are documented in this file. ## Unreleased +- Support uploading GZIP compressed SCIP indexes [1146](https://github.com/sourcegraph/src-cli/pull/1146) + ## 6.0.1 - Container signature verification support: Container signatures can now be verified for Sourcegraph releases after 5.11.4013 using `src signature verify -v ` [#1143](https://github.com/sourcegraph/src-cli/pull/1143) @@ -153,7 +155,7 @@ All notable changes to `src-cli` are documented in this file. ### Fixed -- Fixed `src validate install` requiring `SRC_GITHUB_TOKEN` in all cases. [958](https://github.com/sourcegraph/src-cli/pull/958) +- Fixed `src validate install` requiring `SRC_GITHUB_TOKEN` in all cases. [958](https://github.com/sourcegraph/src-cli/pull/958) ## 5.0.1 diff --git a/cmd/src/code_intel_upload.go b/cmd/src/code_intel_upload.go index dfe761939e..f63f7394a9 100644 --- a/cmd/src/code_intel_upload.go +++ b/cmd/src/code_intel_upload.go @@ -82,7 +82,12 @@ func handleCodeIntelUpload(args []string) error { }) uploadOptions := codeintelUploadOptions(out) - uploadID, err := upload.UploadIndex(ctx, codeintelUploadFlags.file, client, uploadOptions) + var uploadID int + if codeintelUploadFlags.gzipCompressed { + uploadID, err = UploadCompressedIndex(ctx, codeintelUploadFlags.file, client, uploadOptions, 0) + } else { + uploadID, err = UploadUncompressedIndex(ctx, codeintelUploadFlags.file, client, uploadOptions) + } if err != nil { return handleUploadError(uploadOptions.SourcegraphInstanceOptions.AccessToken, err) } diff --git a/cmd/src/code_intel_upload_flags.go b/cmd/src/code_intel_upload_flags.go index b63735944a..2a1b31c289 100644 --- a/cmd/src/code_intel_upload_flags.go +++ b/cmd/src/code_intel_upload_flags.go @@ -1,9 +1,12 @@ package main import ( + "compress/gzip" "flag" "fmt" + "io" "os" + "path" "strings" "github.com/sourcegraph/scip/bindings/go/scip" @@ -15,7 +18,8 @@ import ( ) var codeintelUploadFlags struct { - file string + file string + gzipCompressed bool // UploadRecordOptions repo string @@ -110,7 +114,7 @@ func parseAndValidateCodeIntelUploadFlags(args []string) (*output.Output, error) } if !isFlagSet(codeintelUploadFlagSet, "file") { - defaultFile, err := inferDefaultFile() + defaultFile, err := inferDefaultFile(out) if err != nil { return nil, err } @@ -131,6 +135,10 @@ func parseAndValidateCodeIntelUploadFlags(args []string) (*output.Output, error) return nil, errors.Newf("file %q does not exist", codeintelUploadFlags.file) } + if err := inferGzipFlag(); err != nil { + return nil, err + } + // Infer the remaining default arguments (may require reading from new file) if inferenceErrors := inferMissingCodeIntelUploadFlags(); len(inferenceErrors) > 0 { return nil, formatInferenceError(inferenceErrors[0]) @@ -143,6 +151,22 @@ func parseAndValidateCodeIntelUploadFlags(args []string) (*output.Output, error) return out, nil } +func inferGzipFlag() error { + if codeintelUploadFlags.gzipCompressed || path.Ext(codeintelUploadFlags.file) == ".gz" { + file, err := os.Open(codeintelUploadFlags.file) + if err != nil { + return err + } + defer file.Close() + if err := checkGzipHeader(file); err != nil { + return errors.Wrapf(err, "could not verify that %s is a valid gzip file", codeintelUploadFlags.file) + } + codeintelUploadFlags.gzipCompressed = true + } + + return nil +} + // codeintelUploadOutput returns an output object that should be used to print the progres // of requests made during this upload. If -json, -no-progress, or -trace>0 is given, // then no output object is defined. @@ -164,19 +188,40 @@ type argumentInferenceError struct { err error } -func inferDefaultFile() (string, error) { +func inferDefaultFile(out *output.Output) (string, error) { const scipFilename = "index.scip" - _, err := os.Stat(scipFilename) + const scipCompressedFilename = "index.scip.gz" - if err == nil { + hasSCIP, err := doesFileExist(scipFilename) + if err != nil { + return "", err + } + hasCompressedSCIP, err := doesFileExist(scipCompressedFilename) + if err != nil { + return "", err + } + + if !hasSCIP && !hasCompressedSCIP { + return "", formatInferenceError(argumentInferenceError{"file", errors.Newf("Unable to locate SCIP index. Checked paths: %q and %q.", scipFilename, scipCompressedFilename)}) + } else if hasCompressedSCIP { + if hasSCIP { + out.WriteLine(output.Linef(output.EmojiInfo, output.StyleBold, "Both %s and %s exist, choosing %s", scipFilename, scipCompressedFilename, scipCompressedFilename)) + } + return scipCompressedFilename, nil + } else { return scipFilename, nil } +} +func doesFileExist(filename string) (bool, error) { + info, err := os.Stat(filename) if os.IsNotExist(err) { - return "", formatInferenceError(argumentInferenceError{"file", errors.Newf("%s does not exist", scipFilename)}) + return false, nil + } else if err != nil { + return false, err + } else { + return !info.IsDir(), nil } - - return "", err } func formatInferenceError(inferenceErr argumentInferenceError) error { @@ -271,6 +316,17 @@ func readIndexerNameAndVersion(indexFile string) (string, string, error) { } defer file.Close() + var indexReader io.Reader = file + + if codeintelUploadFlags.gzipCompressed { + gzipReader, err := gzip.NewReader(file) + if err != nil { + return "", "", err + } + indexReader = gzipReader + defer gzipReader.Close() + } + var metadata *scip.Metadata visitor := scip.IndexVisitor{ @@ -280,7 +336,7 @@ func readIndexerNameAndVersion(indexFile string) (string, string, error) { } // convert file to io.Reader - if err := visitor.ParseStreaming(file); err != nil { + if err := visitor.ParseStreaming(indexReader); err != nil { return "", "", err } @@ -307,3 +363,12 @@ func validateCodeIntelUploadFlags() error { return nil } + +func checkGzipHeader(r io.Reader) error { + gz, err := gzip.NewReader(r) + if err != nil { + return err + } + defer gz.Close() + return nil +} diff --git a/cmd/src/code_intel_upload_transfer.go b/cmd/src/code_intel_upload_transfer.go new file mode 100644 index 0000000000..a6062d9cb8 --- /dev/null +++ b/cmd/src/code_intel_upload_transfer.go @@ -0,0 +1,82 @@ +package main + +import ( + "context" + "os" + + "github.com/sourcegraph/sourcegraph/lib/codeintel/upload" + "github.com/sourcegraph/sourcegraph/lib/output" +) + +func UploadUncompressedIndex(ctx context.Context, filename string, httpClient upload.Client, opts upload.UploadOptions) (int, error) { + originalReader, originalSize, err := openFileAndGetSize(filename) + if err != nil { + return 0, err + } + defer func() { + _ = originalReader.Close() + }() + + bars := []output.ProgressBar{{Label: "Compressing", Max: 1.0}} + progress, _, cleanup := logProgress( + opts.Output, + bars, + "Index compressed", + "Failed to compress index", + ) + + compressedFile, err := compressReaderToDisk(originalReader, originalSize, progress) + if err != nil { + cleanup(err) + return 0, err + } + defer func() { + _ = os.Remove(compressedFile) + }() + + compressedSize, err := getFileSize(compressedFile) + if err != nil { + cleanup(err) + return 0, err + } + + cleanup(nil) + + if opts.Output != nil { + opts.Output.WriteLine(output.Linef( + output.EmojiLightbulb, + output.StyleItalic, + "Indexed compressed (%.2fMB -> %.2fMB).", + float64(originalSize)/1000/1000, + float64(compressedSize)/1000/1000, + )) + } + + return UploadCompressedIndex(ctx, compressedFile, httpClient, opts, originalSize) +} + +func UploadCompressedIndex(ctx context.Context, compressedFile string, httpClient upload.Client, opts upload.UploadOptions, uncompressedSize int64) (int, error) { + compressedReader, compressedSize, err := openFileAndGetSize(compressedFile) + if err != nil { + // cleanup(err) + return 0, err + } + defer func() { + _ = compressedReader.Close() + }() + + if compressedSize <= opts.MaxPayloadSizeBytes { + return uploadIndex(ctx, httpClient, opts, compressedReader, compressedSize, uncompressedSize) + } + + return uploadMultipartIndex(ctx, httpClient, opts, compressedReader, compressedSize, uncompressedSize) +} + +func getFileSize(filename string) (int64, error) { + fileInfo, err := os.Stat(filename) + if err != nil { + return 1, err + } + + return fileInfo.Size(), nil +} diff --git a/cmd/src/code_intel_upload_vendored.go b/cmd/src/code_intel_upload_vendored.go new file mode 100644 index 0000000000..2cc01042a6 --- /dev/null +++ b/cmd/src/code_intel_upload_vendored.go @@ -0,0 +1,627 @@ +package main + +import ( + "bytes" + "compress/gzip" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "os" + "strconv" + "sync" + "time" + + "github.com/sourcegraph/conc/pool" + "github.com/sourcegraph/sourcegraph/lib/codeintel/upload" + "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/output" +) + +/* + NOTE: + + All the definitions below have been vendored in from the Sourcegraph repository public snapshot at + this commit: https://github.com/sourcegraph/sourcegraph-public-snapshot/commit/1af563b61442c255af7b07a526efd71b3b0bad0d + + All necessary definitions were vendored in without changes until the code built successfully. +*/ + +// uploadIndex uploads the index file described by the given options to a Sourcegraph +// instance via a single HTTP POST request. The identifier of the upload is returned +// after a successful upload. +func uploadIndex(ctx context.Context, httpClient upload.Client, opts upload.UploadOptions, r io.ReaderAt, readerLen, uncompressedSize int64) (id int, err error) { + bars := []output.ProgressBar{{Label: "Upload", Max: 1.0}} + progress, retry, complete := logProgress( + opts.Output, + bars, + "Index uploaded", + "Failed to upload index file", + ) + defer func() { complete(err) }() + + // Create a section reader that can reset our reader view for retries + reader := io.NewSectionReader(r, 0, readerLen) + + requestOptions := uploadRequestOptions{ + UploadOptions: opts, + Target: &id, + UncompressedSize: uncompressedSize, + } + err = uploadIndexFile(ctx, httpClient, opts, reader, readerLen, requestOptions, progress, retry, 0, 1) + + if progress != nil { + // Mark complete in case we debounced our last updates + progress.SetValue(0, 1) + } + + return id, err +} + +// uploadIndexFile uploads the contents available via the given reader to a +// Sourcegraph instance with the given request options.i +func uploadIndexFile(ctx context.Context, httpClient upload.Client, uploadOptions upload.UploadOptions, reader io.ReadSeeker, readerLen int64, requestOptions uploadRequestOptions, progress output.Progress, retry onRetryLogFn, barIndex int, numParts int) error { + retrier := makeRetry(uploadOptions.MaxRetries, uploadOptions.RetryInterval) + + return retrier(func(attempt int) (_ bool, err error) { + defer func() { + if err != nil && !errors.Is(err, ctx.Err()) && progress != nil { + progress.SetValue(barIndex, 0) + } + }() + + if attempt != 0 { + suffix := "" + if numParts != 1 { + suffix = fmt.Sprintf(" %d of %d", barIndex+1, numParts) + } + + if progress != nil { + progress.SetValue(barIndex, 0) + } + progress = retry(fmt.Sprintf("Failed to upload index file%s (will retry; attempt #%d)", suffix, attempt)) + } + + // Create fresh reader on each attempt + reader.Seek(0, io.SeekStart) + + // Report upload progress as writes occur + requestOptions.Payload = newProgressCallbackReader(reader, readerLen, progress, barIndex) + + // Perform upload + return performUploadRequest(ctx, httpClient, requestOptions) + }) +} + +// uploadMultipartIndex uploads the index file described by the given options to a +// Sourcegraph instance over multiple HTTP POST requests. The identifier of the upload +// is returned after a successful upload. +func uploadMultipartIndex(ctx context.Context, httpClient upload.Client, opts upload.UploadOptions, r io.ReaderAt, readerLen, uncompressedSize int64) (_ int, err error) { + // Create a slice of section readers for upload part retries. + // This allows us to both read concurrently from the same reader, + // but also retry reads from arbitrary offsets. + readers := splitReader(r, readerLen, opts.MaxPayloadSizeBytes) + + // Perform initial request that gives us our upload identifier + id, err := uploadMultipartIndexInit(ctx, httpClient, opts, len(readers), uncompressedSize) + if err != nil { + return 0, err + } + + // Upload each payload of the multipart index + if err := uploadMultipartIndexParts(ctx, httpClient, opts, readers, id, readerLen); err != nil { + return 0, err + } + + // Finalize the upload and mark it as ready for processing + if err := uploadMultipartIndexFinalize(ctx, httpClient, opts, id); err != nil { + return 0, err + } + + return id, nil +} + +// uploadMultipartIndexInit performs an initial request to prepare the backend to accept upload +// parts via additional HTTP requests. This upload will be in a pending state until all upload +// parts are received and the multipart upload is finalized, or until the record is deleted by +// a background process after an expiry period. +func uploadMultipartIndexInit(ctx context.Context, httpClient upload.Client, opts upload.UploadOptions, numParts int, uncompressedSize int64) (id int, err error) { + retry, complete := logPending( + opts.Output, + "Preparing multipart upload", + "Prepared multipart upload", + "Failed to prepare multipart upload", + ) + defer func() { complete(err) }() + + err = makeRetry(opts.MaxRetries, opts.RetryInterval)(func(attempt int) (bool, error) { + if attempt != 0 { + retry(fmt.Sprintf("Failed to prepare multipart upload (will retry; attempt #%d)", attempt)) + } + + return performUploadRequest(ctx, httpClient, uploadRequestOptions{ + UploadOptions: opts, + Target: &id, + MultiPart: true, + NumParts: numParts, + UncompressedSize: uncompressedSize, + }) + }) + + return id, err +} + +// uploadMultipartIndexParts uploads the contents available via each of the given reader(s) +// to a Sourcegraph instance as part of the same multipart upload as indiciated +// by the given identifier. +func uploadMultipartIndexParts(ctx context.Context, httpClient upload.Client, opts upload.UploadOptions, readers []io.ReadSeeker, id int, readerLen int64) (err error) { + var bars []output.ProgressBar + for i := range readers { + label := fmt.Sprintf("Upload part %d of %d", i+1, len(readers)) + bars = append(bars, output.ProgressBar{Label: label, Max: 1.0}) + } + progress, retry, complete := logProgress( + opts.Output, + bars, + "Index parts uploaded", + "Failed to upload index parts", + ) + defer func() { complete(err) }() + + pool := new(pool.ErrorPool).WithFirstError().WithContext(ctx) + if opts.MaxConcurrency > 0 { + pool.WithMaxGoroutines(opts.MaxConcurrency) + } + + for i, reader := range readers { + i, reader := i, reader + + pool.Go(func(ctx context.Context) error { + // Determine size of this reader. If we're not the last reader in the slice, + // then we're the maximum payload size. Otherwise, we're whatever is left. + partReaderLen := opts.MaxPayloadSizeBytes + if i == len(readers)-1 { + partReaderLen = readerLen - int64(len(readers)-1)*opts.MaxPayloadSizeBytes + } + + requestOptions := uploadRequestOptions{ + UploadOptions: opts, + UploadID: id, + Index: i, + } + + if err := uploadIndexFile(ctx, httpClient, opts, reader, partReaderLen, requestOptions, progress, retry, i, len(readers)); err != nil { + return err + } else if progress != nil { + // Mark complete in case we debounced our last updates + progress.SetValue(i, 1) + } + return nil + }) + } + + return pool.Wait() +} + +// uploadMultipartIndexFinalize performs the request to stitch the uploaded parts together and +// mark it ready as processing in the backend. +func uploadMultipartIndexFinalize(ctx context.Context, httpClient upload.Client, opts upload.UploadOptions, id int) (err error) { + retry, complete := logPending( + opts.Output, + "Finalizing multipart upload", + "Finalized multipart upload", + "Failed to finalize multipart upload", + ) + defer func() { complete(err) }() + + return makeRetry(opts.MaxRetries, opts.RetryInterval)(func(attempt int) (bool, error) { + if attempt != 0 { + retry(fmt.Sprintf("Failed to finalize multipart upload (will retry; attempt #%d)", attempt)) + } + + return performUploadRequest(ctx, httpClient, uploadRequestOptions{ + UploadOptions: opts, + UploadID: id, + Done: true, + }) + }) +} + +// splitReader returns a slice of read-seekers into the input ReaderAt, each of max size maxPayloadSize. +// +// The sequential concatenation of each reader produces the content of the original reader. +// +// Each reader is safe to use concurrently with others. The original reader should be closed when all produced +// readers are no longer active. +func splitReader(r io.ReaderAt, n, maxPayloadSize int64) (readers []io.ReadSeeker) { + for offset := int64(0); offset < n; offset += maxPayloadSize { + readers = append(readers, io.NewSectionReader(r, offset, maxPayloadSize)) + } + + return readers +} + +// openFileAndGetSize returns an open file handle and the size on disk for the given filename. +func openFileAndGetSize(filename string) (*os.File, int64, error) { + fileInfo, err := os.Stat(filename) + if err != nil { + return nil, 0, err + } + + file, err := os.Open(filename) + if err != nil { + return nil, 0, err + } + + return file, fileInfo.Size(), err +} + +// logPending creates a pending object from the given output value and returns a retry function that +// can be called to print a message then reset the pending display, and a complete function that should +// be called once the work attached to this log call has completed. This complete function takes an error +// value that determines whether the success or failure message is displayed. If the given output value is +// nil then a no-op complete function is returned. +func logPending(out *output.Output, pendingMessage, successMessage, failureMessage string) (func(message string), func(error)) { + if out == nil { + return func(message string) {}, func(err error) {} + } + + pending := out.Pending(output.Line("", output.StylePending, pendingMessage)) + + retry := func(message string) { + pending.Destroy() + out.WriteLine(output.Line(output.EmojiFailure, output.StyleReset, message)) + pending = out.Pending(output.Line("", output.StylePending, pendingMessage)) + } + + complete := func(err error) { + if err == nil { + pending.Complete(output.Line(output.EmojiSuccess, output.StyleSuccess, successMessage)) + } else { + pending.Complete(output.Line(output.EmojiFailure, output.StyleBold, failureMessage)) + } + } + + return retry, complete +} + +type onRetryLogFn func(message string) output.Progress + +// logProgress creates and returns a progress from the given output value and bars configuration. +// This function also returns a retry function that can be called to print a message then reset the +// progress bar display, and a complete function that should be called once the work attached to +// this log call has completed. This complete function takes an error value that determines whether +// the success or failure message is displayed. If the given output value is nil then a no-op complete +// function is returned. +func logProgress(out *output.Output, bars []output.ProgressBar, successMessage, failureMessage string) (output.Progress, onRetryLogFn, func(error)) { + if out == nil { + return nil, func(message string) output.Progress { return nil }, func(err error) {} + } + + var mu sync.Mutex + progress := out.Progress(bars, nil) + + retry := func(message string) output.Progress { + mu.Lock() + defer mu.Unlock() + + progress.Destroy() + out.WriteLine(output.Line(output.EmojiFailure, output.StyleReset, message)) + progress = out.Progress(bars, nil) + return progress + } + + complete := func(err error) { + progress.Destroy() + + if err == nil { + out.WriteLine(output.Line(output.EmojiSuccess, output.StyleSuccess, successMessage)) + } else { + out.WriteLine(output.Line(output.EmojiFailure, output.StyleBold, failureMessage)) + } + } + + return progress, retry, complete +} + +type uploadRequestOptions struct { + upload.UploadOptions + + Payload io.Reader // Request payload + Target *int // Pointer to upload id decoded from resp + MultiPart bool // Whether the request is a multipart init + NumParts int // The number of upload parts + UncompressedSize int64 // The uncompressed size of the upload + UploadID int // The multipart upload ID + Index int // The index part being uploaded + Done bool // Whether the request is a multipart finalize +} + +// ErrUnauthorized occurs when the upload endpoint returns a 401 response. +var ErrUnauthorized = errors.New("unauthorized upload") + +// performUploadRequest performs an HTTP POST to the upload endpoint. The query string of the request +// is constructed from the given request options and the body of the request is the unmodified reader. +// If target is a non-nil pointer, it will be assigned the value of the upload identifier present +// in the response body. This function returns an error as well as a boolean flag indicating if the +// function can be retried. +func performUploadRequest(ctx context.Context, httpClient upload.Client, opts uploadRequestOptions) (bool, error) { + req, err := makeUploadRequest(opts) + if err != nil { + return false, err + } + + // body closed as part of performRequest + //nolint:bodyclose + resp, body, err := performRequest(ctx, req, httpClient, opts.OutputOptions.Logger) + if err != nil { + return false, err + } + + return decodeUploadPayload(resp, body, opts.Target) +} + +// makeUploadRequest creates an HTTP request to the upload endpoint described by the given arguments. +func makeUploadRequest(opts uploadRequestOptions) (*http.Request, error) { + uploadURL, err := makeUploadURL(opts) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("POST", uploadURL.String(), opts.Payload) + if err != nil { + return nil, err + } + if opts.UncompressedSize != 0 { + req.Header.Set("X-Uncompressed-Size", strconv.Itoa(int(opts.UncompressedSize))) + } + if opts.SourcegraphInstanceOptions.AccessToken != "" { + req.Header.Set("Authorization", fmt.Sprintf("token %s", opts.SourcegraphInstanceOptions.AccessToken)) + } + + for k, v := range opts.SourcegraphInstanceOptions.AdditionalHeaders { + req.Header.Set(k, v) + } + + return req, nil +} + +// performRequest performs an HTTP request and returns the HTTP response as well as the entire +// body as a byte slice. If a logger is supplied, the request, response, and response body will +// be logged. +func performRequest(ctx context.Context, req *http.Request, httpClient upload.Client, logger upload.RequestLogger) (*http.Response, []byte, error) { + started := time.Now() + if logger != nil { + logger.LogRequest(req) + } + + resp, err := httpClient.Do(req.WithContext(ctx)) + if err != nil { + return nil, nil, err + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if logger != nil { + logger.LogResponse(req, resp, body, time.Since(started)) + } + if err != nil { + return nil, nil, err + } + + return resp, body, nil +} + +// decodeUploadPayload reads the given response to an upload request. If target is a non-nil pointer, +// it will be assigned the value of the upload identifier present in the response body. This function +// returns a boolean flag indicating if the function can be retried on failure (error-dependent). +func decodeUploadPayload(resp *http.Response, body []byte, target *int) (bool, error) { + if resp.StatusCode >= 300 { + if resp.StatusCode == http.StatusUnauthorized { + return false, ErrUnauthorized + } + + suffix := "" + if !bytes.HasPrefix(bytes.TrimSpace(body), []byte{'<'}) { + suffix = fmt.Sprintf(" (%s)", bytes.TrimSpace(body)) + } + + // Do not retry client errors + return resp.StatusCode >= 500, errors.Errorf("unexpected status code: %d%s", resp.StatusCode, suffix) + } + + if target == nil { + // No target expected, skip decoding body + return false, nil + } + + var respPayload struct { + ID string `json:"id"` + } + if err := json.Unmarshal(body, &respPayload); err != nil { + return false, errors.Errorf("unexpected response (%s)", err) + } + + id, err := strconv.Atoi(respPayload.ID) + if err != nil { + return false, errors.Errorf("unexpected response (%s)", err) + } + + *target = id + return false, nil +} + +// makeUploadURL creates a URL pointing to the configured Sourcegraph upload +// endpoint with the query string described by the given request options. +func makeUploadURL(opts uploadRequestOptions) (*url.URL, error) { + qs := url.Values{} + + if opts.SourcegraphInstanceOptions.GitHubToken != "" { + qs.Add("github_token", opts.SourcegraphInstanceOptions.GitHubToken) + } + if opts.SourcegraphInstanceOptions.GitLabToken != "" { + qs.Add("gitlab_token", opts.SourcegraphInstanceOptions.GitLabToken) + } + if opts.UploadRecordOptions.Repo != "" { + qs.Add("repository", opts.UploadRecordOptions.Repo) + } + if opts.UploadRecordOptions.Commit != "" { + qs.Add("commit", opts.UploadRecordOptions.Commit) + } + if opts.UploadRecordOptions.Root != "" { + qs.Add("root", opts.UploadRecordOptions.Root) + } + if opts.UploadRecordOptions.Indexer != "" { + qs.Add("indexerName", opts.UploadRecordOptions.Indexer) + } + if opts.UploadRecordOptions.IndexerVersion != "" { + qs.Add("indexerVersion", opts.UploadRecordOptions.IndexerVersion) + } + if opts.UploadRecordOptions.AssociatedIndexID != nil { + qs.Add("associatedIndexId", formatInt(*opts.UploadRecordOptions.AssociatedIndexID)) + } + if opts.MultiPart { + qs.Add("multiPart", "true") + } + if opts.NumParts != 0 { + qs.Add("numParts", formatInt(opts.NumParts)) + } + if opts.UploadID != 0 { + qs.Add("uploadId", formatInt(opts.UploadID)) + } + if opts.UploadID != 0 && !opts.MultiPart && !opts.Done { + // Do not set an index of zero unless we're uploading a part + qs.Add("index", formatInt(opts.Index)) + } + if opts.Done { + qs.Add("done", "true") + } + + path := opts.SourcegraphInstanceOptions.Path + if path == "" { + path = "/.api/lsif/upload" + } + + parsedUrl, err := url.Parse(opts.SourcegraphInstanceOptions.SourcegraphURL + path) + if err != nil { + return nil, err + } + + parsedUrl.RawQuery = qs.Encode() + return parsedUrl, nil +} + +func formatInt(v int) string { + return strconv.FormatInt(int64(v), 10) +} + +// RetryableFunc is a function that takes the invocation index and returns an error as well as a +// boolean-value flag indicating whether or not the error is considered retryable. +type RetryableFunc = func(attempt int) (bool, error) + +// makeRetry returns a function that calls retry with the given max attempt and interval values. +func makeRetry(n int, interval time.Duration) func(f RetryableFunc) error { + return func(f RetryableFunc) error { + return retry(f, n, interval) + } +} + +// retry will re-invoke the given function until it returns a nil error value, the function returns +// a non-retryable error (as indicated by its boolean return value), or until the maximum number of +// retries have been attempted. All errors encountered will be returned. +func retry(f RetryableFunc, n int, interval time.Duration) (errs error) { + for i := 0; i <= n; i++ { + retry, err := f(i) + + errs = errors.CombineErrors(errs, err) + + if err == nil || !retry { + break + } + + time.Sleep(interval) + } + + return errs +} + +type progressCallbackReader struct { + reader io.Reader + totalRead int64 + progressCallback func(totalRead int64) +} + +var debounceInterval = time.Millisecond * 50 + +// newProgressCallbackReader returns a modified version of the given reader that +// updates the value of a progress bar on each read. If progress is nil or n is +// zero, then the reader is returned unmodified. +// +// Calls to the progress bar update will be debounced so that two updates do not +// occur within 50ms of each other. This is to reduce flicker on the screen for +// massive writes, which make progress more quickly than the screen can redraw. +func newProgressCallbackReader(r io.Reader, readerLen int64, progress output.Progress, barIndex int) io.Reader { + if progress == nil || readerLen == 0 { + return r + } + + var lastUpdated time.Time + + progressCallback := func(totalRead int64) { + if debounceInterval <= time.Since(lastUpdated) { + // Calculate progress through the reader; do not ever complete + // as we wait for the HTTP request finish the remaining small + // percentage. + + p := float64(totalRead) / float64(readerLen) + if p >= 1 { + p = 1 - 10e-3 + } + + lastUpdated = time.Now() + progress.SetValue(barIndex, p) + } + } + + return &progressCallbackReader{reader: r, progressCallback: progressCallback} +} + +func (r *progressCallbackReader) Read(p []byte) (int, error) { + n, err := r.reader.Read(p) + r.totalRead += int64(n) + r.progressCallback(r.totalRead) + return n, err +} + +// compressReaderToDisk compresses and writes the content of the given reader to a temporary +// file and returns the file's path. If the given progress object is non-nil, then the progress's +// first bar will be updated with the percentage of bytes read on each read. +func compressReaderToDisk(r io.Reader, readerLen int64, progress output.Progress) (filename string, err error) { + compressedFile, err := os.CreateTemp("", "") + if err != nil { + return "", err + } + defer func() { + if closeErr := compressedFile.Close(); err != nil { + err = errors.Append(err, closeErr) + } + }() + + gzipWriter := gzip.NewWriter(compressedFile) + defer func() { + if closeErr := gzipWriter.Close(); err != nil { + err = errors.Append(err, closeErr) + } + }() + + if progress != nil { + r = newProgressCallbackReader(r, readerLen, progress, 0) + } + if _, err := io.Copy(gzipWriter, r); err != nil { + return "", nil + } + + return compressedFile.Name(), nil +} From 2d94c4ae840ab43f13777471188b7803be15bd40 Mon Sep 17 00:00:00 2001 From: Anton Sviridov Date: Thu, 27 Feb 2025 13:01:03 +0000 Subject: [PATCH 461/647] Changelog entries for 6.1.0 (#1149) --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index f596554e7f..e197dcc4fe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,7 +11,9 @@ All notable changes to `src-cli` are documented in this file. ## Unreleased +## 6.1.0 - Support uploading GZIP compressed SCIP indexes [1146](https://github.com/sourcegraph/src-cli/pull/1146) +- Remove deprecated `lsif` subcommand, and remove LSIF->SCIP conversion support [1147](https://github.com/sourcegraph/src-cli/pull/1147) ## 6.0.1 From bd4f568112dc5fa49597205643e1495af291f9ee Mon Sep 17 00:00:00 2001 From: Marc <7050295+marcleblanc2@users.noreply.github.com> Date: Tue, 11 Mar 2025 21:32:35 -0600 Subject: [PATCH 462/647] Fixed broken link in error message in login.go (#1152) --- cmd/src/login.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/src/login.go b/cmd/src/login.go index b368f617e2..ab5a097c71 100644 --- a/cmd/src/login.go +++ b/cmd/src/login.go @@ -110,7 +110,7 @@ func loginCmd(ctx context.Context, cfg *config, client api.Client, endpointArg s printProblem(fmt.Sprintf("Error communicating with %s: %s", endpointArg, err)) } fmt.Fprintln(out, createAccessTokenMessage) - fmt.Fprintln(out, " (If you need to supply custom HTTP request headers, see information about SRC_HEADER_* and SRC_HEADERS env vars at https://github.com/sourcegraph/src-cli/blob/main/AUTH_PROXY.md.)") + fmt.Fprintln(out, " (If you need to supply custom HTTP request headers, see information about SRC_HEADER_* and SRC_HEADERS env vars at https://github.com/sourcegraph/src-cli/blob/main/AUTH_PROXY.md)") return cmderrors.ExitCode1 } From 912ba5ccb54730cdb3107d9a0b891f9f0a51f4ce Mon Sep 17 00:00:00 2001 From: Travis Lyons Date: Wed, 12 Mar 2025 10:43:59 -0400 Subject: [PATCH 463/647] fix: remove trailing period in error message test (#1153) --- cmd/src/login_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/src/login_test.go b/cmd/src/login_test.go index ce23343fce..37fbf7a703 100644 --- a/cmd/src/login_test.go +++ b/cmd/src/login_test.go @@ -67,7 +67,7 @@ func TestLogin(t *testing.T) { if err != cmderrors.ExitCode1 { t.Fatal(err) } - wantOut := "❌ Problem: Invalid access token.\n\n🛠 To fix: Create an access token by going to $ENDPOINT/user/settings/tokens, then set the following environment variables in your terminal:\n\n export SRC_ENDPOINT=$ENDPOINT\n export SRC_ACCESS_TOKEN=(your access token)\n\n To verify that it's working, run the login command again.\n\n (If you need to supply custom HTTP request headers, see information about SRC_HEADER_* and SRC_HEADERS env vars at https://github.com/sourcegraph/src-cli/blob/main/AUTH_PROXY.md.)" + wantOut := "❌ Problem: Invalid access token.\n\n🛠 To fix: Create an access token by going to $ENDPOINT/user/settings/tokens, then set the following environment variables in your terminal:\n\n export SRC_ENDPOINT=$ENDPOINT\n export SRC_ACCESS_TOKEN=(your access token)\n\n To verify that it's working, run the login command again.\n\n (If you need to supply custom HTTP request headers, see information about SRC_HEADER_* and SRC_HEADERS env vars at https://github.com/sourcegraph/src-cli/blob/main/AUTH_PROXY.md)" wantOut = strings.ReplaceAll(wantOut, "$ENDPOINT", endpoint) if out != wantOut { t.Errorf("got output %q, want %q", out, wantOut) From 8d95a1365dd423b62cae9f9bf923728210c292c2 Mon Sep 17 00:00:00 2001 From: Michael Bahr <1830132+bahrmichael@users.noreply.github.com> Date: Thu, 20 Mar 2025 16:36:47 +0100 Subject: [PATCH 464/647] feat: introduce -fail-fast flag for src batch (#1154) --- CHANGELOG.md | 4 + cmd/src/batch_common.go | 9 +++ internal/batches/executor/coordinator.go | 4 +- internal/batches/executor/coordinator_test.go | 4 +- internal/batches/executor/executor.go | 81 +++++++------------ internal/batches/executor/executor_test.go | 60 +++++++++++--- 6 files changed, 97 insertions(+), 65 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e197dcc4fe..de4ab78c04 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,10 @@ All notable changes to `src-cli` are documented in this file. ## Unreleased +### Added + +- Batch Changes: Added `-fail-fast` flag to `src batch preview` and `src batch apply` that causes execution to immediately halt on the first error instead of continuing with other repositories. This enables faster iteration on batch specs. [#1154](https://github.com/sourcegraph/src-cli/pull/1154) + ## 6.1.0 - Support uploading GZIP compressed SCIP indexes [1146](https://github.com/sourcegraph/src-cli/pull/1146) - Remove deprecated `lsif` subcommand, and remove LSIF->SCIP conversion support [1147](https://github.com/sourcegraph/src-cli/pull/1147) diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index 8171156675..157af55927 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -98,6 +98,9 @@ type batchExecuteFlags struct { skipErrors bool runAsRoot bool + // If true, fail fast on first error instead of continuing execution + failFast bool + // EXPERIMENTAL textOnly bool } @@ -164,6 +167,11 @@ func newBatchExecuteFlags(flagSet *flag.FlagSet, cacheDir, tempDir string) *batc "If true, forces all step containers to run as root.", ) + flagSet.BoolVar( + &caf.failFast, "fail-fast", false, + "Halts execution immediately upon first error instead of continuing with other tasks.", + ) + return caf } @@ -430,6 +438,7 @@ func executeBatchSpec(ctx context.Context, opts executeBatchSpecOpts) (err error TempDir: opts.flags.tempDir, GlobalEnv: os.Environ(), ForceRoot: opts.flags.runAsRoot, + FailFast: opts.flags.failFast, BinaryDiffs: ffs.BinaryDiffs, }, Logger: logManager, diff --git a/internal/batches/executor/coordinator.go b/internal/batches/executor/coordinator.go index 15855f5d37..746ea86d8e 100644 --- a/internal/batches/executor/coordinator.go +++ b/internal/batches/executor/coordinator.go @@ -14,7 +14,7 @@ import ( type taskExecutor interface { Start(context.Context, []*Task, TaskExecutionUI) - Wait(context.Context) ([]taskResult, error) + Wait() ([]taskResult, error) } // Coordinator coordinates the execution of Tasks. It makes use of an executor, @@ -182,7 +182,7 @@ func (c *Coordinator) ExecuteAndBuildSpecs(ctx context.Context, batchSpec *batch // Run executor. c.exec.Start(ctx, tasks, ui) - results, errs := c.exec.Wait(ctx) + results, errs := c.exec.Wait() // Write all step cache results to the cache. for _, res := range results { diff --git a/internal/batches/executor/coordinator_test.go b/internal/batches/executor/coordinator_test.go index 9ce252cda3..53e17c0fab 100644 --- a/internal/batches/executor/coordinator_test.go +++ b/internal/batches/executor/coordinator_test.go @@ -481,7 +481,7 @@ func assertCacheSize(t *testing.T, cache *inMemoryExecutionCache, want int) { // expectCachedResultForStep returns a function that can be used as a // startCallback on dummyExecutor to assert that the first Task has no cached results. func assertNoCachedResult(t *testing.T) func(context.Context, []*Task, TaskExecutionUI) { - return func(c context.Context, tasks []*Task, ui TaskExecutionUI) { + return func(_ context.Context, tasks []*Task, ui TaskExecutionUI) { t.Helper() task := tasks[0] @@ -562,7 +562,7 @@ func (d *dummyExecutor) Start(ctx context.Context, ts []*Task, ui TaskExecutionU // "noop noop noop", the crowd screams } -func (d *dummyExecutor) Wait(context.Context) ([]taskResult, error) { +func (d *dummyExecutor) Wait() ([]taskResult, error) { return d.results, d.waitErr } diff --git a/internal/batches/executor/executor.go b/internal/batches/executor/executor.go index 9ccb94a8fc..45fb7307c2 100644 --- a/internal/batches/executor/executor.go +++ b/internal/batches/executor/executor.go @@ -3,10 +3,9 @@ package executor import ( "context" "fmt" - "sync" "time" - "github.com/neelance/parallel" + "github.com/sourcegraph/conc/pool" "github.com/sourcegraph/sourcegraph/lib/errors" @@ -69,6 +68,7 @@ type NewExecutorOpts struct { IsRemote bool GlobalEnv []string ForceRoot bool + FailFast bool BinaryDiffs bool } @@ -76,19 +76,14 @@ type NewExecutorOpts struct { type executor struct { opts NewExecutorOpts - par *parallel.Run + workPool *pool.ResultContextPool[*taskResult] doneEnqueuing chan struct{} - - results []taskResult - resultsMu sync.Mutex } func NewExecutor(opts NewExecutorOpts) *executor { return &executor{ - opts: opts, - + opts: opts, doneEnqueuing: make(chan struct{}), - par: parallel.NewRun(opts.Parallelism), } } @@ -97,6 +92,11 @@ func NewExecutor(opts NewExecutorOpts) *executor { func (x *executor) Start(ctx context.Context, tasks []*Task, ui TaskExecutionUI) { defer func() { close(x.doneEnqueuing) }() + x.workPool = pool.NewWithResults[*taskResult]().WithMaxGoroutines(x.opts.Parallelism).WithContext(ctx) + if x.opts.FailFast { + x.workPool = x.workPool.WithCancelOnError() + } + for _, task := range tasks { select { case <-ctx.Done(): @@ -104,48 +104,33 @@ func (x *executor) Start(ctx context.Context, tasks []*Task, ui TaskExecutionUI) default: } - x.par.Acquire() - - go func(task *Task, ui TaskExecutionUI) { - defer x.par.Release() - - select { - case <-ctx.Done(): - return - default: - err := x.do(ctx, task, ui) - if err != nil { - x.par.Error(err) - } - } - }(task, ui) + x.workPool.Go(func(c context.Context) (*taskResult, error) { + return x.do(c, task, ui) + }) } } // Wait blocks until all Tasks enqueued with Start have been executed. -func (x *executor) Wait(ctx context.Context) ([]taskResult, error) { +func (x *executor) Wait() ([]taskResult, error) { <-x.doneEnqueuing - result := make(chan error, 1) - - go func(ch chan error) { - ch <- x.par.Wait() - }(result) - - select { - case <-ctx.Done(): - return x.results, ctx.Err() - case err := <-result: - close(result) - if err != nil { - return x.results, err + r, err := x.workPool.Wait() + results := make([]taskResult, len(r)) + for i, r := range r { + if r == nil { + results[i] = taskResult{ + task: nil, + stepResults: nil, + err: err, + } + } else { + results[i] = *r } } - - return x.results, nil + return results, err } -func (x *executor) do(ctx context.Context, task *Task, ui TaskExecutionUI) (err error) { +func (x *executor) do(ctx context.Context, task *Task, ui TaskExecutionUI) (result *taskResult, err error) { // Ensure that the status is updated when we're done. defer func() { ui.TaskFinished(task, err) @@ -157,7 +142,7 @@ func (x *executor) do(ctx context.Context, task *Task, ui TaskExecutionUI) (err // Let's set up our logging. l, err := x.opts.Logger.AddTask(util.SlugForPathInRepo(task.Repository.Name, task.Repository.Rev(), task.Path)) if err != nil { - return errors.Wrap(err, "creating log file") + return nil, errors.Wrap(err, "creating log file") } defer l.Close() @@ -196,18 +181,10 @@ func (x *executor) do(ctx context.Context, task *Task, ui TaskExecutionUI) (err } l.MarkErrored() } - x.addResult(task, stepResults, err) - - return err -} - -func (x *executor) addResult(task *Task, stepResults []execution.AfterStepResult, err error) { - x.resultsMu.Lock() - defer x.resultsMu.Unlock() - x.results = append(x.results, taskResult{ + return &taskResult{ task: task, stepResults: stepResults, err: err, - }) + }, err } diff --git a/internal/batches/executor/executor_test.go b/internal/batches/executor/executor_test.go index c4accc0f87..2df8c21ea0 100644 --- a/internal/batches/executor/executor_test.go +++ b/internal/batches/executor/executor_test.go @@ -78,6 +78,8 @@ func TestExecutor_Integration(t *testing.T) { wantFinishedWithErr int wantCacheCount int + + failFast bool }{ { name: "success", @@ -316,6 +318,39 @@ func TestExecutor_Integration(t *testing.T) { wantFinishedWithErr: 1, wantCacheCount: 2, }, + { + name: "fail fast mode", + archives: []mock.RepoArchive{ + {RepoName: testRepo1.Name, Commit: testRepo1.Rev(), Files: map[string]string{ + "README.md": "# Welcome to the README\n", + }}, + {RepoName: testRepo2.Name, Commit: testRepo2.Rev(), Files: map[string]string{ + "README.md": "# Sourcegraph README\n", + }}, + }, + steps: []batcheslib.Step{ + { + Run: `exit 1`, + // We must fail for the first repository, so that the other repo's work is cancelled in fail fast mode. + If: fmt.Sprintf(`${{ eq repository.name %q }}`, testRepo1.Name), + }, + { + // We introduce an artificial way for the second repository, so that it can't complete before the failure of the first one. + Run: `sleep 0.1`, + If: fmt.Sprintf(`${{ eq repository.name %q }}`, testRepo2.Name), + }, + {Run: `echo -e "foobar\n" >> README.md`}, + }, + tasks: []*Task{ + {Repository: testRepo1}, + {Repository: testRepo2}, + }, + wantErrInclude: "execution in github.com/sourcegraph/src-cli failed: run: exit 1", + // In fail fast mode, we expect that other steps are cancelled. + wantFinished: 0, + wantFinishedWithErr: 2, + failFast: true, + }, { name: "mount path", archives: []mock.RepoArchive{ @@ -376,8 +411,13 @@ func TestExecutor_Integration(t *testing.T) { // Temp dir for log files and downloaded archives testTempDir := t.TempDir() - cr, _ := workspace.NewCreator(context.Background(), "bind", testTempDir, testTempDir, images) + ctx := context.Background() + cr, _ := workspace.NewCreator(ctx, "bind", testTempDir, testTempDir, images) // Setup executor + parallelism := 0 + if tc.failFast { + parallelism = 1 + } opts := NewExecutorOpts{ Creator: cr, RepoArchiveRegistry: repozip.NewArchiveRegistry(client, testTempDir, false), @@ -385,8 +425,9 @@ func TestExecutor_Integration(t *testing.T) { EnsureImage: imageMapEnsurer(images), TempDir: testTempDir, - Parallelism: runtime.GOMAXPROCS(0), + Parallelism: runtime.GOMAXPROCS(parallelism), Timeout: tc.executorTimeout, + FailFast: tc.failFast, } if opts.Timeout == 0 { @@ -397,9 +438,9 @@ func TestExecutor_Integration(t *testing.T) { executor := NewExecutor(opts) // Run executor - executor.Start(context.Background(), tc.tasks, dummyUI) + executor.Start(ctx, tc.tasks, dummyUI) - results, err := executor.Wait(context.Background()) + results, err := executor.Wait() if tc.wantErrInclude == "" { if err != nil { t.Fatalf("execution failed: %s", err) @@ -490,10 +531,10 @@ func TestExecutor_Integration(t *testing.T) { // Make sure that all the Tasks have been updated correctly if have, want := len(dummyUI.finished), tc.wantFinished; have != want { - t.Fatalf("wrong number of finished tasks. want=%d, have=%d", want, have) + t.Fatalf("wrong number of UI finished tasks. want=%d, have=%d", want, have) } if have, want := len(dummyUI.finishedWithErr), tc.wantFinishedWithErr; have != want { - t.Fatalf("wrong number of finished-with-err tasks. want=%d, have=%d", want, have) + t.Fatalf("wrong number of UI finished-with-err tasks. want=%d, have=%d", want, have) } }) } @@ -797,7 +838,8 @@ func testExecuteTasks(t *testing.T, tasks []*Task, archives ...mock.RepoArchive) } } - cr, _ := workspace.NewCreator(context.Background(), "bind", testTempDir, testTempDir, images) + ctx := context.Background() + cr, _ := workspace.NewCreator(ctx, "bind", testTempDir, testTempDir, images) // Setup executor executor := NewExecutor(NewExecutorOpts{ Creator: cr, @@ -810,8 +852,8 @@ func testExecuteTasks(t *testing.T, tasks []*Task, archives ...mock.RepoArchive) Timeout: 30 * time.Second, }) - executor.Start(context.Background(), tasks, newDummyTaskExecutionUI()) - return executor.Wait(context.Background()) + executor.Start(ctx, tasks, newDummyTaskExecutionUI()) + return executor.Wait() } func imageMapEnsurer(m map[string]docker.Image) imageEnsurer { From a7dfc602cc7290887e08e59b445cbe69555842f1 Mon Sep 17 00:00:00 2001 From: Will Dollman Date: Mon, 31 Mar 2025 13:07:20 +0100 Subject: [PATCH 465/647] chore: update go to latest and patch vulnerable modules (#1155) * Update go to latest and patch vulnerable modules * More go mod updates * Fix govet errors * Bump version in changelog * Match up k8s.io module versions --- .github/workflows/go-ci.yml | 2 +- .github/workflows/go-lint.yml | 2 +- .github/workflows/goreleaser-check.yml | 2 +- .github/workflows/goreleaser.yml | 2 +- .github/workflows/scip.yml | 2 +- .tool-versions | 4 +- CHANGELOG.md | 6 + Dockerfile | 2 +- go.mod | 81 ++++++------ go.sum | 171 +++++++++++++------------ internal/scout/style/resource_table.go | 12 +- internal/scout/style/usage_table.go | 12 +- 12 files changed, 148 insertions(+), 150 deletions(-) diff --git a/.github/workflows/go-ci.yml b/.github/workflows/go-ci.yml index 5e467bcc65..5ab699bfde 100644 --- a/.github/workflows/go-ci.yml +++ b/.github/workflows/go-ci.yml @@ -11,7 +11,7 @@ jobs: go-test: strategy: matrix: - go-version: [1.23.2] + go-version: [1.24.1] os: [ubuntu-latest, macos-latest, windows-latest] runs-on: ${{ matrix.os }} steps: diff --git a/.github/workflows/go-lint.yml b/.github/workflows/go-lint.yml index 0af8fa22b4..3343e9ae8c 100644 --- a/.github/workflows/go-lint.yml +++ b/.github/workflows/go-lint.yml @@ -16,7 +16,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v5 with: - go-version: 1.23.2 + go-version: 1.24.1 - name: Enable pulling Go modules from private sourcegraph/sourcegraph run: git config --global url."https://${PRIVATE_TOKEN}@github.com/sourcegraph/".insteadOf "https://github.com/sourcegraph/" - run: ./dev/go-lint.sh diff --git a/.github/workflows/goreleaser-check.yml b/.github/workflows/goreleaser-check.yml index 59179af2e6..8ff2f3b5c9 100644 --- a/.github/workflows/goreleaser-check.yml +++ b/.github/workflows/goreleaser-check.yml @@ -19,7 +19,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v5 with: - go-version: 1.23.2 + go-version: 1.24.1 - name: Enable pulling Go modules from private sourcegraph/sourcegraph run: git config --global url."https://${PRIVATE_TOKEN}@github.com/sourcegraph/".insteadOf "https://github.com/sourcegraph/" - name: Check GoReleaser config diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index 46af514805..b4786c336c 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -181,7 +181,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v5 with: - go-version: 1.23.2 + go-version: 1.24.1 - name: Enable pulling Go modules from private sourcegraph/sourcegraph run: git config --global url."https://${PRIVATE_TOKEN}@github.com/sourcegraph/".insteadOf "https://github.com/sourcegraph/" - run: go test ./... diff --git a/.github/workflows/scip.yml b/.github/workflows/scip.yml index 24463d7dbe..88e836e774 100644 --- a/.github/workflows/scip.yml +++ b/.github/workflows/scip.yml @@ -14,7 +14,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v5 with: - go-version: 1.23.2 + go-version: 1.24.1 - name: Set directory to safe for git run: git config --global --add safe.directory $GITHUB_WORKSPACE diff --git a/.tool-versions b/.tool-versions index a184b8990c..e21aa83dff 100644 --- a/.tool-versions +++ b/.tool-versions @@ -1,3 +1,3 @@ -golang 1.23.2 -shfmt 3.8.0 +golang 1.24.1 +shfmt 3.8.0 shellcheck 0.10.0 diff --git a/CHANGELOG.md b/CHANGELOG.md index de4ab78c04..93cfa09413 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,10 +11,16 @@ All notable changes to `src-cli` are documented in this file. ## Unreleased +## 6.1.1 + ### Added - Batch Changes: Added `-fail-fast` flag to `src batch preview` and `src batch apply` that causes execution to immediately halt on the first error instead of continuing with other repositories. This enables faster iteration on batch specs. [#1154](https://github.com/sourcegraph/src-cli/pull/1154) +### Changed + +- Updated Go to 1.24.1 + ## 6.1.0 - Support uploading GZIP compressed SCIP indexes [1146](https://github.com/sourcegraph/src-cli/pull/1146) - Remove deprecated `lsif` subcommand, and remove LSIF->SCIP conversion support [1147](https://github.com/sourcegraph/src-cli/pull/1147) diff --git a/Dockerfile b/Dockerfile index 27daef0b70..e183e19702 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,7 +4,7 @@ # # Nothing fancy here: we copy in the source code and build on the Alpine Go # image. Refer to .dockerignore to get a sense of what we're not going to copy. -FROM golang:1.22.8-alpine@sha256:f56a8a4a1aea41bc4694728b69c219af1523aea15690cbbed82dc9bac81e6603 as builder +FROM golang:1.24.1-alpine@sha256:43c094ad24b6ac0546c62193baeb3e6e49ce14d3250845d166c77c25f64b0386 as builder COPY . /src WORKDIR /src diff --git a/go.mod b/go.mod index b43384406e..6c581211e3 100644 --- a/go.mod +++ b/go.mod @@ -1,8 +1,8 @@ module github.com/sourcegraph/src-cli -go 1.22 +go 1.24 -toolchain go1.22.8 +toolchain go1.24.1 require ( cloud.google.com/go/storage v1.30.1 @@ -34,21 +34,22 @@ require ( github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf github.com/sourcegraph/scip v0.3.1-0.20230627154934-45df7f6d33fc github.com/sourcegraph/sourcegraph/lib v0.0.0-20240709083501-1af563b61442 - github.com/stretchr/testify v1.8.4 - golang.org/x/net v0.33.0 - golang.org/x/sync v0.10.0 + github.com/stretchr/testify v1.9.0 + golang.org/x/net v0.38.0 + golang.org/x/sync v0.12.0 google.golang.org/api v0.132.0 - google.golang.org/protobuf v1.33.0 + google.golang.org/protobuf v1.35.1 gopkg.in/yaml.v3 v3.0.1 jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7 - k8s.io/api v0.27.1 - k8s.io/apimachinery v0.27.1 - k8s.io/client-go v0.27.1 - k8s.io/metrics v0.27.1 + k8s.io/api v0.32.3 + k8s.io/apimachinery v0.32.3 + k8s.io/client-go v0.32.3 + k8s.io/metrics v0.32.3 ) require ( - github.com/google/pprof v0.0.0-20230602150820-91b7bce49751 // indirect + github.com/fxamacker/cbor/v2 v2.7.0 // indirect + github.com/google/gnostic-models v0.6.8 // indirect github.com/google/s2a-go v0.1.4 // indirect github.com/jackc/chunkreader/v2 v2.0.1 // indirect github.com/jackc/pgconn v1.14.3 // indirect @@ -56,17 +57,16 @@ require ( github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgproto3/v2 v2.3.3 // indirect github.com/jackc/pgservicefile v0.0.0-20231201235250-de7065d80cb9 // indirect - github.com/onsi/ginkgo/v2 v2.9.7 // indirect - github.com/onsi/gomega v1.27.8 // indirect - go.uber.org/goleak v1.2.1 // indirect + github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f // indirect + github.com/x448/float16 v0.8.4 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20231016165738-49dd2c1f3d0b // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20231106174013-bbf56f31fb17 // indirect + gopkg.in/evanphx/json-patch.v4 v4.12.0 // indirect ) require ( cloud.google.com/go v0.110.9 // indirect - cloud.google.com/go/compute v1.23.2 // indirect - cloud.google.com/go/compute/metadata v0.2.4-0.20230617002413-005d2dfb6b68 // indirect + cloud.google.com/go/compute/metadata v0.3.0 // indirect cloud.google.com/go/iam v1.1.4 // indirect github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect github.com/Masterminds/goutils v1.1.1 // indirect @@ -94,23 +94,22 @@ require ( github.com/cockroachdb/redact v1.1.5 // indirect github.com/containerd/console v1.0.3 // indirect github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect - github.com/davecgh/go-spew v1.1.1 // indirect + github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/dlclark/regexp2 v1.8.0 // indirect - github.com/emicklei/go-restful/v3 v3.9.0 // indirect + github.com/emicklei/go-restful/v3 v3.11.0 // indirect github.com/envoyproxy/protoc-gen-validate v1.0.2 // indirect github.com/fatih/color v1.15.0 // indirect github.com/getsentry/sentry-go v0.27.0 // indirect github.com/ghodss/yaml v1.0.0 // indirect - github.com/go-logr/logr v1.2.4 // indirect - github.com/go-openapi/jsonpointer v0.19.6 // indirect - github.com/go-openapi/jsonreference v0.20.1 // indirect - github.com/go-openapi/swag v0.22.3 // indirect + github.com/go-logr/logr v1.4.2 // indirect + github.com/go-openapi/jsonpointer v0.21.0 // indirect + github.com/go-openapi/jsonreference v0.20.2 // indirect + github.com/go-openapi/swag v0.23.0 // indirect github.com/gofrs/flock v0.8.1 // indirect github.com/gofrs/uuid v4.2.0+incompatible // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect - github.com/golang/protobuf v1.5.3 // indirect - github.com/google/gnostic v0.5.7-v3refs // indirect + github.com/golang/protobuf v1.5.4 // indirect github.com/google/gofuzz v1.2.0 // indirect github.com/google/uuid v1.6.0 // indirect github.com/googleapis/enterprise-certificate-proxy v0.2.5 // indirect @@ -138,7 +137,7 @@ require ( github.com/microcosm-cc/bluemonday v1.0.23 // indirect github.com/mitchellh/copystructure v1.2.0 // indirect github.com/mitchellh/reflectwalk v1.0.2 // indirect - github.com/moby/spdystream v0.2.0 // indirect + github.com/moby/spdystream v0.5.0 // indirect github.com/moby/term v0.0.0-20221205130635-1aeaba878587 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect @@ -152,7 +151,7 @@ require ( github.com/olekukonko/tablewriter v0.0.5 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/pkg/profile v1.6.0 // indirect - github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect github.com/pseudomuto/protoc-gen-doc v1.5.1 // indirect github.com/pseudomuto/protokit v0.2.0 // indirect github.com/rivo/uniseg v0.4.3 // indirect @@ -162,7 +161,7 @@ require ( github.com/spf13/cobra v1.7.0 // indirect github.com/spf13/pflag v1.0.5 // indirect github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect - github.com/stretchr/objx v0.5.0 // indirect + github.com/stretchr/objx v0.5.2 // indirect github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect github.com/xeipuuv/gojsonschema v1.2.0 // indirect @@ -172,27 +171,27 @@ require ( go.uber.org/atomic v1.11.0 // indirect go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.24.0 // indirect - golang.org/x/crypto v0.31.0 // indirect - golang.org/x/mod v0.17.0 // indirect - golang.org/x/oauth2 v0.11.0 // indirect - golang.org/x/sys v0.28.0 // indirect - golang.org/x/term v0.27.0 // indirect - golang.org/x/text v0.21.0 // indirect - golang.org/x/time v0.3.0 // indirect - golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d // indirect + golang.org/x/crypto v0.36.0 // indirect + golang.org/x/mod v0.21.0 // indirect + golang.org/x/oauth2 v0.28.0 // indirect + golang.org/x/sys v0.31.0 // indirect + golang.org/x/term v0.30.0 // indirect + golang.org/x/text v0.23.0 // indirect + golang.org/x/time v0.7.0 // indirect + golang.org/x/tools v0.26.0 // indirect golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 // indirect google.golang.org/appengine v1.6.7 // indirect google.golang.org/genproto v0.0.0-20231030173426-d783a09b4405 // indirect google.golang.org/grpc v1.59.0 // indirect gopkg.in/inf.v0 v0.9.1 // direct gopkg.in/yaml.v2 v2.4.0 // indirect - k8s.io/klog/v2 v2.90.1 // indirect - k8s.io/kube-openapi v0.0.0-20230308215209-15aac26d736a // indirect - k8s.io/utils v0.0.0-20230209194617-a36077c30491 // indirect + k8s.io/klog/v2 v2.130.1 // indirect + k8s.io/kube-openapi v0.0.0-20241105132330-32ad38e42d3f // indirect + k8s.io/utils v0.0.0-20241104100929-3ea5e8cea738 // indirect mvdan.cc/gofumpt v0.4.0 // indirect - sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd // indirect - sigs.k8s.io/structured-merge-diff/v4 v4.2.3 // indirect - sigs.k8s.io/yaml v1.3.0 // indirect + sigs.k8s.io/json v0.0.0-20241010143419-9aa6b5e7a4b3 // indirect + sigs.k8s.io/structured-merge-diff/v4 v4.4.2 // indirect + sigs.k8s.io/yaml v1.4.0 // indirect ) // See: https://github.com/ghodss/yaml/pull/65 diff --git a/go.sum b/go.sum index 7e918c201e..7680436b99 100644 --- a/go.sum +++ b/go.sum @@ -2,10 +2,8 @@ cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMT cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.110.9 h1:e7ITSqGFFk4rbz/JFIqZh3G4VEHguhAL4BQcFlWtU68= cloud.google.com/go v0.110.9/go.mod h1:rpxevX/0Lqvlbc88b7Sc1SPNdyK1riNBTUU6JXhYNpM= -cloud.google.com/go/compute v1.23.2 h1:nWEMDhgbBkBJjfpVySqU4jgWdc22PLR0o4vEexZHers= -cloud.google.com/go/compute v1.23.2/go.mod h1:JJ0atRC0J/oWYiiVBmsSsrRnh92DhZPG4hFDcR04Rns= -cloud.google.com/go/compute/metadata v0.2.4-0.20230617002413-005d2dfb6b68 h1:aRVqY1p2IJaBGStWMsQMpkAa83cPkCDLl80eOj0Rbz4= -cloud.google.com/go/compute/metadata v0.2.4-0.20230617002413-005d2dfb6b68/go.mod h1:1a3eRNYX12fs5UABBIXS8HXVvQbX9hRB/RkEBPORpe8= +cloud.google.com/go/compute/metadata v0.3.0 h1:Tz+eQXMEqDIKRsmY3cHTL6FVaynIjX2QxYC4trgAKZc= +cloud.google.com/go/compute/metadata v0.3.0/go.mod h1:zFmK7XCadkQkj6TtorcaGlCW1hT1fIilQDwofLpJ20k= cloud.google.com/go/iam v1.1.4 h1:K6n/GZHFTtEoKT5aUG3l9diPi0VduZNQ1PfdnpkkIFk= cloud.google.com/go/iam v1.1.4/go.mod h1:l/rg8l1AaA+VFMho/HYx2Vv6xinPSLMF8qfhRPIZ0L8= cloud.google.com/go/storage v1.30.1 h1:uOdMxAs8HExqBlnLtnQyP0YkvbiDpdGShGKtx6U/oNM= @@ -103,8 +101,9 @@ github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ3 github.com/creack/pty v1.1.18 h1:n56/Zwd5o6whRC5PMGretI4IdRLlmBXYNjScPaBgsbY= github.com/creack/pty v1.1.18/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/derision-test/glock v1.0.0 h1:b6sViZG+Cm6QtdpqbfWEjaBVbzNPntIS4GzsxpS+CmM= github.com/derision-test/glock v1.0.0/go.mod h1:jKtLdBMrF+XQatqvg46wiWdDfDSSDjdhO4dOM2FX9H4= github.com/dineshappavoo/basex v0.0.0-20170425072625-481a6f6dc663 h1:fctNkSsavbXpt8geFWZb8n+noCqS8MrOXRJ/YfdZ2dQ= @@ -112,11 +111,10 @@ github.com/dineshappavoo/basex v0.0.0-20170425072625-481a6f6dc663/go.mod h1:Kad2 github.com/dlclark/regexp2 v1.4.0/go.mod h1:2pZnwuY/m+8K6iRw6wQdMtk+rH5tNGR1i55kozfMjCc= github.com/dlclark/regexp2 v1.8.0 h1:rJD5HeGIT/2b5CDk63FVCwZA3qgYElfg+oQK7uH5pfE= github.com/dlclark/regexp2 v1.8.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= -github.com/docopt/docopt-go v0.0.0-20180111231733-ee0de3bc6815/go.mod h1:WwZ+bS3ebgob9U8Nd0kOddGdZWjyMGR8Wziv+TBNwSE= github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= -github.com/emicklei/go-restful/v3 v3.9.0 h1:XwGDlfxEnQZzuopoqxwSEllNcCOM9DhhFyhFIIGKwxE= -github.com/emicklei/go-restful/v3 v3.9.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= +github.com/emicklei/go-restful/v3 v3.11.0 h1:rAQeMHw1c7zTmncogyy8VvRZwtkmkZ4FxERmMY4rD+g= +github.com/emicklei/go-restful/v3 v3.11.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= @@ -131,21 +129,24 @@ github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs= github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw= github.com/frankban/quicktest v1.14.3 h1:FJKSZTDHjyhriyC81FLQ0LY93eSai0ZyR/ZIkd3ZUKE= github.com/frankban/quicktest v1.14.3/go.mod h1:mgiwOwqx65TmIk1wJ6Q7wvnVMocbUorkibMOrVTHZps= +github.com/fxamacker/cbor/v2 v2.7.0 h1:iM5WgngdRBanHcxugY4JySA0nk1wZorNOpTgCMedv5E= +github.com/fxamacker/cbor/v2 v2.7.0/go.mod h1:pxXPTn3joSm21Gbwsv0w9OSA2y1HFR9qXEeXQVeNoDQ= github.com/getsentry/sentry-go v0.27.0 h1:Pv98CIbtB3LkMWmXi4Joa5OOcwbmnX88sF5qbK3r3Ps= github.com/getsentry/sentry-go v0.27.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA= github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og= -github.com/go-logr/logr v1.2.0/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -github.com/go-logr/logr v1.2.4 h1:g01GSCwiDw2xSZfjJ2/T9M+S6pFdcNtFYsp+Y43HYDQ= -github.com/go-logr/logr v1.2.4/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -github.com/go-openapi/jsonpointer v0.19.6 h1:eCs3fxoIi3Wh6vtgmLTOjdhSpiqphQ+DaPn38N2ZdrE= +github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= +github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-openapi/jsonpointer v0.19.6/go.mod h1:osyAmYz/mB/C3I+WsTTSgw1ONzaLJoLCyoi6/zppojs= -github.com/go-openapi/jsonreference v0.20.1 h1:FBLnyygC4/IZZr893oiomc9XaghoveYTrLC1F86HID8= -github.com/go-openapi/jsonreference v0.20.1/go.mod h1:Bl1zwGIM8/wsvqjsOQLJ/SH+En5Ap4rVB5KVcIDZG2k= -github.com/go-openapi/swag v0.22.3 h1:yMBqmnQ0gyZvEb/+KzuWZOXgllrXT4SADYbvDaXHv/g= +github.com/go-openapi/jsonpointer v0.21.0 h1:YgdVicSA9vH5RiHs9TZW5oyafXZFc6+2Vc1rr/O9oNQ= +github.com/go-openapi/jsonpointer v0.21.0/go.mod h1:IUyH9l/+uyhIYQ/PXVA41Rexl+kOkAPDdXEYns6fzUY= +github.com/go-openapi/jsonreference v0.20.2 h1:3sVjiK66+uXK/6oQ8xgcRKcFgQ5KXa2KvnJRumpMGbE= +github.com/go-openapi/jsonreference v0.20.2/go.mod h1:Bl1zwGIM8/wsvqjsOQLJ/SH+En5Ap4rVB5KVcIDZG2k= github.com/go-openapi/swag v0.22.3/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14= -github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 h1:tfuBGBXKqDEevZMzYi5KSi8KkcZtzBcTgAUUtapy0OI= -github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572/go.mod h1:9Pwr4B2jHnOSGXyyzV8ROjYa2ojvAY6HCGYYfMoC3Ls= +github.com/go-openapi/swag v0.23.0 h1:vsEVJDUo2hPJ2tu0/Xc+4noaxyEffXNIs3cOULZ+GrE= +github.com/go-openapi/swag v0.23.0/go.mod h1:esZ8ITTYEsH1V2trKHjAN8Ai7xHb8RV+YSZ577vPjgQ= +github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI= +github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y= github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8= github.com/gofrs/flock v0.8.1 h1:+gYjHKf32LDeiEEFhQaotPbLuUXjY5ZqxKgXy7n59aw= @@ -174,10 +175,10 @@ github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= -github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= -github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= -github.com/google/gnostic v0.5.7-v3refs h1:FhTMOKj2VhjpouxvWJAV1TL304uMlb9zcDqkl6cEI54= -github.com/google/gnostic v0.5.7-v3refs/go.mod h1:73MKFl6jIHelAJNaBGFzt3SPtZULs9dYrGFt8OiIsHQ= +github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= +github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= +github.com/google/gnostic-models v0.6.8 h1:yo/ABAfM5IMRsS1VnXjTBvUb61tFIHozhlYvRgGre9I= +github.com/google/gnostic-models v0.6.8/go.mod h1:5n7qKqH0f5wFt+aWF8CW6pZLLNOfYuF5OpfBSENuI8U= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= @@ -197,8 +198,8 @@ github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/martian/v3 v3.3.2 h1:IqNFLAmvJOgVlpdEBiQbDc2EwKW77amAycfTuWKdfvw= github.com/google/martian/v3 v3.3.2/go.mod h1:oBOf6HBosgwRXnUGWUB05QECsc6uvmMiJ3+6W4l/CUk= -github.com/google/pprof v0.0.0-20230602150820-91b7bce49751 h1:hR7/MlvK23p6+lIw9SN1TigNLn9ZnF3W4SYRKq2gAHs= -github.com/google/pprof v0.0.0-20230602150820-91b7bce49751/go.mod h1:Jh3hGz2jkYak8qXPD19ryItVnUgpgeqzdkY/D0EaeuA= +github.com/google/pprof v0.0.0-20241029153458-d1b30febd7db h1:097atOisP2aRj7vFgYQBbFN4U4JNXUNYpxael3UzMyo= +github.com/google/pprof v0.0.0-20241029153458-d1b30febd7db/go.mod h1:vavhavw2zAxS5dIdcRluK6cSGGPlZynqzFM8NdvU144= github.com/google/s2a-go v0.1.4 h1:1kZ/sQM3srePvKs3tXAvQzo66XfcReoqFpIpIccE7Oc= github.com/google/s2a-go v0.1.4/go.mod h1:Ej+mSEMGRnqRzjc7VtF+jdBwYG5fuJfiZ8ELkjEwM0A= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= @@ -210,7 +211,6 @@ github.com/googleapis/gax-go/v2 v2.12.0 h1:A+gCJKdRfqXkr+BIRGtZLibNXf0m1f9E4HG56 github.com/googleapis/gax-go/v2 v2.12.0/go.mod h1:y+aIqrI5eb1YGMVJfuV3185Ts/D7qKpsEkdD5+I6QGU= github.com/gorilla/css v1.0.0 h1:BQqNyPTi50JCFMTw/b67hByjMVXZRwGha6wxVGkeihY= github.com/gorilla/css v1.0.0/go.mod h1:Dn721qIggHpt4+EFCcTLTU/vk5ySda2ReITrtgBl60c= -github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/grafana/regexp v0.0.0-20221123153739-15dc172cd2db h1:7aN5cccjIqCLTzedH7MZzRZt5/lsAHch6Z3L2ZGn5FA= @@ -276,7 +276,6 @@ github.com/klauspost/compress v1.16.7/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQs github.com/klauspost/pgzip v1.2.5 h1:qnWYvvKqedOF2ulHpMG72XQol4ILEJ8k2wwRl/Km8oE= github.com/klauspost/pgzip v1.2.5/go.mod h1:Ch1tH69qFZu15pkjo5kYi6mth2Zzwzt50oCQKQE9RUs= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= -github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= @@ -314,8 +313,8 @@ github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa1 github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s= github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ= github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= -github.com/moby/spdystream v0.2.0 h1:cjW1zVyyoiM0T7b6UoySUFqzXMoqRckQtXwGPiBhOM8= -github.com/moby/spdystream v0.2.0/go.mod h1:f7i0iNDQJ059oMTcWxx8MA/zKFIuD/lY+0GqbN2Wy8c= +github.com/moby/spdystream v0.5.0 h1:7r0J1Si3QO/kjRitvSLVVFUjxMEb/YLj6S9FF62JBCU= +github.com/moby/spdystream v0.5.0/go.mod h1:xBAYlnt/ay+11ShkdFKNAG7LsyK/tmNBVvVOwrfMgdI= github.com/moby/term v0.0.0-20221205130635-1aeaba878587 h1:HfkjXDfhgVaN5rmueG8cL8KKeFNecRCXFhaJ2qZ5SKA= github.com/moby/term v0.0.0-20221205130635-1aeaba878587/go.mod h1:8FzsFHVUBGZdbDsJw/ot+X+d5HLUbvklYLJ9uGfcI3Y= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -339,6 +338,8 @@ github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/mwitkow/go-proto-validators v0.3.2 h1:qRlmpTzm2pstMKKzTdvwPCF5QfBNURSlAgN/R+qbKos= github.com/mwitkow/go-proto-validators v0.3.2/go.mod h1:ej0Qp0qMgHN/KtDyUt+Q1/tA7a5VarXUOUxD+oeD30w= +github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f h1:y5//uYreIhSUg3J1GEMiLbxo1LJaP8RfCpH6pymGZus= +github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f/go.mod h1:ZdcZmHo+o7JKHSa8/e818NopupXU1YMK5fe1lsApnBw= github.com/neelance/parallel v0.0.0-20160708114440-4de9ce63d14c h1:NZOii9TDGRAfCS5VM16XnF4K7afoLQmIiZX8EkKnxtE= github.com/neelance/parallel v0.0.0-20160708114440-4de9ce63d14c/go.mod h1:eTBvSIlRgLo+CNFFQRQTwUGTZOEdvXIKeZS/xG+D2yU= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= @@ -346,10 +347,10 @@ github.com/nightlyone/lockfile v1.0.0 h1:RHep2cFKK4PonZJDdEl4GmkabuhbsRMgk/k3uAm github.com/nightlyone/lockfile v1.0.0/go.mod h1:rywoIealpdNse2r832aiD9jRk8ErCatROs6LzC841CI= github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec= github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY= -github.com/onsi/ginkgo/v2 v2.9.7 h1:06xGQy5www2oN160RtEZoTvnP2sPhEfePYmCDc2szss= -github.com/onsi/ginkgo/v2 v2.9.7/go.mod h1:cxrmXWykAwTwhQsJOPfdIDiJ+l2RYq7U8hFU+M/1uw0= -github.com/onsi/gomega v1.27.8 h1:gegWiwZjBsf2DgiSbf5hpokZ98JVDMcWkUiigk6/KXc= -github.com/onsi/gomega v1.27.8/go.mod h1:2J8vzI/s+2shY9XHRApDkdgPo1TKT7P2u6fXeJKFnNQ= +github.com/onsi/ginkgo/v2 v2.21.0 h1:7rg/4f3rB88pb5obDgNZrNHrQ4e6WpjonchcpuBRnZM= +github.com/onsi/ginkgo/v2 v2.21.0/go.mod h1:7Du3c42kxCUegi0IImZ1wUQzMBVecgIHjR1C+NkhLQo= +github.com/onsi/gomega v1.35.1 h1:Cwbd75ZBPxFSuZ6T+rN/WCb/gOc6YgFBXLlZLhC7Ds4= +github.com/onsi/gomega v1.35.1/go.mod h1:PvZbdDc8J6XJEpDK4HCuRBm8a6Fzp9/DmhC9C7yFlog= github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4= github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8= github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 h1:KoWmjvw+nsYOo29YJK9vDA65RGE3NrOnUtO7a+RF9HU= @@ -359,8 +360,9 @@ github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/profile v1.6.0 h1:hUDfIISABYI59DyeB3OTay/HxSRwTQ8rB/H83k6r5dM= github.com/pkg/profile v1.6.0/go.mod h1:qBsxPvzyUincmltOk6iyRVxHYg4adc0OFOv72ZdLa18= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/pseudomuto/protoc-gen-doc v1.5.1 h1:Ah259kcrio7Ix1Rhb6u8FCaOkzf9qRBqXnvAufg061w= github.com/pseudomuto/protoc-gen-doc v1.5.1/go.mod h1:XpMKYg6zkcpgfpCfQ8GcWBDRtRxOmMR5w7pz4Xo+dYM= @@ -400,11 +402,11 @@ github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf h1:pvbZ0lM0XWPBqUKqFU8cmavspvIl9nulOYwdy6IFRRo= github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf/go.mod h1:RJID2RhlZKId02nZ62WenDCkgHFerpIOmW0iT7GKmXM= -github.com/stoewer/go-strcase v1.2.0/go.mod h1:IBiWB2sKIp3wVVQ3Y035++gc+knqhUQag1KpM8ahLw8= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= -github.com/stretchr/objx v0.5.0 h1:1zr/of2m5FGMsad5YfcqgdqdWrIhu+EBEJRhR1U7z/c= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= @@ -414,8 +416,10 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ github.com/stretchr/testify v1.7.4/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= -github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= -github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= +github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb h1:zGWFAtiMcyryUHoUjUJX0/lt1H2+i2Ka2n+D3DImSNo= github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= @@ -436,8 +440,8 @@ go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo= go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI= go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= -go.uber.org/goleak v1.2.1 h1:NBol2c7O1ZokfZ0LEU9K6Whx/KnwvepVetCUhtKja4A= -go.uber.org/goleak v1.2.1/go.mod h1:qlT2yGI9QafXHhZZLxlSuNsMw3FFLxBr+tBRlmO1xH4= +go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= +go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= go.uber.org/zap v1.24.0 h1:FiJd5l1UOLj0wCgbSE0rwwXHzEdAZS6hiiSnxJN/D60= @@ -447,8 +451,8 @@ golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8U golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20220314234659-1baeb1ce4c0b/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= -golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U= -golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk= +golang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34= +golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= @@ -457,8 +461,8 @@ golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.7.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/mod v0.17.0 h1:zY54UmvipHiNd+pm+m0x9KhZ9hl1/7QNMyxXbc6ICqA= -golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/mod v0.21.0 h1:vvrHzRwRfVKSiLrG+d4FMl/Qi4ukBCE6kZlTUkDYRT0= +golang.org/x/mod v0.21.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -477,14 +481,12 @@ golang.org/x/net v0.0.0-20210614182718-04defd469f4e/go.mod h1:9nx3DQGgdP8bBQD5qx golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.3.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE= -golang.org/x/net v0.26.0 h1:soB7SVo0PWrY4vPW/+ay0jKDNScG2X9wFeYlXIvJsOQ= -golang.org/x/net v0.26.0/go.mod h1:5YKkiSynbBIh3p6iOc/vibscux0x38BZDkn8sCUPxHE= -golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I= -golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4= +golang.org/x/net v0.38.0 h1:vRMAPTMaeGqVhG5QyLJHqNDwecKTomGeqbnfZyKlBI8= +golang.org/x/net v0.38.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.11.0 h1:vPL4xzxBM4niKCW6g9whtaWVXTJf1U5e4aZxxFx/gbU= -golang.org/x/oauth2 v0.11.0/go.mod h1:LdF7O/8bLR/qWK9DrpXmbHLTouvRHK0SgJl0GmDBchk= +golang.org/x/oauth2 v0.28.0 h1:CrgCKl8PPAVtLnU3c+EDw6x11699EWlsDeWNWKdIOkc= +golang.org/x/oauth2 v0.28.0/go.mod h1:onh5ek6nERTohokkhCD/y2cV4Do3fxFHFuAejCkRWT8= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -495,8 +497,8 @@ golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220819030929-7fc1605a5dde/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ= -golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sync v0.12.0 h1:MHc5BpPuC30uJk597Ri8TV3CNZcTLu6B6z4lJy+g6Jw= +golang.org/x/sync v0.12.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -518,13 +520,13 @@ golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220829200755-d48e67d00261/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA= -golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik= +golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.3.0/go.mod h1:q750SLmJuPmVoN1blW3UFBPREJfb1KmY3vwxfr+nFDA= -golang.org/x/term v0.27.0 h1:WP60Sv1nlK1T6SupCHbXzSaN0b9wUmsPoRS9b61A23Q= -golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM= +golang.org/x/term v0.30.0 h1:PQ39fJZ+mfadBm0y5WlL4vlM7Sx1Hgf13sMIY2+QS9Y= +golang.org/x/term v0.30.0/go.mod h1:NYYFdzHoI5wRh/h5tDMdMqCqPJZEuNqVR5xJLd/n67g= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= @@ -532,10 +534,10 @@ golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo= -golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ= -golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4= -golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY= +golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4= +golang.org/x/time v0.7.0 h1:ntUhktv3OPE6TgYxXWv9vKvUSJyIFJlyohwbkEwPrKQ= +golang.org/x/time v0.7.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -548,8 +550,8 @@ golang.org/x/tools v0.0.0-20200624163319-25775e59acb7/go.mod h1:EkVYQZoAsY45+roY golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.4.0/go.mod h1:UE5sM2OK9E/d67R0ANs2xJizIymRP5gJU295PvKXxjQ= -golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d h1:vU5i/LfpvrRCpgM/VPfJLg5KjxD3E+hfT1SH+d9zLwg= -golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk= +golang.org/x/tools v0.26.0 h1:v/60pFQmzmT9ExmjDv2gGIfi3OqfKoEP6I5+umXlbnQ= +golang.org/x/tools v0.26.0/go.mod h1:TPVVj70c7JJ3WCazhD8OdXcZg/og+b9+tH/KxylGwH0= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -566,7 +568,6 @@ google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoA google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= google.golang.org/genproto v0.0.0-20200513103714-09dca8ec2884/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= -google.golang.org/genproto v0.0.0-20201019141844-1ed22bb0c154/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20231030173426-d783a09b4405 h1:I6WNifs6pF9tNdSob2W24JtyxIYjzFB9qDlpUC76q+U= google.golang.org/genproto v0.0.0-20231030173426-d783a09b4405/go.mod h1:3WDQMjmJk36UQhjQ89emUzb1mdaHcPeeAh4SCBKznB4= google.golang.org/genproto/googleapis/api v0.0.0-20231016165738-49dd2c1f3d0b h1:CIC2YMXmIhYw6evmhPxBKJ4fmLbOFtXQN/GV3XOZR8k= @@ -592,13 +593,12 @@ google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzi google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGjtUeSXeh4= google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.27.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI= -google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= +google.golang.org/protobuf v1.35.1 h1:m3LfL6/Ca+fqnjnlqQXNpFPABW1UD7mjh8KO2mKFytA= +google.golang.org/protobuf v1.35.1/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= @@ -606,6 +606,8 @@ gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b/go.mod h1:Co6ibVJAznAaIkqp8 gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= +gopkg.in/evanphx/json-patch.v4 v4.12.0 h1:n6jtcsulIzXPJaxegRbvFNNrZDjbij7ny3gmSPG+6V4= +gopkg.in/evanphx/json-patch.v4 v4.12.0/go.mod h1:p8EYWUEYMpynmqDbY58zCKCFZw8pRWMG4EsWvDvM72M= gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc= gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= @@ -614,34 +616,33 @@ gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7 h1:mub0MmFLOn8XLikZOAhgLD1kXJq8jgftSrrv7m00xFo= jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7/go.mod h1:OxvTsCwKosqQ1q7B+8FwXqg4rKZ/UG9dUW+g/VL2xH4= -k8s.io/api v0.27.1 h1:Z6zUGQ1Vd10tJ+gHcNNNgkV5emCyW+v2XTmn+CLjSd0= -k8s.io/api v0.27.1/go.mod h1:z5g/BpAiD+f6AArpqNjkY+cji8ueZDU/WV1jcj5Jk4E= -k8s.io/apimachinery v0.27.1 h1:EGuZiLI95UQQcClhanryclaQE6xjg1Bts6/L3cD7zyc= -k8s.io/apimachinery v0.27.1/go.mod h1:5ikh59fK3AJ287GUvpUsryoMFtH9zj/ARfWCo3AyXTM= -k8s.io/client-go v0.27.1 h1:oXsfhW/qncM1wDmWBIuDzRHNS2tLhK3BZv512Nc59W8= -k8s.io/client-go v0.27.1/go.mod h1:f8LHMUkVb3b9N8bWturc+EDtVVVwZ7ueTVquFAJb2vA= -k8s.io/klog/v2 v2.90.1 h1:m4bYOKall2MmOiRaR1J+We67Do7vm9KiQVlT96lnHUw= -k8s.io/klog/v2 v2.90.1/go.mod h1:y1WjHnz7Dj687irZUWR/WLkLc5N1YHtjLdmgWjndZn0= -k8s.io/kube-openapi v0.0.0-20230308215209-15aac26d736a h1:gmovKNur38vgoWfGtP5QOGNOA7ki4n6qNYoFAgMlNvg= -k8s.io/kube-openapi v0.0.0-20230308215209-15aac26d736a/go.mod h1:y5VtZWM9sHHc2ZodIH/6SHzXj+TPU5USoA8lcIeKEKY= -k8s.io/metrics v0.27.1 h1:qIASSok+9dhKPrfAZmFreIdpgBgKTfXwkM9CQ+tNM90= -k8s.io/metrics v0.27.1/go.mod h1:5sYmQTC3aeL/24kkJ5fYECVuIz0xhO6oipfGJ81JC1Y= -k8s.io/utils v0.0.0-20230209194617-a36077c30491 h1:r0BAOLElQnnFhE/ApUsg3iHdVYYPBjNSSOMowRZxxsY= -k8s.io/utils v0.0.0-20230209194617-a36077c30491/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= +k8s.io/api v0.32.3 h1:Hw7KqxRusq+6QSplE3NYG4MBxZw1BZnq4aP4cJVINls= +k8s.io/api v0.32.3/go.mod h1:2wEDTXADtm/HA7CCMD8D8bK4yuBUptzaRhYcYEEYA3k= +k8s.io/apimachinery v0.32.3 h1:JmDuDarhDmA/Li7j3aPrwhpNBA94Nvk5zLeOge9HH1U= +k8s.io/apimachinery v0.32.3/go.mod h1:GpHVgxoKlTxClKcteaeuF1Ul/lDVb74KpZcxcmLDElE= +k8s.io/client-go v0.32.3 h1:RKPVltzopkSgHS7aS98QdscAgtgah/+zmpAogooIqVU= +k8s.io/client-go v0.32.3/go.mod h1:3v0+3k4IcT9bXTc4V2rt+d2ZPPG700Xy6Oi0Gdl2PaY= +k8s.io/klog/v2 v2.130.1 h1:n9Xl7H1Xvksem4KFG4PYbdQCQxqc/tTUyrgXaOhHSzk= +k8s.io/klog/v2 v2.130.1/go.mod h1:3Jpz1GvMt720eyJH1ckRHK1EDfpxISzJ7I9OYgaDtPE= +k8s.io/kube-openapi v0.0.0-20241105132330-32ad38e42d3f h1:GA7//TjRY9yWGy1poLzYYJJ4JRdzg3+O6e8I+e+8T5Y= +k8s.io/kube-openapi v0.0.0-20241105132330-32ad38e42d3f/go.mod h1:R/HEjbvWI0qdfb8viZUeVZm0X6IZnxAydC7YU42CMw4= +k8s.io/metrics v0.32.3 h1:2vsBvw0v8rIIlczZ/lZ8Kcqk9tR6Fks9h+dtFNbc2a4= +k8s.io/metrics v0.32.3/go.mod h1:9R1Wk5cb+qJpCQon9h52mgkVCcFeYxcY+YkumfwHVCU= +k8s.io/utils v0.0.0-20241104100929-3ea5e8cea738 h1:M3sRQVHv7vB20Xc2ybTt7ODCeFj6JSWYFzOFnYeS6Ro= +k8s.io/utils v0.0.0-20241104100929-3ea5e8cea738/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= mvdan.cc/gofumpt v0.4.0 h1:JVf4NN1mIpHogBj7ABpgOyZc65/UUOkKQFkoURsz4MM= mvdan.cc/gofumpt v0.4.0/go.mod h1:PljLOHDeZqgS8opHRKLzp2It2VBuSdteAgqUfzMTxlQ= pgregory.net/rapid v1.1.0 h1:CMa0sjHSru3puNx+J0MIAuiiEV4N0qj8/cMWGBBCsjw= pgregory.net/rapid v1.1.0/go.mod h1:PY5XlDGj0+V1FCq0o192FdRhpKHGTRIWBgqjDBTrq04= -sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd h1:EDPBXCAspyGV4jQlpZSudPeMmr1bNJefnuqLsRAsHZo= -sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd/go.mod h1:B8JuhiUyNFVKdsE8h686QcCxMaH6HrOAZj4vswFpcB0= -sigs.k8s.io/structured-merge-diff/v4 v4.2.3 h1:PRbqxJClWWYMNV1dhaG4NsibJbArud9kFxnAMREiWFE= -sigs.k8s.io/structured-merge-diff/v4 v4.2.3/go.mod h1:qjx8mGObPmV2aSZepjQjbmb2ihdVs8cGKBraizNC69E= -sigs.k8s.io/yaml v1.3.0 h1:a2VclLzOGrwOHDiV8EfBGhvjHvP46CtW5j6POvhYGGo= -sigs.k8s.io/yaml v1.3.0/go.mod h1:GeOyir5tyXNByN85N/dRIT9es5UQNerPYEKK56eTBm8= +sigs.k8s.io/json v0.0.0-20241010143419-9aa6b5e7a4b3 h1:/Rv+M11QRah1itp8VhT6HoVx1Ray9eB4DBr+K+/sCJ8= +sigs.k8s.io/json v0.0.0-20241010143419-9aa6b5e7a4b3/go.mod h1:18nIHnGi6636UCz6m8i4DhaJ65T6EruyzmoQqI2BVDo= +sigs.k8s.io/structured-merge-diff/v4 v4.4.2 h1:MdmvkGuXi/8io6ixD5wud3vOLwc1rj0aNqRlpuvjmwA= +sigs.k8s.io/structured-merge-diff/v4 v4.4.2/go.mod h1:N8f93tFZh9U6vpxwRArLiikrE5/2tiu1w1AGfACIGE4= +sigs.k8s.io/yaml v1.4.0 h1:Mk1wCc2gy/F0THH0TAp1QYyJNzRm2KCLy3o5ASXVI5E= +sigs.k8s.io/yaml v1.4.0/go.mod h1:Ejl7/uTz7PSA4eKMyQCUTnhZYNmLIl+5c2lQPGR2BPY= diff --git a/internal/scout/style/resource_table.go b/internal/scout/style/resource_table.go index 86f9482bb3..db5455ffdb 100644 --- a/internal/scout/style/resource_table.go +++ b/internal/scout/style/resource_table.go @@ -40,9 +40,7 @@ func (m resourceTableModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { m.table.SelectedRow()[0], )) return m, tea.Batch( - tea.Printf( - copiedMessage, - ), + tea.Printf("%s", copiedMessage), ) case "C": tmpDir := os.TempDir() @@ -55,9 +53,7 @@ func (m resourceTableModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { filePath, )) return m, tea.Batch( - tea.Printf( - savedMessage, - ), + tea.Printf("%s", savedMessage), ) } } @@ -106,14 +102,14 @@ func (m resourceTableModel) dump(rows []table.Row, filePath string) error { } } - fmt.Fprintf(tw, strings.Join(headers, "\t")+"\n") + fmt.Fprintf(tw, "%s\n", strings.Join(headers, "\t")) for _, row := range rows { values := []string{row[0], row[1], row[2], row[3], row[4]} if len(row) == 6 { values = append(values, row[5]) } - fmt.Fprintf(tw, strings.Join(values, "\t")+"\n") + fmt.Fprintf(tw, "%s\n", strings.Join(values, "\t")) } return nil } diff --git a/internal/scout/style/usage_table.go b/internal/scout/style/usage_table.go index 533cf6864e..f76ba19475 100644 --- a/internal/scout/style/usage_table.go +++ b/internal/scout/style/usage_table.go @@ -40,9 +40,7 @@ func (m usageTableModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { m.table.SelectedRow()[0], )) return m, tea.Batch( - tea.Printf( - copiedMessage, - ), + tea.Printf("%s", copiedMessage), ) case "C": tmpDir := os.TempDir() @@ -55,9 +53,7 @@ func (m usageTableModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { filePath, )) return m, tea.Batch( - tea.Printf( - savedMessage, - ), + tea.Printf("%s", savedMessage), ) } } @@ -107,14 +103,14 @@ func (m usageTableModel) dump(rows []table.Row, filePath string) error { } } - fmt.Fprintf(tw, strings.Join(headers, "\t")+"\n") + fmt.Fprintf(tw, "%s\n", strings.Join(headers, "\t")) for _, row := range rows { values := []string{row[0], row[1], row[2], row[3], row[4]} if len(row) == 7 { values = append(values, row[5]) values = append(values, row[6]) } - fmt.Fprintf(tw, strings.Join(values, "\t")+"\n") + fmt.Fprintf(tw, "%s\n", strings.Join(values, "\t")) } return nil } From 29ccb972f4232edb13737dda4dab7dc28cc0737e Mon Sep 17 00:00:00 2001 From: Travis Lyons Date: Mon, 5 May 2025 14:17:56 -0400 Subject: [PATCH 466/647] feat: Add search-jobs CLI commands for managing search jobs (#1145) * feat: Add search-jobs CLI commands for managing search jobs Add new `src search-jobs` command with subcommands to manage search jobs: - create: Create new search jobs with query validation - get: Retrieve search job details by ID - list: List search jobs with sorting and pagination - cancel: Cancel running search jobs - delete: Remove search jobs The command provides functionality to: - Format output using Go templates - Sort and filter search jobs - Track job status * feat: implement search-jobs logs command search_jobs_logs: Implement a new search-jobs subcommand to retrieve jobs logs from the configured Sourcegraph instance. search_jobs_get.go: Extract the GraphQL query logic for fetching a search job into a separate helper function to improve code organization and reusability. This change: - Creates new getSearchJob helper function that encapsulates the GraphQL query logic - Simplifies the main handler function by delegating job fetching - Maintains existing functionality while improving code structure * feat: Add search jobs results retrieval command Add new command to retrieve search job results in JSONL format with the following capabilities: - Fetch results using search job ID - Optional file output with -out flag * cleanup trailing whitespace * remove tests as they are not functionally testing production code * Fix linter issues. Add support for job id numbers (#1151) * feat: Add search jobs restart command This commit introduces the `search-jobs restart` command, enabling users to restart a search job by its ID. The command retrieves the query from the original job and creates a new search job with the same query. * (lint) removed unused testutil * refactor: Redesign search-jobs command structure with builder pattern This commit refactors the search-jobs commands to: - Implement a builder pattern for consistent command creation - Add column-based output format with customizable columns - Support JSON output format for programmatic access - Improve argument handling by using positional arguments for IDs - Separate command logic from presentation for better testability - Extract common functionality into reusable helper functions - Enhance usage documentation with better examples - Remove SearchJobID parsing functions in favor of direct ID handling * refactor: make search-jobs command builder methods private * (fix) do not display command success output when using -get-curl * (fix) clean up inconsistencies in usage text --------- Co-authored-by: Peter Guy --- cmd/src/main.go | 1 + cmd/src/search_jobs.go | 297 +++++++++++++++++++++++++++++++++ cmd/src/search_jobs_cancel.go | 78 +++++++++ cmd/src/search_jobs_create.go | 101 +++++++++++ cmd/src/search_jobs_delete.go | 77 +++++++++ cmd/src/search_jobs_get.go | 79 +++++++++ cmd/src/search_jobs_list.go | 128 ++++++++++++++ cmd/src/search_jobs_logs.go | 104 ++++++++++++ cmd/src/search_jobs_restart.go | 71 ++++++++ cmd/src/search_jobs_results.go | 106 ++++++++++++ internal/api/flags.go | 7 + 11 files changed, 1049 insertions(+) create mode 100644 cmd/src/search_jobs.go create mode 100644 cmd/src/search_jobs_cancel.go create mode 100644 cmd/src/search_jobs_create.go create mode 100644 cmd/src/search_jobs_delete.go create mode 100644 cmd/src/search_jobs_get.go create mode 100644 cmd/src/search_jobs_list.go create mode 100644 cmd/src/search_jobs_logs.go create mode 100644 cmd/src/search_jobs_restart.go create mode 100644 cmd/src/search_jobs_results.go diff --git a/cmd/src/main.go b/cmd/src/main.go index 06feaa5ac0..38c63afa45 100644 --- a/cmd/src/main.go +++ b/cmd/src/main.go @@ -60,6 +60,7 @@ The commands are: repos,repo manages repositories sbom manages SBOM (Software Bill of Materials) data search search for results on Sourcegraph + search-jobs manages search jobs serve-git serves your local git repositories over HTTP for Sourcegraph to pull users,user manages users codeowners manages code ownership information diff --git a/cmd/src/search_jobs.go b/cmd/src/search_jobs.go new file mode 100644 index 0000000000..d821386161 --- /dev/null +++ b/cmd/src/search_jobs.go @@ -0,0 +1,297 @@ +package main + +import ( + "encoding/json" + "flag" + "fmt" + "strings" + + "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/cmderrors" +) + +// searchJobFragment is a GraphQL fragment that defines the fields to be queried +// for a SearchJob. It includes the job's ID, query, state, creator information, +// timestamps, URLs, and repository statistics. +const searchJobFragment = ` +fragment SearchJobFields on SearchJob { + id + query + state + creator { + username + } + createdAt + startedAt + finishedAt + URL + logURL + repoStats { + total + completed + failed + inProgress + } +}` + +// SearchJob represents a search job with its metadata, including the search query, +// execution state, creator information, timestamps, URLs, and repository statistics. +type SearchJob struct { + ID string + Query string + State string + Creator struct { + Username string + } + CreatedAt string + StartedAt string + FinishedAt string + URL string + LogURL string + RepoStats struct { + Total int + Completed int + Failed int + InProgress int + } +} + +// availableColumns defines the available column names for output +var availableColumns = map[string]bool{ + "id": true, + "query": true, + "state": true, + "username": true, + "createdat": true, + "startedat": true, + "finishedat": true, + "url": true, + "logurl": true, + "total": true, + "completed": true, + "failed": true, + "inprogress": true, +} + +// defaultColumns defines the default columns to display +var defaultColumns = []string{"id", "username", "state", "query"} + +// SearchJobCommandBuilder helps build search job commands with common flags and options +type SearchJobCommandBuilder struct { + Name string + Usage string + Flags *flag.FlagSet + ApiFlags *api.Flags +} + +// Global variables +var searchJobsCommands commander + +// newSearchJobCommand creates a new search job command builder +func newSearchJobCommand(name string, usage string) *SearchJobCommandBuilder { + flagSet := flag.NewFlagSet(name, flag.ExitOnError) + return &SearchJobCommandBuilder{ + Name: name, + Usage: usage, + Flags: flagSet, + ApiFlags: api.NewFlags(flagSet), + } +} + +// build creates and registers the command +func (b *SearchJobCommandBuilder) build(handlerFunc func(*flag.FlagSet, *api.Flags, []string, bool, api.Client) error) { + columnsFlag := b.Flags.String("c", strings.Join(defaultColumns, ","), + "Comma-separated list of columns to display. Available: id,query,state,username,createdat,startedat,finishedat,url,logurl,total,completed,failed,inprogress") + jsonFlag := b.Flags.Bool("json", false, "Output results as JSON for programmatic access") + + usageFunc := func() { + fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src search-jobs %s':\n", b.Name) + b.Flags.PrintDefaults() + fmt.Println(b.Usage) + } + + handler := func(args []string) error { + if err := parseSearchJobsArgs(b.Flags, args); err != nil { + return err + } + + // Parse columns + columns := parseColumns(*columnsFlag) + + client := createSearchJobsClient(b.Flags, b.ApiFlags) + + return handlerFunc(b.Flags, b.ApiFlags, columns, *jsonFlag, client) + } + + searchJobsCommands = append(searchJobsCommands, &command{ + flagSet: b.Flags, + handler: handler, + usageFunc: usageFunc, + }) +} + +// parseColumns parses and validates the columns flag +func parseColumns(columnsFlag string) []string { + if columnsFlag == "" { + return defaultColumns + } + + columns := strings.Split(columnsFlag, ",") + var validColumns []string + + for _, col := range columns { + col = strings.ToLower(strings.TrimSpace(col)) + if availableColumns[col] { + validColumns = append(validColumns, col) + } + } + + if len(validColumns) == 0 { + return defaultColumns + } + + return validColumns +} + +// createSearchJobsClient creates a reusable API client for search jobs commands +func createSearchJobsClient(out *flag.FlagSet, apiFlags *api.Flags) api.Client { + return api.NewClient(api.ClientOpts{ + Endpoint: cfg.Endpoint, + AccessToken: cfg.AccessToken, + Out: out.Output(), + Flags: apiFlags, + }) +} + +// parseSearchJobsArgs parses command arguments with the provided flag set +// and returns an error if parsing fails +func parseSearchJobsArgs(flagSet *flag.FlagSet, args []string) error { + if err := flagSet.Parse(args); err != nil { + return err + } + return nil +} + +// validateJobID validates that a job ID was provided +func validateJobID(args []string) (string, error) { + if len(args) != 1 { + return "", cmderrors.Usage("must provide a search job ID") + } + return args[0], nil +} + +// displaySearchJob formats and outputs a search job based on selected columns or JSON +func displaySearchJob(job *SearchJob, columns []string, asJSON bool) error { + if asJSON { + return outputAsJSON(job) + } + return outputAsColumns(job, columns) +} + +// displaySearchJobs formats and outputs multiple search jobs +func displaySearchJobs(jobs []SearchJob, columns []string, asJSON bool) error { + if asJSON { + return outputAsJSON(jobs) + } + + for _, job := range jobs { + if err := outputAsColumns(&job, columns); err != nil { + return err + } + } + return nil +} + +// outputAsJSON outputs data as JSON +func outputAsJSON(data interface{}) error { + jsonBytes, err := json.MarshalIndent(data, "", " ") + if err != nil { + return err + } + fmt.Println(string(jsonBytes)) + return nil +} + +// outputAsColumns outputs a search job as tab-delimited columns +func outputAsColumns(job *SearchJob, columns []string) error { + values := make([]string, 0, len(columns)) + + for _, col := range columns { + switch col { + case "id": + values = append(values, job.ID) + case "query": + values = append(values, job.Query) + case "state": + values = append(values, job.State) + case "username": + values = append(values, job.Creator.Username) + case "createdat": + values = append(values, job.CreatedAt) + case "startedat": + values = append(values, job.StartedAt) + case "finishedat": + values = append(values, job.FinishedAt) + case "url": + values = append(values, job.URL) + case "logurl": + values = append(values, job.LogURL) + case "total": + values = append(values, fmt.Sprintf("%d", job.RepoStats.Total)) + case "completed": + values = append(values, fmt.Sprintf("%d", job.RepoStats.Completed)) + case "failed": + values = append(values, fmt.Sprintf("%d", job.RepoStats.Failed)) + case "inprogress": + values = append(values, fmt.Sprintf("%d", job.RepoStats.InProgress)) + } + } + + fmt.Println(strings.Join(values, "\t")) + return nil +} + +// init registers the 'src search-jobs' command with the CLI. It provides subcommands +// for managing search jobs, including creating, listing, getting, canceling and deleting +// jobs. The command uses a flagset for parsing options and displays usage information +// when help is requested. +func init() { + usage := `'src search-jobs' is a tool that manages search jobs on a Sourcegraph instance. + + Usage: + + src search-jobs command [command options] + + The commands are: + + cancel cancels a search job by ID + create creates a search job + delete deletes a search job by ID + get gets a search job by ID + list lists search jobs + logs fetches logs for a search job by ID + restart restarts a search job by ID + results fetches results for a search job by ID + + Common options for all commands: + -c Select columns to display (e.g., -c id,query,state,username) + -json Output results in JSON format + + Use "src search-jobs [command] -h" for more information about a command. + ` + + flagSet := flag.NewFlagSet("search-jobs", flag.ExitOnError) + handler := func(args []string) error { + searchJobsCommands.run(flagSet, "src search-jobs", usage, args) + return nil + } + + commands = append(commands, &command{ + flagSet: flagSet, + aliases: []string{"search-job"}, + handler: handler, + usageFunc: func() { + fmt.Println(usage) + }, + }) +} diff --git a/cmd/src/search_jobs_cancel.go b/cmd/src/search_jobs_cancel.go new file mode 100644 index 0000000000..507cf3481f --- /dev/null +++ b/cmd/src/search_jobs_cancel.go @@ -0,0 +1,78 @@ +package main + +import ( + "context" + "flag" + "fmt" + + "github.com/sourcegraph/src-cli/internal/api" +) + +// GraphQL mutation constants +const cancelSearchJobMutation = `mutation CancelSearchJob($id: ID!) { + cancelSearchJob(id: $id) { + alwaysNil + } +}` + +// cancelSearchJob cancels a search job with the given ID +func cancelSearchJob(client api.Client, jobID string) error { + var result struct { + CancelSearchJob struct { + AlwaysNil bool + } + } + + if ok, err := client.NewRequest(cancelSearchJobMutation, map[string]interface{}{ + "id": jobID, + }).Do(context.Background(), &result); err != nil || !ok { + return err + } + + return nil +} + +// displayCancelSuccessMessage outputs a success message for the canceled job +func displayCancelSuccessMessage(out *flag.FlagSet, jobID string) { + fmt.Fprintf(out.Output(), "Search job %s canceled successfully\n", jobID) +} + +// init registers the 'cancel' subcommand for search jobs, which allows users to cancel +// a running search job by its ID. It sets up the command's flag parsing, usage information, +// and handles the GraphQL mutation to cancel the specified search job. +func init() { + usage := ` + Examples: + + Cancel a search job by ID: + + $ src search-jobs cancel U2VhcmNoSm9iOjY5 + + Arguments: + The ID of the search job to cancel. + + The cancel command stops a running search job and outputs a confirmation message. + ` + + cmd := newSearchJobCommand("cancel", usage) + + cmd.build(func(flagSet *flag.FlagSet, apiFlags *api.Flags, columns []string, asJSON bool, client api.Client) error { + + jobID, err := validateJobID(flagSet.Args()) + if err != nil { + return err + } + + if err := cancelSearchJob(client, jobID); err != nil { + return err + } + + if apiFlags.GetCurl() { + return nil + } + + displayCancelSuccessMessage(flagSet, jobID) + + return nil + }) +} diff --git a/cmd/src/search_jobs_create.go b/cmd/src/search_jobs_create.go new file mode 100644 index 0000000000..14cd564e22 --- /dev/null +++ b/cmd/src/search_jobs_create.go @@ -0,0 +1,101 @@ +package main + +import ( + "context" + "flag" + + "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/cmderrors" +) + +// GraphQL query and mutation constants +const ( + // createSearchJobQuery defines the GraphQL mutation for creating search jobs + createSearchJobQuery = `mutation CreateSearchJob($query: String!) { + createSearchJob(query: $query) { + ...SearchJobFields + } + }` + searchJobFragment + + // validateSearchJobQuery defines the GraphQL query for validating search queries + validateSearchJobQuery = `query ValidateSearchJob($query: String!) { + validateSearchJob(query: $query) { alwaysNil } + }` +) + +// validateSearchQuery validates a search query with the server +func validateSearchQuery(client api.Client, query string) error { + var validateResult struct{} + + if ok, err := client.NewRequest(validateSearchJobQuery, map[string]any{ + "query": query, + }).Do(context.Background(), &validateResult); err != nil || !ok { + return err + } + + return nil +} + +// createSearchJob creates a new search job with the given query +func createSearchJob(client api.Client, query string) (*SearchJob, error) { + var result struct { + CreateSearchJob *SearchJob `json:"createSearchJob"` + } + + if err := validateSearchQuery(client, query); err != nil { + return nil, err + } + + if ok, err := client.NewRequest(createSearchJobQuery, map[string]any{ + "query": query, + }).Do(context.Background(), &result); !ok { + return nil, err + } + + return result.CreateSearchJob, nil +} + +// init registers the "search-jobs create" subcommand. +func init() { + usage := ` + Examples: + + Create a search job: + + $ src search-jobs create "repo:^github\.com/sourcegraph/sourcegraph$ sort:indexed-desc" + + Create a search job and display specific columns: + + $ src search-jobs create "repo:sourcegraph" -c id,state,username + + Create a search job and output in JSON format: + + $ src search-jobs create "repo:sourcegraph" -json + + Available columns are: id, query, state, username, createdat, startedat, finishedat, + url, logurl, total, completed, failed, inprogress + ` + + // Use the builder pattern for command creation + cmd := newSearchJobCommand("create", usage) + + cmd.build(func(flagSet *flag.FlagSet, apiFlags *api.Flags, columns []string, asJSON bool, client api.Client) error { + + if flagSet.NArg() != 1 { + return cmderrors.Usage("must provide a query") + } + + query := flagSet.Arg(0) + + job, err := createSearchJob(client, query) + if err != nil { + return err + } + + if apiFlags.GetCurl() { + return nil + } + + return displaySearchJob(job, columns, asJSON) + }) +} diff --git a/cmd/src/search_jobs_delete.go b/cmd/src/search_jobs_delete.go new file mode 100644 index 0000000000..183ca2bf4e --- /dev/null +++ b/cmd/src/search_jobs_delete.go @@ -0,0 +1,77 @@ +package main + +import ( + "context" + "flag" + "fmt" + + "github.com/sourcegraph/src-cli/internal/api" +) + +// GraphQL mutation constants +const deleteSearchJobQuery = `mutation DeleteSearchJob($id: ID!) { + deleteSearchJob(id: $id) { + alwaysNil + } +}` + +// deleteSearchJob deletes a search job with the given ID +func deleteSearchJob(client api.Client, jobID string) error { + var result struct { + DeleteSearchJob struct { + AlwaysNil bool + } + } + + if ok, err := client.NewRequest(deleteSearchJobQuery, map[string]interface{}{ + "id": jobID, + }).Do(context.Background(), &result); err != nil || !ok { + return err + } + + return nil +} + +// displaySuccessMessage outputs a success message for the deleted job +func displaySuccessMessage(out *flag.FlagSet, jobID string) { + fmt.Fprintf(out.Output(), "Search job %s deleted successfully\n", jobID) +} + +// init registers the 'delete' subcommand for search-jobs which allows users to delete +// a search job by its ID. The command requires a search job ID to be provided via +// the -id flag and will make a GraphQL mutation to delete the specified job. +func init() { + usage := ` + Examples: + + Delete a search job by ID: + + $ src search-jobs delete U2VhcmNoSm9iOjY5 + + Arguments: + The ID of the search job to delete. + + The delete command permanently removes a search job and outputs a confirmation message. + ` + + cmd := newSearchJobCommand("delete", usage) + + cmd.build(func(flagSet *flag.FlagSet, apiFlags *api.Flags, columns []string, asJSON bool, client api.Client) error { + + jobID, err := validateJobID(flagSet.Args()) + if err != nil { + return err + } + + if err := deleteSearchJob(client, jobID); err != nil { + return err + } + + if apiFlags.GetCurl() { + return nil + } + + displaySuccessMessage(flagSet, jobID) + return nil + }) +} diff --git a/cmd/src/search_jobs_get.go b/cmd/src/search_jobs_get.go new file mode 100644 index 0000000000..e5c49aefc2 --- /dev/null +++ b/cmd/src/search_jobs_get.go @@ -0,0 +1,79 @@ +package main + +import ( + "context" + "flag" + + "github.com/sourcegraph/src-cli/internal/api" +) + +// GraphQL query constants +const getSearchJobQuery = `query SearchJob($id: ID!) { + node(id: $id) { + ... on SearchJob { + ...SearchJobFields + } + } +} +` + +// getSearchJob fetches a search job by ID +func getSearchJob(client api.Client, id string) (*SearchJob, error) { + query := getSearchJobQuery + searchJobFragment + + var result struct { + Node *SearchJob + } + + if ok, err := client.NewRequest(query, map[string]interface{}{ + "id": api.NullString(id), + }).Do(context.Background(), &result); err != nil || !ok { + return nil, err + } + + return result.Node, nil +} + +// init registers the "get" subcommand for search-jobs +func init() { + usage := ` + Examples: + + Get a search job by ID: + + $ src search-jobs get U2VhcmNoSm9iOjY5 + + Get a search job with specific columns: + + $ src search-jobs get U2VhcmNoSm9iOjY5 -c id,state,username + + Get a search job in JSON format: + + $ src search-jobs get U2VhcmNoSm9iOjY5 -json + + Available columns are: id, query, state, username, createdat, startedat, finishedat, + url, logurl, total, completed, failed, inprogress + ` + + cmd := newSearchJobCommand("get", usage) + + cmd.build(func(flagSet *flag.FlagSet, apiFlags *api.Flags, columns []string, asJSON bool, client api.Client) error { + + id, err := validateJobID(flagSet.Args()) + if err != nil { + return err + } + + job, err := getSearchJob(client, id) + if err != nil { + return err + } + + if apiFlags.GetCurl() { + return nil + } + + // Display the job with selected columns or as JSON + return displaySearchJob(job, columns, asJSON) + }) +} diff --git a/cmd/src/search_jobs_list.go b/cmd/src/search_jobs_list.go new file mode 100644 index 0000000000..608bf96ddc --- /dev/null +++ b/cmd/src/search_jobs_list.go @@ -0,0 +1,128 @@ +package main + +import ( + "context" + "flag" + "fmt" + + "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/cmderrors" +) + +// GraphQL query constants +const listSearchJobsQuery = `query SearchJobs($first: Int!, $descending: Boolean!, $orderBy: SearchJobsOrderBy!) { + searchJobs(first: $first, orderBy: $orderBy, descending: $descending) { + nodes { + ...SearchJobFields + } + } +} +` + +// validOrderByValues defines the allowed values for the order-by flag +var validOrderByValues = map[string]bool{ + "QUERY": true, + "CREATED_AT": true, + "STATE": true, +} + +// listSearchJobs fetches search jobs based on the provided parameters +func listSearchJobs(client api.Client, limit int, descending bool, orderBy string) ([]SearchJob, error) { + query := listSearchJobsQuery + searchJobFragment + + var result struct { + SearchJobs struct { + Nodes []SearchJob + } + } + + if ok, err := client.NewRequest(query, map[string]interface{}{ + "first": limit, + "descending": descending, + "orderBy": orderBy, + }).Do(context.Background(), &result); err != nil || !ok { + return nil, err + } + + return result.SearchJobs.Nodes, nil +} + +// validateListFlags checks if the provided flags are valid +func validateListFlags(limit int, orderBy string) error { + if limit < 1 { + return cmderrors.Usage("limit flag must be greater than 0") + } + + if !validOrderByValues[orderBy] { + return cmderrors.Usage("order-by must be one of: QUERY, CREATED_AT, STATE") + } + + return nil +} + +// init registers the "list" subcommand for search-jobs which displays search jobs +// based on the provided filtering and formatting options. +func init() { + usage := ` + Examples: + + List all search jobs: + + $ src search-jobs list + + List all search jobs in ascending order: + + $ src search-jobs list --asc + + Limit the number of search jobs returned: + + $ src search-jobs list --limit 5 + + Order search jobs by a field (must be one of: QUERY, CREATED_AT, STATE): + + $ src search-jobs list --order-by QUERY + + Select specific columns to display: + + $ src search-jobs list -c id,state,username,createdat + + Output results as JSON: + + $ src search-jobs list -json + + Combine options: + + $ src search-jobs list --limit 10 --order-by STATE --asc -c id,query,state + + Available columns are: id, query, state, username, createdat, startedat, finishedat, + url, logurl, total, completed, failed, inprogress + ` + + cmd := newSearchJobCommand("list", usage) + + limitFlag := cmd.Flags.Int("limit", 10, "Limit the number of search jobs returned") + ascFlag := cmd.Flags.Bool("asc", false, "Sort search jobs in ascending order") + orderByFlag := cmd.Flags.String("order-by", "CREATED_AT", "Sort search jobs by a sortable field (QUERY, CREATED_AT, STATE)") + + cmd.build(func(flagSet *flag.FlagSet, apiFlags *api.Flags, columns []string, asJSON bool, client api.Client) error { + + if err := validateListFlags(*limitFlag, *orderByFlag); err != nil { + return err + } + + jobs, err := listSearchJobs(client, *limitFlag, !*ascFlag, *orderByFlag) + if err != nil { + return err + } + + if len(jobs) == 0 { + return cmderrors.ExitCode(1, fmt.Errorf("no search jobs found")) + } + + if apiFlags.GetCurl() { + return nil + } + + return displaySearchJobs(jobs, columns, asJSON) + }) +} diff --git a/cmd/src/search_jobs_logs.go b/cmd/src/search_jobs_logs.go new file mode 100644 index 0000000000..2fe9b6bfee --- /dev/null +++ b/cmd/src/search_jobs_logs.go @@ -0,0 +1,104 @@ +package main + +import ( + "flag" + "fmt" + "io" + "net/http" + "os" + + "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/cmderrors" +) + +// fetchJobLogs retrieves logs for a search job from its log URL +func fetchJobLogs(jobID string, logURL string) (io.ReadCloser, error) { + if logURL == "" { + return nil, fmt.Errorf("no logs URL found for search job %s", jobID) + } + + req, err := http.NewRequest("GET", logURL, nil) + if err != nil { + return nil, err + } + + req.Header.Add("Authorization", "token "+cfg.AccessToken) + + resp, err := http.DefaultClient.Do(req) + if err != nil { + return nil, err + } + + return resp.Body, nil +} + +func outputLogs(logs io.Reader, outputPath string) error { + if outputPath != "" { + file, err := os.Create(outputPath) + if err != nil { + return fmt.Errorf("failed to create output file: %w", err) + } + defer file.Close() + + _, err = io.Copy(file, logs) + if err != nil { + return fmt.Errorf("failed to write to output file: %w", err) + } + return nil + } + + _, err := io.Copy(os.Stdout, logs) + return err +} + +// init registers the 'logs' subcommand for search jobs, which allows users to view +// logs for a specific search job by its ID. The command requires a search job ID +// and uses the configured API client to fetch and display the logs. +func init() { + usage := ` + Examples: + + View the logs of a search job: + $ src search-jobs logs U2VhcmNoSm9iOjY5 + + Save the logs to a file: + $ src search-jobs logs U2VhcmNoSm9iOjY5 -out logs.csv + + The logs command retrieves the raw log data in CSV format. The data will be + displayed on stdout or written to the file specified with -out. + ` + + cmd := newSearchJobCommand("logs", usage) + + outFlag := cmd.Flags.String("out", "", "File path to save the logs (optional)") + + cmd.build(func(flagSet *flag.FlagSet, apiFlags *api.Flags, columns []string, asJSON bool, client api.Client) error { + if flagSet.NArg() == 0 { + return cmderrors.Usage("must provide a search job ID") + } + + jobID := flagSet.Arg(0) + + job, err := getSearchJob(client, jobID) + if err != nil { + return err + } + + if job == nil { + return fmt.Errorf("no job found with ID %s", jobID) + } + + logsData, err := fetchJobLogs(jobID, job.LogURL) + if err != nil { + return err + } + + if apiFlags.GetCurl() { + return nil + } + + defer logsData.Close() + + return outputLogs(logsData, *outFlag) + }) +} diff --git a/cmd/src/search_jobs_restart.go b/cmd/src/search_jobs_restart.go new file mode 100644 index 0000000000..a2733e18f4 --- /dev/null +++ b/cmd/src/search_jobs_restart.go @@ -0,0 +1,71 @@ +package main + +import ( + "flag" + "fmt" + + "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/cmderrors" +) + +// restartSearchJob restarts a search job with the same query as the original +func restartSearchJob(client api.Client, jobID string) (*SearchJob, error) { + originalJob, err := getSearchJob(client, jobID) + if err != nil { + return nil, err + } + + if originalJob == nil { + return nil, fmt.Errorf("no job found with ID %s", jobID) + } + + query := originalJob.Query + + return createSearchJob(client, query) +} + +// init registers the "restart" subcommand for search jobs, which allows restarting +// a search job by its ID. It sets up command-line flags for job ID and output formatting, +// validates the search job query, and creates a new search job with the same query +// as the original job. +func init() { + usage := ` + Examples: + + Restart a search job by ID: + + $ src search-jobs restart U2VhcmNoSm9iOjY5 + + Restart a search job and display specific columns: + + $ src search-jobs restart U2VhcmNoSm9iOjY5 -c id,state,query + + Restart a search job and output in JSON format: + + $ src search-jobs restart U2VhcmNoSm9iOjY5 -json + + Available columns are: id, query, state, username, createdat, startedat, finishedat, + url, logurl, total, completed, failed, inprogress + ` + + cmd := newSearchJobCommand("restart", usage) + + cmd.build(func(flagSet *flag.FlagSet, apiFlags *api.Flags, columns []string, asJSON bool, client api.Client) error { + if flagSet.NArg() != 1 { + return cmderrors.Usage("must provide a job ID") + } + jobID := flagSet.Arg(0) + + newJob, err := restartSearchJob(client, jobID) + + if err != nil { + return err + } + + if apiFlags.GetCurl() { + return nil + } + + return displaySearchJob(newJob, columns, asJSON) + }) +} diff --git a/cmd/src/search_jobs_results.go b/cmd/src/search_jobs_results.go new file mode 100644 index 0000000000..2e45f8219f --- /dev/null +++ b/cmd/src/search_jobs_results.go @@ -0,0 +1,106 @@ +package main + +import ( + "flag" + "fmt" + "io" + "net/http" + "os" + + "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/cmderrors" +) + +// fetchJobResults retrieves results for a search job from its results URL +func fetchJobResults(jobID string, resultsURL string) (io.ReadCloser, error) { + if resultsURL == "" { + return nil, fmt.Errorf("no results URL found for search job %s", jobID) + } + + req, err := http.NewRequest("GET", resultsURL, nil) + if err != nil { + return nil, err + } + + req.Header.Add("Authorization", "token "+cfg.AccessToken) + + resp, err := http.DefaultClient.Do(req) + if err != nil { + return nil, err + } + + return resp.Body, nil +} + +// outputResults writes results to either a file or stdout +func outputResults(results io.Reader, outputPath string) error { + if outputPath != "" { + + file, err := os.Create(outputPath) + if err != nil { + return fmt.Errorf("failed to create output file: %w", err) + } + defer file.Close() + + _, err = io.Copy(file, results) + if err != nil { + return fmt.Errorf("failed to write to output file: %w", err) + } + return nil + } + + _, err := io.Copy(os.Stdout, results) + return err +} + +// init registers the "results" subcommand for search jobs, which allows users to view +// results for a specific search job by its ID. The command requires a search job ID +// and uses the configured API client to fetch and display the results. +func init() { + usage := ` + Examples: + + Get the results of a search job: + $ src search-jobs results U2VhcmNoSm9iOjY5 + + Save search results to a file: + $ src search-jobs results U2VhcmNoSm9iOjY5 -out results.jsonl + + The results command retrieves the raw search results in JSON Lines format. + Each line contains a single JSON object representing a search result. The data + will be displayed on stdout or written to the file specified with -out. + ` + + cmd := newSearchJobCommand("results", usage) + + outFlag := cmd.Flags.String("out", "", "File path to save the results (optional)") + + cmd.build(func(flagSet *flag.FlagSet, apiFlags *api.Flags, columns []string, asJSON bool, client api.Client) error { + if flagSet.NArg() != 1 { + return cmderrors.Usage("must provide a search job ID") + } + jobID := flagSet.Arg(0) + + job, err := getSearchJob(client, jobID) + if err != nil { + return err + } + + if job == nil { + return fmt.Errorf("no job found with ID %s", jobID) + } + + resultsData, err := fetchJobResults(jobID, job.URL) + if err != nil { + return err + } + + if apiFlags.GetCurl() { + return nil + } + + defer resultsData.Close() + + return outputResults(resultsData, *outFlag) + }) +} diff --git a/internal/api/flags.go b/internal/api/flags.go index 5a640da86d..32a255e371 100644 --- a/internal/api/flags.go +++ b/internal/api/flags.go @@ -22,6 +22,13 @@ func (f *Flags) Trace() bool { return *(f.trace) } +func (f *Flags) GetCurl() bool { + if f.getCurl == nil { + return false + } + return *(f.getCurl) +} + func (f *Flags) UserAgentTelemetry() bool { if f.userAgentTelemetry == nil { return defaultUserAgentTelemetry() From c5bda20665e41c96dc586c7e9fe7090c77ce2aca Mon Sep 17 00:00:00 2001 From: Jacob Pleiness Date: Wed, 14 May 2025 08:59:46 -0400 Subject: [PATCH 467/647] Add 6.3.0 entry to changelog (#1160) --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 93cfa09413..db25f327fb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,10 @@ All notable changes to `src-cli` are documented in this file. ## Unreleased +## 6.3.0 + +## 6.2.0 + ## 6.1.1 ### Added From 1d87e619b4e7a710479db1096cd480b1438ff262 Mon Sep 17 00:00:00 2001 From: Jacob Pleiness Date: Wed, 14 May 2025 09:29:39 -0400 Subject: [PATCH 468/647] chore: update secrets (#1161) --- .github/workflows/goreleaser.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index b4786c336c..79c749ae43 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -124,7 +124,7 @@ jobs: with: repository: sourcegraph/homebrew-src-cli fetch-depth: 0 - token: ${{ secrets.BOT_CROSS_REPO_PAT }} + token: ${{ secrets.BOT_GITHUB_TOKEN }} - name: Copy main release formula file to versioned formula file run: cp Formula/src-cli.rb ${{ env.versioned_formula_file }} # Homebrew expects the name of the class in a versioned formula file to be of the @@ -202,7 +202,7 @@ jobs: args: release --clean --config=${{ env.config_file }} env: # Use separate access token, because we need a scope:repo token to publish the brew formula. - GITHUB_TOKEN: ${{ secrets.GH_PAT }} + GITHUB_TOKEN: ${{ secrets.BOT_GITHUB_TOKEN }} # goreleaser_post updates the symlink name to refer to the new release version. The # symlink enables users to install the latest src-cli with the versioned command: From f72ed6c0f09efc8e1c32b3d54b5d42abb41f1698 Mon Sep 17 00:00:00 2001 From: Jacob Pleiness Date: Wed, 14 May 2025 10:01:45 -0400 Subject: [PATCH 469/647] chore: update secrets v2 (#1162) --- .github/workflows/goreleaser.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index 79c749ae43..00a0e620fd 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -230,7 +230,7 @@ jobs: with: repository: sourcegraph/homebrew-src-cli fetch-depth: 0 - token: ${{ secrets.BOT_CROSS_REPO_PAT }} + token: ${{ secrets.BOT_GITHUB_TOKEN }} - name: Replace symlink run: mv ${{ env.old_symlink_name }} ${{ env.new_symlink_name }} - name: Commit result From b906d3205e4dc35c546276864a732f07b9956fc9 Mon Sep 17 00:00:00 2001 From: Jacob Pleiness Date: Wed, 14 May 2025 13:36:08 -0400 Subject: [PATCH 470/647] fix changelog formatting (#1163) --- CHANGELOG.md | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index db25f327fb..fcf21b6e87 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,7 @@ All notable changes to `src-cli` are documented in this file. - Updated Go to 1.24.1 ## 6.1.0 + - Support uploading GZIP compressed SCIP indexes [1146](https://github.com/sourcegraph/src-cli/pull/1146) - Remove deprecated `lsif` subcommand, and remove LSIF->SCIP conversion support [1147](https://github.com/sourcegraph/src-cli/pull/1147) @@ -42,6 +43,7 @@ All notable changes to `src-cli` are documented in this file. - Update x/crypto to fix reported CVE-2024-45337 ## 5.10.0 + - cody gateway benchmark changes - fix local builds for non sourcegraph team [1121](https://github.com/sourcegraph/src-cli/pull/1121) @@ -82,7 +84,7 @@ All notable changes to `src-cli` are documented in this file. ### Added -- Batch Changes: Added support for batch spec versions. Batch specs with `version: 2` will default to keyword search to resolve workspaces if the pattern type is not specified explicitly. (https://github.com/sourcegraph/sourcegraph/pull/63613) +- Batch Changes: Added support for batch spec versions. Batch specs with `version: 2` will default to keyword search to resolve workspaces if the pattern type is not specified explicitly. () ### Changed @@ -149,11 +151,13 @@ All notable changes to `src-cli` are documented in this file. ## 5.1.0 ### Added + - `src validate install` can check executor connections [#974](https://github.com/sourcegraph/src-cli/pull/974) - `src validate install` can send test SMTP message [#973](https://github.com/sourcegraph/src-cli/pull/973) - `src repos {add|update|delete}-metadata -repo-name` flag support [#977](https://github.com/sourcegraph/src-cli/pull/977) ### Changed + - Renamed `src repo {add|update|delete}-kvp` to `repo {add|update|delete}-metadata` [#972](https://github.com/sourcegraph/src-cli/pull/972) ## 5.0.3 @@ -194,7 +198,7 @@ No noteworthy changes, mechanical release to match Sourcegraph release. ### Fixed -- `src codeintel upload` will no longer overwrite the entire route supplied via `-upload-route` if SCIP data is detected. [#934](https://github.com/sourcegraph/src-cli/pull/934) +- `src codeintel upload` will no longer overwrite the entire route supplied via `-upload-route` if SCIP data is detected. [#934](https://github.com/sourcegraph/src-cli/pull/934) ## 4.4.1 @@ -240,7 +244,7 @@ No noteworthy changes, mechanical release to match Sourcegraph release. ### Added - Batch specs being run locally with `src batch preview` or `src batch apply` can now be run with the `-run-as-root` flag, which will run all step containers as root instead of the default user for the image. This is off by default. [#886](https://github.com/sourcegraph/src-cli/pull/886) -- An **experimental** set of `src snapshot` commands for generating and sharing snapshots of Sourcegraph instances, as well as testing Sourcegraph instances restored from snapshots. [#888](https://github.com/sourcegraph/src-cli/pull/888), [#889](https://github.com/sourcegraph/src-cli/pull/889), [#890](https://github.com/sourcegraph/src-cli/pull/890) +- An __experimental__ set of `src snapshot` commands for generating and sharing snapshots of Sourcegraph instances, as well as testing Sourcegraph instances restored from snapshots. [#888](https://github.com/sourcegraph/src-cli/pull/888), [#889](https://github.com/sourcegraph/src-cli/pull/889), [#890](https://github.com/sourcegraph/src-cli/pull/890) ### Changed @@ -314,7 +318,7 @@ No noteworthy changes, mechanical release to match Sourcegraph release. ### Changed -- **IMPORTANT:** Searches using the command `src search -stream` is updated to use a **new and better search result schema**, improving highlighting and accurate result counts for multiline matches. Please see the new JSON schema for results if you use the `src search -stream -json` output: [#807](https://github.com/sourcegraph/src-cli/pull/807) +- __IMPORTANT:__ Searches using the command `src search -stream` is updated to use a __new and better search result schema__, improving highlighting and accurate result counts for multiline matches. Please see the new JSON schema for results if you use the `src search -stream -json` output: [#807](https://github.com/sourcegraph/src-cli/pull/807) ### Fixed @@ -937,7 +941,7 @@ Re-release of 3.29.3 for Sourcegraph 3.30. ### Changed - `src campaign [apply|preview]` now prints more detailed information about the diffs produced in each repository when run in verbose mode with `-v`. [#390](https://github.com/sourcegraph/src-cli/pull/390) -- The dependency `go-diff` has been upgraded to 0.6.1 to include https://github.com/sourcegraph/go-diff/pull/55. +- The dependency `go-diff` has been upgraded to 0.6.1 to include . ## 3.22.2 From bd686cebdc256add110ceb79840c722befeed23d Mon Sep 17 00:00:00 2001 From: Jacob Pleiness Date: Thu, 22 May 2025 10:17:15 -0700 Subject: [PATCH 471/647] fix(rel): udpate token reference (#1166) Update GH action token reference. Previous token did not have proper scope needed for GH action ### Test plan CI --- .github/workflows/goreleaser.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index 00a0e620fd..6dee404c51 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -124,7 +124,7 @@ jobs: with: repository: sourcegraph/homebrew-src-cli fetch-depth: 0 - token: ${{ secrets.BOT_GITHUB_TOKEN }} + token: ${{ secrets.BOT_CROSS_REPO_PAT }} - name: Copy main release formula file to versioned formula file run: cp Formula/src-cli.rb ${{ env.versioned_formula_file }} # Homebrew expects the name of the class in a versioned formula file to be of the From bc9fc81e9f74abc01d19918cd9e7b14157bd148e Mon Sep 17 00:00:00 2001 From: Jacob Pleiness Date: Thu, 22 May 2025 11:44:08 -0700 Subject: [PATCH 472/647] fix(rel): udpate token references for other GH actions (#1167) Update GH token references for other GH actions ### Test plan CI --- .github/workflows/goreleaser.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index 6dee404c51..bb39f6a067 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -202,7 +202,7 @@ jobs: args: release --clean --config=${{ env.config_file }} env: # Use separate access token, because we need a scope:repo token to publish the brew formula. - GITHUB_TOKEN: ${{ secrets.BOT_GITHUB_TOKEN }} + GITHUB_TOKEN: ${{ secrets.BOT_CROSS_REPO_PAT }} # goreleaser_post updates the symlink name to refer to the new release version. The # symlink enables users to install the latest src-cli with the versioned command: @@ -230,7 +230,7 @@ jobs: with: repository: sourcegraph/homebrew-src-cli fetch-depth: 0 - token: ${{ secrets.BOT_GITHUB_TOKEN }} + token: ${{ secrets.BOT_CROSS_REPO_PAT }} - name: Replace symlink run: mv ${{ env.old_symlink_name }} ${{ env.new_symlink_name }} - name: Commit result From 82cdb4c7204282c48c017e018ee74b921c4d2608 Mon Sep 17 00:00:00 2001 From: Warren Gifford Date: Thu, 29 May 2025 12:19:25 -0700 Subject: [PATCH 473/647] release 6.4.0 changelog update (#1170) --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index fcf21b6e87..469c765686 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ All notable changes to `src-cli` are documented in this file. ## Unreleased +## 6.4.0 + ## 6.3.0 ## 6.2.0 From e9921505c3a49b95908e5a99658a8de6f9ff8ada Mon Sep 17 00:00:00 2001 From: Warren Gifford Date: Thu, 29 May 2025 16:01:00 -0700 Subject: [PATCH 474/647] add note about running sg bazel configure (#1171) --- DEVELOPMENT.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index 51b9b39d40..825427c0f5 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -83,7 +83,7 @@ We adhere to the [general Sourcegraph principles for testing](https://docs.sourc [...] ``` After updating the checksums, rerun the command to verify that the values are correct. - 4. Run `sg generate bazel` (this may not result in any changes) + 4. Run `sg generate bazel` and `sg bazel configure` (this may not result in any changes) 4. Commit the changes, and open a PR. 6. Once the version bump PR is merged and the commit is live on dotcom, check that the [curl commands in the README](README.md#installation) also fetch the new latest version. From 983280ce4bf15b75f7a685101261246c6906b8ae Mon Sep 17 00:00:00 2001 From: Marc <7050295+marcleblanc2@users.noreply.github.com> Date: Wed, 4 Jun 2025 04:18:52 -0600 Subject: [PATCH 475/647] Add image name filters to src sbom fetch command (#1172) * Added --image and --exclude-image filters to `src sbom fetch` command --- CHANGELOG.md | 4 ++++ cmd/src/sbom_fetch.go | 36 +++++++++++++++++++++++++++++++++--- cmd/src/sbom_utils.go | 40 +++++++++++++++++++++++++++++++++++++++- 3 files changed, 76 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 469c765686..74cb41e0cc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,10 @@ All notable changes to `src-cli` are documented in this file. ## Unreleased +### Added + +- SBOM support: Added `--image` and `--exclude-image` flags to `src sbom fetch` for filtering which docker images SBOMs are fetched for. Both flags support glob patterns (e.g., `frontend`, `*api*`) and comma-separated lists. The `sourcegraph/` image name prefix is optional. + ## 6.4.0 ## 6.3.0 diff --git a/cmd/src/sbom_fetch.go b/cmd/src/sbom_fetch.go index d6fa90f79a..6a8ad4aa85 100644 --- a/cmd/src/sbom_fetch.go +++ b/cmd/src/sbom_fetch.go @@ -25,13 +25,23 @@ func init() { Usage: - src sbom fetch -v + src sbom fetch -v [--image ] [--exclude-image ] Examples: - $ src sbom fetch -v 5.8.0 # Fetch all SBOMs for the 5.8.0 release + $ src sbom fetch -v 5.8.0 # Fetch all SBOMs for the 5.8.0 release - $ src sbom fetch -v 5.8.123 -internal -d /tmp/sboms # Fetch all SBOMs for the internal 5.8.123 release and store them in /tmp/sboms + $ src sbom fetch -v 5.8.0 --image frontend # Fetch SBOM only for the frontend image + + $ src sbom fetch -v 5.8.0 --image "redis*" # Fetch SBOMs for all images with names beginning with 'redis' + + $ src sbom fetch -v 5.8.0 --image "frontend,redis*" # Fetch SBOMs for frontend, and all redis images + + $ src sbom fetch -v 5.8.0 --exclude-image "sg,*redis*" # Fetch SBOMs for all images, except sg and redis + + $ src sbom fetch -v 5.8.0 --image "postgres*" --exclude-image "*exporter*" # Fetch SBOMs for all postgres images, except exporters + + $ src sbom fetch -v 5.8.123 -internal -d /tmp/sboms # Fetch all SBOMs for the internal 5.8.123 release and store them in /tmp/sboms ` flagSet := flag.NewFlagSet("fetch", flag.ExitOnError) @@ -39,6 +49,8 @@ Examples: outputDirFlag := flagSet.String("d", "sourcegraph-sboms", "The directory to store validated SBOMs in.") internalReleaseFlag := flagSet.Bool("internal", false, "Fetch SBOMs for an internal release. Defaults to false.") insecureIgnoreTransparencyLogFlag := flagSet.Bool("insecure-ignore-tlog", false, "Disable transparency log verification. Defaults to false.") + imageFlag := flagSet.String("image", "", "Filter list of image names, to only fetch SBOMs for Docker images with names matching these patterns. Supports literal names, like frontend, and glob patterns like '*postgres*'. Multiple patterns can be specified as a comma-separated list (e.g., 'frontend,*postgres-1?-*'). The 'sourcegraph/' prefix is optional. If not specified, SBOMs for all images are fetched.") + excludeImageFlag := flagSet.String("exclude-image", "", "Exclude Docker images with names matching these patterns from being fetched. Supports the same formats as --image. Takes precedence over --image filters.") handler := func(args []string) error { c := cosignConfig{ @@ -73,6 +85,24 @@ Examples: c.insecureIgnoreTransparencyLog = true } + if imageFlag != nil && *imageFlag != "" { + // Parse comma-separated patterns + patterns := strings.Split(*imageFlag, ",") + for i, pattern := range patterns { + patterns[i] = strings.TrimSpace(pattern) + } + c.imageFilters = patterns + } + + if excludeImageFlag != nil && *excludeImageFlag != "" { + // Parse comma-separated exclude patterns + patterns := strings.Split(*excludeImageFlag, ",") + for i, pattern := range patterns { + patterns[i] = strings.TrimSpace(pattern) + } + c.excludeImageFilters = patterns + } + out := output.NewOutput(flagSet.Output(), output.OutputOpts{Verbose: *verbose}) if err := verifyCosign(); err != nil { diff --git a/cmd/src/sbom_utils.go b/cmd/src/sbom_utils.go index 44e46279fa..40dae7b03e 100644 --- a/cmd/src/sbom_utils.go +++ b/cmd/src/sbom_utils.go @@ -10,6 +10,7 @@ import ( "net/http" "os/exec" "path" + "path/filepath" "regexp" "strings" "time" @@ -26,6 +27,8 @@ type cosignConfig struct { version string internalRelease bool insecureIgnoreTransparencyLog bool + imageFilters []string + excludeImageFilters []string } // TokenResponse represents the JSON response from dockerHub's token service @@ -251,7 +254,21 @@ func (c cosignConfig) getImageList() ([]string, error) { if image != "" { // Strip off a version suffix if present parts := strings.SplitN(image, ":", 2) - images = append(images, parts[0]) + imageName := parts[0] + + // If the --image arg was provided, and if the image name doesn't match any of the filters + // then skip this image + if len(c.imageFilters) > 0 && !matchesImageFilter(c.imageFilters, imageName) { + continue + } + + // If the --exclude-image arg was provided, and if the image name does match any of the filters + // then skip this image + if len(c.excludeImageFilters) > 0 && matchesImageFilter(c.excludeImageFilters, imageName) { + continue + } + + images = append(images, imageName) } } @@ -270,3 +287,24 @@ func (c *cosignConfig) getImageReleaseListURL() string { return fmt.Sprintf("%s/release/%s/%s", imageListBaseURL, c.version, imageListFilename) } } + +// matchesImageFilter checks if the image name from the list of published images +// matches any user-provided --image or --exclude-image glob patterns +// It matches against both the full image name, and the image name without the "sourcegraph/" prefix. +func matchesImageFilter(patterns []string, imageName string) bool { + for _, pattern := range patterns { + // Try matching against the full image name + if matched, _ := filepath.Match(pattern, imageName); matched { + return true + } + + // Try matching against the image name without "sourcegraph/" prefix + if strings.HasPrefix(imageName, "sourcegraph/") { + shortName := strings.TrimPrefix(imageName, "sourcegraph/") + if matched, _ := filepath.Match(pattern, shortName); matched { + return true + } + } + } + return false +} From ce9dd7869e90e32939df6ccaed48a6054913ad03 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Thu, 19 Jun 2025 19:22:00 +0200 Subject: [PATCH 476/647] chore: Remove deprecated extensions commands (#1173) Long deprecated, let's remove it to declutter. Test plan: Other commands still work locally. The deprecated `src extensions` commands have been removed. --- CHANGELOG.md | 4 + cmd/src/cmd.go | 16 -- cmd/src/doc.go | 1 - cmd/src/extensions.go | 87 -------- cmd/src/extensions_copy.go | 174 ---------------- cmd/src/extensions_delete.go | 77 ------- cmd/src/extensions_get.go | 83 -------- cmd/src/extensions_list.go | 104 ---------- cmd/src/extensions_publish.go | 318 ----------------------------- cmd/src/extensions_publish_test.go | 80 -------- cmd/src/users_prune.go | 4 +- 11 files changed, 6 insertions(+), 942 deletions(-) delete mode 100644 cmd/src/extensions.go delete mode 100644 cmd/src/extensions_copy.go delete mode 100644 cmd/src/extensions_delete.go delete mode 100644 cmd/src/extensions_get.go delete mode 100644 cmd/src/extensions_list.go delete mode 100644 cmd/src/extensions_publish.go delete mode 100644 cmd/src/extensions_publish_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 74cb41e0cc..b89490e9df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,10 @@ All notable changes to `src-cli` are documented in this file. - SBOM support: Added `--image` and `--exclude-image` flags to `src sbom fetch` for filtering which docker images SBOMs are fetched for. Both flags support glob patterns (e.g., `frontend`, `*api*`) and comma-separated lists. The `sourcegraph/` image name prefix is optional. +### Changed + +- The deprecated `src extensions` commands have been removed. + ## 6.4.0 ## 6.3.0 diff --git a/cmd/src/cmd.go b/cmd/src/cmd.go index 35cc240fac..95c16e6e0e 100644 --- a/cmd/src/cmd.go +++ b/cmd/src/cmd.go @@ -6,9 +6,6 @@ import ( "log" "os" "slices" - "strings" - - "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/cmderrors" ) @@ -128,16 +125,3 @@ func (c commander) run(flagSet *flag.FlagSet, cmdName, usageText string, args [] log.Printf("%s: unknown subcommand %q", cmdName, name) log.Fatalf("Run '%s help' for usage.", cmdName) } - -func didYouMeanOtherCommand(actual string, suggested []string) *command { - fullSuggestions := make([]string, len(suggested)) - for i, s := range suggested { - fullSuggestions[i] = "src " + s - } - msg := fmt.Sprintf("src: unknown subcommand %q\n\nDid you mean:\n\n\t%s", actual, strings.Join(fullSuggestions, "\n\t")) - return &command{ - flagSet: flag.NewFlagSet(actual, flag.ExitOnError), - handler: func(args []string) error { return errors.New(msg) }, - usageFunc: func() { log.Println(msg) }, - } -} diff --git a/cmd/src/doc.go b/cmd/src/doc.go index dc4e7a222c..0bcb7b9d1a 100644 --- a/cmd/src/doc.go +++ b/cmd/src/doc.go @@ -56,7 +56,6 @@ Examples: "": &commands, "batch": &batchCommands, "config": &configCommands, - "extensions": &extensionsCommands, "extsvc": &extsvcCommands, "code-intel": &codeintelCommands, "orgs": &orgsCommands, diff --git a/cmd/src/extensions.go b/cmd/src/extensions.go deleted file mode 100644 index 9c33ab3bc2..0000000000 --- a/cmd/src/extensions.go +++ /dev/null @@ -1,87 +0,0 @@ -package main - -import ( - "flag" - "fmt" -) - -var extensionsCommands commander - -func init() { - usage := `'src extensions' is a tool that manages extensions in the extension registry on a Sourcegraph instance. - -DEPRECATED: We're in the process of removing Sourcegraph extensions with our September release. - Learn more: https://docs.sourcegraph.com/extensions/deprecation - -Usage: - - src extensions command [command options] - -The commands are: - - copy copy an extension from Sourcegraph.com to your private extension registry - publish publish the extension in the current directory - list lists extensions - get gets an extension - delete deletes an extension - -Use "src extensions [command] -h" for more information about a command. - -Alias: "src ext" -` - - flagSet := flag.NewFlagSet("extensions", flag.ExitOnError) - handler := func(args []string) error { - extensionsCommands.run(flagSet, "src extensions", usage, args) - return nil - } - - // Register the command. - commands = append(commands, &command{ - flagSet: flagSet, - aliases: []string{"ext", "extension"}, - handler: handler, - usageFunc: func() { - fmt.Println(usage) - }, - }) -} - -const registryExtensionFragment = ` -fragment RegistryExtensionFields on RegistryExtension { - id - uuid - extensionID - name - createdAt - updatedAt - url - remoteURL - registryName - isLocal - manifest { - raw - description - bundleURL - } -} -` - -type Extension struct { - ID string - UUID string - ExtensionID string - Name string - CreatedAt string - UpdatedAt string - URL string - RemoteURL string - RegistryName string - IsLocal bool - Manifest struct { - Raw string - Title string - Description string - BundleURL string - } -} diff --git a/cmd/src/extensions_copy.go b/cmd/src/extensions_copy.go deleted file mode 100644 index 4b91cf9f62..0000000000 --- a/cmd/src/extensions_copy.go +++ /dev/null @@ -1,174 +0,0 @@ -package main - -import ( - "context" - "flag" - "fmt" - "io" - "net/http" - "strings" - - "github.com/sourcegraph/src-cli/internal/api" -) - -func withCfg(new *config, f func()) { - old := cfg - cfg = new - f() - cfg = old -} - -func init() { - usage := ` -Copy an extension from Sourcegraph.com to your private registry. -` - - flagSet := flag.NewFlagSet("copy", flag.ExitOnError) - usageFunc := func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src extensions %s':\n", flagSet.Name()) - flagSet.PrintDefaults() - fmt.Println(usage) - } - var ( - extensionIDFlag = flagSet.String("extension-id", "", `The in https://sourcegraph.com/extensions/ (e.g. sourcegraph/java)`) - currentUserFlag = flagSet.String("current-user", "", `The current user`) - apiFlags = api.NewFlags(flagSet) - ) - - handler := func(args []string) error { - err := flagSet.Parse(args) - if err != nil { - return err - } - - extensionID := *extensionIDFlag - if extensionID == "" { - return fmt.Errorf("must provide -extension-id") - } - - currentUser := *currentUserFlag - if currentUser == "" { - return fmt.Errorf("must provide -current-user") - } - - extensionIDParts := strings.Split(extensionID, "/") - if len(extensionIDParts) != 2 { - return fmt.Errorf("-extension-id must have the form /") - } - extensionName := extensionIDParts[1] - - ctx := context.Background() - client := cfg.apiClient(apiFlags, flagSet.Output()) - ok := false - - var extensionResult struct { - ExtensionRegistry struct { - Extension struct { - Manifest struct { - Raw string - BundleURL string - } - } - } - } - - withCfg(&config{Endpoint: "https://sourcegraph.com"}, func() { - dotComClient := cfg.apiClient(apiFlags, flagSet.Output()) - query := `query GetExtension( - $extensionID: String! -){ - extensionRegistry{ - extension(extensionID: $extensionID) { - manifest{ - raw - bundleURL - } - } - } -}` - - ok, err = dotComClient.NewRequest(query, map[string]interface{}{ - "extensionID": extensionID, - }).Do(ctx, &extensionResult) - }) - if err != nil || !ok { - return err - } - - rawManifest := []byte(extensionResult.ExtensionRegistry.Extension.Manifest.Raw) - manifest, err := updatePropertyInManifest(rawManifest, "extensionID", extensionID) - if err != nil { - return err - } - // Remove sourcegraph.com bundle URL. - manifest, err = updatePropertyInManifest(manifest, "url", "") - if err != nil { - return err - } - - response, err := http.Get(extensionResult.ExtensionRegistry.Extension.Manifest.BundleURL) - if err != nil { - return err - } - defer response.Body.Close() - bundle, err := io.ReadAll(response.Body) - if err != nil { - return err - } - fmt.Printf("bundle: %s\n", string(bundle[0:100])) - fmt.Printf("manifest: %s\n", string(manifest[0:])) - - query := `mutation PublishExtension( - $extensionID: String!, - $manifest: String!, - $bundle: String, -) { - extensionRegistry { - publishExtension( - extensionID: $extensionID, - manifest: $manifest, - bundle: $bundle - ) { - extension { - extensionID - url - } - } - } -}` - - var publishResult struct { - ExtensionRegistry struct { - PublishExtension struct { - Extension struct { - ExtensionID string - URL string - } - } - } - } - if ok, err := client.NewRequest(query, map[string]interface{}{ - "extensionID": currentUser + "/" + extensionName, - "manifest": string(manifest), - "bundle": bundle, - }).Do(ctx, &publishResult); err != nil || !ok { - return err - } - - fmt.Println("Extension published!") - fmt.Println() - fmt.Printf("\tExtension ID: %s\n\n", publishResult.ExtensionRegistry.PublishExtension.Extension.ExtensionID) - fmt.Printf("View, enable, and configure it at: %s\n", cfg.Endpoint+publishResult.ExtensionRegistry.PublishExtension.Extension.URL) - return nil - } - - // Register the command. - extensionsCommands = append(extensionsCommands, &command{ - flagSet: flagSet, - handler: handler, - usageFunc: usageFunc, - }) - - // Catch the mistake of omitting the "extensions" subcommand. - commands = append(commands, didYouMeanOtherCommand("publish", []string{"extensions publish", "ext publish (alias)"})) -} diff --git a/cmd/src/extensions_delete.go b/cmd/src/extensions_delete.go deleted file mode 100644 index 863c2c655b..0000000000 --- a/cmd/src/extensions_delete.go +++ /dev/null @@ -1,77 +0,0 @@ -package main - -import ( - "context" - "flag" - "fmt" - - "github.com/sourcegraph/src-cli/internal/api" -) - -func init() { - usage := ` -Examples: - - Delete the extension by ID (GraphQL API ID, not extension ID): - - $ src extensions delete -id=UmVnaXN0cnlFeHRlbnNpb246... - - Delete the extension with extension ID "alice/myextension": - - $ src extensions delete -id=$(src extensions get -f '{{.ID}}' -extension-id=alice/myextension) - -` - - flagSet := flag.NewFlagSet("delete", flag.ExitOnError) - usageFunc := func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src extensions %s':\n", flagSet.Name()) - flagSet.PrintDefaults() - fmt.Println(usage) - } - var ( - extensionIDFlag = flagSet.String("id", "", `The ID (GraphQL API ID, not extension ID) of the extension to delete.`) - apiFlags = api.NewFlags(flagSet) - ) - - handler := func(args []string) error { - err := flagSet.Parse(args) - if err != nil { - return err - } - - client := cfg.apiClient(apiFlags, flagSet.Output()) - - query := `mutation DeleteExtension( - $extension: ID! -) { - extensionRegistry { - deleteExtension( - extension: $extension - ) { - alwaysNil - } - } -}` - - var result struct { - ExtensionRegistry struct { - DeleteExtension struct{} - } - } - if ok, err := client.NewRequest(query, map[string]interface{}{ - "extension": *extensionIDFlag, - }).Do(context.Background(), &result); err != nil || !ok { - return err - } - - fmt.Printf("Extension with ID %q deleted.\n", *extensionIDFlag) - return nil - } - - // Register the command. - extensionsCommands = append(extensionsCommands, &command{ - flagSet: flagSet, - handler: handler, - usageFunc: usageFunc, - }) -} diff --git a/cmd/src/extensions_get.go b/cmd/src/extensions_get.go deleted file mode 100644 index 9763e504ba..0000000000 --- a/cmd/src/extensions_get.go +++ /dev/null @@ -1,83 +0,0 @@ -package main - -import ( - "context" - "flag" - "fmt" - - "github.com/sourcegraph/src-cli/internal/api" -) - -func init() { - usage := ` -Examples: - - Get extension with extension ID "alice/myextension": - - $ src extensions get alice/myextension - $ src extensions get -extension-id=alice/myextension - -` - - flagSet := flag.NewFlagSet("get", flag.ExitOnError) - usageFunc := func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src extensions %s':\n", flagSet.Name()) - flagSet.PrintDefaults() - fmt.Println(usage) - } - var ( - extensionIDFlag = flagSet.String("extension-id", "", `Look up extension by extension ID. (e.g. "alice/myextension")`) - formatFlag = flagSet.String("f", "{{.|json}}", `Format for the output, using the syntax of Go package text/template. (e.g. "{{.ExtensionID}}: {{.Manifest.Title}} ({{.RemoteURL}})" or "{{.|json}}")`) - apiFlags = api.NewFlags(flagSet) - ) - - handler := func(args []string) error { - if err := flagSet.Parse(args); err != nil { - return err - } - - tmpl, err := parseTemplate(*formatFlag) - if err != nil { - return err - } - - client := cfg.apiClient(apiFlags, flagSet.Output()) - - query := `query RegistryExtension( - $extensionID: String!, -) { - extensionRegistry { - extension( - extensionID: $extensionID - ) { - ...RegistryExtensionFields - } - } -}` + registryExtensionFragment - - extensionID := *extensionIDFlag - if extensionID == "" && flagSet.NArg() == 1 { - extensionID = flagSet.Arg(0) - } - - var result struct { - ExtensionRegistry struct { - Extension *Extension - } - } - if ok, err := client.NewRequest(query, map[string]interface{}{ - "extensionID": extensionID, - }).Do(context.Background(), &result); err != nil || !ok { - return err - } - - return execTemplate(tmpl, result.ExtensionRegistry.Extension) - } - - // Register the command. - extensionsCommands = append(extensionsCommands, &command{ - flagSet: flagSet, - handler: handler, - usageFunc: usageFunc, - }) -} diff --git a/cmd/src/extensions_list.go b/cmd/src/extensions_list.go deleted file mode 100644 index 6aa5bead6c..0000000000 --- a/cmd/src/extensions_list.go +++ /dev/null @@ -1,104 +0,0 @@ -package main - -import ( - "context" - "flag" - "fmt" - - "github.com/sourcegraph/src-cli/internal/api" -) - -func init() { - usage := ` -Examples: - - List extensions: - - $ src extensions list - - List extensions whose names match the query: - - $ src extensions list -query='myquery' - - List *all* extensions (may be slow!): - - $ src extensions list -first='-1' - -` - - flagSet := flag.NewFlagSet("list", flag.ExitOnError) - usageFunc := func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src extensions %s':\n", flagSet.Name()) - flagSet.PrintDefaults() - fmt.Println(usage) - } - var ( - firstFlag = flagSet.Int("first", 1000, "Returns the first n extensions from the list. (use -1 for unlimited)") - queryFlag = flagSet.String("query", "", `Returns extensions whose extension IDs match the query. (e.g. "myextension")`) - formatFlag = flagSet.String("f", "{{.ExtensionID}}", `Format for the output, using the syntax of Go package text/template. (e.g. "{{.ExtensionID}}: {{.Manifest.Description}} ({{.RemoteURL}})" or "{{.|json}}")`) - apiFlags = api.NewFlags(flagSet) - ) - - handler := func(args []string) error { - if err := flagSet.Parse(args); err != nil { - return err - } - - tmpl, err := parseTemplate(*formatFlag) - if err != nil { - return err - } - - client := cfg.apiClient(apiFlags, flagSet.Output()) - - query := `query RegistryExtensions( - $first: Int, - $query: String, -) { - extensionRegistry { - extensions( - first: $first, - query: $query, - ) { - nodes { - ...RegistryExtensionFields - } - error - } - } -}` + registryExtensionFragment - - var result struct { - ExtensionRegistry struct { - Extensions struct { - Nodes []Extension - Error string - } - } - } - if ok, err := client.NewRequest(query, map[string]interface{}{ - "first": api.NullInt(*firstFlag), - "query": api.NullString(*queryFlag), - }).Do(context.Background(), &result); err != nil || !ok { - return err - } - - if result.ExtensionRegistry.Extensions.Error != "" { - return fmt.Errorf("%s", result.ExtensionRegistry.Extensions.Error) - } - - for _, extension := range result.ExtensionRegistry.Extensions.Nodes { - if err := execTemplate(tmpl, extension); err != nil { - return err - } - } - return nil - } - - // Register the command. - extensionsCommands = append(extensionsCommands, &command{ - flagSet: flagSet, - handler: handler, - usageFunc: usageFunc, - }) -} diff --git a/cmd/src/extensions_publish.go b/cmd/src/extensions_publish.go deleted file mode 100644 index 2156c7b170..0000000000 --- a/cmd/src/extensions_publish.go +++ /dev/null @@ -1,318 +0,0 @@ -package main - -import ( - "context" - "encoding/json" - "flag" - "fmt" - "os" - "os/exec" - "path/filepath" - "strings" - - "github.com/sourcegraph/sourcegraph/lib/errors" - - "github.com/sourcegraph/src-cli/internal/api" -) - -func init() { - usage := ` -Publish an extension to Sourcegraph, creating it (if necessary). - -Examples: - - Publish the "alice/myextension" extension described by package.json in the current directory: - - $ cat package.json - { - "name": "myextension", - "publisher": "alice", - "title": "My Extension", - "main": "dist/myext.js", - "scripts": {"sourcegraph:prepublish": "parcel build --out-file dist/myext.js src/myext.ts"} - } - $ src extensions publish - -Notes: - - Source maps are supported (for easier debugging of extensions). If the main JavaScript bundle is "dist/myext.js", - it looks for a source map in "dist/myext.map". - -` - - flagSet := flag.NewFlagSet("publish", flag.ExitOnError) - usageFunc := func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src extensions %s':\n", flagSet.Name()) - flagSet.PrintDefaults() - fmt.Println(usage) - } - var ( - extensionIDFlag = flagSet.String("extension-id", "", `Override the extension ID in the manifest. (default: read from -manifest file)`) - urlFlag = flagSet.String("url", "", `Override the URL for the bundle. (example: set to http://localhost:1234/myext.js for local dev with parcel)`) - gitHeadFlag = flagSet.String("git-head", "", "Override the current git commit for the bundle. (default: uses `git rev-parse head`)") - manifestFlag = flagSet.String("manifest", "package.json", `The extension manifest file.`) - forceFlag = flagSet.Bool("force", false, `Force publish the extension, even if there are validation problems or other warnings.`) - apiFlags = api.NewFlags(flagSet) - ) - - handler := func(args []string) error { - if err := flagSet.Parse(args); err != nil { - return err - } - - manifestPath, err := filepath.Abs(*manifestFlag) - if err != nil { - return err - } - manifestDir := filepath.Dir(manifestPath) - - manifest, err := os.ReadFile(manifestPath) - if err != nil { - return fmt.Errorf("%s\n\nRun this command in a directory with a %s file for an extension.\n\nSee 'src extensions %s -h' for help", err, *manifestFlag, flagSet.Name()) - } - extensionID := *extensionIDFlag - if extensionID == "" { - extensionID, err = readExtensionIDFromManifest(manifest) - if err != nil { - return err - } - } - manifest, err = updatePropertyInManifest(manifest, "extensionID", extensionID) - if err != nil { - return err - } - manifest, err = addReadmeToManifest(manifest, manifestDir) - if err != nil { - return err - } - - var bundle, sourceMap *string - if *urlFlag != "" { - manifest, err = updatePropertyInManifest(manifest, "url", *urlFlag) - if err != nil { - return err - } - } else { - // Prepare and upload bundle. - if err := runManifestPrepublishScript(manifest, manifestDir); err != nil { - return err - } - - var err error - bundle, sourceMap, err = readExtensionArtifacts(manifest, manifestDir) - if err != nil { - return err - } - } - - if *gitHeadFlag != "" { - manifest, err = updatePropertyInManifest(manifest, "gitHead", *gitHeadFlag) - if err != nil { - return err - } - } else { - command := exec.Command("git", "rev-parse", "head") - command.Dir = manifestDir - - out, err := command.CombinedOutput() - if err != nil { - fmt.Printf("failed to determine git head: %q\n", err) - } else { - manifest, err = updatePropertyInManifest(manifest, "gitHead", strings.TrimSpace(string(out))) - if err != nil { - return err - } - } - } - - client := cfg.apiClient(apiFlags, flagSet.Output()) - - query := `mutation PublishExtension( - $extensionID: String!, - $manifest: String!, - $bundle: String, - $sourceMap: String, - $force: Boolean!, -) { - extensionRegistry { - publishExtension( - extensionID: $extensionID, - manifest: $manifest, - bundle: $bundle, - sourceMap: $sourceMap, - force: $force, - ) { - extension { - extensionID - url - } - } - } -}` - - var result struct { - ExtensionRegistry struct { - PublishExtension struct { - Extension struct { - ExtensionID string - URL string - } - } - } - } - if ok, err := client.NewRequest(query, map[string]interface{}{ - "extensionID": extensionID, - "manifest": string(manifest), - "bundle": bundle, - "sourceMap": sourceMap, - "force": *forceFlag, - }).Do(context.Background(), &result); err != nil || !ok { - return err - } - - fmt.Println("Extension published!") - fmt.Println() - fmt.Printf("\tExtension ID: %s\n\n", result.ExtensionRegistry.PublishExtension.Extension.ExtensionID) - fmt.Printf("View, enable, and configure it at: %s\n", cfg.Endpoint+result.ExtensionRegistry.PublishExtension.Extension.URL) - return nil - } - - // Register the command. - extensionsCommands = append(extensionsCommands, &command{ - flagSet: flagSet, - handler: handler, - usageFunc: usageFunc, - }) - - // Catch the mistake of omitting the "extensions" subcommand. - commands = append(commands, didYouMeanOtherCommand("publish", []string{"extensions publish", "ext publish (alias)"})) -} - -func runManifestPrepublishScript(manifest []byte, dir string) error { - var o struct { - Scripts struct { - SourcegraphPrepublish string `json:"sourcegraph:prepublish"` - } `json:"scripts"` - } - if err := json.Unmarshal(manifest, &o); err != nil { - return err - } - - if o.Scripts.SourcegraphPrepublish == "" { - return nil - } - cmd := exec.Command("bash", "-c", o.Scripts.SourcegraphPrepublish) - cmd.Env = append(os.Environ(), fmt.Sprintf("PATH=%s:%s", filepath.Join(dir, "node_modules", ".bin"), os.Getenv("PATH"))) - cmd.Dir = dir - cmd.Stdout = os.Stderr - cmd.Stderr = os.Stderr - fmt.Fprintf(os.Stderr, "# sourcegraph:prepublish: %s\n", o.Scripts.SourcegraphPrepublish) - if err := cmd.Run(); err != nil { - return fmt.Errorf("sourcegraph:prepublish script failed: %w (see output above)", err) - } - fmt.Fprintln(os.Stderr) - return nil -} - -func readExtensionIDFromManifest(manifest []byte) (string, error) { - var o map[string]interface{} - if err := json.Unmarshal(manifest, &o); err != nil { - return "", err - } - - extensionID, _ := o["extensionID"].(string) - if extensionID != "" { - return extensionID, nil - } - - name, _ := o["name"].(string) - publisher, _ := o["publisher"].(string) - if name == "" && publisher == "" { - return "", errors.New(`extension manifest must contain "name" and "publisher" string properties (the extension ID is of the form "publisher/name" and uses these values)`) - } - if name == "" { - return "", fmt.Errorf(`extension manifest must contain a "name" string property for the extension name (the extension ID will be %q)`, publisher+"/name") - } - if publisher == "" { - return "", fmt.Errorf(`extension manifest must contain a "publisher" string property referring to a username or organization name on Sourcegraph (the extension ID will be %q)`, "publisher/"+name) - } - return publisher + "/" + name, nil -} - -func updatePropertyInManifest(manifest []byte, property, value string) (updatedManifest []byte, err error) { - var o map[string]interface{} - if err := json.Unmarshal(manifest, &o); err != nil { - return nil, err - } - if o == nil { - o = map[string]interface{}{} - } - if value == "" { - delete(o, property) - } else { - o[property] = value - } - return json.MarshalIndent(o, "", " ") -} - -func addReadmeToManifest(manifest []byte, dir string) ([]byte, error) { - var readme string - filenames := []string{"README.md", "README.txt", "README", "readme.md", "readme.txt", "readme", "Readme.md", "Readme.txt", "Readme"} - for _, f := range filenames { - data, err := os.ReadFile(filepath.Join(dir, f)) - if err != nil { - continue - } - readme = string(data) - break - } - - if readme == "" { - return manifest, nil - } - - var o map[string]interface{} - if err := json.Unmarshal(manifest, &o); err != nil { - return nil, err - } - if o == nil { - o = map[string]interface{}{} - } - o["readme"] = readme - return json.MarshalIndent(o, "", " ") -} - -func readExtensionArtifacts(manifest []byte, dir string) (bundle, sourceMap *string, err error) { - var o struct { - Main string `json:"main"` - } - if err := json.Unmarshal(manifest, &o); err != nil { - return nil, nil, err - } - if o.Main == "" { - return nil, nil, nil - } - - mainPath := filepath.Join(dir, o.Main) - - data, err := os.ReadFile(mainPath) - if err != nil { - return nil, nil, fmt.Errorf(`extension manifest "main" bundle file: %s`, err) - } - { - tmp := string(data) - bundle = &tmp - } - - // Guess that source map is the main file with a ".map" extension. - sourceMapPath := strings.TrimSuffix(mainPath, filepath.Ext(mainPath)) + ".map" - data, err = os.ReadFile(sourceMapPath) - if err == nil { - tmp := string(data) - sourceMap = &tmp - } else if !os.IsNotExist(err) { - return nil, nil, err - } - - return bundle, sourceMap, nil -} diff --git a/cmd/src/extensions_publish_test.go b/cmd/src/extensions_publish_test.go deleted file mode 100644 index abf2832968..0000000000 --- a/cmd/src/extensions_publish_test.go +++ /dev/null @@ -1,80 +0,0 @@ -package main - -import ( - "encoding/json" - "reflect" - "testing" -) - -func TestReadExtensionIDFromManifest(t *testing.T) { - tests := map[string]string{ - `{"name": "a", "publisher": "b"}`: "b/a", - `{"name": "a", "publisher": "b", "extensionID": "c"}`: "c", - `{"extensionID": "c"}`: "c", - } - for manifest, want := range tests { - t.Run(manifest, func(t *testing.T) { - got, err := readExtensionIDFromManifest([]byte(manifest)) - if err != nil { - t.Fatal(err) - } - if got != want { - t.Errorf("got %q, want %q", got, want) - } - }) - } - - t.Run("no name", func(t *testing.T) { - if _, err := readExtensionIDFromManifest([]byte(`{}`)); err == nil { - t.Fatal() - } - }) - - t.Run("no publisher", func(t *testing.T) { - if _, err := readExtensionIDFromManifest([]byte(`{"name":"a"}`)); err == nil { - t.Fatal() - } - }) -} - -func TestUpdatePropertyInManifest(t *testing.T) { - tests := map[string]string{ - `{}`: `{"p": "x"}`, - `{"a":1}`: `{"a":1, "p": "x"}`, - `{"p":"a"}`: `{"p": "x"}`, - } - for manifest, want := range tests { - t.Run(manifest, func(t *testing.T) { - got, err := updatePropertyInManifest([]byte(manifest), "p", "x") - if err != nil { - t.Fatal(err) - } - if !jsonDeepEqual(string(got), want) { - t.Errorf("got %q, want %q", got, want) - } - }) - } - - t.Run("remove property", func(t *testing.T) { - manifest := `{"extensionID":"sourcegraph/typescript", "url":"https://sourcegraph.com"}` - want := `{"extensionID": "sourcegraph/typescript"}` - got, err := updatePropertyInManifest([]byte(manifest), "url", "") - if err != nil { - t.Fatal(err) - } - if !jsonDeepEqual(string(got), want) { - t.Errorf("got %q, want %q", got, want) - } - }) -} - -func jsonDeepEqual(a, b string) bool { - var va, vb interface{} - if err := json.Unmarshal([]byte(a), &va); err != nil { - panic(err) - } - if err := json.Unmarshal([]byte(b), &vb); err != nil { - panic(err) - } - return reflect.DeepEqual(va, vb) -} diff --git a/cmd/src/users_prune.go b/cmd/src/users_prune.go index e35555feb6..8c78ef2b11 100644 --- a/cmd/src/users_prune.go +++ b/cmd/src/users_prune.go @@ -166,7 +166,7 @@ Examples: } // confirm and remove users - if confirmed, _ := confirmUserRemoval(usersToDelete, int(totalUsers.Site.Users.TotalCount), *daysToDelete, *displayUsersToDelete); !confirmed { + if confirmed, _ := confirmUserRemoval(usersToDelete, *daysToDelete, *displayUsersToDelete); !confirmed { fmt.Println("Aborting removal") return nil } else { @@ -223,7 +223,7 @@ type UserToDelete struct { } // Verify user wants to remove users with table of users and a command prompt for [y/N] -func confirmUserRemoval(usersToDelete []UserToDelete, totalUsers int, daysThreshold int, displayUsers bool) (bool, error) { +func confirmUserRemoval(usersToDelete []UserToDelete, daysThreshold int, displayUsers bool) (bool, error) { if displayUsers { fmt.Printf("Users to remove from %s\n", cfg.Endpoint) t := table.NewWriter() From ce79fc982a790be87a685b7a331767daff4dde80 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Thu, 19 Jun 2025 19:25:13 +0200 Subject: [PATCH 477/647] chore: Remove gateway commands (#1174) These were used for internal testing. Test plan: Other commands still work locally. Changelog: The deprecated `src gateway` commands have been removed. --- cmd/src/gateway.go | 39 --- cmd/src/gateway_benchmark.go | 523 ---------------------------- cmd/src/gateway_benchmark_stream.go | 283 --------------- 3 files changed, 845 deletions(-) delete mode 100644 cmd/src/gateway.go delete mode 100644 cmd/src/gateway_benchmark.go delete mode 100644 cmd/src/gateway_benchmark_stream.go diff --git a/cmd/src/gateway.go b/cmd/src/gateway.go deleted file mode 100644 index 0540d694e3..0000000000 --- a/cmd/src/gateway.go +++ /dev/null @@ -1,39 +0,0 @@ -package main - -import ( - "flag" - "fmt" -) - -var gatewayCommands commander - -func init() { - usage := `'src gateway' interacts with Cody Gateway (directly or through a Sourcegraph instance). - -Usage: - - src gateway command [command options] - -The commands are: - - benchmark runs benchmarks against Cody Gateway - benchmark-stream runs benchmarks against Cody Gateway code completion streaming endpoints - -Use "src gateway [command] -h" for more information about a command. - -` - - flagSet := flag.NewFlagSet("gateway", flag.ExitOnError) - handler := func(args []string) error { - gatewayCommands.run(flagSet, "src gateway", usage, args) - return nil - } - - // Register the command. - commands = append(commands, &command{ - flagSet: flagSet, - aliases: []string{}, // No aliases for gateway command - handler: handler, - usageFunc: func() { fmt.Println(usage) }, - }) -} diff --git a/cmd/src/gateway_benchmark.go b/cmd/src/gateway_benchmark.go deleted file mode 100644 index cc354bc625..0000000000 --- a/cmd/src/gateway_benchmark.go +++ /dev/null @@ -1,523 +0,0 @@ -package main - -import ( - "encoding/csv" - "flag" - "fmt" - "io" - "net/http" - "os" - "sort" - "strings" - "time" - - "github.com/gorilla/websocket" - - "github.com/sourcegraph/src-cli/internal/cmderrors" -) - -type Stats struct { - Avg time.Duration - P5 time.Duration - P75 time.Duration - P80 time.Duration - P95 time.Duration - Median time.Duration - Total time.Duration -} - -type requestResult struct { - duration time.Duration - traceID string // X-Trace header value -} - -func init() { - usage := ` -'src gateway benchmark' runs performance benchmarks against Cody Gateway and Sourcegraph test endpoints. - -Usage: - - src gateway benchmark [flags] - -Examples: - - $ src gateway benchmark --sgp - $ src gateway benchmark --requests 50 --sgp - $ src gateway benchmark --gateway http://localhost:9992 --sourcegraph http://localhost:3082 --sgp - $ src gateway benchmark --requests 50 --csv results.csv --request-csv requests.csv --sgp - $ src gateway benchmark --gateway https://cody-gateway.sourcegraph.com --sourcegraph https://sourcegraph.com --sgp --use-special-header -` - - flagSet := flag.NewFlagSet("benchmark", flag.ExitOnError) - - var ( - requestCount = flagSet.Int("requests", 1000, "Number of requests to make per endpoint") - csvOutput = flagSet.String("csv", "", "Export results to CSV file (provide filename)") - requestLevelCsvOutput = flagSet.String("request-csv", "", "Export request results to CSV file (provide filename)") - gatewayEndpoint = flagSet.String("gateway", "", "Cody Gateway endpoint") - sgEndpoint = flagSet.String("sourcegraph", "", "Sourcegraph endpoint") - sgpToken = flagSet.String("sgp", "", "Sourcegraph personal access token for the called instance") - useSpecialHeader = flagSet.Bool("use-special-header", false, "Use special header to test the gateway") - ) - - handler := func(args []string) error { - if err := flagSet.Parse(args); err != nil { - return err - } - - if len(flagSet.Args()) != 0 { - return cmderrors.Usage("additional arguments not allowed") - } - - if *useSpecialHeader { - fmt.Println("Using special header 'cody-core-gc-test'") - } - - var ( - httpClient = &http.Client{} - endpoints = map[string]any{} // Values: URL `string`s or `*webSocketClient`s - ) - if *gatewayEndpoint != "" { - fmt.Println("Benchmarking Cody Gateway instance:", *gatewayEndpoint) - headers := http.Header{ - "X-Sourcegraph-Should-Trace": []string{"true"}, - } - endpoints["ws(s): gateway"] = &webSocketClient{ - conn: nil, - URL: strings.Replace(fmt.Sprint(*gatewayEndpoint, "/v2/websocket"), "http", "ws", 1), - reqHeaders: headers, - } - endpoints["http(s): gateway"] = fmt.Sprint(*gatewayEndpoint, "/v2/http") - } else { - fmt.Println("warning: not benchmarking Cody Gateway (-gateway endpoint not provided)") - } - if *sgEndpoint != "" { - if *sgpToken == "" { - return cmderrors.Usage("must specify --sgp ") - } - fmt.Println("Benchmarking Sourcegraph instance:", *sgEndpoint) - headers := http.Header{ - "Authorization": []string{"token " + *sgpToken}, - "X-Sourcegraph-Should-Trace": []string{"true"}, - } - if *useSpecialHeader { - headers.Set("cody-core-gc-test", "M2R{+6VI?1,M3n&") - } - - endpoints["ws(s): sourcegraph"] = &webSocketClient{ - conn: nil, - URL: strings.Replace(fmt.Sprint(*sgEndpoint, "/.api/gateway/websocket"), "http", "ws", 1), - reqHeaders: headers, - } - endpoints["http(s): sourcegraph"] = fmt.Sprint(*sgEndpoint, "/.api/gateway/http") - endpoints["http(s): http-then-ws"] = fmt.Sprint(*sgEndpoint, "/.api/gateway/http-then-websocket") - } else { - fmt.Println("warning: not benchmarking Sourcegraph instance (-sourcegraph endpoint not provided)") - } - - fmt.Printf("Starting benchmark with %d requests per endpoint...\n", *requestCount) - - var eResults []endpointResult - rResults := map[string][]requestResult{} - for name, clientOrURL := range endpoints { - durations := make([]time.Duration, 0, *requestCount) - rResults[name] = make([]requestResult, 0, *requestCount) - fmt.Printf("\nTesting %s...", name) - - for i := 0; i < *requestCount; i++ { - if ws, ok := clientOrURL.(*webSocketClient); ok { - result := benchmarkEndpointWebSocket(ws) - if result.duration > 0 { - durations = append(durations, result.duration) - rResults[name] = append(rResults[name], result) - } - } else if url, ok := clientOrURL.(string); ok { - result := benchmarkEndpointHTTP(httpClient, url, *sgpToken, *useSpecialHeader) - if result.duration > 0 { - durations = append(durations, result.duration) - rResults[name] = append(rResults[name], result) - } - } - } - fmt.Println() - - stats := calculateStats(durations) - - eResults = append(eResults, endpointResult{ - name: name, - avg: stats.Avg, - median: stats.Median, - p5: stats.P5, - p75: stats.P75, - p80: stats.P80, - p95: stats.P95, - total: stats.Total, - successful: len(durations), - }) - } - - printResults(eResults, requestCount) - - if *csvOutput != "" { - if err := writeResultsToCSV(*csvOutput, eResults, requestCount); err != nil { - return fmt.Errorf("failed to export CSV: %v", err) - } - fmt.Printf("\nResults exported to %s\n", *csvOutput) - } - if *requestLevelCsvOutput != "" { - if err := writeRequestResultsToCSV(*requestLevelCsvOutput, rResults); err != nil { - return fmt.Errorf("failed to export request-level CSV: %v", err) - } - fmt.Printf("\nRequest-level results exported to %s\n", *requestLevelCsvOutput) - } - - return nil - } - - gatewayCommands = append(gatewayCommands, &command{ - flagSet: flagSet, - aliases: []string{}, - handler: handler, - usageFunc: func() { - _, err := fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src gateway %s':\n", flagSet.Name()) - if err != nil { - return - } - flagSet.PrintDefaults() - fmt.Println(usage) - }, - }) -} - -type webSocketClient struct { - conn *websocket.Conn - URL string - reqHeaders http.Header - respHeaders http.Header -} - -func (c *webSocketClient) reconnect() error { - if c.conn != nil { - c.conn.Close() // don't leak connections - } - fmt.Println("Connecting to WebSocket..", c.URL) - var err error - var resp *http.Response - //nolint:bodyclose // closed as part of webSocketClient - c.conn, resp, err = websocket.DefaultDialer.Dial(c.URL, c.reqHeaders) - if err != nil { - c.conn = nil // retry again later - return fmt.Errorf("WebSocket dial(%s): %v", c.URL, err) - } - c.respHeaders = resp.Header - fmt.Println("Connected!") - return nil -} - -type endpointResult struct { - name string - avg time.Duration - median time.Duration - p5 time.Duration - p75 time.Duration - p80 time.Duration - p95 time.Duration - total time.Duration - successful int -} - -func benchmarkEndpointHTTP(client *http.Client, url, accessToken string, useSpecialHeader bool) requestResult { - start := time.Now() - req, err := http.NewRequest("POST", url, strings.NewReader("ping")) - if err != nil { - fmt.Printf("Error creating request: %v\n", err) - return requestResult{} - } - req.Header.Set("Content-Type", "application/json") - req.Header.Set("Authorization", "token "+accessToken) - req.Header.Set("X-Sourcegraph-Should-Trace", "true") - if useSpecialHeader { - req.Header.Set("cody-core-gc-test", "M2R{+6VI?1,M3n&") - } - resp, err := client.Do(req) - if err != nil { - fmt.Printf("Error calling %s: %v\n", url, err) - return requestResult{} - } - defer func() { - err := resp.Body.Close() - if err != nil { - fmt.Printf("Error closing response body: %v\n", err) - } - }() - if resp.StatusCode != http.StatusOK { - fmt.Printf("non-200 response: %v\n", resp.Status) - return requestResult{} - } - body, err := io.ReadAll(resp.Body) - if err != nil { - fmt.Printf("Error reading response body: %v\n", err) - return requestResult{} - } - if string(body) != "pong" { - fmt.Printf("Expected 'pong' response, got: %q\n", string(body)) - return requestResult{} - } - - return requestResult{ - duration: time.Since(start), - traceID: resp.Header.Get("X-Trace"), - } -} - -func benchmarkEndpointWebSocket(client *webSocketClient) requestResult { - // Perform initial websocket connection, if needed. - if client.conn == nil { - if err := client.reconnect(); err != nil { - fmt.Printf("Error reconnecting: %v\n", err) - return requestResult{} - } - } - - // Perform the benchmarked request using the websocket. - start := time.Now() - err := client.conn.WriteMessage(websocket.TextMessage, []byte("ping")) - if err != nil { - fmt.Printf("WebSocket write error: %v\n", err) - if err := client.reconnect(); err != nil { - fmt.Printf("Error reconnecting: %v\n", err) - } - return requestResult{} - } - _, message, err := client.conn.ReadMessage() - - if err != nil { - fmt.Printf("WebSocket read error: %v\n", err) - if err := client.reconnect(); err != nil { - fmt.Printf("Error reconnecting: %v\n", err) - } - return requestResult{} - } - if string(message) != "pong" { - fmt.Printf("Expected 'pong' response, got: %q\n", string(message)) - if err := client.reconnect(); err != nil { - fmt.Printf("Error reconnecting: %v\n", err) - } - return requestResult{} - } - return requestResult{ - duration: time.Since(start), - traceID: client.respHeaders.Get("Content-Type"), - } -} - -func calculateStats(durations []time.Duration) Stats { - if len(durations) == 0 { - return Stats{0, 0, 0, 0, 0, 0, 0} - } - - // Sort durations in ascending order - sort.Slice(durations, func(i, j int) bool { - return durations[i] < durations[j] - }) - - var sum time.Duration - for _, d := range durations { - sum += d - } - avg := sum / time.Duration(len(durations)) - - return Stats{ - Avg: avg, - P5: durations[int(float64(len(durations))*0.05)], - P75: durations[int(float64(len(durations))*0.75)], - P80: durations[int(float64(len(durations))*0.80)], - P95: durations[int(float64(len(durations))*0.95)], - Median: durations[(len(durations) / 2)], - Total: sum, - } -} - -func formatDuration(d time.Duration, best bool, worst bool) string { - value := fmt.Sprintf("%.2fms", float64(d.Microseconds())/1000) - if best { - return ansiColors["green"] + value + ansiColors["nc"] - } - if worst { - return ansiColors["red"] + value + ansiColors["nc"] - } - return ansiColors["yellow"] + value + ansiColors["nc"] -} - -func formatSuccessRate(successful, total int, best bool, worst bool) string { - value := fmt.Sprintf("%d/%d", successful, total) - if best { - return ansiColors["green"] + value + ansiColors["nc"] - } - if worst { - return ansiColors["red"] + value + ansiColors["nc"] - } - return ansiColors["yellow"] + value + ansiColors["nc"] -} - -func printResults(results []endpointResult, requestCount *int) { - // Print header - headerFmt := ansiColors["blue"] + "%-25s | %-10s | %-10s | %-10s | %-10s | %-10s | %-10s | %-10s | %-10s" + ansiColors["nc"] + "\n" - fmt.Printf("\n"+headerFmt, - "Endpoint ", "Average", "Median", "P5", "P75", "P80", "P95", "Total", "Success") - fmt.Println(ansiColors["blue"] + strings.Repeat("-", 121) + ansiColors["nc"]) - - // Find best/worst values for each metric - var bestAvg, worstAvg time.Duration - var bestMedian, worstMedian time.Duration - var bestP5, worstP5 time.Duration - var bestP75, worstP75 time.Duration - var bestP80, worstP80 time.Duration - var bestP95, worstP95 time.Duration - var bestTotal, worstTotal time.Duration - var bestSuccess, worstSuccess int - - for i, r := range results { - if i == 0 || r.avg < bestAvg { - bestAvg = r.avg - } - if i == 0 || r.avg > worstAvg { - worstAvg = r.avg - } - if i == 0 || r.median < bestMedian { - bestMedian = r.median - } - if i == 0 || r.median > worstMedian { - worstMedian = r.median - } - if i == 0 || r.p5 < bestP5 { - bestP5 = r.p5 - } - if i == 0 || r.p5 > worstP5 { - worstP5 = r.p5 - } - if i == 0 || r.p75 < bestP75 { - bestP75 = r.p75 - } - if i == 0 || r.p75 > worstP75 { - worstP75 = r.p75 - } - if i == 0 || r.p80 < bestP80 { - bestP80 = r.p80 - } - if i == 0 || r.p80 > worstP80 { - worstP80 = r.p80 - } - if i == 0 || r.p95 < bestP95 { - bestP95 = r.p95 - } - if i == 0 || r.p95 > worstP95 { - worstP95 = r.p95 - } - if i == 0 || r.total < bestTotal { - bestTotal = r.total - } - if i == 0 || r.total > worstTotal { - worstTotal = r.total - } - if i == 0 || r.successful > bestSuccess { - bestSuccess = r.successful - } - if i == 0 || r.successful < worstSuccess { - worstSuccess = r.successful - } - } - - // Print each row - for _, r := range results { - fmt.Printf("%-25s | %-19s | %-19s | %-19s | %-19s | %-19s | %-19s | %-19s | %s\n", - r.name, - formatDuration(r.avg, r.avg == bestAvg, r.avg == worstAvg), - formatDuration(r.median, r.median == bestMedian, r.median == worstMedian), - formatDuration(r.p5, r.p5 == bestP5, r.p5 == worstP5), - formatDuration(r.p75, r.p75 == bestP75, r.p75 == worstP75), - formatDuration(r.p80, r.p80 == bestP80, r.p80 == worstP80), - formatDuration(r.p95, r.p95 == bestP95, r.p95 == worstP95), - formatDuration(r.total, r.total == bestTotal, r.total == worstTotal), - formatSuccessRate(r.successful, *requestCount, r.successful == bestSuccess, r.successful == worstSuccess)) - } -} - -func writeResultsToCSV(filename string, results []endpointResult, requestCount *int) error { - file, err := os.Create(filename) - if err != nil { - return fmt.Errorf("failed to create CSV file: %v", err) - } - defer func() { - err := file.Close() - if err != nil { - return - } - }() - - writer := csv.NewWriter(file) - defer writer.Flush() - - // Write header - header := []string{"Endpoint", "Average (ms)", "Median (ms)", "P5 (ms)", "P75 (ms)", "P80 (ms)", "P95 (ms)", "Total (ms)", "Success Rate"} - if err := writer.Write(header); err != nil { - return fmt.Errorf("failed to write CSV header: %v", err) - } - - // Write data rows - for _, r := range results { - row := []string{ - r.name, - fmt.Sprintf("%.2f", float64(r.avg.Microseconds())/1000), - fmt.Sprintf("%.2f", float64(r.median.Microseconds())/1000), - fmt.Sprintf("%.2f", float64(r.p5.Microseconds())/1000), - fmt.Sprintf("%.2f", float64(r.p75.Microseconds())/1000), - fmt.Sprintf("%.2f", float64(r.p80.Microseconds())/1000), - fmt.Sprintf("%.2f", float64(r.p95.Microseconds())/1000), - fmt.Sprintf("%.2f", float64(r.total.Microseconds())/1000), - fmt.Sprintf("%d/%d", r.successful, *requestCount), - } - if err := writer.Write(row); err != nil { - return fmt.Errorf("failed to write CSV row: %v", err) - } - } - - return nil -} - -func writeRequestResultsToCSV(filename string, results map[string][]requestResult) error { - file, err := os.Create(filename) - if err != nil { - return fmt.Errorf("failed to create CSV file: %v", err) - } - defer func() { - err := file.Close() - if err != nil { - return - } - }() - - writer := csv.NewWriter(file) - defer writer.Flush() - - // Write header - header := []string{"Endpoint", "Duration (ms)", "Trace ID"} - if err := writer.Write(header); err != nil { - return fmt.Errorf("failed to write CSV header: %v", err) - } - - for endpoint, requestResults := range results { - for _, result := range requestResults { - row := []string{ - endpoint, - fmt.Sprintf("%.2f", float64(result.duration.Microseconds())/1000), - result.traceID, - } - if err := writer.Write(row); err != nil { - return fmt.Errorf("failed to write CSV row: %v", err) - } - } - } - - return nil -} diff --git a/cmd/src/gateway_benchmark_stream.go b/cmd/src/gateway_benchmark_stream.go deleted file mode 100644 index 66154a5c8b..0000000000 --- a/cmd/src/gateway_benchmark_stream.go +++ /dev/null @@ -1,283 +0,0 @@ -package main - -import ( - "flag" - "fmt" - "io" - "net/http" - "strings" - "time" - - "github.com/sourcegraph/src-cli/internal/cmderrors" -) - -type httpEndpoint struct { - url string - authHeader string - body string -} - -func init() { - usage := ` -'src gateway benchmark-stream' runs performance benchmarks against Cody Gateway and Sourcegraph -code completion streaming endpoints. - -Usage: - - src gateway benchmark-stream [flags] - -Examples: - - $ src gateway benchmark-stream --requests 50 --csv results.csv --sgd --sgp - $ src gateway benchmark-stream --gateway http://localhost:9992 --sourcegraph http://localhost:3082 --sgd --sgp - $ src gateway benchmark-stream --requests 250 --gateway http://localhost:9992 --sourcegraph http://localhost:3082 --sgd --sgp --max-tokens 50 --provider fireworks --stream -` - - flagSet := flag.NewFlagSet("benchmark-stream", flag.ExitOnError) - - var ( - requestCount = flagSet.Int("requests", 1000, "Number of requests to make per endpoint") - csvOutput = flagSet.String("csv", "", "Export results to CSV file (provide filename)") - requestLevelCsvOutput = flagSet.String("request-csv", "", "Export request results to CSV file (provide filename)") - gatewayEndpoint = flagSet.String("gateway", "", "Cody Gateway endpoint") - sgEndpoint = flagSet.String("sourcegraph", "", "Sourcegraph endpoint") - sgdToken = flagSet.String("sgd", "", "Sourcegraph Dotcom user key for Cody Gateway") - sgpToken = flagSet.String("sgp", "", "Sourcegraph personal access token for the called instance") - maxTokens = flagSet.Int("max-tokens", 256, "Maximum number of tokens to generate") - provider = flagSet.String("provider", "anthropic", "Provider to use for completion. Supported values: 'anthropic', 'fireworks'") - stream = flagSet.Bool("stream", false, "Whether to stream completions. Default: false") - ) - - handler := func(args []string) error { - // Parse the flags. - if err := flagSet.Parse(args); err != nil { - return err - } - if len(flagSet.Args()) != 0 { - return cmderrors.Usage("additional arguments not allowed") - } - if *gatewayEndpoint != "" && *sgdToken == "" { - return cmderrors.Usage("must specify --sgp ") - } - if *sgEndpoint != "" && *sgpToken == "" { - return cmderrors.Usage("must specify --sgp ") - } - - var httpClient = &http.Client{} - var cgResult, sgResult endpointResult - var cgRequestResults, sgRequestResults []requestResult - - // Do the benchmarking. - fmt.Printf("Starting benchmark with %d requests per endpoint...\n", *requestCount) - if *gatewayEndpoint != "" { - fmt.Println("Benchmarking Cody Gateway instance:", *gatewayEndpoint) - endpoint := buildGatewayHttpEndpoint(*gatewayEndpoint, *sgdToken, *maxTokens, *provider, *stream) - cgResult, cgRequestResults = benchmarkCodeCompletions("gateway", httpClient, endpoint, *requestCount) - fmt.Println() - } else { - fmt.Println("warning: not benchmarking Cody Gateway (-gateway endpoint not provided)") - } - if *sgEndpoint != "" { - fmt.Println("Benchmarking Sourcegraph instance:", *sgEndpoint) - endpoint := buildSourcegraphHttpEndpoint(*sgEndpoint, *sgpToken, *maxTokens, *provider, *stream) - sgResult, sgRequestResults = benchmarkCodeCompletions("sourcegraph", httpClient, endpoint, *requestCount) - fmt.Println() - } else { - fmt.Println("warning: not benchmarking Sourcegraph instance (-sourcegraph endpoint not provided)") - } - - // Output the results. - endpointResults := []endpointResult{cgResult, sgResult} - printResults(endpointResults, requestCount) - if *csvOutput != "" { - if err := writeResultsToCSV(*csvOutput, endpointResults, requestCount); err != nil { - return fmt.Errorf("failed to export CSV: %v", err) - } - fmt.Printf("\nAggregate results exported to %s\n", *csvOutput) - } - if *requestLevelCsvOutput != "" { - if err := writeRequestResultsToCSV(*requestLevelCsvOutput, map[string][]requestResult{"gateway": cgRequestResults, "sourcegraph": sgRequestResults}); err != nil { - return fmt.Errorf("failed to export CSV: %v", err) - } - fmt.Printf("\nRequest-level results exported to %s\n", *requestLevelCsvOutput) - } - - return nil - } - gatewayCommands = append(gatewayCommands, &command{ - flagSet: flagSet, - aliases: []string{}, - handler: handler, - usageFunc: func() { - _, err := fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src gateway %s':\n", flagSet.Name()) - if err != nil { - return - } - flagSet.PrintDefaults() - fmt.Println(usage) - }, - }) -} - -func buildGatewayHttpEndpoint(gatewayEndpoint string, sgdToken string, maxTokens int, provider string, stream bool) httpEndpoint { - s := "true" - if !stream { - s = "false" - } - if provider == "anthropic" { - return httpEndpoint{ - url: fmt.Sprint(gatewayEndpoint, "/v1/completions/anthropic-messages"), - authHeader: fmt.Sprintf("Bearer %s", sgdToken), - body: fmt.Sprintf(`{ - "model": "claude-3-haiku-20240307", - "messages": [ - {"role": "user", "content": "def bubble_sort(arr):"}, - {"role": "assistant", "content": "Here is a bubble sort:"} - ], - "max_tokens": %d, - "temperature": 0.0, - "stream": %s -}`, maxTokens, s), - } - } else if provider == "fireworks" { - return httpEndpoint{ - url: fmt.Sprint(gatewayEndpoint, "/v1/completions/fireworks"), - authHeader: fmt.Sprintf("Bearer %s", sgdToken), - body: fmt.Sprintf(`{ - "model": "starcoder", - "prompt": "#hello.ts<|fim▁begin|>const sayHello = () => <|fim▁hole|><|fim▁end|>", - "max_tokens": %d, - "stop": [ - "\n\n", - "\n\r\n", - "<|fim▁begin|>", - "<|fim▁hole|>", - "<|fim▁end|>, <|eos_token|>" - ], - "temperature": 0.2, - "topK": 0, - "topP": 0, - "stream": %s -}`, maxTokens, s), - } - } - - return httpEndpoint{} -} - -func buildSourcegraphHttpEndpoint(sgEndpoint string, sgpToken string, maxTokens int, provider string, stream bool) httpEndpoint { - s := "true" - if !stream { - s = "false" - } - if provider == "anthropic" { - return httpEndpoint{ - url: fmt.Sprint(sgEndpoint, "/.api/completions/stream"), - authHeader: fmt.Sprintf("token %s", sgpToken), - body: fmt.Sprintf(`{ - "model": "anthropic::2023-06-01::claude-3-haiku", - "messages": [ - {"speaker": "human", "text": "def bubble_sort(arr):"}, - {"speaker": "assistant", "text": "Here is a bubble sort:"} - ], - "maxTokensToSample": %d, - "temperature": 0.0, - "stream": %s -}`, maxTokens, s), - } - } else if provider == "fireworks" { - return httpEndpoint{ - url: fmt.Sprint(sgEndpoint, "/.api/completions/code"), - authHeader: fmt.Sprintf("token %s", sgpToken), - body: fmt.Sprintf(`{ - "model": "fireworks::v1::starcoder", - "messages": [ - {"speaker": "human", "text": "#hello.ts<|fim▁begin|>const sayHello = () => <|fim▁hole|><|fim▁end|>"} - ], - "maxTokensToSample": %d, - "stopSequences": [ - "\n\n", - "\n\r\n", - "<|fim▁begin|>", - "<|fim▁hole|>", - "<|fim▁end|>, <|eos_token|>" - ], - "temperature": 0.2, - "topK": 0, - "topP": 0, - "stream": %s -}`, maxTokens, s), - } - } - - return httpEndpoint{} -} - -func benchmarkCodeCompletions(benchmarkName string, client *http.Client, endpoint httpEndpoint, requestCount int) (endpointResult, []requestResult) { - results := make([]requestResult, 0, requestCount) - durations := make([]time.Duration, 0, requestCount) - - for i := 0; i < requestCount; i++ { - result := benchmarkCodeCompletion(client, endpoint) - if result.duration > 0 { - results = append(results, result) - durations = append(durations, result.duration) - } - } - stats := calculateStats(durations) - - return toEndpointResult(benchmarkName, stats, len(durations)), results -} - -func benchmarkCodeCompletion(client *http.Client, endpoint httpEndpoint) requestResult { - start := time.Now() - req, err := http.NewRequest("POST", endpoint.url, strings.NewReader(endpoint.body)) - if err != nil { - fmt.Printf("Error creating request: %v\n", err) - return requestResult{0, ""} - } - req.Header.Set("Content-Type", "application/json") - req.Header.Set("Authorization", endpoint.authHeader) - req.Header.Set("X-Sourcegraph-Should-Trace", "true") - req.Header.Set("X-Sourcegraph-Feature", "code_completions") - resp, err := client.Do(req) - if err != nil { - fmt.Printf("Error calling %s: %v\n", endpoint.url, err) - return requestResult{0, ""} - } - defer func() { - err := resp.Body.Close() - if err != nil { - fmt.Printf("Error closing response body: %v\n", err) - } - }() - if resp.StatusCode != http.StatusOK { - body, _ := io.ReadAll(resp.Body) - fmt.Printf("non-200 response: %v - %s\n", resp.Status, body) - return requestResult{0, ""} - } - _, err = io.ReadAll(resp.Body) - if err != nil { - fmt.Printf("Error reading response body: %v\n", err) - return requestResult{0, ""} - } - - return requestResult{ - duration: time.Since(start), - traceID: resp.Header.Get("X-Trace"), - } -} - -func toEndpointResult(name string, stats Stats, requestCount int) endpointResult { - return endpointResult{ - name: name, - avg: stats.Avg, - median: stats.Median, - p5: stats.P5, - p75: stats.P75, - p80: stats.P80, - p95: stats.P95, - successful: requestCount, - total: stats.Total, - } -} From d3c98cb9a6c79847bfbaab77fefc891a6c245c9a Mon Sep 17 00:00:00 2001 From: Will Dollman Date: Tue, 24 Jun 2025 13:48:04 +0100 Subject: [PATCH 478/647] Add a check that only succeeds if all matrix tests pass (#1175) * Add a check that only succeeds if all matrix tests pass This is required so that we can make the checks mandatory in branch protection - otherwise the names will keep changing * Tweak name --- .github/workflows/go-ci.yml | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/.github/workflows/go-ci.yml b/.github/workflows/go-ci.yml index 5ab699bfde..33dce1f948 100644 --- a/.github/workflows/go-ci.yml +++ b/.github/workflows/go-ci.yml @@ -30,3 +30,18 @@ jobs: - run: | go test -race -v ./... go test -v ./... + + # This job provides a stable name for branch protection rules + # It will only pass if all Go CI matrix tests above pass + go-test-complete: + runs-on: ubuntu-latest + needs: go-test + if: always() + steps: + - name: Check Go CI results + run: | + if [[ "${{ needs.go-test.result }}" != "success" ]]; then + echo "One or more Go CI tests failed" + exit 1 + fi + echo "All Go CI tests passed" From 795f4d64b6af999125002ba91e11fe5669096320 Mon Sep 17 00:00:00 2001 From: Will Dollman Date: Tue, 24 Jun 2025 15:55:18 +0100 Subject: [PATCH 479/647] Add semgrep scan (#1177) --- .github/workflows/semgrep.yml | 37 +++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 .github/workflows/semgrep.yml diff --git a/.github/workflows/semgrep.yml b/.github/workflows/semgrep.yml new file mode 100644 index 0000000000..3812ab18fc --- /dev/null +++ b/.github/workflows/semgrep.yml @@ -0,0 +1,37 @@ +name: Semgrep - SAST Scan + +on: + pull_request_target: + types: [ closed, edited, opened, synchronize, ready_for_review ] + +jobs: + semgrep: + permissions: + contents: read # for actions/checkout to fetch code + security-events: write # for github/codeql-action/upload-sarif to upload SARIF results + actions: read # only required for a private repository by github/codeql-action/upload-sarif to get the Action run status + runs-on: ubuntu-latest + container: + image: returntocorp/semgrep + + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.ref }} + repository: ${{ github.event.pull_request.head.repo.full_name }} + + - name: Checkout semgrep-rules repo + uses: actions/checkout@v4 + with: + repository: sourcegraph/security-semgrep-rules + token: ${{ secrets.GH_SEMGREP_SAST_TOKEN }} + path: semgrep-rules + + - name: Run Semgrep SAST Scan + run: | + mv semgrep-rules ../ + semgrep ci -f ../semgrep-rules/semgrep-rules/ --metrics=off --oss-only --suppress-errors --sarif -o results.sarif --exclude='semgrep-rules' --baseline-commit "$(git merge-base main HEAD)" || true + - name: Upload SARIF file + uses: github/codeql-action/upload-sarif@v3 + with: + sarif_file: results.sarif From e9a68058a861c3a26a8ff6c3d954d127b91edcb0 Mon Sep 17 00:00:00 2001 From: Jacob Pleiness Date: Wed, 25 Jun 2025 15:05:31 -0400 Subject: [PATCH 480/647] feat(rel): update changelog with 6.5.0 (#1178) --- CHANGELOG.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b89490e9df..76f5a2fc37 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,12 @@ All notable changes to `src-cli` are documented in this file. ### Added +### Changed + +## 6.5.0 + +### Added + - SBOM support: Added `--image` and `--exclude-image` flags to `src sbom fetch` for filtering which docker images SBOMs are fetched for. Both flags support glob patterns (e.g., `frontend`, `*api*`) and comma-separated lists. The `sourcegraph/` image name prefix is optional. ### Changed From cdeed31ed784c5d47e5f8f41289c48ad8ee8990e Mon Sep 17 00:00:00 2001 From: Audrey Sage Lorberfeld Date: Wed, 16 Jul 2025 15:40:14 -0700 Subject: [PATCH 481/647] Add automerge setting for renovate bot (#1179) --- renovate.json | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/renovate.json b/renovate.json index ab445a56a8..dd226f0096 100644 --- a/renovate.json +++ b/renovate.json @@ -1,5 +1,7 @@ { - "$schema": "http://json.schemastore.org/renovate", + "$schema": "http://json.schemastore.org/renovate",, + "automerge": true, + "automergeType": "pr", "extends": [ "github>sourcegraph/renovate-config" ], From a8695294ab07ad884fa2b4801f6e568dfa9d32e7 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 16 Jul 2025 20:43:08 -0700 Subject: [PATCH 482/647] Update dependency aspect_bazel_lib to v2.20.0 (#1071) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> Co-authored-by: Audrey Sage Lorberfeld --- WORKSPACE | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/WORKSPACE b/WORKSPACE index 48f5d167b5..3c5ffd973b 100644 --- a/WORKSPACE +++ b/WORKSPACE @@ -15,9 +15,9 @@ bazel_skylib_workspace() http_archive( name = "aspect_bazel_lib", - sha256 = "357dad9d212327c35d9244190ef010aad315e73ffa1bed1a29e20c372f9ca346", - strip_prefix = "bazel-lib-2.7.0", - url = "https://github.com/aspect-build/bazel-lib/releases/download/v2.7.0/bazel-lib-v2.7.0.tar.gz", + sha256 = "3522895fa13b97e8b27e3b642045682aa4233ae1a6b278aad6a3b483501dc9f2", + strip_prefix = "bazel-lib-2.20.0", + url = "https://github.com/aspect-build/bazel-lib/releases/download/v2.20.0/bazel-lib-v2.20.0.tar.gz", ) http_archive( From add5c3b2a8f83dbe9d056d98c18e3ae6addaeebe Mon Sep 17 00:00:00 2001 From: Jacob Pleiness Date: Wed, 20 Aug 2025 16:30:35 -0400 Subject: [PATCH 483/647] chore(rel): update changelog (#1181) Add changelog entry for 6.7.0 ### Test plan CI --- CHANGELOG.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 76f5a2fc37..03604fcb8b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,18 @@ All notable changes to `src-cli` are documented in this file. ### Changed +## 6.7.0 + +### Added + +### Changed + +## 6.6.0 + +### Added + +### Changed + ## 6.5.0 ### Added From a2246055466b1eb980ee29332f1d1ed4351f2640 Mon Sep 17 00:00:00 2001 From: Will Dollman Date: Wed, 27 Aug 2025 20:07:22 +0100 Subject: [PATCH 484/647] Update alpine version for release image (#1182) * Update Alpine version in dockerfiles * Update alpine version in additional dockerfile * Drop go version --- Dockerfile | 4 ++-- Dockerfile.release | 2 +- docker/batch-change-volume-workspace/Dockerfile | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Dockerfile b/Dockerfile index e183e19702..c039cc485f 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,14 +4,14 @@ # # Nothing fancy here: we copy in the source code and build on the Alpine Go # image. Refer to .dockerignore to get a sense of what we're not going to copy. -FROM golang:1.24.1-alpine@sha256:43c094ad24b6ac0546c62193baeb3e6e49ce14d3250845d166c77c25f64b0386 as builder +FROM golang:1.24.1-alpine@sha256:43c094ad24b6ac0546c62193baeb3e6e49ce14d3250845d166c77c25f64b0386 AS builder COPY . /src WORKDIR /src RUN go build ./cmd/src # This stage should be kept in sync with Dockerfile.release. -FROM sourcegraph/alpine:3.12@sha256:ce099fbcd3cf70b338fc4cb2a4e1fa9ae847de21afdb0a849a393b87d94fb174 +FROM alpine:3.22@sha256:4bcff63911fcb4448bd4fdacec207030997caf25e9bea4045fa6c8c44de311d1 # needed for `src code-intel upload` and `src actions exec` RUN apk add --no-cache git diff --git a/Dockerfile.release b/Dockerfile.release index ca2e3d321d..db46c56835 100644 --- a/Dockerfile.release +++ b/Dockerfile.release @@ -2,7 +2,7 @@ # suitable for testing, since it depends on a src binary being at the project # root _and_ that src binary being runnable on Alpine. To test this, refer to # the main Dockerfile, which should have an identical second stage. -FROM sourcegraph/alpine:3.12@sha256:ce099fbcd3cf70b338fc4cb2a4e1fa9ae847de21afdb0a849a393b87d94fb174 +FROM alpine:3.22@sha256:4bcff63911fcb4448bd4fdacec207030997caf25e9bea4045fa6c8c44de311d1 # needed for `src code-intel upload` and `src actions exec` RUN apk add --no-cache git diff --git a/docker/batch-change-volume-workspace/Dockerfile b/docker/batch-change-volume-workspace/Dockerfile index 42002273fb..5591858105 100644 --- a/docker/batch-change-volume-workspace/Dockerfile +++ b/docker/batch-change-volume-workspace/Dockerfile @@ -2,6 +2,6 @@ # image that we use to run curl, git, and unzip against a Docker volume when # using the volume workspace. -FROM alpine:3.19.1@sha256:c5b1261d6d3e43071626931fc004f70149baeba2c8ec672bd4f27761f8e1ad6b +FROM alpine:3.22@sha256:4bcff63911fcb4448bd4fdacec207030997caf25e9bea4045fa6c8c44de311d1 RUN apk add --update git unzip From f454b2c46697d3249a9eadcbcb2d3fe98f72a078 Mon Sep 17 00:00:00 2001 From: Will Dollman Date: Wed, 27 Aug 2025 20:46:30 +0100 Subject: [PATCH 485/647] Update changelog (#1183) --- CHANGELOG.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 03604fcb8b..409805aa3e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,14 @@ All notable changes to `src-cli` are documented in this file. ### Changed +## 6.7.1104 + +### Added + +### Changed + +- Updated Docker base image to alpine:3.22 + ## 6.7.0 ### Added From 806985b7ca26886d323f4e93c4bf53cf2f8fe319 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Kie=C5=82bowicz?= Date: Thu, 2 Oct 2025 08:55:46 +0200 Subject: [PATCH 486/647] Remove LSIF functionality, keeping only SCIP support (#1184) --- CODEOWNERS | 1 - README.md | 2 +- cmd/src/BUILD.bazel | 2 -- cmd/src/code_intel_upload.go | 2 +- cmd/src/code_intel_upload_vendored.go | 2 +- 5 files changed, 3 insertions(+), 6 deletions(-) diff --git a/CODEOWNERS b/CODEOWNERS index 71c2c03ab9..c27e120639 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -1,4 +1,3 @@ -cmd/src/lsif* @sourcegraph/team-graph cmd/src/code_intel* @sourcegraph/team-graph cmd/src/search* @sourcegraph/search-platform diff --git a/README.md b/README.md index 4a1f744404..46ee3f42d1 100644 --- a/README.md +++ b/README.md @@ -168,7 +168,7 @@ Is your Sourcegraph instance behind a custom auth proxy? See [auth proxy configu - `src config` - manage global, org, and user settings - `src extsvc` - manage external services (repository configuration) - `src extensions` - manage extensions - - `src code-intel` - manages Code Intelligence data (deprecated alias: `src lsif`) + - `src code-intel` - manages Code Intelligence data - `src serve-git` - serves your local git repositories over HTTP for Sourcegraph to pull - `src version` - check version and guaranteed-compatible version for your Sourcegraph instance diff --git a/cmd/src/BUILD.bazel b/cmd/src/BUILD.bazel index fdc0530dee..44dcf7729d 100644 --- a/cmd/src/BUILD.bazel +++ b/cmd/src/BUILD.bazel @@ -48,7 +48,6 @@ go_library( "format.go", "headers.go", "login.go", - "lsif.go", "main.go", "orgs.go", "orgs_create.go", @@ -132,7 +131,6 @@ go_library( "@com_github_sourcegraph_scip//bindings/go/scip", "@com_github_sourcegraph_sourcegraph_lib//batches", "@com_github_sourcegraph_sourcegraph_lib//batches/template", - "@com_github_sourcegraph_sourcegraph_lib//codeintel/lsif/scip", "@com_github_sourcegraph_sourcegraph_lib//codeintel/upload", "@com_github_sourcegraph_sourcegraph_lib//errors", "@com_github_sourcegraph_sourcegraph_lib//output", diff --git a/cmd/src/code_intel_upload.go b/cmd/src/code_intel_upload.go index f63f7394a9..24fab8eed6 100644 --- a/cmd/src/code_intel_upload.go +++ b/cmd/src/code_intel_upload.go @@ -202,7 +202,7 @@ func makeCodeIntelUploadURL(uploadID int) (string, error) { return "", err } - graphqlID := base64.URLEncoding.EncodeToString([]byte(fmt.Sprintf(`LSIFUpload:%d`, uploadID))) + graphqlID := base64.URLEncoding.EncodeToString([]byte(fmt.Sprintf(`SCIPUpload:%d`, uploadID))) url.Path = codeintelUploadFlags.repo + "/-/code-intelligence/uploads/" + graphqlID url.User = nil return url.String(), nil diff --git a/cmd/src/code_intel_upload_vendored.go b/cmd/src/code_intel_upload_vendored.go index 2cc01042a6..b5e4897af0 100644 --- a/cmd/src/code_intel_upload_vendored.go +++ b/cmd/src/code_intel_upload_vendored.go @@ -501,7 +501,7 @@ func makeUploadURL(opts uploadRequestOptions) (*url.URL, error) { path := opts.SourcegraphInstanceOptions.Path if path == "" { - path = "/.api/lsif/upload" + path = "/.api/scip/upload" } parsedUrl, err := url.Parse(opts.SourcegraphInstanceOptions.SourcegraphURL + path) From c15e3968029dead676026e72ae2b2f55aeaabffa Mon Sep 17 00:00:00 2001 From: Marc <7050295+marcleblanc2@users.noreply.github.com> Date: Sun, 2 Nov 2025 19:54:06 -0700 Subject: [PATCH 487/647] Chore: Fix snapshot upload filter for incompatible SQL statements (#1186) * Fix pgsql database name * Change extension filter to list of filters and stops * Revert "Fix pgsql database name" This reverts commit 30737b1491fd879215dfc83acf3a24c8a6fefbcb. * Update comments, function name, and file name for clarity --- cmd/src/snapshot_upload.go | 20 +-- internal/pgdump/extensions.go | 67 -------- internal/pgdump/extensions_test.go | 70 -------- internal/pgdump/pgdump_sql_filter.go | 136 +++++++++++++++ internal/pgdump/pgdump_sql_filter_test.go | 200 ++++++++++++++++++++++ 5 files changed, 346 insertions(+), 147 deletions(-) delete mode 100644 internal/pgdump/extensions.go delete mode 100644 internal/pgdump/extensions_test.go create mode 100644 internal/pgdump/pgdump_sql_filter.go create mode 100644 internal/pgdump/pgdump_sql_filter_test.go diff --git a/cmd/src/snapshot_upload.go b/cmd/src/snapshot_upload.go index b96df483d9..85e938f6e8 100644 --- a/cmd/src/snapshot_upload.go +++ b/cmd/src/snapshot_upload.go @@ -152,30 +152,30 @@ func copyDumpToBucket(ctx context.Context, src io.ReadSeeker, stat fs.FileInfo, // To assert against actual file size var totalWritten int64 - // Do a partial copy that trims out unwanted statements + // Do a partial copy, that filters out incompatible statements if trimExtensions { - written, err := pgdump.PartialCopyWithoutExtensions(object, src, progressFn) + written, err := pgdump.FilterInvalidLines(object, src, progressFn) if err != nil { - return errors.Wrap(err, "trim extensions and upload") + return errors.Wrap(err, "filter out incompatible statements and upload") } totalWritten += written } - // io.Copy is the best way to copy from a reader to writer in Go, and storage.Writer - // has its own chunking mechanisms internally. io.Reader is stateful, so this copy - // will just continue from where we left off if we use copyAndTrimExtensions. + // io.Copy is the best way to copy from a reader to writer in Go, + // storage.Writer has its own chunking mechanisms internally. + // io.Reader is stateful, so this copy will just continue from where FilterInvalidLines left off, if used written, err := io.Copy(object, src) if err != nil { return errors.Wrap(err, "upload") } totalWritten += written - // Progress is not called on completion of io.Copy, so we call it manually after to - // update our pretty progress bars. + // Progress is not called on completion of io.Copy, + // so we call it manually after to update our pretty progress bars. progressFn(written) - // Validate we have sent all data. copyAndTrimExtensions may add some bytes, so the - // check is not a strict equality. + // Validate we have sent all data. + // FilterInvalidLines may add some bytes, so the check is not a strict equality. size := stat.Size() if totalWritten < size { return errors.Newf("expected to write %d bytes, but actually wrote %d bytes (diff: %d bytes)", diff --git a/internal/pgdump/extensions.go b/internal/pgdump/extensions.go deleted file mode 100644 index 70f896a335..0000000000 --- a/internal/pgdump/extensions.go +++ /dev/null @@ -1,67 +0,0 @@ -package pgdump - -import ( - "bufio" - "bytes" - "io" - - "github.com/sourcegraph/sourcegraph/lib/errors" -) - -// PartialCopyWithoutExtensions will perform a partial copy of a SQL database dump from -// src to dst while commenting out EXTENSIONs-related statements. When it determines there -// are no more EXTENSIONs-related statements, it will return, resetting src to the position -// of the last contents written to dst. -// -// This is needed for import to Google Cloud Storage, which does not like many EXTENSION -// statements. For more details, see https://cloud.google.com/sql/docs/postgres/import-export/import-export-dmp -// -// Filtering requires reading entire lines into memory - this can be a very expensive -// operation, so when filtering is complete the more efficient io.Copy should be used -// to perform the remainder of the copy from src to dst. -func PartialCopyWithoutExtensions(dst io.Writer, src io.ReadSeeker, progressFn func(int64)) (int64, error) { - var ( - reader = bufio.NewReader(src) - // position we have consumed up to, track separately because bufio.Reader may have - // read ahead on src. This allows us to reset src later. - consumed int64 - // number of bytes we have actually written to dst - it should always be returned. - written int64 - // set to true when we have done all our filtering - noMoreExtensions bool - ) - - for !noMoreExtensions { - // Read up to a line, keeping track of our position in src - line, err := reader.ReadBytes('\n') - consumed += int64(len(line)) - if err != nil { - return written, err - } - - // Once we start seeing table creations, we are definitely done with extensions, - // so we can hand off the rest to the superior io.Copy implementation. - if bytes.HasPrefix(line, []byte("CREATE TABLE")) { - // we are done with extensions - noMoreExtensions = true - } else if bytes.HasPrefix(line, []byte("COMMENT ON EXTENSION")) { - // comment out this line - line = append([]byte("-- "), line...) - } - - // Write this line and update our progress before returning on error - lineWritten, err := dst.Write(line) - written += int64(lineWritten) - progressFn(written) - if err != nil { - return written, err - } - } - - // No more extensions - reset src to the last actual consumed position - _, err := src.Seek(consumed, io.SeekStart) - if err != nil { - return written, errors.Wrap(err, "reset src position") - } - return written, nil -} diff --git a/internal/pgdump/extensions_test.go b/internal/pgdump/extensions_test.go deleted file mode 100644 index d6c3286a84..0000000000 --- a/internal/pgdump/extensions_test.go +++ /dev/null @@ -1,70 +0,0 @@ -package pgdump - -import ( - "bytes" - "io" - "os" - "path/filepath" - "runtime" - "testing" - - "github.com/hexops/autogold" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestPartialCopyWithoutExtensions(t *testing.T) { - if runtime.GOOS == "windows" { - t.Skip("Test doesn't work on Windows of weirdness with t.TempDir() handling") - } - - // Create test data - there is no stdlib in-memory io.ReadSeeker implementation - src, err := os.Create(filepath.Join(t.TempDir(), t.Name())) - require.NoError(t, err) - _, err = src.WriteString(`-- Some comment - -CREATE EXTENSION foobar - -COMMENT ON EXTENSION barbaz - -CREATE TYPE asdf - -CREATE TABLE robert ( - ... -) - -CREATE TABLE bobhead ( - ... -)`) - require.NoError(t, err) - _, err = src.Seek(0, io.SeekStart) - require.NoError(t, err) - - // Set up target to assert against - var dst bytes.Buffer - - // Perform partial copy - _, err = PartialCopyWithoutExtensions(&dst, src, func(i int64) {}) - assert.NoError(t, err) - - // Copy rest of contents - _, err = io.Copy(&dst, src) - assert.NoError(t, err) - - // Assert contents (update with -update) - autogold.Want("partial-copy-without-extensions", `-- Some comment - -CREATE EXTENSION foobar - --- COMMENT ON EXTENSION barbaz - -CREATE TYPE asdf - -CREATE TABLE robert ( - ... -) - -CREATE TABLE bobhead ( - ... -)`).Equal(t, dst.String()) -} diff --git a/internal/pgdump/pgdump_sql_filter.go b/internal/pgdump/pgdump_sql_filter.go new file mode 100644 index 0000000000..e365230229 --- /dev/null +++ b/internal/pgdump/pgdump_sql_filter.go @@ -0,0 +1,136 @@ +package pgdump + +import ( + "bufio" + "bytes" + "io" + + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +// FilterInvalidLines copies the initial lines of the pg_dump-created .sql files, +// from src to dst (the GCS bucket), +// until it hits a line prefixed with a filterEndMarker, +// while commenting out the linesToFilter which cause `gcloud sql import` to error out. +// It then resets src to the position of the last contents written to dst. +// +// Filtering requires reading entire lines into memory, +// this can be a very expensive operation, so when filtering is complete, +// the more efficient io.Copy is used to perform the remainder of the copy in the calling funciton +// +// pg_dump writes these .sql files based on its own version, +// not based on the Postgres version of either the source or destination database; +// so self-hosted customers' diverse database environments +// have inserted a variety of statements into the .sql files which cause the import to fail +// For details, see https://cloud.google.com/sql/docs/postgres/import-export/import-export-dmp +func FilterInvalidLines(dst io.Writer, src io.ReadSeeker, progressFn func(int64)) (int64, error) { + var ( + reader = bufio.NewReader(src) + + // Position we have consumed up to + // Tracked separately because bufio.Reader may have read ahead on src + // This allows us to reset src later + consumed int64 + + // Number of bytes we have actually written to dst + // It should always be returned + written int64 + + // Set to true when we start to hit lines which indicate that we may be finished filtering + noMoreLinesToFilter bool + + filterEndMarkers = []string{ + "CREATE TABLE", + "INSERT INTO", + } + + linesToFilter = []string{ + + "DROP DATABASE", + "CREATE DATABASE", + "COMMENT ON DATABASE", + + "DROP SCHEMA", + "CREATE SCHEMA", + "COMMENT ON SCHEMA", + + "DROP EXTENSION", + "CREATE EXTENSION", + "COMMENT ON EXTENSION", + + "SET transaction_timeout", // pg_dump v17, importing to Postgres 16 + + "\\connect", + + // Cloud instances' databases have been upgraded to Postgres v16.10, + // which should include support for \restrict and \unrestrict + // but leaving in the list in case we need to re-add them + // "\\restrict", + // To handle the \unrestrict command, + // we'd have to add a search from the end of the file + // "\\unrestrict", + // Remove comments after databases are upgraded >= Postgres 17 + } + ) + + for !noMoreLinesToFilter { + + // Read up to a line, keeping track of our position in src + line, err := reader.ReadBytes('\n') + consumed += int64(len(line)) + + // If this function has read through the whole file without hitting a filterEndMarker, + // then handle the last line correctly + if err == io.EOF { + noMoreLinesToFilter = true + + // If the reader has found a different error, + // then return what we've processed so far + } else if err != nil { + return written, err + } + + // Once we start seeing these lines, + // we are probably done with the invalid statements, + // so we can hand off the rest to the more efficient io.Copy implementation + for _, filterEndMarker := range filterEndMarkers { + + if bytes.HasPrefix(line, []byte(filterEndMarker)) { + + // We are probably done with the invalid statements + noMoreLinesToFilter = true + break + + } + } + + if !noMoreLinesToFilter { + + for _, lineToFilter := range linesToFilter { + + if bytes.HasPrefix(line, []byte(lineToFilter)) { + + line = append([]byte("-- "), line...) + break + + } + } + } + + // Write this line and update our progress before returning on error + lineWritten, err := dst.Write(line) + written += int64(lineWritten) + progressFn(written) + if err != nil { + return written, err + } + } + + // No more lines to filter + // Reset src to the last actual consumed position + _, err := src.Seek(consumed, io.SeekStart) + if err != nil { + return written, errors.Wrap(err, "reset src position") + } + return written, nil +} diff --git a/internal/pgdump/pgdump_sql_filter_test.go b/internal/pgdump/pgdump_sql_filter_test.go new file mode 100644 index 0000000000..57a9b13a1b --- /dev/null +++ b/internal/pgdump/pgdump_sql_filter_test.go @@ -0,0 +1,200 @@ +package pgdump + +import ( + "bytes" + "io" + "os" + "runtime" + "testing" + + "github.com/hexops/autogold" + "github.com/stretchr/testify/require" +) + +// createTestFile creates a temporary file with the given content for testing +func createTestFile(t *testing.T, content string) *os.File { + src, err := os.CreateTemp(t.TempDir(), "test-*.sql") + require.NoError(t, err) + _, err = src.WriteString(content) + require.NoError(t, err) + _, err = src.Seek(0, io.SeekStart) + require.NoError(t, err) + return src +} + +func TestFilterInvalidLines(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("Test doesn't work on Windows of weirdness with t.TempDir() handling") + } + + tests := []struct { + name string + input string + want string + }{ + + { + name: "EOF - input file doesn't contain any filterEndMarkers, or linesToFilter", + input: ` +-- +-- PostgreSQL database dump +-- +`, + want: ` +-- +-- PostgreSQL database dump +-- +`, + }, + { + name: "EOF - input file doesn't contain any filterEndMarkers, but does contain linesToFilter", + input: ` +DROP DATABASE pgsql; +`, + want: ` +-- DROP DATABASE pgsql; +`, + }, + { + name: "Customer-realistic dump, with extensions and schemas", + input: ` +-- +-- PostgreSQL database dump +-- + +\restrict 1e9XN4yltwkS6RMoyhkFC6hmzrkbz4fZIVvJSYP3h5B1Qvii1WnhlslcPAzK8Tb + +-- Dumped from database version 12.22 +-- Dumped by pg_dump version 14.19 (Homebrew) + +-- Started on 2025-10-29 20:49:56 IST + +SET transaction_timeout = 10; +SET statement_timeout = 0; +SET lock_timeout = 0; +SET idle_in_transaction_session_timeout = 0; +SET client_encoding = 'UTF8'; +SET standard_conforming_strings = on; +SELECT pg_catalog.set_config('search_path', '', false); +SET check_function_bodies = false; +SET xmloption = content; +SET client_min_messages = warning; +SET row_security = off; + +DROP DATABASE pgsql IF EXISTS; +CREATE DATABASE pgsql; +COMMENT ON DATABASE pgsql IS 'database'; + +\connect pgsql + +DROP SCHEMA public IF EXISTS; +CREATE SCHEMA public; +COMMENT ON SCHEMA public IS 'schema'; + +DROP EXTENSION IF EXISTS pg_stat_statements; +CREATE EXTENSION pg_stat_statements; +COMMENT ON EXTENSION pg_stat_statements IS 'extension'; + +ALTER TABLE IF EXISTS ONLY "public"."webhooks" DROP CONSTRAINT IF EXISTS "webhooks_updated_by_user_id_fkey"; +DROP TRIGGER IF EXISTS "versions_insert" ON "public"."versions"; +DROP INDEX IF EXISTS "public"."webhook_logs_status_code_idx"; +DROP SEQUENCE IF EXISTS "public"."webhooks_id_seq"; +DROP TABLE IF EXISTS "public"."webhooks"; +SET default_tablespace = ''; +SET default_table_access_method = "heap"; + +CREATE TABLE "public"."access_tokens" ( + "id" bigint NOT NULL, + "subject_user_id" integer NOT NULL, + "value_sha256" "bytea" NOT NULL, + "note" "text" NOT NULL, + "created_at" timestamp with time zone DEFAULT "now"() NOT NULL, + "last_used_at" timestamp with time zone, + "deleted_at" timestamp with time zone, + "creator_user_id" integer NOT NULL, + "scopes" "text"[] NOT NULL, + "internal" boolean DEFAULT false +); + +\unrestrict 1e9XN4yltwkS6RMoyhkFC6hmzrkbz4fZIVvJSYP3h5B1Qvii1WnhlslcPAzK8Tb +`, + want: ` +-- +-- PostgreSQL database dump +-- + +\restrict 1e9XN4yltwkS6RMoyhkFC6hmzrkbz4fZIVvJSYP3h5B1Qvii1WnhlslcPAzK8Tb + +-- Dumped from database version 12.22 +-- Dumped by pg_dump version 14.19 (Homebrew) + +-- Started on 2025-10-29 20:49:56 IST + +-- SET transaction_timeout = 10; +SET statement_timeout = 0; +SET lock_timeout = 0; +SET idle_in_transaction_session_timeout = 0; +SET client_encoding = 'UTF8'; +SET standard_conforming_strings = on; +SELECT pg_catalog.set_config('search_path', '', false); +SET check_function_bodies = false; +SET xmloption = content; +SET client_min_messages = warning; +SET row_security = off; + +-- DROP DATABASE pgsql IF EXISTS; +-- CREATE DATABASE pgsql; +-- COMMENT ON DATABASE pgsql IS 'database'; + +-- \connect pgsql + +-- DROP SCHEMA public IF EXISTS; +-- CREATE SCHEMA public; +-- COMMENT ON SCHEMA public IS 'schema'; + +-- DROP EXTENSION IF EXISTS pg_stat_statements; +-- CREATE EXTENSION pg_stat_statements; +-- COMMENT ON EXTENSION pg_stat_statements IS 'extension'; + +ALTER TABLE IF EXISTS ONLY "public"."webhooks" DROP CONSTRAINT IF EXISTS "webhooks_updated_by_user_id_fkey"; +DROP TRIGGER IF EXISTS "versions_insert" ON "public"."versions"; +DROP INDEX IF EXISTS "public"."webhook_logs_status_code_idx"; +DROP SEQUENCE IF EXISTS "public"."webhooks_id_seq"; +DROP TABLE IF EXISTS "public"."webhooks"; +SET default_tablespace = ''; +SET default_table_access_method = "heap"; + +CREATE TABLE "public"."access_tokens" ( + "id" bigint NOT NULL, + "subject_user_id" integer NOT NULL, + "value_sha256" "bytea" NOT NULL, + "note" "text" NOT NULL, + "created_at" timestamp with time zone DEFAULT "now"() NOT NULL, + "last_used_at" timestamp with time zone, + "deleted_at" timestamp with time zone, + "creator_user_id" integer NOT NULL, + "scopes" "text"[] NOT NULL, + "internal" boolean DEFAULT false +); + +\unrestrict 1e9XN4yltwkS6RMoyhkFC6hmzrkbz4fZIVvJSYP3h5B1Qvii1WnhlslcPAzK8Tb +`, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + src := createTestFile(t, tt.input) + var dst bytes.Buffer + + _, err := FilterInvalidLines(&dst, src, func(i int64) {}) + require.NoError(t, err) + + // Copy rest of contents + _, err = io.Copy(&dst, src) + require.NoError(t, err) + + autogold.Want(tt.name, tt.want).Equal(t, dst.String()) + }) + } +} From 153141af526394cccfe4b26ec121adbbeec4bcf6 Mon Sep 17 00:00:00 2001 From: Marc <7050295+marcleblanc2@users.noreply.github.com> Date: Mon, 3 Nov 2025 09:57:44 -0700 Subject: [PATCH 488/647] Chore: Rename 'primary' to 'pgsql' in the src-cli commands for database uploads (#1187) Renaming the database in the src-cli commands, to make instructions consistent to customer admins and IEs during the self-hosted -> SG Cloud migration --- cmd/src/snapshot_databases.go | 10 +++++----- cmd/src/snapshot_restore.go | 2 +- internal/pgdump/pgdump.go | 6 +++--- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/cmd/src/snapshot_databases.go b/cmd/src/snapshot_databases.go index 648667f6fe..c614f3d21e 100644 --- a/cmd/src/snapshot_databases.go +++ b/cmd/src/snapshot_databases.go @@ -19,13 +19,13 @@ func init() { Note that these commands are intended for use as reference - you may need to adjust the commands for your deployment. USAGE - src [-v] snapshot databases [--targets=] [--run] + src [-v] snapshot databases [--targets=] [--run] TARGETS FILES Predefined targets are available based on default Sourcegraph configurations ('docker', 'k8s'). Custom targets configuration can be provided in YAML format with '--targets=target.yaml', e.g. - primary: + pgsql: target: ... # the DSN of the database deployment, e.g. in docker, the name of the database container dbname: ... # name of database username: ... # username for database access @@ -109,7 +109,7 @@ TARGETS FILES // predefinedDatabaseDumpTargets is based on default Sourcegraph configurations. var predefinedDatabaseDumpTargets = map[string]pgdump.Targets{ "local": { - Primary: pgdump.Target{ + Pgsql: pgdump.Target{ DBName: "sg", Username: "sg", Password: "sg", @@ -126,7 +126,7 @@ var predefinedDatabaseDumpTargets = map[string]pgdump.Targets{ }, }, "docker": { // based on deploy-sourcegraph-managed - Primary: pgdump.Target{ + Pgsql: pgdump.Target{ Target: "pgsql", DBName: "sg", Username: "sg", @@ -146,7 +146,7 @@ var predefinedDatabaseDumpTargets = map[string]pgdump.Targets{ }, }, "k8s": { // based on deploy-sourcegraph-helm - Primary: pgdump.Target{ + Pgsql: pgdump.Target{ Target: "statefulset/pgsql", DBName: "sg", Username: "sg", diff --git a/cmd/src/snapshot_restore.go b/cmd/src/snapshot_restore.go index a1d71018fa..9ae941e609 100644 --- a/cmd/src/snapshot_restore.go +++ b/cmd/src/snapshot_restore.go @@ -25,7 +25,7 @@ TARGETS FILES Predefined targets are available based on default Sourcegraph configurations ('docker', 'k8s'). Custom targets configuration can be provided in YAML format with '--targets=target.yaml', e.g. - primary: + pgsql: target: ... # the DSN of the database deployment, e.g. in docker, the name of the database container dbname: ... # name of database username: ... # username for database access diff --git a/internal/pgdump/pgdump.go b/internal/pgdump/pgdump.go index 6734342bbe..1a3530a065 100644 --- a/internal/pgdump/pgdump.go +++ b/internal/pgdump/pgdump.go @@ -9,7 +9,7 @@ import ( // Targets represents configuration for each of Sourcegraph's databases. type Targets struct { - Primary Target `yaml:"primary"` + Pgsql Target `yaml:"pgsql"` CodeIntel Target `yaml:"codeintel"` CodeInsights Target `yaml:"codeinsights"` } @@ -59,8 +59,8 @@ type Output struct { // path. It can be provided a zero-value Targets to just generate the output paths. func Outputs(dir string, targets Targets) []Output { return []Output{{ - Output: filepath.Join(dir, "primary.sql"), - Target: targets.Primary, + Output: filepath.Join(dir, "pgsql.sql"), + Target: targets.Pgsql, }, { Output: filepath.Join(dir, "codeintel.sql"), Target: targets.CodeIntel, From c146be394c82aded15abe9269b02a3ed33858478 Mon Sep 17 00:00:00 2001 From: Keegan Carruthers-Smith Date: Thu, 6 Nov 2025 11:26:06 +0200 Subject: [PATCH 489/647] Remove outdated Bazel build files (#1189) These build files are no longer used by CI, and the SG monorepo relies on pre-built binaries instead of depending on these build files. Amp-Thread-ID: https://ampcode.com/threads/T-00f05ffe-a46d-40bd-9916-eee14e9cf89b Co-authored-by: Amp --- BUILD.bazel | 16 - WORKSPACE | 62 - cmd/src/BUILD.bazel | 184 -- deps.bzl | 3301 ------------------------ internal/api/BUILD.bazel | 34 - internal/api/mock/BUILD.bazel | 12 - internal/batches/BUILD.bazel | 17 - internal/batches/docker/BUILD.bazel | 35 - internal/batches/executor/BUILD.bazel | 66 - internal/batches/graphql/BUILD.bazel | 12 - internal/batches/log/BUILD.bazel | 14 - internal/batches/mock/BUILD.bazel | 18 - internal/batches/repozip/BUILD.bazel | 28 - internal/batches/service/BUILD.bazel | 43 - internal/batches/ui/BUILD.bazel | 50 - internal/batches/util/BUILD.bazel | 9 - internal/batches/watchdog/BUILD.bazel | 16 - internal/batches/workspace/BUILD.bazel | 47 - internal/cmderrors/BUILD.bazel | 9 - internal/codeintel/BUILD.bazel | 20 - internal/exec/BUILD.bazel | 11 - internal/exec/expect/BUILD.bazel | 14 - internal/instancehealth/BUILD.bazel | 27 - internal/lazyregexp/BUILD.bazel | 9 - internal/pgdump/BUILD.bazel | 23 - internal/servegit/BUILD.bazel | 22 - internal/streaming/BUILD.bazel | 25 - internal/users/BUILD.bazel | 13 - internal/validate/BUILD.bazel | 8 - internal/validate/install/BUILD.bazel | 19 - internal/validate/kube/BUILD.bazel | 48 - internal/version/BUILD.bazel | 8 - 32 files changed, 4220 deletions(-) delete mode 100644 BUILD.bazel delete mode 100644 WORKSPACE delete mode 100644 cmd/src/BUILD.bazel delete mode 100644 deps.bzl delete mode 100644 internal/api/BUILD.bazel delete mode 100644 internal/api/mock/BUILD.bazel delete mode 100644 internal/batches/BUILD.bazel delete mode 100644 internal/batches/docker/BUILD.bazel delete mode 100644 internal/batches/executor/BUILD.bazel delete mode 100644 internal/batches/graphql/BUILD.bazel delete mode 100644 internal/batches/log/BUILD.bazel delete mode 100644 internal/batches/mock/BUILD.bazel delete mode 100644 internal/batches/repozip/BUILD.bazel delete mode 100644 internal/batches/service/BUILD.bazel delete mode 100644 internal/batches/ui/BUILD.bazel delete mode 100644 internal/batches/util/BUILD.bazel delete mode 100644 internal/batches/watchdog/BUILD.bazel delete mode 100644 internal/batches/workspace/BUILD.bazel delete mode 100644 internal/cmderrors/BUILD.bazel delete mode 100644 internal/codeintel/BUILD.bazel delete mode 100644 internal/exec/BUILD.bazel delete mode 100644 internal/exec/expect/BUILD.bazel delete mode 100644 internal/instancehealth/BUILD.bazel delete mode 100644 internal/lazyregexp/BUILD.bazel delete mode 100644 internal/pgdump/BUILD.bazel delete mode 100644 internal/servegit/BUILD.bazel delete mode 100644 internal/streaming/BUILD.bazel delete mode 100644 internal/users/BUILD.bazel delete mode 100644 internal/validate/BUILD.bazel delete mode 100644 internal/validate/install/BUILD.bazel delete mode 100644 internal/validate/kube/BUILD.bazel delete mode 100644 internal/version/BUILD.bazel diff --git a/BUILD.bazel b/BUILD.bazel deleted file mode 100644 index fada8decbf..0000000000 --- a/BUILD.bazel +++ /dev/null @@ -1,16 +0,0 @@ -# gazelle:prefix github.com/sourcegraph/src-cli -# gazelle:build_file_name BUILD.bazel -load("@bazel_gazelle//:def.bzl", "gazelle") - -gazelle(name = "gazelle") - -gazelle( - name = "gazelle-update-repos", - args = [ - "-from_file=go.mod", - "-to_macro=deps.bzl%go_dependencies", - "-prune", - "-build_file_proto_mode=disable_global", - ], - command = "update-repos", -) diff --git a/WORKSPACE b/WORKSPACE deleted file mode 100644 index 3c5ffd973b..0000000000 --- a/WORKSPACE +++ /dev/null @@ -1,62 +0,0 @@ -load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") - -http_archive( - name = "bazel_skylib", - sha256 = "cd55a062e763b9349921f0f5db8c3933288dc8ba4f76dd9416aac68acee3cb94", - urls = [ - "https://mirror.bazel.build/github.com/bazelbuild/bazel-skylib/releases/download/1.5.0/bazel-skylib-1.5.0.tar.gz", - "https://github.com/bazelbuild/bazel-skylib/releases/download/1.5.0/bazel-skylib-1.5.0.tar.gz", - ], -) - -load("@bazel_skylib//:workspace.bzl", "bazel_skylib_workspace") - -bazel_skylib_workspace() - -http_archive( - name = "aspect_bazel_lib", - sha256 = "3522895fa13b97e8b27e3b642045682aa4233ae1a6b278aad6a3b483501dc9f2", - strip_prefix = "bazel-lib-2.20.0", - url = "https://github.com/aspect-build/bazel-lib/releases/download/v2.20.0/bazel-lib-v2.20.0.tar.gz", -) - -http_archive( - name = "io_bazel_rules_go", - sha256 = "f74c98d6df55217a36859c74b460e774abc0410a47cc100d822be34d5f990f16", - urls = [ - "https://mirror.bazel.build/github.com/bazelbuild/rules_go/releases/download/v0.47.1/rules_go-v0.47.1.zip", - "https://github.com/bazelbuild/rules_go/releases/download/v0.47.1/rules_go-v0.47.1.zip", - ], -) - -http_archive( - name = "bazel_gazelle", - sha256 = "75df288c4b31c81eb50f51e2e14f4763cb7548daae126817247064637fd9ea62", - urls = [ - "https://mirror.bazel.build/github.com/bazelbuild/bazel-gazelle/releases/download/v0.36.0/bazel-gazelle-v0.36.0.tar.gz", - "https://github.com/bazelbuild/bazel-gazelle/releases/download/v0.36.0/bazel-gazelle-v0.36.0.tar.gz", - ], -) - -# Go toolchain setup -load("@io_bazel_rules_go//go:deps.bzl", "go_register_toolchains", "go_rules_dependencies") -load("@bazel_gazelle//:deps.bzl", "gazelle_dependencies","go_repository") -load("//:deps.bzl", "go_dependencies") - -# gazelle:repository_macro deps.bzl%go_dependencies -go_dependencies() - -go_rules_dependencies() - -go_register_toolchains( - version = "1.19.6", -) - -gazelle_dependencies() - -go_repository( - name = "com_github_aws_aws_sdk_go_v2_service_eks", - importpath = "github.com/aws/aws-sdk-go-v2/service/eks", - version = "v1.27.3", - sum = "h1:jlh0AJVhauqSGaiwRJx4j0LNBGEAaGn46sA1XJyTj0E=", -) \ No newline at end of file diff --git a/cmd/src/BUILD.bazel b/cmd/src/BUILD.bazel deleted file mode 100644 index 44dcf7729d..0000000000 --- a/cmd/src/BUILD.bazel +++ /dev/null @@ -1,184 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library", "go_test") - -go_library( - name = "src_lib", - srcs = [ - "admin.go", - "admin_create.go", - "api.go", - "batch.go", - "batch_apply.go", - "batch_common.go", - "batch_exec.go", - "batch_new.go", - "batch_preview.go", - "batch_remote.go", - "batch_repositories.go", - "batch_validate.go", - "cmd.go", - "code_intel.go", - "code_intel_upload.go", - "code_intel_upload_flags.go", - "codeowners.go", - "codeowners_create.go", - "codeowners_delete.go", - "codeowners_get.go", - "codeowners_update.go", - "colors.go", - "config.go", - "config_edit.go", - "config_get.go", - "config_list.go", - "debug.go", - "debug_common.go", - "debug_compose.go", - "debug_kube.go", - "debug_server.go", - "doc.go", - "extensions.go", - "extensions_copy.go", - "extensions_delete.go", - "extensions_get.go", - "extensions_list.go", - "extensions_publish.go", - "extsvc.go", - "extsvc_create.go", - "extsvc_edit.go", - "extsvc_list.go", - "format.go", - "headers.go", - "login.go", - "main.go", - "orgs.go", - "orgs_create.go", - "orgs_delete.go", - "orgs_get.go", - "orgs_list.go", - "orgs_members.go", - "orgs_members_add.go", - "orgs_members_remove.go", - "repos.go", - "repos_add_metadata.go", - "repos_delete.go", - "repos_delete_metadata.go", - "repos_get.go", - "repos_list.go", - "repos_update_metadata.go", - "search.go", - "search_alert.go", - "search_stream.go", - "servegit.go", - "snapshot.go", - "snapshot_databases.go", - "snapshot_restore.go", - "snapshot_summary.go", - "snapshot_testcmd.go", - "snapshot_upload.go", - "team_members_list.go", - "teams.go", - "teams_create.go", - "teams_delete.go", - "teams_list.go", - "teams_members.go", - "teams_members_add.go", - "teams_members_remove.go", - "teams_update.go", - "users.go", - "users_create.go", - "users_delete.go", - "users_get.go", - "users_list.go", - "users_prune.go", - "users_tag.go", - "validate.go", - "validate_install.go", - "validate_kube.go", - "version.go", - ], - importpath = "github.com/sourcegraph/src-cli/cmd/src", - visibility = ["//visibility:private"], - deps = [ - "//internal/api", - "//internal/batches", - "//internal/batches/docker", - "//internal/batches/executor", - "//internal/batches/graphql", - "//internal/batches/log", - "//internal/batches/repozip", - "//internal/batches/service", - "//internal/batches/ui", - "//internal/batches/watchdog", - "//internal/batches/workspace", - "//internal/cmderrors", - "//internal/codeintel", - "//internal/exec", - "//internal/instancehealth", - "//internal/pgdump", - "//internal/servegit", - "//internal/streaming", - "//internal/users", - "//internal/validate/install", - "//internal/validate/kube", - "//internal/version", - "@com_github_dustin_go_humanize//:go-humanize", - "@com_github_google_go_cmp//cmp", - "@com_github_grafana_regexp//:regexp", - "@com_github_jedib0t_go_pretty_v6//table", - "@com_github_mattn_go_isatty//:go-isatty", - "@com_github_pkg_browser//:browser", - "@com_github_sourcegraph_conc//pool", - "@com_github_sourcegraph_jsonx//:jsonx", - "@com_github_sourcegraph_scip//bindings/go/scip", - "@com_github_sourcegraph_sourcegraph_lib//batches", - "@com_github_sourcegraph_sourcegraph_lib//batches/template", - "@com_github_sourcegraph_sourcegraph_lib//codeintel/upload", - "@com_github_sourcegraph_sourcegraph_lib//errors", - "@com_github_sourcegraph_sourcegraph_lib//output", - "@com_google_cloud_go_storage//:storage", - "@com_jaytaylor_html2text//:html2text", - "@in_gopkg_yaml_v3//:yaml_v3", - "@io_k8s_client_go//kubernetes", - "@io_k8s_client_go//plugin/pkg/client/auth/azure", - "@io_k8s_client_go//plugin/pkg/client/auth/gcp", - "@io_k8s_client_go//tools/clientcmd", - "@io_k8s_client_go//util/homedir", - "@org_golang_google_api//option", - "@org_golang_google_protobuf//proto", - "@org_golang_x_net//context", - "@org_golang_x_sync//errgroup", - "@org_golang_x_sync//semaphore", - ], -) - -go_binary( - name = "src", - embed = [":src_lib"], - visibility = ["//visibility:public"], -) - -go_test( - name = "src_test", - srcs = [ - "code_intel_upload_flags_test.go", - "extensions_publish_test.go", - "headers_test.go", - "login_test.go", - "main_test.go", - "search_alert_test.go", - "search_stream_test.go", - "search_test.go", - ], - data = glob(["testdata/**"]), - embed = [":src_lib"], - deps = [ - "//internal/api", - "//internal/cmderrors", - "//internal/streaming", - "@com_github_google_go_cmp//cmp", - "@com_github_grafana_regexp//:regexp", - "@com_github_hexops_autogold//:autogold", - "@com_github_sourcegraph_scip//bindings/go/scip", - "@com_github_stretchr_testify//require", - "@org_golang_google_protobuf//proto", - ], -) diff --git a/deps.bzl b/deps.bzl deleted file mode 100644 index 2c5cf55adc..0000000000 --- a/deps.bzl +++ /dev/null @@ -1,3301 +0,0 @@ -load("@bazel_gazelle//:deps.bzl", "go_repository") - -def go_dependencies(): - go_repository( - name = "cc_mvdan_gofumpt", - build_file_proto_mode = "disable_global", - importpath = "mvdan.cc/gofumpt", - sum = "h1:JVf4NN1mIpHogBj7ABpgOyZc65/UUOkKQFkoURsz4MM=", - version = "v0.4.0", - ) - go_repository( - name = "co_honnef_go_tools", - build_file_proto_mode = "disable_global", - importpath = "honnef.co/go/tools", - sum = "h1:/hemPrYIhOhy8zYrNj+069zDB68us2sMGsfkFJO0iZs=", - version = "v0.0.0-20190523083050-ea95bdfd59fc", - ) - go_repository( - name = "com_github_ajg_form", - build_file_proto_mode = "disable_global", - importpath = "github.com/ajg/form", - sum = "h1:t9c7v8JUKu/XxOGBU0yjNpaMloxGEJhUkqFRq0ibGeU=", - version = "v1.5.1", - ) - go_repository( - name = "com_github_alecthomas_chroma", - build_file_proto_mode = "disable_global", - importpath = "github.com/alecthomas/chroma", - sum = "h1:7XDcGkCQopCNKjZHfYrNLraA+M7e0fMiJ/Mfikbfjek=", - version = "v0.10.0", - ) - go_repository( - name = "com_github_alecthomas_kingpin", - build_file_proto_mode = "disable_global", - importpath = "github.com/alecthomas/kingpin", - sum = "h1:5svnBTFgJjZvGKyYBtMB0+m5wvrbUHiqye8wRJMlnYI=", - version = "v2.2.6+incompatible", - ) - go_repository( - name = "com_github_alecthomas_template", - build_file_proto_mode = "disable_global", - importpath = "github.com/alecthomas/template", - sum = "h1:JYp7IbQjafoB+tBA3gMyHYHrpOtNuDiK/uB5uXxq5wM=", - version = "v0.0.0-20190718012654-fb15b899a751", - ) - go_repository( - name = "com_github_alecthomas_units", - build_file_proto_mode = "disable_global", - importpath = "github.com/alecthomas/units", - sum = "h1:s6gZFSlWYmbqAuRjVTiNNhvNRfY2Wxp9nhfyel4rklc=", - version = "v0.0.0-20211218093645-b94a6e3cc137", - ) - go_repository( - name = "com_github_andreasbriese_bbloom", - build_file_proto_mode = "disable_global", - importpath = "github.com/AndreasBriese/bbloom", - sum = "h1:HD8gA2tkByhMAwYaFAX9w2l7vxvBQ5NMoxDrkhqhtn4=", - version = "v0.0.0-20190306092124-e2d15f34fcf9", - ) - go_repository( - name = "com_github_andybalholm_brotli", - build_file_proto_mode = "disable_global", - importpath = "github.com/andybalholm/brotli", - sum = "h1:V7DdXeJtZscaqfNuAdSRuRFzuiKlHSC/Zh3zl9qY3JY=", - version = "v1.0.4", - ) - go_repository( - name = "com_github_aokoli_goutils", - build_file_proto_mode = "disable_global", - importpath = "github.com/aokoli/goutils", - sum = "h1:7fpzNGoJ3VA8qcrm++XEE1QUe0mIwNeLa02Nwq7RDkg=", - version = "v1.0.1", - ) - go_repository( - name = "com_github_armon_consul_api", - build_file_proto_mode = "disable_global", - importpath = "github.com/armon/consul-api", - sum = "h1:G1bPvciwNyF7IUmKXNt9Ak3m6u9DE1rF+RmtIkBpVdA=", - version = "v0.0.0-20180202201655-eb2c6b5be1b6", - ) - go_repository( - name = "com_github_armon_go_socks5", - build_file_proto_mode = "disable_global", - importpath = "github.com/armon/go-socks5", - sum = "h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio=", - version = "v0.0.0-20160902184237-e75332964ef5", - ) - go_repository( - name = "com_github_asaskevich_govalidator", - build_file_proto_mode = "disable_global", - importpath = "github.com/asaskevich/govalidator", - sum = "h1:idn718Q4B6AGu/h5Sxe66HYVdqdGu2l9Iebqhi/AEoA=", - version = "v0.0.0-20190424111038-f61b66f89f4a", - ) - go_repository( - name = "com_github_aws_aws_sdk_go_v2", - build_file_proto_mode = "disable_global", - importpath = "github.com/aws/aws-sdk-go-v2", - sum = "h1:TzCUW1Nq4H8Xscph5M/skINUitxM5UBAyvm2s7XBzL4=", - version = "v1.17.5", - ) - go_repository( - name = "com_github_aws_aws_sdk_go_v2_config", - build_file_proto_mode = "disable_global", - importpath = "github.com/aws/aws-sdk-go-v2/config", - sum = "h1:v0xlYqbO6/EVlM8tUn2QEOA7btQxcgidEq2JRDBPTho=", - version = "v1.18.13", - ) - go_repository( - name = "com_github_aws_aws_sdk_go_v2_credentials", - build_file_proto_mode = "disable_global", - importpath = "github.com/aws/aws-sdk-go-v2/credentials", - sum = "h1:zw1KAc1kl00NYd3ofVmFrb09qnYlSQMeh+fmlQRAihI=", - version = "v1.13.13", - ) - go_repository( - name = "com_github_aws_aws_sdk_go_v2_feature_ec2_imds", - build_file_proto_mode = "disable_global", - importpath = "github.com/aws/aws-sdk-go-v2/feature/ec2/imds", - sum = "h1:3aMfcTmoXtTZnaT86QlVaYh+BRMbvrrmZwIQ5jWqCZQ=", - version = "v1.12.22", - ) - go_repository( - name = "com_github_aws_aws_sdk_go_v2_internal_configsources", - build_file_proto_mode = "disable_global", - importpath = "github.com/aws/aws-sdk-go-v2/internal/configsources", - sum = "h1:9/aKwwus0TQxppPXFmf010DFrE+ssSbzroLVYINA+xE=", - version = "v1.1.29", - ) - go_repository( - name = "com_github_aws_aws_sdk_go_v2_internal_endpoints_v2", - build_file_proto_mode = "disable_global", - importpath = "github.com/aws/aws-sdk-go-v2/internal/endpoints/v2", - sum = "h1:b/Vn141DBuLVgXbhRWIrl9g+ww7G+ScV5SzniWR13jQ=", - version = "v2.4.23", - ) - go_repository( - name = "com_github_aws_aws_sdk_go_v2_internal_ini", - build_file_proto_mode = "disable_global", - importpath = "github.com/aws/aws-sdk-go-v2/internal/ini", - sum = "h1:J4xhFd6zHhdF9jPP0FQJ6WknzBboGMBNjKOv4iTuw4A=", - version = "v1.3.29", - ) - go_repository( - name = "com_github_aws_aws_sdk_go_v2_service_ec2", - build_file_proto_mode = "disable_global", - importpath = "github.com/aws/aws-sdk-go-v2/service/ec2", - sum = "h1:4dt0Mg5veHbMLcA2JAR9LDxvqXjtG0ZLQdxZG/2wHy4=", - version = "v1.86.0", - ) - go_repository( - name = "com_github_aws_aws_sdk_go_v2_service_eks", - build_file_proto_mode = "disable_global", - importpath = "github.com/aws/aws-sdk-go-v2/service/eks", - sum = "h1:jlh0AJVhauqSGaiwRJx4j0LNBGEAaGn46sA1XJyTj0E=", - version = "v1.27.3", - ) - go_repository( - name = "com_github_aws_aws_sdk_go_v2_service_iam", - build_file_proto_mode = "disable_global", - importpath = "github.com/aws/aws-sdk-go-v2/service/iam", - sum = "h1:vaDXu/p/5RNK++B2pqKS3hwsWGxsVjJJqPaAMg0OkiM=", - version = "v1.19.3", - ) - go_repository( - name = "com_github_aws_aws_sdk_go_v2_service_internal_presigned_url", - build_file_proto_mode = "disable_global", - importpath = "github.com/aws/aws-sdk-go-v2/service/internal/presigned-url", - sum = "h1:LjFQf8hFuMO22HkV5VWGLBvmCLBCLPivUAmpdpnp4Vs=", - version = "v1.9.22", - ) - go_repository( - name = "com_github_aws_aws_sdk_go_v2_service_sso", - build_file_proto_mode = "disable_global", - importpath = "github.com/aws/aws-sdk-go-v2/service/sso", - sum = "h1:EN102fWY7hI5u/2FPheTrwwMHkSXfl49RYkeEnJsrCU=", - version = "v1.12.2", - ) - go_repository( - name = "com_github_aws_aws_sdk_go_v2_service_ssooidc", - build_file_proto_mode = "disable_global", - importpath = "github.com/aws/aws-sdk-go-v2/service/ssooidc", - sum = "h1:f1lmlce7r13CX1BPyPqt9oh/H+uqOWc9367lDoGGwNQ=", - version = "v1.14.2", - ) - go_repository( - name = "com_github_aws_aws_sdk_go_v2_service_sts", - build_file_proto_mode = "disable_global", - importpath = "github.com/aws/aws-sdk-go-v2/service/sts", - sum = "h1:s49mSnsBZEXjfGBkRfmK+nPqzT7Lt3+t2SmAKNyHblw=", - version = "v1.18.3", - ) - go_repository( - name = "com_github_aws_smithy_go", - build_file_proto_mode = "disable_global", - importpath = "github.com/aws/smithy-go", - sum = "h1:hgz0X/DX0dGqTYpGALqXJoRKRj5oQ7150i5FdTePzO8=", - version = "v1.13.5", - ) - go_repository( - name = "com_github_aymerick_douceur", - build_file_proto_mode = "disable_global", - importpath = "github.com/aymerick/douceur", - sum = "h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk=", - version = "v0.2.0", - ) - go_repository( - name = "com_github_aymerick_raymond", - build_file_proto_mode = "disable_global", - importpath = "github.com/aymerick/raymond", - sum = "h1:Ppm0npCCsmuR9oQaBtRuZcmILVE74aXE+AmrJj8L2ns=", - version = "v2.0.3-0.20180322193309-b565731e1464+incompatible", - ) - go_repository( - name = "com_github_azure_go_ansiterm", - build_file_proto_mode = "disable_global", - importpath = "github.com/Azure/go-ansiterm", - sum = "h1:UQHMgLO+TxOElx5B5HZ4hJQsoJ/PvUvKRhJHDQXO8P8=", - version = "v0.0.0-20210617225240-d185dfc1b5a1", - ) - go_repository( - name = "com_github_benbjohnson_clock", - build_file_proto_mode = "disable_global", - importpath = "github.com/benbjohnson/clock", - sum = "h1:ip6w0uFQkncKQ979AypyG0ER7mqUSBdKLOgAle/AT8A=", - version = "v1.3.0", - ) - go_repository( - name = "com_github_bufbuild_buf", - build_file_proto_mode = "disable_global", - importpath = "github.com/bufbuild/buf", - sum = "h1:GqE3a8CMmcFvWPzuY3Mahf9Kf3S9XgZ/ORpfYFzO+90=", - version = "v1.4.0", - ) - go_repository( - name = "com_github_burntsushi_toml", - build_file_proto_mode = "disable_global", - importpath = "github.com/BurntSushi/toml", - sum = "h1:Rt8g24XnyGTyglgET/PRUNlrUeu9F5L+7FilkXfZgs0=", - version = "v1.2.0", - ) - go_repository( - name = "com_github_census_instrumentation_opencensus_proto", - build_file_proto_mode = "disable_global", - importpath = "github.com/census-instrumentation/opencensus-proto", - sum = "h1:iKLQ0xPNFxR/2hzXZMrBo8f1j86j5WHzznCCQxV/b8g=", - version = "v0.4.1", - ) - go_repository( - name = "com_github_cespare_xxhash_v2", - build_file_proto_mode = "disable_global", - importpath = "github.com/cespare/xxhash/v2", - sum = "h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=", - version = "v2.2.0", - ) - go_repository( - name = "com_github_charmbracelet_glamour", - build_file_proto_mode = "disable_global", - importpath = "github.com/charmbracelet/glamour", - sum = "h1:wu15ykPdB7X6chxugG/NNfDUbyyrCLV9XBalj5wdu3g=", - version = "v0.5.0", - ) - go_repository( - name = "com_github_client9_misspell", - build_file_proto_mode = "disable_global", - importpath = "github.com/client9/misspell", - sum = "h1:ta993UF76GwbvJcIo3Y68y/M3WxlpEHPWIGDkJYwzJI=", - version = "v0.3.4", - ) - go_repository( - name = "com_github_cloudykit_fastprinter", - build_file_proto_mode = "disable_global", - importpath = "github.com/CloudyKit/fastprinter", - sum = "h1:sR+/8Yb4slttB4vD+b9btVEnWgL3Q00OBTzVT8B9C0c=", - version = "v0.0.0-20200109182630-33d98a066a53", - ) - go_repository( - name = "com_github_cloudykit_jet", - build_file_proto_mode = "disable_global", - importpath = "github.com/CloudyKit/jet", - sum = "h1:rZgFj+Gtf3NMi/U5FvCvhzaxzW/TaPYgUYx3bAPz9DE=", - version = "v2.1.3-0.20180809161101-62edd43e4f88+incompatible", - ) - go_repository( - name = "com_github_cloudykit_jet_v3", - build_file_proto_mode = "disable_global", - importpath = "github.com/CloudyKit/jet/v3", - sum = "h1:1PwO5w5VCtlUUl+KTOBsTGZlhjWkcybsGaAau52tOy8=", - version = "v3.0.0", - ) - go_repository( - name = "com_github_cloudykit_jet_v6", - build_file_proto_mode = "disable_global", - importpath = "github.com/CloudyKit/jet/v6", - sum = "h1:hvO96X345XagdH1fAoBjpBYG4a1ghhL/QzalkduPuXk=", - version = "v6.1.0", - ) - go_repository( - name = "com_github_cncf_udpa_go", - build_file_proto_mode = "disable_global", - importpath = "github.com/cncf/udpa/go", - sum = "h1:QQ3GSy+MqSHxm/d8nCtnAiZdYFd45cYZPs8vOOIYKfk=", - version = "v0.0.0-20220112060539-c52dc94e7fbe", - ) - go_repository( - name = "com_github_cncf_xds_go", - build_file_proto_mode = "disable_global", - importpath = "github.com/cncf/xds/go", - sum = "h1:ACGZRIr7HsgBKHsueQ1yM4WaVaXh21ynwqsF8M8tXhA=", - version = "v0.0.0-20230105202645-06c439db220b", - ) - go_repository( - name = "com_github_cockroachdb_datadriven", - build_file_proto_mode = "disable_global", - importpath = "github.com/cockroachdb/datadriven", - sum = "h1:GCR5egmFNSTyGOv9IvMh636aELybEhZOlpPlW2NtuiU=", - version = "v1.0.1-0.20220214170620-9913f5bc19b7", - ) - go_repository( - name = "com_github_cockroachdb_errors", - build_file_proto_mode = "disable_global", - importpath = "github.com/cockroachdb/errors", - sum = "h1:B48dYem5SlAY7iU8AKsgedb4gH6mo+bDkbtLIvM/a88=", - version = "v1.9.0", - ) - go_repository( - name = "com_github_cockroachdb_logtags", - build_file_proto_mode = "disable_global", - importpath = "github.com/cockroachdb/logtags", - sum = "h1:6jduT9Hfc0njg5jJ1DdKCFPdMBrp/mdZfCpa5h+WM74=", - version = "v0.0.0-20211118104740-dabe8e521a4f", - ) - go_repository( - name = "com_github_cockroachdb_redact", - build_file_proto_mode = "disable_global", - importpath = "github.com/cockroachdb/redact", - sum = "h1:AKZds10rFSIj7qADf0g46UixK8NNLwWTNdCIGS5wfSQ=", - version = "v1.1.3", - ) - go_repository( - name = "com_github_cockroachdb_sentry_go", - build_file_proto_mode = "disable_global", - importpath = "github.com/cockroachdb/sentry-go", - sum = "h1:IKgmqgMQlVJIZj19CdocBeSfSaiCbEBZGKODaixqtHM=", - version = "v0.6.1-cockroachdb.2", - ) - go_repository( - name = "com_github_codegangsta_inject", - build_file_proto_mode = "disable_global", - importpath = "github.com/codegangsta/inject", - sum = "h1:sDMmm+q/3+BukdIpxwO365v/Rbspp2Nt5XntgQRXq8Q=", - version = "v0.0.0-20150114235600-33e0aa1cb7c0", - ) - go_repository( - name = "com_github_coreos_etcd", - build_file_proto_mode = "disable_global", - importpath = "github.com/coreos/etcd", - sum = "h1:jFneRYjIvLMLhDLCzuTuU4rSJUjRplcJQ7pD7MnhC04=", - version = "v3.3.10+incompatible", - ) - go_repository( - name = "com_github_coreos_go_etcd", - build_file_proto_mode = "disable_global", - importpath = "github.com/coreos/go-etcd", - sum = "h1:bXhRBIXoTm9BYHS3gE0TtQuyNZyeEMux2sDi4oo5YOo=", - version = "v2.0.0+incompatible", - ) - go_repository( - name = "com_github_coreos_go_semver", - build_file_proto_mode = "disable_global", - importpath = "github.com/coreos/go-semver", - sum = "h1:3Jm3tLmsgAYcjC+4Up7hJrFBPr+n7rAqYeSw/SZazuY=", - version = "v0.2.0", - ) - go_repository( - name = "com_github_cpuguy83_go_md2man", - build_file_proto_mode = "disable_global", - importpath = "github.com/cpuguy83/go-md2man", - sum = "h1:BSKMNlYxDvnunlTymqtgONjNnaRV1sTpcovwwjF22jk=", - version = "v1.0.10", - ) - go_repository( - name = "com_github_cpuguy83_go_md2man_v2", - build_file_proto_mode = "disable_global", - importpath = "github.com/cpuguy83/go-md2man/v2", - sum = "h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w=", - version = "v2.0.2", - ) - go_repository( - name = "com_github_creack_goselect", - build_file_proto_mode = "disable_global", - importpath = "github.com/creack/goselect", - sum = "h1:2DNy14+JPjRBgPzAd1thbQp4BSIihxcBf0IXhQXDRa0=", - version = "v0.1.2", - ) - go_repository( - name = "com_github_creack_pty", - build_file_proto_mode = "disable_global", - importpath = "github.com/creack/pty", - sum = "h1:07n33Z8lZxZ2qwegKbObQohDhXDQxiMMz1NOUGYlesw=", - version = "v1.1.11", - ) - go_repository( - name = "com_github_dave_jennifer", - build_file_proto_mode = "disable_global", - importpath = "github.com/dave/jennifer", - sum = "h1:HmgPN93bVDpkQyYbqhCHj5QlgvUkvEOzMyEvKLgCRrg=", - version = "v1.5.0", - ) - go_repository( - name = "com_github_davecgh_go_spew", - build_file_proto_mode = "disable_global", - importpath = "github.com/davecgh/go-spew", - sum = "h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=", - version = "v1.1.1", - ) - go_repository( - name = "com_github_derision_test_glock", - build_file_proto_mode = "disable_global", - importpath = "github.com/derision-test/glock", - sum = "h1:O07j7ewg0eFHRx+7bxCA/7z86HJexl7HLY9kyVMmPDo=", - version = "v0.0.0-20210316032053-f5b74334bb29", - ) - go_repository( - name = "com_github_derision_test_go_mockgen", - build_file_proto_mode = "disable_global", - importpath = "github.com/derision-test/go-mockgen", - sum = "h1:b/DXAXL2FkaRPpnbYK3ODdZzklmJAwox0tkc6yyXx74=", - version = "v1.3.7", - ) - go_repository( - name = "com_github_dgraph_io_badger", - build_file_proto_mode = "disable_global", - importpath = "github.com/dgraph-io/badger", - sum = "h1:DshxFxZWXUcO0xX476VJC07Xsr6ZCBVRHKZ93Oh7Evo=", - version = "v1.6.0", - ) - go_repository( - name = "com_github_dgrijalva_jwt_go", - build_file_proto_mode = "disable_global", - importpath = "github.com/dgrijalva/jwt-go", - sum = "h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=", - version = "v3.2.0+incompatible", - ) - go_repository( - name = "com_github_dgryski_go_farm", - build_file_proto_mode = "disable_global", - importpath = "github.com/dgryski/go-farm", - sum = "h1:tdlZCpZ/P9DhczCTSixgIKmwPv6+wP5DGjqLYw5SUiA=", - version = "v0.0.0-20190423205320-6a90982ecee2", - ) - go_repository( - name = "com_github_dineshappavoo_basex", - build_file_proto_mode = "disable_global", - importpath = "github.com/dineshappavoo/basex", - sum = "h1:fctNkSsavbXpt8geFWZb8n+noCqS8MrOXRJ/YfdZ2dQ=", - version = "v0.0.0-20170425072625-481a6f6dc663", - ) - go_repository( - name = "com_github_dlclark_regexp2", - build_file_proto_mode = "disable_global", - importpath = "github.com/dlclark/regexp2", - sum = "h1:7lJfhqlPssTb1WQx4yvTHN0uElPEv52sbaECrAQxjAo=", - version = "v1.7.0", - ) - go_repository( - name = "com_github_docopt_docopt_go", - build_file_proto_mode = "disable_global", - importpath = "github.com/docopt/docopt-go", - sum = "h1:bWDMxwH3px2JBh6AyO7hdCn/PkvCZXii8TGj7sbtEbQ=", - version = "v0.0.0-20180111231733-ee0de3bc6815", - ) - go_repository( - name = "com_github_dustin_go_humanize", - build_file_proto_mode = "disable_global", - importpath = "github.com/dustin/go-humanize", - sum = "h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=", - version = "v1.0.1", - ) - go_repository( - name = "com_github_eknkc_amber", - build_file_proto_mode = "disable_global", - importpath = "github.com/eknkc/amber", - sum = "h1:clC1lXBpe2kTj2VHdaIu9ajZQe4kcEY9j0NsnDDBZ3o=", - version = "v0.0.0-20171010120322-cdade1c07385", - ) - go_repository( - name = "com_github_elazarl_goproxy", - build_file_proto_mode = "disable_global", - importpath = "github.com/elazarl/goproxy", - sum = "h1:yUdfgN0XgIJw7foRItutHYUIhlcKzcSf5vDpdhQAKTc=", - version = "v0.0.0-20180725130230-947c36da3153", - ) - go_repository( - name = "com_github_emicklei_go_restful_v3", - build_file_proto_mode = "disable_global", - importpath = "github.com/emicklei/go-restful/v3", - sum = "h1:XwGDlfxEnQZzuopoqxwSEllNcCOM9DhhFyhFIIGKwxE=", - version = "v3.9.0", - ) - go_repository( - name = "com_github_envoyproxy_go_control_plane", - build_file_proto_mode = "disable_global", - importpath = "github.com/envoyproxy/go-control-plane", - sum = "h1:xdCVXxEe0Y3FQith+0cj2irwZudqGYvecuLB1HtdexY=", - version = "v0.10.3", - ) - go_repository( - name = "com_github_envoyproxy_protoc_gen_validate", - build_file_proto_mode = "disable_global", - importpath = "github.com/envoyproxy/protoc-gen-validate", - sum = "h1:PS7VIOgmSVhWUEeZwTe7z7zouA22Cr590PzXKbZHOVY=", - version = "v0.9.1", - ) - go_repository( - name = "com_github_etcd_io_bbolt", - build_file_proto_mode = "disable_global", - importpath = "github.com/etcd-io/bbolt", - sum = "h1:gSJmxrs37LgTqR/oyJBWok6k6SvXEUerFTbltIhXkBM=", - version = "v1.3.3", - ) - go_repository( - name = "com_github_evanphx_json_patch", - build_file_proto_mode = "disable_global", - importpath = "github.com/evanphx/json-patch", - sum = "h1:4onqiflcdA9EOZ4RxV643DvftH5pOlLGNtQ5lPWQu84=", - version = "v4.12.0+incompatible", - ) - go_repository( - name = "com_github_fasthttp_contrib_websocket", - build_file_proto_mode = "disable_global", - importpath = "github.com/fasthttp-contrib/websocket", - sum = "h1:DddqAaWDpywytcG8w/qoQ5sAN8X12d3Z3koB0C3Rxsc=", - version = "v0.0.0-20160511215533-1f3b11f56072", - ) - go_repository( - name = "com_github_fatih_color", - build_file_proto_mode = "disable_global", - importpath = "github.com/fatih/color", - sum = "h1:8LOYc1KYPPmyKMuN8QV2DNRWNbLo6LZ0iLs8+mlH53w=", - version = "v1.13.0", - ) - go_repository( - name = "com_github_fatih_structs", - build_file_proto_mode = "disable_global", - importpath = "github.com/fatih/structs", - sum = "h1:Q7juDM0QtcnhCpeyLGQKyg4TOIghuNXrkL32pHAUMxo=", - version = "v1.1.0", - ) - go_repository( - name = "com_github_flosch_pongo2", - build_file_proto_mode = "disable_global", - importpath = "github.com/flosch/pongo2", - sum = "h1:GY1+t5Dr9OKADM64SYnQjw/w99HMYvQ0A8/JoUkxVmc=", - version = "v0.0.0-20190707114632-bbf5a6c351f4", - ) - go_repository( - name = "com_github_flosch_pongo2_v4", - build_file_proto_mode = "disable_global", - importpath = "github.com/flosch/pongo2/v4", - sum = "h1:gv+5Pe3vaSVmiJvh/BZa82b7/00YUGm0PIyVVLop0Hw=", - version = "v4.0.2", - ) - go_repository( - name = "com_github_frankban_quicktest", - build_file_proto_mode = "disable_global", - importpath = "github.com/frankban/quicktest", - sum = "h1:FJKSZTDHjyhriyC81FLQ0LY93eSai0ZyR/ZIkd3ZUKE=", - version = "v1.14.3", - ) - go_repository( - name = "com_github_fsnotify_fsnotify", - build_file_proto_mode = "disable_global", - importpath = "github.com/fsnotify/fsnotify", - sum = "h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4=", - version = "v1.4.9", - ) - go_repository( - name = "com_github_gavv_httpexpect", - build_file_proto_mode = "disable_global", - importpath = "github.com/gavv/httpexpect", - sum = "h1:1X9kcRshkSKEjNJJxX9Y9mQ5BRfbxU5kORdjhlA1yX8=", - version = "v2.0.0+incompatible", - ) - go_repository( - name = "com_github_getsentry_sentry_go", - build_file_proto_mode = "disable_global", - importpath = "github.com/getsentry/sentry-go", - sum = "h1:CP9bmA7pralrVUedYZsmIHWpq/pBtXTSew7xvVpfLaA=", - version = "v0.15.0", - ) - go_repository( - name = "com_github_ghodss_yaml", - build_file_proto_mode = "disable_global", - importpath = "github.com/ghodss/yaml", - replace = "github.com/sourcegraph/yaml", - sum = "h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o=", - version = "v1.0.1-0.20200714132230-56936252f152", - ) - go_repository( - name = "com_github_gin_contrib_sse", - build_file_proto_mode = "disable_global", - importpath = "github.com/gin-contrib/sse", - sum = "h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=", - version = "v0.1.0", - ) - go_repository( - name = "com_github_gin_gonic_gin", - build_file_proto_mode = "disable_global", - importpath = "github.com/gin-gonic/gin", - sum = "h1:4+fr/el88TOO3ewCmQr8cx/CtZ/umlIRIs5M4NTNjf8=", - version = "v1.8.1", - ) - go_repository( - name = "com_github_go_check_check", - build_file_proto_mode = "disable_global", - importpath = "github.com/go-check/check", - sum = "h1:0gkP6mzaMqkmpcJYCFOLkIBwI7xFExG03bbkOkCvUPI=", - version = "v0.0.0-20180628173108-788fd7840127", - ) - go_repository( - name = "com_github_go_enry_go_enry_v2", - build_file_proto_mode = "disable_global", - importpath = "github.com/go-enry/go-enry/v2", - sum = "h1:IBtFo783PgL7oyd/TL1/8HQFMNzOAl4NaLPbzNOvbwM=", - version = "v2.7.2", - ) - go_repository( - name = "com_github_go_enry_go_oniguruma", - build_file_proto_mode = "disable_global", - importpath = "github.com/go-enry/go-oniguruma", - sum = "h1:k8aAMuJfMrqm/56SG2lV9Cfti6tC4x8673aHCcBk+eo=", - version = "v1.2.1", - ) - go_repository( - name = "com_github_go_errors_errors", - build_file_proto_mode = "disable_global", - importpath = "github.com/go-errors/errors", - sum = "h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA=", - version = "v1.4.2", - ) - go_repository( - name = "com_github_go_logr_logr", - build_file_proto_mode = "disable_global", - importpath = "github.com/go-logr/logr", - sum = "h1:2DntVwHkVopvECVRSlL5PSo9eG+cAkDCuckLubN+rq0=", - version = "v1.2.3", - ) - go_repository( - name = "com_github_go_martini_martini", - build_file_proto_mode = "disable_global", - importpath = "github.com/go-martini/martini", - sum = "h1:xveKWz2iaueeTaUgdetzel+U7exyigDYBryyVfV/rZk=", - version = "v0.0.0-20170121215854-22fa46961aab", - ) - go_repository( - name = "com_github_go_openapi_jsonpointer", - build_file_proto_mode = "disable_global", - importpath = "github.com/go-openapi/jsonpointer", - sum = "h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUeOFYEICuY=", - version = "v0.19.5", - ) - go_repository( - name = "com_github_go_openapi_jsonreference", - build_file_proto_mode = "disable_global", - importpath = "github.com/go-openapi/jsonreference", - sum = "h1:MYlu0sBgChmCfJxxUKZ8g1cPWFOB37YSZqewK7OKeyA=", - version = "v0.20.0", - ) - go_repository( - name = "com_github_go_openapi_swag", - build_file_proto_mode = "disable_global", - importpath = "github.com/go-openapi/swag", - sum = "h1:gm3vOOXfiuw5i9p5N9xJvfjvuofpyvLA9Wr6QfK5Fng=", - version = "v0.19.14", - ) - go_repository( - name = "com_github_go_playground_locales", - build_file_proto_mode = "disable_global", - importpath = "github.com/go-playground/locales", - sum = "h1:u50s323jtVGugKlcYeyzC0etD1HifMjqmJqb8WugfUU=", - version = "v0.14.0", - ) - go_repository( - name = "com_github_go_playground_universal_translator", - build_file_proto_mode = "disable_global", - importpath = "github.com/go-playground/universal-translator", - sum = "h1:82dyy6p4OuJq4/CByFNOn/jYrnRPArHwAcmLoJZxyho=", - version = "v0.18.0", - ) - go_repository( - name = "com_github_go_playground_validator_v10", - build_file_proto_mode = "disable_global", - importpath = "github.com/go-playground/validator/v10", - sum = "h1:prmOlTVv+YjZjmRmNSF3VmspqJIxJWXmqUsHwfTRRkQ=", - version = "v10.11.1", - ) - go_repository( - name = "com_github_gobwas_glob", - build_file_proto_mode = "disable_global", - importpath = "github.com/gobwas/glob", - sum = "h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=", - version = "v0.2.3", - ) - go_repository( - name = "com_github_gobwas_httphead", - build_file_proto_mode = "disable_global", - importpath = "github.com/gobwas/httphead", - sum = "h1:s+21KNqlpePfkah2I+gwHF8xmJWRjooY+5248k6m4A0=", - version = "v0.0.0-20180130184737-2c6c146eadee", - ) - go_repository( - name = "com_github_gobwas_pool", - build_file_proto_mode = "disable_global", - importpath = "github.com/gobwas/pool", - sum = "h1:QEmUOlnSjWtnpRGHF3SauEiOsy82Cup83Vf2LcMlnc8=", - version = "v0.2.0", - ) - go_repository( - name = "com_github_gobwas_ws", - build_file_proto_mode = "disable_global", - importpath = "github.com/gobwas/ws", - sum = "h1:CoAavW/wd/kulfZmSIBt6p24n4j7tHgNVCjsfHVNUbo=", - version = "v1.0.2", - ) - go_repository( - name = "com_github_goccy_go_json", - build_file_proto_mode = "disable_global", - importpath = "github.com/goccy/go-json", - sum = "h1:/pAaQDLHEoCq/5FFmSKBswWmK6H0e8g4159Kc/X/nqk=", - version = "v0.9.11", - ) - go_repository( - name = "com_github_gofrs_flock", - build_file_proto_mode = "disable_global", - importpath = "github.com/gofrs/flock", - sum = "h1:+gYjHKf32LDeiEEFhQaotPbLuUXjY5ZqxKgXy7n59aw=", - version = "v0.8.1", - ) - go_repository( - name = "com_github_gofrs_uuid", - build_file_proto_mode = "disable_global", - importpath = "github.com/gofrs/uuid", - sum = "h1:yyYWMnhkhrKwwr8gAOcOCYxOOscHgDS9yZgBrnJfGa0=", - version = "v4.2.0+incompatible", - ) - go_repository( - name = "com_github_gogo_googleapis", - build_file_proto_mode = "disable_global", - importpath = "github.com/gogo/googleapis", - sum = "h1:1Yx4Myt7BxzvUr5ldGSbwYiZG6t9wGBZ+8/fX3Wvtq0=", - version = "v1.4.1", - ) - go_repository( - name = "com_github_gogo_protobuf", - build_file_proto_mode = "disable_global", - importpath = "github.com/gogo/protobuf", - sum = "h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=", - version = "v1.3.2", - ) - go_repository( - name = "com_github_gogo_status", - build_file_proto_mode = "disable_global", - importpath = "github.com/gogo/status", - sum = "h1:+eIkrewn5q6b30y+g/BJINVVdi2xH7je5MPJ3ZPK3JA=", - version = "v1.1.0", - ) - go_repository( - name = "com_github_golang_glog", - build_file_proto_mode = "disable_global", - importpath = "github.com/golang/glog", - sum = "h1:nfP3RFugxnNRyKgeWd4oI1nYvXpxrx8ck8ZrcizshdQ=", - version = "v1.0.0", - ) - go_repository( - name = "com_github_golang_groupcache", - build_file_proto_mode = "disable_global", - importpath = "github.com/golang/groupcache", - sum = "h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE=", - version = "v0.0.0-20210331224755-41bb18bfe9da", - ) - go_repository( - name = "com_github_golang_jwt_jwt", - build_file_proto_mode = "disable_global", - importpath = "github.com/golang-jwt/jwt", - sum = "h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY=", - version = "v3.2.2+incompatible", - ) - go_repository( - name = "com_github_golang_mock", - build_file_proto_mode = "disable_global", - importpath = "github.com/golang/mock", - sum = "h1:G5FRp8JnTd7RQH5kemVNlMeyXQAztQ3mOWV95KxsXH8=", - version = "v1.1.1", - ) - go_repository( - name = "com_github_golang_protobuf", - build_file_proto_mode = "disable_global", - importpath = "github.com/golang/protobuf", - sum = "h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw=", - version = "v1.5.2", - ) - go_repository( - name = "com_github_golang_snappy", - build_file_proto_mode = "disable_global", - importpath = "github.com/golang/snappy", - sum = "h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM=", - version = "v0.0.4", - ) - go_repository( - name = "com_github_gomodule_redigo", - build_file_proto_mode = "disable_global", - importpath = "github.com/gomodule/redigo", - sum = "h1:y0Wmhvml7cGnzPa9nocn/fMraMH/lMDdeG+rkx4VgYY=", - version = "v1.7.1-0.20190724094224-574c33c3df38", - ) - go_repository( - name = "com_github_google_btree", - build_file_proto_mode = "disable_global", - importpath = "github.com/google/btree", - sum = "h1:gK4Kx5IaGY9CD5sPJ36FHiBJ6ZXl0kilRiiCj+jdYp4=", - version = "v1.0.1", - ) - go_repository( - name = "com_github_google_gnostic", - build_file_proto_mode = "disable_global", - importpath = "github.com/google/gnostic", - sum = "h1:FhTMOKj2VhjpouxvWJAV1TL304uMlb9zcDqkl6cEI54=", - version = "v0.5.7-v3refs", - ) - go_repository( - name = "com_github_google_go_cmp", - build_file_proto_mode = "disable_global", - importpath = "github.com/google/go-cmp", - sum = "h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=", - version = "v0.5.9", - ) - go_repository( - name = "com_github_google_go_querystring", - build_file_proto_mode = "disable_global", - importpath = "github.com/google/go-querystring", - sum = "h1:Xkwi/a1rcvNg1PPYe5vI8GbeBY/jrVuDX5ASuANWTrk=", - version = "v1.0.0", - ) - go_repository( - name = "com_github_google_gofuzz", - build_file_proto_mode = "disable_global", - importpath = "github.com/google/gofuzz", - sum = "h1:Hsa8mG0dQ46ij8Sl2AYJDUv1oA9/d6Vk+3LG99Oe02g=", - version = "v1.1.0", - ) - go_repository( - name = "com_github_google_martian_v3", - build_file_proto_mode = "disable_global", - importpath = "github.com/google/martian/v3", - sum = "h1:d8MncMlErDFTwQGBK1xhv026j9kqhvw1Qv9IbWT1VLQ=", - version = "v3.2.1", - ) - go_repository( - name = "com_github_google_uuid", - build_file_proto_mode = "disable_global", - importpath = "github.com/google/uuid", - sum = "h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=", - version = "v1.3.0", - ) - go_repository( - name = "com_github_googleapis_enterprise_certificate_proxy", - build_file_proto_mode = "disable_global", - importpath = "github.com/googleapis/enterprise-certificate-proxy", - sum = "h1:yk9/cqRKtT9wXZSsRH9aurXEpJX+U6FLtpYTdC3R06k=", - version = "v0.2.3", - ) - go_repository( - name = "com_github_googleapis_gax_go_v2", - build_file_proto_mode = "disable_global", - importpath = "github.com/googleapis/gax-go/v2", - sum = "h1:IcsPKeInNvYi7eqSaDjiZqDDKu5rsmunY0Y1YupQSSQ=", - version = "v2.7.0", - ) - go_repository( - name = "com_github_gopherjs_gopherjs", - build_file_proto_mode = "disable_global", - importpath = "github.com/gopherjs/gopherjs", - sum = "h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8=", - version = "v0.0.0-20181017120253-0766667cb4d1", - ) - go_repository( - name = "com_github_gorilla_css", - build_file_proto_mode = "disable_global", - importpath = "github.com/gorilla/css", - sum = "h1:BQqNyPTi50JCFMTw/b67hByjMVXZRwGha6wxVGkeihY=", - version = "v1.0.0", - ) - go_repository( - name = "com_github_gorilla_websocket", - build_file_proto_mode = "disable_global", - importpath = "github.com/gorilla/websocket", - sum = "h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc=", - version = "v1.4.2", - ) - go_repository( - name = "com_github_grafana_regexp", - build_file_proto_mode = "disable_global", - importpath = "github.com/grafana/regexp", - sum = "h1:7aN5cccjIqCLTzedH7MZzRZt5/lsAHch6Z3L2ZGn5FA=", - version = "v0.0.0-20221123153739-15dc172cd2db", - ) - go_repository( - name = "com_github_gregjones_httpcache", - build_file_proto_mode = "disable_global", - importpath = "github.com/gregjones/httpcache", - sum = "h1:pdN6V1QBWetyv/0+wjACpqVH+eVULgEjkurDLq3goeM=", - version = "v0.0.0-20180305231024-9cad4c3443a7", - ) - go_repository( - name = "com_github_hashicorp_go_version", - build_file_proto_mode = "disable_global", - importpath = "github.com/hashicorp/go-version", - sum = "h1:3vNe/fWF5CBgRIguda1meWhsZHy3m8gCJ5wx+dIzX/E=", - version = "v1.2.0", - ) - go_repository( - name = "com_github_hashicorp_hcl", - build_file_proto_mode = "disable_global", - importpath = "github.com/hashicorp/hcl", - sum = "h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=", - version = "v1.0.0", - ) - go_repository( - name = "com_github_hexops_autogold", - build_file_proto_mode = "disable_global", - importpath = "github.com/hexops/autogold", - sum = "h1:IEtGNPxBeBu8RMn8eKWh/Ll9dVNgSnJ7bp/qHgMQ14o=", - version = "v1.3.0", - ) - go_repository( - name = "com_github_hexops_autogold_v2", - build_file_proto_mode = "disable_global", - importpath = "github.com/hexops/autogold/v2", - sum = "h1:zyrfTlNfyxLpX/zuk8wjTeTYP5AXaFeeRYFEZfHPwao=", - version = "v2.0.3", - ) - go_repository( - name = "com_github_hexops_gotextdiff", - build_file_proto_mode = "disable_global", - importpath = "github.com/hexops/gotextdiff", - sum = "h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM=", - version = "v1.0.3", - ) - go_repository( - name = "com_github_hexops_valast", - build_file_proto_mode = "disable_global", - importpath = "github.com/hexops/valast", - sum = "h1:oBoGERMJh6UZdRc6cduE1CTPK+VAdXA59Y1HFgu3sm0=", - version = "v1.4.3", - ) - go_repository( - name = "com_github_hhatto_gocloc", - build_file_proto_mode = "disable_global", - importpath = "github.com/hhatto/gocloc", - sum = "h1:deh3Xb1uqiySNgOccMNYb3HbKsUoQDzsZRpfQmbTIhs=", - version = "v0.4.2", - ) - go_repository( - name = "com_github_hpcloud_tail", - build_file_proto_mode = "disable_global", - importpath = "github.com/hpcloud/tail", - sum = "h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI=", - version = "v1.0.0", - ) - go_repository( - name = "com_github_huandu_xstrings", - build_file_proto_mode = "disable_global", - importpath = "github.com/huandu/xstrings", - sum = "h1:L18LIDzqlW6xN2rEkpdV8+oL/IXWJ1APd+vsdYy4Wdw=", - version = "v1.3.2", - ) - go_repository( - name = "com_github_hydrogen18_memlistener", - build_file_proto_mode = "disable_global", - importpath = "github.com/hydrogen18/memlistener", - sum = "h1:KyZDvZ/GGn+r+Y3DKZ7UOQ/TP4xV6HNkrwiVMB1GnNY=", - version = "v0.0.0-20200120041712-dcc25e7acd91", - ) - go_repository( - name = "com_github_iancoleman_strcase", - build_file_proto_mode = "disable_global", - importpath = "github.com/iancoleman/strcase", - sum = "h1:05I4QRnGpI0m37iZQRuskXh+w77mr6Z41lwQzuHLwW0=", - version = "v0.2.0", - ) - go_repository( - name = "com_github_imdario_mergo", - build_file_proto_mode = "disable_global", - importpath = "github.com/imdario/mergo", - sum = "h1:lFzP57bqS/wsqKssCGmtLAb8A0wKjLGrve2q3PPVcBk=", - version = "v0.3.13", - ) - go_repository( - name = "com_github_imkira_go_interpol", - build_file_proto_mode = "disable_global", - importpath = "github.com/imkira/go-interpol", - sum = "h1:KIiKr0VSG2CUW1hl1jpiyuzuJeKUUpC8iM1AIE7N1Vk=", - version = "v1.1.0", - ) - go_repository( - name = "com_github_inconshreveable_mousetrap", - build_file_proto_mode = "disable_global", - importpath = "github.com/inconshreveable/mousetrap", - sum = "h1:U3uMjPSQEBMNp1lFxmllqCPM6P5u/Xq7Pgzkat/bFNc=", - version = "v1.0.1", - ) - go_repository( - name = "com_github_iris_contrib_blackfriday", - build_file_proto_mode = "disable_global", - importpath = "github.com/iris-contrib/blackfriday", - sum = "h1:o5sHQHHm0ToHUlAJSTjW9UWicjJSDDauOOQ2AHuIVp4=", - version = "v2.0.0+incompatible", - ) - go_repository( - name = "com_github_iris_contrib_go_uuid", - build_file_proto_mode = "disable_global", - importpath = "github.com/iris-contrib/go.uuid", - sum = "h1:XZubAYg61/JwnJNbZilGjf3b3pB80+OQg2qf6c8BfWE=", - version = "v2.0.0+incompatible", - ) - go_repository( - name = "com_github_iris_contrib_i18n", - build_file_proto_mode = "disable_global", - importpath = "github.com/iris-contrib/i18n", - sum = "h1:Kyp9KiXwsyZRTeoNjgVCrWks7D8ht9+kg6yCjh8K97o=", - version = "v0.0.0-20171121225848-987a633949d0", - ) - go_repository( - name = "com_github_iris_contrib_jade", - build_file_proto_mode = "disable_global", - importpath = "github.com/iris-contrib/jade", - sum = "h1:WoYdfyJFfZIUgqNAeOyRfTNQZOksSlZ6+FnXR3AEpX0=", - version = "v1.1.4", - ) - go_repository( - name = "com_github_iris_contrib_pongo2", - build_file_proto_mode = "disable_global", - importpath = "github.com/iris-contrib/pongo2", - sum = "h1:zGP7pW51oi5eQZMIlGA3I+FHY9/HOQWDB+572yin0to=", - version = "v0.0.1", - ) - go_repository( - name = "com_github_iris_contrib_schema", - build_file_proto_mode = "disable_global", - importpath = "github.com/iris-contrib/schema", - sum = "h1:CPSBLyx2e91H2yJzPuhGuifVRnZBBJ3pCOMbOvPZaTw=", - version = "v0.0.6", - ) - go_repository( - name = "com_github_jdxcode_netrc", - build_file_proto_mode = "disable_global", - importpath = "github.com/jdxcode/netrc", - sum = "h1:d4+I1YEKVmWZrgkt6jpXBnLgV2ZjO0YxEtLDdfIZfH4=", - version = "v0.0.0-20210204082910-926c7f70242a", - ) - go_repository( - name = "com_github_jedib0t_go_pretty_v6", - build_file_proto_mode = "disable_global", - importpath = "github.com/jedib0t/go-pretty/v6", - sum = "h1:H3Ulkf7h6A+p0HgKBGzgDn0bZIupRbKKWF4pO4Bs7iA=", - version = "v6.3.7", - ) - go_repository( - name = "com_github_jhump_gopoet", - build_file_proto_mode = "disable_global", - importpath = "github.com/jhump/gopoet", - sum = "h1:gYjOPnzHd2nzB37xYQZxj4EIQNpBrBskRqQQ3q4ZgSg=", - version = "v0.1.0", - ) - go_repository( - name = "com_github_jhump_goprotoc", - build_file_proto_mode = "disable_global", - importpath = "github.com/jhump/goprotoc", - sum = "h1:Y1UgUX+txUznfqcGdDef8ZOVlyQvnV0pKWZH08RmZuo=", - version = "v0.5.0", - ) - go_repository( - name = "com_github_jhump_protocompile", - build_file_proto_mode = "disable_global", - importpath = "github.com/jhump/protocompile", - sum = "h1:BNuUg9k2EiJmlMwjoef3e8vZLHplbVw6DrjGFjLL+Yo=", - version = "v0.0.0-20220216033700-d705409f108f", - ) - go_repository( - name = "com_github_jhump_protoreflect", - build_file_proto_mode = "disable_global", - importpath = "github.com/jhump/protoreflect", - sum = "h1:uFlcJKZPLQd7rmOY/RrvBuUaYmAFnlFHKLivhO6cOy8=", - version = "v1.12.1-0.20220417024638-438db461d753", - ) - go_repository( - name = "com_github_jig_teereadcloser", - build_file_proto_mode = "disable_global", - importpath = "github.com/jig/teereadcloser", - sum = "h1:dSwwtWuwMyarzsbVWOq4QJ8xVy9wgcNomvWyGtrKe+E=", - version = "v0.0.0-20181016160506-953720c48e05", - ) - go_repository( - name = "com_github_jmespath_go_jmespath", - build_file_proto_mode = "disable_global", - importpath = "github.com/jmespath/go-jmespath", - sum = "h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg=", - version = "v0.4.0", - ) - go_repository( - name = "com_github_jmespath_go_jmespath_internal_testify", - build_file_proto_mode = "disable_global", - importpath = "github.com/jmespath/go-jmespath/internal/testify", - sum = "h1:shLQSRRSCCPj3f2gpwzGwWFoC7ycTf1rcQZHOlsJ6N8=", - version = "v1.5.1", - ) - go_repository( - name = "com_github_joker_hpp", - build_file_proto_mode = "disable_global", - importpath = "github.com/Joker/hpp", - sum = "h1:65+iuJYdRXv/XyN62C1uEmmOx3432rNG/rKlX6V7Kkc=", - version = "v1.0.0", - ) - go_repository( - name = "com_github_joker_jade", - build_file_proto_mode = "disable_global", - importpath = "github.com/Joker/jade", - sum = "h1:mreN1m/5VJ/Zc3b4pzj9qU6D9SRQ6Vm+3KfI328t3S8=", - version = "v1.0.1-0.20190614124447-d475f43051e7", - ) - go_repository( - name = "com_github_josharian_intern", - build_file_proto_mode = "disable_global", - importpath = "github.com/josharian/intern", - sum = "h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=", - version = "v1.0.0", - ) - go_repository( - name = "com_github_json_iterator_go", - build_file_proto_mode = "disable_global", - importpath = "github.com/json-iterator/go", - sum = "h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=", - version = "v1.1.12", - ) - go_repository( - name = "com_github_jtolds_gls", - build_file_proto_mode = "disable_global", - importpath = "github.com/jtolds/gls", - sum = "h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo=", - version = "v4.20.0+incompatible", - ) - go_repository( - name = "com_github_juju_errors", - build_file_proto_mode = "disable_global", - importpath = "github.com/juju/errors", - sum = "h1:rhqTjzJlm7EbkELJDKMTU7udov+Se0xZkWmugr6zGok=", - version = "v0.0.0-20181118221551-089d3ea4e4d5", - ) - go_repository( - name = "com_github_juju_loggo", - build_file_proto_mode = "disable_global", - importpath = "github.com/juju/loggo", - sum = "h1:MK144iBQF9hTSwBW/9eJm034bVoG30IshVm688T2hi8=", - version = "v0.0.0-20180524022052-584905176618", - ) - go_repository( - name = "com_github_juju_testing", - build_file_proto_mode = "disable_global", - importpath = "github.com/juju/testing", - sum = "h1:WQM1NildKThwdP7qWrNAFGzp4ijNLw8RlgENkaI4MJs=", - version = "v0.0.0-20180920084828-472a3e8b2073", - ) - go_repository( - name = "com_github_k0kubun_colorstring", - build_file_proto_mode = "disable_global", - importpath = "github.com/k0kubun/colorstring", - sum = "h1:uC1QfSlInpQF+M0ao65imhwqKnz3Q2z/d8PWZRMQvDM=", - version = "v0.0.0-20150214042306-9440f1994b88", - ) - go_repository( - name = "com_github_k0kubun_pp_v3", - build_file_proto_mode = "disable_global", - importpath = "github.com/k0kubun/pp/v3", - sum = "h1:ifxtqJkRZhw3h554/z/8zm6AAbyO4LLKDlA5eV+9O8Q=", - version = "v3.1.0", - ) - go_repository( - name = "com_github_kataras_blocks", - build_file_proto_mode = "disable_global", - importpath = "github.com/kataras/blocks", - sum = "h1:cF3RDY/vxnSRezc7vLFlQFTYXG/yAr1o7WImJuZbzC4=", - version = "v0.0.7", - ) - go_repository( - name = "com_github_kataras_golog", - build_file_proto_mode = "disable_global", - importpath = "github.com/kataras/golog", - sum = "h1:0TY5tHn5L5DlRIikepcaRR/6oInIr9AiWsxzt0vvlBE=", - version = "v0.1.7", - ) - go_repository( - name = "com_github_kataras_iris_v12", - build_file_proto_mode = "disable_global", - importpath = "github.com/kataras/iris/v12", - sum = "h1:grB/oCf5baZhmYIeDMfgN3LYrtEcmK8pbxlRvEZ2pgw=", - version = "v12.2.0-beta5", - ) - go_repository( - name = "com_github_kataras_neffos", - build_file_proto_mode = "disable_global", - importpath = "github.com/kataras/neffos", - sum = "h1:pdJaTvUG3NQfeMbbVCI8JT2T5goPldyyfUB2PJfh1Bs=", - version = "v0.0.14", - ) - go_repository( - name = "com_github_kataras_pio", - build_file_proto_mode = "disable_global", - importpath = "github.com/kataras/pio", - sum = "h1:kqreJ5KOEXGMwHAWHDwIl+mjfNCPhAwZPa8gK7MKlyw=", - version = "v0.0.11", - ) - go_repository( - name = "com_github_kataras_sitemap", - build_file_proto_mode = "disable_global", - importpath = "github.com/kataras/sitemap", - sum = "h1:w71CRMMKYMJh6LR2wTgnk5hSgjVNB9KL60n5e2KHvLY=", - version = "v0.0.6", - ) - go_repository( - name = "com_github_kataras_tunnel", - build_file_proto_mode = "disable_global", - importpath = "github.com/kataras/tunnel", - sum = "h1:sCAqWuJV7nPzGrlb0os3j49lk2JhILT0rID38NHNLpA=", - version = "v0.0.4", - ) - go_repository( - name = "com_github_kballard_go_shellquote", - build_file_proto_mode = "disable_global", - importpath = "github.com/kballard/go-shellquote", - sum = "h1:Z9n2FFNUXsshfwJMBgNA0RU6/i7WVaAegv3PtuIHPMs=", - version = "v0.0.0-20180428030007-95032a82bc51", - ) - go_repository( - name = "com_github_kisielk_errcheck", - build_file_proto_mode = "disable_global", - importpath = "github.com/kisielk/errcheck", - sum = "h1:e8esj/e4R+SAOwFwN+n3zr0nYeCyeweozKfO23MvHzY=", - version = "v1.5.0", - ) - go_repository( - name = "com_github_kisielk_gotool", - build_file_proto_mode = "disable_global", - importpath = "github.com/kisielk/gotool", - sum = "h1:AV2c/EiW3KqPNT9ZKl07ehoAGi4C5/01Cfbblndcapg=", - version = "v1.0.0", - ) - go_repository( - name = "com_github_klauspost_compress", - build_file_proto_mode = "disable_global", - importpath = "github.com/klauspost/compress", - sum = "h1:Lcadnb3RKGin4FYM/orgq0qde+nc15E5Cbqg4B9Sx9c=", - version = "v1.15.11", - ) - go_repository( - name = "com_github_klauspost_cpuid", - build_file_proto_mode = "disable_global", - importpath = "github.com/klauspost/cpuid", - sum = "h1:vJi+O/nMdFt0vqm8NZBI6wzALWdA2X+egi0ogNyrC/w=", - version = "v1.2.1", - ) - go_repository( - name = "com_github_klauspost_pgzip", - build_file_proto_mode = "disable_global", - importpath = "github.com/klauspost/pgzip", - sum = "h1:qnWYvvKqedOF2ulHpMG72XQol4ILEJ8k2wwRl/Km8oE=", - version = "v1.2.5", - ) - go_repository( - name = "com_github_kr_pretty", - build_file_proto_mode = "disable_global", - importpath = "github.com/kr/pretty", - sum = "h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=", - version = "v0.3.1", - ) - go_repository( - name = "com_github_kr_pty", - build_file_proto_mode = "disable_global", - importpath = "github.com/kr/pty", - sum = "h1:VkoXIwSboBpnk99O/KFauAEILuNHv5DVFKZMBN/gUgw=", - version = "v1.1.1", - ) - go_repository( - name = "com_github_kr_text", - build_file_proto_mode = "disable_global", - importpath = "github.com/kr/text", - sum = "h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=", - version = "v0.2.0", - ) - go_repository( - name = "com_github_labstack_echo_v4", - build_file_proto_mode = "disable_global", - importpath = "github.com/labstack/echo/v4", - sum = "h1:wPOF1CE6gvt/kmbMR4dGzWvHMPT+sAEUJOwOTtvITVY=", - version = "v4.9.0", - ) - go_repository( - name = "com_github_labstack_gommon", - build_file_proto_mode = "disable_global", - importpath = "github.com/labstack/gommon", - sum = "h1:OomWaJXm7xR6L1HmEtGyQf26TEn7V6X88mktX9kee9o=", - version = "v0.3.1", - ) - go_repository( - name = "com_github_leodido_go_urn", - build_file_proto_mode = "disable_global", - importpath = "github.com/leodido/go-urn", - sum = "h1:BqpAaACuzVSgi/VLzGZIobT2z4v53pjosyNd9Yv6n/w=", - version = "v1.2.1", - ) - go_repository( - name = "com_github_lucasb_eyer_go_colorful", - build_file_proto_mode = "disable_global", - importpath = "github.com/lucasb-eyer/go-colorful", - sum = "h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=", - version = "v1.2.0", - ) - go_repository( - name = "com_github_lyft_protoc_gen_star", - build_file_proto_mode = "disable_global", - importpath = "github.com/lyft/protoc-gen-star", - sum = "h1:erE0rdztuaDq3bpGifD95wfoPrSZc95nGA6tbiNYh6M=", - version = "v0.6.1", - ) - go_repository( - name = "com_github_magiconair_properties", - build_file_proto_mode = "disable_global", - importpath = "github.com/magiconair/properties", - sum = "h1:LLgXmsheXeRoUOBOjtwPQCWIYqM/LU1ayDtDePerRcY=", - version = "v1.8.0", - ) - go_repository( - name = "com_github_mailgun_raymond_v2", - build_file_proto_mode = "disable_global", - importpath = "github.com/mailgun/raymond/v2", - sum = "h1:aOYHhvTpF5USySJ0o7cpPno/Uh2I5qg2115K25A+Ft4=", - version = "v2.0.46", - ) - go_repository( - name = "com_github_mailru_easyjson", - build_file_proto_mode = "disable_global", - importpath = "github.com/mailru/easyjson", - sum = "h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=", - version = "v0.7.7", - ) - go_repository( - name = "com_github_masterminds_goutils", - build_file_proto_mode = "disable_global", - importpath = "github.com/Masterminds/goutils", - sum = "h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI=", - version = "v1.1.1", - ) - go_repository( - name = "com_github_masterminds_semver", - build_file_proto_mode = "disable_global", - importpath = "github.com/Masterminds/semver", - sum = "h1:H65muMkzWKEuNDnfl9d70GUjFniHKHRbFPGBuZ3QEww=", - version = "v1.5.0", - ) - go_repository( - name = "com_github_masterminds_sprig", - build_file_proto_mode = "disable_global", - importpath = "github.com/Masterminds/sprig", - sum = "h1:z4yfnGrZ7netVz+0EDJ0Wi+5VZCSYp4Z0m2dk6cEM60=", - version = "v2.22.0+incompatible", - ) - go_repository( - name = "com_github_mattn_go_colorable", - build_file_proto_mode = "disable_global", - importpath = "github.com/mattn/go-colorable", - sum = "h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=", - version = "v0.1.13", - ) - go_repository( - name = "com_github_mattn_go_isatty", - build_file_proto_mode = "disable_global", - importpath = "github.com/mattn/go-isatty", - sum = "h1:bq3VjFmv/sOjHtdEhmkEV4x1AJtvUvOJ2PFAZ5+peKQ=", - version = "v0.0.16", - ) - go_repository( - name = "com_github_mattn_go_runewidth", - build_file_proto_mode = "disable_global", - importpath = "github.com/mattn/go-runewidth", - sum = "h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU=", - version = "v0.0.14", - ) - go_repository( - name = "com_github_mattn_goveralls", - build_file_proto_mode = "disable_global", - importpath = "github.com/mattn/goveralls", - sum = "h1:7eJB6EqsPhRVxvwEXGnqdO2sJI0PTsrWoTMXEk9/OQc=", - version = "v0.0.2", - ) - go_repository( - name = "com_github_mediocregopher_mediocre_go_lib", - build_file_proto_mode = "disable_global", - importpath = "github.com/mediocregopher/mediocre-go-lib", - sum = "h1:3dQJqqDouawQgl3gBE1PNHKFkJYGEuFb1DbSlaxdosE=", - version = "v0.0.0-20181029021733-cb65787f37ed", - ) - go_repository( - name = "com_github_mediocregopher_radix_v3", - build_file_proto_mode = "disable_global", - importpath = "github.com/mediocregopher/radix/v3", - sum = "h1:galbPBjIwmyREgwGCfQEN4X8lxbJnKBYurgz+VfcStA=", - version = "v3.4.2", - ) - go_repository( - name = "com_github_microcosm_cc_bluemonday", - build_file_proto_mode = "disable_global", - importpath = "github.com/microcosm-cc/bluemonday", - sum = "h1:p2tT7RNzRdCi0qmwxG+HbqD6ILkmwter1ZwVZn1oTxA=", - version = "v1.0.22", - ) - go_repository( - name = "com_github_mitchellh_copystructure", - build_file_proto_mode = "disable_global", - importpath = "github.com/mitchellh/copystructure", - sum = "h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=", - version = "v1.2.0", - ) - go_repository( - name = "com_github_mitchellh_go_homedir", - build_file_proto_mode = "disable_global", - importpath = "github.com/mitchellh/go-homedir", - sum = "h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y=", - version = "v1.1.0", - ) - go_repository( - name = "com_github_mitchellh_go_wordwrap", - build_file_proto_mode = "disable_global", - importpath = "github.com/mitchellh/go-wordwrap", - sum = "h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0=", - version = "v1.0.1", - ) - go_repository( - name = "com_github_mitchellh_mapstructure", - build_file_proto_mode = "disable_global", - importpath = "github.com/mitchellh/mapstructure", - sum = "h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE=", - version = "v1.1.2", - ) - go_repository( - name = "com_github_mitchellh_reflectwalk", - build_file_proto_mode = "disable_global", - importpath = "github.com/mitchellh/reflectwalk", - sum = "h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=", - version = "v1.0.2", - ) - go_repository( - name = "com_github_moby_spdystream", - build_file_proto_mode = "disable_global", - importpath = "github.com/moby/spdystream", - sum = "h1:cjW1zVyyoiM0T7b6UoySUFqzXMoqRckQtXwGPiBhOM8=", - version = "v0.2.0", - ) - go_repository( - name = "com_github_moby_term", - build_file_proto_mode = "disable_global", - importpath = "github.com/moby/term", - sum = "h1:O4SWKdcHVCvYqyDV+9CJA1fcDN2L11Bule0iFy3YlAI=", - version = "v0.0.0-20220808134915-39b0c02b01ae", - ) - go_repository( - name = "com_github_modern_go_concurrent", - build_file_proto_mode = "disable_global", - importpath = "github.com/modern-go/concurrent", - sum = "h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=", - version = "v0.0.0-20180306012644-bacd9c7ef1dd", - ) - go_repository( - name = "com_github_modern_go_reflect2", - build_file_proto_mode = "disable_global", - importpath = "github.com/modern-go/reflect2", - sum = "h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=", - version = "v1.0.2", - ) - go_repository( - name = "com_github_moul_http2curl", - build_file_proto_mode = "disable_global", - importpath = "github.com/moul/http2curl", - sum = "h1:dRMWoAtb+ePxMlLkrCbAqh4TlPHXvoGUSQ323/9Zahs=", - version = "v1.0.0", - ) - go_repository( - name = "com_github_muesli_reflow", - build_file_proto_mode = "disable_global", - importpath = "github.com/muesli/reflow", - sum = "h1:IFsN6K9NfGtjeggFP+68I4chLZV2yIKsXJFNZ+eWh6s=", - version = "v0.3.0", - ) - go_repository( - name = "com_github_muesli_termenv", - build_file_proto_mode = "disable_global", - importpath = "github.com/muesli/termenv", - sum = "h1:KuQRUE3PgxRFWhq4gHvZtPSLCGDqM5q/cYr1pZ39ytc=", - version = "v0.12.0", - ) - go_repository( - name = "com_github_munnerz_goautoneg", - build_file_proto_mode = "disable_global", - importpath = "github.com/munnerz/goautoneg", - sum = "h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=", - version = "v0.0.0-20191010083416-a7dc8b61c822", - ) - go_repository( - name = "com_github_mwitkow_go_proto_validators", - build_file_proto_mode = "disable_global", - importpath = "github.com/mwitkow/go-proto-validators", - sum = "h1:qRlmpTzm2pstMKKzTdvwPCF5QfBNURSlAgN/R+qbKos=", - version = "v0.3.2", - ) - go_repository( - name = "com_github_mxk_go_flowrate", - build_file_proto_mode = "disable_global", - importpath = "github.com/mxk/go-flowrate", - sum = "h1:y5//uYreIhSUg3J1GEMiLbxo1LJaP8RfCpH6pymGZus=", - version = "v0.0.0-20140419014527-cca7078d478f", - ) - go_repository( - name = "com_github_nats_io_jwt", - build_file_proto_mode = "disable_global", - importpath = "github.com/nats-io/jwt", - sum = "h1:xdnzwFETV++jNc4W1mw//qFyJGb2ABOombmZJQS4+Qo=", - version = "v0.3.0", - ) - go_repository( - name = "com_github_nats_io_nats_go", - build_file_proto_mode = "disable_global", - importpath = "github.com/nats-io/nats.go", - sum = "h1:ik3HbLhZ0YABLto7iX80pZLPw/6dx3T+++MZJwLnMrQ=", - version = "v1.9.1", - ) - go_repository( - name = "com_github_nats_io_nkeys", - build_file_proto_mode = "disable_global", - importpath = "github.com/nats-io/nkeys", - sum = "h1:qMd4+pRHgdr1nAClu+2h/2a5F2TmKcCzjCDazVgRoX4=", - version = "v0.1.0", - ) - go_repository( - name = "com_github_nats_io_nuid", - build_file_proto_mode = "disable_global", - importpath = "github.com/nats-io/nuid", - sum = "h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw=", - version = "v1.0.1", - ) - go_repository( - name = "com_github_neelance_parallel", - build_file_proto_mode = "disable_global", - importpath = "github.com/neelance/parallel", - sum = "h1:NZOii9TDGRAfCS5VM16XnF4K7afoLQmIiZX8EkKnxtE=", - version = "v0.0.0-20160708114440-4de9ce63d14c", - ) - go_repository( - name = "com_github_niemeyer_pretty", - build_file_proto_mode = "disable_global", - importpath = "github.com/niemeyer/pretty", - sum = "h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=", - version = "v0.0.0-20200227124842-a10e7caefd8e", - ) - go_repository( - name = "com_github_nightlyone_lockfile", - build_file_proto_mode = "disable_global", - importpath = "github.com/nightlyone/lockfile", - sum = "h1:RHep2cFKK4PonZJDdEl4GmkabuhbsRMgk/k3uAmxBiA=", - version = "v1.0.0", - ) - go_repository( - name = "com_github_nxadm_tail", - build_file_proto_mode = "disable_global", - importpath = "github.com/nxadm/tail", - sum = "h1:DQuhQpB1tVlglWS2hLQ5OV6B5r8aGxSrPc5Qo6uTN78=", - version = "v1.4.4", - ) - go_repository( - name = "com_github_nytimes_gziphandler", - build_file_proto_mode = "disable_global", - importpath = "github.com/NYTimes/gziphandler", - sum = "h1:lsxEuwrXEAokXB9qhlbKWPpo3KMLZQ5WB5WLQRW1uq0=", - version = "v0.0.0-20170623195520-56545f4a5d46", - ) - go_repository( - name = "com_github_oklog_ulid_v2", - build_file_proto_mode = "disable_global", - importpath = "github.com/oklog/ulid/v2", - sum = "h1:r4fFzBm+bv0wNKNh5eXTwU7i85y5x+uwkxCUTNVQqLc=", - version = "v2.0.2", - ) - go_repository( - name = "com_github_olekukonko_tablewriter", - build_file_proto_mode = "disable_global", - importpath = "github.com/olekukonko/tablewriter", - sum = "h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec=", - version = "v0.0.5", - ) - go_repository( - name = "com_github_onsi_ginkgo", - build_file_proto_mode = "disable_global", - importpath = "github.com/onsi/ginkgo", - sum = "h1:M76yO2HkZASFjXL0HSoZJ1AYEmQxNJmY41Jx1zNUq1Y=", - version = "v1.13.0", - ) - go_repository( - name = "com_github_onsi_ginkgo_v2", - build_file_proto_mode = "disable_global", - importpath = "github.com/onsi/ginkgo/v2", - sum = "h1:+Ig9nvqgS5OBSACXNk15PLdp0U9XPYROt9CFzVdFGIs=", - version = "v2.4.0", - ) - go_repository( - name = "com_github_onsi_gomega", - build_file_proto_mode = "disable_global", - importpath = "github.com/onsi/gomega", - sum = "h1:/oxKu9c2HVap+F3PfKort2Hw5DEU+HGlW8n+tguWsys=", - version = "v1.23.0", - ) - go_repository( - name = "com_github_pelletier_go_toml", - build_file_proto_mode = "disable_global", - importpath = "github.com/pelletier/go-toml", - sum = "h1:T5zMGML61Wp+FlcbWjRDT7yAxhJNAiPPLOFECq181zc=", - version = "v1.2.0", - ) - go_repository( - name = "com_github_pelletier_go_toml_v2", - build_file_proto_mode = "disable_global", - importpath = "github.com/pelletier/go-toml/v2", - sum = "h1:ipoSadvV8oGUjnUbMub59IDPPwfxF694nG/jwbMiyQg=", - version = "v2.0.5", - ) - go_repository( - name = "com_github_peterbourgon_diskv", - build_file_proto_mode = "disable_global", - importpath = "github.com/peterbourgon/diskv", - sum = "h1:UBdAOUP5p4RWqPBg048CAvpKN+vxiaj6gdUUzhl4XmI=", - version = "v2.0.1+incompatible", - ) - go_repository( - name = "com_github_pingcap_errors", - build_file_proto_mode = "disable_global", - importpath = "github.com/pingcap/errors", - sum = "h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4=", - version = "v0.11.4", - ) - go_repository( - name = "com_github_pkg_browser", - build_file_proto_mode = "disable_global", - importpath = "github.com/pkg/browser", - sum = "h1:KoWmjvw+nsYOo29YJK9vDA65RGE3NrOnUtO7a+RF9HU=", - version = "v0.0.0-20210911075715-681adbf594b8", - ) - go_repository( - name = "com_github_pkg_diff", - build_file_proto_mode = "disable_global", - importpath = "github.com/pkg/diff", - sum = "h1:aoZm08cpOy4WuID//EZDgcC4zIxODThtZNPirFr42+A=", - version = "v0.0.0-20210226163009-20ebb0f2a09e", - ) - go_repository( - name = "com_github_pkg_errors", - build_file_proto_mode = "disable_global", - importpath = "github.com/pkg/errors", - sum = "h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=", - version = "v0.9.1", - ) - go_repository( - name = "com_github_pkg_profile", - build_file_proto_mode = "disable_global", - importpath = "github.com/pkg/profile", - sum = "h1:hUDfIISABYI59DyeB3OTay/HxSRwTQ8rB/H83k6r5dM=", - version = "v1.6.0", - ) - go_repository( - name = "com_github_pmezard_go_difflib", - build_file_proto_mode = "disable_global", - importpath = "github.com/pmezard/go-difflib", - sum = "h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=", - version = "v1.0.0", - ) - go_repository( - name = "com_github_prometheus_client_model", - build_file_proto_mode = "disable_global", - importpath = "github.com/prometheus/client_model", - sum = "h1:gQz4mCbXsO+nc9n1hCxHcGA3Zx3Eo+UHZoInFGUIXNM=", - version = "v0.0.0-20190812154241-14fe0d1b01d4", - ) - go_repository( - name = "com_github_pseudomuto_protoc_gen_doc", - build_file_proto_mode = "disable_global", - importpath = "github.com/pseudomuto/protoc-gen-doc", - sum = "h1:Ah259kcrio7Ix1Rhb6u8FCaOkzf9qRBqXnvAufg061w=", - version = "v1.5.1", - ) - go_repository( - name = "com_github_pseudomuto_protokit", - build_file_proto_mode = "disable_global", - importpath = "github.com/pseudomuto/protokit", - sum = "h1:hlnBDcy3YEDXH7kc9gV+NLaN0cDzhDvD1s7Y6FZ8RpM=", - version = "v0.2.0", - ) - go_repository( - name = "com_github_puerkitobio_purell", - build_file_proto_mode = "disable_global", - importpath = "github.com/PuerkitoBio/purell", - sum = "h1:WEQqlqaGbrPkxLJWfBwQmfEAE1Z7ONdDLqrN38tNFfI=", - version = "v1.1.1", - ) - go_repository( - name = "com_github_puerkitobio_urlesc", - build_file_proto_mode = "disable_global", - importpath = "github.com/PuerkitoBio/urlesc", - sum = "h1:d+Bc7a5rLufV/sSk/8dngufqelfh6jnri85riMAaF/M=", - version = "v0.0.0-20170810143723-de5bf2ad4578", - ) - go_repository( - name = "com_github_rivo_uniseg", - build_file_proto_mode = "disable_global", - importpath = "github.com/rivo/uniseg", - sum = "h1:YwD0ulJSJytLpiaWua0sBDusfsCZohxjxzVTYjwxfV8=", - version = "v0.4.2", - ) - go_repository( - name = "com_github_rogpeppe_go_internal", - build_file_proto_mode = "disable_global", - importpath = "github.com/rogpeppe/go-internal", - sum = "h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=", - version = "v1.9.0", - ) - go_repository( - name = "com_github_russross_blackfriday", - build_file_proto_mode = "disable_global", - importpath = "github.com/russross/blackfriday", - sum = "h1:HyvC0ARfnZBqnXwABFeSZHpKvJHJJfPz81GNueLj0oo=", - version = "v1.5.2", - ) - go_repository( - name = "com_github_russross_blackfriday_v2", - build_file_proto_mode = "disable_global", - importpath = "github.com/russross/blackfriday/v2", - sum = "h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=", - version = "v2.1.0", - ) - go_repository( - name = "com_github_ryanuber_columnize", - build_file_proto_mode = "disable_global", - importpath = "github.com/ryanuber/columnize", - sum = "h1:j1Wcmh8OrK4Q7GXY+V7SVSY8nUWQxHW5TkBe7YUl+2s=", - version = "v2.1.0+incompatible", - ) - go_repository( - name = "com_github_schollz_closestmatch", - build_file_proto_mode = "disable_global", - importpath = "github.com/schollz/closestmatch", - sum = "h1:Uel2GXEpJqOWBrlyI+oY9LTiyyjYS17cCYRqP13/SHk=", - version = "v2.1.0+incompatible", - ) - go_repository( - name = "com_github_sclevine_agouti", - build_file_proto_mode = "disable_global", - importpath = "github.com/sclevine/agouti", - sum = "h1:8IBJS6PWz3uTlMP3YBIR5f+KAldcGuOeFkFbUWfBgK4=", - version = "v3.0.0+incompatible", - ) - go_repository( - name = "com_github_sergi_go_diff", - build_file_proto_mode = "disable_global", - importpath = "github.com/sergi/go-diff", - sum = "h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0=", - version = "v1.1.0", - ) - go_repository( - name = "com_github_shopify_goreferrer", - build_file_proto_mode = "disable_global", - importpath = "github.com/Shopify/goreferrer", - sum = "h1:KkH3I3sJuOLP3TjA/dfr4NAY8bghDwnXiU7cTKxQqo0=", - version = "v0.0.0-20220729165902-8cddb4f5de06", - ) - go_repository( - name = "com_github_shurcool_go", - build_file_proto_mode = "disable_global", - importpath = "github.com/shurcooL/go", - sum = "h1:MZM7FHLqUHYI0Y/mQAt3d2aYa0SiNms/hFqC9qJYolM=", - version = "v0.0.0-20180423040247-9e1955d9fb6e", - ) - go_repository( - name = "com_github_shurcool_go_goon", - build_file_proto_mode = "disable_global", - importpath = "github.com/shurcooL/go-goon", - sum = "h1:lRAUE0dIvigSSFAmaM2dfg7OH8T+a8zJ5smEh09a/GI=", - version = "v0.0.0-20210110234559-7585751d9a17", - ) - go_repository( - name = "com_github_shurcool_sanitized_anchor_name", - build_file_proto_mode = "disable_global", - importpath = "github.com/shurcooL/sanitized_anchor_name", - sum = "h1:PdmoCO6wvbs+7yrJyMORt4/BmY5IYyJwS/kOiWx8mHo=", - version = "v1.0.0", - ) - go_repository( - name = "com_github_sirupsen_logrus", - build_file_proto_mode = "disable_global", - importpath = "github.com/sirupsen/logrus", - sum = "h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0=", - version = "v1.9.0", - ) - go_repository( - name = "com_github_smacker_go_tree_sitter", - build_file_proto_mode = "disable_global", - importpath = "github.com/smacker/go-tree-sitter", - sum = "h1:WrsSqod9T70HFyq8hjL6wambOKb4ISUXzFUuNTJHDwo=", - version = "v0.0.0-20220209044044-0d3022e933c3", - ) - go_repository( - name = "com_github_smartystreets_assertions", - build_file_proto_mode = "disable_global", - importpath = "github.com/smartystreets/assertions", - sum = "h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM=", - version = "v0.0.0-20180927180507-b2de0cb4f26d", - ) - go_repository( - name = "com_github_smartystreets_goconvey", - build_file_proto_mode = "disable_global", - importpath = "github.com/smartystreets/goconvey", - sum = "h1:fv0U8FUIMPNf1L9lnHLvLhgicrIVChEkdzIKYqbNC9s=", - version = "v1.6.4", - ) - go_repository( - name = "com_github_sourcegraph_conc", - build_file_proto_mode = "disable_global", - importpath = "github.com/sourcegraph/conc", - sum = "h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo=", - version = "v0.3.0", - ) - go_repository( - name = "com_github_sourcegraph_go_diff", - build_file_proto_mode = "disable_global", - importpath = "github.com/sourcegraph/go-diff", - sum = "h1:11miag7hlORpW7ici5mL7T9PyiEsmVmf+8PFOvJ/ZrA=", - version = "v0.6.2-0.20221123165719-f8cd299c40f3", - ) - go_repository( - name = "com_github_sourcegraph_jsonx", - build_file_proto_mode = "disable_global", - importpath = "github.com/sourcegraph/jsonx", - sum = "h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI=", - version = "v0.0.0-20200629203448-1a936bd500cf", - ) - go_repository( - name = "com_github_sourcegraph_log", - build_file_proto_mode = "disable_global", - importpath = "github.com/sourcegraph/log", - sum = "h1:hgZHfGYG3KMlDDfACuPgzhMIaEjblCqZ+YltcPgd0tw=", - version = "v0.0.0-20221206163500-7d93c6ad7037", - ) - go_repository( - name = "com_github_sourcegraph_scip", - build_file_proto_mode = "disable_global", - importpath = "github.com/sourcegraph/scip", - sum = "h1:fWPxLkDObzzKTGe9vb6wpzK0FYkwcfSxmxUBvAOc8aw=", - version = "v0.2.4-0.20221213205653-aa0e511dcfef", - ) - go_repository( - name = "com_github_sourcegraph_sourcegraph_lib", - build_file_proto_mode = "disable_global", - importpath = "github.com/sourcegraph/sourcegraph/lib", - sum = "h1:0hAo7bbfcF3uujbq2eNl2DpN6zUrjacWAK3iSan5Q0k=", - version = "v0.0.0-20230914103605-e3a8bc516ddc", - ) - go_repository( - name = "com_github_spf13_afero", - build_file_proto_mode = "disable_global", - importpath = "github.com/spf13/afero", - sum = "h1:j49Hj62F0n+DaZ1dDCvhABaPNSGNkt32oRFxI33IEMw=", - version = "v1.9.2", - ) - go_repository( - name = "com_github_spf13_cast", - build_file_proto_mode = "disable_global", - importpath = "github.com/spf13/cast", - sum = "h1:oget//CVOEoFewqQxwr0Ej5yjygnqGkvggSE/gB35Q8=", - version = "v1.3.0", - ) - go_repository( - name = "com_github_spf13_cobra", - build_file_proto_mode = "disable_global", - importpath = "github.com/spf13/cobra", - sum = "h1:42a0n6jwCot1pUmomAp4T7DeMD+20LFv4Q54pxLf2LI=", - version = "v1.6.0", - ) - go_repository( - name = "com_github_spf13_jwalterweatherman", - build_file_proto_mode = "disable_global", - importpath = "github.com/spf13/jwalterweatherman", - sum = "h1:XHEdyB+EcvlqZamSM4ZOMGlc93t6AcsBEu9Gc1vn7yk=", - version = "v1.0.0", - ) - go_repository( - name = "com_github_spf13_pflag", - build_file_proto_mode = "disable_global", - importpath = "github.com/spf13/pflag", - sum = "h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=", - version = "v1.0.5", - ) - go_repository( - name = "com_github_spf13_viper", - build_file_proto_mode = "disable_global", - importpath = "github.com/spf13/viper", - sum = "h1:VUFqw5KcqRf7i70GOzW7N+Q7+gxVBkSSqiXB12+JQ4M=", - version = "v1.3.2", - ) - go_repository( - name = "com_github_ssor_bom", - build_file_proto_mode = "disable_global", - importpath = "github.com/ssor/bom", - sum = "h1:pvbZ0lM0XWPBqUKqFU8cmavspvIl9nulOYwdy6IFRRo=", - version = "v0.0.0-20170718123548-6386211fdfcf", - ) - go_repository( - name = "com_github_stoewer_go_strcase", - build_file_proto_mode = "disable_global", - importpath = "github.com/stoewer/go-strcase", - sum = "h1:Z2iHWqGXH00XYgqDmNgQbIBxf3wrNq0F3feEy0ainaU=", - version = "v1.2.0", - ) - go_repository( - name = "com_github_stretchr_objx", - build_file_proto_mode = "disable_global", - importpath = "github.com/stretchr/objx", - sum = "h1:1zr/of2m5FGMsad5YfcqgdqdWrIhu+EBEJRhR1U7z/c=", - version = "v0.5.0", - ) - go_repository( - name = "com_github_stretchr_testify", - build_file_proto_mode = "disable_global", - importpath = "github.com/stretchr/testify", - sum = "h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=", - version = "v1.8.1", - ) - go_repository( - name = "com_github_tdewolff_minify_v2", - build_file_proto_mode = "disable_global", - importpath = "github.com/tdewolff/minify/v2", - sum = "h1:kejsHQMM17n6/gwdw53qsi6lg0TGddZADVyQOz1KMdE=", - version = "v2.12.4", - ) - go_repository( - name = "com_github_tdewolff_parse_v2", - build_file_proto_mode = "disable_global", - importpath = "github.com/tdewolff/parse/v2", - sum = "h1:KCkDvNUMof10e3QExio9OPZJT8SbdKojLBumw8YZycQ=", - version = "v2.6.4", - ) - go_repository( - name = "com_github_ugorji_go", - build_file_proto_mode = "disable_global", - importpath = "github.com/ugorji/go", - sum = "h1:/68gy2h+1mWMrwZFeD1kQialdSzAb432dtpeJ42ovdo=", - version = "v1.1.7", - ) - go_repository( - name = "com_github_ugorji_go_codec", - build_file_proto_mode = "disable_global", - importpath = "github.com/ugorji/go/codec", - sum = "h1:YPXUKf7fYbp/y8xloBqZOw2qaVggbfwMlI8WM3wZUJ0=", - version = "v1.2.7", - ) - go_repository( - name = "com_github_urfave_cli_v2", - build_file_proto_mode = "disable_global", - importpath = "github.com/urfave/cli/v2", - sum = "h1:YHDQ46s3VghFHFf1DdF+Sh7H4RqhcM+t0TmZRJx4oJY=", - version = "v2.23.7", - ) - go_repository( - name = "com_github_urfave_negroni", - build_file_proto_mode = "disable_global", - importpath = "github.com/urfave/negroni", - sum = "h1:kIimOitoypq34K7TG7DUaJ9kq/N4Ofuwi1sjz0KipXc=", - version = "v1.0.0", - ) - go_repository( - name = "com_github_valyala_bytebufferpool", - build_file_proto_mode = "disable_global", - importpath = "github.com/valyala/bytebufferpool", - sum = "h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=", - version = "v1.0.0", - ) - go_repository( - name = "com_github_valyala_fasthttp", - build_file_proto_mode = "disable_global", - importpath = "github.com/valyala/fasthttp", - sum = "h1:CRq/00MfruPGFLTQKY8b+8SfdK60TxNztjRMnH0t1Yc=", - version = "v1.40.0", - ) - go_repository( - name = "com_github_valyala_fasttemplate", - build_file_proto_mode = "disable_global", - importpath = "github.com/valyala/fasttemplate", - sum = "h1:TVEnxayobAdVkhQfrfes2IzOB6o+z4roRkPF52WA1u4=", - version = "v1.2.1", - ) - go_repository( - name = "com_github_valyala_tcplisten", - build_file_proto_mode = "disable_global", - importpath = "github.com/valyala/tcplisten", - sum = "h1:0R4NLDRDZX6JcmhJgXi5E4b8Wg84ihbmUKp/GvSPEzc=", - version = "v0.0.0-20161114210144-ceec8f93295a", - ) - go_repository( - name = "com_github_vmihailenco_msgpack_v5", - build_file_proto_mode = "disable_global", - importpath = "github.com/vmihailenco/msgpack/v5", - sum = "h1:5gO0H1iULLWGhs2H5tbAHIZTV8/cYafcFOr9znI5mJU=", - version = "v5.3.5", - ) - go_repository( - name = "com_github_vmihailenco_tagparser_v2", - build_file_proto_mode = "disable_global", - importpath = "github.com/vmihailenco/tagparser/v2", - sum = "h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g=", - version = "v2.0.0", - ) - go_repository( - name = "com_github_xeipuuv_gojsonpointer", - build_file_proto_mode = "disable_global", - importpath = "github.com/xeipuuv/gojsonpointer", - sum = "h1:zGWFAtiMcyryUHoUjUJX0/lt1H2+i2Ka2n+D3DImSNo=", - version = "v0.0.0-20190905194746-02993c407bfb", - ) - go_repository( - name = "com_github_xeipuuv_gojsonreference", - build_file_proto_mode = "disable_global", - importpath = "github.com/xeipuuv/gojsonreference", - sum = "h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0=", - version = "v0.0.0-20180127040603-bd5ef7bd5415", - ) - go_repository( - name = "com_github_xeipuuv_gojsonschema", - build_file_proto_mode = "disable_global", - importpath = "github.com/xeipuuv/gojsonschema", - sum = "h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74=", - version = "v1.2.0", - ) - go_repository( - name = "com_github_xordataexchange_crypt", - build_file_proto_mode = "disable_global", - importpath = "github.com/xordataexchange/crypt", - sum = "h1:ESFSdwYZvkeru3RtdrYueztKhOBCSAAzS4Gf+k0tEow=", - version = "v0.0.3-0.20170626215501-b2862e3d0a77", - ) - go_repository( - name = "com_github_xrash_smetrics", - build_file_proto_mode = "disable_global", - importpath = "github.com/xrash/smetrics", - sum = "h1:bAn7/zixMGCfxrRTfdpNzjtPYqr8smhKouy9mxVdGPU=", - version = "v0.0.0-20201216005158-039620a65673", - ) - go_repository( - name = "com_github_yalp_jsonpath", - build_file_proto_mode = "disable_global", - importpath = "github.com/yalp/jsonpath", - sum = "h1:6fRhSjgLCkTD3JnJxvaJ4Sj+TYblw757bqYgZaOq5ZY=", - version = "v0.0.0-20180802001716-5cc68e5049a0", - ) - go_repository( - name = "com_github_yosssi_ace", - build_file_proto_mode = "disable_global", - importpath = "github.com/yosssi/ace", - sum = "h1:tUkIP/BLdKqrlrPwcmH0shwEEhTRHoGnc1wFIWmaBUA=", - version = "v0.0.5", - ) - go_repository( - name = "com_github_yudai_gojsondiff", - build_file_proto_mode = "disable_global", - importpath = "github.com/yudai/gojsondiff", - sum = "h1:27cbfqXLVEJ1o8I6v3y9lg8Ydm53EKqHXAOMxEGlCOA=", - version = "v1.0.0", - ) - go_repository( - name = "com_github_yudai_golcs", - build_file_proto_mode = "disable_global", - importpath = "github.com/yudai/golcs", - sum = "h1:BHyfKlQyqbsFN5p3IfnEUduWvb9is428/nNb5L3U01M=", - version = "v0.0.0-20170316035057-ecda9a501e82", - ) - go_repository( - name = "com_github_yudai_pp", - build_file_proto_mode = "disable_global", - importpath = "github.com/yudai/pp", - sum = "h1:Q4//iY4pNF6yPLZIigmvcl7k/bPgrcTPIFIcmawg5bI=", - version = "v2.0.1+incompatible", - ) - go_repository( - name = "com_github_yuin_goldmark", - build_file_proto_mode = "disable_global", - importpath = "github.com/yuin/goldmark", - sum = "h1:ALmeCk/px5FSm1MAcFBAsVKZjDuMVj8Tm7FFIlMJnqU=", - version = "v1.5.2", - ) - go_repository( - name = "com_github_yuin_goldmark_emoji", - build_file_proto_mode = "disable_global", - importpath = "github.com/yuin/goldmark-emoji", - sum = "h1:ctuWEyzGBwiucEqxzwe0SOYDXPAucOrE9NQC18Wa1os=", - version = "v1.0.1", - ) - go_repository( - name = "com_google_cloud_go", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go", - sum = "h1:qkj22L7bgkl6vIeZDlOY2po43Mx/TIa2Wsa7VR+PEww=", - version = "v0.107.0", - ) - go_repository( - name = "com_google_cloud_go_accessapproval", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/accessapproval", - sum = "h1:/nTivgnV/n1CaAeo+ekGexTYUsKEU9jUVkoY5359+3Q=", - version = "v1.5.0", - ) - go_repository( - name = "com_google_cloud_go_accesscontextmanager", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/accesscontextmanager", - sum = "h1:CFhNhU7pcD11cuDkQdrE6PQJgv0EXNKNv06jIzbLlCU=", - version = "v1.4.0", - ) - go_repository( - name = "com_google_cloud_go_aiplatform", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/aiplatform", - sum = "h1:DBi3Jk9XjCJ4pkkLM4NqKgj3ozUL1wq4l+d3/jTGXAI=", - version = "v1.27.0", - ) - go_repository( - name = "com_google_cloud_go_analytics", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/analytics", - sum = "h1:NKw6PpQi6V1O+KsjuTd+bhip9d0REYu4NevC45vtGp8=", - version = "v0.12.0", - ) - go_repository( - name = "com_google_cloud_go_apigateway", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/apigateway", - sum = "h1:IIoXKR7FKrEAQhMTz5hK2wiDz2WNFHS7eVr/L1lE/rM=", - version = "v1.4.0", - ) - go_repository( - name = "com_google_cloud_go_apigeeconnect", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/apigeeconnect", - sum = "h1:AONoTYJviyv1vS4IkvWzq69gEVdvHx35wKXc+e6wjZQ=", - version = "v1.4.0", - ) - go_repository( - name = "com_google_cloud_go_apigeeregistry", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/apigeeregistry", - sum = "h1:Av+wedLP6pM8NsLruknv/RFCE/5VVavOhZ8j722vBxg=", - version = "v0.4.0", - ) - go_repository( - name = "com_google_cloud_go_apikeys", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/apikeys", - sum = "h1:d+t1B9U1Ze3LmiRYdSVhNrcRlU6coLvPzNDkqYVuHoc=", - version = "v0.4.0", - ) - go_repository( - name = "com_google_cloud_go_appengine", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/appengine", - sum = "h1:lmG+O5oaR9xNwaRBwE2XoMhwQHsHql5IoiGr1ptdDwU=", - version = "v1.5.0", - ) - go_repository( - name = "com_google_cloud_go_area120", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/area120", - sum = "h1:TCMhwWEWhCn8d44/Zs7UCICTWje9j3HuV6nVGMjdpYw=", - version = "v0.6.0", - ) - go_repository( - name = "com_google_cloud_go_artifactregistry", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/artifactregistry", - sum = "h1:3d0LRAU1K6vfqCahhl9fx2oGHcq+s5gftdix4v8Ibrc=", - version = "v1.9.0", - ) - go_repository( - name = "com_google_cloud_go_asset", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/asset", - sum = "h1:aCrlaLGJWTODJX4G56ZYzJefITKEWNfbjjtHSzWpxW0=", - version = "v1.10.0", - ) - go_repository( - name = "com_google_cloud_go_assuredworkloads", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/assuredworkloads", - sum = "h1:hhIdCOowsT1GG5eMCIA0OwK6USRuYTou/1ZeNxCSRtA=", - version = "v1.9.0", - ) - go_repository( - name = "com_google_cloud_go_automl", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/automl", - sum = "h1:BMioyXSbg7d7xLibn47cs0elW6RT780IUWr42W8rp2Q=", - version = "v1.8.0", - ) - go_repository( - name = "com_google_cloud_go_baremetalsolution", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/baremetalsolution", - sum = "h1:g9KO6SkakcYPcc/XjAzeuUrEOXlYPnMpuiaywYaGrmQ=", - version = "v0.4.0", - ) - go_repository( - name = "com_google_cloud_go_batch", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/batch", - sum = "h1:1jvEBY55OH4Sd2FxEXQfxGExFWov1A/IaRe+Z5Z71Fw=", - version = "v0.4.0", - ) - go_repository( - name = "com_google_cloud_go_beyondcorp", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/beyondcorp", - sum = "h1:w+4kThysgl0JiKshi2MKDCg2NZgOyqOI0wq2eBZyrzA=", - version = "v0.3.0", - ) - go_repository( - name = "com_google_cloud_go_bigquery", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/bigquery", - sum = "h1:Wi4dITi+cf9VYp4VH2T9O41w0kCW0uQTELq2Z6tukN0=", - version = "v1.44.0", - ) - go_repository( - name = "com_google_cloud_go_billing", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/billing", - sum = "h1:Xkii76HWELHwBtkQVZvqmSo9GTr0O+tIbRNnMcGdlg4=", - version = "v1.7.0", - ) - go_repository( - name = "com_google_cloud_go_binaryauthorization", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/binaryauthorization", - sum = "h1:pL70vXWn9TitQYXBWTK2abHl2JHLwkFRjYw6VflRqEA=", - version = "v1.4.0", - ) - go_repository( - name = "com_google_cloud_go_certificatemanager", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/certificatemanager", - sum = "h1:tzbR4UHBbgsewMWUD93JHi8EBi/gHBoSAcY1/sThFGk=", - version = "v1.4.0", - ) - go_repository( - name = "com_google_cloud_go_channel", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/channel", - sum = "h1:pNuUlZx0Jb0Ts9P312bmNMuH5IiFWIR4RUtLb70Ke5s=", - version = "v1.9.0", - ) - go_repository( - name = "com_google_cloud_go_cloudbuild", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/cloudbuild", - sum = "h1:TAAmCmAlOJ4uNBu6zwAjwhyl/7fLHHxIEazVhr3QBbQ=", - version = "v1.4.0", - ) - go_repository( - name = "com_google_cloud_go_clouddms", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/clouddms", - sum = "h1:UhzHIlgFfMr6luVYVNydw/pl9/U5kgtjCMJHnSvoVws=", - version = "v1.4.0", - ) - go_repository( - name = "com_google_cloud_go_cloudtasks", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/cloudtasks", - sum = "h1:faUiUgXjW8yVZ7XMnKHKm1WE4OldPBUWWfIRN/3z1dc=", - version = "v1.8.0", - ) - go_repository( - name = "com_google_cloud_go_compute", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/compute", - sum = "h1:FEigFqoDbys2cvFkZ9Fjq4gnHBP55anJ0yQyau2f9oY=", - version = "v1.18.0", - ) - go_repository( - name = "com_google_cloud_go_compute_metadata", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/compute/metadata", - sum = "h1:mg4jlk7mCAj6xXp9UJ4fjI9VUI5rubuGBW5aJ7UnBMY=", - version = "v0.2.3", - ) - go_repository( - name = "com_google_cloud_go_contactcenterinsights", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/contactcenterinsights", - sum = "h1:tTQLI/ZvguUf9Hv+36BkG2+/PeC8Ol1q4pBW+tgCx0A=", - version = "v1.4.0", - ) - go_repository( - name = "com_google_cloud_go_container", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/container", - sum = "h1:nbEK/59GyDRKKlo1SqpohY1TK8LmJ2XNcvS9Gyom2A0=", - version = "v1.7.0", - ) - go_repository( - name = "com_google_cloud_go_containeranalysis", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/containeranalysis", - sum = "h1:2824iym832ljKdVpCBnpqm5K94YT/uHTVhNF+dRTXPI=", - version = "v0.6.0", - ) - go_repository( - name = "com_google_cloud_go_datacatalog", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/datacatalog", - sum = "h1:6kZ4RIOW/uT7QWC5SfPfq/G8sYzr/v+UOmOAxy4Z1TE=", - version = "v1.8.0", - ) - go_repository( - name = "com_google_cloud_go_dataflow", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/dataflow", - sum = "h1:CW3541Fm7KPTyZjJdnX6NtaGXYFn5XbFC5UcjgALKvU=", - version = "v0.7.0", - ) - go_repository( - name = "com_google_cloud_go_dataform", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/dataform", - sum = "h1:vLwowLF2ZB5J5gqiZCzv076lDI/Rd7zYQQFu5XO1PSg=", - version = "v0.5.0", - ) - go_repository( - name = "com_google_cloud_go_datafusion", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/datafusion", - sum = "h1:j5m2hjWovTZDTQak4MJeXAR9yN7O+zMfULnjGw/OOLg=", - version = "v1.5.0", - ) - go_repository( - name = "com_google_cloud_go_datalabeling", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/datalabeling", - sum = "h1:dp8jOF21n/7jwgo/uuA0RN8hvLcKO4q6s/yvwevs2ZM=", - version = "v0.6.0", - ) - go_repository( - name = "com_google_cloud_go_dataplex", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/dataplex", - sum = "h1:cNxeA2DiWliQGi21kPRqnVeQ5xFhNoEjPRt1400Pm8Y=", - version = "v1.4.0", - ) - go_repository( - name = "com_google_cloud_go_dataproc", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/dataproc", - sum = "h1:gVOqNmElfa6n/ccG/QDlfurMWwrK3ezvy2b2eDoCmS0=", - version = "v1.8.0", - ) - go_repository( - name = "com_google_cloud_go_dataqna", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/dataqna", - sum = "h1:gx9jr41ytcA3dXkbbd409euEaWtofCVXYBvJz3iYm18=", - version = "v0.6.0", - ) - go_repository( - name = "com_google_cloud_go_datastore", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/datastore", - sum = "h1:4siQRf4zTiAVt/oeH4GureGkApgb2vtPQAtOmhpqQwE=", - version = "v1.10.0", - ) - go_repository( - name = "com_google_cloud_go_datastream", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/datastream", - sum = "h1:PgIgbhedBtYBU6POGXFMn2uSl9vpqubc3ewTNdcU8Mk=", - version = "v1.5.0", - ) - go_repository( - name = "com_google_cloud_go_deploy", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/deploy", - sum = "h1:kI6dxt8Ml0is/x7YZjLveTvR7YPzXAUD/8wQZ2nH5zA=", - version = "v1.5.0", - ) - go_repository( - name = "com_google_cloud_go_dialogflow", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/dialogflow", - sum = "h1:Opy6fM2IV9ecQOXkce0JByjBVg8+4X+1AbTAQLbgrCg=", - version = "v1.29.0", - ) - go_repository( - name = "com_google_cloud_go_dlp", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/dlp", - sum = "h1:9I4BYeJSVKoSKgjr70fLdRDumqcUeVmHV4fd5f9LR6Y=", - version = "v1.7.0", - ) - go_repository( - name = "com_google_cloud_go_documentai", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/documentai", - sum = "h1:jfq09Fdjtnpnmt/MLyf6A3DM3ynb8B2na0K+vSXvpFM=", - version = "v1.10.0", - ) - go_repository( - name = "com_google_cloud_go_domains", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/domains", - sum = "h1:pu3JIgC1rswIqi5romW0JgNO6CTUydLYX8zyjiAvO1c=", - version = "v0.7.0", - ) - go_repository( - name = "com_google_cloud_go_edgecontainer", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/edgecontainer", - sum = "h1:hd6J2n5dBBRuAqnNUEsKWrp6XNPKsaxwwIyzOPZTokk=", - version = "v0.2.0", - ) - go_repository( - name = "com_google_cloud_go_errorreporting", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/errorreporting", - sum = "h1:kj1XEWMu8P0qlLhm3FwcaFsUvXChV/OraZwA70trRR0=", - version = "v0.3.0", - ) - go_repository( - name = "com_google_cloud_go_essentialcontacts", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/essentialcontacts", - sum = "h1:b6csrQXCHKQmfo9h3dG/pHyoEh+fQG1Yg78a53LAviY=", - version = "v1.4.0", - ) - go_repository( - name = "com_google_cloud_go_eventarc", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/eventarc", - sum = "h1:AgCqrmMMIcel5WWKkzz5EkCUKC3Rl5LNMMYsS+LvsI0=", - version = "v1.8.0", - ) - go_repository( - name = "com_google_cloud_go_filestore", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/filestore", - sum = "h1:yjKOpzvqtDmL5AXbKttLc8j0hL20kuC1qPdy5HPcxp0=", - version = "v1.4.0", - ) - go_repository( - name = "com_google_cloud_go_firestore", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/firestore", - sum = "h1:IBlRyxgGySXu5VuW0RgGFlTtLukSnNkpDiEOMkQkmpA=", - version = "v1.9.0", - ) - go_repository( - name = "com_google_cloud_go_functions", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/functions", - sum = "h1:35tgv1fQOtvKqH/uxJMzX3w6usneJ0zXpsFr9KAVhNE=", - version = "v1.9.0", - ) - go_repository( - name = "com_google_cloud_go_gaming", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/gaming", - sum = "h1:97OAEQtDazAJD7yh/kvQdSCQuTKdR0O+qWAJBZJ4xiA=", - version = "v1.8.0", - ) - go_repository( - name = "com_google_cloud_go_gkebackup", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/gkebackup", - sum = "h1:4K+jiv4ocqt1niN8q5Imd8imRoXBHTrdnJVt/uFFxF4=", - version = "v0.3.0", - ) - go_repository( - name = "com_google_cloud_go_gkeconnect", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/gkeconnect", - sum = "h1:zAcvDa04tTnGdu6TEZewaLN2tdMtUOJJ7fEceULjguA=", - version = "v0.6.0", - ) - go_repository( - name = "com_google_cloud_go_gkehub", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/gkehub", - sum = "h1:JTcTaYQRGsVm+qkah7WzHb6e9sf1C0laYdRPn9aN+vg=", - version = "v0.10.0", - ) - go_repository( - name = "com_google_cloud_go_gkemulticloud", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/gkemulticloud", - sum = "h1:8F1NhJj8ucNj7lK51UZMtAjSWTgP1zO18XF6vkfiPPU=", - version = "v0.4.0", - ) - go_repository( - name = "com_google_cloud_go_gsuiteaddons", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/gsuiteaddons", - sum = "h1:TGT2oGmO5q3VH6SjcrlgPUWI0njhYv4kywLm6jag0to=", - version = "v1.4.0", - ) - go_repository( - name = "com_google_cloud_go_iam", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/iam", - sum = "h1:DRtTY29b75ciH6Ov1PHb4/iat2CLCvrOm40Q0a6DFpE=", - version = "v0.12.0", - ) - go_repository( - name = "com_google_cloud_go_iap", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/iap", - sum = "h1:BGEXovwejOCt1zDk8hXq0bOhhRu9haXKWXXXp2B4wBM=", - version = "v1.5.0", - ) - go_repository( - name = "com_google_cloud_go_ids", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/ids", - sum = "h1:LncHK4HHucb5Du310X8XH9/ICtMwZ2PCfK0ScjWiJoY=", - version = "v1.2.0", - ) - go_repository( - name = "com_google_cloud_go_iot", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/iot", - sum = "h1:Y9+oZT9jD4GUZzORXTU45XsnQrhxmDT+TFbPil6pRVQ=", - version = "v1.4.0", - ) - go_repository( - name = "com_google_cloud_go_kms", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/kms", - sum = "h1:OWRZzrPmOZUzurjI2FBGtgY2mB1WaJkqhw6oIwSj0Yg=", - version = "v1.6.0", - ) - go_repository( - name = "com_google_cloud_go_language", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/language", - sum = "h1:3Wa+IUMamL4JH3Zd3cDZUHpwyqplTACt6UZKRD2eCL4=", - version = "v1.8.0", - ) - go_repository( - name = "com_google_cloud_go_lifesciences", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/lifesciences", - sum = "h1:tIqhivE2LMVYkX0BLgG7xL64oNpDaFFI7teunglt1tI=", - version = "v0.6.0", - ) - go_repository( - name = "com_google_cloud_go_logging", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/logging", - sum = "h1:ZBsZK+JG+oCDT+vaxwqF2egKNRjz8soXiS6Xv79benI=", - version = "v1.6.1", - ) - go_repository( - name = "com_google_cloud_go_longrunning", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/longrunning", - sum = "h1:NjljC+FYPV3uh5/OwWT6pVU+doBqMg2x/rZlE+CamDs=", - version = "v0.3.0", - ) - go_repository( - name = "com_google_cloud_go_managedidentities", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/managedidentities", - sum = "h1:3Kdajn6X25yWQFhFCErmKSYTSvkEd3chJROny//F1A0=", - version = "v1.4.0", - ) - go_repository( - name = "com_google_cloud_go_maps", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/maps", - sum = "h1:kLReRbclTgJefw2fcCbdLPLhPj0U6UUWN10ldG8sdOU=", - version = "v0.1.0", - ) - go_repository( - name = "com_google_cloud_go_mediatranslation", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/mediatranslation", - sum = "h1:qAJzpxmEX+SeND10Y/4868L5wfZpo4Y3BIEnIieP4dk=", - version = "v0.6.0", - ) - go_repository( - name = "com_google_cloud_go_memcache", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/memcache", - sum = "h1:yLxUzJkZVSH2kPaHut7k+7sbIBFpvSh1LW9qjM2JDjA=", - version = "v1.7.0", - ) - go_repository( - name = "com_google_cloud_go_metastore", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/metastore", - sum = "h1:3KcShzqWdqxrDEXIBWpYJpOOrgpDj+HlBi07Grot49Y=", - version = "v1.8.0", - ) - go_repository( - name = "com_google_cloud_go_monitoring", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/monitoring", - sum = "h1:c9riaGSPQ4dUKWB+M1Fl0N+iLxstMbCktdEwYSPGDvA=", - version = "v1.8.0", - ) - go_repository( - name = "com_google_cloud_go_networkconnectivity", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/networkconnectivity", - sum = "h1:BVdIKaI68bihnXGdCVL89Jsg9kq2kg+II30fjVqo62E=", - version = "v1.7.0", - ) - go_repository( - name = "com_google_cloud_go_networkmanagement", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/networkmanagement", - sum = "h1:mDHA3CDW00imTvC5RW6aMGsD1bH+FtKwZm/52BxaiMg=", - version = "v1.5.0", - ) - go_repository( - name = "com_google_cloud_go_networksecurity", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/networksecurity", - sum = "h1:qDEX/3sipg9dS5JYsAY+YvgTjPR63cozzAWop8oZS94=", - version = "v0.6.0", - ) - go_repository( - name = "com_google_cloud_go_notebooks", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/notebooks", - sum = "h1:AC8RPjNvel3ExgXjO1YOAz+teg9+j+89TNxa7pIZfww=", - version = "v1.5.0", - ) - go_repository( - name = "com_google_cloud_go_optimization", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/optimization", - sum = "h1:7PxOq9VTT7TMib/6dMoWpMvWS2E4dJEvtYzjvBreaec=", - version = "v1.2.0", - ) - go_repository( - name = "com_google_cloud_go_orchestration", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/orchestration", - sum = "h1:39d6tqvNjd/wsSub1Bn4cEmrYcet5Ur6xpaN+SxOxtY=", - version = "v1.4.0", - ) - go_repository( - name = "com_google_cloud_go_orgpolicy", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/orgpolicy", - sum = "h1:erF5PHqDZb6FeFrUHiYj2JK2BMhsk8CyAg4V4amJ3rE=", - version = "v1.5.0", - ) - go_repository( - name = "com_google_cloud_go_osconfig", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/osconfig", - sum = "h1:NO0RouqCOM7M2S85Eal6urMSSipWwHU8evzwS+siqUI=", - version = "v1.10.0", - ) - go_repository( - name = "com_google_cloud_go_oslogin", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/oslogin", - sum = "h1:pKGDPfeZHDybtw48WsnVLjoIPMi9Kw62kUE5TXCLCN4=", - version = "v1.7.0", - ) - go_repository( - name = "com_google_cloud_go_phishingprotection", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/phishingprotection", - sum = "h1:OrwHLSRSZyaiOt3tnY33dsKSedxbMzsXvqB21okItNQ=", - version = "v0.6.0", - ) - go_repository( - name = "com_google_cloud_go_policytroubleshooter", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/policytroubleshooter", - sum = "h1:NQklJuOUoz1BPP+Epjw81COx7IISWslkZubz/1i0UN8=", - version = "v1.4.0", - ) - go_repository( - name = "com_google_cloud_go_privatecatalog", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/privatecatalog", - sum = "h1:Vz86uiHCtNGm1DeC32HeG2VXmOq5JRYA3VRPf8ZEcSg=", - version = "v0.6.0", - ) - go_repository( - name = "com_google_cloud_go_pubsub", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/pubsub", - sum = "h1:q+J/Nfr6Qx4RQeu3rJcnN48SNC0qzlYzSeqkPq93VHs=", - version = "v1.27.1", - ) - go_repository( - name = "com_google_cloud_go_pubsublite", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/pubsublite", - sum = "h1:iqrD8vp3giTb7hI1q4TQQGj77cj8zzgmMPsTZtLnprM=", - version = "v1.5.0", - ) - go_repository( - name = "com_google_cloud_go_recaptchaenterprise_v2", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/recaptchaenterprise/v2", - sum = "h1:UqzFfb/WvhwXGDF1eQtdHLrmni+iByZXY4h3w9Kdyv8=", - version = "v2.5.0", - ) - go_repository( - name = "com_google_cloud_go_recommendationengine", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/recommendationengine", - sum = "h1:6w+WxPf2LmUEqX0YyvfCoYb8aBYOcbIV25Vg6R0FLGw=", - version = "v0.6.0", - ) - go_repository( - name = "com_google_cloud_go_recommender", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/recommender", - sum = "h1:9kMZQGeYfcOD/RtZfcNKGKtoex3DdoB4zRgYU/WaIwE=", - version = "v1.8.0", - ) - go_repository( - name = "com_google_cloud_go_redis", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/redis", - sum = "h1:/zTwwBKIAD2DEWTrXZp8WD9yD/gntReF/HkPssVYd0U=", - version = "v1.10.0", - ) - go_repository( - name = "com_google_cloud_go_resourcemanager", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/resourcemanager", - sum = "h1:NDao6CHMwEZIaNsdWy+tuvHaavNeGP06o1tgrR0kLvU=", - version = "v1.4.0", - ) - go_repository( - name = "com_google_cloud_go_resourcesettings", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/resourcesettings", - sum = "h1:eTzOwB13WrfF0kuzG2ZXCfB3TLunSHBur4s+HFU6uSM=", - version = "v1.4.0", - ) - go_repository( - name = "com_google_cloud_go_retail", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/retail", - sum = "h1:N9fa//ecFUOEPsW/6mJHfcapPV0wBSwIUwpVZB7MQ3o=", - version = "v1.11.0", - ) - go_repository( - name = "com_google_cloud_go_run", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/run", - sum = "h1:AWPuzU7Xtaj3Jf+QarDWIs6AJ5hM1VFQ+F6Q+VZ6OT4=", - version = "v0.3.0", - ) - go_repository( - name = "com_google_cloud_go_scheduler", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/scheduler", - sum = "h1:K/mxOewgHGeKuATUJNGylT75Mhtjmx1TOkKukATqMT8=", - version = "v1.7.0", - ) - go_repository( - name = "com_google_cloud_go_secretmanager", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/secretmanager", - sum = "h1:xE6uXljAC1kCR8iadt9+/blg1fvSbmenlsDN4fT9gqw=", - version = "v1.9.0", - ) - go_repository( - name = "com_google_cloud_go_security", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/security", - sum = "h1:KSKzzJMyUoMRQzcz7azIgqAUqxo7rmQ5rYvimMhikqg=", - version = "v1.10.0", - ) - go_repository( - name = "com_google_cloud_go_securitycenter", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/securitycenter", - sum = "h1:QTVtk/Reqnx2bVIZtJKm1+mpfmwRwymmNvlaFez7fQY=", - version = "v1.16.0", - ) - go_repository( - name = "com_google_cloud_go_servicecontrol", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/servicecontrol", - sum = "h1:ImIzbOu6y4jL6ob65I++QzvqgFaoAKgHOG+RU9/c4y8=", - version = "v1.5.0", - ) - go_repository( - name = "com_google_cloud_go_servicedirectory", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/servicedirectory", - sum = "h1:f7M8IMcVzO3T425AqlZbP3yLzeipsBHtRza8vVFYMhQ=", - version = "v1.7.0", - ) - go_repository( - name = "com_google_cloud_go_servicemanagement", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/servicemanagement", - sum = "h1:TpkCO5M7dhKSy1bKUD9o/sSEW/U1Gtx7opA1fsiMx0c=", - version = "v1.5.0", - ) - go_repository( - name = "com_google_cloud_go_serviceusage", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/serviceusage", - sum = "h1:b0EwJxPJLpavSljMQh0RcdHsUrr5DQ+Nelt/3BAs5ro=", - version = "v1.4.0", - ) - go_repository( - name = "com_google_cloud_go_shell", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/shell", - sum = "h1:b1LFhFBgKsG252inyhtmsUUZwchqSz3WTvAIf3JFo4g=", - version = "v1.4.0", - ) - go_repository( - name = "com_google_cloud_go_spanner", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/spanner", - sum = "h1:NvdTpRwf7DTegbfFdPjAWyD7bOVu0VeMqcvR9aCQCAc=", - version = "v1.41.0", - ) - go_repository( - name = "com_google_cloud_go_speech", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/speech", - sum = "h1:yK0ocnFH4Wsf0cMdUyndJQ/hPv02oTJOxzi6AgpBy4s=", - version = "v1.9.0", - ) - go_repository( - name = "com_google_cloud_go_storage", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/storage", - sum = "h1:DLrIZ6xkeZX6K70fU/boWx5INJumt6f+nwwWSHXzzGY=", - version = "v1.28.0", - ) - go_repository( - name = "com_google_cloud_go_storagetransfer", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/storagetransfer", - sum = "h1:fUe3OydbbvHcAYp07xY+2UpH4AermGbmnm7qdEj3tGE=", - version = "v1.6.0", - ) - go_repository( - name = "com_google_cloud_go_talent", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/talent", - sum = "h1:MrekAGxLqAeAol4Sc0allOVqUGO8j+Iim8NMvpiD7tM=", - version = "v1.4.0", - ) - go_repository( - name = "com_google_cloud_go_texttospeech", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/texttospeech", - sum = "h1:ccPiHgTewxgyAeCWgQWvZvrLmbfQSFABTMAfrSPLPyY=", - version = "v1.5.0", - ) - go_repository( - name = "com_google_cloud_go_tpu", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/tpu", - sum = "h1:ztIdKoma1Xob2qm6QwNh4Xi9/e7N3IfvtwG5AcNsj1g=", - version = "v1.4.0", - ) - go_repository( - name = "com_google_cloud_go_trace", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/trace", - sum = "h1:qO9eLn2esajC9sxpqp1YKX37nXC3L4BfGnPS0Cx9dYo=", - version = "v1.4.0", - ) - go_repository( - name = "com_google_cloud_go_translate", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/translate", - sum = "h1:AOYOH3MspzJ/bH1YXzB+xTE8fMpn3mwhLjugwGXvMPI=", - version = "v1.4.0", - ) - go_repository( - name = "com_google_cloud_go_video", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/video", - sum = "h1:ttlvO4J5c1VGq6FkHqWPD/aH6PfdxujHt+muTJlW1Zk=", - version = "v1.9.0", - ) - go_repository( - name = "com_google_cloud_go_videointelligence", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/videointelligence", - sum = "h1:RPFgVVXbI2b5vnrciZjtsUgpNKVtHO/WIyXUhEfuMhA=", - version = "v1.9.0", - ) - go_repository( - name = "com_google_cloud_go_vision_v2", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/vision/v2", - sum = "h1:TQHxRqvLMi19azwm3qYuDbEzZWmiKJNTpGbkNsfRCik=", - version = "v2.5.0", - ) - go_repository( - name = "com_google_cloud_go_vmmigration", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/vmmigration", - sum = "h1:A2Tl2ZmwMRpvEmhV2ibISY85fmQR+Y5w9a0PlRz5P3s=", - version = "v1.3.0", - ) - go_repository( - name = "com_google_cloud_go_vmwareengine", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/vmwareengine", - sum = "h1:JMPZaOT/gIUxVlTqSl/QQ32Y2k+r0stNeM1NSqhVP9o=", - version = "v0.1.0", - ) - go_repository( - name = "com_google_cloud_go_vpcaccess", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/vpcaccess", - sum = "h1:woHXXtnW8b9gLFdWO9HLPalAddBQ9V4LT+1vjKwR3W8=", - version = "v1.5.0", - ) - go_repository( - name = "com_google_cloud_go_webrisk", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/webrisk", - sum = "h1:ypSnpGlJnZSXbN9a13PDmAYvVekBLnGKxQ3Q9SMwnYY=", - version = "v1.7.0", - ) - go_repository( - name = "com_google_cloud_go_websecurityscanner", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/websecurityscanner", - sum = "h1:y7yIFg/h/mO+5Y5aCOtVAnpGUOgqCH5rXQ2Oc8Oq2+g=", - version = "v1.4.0", - ) - go_repository( - name = "com_google_cloud_go_workflows", - build_file_proto_mode = "disable_global", - importpath = "cloud.google.com/go/workflows", - sum = "h1:7Chpin9p50NTU8Tb7qk+I11U/IwVXmDhEoSsdccvInE=", - version = "v1.9.0", - ) - go_repository( - name = "com_jaytaylor_html2text", - build_file_proto_mode = "disable_global", - importpath = "jaytaylor.com/html2text", - sum = "h1:mub0MmFLOn8XLikZOAhgLD1kXJq8jgftSrrv7m00xFo=", - version = "v0.0.0-20200412013138-3577fbdbcff7", - ) - go_repository( - name = "in_gopkg_check_v1", - build_file_proto_mode = "disable_global", - importpath = "gopkg.in/check.v1", - sum = "h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=", - version = "v1.0.0-20201130134442-10cb98267c6c", - ) - go_repository( - name = "in_gopkg_errgo_v2", - build_file_proto_mode = "disable_global", - importpath = "gopkg.in/errgo.v2", - sum = "h1:0vLT13EuvQ0hNvakwLuFZ/jYrLp5F3kcWHXdRggjCE8=", - version = "v2.1.0", - ) - go_repository( - name = "in_gopkg_fsnotify_v1", - build_file_proto_mode = "disable_global", - importpath = "gopkg.in/fsnotify.v1", - sum = "h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4=", - version = "v1.4.7", - ) - go_repository( - name = "in_gopkg_go_playground_assert_v1", - build_file_proto_mode = "disable_global", - importpath = "gopkg.in/go-playground/assert.v1", - sum = "h1:xoYuJVE7KT85PYWrN730RguIQO0ePzVRfFMXadIrXTM=", - version = "v1.2.1", - ) - go_repository( - name = "in_gopkg_go_playground_validator_v8", - build_file_proto_mode = "disable_global", - importpath = "gopkg.in/go-playground/validator.v8", - sum = "h1:lFB4DoMU6B626w8ny76MV7VX6W2VHct2GVOI3xgiMrQ=", - version = "v8.18.2", - ) - go_repository( - name = "in_gopkg_inf_v0", - build_file_proto_mode = "disable_global", - importpath = "gopkg.in/inf.v0", - sum = "h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc=", - version = "v0.9.1", - ) - go_repository( - name = "in_gopkg_ini_v1", - build_file_proto_mode = "disable_global", - importpath = "gopkg.in/ini.v1", - sum = "h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA=", - version = "v1.67.0", - ) - go_repository( - name = "in_gopkg_mgo_v2", - build_file_proto_mode = "disable_global", - importpath = "gopkg.in/mgo.v2", - sum = "h1:xcEWjVhvbDy+nHP67nPDDpbYrY+ILlfndk4bRioVHaU=", - version = "v2.0.0-20180705113604-9856a29383ce", - ) - go_repository( - name = "in_gopkg_tomb_v1", - build_file_proto_mode = "disable_global", - importpath = "gopkg.in/tomb.v1", - sum = "h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=", - version = "v1.0.0-20141024135613-dd632973f1e7", - ) - go_repository( - name = "in_gopkg_yaml_v2", - build_file_proto_mode = "disable_global", - importpath = "gopkg.in/yaml.v2", - sum = "h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=", - version = "v2.4.0", - ) - go_repository( - name = "in_gopkg_yaml_v3", - build_file_proto_mode = "disable_global", - importpath = "gopkg.in/yaml.v3", - sum = "h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=", - version = "v3.0.1", - ) - go_repository( - name = "io_k8s_api", - build_file_proto_mode = "disable_global", - importpath = "k8s.io/api", - sum = "h1:f+SWYiPd/GsiWwVRz+NbFyCgvv75Pk9NK6dlkZgpCRQ=", - version = "v0.26.1", - ) - go_repository( - name = "io_k8s_apimachinery", - build_file_proto_mode = "disable_global", - importpath = "k8s.io/apimachinery", - sum = "h1:8EZ/eGJL+hY/MYCNwhmDzVqq2lPl3N3Bo8rvweJwXUQ=", - version = "v0.26.1", - ) - go_repository( - name = "io_k8s_client_go", - build_file_proto_mode = "disable_global", - importpath = "k8s.io/client-go", - sum = "h1:87CXzYJnAMGaa/IDDfRdhTzxk/wzGZ+/HUQpqgVSZXU=", - version = "v0.26.1", - ) - go_repository( - name = "io_k8s_gengo", - build_file_proto_mode = "disable_global", - importpath = "k8s.io/gengo", - sum = "h1:GohjlNKauSai7gN4wsJkeZ3WAJx4Sh+oT/b5IYn5suA=", - version = "v0.0.0-20210813121822-485abfe95c7c", - ) - go_repository( - name = "io_k8s_klog_v2", - build_file_proto_mode = "disable_global", - importpath = "k8s.io/klog/v2", - sum = "h1:atnLQ121W371wYYFawwYx1aEY2eUfs4l3J72wtgAwV4=", - version = "v2.80.1", - ) - go_repository( - name = "io_k8s_kube_openapi", - build_file_proto_mode = "disable_global", - importpath = "k8s.io/kube-openapi", - sum = "h1:+70TFaan3hfJzs+7VK2o+OGxg8HsuBr/5f6tVAjDu6E=", - version = "v0.0.0-20221012153701-172d655c2280", - ) - go_repository( - name = "io_k8s_sigs_json", - build_file_proto_mode = "disable_global", - importpath = "sigs.k8s.io/json", - sum = "h1:iXTIw73aPyC+oRdyqqvVJuloN1p0AC/kzH07hu3NE+k=", - version = "v0.0.0-20220713155537-f223a00ba0e2", - ) - go_repository( - name = "io_k8s_sigs_structured_merge_diff_v4", - build_file_proto_mode = "disable_global", - importpath = "sigs.k8s.io/structured-merge-diff/v4", - sum = "h1:PRbqxJClWWYMNV1dhaG4NsibJbArud9kFxnAMREiWFE=", - version = "v4.2.3", - ) - go_repository( - name = "io_k8s_sigs_yaml", - build_file_proto_mode = "disable_global", - importpath = "sigs.k8s.io/yaml", - sum = "h1:a2VclLzOGrwOHDiV8EfBGhvjHvP46CtW5j6POvhYGGo=", - version = "v1.3.0", - ) - go_repository( - name = "io_k8s_utils", - build_file_proto_mode = "disable_global", - importpath = "k8s.io/utils", - sum = "h1:0Smp/HP1OH4Rvhe+4B8nWGERtlqAGSftbSbbmm45oFs=", - version = "v0.0.0-20221107191617-1a15be271d1d", - ) - go_repository( - name = "io_opencensus_go", - build_file_proto_mode = "disable_global", - importpath = "go.opencensus.io", - sum = "h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0=", - version = "v0.24.0", - ) - go_repository( - name = "org_golang_google_api", - build_file_proto_mode = "disable_global", - importpath = "google.golang.org/api", - sum = "h1:l+rh0KYUooe9JGbGVx71tbFo4SMbMTXK3I3ia2QSEeU=", - version = "v0.110.0", - ) - go_repository( - name = "org_golang_google_appengine", - build_file_proto_mode = "disable_global", - importpath = "google.golang.org/appengine", - sum = "h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c=", - version = "v1.6.7", - ) - go_repository( - name = "org_golang_google_genproto", - build_file_proto_mode = "disable_global", - importpath = "google.golang.org/genproto", - sum = "h1:EfLuoKW5WfkgVdDy7dTK8qSbH37AX5mj/MFh+bGPz14=", - version = "v0.0.0-20230216225411-c8e22ba71e44", - ) - go_repository( - name = "org_golang_google_grpc", - build_file_proto_mode = "disable_global", - importpath = "google.golang.org/grpc", - sum = "h1:LAv2ds7cmFV/XTS3XG1NneeENYrXGmorPxsBbptIjNc=", - version = "v1.53.0", - ) - go_repository( - name = "org_golang_google_protobuf", - build_file_proto_mode = "disable_global", - importpath = "google.golang.org/protobuf", - sum = "h1:d0NfwRgPtno5B1Wa6L2DAG+KivqkdutMf1UhdNx175w=", - version = "v1.28.1", - ) - go_repository( - name = "org_golang_x_crypto", - build_file_proto_mode = "disable_global", - importpath = "golang.org/x/crypto", - sum = "h1:a06MkbcxBrEFc0w0QIZWXrH/9cCX6KJyWbBOIwAn+7A=", - version = "v0.3.0", - ) - go_repository( - name = "org_golang_x_exp", - build_file_proto_mode = "disable_global", - importpath = "golang.org/x/exp", - sum = "h1:c2HOrn5iMezYjSlGPncknSEr/8x5LELb/ilJbXi9DEA=", - version = "v0.0.0-20190121172915-509febef88a4", - ) - go_repository( - name = "org_golang_x_lint", - build_file_proto_mode = "disable_global", - importpath = "golang.org/x/lint", - sum = "h1:VLliZ0d+/avPrXXH+OakdXhpJuEoBZuwh1m2j7U6Iug=", - version = "v0.0.0-20210508222113-6edffad5e616", - ) - go_repository( - name = "org_golang_x_mod", - build_file_proto_mode = "disable_global", - importpath = "golang.org/x/mod", - sum = "h1:KENHtAZL2y3NLMYZeHY9DW8HW8V+kQyJsY/V9JlKvCs=", - version = "v0.9.0", - ) - go_repository( - name = "org_golang_x_net", - build_file_proto_mode = "disable_global", - importpath = "golang.org/x/net", - sum = "h1:Zrh2ngAOFYneWTAIAPethzeaQLuHwhuBkuV6ZiRnUaQ=", - version = "v0.8.0", - ) - go_repository( - name = "org_golang_x_oauth2", - build_file_proto_mode = "disable_global", - importpath = "golang.org/x/oauth2", - sum = "h1:HuArIo48skDwlrvM3sEdHXElYslAMsf3KwRkkW4MC4s=", - version = "v0.5.0", - ) - go_repository( - name = "org_golang_x_sync", - build_file_proto_mode = "disable_global", - importpath = "golang.org/x/sync", - sum = "h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=", - version = "v0.1.0", - ) - go_repository( - name = "org_golang_x_sys", - build_file_proto_mode = "disable_global", - importpath = "golang.org/x/sys", - sum = "h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ=", - version = "v0.6.0", - ) - go_repository( - name = "org_golang_x_term", - build_file_proto_mode = "disable_global", - importpath = "golang.org/x/term", - sum = "h1:clScbb1cHjoCkyRbWwBEUZ5H/tIFu5TAXIqaZD0Gcjw=", - version = "v0.6.0", - ) - go_repository( - name = "org_golang_x_text", - build_file_proto_mode = "disable_global", - importpath = "golang.org/x/text", - sum = "h1:57P1ETyNKtuIjB4SRd15iJxuhj8Gc416Y78H3qgMh68=", - version = "v0.8.0", - ) - go_repository( - name = "org_golang_x_time", - build_file_proto_mode = "disable_global", - importpath = "golang.org/x/time", - sum = "h1:Yx9k8YCG3dvF87UAn2tu2HQLf2dt/eR1bXxpLMWeH+Y=", - version = "v0.0.0-20220922220347-f3bd1da661af", - ) - go_repository( - name = "org_golang_x_tools", - build_file_proto_mode = "disable_global", - importpath = "golang.org/x/tools", - sum = "h1:W4OVu8VVOaIO0yzWMNdepAulS7YfoS3Zabrm8DOXXU4=", - version = "v0.7.0", - ) - go_repository( - name = "org_golang_x_xerrors", - build_file_proto_mode = "disable_global", - importpath = "golang.org/x/xerrors", - sum = "h1:H2TDz8ibqkAF6YGhCdN3jS9O0/s90v0rJh3X/OLHEUk=", - version = "v0.0.0-20220907171357-04be3eba64a2", - ) - go_repository( - name = "org_uber_go_atomic", - build_file_proto_mode = "disable_global", - importpath = "go.uber.org/atomic", - sum = "h1:9qC72Qh0+3MqyJbAn8YU5xVq1frD8bn3JtD2oXtafVQ=", - version = "v1.10.0", - ) - go_repository( - name = "org_uber_go_goleak", - build_file_proto_mode = "disable_global", - importpath = "go.uber.org/goleak", - sum = "h1:xqgm/S+aQvhWFTtR0XK3Jvg7z8kGV8P4X14IzwN3Eqk=", - version = "v1.2.0", - ) - go_repository( - name = "org_uber_go_multierr", - build_file_proto_mode = "disable_global", - importpath = "go.uber.org/multierr", - sum = "h1:7fIwc/ZtS0q++VgcfqFDxSBZVv/Xo49/SYnDFupUwlI=", - version = "v1.9.0", - ) - go_repository( - name = "org_uber_go_zap", - build_file_proto_mode = "disable_global", - importpath = "go.uber.org/zap", - sum = "h1:FiJd5l1UOLj0wCgbSE0rwwXHzEdAZS6hiiSnxJN/D60=", - version = "v1.24.0", - ) - go_repository( - name = "tools_gotest_v3", - build_file_proto_mode = "disable_global", - importpath = "gotest.tools/v3", - sum = "h1:4AuOwCGf4lLR9u3YOe2awrHygurzhO/HeQ6laiA6Sx0=", - version = "v3.0.3", - ) diff --git a/internal/api/BUILD.bazel b/internal/api/BUILD.bazel deleted file mode 100644 index 4441a7b3ba..0000000000 --- a/internal/api/BUILD.bazel +++ /dev/null @@ -1,34 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") - -go_library( - name = "api", - srcs = [ - "api.go", - "errors.go", - "flags.go", - "gzip.go", - "nullable.go", - "proxy.go", - "test_unix_socket_server.go", - ], - importpath = "github.com/sourcegraph/src-cli/internal/api", - visibility = ["//:__subpackages__"], - deps = [ - "//internal/version", - "@com_github_jig_teereadcloser//:teereadcloser", - "@com_github_kballard_go_shellquote//:go-shellquote", - "@com_github_mattn_go_isatty//:go-isatty", - "@com_github_sourcegraph_sourcegraph_lib//errors", - ], -) - -go_test( - name = "api_test", - srcs = [ - "api_test.go", - "errors_test.go", - "gzip_test.go", - ], - embed = [":api"], - deps = ["@com_github_google_go_cmp//cmp"], -) diff --git a/internal/api/mock/BUILD.bazel b/internal/api/mock/BUILD.bazel deleted file mode 100644 index 01c5399f8d..0000000000 --- a/internal/api/mock/BUILD.bazel +++ /dev/null @@ -1,12 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library") - -go_library( - name = "mock", - srcs = ["api.go"], - importpath = "github.com/sourcegraph/src-cli/internal/api/mock", - visibility = ["//:__subpackages__"], - deps = [ - "//internal/api", - "@com_github_stretchr_testify//mock", - ], -) diff --git a/internal/batches/BUILD.bazel b/internal/batches/BUILD.bazel deleted file mode 100644 index 96699bf327..0000000000 --- a/internal/batches/BUILD.bazel +++ /dev/null @@ -1,17 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library") - -go_library( - name = "batches", - srcs = [ - "errors.go", - "features.go", - "license.go", - ], - importpath = "github.com/sourcegraph/src-cli/internal/batches", - visibility = ["//:__subpackages__"], - deps = [ - "//internal/batches/graphql", - "@com_github_sourcegraph_sourcegraph_lib//api", - "@com_github_sourcegraph_sourcegraph_lib//errors", - ], -) diff --git a/internal/batches/docker/BUILD.bazel b/internal/batches/docker/BUILD.bazel deleted file mode 100644 index 21a8ee5c92..0000000000 --- a/internal/batches/docker/BUILD.bazel +++ /dev/null @@ -1,35 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") - -go_library( - name = "docker", - srcs = [ - "cache.go", - "context.go", - "image.go", - "info.go", - "version.go", - ], - importpath = "github.com/sourcegraph/src-cli/internal/batches/docker", - visibility = ["//:__subpackages__"], - deps = [ - "//internal/exec", - "@com_github_kballard_go_shellquote//:go-shellquote", - "@com_github_sourcegraph_sourcegraph_lib//errors", - ], -) - -go_test( - name = "docker_test", - srcs = [ - "cache_test.go", - "image_test.go", - "info_test.go", - "main_test.go", - ], - embed = [":docker"], - deps = [ - "//internal/exec/expect", - "@com_github_google_go_cmp//cmp", - "@com_github_stretchr_testify//assert", - ], -) diff --git a/internal/batches/executor/BUILD.bazel b/internal/batches/executor/BUILD.bazel deleted file mode 100644 index 5ffd119911..0000000000 --- a/internal/batches/executor/BUILD.bazel +++ /dev/null @@ -1,66 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") - -go_library( - name = "executor", - srcs = [ - "coordinator.go", - "execution_cache.go", - "executor.go", - "run_steps.go", - "task.go", - "ui.go", - ], - importpath = "github.com/sourcegraph/src-cli/internal/batches/executor", - visibility = ["//:__subpackages__"], - deps = [ - "//internal/batches/docker", - "//internal/batches/graphql", - "//internal/batches/log", - "//internal/batches/repozip", - "//internal/batches/util", - "//internal/batches/workspace", - "@com_github_neelance_parallel//:parallel", - "@com_github_sourcegraph_sourcegraph_lib//batches", - "@com_github_sourcegraph_sourcegraph_lib//batches/execution", - "@com_github_sourcegraph_sourcegraph_lib//batches/execution/cache", - "@com_github_sourcegraph_sourcegraph_lib//batches/git", - "@com_github_sourcegraph_sourcegraph_lib//batches/template", - "@com_github_sourcegraph_sourcegraph_lib//errors", - "@com_github_sourcegraph_sourcegraph_lib//process", - "@in_gopkg_yaml_v3//:yaml_v3", - ], -) - -go_test( - name = "executor_test", - srcs = [ - "coordinator_test.go", - "execution_cache_test.go", - "executor_test.go", - "main_test.go", - "task_test.go", - ], - data = glob(["testdata/**"]), - embed = [":executor"], - deps = [ - "//internal/api", - "//internal/batches/docker", - "//internal/batches/graphql", - "//internal/batches/mock", - "//internal/batches/repozip", - "//internal/batches/util", - "//internal/batches/workspace", - "@com_github_google_go_cmp//cmp", - "@com_github_google_go_cmp//cmp/cmpopts", - "@com_github_sourcegraph_go_diff//diff", - "@com_github_sourcegraph_sourcegraph_lib//batches", - "@com_github_sourcegraph_sourcegraph_lib//batches/execution", - "@com_github_sourcegraph_sourcegraph_lib//batches/execution/cache", - "@com_github_sourcegraph_sourcegraph_lib//batches/git", - "@com_github_sourcegraph_sourcegraph_lib//batches/overridable", - "@com_github_sourcegraph_sourcegraph_lib//batches/template", - "@com_github_sourcegraph_sourcegraph_lib//errors", - "@com_github_stretchr_testify//assert", - "@com_github_stretchr_testify//require", - ], -) diff --git a/internal/batches/graphql/BUILD.bazel b/internal/batches/graphql/BUILD.bazel deleted file mode 100644 index 0c61ae53d1..0000000000 --- a/internal/batches/graphql/BUILD.bazel +++ /dev/null @@ -1,12 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library") - -go_library( - name = "graphql", - srcs = [ - "batches.go", - "repository.go", - ], - importpath = "github.com/sourcegraph/src-cli/internal/batches/graphql", - visibility = ["//:__subpackages__"], - deps = ["//internal/batches/util"], -) diff --git a/internal/batches/log/BUILD.bazel b/internal/batches/log/BUILD.bazel deleted file mode 100644 index b287a96e24..0000000000 --- a/internal/batches/log/BUILD.bazel +++ /dev/null @@ -1,14 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library") - -go_library( - name = "log", - srcs = [ - "disk_manager.go", - "disk_task_logger.go", - "logger.go", - "noop_task_logger.go", - ], - importpath = "github.com/sourcegraph/src-cli/internal/batches/log", - visibility = ["//:__subpackages__"], - deps = ["@com_github_sourcegraph_sourcegraph_lib//errors"], -) diff --git a/internal/batches/mock/BUILD.bazel b/internal/batches/mock/BUILD.bazel deleted file mode 100644 index f45dc39723..0000000000 --- a/internal/batches/mock/BUILD.bazel +++ /dev/null @@ -1,18 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library") - -go_library( - name = "mock", - srcs = [ - "cache.go", - "docker_image_progress.go", - "image.go", - "logger.go", - "repo_archive.go", - ], - importpath = "github.com/sourcegraph/src-cli/internal/batches/mock", - visibility = ["//:__subpackages__"], - deps = [ - "//internal/batches/docker", - "//internal/batches/log", - ], -) diff --git a/internal/batches/repozip/BUILD.bazel b/internal/batches/repozip/BUILD.bazel deleted file mode 100644 index 1d03d70fbb..0000000000 --- a/internal/batches/repozip/BUILD.bazel +++ /dev/null @@ -1,28 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") - -go_library( - name = "repozip", - srcs = [ - "fetcher.go", - "noop.go", - ], - importpath = "github.com/sourcegraph/src-cli/internal/batches/repozip", - visibility = ["//:__subpackages__"], - deps = [ - "//internal/batches/util", - "@com_github_sourcegraph_sourcegraph_lib//errors", - ], -) - -go_test( - name = "repozip_test", - srcs = ["fetcher_test.go"], - embed = [":repozip"], - deps = [ - "//internal/api", - "//internal/batches/mock", - "//internal/batches/util", - "@com_github_google_go_cmp//cmp", - "@com_github_google_go_cmp//cmp/cmpopts", - ], -) diff --git a/internal/batches/service/BUILD.bazel b/internal/batches/service/BUILD.bazel deleted file mode 100644 index 8b20ccb96a..0000000000 --- a/internal/batches/service/BUILD.bazel +++ /dev/null @@ -1,43 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") - -go_library( - name = "service", - srcs = [ - "build_tasks.go", - "remote.go", - "service.go", - ], - importpath = "github.com/sourcegraph/src-cli/internal/batches/service", - visibility = ["//:__subpackages__"], - deps = [ - "//internal/api", - "//internal/batches", - "//internal/batches/docker", - "//internal/batches/executor", - "//internal/batches/graphql", - "@com_github_sourcegraph_sourcegraph_lib//batches", - "@com_github_sourcegraph_sourcegraph_lib//batches/template", - "@com_github_sourcegraph_sourcegraph_lib//errors", - ], -) - -go_test( - name = "service_test", - srcs = [ - "remote_test.go", - "remote_windows_test.go", - "service_test.go", - ], - embed = [":service"], - deps = [ - "//internal/api/mock", - "//internal/batches/docker", - "//internal/batches/graphql", - "//internal/batches/mock", - "@com_github_sourcegraph_sourcegraph_lib//batches", - "@com_github_sourcegraph_sourcegraph_lib//errors", - "@com_github_stretchr_testify//assert", - "@com_github_stretchr_testify//mock", - "@com_github_stretchr_testify//require", - ], -) diff --git a/internal/batches/ui/BUILD.bazel b/internal/batches/ui/BUILD.bazel deleted file mode 100644 index c267ca1777..0000000000 --- a/internal/batches/ui/BUILD.bazel +++ /dev/null @@ -1,50 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") - -go_library( - name = "ui", - srcs = [ - "exec_ui.go", - "interval_writer.go", - "json_lines.go", - "task_exec_tui.go", - "tty.go", - "tui.go", - ], - importpath = "github.com/sourcegraph/src-cli/internal/batches/ui", - visibility = ["//:__subpackages__"], - deps = [ - "//internal/api", - "//internal/batches", - "//internal/batches/executor", - "//internal/batches/graphql", - "//internal/batches/workspace", - "//internal/cmderrors", - "@com_github_creack_goselect//:goselect", - "@com_github_derision_test_glock//:glock", - "@com_github_dineshappavoo_basex//:basex", - "@com_github_neelance_parallel//:parallel", - "@com_github_sourcegraph_go_diff//diff", - "@com_github_sourcegraph_sourcegraph_lib//batches", - "@com_github_sourcegraph_sourcegraph_lib//batches/execution", - "@com_github_sourcegraph_sourcegraph_lib//batches/git", - "@com_github_sourcegraph_sourcegraph_lib//errors", - "@com_github_sourcegraph_sourcegraph_lib//output", - ], -) - -go_test( - name = "ui_test", - srcs = [ - "interval_writer_test.go", - "task_exec_tui_test.go", - ], - embed = [":ui"], - deps = [ - "//internal/batches/executor", - "//internal/batches/graphql", - "@com_github_derision_test_glock//:glock", - "@com_github_google_go_cmp//cmp", - "@com_github_sourcegraph_sourcegraph_lib//batches", - "@com_github_sourcegraph_sourcegraph_lib//output", - ], -) diff --git a/internal/batches/util/BUILD.bazel b/internal/batches/util/BUILD.bazel deleted file mode 100644 index c59ade842e..0000000000 --- a/internal/batches/util/BUILD.bazel +++ /dev/null @@ -1,9 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library") - -go_library( - name = "util", - srcs = ["repo.go"], - importpath = "github.com/sourcegraph/src-cli/internal/batches/util", - visibility = ["//:__subpackages__"], - deps = ["@com_github_sourcegraph_sourcegraph_lib//batches/template"], -) diff --git a/internal/batches/watchdog/BUILD.bazel b/internal/batches/watchdog/BUILD.bazel deleted file mode 100644 index 5ac56539aa..0000000000 --- a/internal/batches/watchdog/BUILD.bazel +++ /dev/null @@ -1,16 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") - -go_library( - name = "watchdog", - srcs = ["watchdog.go"], - importpath = "github.com/sourcegraph/src-cli/internal/batches/watchdog", - visibility = ["//:__subpackages__"], - deps = ["@com_github_derision_test_glock//:glock"], -) - -go_test( - name = "watchdog_test", - srcs = ["watchdog_test.go"], - embed = [":watchdog"], - deps = ["@com_github_derision_test_glock//:glock"], -) diff --git a/internal/batches/workspace/BUILD.bazel b/internal/batches/workspace/BUILD.bazel deleted file mode 100644 index dc56ef0575..0000000000 --- a/internal/batches/workspace/BUILD.bazel +++ /dev/null @@ -1,47 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") - -go_library( - name = "workspace", - srcs = [ - "bind_workspace.go", - "executor_workspace.go", - "git.go", - "volume_workspace.go", - "workspace.go", - ], - importpath = "github.com/sourcegraph/src-cli/internal/batches/workspace", - visibility = ["//:__subpackages__"], - deps = [ - "//internal/batches/docker", - "//internal/batches/graphql", - "//internal/batches/repozip", - "//internal/batches/util", - "//internal/exec", - "//internal/version", - "@com_github_sourcegraph_sourcegraph_lib//batches", - "@com_github_sourcegraph_sourcegraph_lib//errors", - ], -) - -go_test( - name = "workspace_test", - srcs = [ - "bind_workspace_nonwin_test.go", - "bind_workspace_test.go", - "bind_workspace_windows_test.go", - "main_test.go", - "volume_workspace_test.go", - "workspace_test.go", - ], - embed = [":workspace"], - deps = [ - "//internal/batches/docker", - "//internal/batches/graphql", - "//internal/batches/mock", - "//internal/batches/repozip", - "//internal/exec/expect", - "@com_github_google_go_cmp//cmp", - "@com_github_sourcegraph_sourcegraph_lib//batches", - "@com_github_sourcegraph_sourcegraph_lib//errors", - ], -) diff --git a/internal/cmderrors/BUILD.bazel b/internal/cmderrors/BUILD.bazel deleted file mode 100644 index 8cea3ca98a..0000000000 --- a/internal/cmderrors/BUILD.bazel +++ /dev/null @@ -1,9 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library") - -go_library( - name = "cmderrors", - srcs = ["errors.go"], - importpath = "github.com/sourcegraph/src-cli/internal/cmderrors", - visibility = ["//:__subpackages__"], - deps = ["@com_github_sourcegraph_sourcegraph_lib//errors"], -) diff --git a/internal/codeintel/BUILD.bazel b/internal/codeintel/BUILD.bazel deleted file mode 100644 index 981a0b59fa..0000000000 --- a/internal/codeintel/BUILD.bazel +++ /dev/null @@ -1,20 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") - -go_library( - name = "codeintel", - srcs = [ - "gitutil.go", - "sanitation.go", - ], - importpath = "github.com/sourcegraph/src-cli/internal/codeintel", - visibility = ["//:__subpackages__"], -) - -go_test( - name = "codeintel_test", - srcs = [ - "gitutil_test.go", - "sanitation_test.go", - ], - embed = [":codeintel"], -) diff --git a/internal/exec/BUILD.bazel b/internal/exec/BUILD.bazel deleted file mode 100644 index fa0ed3a7d7..0000000000 --- a/internal/exec/BUILD.bazel +++ /dev/null @@ -1,11 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library") - -go_library( - name = "exec", - srcs = [ - "exec.go", - "middleware.go", - ], - importpath = "github.com/sourcegraph/src-cli/internal/exec", - visibility = ["//:__subpackages__"], -) diff --git a/internal/exec/expect/BUILD.bazel b/internal/exec/expect/BUILD.bazel deleted file mode 100644 index bb299fe90d..0000000000 --- a/internal/exec/expect/BUILD.bazel +++ /dev/null @@ -1,14 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library") - -go_library( - name = "expect", - srcs = ["expect.go"], - importpath = "github.com/sourcegraph/src-cli/internal/exec/expect", - visibility = ["//:__subpackages__"], - deps = [ - "//internal/exec", - "@com_github_gobwas_glob//:glob", - "@com_github_google_go_cmp//cmp", - "@com_github_sourcegraph_sourcegraph_lib//errors", - ], -) diff --git a/internal/instancehealth/BUILD.bazel b/internal/instancehealth/BUILD.bazel deleted file mode 100644 index 146bb95192..0000000000 --- a/internal/instancehealth/BUILD.bazel +++ /dev/null @@ -1,27 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") - -go_library( - name = "instancehealth", - srcs = [ - "checks.go", - "summary.go", - ], - importpath = "github.com/sourcegraph/src-cli/internal/instancehealth", - visibility = ["//:__subpackages__"], - deps = [ - "//internal/api", - "@com_github_sourcegraph_sourcegraph_lib//errors", - "@com_github_sourcegraph_sourcegraph_lib//output", - ], -) - -go_test( - name = "instancehealth_test", - srcs = ["checks_test.go"], - embed = [":instancehealth"], - deps = [ - "@com_github_sourcegraph_sourcegraph_lib//output", - "@com_github_stretchr_testify//assert", - "@com_github_stretchr_testify//require", - ], -) diff --git a/internal/lazyregexp/BUILD.bazel b/internal/lazyregexp/BUILD.bazel deleted file mode 100644 index e0638b595f..0000000000 --- a/internal/lazyregexp/BUILD.bazel +++ /dev/null @@ -1,9 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library") - -go_library( - name = "lazyregexp", - srcs = ["lazyregexp.go"], - importpath = "github.com/sourcegraph/src-cli/internal/lazyregexp", - visibility = ["//:__subpackages__"], - deps = ["@com_github_grafana_regexp//:regexp"], -) diff --git a/internal/pgdump/BUILD.bazel b/internal/pgdump/BUILD.bazel deleted file mode 100644 index 3ae1599e86..0000000000 --- a/internal/pgdump/BUILD.bazel +++ /dev/null @@ -1,23 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") - -go_library( - name = "pgdump", - srcs = [ - "extensions.go", - "pgdump.go", - ], - importpath = "github.com/sourcegraph/src-cli/internal/pgdump", - visibility = ["//:__subpackages__"], - deps = ["@com_github_sourcegraph_sourcegraph_lib//errors"], -) - -go_test( - name = "pgdump_test", - srcs = ["extensions_test.go"], - embed = [":pgdump"], - deps = [ - "@com_github_hexops_autogold//:autogold", - "@com_github_stretchr_testify//assert", - "@com_github_stretchr_testify//require", - ], -) diff --git a/internal/servegit/BUILD.bazel b/internal/servegit/BUILD.bazel deleted file mode 100644 index f99e9a1bfc..0000000000 --- a/internal/servegit/BUILD.bazel +++ /dev/null @@ -1,22 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") - -go_library( - name = "servegit", - srcs = ["serve.go"], - importpath = "github.com/sourcegraph/src-cli/internal/servegit", - visibility = ["//:__subpackages__"], - deps = [ - "@com_github_sourcegraph_sourcegraph_lib//errors", - "@com_github_sourcegraph_sourcegraph_lib//gitservice", - ], -) - -go_test( - name = "servegit_test", - srcs = ["serve_test.go"], - embed = [":servegit"], - deps = [ - "@com_github_google_go_cmp//cmp", - "@com_github_google_go_cmp//cmp/cmpopts", - ], -) diff --git a/internal/streaming/BUILD.bazel b/internal/streaming/BUILD.bazel deleted file mode 100644 index 2963b75ad3..0000000000 --- a/internal/streaming/BUILD.bazel +++ /dev/null @@ -1,25 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") - -go_library( - name = "streaming", - srcs = [ - "api.go", - "client.go", - "events.go", - "search.go", - "writer.go", - ], - importpath = "github.com/sourcegraph/src-cli/internal/streaming", - visibility = ["//:__subpackages__"], - deps = [ - "//internal/api", - "@com_github_sourcegraph_sourcegraph_lib//errors", - ], -) - -go_test( - name = "streaming_test", - srcs = ["client_test.go"], - embed = [":streaming"], - deps = ["@com_github_google_go_cmp//cmp"], -) diff --git a/internal/users/BUILD.bazel b/internal/users/BUILD.bazel deleted file mode 100644 index 3897cade1f..0000000000 --- a/internal/users/BUILD.bazel +++ /dev/null @@ -1,13 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library") - -go_library( - name = "users", - srcs = ["admin.go"], - importpath = "github.com/sourcegraph/src-cli/internal/users", - visibility = ["//:__subpackages__"], - deps = [ - "//internal/lazyregexp", - "@com_github_json_iterator_go//:go", - "@com_github_sourcegraph_sourcegraph_lib//errors", - ], -) diff --git a/internal/validate/BUILD.bazel b/internal/validate/BUILD.bazel deleted file mode 100644 index 19190edb10..0000000000 --- a/internal/validate/BUILD.bazel +++ /dev/null @@ -1,8 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library") - -go_library( - name = "validate", - srcs = ["validate.go"], - importpath = "github.com/sourcegraph/src-cli/internal/validate", - visibility = ["//:__subpackages__"], -) diff --git a/internal/validate/install/BUILD.bazel b/internal/validate/install/BUILD.bazel deleted file mode 100644 index dc5ef4fb35..0000000000 --- a/internal/validate/install/BUILD.bazel +++ /dev/null @@ -1,19 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library") - -go_library( - name = "install", - srcs = [ - "config.go", - "github.go", - "insight.go", - "install.go", - ], - importpath = "github.com/sourcegraph/src-cli/internal/validate/install", - visibility = ["//:__subpackages__"], - deps = [ - "//internal/api", - "//internal/validate", - "@com_github_sourcegraph_sourcegraph_lib//errors", - "@in_gopkg_yaml_v3//:yaml_v3", - ], -) diff --git a/internal/validate/kube/BUILD.bazel b/internal/validate/kube/BUILD.bazel deleted file mode 100644 index 61325ae23f..0000000000 --- a/internal/validate/kube/BUILD.bazel +++ /dev/null @@ -1,48 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") - -go_library( - name = "kube", - srcs = [ - "aks.go", - "eks.go", - "gke.go", - "kube.go", - ], - importpath = "github.com/sourcegraph/src-cli/internal/validate/kube", - visibility = ["//:__subpackages__"], - deps = [ - "//internal/validate", - "@com_github_aws_aws_sdk_go_v2_config//:config", - "@com_github_aws_aws_sdk_go_v2_service_ec2//:ec2", - "@com_github_aws_aws_sdk_go_v2_service_ec2//types", - "@com_github_aws_aws_sdk_go_v2_service_eks//:eks", - "@com_github_aws_aws_sdk_go_v2_service_iam//:iam", - "@com_github_sourcegraph_sourcegraph_lib//errors", - "@io_k8s_api//core/v1:core", - "@io_k8s_apimachinery//pkg/apis/meta/v1:meta", - "@io_k8s_client_go//kubernetes", - "@io_k8s_client_go//kubernetes/scheme", - "@io_k8s_client_go//rest", - "@io_k8s_client_go//tools/clientcmd", - "@io_k8s_client_go//tools/remotecommand", - "@io_k8s_client_go//util/homedir", - ], -) - -go_test( - name = "kube_test", - srcs = [ - "eks_test.go", - "kube_test.go", - ], - embed = [":kube"], - deps = [ - "//internal/validate", - "@com_github_aws_aws_sdk_go_v2_service_ec2//types", - "@com_github_aws_aws_sdk_go_v2_service_eks//:eks", - "@com_github_aws_aws_sdk_go_v2_service_iam//:iam", - "@com_github_aws_aws_sdk_go_v2_service_iam//types", - "@io_k8s_api//core/v1:core", - "@io_k8s_apimachinery//pkg/apis/meta/v1:meta", - ], -) diff --git a/internal/version/BUILD.bazel b/internal/version/BUILD.bazel deleted file mode 100644 index df7ba5c8fc..0000000000 --- a/internal/version/BUILD.bazel +++ /dev/null @@ -1,8 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library") - -go_library( - name = "version", - srcs = ["version.go"], - importpath = "github.com/sourcegraph/src-cli/internal/version", - visibility = ["//:__subpackages__"], -) From 14811c7a4a41d4b9d078bffe432ea8cd271d8152 Mon Sep 17 00:00:00 2001 From: Marc <7050295+marcleblanc2@users.noreply.github.com> Date: Mon, 10 Nov 2025 16:21:02 -0700 Subject: [PATCH 490/647] Feature: Allow subsets of files in src snapshot upload (#1188) Customer admins can now use a `--file=` arg to the `src snapshot upload` command, to prevent unnecessary duplication of uploads in cases when a database file needs to be re-uploaded, but other large database files have already been uploaded. --- cmd/src/snapshot.go | 16 +- cmd/src/snapshot_upload.go | 418 +++++++++++++++++++++++--------- cmd/src/snapshot_upload_test.go | 286 ++++++++++++++++++++++ 3 files changed, 595 insertions(+), 125 deletions(-) create mode 100644 cmd/src/snapshot_upload_test.go diff --git a/cmd/src/snapshot.go b/cmd/src/snapshot.go index 0c604ca088..837ed3c21a 100644 --- a/cmd/src/snapshot.go +++ b/cmd/src/snapshot.go @@ -8,15 +8,23 @@ import ( var snapshotCommands commander func init() { - usage := `'src snapshot' manages snapshots of Sourcegraph instance data. All subcommands are currently EXPERIMENTAL. + usage := `'src snapshot' manages snapshots of Sourcegraph instance databases. All subcommands are currently EXPERIMENTAL. -USAGE - src [-v] snapshot +Usage: -COMMANDS + src snapshot + +The commands are: + + databases export databases from a Sourcegraph instance + restore restore databases from an export + upload upload exported databases and summary file when migrating to Sourcegraph Cloud summary export summary data about an instance for acceptance testing of a restored Sourcegraph instance test use exported summary data and instance health indicators to validate a restored and upgraded instance + +Use "src snapshot [command] -h" for more information about a command. + ` flagSet := flag.NewFlagSet("snapshot", flag.ExitOnError) diff --git a/cmd/src/snapshot_upload.go b/cmd/src/snapshot_upload.go index 85e938f6e8..86c141053b 100644 --- a/cmd/src/snapshot_upload.go +++ b/cmd/src/snapshot_upload.go @@ -5,9 +5,10 @@ import ( "flag" "fmt" "io" - "io/fs" "os" - "path" + "path/filepath" + "slices" + "strings" "cloud.google.com/go/storage" "github.com/sourcegraph/conc/pool" @@ -15,171 +16,346 @@ import ( "github.com/sourcegraph/sourcegraph/lib/output" "google.golang.org/api/option" + "github.com/sourcegraph/src-cli/internal/cmderrors" "github.com/sourcegraph/src-cli/internal/pgdump" ) +// Package-level variables const srcSnapshotDir = "./src-snapshot" -var srcSnapshotSummaryPath = path.Join(srcSnapshotDir, "summary.json") +// summaryFile on its own, as it gets handled a little differently +const summaryFile = "summary.json" -// https://pkg.go.dev/cloud.google.com/go/storage#section-readme +var srcSnapshotSummaryPath = filepath.Join(srcSnapshotDir, summaryFile) + +// listOfValidFiles defines the valid snapshot filenames (with extensions) that can be uploaded +var listOfValidFiles = []string{ + "codeinsights.sql", + "codeintel.sql", + "pgsql.sql", + summaryFile, +} + +// Define types +type uploadArgs struct { + bucketName string + credentialsPath string + filterSQL bool + filesToUpload []string +} + +// Google Cloud Storage upload client +type gcsClient struct { + ctx context.Context + out *output.Output + storageClient *storage.Client +} + +// uploadFile represents a file opened for upload +type uploadFile struct { + file *os.File + stat os.FileInfo + filterSQL bool // Whether to filter incompatible SQL statements during upload, true for database files, false for summary file +} func init() { - usage := `'src snapshot upload' uploads instance snapshot contents generated by 'src snapshot databases' and 'src snapshot summary' to the designated bucket. + usage := fmt.Sprintf(`'src snapshot upload' uploads the files generated by 'src snapshot databases' and 'src snapshot summary' to the specified GCS bucket, for self-hosted Sourcegraph customers migrating to Sourcegraph Cloud. + +Usage: + + src snapshot upload -bucket=$MIGRATION_BUCKET_NAME -credentials=$CREDENTIALS_FILE_PATH [-file] + +Examples: + + src snapshot upload -bucket=example-bucket-name -credentials=path/to/migration_private_key.json + + src snapshot upload -bucket=example-bucket-name -credentials=./migration_private_key.json -file=pgsql.sql -USAGE - src snapshot upload -bucket=$BUCKET -credentials=$CREDENTIALS_FILE + src snapshot upload -bucket=example-bucket-name -credentials=./migration_private_key.json -file="codeinsights.sql, codeintel.sql, pgsql.sql" + +Args: + + -bucket + Name of the Google Cloud Storage bucket provided by Sourcegraph + Required + Type: string + + -credentials + File path to the credentials file provided by Sourcegraph + Required + Type: file path, as string + + -file + Specify which files from the ./src-snapshot directory to upload + Optional + Type: comma-delimited list of file names, with file-type extensions, as a string + Valid values: %s + Default: All valid values + +`, strings.Join(listOfValidFiles, ", ")) -BUCKET - In general, a Google Cloud Storage bucket and relevant credentials will be provided by Sourcegraph when using this functionality to share a snapshot with Sourcegraph. -` flagSet := flag.NewFlagSet("upload", flag.ExitOnError) - bucketName := flagSet.String("bucket", "", "destination Cloud Storage bucket name") - credentialsPath := flagSet.String("credentials", "", "JSON credentials file for Google Cloud service account") - trimExtensions := flagSet.Bool("trim-extensions", true, "trim EXTENSION statements from database dumps for import to Google Cloud SQL") + bucketName := flagSet.String("bucket", "", "Name of the Google Cloud Storage bucket provided by Sourcegraph") + credentialsPath := flagSet.String("credentials", "", "File path to the credentials file provided by Sourcegraph") + fileArg := flagSet.String("file", strings.Join(listOfValidFiles, ","), "Specify which files from the ./src-snapshot directory to upload") + filterSQL := flagSet.Bool("filter-sql", true, "Filter incompatible SQL statements from database snapshots which break the import into Google Cloud SQL") + // Register this command with the parent 'src snapshot' command. + // The parent snapshot.go command runs all registered subcommands via snapshotCommands.run(). + // This self-registration pattern allows subcommands to automatically register themselves + // when their init() functions run, without requiring a central registry file. snapshotCommands = append(snapshotCommands, &command{ - flagSet: flagSet, - handler: func(args []string) error { - if err := flagSet.Parse(args); err != nil { - return err - } + flagSet: flagSet, + handler: snapshotUploadHandler(flagSet, bucketName, credentialsPath, filterSQL, fileArg), + usageFunc: func() { fmt.Fprint(flag.CommandLine.Output(), usage) }, + }) +} - if *bucketName == "" { - return errors.New("-bucket required") - } - if *credentialsPath == "" { - return errors.New("-credentials required") - } +// Handler function to keep init() succinct +func snapshotUploadHandler(flagSet *flag.FlagSet, bucketName, credentialsPath *string, filterSQL *bool, fileArg *string) func([]string) error { - out := output.NewOutput(flagSet.Output(), output.OutputOpts{Verbose: *verbose}) - ctx := context.Background() - c, err := storage.NewClient(ctx, option.WithCredentialsFile(*credentialsPath)) - if err != nil { - return errors.Wrap(err, "create Cloud Storage client") - } + return func(args []string) error { + if err := flagSet.Parse(args); err != nil { + return err + } - type upload struct { - file *os.File - stat os.FileInfo - trimExtensions bool - } - var ( - uploads []upload // index aligned with progressBars - progressBars []output.ProgressBar // index aligned with uploads - ) - - // Open snapshot summary - if f, err := os.Open(srcSnapshotSummaryPath); err != nil { - return errors.Wrap(err, "failed to open snapshot summary - generate one with 'src snapshot summary'") - } else { - stat, err := f.Stat() - if err != nil { - return errors.Wrap(err, "get file size") - } - uploads = append(uploads, upload{ - file: f, - stat: stat, - trimExtensions: false, // not a database dump - }) - progressBars = append(progressBars, output.ProgressBar{ - Label: stat.Name(), - Max: float64(stat.Size()), - }) - } + // Validate and parse inputs into an uploadArgs-type object + uploadArgs, err := validateUploadInputs(*bucketName, *credentialsPath, *fileArg, *filterSQL) + if err != nil { + return err + } - // Open database dumps - for _, o := range pgdump.Outputs(srcSnapshotDir, pgdump.Targets{}) { - if f, err := os.Open(o.Output); err != nil { - return errors.Wrap(err, "failed to database dump - generate one with 'src snapshot databases'") - } else { - stat, err := f.Stat() - if err != nil { - return errors.Wrap(err, "get file size") - } - uploads = append(uploads, upload{ - file: f, - stat: stat, - trimExtensions: *trimExtensions, - }) - progressBars = append(progressBars, output.ProgressBar{ - Label: stat.Name(), - Max: float64(stat.Size()), - }) - } - } + // Create client + client, err := createGcsClient(flagSet, uploadArgs.credentialsPath) + if err != nil { + return err + } + + // Open files and create progress bars + openedFiles, progressBars, err := openFilesAndCreateProgressBars(uploadArgs) + if err != nil { + return err + } + + // Upload files to bucket + return uploadFilesToBucket(client, uploadArgs, openedFiles, progressBars) + } +} + +// Validate user inputs, and convert them to an object of type uploadArgs +func validateUploadInputs(bucketName, credentialsPath, fileArg string, filterSQL bool) (*uploadArgs, error) { + + if bucketName == "" { + return nil, cmderrors.Usage("-bucket required") + } + + if credentialsPath == "" { + return nil, cmderrors.Usage("-credentials required") + } + + filesToUpload, err := parseFileArg(fileArg) + if err != nil { + return nil, err + } + + return &uploadArgs{ + bucketName: bucketName, + credentialsPath: credentialsPath, + filterSQL: filterSQL, + filesToUpload: filesToUpload, + }, nil +} + +// Parse the --file arg values, and return a list of strings of the files to upload +func parseFileArg(fileArg string) ([]string, error) { + + // Default: all files + if fileArg == "" { + return listOfValidFiles, nil + } - // Start uploads - progress := out.Progress(progressBars, nil) - progress.WriteLine(output.Emoji(output.EmojiHourglass, "Starting uploads...")) - bucket := c.Bucket(*bucketName) - g := pool.New().WithErrors().WithContext(ctx) - for i, u := range uploads { - i := i - u := u - g.Go(func(ctx context.Context) error { - progressFn := func(p int64) { progress.SetValue(i, float64(p)) } - - if err := copyDumpToBucket(ctx, u.file, u.stat, bucket, progressFn, u.trimExtensions); err != nil { - return errors.Wrap(err, u.stat.Name()) - } - - return nil - }) + var filesToUpload []string + + // Parse comma-delimited list + for _, part := range strings.Split(fileArg, ",") { + + // Trim whitespace + filename := strings.TrimSpace(part) + + // Validate against list of valid files + if !slices.Contains(listOfValidFiles, filename) { + return nil, cmderrors.Usagef("invalid -file value %q. Valid values: %s", part, strings.Join(listOfValidFiles, ", ")) + } + + filesToUpload = append(filesToUpload, filename) + } + + // Sort files alphabetically for consistent ordering + slices.Sort(filesToUpload) + + // Remove duplicates (works on sorted slices by removing adjacent duplicates) + filesToUpload = slices.Compact(filesToUpload) + + return filesToUpload, nil +} + +func createGcsClient(flagSet *flag.FlagSet, credentialsPath string) (*gcsClient, error) { + + ctx := context.Background() + out := output.NewOutput(flagSet.Output(), output.OutputOpts{Verbose: *verbose}) + + // https://pkg.go.dev/cloud.google.com/go/storage#section-readme + client, err := storage.NewClient(ctx, option.WithCredentialsFile(credentialsPath)) + + if err != nil { + return nil, errors.Wrap(err, "create Google Cloud Storage client") + } + + return &gcsClient{ + ctx: ctx, + out: out, + storageClient: client, + }, nil +} + +// openFilesAndCreateProgressBars opens selected snapshot files from disk and creates progress bars for UI display. +// Returns arrays of uploadFile and progress bars (aligned by index). +func openFilesAndCreateProgressBars(args *uploadArgs) ([]uploadFile, []output.ProgressBar, error) { + var ( + openedFiles []uploadFile // Files opened from disk, ready for upload (aligned with progressBars) + progressBars []output.ProgressBar // Progress bars for UI (aligned with openedFiles) + ) + + // addFile opens a file from disk and registers it for upload. + // It adds the file to the openedFiles array and creates a corresponding progress bar. + // For database dumps (!isSummary), SQL filtering is enabled based on args.filterSQL. + addFile := func(filePath string) error { + + isSummary := strings.HasSuffix(filePath, summaryFile) + + // Open the file + openFile, err := os.Open(filePath) + + if err != nil { + if isSummary { + return errors.Wrap(err, fmt.Sprintf("failed to open snapshot summary %s - Please generate it with 'src snapshot summary'", filePath)) } + return errors.Wrap(err, fmt.Sprintf("failed to open database dump %s - Please generate them with 'src snapshot databases'", filePath)) + } - // Finalize - errs := g.Wait() - progress.Complete() - if errs != nil { - out.WriteLine(output.Line(output.EmojiFailure, output.StyleFailure, "Some snapshot contents failed to upload.")) - return errs + // Get file metadata (name, size) + stat, err := openFile.Stat() + if err != nil { + return errors.Wrap(err, "get file size") + } + + // Register file for upload + openedFiles = append(openedFiles, uploadFile{ + file: openFile, + stat: stat, + filterSQL: !isSummary && args.filterSQL, // Only filter SQL for database dumps + }) + + // Create progress bar for this file + progressBars = append(progressBars, output.ProgressBar{ + Label: stat.Name(), + Max: float64(stat.Size()), + }) + return nil + } + + // Open files based on user's selection (via --file arg) + // Iterate through the user's selected files and open each one + for _, selectedFile := range args.filesToUpload { + + // Construct full file path + filePath := filepath.Join(srcSnapshotDir, selectedFile) + + if err := addFile(filePath); err != nil { + return nil, nil, err + } + } + + return openedFiles, progressBars, nil +} + +// uploadFilesToBucket uploads the prepared files to Google Cloud Storage bucket. +// Uploads are performed in parallel with progress tracking. +func uploadFilesToBucket(client *gcsClient, args *uploadArgs, openedFiles []uploadFile, progressBars []output.ProgressBar) error { + + // Start uploads with progress tracking + progress := client.out.Progress(progressBars, nil) + progress.WriteLine(output.Emoji(output.EmojiHourglass, "Starting uploads...")) + bucket := client.storageClient.Bucket(args.bucketName) + uploadPool := pool.New().WithErrors().WithContext(client.ctx) + + // Upload each file in parallel + for fileIndex, openedFile := range openedFiles { + + fileIndex := fileIndex + openedFile := openedFile + + uploadPool.Go(func(ctx context.Context) error { + progressFn := func(bytesWritten int64) { progress.SetValue(fileIndex, float64(bytesWritten)) } + + if err := streamFileToBucket(ctx, &openedFile, bucket, progressFn); err != nil { + return errors.Wrap(err, openedFile.stat.Name()) } - out.WriteLine(output.Emoji(output.EmojiSuccess, "Summary contents uploaded!")) return nil - }, - usageFunc: func() { fmt.Fprint(flag.CommandLine.Output(), usage) }, - }) + }) + } + + // Wait for all uploads to complete + errs := uploadPool.Wait() + progress.Complete() + if errs != nil { + client.out.WriteLine(output.Line(output.EmojiFailure, output.StyleFailure, "Some file(s) failed to upload.")) + return errs + } + + client.out.WriteLine(output.Emoji(output.EmojiSuccess, "File(s) uploaded successfully!")) + return nil } -func copyDumpToBucket(ctx context.Context, src io.ReadSeeker, stat fs.FileInfo, dst *storage.BucketHandle, progressFn func(int64), trimExtensions bool) error { - // Set up object to write to - object := dst.Object(stat.Name()).NewWriter(ctx) - object.ProgressFunc = progressFn - defer object.Close() +func streamFileToBucket(ctx context.Context, file *uploadFile, bucket *storage.BucketHandle, progressFn func(int64)) error { + + // Set up GCS writer for the destination file + writer := bucket.Object(file.stat.Name()).NewWriter(ctx) + writer.ProgressFunc = progressFn + defer writer.Close() // To assert against actual file size - var totalWritten int64 + var totalBytesWritten int64 - // Do a partial copy, that filters out incompatible statements - if trimExtensions { - written, err := pgdump.FilterInvalidLines(object, src, progressFn) + // Start a partial copy, that filters out incompatible statements + if file.filterSQL { + bytesWritten, err := pgdump.FilterInvalidLines(writer, file.file, progressFn) if err != nil { return errors.Wrap(err, "filter out incompatible statements and upload") } - totalWritten += written + totalBytesWritten += bytesWritten } // io.Copy is the best way to copy from a reader to writer in Go, // storage.Writer has its own chunking mechanisms internally. // io.Reader is stateful, so this copy will just continue from where FilterInvalidLines left off, if used - written, err := io.Copy(object, src) + bytesWritten, err := io.Copy(writer, file.file) if err != nil { return errors.Wrap(err, "upload") } - totalWritten += written + totalBytesWritten += bytesWritten // Progress is not called on completion of io.Copy, // so we call it manually after to update our pretty progress bars. - progressFn(written) + progressFn(bytesWritten) // Validate we have sent all data. // FilterInvalidLines may add some bytes, so the check is not a strict equality. - size := stat.Size() - if totalWritten < size { + fileSize := file.stat.Size() + if totalBytesWritten < fileSize { return errors.Newf("expected to write %d bytes, but actually wrote %d bytes (diff: %d bytes)", - size, totalWritten, totalWritten-size) + fileSize, totalBytesWritten, totalBytesWritten-fileSize) } return nil diff --git a/cmd/src/snapshot_upload_test.go b/cmd/src/snapshot_upload_test.go new file mode 100644 index 0000000000..568e582111 --- /dev/null +++ b/cmd/src/snapshot_upload_test.go @@ -0,0 +1,286 @@ +package main + +import ( + "os" + "path/filepath" + "slices" + "strings" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/sourcegraph/src-cli/internal/pgdump" +) + +func setupSnapshotFiles(t *testing.T) string { + t.Helper() + dir := t.TempDir() + + // Create the snapshot directory structure + snapshotDir := filepath.Join(dir, "src-snapshot") + err := os.Mkdir(snapshotDir, 0755) + require.NoError(t, err) + + // Create summary.json + summaryPath := filepath.Join(snapshotDir, "summary.json") + err = os.WriteFile(summaryPath, []byte(`{"version": "test"}`), 0644) + require.NoError(t, err) + + // Create database dump files + for _, output := range pgdump.Outputs(snapshotDir, pgdump.Targets{}) { + err = os.WriteFile(output.Output, []byte("-- test SQL dump"), 0644) + require.NoError(t, err) + } + + return snapshotDir +} + +func TestFileFilterValidation(t *testing.T) { + tests := []struct { + name string + fileFlag string + wantError bool + }{ + { + name: "valid: summary.json", + fileFlag: "summary.json", + wantError: false, + }, + { + name: "valid: pgsql.sql", + fileFlag: "pgsql.sql", + wantError: false, + }, + { + name: "valid: codeintel.sql", + fileFlag: "codeintel.sql", + wantError: false, + }, + { + name: "valid: codeinsights.sql", + fileFlag: "codeinsights.sql", + wantError: false, + }, + { + name: "valid: empty (all files)", + fileFlag: "", + wantError: false, + }, + { + name: "valid: comma-delimited", + fileFlag: "summary.json,pgsql.sql", + wantError: false, + }, + { + name: "valid: comma-delimited with spaces", + fileFlag: "summary.json, pgsql.sql, codeintel.sql", + wantError: false, + }, + { + name: "invalid: unknown file", + fileFlag: "unknown", + wantError: true, + }, + { + name: "invalid: typo", + fileFlag: "primry", + wantError: true, + }, + { + name: "invalid: one valid, one invalid", + fileFlag: "summary.json,invalid", + wantError: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Test the validation logic using the shared listOfValidFiles + var hasError bool + if tt.fileFlag == "" { + // Empty is valid (defaults to all files) + hasError = false + } else { + parts := strings.Split(tt.fileFlag, ",") + for _, part := range parts { + filename := strings.TrimSpace(part) + + if !slices.Contains(listOfValidFiles, filename) { + hasError = true + break + } + } + } + + if tt.wantError { + require.True(t, hasError, "expected invalid file flag to be rejected") + } else { + require.False(t, hasError, "expected valid file flag to be accepted") + } + }) + } +} + +func TestFileSelection(t *testing.T) { + snapshotDir := setupSnapshotFiles(t) + + tests := []struct { + name string + fileFilter string + expectedFiles []string + }{ + { + name: "no filter - all files", + fileFilter: "", + expectedFiles: []string{ + "codeinsights.sql", + "codeintel.sql", + "pgsql.sql", + "summary.json", + }, + }, + { + name: "summary only", + fileFilter: "summary.json", + expectedFiles: []string{ + "summary.json", + }, + }, + { + name: "pgsql only", + fileFilter: "pgsql.sql", + expectedFiles: []string{ + "pgsql.sql", + }, + }, + { + name: "codeintel only", + fileFilter: "codeintel.sql", + expectedFiles: []string{ + "codeintel.sql", + }, + }, + { + name: "codeinsights only", + fileFilter: "codeinsights.sql", + expectedFiles: []string{ + "codeinsights.sql", + }, + }, + { + name: "comma-delimited: summary and pgsql", + fileFilter: "summary.json,pgsql.sql", + expectedFiles: []string{ + "summary.json", + "pgsql.sql", + }, + }, + { + name: "comma-delimited: all database files", + fileFilter: "pgsql.sql,codeintel.sql,codeinsights.sql", + expectedFiles: []string{ + "pgsql.sql", + "codeintel.sql", + "codeinsights.sql", + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Parse file filter into list (mimicking parseFileFilter logic) + var filesToUpload []string + if tt.fileFilter == "" { + filesToUpload = listOfValidFiles + } else { + parts := strings.Split(tt.fileFilter, ",") + for _, part := range parts { + filename := strings.TrimSpace(part) + filesToUpload = append(filesToUpload, filename) + } + } + + // Simulate the file opening logic from openFilesAndCreateProgressBars + var selectedFiles []string + for _, selectedFile := range filesToUpload { + // Construct path and check if file matches + filePath := filepath.Join(snapshotDir, selectedFile) + if _, err := os.Stat(filePath); err == nil { + selectedFiles = append(selectedFiles, selectedFile) + } + } + + require.Equal(t, tt.expectedFiles, selectedFiles, "selected files should match expected") + }) + } +} + +func TestFilterSQLBehavior(t *testing.T) { + tests := []struct { + name string + isSummary bool + filterSQLFlag bool + expectedFilter bool + }{ + { + name: "summary file - filterSQL should be false", + isSummary: true, + filterSQLFlag: true, + expectedFilter: false, + }, + { + name: "database dump - filterSQL flag true", + isSummary: false, + filterSQLFlag: true, + expectedFilter: true, + }, + { + name: "database dump - filterSQL flag false", + isSummary: false, + filterSQLFlag: false, + expectedFilter: false, + }, + { + name: "summary file - filterSQL flag false (should still be false)", + isSummary: true, + filterSQLFlag: false, + expectedFilter: false, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Simulate the filterSQL logic from snapshot_upload.go + actualFilter := !tt.isSummary && tt.filterSQLFlag + + require.Equal(t, tt.expectedFilter, actualFilter, "filterSQL should be set correctly") + }) + } +} + +func TestDatabaseOutputs(t *testing.T) { + snapshotDir := setupSnapshotFiles(t) + + outputs := pgdump.Outputs(snapshotDir, pgdump.Targets{}) + + // Should have exactly 3 database files + require.Len(t, outputs, 3, "should have 3 database outputs") + + expectedFiles := map[string]bool{ + "pgsql.sql": false, + "codeintel.sql": false, + "codeinsights.sql": false, + } + + for _, output := range outputs { + fileName := filepath.Base(output.Output) + _, exists := expectedFiles[fileName] + require.True(t, exists, "unexpected file: %s", fileName) + expectedFiles[fileName] = true + } + + // Verify all expected files were found + for fileName, found := range expectedFiles { + require.True(t, found, "expected file not found: %s", fileName) + } +} From 68860d04529d7d0e83b516cff87c7fec8487553c Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Tue, 11 Nov 2025 10:19:49 +0200 Subject: [PATCH 491/647] go 1.25 + upgrade containers (#1192) * go 1.25 + upgrade containers * update workflows * use golangci-lint 2.6.1 * migrate golangci-lint to v2 * fix golang container tag * set minimum go version in go.mod --- .github/workflows/go-ci.yml | 2 +- .github/workflows/go-lint.yml | 2 +- .github/workflows/goreleaser-check.yml | 2 +- .github/workflows/goreleaser.yml | 2 +- .github/workflows/scip.yml | 2 +- .golangci.yml | 102 +++++++++++++------------ .tool-versions | 2 +- Dockerfile | 4 +- dev/golangci-lint.sh | 2 +- go.mod | 6 +- 10 files changed, 66 insertions(+), 60 deletions(-) diff --git a/.github/workflows/go-ci.yml b/.github/workflows/go-ci.yml index 33dce1f948..0d3acea806 100644 --- a/.github/workflows/go-ci.yml +++ b/.github/workflows/go-ci.yml @@ -11,7 +11,7 @@ jobs: go-test: strategy: matrix: - go-version: [1.24.1] + go-version: ['1.25'] os: [ubuntu-latest, macos-latest, windows-latest] runs-on: ${{ matrix.os }} steps: diff --git a/.github/workflows/go-lint.yml b/.github/workflows/go-lint.yml index 3343e9ae8c..7c99b5999f 100644 --- a/.github/workflows/go-lint.yml +++ b/.github/workflows/go-lint.yml @@ -16,7 +16,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v5 with: - go-version: 1.24.1 + go-version: '1.25' - name: Enable pulling Go modules from private sourcegraph/sourcegraph run: git config --global url."https://${PRIVATE_TOKEN}@github.com/sourcegraph/".insteadOf "https://github.com/sourcegraph/" - run: ./dev/go-lint.sh diff --git a/.github/workflows/goreleaser-check.yml b/.github/workflows/goreleaser-check.yml index 8ff2f3b5c9..45d5c46e47 100644 --- a/.github/workflows/goreleaser-check.yml +++ b/.github/workflows/goreleaser-check.yml @@ -19,7 +19,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v5 with: - go-version: 1.24.1 + go-version: '1.25' - name: Enable pulling Go modules from private sourcegraph/sourcegraph run: git config --global url."https://${PRIVATE_TOKEN}@github.com/sourcegraph/".insteadOf "https://github.com/sourcegraph/" - name: Check GoReleaser config diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index bb39f6a067..72a4a0f825 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -181,7 +181,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v5 with: - go-version: 1.24.1 + go-version: 1.25 - name: Enable pulling Go modules from private sourcegraph/sourcegraph run: git config --global url."https://${PRIVATE_TOKEN}@github.com/sourcegraph/".insteadOf "https://github.com/sourcegraph/" - run: go test ./... diff --git a/.github/workflows/scip.yml b/.github/workflows/scip.yml index 88e836e774..2df5a1e5c1 100644 --- a/.github/workflows/scip.yml +++ b/.github/workflows/scip.yml @@ -14,7 +14,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v5 with: - go-version: 1.24.1 + go-version: 1.25 - name: Set directory to safe for git run: git config --global --add safe.directory $GITHUB_WORKSPACE diff --git a/.golangci.yml b/.golangci.yml index 961158d5e1..39e52917b9 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,59 +1,67 @@ -# See explanation of linters at https://golangci-lint.run/usage/linters/ +version: "2" linters: - disable-all: true + default: none enable: - bodyclose - depguard - gocritic - - goimports - - gosimple - govet - ineffassign - nolintlint - staticcheck - - typecheck - unconvert - unused - -linters-settings: - depguard: + settings: + depguard: + rules: + main: + deny: + - pkg: errors + desc: Use github.com/sourcegraph/sourcegraph/lib/errors instead + - pkg: github.com/pkg/errors + desc: Use github.com/sourcegraph/sourcegraph/lib/errors instead + - pkg: github.com/cockroachdb/errors + desc: Use github.com/sourcegraph/sourcegraph/lib/errors instead + - pkg: github.com/hashicorp/go-multierror + desc: Use github.com/sourcegraph/sourcegraph/lib/errors instead + - pkg: io/ioutil + desc: The ioutil package has been deprecated + forbidigo: + forbid: + - pattern: fmt\.Errorf + gocritic: + disabled-checks: + - appendAssign + - assignOp + - commentFormatting + - deprecatedComment + - exitAfterDefer + - ifElseChain + - singleCaseSwitch + govet: + disable: + - composites + exclusions: + generated: lax + presets: + - comments + - common-false-positives + - legacy + - std-error-handling rules: - main: - deny: - - pkg: "errors" - desc: "Use github.com/sourcegraph/sourcegraph/lib/errors instead" - - pkg: "github.com/pkg/errors" - desc: "Use github.com/sourcegraph/sourcegraph/lib/errors instead" - - pkg: "github.com/cockroachdb/errors" - desc: "Use github.com/sourcegraph/sourcegraph/lib/errors instead" - - pkg: "github.com/hashicorp/go-multierror" - desc: "Use github.com/sourcegraph/sourcegraph/lib/errors instead" - - pkg: "io/ioutil" - desc: "The ioutil package has been deprecated" - gocritic: - disabled-checks: - - appendAssign # Too many false positives - - assignOp # Maybe worth adding, but likely not worth the noise - - commentFormatting # No strong benefit - - deprecatedComment # Unnecessary - - exitAfterDefer # Only occurs in auxiliary tools - - ifElseChain # Noisy for not much gain - - singleCaseSwitch # Noisy for not much gain - govet: - disable: - - composites - forbidigo: - forbid: - # Use errors.New instead - - 'fmt\.Errorf' - -issues: - exclude-rules: - # Exclude bodyclose lint from tests because leaking connections in tests - # is a non-issue, and checking that adds unnecessary noise - - path: _test\.go - linters: - - bodyclose - -run: - timeout: 5m + - linters: + - bodyclose + path: _test\.go + paths: + - third_party$ + - builtin$ + - examples$ +formatters: + enable: + - goimports + exclusions: + generated: lax + paths: + - third_party$ + - builtin$ + - examples$ diff --git a/.tool-versions b/.tool-versions index e21aa83dff..2dc1382b79 100644 --- a/.tool-versions +++ b/.tool-versions @@ -1,3 +1,3 @@ -golang 1.24.1 +golang 1.25.4 shfmt 3.8.0 shellcheck 0.10.0 diff --git a/Dockerfile b/Dockerfile index c039cc485f..a3c6ff8fb7 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,14 +4,14 @@ # # Nothing fancy here: we copy in the source code and build on the Alpine Go # image. Refer to .dockerignore to get a sense of what we're not going to copy. -FROM golang:1.24.1-alpine@sha256:43c094ad24b6ac0546c62193baeb3e6e49ce14d3250845d166c77c25f64b0386 AS builder +FROM golang:1.25.4-alpine3.22@sha256:d3f0cf7723f3429e3f9ed846243970b20a2de7bae6a5b66fc5914e228d831bbb AS builder COPY . /src WORKDIR /src RUN go build ./cmd/src # This stage should be kept in sync with Dockerfile.release. -FROM alpine:3.22@sha256:4bcff63911fcb4448bd4fdacec207030997caf25e9bea4045fa6c8c44de311d1 +FROM alpine:3.22@sha256:4b7ce07002c69e8f3d704a9c5d6fd3053be500b7f1c69fc0d80990c2ad8dd412 # needed for `src code-intel upload` and `src actions exec` RUN apk add --no-cache git diff --git a/dev/golangci-lint.sh b/dev/golangci-lint.sh index c4663dc8ec..dffeb31b2f 100755 --- a/dev/golangci-lint.sh +++ b/dev/golangci-lint.sh @@ -6,7 +6,7 @@ pushd "$(dirname "${BASH_SOURCE[0]}")/.." >/dev/null mkdir -p dev/.bin -version="1.64.5" +version="2.6.1" suffix="${version}-$(go env GOOS)-$(go env GOARCH)" target="$PWD/dev/.bin/golangci-lint-${suffix}" url="https://github.com/golangci/golangci-lint/releases/download/v${version}/golangci-lint-${suffix}.tar.gz" diff --git a/go.mod b/go.mod index 6c581211e3..678a2cd4e8 100644 --- a/go.mod +++ b/go.mod @@ -1,8 +1,6 @@ module github.com/sourcegraph/src-cli -go 1.24 - -toolchain go1.24.1 +go 1.23.12 require ( cloud.google.com/go/storage v1.30.1 @@ -19,7 +17,6 @@ require ( github.com/dustin/go-humanize v1.0.1 github.com/gobwas/glob v0.2.3 github.com/google/go-cmp v0.6.0 - github.com/gorilla/websocket v1.5.3 github.com/grafana/regexp v0.0.0-20221123153739-15dc172cd2db github.com/hexops/autogold v1.3.1 github.com/jedib0t/go-pretty/v6 v6.3.7 @@ -51,6 +48,7 @@ require ( github.com/fxamacker/cbor/v2 v2.7.0 // indirect github.com/google/gnostic-models v0.6.8 // indirect github.com/google/s2a-go v0.1.4 // indirect + github.com/gorilla/websocket v1.5.3 // indirect github.com/jackc/chunkreader/v2 v2.0.1 // indirect github.com/jackc/pgconn v1.14.3 // indirect github.com/jackc/pgio v1.0.0 // indirect From ce38afcecea61b5c81d4d4182aebf9671162730d Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Tue, 11 Nov 2025 11:32:32 +0200 Subject: [PATCH 492/647] fix: go linting issues (#1194) * remove deprecated build tags * fix error string formatting * remove embedded field selectors * convert if-else chains to tagged switches * use fmt.Fprintf instead of Write with Sprintf * remove duplicate import * apply de morgan's law * fix compilation errors * remove more embedded field selectors * remove final embedded field selectors * Revert "apply de morgan's law" This reverts commit d76cb21c54ccf1242b4a057e89f847fe7896960c. * ignore qf1001 and st1003 lint rules * add comments for disabled lint rules * Revert "remove final embedded field selectors" This reverts commit 0a1407c36e57b48d95d6254979096273a3ddb295. * Revert "remove more embedded field selectors" This reverts commit 64642ad1c96fb3d6309f91b10bafcced0ba911bd. * Revert "remove embedded field selectors" This reverts commit 563205a0bf7d417c04a597f305b1b740cd17bcc0. * disable qf1008 embedded field lint --- .golangci.yml | 6 ++++++ cmd/src/batch_common.go | 2 +- cmd/src/search.go | 10 ++++++---- cmd/src/signature_fetch.go | 2 +- internal/api/api.go | 3 +-- internal/api/proxy.go | 6 +++--- internal/batches/debug.go | 1 - internal/batches/docker/version.go | 2 +- internal/batches/executor/execution_cache_test.go | 5 ++--- .../batches/workspace/bind_workspace_nonwin_test.go | 1 - internal/batches/workspace/workspace.go | 7 ++++--- internal/validate/kube/kube.go | 7 ++++--- 12 files changed, 29 insertions(+), 23 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 39e52917b9..c0a2851b19 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -41,6 +41,12 @@ linters: govet: disable: - composites + staticcheck: + checks: + - all + - -QF1001 # De Morgan's law simplifications + - -QF1008 # Embedded field selector simplifications + - -ST1003 # Naming conventions (ID vs Id, URL vs Url, etc.) exclusions: generated: lax presets: diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index 157af55927..21fdce2e21 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -632,7 +632,7 @@ func getBatchSpecDirectory(file string) (string, error) { func checkExecutable(cmd string, args ...string) error { if err := exec.Command(cmd, args...).Run(); err != nil { return fmt.Errorf( - "failed to execute \"%s %s\":\n\t%s\n\n'src batch' requires %q to be available.", + "failed to execute \"%s %s\":\n\t%s\n\n'src batch' requires %q to be available", cmd, strings.Join(args, " "), err, diff --git a/cmd/src/search.go b/cmd/src/search.go index b4529da7c3..69ff1995b9 100644 --- a/cmd/src/search.go +++ b/cmd/src/search.go @@ -457,9 +457,10 @@ func applyHighlightsForFile(fileContent string, highlights []highlight) string { for _, highlight := range highlights { line := lines[highlight.line] for characterIndex, character := range []rune(line + "\n") { - if characterIndex == highlight.character { + switch characterIndex { + case highlight.character: result = append(result, []rune(start)...) - } else if characterIndex == highlight.character+highlight.length { + case highlight.character + highlight.length: result = append(result, []rune(end)...) } result = append(result, character) @@ -478,9 +479,10 @@ func applyHighlights(input string, highlights []highlight, start, end string) st for characterIndex, character := range []rune(line + "\n") { for _, highlight := range highlights { if highlight.line == lineNumber { - if characterIndex == highlight.character { + switch characterIndex { + case highlight.character: result = append(result, []rune(start)...) - } else if characterIndex == highlight.character+highlight.length { + case highlight.character + highlight.length: result = append(result, []rune(end)...) } } diff --git a/cmd/src/signature_fetch.go b/cmd/src/signature_fetch.go index e0bfa34e9f..4b9fd03a16 100644 --- a/cmd/src/signature_fetch.go +++ b/cmd/src/signature_fetch.go @@ -174,7 +174,7 @@ func (c cosignConfig) verifySignatureForImageHash(image string, hash string) err output, err := cmd.CombinedOutput() if err != nil { - return fmt.Errorf("Signature verification failed: %w\nOutput: %s", err, output) + return fmt.Errorf("signature verification failed: %w\nOutput: %s", err, output) } return nil diff --git a/internal/api/api.go b/internal/api/api.go index 63cef92b50..a31fae55e4 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -236,8 +236,7 @@ func (r *request) do(ctx context.Context, result interface{}) (bool, error) { // Check trace header before we potentially early exit if *r.client.opts.Flags.trace { - _, err := r.client.opts.Out.Write([]byte(fmt.Sprintf("x-trace: %s\n", resp.Header.Get("x-trace")))) - if err != nil { + if _, err := fmt.Fprintf(r.client.opts.Out, "x-trace: %s\n", resp.Header.Get("x-trace")); err != nil { return false, err } } diff --git a/internal/api/proxy.go b/internal/api/proxy.go index 5e5fbf30ef..3cf8673829 100644 --- a/internal/api/proxy.go +++ b/internal/api/proxy.go @@ -54,12 +54,12 @@ func applyProxy(transport *http.Transport, proxyURL *url.URL, proxyPath string) transport.Proxy = nil proxyApplied = true } else if proxyURL != nil { - if proxyURL.Scheme == "socks5" || - proxyURL.Scheme == "socks5h" { + switch proxyURL.Scheme { + case "socks5", "socks5h": // SOCKS proxies work out of the box - no need to manually dial transport.Proxy = http.ProxyURL(proxyURL) proxyApplied = true - } else if proxyURL.Scheme == "http" || proxyURL.Scheme == "https" { + case "http", "https": dial := func(ctx context.Context, network, addr string) (net.Conn, error) { // Dial the proxy d := net.Dialer{} diff --git a/internal/batches/debug.go b/internal/batches/debug.go index c5754d63e7..3a7310f664 100644 --- a/internal/batches/debug.go +++ b/internal/batches/debug.go @@ -1,5 +1,4 @@ //go:build debug -// +build debug package batches diff --git a/internal/batches/docker/version.go b/internal/batches/docker/version.go index 84cfdcd1e7..d6a858f508 100644 --- a/internal/batches/docker/version.go +++ b/internal/batches/docker/version.go @@ -12,7 +12,7 @@ func CheckVersion(ctx context.Context) error { _, err := executeFastCommand(ctx, "version") if err != nil { return fmt.Errorf( - "failed to execute \"docker version\":\n\t%s\n\n'src batch' requires \"docker\" to be available.", + "failed to execute \"docker version\":\n\t%s\n\n'src batch' requires \"docker\" to be available", err, ) } diff --git a/internal/batches/executor/execution_cache_test.go b/internal/batches/executor/execution_cache_test.go index d5ff754ffc..5357278420 100644 --- a/internal/batches/executor/execution_cache_test.go +++ b/internal/batches/executor/execution_cache_test.go @@ -6,14 +6,13 @@ import ( "github.com/google/go-cmp/cmp" - "github.com/sourcegraph/sourcegraph/lib/batches" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/execution" "github.com/sourcegraph/sourcegraph/lib/batches/execution/cache" "github.com/sourcegraph/sourcegraph/lib/batches/git" ) -var cacheRepo1 = batches.Repository{ +var cacheRepo1 = batcheslib.Repository{ ID: "src-cli", Name: "github.com/sourcegraph/src-cli", BaseRef: "refs/heads/main", @@ -21,7 +20,7 @@ var cacheRepo1 = batches.Repository{ FileMatches: []string{"README.md", "main.go"}, } -var cacheRepo2 = batches.Repository{ +var cacheRepo2 = batcheslib.Repository{ ID: "sourcegraph", Name: "github.com/sourcegraph/sourcegraph", BaseRef: "refs/heads/main-2", diff --git a/internal/batches/workspace/bind_workspace_nonwin_test.go b/internal/batches/workspace/bind_workspace_nonwin_test.go index 2943dcd598..238a884f13 100644 --- a/internal/batches/workspace/bind_workspace_nonwin_test.go +++ b/internal/batches/workspace/bind_workspace_nonwin_test.go @@ -1,5 +1,4 @@ //go:build !windows -// +build !windows package workspace diff --git a/internal/batches/workspace/workspace.go b/internal/batches/workspace/workspace.go index b13f0b24dc..8aaf3b3234 100644 --- a/internal/batches/workspace/workspace.go +++ b/internal/batches/workspace/workspace.go @@ -56,11 +56,12 @@ const ( func NewCreator(ctx context.Context, preference, cacheDir, tempDir string, images map[string]docker.Image) (Creator, CreatorType) { var workspaceType CreatorType - if preference == "volume" { + switch preference { + case "volume": workspaceType = CreatorTypeVolume - } else if preference == "bind" { + case "bind": workspaceType = CreatorTypeBind - } else { + default: workspaceType = BestCreatorType(ctx, images) } diff --git a/internal/validate/kube/kube.go b/internal/validate/kube/kube.go index a1382e9116..ae7555b323 100644 --- a/internal/validate/kube/kube.go +++ b/internal/validate/kube/kube.go @@ -379,13 +379,14 @@ func CurrentContextSetTo(clusterService string) error { return err } - if clusterService == "gke" { + switch clusterService { + case "gke": got := strings.Split(currentContext, "_")[0] want := clusterService if got != want { return errors.New("no gke cluster configured") } - } else if clusterService == "eks" { + case "eks": got := strings.Split(currentContext, ":") want := []string{"arn", "aws", clusterService} @@ -399,7 +400,7 @@ func CurrentContextSetTo(clusterService string) error { return errors.New("no eks cluster configured") } } - } else if clusterService == "aks" { + case "aks": colons := strings.Split(currentContext, ":") // aws string underscores := strings.Split(currentContext, "_") // gke string From 10a73edfe9522b44439e21eaa807b30ff0dac667 Mon Sep 17 00:00:00 2001 From: Jason Hawk Harris Date: Tue, 11 Nov 2025 14:01:36 -0600 Subject: [PATCH 493/647] Cleanup: rip out the `scout` tool (#1196) * rip out the scout tool * remove build file --- cmd/src/scout.go | 43 --- cmd/src/scout_advise.go | 113 -------- cmd/src/scout_resource.go | 82 ------ cmd/src/scout_usage.go | 98 ------- internal/scout/advise/advise.go | 97 ------- internal/scout/advise/advise_test.go | 147 ---------- internal/scout/advise/k8s.go | 146 ---------- internal/scout/constants.go | 12 - internal/scout/helpers.go | 24 -- internal/scout/kube/kube.go | 353 ----------------------- internal/scout/kube/kube_test.go | 84 ------ internal/scout/resource/resource.go | 122 -------- internal/scout/resource/resource_test.go | 68 ----- internal/scout/style/resource_table.go | 174 ----------- internal/scout/style/usage_table.go | 176 ----------- internal/scout/types.go | 44 --- internal/scout/usage/k8s.go | 164 ----------- internal/scout/usage/usage.go | 19 -- internal/scout/usage/usage_test.go | 164 ----------- 19 files changed, 2130 deletions(-) delete mode 100644 cmd/src/scout.go delete mode 100644 cmd/src/scout_advise.go delete mode 100644 cmd/src/scout_resource.go delete mode 100644 cmd/src/scout_usage.go delete mode 100644 internal/scout/advise/advise.go delete mode 100644 internal/scout/advise/advise_test.go delete mode 100644 internal/scout/advise/k8s.go delete mode 100644 internal/scout/constants.go delete mode 100644 internal/scout/helpers.go delete mode 100644 internal/scout/kube/kube.go delete mode 100644 internal/scout/kube/kube_test.go delete mode 100644 internal/scout/resource/resource.go delete mode 100644 internal/scout/resource/resource_test.go delete mode 100644 internal/scout/style/resource_table.go delete mode 100644 internal/scout/style/usage_table.go delete mode 100644 internal/scout/types.go delete mode 100644 internal/scout/usage/k8s.go delete mode 100644 internal/scout/usage/usage.go delete mode 100644 internal/scout/usage/usage_test.go diff --git a/cmd/src/scout.go b/cmd/src/scout.go deleted file mode 100644 index d5df574a80..0000000000 --- a/cmd/src/scout.go +++ /dev/null @@ -1,43 +0,0 @@ -package main - -import ( - "flag" - "fmt" -) - -var scoutCommands commander - -func init() { - usage := `'src scout' is a tool that provides monitoring for Sourcegraph resources - - EXPERIMENTAL: 'scout' is an experimental command in the 'src' tool. To use, you must - point your .kube config to your Sourcegraph instance. - - Usage: - - src scout command [command options] - - The commands are: - - resource print all known sourcegraph resources and their allocations - usage get CPU, memory and current disk usage - advise recommend lowering or raising resource allocations based on actual usage - - Use "src scout [command] -h" for more information about a command. - ` - - flagSet := flag.NewFlagSet("scout", flag.ExitOnError) - handler := func(args []string) error { - scoutCommands.run(flagSet, "src scout", usage, args) - return nil - } - - commands = append(commands, &command{ - flagSet: flagSet, - aliases: []string{"scout"}, - handler: handler, - usageFunc: func() { - fmt.Println(usage) - }, - }) -} diff --git a/cmd/src/scout_advise.go b/cmd/src/scout_advise.go deleted file mode 100644 index 129a13c660..0000000000 --- a/cmd/src/scout_advise.go +++ /dev/null @@ -1,113 +0,0 @@ -package main - -import ( - "context" - "flag" - "fmt" - "path/filepath" - - "github.com/sourcegraph/src-cli/internal/scout/advise" - "k8s.io/client-go/kubernetes" - "k8s.io/client-go/tools/clientcmd" - "k8s.io/client-go/util/homedir" - metricsv "k8s.io/metrics/pkg/client/clientset/versioned" - - "github.com/sourcegraph/sourcegraph/lib/errors" -) - -func init() { - cmdUsage := `'src scout advise' is a tool that makes resource allocation recommendations. Based on current usage. - Part of the EXPERIMENTAL "src scout" tool. - - Examples - Make recommendations for all pods in a kubernetes deployment of Sourcegraph. - $ src scout advise - - Make recommendations for specific pod: - $ src scout advise --pod - - Add namespace if using namespace in a Kubernetes cluster - $ src scout advise --namespace - - Output advice to file - $ src scout advise --o path/to/file - - Output with warnings - $ src scout advise --warnings - ` - - flagSet := flag.NewFlagSet("advise", flag.ExitOnError) - usage := func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src scout %s':\n", flagSet.Name()) - flagSet.PrintDefaults() - fmt.Println(cmdUsage) - } - - var ( - kubeConfig *string - namespace = flagSet.String("namespace", "", "(optional) specify the kubernetes namespace to use") - pod = flagSet.String("pod", "", "(optional) specify a single pod") - output = flagSet.String("o", "", "(optional) output advice to file") - warnings = flagSet.Bool("warnings", false, "(optional) output advice with warnings") - ) - - if home := homedir.HomeDir(); home != "" { - kubeConfig = flagSet.String( - "kubeconfig", - filepath.Join(home, ".kube", "config"), - "(optional) absolute path to the kubeconfig file", - ) - } else { - kubeConfig = flagSet.String("kubeconfig", "", "absolute path to the kubeconfig file") - } - - handler := func(args []string) error { - if err := flagSet.Parse(args); err != nil { - return err - } - - config, err := clientcmd.BuildConfigFromFlags("", *kubeConfig) - if err != nil { - return errors.Wrap(err, "failed to load .kube config: ") - } - - clientSet, err := kubernetes.NewForConfig(config) - if err != nil { - return errors.Wrap(err, "failed to initiate kubernetes client: ") - } - - metricsClient, err := metricsv.NewForConfig(config) - if err != nil { - return errors.Wrap(err, "failed to initiate metrics client") - } - - var options []advise.Option - - if *namespace != "" { - options = append(options, advise.WithNamespace(*namespace)) - } - if *pod != "" { - options = append(options, advise.WithPod(*pod)) - } - if *output != "" { - options = append(options, advise.WithOutput(*output)) - } - if *warnings { - options = append(options, advise.WithWarnings(true)) - } - - return advise.K8s( - context.Background(), - clientSet, - metricsClient, - config, - options..., - ) - } - - scoutCommands = append(scoutCommands, &command{ - flagSet: flagSet, - handler: handler, - usageFunc: usage, - }) -} diff --git a/cmd/src/scout_resource.go b/cmd/src/scout_resource.go deleted file mode 100644 index f4c8cf2b5b..0000000000 --- a/cmd/src/scout_resource.go +++ /dev/null @@ -1,82 +0,0 @@ -package main - -import ( - "context" - "flag" - "fmt" - "path/filepath" - - "github.com/sourcegraph/sourcegraph/lib/errors" - "k8s.io/client-go/kubernetes" - "k8s.io/client-go/tools/clientcmd" - "k8s.io/client-go/util/homedir" - - "github.com/sourcegraph/src-cli/internal/scout/resource" -) - -func init() { - usage := `'src scout resource' is a tool that provides an overview of resource usage - across an instance of Sourcegraph. Part of the EXPERIMENTAL "src scout" tool. - - Examples - List pods and resource allocations in a Kubernetes deployment: - $ src scout resource - - Add namespace if using namespace in a Kubernetes cluster - $ src scout resource --namespace sg - ` - - flagSet := flag.NewFlagSet("resource", flag.ExitOnError) - usageFunc := func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src scout %s':\n", flagSet.Name()) - flagSet.PrintDefaults() - fmt.Println(usage) - } - - var ( - kubeConfig *string - namespace = flagSet.String("namespace", "", "(optional) specify the kubernetes namespace to use") - // TODO: option for getting resource allocation of the Node - // nodes = flagSet.Bool("node", false, "(optional) view resources for node(s)") - ) - - if home := homedir.HomeDir(); home != "" { - kubeConfig = flagSet.String( - "kubeconfig", - filepath.Join(home, ".kube", "config"), - "(optional) absolute path to the kubeconfig file", - ) - } else { - kubeConfig = flagSet.String("kubeconfig", "", "absolute path to the kubeconfig file") - } - - handler := func(args []string) error { - if err := flagSet.Parse(args); err != nil { - return err - } - - config, err := clientcmd.BuildConfigFromFlags("", *kubeConfig) - if err != nil { - return errors.New(fmt.Sprintf("%v: failed to load kubernetes config", err)) - } - - clientSet, err := kubernetes.NewForConfig(config) - if err != nil { - return errors.New(fmt.Sprintf("%v: failed to load kubernetes config", err)) - } - - var options []resource.Option - - if *namespace != "" { - options = append(options, resource.WithNamespace(*namespace)) - } - - return resource.K8s(context.Background(), clientSet, config, options...) - } - - scoutCommands = append(scoutCommands, &command{ - flagSet: flagSet, - handler: handler, - usageFunc: usageFunc, - }) -} diff --git a/cmd/src/scout_usage.go b/cmd/src/scout_usage.go deleted file mode 100644 index ba12fd6c11..0000000000 --- a/cmd/src/scout_usage.go +++ /dev/null @@ -1,98 +0,0 @@ -package main - -import ( - "context" - "flag" - "fmt" - "path/filepath" - - "github.com/sourcegraph/sourcegraph/lib/errors" - "github.com/sourcegraph/src-cli/internal/scout/usage" - "k8s.io/client-go/kubernetes" - "k8s.io/client-go/tools/clientcmd" - "k8s.io/client-go/util/homedir" - metricsv "k8s.io/metrics/pkg/client/clientset/versioned" -) - -func init() { - cmdUsage := `'src scout usage' is a tool that tracks resource usage for Sourcegraph instances. - Part of the EXPERIMENTAL "src scout" tool. - - Examples - List pods and resource usage in a Kubernetes deployment: - $ src scout usage - - Check usage for specific pod - $ src scout usage --pod - - Add namespace if using namespace in a Kubernetes cluster - $ src scout usage --namespace - ` - - flagSet := flag.NewFlagSet("usage", flag.ExitOnError) - usageFunc := func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src scout %s':\n", flagSet.Name()) - flagSet.PrintDefaults() - fmt.Println(cmdUsage) - } - - var ( - kubeConfig *string - namespace = flagSet.String("namespace", "", "(optional) specify the kubernetes namespace to use") - pod = flagSet.String("pod", "", "(optional) specify a single pod") - ) - - if home := homedir.HomeDir(); home != "" { - kubeConfig = flagSet.String( - "kubeconfig", - filepath.Join(home, ".kube", "config"), - "(optional) absolute path to the kubeconfig file", - ) - } else { - kubeConfig = flagSet.String("kubeconfig", "", "absolute path to the kubeconfig file") - } - - handler := func(args []string) error { - if err := flagSet.Parse(args); err != nil { - return err - } - - config, err := clientcmd.BuildConfigFromFlags("", *kubeConfig) - if err != nil { - return errors.Wrap(err, "failed to load .kube config: ") - } - - clientSet, err := kubernetes.NewForConfig(config) - if err != nil { - return errors.Wrap(err, "failed to initiate kubernetes client: ") - } - - metricsClient, err := metricsv.NewForConfig(config) - if err != nil { - return errors.Wrap(err, "failed to initiate metrics client") - } - - var options []usage.Option - if *namespace != "" { - options = append(options, usage.WithNamespace(*namespace)) - } - if *pod != "" { - options = append(options, usage.WithPod(*pod)) - } - - return usage.K8s( - context.Background(), - clientSet, - metricsClient, - config, - options..., - ) - } - - scoutCommands = append(scoutCommands, &command{ - flagSet: flagSet, - handler: handler, - usageFunc: usageFunc, - }) - -} diff --git a/internal/scout/advise/advise.go b/internal/scout/advise/advise.go deleted file mode 100644 index c1cefe90c0..0000000000 --- a/internal/scout/advise/advise.go +++ /dev/null @@ -1,97 +0,0 @@ -package advise - -import ( - "context" - "fmt" - "os" - - "github.com/sourcegraph/sourcegraph/lib/errors" - "github.com/sourcegraph/src-cli/internal/scout" -) - -type Option = func(config *scout.Config) - -const ( - UNDER_PROVISIONED = "%s %s: %s is under-provisioned (%.2f%% usage). Add resources." - WELL_PROVISIONED = "%s %s: %s is well-provisioned (%.2f%% usage). No action needed." - OVER_PROVISIONED = "%s %s: %s is over-provisioned (%.2f%% usage). Trim resources." -) - -func WithNamespace(namespace string) Option { - return func(config *scout.Config) { - config.Namespace = namespace - } -} - -func WithPod(podname string) Option { - return func(config *scout.Config) { - config.Pod = podname - } -} - -func WithOutput(pathToFile string) Option { - return func(config *scout.Config) { - config.Output = pathToFile - } -} - -func WithWarnings(includeWarnings bool) Option { - return func(config *scout.Config) { - config.Warnings = includeWarnings - } -} - -func CheckUsage(usage float64, resourceType string, container string) scout.Advice { - var advice scout.Advice - switch { - case usage >= 80: - advice.Kind = scout.DANGER - advice.Msg = fmt.Sprintf( - UNDER_PROVISIONED, - scout.FlashingLightEmoji, - container, - resourceType, - usage, - ) - case usage >= 20 && usage < 80: - advice.Kind = scout.HEALTHY - advice.Msg = fmt.Sprintf( - WELL_PROVISIONED, - scout.SuccessEmoji, - container, - resourceType, - usage, - ) - default: - advice.Kind = scout.WARNING - advice.Msg = fmt.Sprintf( - OVER_PROVISIONED, - scout.WarningSign, - container, - resourceType, - usage, - ) - } - - return advice -} - -// outputToFile writes resource allocation advice for a Kubernetes pod to a file. -func OutputToFile(ctx context.Context, cfg *scout.Config, name string, advice []scout.Advice) error { - file, err := os.OpenFile(cfg.Output, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) - if err != nil { - return errors.Wrap(err, "failed to open file") - } - defer file.Close() - - if _, err := fmt.Fprintf(file, "- %s\n", name); err != nil { - return errors.Wrap(err, "failed to write service name to file") - } - - for _, adv := range advice { - if _, err := fmt.Fprintf(file, "%s\n", adv.Msg); err != nil { - return errors.Wrap(err, "failed to write container advice to file") - } - } - return nil -} diff --git a/internal/scout/advise/advise_test.go b/internal/scout/advise/advise_test.go deleted file mode 100644 index c93696c20f..0000000000 --- a/internal/scout/advise/advise_test.go +++ /dev/null @@ -1,147 +0,0 @@ -package advise - -import ( - "bufio" - "context" - "os" - "testing" - "time" - - "github.com/sourcegraph/src-cli/internal/scout" -) - -func TestCheckUsage(t *testing.T) { - cases := []struct { - name string - usage float64 - resourceType string - container string - want scout.Advice - }{ - { - name: "should return correct message for usage over 100", - usage: 110, - resourceType: "cpu", - container: "gitserver-0", - want: scout.Advice{ - Kind: scout.DANGER, - Msg: "🚨 gitserver-0: cpu is under-provisioned (110.00% usage). Add resources.", - }, - }, - { - name: "should return correct message for usage over 80 and under 100", - usage: 87, - resourceType: "memory", - container: "gitserver-0", - want: scout.Advice{ - Kind: scout.DANGER, - Msg: "🚨 gitserver-0: memory is under-provisioned (87.00% usage). Add resources.", - }, - }, - { - name: "should return correct message for usage over 40 and under 80", - usage: 63.4, - resourceType: "memory", - container: "gitserver-0", - want: scout.Advice{ - Kind: scout.HEALTHY, - Msg: "✅ gitserver-0: memory is well-provisioned (63.40% usage). No action needed.", - }, - }, - { - name: "should return correct message for usage under 40", - usage: 12.33, - resourceType: "memory", - container: "gitserver-0", - want: scout.Advice{ - Kind: scout.WARNING, - Msg: "⚠️ gitserver-0: memory is over-provisioned (12.33% usage). Trim resources.", - }, - }, - } - - for _, tc := range cases { - tc := tc - t.Run(tc.name, func(t *testing.T) { - got := CheckUsage(tc.usage, tc.resourceType, tc.container) - - if got != tc.want { - t.Errorf("got: '%s' want '%s'", got, tc.want) - } - }) - } -} - -func TestOutputToFile(t *testing.T) { - cfg := &scout.Config{ - Output: os.TempDir() + string(os.PathSeparator) + "test.txt", - } - name := "gitserver-0" - advice := []scout.Advice{ - { - Kind: scout.WARNING, - Msg: "Add more CPU", - }, - { - Kind: scout.WARNING, - Msg: "Add more memory", - }, - } - - err := OutputToFile(context.Background(), cfg, name, advice) - if err != nil { - t.Fatal(err) - } - - lines := readOutputFile(t, cfg) - - cases := []struct { - lineNum int - want string - }{ - {1, "- gitserver-0"}, - {2, advice[0].Msg}, - {3, advice[1].Msg}, - } - - for _, tc := range cases { - tc := tc - got := lines[tc.lineNum-1] - if got != tc.want { - t.Errorf("Expected %q, got %q", tc.want, lines[tc.lineNum-1]) - } - } - - if len(lines) > 3 { - t.Error("Expected only 3 lines, got more") - } - - if err != nil { - t.Fatal(err) - } -} - -func readOutputFile(t *testing.T, cfg *scout.Config) []string { - file, err := os.Open(cfg.Output) - if err != nil { - t.Fatal(err) - } - - var lines []string - scanner := bufio.NewScanner(file) - for scanner.Scan() { - lines = append(lines, scanner.Text()) - } - - file.Close() - err = os.Remove(cfg.Output) - if err != nil { - // try again after waiting a bit - time.Sleep(100 * time.Millisecond) - err = os.Remove(cfg.Output) - if err != nil { - t.Fatal(err) - } - } - return lines -} diff --git a/internal/scout/advise/k8s.go b/internal/scout/advise/k8s.go deleted file mode 100644 index 4226762730..0000000000 --- a/internal/scout/advise/k8s.go +++ /dev/null @@ -1,146 +0,0 @@ -package advise - -import ( - "context" - "fmt" - "time" - - "github.com/sourcegraph/sourcegraph/lib/errors" - "github.com/sourcegraph/src-cli/internal/scout" - "github.com/sourcegraph/src-cli/internal/scout/kube" - v1 "k8s.io/api/core/v1" - "k8s.io/client-go/kubernetes" - "k8s.io/client-go/rest" - metricsv "k8s.io/metrics/pkg/client/clientset/versioned" -) - -func K8s( - ctx context.Context, - k8sClient *kubernetes.Clientset, - metricsClient *metricsv.Clientset, - restConfig *rest.Config, - opts ...Option, -) error { - cfg := &scout.Config{ - Namespace: "default", - Pod: "", - Output: "", - Warnings: false, - RestConfig: restConfig, - K8sClient: k8sClient, - MetricsClient: metricsClient, - } - - for _, opt := range opts { - opt(cfg) - } - - pods, err := kube.GetPods(ctx, cfg) - if err != nil { - return errors.Wrap(err, "could not get list of pods") - } - - if cfg.Pod != "" { - pod, err := kube.GetPod(cfg.Pod, pods) - if err != nil { - return errors.Wrap(err, "could not get pod") - } - - err = Advise(ctx, cfg, pod) - if err != nil { - return errors.Wrap(err, "could not advise") - } - return nil - } - - if cfg.Output != "" { - fmt.Printf("writing to %s. This can take a few minutes...", cfg.Output) - } - - for _, pod := range pods { - err = Advise(ctx, cfg, pod) - if err != nil { - return errors.Wrap(err, "could not advise") - } - } - - return nil -} - -// Advise generates resource allocation advice for a Kubernetes pod. -// The function fetches usage metrics for each container in the pod. It then -// checks the usage percentages against thresholds to determine if more or less -// of a resource is needed. Advice is generated and either printed to the console -// or output to a file depending on the cfg.Output field. -func Advise(ctx context.Context, cfg *scout.Config, pod v1.Pod) error { - var advice []scout.Advice - usageMetrics, err := getUsageMetrics(ctx, cfg, pod) - if err != nil { - return errors.Wrap(err, "could not get usage metrics") - } - for _, metrics := range usageMetrics { - cpuAdvice := CheckUsage(metrics.CpuUsage, "CPU", metrics.ContainerName) - if cfg.Warnings { - advice = append(advice, cpuAdvice) - } else if !cfg.Warnings && cpuAdvice.Kind != scout.WARNING { - advice = append(advice, cpuAdvice) - } - - memoryAdvice := CheckUsage(metrics.MemoryUsage, "memory", metrics.ContainerName) - if cfg.Warnings { - advice = append(advice, memoryAdvice) - } else if !cfg.Warnings && memoryAdvice.Kind != scout.WARNING { - advice = append(advice, memoryAdvice) - } - - if metrics.Storage != nil { - storageAdvice := CheckUsage(metrics.StorageUsage, "storage", metrics.ContainerName) - if cfg.Warnings { - advice = append(advice, storageAdvice) - } else if !cfg.Warnings && storageAdvice.Kind != scout.WARNING { - advice = append(advice, storageAdvice) - } - } - - if cfg.Output != "" { - OutputToFile(ctx, cfg, pod.Name, advice) - } else { - fmt.Printf("%s %s: advising...\n", scout.EmojiFingerPointRight, pod.Name) - time.Sleep(time.Millisecond * 300) - for _, adv := range advice { - fmt.Printf("\t%s\n", adv.Msg) - } - } - } - - return nil -} - -// getUsageMetrics generates resource usage statistics for containers in a Kubernetes pod. -func getUsageMetrics(ctx context.Context, cfg *scout.Config, pod v1.Pod) ([]scout.UsageStats, error) { - var usages []scout.UsageStats - var usage scout.UsageStats - podMetrics, err := kube.GetPodMetrics(ctx, cfg, pod) - if err != nil { - return usages, errors.Wrap(err, "while attempting to fetch pod metrics") - } - - containerMetrics := &scout.ContainerMetrics{ - PodName: cfg.Pod, - Limits: map[string]scout.Resources{}, - } - - if err = kube.AddLimits(ctx, cfg, &pod, containerMetrics); err != nil { - return usages, errors.Wrap(err, "failed to get get container metrics") - } - - for _, container := range podMetrics.Containers { - usage, err = kube.GetUsage(ctx, cfg, *containerMetrics, pod, container) - if err != nil { - return usages, errors.Wrapf(err, "could not compile usages data for row: %s\n", container.Name) - } - usages = append(usages, usage) - } - - return usages, nil -} diff --git a/internal/scout/constants.go b/internal/scout/constants.go deleted file mode 100644 index 3549ceabd6..0000000000 --- a/internal/scout/constants.go +++ /dev/null @@ -1,12 +0,0 @@ -package scout - -const ( - ABillion float64 = 1_000_000_000 - EmojiFingerPointRight = "👉" - FlashingLightEmoji = "🚨" - SuccessEmoji = "✅" - WarningSign = "⚠️ " // why does this need an extra space to align?!?! - HEALTHY = "HEALTHY" - WARNING = "WARNING" - DANGER = "DANGER" -) diff --git a/internal/scout/helpers.go b/internal/scout/helpers.go deleted file mode 100644 index 1c917d3b94..0000000000 --- a/internal/scout/helpers.go +++ /dev/null @@ -1,24 +0,0 @@ -package scout - -// contains checks if a string slice contains a given value. -func Contains(slice []string, value string) bool { - for _, v := range slice { - if v == value { - return true - } - } - return false -} - -// getPercentage calculates the percentage of x in relation to y. -func GetPercentage(x, y float64) float64 { - if x == 0 { - return 0 - } - - if y == 0 { - return 0 - } - - return x * 100 / y -} diff --git a/internal/scout/kube/kube.go b/internal/scout/kube/kube.go deleted file mode 100644 index 7dc0a6f0e0..0000000000 --- a/internal/scout/kube/kube.go +++ /dev/null @@ -1,353 +0,0 @@ -package kube - -import ( - "bytes" - "context" - "fmt" - "os" - "regexp" - "strconv" - "strings" - - "github.com/charmbracelet/lipgloss" - "github.com/sourcegraph/sourcegraph/lib/errors" - "github.com/sourcegraph/src-cli/internal/scout" - "gopkg.in/inf.v0" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/resource" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/client-go/kubernetes/scheme" - "k8s.io/client-go/tools/remotecommand" - metav1beta1 "k8s.io/metrics/pkg/apis/metrics/v1beta1" -) - -// GetPods fetches all pods in a given namespace. -func GetPods(ctx context.Context, cfg *scout.Config) ([]corev1.Pod, error) { - podInterface := cfg.K8sClient.CoreV1().Pods(cfg.Namespace) - podList, err := podInterface.List(ctx, metav1.ListOptions{}) - if err != nil { - return []corev1.Pod{}, errors.Wrap(err, "could not list pods") - } - - if len(podList.Items) == 0 { - msg := lipgloss.NewStyle().Foreground(lipgloss.Color("#FFA500")) - fmt.Println(msg.Render(` - No pods exist in this namespace. - Did you mean to use the --namespace flag? - - If you are attempting to check - resources for a docker deployment, you - must use the --docker flag. - See --help for more info. - `)) - os.Exit(1) - } - - return podList.Items, nil -} - -// GetPod returns a pod object with the given name from a list of pods. -func GetPod(podName string, pods []corev1.Pod) (corev1.Pod, error) { - for _, p := range pods { - if p.Name == podName { - return p, nil - } - } - return corev1.Pod{}, errors.New("no pod with this name exists in this namespace") -} - -// GetPodMetrics fetches metrics for a given pod from the Kubernetes Metrics API. -// It accepts: -// - ctx: The context for the request -// - cfg: The scout config containing Kubernetes clientsets -// - pod: The pod specification -// -// It returns: -// - podMetrics: The PodMetrics object containing metrics for the pod -// - Any error that occurred while fetching the metrics -func GetPodMetrics(ctx context.Context, cfg *scout.Config, pod corev1.Pod) (*metav1beta1.PodMetrics, error) { - podMetrics, err := cfg.MetricsClient. - MetricsV1beta1(). - PodMetricses(cfg.Namespace). - Get(ctx, pod.Name, metav1.GetOptions{}) - if err != nil { - return nil, errors.Wrap(err, "failed to get pod metrics") - } - - return podMetrics, nil -} - -// GetLimits generates resource limits for containers in a pod. -// -// It accepts: -// - ctx: The context for the request -// - cfg: The scout config containing Kubernetes clientsets -// - pod: The pod specification -// - containerMetrics: A pointer to a ContainerMetrics struct to populate -// -// It populates the containerMetrics.Limits field with a map of container names -// to resource limits (CPU, memory, storage) for each container in the pod. -// -// It returns: -// - Any error that occurred while fetching resource limits -func AddLimits(ctx context.Context, cfg *scout.Config, pod *corev1.Pod, containerMetrics *scout.ContainerMetrics) error { - for _, container := range pod.Spec.Containers { - containerName := container.Name - capacity, err := GetPvcCapacity(ctx, cfg, container, pod) - if err != nil { - return errors.Wrap(err, "while getting storage capacity of PV") - } - - rsrcs := scout.Resources{ - Cpu: container.Resources.Limits.Cpu().ToDec(), - Memory: container.Resources.Limits.Memory().ToDec(), - Storage: capacity, - } - containerMetrics.Limits[containerName] = rsrcs - } - return nil -} - -// GetUsage generates resource usage statistics for a Kubernetes container. -// -// It accepts: -// - ctx: The context for the request -// - cfg: The scout config containing Kubernetes clientsets -// - metrics: Container resource limits -// - pod: The pod specification -// - container: Container metrics from the Metrics API -// -// It returns: -// - usageStats: A UsageStats struct containing the resource usage info -// - Any error that occurred while generating the usage stats -func GetUsage( - ctx context.Context, - cfg *scout.Config, - metrics scout.ContainerMetrics, - pod corev1.Pod, - container metav1beta1.ContainerMetrics, -) (scout.UsageStats, error) { - var usageStats scout.UsageStats - usageStats.ContainerName = container.Name - - cpuUsage, err := GetRawUsage(container.Usage, "cpu") - if err != nil { - return usageStats, errors.Wrap(err, "failed to get raw CPU usage") - } - - memUsage, err := GetRawUsage(container.Usage, "memory") - if err != nil { - return usageStats, errors.Wrap(err, "failed to get raw memory usage") - } - - limits := metrics.Limits[container.Name] - - var storageCapacity float64 - var storageUsage float64 - if limits.Storage != nil { - storageCapacity, storageUsage, err = GetStorageUsage(ctx, cfg, pod.Name, container.Name) - if err != nil { - return usageStats, errors.Wrap(err, "failed to get storage usage") - } - } - - usageStats.CpuCores = limits.Cpu - usageStats.CpuUsage = scout.GetPercentage( - cpuUsage, - limits.Cpu.AsApproximateFloat64()*scout.ABillion, - ) - - usageStats.Memory = limits.Memory - usageStats.MemoryUsage = scout.GetPercentage( - memUsage, - limits.Memory.AsApproximateFloat64(), - ) - - if limits.Storage == nil { - storageDec := *inf.NewDec(0, 0) - usageStats.Storage = resource.NewDecimalQuantity(storageDec, resource.Format("DecimalSI")) - } else { - usageStats.Storage = limits.Storage - } - - usageStats.StorageUsage = scout.GetPercentage( - storageUsage, - storageCapacity, - ) - - if metrics.Limits[container.Name].Storage == nil { - usageStats.Storage = nil - } - - return usageStats, nil -} - -// GetRawUsage returns the raw usage value for a given resource type from a Kubernetes ResourceList. -// -// It accepts: -// - usages: A Kubernetes ResourceList containing usage values -// - targetKey: The resource type to get the usage for (e.g. "cpu" or "memory") -// -// It returns: -// - The raw usage value for the target resource type -// - Any error that occurred while parsing the usage value -func GetRawUsage(usages corev1.ResourceList, targetKey string) (float64, error) { - var usage *inf.Dec - - for key, val := range usages { - if key.String() == targetKey { - usage = val.AsDec().SetScale(0) - } - } - - toFloat, err := strconv.ParseFloat(usage.String(), 64) - if err != nil { - return 0, errors.Wrap(err, "failed to convert inf.Dec type to float") - } - - return toFloat, nil -} - -// GetPvcCapacity returns the storage capacity of a PersistentVolumeClaim mounted to a container. -// -// It accepts: -// - ctx: The context for the request -// - cfg: The scout config containing Kubernetes clientsets -// - container: The container specification -// - pod: The pod specification -// -// It returns: -// - The storage capacity of the PVC in bytes -// - Any error that occurred while fetching the PVC -// -// If no PVC is mounted to the container, nil is returned for the capacity and no error. -func GetPvcCapacity(ctx context.Context, cfg *scout.Config, container corev1.Container, pod *corev1.Pod) (*resource.Quantity, error) { - for _, vm := range container.VolumeMounts { - for _, v := range pod.Spec.Volumes { - if v.Name == vm.Name && v.PersistentVolumeClaim != nil { - pvc, err := cfg.K8sClient. - CoreV1(). - PersistentVolumeClaims(cfg.Namespace). - Get( - ctx, - v.PersistentVolumeClaim.ClaimName, - metav1.GetOptions{}, - ) - if err != nil { - return nil, errors.Wrapf( - err, - "failed to get PVC %s", - v.PersistentVolumeClaim.ClaimName, - ) - } - return pvc.Status.Capacity.Storage().ToDec(), nil - } - } - } - return nil, nil -} - -// GetStorageUsage returns the storage capacity and usage for a given pod and container. -// -// It accepts: -// - ctx: The context for the request -// - cfg: The scout config containing Kubernetes clientsets -// - podName: The name of the pod -// - containerName: The name of the container -// -// It returns: -// - storageCapacity: The total storage capacity for the container in bytes -// - storageUsage: The used storage for the container in bytes -// - Any error that occurred while fetching the storage usage -func GetStorageUsage( - ctx context.Context, - cfg *scout.Config, - podName string, - containerName string, -) (float64, float64, error) { - var storageCapacity float64 - var storageUsage float64 - - stateless := []string{ - "cadvisor", - "pgsql-exporter", - "executor", - "dind", - "github-proxy", - "jaeger", - "node-exporter", - "otel-agent", - "otel-collector", - "precise-code-intel-worker", - "redis-exporter", - "repo-updater", - "frontend", - "syntect-server", - "worker", - } - - // if pod is stateless, return 0 for capacity and usage - if scout.Contains(stateless, containerName) { - return storageCapacity, storageUsage, nil - } - - req := cfg.K8sClient.CoreV1().RESTClient().Post(). - Resource("pods"). - Name(podName). - Namespace(cfg.Namespace). - SubResource("exec") - - req.VersionedParams(&corev1.PodExecOptions{ - Container: containerName, - Command: []string{"df"}, - Stdin: false, - Stdout: true, - Stderr: true, - TTY: false, - }, scheme.ParameterCodec) - - exec, err := remotecommand.NewSPDYExecutor(cfg.RestConfig, "POST", req.URL()) - if err != nil { - return 0, 0, err - } - - var stdout, stderr bytes.Buffer - err = exec.StreamWithContext(ctx, remotecommand.StreamOptions{ - Stdout: &stdout, - Stderr: &stderr, - }) - if err != nil { - return 0, 0, err - } - - lines := strings.Split(stdout.String(), "\n") - for _, line := range lines[1 : len(lines)-1] { - fields := strings.Fields(line) - - if acceptedFileSystem(fields[0]) { - capacityFloat, err := strconv.ParseFloat(fields[1], 64) - if err != nil { - return 0, 0, errors.Wrap(err, "could not convert string to float64") - } - - usageFloat, err := strconv.ParseFloat(fields[2], 64) - if err != nil { - return 0, 0, errors.Wrap(err, "could not convert string to float64") - } - return capacityFloat, usageFloat, nil - } - } - - return 0, 0, nil -} - -// acceptedFileSystem checks if a given file system, represented -// as a string, is an accepted system. -// -// It returns: -// - True if the file system matches the pattern '/dev/sd[a-z]$' -// - False otherwise -func acceptedFileSystem(fileSystem string) bool { - matched, _ := regexp.MatchString(`/dev/sd[a-z]$`, fileSystem) - return matched -} diff --git a/internal/scout/kube/kube_test.go b/internal/scout/kube/kube_test.go deleted file mode 100644 index c45080dced..0000000000 --- a/internal/scout/kube/kube_test.go +++ /dev/null @@ -1,84 +0,0 @@ -package kube - -import ( - "testing" - - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -func TestAcceptedFileSystem(t *testing.T) { - cases := []struct { - name string - filesystem string - want bool - }{ - { - name: "should return true if filesystem matches 'matched' regular expression", - filesystem: "/dev/sda", - want: true, - }, - { - name: "should return false if filesystem doesn't match 'matched' regular expression", - filesystem: "/dev/sda1", - want: false, - }, - } - - for _, tc := range cases { - tc := tc - t.Run(tc.name, func(t *testing.T) { - got := acceptedFileSystem(tc.filesystem) - if got != tc.want { - t.Errorf("got %v want %v", got, tc.want) - } - }) - } -} - -func TestGetPod(t *testing.T) { - cases := []struct { - name string - podList []corev1.Pod - wantPod string - }{ - { - name: "should return correct pod", - podList: []corev1.Pod{ - *testPod("sg", "soucegraph-frontend-0", "sourcegraph-frontend"), - *testPod("sg", "gitserver-0", "gitserver"), - *testPod("sg", "indexed-search-0", "indexed-search"), - }, - wantPod: "gitserver-0", - }, - { - name: "should return empty pod if pod not found", - podList: []corev1.Pod{ - *testPod("sg", "soucegraph-frontend-0", "sourcegraph-frontend"), - *testPod("sg", "indexed-search-0", "indexed-search"), - }, - wantPod: "", - }, - } - - for _, tc := range cases { - tc := tc - t.Run(tc.name, func(t *testing.T) { - got, _ := GetPod("gitserver-0", tc.podList) - gotPod := got.Name - - if gotPod != tc.wantPod { - t.Errorf("want pod %s, got pod %s", tc.wantPod, gotPod) - } - }) - } -} - -func testPod(namespace, podName, containerName string) *corev1.Pod { - return &corev1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: namespace, - Name: podName, - }, - } -} diff --git a/internal/scout/resource/resource.go b/internal/scout/resource/resource.go deleted file mode 100644 index 6be8a873e0..0000000000 --- a/internal/scout/resource/resource.go +++ /dev/null @@ -1,122 +0,0 @@ -package resource - -import ( - "context" - "fmt" - "os" - - "github.com/charmbracelet/bubbles/table" - "github.com/charmbracelet/lipgloss" - "github.com/sourcegraph/sourcegraph/lib/errors" - "github.com/sourcegraph/src-cli/internal/scout" - "github.com/sourcegraph/src-cli/internal/scout/kube" - "github.com/sourcegraph/src-cli/internal/scout/style" - "k8s.io/client-go/kubernetes" - "k8s.io/client-go/rest" -) - -type Option = func(config *scout.Config) - -func WithNamespace(namespace string) Option { - return func(config *scout.Config) { - config.Namespace = namespace - } -} - -// K8s prints the CPU and memory resource limits and requests for all pods in the given namespace. -func K8s(ctx context.Context, clientSet *kubernetes.Clientset, restConfig *rest.Config, opts ...Option) error { - cfg := &scout.Config{ - Namespace: "default", - Pod: "", - RestConfig: restConfig, - K8sClient: clientSet, - MetricsClient: nil, - } - - for _, opt := range opts { - opt(cfg) - } - - return listPodResources(ctx, cfg) -} - -func listPodResources(ctx context.Context, cfg *scout.Config) error { - pods, err := kube.GetPods(ctx, cfg) - if err != nil { - return errors.Wrap(err, "could not get pods") - } - - columns := []table.Column{ - {Title: "CONTAINER", Width: 20}, - {Title: "CPU LIMITS", Width: 10}, - {Title: "CPU REQUESTS", Width: 12}, - {Title: "MEM LIMITS", Width: 10}, - {Title: "MEM REQUESTS", Width: 12}, - {Title: "CAPACITY", Width: 8}, - } - - if len(pods) == 0 { - msg := lipgloss.NewStyle().Foreground(lipgloss.Color("#FFA500")) - fmt.Println(msg.Render(` - No pods exist in this namespace. - Did you mean to use the --namespace flag? - - If you are attemptying to check - resources for a docker deployment, you - must use the --docker flag. - See --help for more info. - `)) - os.Exit(1) - } - - var rows []table.Row - for _, pod := range pods { - if pod.GetNamespace() == cfg.Namespace { - for _, container := range pod.Spec.Containers { - cpuLimits := container.Resources.Limits.Cpu() - cpuRequests := container.Resources.Requests.Cpu() - memLimits := container.Resources.Limits.Memory() - memRequests := container.Resources.Requests.Memory() - - capacity, err := kube.GetPvcCapacity(ctx, cfg, container, &pod) - if err != nil { - return err - } - - row := table.Row{ - container.Name, - cpuLimits.String(), - cpuRequests.String(), - memLimits.String(), - memRequests.String(), - capacity.String(), - } - rows = append(rows, row) - } - } - } - - style.ResourceTable(columns, rows) - return nil -} - -// getMemUnits converts a byte value to the appropriate memory unit. -func getMemUnits(valToConvert int64) (string, int64, error) { - if valToConvert < 0 { - return "", valToConvert, fmt.Errorf("invalid memory value: %d", valToConvert) - } - - var memUnit string - switch { - case valToConvert < 1000000: - memUnit = "KB" - case valToConvert < 1000000000: - memUnit = "MB" - valToConvert = valToConvert / 1000000 - default: - memUnit = "GB" - valToConvert = valToConvert / 1000000000 - } - - return memUnit, valToConvert, nil -} diff --git a/internal/scout/resource/resource_test.go b/internal/scout/resource/resource_test.go deleted file mode 100644 index f0cbd74d36..0000000000 --- a/internal/scout/resource/resource_test.go +++ /dev/null @@ -1,68 +0,0 @@ -package resource - -import ( - "fmt" - "testing" -) - -func TestGetMemUnits(t *testing.T) { - cases := []struct { - name string - param int64 - wantUnit string - wantValue int64 - wantError error - }{ - { - name: "convert bytes below a million to KB", - param: 999999, - wantUnit: "KB", - wantValue: 999999, - wantError: nil, - }, - { - name: "convert bytes below a billion to MB", - param: 999999999, - wantUnit: "MB", - wantValue: 999, - wantError: nil, - }, - { - name: "convert bytes above a billion to GB", - param: 12999999900, - wantUnit: "GB", - wantValue: 12, - wantError: nil, - }, - { - name: "return error for a negative number", - param: -300, - wantUnit: "", - wantValue: -300, - wantError: fmt.Errorf("invalid memory value: %d", -300), - }, - } - - for _, tc := range cases { - tc := tc - t.Run(tc.name, func(t *testing.T) { - gotUnit, gotValue, gotError := getMemUnits(tc.param) - - if gotUnit != tc.wantUnit { - t.Errorf("got %s want %s", gotUnit, tc.wantUnit) - } - - if gotValue != tc.wantValue { - t.Errorf("got %v want %v", gotValue, tc.wantValue) - } - - if gotError == nil && tc.wantError != nil { - t.Error("got nil want error") - } - - if gotError != nil && tc.wantError == nil { - t.Error("got error want nil") - } - }) - } -} diff --git a/internal/scout/style/resource_table.go b/internal/scout/style/resource_table.go deleted file mode 100644 index db5455ffdb..0000000000 --- a/internal/scout/style/resource_table.go +++ /dev/null @@ -1,174 +0,0 @@ -package style - -import ( - "fmt" - "os" - "path/filepath" - "strings" - "text/tabwriter" - - "github.com/atotto/clipboard" - "github.com/charmbracelet/bubbles/table" - tea "github.com/charmbracelet/bubbletea" - "github.com/charmbracelet/lipgloss" - "github.com/sourcegraph/sourcegraph/lib/errors" -) - -var resourceTableStyle = lipgloss.NewStyle(). - BorderStyle(lipgloss.NormalBorder()). - BorderForeground(lipgloss.Color("240")) - -type resourceTableModel struct { - table table.Model -} - -func (m resourceTableModel) Init() tea.Cmd { return nil } - -func (m resourceTableModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { - var cmd tea.Cmd - switch msg := msg.(type) { - case tea.KeyMsg: - switch msg.String() { - case "esc", "q", "ctrl+c": - return m, tea.Quit - case "c": - m.copyRowToClipboard(m.table.SelectedRow()) - copiedMessage := lipgloss.NewStyle(). - Foreground(lipgloss.Color("#32CD32")). - Render(fmt.Sprintf( - "Copied resource allocations for '%s' to clipboard", - m.table.SelectedRow()[0], - )) - return m, tea.Batch( - tea.Printf("%s", copiedMessage), - ) - case "C": - tmpDir := os.TempDir() - filePath := filepath.Join(tmpDir, "resource-dump.txt") - m.dump(m.table.Rows(), filePath) - savedMessage := lipgloss.NewStyle(). - Foreground(lipgloss.Color("#32CD32")). - Render(fmt.Sprintf( - "saved resource allocations to %s", - filePath, - )) - return m, tea.Batch( - tea.Printf("%s", savedMessage), - ) - } - } - m.table, cmd = m.table.Update(msg) - return m, cmd -} - -func (m resourceTableModel) View() string { - s := "\n > Press 'j' and 'k' to go up and down\n" - s += " > Press 'c' to copy highlighted row to clipboard\n" - s += " > Press 'C' to copy all rows to a file\n" - s += " > Press 'q' to quit\n\n" - s += resourceTableStyle.Render(m.table.View()) + "\n" - return s -} - -func (m resourceTableModel) dump(rows []table.Row, filePath string) error { - dumpFile, err := os.Create(filePath) - if err != nil { - return errors.Wrap(err, "error while creating new file") - } - defer dumpFile.Close() - - tw := tabwriter.NewWriter(dumpFile, 0, 0, 3, ' ', 0) - defer tw.Flush() - - // default to docker terms - headers := []string{ - "NAME", - "CPU CORES", - "CPU SHARES", - "MEM LIMITS", - "MEM RESERVATIONS", - } - - // kubernetes rows will always have 6 items - // change column headers to reflect k8s terms - if len(rows[0]) == 6 { - headers = []string{ - "NAME", - "CPU LIMITS", - "CPU REQUESTS", - "MEM LIMITS", - "MEM REQUESTS", - "CAPACITY", - } - } - - fmt.Fprintf(tw, "%s\n", strings.Join(headers, "\t")) - - for _, row := range rows { - values := []string{row[0], row[1], row[2], row[3], row[4]} - if len(row) == 6 { - values = append(values, row[5]) - } - fmt.Fprintf(tw, "%s\n", strings.Join(values, "\t")) - } - return nil -} - -func (m resourceTableModel) copyRowToClipboard(row table.Row) { - var containerInfo string - - // default to docker headers - headers := []string{ - "NAME", - "CPU CORES", - "CPU SHARES", - "MEM LIMITS", - "MEM RESERVATIONS", - } - - // kubernetes rows will always have 6 items - // change column headers to reflect k8s terms - if len(row) == 6 { - headers = []string{ - "NAME", - "CPU LIMITS", - "CPU REQUESTS", - "MEM LIMITS", - "MEM REQUESTS", - "CAPACITY", - } - } - - for i, header := range headers { - containerInfo += fmt.Sprintf("%s: %s\n", header, row[i]) - } - - clipboard.WriteAll(containerInfo) -} - -func ResourceTable(columns []table.Column, rows []table.Row) { - t := table.New( - table.WithColumns(columns), - table.WithRows(rows), - table.WithFocused(true), - table.WithHeight(14), - ) - - s := table.DefaultStyles() - s.Header = s.Header. - BorderStyle(lipgloss.NormalBorder()). - BorderForeground(lipgloss.Color("240")). - BorderBottom(true). - Bold(false) - s.Selected = s.Selected. - Foreground(lipgloss.Color("229")). - Background(lipgloss.Color("57")). - Bold(false) - t.SetStyles(s) - - m := resourceTableModel{t} - if _, err := tea.NewProgram(m).Run(); err != nil { - fmt.Println("Error running program:", err) - os.Exit(1) - } -} diff --git a/internal/scout/style/usage_table.go b/internal/scout/style/usage_table.go deleted file mode 100644 index f76ba19475..0000000000 --- a/internal/scout/style/usage_table.go +++ /dev/null @@ -1,176 +0,0 @@ -package style - -import ( - "fmt" - "os" - "path/filepath" - "strings" - "text/tabwriter" - - "github.com/atotto/clipboard" - "github.com/charmbracelet/bubbles/table" - tea "github.com/charmbracelet/bubbletea" - "github.com/charmbracelet/lipgloss" - "github.com/sourcegraph/sourcegraph/lib/errors" -) - -var usageTableStyle = lipgloss.NewStyle(). - BorderStyle(lipgloss.NormalBorder()). - BorderForeground(lipgloss.Color("240")) - -type usageTableModel struct { - table table.Model -} - -func (m usageTableModel) Init() tea.Cmd { return nil } - -func (m usageTableModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { - var cmd tea.Cmd - switch msg := msg.(type) { - case tea.KeyMsg: - switch msg.String() { - case "esc", "q", "ctrl+c": - return m, tea.Quit - case "c": - m.copyRowToClipboard(m.table.SelectedRow()) - copiedMessage := lipgloss.NewStyle(). - Foreground(lipgloss.Color("#32CD32")). - Render(fmt.Sprintf( - "Copied usage data for '%s' to clipboard", - m.table.SelectedRow()[0], - )) - return m, tea.Batch( - tea.Printf("%s", copiedMessage), - ) - case "C": - tmpDir := os.TempDir() - filePath := filepath.Join(tmpDir, "usage-dump.txt") - m.dump(m.table.Rows(), filePath) - savedMessage := lipgloss.NewStyle(). - Foreground(lipgloss.Color("#32CD32")). - Render(fmt.Sprintf( - "saved usage data to %s", - filePath, - )) - return m, tea.Batch( - tea.Printf("%s", savedMessage), - ) - } - } - m.table, cmd = m.table.Update(msg) - return m, cmd -} - -func (m usageTableModel) View() string { - s := "\n > Press 'j' and 'k' to go up and down\n" - s += " > Press 'c' to copy highlighted row to clipboard\n" - s += " > Press 'C' to copy all rows to a file\n" - s += " > Press 'q' to quit\n\n" - s += usageTableStyle.Render(m.table.View()) + "\n" - return s -} - -func (m usageTableModel) dump(rows []table.Row, filePath string) error { - dumpFile, err := os.Create(filePath) - if err != nil { - return errors.Wrap(err, "error while creating new file") - } - defer dumpFile.Close() - - tw := tabwriter.NewWriter(dumpFile, 5, 0, 3, ' ', 0) - defer tw.Flush() - - // default to docker terms - headers := []string{ - "Name", - "Cores", - "Usage", - "Memory", - "Usage", - } - - // kubernetes rows will always have 6 items - // change column headers to reflect k8s terms - if len(rows[0]) == 7 { - headers = []string{ - "Name", - "Cores", - "Usage", - "Memory", - "Usage", - "Storage", - "Usage", - } - } - - fmt.Fprintf(tw, "%s\n", strings.Join(headers, "\t")) - for _, row := range rows { - values := []string{row[0], row[1], row[2], row[3], row[4]} - if len(row) == 7 { - values = append(values, row[5]) - values = append(values, row[6]) - } - fmt.Fprintf(tw, "%s\n", strings.Join(values, "\t")) - } - return nil -} - -func (m usageTableModel) copyRowToClipboard(row table.Row) { - var containerInfo string - - // default to docker headers - headers := []string{ - "Name", - "Cores", - "Usage", - "Memory", - "Usage", - } - - // kubernetes rows will always have 6 items - // change column headers to reflect k8s terms - if len(row) == 7 { - headers = []string{ - "Name", - "Cores", - "Usage", - "Memory", - "Usage", - "Storage", - "Usage", - } - } - - for i, header := range headers { - containerInfo += fmt.Sprintf("%s: %s\n", header, row[i]) - } - - clipboard.WriteAll(containerInfo) -} - -func UsageTable(columns []table.Column, rows []table.Row) { - t := table.New( - table.WithColumns(columns), - table.WithRows(rows), - table.WithFocused(true), - table.WithHeight(14), - ) - - s := table.DefaultStyles() - s.Header = s.Header. - BorderStyle(lipgloss.NormalBorder()). - BorderForeground(lipgloss.Color("240")). - BorderBottom(true). - Bold(false) - s.Selected = s.Selected. - Foreground(lipgloss.Color("229")). - Background(lipgloss.Color("57")). - Bold(false) - t.SetStyles(s) - - m := usageTableModel{t} - if _, err := tea.NewProgram(m).Run(); err != nil { - fmt.Println("Error running program:", err) - os.Exit(1) - } -} diff --git a/internal/scout/types.go b/internal/scout/types.go deleted file mode 100644 index 09bf11d2c9..0000000000 --- a/internal/scout/types.go +++ /dev/null @@ -1,44 +0,0 @@ -package scout - -import ( - "k8s.io/apimachinery/pkg/api/resource" - "k8s.io/client-go/kubernetes" - "k8s.io/client-go/rest" - metricsv "k8s.io/metrics/pkg/client/clientset/versioned" -) - -type Config struct { - Namespace string - Pod string - Output string - Warnings bool - RestConfig *rest.Config - K8sClient *kubernetes.Clientset - MetricsClient *metricsv.Clientset -} - -type ContainerMetrics struct { - PodName string - Limits map[string]Resources -} - -type Resources struct { - Cpu *resource.Quantity - Memory *resource.Quantity - Storage *resource.Quantity -} - -type UsageStats struct { - ContainerName string - CpuCores *resource.Quantity - Memory *resource.Quantity - Storage *resource.Quantity - CpuUsage float64 - MemoryUsage float64 - StorageUsage float64 -} - -type Advice struct { - Kind string - Msg string -} diff --git a/internal/scout/usage/k8s.go b/internal/scout/usage/k8s.go deleted file mode 100644 index c3805938a0..0000000000 --- a/internal/scout/usage/k8s.go +++ /dev/null @@ -1,164 +0,0 @@ -package usage - -import ( - "context" - "fmt" - - "github.com/charmbracelet/bubbles/table" - "github.com/sourcegraph/sourcegraph/lib/errors" - "github.com/sourcegraph/src-cli/internal/scout" - "github.com/sourcegraph/src-cli/internal/scout/kube" - "github.com/sourcegraph/src-cli/internal/scout/style" - - corev1 "k8s.io/api/core/v1" - "k8s.io/client-go/kubernetes" - restclient "k8s.io/client-go/rest" - metricsv "k8s.io/metrics/pkg/client/clientset/versioned" -) - -func K8s( - ctx context.Context, - clientSet *kubernetes.Clientset, - metricsClient *metricsv.Clientset, - restConfig *restclient.Config, - opts ...Option, -) error { - cfg := &scout.Config{ - Namespace: "default", - Pod: "", - RestConfig: restConfig, - K8sClient: clientSet, - MetricsClient: metricsClient, - } - - for _, opt := range opts { - opt(cfg) - } - - pods, err := kube.GetPods(ctx, cfg) - if err != nil { - return errors.Wrap(err, "could not get list of pods") - } - - if cfg.Pod != "" { - return renderSinglePodUsageTable(ctx, cfg, pods) - } - - return renderUsageTable(ctx, cfg, pods) -} - -// renderSinglePodUsageStats prints resource usage statistics for a single pod. -func renderSinglePodUsageTable(ctx context.Context, cfg *scout.Config, pods []corev1.Pod) error { - pod, err := kube.GetPod(cfg.Pod, pods) - if err != nil { - return errors.Wrapf(err, "could not get pod with name %s", cfg.Pod) - } - - containerMetrics := &scout.ContainerMetrics{ - PodName: cfg.Pod, - Limits: map[string]scout.Resources{}, - } - if err = kube.AddLimits(ctx, cfg, &pod, containerMetrics); err != nil { - return errors.Wrap(err, "failed to add limits to container metrics") - } - - columns := []table.Column{ - {Title: "Container", Width: 20}, - {Title: "Cores", Width: 10}, - {Title: "Usage(%)", Width: 10}, - {Title: "Memory", Width: 10}, - {Title: "Usage(%)", Width: 10}, - {Title: "Storage", Width: 10}, - {Title: "Usage(%)", Width: 10}, - } - var rows []table.Row - - podMetrics, err := kube.GetPodMetrics(ctx, cfg, pod) - if err != nil { - return errors.Wrap(err, "while attempting to fetch pod metrics") - } - - for _, container := range podMetrics.Containers { - stats, err := kube.GetUsage(ctx, cfg, *containerMetrics, pod, container) - if err != nil { - return errors.Wrapf(err, "could not compile usage data for row: %s\n", container.Name) - } - - row := makeRow(stats) - rows = append(rows, row) - } - - style.ResourceTable(columns, rows) - return nil -} - -// renderUsageTable renders a table displaying resource usage for pods. -func renderUsageTable(ctx context.Context, cfg *scout.Config, pods []corev1.Pod) error { - columns := []table.Column{ - {Title: "Container", Width: 20}, - {Title: "Cores", Width: 10}, - {Title: "Usage(%)", Width: 10}, - {Title: "Memory", Width: 10}, - {Title: "Usage(%)", Width: 10}, - {Title: "Storage", Width: 10}, - {Title: "Usage(%)", Width: 10}, - } - var rows []table.Row - - for _, pod := range pods { - containerMetrics := &scout.ContainerMetrics{ - PodName: pod.Name, - Limits: map[string]scout.Resources{}, - } - - if err := kube.AddLimits(ctx, cfg, &pod, containerMetrics); err != nil { - return errors.Wrap(err, "failed to get get container metrics") - } - - podMetrics, err := kube.GetPodMetrics(ctx, cfg, pod) - if err != nil { - return errors.Wrap(err, "while attempting to fetch pod metrics") - } - - for _, container := range podMetrics.Containers { - stats, err := kube.GetUsage(ctx, cfg, *containerMetrics, pod, container) - if err != nil { - return errors.Wrapf(err, "could not compile usage data for row %s\n", container.Name) - } - - row := makeRow(stats) - rows = append(rows, row) - } - } - - style.UsageTable(columns, rows) - return nil -} - -// makeRow generates a table row containing resource usage data for a container. -// It returns: -// - A table.Row containing the resource usage information -// - An error if there was an issue generating the row -func makeRow(usageStats scout.UsageStats) table.Row { - if usageStats.Storage == nil { - return table.Row{ - usageStats.ContainerName, - usageStats.CpuCores.String(), - fmt.Sprintf("%.2f%%", usageStats.CpuUsage), - usageStats.Memory.String(), - fmt.Sprintf("%.2f%%", usageStats.MemoryUsage), - "-", - "-", - } - } - - return table.Row{ - usageStats.ContainerName, - usageStats.CpuCores.String(), - fmt.Sprintf("%.2f%%", usageStats.CpuUsage), - usageStats.Memory.String(), - fmt.Sprintf("%.2f%%", usageStats.MemoryUsage), - usageStats.Storage.String(), - fmt.Sprintf("%.2f%%", usageStats.StorageUsage), - } -} diff --git a/internal/scout/usage/usage.go b/internal/scout/usage/usage.go deleted file mode 100644 index df4cb31b7a..0000000000 --- a/internal/scout/usage/usage.go +++ /dev/null @@ -1,19 +0,0 @@ -package usage - -import ( - "github.com/sourcegraph/src-cli/internal/scout" -) - -type Option = func(config *scout.Config) - -func WithNamespace(namespace string) Option { - return func(config *scout.Config) { - config.Namespace = namespace - } -} - -func WithPod(podname string) Option { - return func(config *scout.Config) { - config.Pod = podname - } -} diff --git a/internal/scout/usage/usage_test.go b/internal/scout/usage/usage_test.go deleted file mode 100644 index 14cc444b28..0000000000 --- a/internal/scout/usage/usage_test.go +++ /dev/null @@ -1,164 +0,0 @@ -package usage - -import ( - "testing" - - "github.com/sourcegraph/src-cli/internal/scout" - "github.com/sourcegraph/src-cli/internal/scout/kube" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/resource" -) - -func TestGetPercentage(t *testing.T) { - cases := []struct { - name string - x float64 - y float64 - want float64 - shouldError bool - }{ - { - name: "should return 0 if x is 0", - x: 0, - y: 1, - want: 0, - shouldError: false, - }, - { - name: "should return correct percentage", - x: 36, - y: 72, - want: 50, - shouldError: false, - }, - { - name: "should return correct percentage", - x: 75, - y: 100, - want: 75, - shouldError: false, - }, - { - name: "should return correct percentages over 100%", - x: 3800, - y: 2000, - want: 190, - shouldError: false, - }, - { - name: "should return 0 if y is 0", - x: 75, - y: 0, - want: 0, - shouldError: true, - }, - } - - for _, tc := range cases { - tc := tc - t.Run(tc.name, func(t *testing.T) { - got := scout.GetPercentage(tc.x, tc.y) - - if got != tc.want { - t.Errorf("got %.2f want %.2f", tc.want, got) - } - }) - } -} - -func TestGetRawUsage(t *testing.T) { - cases := []struct { - name string - cpu *resource.Quantity - mem *resource.Quantity - targetKey string - want float64 - shouldError bool - }{ - { - name: "return cpu usage in nanocores", - cpu: resource.NewQuantity(2756053, resource.Format("BinarySI")), - mem: resource.NewQuantity(838374, resource.Format("BinarySI")), - targetKey: "cpu", - want: 2756053, - shouldError: false, - }, - { - name: "return memory usage in KiB", - cpu: resource.NewQuantity(8926483, resource.Format("BinarySI")), - mem: resource.NewQuantity(2332343, resource.Format("BinarySI")), - targetKey: "memory", - want: 2332343, - shouldError: false, - }, - { - name: "should error with non-existant targetKey", - cpu: resource.NewQuantity(8, resource.Format("BinarySI")), - mem: resource.NewQuantity(2, resource.Format("BinarySI")), - targetKey: "mem", - want: 0, - shouldError: true, - }, - } - - for _, tc := range cases { - tc := tc - t.Run(tc.name, func(t *testing.T) { - resourceList := resourceListHelper(tc.cpu, tc.mem) - got, err := kube.GetRawUsage(resourceList, tc.targetKey) - if !tc.shouldError && err != nil { - t.Errorf("unexpected error: %v", err) - } - - want := tc.want - if got != want { - t.Errorf("got %v, want %v", got, want) - } - }) - } -} - -func TestContains(t *testing.T) { - cases := []struct { - name string - s []string - val string - want bool - }{ - { - name: "should return true if given slice contains given value", - s: []string{"this", "is", "a", "unit", "test"}, - val: "unit", - want: true, - }, - { - name: "should return false if given slice does not contains given value", - s: []string{"this", "is", "a", "unit", "test"}, - val: "foobar", - want: false, - }, - { - name: "should return true if given slice contains for than one instance of the given value", - s: []string{"this", "is", "a", "unit", "unit", "test", "unit"}, - val: "unit", - want: true, - }, - } - - for _, tc := range cases { - tc := tc - t.Run(tc.name, func(t *testing.T) { - got := scout.Contains(tc.s, tc.val) - if got != tc.want { - t.Errorf("got %v, want %v", got, tc.want) - } - }) - } -} - -func resourceListHelper(cpu *resource.Quantity, mem *resource.Quantity) corev1.ResourceList { - return corev1.ResourceList{ - corev1.ResourceCPU: *cpu, - corev1.ResourceMemory: *mem, - } -} From 6dfcb474ea09277543ed8ae74fe0741369877951 Mon Sep 17 00:00:00 2001 From: Keegan Carruthers-Smith Date: Tue, 11 Nov 2025 22:50:29 +0200 Subject: [PATCH 494/647] chore(ci): always use go version in .tool-versions (#1198) setup-go@v6 supports reading in .tool-versions which means we will now always run the same version we run in local dev. This is also a better version to use than go.mod since that is a minimum version. Note: they have not tagged a release for this support, but we want to use it. So for now we pin to the latest commit which supports it. Once there is a tagged release I will update the workflow files. Test Plan: CI --- .github/workflows/go-ci.yml | 5 ++--- .github/workflows/go-lint.yml | 4 ++-- .github/workflows/goreleaser-check.yml | 4 ++-- .github/workflows/goreleaser.yml | 4 ++-- .github/workflows/pr-auditor.yml | 4 ++-- .github/workflows/scip.yml | 4 ++-- 6 files changed, 12 insertions(+), 13 deletions(-) diff --git a/.github/workflows/go-ci.yml b/.github/workflows/go-ci.yml index 0d3acea806..bd79703fe1 100644 --- a/.github/workflows/go-ci.yml +++ b/.github/workflows/go-ci.yml @@ -11,16 +11,15 @@ jobs: go-test: strategy: matrix: - go-version: ['1.25'] os: [ubuntu-latest, macos-latest, windows-latest] runs-on: ${{ matrix.os }} steps: - name: Checkout uses: actions/checkout@v4 - name: Set up Go - uses: actions/setup-go@v5 + uses: actions/setup-go@faf52423ec0d44c58f68e83b614bfcd99dded66f with: - go-version: ${{ matrix.go-version }} + go-version-file: '.tool-versions' - name: (Windows) Enable pulling Go modules from private sourcegraph/sourcegraph if: runner.os == 'Windows' run: git config --global url."https://$env:PRIVATE_TOKEN@github.com/sourcegraph/".insteadOf "https://github.com/sourcegraph/" diff --git a/.github/workflows/go-lint.yml b/.github/workflows/go-lint.yml index 7c99b5999f..4fe3c4fca4 100644 --- a/.github/workflows/go-lint.yml +++ b/.github/workflows/go-lint.yml @@ -14,9 +14,9 @@ jobs: - name: Checkout uses: actions/checkout@v4 - name: Set up Go - uses: actions/setup-go@v5 + uses: actions/setup-go@faf52423ec0d44c58f68e83b614bfcd99dded66f with: - go-version: '1.25' + go-version-file: '.tool-versions' - name: Enable pulling Go modules from private sourcegraph/sourcegraph run: git config --global url."https://${PRIVATE_TOKEN}@github.com/sourcegraph/".insteadOf "https://github.com/sourcegraph/" - run: ./dev/go-lint.sh diff --git a/.github/workflows/goreleaser-check.yml b/.github/workflows/goreleaser-check.yml index 45d5c46e47..43209622cd 100644 --- a/.github/workflows/goreleaser-check.yml +++ b/.github/workflows/goreleaser-check.yml @@ -17,9 +17,9 @@ jobs: with: fetch-depth: 0 - name: Set up Go - uses: actions/setup-go@v5 + uses: actions/setup-go@faf52423ec0d44c58f68e83b614bfcd99dded66f with: - go-version: '1.25' + go-version-file: '.tool-versions' - name: Enable pulling Go modules from private sourcegraph/sourcegraph run: git config --global url."https://${PRIVATE_TOKEN}@github.com/sourcegraph/".insteadOf "https://github.com/sourcegraph/" - name: Check GoReleaser config diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index 72a4a0f825..588d5e9d90 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -179,9 +179,9 @@ jobs: with: fetch-depth: 0 - name: Set up Go - uses: actions/setup-go@v5 + uses: actions/setup-go@faf52423ec0d44c58f68e83b614bfcd99dded66f with: - go-version: 1.25 + go-version-file: '.tool-versions' - name: Enable pulling Go modules from private sourcegraph/sourcegraph run: git config --global url."https://${PRIVATE_TOKEN}@github.com/sourcegraph/".insteadOf "https://github.com/sourcegraph/" - run: go test ./... diff --git a/.github/workflows/pr-auditor.yml b/.github/workflows/pr-auditor.yml index fe0862e021..c338878bd9 100644 --- a/.github/workflows/pr-auditor.yml +++ b/.github/workflows/pr-auditor.yml @@ -13,8 +13,8 @@ jobs: with: repository: 'sourcegraph/devx-service' token: ${{ secrets.PR_AUDITOR_TOKEN }} - - uses: actions/setup-go@v5 - with: { go-version: '1.23' } + - uses: actions/setup-go@faf52423ec0d44c58f68e83b614bfcd99dded66f + with: { go-version-file: '.tool-versions' } - run: 'go run ./cmd/pr-auditor' env: diff --git a/.github/workflows/scip.yml b/.github/workflows/scip.yml index 2df5a1e5c1..2d380ae660 100644 --- a/.github/workflows/scip.yml +++ b/.github/workflows/scip.yml @@ -12,9 +12,9 @@ jobs: steps: - uses: actions/checkout@v4 - name: Set up Go - uses: actions/setup-go@v5 + uses: actions/setup-go@faf52423ec0d44c58f68e83b614bfcd99dded66f with: - go-version: 1.25 + go-version-file: '.tool-versions' - name: Set directory to safe for git run: git config --global --add safe.directory $GITHUB_WORKSPACE From 85fc546539757cc38cdeb62d5988d35c7573b035 Mon Sep 17 00:00:00 2001 From: Keegan Carruthers-Smith Date: Tue, 11 Nov 2025 23:03:48 +0200 Subject: [PATCH 495/647] Fix: -h / --help now show usage text for subcommands (#1195) Previously we special cased --help only for the first level of subcommands. However, this broke for example if you did "src snapshot upload --help". So instead we normalize our command line arguments so that if a user does "--help" we see "-help". We can then rely on go's stdlib flag parser to do the right thing w.r.t. sub commands/etc. Test Plan: ran with --help in a few different places and observed good behaviour. --- cmd/src/cmd.go | 11 ----------- cmd/src/main.go | 17 ++++++++++++++++- 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/cmd/src/cmd.go b/cmd/src/cmd.go index 95c16e6e0e..d0b20efb1c 100644 --- a/cmd/src/cmd.go +++ b/cmd/src/cmd.go @@ -5,7 +5,6 @@ import ( "fmt" "log" "os" - "slices" "github.com/sourcegraph/src-cli/internal/cmderrors" ) @@ -86,16 +85,6 @@ func (c commander) run(flagSet *flag.FlagSet, cmdName, usageText string, args [] log.Fatal("reading config: ", err) } - // Print help to stdout if requested - if slices.IndexFunc(args, func(s string) bool { - return s == "--help" - }) >= 0 { - cmd.flagSet.SetOutput(os.Stdout) - flag.CommandLine.SetOutput(os.Stdout) - cmd.flagSet.Usage() - os.Exit(0) - } - // Parse subcommand flags. args := flagSet.Args()[1:] if err := cmd.flagSet.Parse(args); err != nil { diff --git a/cmd/src/main.go b/cmd/src/main.go index 38c63afa45..fa2e234138 100644 --- a/cmd/src/main.go +++ b/cmd/src/main.go @@ -9,6 +9,7 @@ import ( "net/url" "os" "path/filepath" + "slices" "strings" "github.com/sourcegraph/sourcegraph/lib/errors" @@ -89,7 +90,21 @@ func main() { log.SetFlags(0) log.SetPrefix("") - commands.run(flag.CommandLine, "src", usageText, os.Args[1:]) + commands.run(flag.CommandLine, "src", usageText, normalizeDashHelp(os.Args[1:])) +} + +// normalizeDashHelp converts --help to -help since Go's flag parser only supports single dash. +func normalizeDashHelp(args []string) []string { + args = slices.Clone(args) + for i, arg := range args { + if arg == "--" { + break + } + if arg == "--help" { + args[i] = "-help" + } + } + return args } var cfg *config From 0621d3474c4792e13ca2e3f6f4adb57e4187dd3e Mon Sep 17 00:00:00 2001 From: Marc <7050295+marcleblanc2@users.noreply.github.com> Date: Wed, 12 Nov 2025 00:10:31 -0700 Subject: [PATCH 496/647] Chore: Fix pg_dump args (#1193) Add --quote-all-identifiers to improve cross-Postgres-version imports, and improve readability --- internal/pgdump/pgdump.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/pgdump/pgdump.go b/internal/pgdump/pgdump.go index 1a3530a065..05d916b16b 100644 --- a/internal/pgdump/pgdump.go +++ b/internal/pgdump/pgdump.go @@ -42,7 +42,7 @@ func RestoreCommand(t Target) string { // DumpCommand generates a pg_dump command that can be used for on-prem-to-Cloud migrations. func DumpCommand(t Target) string { - dump := fmt.Sprintf("pg_dump --no-owner --format=p --no-acl --clean --if-exists --username=%s --dbname=%s", + dump := fmt.Sprintf("pg_dump --clean --format=plain --if-exists --no-acl --no-owner --quote-all-identifiers --username=%s --dbname=%s", t.Username, t.DBName) if t.Password == "" { return dump From f6555cbd8f70bbb927cda7300f04683ea44336ae Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Thu, 13 Nov 2025 16:25:44 +0200 Subject: [PATCH 497/647] remove pr auditor (#1199) --- .github/workflows/pr-auditor.yml | 23 ----------------------- 1 file changed, 23 deletions(-) delete mode 100644 .github/workflows/pr-auditor.yml diff --git a/.github/workflows/pr-auditor.yml b/.github/workflows/pr-auditor.yml deleted file mode 100644 index c338878bd9..0000000000 --- a/.github/workflows/pr-auditor.yml +++ /dev/null @@ -1,23 +0,0 @@ -# See https://docs.sourcegraph.com/dev/background-information/ci#pr-auditor -name: pr-auditor -on: - pull_request_target: - types: [ closed, edited, opened, synchronize, ready_for_review ] - - -jobs: - check-pr: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - with: - repository: 'sourcegraph/devx-service' - token: ${{ secrets.PR_AUDITOR_TOKEN }} - - uses: actions/setup-go@faf52423ec0d44c58f68e83b614bfcd99dded66f - with: { go-version-file: '.tool-versions' } - - - run: 'go run ./cmd/pr-auditor' - env: - GITHUB_EVENT_PATH: ${{ env.GITHUB_EVENT_PATH }} - GITHUB_TOKEN: ${{ secrets.PR_AUDITOR_TOKEN }} - GITHUB_RUN_URL: https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }} From a6805a6030a24cd1274181b37c62db049892224c Mon Sep 17 00:00:00 2001 From: Keegan Carruthers-Smith Date: Fri, 14 Nov 2025 17:20:53 +0200 Subject: [PATCH 498/647] refactor(servegit): vendor in lib/gitservice (#1200) This is the only use of gitservice so lets just vendor it in. Test Plan: go test --- internal/servegit/gitservice.go | 173 +++++++++++++++++++++++++++ internal/servegit/gitservice_test.go | 106 ++++++++++++++++ internal/servegit/serve.go | 7 +- 3 files changed, 282 insertions(+), 4 deletions(-) create mode 100644 internal/servegit/gitservice.go create mode 100644 internal/servegit/gitservice_test.go diff --git a/internal/servegit/gitservice.go b/internal/servegit/gitservice.go new file mode 100644 index 0000000000..9c815ba9ca --- /dev/null +++ b/internal/servegit/gitservice.go @@ -0,0 +1,173 @@ +// package servegit provides a smart Git HTTP transfer protocol handler. +package servegit + +import ( + "bytes" + "compress/gzip" + "context" + "net/http" + "os" + "os/exec" + "strconv" + "strings" + + "slices" + + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +var uploadPackArgs = []string{ + // Partial clones/fetches + "-c", "uploadpack.allowFilter=true", + + // Can fetch any object. Used in case of race between a resolve ref and a + // fetch of a commit. Safe to do, since this is only used internally. + "-c", "uploadpack.allowAnySHA1InWant=true", + + // The maximum size of memory that is consumed by each thread in git-pack-objects[1] + // for pack window memory when no limit is given on the command line. + // + // Important for large monorepos to not run into memory issues when cloned. + "-c", "pack.windowMemory=100m", + + "upload-pack", + + "--stateless-rpc", "--strict", +} + +// Handler is a smart Git HTTP transfer protocol as documented at +// https://www.git-scm.com/docs/http-protocol. +// +// This allows users to clone any git repo. We only support the smart +// protocol. We aim to support modern git features such as protocol v2 to +// minimize traffic. +type Handler struct { + // Dir is a function which takes a repository name and returns an absolute + // path to the GIT_DIR for it. + Dir func(context.Context, string) (string, error) + + // ErrorHook is called if we fail to run the git command. The main use of + // this is to inject logging. For example in src-cli we don't use + // sourcegraph/log so this allows us to use stdlib log. + // + // Note: This is required to be set + ErrorHook func(err error, stderr string) + + // CommandHook if non-nil will run with the git upload command before we + // start the command. + // + // This allows the command to be modified before running. In practice + // sourcegraph.com will add a flowrated writer for Stdout to treat our + // internal networks more kindly. + CommandHook func(*exec.Cmd) + + // Trace if non-nil is called at the start of serving a request. It will + // call the returned function when done executing. If the executation + // failed, it will pass in a non-nil error. + Trace func(ctx context.Context, svc, repo, protocol string) func(error) +} + +func (s *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + // Only support clones and fetches (git upload-pack). /info/refs sets the + // service field. + if svcQ := r.URL.Query().Get("service"); svcQ != "" && svcQ != "git-upload-pack" { + http.Error(w, "only support service git-upload-pack", http.StatusBadRequest) + return + } + + var repo, svc string + for _, suffix := range []string{"/info/refs", "/git-upload-pack"} { + if strings.HasSuffix(r.URL.Path, suffix) { + svc = suffix + repo = strings.TrimSuffix(r.URL.Path, suffix) + repo = strings.TrimPrefix(repo, "/") + break + } + } + + dir, err := s.Dir(ctx, repo) + if err != nil { + http.Error(w, "failed to determine repository path: "+err.Error(), http.StatusInternalServerError) + return + } + + if _, err = os.Stat(dir); os.IsNotExist(err) { + http.Error(w, "repository not found", http.StatusNotFound) + return + } else if err != nil { + http.Error(w, "failed to stat repo: "+err.Error(), http.StatusInternalServerError) + return + } + + body := r.Body + defer body.Close() + + if r.Header.Get("Content-Encoding") == "gzip" { + gzipReader, err := gzip.NewReader(body) + if err != nil { + http.Error(w, "malformed payload: "+err.Error(), http.StatusBadRequest) + return + } + defer gzipReader.Close() + + body = gzipReader + } + + // err is set if we fail to run command or have an unexpected svc. It is + // captured for tracing. + if s.Trace != nil { + done := s.Trace(ctx, svc, repo, r.Header.Get("Git-Protocol")) + defer func() { + done(err) + }() + } + + args := slices.Clone(uploadPackArgs) + switch svc { + case "/info/refs": + w.Header().Set("Content-Type", "application/x-git-upload-pack-advertisement") + _, _ = w.Write(packetWrite("# service=git-upload-pack\n")) + _, _ = w.Write([]byte("0000")) + args = append(args, "--advertise-refs") + case "/git-upload-pack": + w.Header().Set("Content-Type", "application/x-git-upload-pack-result") + default: + err = errors.Errorf("unexpected subpath (want /info/refs or /git-upload-pack): %q", svc) + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + args = append(args, dir) + + env := os.Environ() + if protocol := r.Header.Get("Git-Protocol"); protocol != "" { + env = append(env, "GIT_PROTOCOL="+protocol) + } + + var stderr bytes.Buffer + cmd := exec.CommandContext(ctx, "git", args...) + cmd.Env = env + cmd.Stdout = w + cmd.Stderr = &stderr + cmd.Stdin = body + + if s.CommandHook != nil { + s.CommandHook(cmd) + } + + err = cmd.Run() + if err != nil { + err = errors.Errorf("error running git service command args=%q: %w", args, err) + s.ErrorHook(err, stderr.String()) + _, _ = w.Write([]byte("\n" + err.Error() + "\n")) + } +} + +func packetWrite(str string) []byte { + s := strconv.FormatInt(int64(len(str)+4), 16) + if len(s)%4 != 0 { + s = strings.Repeat("0", 4-len(s)%4) + s + } + return []byte(s + str) +} diff --git a/internal/servegit/gitservice_test.go b/internal/servegit/gitservice_test.go new file mode 100644 index 0000000000..e1b7b87083 --- /dev/null +++ b/internal/servegit/gitservice_test.go @@ -0,0 +1,106 @@ +package servegit + +import ( + "bytes" + "context" + "fmt" + "net/http/httptest" + "os/exec" + "path/filepath" + "strings" + "testing" +) + +// numTestCommits determines the number of files/commits/tags to create for +// the local test repo. The value of 25 causes clonev1 and clonev2 to use gzip +// compression but shallow to be uncompressed. The value of 10 does not trigger +// this same behavior. +const numTestCommits = 25 + +func TestHandler(t *testing.T) { + root := t.TempDir() + repo := filepath.Join(root, "testrepo") + + // Setup a repo with a commit so we can add bad refs + runCmd(t, root, "git", "init", repo) + + for i := range numTestCommits { + runCmd(t, repo, "sh", "-c", fmt.Sprintf("echo hello world > hello-%d.txt", i+1)) + runCmd(t, repo, "git", "add", fmt.Sprintf("hello-%d.txt", i+1)) + runCmd(t, repo, "git", "commit", "-m", fmt.Sprintf("c%d", i+1)) + runCmd(t, repo, "git", "tag", fmt.Sprintf("v%d", i+1)) + } + + ts := httptest.NewServer(&Handler{ + Dir: func(_ context.Context, s string) (string, error) { + return filepath.Join(root, s, ".git"), nil + }, + }) + defer ts.Close() + + t.Run("404", func(t *testing.T) { + c := exec.Command("git", "clone", ts.URL+"/doesnotexist") + c.Dir = t.TempDir() + b, err := c.CombinedOutput() + if !bytes.Contains(b, []byte("repository not found")) { + t.Fatal("expected clone to fail with repository not found", string(b), err) + } + }) + + cloneURL := ts.URL + "/testrepo" + + t.Run("clonev1", func(t *testing.T) { + runCmd(t, t.TempDir(), "git", "-c", "protocol.version=1", "clone", cloneURL) + }) + + cloneV2 := []struct { + Name string + Args []string + }{{ + "clonev2", + []string{}, + }, { + "shallow", + []string{"--depth=1"}, + }} + + for _, tc := range cloneV2 { + t.Run(tc.Name, func(t *testing.T) { + args := []string{"-c", "protocol.version=2", "clone"} + args = append(args, tc.Args...) + args = append(args, cloneURL) + + c := exec.Command("git", args...) + c.Dir = t.TempDir() + c.Env = []string{ + "GIT_TRACE_PACKET=1", + } + b, err := c.CombinedOutput() + if err != nil { + t.Fatalf("command failed: %s\nOutput: %s", err, b) + } + + // This is the same test done by git's tests for checking if the + // server is using protocol v2. + if !bytes.Contains(b, []byte("git< version 2")) { + t.Fatalf("protocol v2 not used by server. Output:\n%s", b) + } + }) + } +} + +func runCmd(t *testing.T, dir string, cmd string, arg ...string) { + t.Helper() + c := exec.Command(cmd, arg...) + c.Dir = dir + c.Env = []string{ + "GIT_COMMITTER_NAME=a", + "GIT_COMMITTER_EMAIL=a@a.com", + "GIT_AUTHOR_NAME=a", + "GIT_AUTHOR_EMAIL=a@a.com", + } + b, err := c.CombinedOutput() + if err != nil { + t.Fatalf("%s %s failed: %s\nOutput: %s", cmd, strings.Join(arg, " "), err, b) + } +} diff --git a/internal/servegit/serve.go b/internal/servegit/serve.go index 306bc67aa4..22286531e5 100644 --- a/internal/servegit/serve.go +++ b/internal/servegit/serve.go @@ -16,7 +16,6 @@ import ( "time" "github.com/sourcegraph/sourcegraph/lib/errors" - "github.com/sourcegraph/sourcegraph/lib/gitservice" ) type Serve struct { @@ -102,9 +101,9 @@ func (s *Serve) handler() http.Handler { }) fs := http.FileServer(http.Dir(s.Root)) - svc := &gitservice.Handler{ - Dir: func(name string) string { - return filepath.Join(s.Root, filepath.FromSlash(name)) + svc := &Handler{ + Dir: func(_ context.Context, name string) (string, error) { + return filepath.Join(s.Root, filepath.FromSlash(name)), nil }, ErrorHook: func(err error, stderr string) { s.Info.Printf("git-service error: %s\nstderr:\n%s", err.Error(), stderr) From 759cc5fc11353704486844bf4954a67aeae419b3 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Sun, 16 Nov 2025 17:39:17 +0100 Subject: [PATCH 499/647] Run go mod tidy (#1201) --- go.mod | 14 +------------- go.sum | 37 ------------------------------------- 2 files changed, 1 insertion(+), 50 deletions(-) diff --git a/go.mod b/go.mod index 678a2cd4e8..c1028d1880 100644 --- a/go.mod +++ b/go.mod @@ -4,13 +4,10 @@ go 1.23.12 require ( cloud.google.com/go/storage v1.30.1 - github.com/atotto/clipboard v0.1.4 github.com/aws/aws-sdk-go-v2/config v1.18.13 github.com/aws/aws-sdk-go-v2/service/ec2 v1.86.0 github.com/aws/aws-sdk-go-v2/service/eks v1.27.3 github.com/aws/aws-sdk-go-v2/service/iam v1.19.3 - github.com/charmbracelet/bubbles v0.15.0 - github.com/charmbracelet/lipgloss v0.7.1 github.com/creack/goselect v0.1.2 github.com/derision-test/glock v1.0.0 github.com/dineshappavoo/basex v0.0.0-20170425072625-481a6f6dc663 @@ -41,21 +38,18 @@ require ( k8s.io/api v0.32.3 k8s.io/apimachinery v0.32.3 k8s.io/client-go v0.32.3 - k8s.io/metrics v0.32.3 ) require ( github.com/fxamacker/cbor/v2 v2.7.0 // indirect github.com/google/gnostic-models v0.6.8 // indirect github.com/google/s2a-go v0.1.4 // indirect - github.com/gorilla/websocket v1.5.3 // indirect github.com/jackc/chunkreader/v2 v2.0.1 // indirect github.com/jackc/pgconn v1.14.3 // indirect github.com/jackc/pgio v1.0.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgproto3/v2 v2.3.3 // indirect github.com/jackc/pgservicefile v0.0.0-20231201235250-de7065d80cb9 // indirect - github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f // indirect github.com/x448/float16 v0.8.4 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20231016165738-49dd2c1f3d0b // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20231106174013-bbf56f31fb17 // indirect @@ -85,12 +79,10 @@ require ( github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect github.com/aymerick/douceur v0.2.0 // indirect github.com/bufbuild/buf v1.4.0 // indirect - github.com/charmbracelet/bubbletea v0.23.1 // direct github.com/charmbracelet/glamour v0.5.0 // indirect github.com/cockroachdb/errors v1.11.1 // indirect github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect github.com/cockroachdb/redact v1.1.5 // indirect - github.com/containerd/console v1.0.3 // indirect github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/dlclark/regexp2 v1.8.0 // indirect @@ -130,17 +122,13 @@ require ( github.com/lucasb-eyer/go-colorful v1.2.0 // indirect github.com/mailru/easyjson v0.7.7 // indirect github.com/mattn/go-colorable v0.1.13 // indirect - github.com/mattn/go-localereader v0.0.1 // indirect github.com/mattn/go-runewidth v0.0.14 // indirect github.com/microcosm-cc/bluemonday v1.0.23 // indirect github.com/mitchellh/copystructure v1.2.0 // indirect github.com/mitchellh/reflectwalk v1.0.2 // indirect - github.com/moby/spdystream v0.5.0 // indirect github.com/moby/term v0.0.0-20221205130635-1aeaba878587 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect - github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b // indirect - github.com/muesli/cancelreader v0.2.2 // indirect github.com/muesli/reflow v0.3.0 // indirect github.com/muesli/termenv v0.15.1 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect @@ -181,7 +169,7 @@ require ( google.golang.org/appengine v1.6.7 // indirect google.golang.org/genproto v0.0.0-20231030173426-d783a09b4405 // indirect google.golang.org/grpc v1.59.0 // indirect - gopkg.in/inf.v0 v0.9.1 // direct + gopkg.in/inf.v0 v0.9.1 // indirect; direct gopkg.in/yaml.v2 v2.4.0 // indirect k8s.io/klog/v2 v2.130.1 // indirect k8s.io/kube-openapi v0.0.0-20241105132330-32ad38e42d3f // indirect diff --git a/go.sum b/go.sum index 7680436b99..d1f4a1f59c 100644 --- a/go.sum +++ b/go.sum @@ -20,10 +20,6 @@ github.com/Masterminds/sprig v2.22.0+incompatible/go.mod h1:y6hNFY5UBTIWBxnzTeuN github.com/alecthomas/chroma v0.10.0 h1:7XDcGkCQopCNKjZHfYrNLraA+M7e0fMiJ/Mfikbfjek= github.com/alecthomas/chroma v0.10.0/go.mod h1:jtJATyUxlIORhUOFNA9NZDWGAQ8wpxQQqNSB4rjA/1s= github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= -github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio= -github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs= -github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4= -github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI= github.com/aws/aws-sdk-go-v2 v1.17.4/go.mod h1:uzbQtefpm44goOPmdKyAlXSNcwlRgF3ePWVW6EtJvvw= github.com/aws/aws-sdk-go-v2 v1.17.5 h1:TzCUW1Nq4H8Xscph5M/skINUitxM5UBAyvm2s7XBzL4= github.com/aws/aws-sdk-go-v2 v1.17.5/go.mod h1:uzbQtefpm44goOPmdKyAlXSNcwlRgF3ePWVW6EtJvvw= @@ -57,7 +53,6 @@ github.com/aws/aws-sdk-go-v2/service/sts v1.18.3 h1:s49mSnsBZEXjfGBkRfmK+nPqzT7L github.com/aws/aws-sdk-go-v2/service/sts v1.18.3/go.mod h1:b+psTJn33Q4qGoDaM7ZiOVVG8uVjGI6HaZ8WBHdgDgU= github.com/aws/smithy-go v1.13.5 h1:hgz0X/DX0dGqTYpGALqXJoRKRj5oQ7150i5FdTePzO8= github.com/aws/smithy-go v1.13.5/go.mod h1:Tg+OJXh4MB2R/uN61Ko2f6hTZwB/ZYGOtib8J3gBHzA= -github.com/aymanbagabas/go-osc52 v1.0.3/go.mod h1:zT8H+Rk4VSabYN90pWyugflM3ZhpTZNC7cASDfUCdT4= github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k= github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8= github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk= @@ -68,16 +63,8 @@ github.com/bufbuild/buf v1.4.0 h1:GqE3a8CMmcFvWPzuY3Mahf9Kf3S9XgZ/ORpfYFzO+90= github.com/bufbuild/buf v1.4.0/go.mod h1:mwHG7klTHnX+rM/ym8LXGl7vYpVmnwT96xWoRB4H5QI= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= -github.com/charmbracelet/bubbles v0.15.0 h1:c5vZ3woHV5W2b8YZI1q7v4ZNQaPetfHuoHzx+56Z6TI= -github.com/charmbracelet/bubbles v0.15.0/go.mod h1:Y7gSFbBzlMpUDR/XM9MhZI374Q+1p1kluf1uLl8iK74= -github.com/charmbracelet/bubbletea v0.23.1 h1:CYdteX1wCiCzKNUlwm25ZHBIc1GXlYFyUIte8WPvhck= -github.com/charmbracelet/bubbletea v0.23.1/go.mod h1:JAfGK/3/pPKHTnAS8JIE2u9f61BjWTQY57RbT25aMXU= github.com/charmbracelet/glamour v0.5.0 h1:wu15ykPdB7X6chxugG/NNfDUbyyrCLV9XBalj5wdu3g= github.com/charmbracelet/glamour v0.5.0/go.mod h1:9ZRtG19AUIzcTm7FGLGbq3D5WKQ5UyZBbQsMQN0XIqc= -github.com/charmbracelet/harmonica v0.2.0/go.mod h1:KSri/1RMQOZLbw7AHqgcBycp8pgJnQMYYT8QZRqZ1Ao= -github.com/charmbracelet/lipgloss v0.6.0/go.mod h1:tHh2wr34xcHjC2HCXIlGSG1jaDF0S0atAUvBMP6Ppuk= -github.com/charmbracelet/lipgloss v0.7.1 h1:17WMwi7N1b1rVWOjMT+rCh7sQkvDU75B2hbZpc5Kc1E= -github.com/charmbracelet/lipgloss v0.7.1/go.mod h1:yG0k3giv8Qj8edTCbbg6AlQ5e8KNWpFujkNawKNhE2c= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= @@ -91,8 +78,6 @@ github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b h1:r6VH0faHjZe github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= github.com/cockroachdb/redact v1.1.5 h1:u1PMllDkdFfPWaNGMyLD1+so+aq3uUItthCFqzwPJ30= github.com/cockroachdb/redact v1.1.5/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= -github.com/containerd/console v1.0.3 h1:lIr7SlA5PxZyMV30bDW0MGbiOPXwc63yRuCP0ARubLw= -github.com/containerd/console v1.0.3/go.mod h1:7LqA/THxQ86k76b8c/EMSiaJ3h1eZkMkXar0TQ1gf3U= github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w= github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/creack/goselect v0.1.2 h1:2DNy14+JPjRBgPzAd1thbQp4BSIihxcBf0IXhQXDRa0= @@ -211,8 +196,6 @@ github.com/googleapis/gax-go/v2 v2.12.0 h1:A+gCJKdRfqXkr+BIRGtZLibNXf0m1f9E4HG56 github.com/googleapis/gax-go/v2 v2.12.0/go.mod h1:y+aIqrI5eb1YGMVJfuV3185Ts/D7qKpsEkdD5+I6QGU= github.com/gorilla/css v1.0.0 h1:BQqNyPTi50JCFMTw/b67hByjMVXZRwGha6wxVGkeihY= github.com/gorilla/css v1.0.0/go.mod h1:Dn721qIggHpt4+EFCcTLTU/vk5ySda2ReITrtgBl60c= -github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= -github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/grafana/regexp v0.0.0-20221123153739-15dc172cd2db h1:7aN5cccjIqCLTzedH7MZzRZt5/lsAHch6Z3L2ZGn5FA= github.com/grafana/regexp v0.0.0-20221123153739-15dc172cd2db/go.mod h1:M5qHK+eWfAv8VR/265dIuEpL3fNfeC21tXXp9itM24A= github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= @@ -284,7 +267,6 @@ github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= -github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= @@ -298,10 +280,7 @@ github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27k github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= -github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4= -github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88= github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= -github.com/mattn/go-runewidth v0.0.10/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk= github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk= github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU= @@ -313,8 +292,6 @@ github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa1 github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s= github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ= github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= -github.com/moby/spdystream v0.5.0 h1:7r0J1Si3QO/kjRitvSLVVFUjxMEb/YLj6S9FF62JBCU= -github.com/moby/spdystream v0.5.0/go.mod h1:xBAYlnt/ay+11ShkdFKNAG7LsyK/tmNBVvVOwrfMgdI= github.com/moby/term v0.0.0-20221205130635-1aeaba878587 h1:HfkjXDfhgVaN5rmueG8cL8KKeFNecRCXFhaJ2qZ5SKA= github.com/moby/term v0.0.0-20221205130635-1aeaba878587/go.mod h1:8FzsFHVUBGZdbDsJw/ot+X+d5HLUbvklYLJ9uGfcI3Y= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -322,24 +299,15 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= -github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b h1:1XF24mVaiu7u+CFywTdcDo2ie1pzzhwjt6RHqzpMU34= -github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b/go.mod h1:fQuZ0gauxyBcmsdE3ZT4NasjaRdxmbCS0jRHsrWu3Ho= -github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA= -github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo= -github.com/muesli/reflow v0.2.1-0.20210115123740-9e1d0d53df68/go.mod h1:Xk+z4oIWdQqJzsxyjgl3P22oYZnHdZ8FFTHAQQt5BMQ= github.com/muesli/reflow v0.3.0 h1:IFsN6K9NfGtjeggFP+68I4chLZV2yIKsXJFNZ+eWh6s= github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKtnHY/8= github.com/muesli/termenv v0.9.0/go.mod h1:R/LzAKf+suGs4IsO95y7+7DpFHO0KABgnZqtlyx2mBw= -github.com/muesli/termenv v0.11.1-0.20220204035834-5ac8409525e0/go.mod h1:Bd5NYQ7pd+SrtBSrSNoBBmXlcY8+Xj4BMJgh8qcZrvs= -github.com/muesli/termenv v0.13.0/go.mod h1:sP1+uffeLaEYpyOTb8pLCUctGcGLnoFjSn4YJK5e2bc= github.com/muesli/termenv v0.15.1 h1:UzuTb/+hhlBugQz28rpzey4ZuKcZ03MeKsoG7IJZIxs= github.com/muesli/termenv v0.15.1/go.mod h1:HeAQPTzpfs016yGtA4g00CsdYnVLJvxsS4ANqrZs2sQ= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/mwitkow/go-proto-validators v0.3.2 h1:qRlmpTzm2pstMKKzTdvwPCF5QfBNURSlAgN/R+qbKos= github.com/mwitkow/go-proto-validators v0.3.2/go.mod h1:ej0Qp0qMgHN/KtDyUt+Q1/tA7a5VarXUOUxD+oeD30w= -github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f h1:y5//uYreIhSUg3J1GEMiLbxo1LJaP8RfCpH6pymGZus= -github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f/go.mod h1:ZdcZmHo+o7JKHSa8/e818NopupXU1YMK5fe1lsApnBw= github.com/neelance/parallel v0.0.0-20160708114440-4de9ce63d14c h1:NZOii9TDGRAfCS5VM16XnF4K7afoLQmIiZX8EkKnxtE= github.com/neelance/parallel v0.0.0-20160708114440-4de9ce63d14c/go.mod h1:eTBvSIlRgLo+CNFFQRQTwUGTZOEdvXIKeZS/xG+D2yU= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= @@ -379,7 +347,6 @@ github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= -github.com/sahilm/fuzzy v0.1.0/go.mod h1:VFvziUEIMCrT6A6tw2RFIXPXXmzXbOsSHF0DOI8ZK9Y= github.com/shurcooL/go v0.0.0-20180423040247-9e1955d9fb6e/go.mod h1:TDJrrUr11Vxrven61rcy3hJMUqaf/CLWYhHNPmT14Lk= github.com/shurcooL/go-goon v0.0.0-20170922171312-37c2f522c041/go.mod h1:N5mDOmsrJOB+vfqUK+7DmDyjhSLIIBnXo9lvZJj3MWQ= github.com/sourcegraph/conc v0.3.1-0.20240108182409-4afefce20f9b h1:0FsjN+u9fNXTS2C1JnJ6G/gkgcUg8dscyyfu3PwHWUQ= @@ -507,13 +474,11 @@ golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210616045830-e2b7044e8c71/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220204135822-1c1b9b1eba6a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -632,8 +597,6 @@ k8s.io/klog/v2 v2.130.1 h1:n9Xl7H1Xvksem4KFG4PYbdQCQxqc/tTUyrgXaOhHSzk= k8s.io/klog/v2 v2.130.1/go.mod h1:3Jpz1GvMt720eyJH1ckRHK1EDfpxISzJ7I9OYgaDtPE= k8s.io/kube-openapi v0.0.0-20241105132330-32ad38e42d3f h1:GA7//TjRY9yWGy1poLzYYJJ4JRdzg3+O6e8I+e+8T5Y= k8s.io/kube-openapi v0.0.0-20241105132330-32ad38e42d3f/go.mod h1:R/HEjbvWI0qdfb8viZUeVZm0X6IZnxAydC7YU42CMw4= -k8s.io/metrics v0.32.3 h1:2vsBvw0v8rIIlczZ/lZ8Kcqk9tR6Fks9h+dtFNbc2a4= -k8s.io/metrics v0.32.3/go.mod h1:9R1Wk5cb+qJpCQon9h52mgkVCcFeYxcY+YkumfwHVCU= k8s.io/utils v0.0.0-20241104100929-3ea5e8cea738 h1:M3sRQVHv7vB20Xc2ybTt7ODCeFj6JSWYFzOFnYeS6Ro= k8s.io/utils v0.0.0-20241104100929-3ea5e8cea738/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= mvdan.cc/gofumpt v0.4.0 h1:JVf4NN1mIpHogBj7ABpgOyZc65/UUOkKQFkoURsz4MM= From 7cb402a6c3730d375ec167ab295d331d855fa5a4 Mon Sep 17 00:00:00 2001 From: Keegan Carruthers-Smith Date: Tue, 18 Nov 2025 09:47:38 +0200 Subject: [PATCH 500/647] vendor in lib from sourcegraph (#1202) We no longer need to point at an old version of lib. Instead we create a script which copies over the subset of lib we use. This is a temporary solution. We likely need to publish this library somewhere as open source instead. --- cmd/src/code_intel_upload_flags.go | 6 +- dev/vendor-lib.sh | 166 +++++++ go.mod | 129 ++++-- go.sum | 302 ++++++++----- lib/README.md | 23 + lib/accesstoken/personal_access_token.go | 29 ++ lib/api/version_check.go | 49 +++ lib/batches/batch_spec.go | 264 +++++++++++ lib/batches/changeset_spec.go | 273 ++++++++++++ lib/batches/changeset_specs.go | 310 +++++++++++++ lib/batches/env/env.go | 170 ++++++++ lib/batches/env/var.go | 99 +++++ lib/batches/execution/cache/cache.go | 174 ++++++++ lib/batches/execution/cache/util.go | 7 + lib/batches/execution/results.go | 98 +++++ lib/batches/git/changes.go | 37 ++ lib/batches/git/refs.go | 10 + lib/batches/json/validate.go | 24 + lib/batches/json_logs.go | 334 ++++++++++++++ lib/batches/jsonschema/jsonschema.go | 36 ++ lib/batches/outputs.go | 48 ++ lib/batches/overridable/bool.go | 69 +++ lib/batches/overridable/bool_or_string.go | 83 ++++ lib/batches/overridable/overridable.go | 143 ++++++ lib/batches/published.go | 110 +++++ lib/batches/schema/batch_spec_stringdata.go | 412 ++++++++++++++++++ .../schema/changeset_spec_stringdata.go | 121 +++++ lib/batches/template/partial_eval.go | 345 +++++++++++++++ lib/batches/template/template.go | 18 + lib/batches/template/templating.go | 334 ++++++++++++++ lib/batches/workspaces_execution_input.go | 39 ++ lib/batches/yaml/validate.go | 33 ++ lib/codeintel/upload/compress.go | 42 ++ lib/codeintel/upload/indexer_name.go | 76 ++++ lib/codeintel/upload/progress_reader.go | 56 +++ lib/codeintel/upload/request.go | 204 +++++++++ lib/codeintel/upload/request_logger.go | 90 ++++ lib/codeintel/upload/retry.go | 37 ++ lib/codeintel/upload/upload.go | 369 ++++++++++++++++ lib/codeintel/upload/upload_options.go | 47 ++ lib/errors/client_error.go | 26 ++ lib/errors/cockroach.go | 186 ++++++++ lib/errors/errors.go | 24 + lib/errors/filter.go | 51 +++ lib/errors/multi_error.go | 113 +++++ lib/errors/postgres.go | 12 + lib/errors/rich_error.go | 171 ++++++++ lib/errors/tree.go | 56 +++ lib/errors/warning.go | 96 ++++ lib/go.mod | 133 ++++++ lib/go.sum | 381 ++++++++++++++++ lib/output/block.go | 58 +++ lib/output/capabilities.go | 124 ++++++ lib/output/emoji.go | 32 ++ lib/output/line.go | 78 ++++ lib/output/logger.go | 31 ++ lib/output/noop_writer.go | 10 + lib/output/output.go | 354 +++++++++++++++ lib/output/output_unix.go | 79 ++++ lib/output/output_windows.go | 61 +++ lib/output/pending.go | 26 ++ lib/output/pending_simple.go | 26 ++ lib/output/pending_tty.go | 160 +++++++ lib/output/progress.go | 60 +++ lib/output/progress_simple.go | 91 ++++ lib/output/progress_tty.go | 295 +++++++++++++ lib/output/progress_with_status_bars.go | 23 + .../progress_with_status_bars_simple.go | 106 +++++ lib/output/progress_with_status_bars_tty.go | 309 +++++++++++++ lib/output/spinner.go | 47 ++ lib/output/status_bar.go | 68 +++ lib/output/style.go | 75 ++++ lib/output/table.go | 52 +++ lib/output/visible_string_width.go | 16 + lib/process/pipe.go | 140 ++++++ 75 files changed, 8631 insertions(+), 155 deletions(-) create mode 100755 dev/vendor-lib.sh create mode 100644 lib/README.md create mode 100644 lib/accesstoken/personal_access_token.go create mode 100644 lib/api/version_check.go create mode 100644 lib/batches/batch_spec.go create mode 100644 lib/batches/changeset_spec.go create mode 100644 lib/batches/changeset_specs.go create mode 100644 lib/batches/env/env.go create mode 100644 lib/batches/env/var.go create mode 100644 lib/batches/execution/cache/cache.go create mode 100644 lib/batches/execution/cache/util.go create mode 100644 lib/batches/execution/results.go create mode 100644 lib/batches/git/changes.go create mode 100644 lib/batches/git/refs.go create mode 100644 lib/batches/json/validate.go create mode 100644 lib/batches/json_logs.go create mode 100644 lib/batches/jsonschema/jsonschema.go create mode 100644 lib/batches/outputs.go create mode 100644 lib/batches/overridable/bool.go create mode 100644 lib/batches/overridable/bool_or_string.go create mode 100644 lib/batches/overridable/overridable.go create mode 100644 lib/batches/published.go create mode 100644 lib/batches/schema/batch_spec_stringdata.go create mode 100644 lib/batches/schema/changeset_spec_stringdata.go create mode 100644 lib/batches/template/partial_eval.go create mode 100644 lib/batches/template/template.go create mode 100644 lib/batches/template/templating.go create mode 100644 lib/batches/workspaces_execution_input.go create mode 100644 lib/batches/yaml/validate.go create mode 100644 lib/codeintel/upload/compress.go create mode 100644 lib/codeintel/upload/indexer_name.go create mode 100644 lib/codeintel/upload/progress_reader.go create mode 100644 lib/codeintel/upload/request.go create mode 100644 lib/codeintel/upload/request_logger.go create mode 100644 lib/codeintel/upload/retry.go create mode 100644 lib/codeintel/upload/upload.go create mode 100644 lib/codeintel/upload/upload_options.go create mode 100644 lib/errors/client_error.go create mode 100644 lib/errors/cockroach.go create mode 100644 lib/errors/errors.go create mode 100644 lib/errors/filter.go create mode 100644 lib/errors/multi_error.go create mode 100644 lib/errors/postgres.go create mode 100644 lib/errors/rich_error.go create mode 100644 lib/errors/tree.go create mode 100644 lib/errors/warning.go create mode 100644 lib/go.mod create mode 100644 lib/go.sum create mode 100644 lib/output/block.go create mode 100644 lib/output/capabilities.go create mode 100644 lib/output/emoji.go create mode 100644 lib/output/line.go create mode 100644 lib/output/logger.go create mode 100644 lib/output/noop_writer.go create mode 100644 lib/output/output.go create mode 100644 lib/output/output_unix.go create mode 100644 lib/output/output_windows.go create mode 100644 lib/output/pending.go create mode 100644 lib/output/pending_simple.go create mode 100644 lib/output/pending_tty.go create mode 100644 lib/output/progress.go create mode 100644 lib/output/progress_simple.go create mode 100644 lib/output/progress_tty.go create mode 100644 lib/output/progress_with_status_bars.go create mode 100644 lib/output/progress_with_status_bars_simple.go create mode 100644 lib/output/progress_with_status_bars_tty.go create mode 100644 lib/output/spinner.go create mode 100644 lib/output/status_bar.go create mode 100644 lib/output/style.go create mode 100644 lib/output/table.go create mode 100644 lib/output/visible_string_width.go create mode 100644 lib/process/pipe.go diff --git a/cmd/src/code_intel_upload_flags.go b/cmd/src/code_intel_upload_flags.go index 2a1b31c289..6a1f3031a0 100644 --- a/cmd/src/code_intel_upload_flags.go +++ b/cmd/src/code_intel_upload_flags.go @@ -2,6 +2,7 @@ package main import ( "compress/gzip" + "context" "flag" "fmt" "io" @@ -330,13 +331,14 @@ func readIndexerNameAndVersion(indexFile string) (string, string, error) { var metadata *scip.Metadata visitor := scip.IndexVisitor{ - VisitMetadata: func(m *scip.Metadata) { + VisitMetadata: func(ctx context.Context, m *scip.Metadata) error { metadata = m + return nil }, } // convert file to io.Reader - if err := visitor.ParseStreaming(indexReader); err != nil { + if err := visitor.ParseStreaming(context.Background(), indexReader); err != nil { return "", "", err } diff --git a/dev/vendor-lib.sh b/dev/vendor-lib.sh new file mode 100755 index 0000000000..ef53800ab7 --- /dev/null +++ b/dev/vendor-lib.sh @@ -0,0 +1,166 @@ +#!/usr/bin/env bash + +set -euo pipefail + +SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" +ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)" +SRC_REPO="$ROOT_DIR/../sourcegraph" +SRC_LIB="$SRC_REPO/lib" +DEST_LIB="$ROOT_DIR/lib" + +# Validate source repository +echo "Validating source repository..." +cd "$SRC_REPO" + +# Check if on main branch +CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD) +if [ "$CURRENT_BRANCH" != "main" ]; then + echo "Error: Source repository is not on main branch (currently on: $CURRENT_BRANCH)" + exit 1 +fi + +# Check for uncommitted changes +if ! git diff-index --quiet HEAD -- ; then + echo "Error: Source repository has uncommitted changes" + git status --short + exit 1 +fi + +# Get commit info +COMMIT_HASH=$(git rev-parse HEAD) +COMMIT_DATE=$(git show -s --format=%ci HEAD) + +echo "Source repository validated:" +echo " Branch: $CURRENT_BRANCH" +echo " Commit: $COMMIT_HASH" +echo " Date: $COMMIT_DATE" + +cd "$ROOT_DIR" + +echo "" +echo "Discovering packages to vendor..." + +# Get direct imports (including test imports) +DIRECT_IMPORTS=$(go list -f '{{ join .Imports "\n" }} +{{ join .TestImports "\n" }} +{{ join .XTestImports "\n" }}' ./... | grep 'github.com/sourcegraph/sourcegraph/lib' | sort | uniq || true) + +if [ -z "$DIRECT_IMPORTS" ]; then + echo "Error: No lib imports found" + exit 1 +fi + +echo "Direct imports found (including test imports):" +echo "$DIRECT_IMPORTS" + +# Get transitive dependencies within lib +echo "" +echo "Finding transitive dependencies..." +cd "$SRC_REPO" +TRANSITIVE=$(echo "$DIRECT_IMPORTS" | xargs go list -f '{{ join .Deps "\n" }}' 2>/dev/null | grep 'github.com/sourcegraph/sourcegraph/lib' | sort | uniq || true) +cd "$SCRIPT_DIR" + +# Combine and deduplicate +ALL_PACKAGES=$(echo -e "$DIRECT_IMPORTS\n$TRANSITIVE" | sort | uniq) + +echo "" +echo "All packages to vendor:" +echo "$ALL_PACKAGES" + +# Remove existing lib directory +if [ -d "$DEST_LIB" ]; then + echo "" + echo "Removing existing $DEST_LIB directory..." + rm -rf "$DEST_LIB" +fi + +# Create lib directory +mkdir -p "$DEST_LIB" + +# Copy each package +echo "" +echo "Copying packages..." +for pkg in $ALL_PACKAGES; do + # Extract the path after github.com/sourcegraph/sourcegraph/lib/ + pkg_path=${pkg#github.com/sourcegraph/sourcegraph/lib/} + + src_dir="$SRC_LIB/$pkg_path" + dest_dir="$DEST_LIB/$pkg_path" + + if [ ! -d "$src_dir" ]; then + echo "Warning: Source directory not found: $src_dir" + continue + fi + + echo " $pkg_path" + mkdir -p "$dest_dir" + + # Copy Go files (excluding tests) and other relevant files + for gofile in "$src_dir"/*.go; do + [ -e "$gofile" ] || continue + if [[ ! "$gofile" =~ _test\.go$ ]]; then + cp "$gofile" "$dest_dir/" 2>/dev/null || true + fi + done + cp -r "$src_dir"/*.mod "$dest_dir/" 2>/dev/null || true + cp -r "$src_dir"/*.sum "$dest_dir/" 2>/dev/null || true + + # Copy any subdirectories that might contain embedded files or test data + for item in "$src_dir"/*; do + if [ -d "$item" ] && [ "$(basename "$item")" != "." ] && [ "$(basename "$item")" != ".." ]; then + subdir=$(basename "$item") + # Skip if it's a package we're already copying separately + if ! echo "$ALL_PACKAGES" | grep -q "lib/$pkg_path/$subdir"; then + if ls "$item"/*.go 2>/dev/null | grep -v '_test\.go$' >/dev/null 2>&1; then + # Contains non-test Go files, skip it (it's a separate package) + continue + fi + # Copy non-package directories (e.g., testdata, embedded files) + cp -r "$item" "$dest_dir/" 2>/dev/null || true + fi + fi + done +done + +# Create go.mod file +echo "" +echo "Creating go.mod file..." +cat > "$DEST_LIB/go.mod" < "$DEST_LIB/README.md" < github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 -replace github.com/sourcegraph/sourcegraph/lib => github.com/sourcegraph/sourcegraph-public-snapshot/lib v0.0.0-20240709083501-1af563b61442 +replace github.com/sourcegraph/sourcegraph/lib => ./lib diff --git a/go.sum b/go.sum index d1f4a1f59c..4a873f16a1 100644 --- a/go.sum +++ b/go.sum @@ -8,17 +8,24 @@ cloud.google.com/go/iam v1.1.4 h1:K6n/GZHFTtEoKT5aUG3l9diPi0VduZNQ1PfdnpkkIFk= cloud.google.com/go/iam v1.1.4/go.mod h1:l/rg8l1AaA+VFMho/HYx2Vv6xinPSLMF8qfhRPIZ0L8= cloud.google.com/go/storage v1.30.1 h1:uOdMxAs8HExqBlnLtnQyP0YkvbiDpdGShGKtx6U/oNM= cloud.google.com/go/storage v1.30.1/go.mod h1:NfxhC0UJE1aXSx7CIIbCf7y9HKT7BiccwkR7+P7gN8E= -github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 h1:UQHMgLO+TxOElx5B5HZ4hJQsoJ/PvUvKRhJHDQXO8P8= -github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= +github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg= +github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/BurntSushi/toml v1.2.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI= github.com/Masterminds/goutils v1.1.1/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU= github.com/Masterminds/semver v1.5.0 h1:H65muMkzWKEuNDnfl9d70GUjFniHKHRbFPGBuZ3QEww= github.com/Masterminds/semver v1.5.0/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y= github.com/Masterminds/sprig v2.22.0+incompatible h1:z4yfnGrZ7netVz+0EDJ0Wi+5VZCSYp4Z0m2dk6cEM60= github.com/Masterminds/sprig v2.22.0+incompatible/go.mod h1:y6hNFY5UBTIWBxnzTeuNhlNS5hqE0NB0E6fgfo2Br3o= -github.com/alecthomas/chroma v0.10.0 h1:7XDcGkCQopCNKjZHfYrNLraA+M7e0fMiJ/Mfikbfjek= -github.com/alecthomas/chroma v0.10.0/go.mod h1:jtJATyUxlIORhUOFNA9NZDWGAQ8wpxQQqNSB4rjA/1s= +github.com/Microsoft/go-winio v0.6.1 h1:9/kr64B9VUZrLm5YYwbGtUJnMgqWVOdUAXu6Migciow= +github.com/Microsoft/go-winio v0.6.1/go.mod h1:LRdKpFKfdobln8UmuiYcKPot9D2v6svN5+sAH+4kjUM= +github.com/alecthomas/assert/v2 v2.7.0 h1:QtqSACNS3tF7oasA8CU6A6sXZSBDqnm7RfpLl9bZqbE= +github.com/alecthomas/assert/v2 v2.7.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k= +github.com/alecthomas/chroma/v2 v2.14.0 h1:R3+wzpnUArGcQz7fCETQBzO5n9IMNi13iIs46aU4V9E= +github.com/alecthomas/chroma/v2 v2.14.0/go.mod h1:QolEbTfmUHIMVpBqxeDnNBj2uoeI4EbYP4i6n68SG4I= +github.com/alecthomas/repr v0.4.0 h1:GhI2A8MACjfegCPVq9f1FLvIBS+DrQ2KQBFZP1iFzXc= +github.com/alecthomas/repr v0.4.0/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4= github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= github.com/aws/aws-sdk-go-v2 v1.17.4/go.mod h1:uzbQtefpm44goOPmdKyAlXSNcwlRgF3ePWVW6EtJvvw= github.com/aws/aws-sdk-go-v2 v1.17.5 h1:TzCUW1Nq4H8Xscph5M/skINUitxM5UBAyvm2s7XBzL4= @@ -55,29 +62,58 @@ github.com/aws/smithy-go v1.13.5 h1:hgz0X/DX0dGqTYpGALqXJoRKRj5oQ7150i5FdTePzO8= github.com/aws/smithy-go v1.13.5/go.mod h1:Tg+OJXh4MB2R/uN61Ko2f6hTZwB/ZYGOtib8J3gBHzA= github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k= github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8= +github.com/aymanbagabas/go-udiff v0.2.0 h1:TK0fH4MteXUDspT88n8CKzvK0X9O2xu9yQjWpi6yML8= +github.com/aymanbagabas/go-udiff v0.2.0/go.mod h1:RE4Ex0qsGkTAJoQdQQCA0uG+nAzJO/pI/QwceO5fgrA= github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk= github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4= -github.com/benbjohnson/clock v1.3.0 h1:ip6w0uFQkncKQ979AypyG0ER7mqUSBdKLOgAle/AT8A= -github.com/benbjohnson/clock v1.3.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= -github.com/bufbuild/buf v1.4.0 h1:GqE3a8CMmcFvWPzuY3Mahf9Kf3S9XgZ/ORpfYFzO+90= -github.com/bufbuild/buf v1.4.0/go.mod h1:mwHG7klTHnX+rM/ym8LXGl7vYpVmnwT96xWoRB4H5QI= +github.com/benbjohnson/clock v1.3.5 h1:VvXlSJBzZpA/zum6Sj74hxwYI2DIxRWuNIoXAzHZz5o= +github.com/benbjohnson/clock v1.3.5/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= +github.com/bufbuild/buf v1.25.0 h1:HFxKrR8wFcZwrBInN50K/oJX/WOtPVq24rHb/ArjfBA= +github.com/bufbuild/buf v1.25.0/go.mod h1:GCKZ5bAP6Ht4MF7KcfaGVgBEXGumwAz2hXjjLVxx8ZU= +github.com/bufbuild/connect-go v1.9.0 h1:JIgAeNuFpo+SUPfU19Yt5TcWlznsN5Bv10/gI/6Pjoc= +github.com/bufbuild/connect-go v1.9.0/go.mod h1:CAIePUgkDR5pAFaylSMtNK45ANQjp9JvpluG20rhpV8= +github.com/bufbuild/connect-opentelemetry-go v0.4.0 h1:6JAn10SNqlQ/URhvRNGrIlczKw1wEXknBUUtmWqOiak= +github.com/bufbuild/connect-opentelemetry-go v0.4.0/go.mod h1:nwPXYoDOoc2DGyKE/6pT1Q9MPSi2Et2e6BieMD0l6WU= +github.com/bufbuild/protocompile v0.5.1 h1:mixz5lJX4Hiz4FpqFREJHIXLfaLBntfaJv1h+/jS+Qg= +github.com/bufbuild/protocompile v0.5.1/go.mod h1:G5iLmavmF4NsYtpZFvE3B/zFch2GIY8+wjsYLR/lc40= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= -github.com/charmbracelet/glamour v0.5.0 h1:wu15ykPdB7X6chxugG/NNfDUbyyrCLV9XBalj5wdu3g= -github.com/charmbracelet/glamour v0.5.0/go.mod h1:9ZRtG19AUIzcTm7FGLGbq3D5WKQ5UyZBbQsMQN0XIqc= +github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc h1:4pZI35227imm7yK2bGPcfpFEmuY1gc2YSTShr4iJBfs= +github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc/go.mod h1:X4/0JoqgTIPSFcRA/P6INZzIuyqdFY5rm8tb41s9okk= +github.com/charmbracelet/glamour v0.10.0 h1:MtZvfwsYCx8jEPFJm3rIBFIMZUfUJ765oX8V6kXldcY= +github.com/charmbracelet/glamour v0.10.0/go.mod h1:f+uf+I/ChNmqo087elLnVdCiVgjSKWuXa/l6NU2ndYk= +github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834 h1:ZR7e0ro+SZZiIZD7msJyA+NjkCNNavuiPBLgerbOziE= +github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834/go.mod h1:aKC/t2arECF6rNOnaKaVU6y4t4ZeHQzqfxedE/VkVhA= +github.com/charmbracelet/x/ansi v0.8.0 h1:9GTq3xq9caJW8ZrBTe0LIe2fvfLR/bYXKTx2llXn7xE= +github.com/charmbracelet/x/ansi v0.8.0/go.mod h1:wdYl/ONOLHLIVmQaxbIYEC/cRKOQyjTkowiI4blgS9Q= +github.com/charmbracelet/x/cellbuf v0.0.13 h1:/KBBKHuVRbq1lYx5BzEHBAFBP8VcQzJejZ/IA3iR28k= +github.com/charmbracelet/x/cellbuf v0.0.13/go.mod h1:xe0nKWGd3eJgtqZRaN9RjMtK7xUYchjzPr7q6kcvCCs= +github.com/charmbracelet/x/exp/golden v0.0.0-20240806155701-69247e0abc2a h1:G99klV19u0QnhiizODirwVksQB91TJKV/UaTnACcG30= +github.com/charmbracelet/x/exp/golden v0.0.0-20240806155701-69247e0abc2a/go.mod h1:wDlXFlCrmJ8J+swcL/MnGUuYnqgQdW9rhSD61oNMb6U= +github.com/charmbracelet/x/exp/slice v0.0.0-20250327172914-2fdc97757edf h1:rLG0Yb6MQSDKdB52aGX55JT1oi0P0Kuaj7wi1bLUpnI= +github.com/charmbracelet/x/exp/slice v0.0.0-20250327172914-2fdc97757edf/go.mod h1:B3UgsnsBZS/eX42BlaNiJkD1pPOUa+oF1IYC6Yd2CEU= +github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ= +github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg= +github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= +github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= +github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/clipperhouse/uax29/v2 v2.2.0 h1:ChwIKnQN3kcZteTXMgb1wztSgaU+ZemkgWdohwgs8tY= +github.com/clipperhouse/uax29/v2 v2.2.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= github.com/cncf/udpa/go v0.0.0-20210930031921-04548b0d99d4/go.mod h1:6pvJx4me5XPnfI9Z40ddWsdw2W/uZgQLFXToKeRcDiI= github.com/cncf/xds/go v0.0.0-20210805033703-aa0b78936158/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cncf/xds/go v0.0.0-20210922020428-25de7278fc84/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= -github.com/cockroachdb/errors v1.11.1 h1:xSEW75zKaKCWzR3OfxXUxgrk/NtT4G1MiOv5lWZazG8= -github.com/cockroachdb/errors v1.11.1/go.mod h1:8MUxA3Gi6b25tYlFEBGLf+D8aISL+M4MIpiWMSNRfxw= +github.com/cockroachdb/errors v1.12.0 h1:d7oCs6vuIMUQRVbi6jWWWEJZahLCfJpnJSVobd1/sUo= +github.com/cockroachdb/errors v1.12.0/go.mod h1:SvzfYNNBshAVbZ8wzNc/UPK3w1vf0dKDUP41ucAIf7g= github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b h1:r6VH0faHjZeQy818SGhaone5OnYfxFR/+AzdY3sf5aE= github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= -github.com/cockroachdb/redact v1.1.5 h1:u1PMllDkdFfPWaNGMyLD1+so+aq3uUItthCFqzwPJ30= -github.com/cockroachdb/redact v1.1.5/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= +github.com/cockroachdb/redact v1.1.6 h1:zXJBwDZ84xJNlHl1rMyCojqyIxv+7YUpQiJLQ7n4314= +github.com/cockroachdb/redact v1.1.6/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= +github.com/containerd/stargz-snapshotter/estargz v0.14.3 h1:OqlDCK3ZVUO6C3B/5FSkDwbkEETK84kQgEeFwDC+62k= +github.com/containerd/stargz-snapshotter/estargz v0.14.3/go.mod h1:KY//uOCIkSuNAHhJogcZtrNHdKrA99/FCCRjE3HD36o= github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w= github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/creack/goselect v0.1.2 h1:2DNy14+JPjRBgPzAd1thbQp4BSIihxcBf0IXhQXDRa0= @@ -93,9 +129,20 @@ github.com/derision-test/glock v1.0.0 h1:b6sViZG+Cm6QtdpqbfWEjaBVbzNPntIS4GzsxpS github.com/derision-test/glock v1.0.0/go.mod h1:jKtLdBMrF+XQatqvg46wiWdDfDSSDjdhO4dOM2FX9H4= github.com/dineshappavoo/basex v0.0.0-20170425072625-481a6f6dc663 h1:fctNkSsavbXpt8geFWZb8n+noCqS8MrOXRJ/YfdZ2dQ= github.com/dineshappavoo/basex v0.0.0-20170425072625-481a6f6dc663/go.mod h1:Kad2hux31v/IyD4Rf4wAwIyK48995rs3qAl9IUAhc2k= -github.com/dlclark/regexp2 v1.4.0/go.mod h1:2pZnwuY/m+8K6iRw6wQdMtk+rH5tNGR1i55kozfMjCc= -github.com/dlclark/regexp2 v1.8.0 h1:rJD5HeGIT/2b5CDk63FVCwZA3qgYElfg+oQK7uH5pfE= -github.com/dlclark/regexp2 v1.8.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= +github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI= +github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= +github.com/docker/cli v24.0.4+incompatible h1:Y3bYF9ekNTm2VFz5U/0BlMdJy73D+Y1iAAZ8l63Ydzw= +github.com/docker/cli v24.0.4+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8= +github.com/docker/distribution v2.8.2+incompatible h1:T3de5rq0dB1j30rp0sA2rER+m322EBzniBPB6ZIzuh8= +github.com/docker/distribution v2.8.2+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= +github.com/docker/docker v24.0.4+incompatible h1:s/LVDftw9hjblvqIeTiGYXBCD95nOEEl7qRsRrIOuQI= +github.com/docker/docker v24.0.4+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= +github.com/docker/docker-credential-helpers v0.8.0 h1:YQFtbBQb4VrpoPxhFuzEBPQ9E16qz5SpHLS+uswaCp8= +github.com/docker/docker-credential-helpers v0.8.0/go.mod h1:UGFXcuoQ5TxPiB54nHOZ32AWRqQdECoh/Mg0AlEYb40= +github.com/docker/go-connections v0.4.0 h1:El9xVISelRB7BuFusrZozjnkIM5YnzCViNKohAFqRJQ= +github.com/docker/go-connections v0.4.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5XhDvyHbTtUxmeec= +github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4= +github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/emicklei/go-restful/v3 v3.11.0 h1:rAQeMHw1c7zTmncogyy8VvRZwtkmkZ4FxERmMY4rD+g= @@ -104,7 +151,6 @@ github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymF github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= -github.com/envoyproxy/go-control-plane v0.9.9-0.20210217033140-668b12f5399d/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= github.com/envoyproxy/go-control-plane v0.9.10-0.20210907150352-cf90f659a021/go.mod h1:AFq3mo9L8Lqqiid3OhADV3RfLJnjiw63cSpi+fDTRC0= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/envoyproxy/protoc-gen-validate v1.0.2 h1:QkIBuU5k+x7/QXPvPPnWXWlCdaBFApVqftFV6k087DA= @@ -112,16 +158,24 @@ github.com/envoyproxy/protoc-gen-validate v1.0.2/go.mod h1:GpiZQP3dDbg4JouG/NNS7 github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs= github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw= -github.com/frankban/quicktest v1.14.3 h1:FJKSZTDHjyhriyC81FLQ0LY93eSai0ZyR/ZIkd3ZUKE= +github.com/felixge/fgprof v0.9.3 h1:VvyZxILNuCiUCSXtPtYmmtGvb65nqXh2QFWc0Wpf2/g= +github.com/felixge/fgprof v0.9.3/go.mod h1:RdbpDgzqYVh/T9fPELJyV7EYJuHB55UTEULNun8eiPw= github.com/frankban/quicktest v1.14.3/go.mod h1:mgiwOwqx65TmIk1wJ6Q7wvnVMocbUorkibMOrVTHZps= +github.com/frankban/quicktest v1.14.4 h1:g2rn0vABPOOXmZUj+vbmUp0lPoXEMuhTpIluN0XL9UY= +github.com/frankban/quicktest v1.14.4/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= github.com/fxamacker/cbor/v2 v2.7.0 h1:iM5WgngdRBanHcxugY4JySA0nk1wZorNOpTgCMedv5E= github.com/fxamacker/cbor/v2 v2.7.0/go.mod h1:pxXPTn3joSm21Gbwsv0w9OSA2y1HFR9qXEeXQVeNoDQ= github.com/getsentry/sentry-go v0.27.0 h1:Pv98CIbtB3LkMWmXi4Joa5OOcwbmnX88sF5qbK3r3Ps= github.com/getsentry/sentry-go v0.27.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= +github.com/go-chi/chi/v5 v5.0.10 h1:rLz5avzKpjqxrYwXNfmjkrYYXOyLJd37pz53UFHC6vk= +github.com/go-chi/chi/v5 v5.0.10/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8= github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA= github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og= -github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= -github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= +github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/go-openapi/jsonpointer v0.19.6/go.mod h1:osyAmYz/mB/C3I+WsTTSgw1ONzaLJoLCyoi6/zppojs= github.com/go-openapi/jsonpointer v0.21.0 h1:YgdVicSA9vH5RiHs9TZW5oyafXZFc6+2Vc1rr/O9oNQ= github.com/go-openapi/jsonpointer v0.21.0/go.mod h1:IUyH9l/+uyhIYQ/PXVA41Rexl+kOkAPDdXEYns6fzUY= @@ -136,8 +190,8 @@ github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y= github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8= github.com/gofrs/flock v0.8.1 h1:+gYjHKf32LDeiEEFhQaotPbLuUXjY5ZqxKgXy7n59aw= github.com/gofrs/flock v0.8.1/go.mod h1:F1TvTiK9OcQqauNUHlbJvyl9Qa1QvF/gOUDKA14jxHU= -github.com/gofrs/uuid v4.2.0+incompatible h1:yyYWMnhkhrKwwr8gAOcOCYxOOscHgDS9yZgBrnJfGa0= -github.com/gofrs/uuid v4.2.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= +github.com/gofrs/uuid/v5 v5.0.0 h1:p544++a97kEL+svbcFbCQVM9KFu0Yo25UoISXGNNH9M= +github.com/gofrs/uuid/v5 v5.0.0/go.mod h1:CDOjlDMVAtN56jqyRUZh58JT31Tiw7/oQyEXZV+9bD8= github.com/gogo/protobuf v1.3.0/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= @@ -176,13 +230,16 @@ github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE= github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= -github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= -github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/go-containerregistry v0.15.2 h1:MMkSh+tjSdnmJZO7ljvEqV1DjfekB6VUEAZgy3a+TQE= +github.com/google/go-containerregistry v0.15.2/go.mod h1:wWK+LnOv4jXMM23IT/F1wdYftGWGr47Is8CG+pmHK1Q= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/martian/v3 v3.3.2 h1:IqNFLAmvJOgVlpdEBiQbDc2EwKW77amAycfTuWKdfvw= github.com/google/martian/v3 v3.3.2/go.mod h1:oBOf6HBosgwRXnUGWUB05QECsc6uvmMiJ3+6W4l/CUk= +github.com/google/pprof v0.0.0-20211214055906-6f57359322fd/go.mod h1:KgnwoLYCZ8IQu3XUZ8Nc/bM9CCZFOyjUNOSygVozoDg= github.com/google/pprof v0.0.0-20241029153458-d1b30febd7db h1:097atOisP2aRj7vFgYQBbFN4U4JNXUNYpxael3UzMyo= github.com/google/pprof v0.0.0-20241029153458-d1b30febd7db/go.mod h1:vavhavw2zAxS5dIdcRluK6cSGGPlZynqzFM8NdvU144= github.com/google/s2a-go v0.1.4 h1:1kZ/sQM3srePvKs3tXAvQzo66XfcReoqFpIpIccE7Oc= @@ -194,20 +251,24 @@ github.com/googleapis/enterprise-certificate-proxy v0.2.5 h1:UR4rDjcgpgEnqpIEvki github.com/googleapis/enterprise-certificate-proxy v0.2.5/go.mod h1:RxW0N9901Cko1VOCW3SXCpWP+mlIEkk2tP7jnHy9a3w= github.com/googleapis/gax-go/v2 v2.12.0 h1:A+gCJKdRfqXkr+BIRGtZLibNXf0m1f9E4HG56etFpas= github.com/googleapis/gax-go/v2 v2.12.0/go.mod h1:y+aIqrI5eb1YGMVJfuV3185Ts/D7qKpsEkdD5+I6QGU= -github.com/gorilla/css v1.0.0 h1:BQqNyPTi50JCFMTw/b67hByjMVXZRwGha6wxVGkeihY= -github.com/gorilla/css v1.0.0/go.mod h1:Dn721qIggHpt4+EFCcTLTU/vk5ySda2ReITrtgBl60c= -github.com/grafana/regexp v0.0.0-20221123153739-15dc172cd2db h1:7aN5cccjIqCLTzedH7MZzRZt5/lsAHch6Z3L2ZGn5FA= -github.com/grafana/regexp v0.0.0-20221123153739-15dc172cd2db/go.mod h1:M5qHK+eWfAv8VR/265dIuEpL3fNfeC21tXXp9itM24A= +github.com/gorilla/css v1.0.1 h1:ntNaBIghp6JmvWnxbZKANoLyuXTPZ4cAMlo6RyhlbO8= +github.com/gorilla/css v1.0.1/go.mod h1:BvnYkspnSzMmwRK+b8/xgNPLiIuNZr6vbZBTPQ2A3b0= +github.com/grafana/regexp v0.0.0-20250905093917-f7b3be9d1853 h1:cLN4IBkmkYZNnk7EAJ0BHIethd+J6LqxFNw5mSiI2bM= +github.com/grafana/regexp v0.0.0-20250905093917-f7b3be9d1853/go.mod h1:+JKpmjMGhpgPL+rXZ5nsZieVzvarn86asRlBg4uNGnk= github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= github.com/hexops/autogold v0.8.1/go.mod h1:97HLDXyG23akzAoRYJh/2OBs3kd80eHyKPvZw0S5ZBY= github.com/hexops/autogold v1.3.1 h1:YgxF9OHWbEIUjhDbpnLhgVsjUDsiHDTyDfy2lrfdlzo= github.com/hexops/autogold v1.3.1/go.mod h1:sQO+mQUCVfxOKPht+ipDSkJ2SCJ7BNJVHZexsXqWMx4= +github.com/hexops/autogold/v2 v2.2.1 h1:JPUXuZQGkcQMv7eeDXuNMovjfoRYaa0yVcm+F3voaGY= +github.com/hexops/autogold/v2 v2.2.1/go.mod h1:IJwxtUfj1BGLm0YsR/k+dIxYi6xbeLjqGke2bzcOTMI= github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM= github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg= -github.com/hexops/valast v1.4.3 h1:oBoGERMJh6UZdRc6cduE1CTPK+VAdXA59Y1HFgu3sm0= github.com/hexops/valast v1.4.3/go.mod h1:Iqx2kLj3Jn47wuXpj3wX40xn6F93QNFBHuiKBerkTGA= +github.com/hexops/valast v1.4.4 h1:rETyycw+/L2ZVJHHNxEBgh8KUn+87WugH9MxcEv9PGs= +github.com/hexops/valast v1.4.4/go.mod h1:Jcy1pNH7LNraVaAZDLyv21hHg2WBv9Nf9FL6fGxU7o4= github.com/huandu/xstrings v1.3.2 h1:L18LIDzqlW6xN2rEkpdV8+oL/IXWJ1APd+vsdYy4Wdw= github.com/huandu/xstrings v1.3.2/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE= +github.com/ianlancetaylor/demangle v0.0.0-20210905161508-09a460cdf81d/go.mod h1:aYm2/VgdVmcIU8iMfdMvDMsRAQjcfZSKFby6HOFvi/w= github.com/imdario/mergo v0.3.16 h1:wwQJbIsHYGMUyLSPrEq1CT16AhnhNJQ51+4fdHUnCl4= github.com/imdario/mergo v0.3.16/go.mod h1:WBLT9ZmE3lPoWsEzCh9LPo3TiwVN+ZKEjmz+hD27ysY= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= @@ -227,18 +288,12 @@ github.com/jackc/pgproto3/v2 v2.3.3 h1:1HLSx5H+tXR9pW3in3zaztoEwQYRC9SQaYUHjTSUO github.com/jackc/pgproto3/v2 v2.3.3/go.mod h1:WfJCnwN3HIg9Ish/j3sgWXnAfK8A9Y0bwXYU5xKaEdA= github.com/jackc/pgservicefile v0.0.0-20231201235250-de7065d80cb9 h1:L0QtFUgDarD7Fpv9jeVMgy/+Ec0mtnmYuImjTz6dtDA= github.com/jackc/pgservicefile v0.0.0-20231201235250-de7065d80cb9/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= -github.com/jdxcode/netrc v0.0.0-20210204082910-926c7f70242a h1:d4+I1YEKVmWZrgkt6jpXBnLgV2ZjO0YxEtLDdfIZfH4= -github.com/jdxcode/netrc v0.0.0-20210204082910-926c7f70242a/go.mod h1:Zi/ZFkEqFHTm7qkjyNJjaWH4LQA9LQhGJyF0lTYGpxw= -github.com/jedib0t/go-pretty/v6 v6.3.7 h1:H3Ulkf7h6A+p0HgKBGzgDn0bZIupRbKKWF4pO4Bs7iA= -github.com/jedib0t/go-pretty/v6 v6.3.7/go.mod h1:MgmISkTWDSFu0xOqiZ0mKNntMQ2mDgOcwOkwBEkMDJI= -github.com/jhump/gopoet v0.0.0-20190322174617-17282ff210b3/go.mod h1:me9yfT6IJSlOL3FCfrg+L6yzUEZ+5jW6WHt4Sk+UPUI= -github.com/jhump/gopoet v0.1.0/go.mod h1:me9yfT6IJSlOL3FCfrg+L6yzUEZ+5jW6WHt4Sk+UPUI= -github.com/jhump/goprotoc v0.5.0/go.mod h1:VrbvcYrQOrTi3i0Vf+m+oqQWk9l72mjkJCYo7UvLHRQ= -github.com/jhump/protocompile v0.0.0-20220216033700-d705409f108f h1:BNuUg9k2EiJmlMwjoef3e8vZLHplbVw6DrjGFjLL+Yo= -github.com/jhump/protocompile v0.0.0-20220216033700-d705409f108f/go.mod h1:qr2b5kx4HbFS7/g4uYO5qv9ei8303JMsC7ESbYiqr2Q= -github.com/jhump/protoreflect v1.11.0/go.mod h1:U7aMIjN0NWq9swDP7xDdoMfRHb35uiuTd3Z9nFXJf5E= -github.com/jhump/protoreflect v1.12.1-0.20220417024638-438db461d753 h1:uFlcJKZPLQd7rmOY/RrvBuUaYmAFnlFHKLivhO6cOy8= -github.com/jhump/protoreflect v1.12.1-0.20220417024638-438db461d753/go.mod h1:JytZfP5d0r8pVNLZvai7U/MCuTWITgrI4tTg7puQFKI= +github.com/jdxcode/netrc v0.0.0-20221124155335-4616370d1a84 h1:2uT3aivO7NVpUPGcQX7RbHijHMyWix/yCnIrCWc+5co= +github.com/jdxcode/netrc v0.0.0-20221124155335-4616370d1a84/go.mod h1:Zi/ZFkEqFHTm7qkjyNJjaWH4LQA9LQhGJyF0lTYGpxw= +github.com/jedib0t/go-pretty/v6 v6.6.3 h1:nGqgS0tgIO1Hto47HSaaK4ac/I/Bu7usmdD3qvs0WvM= +github.com/jedib0t/go-pretty/v6 v6.6.3/go.mod h1:zbn98qrYlh95FIhwwsbIip0LYpwSG8SUOScs+v9/t0E= +github.com/jhump/protoreflect v1.15.1 h1:HUMERORf3I3ZdX05WaQ6MIpd/NJ434hTp5YiKgfCL6c= +github.com/jhump/protoreflect v1.15.1/go.mod h1:jD/2GMKKE6OqX8qTjhADU1e6DShO+gavG9e0Q693nKo= github.com/jig/teereadcloser v0.0.0-20181016160506-953720c48e05 h1:dSwwtWuwMyarzsbVWOq4QJ8xVy9wgcNomvWyGtrKe+E= github.com/jig/teereadcloser v0.0.0-20181016160506-953720c48e05/go.mod h1:sRUFlj+HCejvoCRpuhU0EYnNw5FG+YJpz8UFfCf0F2U= github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg= @@ -254,10 +309,10 @@ github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51/go.mod h1:C github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= -github.com/klauspost/compress v1.16.7 h1:2mk3MPGNzKyxErAw8YaohYh69+pa4sIQSC0fPGCFR9I= -github.com/klauspost/compress v1.16.7/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= -github.com/klauspost/pgzip v1.2.5 h1:qnWYvvKqedOF2ulHpMG72XQol4ILEJ8k2wwRl/Km8oE= -github.com/klauspost/pgzip v1.2.5/go.mod h1:Ch1tH69qFZu15pkjo5kYi6mth2Zzwzt50oCQKQE9RUs= +github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= +github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= +github.com/klauspost/pgzip v1.2.6 h1:8RXeL5crjEUFnR2/Sn6GJNWtSQ3Dk8pq4CL3jvdDyjU= +github.com/klauspost/pgzip v1.2.6/go.mod h1:Ch1tH69qFZu15pkjo5kYi6mth2Zzwzt50oCQKQE9RUs= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= @@ -275,35 +330,35 @@ github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= -github.com/mattn/go-isatty v0.0.13/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= -github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= -github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk= -github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= -github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU= -github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= -github.com/microcosm-cc/bluemonday v1.0.17/go.mod h1:Z0r70sCuXHig8YpBzCc5eGHAap2K7e/u082ZUpDRRqM= -github.com/microcosm-cc/bluemonday v1.0.23 h1:SMZe2IGa0NuHvnVNAZ+6B38gsTbi5e4sViiWJyDDqFY= -github.com/microcosm-cc/bluemonday v1.0.23/go.mod h1:mN70sk7UkkF8TUr2IGBpNN0jAgStuPzlK76QuruE/z4= +github.com/mattn/go-runewidth v0.0.19 h1:v++JhqYnZuu5jSKrk9RbgF5v4CGUjqRfBm05byFGLdw= +github.com/mattn/go-runewidth v0.0.19/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs= +github.com/microcosm-cc/bluemonday v1.0.27 h1:MpEUotklkwCSLeH+Qdx1VJgNqLlpY2KXwXFM08ygZfk= +github.com/microcosm-cc/bluemonday v1.0.27/go.mod h1:jFi9vgW+H7c3V0lb6nR74Ib/DIB5OBs92Dimizgw2cA= github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw= github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s= +github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= +github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ= github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= -github.com/moby/term v0.0.0-20221205130635-1aeaba878587 h1:HfkjXDfhgVaN5rmueG8cL8KKeFNecRCXFhaJ2qZ5SKA= -github.com/moby/term v0.0.0-20221205130635-1aeaba878587/go.mod h1:8FzsFHVUBGZdbDsJw/ot+X+d5HLUbvklYLJ9uGfcI3Y= +github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ= +github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A= +github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc= github.com/muesli/reflow v0.3.0 h1:IFsN6K9NfGtjeggFP+68I4chLZV2yIKsXJFNZ+eWh6s= github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKtnHY/8= -github.com/muesli/termenv v0.9.0/go.mod h1:R/LzAKf+suGs4IsO95y7+7DpFHO0KABgnZqtlyx2mBw= -github.com/muesli/termenv v0.15.1 h1:UzuTb/+hhlBugQz28rpzey4ZuKcZ03MeKsoG7IJZIxs= -github.com/muesli/termenv v0.15.1/go.mod h1:HeAQPTzpfs016yGtA4g00CsdYnVLJvxsS4ANqrZs2sQ= +github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc= +github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/mwitkow/go-proto-validators v0.3.2 h1:qRlmpTzm2pstMKKzTdvwPCF5QfBNURSlAgN/R+qbKos= @@ -319,6 +374,10 @@ github.com/onsi/ginkgo/v2 v2.21.0 h1:7rg/4f3rB88pb5obDgNZrNHrQ4e6WpjonchcpuBRnZM github.com/onsi/ginkgo/v2 v2.21.0/go.mod h1:7Du3c42kxCUegi0IImZ1wUQzMBVecgIHjR1C+NkhLQo= github.com/onsi/gomega v1.35.1 h1:Cwbd75ZBPxFSuZ6T+rN/WCb/gOc6YgFBXLlZLhC7Ds4= github.com/onsi/gomega v1.35.1/go.mod h1:PvZbdDc8J6XJEpDK4HCuRBm8a6Fzp9/DmhC9C7yFlog= +github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= +github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= +github.com/opencontainers/image-spec v1.1.0-rc4 h1:oOxKUJWnFC4YGHCCMNql1x4YaDfYBTS5Y4x/Cgeo1E0= +github.com/opencontainers/image-spec v1.1.0-rc4/go.mod h1:X4pATf0uXsnn3g5aiGIsVnJBR4mxhKzfwmvK/B2NTm8= github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4= github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8= github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 h1:KoWmjvw+nsYOo29YJK9vDA65RGE3NrOnUtO7a+RF9HU= @@ -326,8 +385,8 @@ github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8/go.mod h1:HKlIX3XHQyzL github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pkg/profile v1.6.0 h1:hUDfIISABYI59DyeB3OTay/HxSRwTQ8rB/H83k6r5dM= -github.com/pkg/profile v1.6.0/go.mod h1:qBsxPvzyUincmltOk6iyRVxHYg4adc0OFOv72ZdLa18= +github.com/pkg/profile v1.7.0 h1:hnbDkaNWPCLMO9wGLdBFTIZvzDrDfBM2072E1S9gJkA= +github.com/pkg/profile v1.7.0/go.mod h1:8Uer0jas47ZQMJ7VD+OHknK4YDY07LPUC6dEvqDjvNo= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= @@ -338,29 +397,34 @@ github.com/pseudomuto/protokit v0.2.0 h1:hlnBDcy3YEDXH7kc9gV+NLaN0cDzhDvD1s7Y6FZ github.com/pseudomuto/protokit v0.2.0/go.mod h1:2PdH30hxVHsup8KpBTOXTBeMVhJZVio3Q8ViKSAXT0Q= github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= -github.com/rivo/uniseg v0.4.3 h1:utMvzDsuh3suAEnhH0RdHmoPbU648o6CvXxTx4SBMOw= -github.com/rivo/uniseg v0.4.3/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= +github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= +github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= -github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= -github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= +github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= +github.com/rs/cors v1.9.0 h1:l9HGsTsHJcvW14Nk7J9KFz8bzeAWXn3CG6bgt7LsrAE= +github.com/rs/cors v1.9.0/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU= github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/shurcooL/go v0.0.0-20180423040247-9e1955d9fb6e/go.mod h1:TDJrrUr11Vxrven61rcy3hJMUqaf/CLWYhHNPmT14Lk= github.com/shurcooL/go-goon v0.0.0-20170922171312-37c2f522c041/go.mod h1:N5mDOmsrJOB+vfqUK+7DmDyjhSLIIBnXo9lvZJj3MWQ= +github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= +github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= +github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= +github.com/sourcegraph/beaut v0.0.0-20240611013027-627e4c25335a h1:j/CQ27s679M9wRGBRJYyXGrfkYuQA6VMnD7R08mHD9c= +github.com/sourcegraph/beaut v0.0.0-20240611013027-627e4c25335a/go.mod h1:JG1sdvGTKWwe/oH3/3UKQ26vfcHIN//7fwEJhoqaBcM= github.com/sourcegraph/conc v0.3.1-0.20240108182409-4afefce20f9b h1:0FsjN+u9fNXTS2C1JnJ6G/gkgcUg8dscyyfu3PwHWUQ= github.com/sourcegraph/conc v0.3.1-0.20240108182409-4afefce20f9b/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0= -github.com/sourcegraph/go-diff v0.6.2-0.20221123165719-f8cd299c40f3 h1:11miag7hlORpW7ici5mL7T9PyiEsmVmf+8PFOvJ/ZrA= -github.com/sourcegraph/go-diff v0.6.2-0.20221123165719-f8cd299c40f3/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= +github.com/sourcegraph/go-diff v0.7.0 h1:9uLlrd5T46OXs5qpp8L/MTltk0zikUGi0sNNyCpA8G0= +github.com/sourcegraph/go-diff v0.7.0/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= -github.com/sourcegraph/log v0.0.0-20231018134238-fbadff7458bb h1:tHKdC+bXxxGJ0cy/R06kg6Z0zqwVGOWMx8uWsIwsaoY= -github.com/sourcegraph/log v0.0.0-20231018134238-fbadff7458bb/go.mod h1:IDp09QkoqS8Z3CyN2RW6vXjgABkNpDbyjLIHNQwQ8P8= -github.com/sourcegraph/scip v0.3.1-0.20230627154934-45df7f6d33fc h1:o+eq0cjVV3B5ngIBF04Lv3GwttKOuYFF5NTcfXWXzfA= -github.com/sourcegraph/scip v0.3.1-0.20230627154934-45df7f6d33fc/go.mod h1:7ZKAtLIUmiMvOIgG5LMcBxdtBXVa0v2GWC4Hm1ASYQ0= -github.com/sourcegraph/sourcegraph-public-snapshot/lib v0.0.0-20240709083501-1af563b61442 h1:M/jSgKSzeYbfrE/C6H8b8zu07c59taz4fIQcOGh1vqY= -github.com/sourcegraph/sourcegraph-public-snapshot/lib v0.0.0-20240709083501-1af563b61442/go.mod h1:RBdAauod1tGL33L1Izr2YymwN8uWQV++fL6orhD4aqc= +github.com/sourcegraph/log v0.0.0-20250923023806-517b6960b55b h1:2FQ72y5zECMu9e5z5jMnllb5n1jVK7qsvgjkVtdFV+g= +github.com/sourcegraph/log v0.0.0-20250923023806-517b6960b55b/go.mod h1:IDp09QkoqS8Z3CyN2RW6vXjgABkNpDbyjLIHNQwQ8P8= +github.com/sourcegraph/scip v0.6.1 h1:lcBrTwGjsqpMLQN4pVfJYSB+8oVoc8Lnqb4FAfU8EBM= +github.com/sourcegraph/scip v0.6.1/go.mod h1:c6d9mk1cGT6OXdHutxDakKVEPN1D+iFoYWCsrDxEhus= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I= @@ -380,11 +444,15 @@ github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5 github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.7.4/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= -github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= -github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/tetratelabs/wazero v1.3.0 h1:nqw7zCldxE06B8zSZAY0ACrR9OH5QCcPwYmYlwtcwtE= +github.com/tetratelabs/wazero v1.3.0/go.mod h1:wYx2gNRg8/WihJfSDxA1TIL8H+GkfLYm+bIfbblu9VQ= +github.com/urfave/cli v1.22.12/go.mod h1:sSBEIC79qR6OvcmsD4U3KABeOTxDqQtdDnaFuUN30b8= +github.com/vbatts/tar-split v0.11.3 h1:hLFqsOLQ1SsppQNTMpkpPXClLDfC2A3Zgy9OUU+RVck= +github.com/vbatts/tar-split v0.11.3/go.mod h1:9QlHN18E+fEH7RdG+QAJJcuya3rqT7eXSTY7wGrAokY= github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= @@ -394,16 +462,32 @@ github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHo github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74= github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y= +github.com/xlab/treeprint v1.2.0 h1:HzHnuAF1plUN2zGlAFHbSQP2qJ0ZAD3XF5XD7OesXRQ= +github.com/xlab/treeprint v1.2.0/go.mod h1:gj5Gd3gPdKtR1ikdDK6fnFLdmIS0X30kTTuNd/WEJu0= +github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no= +github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.4.4/go.mod h1:rmuwmfZ0+bvzB24eSC//bk1R1Zp3hM0OXYv/G2LIilg= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= -github.com/yuin/goldmark v1.5.2 h1:ALmeCk/px5FSm1MAcFBAsVKZjDuMVj8Tm7FFIlMJnqU= -github.com/yuin/goldmark v1.5.2/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= -github.com/yuin/goldmark-emoji v1.0.1 h1:ctuWEyzGBwiucEqxzwe0SOYDXPAucOrE9NQC18Wa1os= -github.com/yuin/goldmark-emoji v1.0.1/go.mod h1:2w1E6FEWLcDQkoTE+7HU6QF1F6SLlNGjRIBbIZQFqkQ= +github.com/yuin/goldmark v1.7.1/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E= +github.com/yuin/goldmark v1.7.8 h1:iERMLn0/QJeHFhxSt3p6PeN9mGnvIKSpG9YYorDMnic= +github.com/yuin/goldmark v1.7.8/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E= +github.com/yuin/goldmark-emoji v1.0.5 h1:EMVWyCGPlXJfUXBXpuMu+ii3TIaxbVBnEX9uaDC4cIk= +github.com/yuin/goldmark-emoji v1.0.5/go.mod h1:tTkZEbwu5wkPmgTcitqddVxY9osFZiavD+r4AzQrh1U= go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0= go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo= +go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA= +go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A= +go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8= +go.opentelemetry.io/otel v1.38.0/go.mod h1:zcmtmQ1+YmQM9wrNsTGV/q/uyusom3P8RxwExxkZhjM= +go.opentelemetry.io/otel/metric v1.38.0 h1:Kl6lzIYGAh5M159u9NgiRkmoMKjvbsKtYRwgfrA6WpA= +go.opentelemetry.io/otel/metric v1.38.0/go.mod h1:kB5n/QoRM8YwmUahxvI3bO34eVtQf2i4utNVLr9gEmI= +go.opentelemetry.io/otel/sdk v1.16.0 h1:Z1Ok1YsijYL0CSJpHt4cS3wDDh7p572grzNrBMiMWgE= +go.opentelemetry.io/otel/sdk v1.16.0/go.mod h1:tMsIuKXuuIWPBAOrH+eHtvhTL+SntFtXF9QD68aP6p4= +go.opentelemetry.io/otel/sdk/metric v0.39.0 h1:Kun8i1eYf48kHH83RucG93ffz0zGV1sh46FAScOTuDI= +go.opentelemetry.io/otel/sdk/metric v0.39.0/go.mod h1:piDIRgjcK7u0HCL5pCA4e74qpK/jk3NiUoAHATVAmiI= +go.opentelemetry.io/otel/trace v1.38.0 h1:Fxk5bKrDZJUH+AMyyIXGcFAPah0oRcT+LuNtJrmcNLE= +go.opentelemetry.io/otel/trace v1.38.0/go.mod h1:j1P9ivuFsTceSWe1oY+EeW3sc+Pp42sO++GHkg4wwhs= go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI= go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= @@ -418,9 +502,11 @@ golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8U golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20220314234659-1baeb1ce4c0b/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= -golang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34= -golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc= +golang.org/x/crypto v0.42.0 h1:chiH31gIWm57EkTXpwnqf8qeuMUi0yekh6mT2AvFlqI= +golang.org/x/crypto v0.42.0/go.mod h1:4+rDnOTJhQCx2q7/j6rAN5XDw8kPjeaXEUR2eL94ix8= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20231108232855-2478ac86f678 h1:mchzmB1XO2pMaKFRqk/+MV3mgGG96aqaPXaMifQU47w= +golang.org/x/exp v0.0.0-20231108232855-2478ac86f678/go.mod h1:zk2irFbV9DP96SEBUUAy67IdHUaZuSnrz1n472HUCLE= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= @@ -428,8 +514,8 @@ golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.7.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/mod v0.21.0 h1:vvrHzRwRfVKSiLrG+d4FMl/Qi4ukBCE6kZlTUkDYRT0= -golang.org/x/mod v0.21.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY= +golang.org/x/mod v0.28.0 h1:gQBtGhjxykdjY9YhZpSlZIsbnaE2+PgjfLWUQTnoZ1U= +golang.org/x/mod v0.28.0/go.mod h1:yfB/L0NOf/kmEbXjzCPOx1iK1fRutOydrCMsqRhEBxI= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -439,17 +525,15 @@ golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.0.0-20210614182718-04defd469f4e/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.3.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE= -golang.org/x/net v0.38.0 h1:vRMAPTMaeGqVhG5QyLJHqNDwecKTomGeqbnfZyKlBI8= -golang.org/x/net v0.38.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8= +golang.org/x/net v0.44.0 h1:evd8IRDyfNBMBTTY5XRF1vaZlD+EmWx6x8PkhR04H/I= +golang.org/x/net v0.44.0/go.mod h1:ECOoLqd5U3Lhyeyo/QDCEVQ4sNgYsqvCZ722XogGieY= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.28.0 h1:CrgCKl8PPAVtLnU3c+EDw6x11699EWlsDeWNWKdIOkc= @@ -460,12 +544,11 @@ golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220819030929-7fc1605a5dde/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.12.0 h1:MHc5BpPuC30uJk597Ri8TV3CNZcTLu6B6z4lJy+g6Jw= -golang.org/x/sync v0.12.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= +golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug= +golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -479,19 +562,24 @@ golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20210616045830-e2b7044e8c71/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211007075335-d3039528d8ac/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220829200755-d48e67d00261/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220906165534-d0df966e6959/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik= -golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc= +golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/telemetry v0.0.0-20250908211612-aef8a434d053 h1:dHQOQddU4YHS5gY33/6klKjq7Gp3WwMyOXGNp5nzRj8= +golang.org/x/telemetry v0.0.0-20250908211612-aef8a434d053/go.mod h1:+nZKN+XVh4LCiA9DV3ywrzN4gumyCnKjau3NGb9SGoE= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.3.0/go.mod h1:q750SLmJuPmVoN1blW3UFBPREJfb1KmY3vwxfr+nFDA= -golang.org/x/term v0.30.0 h1:PQ39fJZ+mfadBm0y5WlL4vlM7Sx1Hgf13sMIY2+QS9Y= -golang.org/x/term v0.30.0/go.mod h1:NYYFdzHoI5wRh/h5tDMdMqCqPJZEuNqVR5xJLd/n67g= +golang.org/x/term v0.37.0 h1:8EGAD0qCmHYZg6J17DvsMy9/wJ7/D/4pV/wfnld5lTU= +golang.org/x/term v0.37.0/go.mod h1:5pB4lxRNYYVZuTLmy8oR2BH8dflOR+IbTYFD8fi3254= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= @@ -499,8 +587,8 @@ golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY= -golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4= +golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk= +golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4= golang.org/x/time v0.7.0 h1:ntUhktv3OPE6TgYxXWv9vKvUSJyIFJlyohwbkEwPrKQ= golang.org/x/time v0.7.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -515,8 +603,8 @@ golang.org/x/tools v0.0.0-20200624163319-25775e59acb7/go.mod h1:EkVYQZoAsY45+roY golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.4.0/go.mod h1:UE5sM2OK9E/d67R0ANs2xJizIymRP5gJU295PvKXxjQ= -golang.org/x/tools v0.26.0 h1:v/60pFQmzmT9ExmjDv2gGIfi3OqfKoEP6I5+umXlbnQ= -golang.org/x/tools v0.26.0/go.mod h1:TPVVj70c7JJ3WCazhD8OdXcZg/og+b9+tH/KxylGwH0= +golang.org/x/tools v0.37.0 h1:DVSRzp7FwePZW356yEAChSdNcQo6Nsp+fex1SUW09lE= +golang.org/x/tools v0.37.0/go.mod h1:MBN5QPQtLMHVdvsbtarmTNukZDdgwdwlO5qGacAzF0w= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -546,7 +634,6 @@ google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8 google.golang.org/grpc v1.33.1/go.mod h1:fr5YgcSWrqhRRxogOsw7RzIpsmvOZ6IcH4kBYTpR3n0= google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= -google.golang.org/grpc v1.38.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= google.golang.org/grpc v1.45.0/go.mod h1:lN7owxKUQEqMfSyQikvvk5tf/6zMPsrK+ONuO11+0rQ= google.golang.org/grpc v1.59.0 h1:Z5Iec2pjwb+LEOqzpB2MR12/eKFhDPhuqW91O+4bwUk= google.golang.org/grpc v1.59.0/go.mod h1:aUPDwccQo6OTjy7Hct4AfBPD1GptF4fyUjIkQ9YtF98= @@ -561,12 +648,10 @@ google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpAD google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -google.golang.org/protobuf v1.27.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -google.golang.org/protobuf v1.35.1 h1:m3LfL6/Ca+fqnjnlqQXNpFPABW1UD7mjh8KO2mKFytA= -google.golang.org/protobuf v1.35.1/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= +google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= +google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= @@ -583,6 +668,8 @@ gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gotest.tools/v3 v3.0.3 h1:4AuOwCGf4lLR9u3YOe2awrHygurzhO/HeQ6laiA6Sx0= +gotest.tools/v3 v3.0.3/go.mod h1:Z7Lb0S5l+klDB31fvDQX8ss/FlKDxtlFlw3Oa8Ymbl8= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7 h1:mub0MmFLOn8XLikZOAhgLD1kXJq8jgftSrrv7m00xFo= @@ -599,8 +686,9 @@ k8s.io/kube-openapi v0.0.0-20241105132330-32ad38e42d3f h1:GA7//TjRY9yWGy1poLzYYJ k8s.io/kube-openapi v0.0.0-20241105132330-32ad38e42d3f/go.mod h1:R/HEjbvWI0qdfb8viZUeVZm0X6IZnxAydC7YU42CMw4= k8s.io/utils v0.0.0-20241104100929-3ea5e8cea738 h1:M3sRQVHv7vB20Xc2ybTt7ODCeFj6JSWYFzOFnYeS6Ro= k8s.io/utils v0.0.0-20241104100929-3ea5e8cea738/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= -mvdan.cc/gofumpt v0.4.0 h1:JVf4NN1mIpHogBj7ABpgOyZc65/UUOkKQFkoURsz4MM= mvdan.cc/gofumpt v0.4.0/go.mod h1:PljLOHDeZqgS8opHRKLzp2It2VBuSdteAgqUfzMTxlQ= +mvdan.cc/gofumpt v0.5.0 h1:0EQ+Z56k8tXjj/6TQD25BFNKQXpCvT0rnansIc7Ug5E= +mvdan.cc/gofumpt v0.5.0/go.mod h1:HBeVDtMKRZpXyxFciAirzdKklDlGu8aAy1wEbH5Y9js= pgregory.net/rapid v1.1.0 h1:CMa0sjHSru3puNx+J0MIAuiiEV4N0qj8/cMWGBBCsjw= pgregory.net/rapid v1.1.0/go.mod h1:PY5XlDGj0+V1FCq0o192FdRhpKHGTRIWBgqjDBTrq04= sigs.k8s.io/json v0.0.0-20241010143419-9aa6b5e7a4b3 h1:/Rv+M11QRah1itp8VhT6HoVx1Ray9eB4DBr+K+/sCJ8= diff --git a/lib/README.md b/lib/README.md new file mode 100644 index 0000000000..0b478e3cd1 --- /dev/null +++ b/lib/README.md @@ -0,0 +1,23 @@ +# Vendored lib packages + +This directory contains vendored packages from `github.com/sourcegraph/sourcegraph/lib`. + +## Source + +- **Repository**: https://github.com/sourcegraph/sourcegraph +- **Commit**: 2ee2b8e77de9663b08ce5f6e5a2c7d2217ce721a +- **Date**: 2025-11-17 19:49:42 -0800 + +## Updating + +To update these vendored packages, run: + +```bash +./dev/vendor-lib.sh +``` + +The script will: +1. Validate that `../sourcegraph` is on the `main` branch with no uncommitted changes +2. Discover all direct and transitive dependencies on `lib` packages +3. Copy only the needed packages +4. Update this README with the new commit information diff --git a/lib/accesstoken/personal_access_token.go b/lib/accesstoken/personal_access_token.go new file mode 100644 index 0000000000..2fe68066eb --- /dev/null +++ b/lib/accesstoken/personal_access_token.go @@ -0,0 +1,29 @@ +// Package accesstoken is exposed in lib/ for usage in src-cli +package accesstoken + +import ( + "sync" + + "github.com/grafana/regexp" // avoid pulling in internal lazyregexp package + + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +var makePersonalAccessTokenRegex = sync.OnceValue[*regexp.Regexp](func() *regexp.Regexp { + return regexp.MustCompile("^(?:(?:sgp_|sgph_)(?:[a-zA-Z0-9]+_)?)?([a-fA-F0-9]{40})$") +}) + +// ParsePersonalAccessToken parses a personal access token to remove prefixes and extract the that is stored in the database +// Personal access tokens can take several forms: +// - +// - sgp_ +// - sgp__ +func ParsePersonalAccessToken(token string) (string, error) { + tokenMatches := makePersonalAccessTokenRegex().FindStringSubmatch(token) + if len(tokenMatches) <= 1 { + return "", errors.New("invalid token format") + } + tokenValue := tokenMatches[1] + + return tokenValue, nil +} diff --git a/lib/api/version_check.go b/lib/api/version_check.go new file mode 100644 index 0000000000..a5c1000bdc --- /dev/null +++ b/lib/api/version_check.go @@ -0,0 +1,49 @@ +package api + +import ( + "github.com/grafana/regexp" + + "github.com/Masterminds/semver" +) + +// BuildDateRegex matches the build date in a Sourcegraph version string. +var BuildDateRegex = regexp.MustCompile(`\d+_(\d{4}-\d{2}-\d{2})_(\d+\.\d+)?-?[a-z0-9]{7,}(_patch)?$`) + +// CheckSourcegraphVersion checks if the given version satisfies the given constraint. +// NOTE: A version with a prerelease suffix (e.g. the "-rc.3" of "3.35.1-rc.3") is not +// considered by semver to satisfy a constraint without a prerelease suffix, regardless of +// whether or not the major/minor/patch version is greater than or equal to that of the +// constraint. +// +// For example, the version "3.35.1-rc.3" is not considered to satisfy the constraint ">= +// 3.23.0". This is likely not the expected outcome. However, the same version IS +// considered to satisfy the constraint "3.23.0-0". Thus, it is recommended to pass a +// constraint with a minimum prerelease version suffix attached if comparisons to +// prerelease versions are ever expected. See +// https://github.com/Masterminds/semver#working-with-prerelease-versions for more. +func CheckSourcegraphVersion(version, constraint, minDate string) (bool, error) { + if version == "dev" || version == "0.0.0+dev" { + return true, nil + } + + // Since we don't actually care about the abbreviated commit hash at the end of the + // version string, we match on 7 or more characters. Currently, the Sourcegraph version + // is expected to return 12: + // https://sourcegraph.com/github.com/sourcegraph/sourcegraph/-/blob/dev/ci/internal/ci/config.go?L96. + matches := BuildDateRegex.FindStringSubmatch(version) + if len(matches) > 1 { + return matches[1] >= minDate, nil + } + + c, err := semver.NewConstraint(constraint) + if err != nil { + return false, nil + } + + v, err := semver.NewVersion(version) + if err != nil { + return false, err + } + + return c.Check(v), nil +} diff --git a/lib/batches/batch_spec.go b/lib/batches/batch_spec.go new file mode 100644 index 0000000000..e558c286f4 --- /dev/null +++ b/lib/batches/batch_spec.go @@ -0,0 +1,264 @@ +package batches + +import ( + "fmt" + "strings" + + "github.com/sourcegraph/sourcegraph/lib/batches/env" + "github.com/sourcegraph/sourcegraph/lib/batches/overridable" + "github.com/sourcegraph/sourcegraph/lib/batches/schema" + "github.com/sourcegraph/sourcegraph/lib/batches/template" + "github.com/sourcegraph/sourcegraph/lib/batches/yaml" + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +// Some general notes about the struct definitions below. +// +// 1. They map _very_ closely to the batch spec JSON schema. We don't +// auto-generate the types because we need YAML support (more on that in a +// moment) and because no generator can currently handle oneOf fields +// gracefully in Go, but that's a potential future enhancement. +// +// 2. Fields are tagged with _both_ JSON and YAML tags. Internally, the JSON +// schema library needs to be able to marshal the struct to JSON for +// validation, so we need to ensure that we're generating the right JSON to +// represent the YAML that we unmarshalled. +// +// 3. All JSON tags include omitempty so that the schema validation can pick up +// omitted fields. The other option here was to have everything unmarshal to +// pointers, which is ugly and inefficient. + +type BatchSpec struct { + Version int `json:"version,omitempty" yaml:"version"` + Name string `json:"name,omitempty" yaml:"name"` + Description string `json:"description,omitempty" yaml:"description"` + On []OnQueryOrRepository `json:"on,omitempty" yaml:"on"` + Workspaces []WorkspaceConfiguration `json:"workspaces,omitempty" yaml:"workspaces"` + Steps []Step `json:"steps,omitempty" yaml:"steps"` + TransformChanges *TransformChanges `json:"transformChanges,omitempty" yaml:"transformChanges,omitempty"` + ImportChangesets []ImportChangeset `json:"importChangesets,omitempty" yaml:"importChangesets"` + ChangesetTemplate *ChangesetTemplate `json:"changesetTemplate,omitempty" yaml:"changesetTemplate"` +} + +type ChangesetTemplate struct { + Title string `json:"title,omitempty" yaml:"title"` + Body string `json:"body,omitempty" yaml:"body"` + Branch string `json:"branch,omitempty" yaml:"branch"` + Fork *bool `json:"fork,omitempty" yaml:"fork"` + Commit ExpandedGitCommitDescription `json:"commit" yaml:"commit"` + Published *overridable.BoolOrString `json:"published" yaml:"published"` +} + +type GitCommitAuthor struct { + Name string `json:"name" yaml:"name"` + Email string `json:"email" yaml:"email"` +} + +type ExpandedGitCommitDescription struct { + Message string `json:"message,omitempty" yaml:"message"` + Author *GitCommitAuthor `json:"author,omitempty" yaml:"author"` +} + +type ImportChangeset struct { + Repository string `json:"repository" yaml:"repository"` + ExternalIDs []any `json:"externalIDs" yaml:"externalIDs"` +} + +type WorkspaceConfiguration struct { + RootAtLocationOf string `json:"rootAtLocationOf,omitempty" yaml:"rootAtLocationOf"` + In string `json:"in,omitempty" yaml:"in"` + OnlyFetchWorkspace bool `json:"onlyFetchWorkspace,omitempty" yaml:"onlyFetchWorkspace"` +} + +type OnQueryOrRepository struct { + RepositoriesMatchingQuery string `json:"repositoriesMatchingQuery,omitempty" yaml:"repositoriesMatchingQuery"` + Repository string `json:"repository,omitempty" yaml:"repository"` + Branch string `json:"branch,omitempty" yaml:"branch"` + Branches []string `json:"branches,omitempty" yaml:"branches"` +} + +var ErrConflictingBranches = NewValidationError(errors.New("both branch and branches specified")) + +func (oqor *OnQueryOrRepository) GetBranches() ([]string, error) { + if oqor.Branch != "" { + if len(oqor.Branches) > 0 { + return nil, ErrConflictingBranches + } + return []string{oqor.Branch}, nil + } + return oqor.Branches, nil +} + +type Step struct { + Run string `json:"run,omitempty" yaml:"run"` + Container string `json:"container,omitempty" yaml:"container"` + Env env.Environment `json:"env" yaml:"env"` + Files map[string]string `json:"files,omitempty" yaml:"files,omitempty"` + Outputs Outputs `json:"outputs,omitempty" yaml:"outputs,omitempty"` + Mount []Mount `json:"mount,omitempty" yaml:"mount,omitempty"` + If any `json:"if,omitempty" yaml:"if,omitempty"` +} + +func (s *Step) IfCondition() string { + switch v := s.If.(type) { + case bool: + if v { + return "true" + } + return "false" + case string: + return v + default: + return "" + } +} + +type Outputs map[string]Output + +type Output struct { + Value string `json:"value,omitempty" yaml:"value,omitempty"` + Format string `json:"format,omitempty" yaml:"format,omitempty"` +} + +type TransformChanges struct { + Group []Group `json:"group,omitempty" yaml:"group"` +} + +type Group struct { + Directory string `json:"directory,omitempty" yaml:"directory"` + Branch string `json:"branch,omitempty" yaml:"branch"` + Repository string `json:"repository,omitempty" yaml:"repository"` +} + +type Mount struct { + Mountpoint string `json:"mountpoint" yaml:"mountpoint"` + Path string `json:"path" yaml:"path"` +} + +func ParseBatchSpec(data []byte) (*BatchSpec, error) { + return parseBatchSpec(schema.BatchSpecJSON, data) +} + +func parseBatchSpec(schema string, data []byte) (*BatchSpec, error) { + var spec BatchSpec + if err := yaml.UnmarshalValidate(schema, data, &spec); err != nil { + var multiErr errors.MultiError + if errors.As(err, &multiErr) { + var newMultiError error + + for _, e := range multiErr.Errors() { + // In case of `name` we try to make the error message more user-friendly. + if strings.Contains(e.Error(), "name: Does not match pattern") { + newMultiError = errors.Append(newMultiError, NewValidationError(errors.Newf("The batch change name can only contain word characters, dots and dashes. No whitespace or newlines allowed."))) + } else { + newMultiError = errors.Append(newMultiError, NewValidationError(e)) + } + } + + return nil, newMultiError + } + + return nil, err + } + + var errs error + + if len(spec.Steps) != 0 && spec.ChangesetTemplate == nil { + errs = errors.Append(errs, NewValidationError(errors.New("batch spec includes steps but no changesetTemplate"))) + } + + for i, step := range spec.Steps { + for _, mount := range step.Mount { + if strings.Contains(mount.Path, invalidMountCharacters) { + errs = errors.Append(errs, NewValidationError(errors.Newf("step %d mount path contains invalid characters", i+1))) + } + if strings.Contains(mount.Mountpoint, invalidMountCharacters) { + errs = errors.Append(errs, NewValidationError(errors.Newf("step %d mount mountpoint contains invalid characters", i+1))) + } + } + } + + return &spec, errs +} + +const invalidMountCharacters = "," + +func (on *OnQueryOrRepository) String() string { + if on.RepositoriesMatchingQuery != "" { + return on.RepositoriesMatchingQuery + } else if on.Repository != "" { + return "repository:" + on.Repository + } + + return fmt.Sprintf("%v", *on) +} + +// BatchSpecValidationError is returned when parsing/using values from the batch spec failed. +type BatchSpecValidationError struct { + err error +} + +func NewValidationError(err error) BatchSpecValidationError { + return BatchSpecValidationError{err} +} + +func (e BatchSpecValidationError) Error() string { + return e.err.Error() +} + +func IsValidationError(err error) bool { + return errors.HasType[*BatchSpecValidationError](err) +} + +// SkippedStepsForRepo calculates the steps required to run on the given repo. +func SkippedStepsForRepo(spec *BatchSpec, repoName string, fileMatches []string) (skipped map[int]struct{}, err error) { + skipped = map[int]struct{}{} + + for idx, step := range spec.Steps { + // If no if condition is set the step is always run. + if step.IfCondition() == "" { + continue + } + + batchChange := template.BatchChangeAttributes{ + Name: spec.Name, + Description: spec.Description, + } + // TODO: This step ctx is incomplete, is this allowed? + // We can at least optimize further here and do more static evaluation + // when we have a cached result for the previous step. + stepCtx := &template.StepContext{ + Repository: template.Repository{ + Name: repoName, + FileMatches: fileMatches, + }, + BatchChange: batchChange, + } + static, boolVal, err := template.IsStaticBool(step.IfCondition(), stepCtx) + if err != nil { + return nil, err + } + + if static && !boolVal { + skipped[idx] = struct{}{} + } + } + + return skipped, nil +} + +// RequiredEnvVars inspects all steps for outer environment variables used and +// compiles a deduplicated list from those. +func (s *BatchSpec) RequiredEnvVars() []string { + requiredMap := map[string]struct{}{} + required := []string{} + for _, step := range s.Steps { + for _, v := range step.Env.OuterVars() { + if _, ok := requiredMap[v]; !ok { + requiredMap[v] = struct{}{} + required = append(required, v) + } + } + } + return required +} diff --git a/lib/batches/changeset_spec.go b/lib/batches/changeset_spec.go new file mode 100644 index 0000000000..4b64f670a1 --- /dev/null +++ b/lib/batches/changeset_spec.go @@ -0,0 +1,273 @@ +package batches + +import ( + "encoding/json" + "reflect" + "strconv" + + jsonutil "github.com/sourcegraph/sourcegraph/lib/batches/json" + "github.com/sourcegraph/sourcegraph/lib/batches/schema" + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +// ErrHeadBaseMismatch is returned by (*ChangesetSpec).UnmarshalValidate() if +// the head and base repositories do not match (a case which we do not support +// yet). +var ErrHeadBaseMismatch = errors.New("headRepository does not match baseRepository") + +// ParseChangesetSpec unmarshals the RawSpec into Spec and validates it against +// the ChangesetSpec schema and does additional semantic validation. +func ParseChangesetSpec(rawSpec []byte) (*ChangesetSpec, error) { + spec := &ChangesetSpec{} + err := jsonutil.UnmarshalValidate(schema.ChangesetSpecJSON, rawSpec, &spec) + if err != nil { + return nil, err + } + + headRepo := spec.HeadRepository + baseRepo := spec.BaseRepository + if headRepo != "" && baseRepo != "" && headRepo != baseRepo { + return nil, ErrHeadBaseMismatch + } + + return spec, nil +} + +// ParseChangesetSpecExternalID attempts to parse the ID of a changeset in the +// batch spec that should be imported. +func ParseChangesetSpecExternalID(id any) (string, error) { + var sid string + + switch tid := id.(type) { + case string: + sid = tid + case int, int8, int16, int32, int64: + sid = strconv.FormatInt(reflect.ValueOf(id).Int(), 10) + case uint, uint8, uint16, uint32, uint64: + sid = strconv.FormatUint(reflect.ValueOf(id).Uint(), 10) + case float32: + sid = strconv.FormatFloat(float64(tid), 'f', -1, 32) + case float64: + sid = strconv.FormatFloat(tid, 'f', -1, 64) + default: + return "", NewValidationError(errors.Newf("cannot convert value of type %T into a valid external ID: expected string or int", id)) + } + + return sid, nil +} + +// Note: When modifying this struct, make sure to reflect the new fields below in +// the customized MarshalJSON method. + +type ChangesetSpec struct { + // BaseRepository is the GraphQL ID of the base repository. + BaseRepository string `json:"baseRepository,omitempty"` + + // If this is not empty, the description is a reference to an existing + // changeset and the rest of these fields are empty. + ExternalID string `json:"externalID,omitempty"` + + BaseRev string `json:"baseRev,omitempty"` + BaseRef string `json:"baseRef,omitempty"` + + // HeadRepository is the GraphQL ID of the head repository. + HeadRepository string `json:"headRepository,omitempty"` + HeadRef string `json:"headRef,omitempty"` + + Title string `json:"title,omitempty"` + Body string `json:"body,omitempty"` + Fork *bool `json:"fork,omitempty"` + + Commits []GitCommitDescription `json:"commits,omitempty"` + + Published PublishedValue `json:"published"` +} + +// MarshalJSON overwrites the default behavior of the json lib while unmarshalling +// a *ChangesetSpec. We explicitly only set Published, when it's non-nil. Due to +// it not being a pointer, omitempty does nothing. That causes it to fail schema +// validation. +// TODO: This is the easiest workaround for now, without risking breaking anything +// right before the release. Ideally, we split up this type into two separate ones +// in the future. +// See https://github.com/sourcegraph/sourcegraph-public-snapshot/issues/25968. +func (c *ChangesetSpec) MarshalJSON() ([]byte, error) { + v := struct { + BaseRepository string `json:"baseRepository,omitempty"` + ExternalID string `json:"externalID,omitempty"` + BaseRev string `json:"baseRev,omitempty"` + BaseRef string `json:"baseRef,omitempty"` + HeadRepository string `json:"headRepository,omitempty"` + HeadRef string `json:"headRef,omitempty"` + Title string `json:"title,omitempty"` + Body string `json:"body,omitempty"` + Commits []GitCommitDescription `json:"commits,omitempty"` + Published *PublishedValue `json:"published,omitempty"` + Fork *bool `json:"fork,omitempty"` + }{ + BaseRepository: c.BaseRepository, + ExternalID: c.ExternalID, + BaseRev: c.BaseRev, + BaseRef: c.BaseRef, + HeadRepository: c.HeadRepository, + HeadRef: c.HeadRef, + Title: c.Title, + Body: c.Body, + Commits: c.Commits, + Fork: c.Fork, + } + if !c.Published.Nil() { + v.Published = &c.Published + } + return json.Marshal(&v) +} + +type GitCommitDescription struct { + Version int `json:"version,omitempty"` + Message string `json:"message,omitempty"` + Diff []byte `json:"diff,omitempty"` + AuthorName string `json:"authorName,omitempty"` + AuthorEmail string `json:"authorEmail,omitempty"` +} + +func (a GitCommitDescription) MarshalJSON() ([]byte, error) { + if a.Version == 2 { + return json.Marshal(v2GitCommitDescription(a)) + } + return json.Marshal(v1GitCommitDescription{ + Message: a.Message, + Diff: string(a.Diff), + AuthorName: a.AuthorName, + AuthorEmail: a.AuthorEmail, + }) +} + +func (a *GitCommitDescription) UnmarshalJSON(data []byte) error { + var version versionGitCommitDescription + if err := json.Unmarshal(data, &version); err != nil { + return err + } + if version.Version == 2 { + var v2 v2GitCommitDescription + if err := json.Unmarshal(data, &v2); err != nil { + return err + } + a.Version = v2.Version + a.Message = v2.Message + a.Diff = v2.Diff + a.AuthorName = v2.AuthorName + a.AuthorEmail = v2.AuthorEmail + return nil + } + var v1 v1GitCommitDescription + if err := json.Unmarshal(data, &v1); err != nil { + return err + } + a.Message = v1.Message + a.Diff = []byte(v1.Diff) + a.AuthorName = v1.AuthorName + a.AuthorEmail = v1.AuthorEmail + return nil +} + +type versionGitCommitDescription struct { + Version int `json:"version,omitempty"` +} + +type v2GitCommitDescription struct { + Version int `json:"version,omitempty"` + Message string `json:"message,omitempty"` + Diff []byte `json:"diff,omitempty"` + AuthorName string `json:"authorName,omitempty"` + AuthorEmail string `json:"authorEmail,omitempty"` +} + +type v1GitCommitDescription struct { + Message string `json:"message,omitempty"` + Diff string `json:"diff,omitempty"` + AuthorName string `json:"authorName,omitempty"` + AuthorEmail string `json:"authorEmail,omitempty"` +} + +// Type returns the ChangesetSpecDescriptionType of the ChangesetSpecDescription. +func (d *ChangesetSpec) Type() ChangesetSpecDescriptionType { + if d.ExternalID != "" { + return ChangesetSpecDescriptionTypeExisting + } + return ChangesetSpecDescriptionTypeBranch +} + +// IsImportingExisting returns whether the description is of type +// ChangesetSpecDescriptionTypeExisting. +func (d *ChangesetSpec) IsImportingExisting() bool { + return d.Type() == ChangesetSpecDescriptionTypeExisting +} + +// IsBranch returns whether the description is of type +// ChangesetSpecDescriptionTypeBranch. +func (d *ChangesetSpec) IsBranch() bool { + return d.Type() == ChangesetSpecDescriptionTypeBranch +} + +// ChangesetSpecDescriptionType tells the consumer what the type of a +// ChangesetSpecDescription is without having to look into the description. +// Useful in the GraphQL when a HiddenChangesetSpec is returned. +type ChangesetSpecDescriptionType string + +// Valid ChangesetSpecDescriptionTypes kinds +const ( + ChangesetSpecDescriptionTypeExisting ChangesetSpecDescriptionType = "EXISTING" + ChangesetSpecDescriptionTypeBranch ChangesetSpecDescriptionType = "BRANCH" +) + +// ErrNoCommits is returned by (*ChangesetSpecDescription).Diff if the +// description doesn't have any commits descriptions. +var ErrNoCommits = errors.New("changeset description doesn't contain commit descriptions") + +// Diff returns the Diff of the first GitCommitDescription in Commits. If the +// ChangesetSpecDescription doesn't have Commits it returns ErrNoCommits. +// +// We currently only support a single commit in Commits. Once we support more, +// this method will need to be revisited. +func (d *ChangesetSpec) Diff() ([]byte, error) { + if len(d.Commits) == 0 { + return nil, ErrNoCommits + } + return d.Commits[0].Diff, nil +} + +// CommitMessage returns the Message of the first GitCommitDescription in Commits. If the +// ChangesetSpecDescription doesn't have Commits it returns ErrNoCommits. +// +// We currently only support a single commit in Commits. Once we support more, +// this method will need to be revisited. +func (d *ChangesetSpec) CommitMessage() (string, error) { + if len(d.Commits) == 0 { + return "", ErrNoCommits + } + return d.Commits[0].Message, nil +} + +// AuthorName returns the author name of the first GitCommitDescription in Commits. If the +// ChangesetSpecDescription doesn't have Commits it returns ErrNoCommits. +// +// We currently only support a single commit in Commits. Once we support more, +// this method will need to be revisited. +func (d *ChangesetSpec) AuthorName() (string, error) { + if len(d.Commits) == 0 { + return "", ErrNoCommits + } + return d.Commits[0].AuthorName, nil +} + +// AuthorEmail returns the author email of the first GitCommitDescription in Commits. If the +// ChangesetSpecDescription doesn't have Commits it returns ErrNoCommits. +// +// We currently only support a single commit in Commits. Once we support more, +// this method will need to be revisited. +func (d *ChangesetSpec) AuthorEmail() (string, error) { + if len(d.Commits) == 0 { + return "", ErrNoCommits + } + return d.Commits[0].AuthorEmail, nil +} diff --git a/lib/batches/changeset_specs.go b/lib/batches/changeset_specs.go new file mode 100644 index 0000000000..a3758d09a6 --- /dev/null +++ b/lib/batches/changeset_specs.go @@ -0,0 +1,310 @@ +package batches + +import ( + "context" + "strings" + + godiff "github.com/sourcegraph/go-diff/diff" + + "github.com/sourcegraph/sourcegraph/lib/batches/execution" + "github.com/sourcegraph/sourcegraph/lib/batches/git" + "github.com/sourcegraph/sourcegraph/lib/batches/template" + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +// Repository is a repository in which the steps of a batch spec are executed. +// +// It is part of the cache.ExecutionKey, so changes to the names of fields here +// will lead to cache busts. +type Repository struct { + ID string + Name string + BaseRef string + BaseRev string + FileMatches []string +} + +type ChangesetSpecInput struct { + Repository Repository + + BatchChangeAttributes *template.BatchChangeAttributes `json:"-"` + Template *ChangesetTemplate `json:"-"` + TransformChanges *TransformChanges `json:"-"` + Path string + + Result execution.AfterStepResult +} + +type ChangesetSpecAuthor struct { + Name string + Email string +} + +func BuildChangesetSpecs(input *ChangesetSpecInput, binaryDiffs bool, fallbackAuthor *ChangesetSpecAuthor) ([]*ChangesetSpec, error) { + tmplCtx := &template.ChangesetTemplateContext{ + BatchChangeAttributes: *input.BatchChangeAttributes, + Steps: template.StepsContext{ + Changes: input.Result.ChangedFiles, + Path: input.Path, + }, + Outputs: input.Result.Outputs, + Repository: template.Repository{ + Name: input.Repository.Name, + Branch: strings.TrimPrefix(input.Repository.BaseRef, "refs/heads/"), + FileMatches: input.Repository.FileMatches, + }, + } + + var author ChangesetSpecAuthor + + if input.Template.Commit.Author == nil { + if fallbackAuthor != nil { + author = *fallbackAuthor + } else { + // user did not provide author info, so use defaults + author = ChangesetSpecAuthor{ + Name: "Sourcegraph", + Email: "batch-changes@sourcegraph.com", + } + } + } else { + var err error + author.Name, err = template.RenderChangesetTemplateField("authorName", input.Template.Commit.Author.Name, tmplCtx) + if err != nil { + return nil, err + } + author.Email, err = template.RenderChangesetTemplateField("authorEmail", input.Template.Commit.Author.Email, tmplCtx) + if err != nil { + return nil, err + } + } + + title, err := template.RenderChangesetTemplateField("title", input.Template.Title, tmplCtx) + if err != nil { + return nil, err + } + + body, err := template.RenderChangesetTemplateField("body", input.Template.Body, tmplCtx) + if err != nil { + return nil, err + } + + message, err := template.RenderChangesetTemplateField("message", input.Template.Commit.Message, tmplCtx) + if err != nil { + return nil, err + } + + // TODO: As a next step, we should extend the ChangesetTemplateContext to also include + // TransformChanges.Group and then change validateGroups and groupFileDiffs to, for each group, + // render the branch name *before* grouping the diffs. + defaultBranch, err := template.RenderChangesetTemplateField("branch", input.Template.Branch, tmplCtx) + if err != nil { + return nil, err + } + + newSpec := func(branch string, diff []byte) *ChangesetSpec { + var published any = nil + if input.Template.Published != nil { + published = input.Template.Published.ValueWithSuffix(input.Repository.Name, branch) + } + + fork := input.Template.Fork + + version := 1 + if binaryDiffs { + version = 2 + } + + return &ChangesetSpec{ + BaseRepository: input.Repository.ID, + HeadRepository: input.Repository.ID, + BaseRef: input.Repository.BaseRef, + BaseRev: input.Repository.BaseRev, + + HeadRef: git.EnsureRefPrefix(branch), + Title: title, + Body: body, + Fork: fork, + Commits: []GitCommitDescription{ + { + Version: version, + Message: message, + AuthorName: author.Name, + AuthorEmail: author.Email, + Diff: diff, + }, + }, + Published: PublishedValue{Val: published}, + } + } + + var specs []*ChangesetSpec + + groups := groupsForRepository(input.Repository.Name, input.TransformChanges) + if len(groups) != 0 { + err := validateGroups(input.Repository.Name, input.Template.Branch, groups) + if err != nil { + return specs, err + } + + // TODO: Regarding 'defaultBranch', see comment above + diffsByBranch, err := groupFileDiffs(input.Result.Diff, defaultBranch, groups) + if err != nil { + return specs, errors.Wrap(err, "grouping diffs failed") + } + + for branch, diff := range diffsByBranch { + spec := newSpec(branch, diff) + specs = append(specs, spec) + } + } else { + spec := newSpec(defaultBranch, input.Result.Diff) + specs = append(specs, spec) + } + + return specs, nil +} + +type RepoFetcher func(context.Context, []string) (map[string]string, error) + +func BuildImportChangesetSpecs(ctx context.Context, importChangesets []ImportChangeset, repoFetcher RepoFetcher) (specs []*ChangesetSpec, errs error) { + if len(importChangesets) == 0 { + return nil, nil + } + + var repoNames []string + for _, ic := range importChangesets { + repoNames = append(repoNames, ic.Repository) + } + + repoNameIDs, err := repoFetcher(ctx, repoNames) + if err != nil { + return nil, err + } + + for _, ic := range importChangesets { + repoID, ok := repoNameIDs[ic.Repository] + if !ok { + errs = errors.Append(errs, errors.Newf("repository %q not found", ic.Repository)) + continue + } + for _, id := range ic.ExternalIDs { + extID, err := ParseChangesetSpecExternalID(id) + if err != nil { + errs = errors.Append(errs, err) + continue + } + specs = append(specs, &ChangesetSpec{ + BaseRepository: repoID, + ExternalID: extID, + }) + } + } + + return specs, errs +} + +func groupsForRepository(repoName string, transform *TransformChanges) []Group { + groups := []Group{} + + if transform == nil { + return groups + } + + for _, g := range transform.Group { + if g.Repository != "" { + if g.Repository == repoName { + groups = append(groups, g) + } + } else { + groups = append(groups, g) + } + } + + return groups +} + +func validateGroups(repoName, defaultBranch string, groups []Group) error { + uniqueBranches := make(map[string]struct{}, len(groups)) + + for _, g := range groups { + if _, ok := uniqueBranches[g.Branch]; ok { + return NewValidationError(errors.Newf("transformChanges would lead to multiple changesets in repository %s to have the same branch %q", repoName, g.Branch)) + } else { + uniqueBranches[g.Branch] = struct{}{} + } + + if g.Branch == defaultBranch { + return NewValidationError(errors.Newf("transformChanges group branch for repository %s is the same as branch %q in changesetTemplate", repoName, defaultBranch)) + } + } + + return nil +} + +func groupFileDiffs(completeDiff []byte, defaultBranch string, groups []Group) (map[string][]byte, error) { + fileDiffs, err := godiff.ParseMultiFileDiff(completeDiff) + if err != nil { + return nil, err + } + + // Housekeeping: we setup these two datastructures so we can + // - access the group.Branch by the directory for which they should be used + // - check against the given directories, in order. + branchesByDirectory := make(map[string]string, len(groups)) + dirs := make([]string, 0, len(groups)) + for _, g := range groups { + branchesByDirectory[g.Directory] = g.Branch + dirs = append(dirs, g.Directory) + } + + byBranch := make(map[string][]*godiff.FileDiff, len(groups)) + byBranch[defaultBranch] = []*godiff.FileDiff{} + + // For each file diff... + for _, f := range fileDiffs { + // strip git's b/ or a/ prefix off paths + name := strings.TrimPrefix(f.NewName, "b/") + if name == "/dev/null" { + name = strings.TrimPrefix(f.OrigName, "a/") + } + + // .. we check whether it matches one of the given directories in the + // group transformations, with the last match winning: + var matchingDir string + for _, d := range dirs { + // We ignore the ~ . and ./ prefixes so that we can support relative and absolute paths. + dWithoutPrefix := strings.TrimLeft(d, "~./") + // We have to add a trailing suffix so that we don't match files that have the same name as other directories. + dWithDirSuffix := dWithoutPrefix + "/" + if strings.HasPrefix(name, dWithDirSuffix) { + matchingDir = d + } + } + + // If the diff didn't match a rule, it goes into the default branch and + // the default changeset. + if matchingDir == "" { + byBranch[defaultBranch] = append(byBranch[defaultBranch], f) + continue + } + + // If it *did* match a directory, we look up which branch we should use: + branch, ok := branchesByDirectory[matchingDir] + if !ok { + panic("this should not happen: " + matchingDir) + } + + byBranch[branch] = append(byBranch[branch], f) + } + + finalDiffsByBranch := make(map[string][]byte, len(byBranch)) + for branch, diffs := range byBranch { + printed, err := godiff.PrintMultiFileDiff(diffs) + if err != nil { + return nil, errors.Wrap(err, "printing multi file diff failed") + } + finalDiffsByBranch[branch] = printed + } + return finalDiffsByBranch, nil +} diff --git a/lib/batches/env/env.go b/lib/batches/env/env.go new file mode 100644 index 0000000000..89e60619f1 --- /dev/null +++ b/lib/batches/env/env.go @@ -0,0 +1,170 @@ +// Package env provides types to handle step environments in batch specs. +package env + +import ( + "encoding/json" + "strings" + + "github.com/google/go-cmp/cmp" + + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +// Environment represents an environment used for a batch step, which may +// require values to be resolved from the outer environment the executor is +// running within. +type Environment struct { + vars []variable +} + +// MarshalJSON marshals the environment. +func (e Environment) MarshalJSON() ([]byte, error) { + if e.vars == nil { + return []byte(`{}`), nil + } + + // For compatibility with older versions of Sourcegraph, if all environment + // variables have static values defined, we'll encode to the object variant. + if e.IsStatic() { + vars := make(map[string]string, len(e.vars)) + for _, v := range e.vars { + vars[v.name] = *v.value + } + + return json.Marshal(vars) + } + + // Otherwise, we have to return the array variant. + return json.Marshal(e.vars) +} + +// UnmarshalJSON unmarshals an environment from one of the two supported JSON +// forms: an array, or a string→string object. +func (e *Environment) UnmarshalJSON(data []byte) error { + // data is either an array or object. (Or invalid.) Let's start by trying to + // unmarshal it as an array. + if err := json.Unmarshal(data, &e.vars); err == nil { + return nil + } + + // It's an object, then. We need to put it into a map, then convert it into + // an array of variables. + kv := make(map[string]string) + if err := json.Unmarshal(data, &kv); err != nil { + return err + } + + e.vars = make([]variable, len(kv)) + i := 0 + for k, v := range kv { + copy := v + e.vars[i].name = k + e.vars[i].value = © + i++ + } + + return nil +} + +// UnmarshalYAML unmarshals an environment from one of the two supported YAML +// forms: an array, or a string→string object. +func (e *Environment) UnmarshalYAML(unmarshal func(any) error) error { + // data is either an array or object. (Or invalid.) Let's start by trying to + // unmarshal it as an array. + if err := unmarshal(&e.vars); err == nil { + return nil + } + + // It's an object, then. As above, we need to convert this via a map. + kv := make(map[string]string) + if err := unmarshal(&kv); err != nil { + return err + } + + e.vars = make([]variable, len(kv)) + i := 0 + for k, v := range kv { + copy := v + e.vars[i].name = k + e.vars[i].value = © + i++ + } + + return nil +} + +// IsStatic returns true if the environment doesn't depend on any outer +// environment variables. +// +// Put another way: if this function returns true, then Resolve() will always +// return the same map for the environment. +func (e Environment) IsStatic() bool { + for _, v := range e.vars { + if v.value == nil { + return false + } + } + return true +} + +// OuterVars returns the list of environment variables that depend on any +// environment variable defined in the global env. +func (e Environment) OuterVars() []string { + outer := []string{} + for _, v := range e.vars { + if v.value == nil { + outer = append(outer, v.name) + } + } + return outer +} + +// Resolve resolves the environment, using values from the given outer +// environment to fill in environment values as needed. If an environment +// variable doesn't exist in the outer environment, then an empty string will be +// used as the value. +// +// outer must be an array of strings in the form `KEY=VALUE`. Generally +// speaking, this will be the return value from os.Environ(). +func (e Environment) Resolve(outer []string) (map[string]string, error) { + // Convert the given outer environment into a map. + omap := make(map[string]string, len(outer)) + for _, v := range outer { + kv := strings.SplitN(v, "=", 2) + if len(kv) != 2 { + return nil, errors.Errorf("unable to parse environment variable %q", v) + } + omap[kv[0]] = kv[1] + } + + // Now we can iterate over our own environment and fill in the missing + // values. + resolved := make(map[string]string, len(e.vars)) + for _, v := range e.vars { + if v.value == nil { + // We don't bother checking if v.name exists in omap here because + // the default behaviour is what we want anyway: we'll get an empty + // string (since that's the zero value for a string), and that is + // the desired outcome if the environment variable isn't set. + resolved[v.name] = omap[v.name] + } else { + resolved[v.name] = *v.value + } + } + + return resolved, nil +} + +// Equal verifies if two environments are equal. +func (e Environment) Equal(other Environment) bool { + return cmp.Equal(e.mapify(), other.mapify()) +} + +func (e Environment) mapify() map[string]*string { + m := make(map[string]*string, len(e.vars)) + for _, v := range e.vars { + m[v.name] = v.value + } + + return m +} diff --git a/lib/batches/env/var.go b/lib/batches/env/var.go new file mode 100644 index 0000000000..1e63c00662 --- /dev/null +++ b/lib/batches/env/var.go @@ -0,0 +1,99 @@ +package env + +import ( + "encoding/json" + "fmt" + + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +// variable is an individual environment variable within an Environment +// instance. If the value is nil, then it needs to be resolved before being +// used, which occurs in Environment.Resolve(). +type variable struct { + name string + value *string +} + +var errInvalidVariableType = errors.New("invalid environment variable: unknown type") + +type errInvalidVariableObject struct{ n int } + +func (e errInvalidVariableObject) Error() string { + return fmt.Sprintf("invalid environment variable: incorrect number of object elements (expected 1, got %d)", e.n) +} + +func (v variable) MarshalJSON() ([]byte, error) { + if v.value != nil { + return json.Marshal(map[string]string{v.name: *v.value}) + } + + return json.Marshal(v.name) +} + +func (v *variable) UnmarshalJSON(data []byte) error { + // This can be a string or an object with one property. Let's try the string + // case first. + var k string + if err := json.Unmarshal(data, &k); err == nil { + v.name = k + v.value = nil + return nil + } + + // We should have a bouncing baby object, then. + var kv map[string]string + if err := json.Unmarshal(data, &kv); err != nil { + return errInvalidVariableType + } else if len(kv) != 1 { + return errInvalidVariableObject{n: len(kv)} + } + + for k, value := range kv { + v.name = k + v.value = &value + } + + return nil +} + +func (v *variable) UnmarshalYAML(unmarshal func(any) error) error { + // This can be a string or an object with one property. Let's try the string + // case first. + var k string + if err := unmarshal(&k); err == nil { + v.name = k + v.value = nil + return nil + } + + // Object time. + var kv map[string]string + if err := unmarshal(&kv); err != nil { + return errInvalidVariableType + } else if len(kv) != 1 { + return errInvalidVariableObject{n: len(kv)} + } + + for k, value := range kv { + v.name = k + v.value = &value + } + + return nil +} + +// Equal checks if two environment variables are equal. +func (a variable) Equal(b variable) bool { + if a.name != b.name { + return false + } + + if a.value == nil && b.value == nil { + return true + } + if a.value == nil || b.value == nil { + return false + } + return *a.value == *b.value +} diff --git a/lib/batches/execution/cache/cache.go b/lib/batches/execution/cache/cache.go new file mode 100644 index 0000000000..9392cd2c31 --- /dev/null +++ b/lib/batches/execution/cache/cache.go @@ -0,0 +1,174 @@ +package cache + +import ( + "context" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "fmt" + "sort" + "time" + + "github.com/sourcegraph/sourcegraph/lib/batches" + "github.com/sourcegraph/sourcegraph/lib/batches/execution" + "github.com/sourcegraph/sourcegraph/lib/batches/template" + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +type Cache interface { + Get(ctx context.Context, key Keyer) (result execution.AfterStepResult, found bool, err error) + Set(ctx context.Context, key Keyer, result execution.AfterStepResult) error + + Clear(ctx context.Context, key Keyer) error +} + +type Keyer interface { + Key() (string, error) + Slug() string +} + +// MetadataRetriever retrieves mount metadata. +type MetadataRetriever interface { + // Get returns the mount metadata from the provided steps. + Get([]batches.Step) ([]MountMetadata, error) +} + +// MountMetadata is the metadata of a file that is mounted by a Step. +type MountMetadata struct { + Path string + Size int64 + Modified time.Time +} + +func (key CacheKey) mountsMetadata() ([]MountMetadata, error) { + if key.MetadataRetriever != nil { + return key.MetadataRetriever.Get(key.Steps) + } + return nil, nil +} + +// resolveStepsEnvironment returns a slice of environments for each of the steps, +// containing only the env vars that are actually used. +func resolveStepsEnvironment(globalEnv []string, steps []batches.Step) ([]map[string]string, error) { + // We have to resolve the step environments and include them in the cache + // key to ensure that the cache is properly invalidated when an environment + // variable changes. + // + // Note that we don't base the cache key on the entire global environment: + // if an unrelated environment variable changes, that's fine. We're only + // interested in the ones that actually make it into the step container. + envs := make([]map[string]string, len(steps)) + for i, step := range steps { + // TODO: This should also render templates inside env vars. + env, err := step.Env.Resolve(globalEnv) + if err != nil { + return nil, errors.Wrapf(err, "resolving environment for step %d", i) + } + envs[i] = env + } + return envs, nil +} + +func marshalAndHash(key *CacheKey, envs []map[string]string, metadata []MountMetadata) (string, error) { + raw, err := json.Marshal(struct { + *CacheKey + Environments []map[string]string + // Omit if empty to be backwards compatible. + MountsMetadata []MountMetadata `json:"MountsMetadata,omitempty"` + }{ + CacheKey: key, + Environments: envs, + MountsMetadata: metadata, + }) + if err != nil { + return "", err + } + + hash := sha256.Sum256(raw) + return base64.RawURLEncoding.EncodeToString(hash[:16]), nil +} + +// CacheKey implements the Keyer interface for a batch spec execution in a +// repository workspace and a *subset* of its Steps, up to and including the +// step with index StepIndex in Task.Steps. +type CacheKey struct { + Repository batches.Repository + Path string + OnlyFetchWorkspace bool + Steps []batches.Step + BatchChangeAttributes *template.BatchChangeAttributes + + // Ignore from serialization. + MetadataRetriever MetadataRetriever `json:"-"` + // Ignore from serialization. + GlobalEnv []string `json:"-"` + + StepIndex int +} + +// Key converts the key into a string form that can be used to uniquely identify +// the cache key in a more concise form than the entire Task. +func (key CacheKey) Key() (string, error) { + // Setup a copy of the cache key that only includes the Steps up to and + // including key.StepIndex. + clone := key + clone.Steps = key.Steps[0 : key.StepIndex+1] + + // Resolve environment only for the subset of Steps. + envs, err := resolveStepsEnvironment(key.GlobalEnv, clone.Steps) + if err != nil { + return "", err + } + metadata, err := key.mountsMetadata() + if err != nil { + return "", err + } + + hash, err := marshalAndHash(&clone, envs, metadata) + if err != nil { + return "", err + } + return fmt.Sprintf("%s-step-%d", hash, key.StepIndex), err +} + +func (key CacheKey) Slug() string { + return SlugForRepo(key.Repository.Name, key.Repository.BaseRev) +} + +func KeyForWorkspace(batchChangeAttributes *template.BatchChangeAttributes, r batches.Repository, path string, globalEnv []string, onlyFetchWorkspace bool, steps []batches.Step, stepIndex int, retriever MetadataRetriever) Keyer { + sort.Strings(r.FileMatches) + + return CacheKey{ + Repository: r, + Path: path, + OnlyFetchWorkspace: onlyFetchWorkspace, + GlobalEnv: globalEnv, + Steps: steps, + BatchChangeAttributes: batchChangeAttributes, + StepIndex: stepIndex, + MetadataRetriever: retriever, + } +} + +// ChangesetSpecsFromCache takes the execution.Result and generates all changeset specs from it. +func ChangesetSpecsFromCache(spec *batches.BatchSpec, r batches.Repository, result execution.AfterStepResult, path string, binaryDiffs bool, fallbackAuthor *batches.ChangesetSpecAuthor) ([]*batches.ChangesetSpec, error) { + if len(result.Diff) == 0 { + return []*batches.ChangesetSpec{}, nil + } + + sort.Strings(r.FileMatches) + + input := &batches.ChangesetSpecInput{ + Repository: r, + BatchChangeAttributes: &template.BatchChangeAttributes{ + Name: spec.Name, + Description: spec.Description, + }, + Template: spec.ChangesetTemplate, + TransformChanges: spec.TransformChanges, + Result: result, + Path: path, + } + + return batches.BuildChangesetSpecs(input, binaryDiffs, fallbackAuthor) +} diff --git a/lib/batches/execution/cache/util.go b/lib/batches/execution/cache/util.go new file mode 100644 index 0000000000..bc4cf8436e --- /dev/null +++ b/lib/batches/execution/cache/util.go @@ -0,0 +1,7 @@ +package cache + +import "strings" + +func SlugForRepo(repoName, commit string) string { + return strings.ReplaceAll(repoName, "/", "-") + "-" + commit +} diff --git a/lib/batches/execution/results.go b/lib/batches/execution/results.go new file mode 100644 index 0000000000..4426430708 --- /dev/null +++ b/lib/batches/execution/results.go @@ -0,0 +1,98 @@ +package execution + +import ( + "encoding/json" + + "github.com/sourcegraph/sourcegraph/lib/batches/git" +) + +// AfterStepResult is the execution result after executing a step with the given +// index in Steps. +type AfterStepResult struct { + Version int `json:"version"` + // Files are the changes made to Files by the step. + ChangedFiles git.Changes `json:"changedFiles"` + // Stdout is the output produced by the step on standard out. + Stdout string `json:"stdout"` + // Stderr is the output produced by the step on standard error. + Stderr string `json:"stderr"` + // StepIndex is the index of the step in the list of steps. + StepIndex int `json:"stepIndex"` + // Diff is the cumulative `git diff` after executing the Step. + Diff []byte `json:"diff"` + // Outputs is a copy of the Outputs after executing the Step. + Outputs map[string]any `json:"outputs"` + // Skipped determines whether the step was skipped. + Skipped bool `json:"skipped"` +} + +func (a AfterStepResult) MarshalJSON() ([]byte, error) { + if a.Version == 2 { + return json.Marshal(v2AfterStepResult(a)) + } + return json.Marshal(v1AfterStepResult{ + ChangedFiles: a.ChangedFiles, + Stdout: a.Stdout, + Stderr: a.Stderr, + StepIndex: a.StepIndex, + Diff: string(a.Diff), + Outputs: a.Outputs, + }) +} + +func (a *AfterStepResult) UnmarshalJSON(data []byte) error { + var version versionAfterStepResult + if err := json.Unmarshal(data, &version); err != nil { + return err + } + if version.Version == 2 { + var v2 v2AfterStepResult + if err := json.Unmarshal(data, &v2); err != nil { + return err + } + a.Version = v2.Version + a.ChangedFiles = v2.ChangedFiles + a.Stdout = v2.Stdout + a.Stderr = v2.Stderr + a.StepIndex = v2.StepIndex + a.Diff = v2.Diff + a.Outputs = v2.Outputs + a.Skipped = v2.Skipped + return nil + } + var v1 v1AfterStepResult + if err := json.Unmarshal(data, &v1); err != nil { + return err + } + a.ChangedFiles = v1.ChangedFiles + a.Stdout = v1.Stdout + a.Stderr = v1.Stderr + a.StepIndex = v1.StepIndex + a.Diff = []byte(v1.Diff) + a.Outputs = v1.Outputs + return nil +} + +type versionAfterStepResult struct { + Version int `json:"version"` +} + +type v2AfterStepResult struct { + Version int `json:"version"` + ChangedFiles git.Changes `json:"changedFiles"` + Stdout string `json:"stdout"` + Stderr string `json:"stderr"` + StepIndex int `json:"stepIndex"` + Diff []byte `json:"diff"` + Outputs map[string]any `json:"outputs"` + Skipped bool `json:"skipped"` +} + +type v1AfterStepResult struct { + ChangedFiles git.Changes `json:"changedFiles"` + Stdout string `json:"stdout"` + Stderr string `json:"stderr"` + StepIndex int `json:"stepIndex"` + Diff string `json:"diff"` + Outputs map[string]any `json:"outputs"` +} diff --git a/lib/batches/git/changes.go b/lib/batches/git/changes.go new file mode 100644 index 0000000000..7da33db848 --- /dev/null +++ b/lib/batches/git/changes.go @@ -0,0 +1,37 @@ +package git + +import ( + "github.com/sourcegraph/go-diff/diff" +) + +// Changes are the changes made to files in a repository. +type Changes struct { + Modified []string `json:"modified"` + Added []string `json:"added"` + Deleted []string `json:"deleted"` + Renamed []string `json:"renamed"` +} + +func ChangesInDiff(rawDiff []byte) (Changes, error) { + result := Changes{} + + fileDiffs, err := diff.ParseMultiFileDiff(rawDiff) + if err != nil { + return result, err + } + + for _, fd := range fileDiffs { + switch { + case fd.NewName == "/dev/null": + result.Deleted = append(result.Deleted, fd.OrigName) + case fd.OrigName == "/dev/null": + result.Added = append(result.Added, fd.NewName) + case fd.OrigName == fd.NewName: + result.Modified = append(result.Modified, fd.OrigName) + case fd.OrigName != fd.NewName: + result.Renamed = append(result.Renamed, fd.NewName) + } + } + + return result, nil +} diff --git a/lib/batches/git/refs.go b/lib/batches/git/refs.go new file mode 100644 index 0000000000..7e840c4b29 --- /dev/null +++ b/lib/batches/git/refs.go @@ -0,0 +1,10 @@ +package git + +import "strings" + +func EnsureRefPrefix(ref string) string { + if strings.HasPrefix(ref, "refs/heads/") { + return ref + } + return "refs/heads/" + ref +} diff --git a/lib/batches/json/validate.go b/lib/batches/json/validate.go new file mode 100644 index 0000000000..9e38b6f108 --- /dev/null +++ b/lib/batches/json/validate.go @@ -0,0 +1,24 @@ +package json + +import ( + "encoding/json" + + "github.com/sourcegraph/sourcegraph/lib/batches/jsonschema" + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +// UnmarshalValidate validates the JSON input against the provided JSON schema. +// If the validation is successful the validated input is unmarshalled into the +// target. +func UnmarshalValidate(schema string, input []byte, target any) error { + var errs error + if err := jsonschema.Validate(schema, input); err != nil { + errs = errors.Append(errs, err) + } + + if err := json.Unmarshal(input, target); err != nil { + errs = errors.Append(errs, err) + } + + return errs +} diff --git a/lib/batches/json_logs.go b/lib/batches/json_logs.go new file mode 100644 index 0000000000..03477d038c --- /dev/null +++ b/lib/batches/json_logs.go @@ -0,0 +1,334 @@ +package batches + +import ( + "encoding/json" + "time" + + "github.com/sourcegraph/sourcegraph/lib/batches/execution" + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +type LogEvent struct { + Operation LogEventOperation `json:"operation"` + + Timestamp time.Time `json:"timestamp"` + + Status LogEventStatus `json:"status"` + Metadata any `json:"metadata,omitempty"` +} + +type logEventJSON struct { + Operation LogEventOperation `json:"operation"` + Timestamp time.Time `json:"timestamp"` + Status LogEventStatus `json:"status"` +} + +func (l *LogEvent) UnmarshalJSON(data []byte) error { + var j *logEventJSON + if err := json.Unmarshal(data, &j); err != nil { + return err + } + l.Operation = j.Operation + l.Timestamp = j.Timestamp + l.Status = j.Status + + switch l.Operation { + case LogEventOperationParsingBatchSpec: + l.Metadata = new(ParsingBatchSpecMetadata) + case LogEventOperationResolvingNamespace: + l.Metadata = new(ResolvingNamespaceMetadata) + case LogEventOperationPreparingDockerImages: + l.Metadata = new(PreparingDockerImagesMetadata) + case LogEventOperationDeterminingWorkspaceType: + l.Metadata = new(DeterminingWorkspaceTypeMetadata) + case LogEventOperationDeterminingWorkspaces: + l.Metadata = new(DeterminingWorkspacesMetadata) + case LogEventOperationCheckingCache: + l.Metadata = new(CheckingCacheMetadata) + case LogEventOperationExecutingTasks: + l.Metadata = new(ExecutingTasksMetadata) + case LogEventOperationLogFileKept: + l.Metadata = new(LogFileKeptMetadata) + case LogEventOperationUploadingChangesetSpecs: + l.Metadata = new(UploadingChangesetSpecsMetadata) + case LogEventOperationCreatingBatchSpec: + l.Metadata = new(CreatingBatchSpecMetadata) + case LogEventOperationApplyingBatchSpec: + l.Metadata = new(ApplyingBatchSpecMetadata) + case LogEventOperationBatchSpecExecution: + l.Metadata = new(BatchSpecExecutionMetadata) + case LogEventOperationExecutingTask: + l.Metadata = new(ExecutingTaskMetadata) + case LogEventOperationTaskBuildChangesetSpecs: + l.Metadata = new(TaskBuildChangesetSpecsMetadata) + case LogEventOperationTaskSkippingSteps: + l.Metadata = new(TaskSkippingStepsMetadata) + case LogEventOperationTaskStepSkipped: + l.Metadata = new(TaskStepSkippedMetadata) + case LogEventOperationTaskPreparingStep: + l.Metadata = new(TaskPreparingStepMetadata) + case LogEventOperationTaskStep: + l.Metadata = new(TaskStepMetadata) + case LogEventOperationCacheAfterStepResult: + l.Metadata = new(CacheAfterStepResultMetadata) + case LogEventOperationDockerWatchDog: + l.Metadata = new(DockerWatchDogMetadata) + default: + return errors.Newf("invalid event type %s", l.Operation) + } + + wrapper := struct { + Metadata any `json:"metadata"` + }{ + Metadata: l.Metadata, + } + + return json.Unmarshal(data, &wrapper) +} + +type LogEventOperation string + +const ( + LogEventOperationParsingBatchSpec LogEventOperation = "PARSING_BATCH_SPEC" + LogEventOperationResolvingNamespace LogEventOperation = "RESOLVING_NAMESPACE" + LogEventOperationPreparingDockerImages LogEventOperation = "PREPARING_DOCKER_IMAGES" + LogEventOperationDeterminingWorkspaceType LogEventOperation = "DETERMINING_WORKSPACE_TYPE" + LogEventOperationDeterminingWorkspaces LogEventOperation = "DETERMINING_WORKSPACES" + LogEventOperationCheckingCache LogEventOperation = "CHECKING_CACHE" + LogEventOperationExecutingTasks LogEventOperation = "EXECUTING_TASKS" + LogEventOperationLogFileKept LogEventOperation = "LOG_FILE_KEPT" + LogEventOperationUploadingChangesetSpecs LogEventOperation = "UPLOADING_CHANGESET_SPECS" + LogEventOperationCreatingBatchSpec LogEventOperation = "CREATING_BATCH_SPEC" + LogEventOperationApplyingBatchSpec LogEventOperation = "APPLYING_BATCH_SPEC" + LogEventOperationBatchSpecExecution LogEventOperation = "BATCH_SPEC_EXECUTION" + LogEventOperationExecutingTask LogEventOperation = "EXECUTING_TASK" + LogEventOperationTaskBuildChangesetSpecs LogEventOperation = "TASK_BUILD_CHANGESET_SPECS" + LogEventOperationTaskSkippingSteps LogEventOperation = "TASK_SKIPPING_STEPS" + LogEventOperationTaskStepSkipped LogEventOperation = "TASK_STEP_SKIPPED" + LogEventOperationTaskPreparingStep LogEventOperation = "TASK_PREPARING_STEP" + LogEventOperationTaskStep LogEventOperation = "TASK_STEP" + LogEventOperationCacheAfterStepResult LogEventOperation = "CACHE_AFTER_STEP_RESULT" + LogEventOperationDockerWatchDog LogEventOperation = "DOCKER_WATCH_DOG" +) + +type LogEventStatus string + +const ( + LogEventStatusStarted LogEventStatus = "STARTED" + LogEventStatusSuccess LogEventStatus = "SUCCESS" + LogEventStatusFailure LogEventStatus = "FAILURE" + LogEventStatusProgress LogEventStatus = "PROGRESS" +) + +type ParsingBatchSpecMetadata struct { + Error string `json:"error,omitempty"` +} + +type ResolvingNamespaceMetadata struct { + NamespaceID string `json:"namespaceID,omitempty"` +} + +type PreparingDockerImagesMetadata struct { + Done int `json:"done,omitempty"` + Total int `json:"total,omitempty"` +} + +type DeterminingWorkspaceTypeMetadata struct { + Type string `json:"type,omitempty"` +} + +type DeterminingWorkspacesMetadata struct { + Unsupported int `json:"unsupported,omitempty"` + Ignored int `json:"ignored,omitempty"` + RepoCount int `json:"repoCount,omitempty"` + WorkspaceCount int `json:"workspaceCount,omitempty"` +} + +type CheckingCacheMetadata struct { + CachedSpecsFound int `json:"cachedSpecsFound,omitempty"` + TasksToExecute int `json:"tasksToExecute,omitempty"` +} + +type JSONLinesTask struct { + ID string `json:"id"` + Repository string `json:"repository"` + Workspace string `json:"workspace"` + Steps []Step `json:"steps"` + CachedStepResultsFound bool `json:"cachedStepResultFound"` + StartStep int `json:"startStep"` +} + +type ExecutingTasksMetadata struct { + Tasks []JSONLinesTask `json:"tasks,omitempty"` + Skipped bool `json:"skipped,omitempty"` + Error string `json:"error,omitempty"` +} + +type LogFileKeptMetadata struct { + Path string `json:"path,omitempty"` +} + +type UploadingChangesetSpecsMetadata struct { + Done int `json:"done,omitempty"` + Total int `json:"total,omitempty"` + // IDs is the slice of GraphQL IDs of the created changeset specs. + IDs []string `json:"ids,omitempty"` +} + +type CreatingBatchSpecMetadata struct { + PreviewURL string `json:"previewURL,omitempty"` +} + +type ApplyingBatchSpecMetadata struct { + BatchChangeURL string `json:"batchChangeURL,omitempty"` +} + +type BatchSpecExecutionMetadata struct { + Error string `json:"error,omitempty"` +} + +type ExecutingTaskMetadata struct { + TaskID string `json:"taskID,omitempty"` + Error string `json:"error,omitempty"` +} + +type TaskBuildChangesetSpecsMetadata struct { + TaskID string `json:"taskID,omitempty"` +} + +type TaskSkippingStepsMetadata struct { + TaskID string `json:"taskID,omitempty"` + StartStep int `json:"startStep,omitempty"` +} + +type TaskStepSkippedMetadata struct { + TaskID string `json:"taskID,omitempty"` + Step int `json:"step,omitempty"` +} + +type TaskPreparingStepMetadata struct { + TaskID string `json:"taskID,omitempty"` + Step int `json:"step,omitempty"` + Error string `json:"error,omitempty"` +} + +type TaskStepMetadata struct { + Version int + TaskID string + Step int + + RunScript string + Env map[string]string + + Out string + + Diff []byte + Outputs map[string]any + + ExitCode int + Error string +} + +func (m TaskStepMetadata) MarshalJSON() ([]byte, error) { + if m.Version == 2 { + return json.Marshal(v2TaskStepMetadata{ + Version: 2, + TaskID: m.TaskID, + Step: m.Step, + RunScript: m.RunScript, + Env: m.Env, + Out: m.Out, + Diff: m.Diff, + Outputs: m.Outputs, + ExitCode: m.ExitCode, + Error: m.Error, + }) + } + return json.Marshal(v1TaskStepMetadata{ + TaskID: m.TaskID, + Step: m.Step, + RunScript: m.RunScript, + Env: m.Env, + Out: m.Out, + Diff: string(m.Diff), + Outputs: m.Outputs, + ExitCode: m.ExitCode, + Error: m.Error, + }) +} + +func (m *TaskStepMetadata) UnmarshalJSON(data []byte) error { + var version versionTaskStepMetadata + if err := json.Unmarshal(data, &version); err != nil { + return err + } + if version.Version == 2 { + var v2 v2TaskStepMetadata + if err := json.Unmarshal(data, &v2); err != nil { + return err + } + m.Version = v2.Version + m.TaskID = v2.TaskID + m.Step = v2.Step + m.RunScript = v2.RunScript + m.Env = v2.Env + m.Out = v2.Out + m.Diff = v2.Diff + m.Outputs = v2.Outputs + m.ExitCode = v2.ExitCode + m.Error = v2.Error + return nil + } + var v1 v1TaskStepMetadata + if err := json.Unmarshal(data, &v1); err != nil { + return errors.Wrap(err, string(data)) + } + m.TaskID = v1.TaskID + m.Step = v1.Step + m.RunScript = v1.RunScript + m.Env = v1.Env + m.Out = v1.Out + m.Diff = []byte(v1.Diff) + m.Outputs = v1.Outputs + m.ExitCode = v1.ExitCode + m.Error = v1.Error + return nil +} + +type versionTaskStepMetadata struct { + Version int `json:"version,omitempty"` +} + +type v2TaskStepMetadata struct { + Version int `json:"version,omitempty"` + TaskID string `json:"taskID,omitempty"` + Step int `json:"step,omitempty"` + RunScript string `json:"runScript,omitempty"` + Env map[string]string `json:"env,omitempty"` + Out string `json:"out,omitempty"` + Diff []byte `json:"diff,omitempty"` + Outputs map[string]any `json:"outputs,omitempty"` + ExitCode int `json:"exitCode,omitempty"` + Error string `json:"error,omitempty"` +} + +type v1TaskStepMetadata struct { + TaskID string `json:"taskID,omitempty"` + Step int `json:"step,omitempty"` + RunScript string `json:"runScript,omitempty"` + Env map[string]string `json:"env,omitempty"` + Out string `json:"out,omitempty"` + Diff string `json:"diff,omitempty"` + Outputs map[string]any `json:"outputs,omitempty"` + ExitCode int `json:"exitCode,omitempty"` + Error string `json:"error,omitempty"` +} + +type CacheAfterStepResultMetadata struct { + Key string `json:"key,omitempty"` + Value execution.AfterStepResult `json:"value"` +} + +type DockerWatchDogMetadata struct { + Error string `json:"error,omitempty"` +} diff --git a/lib/batches/jsonschema/jsonschema.go b/lib/batches/jsonschema/jsonschema.go new file mode 100644 index 0000000000..28d1c10dea --- /dev/null +++ b/lib/batches/jsonschema/jsonschema.go @@ -0,0 +1,36 @@ +package jsonschema + +import ( + "strings" + + "github.com/xeipuuv/gojsonschema" + + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +// Validate validates the given input against the JSON schema. +// +// It returns either nil, in case the input is valid, or an error. +func Validate(schema string, input []byte) error { + sl := gojsonschema.NewSchemaLoader() + sc, err := sl.Compile(gojsonschema.NewStringLoader(schema)) + if err != nil { + return errors.Wrap(err, "failed to compile JSON schema") + } + + res, err := sc.Validate(gojsonschema.NewBytesLoader(input)) + if err != nil { + return errors.Wrap(err, "failed to validate input against schema") + } + + var errs error + for _, err := range res.Errors() { + e := err.String() + // Remove `(root): ` from error formatting since these errors are + // presented to users. + e = strings.TrimPrefix(e, "(root): ") + errs = errors.Append(errs, errors.New(e)) + } + + return errs +} diff --git a/lib/batches/outputs.go b/lib/batches/outputs.go new file mode 100644 index 0000000000..03649b5018 --- /dev/null +++ b/lib/batches/outputs.go @@ -0,0 +1,48 @@ +package batches + +import ( + "bytes" + "encoding/json" + "fmt" + + "github.com/sourcegraph/sourcegraph/lib/batches/template" + "github.com/sourcegraph/sourcegraph/lib/errors" + + yamlv3 "gopkg.in/yaml.v3" +) + +// SetOutputs renders the outputs of the current step into the global outputs +// map using templating. +func SetOutputs(stepOutputs Outputs, global map[string]any, stepCtx *template.StepContext) error { + for name, output := range stepOutputs { + var value bytes.Buffer + + if err := template.RenderStepTemplate("outputs-"+name, output.Value, &value, stepCtx); err != nil { + return errors.Wrap(err, "parsing step run") + } + fmt.Printf("Rendering step output %s %s: %q (stdout is %q)\n", name, output.Value, value.String(), stepCtx.Step.Stdout) + + switch output.Format { + case "yaml": + 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. + // See https://github.com/go-yaml/yaml/issues/139 for context + if err := yamlv3.NewDecoder(&value).Decode(&out); err != nil { + return err + } + global[name] = out + case "json": + var out any + if err := json.NewDecoder(&value).Decode(&out); err != nil { + return err + } + global[name] = out + default: + global[name] = value.String() + } + } + + return nil +} diff --git a/lib/batches/overridable/bool.go b/lib/batches/overridable/bool.go new file mode 100644 index 0000000000..411e466071 --- /dev/null +++ b/lib/batches/overridable/bool.go @@ -0,0 +1,69 @@ +package overridable + +import "encoding/json" + +// Bool represents a bool value that can be modified on a per-repo basis. +type Bool struct { + rules rules +} + +// FromBool creates a Bool representing a static, scalar value. +func FromBool(b bool) Bool { + return Bool{ + rules: rules{simpleRule(b)}, + } +} + +// Value returns the bool value for the given repository. +func (b *Bool) Value(name string) bool { + v := b.rules.Match(name) + if v == nil { + return false + } + return v.(bool) +} + +// MarshalJSON encodes the Bool overridable to a json representation. +func (b Bool) MarshalJSON() ([]byte, error) { + if len(b.rules) == 0 { + return []byte("false"), nil + } + return json.Marshal(b.rules) +} + +// UnmarshalJSON unmarshalls a JSON value into a Bool. +func (b *Bool) UnmarshalJSON(data []byte) error { + var all bool + if err := json.Unmarshal(data, &all); err == nil { + *b = Bool{rules: rules{simpleRule(all)}} + return nil + } + + var c complex + if err := json.Unmarshal(data, &c); err != nil { + return err + } + + return b.rules.hydrateFromComplex(c) +} + +// UnmarshalYAML unmarshalls a YAML value into a Bool. +func (b *Bool) UnmarshalYAML(unmarshal func(any) error) error { + var all bool + if err := unmarshal(&all); err == nil { + *b = Bool{rules: rules{simpleRule(all)}} + return nil + } + + var c complex + if err := unmarshal(&c); err != nil { + return err + } + + return b.rules.hydrateFromComplex(c) +} + +// Equal tests two Bools for equality, used in cmp. +func (b Bool) Equal(other Bool) bool { + return b.rules.Equal(other.rules) +} diff --git a/lib/batches/overridable/bool_or_string.go b/lib/batches/overridable/bool_or_string.go new file mode 100644 index 0000000000..4b910b0571 --- /dev/null +++ b/lib/batches/overridable/bool_or_string.go @@ -0,0 +1,83 @@ +package overridable + +import ( + "encoding/json" +) + +// BoolOrString is a set of rules that either evaluate to a string or a bool. +type BoolOrString struct { + rules rules +} + +// FromBoolOrString creates a BoolOrString representing a static, scalar value. +func FromBoolOrString(v any) BoolOrString { + return BoolOrString{ + rules: rules{simpleRule(v)}, + } +} + +// Value returns the value for the given repository. +func (bs *BoolOrString) Value(name string) any { + return bs.rules.Match(name) +} + +// ValueWithSuffix returns the value for the given repository and branch name. +func (bs *BoolOrString) ValueWithSuffix(name, suffix string) any { + return bs.rules.MatchWithSuffix(name, suffix) +} + +// MarshalJSON encodes the BoolOrString overridable to a json representation. +func (bs BoolOrString) MarshalJSON() ([]byte, error) { + if len(bs.rules) == 0 { + return []byte("false"), nil + } + return json.Marshal(bs.rules) +} + +// UnmarshalJSON unmarshalls a JSON value into a Publish. +func (bs *BoolOrString) UnmarshalJSON(data []byte) error { + var b bool + if err := json.Unmarshal(data, &b); err == nil { + *bs = BoolOrString{rules: rules{simpleRule(b)}} + return nil + } + var s string + if err := json.Unmarshal(data, &s); err == nil { + *bs = BoolOrString{rules: rules{simpleRule(s)}} + return nil + } + + var c complex + if err := json.Unmarshal(data, &c); err != nil { + return err + } + + return bs.rules.hydrateFromComplex(c) +} + +// UnmarshalYAML unmarshalls a YAML value into a Publish. +func (bs *BoolOrString) UnmarshalYAML(unmarshal func(any) error) error { + var b bool + if err := unmarshal(&b); err == nil { + *bs = BoolOrString{rules: rules{simpleRule(b)}} + return nil + } + + var s string + if err := unmarshal(&s); err == nil { + *bs = BoolOrString{rules: rules{simpleRule(s)}} + return nil + } + + var c complex + if err := unmarshal(&c); err != nil { + return err + } + + return bs.rules.hydrateFromComplex(c) +} + +// Equal tests two BoolOrStrings for equality, used in cmp. +func (bs BoolOrString) Equal(other BoolOrString) bool { + return bs.rules.Equal(other.rules) +} diff --git a/lib/batches/overridable/overridable.go b/lib/batches/overridable/overridable.go new file mode 100644 index 0000000000..61cfaadd9b --- /dev/null +++ b/lib/batches/overridable/overridable.go @@ -0,0 +1,143 @@ +// Package overridable provides data types representing values in batch +// specs that can be overridden for specific repositories. +package overridable + +import ( + "encoding/json" + "strings" + + "github.com/gobwas/glob" + + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +// allPattern is used to define default rules for the simple scalar case. +const allPattern = "*" + +// simpleRule creates the simplest of rules for the given value: `"*": value`. +func simpleRule(v any) *rule { + r, err := newRule(allPattern, v) + if err != nil { + // Since we control the pattern being compiled, an error should never + // occur. + panic(err) + } + + return r +} + +type complex []map[string]any + +type rule struct { + // pattern is the glob-syntax pattern, such as "a/b/ceee-*" + pattern string + // patternSuffix is an optional suffix that can be appended to the pattern with "@" + patternSuffix string + + compiled glob.Glob + value any +} + +// newRule builds a new rule instance, ensuring that the glob pattern +// is compiled. +func newRule(pattern string, value any) (*rule, error) { + var suffix string + split := strings.SplitN(pattern, "@", 2) + if len(split) > 1 { + pattern = split[0] + suffix = split[1] + } + + compiled, err := glob.Compile(pattern) + if err != nil { + return nil, err + } + + return &rule{ + pattern: pattern, + patternSuffix: suffix, + compiled: compiled, + value: value, + }, nil +} + +func (a rule) Equal(b rule) bool { + return a.pattern == b.pattern && a.value == b.value +} + +type rules []*rule + +// Match matches the given repository name against all rules, returning the rule value that matches at last, or nil if none match. +func (r rules) Match(name string) any { + // We want the last match to win, so we'll iterate in reverse order. + for i := len(r) - 1; i >= 0; i-- { + if r[i].compiled.Match(name) { + return r[i].value + } + } + return nil +} + +// MatchWithSuffix matches the given repository name against all rules and the +// suffix against provided pattern suffix, returning the rule value that matches +// at last, or nil if none match. +func (r rules) MatchWithSuffix(name, suffix string) any { + // We want the last match to win, so we'll iterate in reverse order. + for i := len(r) - 1; i >= 0; i-- { + if r[i].compiled.Match(name) && (r[i].patternSuffix == "" || r[i].patternSuffix == suffix) { + return r[i].value + } + } + return nil +} + +// MarshalJSON marshalls the bool into its JSON representation, which will +// either be a literal or an array of objects. +func (r rules) MarshalJSON() ([]byte, error) { + if len(r) == 1 && r[0].pattern == allPattern { + return json.Marshal(r[0].value) + } + + rules := []map[string]any{} + for _, rule := range r { + rules = append(rules, map[string]any{ + rule.pattern: rule.value, + }) + } + return json.Marshal(rules) +} + +// hydrateFromComplex builds an array of rules out of a complex value. +func (r *rules) hydrateFromComplex(c []map[string]any) error { + *r = make(rules, len(c)) + for i, rule := range c { + if len(rule) != 1 { + return errors.Errorf("unexpected number of elements in the array at entry %d: %d (must be 1)", i, len(rule)) + } + for pattern, value := range rule { + var err error + (*r)[i], err = newRule(pattern, value) + if err != nil { + return errors.Wrapf(err, "building rule for array entry %d", i) + } + } + } + return nil +} + +// Equal tests two rules for equality. Used in cmp. +func (r rules) Equal(other rules) bool { + if len(r) != len(other) { + return false + } + + for i := range r { + a := r[i] + b := other[i] + if !a.Equal(*b) { + return false + } + } + + return true +} diff --git a/lib/batches/published.go b/lib/batches/published.go new file mode 100644 index 0000000000..7dbd200c34 --- /dev/null +++ b/lib/batches/published.go @@ -0,0 +1,110 @@ +package batches + +import ( + "encoding/json" + + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +// PublishedValue is a wrapper type that supports the quadruple `true`, `false`, +// `"draft"`, `nil`, or `pushed-only`. +type PublishedValue struct { + Val any +} + +// True is true if the enclosed value is a bool being true. +func (p *PublishedValue) True() bool { + if b, ok := p.Val.(bool); ok { + return b + } + return false +} + +// False is true if the enclosed value is a bool being false. +func (p PublishedValue) False() bool { + if b, ok := p.Val.(bool); ok { + return !b + } + return false +} + +// Draft is true if the enclosed value is a string being "draft". +func (p PublishedValue) Draft() bool { + if s, ok := p.Val.(string); ok { + return s == "draft" + } + return false +} + +// PushedOnly is true if the enclosed value is a string being "pushed-only". +func (p PublishedValue) PushedOnly() bool { + if s, ok := p.Val.(string); ok { + return s == "pushed-only" + } + return false +} + +// Nil is true if the enclosed value is a null or omitted. +func (p PublishedValue) Nil() bool { + return p.Val == nil +} + +// Valid returns whether the enclosed value is of any of the permitted types. +func (p *PublishedValue) Valid() bool { + return p.True() || p.False() || p.Draft() || p.PushedOnly() || p.Nil() +} + +// Value returns the underlying value stored in this wrapper. +func (p *PublishedValue) Value() any { + return p.Val +} + +func (p PublishedValue) MarshalJSON() ([]byte, error) { + if p.Nil() { + v := "null" + return []byte(v), nil + } + if p.True() { + v := "true" + return []byte(v), nil + } + if p.False() { + v := "false" + return []byte(v), nil + } + if p.Draft() { + v := `"draft"` + return []byte(v), nil + } + if p.PushedOnly() { + v := `"pushed-only"` + return []byte(v), nil + } + return nil, errors.Errorf("invalid PublishedValue: %s (%T)", p.Val, p.Val) +} + +func (p *PublishedValue) UnmarshalJSON(b []byte) error { + return json.Unmarshal(b, &p.Val) +} + +// UnmarshalYAML unmarshalls a YAML value into a Publish. +func (p *PublishedValue) UnmarshalYAML(unmarshal func(any) error) error { + if err := unmarshal(&p.Val); err != nil { + return err + } + + return nil +} + +func (p *PublishedValue) UnmarshalGraphQL(input any) error { + p.Val = input + if !p.Valid() { + return errors.Errorf("invalid PublishedValue: %v", input) + } + return nil +} + +// ImplementsGraphQLType lets GraphQL-go tell apart the corresponding GraphQL scalar. +func (p *PublishedValue) ImplementsGraphQLType(name string) bool { + return name == "PublishedValue" +} diff --git a/lib/batches/schema/batch_spec_stringdata.go b/lib/batches/schema/batch_spec_stringdata.go new file mode 100644 index 0000000000..6d412a0a33 --- /dev/null +++ b/lib/batches/schema/batch_spec_stringdata.go @@ -0,0 +1,412 @@ +// Code generated by stringdata. DO NOT EDIT. + +package schema + +// BatchSpecJSON is the content of the file "schema/batch_spec.schema.json". +const BatchSpecJSON = `{ + "$id": "batch_spec.schema.json#", + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "BatchSpec", + "description": "A batch specification, which describes the batch change and what kinds of changes to make (or what existing changesets to track).", + "type": "object", + "additionalProperties": false, + "required": ["name"], + "properties": { + "version": { + "type": "number", + "description": "The version of the batch spec schema. Defaults to 1.", + "enum": [1, 2] + }, + "name": { + "type": "string", + "description": "The name of the batch change, which is unique among all batch changes in the namespace. A batch change's name is case-preserving.", + "pattern": "^[\\w.-]+$" + }, + "description": { + "type": "string", + "description": "The description of the batch change." + }, + "on": { + "type": ["array", "null"], + "description": "The set of repositories (and branches) to run the batch change on, specified as a list of search queries (that match repositories) and/or specific repositories.", + "items": { + "title": "OnQueryOrRepository", + "oneOf": [ + { + "title": "OnQuery", + "type": "object", + "description": "A Sourcegraph search query that matches a set of repositories (and branches). Each matched repository branch is added to the list of repositories that the batch change will be run on.", + "additionalProperties": false, + "required": ["repositoriesMatchingQuery"], + "properties": { + "repositoriesMatchingQuery": { + "type": "string", + "description": "A Sourcegraph search query that matches a set of repositories (and branches). If the query matches files, symbols, or some other object inside a repository, the object's repository is included.", + "examples": ["file:README.md"] + } + } + }, + { + "title": "OnRepository", + "type": "object", + "description": "A specific repository (and branch) that is added to the list of repositories that the batch change will be run on.", + "additionalProperties": false, + "required": ["repository"], + "properties": { + "repository": { + "type": "string", + "description": "The name of the repository (as it is known to Sourcegraph).", + "examples": ["github.com/foo/bar"] + }, + "branch": { + "description": "The repository branch to propose changes to. If unset, the repository's default branch is used. If this field is defined, branches cannot be.", + "type": "string" + }, + "branches": { + "description": "The repository branches to propose changes to. If unset, the repository's default branch is used. If this field is defined, branch cannot be.", + "type": "array", + "items": { + "type": "string" + } + } + }, + "$comment": "This is a convoluted way of saying either ` + "`" + `branch` + "`" + ` or ` + "`" + `branches` + "`" + ` can be provided, but not both at once, and neither are required.", + "anyOf": [ + { + "oneOf": [ + { + "required": ["branch"] + }, + { + "required": ["branches"] + } + ] + }, + { + "not": { + "required": ["branch", "branches"] + } + } + ] + } + ] + } + }, + "workspaces": { + "type": ["array", "null"], + "description": "Individual workspace configurations for one or more repositories that define which workspaces to use for the execution of steps in the repositories.", + "items": { + "title": "WorkspaceConfiguration", + "type": "object", + "description": "Configuration for how to setup workspaces in repositories", + "additionalProperties": false, + "required": ["rootAtLocationOf"], + "properties": { + "rootAtLocationOf": { + "type": "string", + "description": "The name of the file that sits at the root of the desired workspace.", + "examples": ["package.json", "go.mod", "Gemfile", "Cargo.toml", "README.md"] + }, + "in": { + "type": "string", + "description": "The repositories in which to apply the workspace configuration. Supports globbing.", + "examples": ["github.com/sourcegraph/src-cli", "github.com/sourcegraph/*"] + }, + "onlyFetchWorkspace": { + "type": "boolean", + "description": "If this is true only the files in the workspace (and additional .gitignore) are downloaded instead of an archive of the full repository.", + "default": false + } + } + } + }, + "steps": { + "type": ["array", "null"], + "description": "The sequence of commands to run (for each repository branch matched in the ` + "`" + `on` + "`" + ` property) to produce the workspace changes that will be included in the batch change.", + "items": { + "title": "Step", + "type": "object", + "description": "A command to run (as part of a sequence) in a repository branch to produce the required changes.", + "additionalProperties": false, + "required": ["run", "container"], + "properties": { + "run": { + "type": "string", + "description": "The shell command to run in the container. It can also be a multi-line shell script. The working directory is the root directory of the repository checkout." + }, + "container": { + "type": "string", + "description": "The Docker image used to launch the Docker container in which the shell command is run.", + "examples": ["alpine:3"] + }, + "outputs": { + "type": ["object", "null"], + "description": "Output variables of this step that can be referenced in the changesetTemplate or other steps via outputs.", + "additionalProperties": { + "title": "OutputVariable", + "type": "object", + "required": ["value"], + "properties": { + "value": { + "type": "string", + "description": "The value of the output, which can be a template string.", + "examples": ["hello world", "${{ step.stdout }}", "${{ repository.name }}"] + }, + "format": { + "type": "string", + "description": "The expected format of the output. If set, the output is being parsed in that format before being stored in the var. If not set, 'text' is assumed to the format.", + "enum": ["json", "yaml", "text"] + } + } + } + }, + "env": { + "description": "Environment variables to set in the step environment.", + "oneOf": [ + { + "type": "null" + }, + { + "type": "object", + "description": "Environment variables to set in the step environment.", + "additionalProperties": { + "type": "string" + } + }, + { + "type": "array", + "items": { + "oneOf": [ + { + "type": "string", + "description": "An environment variable to set in the step environment: the value will be passed through from the environment src is running within." + }, + { + "type": "object", + "description": "An environment variable to set in the step environment: the key is used as the environment variable name and the value as the value.", + "additionalProperties": { + "type": "string" + }, + "minProperties": 1, + "maxProperties": 1 + } + ] + } + } + ] + }, + "files": { + "type": ["object", "null"], + "description": "Files that should be mounted into or be created inside the Docker container.", + "additionalProperties": { + "type": "string" + } + }, + "if": { + "oneOf": [ + { + "type": "boolean" + }, + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "A condition to check before executing steps. Supports templating. The value 'true' is interpreted as true.", + "examples": [ + "true", + "${{ matches repository.name \"github.com/my-org/my-repo*\" }}", + "${{ outputs.goModFileExists }}", + "${{ eq previous_step.stdout \"success\" }}" + ] + }, + "mount": { + "description": "Files that are mounted to the Docker container.", + "type": ["array", "null"], + "items": { + "type": "object", + "additionalProperties": false, + "required": ["path", "mountpoint"], + "properties": { + "path": { + "type": "string", + "description": "The path on the local machine to mount. The path must be in the same directory or a subdirectory of the batch spec.", + "examples": ["local/path/to/file.text", "local/path/to/directory"] + }, + "mountpoint": { + "type": "string", + "description": "The path in the container to mount the path on the local machine to.", + "examples": ["path/to/file.txt", "path/to/directory"] + } + } + } + } + } + } + }, + "transformChanges": { + "type": ["object", "null"], + "description": "Optional transformations to apply to the changes produced in each repository.", + "additionalProperties": false, + "properties": { + "group": { + "type": ["array", "null"], + "description": "A list of groups of changes in a repository that each create a separate, additional changeset for this repository, with all ungrouped changes being in the default changeset.", + "items": { + "title": "TransformChangesGroup", + "type": "object", + "additionalProperties": false, + "required": ["directory", "branch"], + "properties": { + "directory": { + "type": "string", + "description": "The directory path (relative to the repository root) of the changes to include in this group.", + "minLength": 1 + }, + "branch": { + "type": "string", + "description": "The branch on the repository to propose changes to. If unset, the repository's default branch is used.", + "minLength": 1 + }, + "repository": { + "type": "string", + "description": "Only apply this transformation in the repository with this name (as it is known to Sourcegraph).", + "examples": ["github.com/foo/bar"] + } + } + } + } + } + }, + "importChangesets": { + "type": ["array", "null"], + "description": "Import existing changesets on code hosts.", + "items": { + "type": "object", + "additionalProperties": false, + "required": ["repository", "externalIDs"], + "properties": { + "repository": { + "type": "string", + "description": "The repository name as configured on your Sourcegraph instance." + }, + "externalIDs": { + "type": ["array", "null"], + "description": "The changesets to import from the code host. For GitHub this is the PR number, for GitLab this is the MR number, for Bitbucket Server this is the PR number.", + "uniqueItems": true, + "items": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "examples": [120, "120"] + } + } + } + }, + "changesetTemplate": { + "type": "object", + "description": "A template describing how to create (and update) changesets with the file changes produced by the command steps.", + "additionalProperties": false, + "required": ["title", "branch", "commit"], + "properties": { + "title": { + "type": "string", + "description": "The title of the changeset." + }, + "body": { + "type": "string", + "description": "The body (description) of the changeset." + }, + "branch": { + "type": "string", + "description": "The name of the Git branch to create or update on each repository with the changes." + }, + "fork": { + "type": "boolean", + "description": "Whether to publish the changeset to a fork of the target repository. If omitted, the changeset will be published to a branch directly on the target repository, unless the global ` + "`" + `batches.enforceFork` + "`" + ` setting is enabled. If set, this property will override any global setting." + }, + "commit": { + "title": "ExpandedGitCommitDescription", + "type": "object", + "description": "The Git commit to create with the changes.", + "additionalProperties": false, + "required": ["message"], + "properties": { + "message": { + "type": "string", + "description": "The Git commit message." + }, + "author": { + "title": "GitCommitAuthor", + "type": "object", + "description": "The author of the Git commit.", + "additionalProperties": false, + "required": ["name", "email"], + "properties": { + "name": { + "type": "string", + "description": "The Git commit author name." + }, + "email": { + "type": "string", + "format": "email", + "description": "The Git commit author email." + } + } + } + } + }, + "published": { + "description": "Whether to publish the changeset. An unpublished changeset can be previewed on Sourcegraph by any person who can view the batch change, but its commit, branch, and pull request aren't created on the code host. A published changeset results in a commit, branch, and pull request being created on the code host. If omitted, the publication state is controlled from the Batch Changes UI.", + "oneOf": [ + { + "type": "null" + }, + { + "oneOf": [ + { + "type": "boolean" + }, + { + "type": "string", + "pattern": "^draft$" + } + ], + "description": "A single flag to control the publishing state for the entire batch change." + }, + { + "type": "array", + "description": "A list of glob patterns to match repository names. In the event multiple patterns match, the last matching pattern in the list will be used.", + "items": { + "type": "object", + "description": "An object with one field: the key is the glob pattern to match against repository names; the value will be used as the published flag for matching repositories.", + "additionalProperties": { + "oneOf": [ + { + "type": "boolean" + }, + { + "type": "string", + "pattern": "^draft$" + } + ] + }, + "minProperties": 1, + "maxProperties": 1 + } + } + ] + } + } + } + } +} +` diff --git a/lib/batches/schema/changeset_spec_stringdata.go b/lib/batches/schema/changeset_spec_stringdata.go new file mode 100644 index 0000000000..9ec47ef532 --- /dev/null +++ b/lib/batches/schema/changeset_spec_stringdata.go @@ -0,0 +1,121 @@ +// Code generated by stringdata. DO NOT EDIT. + +package schema + +// ChangesetSpecJSON is the content of the file "schema/changeset_spec.schema.json". +const ChangesetSpecJSON = `{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "ChangesetSpec", + "description": "A changeset specification, which describes a changeset to be created or an existing changeset to be tracked.", + "type": "object", + "oneOf": [ + { + "title": "ExistingChangesetSpec", + "type": "object", + "properties": { + "version": { + "type": "integer", + "description": "A field for versioning the payload." + }, + "baseRepository": { + "type": "string", + "description": "The GraphQL ID of the repository that contains the existing changeset on the code host.", + "examples": ["UmVwb3NpdG9yeTo5Cg=="] + }, + "externalID": { + "type": "string", + "description": "The ID that uniquely identifies the existing changeset on the code host", + "examples": ["3912", "12"] + } + }, + "required": ["baseRepository", "externalID"], + "additionalProperties": false + }, + { + "title": "BranchChangesetSpec", + "type": "object", + "properties": { + "version": { + "type": "integer", + "description": "A field for versioning the payload." + }, + "baseRepository": { + "type": "string", + "description": "The GraphQL ID of the repository that this changeset spec is proposing to change.", + "examples": ["UmVwb3NpdG9yeTo5Cg=="] + }, + "baseRef": { + "type": "string", + "description": "The full name of the Git ref in the base repository that this changeset is based on (and is proposing to be merged into). This ref must exist on the base repository.", + "pattern": "^refs\\/heads\\/\\S+$", + "examples": ["refs/heads/master"] + }, + "baseRev": { + "type": "string", + "description": "The base revision this changeset is based on. It is the latest commit in baseRef at the time when the changeset spec was created.", + "examples": ["4095572721c6234cd72013fd49dff4fb48f0f8a4"] + }, + "headRepository": { + "type": "string", + "description": "The GraphQL ID of the repository that contains the branch with this changeset's changes. Fork repositories and cross-repository changesets are not yet supported. Therefore, headRepository must be equal to baseRepository.", + "examples": ["UmVwb3NpdG9yeTo5Cg=="] + }, + "fork": { + "type": "boolean", + "description": "Whether to publish the changeset to a fork of the target repository. If omitted, the changeset will be published to a branch directly on the target repository, unless the global ` + "`" + `batches.enforceFork` + "`" + ` setting is enabled. If set, this property will override any global setting." + }, + "headRef": { + "type": "string", + "description": "The full name of the Git ref that holds the changes proposed by this changeset. This ref will be created or updated with the commits.", + "pattern": "^refs\\/heads\\/\\S+$", + "examples": ["refs/heads/fix-foo"] + }, + "title": { "type": "string", "description": "The title of the changeset on the code host." }, + "body": { "type": "string", "description": "The body (description) of the changeset on the code host." }, + "commits": { + "type": "array", + "description": "The Git commits with the proposed changes. These commits are pushed to the head ref.", + "minItems": 1, + "maxItems": 1, + "items": { + "title": "GitCommitDescription", + "type": "object", + "description": "The Git commit to create with the changes.", + "additionalProperties": false, + "required": ["message", "diff", "authorName", "authorEmail"], + "properties": { + "version": { + "type": "integer", + "description": "A field for versioning the payload." + }, + "message": { + "type": "string", + "description": "The Git commit message." + }, + "diff": { + "type": "string", + "description": "The commit diff (in unified diff format)." + }, + "authorName": { + "type": "string", + "description": "The Git commit author name." + }, + "authorEmail": { + "type": "string", + "format": "email", + "description": "The Git commit author email." + } + } + } + }, + "published": { + "oneOf": [{ "type": "boolean" }, { "type": "string", "pattern": "^draft$" }, { "type": "null" }], + "description": "Whether to publish the changeset. An unpublished changeset can be previewed on Sourcegraph by any person who can view the batch change, but its commit, branch, and pull request aren't created on the code host. A published changeset results in a commit, branch, and pull request being created on the code host." + } + }, + "required": ["baseRepository", "baseRef", "baseRev", "headRepository", "headRef", "title", "body", "commits"], + "additionalProperties": false + } + ] +} +` diff --git a/lib/batches/template/partial_eval.go b/lib/batches/template/partial_eval.go new file mode 100644 index 0000000000..905ece71d5 --- /dev/null +++ b/lib/batches/template/partial_eval.go @@ -0,0 +1,345 @@ +package template + +import ( + "bytes" + "fmt" + "reflect" + "strings" + "text/template" + "text/template/parse" +) + +// IsStaticBool parses the input as a text/template and attempts to evaluate it +// with only the ahead-of-execution information available in StepContext. +// +// To do that it first calls parseAndPartialEval to evaluate the template as +// much as possible. +// +// If, after evaluation, more than text is left (i.e. because the template +// requires information that's only available later) the function returns with +// the first return value being false, because the template is not "static". +// first return value is true. +// +// If only text is left we check whether that text equals "true". The result of +// that check is the second return value. +func IsStaticBool(input string, ctx *StepContext) (isStatic bool, boolVal bool, err error) { + t, err := parseAndPartialEval(input, ctx) + if err != nil { + return false, false, err + } + + isStatic = true + for _, n := range t.Tree.Root.Nodes { + if n.Type() != parse.NodeText { + isStatic = false + break + } + } + if !isStatic { + return isStatic, false, nil + } + + return true, isTrueOutput(t.Tree.Root), nil +} + +// parseAndPartialEval parses input as a text/template and then attempts to +// partially evaluate the parts of the template it can evaluate ahead of time +// (meaning: before we've executed any batch spec steps and have a full +// StepContext available). +// +// If it's possible to evaluate a parse.ActionNode (which is what sits between +// delimiters in a text/template), the node is rewritten into a parse.TextNode, +// to make it look like it's always been text in the template. +// +// Partial evaluation is done in a best effort manner: if it's not possible to +// evaluate a node (because it requires information that we only later get, or +// because it's too complex, etc.) we degrade gracefully and simply abort the +// partial evaluation and leave the node as is. +// +// It also should be noted that we don't do "full" partial evaluation: if we +// come across value that we can't partially evaluate we abort the process *for +// the whole node* without replacing the sub-nodes that we've successfully +// evaluated. Why? Because we can't construct correct `*parse.Node` from +// outside the `parse` package. In other words: we evaluate +// all-parse.ActionNode-or-nothing. +func parseAndPartialEval(input string, ctx *StepContext) (*template.Template, error) { + t, err := template. + New("partial-eval"). + Delims(startDelim, endDelim). + Funcs(builtins). + Funcs(ctx.ToFuncMap()). + Parse(input) + + if err != nil { + return nil, err + } + + for i, n := range t.Tree.Root.Nodes { + t.Tree.Root.Nodes[i] = rewriteNode(n, ctx) + } + + return t, nil +} + +// rewriteNode takes the given parse.Parse and tries to partially evaluate it. +// If that's possible, the output of the evaluation is turned into text and +// instead of the node that was passed in a new parse.TextNode is returned that +// represents the output of the evaluation. +func rewriteNode(n parse.Node, ctx *StepContext) parse.Node { + switch n := n.(type) { + case *parse.ActionNode: + if val, ok := evalPipe(ctx, n.Pipe); ok { + var out bytes.Buffer + fmt.Fprint(&out, val.Interface()) + return &parse.TextNode{ + Text: out.Bytes(), + Pos: n.Pos, + NodeType: parse.NodeText, + } + } + + return n + + default: + return n + } +} + +// noValue is returned by the functions that partially evaluate a parse.Node +// to signify that evaluation was not possible or did not yield a value. +var noValue reflect.Value + +func evalPipe(ctx *StepContext, p *parse.PipeNode) (finalVal reflect.Value, ok bool) { + // If the pipe contains declaration we abort evaluation. + if len(p.Decl) > 0 { + return noValue, false + } + + // TODO: Support finalVal and pass it in to evalCmd + // finalVal is the value of the previous Cmd in a pipe (i.e. `${{ 3 + 3 | eq 6 }}`) + // It needs to be the final (fixed) argument of a call if it's set. + + for _, c := range p.Cmds { + finalVal, ok = evalCmd(ctx, c) + if !ok { + return noValue, false + } + } + + return finalVal, ok +} + +func evalCmd(ctx *StepContext, c *parse.CommandNode) (reflect.Value, bool) { + switch first := c.Args[0].(type) { + case *parse.BoolNode, *parse.NumberNode, *parse.StringNode, *parse.ChainNode: + if len(c.Args) == 1 { + return evalNode(ctx, first) + } + return noValue, false + + case *parse.IdentifierNode: + // A function call always starts with an identifier + return evalFunction(ctx, first.Ident, c.Args) + + default: + // Node type that we don't care about, so we don't even try to evaluate it + return noValue, false + } +} + +func evalNode(ctx *StepContext, n parse.Node) (reflect.Value, bool) { + switch n := n.(type) { + case *parse.BoolNode: + return reflect.ValueOf(n.True), true + + case *parse.NumberNode: + // This case branch is lifted from Go's text/template execution engine: + // https://sourcegraph.com/github.com/golang/go@2c9f5a1da823773c436f8b2c119635797d6db2d3/-/blob/src/text/template/exec.go#L493-530 + // The difference is that we don't do any error handling but simply abort. + switch { + case n.IsComplex: + return reflect.ValueOf(n.Complex128), true + + case n.IsFloat && + !isHexInt(n.Text) && !isRuneInt(n.Text) && + strings.ContainsAny(n.Text, ".eEpP"): + return reflect.ValueOf(n.Float64), true + + case n.IsInt: + num := int(n.Int64) + if int64(num) != n.Int64 { + return noValue, false + } + return reflect.ValueOf(num), true + + case n.IsUint: + return noValue, false + } + + case *parse.StringNode: + return reflect.ValueOf(n.Text), true + + case *parse.ChainNode: + // For now we only support fields that are 1 level deep (see below). + // Should we ever want to support more than one level, we need to + // revise this. + if len(n.Field) != 1 { + return noValue, false + } + + if ident, ok := n.Node.(*parse.IdentifierNode); ok { + switch ident.Ident { + case "repository": + switch n.Field[0] { + case "search_result_paths": + // TODO: We don't eval search_result_paths for now, since it's a + // "complex" value, a slice of strings, and turning that + // into text might not be useful to the user. So we abort. + return noValue, false + case "name": + return reflect.ValueOf(ctx.Repository.Name), true + } + + case "batch_change": + switch n.Field[0] { + case "name": + return reflect.ValueOf(ctx.BatchChange.Name), true + case "description": + return reflect.ValueOf(ctx.BatchChange.Description), true + } + } + } + return noValue, false + + case *parse.PipeNode: + return evalPipe(ctx, n) + } + + return noValue, false +} + +func isRuneInt(s string) bool { + return len(s) > 0 && s[0] == '\'' +} + +func isHexInt(s string) bool { + return len(s) > 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X') && !strings.ContainsAny(s, "pP") +} + +func evalFunction(ctx *StepContext, name string, args []parse.Node) (val reflect.Value, success bool) { + defer func() { + if r := recover(); r != nil { + val = noValue + success = false + } + }() + + switch name { + case "eq": + return evalEqCall(ctx, args[1:]) + + case "ne": + equal, ok := evalEqCall(ctx, args[1:]) + if !ok { + return noValue, false + } + return reflect.ValueOf(!equal.Bool()), true + + case "not": + return evalNotCall(ctx, args[1:]) + + default: + concreteFn, ok := builtins[name] + if !ok { + return noValue, false + } + + fn := reflect.ValueOf(concreteFn) + + // We can eval only if all args are static: + var evaluatedArgs []reflect.Value + for _, a := range args[1:] { + v, ok := evalNode(ctx, a) + if !ok { + // One of the args is not static, abort + return noValue, false + } + evaluatedArgs = append(evaluatedArgs, v) + + } + + ret := fn.Call(evaluatedArgs) + if len(ret) == 2 && !ret[1].IsNil() { + return noValue, false + } + return ret[0], true + } +} + +func evalNotCall(ctx *StepContext, args []parse.Node) (reflect.Value, bool) { + // We only support 1 arg for now: + if len(args) != 1 { + return noValue, false + } + + arg, ok := evalNode(ctx, args[0]) + if !ok { + return noValue, false + } + + return reflect.ValueOf(!isTrue(arg)), true +} + +func evalEqCall(ctx *StepContext, args []parse.Node) (reflect.Value, bool) { + // We only support 2 args for now: + if len(args) != 2 { + return noValue, false + } + + // We only eval `eq` if all args are static: + var evaluatedArgs []reflect.Value + for _, a := range args { + v, ok := evalNode(ctx, a) + if !ok { + // One of the args is not static, abort + return noValue, false + } + evaluatedArgs = append(evaluatedArgs, v) + } + + if len(evaluatedArgs) != 2 { + // safety check + return noValue, false + } + + isEqual := evaluatedArgs[0].Interface() == evaluatedArgs[1].Interface() + return reflect.ValueOf(isEqual), true +} + +// isTrue is taken from Go's text/template/exec.go and simplified +func isTrue(val reflect.Value) (truth bool) { + if !val.IsValid() { + // Something like var x interface{}, never set. It's a form of nil. + return false + } + switch val.Kind() { + case reflect.Array, reflect.Map, reflect.Slice, reflect.String: + return val.Len() > 0 + case reflect.Bool: + return val.Bool() + case reflect.Complex64, reflect.Complex128: + return val.Complex() != 0 + case reflect.Chan, reflect.Func, reflect.Ptr, reflect.Interface: + return !val.IsNil() + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return val.Int() != 0 + case reflect.Float32, reflect.Float64: + return val.Float() != 0 + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return val.Uint() != 0 + case reflect.Struct: + return true // Struct values are always true. + default: + return false + } +} diff --git a/lib/batches/template/template.go b/lib/batches/template/template.go new file mode 100644 index 0000000000..0591ee8870 --- /dev/null +++ b/lib/batches/template/template.go @@ -0,0 +1,18 @@ +package template + +import "text/template" + +func New(name, tmpl, option string, ctxs ...template.FuncMap) (*template.Template, error) { + t := template.New(name).Delims(startDelim, endDelim) + if option != "" { + t = t.Option(option) + } + + t = t.Funcs(builtins) + + for _, ctx := range ctxs { + t = t.Funcs(ctx) + } + + return t.Parse(tmpl) +} diff --git a/lib/batches/template/templating.go b/lib/batches/template/templating.go new file mode 100644 index 0000000000..eae6547860 --- /dev/null +++ b/lib/batches/template/templating.go @@ -0,0 +1,334 @@ +package template + +import ( + "bytes" + "fmt" + "io" + "sort" + "strings" + "text/template" + + "github.com/gobwas/glob" + "github.com/grafana/regexp" + + "github.com/sourcegraph/sourcegraph/lib/batches/execution" + "github.com/sourcegraph/sourcegraph/lib/batches/git" + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +const startDelim = "${{" +const endDelim = "}}" + +var builtins = template.FuncMap{ + "join": strings.Join, + "split": strings.Split, + "replace": strings.ReplaceAll, + "join_if": func(sep string, elems ...string) string { + var nonBlank []string + for _, e := range elems { + if e != "" { + nonBlank = append(nonBlank, e) + } + } + return strings.Join(nonBlank, sep) + }, + "matches": func(in, pattern string) (bool, error) { + g, err := glob.Compile(pattern) + if err != nil { + return false, err + } + return g.Match(in), nil + }, +} + +// ValidateBatchSpecTemplate attempts to perform a dry run replacement of the whole batch +// spec template for any templating variables which are not dependent on execution +// context. It returns a tuple whose first element is whether or not the batch spec is +// valid and whose second element is an error message if the spec is found to be invalid. +func ValidateBatchSpecTemplate(spec string) (bool, error) { + // We use empty contexts to create "dummy" `template.FuncMap`s -- function mappings + // with all the right keys, but no actual values. We'll use these `FuncMap`s to do a + // dry run on the batch spec to determine if it's valid or not, before we actually + // execute it. + sc := &StepContext{} + sfm := sc.ToFuncMap() + cstc := &ChangesetTemplateContext{} + cstfm := cstc.ToFuncMap() + + // Strip any use of `outputs` fields from the spec template. Without using real + // contexts for the `FuncMap`s, they'll fail to `template.Execute`, and it's difficult + // to statically validate them without deeper inspection of the YAML, so our + // validation is just a best-effort without them. + outputRe := regexp.MustCompile(`(?i)\$\{\{\s*[^}]*\s*outputs\.[^}]*\}\}`) + spec = outputRe.ReplaceAllString(spec, "") + + // Also strip index references. We also can't validate whether or not an index is in + // range without real context. + indexRe := regexp.MustCompile(`(?i)\$\{\{\s*index\s*[^}]*\}\}`) + spec = indexRe.ReplaceAllString(spec, "") + + // By default, text/template will continue even if it encounters a key that is not + // indexed in any of the provided `FuncMap`s. A missing key is an indication of an + // unknown or mistyped template variable which would invalidate the batch spec, so we + // want to fail immediately if we encounter one. We accomplish this by setting the + // option "missingkey=error". See https://pkg.go.dev/text/template#Template.Option for + // more. + t, err := New("validateBatchSpecTemplate", spec, "missingkey=error", sfm, cstfm) + + if err != nil { + // Attempt to extract the specific template variable field that caused the error + // to provide a clearer message. + errorRe := regexp.MustCompile(`(?i)function "(?P[^"]+)" not defined`) + if matches := errorRe.FindStringSubmatch(err.Error()); len(matches) > 0 { + return false, errors.New(fmt.Sprintf("validating batch spec template: unknown templating variable: '%s'", matches[1])) + } + // If we couldn't give a more specific error, fall back on the one from text/template. + return false, errors.Wrap(err, "validating batch spec template") + } + + var out bytes.Buffer + if err = t.Execute(&out, &StepContext{}); err != nil { + // Attempt to extract the specific template variable fields that caused the error + // to provide a clearer message. + errorRe := regexp.MustCompile(`(?i)at <(?P[^>]+)>:.*for key "(?P[^"]+)"`) + if matches := errorRe.FindStringSubmatch(err.Error()); len(matches) > 0 { + return false, errors.New(fmt.Sprintf("validating batch spec template: unknown templating variable: '%s.%s'", matches[1], matches[2])) + } + // If we couldn't give a more specific error, fall back on the one from text/template. + return false, errors.Wrap(err, "validating batch spec template") + } + + return true, nil +} + +func isTrueOutput(output interface{ String() string }) bool { + return strings.TrimSpace(output.String()) == "true" +} + +func EvalStepCondition(condition string, stepCtx *StepContext) (bool, error) { + if condition == "" { + return true, nil + } + + var out bytes.Buffer + if err := RenderStepTemplate("step-condition", condition, &out, stepCtx); err != nil { + return false, errors.Wrap(err, "parsing step if") + } + + return isTrueOutput(&out), nil +} + +func RenderStepTemplate(name, tmpl string, out io.Writer, stepCtx *StepContext) error { + // By default, text/template will continue even if it encounters a key that is not + // indexed in any of the provided `FuncMap`s, replacing the variable with "". This means that a mis-typed variable such as "${{ + // repository.search_resalt_paths }}" would just be evaluated as "", which + // is not a particularly useful substitution and will only indirectly manifest to the + // user as an error during execution. Instead, we prefer to fail immediately if we + // encounter an unknown variable. We accomplish this by setting the option + // "missingkey=error". See https://pkg.go.dev/text/template#Template.Option for more. + t, err := New(name, tmpl, "missingkey=error", stepCtx.ToFuncMap()) + if err != nil { + return errors.Wrap(err, "parsing step run") + } + + return t.Execute(out, stepCtx) +} + +func RenderStepMap(m map[string]string, stepCtx *StepContext) (map[string]string, error) { + rendered := make(map[string]string, len(m)) + + for k, v := range m { + var out bytes.Buffer + + if err := RenderStepTemplate(k, v, &out, stepCtx); err != nil { + return rendered, err + } + + rendered[k] = out.String() + } + + return rendered, nil +} + +// TODO(mrnugget): This is bad and should be (a) removed or (b) moved to batches package +type BatchChangeAttributes struct { + Name string + Description string +} + +type Repository struct { + Name string + Branch string + FileMatches []string +} + +func (r Repository) SearchResultPaths() (list fileMatchPathList) { + sort.Strings(r.FileMatches) + return r.FileMatches +} + +type fileMatchPathList []string + +func (f fileMatchPathList) String() string { return strings.Join(f, " ") } + +// StepContext represents the contextual information available when rendering a +// step's fields, such as "run" or "outputs", as templates. +type StepContext struct { + // BatchChange are the attributes in the BatchSpec that are set on the BatchChange. + BatchChange BatchChangeAttributes + // Outputs are the outputs set by the current and all previous steps. + Outputs map[string]any + // Step is the result of the current step. Empty when evaluating the "run" field + // but filled when evaluating the "outputs" field. + Step execution.AfterStepResult + // Steps contains the path in which the steps are being executed and the + // changes made by all steps that were executed up until the current step. + Steps StepsContext + // PreviousStep is the result of the previous step. Empty when there is no + // previous step. + PreviousStep execution.AfterStepResult + // Repository is the Sourcegraph repository in which the steps are executed. + Repository Repository +} + +// ToFuncMap returns a template.FuncMap to access fields on the StepContext in a +// text/template. +func (stepCtx *StepContext) ToFuncMap() template.FuncMap { + newStepResult := func(res *execution.AfterStepResult) map[string]any { + m := map[string]any{ + "modified_files": "", + "added_files": "", + "deleted_files": "", + "renamed_files": "", + "stdout": "", + "stderr": "", + } + if res == nil { + return m + } + + m["modified_files"] = res.ChangedFiles.Modified + m["added_files"] = res.ChangedFiles.Added + m["deleted_files"] = res.ChangedFiles.Deleted + m["renamed_files"] = res.ChangedFiles.Renamed + m["stdout"] = res.Stdout + m["stderr"] = res.Stderr + + return m + } + + return template.FuncMap{ + "previous_step": func() map[string]any { + return newStepResult(&stepCtx.PreviousStep) + }, + "step": func() map[string]any { + return newStepResult(&stepCtx.Step) + }, + "steps": func() map[string]any { + res := newStepResult(&execution.AfterStepResult{ChangedFiles: stepCtx.Steps.Changes}) + res["path"] = stepCtx.Steps.Path + return res + }, + "outputs": func() map[string]any { + return stepCtx.Outputs + }, + "repository": func() map[string]any { + return map[string]any{ + "search_result_paths": stepCtx.Repository.SearchResultPaths(), + "name": stepCtx.Repository.Name, + "branch": stepCtx.Repository.Branch, + } + }, + "batch_change": func() map[string]any { + return map[string]any{ + "name": stepCtx.BatchChange.Name, + "description": stepCtx.BatchChange.Description, + } + }, + } +} + +type StepsContext struct { + // Changes that have been made by executing all steps. + Changes git.Changes + // Path is the relative-to-root directory in which the steps have been + // executed. Default is "". No leading "/". + Path string +} + +// ChangesetTemplateContext represents the contextual information available +// when rendering a field of the ChangesetTemplate as a template. +type ChangesetTemplateContext struct { + // BatchChangeAttributes are the attributes of the BatchChange that will be + // created/updated. + BatchChangeAttributes BatchChangeAttributes + + // Steps are the changes made by all steps that were executed. + Steps StepsContext + + // Outputs are the outputs defined and initialized by the steps. + Outputs map[string]any + + // Repository is the repository in which the steps were executed. + Repository Repository +} + +// ToFuncMap returns a template.FuncMap to access fields on the StepContext in a +// text/template. +func (tmplCtx *ChangesetTemplateContext) ToFuncMap() template.FuncMap { + return template.FuncMap{ + "repository": func() map[string]any { + return map[string]any{ + "search_result_paths": tmplCtx.Repository.SearchResultPaths(), + "name": tmplCtx.Repository.Name, + "branch": tmplCtx.Repository.Branch, + } + }, + "batch_change": func() map[string]any { + return map[string]any{ + "name": tmplCtx.BatchChangeAttributes.Name, + "description": tmplCtx.BatchChangeAttributes.Description, + } + }, + "outputs": func() map[string]any { + return tmplCtx.Outputs + }, + "steps": func() map[string]any { + return map[string]any{ + "modified_files": tmplCtx.Steps.Changes.Modified, + "added_files": tmplCtx.Steps.Changes.Added, + "deleted_files": tmplCtx.Steps.Changes.Deleted, + "renamed_files": tmplCtx.Steps.Changes.Renamed, + "path": tmplCtx.Steps.Path, + } + }, + // Leave batch_change_link alone; it will be rendered during the reconciler phase instead. + "batch_change_link": func() string { + return "${{ batch_change_link }}" + }, + } +} + +func RenderChangesetTemplateField(name, tmpl string, tmplCtx *ChangesetTemplateContext) (string, error) { + var out bytes.Buffer + + // By default, text/template will continue even if it encounters a key that is not + // indexed in any of the provided `FuncMap`s, replacing the variable with "". This means that a mis-typed variable such as "${{ + // repository.search_resalt_paths }}" would just be evaluated as "", which + // is not a particularly useful substitution and will only indirectly manifest to the + // user as an error during execution. Instead, we prefer to fail immediately if we + // encounter an unknown variable. We accomplish this by setting the option + // "missingkey=error". See https://pkg.go.dev/text/template#Template.Option for more. + t, err := New(name, tmpl, "missingkey=error", tmplCtx.ToFuncMap()) + if err != nil { + return "", err + } + + if err := t.Execute(&out, tmplCtx); err != nil { + return "", err + } + + return strings.TrimSpace(out.String()), nil +} diff --git a/lib/batches/workspaces_execution_input.go b/lib/batches/workspaces_execution_input.go new file mode 100644 index 0000000000..76a5a8cb18 --- /dev/null +++ b/lib/batches/workspaces_execution_input.go @@ -0,0 +1,39 @@ +package batches + +import ( + "github.com/sourcegraph/sourcegraph/lib/batches/execution" + "github.com/sourcegraph/sourcegraph/lib/batches/template" +) + +type WorkspacesExecutionInput struct { + BatchChangeAttributes template.BatchChangeAttributes + Repository WorkspaceRepo `json:"repository"` + Branch WorkspaceBranch `json:"branch"` + Path string `json:"path"` + OnlyFetchWorkspace bool `json:"onlyFetchWorkspace"` + Steps []Step `json:"steps"` + SearchResultPaths []string `json:"searchResultPaths"` + // CachedStepResultFound is only required for V1 executions. + // TODO: Remove me once V2 is the only execution format. + CachedStepResultFound bool `json:"cachedStepResultFound"` + // CachedStepResult is only required for V1 executions. + // TODO: Remove me once V2 is the only execution format. + CachedStepResult execution.AfterStepResult `json:"cachedStepResult"` + // SkippedSteps determines which steps are skipped in the execution. + SkippedSteps map[int]struct{} `json:"skippedSteps"` +} + +type WorkspaceRepo struct { + // ID is the GraphQL ID of the repository. + ID string `json:"id"` + Name string `json:"name"` +} + +type WorkspaceBranch struct { + Name string `json:"name"` + Target Commit `json:"target"` +} + +type Commit struct { + OID string `json:"oid"` +} diff --git a/lib/batches/yaml/validate.go b/lib/batches/yaml/validate.go new file mode 100644 index 0000000000..9d901abed2 --- /dev/null +++ b/lib/batches/yaml/validate.go @@ -0,0 +1,33 @@ +package yaml + +import ( + "encoding/json" + + "github.com/ghodss/yaml" + + yamlv3 "gopkg.in/yaml.v3" + + "github.com/sourcegraph/sourcegraph/lib/batches/jsonschema" + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +// UnmarshalValidate validates the input, which can be YAML or JSON, against +// the provided JSON schema. If the validation is successful the validated +// input is unmarshalled into the target. +func UnmarshalValidate(schema string, input []byte, target any) error { + normalized, err := yaml.YAMLToJSONCustom(input, yamlv3.Unmarshal) + if err != nil { + return errors.Wrapf(err, "failed to normalize JSON") + } + + var errs error + if err := jsonschema.Validate(schema, normalized); err != nil { + errs = errors.Append(errs, err) + } + + if err := json.Unmarshal(normalized, target); err != nil { + errs = errors.Append(errs, err) + } + + return errs +} diff --git a/lib/codeintel/upload/compress.go b/lib/codeintel/upload/compress.go new file mode 100644 index 0000000000..3c9a6176f7 --- /dev/null +++ b/lib/codeintel/upload/compress.go @@ -0,0 +1,42 @@ +package upload + +import ( + "io" + "os" + + gzip "github.com/klauspost/pgzip" + + "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/output" +) + +// compressReaderToDisk compresses and writes the content of the given reader to a temporary +// file and returns the file's path. If the given progress object is non-nil, then the progress's +// first bar will be updated with the percentage of bytes read on each read. +func compressReaderToDisk(r io.Reader, readerLen int64, progress output.Progress) (filename string, err error) { + compressedFile, err := os.CreateTemp("", "") + if err != nil { + return "", err + } + defer func() { + if closeErr := compressedFile.Close(); err != nil { + err = errors.Append(err, closeErr) + } + }() + + gzipWriter := gzip.NewWriter(compressedFile) + defer func() { + if closeErr := gzipWriter.Close(); err != nil { + err = errors.Append(err, closeErr) + } + }() + + if progress != nil { + r = newProgressCallbackReader(r, readerLen, progress, 0) + } + if _, err := io.Copy(gzipWriter, r); err != nil { + return "", nil + } + + return compressedFile.Name(), nil +} diff --git a/lib/codeintel/upload/indexer_name.go b/lib/codeintel/upload/indexer_name.go new file mode 100644 index 0000000000..7a1c084765 --- /dev/null +++ b/lib/codeintel/upload/indexer_name.go @@ -0,0 +1,76 @@ +package upload + +import ( + "bufio" + "bytes" + "encoding/json" + "io" + + "github.com/sourcegraph/scip/bindings/go/scip" + "google.golang.org/protobuf/proto" + + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +// MaxBufferSize is the maximum size of the metaData line in the dump. This should be large enough +// to be able to read the output of lsif-tsc for most cases, which will contain all glob-expanded +// file names in the indexing of JavaScript projects. +// +// Data point: lodash's metaData vertex constructed by the args `*.js test/*.js --AllowJs --checkJs` +// is 10639 characters long. +const MaxBufferSize = 128 * 1024 + +// ErrMetadataExceedsBuffer occurs when the first line of an LSIF index is too long to read. +var ErrMetadataExceedsBuffer = errors.New("metaData vertex exceeds buffer") + +// ErrInvalidMetaDataVertex occurs when the first line of an LSIF index is not a valid metadata vertex. +var ErrInvalidMetaDataVertex = errors.New("invalid metaData vertex") + +type metaDataVertex struct { + Label string `json:"label"` + ToolInfo toolInfo `json:"toolInfo"` +} + +type toolInfo struct { + Name string `json:"name"` + Version string `json:"version"` +} + +// ReadIndexerName returns the name of the tool that generated the given index contents. +// This function reads only the first line of the file, where the metadata vertex is +// assumed to be in all valid dumps. +func ReadIndexerName(r io.Reader) (string, error) { + name, _, err := ReadIndexerNameAndVersion(r) + return name, err +} + +// ReadIndexerNameAndVersion returns the name and version of the tool that generated the +// given index contents. This function reads only the first line of the file for LSIF, where +// the metadata vertex is assumed to be in all valid dumps. If its a SCIP index, the name +// and version are read from the contents of the index. +func ReadIndexerNameAndVersion(r io.Reader) (name string, verison string, _ error) { + var buf bytes.Buffer + line, isPrefix, err := bufio.NewReaderSize(io.TeeReader(r, &buf), MaxBufferSize).ReadLine() + if err == nil { + if !isPrefix { + meta := metaDataVertex{} + if err := json.Unmarshal(line, &meta); err == nil { + if meta.Label == "metaData" && meta.ToolInfo.Name != "" { + return meta.ToolInfo.Name, meta.ToolInfo.Version, nil + } + } + } + } + + content, err := io.ReadAll(io.MultiReader(bytes.NewReader(buf.Bytes()), r)) + if err != nil { + return "", "", ErrInvalidMetaDataVertex + } + + var index scip.Index + if err := proto.Unmarshal(content, &index); err != nil { + return "", "", ErrInvalidMetaDataVertex + } + + return index.Metadata.ToolInfo.Name, index.Metadata.ToolInfo.Version, nil +} diff --git a/lib/codeintel/upload/progress_reader.go b/lib/codeintel/upload/progress_reader.go new file mode 100644 index 0000000000..ff62eb6ba1 --- /dev/null +++ b/lib/codeintel/upload/progress_reader.go @@ -0,0 +1,56 @@ +package upload + +import ( + "io" + "time" + + "github.com/sourcegraph/sourcegraph/lib/output" +) + +type progressCallbackReader struct { + reader io.Reader + totalRead int64 + progressCallback func(totalRead int64) +} + +var debounceInterval = time.Millisecond * 50 + +// newProgressCallbackReader returns a modified version of the given reader that +// updates the value of a progress bar on each read. If progress is nil or n is +// zero, then the reader is returned unmodified. +// +// Calls to the progress bar update will be debounced so that two updates do not +// occur within 50ms of each other. This is to reduce flicker on the screen for +// massive writes, which make progress more quickly than the screen can redraw. +func newProgressCallbackReader(r io.Reader, readerLen int64, progress output.Progress, barIndex int) io.Reader { + if progress == nil || readerLen == 0 { + return r + } + + var lastUpdated time.Time + + progressCallback := func(totalRead int64) { + if debounceInterval <= time.Since(lastUpdated) { + // Calculate progress through the reader; do not ever complete + // as we wait for the HTTP request finish the remaining small + // percentage. + + p := float64(totalRead) / float64(readerLen) + if p >= 1 { + p = 1 - 10e-3 + } + + lastUpdated = time.Now() + progress.SetValue(barIndex, p) + } + } + + return &progressCallbackReader{reader: r, progressCallback: progressCallback} +} + +func (r *progressCallbackReader) Read(p []byte) (int, error) { + n, err := r.reader.Read(p) + r.totalRead += int64(n) + r.progressCallback(r.totalRead) + return n, err +} diff --git a/lib/codeintel/upload/request.go b/lib/codeintel/upload/request.go new file mode 100644 index 0000000000..db571435ea --- /dev/null +++ b/lib/codeintel/upload/request.go @@ -0,0 +1,204 @@ +package upload + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "strconv" + "time" + + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +type uploadRequestOptions struct { + UploadOptions + + Payload io.Reader // Request payload + Target *int // Pointer to upload id decoded from resp + MultiPart bool // Whether the request is a multipart init + NumParts int // The number of upload parts + UncompressedSize int64 // The uncompressed size of the upload + UploadID int // The multipart upload ID + Index int // The index part being uploaded + Done bool // Whether the request is a multipart finalize +} + +// ErrUnauthorized occurs when the upload endpoint returns a 401 response. +var ErrUnauthorized = errors.New("unauthorized upload") + +// performUploadRequest performs an HTTP POST to the upload endpoint. The query string of the request +// is constructed from the given request options and the body of the request is the unmodified reader. +// If target is a non-nil pointer, it will be assigned the value of the upload identifier present +// in the response body. This function returns an error as well as a boolean flag indicating if the +// function can be retried. +func performUploadRequest(ctx context.Context, httpClient Client, opts uploadRequestOptions) (bool, error) { + req, err := makeUploadRequest(opts) + if err != nil { + return false, err + } + + resp, body, err := performRequest(ctx, req, httpClient, opts.OutputOptions.Logger) + if err != nil { + return false, err + } + + return decodeUploadPayload(resp, body, opts.Target) +} + +// makeUploadRequest creates an HTTP request to the upload endpoint described by the given arguments. +func makeUploadRequest(opts uploadRequestOptions) (*http.Request, error) { + uploadURL, err := makeUploadURL(opts) + if err != nil { + return nil, err + } + + req, err := http.NewRequest("POST", uploadURL.String(), opts.Payload) + if err != nil { + return nil, err + } + if opts.UncompressedSize != 0 { + req.Header.Set("X-Uncompressed-Size", strconv.Itoa(int(opts.UncompressedSize))) + } + if opts.SourcegraphInstanceOptions.AccessToken != "" { + req.Header.Set("Authorization", fmt.Sprintf("token %s", opts.SourcegraphInstanceOptions.AccessToken)) + } + + for k, v := range opts.SourcegraphInstanceOptions.AdditionalHeaders { + req.Header.Set(k, v) + } + + return req, nil +} + +// performRequest performs an HTTP request and returns the HTTP response as well as the entire +// body as a byte slice. If a logger is supplied, the request, response, and response body will +// be logged. +func performRequest(ctx context.Context, req *http.Request, httpClient Client, logger RequestLogger) (*http.Response, []byte, error) { + started := time.Now() + if logger != nil { + logger.LogRequest(req) + } + + resp, err := httpClient.Do(req.WithContext(ctx)) + if err != nil { + return nil, nil, err + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if logger != nil { + logger.LogResponse(req, resp, body, time.Since(started)) + } + if err != nil { + return nil, nil, err + } + + return resp, body, nil +} + +// decodeUploadPayload reads the given response to an upload request. If target is a non-nil pointer, +// it will be assigned the value of the upload identifier present in the response body. This function +// returns a boolean flag indicating if the function can be retried on failure (error-dependent). +func decodeUploadPayload(resp *http.Response, body []byte, target *int) (bool, error) { + if resp.StatusCode >= 300 { + if resp.StatusCode == http.StatusUnauthorized { + return false, ErrUnauthorized + } + + suffix := "" + if !bytes.HasPrefix(bytes.TrimSpace(body), []byte{'<'}) { + suffix = fmt.Sprintf(" (%s)", bytes.TrimSpace(body)) + } + + // Do not retry client errors + return resp.StatusCode >= 500, errors.Errorf("unexpected status code: %d%s", resp.StatusCode, suffix) + } + + if target == nil { + // No target expected, skip decoding body + return false, nil + } + + var respPayload struct { // See UploadAPIResult for the dual of this type + ID string `json:"id"` + } + if err := json.Unmarshal(body, &respPayload); err != nil { + return false, errors.Errorf("unexpected response (%s)", err) + } + + id, err := strconv.Atoi(respPayload.ID) + if err != nil { + return false, errors.Errorf("unexpected response (%s)", err) + } + + *target = id + return false, nil +} + +// makeUploadURL creates a URL pointing to the configured Sourcegraph upload +// endpoint with the query string described by the given request options. +func makeUploadURL(opts uploadRequestOptions) (*url.URL, error) { + qs := url.Values{} + + if opts.SourcegraphInstanceOptions.GitHubToken != "" { + qs.Add("github_token", opts.SourcegraphInstanceOptions.GitHubToken) + } + if opts.SourcegraphInstanceOptions.GitLabToken != "" { + qs.Add("gitlab_token", opts.SourcegraphInstanceOptions.GitLabToken) + } + if opts.UploadRecordOptions.Repo != "" { + qs.Add("repository", opts.UploadRecordOptions.Repo) + } + if opts.UploadRecordOptions.Commit != "" { + qs.Add("commit", opts.UploadRecordOptions.Commit) + } + if opts.UploadRecordOptions.Root != "" { + qs.Add("root", opts.UploadRecordOptions.Root) + } + if opts.UploadRecordOptions.Indexer != "" { + qs.Add("indexerName", opts.UploadRecordOptions.Indexer) + } + if opts.UploadRecordOptions.IndexerVersion != "" { + qs.Add("indexerVersion", opts.UploadRecordOptions.IndexerVersion) + } + if opts.UploadRecordOptions.AssociatedIndexID != nil { + qs.Add("associatedIndexId", formatInt(*opts.UploadRecordOptions.AssociatedIndexID)) + } + if opts.MultiPart { + qs.Add("multiPart", "true") + } + if opts.NumParts != 0 { + qs.Add("numParts", formatInt(opts.NumParts)) + } + if opts.UploadID != 0 { + qs.Add("uploadId", formatInt(opts.UploadID)) + } + if opts.UploadID != 0 && !opts.MultiPart && !opts.Done { + // Do not set an index of zero unless we're uploading a part + qs.Add("index", formatInt(opts.Index)) + } + if opts.Done { + qs.Add("done", "true") + } + + path := opts.SourcegraphInstanceOptions.Path + if path == "" { + path = "/.api/lsif/upload" + } + + parsedUrl, err := url.Parse(opts.SourcegraphInstanceOptions.SourcegraphURL + path) + if err != nil { + return nil, err + } + + parsedUrl.RawQuery = qs.Encode() + return parsedUrl, nil +} + +func formatInt(v int) string { + return strconv.FormatInt(int64(v), 10) +} diff --git a/lib/codeintel/upload/request_logger.go b/lib/codeintel/upload/request_logger.go new file mode 100644 index 0000000000..8df7e559c0 --- /dev/null +++ b/lib/codeintel/upload/request_logger.go @@ -0,0 +1,90 @@ +package upload + +import ( + "fmt" + "io" + "net/http" + "sort" + "time" +) + +type RequestLogger interface { + // LogRequest is invoked with a request directly before it is performed. + LogRequest(req *http.Request) + + // LogResponse is invoked with a request, response pair directly after it is performed. + LogResponse(req *http.Request, resp *http.Response, body []byte, elapsed time.Duration) +} + +type RequestLoggerVerbosity int + +const ( + RequestLoggerVerbosityNone RequestLoggerVerbosity = iota // -trace=0 (default) + RequestLoggerVerbosityTrace // -trace=1 + RequestLoggerVerbosityTraceShowHeaders // -trace=2 + RequestLoggerVerbosityTraceShowResponseBody // -trace=3 +) + +// NewRequestLogger creates a new request logger that writes requests and response pairs +// to the given writer. +func NewRequestLogger(w io.Writer, verbosity RequestLoggerVerbosity) RequestLogger { + return &requestLogger{ + writer: w, + verbosity: verbosity} +} + +func (l *requestLogger) LogRequest(req *http.Request) { + if l.verbosity == RequestLoggerVerbosityNone { + return + } + + if l.verbosity >= RequestLoggerVerbosityTrace { + fmt.Fprintf(l.writer, "> %s %s\n", req.Method, req.URL) + } + + if l.verbosity >= RequestLoggerVerbosityTraceShowHeaders { + fmt.Fprintf(l.writer, "> Request Headers:\n") + for _, k := range sortHeaders(req.Header) { + fmt.Fprintf(l.writer, "> %s: %s\n", k, req.Header[k]) + } + } + + fmt.Fprintf(l.writer, "\n") +} + +type requestLogger struct { + writer io.Writer + verbosity RequestLoggerVerbosity +} + +func (l *requestLogger) LogResponse(req *http.Request, resp *http.Response, body []byte, elapsed time.Duration) { + if l.verbosity == RequestLoggerVerbosityNone { + return + } + + if l.verbosity >= RequestLoggerVerbosityTrace { + fmt.Fprintf(l.writer, "< %s %s %s in %s\n", req.Method, req.URL, resp.Status, elapsed) + } + + if l.verbosity >= RequestLoggerVerbosityTraceShowHeaders { + fmt.Fprintf(l.writer, "< Response Headers:\n") + for _, k := range sortHeaders(resp.Header) { + fmt.Fprintf(l.writer, "< %s: %s\n", k, resp.Header[k]) + } + } + + if l.verbosity >= RequestLoggerVerbosityTraceShowResponseBody { + fmt.Fprintf(l.writer, "< Response Body: %s\n", body) + } + + fmt.Fprintf(l.writer, "\n") +} + +func sortHeaders(header http.Header) []string { + var keys []string + for k := range header { + keys = append(keys, k) + } + sort.Strings(keys) + return keys +} diff --git a/lib/codeintel/upload/retry.go b/lib/codeintel/upload/retry.go new file mode 100644 index 0000000000..7c70735827 --- /dev/null +++ b/lib/codeintel/upload/retry.go @@ -0,0 +1,37 @@ +package upload + +import ( + "time" + + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +// RetryableFunc is a function that takes the invocation index and returns an error as well as a +// boolean-value flag indicating whether or not the error is considered retryable. +type RetryableFunc = func(attempt int) (bool, error) + +// makeRetry returns a function that calls retry with the given max attempt and interval values. +func makeRetry(n int, interval time.Duration) func(f RetryableFunc) error { + return func(f RetryableFunc) error { + return retry(f, n, interval) + } +} + +// retry will re-invoke the given function until it returns a nil error value, the function returns +// a non-retryable error (as indicated by its boolean return value), or until the maximum number of +// retries have been attempted. All errors encountered will be returned. +func retry(f RetryableFunc, n int, interval time.Duration) (errs error) { + for i := 0; i <= n; i++ { + retry, err := f(i) + + errs = errors.CombineErrors(errs, err) + + if err == nil || !retry { + break + } + + time.Sleep(interval) + } + + return errs +} diff --git a/lib/codeintel/upload/upload.go b/lib/codeintel/upload/upload.go new file mode 100644 index 0000000000..097990d1b8 --- /dev/null +++ b/lib/codeintel/upload/upload.go @@ -0,0 +1,369 @@ +package upload + +import ( + "context" + "fmt" + "io" + "os" + "sync" + + "github.com/sourcegraph/conc/pool" + + "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/output" +) + +// UploadIndex uploads the index file described by the given options to a Sourcegraph +// instance. If the upload file is large, it may be split into multiple segments and +// uploaded over multiple requests. The identifier of the upload is returned after a +// successful upload. +func UploadIndex(ctx context.Context, filename string, httpClient Client, opts UploadOptions) (int, error) { + originalReader, originalSize, err := openFileAndGetSize(filename) + if err != nil { + return 0, err + } + defer func() { + _ = originalReader.Close() + }() + + bars := []output.ProgressBar{{Label: "Compressing", Max: 1.0}} + progress, _, cleanup := logProgress( + opts.Output, + bars, + "Index compressed", + "Failed to compress index", + ) + + compressedFile, err := compressReaderToDisk(originalReader, originalSize, progress) + if err != nil { + cleanup(err) + return 0, err + } + defer func() { + _ = os.Remove(compressedFile) + }() + + compressedReader, compressedSize, err := openFileAndGetSize(compressedFile) + if err != nil { + cleanup(err) + return 0, err + } + defer func() { + _ = compressedReader.Close() + }() + + cleanup(nil) + + if opts.Output != nil { + opts.Output.WriteLine(output.Linef( + output.EmojiLightbulb, + output.StyleItalic, + "Indexed compressed (%.2fMB -> %.2fMB).", + float64(originalSize)/1000/1000, + float64(compressedSize)/1000/1000, + )) + } + + if compressedSize <= opts.MaxPayloadSizeBytes { + return uploadIndex(ctx, httpClient, opts, compressedReader, compressedSize, originalSize) + } + + return uploadMultipartIndex(ctx, httpClient, opts, compressedReader, compressedSize, originalSize) +} + +// uploadIndex uploads the index file described by the given options to a Sourcegraph +// instance via a single HTTP POST request. The identifier of the upload is returned +// after a successful upload. +func uploadIndex(ctx context.Context, httpClient Client, opts UploadOptions, r io.ReaderAt, readerLen, uncompressedSize int64) (id int, err error) { + bars := []output.ProgressBar{{Label: "Upload", Max: 1.0}} + progress, retry, complete := logProgress( + opts.Output, + bars, + "Index uploaded", + "Failed to upload index file", + ) + defer func() { complete(err) }() + + // Create a section reader that can reset our reader view for retries + reader := io.NewSectionReader(r, 0, readerLen) + + requestOptions := uploadRequestOptions{ + UploadOptions: opts, + Target: &id, + UncompressedSize: uncompressedSize, + } + err = uploadIndexFile(ctx, httpClient, opts, reader, readerLen, requestOptions, progress, retry, 0, 1) + + if progress != nil { + // Mark complete in case we debounced our last updates + progress.SetValue(0, 1) + } + + return id, err +} + +// uploadIndexFile uploads the contents available via the given reader to a +// Sourcegraph instance with the given request options.i +func uploadIndexFile(ctx context.Context, httpClient Client, uploadOptions UploadOptions, reader io.ReadSeeker, readerLen int64, requestOptions uploadRequestOptions, progress output.Progress, retry onRetryLogFn, barIndex int, numParts int) error { + retrier := makeRetry(uploadOptions.MaxRetries, uploadOptions.RetryInterval) + + return retrier(func(attempt int) (_ bool, err error) { + defer func() { + if err != nil && !errors.Is(err, ctx.Err()) && progress != nil { + progress.SetValue(barIndex, 0) + } + }() + + if attempt != 0 { + suffix := "" + if numParts != 1 { + suffix = fmt.Sprintf(" %d of %d", barIndex+1, numParts) + } + + if progress != nil { + progress.SetValue(barIndex, 0) + } + progress = retry(fmt.Sprintf("Failed to upload index file%s (will retry; attempt #%d)", suffix, attempt)) + } + + // Create fresh reader on each attempt + reader.Seek(0, io.SeekStart) + + // Report upload progress as writes occur + requestOptions.Payload = newProgressCallbackReader(reader, readerLen, progress, barIndex) + + // Perform upload + return performUploadRequest(ctx, httpClient, requestOptions) + }) +} + +// uploadMultipartIndex uploads the index file described by the given options to a +// Sourcegraph instance over multiple HTTP POST requests. The identifier of the upload +// is returned after a successful upload. +func uploadMultipartIndex(ctx context.Context, httpClient Client, opts UploadOptions, r io.ReaderAt, readerLen, uncompressedSize int64) (_ int, err error) { + // Create a slice of section readers for upload part retries. + // This allows us to both read concurrently from the same reader, + // but also retry reads from arbitrary offsets. + readers := splitReader(r, readerLen, opts.MaxPayloadSizeBytes) + + // Perform initial request that gives us our upload identifier + id, err := uploadMultipartIndexInit(ctx, httpClient, opts, len(readers), uncompressedSize) + if err != nil { + return 0, err + } + + // Upload each payload of the multipart index + if err := uploadMultipartIndexParts(ctx, httpClient, opts, readers, id, readerLen); err != nil { + return 0, err + } + + // Finalize the upload and mark it as ready for processing + if err := uploadMultipartIndexFinalize(ctx, httpClient, opts, id); err != nil { + return 0, err + } + + return id, nil +} + +// uploadMultipartIndexInit performs an initial request to prepare the backend to accept upload +// parts via additional HTTP requests. This upload will be in a pending state until all upload +// parts are received and the multipart upload is finalized, or until the record is deleted by +// a background process after an expiry period. +func uploadMultipartIndexInit(ctx context.Context, httpClient Client, opts UploadOptions, numParts int, uncompressedSize int64) (id int, err error) { + retry, complete := logPending( + opts.Output, + "Preparing multipart upload", + "Prepared multipart upload", + "Failed to prepare multipart upload", + ) + defer func() { complete(err) }() + + err = makeRetry(opts.MaxRetries, opts.RetryInterval)(func(attempt int) (bool, error) { + if attempt != 0 { + retry(fmt.Sprintf("Failed to prepare multipart upload (will retry; attempt #%d)", attempt)) + } + + return performUploadRequest(ctx, httpClient, uploadRequestOptions{ + UploadOptions: opts, + Target: &id, + MultiPart: true, + NumParts: numParts, + UncompressedSize: uncompressedSize, + }) + }) + + return id, err +} + +// uploadMultipartIndexParts uploads the contents available via each of the given reader(s) +// to a Sourcegraph instance as part of the same multipart upload as indiciated +// by the given identifier. +func uploadMultipartIndexParts(ctx context.Context, httpClient Client, opts UploadOptions, readers []io.ReadSeeker, id int, readerLen int64) (err error) { + var bars []output.ProgressBar + for i := range readers { + label := fmt.Sprintf("Upload part %d of %d", i+1, len(readers)) + bars = append(bars, output.ProgressBar{Label: label, Max: 1.0}) + } + progress, retry, complete := logProgress( + opts.Output, + bars, + "Index parts uploaded", + "Failed to upload index parts", + ) + defer func() { complete(err) }() + + pool := new(pool.ErrorPool).WithFirstError().WithContext(ctx) + if opts.MaxConcurrency > 0 { + pool.WithMaxGoroutines(opts.MaxConcurrency) + } + + for i, reader := range readers { + i, reader := i, reader + + pool.Go(func(ctx context.Context) error { + // Determine size of this reader. If we're not the last reader in the slice, + // then we're the maximum payload size. Otherwise, we're whatever is left. + partReaderLen := opts.MaxPayloadSizeBytes + if i == len(readers)-1 { + partReaderLen = readerLen - int64(len(readers)-1)*opts.MaxPayloadSizeBytes + } + + requestOptions := uploadRequestOptions{ + UploadOptions: opts, + UploadID: id, + Index: i, + } + + if err := uploadIndexFile(ctx, httpClient, opts, reader, partReaderLen, requestOptions, progress, retry, i, len(readers)); err != nil { + return err + } else if progress != nil { + // Mark complete in case we debounced our last updates + progress.SetValue(i, 1) + } + return nil + }) + } + + return pool.Wait() +} + +// uploadMultipartIndexFinalize performs the request to stitch the uploaded parts together and +// mark it ready as processing in the backend. +func uploadMultipartIndexFinalize(ctx context.Context, httpClient Client, opts UploadOptions, id int) (err error) { + retry, complete := logPending( + opts.Output, + "Finalizing multipart upload", + "Finalized multipart upload", + "Failed to finalize multipart upload", + ) + defer func() { complete(err) }() + + return makeRetry(opts.MaxRetries, opts.RetryInterval)(func(attempt int) (bool, error) { + if attempt != 0 { + retry(fmt.Sprintf("Failed to finalize multipart upload (will retry; attempt #%d)", attempt)) + } + + return performUploadRequest(ctx, httpClient, uploadRequestOptions{ + UploadOptions: opts, + UploadID: id, + Done: true, + }) + }) +} + +// splitReader returns a slice of read-seekers into the input ReaderAt, each of max size maxPayloadSize. +// +// The sequential concatenation of each reader produces the content of the original reader. +// +// Each reader is safe to use concurrently with others. The original reader should be closed when all produced +// readers are no longer active. +func splitReader(r io.ReaderAt, n, maxPayloadSize int64) (readers []io.ReadSeeker) { + for offset := int64(0); offset < n; offset += maxPayloadSize { + readers = append(readers, io.NewSectionReader(r, offset, maxPayloadSize)) + } + + return readers +} + +// openFileAndGetSize returns an open file handle and the size on disk for the given filename. +func openFileAndGetSize(filename string) (*os.File, int64, error) { + fileInfo, err := os.Stat(filename) + if err != nil { + return nil, 0, err + } + + file, err := os.Open(filename) + if err != nil { + return nil, 0, err + } + + return file, fileInfo.Size(), err +} + +// logPending creates a pending object from the given output value and returns a retry function that +// can be called to print a message then reset the pending display, and a complete function that should +// be called once the work attached to this log call has completed. This complete function takes an error +// value that determines whether the success or failure message is displayed. If the given output value is +// nil then a no-op complete function is returned. +func logPending(out *output.Output, pendingMessage, successMessage, failureMessage string) (func(message string), func(error)) { + if out == nil { + return func(message string) {}, func(err error) {} + } + + pending := out.Pending(output.Line("", output.StylePending, pendingMessage)) + + retry := func(message string) { + pending.Destroy() + out.WriteLine(output.Line(output.EmojiFailure, output.StyleReset, message)) + pending = out.Pending(output.Line("", output.StylePending, pendingMessage)) + } + + complete := func(err error) { + if err == nil { + pending.Complete(output.Line(output.EmojiSuccess, output.StyleSuccess, successMessage)) + } else { + pending.Complete(output.Line(output.EmojiFailure, output.StyleBold, failureMessage)) + } + } + + return retry, complete +} + +type onRetryLogFn func(message string) output.Progress + +// logProgress creates and returns a progress from the given output value and bars configuration. +// This function also returns a retry function that can be called to print a message then reset the +// progress bar display, and a complete function that should be called once the work attached to +// this log call has completed. This complete function takes an error value that determines whether +// the success or failure message is displayed. If the given output value is nil then a no-op complete +// function is returned. +func logProgress(out *output.Output, bars []output.ProgressBar, successMessage, failureMessage string) (output.Progress, onRetryLogFn, func(error)) { + if out == nil { + return nil, func(message string) output.Progress { return nil }, func(err error) {} + } + + var mu sync.Mutex + progress := out.Progress(bars, nil) + + retry := func(message string) output.Progress { + mu.Lock() + defer mu.Unlock() + + progress.Destroy() + out.WriteLine(output.Line(output.EmojiFailure, output.StyleReset, message)) + progress = out.Progress(bars, nil) + return progress + } + + complete := func(err error) { + progress.Destroy() + + if err == nil { + out.WriteLine(output.Line(output.EmojiSuccess, output.StyleSuccess, successMessage)) + } else { + out.WriteLine(output.Line(output.EmojiFailure, output.StyleBold, failureMessage)) + } + } + + return progress, retry, complete +} diff --git a/lib/codeintel/upload/upload_options.go b/lib/codeintel/upload/upload_options.go new file mode 100644 index 0000000000..e8f498399e --- /dev/null +++ b/lib/codeintel/upload/upload_options.go @@ -0,0 +1,47 @@ +package upload + +import ( + "net/http" + "time" + + "github.com/sourcegraph/sourcegraph/lib/output" +) + +type Client interface { + // Do runs an http.Request against the Sourcegraph API. + Do(req *http.Request) (*http.Response, error) +} + +type UploadOptions struct { + SourcegraphInstanceOptions + OutputOptions + UploadRecordOptions +} + +type SourcegraphInstanceOptions struct { + SourcegraphURL string // The URL (including scheme) of the target Sourcegraph instance + AccessToken string // The user access token + AdditionalHeaders map[string]string // Additional request headers on each request + Path string // Custom path on the Sourcegraph instance (used internally) + MaxRetries int // The maximum number of retries per request + RetryInterval time.Duration // Sleep duration between retries + MaxPayloadSizeBytes int64 // The maximum number of bytes sent in a single request + MaxConcurrency int // The maximum number of concurrent uploads. Only relevant for multipart uploads + GitHubToken string // GitHub token used for auth when lsif.enforceAuth is true (optional) + GitLabToken string // GitLab token used for auth when lsif.enforceAuth is true (optional) + HTTPClient Client +} + +type OutputOptions struct { + Logger RequestLogger // Logger of all HTTP request/responses (optional) + Output *output.Output // Output instance used for fancy output (optional) +} + +type UploadRecordOptions struct { + Repo string + Commit string + Root string + Indexer string + IndexerVersion string + AssociatedIndexID *int +} diff --git a/lib/errors/client_error.go b/lib/errors/client_error.go new file mode 100644 index 0000000000..505646a1cf --- /dev/null +++ b/lib/errors/client_error.go @@ -0,0 +1,26 @@ +package errors + +// ClientError indicates that the error is due to a mistake in +// the API client's request (4xx in HTTP), it's not a server-internal +// error (5xx in HTTP). +// +// GraphQL doesn't require tracking this separately, but it's useful +// for making sure that we can set SLOs against server errors. +// +// For example, on Sourcegraph.com, people can send us arbitrary GraphQL +// requests; it wouldn't make sense for errors in processing malformed +// requests to count against our (internal) SLO. +type ClientError struct { + Err error +} + +var _ error = ClientError{nil} +var _ Wrapper = ClientError{nil} + +func (e ClientError) Error() string { + return e.Err.Error() +} + +func (e ClientError) Unwrap() error { + return e.Err +} diff --git a/lib/errors/cockroach.go b/lib/errors/cockroach.go new file mode 100644 index 0000000000..7a8632722d --- /dev/null +++ b/lib/errors/cockroach.go @@ -0,0 +1,186 @@ +package errors + +import ( + "fmt" + "os" + "reflect" + "time" + + "github.com/cockroachdb/errors" //nolint:depguard + "github.com/cockroachdb/redact" +) + +func init() { + registerCockroachSafeTypes() +} + +var ( + // Safe is a arg marker for non-PII arguments. + Safe = redact.Safe + + New = errors.New + // Newf assumes all args are unsafe PII, except for types in registerCockroachSafeTypes. + // Use Safe to mark non-PII args. Contents of format are retained. + Newf = errors.Newf + // Errorf is the same as Newf. It assumes all args are unsafe PII, except for types + // in registerCockroachSafeTypes. Use Safe to mark non-PII args. Contents of format + // are retained. + Errorf = errors.Newf + + Wrap = errors.Wrap + // Wrapf assumes all args are unsafe PII, except for types in registerCockroachSafeTypes. + // Use Safe to mark non-PII args. Contents of format are retained. + Wrapf = errors.Wrapf + // WithMessage is the same as Wrap. + WithMessage = errors.Wrap + + // WithStack annotates err with a stack trace at the point WithStack was + // called. Useful for sentinel errors. + WithStack = errors.WithStack + + // WithSafeDetails annotates an error with the given reportable details. + // The format is made available as a PII-free string, alongside + // with a PII-free representation of every additional argument. + // Arguments can be reported as-is (without redaction) by wrapping + // them using the Safe() function. + // + // If the format is empty and there are no arguments, the + // error argument is returned unchanged. + // + // Detail is shown: + // - when formatting with `%+v`. + // - in Sentry reports. + WithSafeDetails = errors.WithSafeDetails + + // Is checks if the error tree err is equal to the value target. + // + // For error types which do not contain any data, Is is equivalent to As. + // + // For error types which contain data, it's possible that Is + // returns true for a value other than the one returned by As, + // since an error tree can contain multiple errors of the same + // concrete type but with different data. + Is = errors.Is + IsAny = errors.IsAny + Cause = errors.Cause + Unwrap = errors.Unwrap + UnwrapAll = errors.UnwrapAll + + BuildSentryReport = errors.BuildSentryReport +) + +// As checks if the error tree err is of type target, and if so, +// sets target to the value of the error. +// +// If looking for an error of concrete type T, then the second +// argument must be a non-nil pointer of type *T. This implies that +// if the error interface is implemented with a pointer receiver, +// then target must be of type **MyConcreteType. +// +// For error types which do not contain any data, As is equivalent to Is. +// +// For error types which contain data, As will return an arbitrary +// error of the target type, in case there are multiple errors of the +// same concrete type in the error tree. +// +// Compared to errors.As, this method uses a generic argument to prevent +// a runtime panic when target is not a pointer to an error type. +// +// Use AsInterface over this function for interface targets. +func As[T error](err error, target *T) bool { + return errors.As(err, target) +} + +// AsInterface checks if the error tree err is of type target (which must be +// an interface type), and if so, sets target to the value of the error. +// +// In general, 'I' may be any interface, not just an error interface. +// See internal/errcode/code.go for some examples. +// +// Use As over this function for concrete types. +func AsInterface[I any](err error, target *I) bool { + if target == nil { + panic("Expected non-nil pointer to interface") + } + if typ := reflect.TypeOf(target); typ.Elem().Kind() != reflect.Interface { + panic("Expected pointer to interface") + } + return errors.As(err, target) +} + +// HasType checks if the error tree err has a node of type T. +// +// CAVEAT: HasType is implemented via As. So strictly speaking, it is +// possible that HasType returns true via some implementation of +// `interface { As(target any) bool }` in the error tree that +// doesn't actually check the type. +func HasType[T error](err error) bool { + // At the moment, the cockroachdb/errors package's implementation + // of HasType does not correctly handle multi-errors, whereas As does, + // so we implement HasType via As. + // (See https://github.com/cockroachdb/errors/issues/145) + var zero T + return As(err, &zero) +} + +// Extend multiError to work with cockroachdb errors. Implement here to keep imports in +// one place. + +var _ fmt.Formatter = (*multiError)(nil) + +func (e *multiError) Format(s fmt.State, verb rune) { errors.FormatError(e, s, verb) } + +var _ errors.Formatter = (*multiError)(nil) + +func (e *multiError) FormatError(p errors.Printer) error { + if len(e.errs) > 1 { + p.Printf("%d errors occurred:", len(e.errs)) + } + + // Simple output + for _, err := range e.errs { + if len(e.errs) > 1 { + p.Print("\n\t* ") + } + p.Printf("%v", err) + } + + // Print additional details + if p.Detail() { + p.Print("-- details follow") + for i, err := range e.errs { + p.Printf("\n(%d) %+v", i+1, err) + } + } + + return nil +} + +// registerSafeTypes registers types that should not be considered PII by +// cockroachdb/errors. +// +// Sourced from https://sourcegraph.com/github.com/cockroachdb/cockroach/-/blob/pkg/util/log/redact.go?L141 +func registerCockroachSafeTypes() { + // We consider booleans and numeric values to be always safe for + // reporting. A log call can opt out by using redact.Unsafe() around + // a value that would be otherwise considered safe. + redact.RegisterSafeType(reflect.TypeOf(true)) // bool + redact.RegisterSafeType(reflect.TypeOf(123)) // int + redact.RegisterSafeType(reflect.TypeOf(int8(0))) + redact.RegisterSafeType(reflect.TypeOf(int16(0))) + redact.RegisterSafeType(reflect.TypeOf(int32(0))) + redact.RegisterSafeType(reflect.TypeOf(int64(0))) + redact.RegisterSafeType(reflect.TypeOf(uint8(0))) + redact.RegisterSafeType(reflect.TypeOf(uint16(0))) + redact.RegisterSafeType(reflect.TypeOf(uint32(0))) + redact.RegisterSafeType(reflect.TypeOf(uint64(0))) + redact.RegisterSafeType(reflect.TypeOf(float32(0))) + redact.RegisterSafeType(reflect.TypeOf(float64(0))) + redact.RegisterSafeType(reflect.TypeOf(complex64(0))) + redact.RegisterSafeType(reflect.TypeOf(complex128(0))) + // Signal names are also safe for reporting. + redact.RegisterSafeType(reflect.TypeOf(os.Interrupt)) + // Times and durations too. + redact.RegisterSafeType(reflect.TypeOf(time.Time{})) + redact.RegisterSafeType(reflect.TypeOf(time.Duration(0))) +} diff --git a/lib/errors/errors.go b/lib/errors/errors.go new file mode 100644 index 0000000000..37ff23f126 --- /dev/null +++ b/lib/errors/errors.go @@ -0,0 +1,24 @@ +package errors + +// Typed is an interface custom error types that want to be checkable with errors.Is, +// errors.As can implement for more predicable behaviour. Learn more about error checking: +// https://pkg.go.dev/errors#pkg-overview +// +// In all implementations, the error should not attempt to unwrap itself or the target. +type Typed interface { + // As sets the target to the error value of this type if target is of the same type as + // this error. + // + // See https://pkg.go.dev/errors#example-As + As(target any) bool + // Is reports whether this error matches the target. + // + // See: https://pkg.go.dev/errors#example-Is + Is(target error) bool +} + +// Wrapper is an interface custom error types that carry errors internally should +// implement. +type Wrapper interface { + Unwrap() error +} diff --git a/lib/errors/filter.go b/lib/errors/filter.go new file mode 100644 index 0000000000..909e72d74f --- /dev/null +++ b/lib/errors/filter.go @@ -0,0 +1,51 @@ +package errors + +import ( + "context" +) + +// Ignore filters out any errors that match pred. This applies +// recursively to MultiErrors, filtering out any child errors +// that match `pred`, or returning `nil` if all of the child +// errors match `pred`. +func Ignore(err error, pred ErrorPredicate) error { + // If the error (or any wrapped error) is a multierror, + // filter its children. + var multi *multiError + if As(err, &multi) { + filtered := multi.errs[:0] + for _, childErr := range multi.errs { + if ignored := Ignore(childErr, pred); ignored != nil { + filtered = append(filtered, ignored) + } + } + if len(filtered) == 0 { + return nil + } + multi.errs = filtered + return err + } + + if pred(err) { + return nil + } + return err +} + +// ErrorPredicate is a function type that returns whether an error matches a given condition +type ErrorPredicate func(error) bool + +// IsPred returns an ErrorPredicate that returns true for errors that uwrap to the target error +func IsPred(target error) ErrorPredicate { + return func(err error) bool { + return Is(err, target) + } +} + +func IsContextCanceled(err error) bool { + return Is(err, context.Canceled) +} + +func IsDeadlineExceeded(err error) bool { + return Is(err, context.DeadlineExceeded) +} diff --git a/lib/errors/multi_error.go b/lib/errors/multi_error.go new file mode 100644 index 0000000000..452061473e --- /dev/null +++ b/lib/errors/multi_error.go @@ -0,0 +1,113 @@ +package errors + +import ( + "fmt" + + "github.com/cockroachdb/errors" //nolint:depguard // needed for implementation of multiError.As +) + +// MultiError is a container for groups of errors. +type MultiError interface { + error + // Errors returns all errors carried by this MultiError, or an empty slice otherwise. + Errors() []error +} + +// multiError is our default underlying implementation for MultiError. It is compatible +// with cockroachdb.Error's formatting, printing, etc. and supports introspecting via +// As, Is, and friends. +// +// Implementation is based on https://github.com/knz/shakespeare/blob/master/pkg/cmd/errors.go +type multiError struct { + errs []error +} + +var _ MultiError = (*multiError)(nil) +var _ Typed = (*multiError)(nil) + +func combineNonNilErrors(err1 error, err2 error) MultiError { + multi1, ok1 := err1.(MultiError) + multi2, ok2 := err2.(MultiError) + // flatten + var errs []error + if ok1 && ok2 { + errs = append(multi1.Errors(), multi2.Errors()...) + } else if ok1 { + errs = append(multi1.Errors(), err2) + } else if ok2 { + errs = append([]error{err1}, multi2.Errors()...) + } else { + errs = []error{err1, err2} + } + return &multiError{errs: errs} +} + +// CombineErrors returns a MultiError from err1 and err2. If both are nil, nil is returned. +func CombineErrors(err1, err2 error) MultiError { + if err1 == nil && err2 == nil { + return nil + } + if err1 == nil { + if multi, ok := err2.(MultiError); ok { + return multi + } + return &multiError{errs: []error{err2}} + } else if err2 == nil { + if multi, ok := err1.(MultiError); ok { + return multi + } + return &multiError{errs: []error{err1}} + } + return combineNonNilErrors(err1, err2) +} + +// Append returns a MultiError created from all given errors, skipping errs that are nil. +// If no non-nil errors are provided, nil is returned. +func Append(err error, errs ...error) MultiError { + multi := CombineErrors(err, nil) + for _, e := range errs { + if e != nil { + multi = CombineErrors(multi, e) + } + } + return multi +} + +func (e *multiError) Error() string { return fmt.Sprintf("%v", e) } +func (e *multiError) Errors() []error { + if e == nil || e.errs == nil { + return nil + } + return e.errs +} + +func (e *multiError) Cause() error { return e.errs[len(e.errs)-1] } +func (e *multiError) Unwrap() error { return e.errs[len(e.errs)-1] } + +func (e *multiError) Is(refError error) bool { + if e == refError { + return true + } + for _, err := range e.errs { + if Is(err, refError) { + return true + } + } + return false +} + +func (e *multiError) As(target any) bool { + if m, ok := target.(*multiError); ok { + *m = *e + return true + } + for _, err := range e.errs { + // To conform to the Typed interface, 'target' has to be of type + // any. This means we cannot use our custom As wrapper which has + // a generic argument, so use cockroachdb's As instead. + if errors.As(err, target) { + return true + } + } + return false +} diff --git a/lib/errors/postgres.go b/lib/errors/postgres.go new file mode 100644 index 0000000000..a9696a2d0d --- /dev/null +++ b/lib/errors/postgres.go @@ -0,0 +1,12 @@ +package errors + +import ( + "github.com/jackc/pgconn" +) + +// HasPostgresCode checks whether any of the errors in the chain +// signify a postgres error with the given error code. +func HasPostgresCode(err error, code string) bool { + var pgerr *pgconn.PgError + return As(err, &pgerr) && pgerr.Code == code +} diff --git a/lib/errors/rich_error.go b/lib/errors/rich_error.go new file mode 100644 index 0000000000..6315f3e7e1 --- /dev/null +++ b/lib/errors/rich_error.go @@ -0,0 +1,171 @@ +package errors + +import ( + "reflect" + "slices" + "sync" + + "go.opentelemetry.io/otel/attribute" +) + +type RichError interface { + // Unpack extracts the underlying error and attributes from a RichError. + // + // Unpacking should only return attributes one-level deep; a caller may + // optionally continue recursively unpacking the underlying error. + Unpack() RichErrorData +} + +type RichErrorData struct { + Err error + Attrs []attribute.KeyValue +} + +type PtrRichError[A any] interface { + *A + RichError +} + +// NewRichError is a helper function for wrapping custom errors +// for the observation package. +// +// Pre-condition: The outermost level of ptr must be non-nil. +// +// Generally, this is easy to satisfy by using & on a named return value. +// +// The type signature is more complicated than usual to avoid an extra +// level of pointer indirection when the type implementing RichError uses +// a pointer receiver for RichError.Unpack. See rich_error_test.go for +// examples. +func NewRichError[A any, T PtrRichError[A]](ptr2 **A) *RichError { + v := RichError(NewErrorPtr[A, T](ptr2)) + return &v +} + +func UnpackRichErrorPtr(richErr *RichError) (error, []attribute.KeyValue) { + if richErr == nil || *richErr == nil { + return nil, nil + } + if val := reflect.ValueOf(*richErr); val.Kind() == reflect.Ptr && val.IsNil() { + return nil, nil + } + data := (*richErr).Unpack() + return data.Err, data.Attrs +} + +type ErrorPtr[A any, T PtrRichError[A]] struct { + ptr2 **A +} + +// nolint:unused +func typeAssertion[A any, T PtrRichError[A]]() { + var _ RichError = (*ErrorPtr[A, T])(nil) +} + +// NewErrorPtr is the only way to create an ErrorPtr. +func NewErrorPtr[A any, T PtrRichError[A]](ptr2 **A) ErrorPtr[A, T] { + if ptr2 == nil { + panic("Expected non-nil pointer to some error type") + } + return ErrorPtr[A, T]{ptr2: ptr2} +} + +func (p ErrorPtr[A, T]) Unpack() RichErrorData { + var empty RichErrorData + if p.ptr2 == nil { + panic("Incorrectly created ErrorPtr without going through NewErrorPtr") + } + ptr := *p.ptr2 + if ptr == nil { + return RichErrorData{Err: nil, Attrs: nil} + } + // We need this dynamic type checks here because Go doesn't allow + // constraints on type parameters in methods, and we want to + // have a method so that we can satisfy the RichError interface. + val, ok := any(ptr).(RichError) + if !ok { + // We need two different type checks here because RichError may be + // implemented with a struct receiver or a pointer receiver. + // See the tests for more details. + if val, ok = any(*ptr).(RichError); !ok { + panic("Dynamic type check for pointer type failed; did you create ErrorPtr without using NewErrorPtr?") + } + } + if val == nil { + return empty + } + if inner := reflect.ValueOf(val); inner.Kind() == reflect.Ptr && inner.IsNil() { + return empty + } + return val.Unpack() +} + +// ErasedErrorPtr stores a type-erased 'error' instead of +// generic **T like ErrorPtr. +type ErasedErrorPtr struct { + Err *error +} + +var _ RichError = ErasedErrorPtr{} + +func (e ErasedErrorPtr) Unpack() RichErrorData { + if e.Err == nil || *e.Err == nil { + return RichErrorData{Err: nil, Attrs: nil} + } + if re := RichError(nil); AsInterface(*e.Err, &re) { + return re.Unpack() + } + return RichErrorData{Err: *e.Err, Attrs: nil} +} + +// Collector represents multiple errors and additional log fields that arose from those errors. +// This type is thread-safe. +type Collector struct { + mu sync.Mutex + errs error + extraAttrs []attribute.KeyValue +} + +var _ RichError = (*Collector)(nil) + +func NewErrorCollector() *Collector { return &Collector{errs: nil} } + +func (e *Collector) Collect(err *error, attrs ...attribute.KeyValue) { + e.mu.Lock() + defer e.mu.Unlock() + + if err != nil && *err != nil { + e.errs = Append(e.errs, *err) + e.extraAttrs = append(e.extraAttrs, attrs...) + } +} + +func (e *Collector) Error() string { + e.mu.Lock() + defer e.mu.Unlock() + + if e.errs == nil { + return "" + } + return e.errs.Error() +} + +func (e *Collector) Unwrap() error { + // Collector wraps collected errors, for compatibility with errors.HasType, + // errors.Is etc it has to implement Unwrap to return the inner errors the + // collector stores. + e.mu.Lock() + defer e.mu.Unlock() + + return e.errs +} + +func (e *Collector) Unpack() RichErrorData { + if e.Error() == "" { + return RichErrorData{Err: nil, Attrs: nil} + } + e.mu.Lock() + defer e.mu.Unlock() + // Explicitly clone slice for 1 level of thread safety. + return RichErrorData{Err: e.errs, Attrs: slices.Clone(e.extraAttrs)} +} diff --git a/lib/errors/tree.go b/lib/errors/tree.go new file mode 100644 index 0000000000..30656973ff --- /dev/null +++ b/lib/errors/tree.go @@ -0,0 +1,56 @@ +package errors + +import ( + "reflect" + + "github.com/xlab/treeprint" +) + +type TreeNode struct { + TypeName string + Children []*TreeNode +} + +func (n *TreeNode) String() string { + return debugTreeRecursive(n).String() +} + +func debugTreeRecursive(n *TreeNode) treeprint.Tree { + if n == nil { + return treeprint.NewWithRoot("") + } + t := treeprint.NewWithRoot(n.TypeName) + for _, child := range n.Children { + t.AddNode(debugTreeRecursive(child)) + } + return t +} + +// UnpackTree returns a tree of error types and their children. +// +// This function is meant for debugging issues when you're trying to write +// a test for error handling, and want to inspect the structure of an error +// tree. +// +// DO NOT use this function for matching errors -- use errors.Is, errors.As etc. +func UnpackTree(err error) *TreeNode { + if err == nil { + return nil + } + typeName := reflect.TypeOf(err).String() + children := []*TreeNode{} + if e, ok := err.(interface{ Unwrap() []error }); ok { + for _, suberr := range e.Unwrap() { + children = append(children, UnpackTree(suberr)) + } + } else if e, ok := err.(MultiError); ok { + for _, suberr := range e.Errors() { + children = append(children, UnpackTree(suberr)) + } + } else if e, ok := err.(Wrapper); ok { + children = append(children, UnpackTree(e.Unwrap())) + } else if e, ok := err.(interface{ Cause() error }); ok { + children = append(children, UnpackTree(e.Cause())) + } + return &TreeNode{typeName, children} +} diff --git a/lib/errors/warning.go b/lib/errors/warning.go new file mode 100644 index 0000000000..b1d4255d75 --- /dev/null +++ b/lib/errors/warning.go @@ -0,0 +1,96 @@ +package errors + +// Warning embeds an error. Its purpose is to indicate that this error is not a critical error and +// may be ignored. Additionally, it **must** be logged only as a warning. If it cannot be logged as a +// warning, then these are not the droids you're looking for. +type Warning interface { + error + // IsWarning should always return true. It exists to differentiate regular errors with Warning + // errors. That is, all Warning type objects are error types, but not all error types are + // Warning types. + IsWarning() bool +} + +// warning is the error that wraps an error that is meant to be handled as a warning and not a +// critical error. +// +// AUTHOR'S NOTE +// +// @indradhanush: This type does not need a method `As(any) bool` and can be "asserted" with +// errors.As (see example below) when the underlying package being used is cockroachdb/errors. The +// `As` method from the cockroachdb/errors library is able to distinguish between warning and native +// error types. +// +// When writing this part of the code, I had implemented an `As(any) bool` method into this struct +// but it never got invoked and the corresponding tests in TestWarningError still pass the +// assertions. However after further deliberations during code review, I'm choosing to keep it as +// part of the method list of this type with an aim for interoperability in the future. But the +// method is a NOOP. The good news is that I've also added a test for this method in +// TestWarningError. +type warning struct { + error error +} + +// Ensure that warning always implements the Warning error interface. +var _ Warning = (*warning)(nil) + +// NewWarningError will return an error of type warning. This should be used to wrap errors where we +// do not intend to return an error, increment an error metric. That is, if an error is returned and +// it is not critical and / or expected to be intermittent and / or nothing we can do about +// (example: 404 errors from upstream code host APIs in repo syncing), we should wrap the error with +// NewWarningError. +// +// Consumers of these errors should then use errors.As to check if the error is of a warning type +// and based on that, should just log it as a warning. For example: +// +// var ref errors.Warning +// err := someFunctionThatReturnsAWarningErrorOrACriticalError() +// if err != nil && errors.As(err, &ref) { +// log.Warnf("failed to do X: %v", err) +// } +// +// if err != nil { +// return err +// } +func NewWarningError(err error) *warning { + return &warning{ + error: err, + } +} + +func (w *warning) Error() string { + return w.error.Error() +} + +// IsWarning always returns true. It exists to differentiate regular errors with Warning +// errors. That is, all Warning type objects are error types, but not all error types are Warning +// types. +func (w *warning) IsWarning() bool { + return true +} + +// Unwrap returns the underlying error of the warning. +func (w *warning) Unwrap() error { + return w.error +} + +// As will return true if the target is of type warning. +// +// However, this method is not invoked when `errors.As` is invoked. See note in the docstring of the +// warning struct for more context. +func (w *warning) As(target any) bool { + if _, ok := target.(*warning); ok { + return true + } + + return false +} + +// IsWarning is a helper to check whether the specified err is a Warning +func IsWarning(err error) bool { + var ref Warning + if As(err, &ref) { + return ref.IsWarning() + } + return false +} diff --git a/lib/go.mod b/lib/go.mod new file mode 100644 index 0000000000..f84eb9e62d --- /dev/null +++ b/lib/go.mod @@ -0,0 +1,133 @@ +module github.com/sourcegraph/sourcegraph/lib + +go 1.24.1 + +require ( + github.com/Masterminds/semver v1.5.0 + github.com/charmbracelet/glamour v0.10.0 + github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834 + github.com/cockroachdb/errors v1.12.0 + github.com/cockroachdb/redact v1.1.6 + github.com/ghodss/yaml v1.0.0 + github.com/gobwas/glob v0.2.3 + github.com/google/go-cmp v0.7.0 + github.com/grafana/regexp v0.0.0-20250905093917-f7b3be9d1853 + github.com/jackc/pgconn v1.14.3 + github.com/klauspost/pgzip v1.2.6 + github.com/mattn/go-isatty v0.0.20 + github.com/mattn/go-runewidth v0.0.19 + github.com/moby/term v0.5.2 + github.com/muesli/termenv v0.16.0 + github.com/sourcegraph/conc v0.3.0 + github.com/sourcegraph/go-diff v0.7.0 + github.com/sourcegraph/log v0.0.0-20250923023806-517b6960b55b + github.com/sourcegraph/scip v0.6.1 + github.com/xeipuuv/gojsonschema v1.2.0 + github.com/xlab/treeprint v1.2.0 + go.opentelemetry.io/otel v1.38.0 + golang.org/x/sys v0.38.0 + golang.org/x/term v0.37.0 + google.golang.org/protobuf v1.36.10 + gopkg.in/yaml.v3 v3.0.1 +) + +require ( + github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c // indirect + github.com/Masterminds/sprig v2.15.0+incompatible // indirect + github.com/Microsoft/go-winio v0.6.1 // indirect + github.com/alecthomas/chroma/v2 v2.14.0 // indirect + github.com/aokoli/goutils v1.0.1 // indirect + github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect + github.com/aymerick/douceur v0.2.0 // indirect + github.com/bufbuild/buf v1.25.0 // indirect + github.com/bufbuild/connect-go v1.9.0 // indirect + github.com/bufbuild/connect-opentelemetry-go v0.4.0 // indirect + github.com/bufbuild/protocompile v0.5.1 // indirect + github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect + github.com/charmbracelet/x/ansi v0.8.0 // indirect + github.com/charmbracelet/x/cellbuf v0.0.13 // indirect + github.com/charmbracelet/x/exp/slice v0.0.0-20250327172914-2fdc97757edf // indirect + github.com/charmbracelet/x/term v0.2.1 // indirect + github.com/clipperhouse/uax29/v2 v2.2.0 // indirect + github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect + github.com/containerd/stargz-snapshotter/estargz v0.14.3 // indirect + github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect + github.com/dlclark/regexp2 v1.11.0 // indirect + github.com/docker/cli v24.0.4+incompatible // indirect + github.com/docker/distribution v2.8.2+incompatible // indirect + github.com/docker/docker v24.0.4+incompatible // indirect + github.com/docker/docker-credential-helpers v0.8.0 // indirect + github.com/docker/go-connections v0.4.0 // indirect + github.com/docker/go-units v0.5.0 // indirect + github.com/envoyproxy/protoc-gen-validate v0.3.0-java // indirect + github.com/fatih/color v1.15.0 // indirect + github.com/felixge/fgprof v0.9.3 // indirect + github.com/getsentry/sentry-go v0.27.0 // indirect + github.com/go-chi/chi/v5 v5.0.10 // indirect + github.com/go-logr/logr v1.4.3 // indirect + github.com/go-logr/stdr v1.2.2 // indirect + github.com/gofrs/uuid/v5 v5.0.0 // indirect + github.com/gogo/protobuf v1.3.2 // indirect + github.com/golang/protobuf v1.5.3 // indirect + github.com/google/go-containerregistry v0.15.2 // indirect + github.com/google/pprof v0.0.0-20230705174524-200ffdc848b8 // indirect + github.com/google/uuid v1.3.0 // indirect + github.com/gorilla/css v1.0.1 // indirect + github.com/huandu/xstrings v1.0.0 // indirect + github.com/imdario/mergo v0.3.4 // indirect + github.com/inconshreveable/mousetrap v1.1.0 // indirect + github.com/jackc/chunkreader/v2 v2.0.1 // indirect + github.com/jackc/pgio v1.0.0 // indirect + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgproto3/v2 v2.3.3 // indirect + github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect + github.com/jdxcode/netrc v0.0.0-20221124155335-4616370d1a84 // indirect + github.com/klauspost/compress v1.18.0 // indirect + github.com/kr/pretty v0.3.1 // indirect + github.com/kr/text v0.2.0 // indirect + github.com/lucasb-eyer/go-colorful v1.2.0 // indirect + github.com/mattn/go-colorable v0.1.13 // indirect + github.com/microcosm-cc/bluemonday v1.0.27 // indirect + github.com/mitchellh/go-homedir v1.1.0 // indirect + github.com/morikuni/aec v1.0.0 // indirect + github.com/muesli/reflow v0.3.0 // indirect + github.com/mwitkow/go-proto-validators v0.0.0-20180403085117-0950a7990007 // indirect + github.com/opencontainers/go-digest v1.0.0 // indirect + github.com/opencontainers/image-spec v1.1.0-rc4 // indirect + github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 // indirect + github.com/pkg/errors v0.9.1 // indirect + github.com/pkg/profile v1.7.0 // indirect + github.com/pseudomuto/protoc-gen-doc v1.5.1 // indirect + github.com/pseudomuto/protokit v0.2.0 // indirect + github.com/rivo/uniseg v0.4.7 // indirect + github.com/rogpeppe/go-internal v1.13.1 // indirect + github.com/rs/cors v1.9.0 // indirect + github.com/russross/blackfriday/v2 v2.1.0 // indirect + github.com/sirupsen/logrus v1.9.3 // indirect + github.com/sourcegraph/beaut v0.0.0-20240611013027-627e4c25335a // indirect + github.com/spf13/cobra v1.7.0 // indirect + github.com/spf13/pflag v1.0.5 // indirect + github.com/tetratelabs/wazero v1.3.0 // indirect + github.com/vbatts/tar-split v0.11.3 // indirect + github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f // indirect + github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect + github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect + github.com/yuin/goldmark v1.7.8 // indirect + github.com/yuin/goldmark-emoji v1.0.5 // indirect + go.opentelemetry.io/auto/sdk v1.1.0 // indirect + go.opentelemetry.io/otel/metric v1.38.0 // indirect + go.opentelemetry.io/otel/sdk v1.16.0 // indirect + go.opentelemetry.io/otel/trace v1.38.0 // indirect + go.uber.org/atomic v1.11.0 // indirect + go.uber.org/multierr v1.11.0 // indirect + go.uber.org/zap v1.24.0 // indirect + golang.org/x/crypto v0.42.0 // indirect + golang.org/x/mod v0.28.0 // indirect + golang.org/x/net v0.44.0 // indirect + golang.org/x/sync v0.17.0 // indirect + golang.org/x/telemetry v0.0.0-20250908211612-aef8a434d053 // indirect + golang.org/x/text v0.29.0 // indirect + golang.org/x/tools v0.37.0 // indirect + google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 // indirect + gopkg.in/yaml.v2 v2.4.0 // indirect +) diff --git a/lib/go.sum b/lib/go.sum new file mode 100644 index 0000000000..53f39986cd --- /dev/null +++ b/lib/go.sum @@ -0,0 +1,381 @@ +github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg= +github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= +github.com/BurntSushi/toml v1.2.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= +github.com/Masterminds/semver v1.5.0 h1:H65muMkzWKEuNDnfl9d70GUjFniHKHRbFPGBuZ3QEww= +github.com/Masterminds/semver v1.5.0/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y= +github.com/Masterminds/sprig v2.15.0+incompatible h1:0gSxPGWS9PAr7U2NsQ2YQg6juRDINkUyuvbb4b2Xm8w= +github.com/Masterminds/sprig v2.15.0+incompatible/go.mod h1:y6hNFY5UBTIWBxnzTeuNhlNS5hqE0NB0E6fgfo2Br3o= +github.com/Microsoft/go-winio v0.6.1 h1:9/kr64B9VUZrLm5YYwbGtUJnMgqWVOdUAXu6Migciow= +github.com/Microsoft/go-winio v0.6.1/go.mod h1:LRdKpFKfdobln8UmuiYcKPot9D2v6svN5+sAH+4kjUM= +github.com/alecthomas/assert/v2 v2.7.0 h1:QtqSACNS3tF7oasA8CU6A6sXZSBDqnm7RfpLl9bZqbE= +github.com/alecthomas/assert/v2 v2.7.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k= +github.com/alecthomas/chroma/v2 v2.14.0 h1:R3+wzpnUArGcQz7fCETQBzO5n9IMNi13iIs46aU4V9E= +github.com/alecthomas/chroma/v2 v2.14.0/go.mod h1:QolEbTfmUHIMVpBqxeDnNBj2uoeI4EbYP4i6n68SG4I= +github.com/alecthomas/repr v0.4.0 h1:GhI2A8MACjfegCPVq9f1FLvIBS+DrQ2KQBFZP1iFzXc= +github.com/alecthomas/repr v0.4.0/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4= +github.com/aokoli/goutils v1.0.1 h1:7fpzNGoJ3VA8qcrm++XEE1QUe0mIwNeLa02Nwq7RDkg= +github.com/aokoli/goutils v1.0.1/go.mod h1:SijmP0QR8LtwsmDs8Yii5Z/S4trXFGFC2oO5g9DP+DQ= +github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k= +github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8= +github.com/aymanbagabas/go-udiff v0.2.0 h1:TK0fH4MteXUDspT88n8CKzvK0X9O2xu9yQjWpi6yML8= +github.com/aymanbagabas/go-udiff v0.2.0/go.mod h1:RE4Ex0qsGkTAJoQdQQCA0uG+nAzJO/pI/QwceO5fgrA= +github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk= +github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4= +github.com/benbjohnson/clock v1.3.5 h1:VvXlSJBzZpA/zum6Sj74hxwYI2DIxRWuNIoXAzHZz5o= +github.com/benbjohnson/clock v1.3.5/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= +github.com/bufbuild/buf v1.25.0 h1:HFxKrR8wFcZwrBInN50K/oJX/WOtPVq24rHb/ArjfBA= +github.com/bufbuild/buf v1.25.0/go.mod h1:GCKZ5bAP6Ht4MF7KcfaGVgBEXGumwAz2hXjjLVxx8ZU= +github.com/bufbuild/connect-go v1.9.0 h1:JIgAeNuFpo+SUPfU19Yt5TcWlznsN5Bv10/gI/6Pjoc= +github.com/bufbuild/connect-go v1.9.0/go.mod h1:CAIePUgkDR5pAFaylSMtNK45ANQjp9JvpluG20rhpV8= +github.com/bufbuild/connect-opentelemetry-go v0.4.0 h1:6JAn10SNqlQ/URhvRNGrIlczKw1wEXknBUUtmWqOiak= +github.com/bufbuild/connect-opentelemetry-go v0.4.0/go.mod h1:nwPXYoDOoc2DGyKE/6pT1Q9MPSi2Et2e6BieMD0l6WU= +github.com/bufbuild/protocompile v0.5.1 h1:mixz5lJX4Hiz4FpqFREJHIXLfaLBntfaJv1h+/jS+Qg= +github.com/bufbuild/protocompile v0.5.1/go.mod h1:G5iLmavmF4NsYtpZFvE3B/zFch2GIY8+wjsYLR/lc40= +github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc h1:4pZI35227imm7yK2bGPcfpFEmuY1gc2YSTShr4iJBfs= +github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc/go.mod h1:X4/0JoqgTIPSFcRA/P6INZzIuyqdFY5rm8tb41s9okk= +github.com/charmbracelet/glamour v0.10.0 h1:MtZvfwsYCx8jEPFJm3rIBFIMZUfUJ765oX8V6kXldcY= +github.com/charmbracelet/glamour v0.10.0/go.mod h1:f+uf+I/ChNmqo087elLnVdCiVgjSKWuXa/l6NU2ndYk= +github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834 h1:ZR7e0ro+SZZiIZD7msJyA+NjkCNNavuiPBLgerbOziE= +github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834/go.mod h1:aKC/t2arECF6rNOnaKaVU6y4t4ZeHQzqfxedE/VkVhA= +github.com/charmbracelet/x/ansi v0.8.0 h1:9GTq3xq9caJW8ZrBTe0LIe2fvfLR/bYXKTx2llXn7xE= +github.com/charmbracelet/x/ansi v0.8.0/go.mod h1:wdYl/ONOLHLIVmQaxbIYEC/cRKOQyjTkowiI4blgS9Q= +github.com/charmbracelet/x/cellbuf v0.0.13 h1:/KBBKHuVRbq1lYx5BzEHBAFBP8VcQzJejZ/IA3iR28k= +github.com/charmbracelet/x/cellbuf v0.0.13/go.mod h1:xe0nKWGd3eJgtqZRaN9RjMtK7xUYchjzPr7q6kcvCCs= +github.com/charmbracelet/x/exp/golden v0.0.0-20240806155701-69247e0abc2a h1:G99klV19u0QnhiizODirwVksQB91TJKV/UaTnACcG30= +github.com/charmbracelet/x/exp/golden v0.0.0-20240806155701-69247e0abc2a/go.mod h1:wDlXFlCrmJ8J+swcL/MnGUuYnqgQdW9rhSD61oNMb6U= +github.com/charmbracelet/x/exp/slice v0.0.0-20250327172914-2fdc97757edf h1:rLG0Yb6MQSDKdB52aGX55JT1oi0P0Kuaj7wi1bLUpnI= +github.com/charmbracelet/x/exp/slice v0.0.0-20250327172914-2fdc97757edf/go.mod h1:B3UgsnsBZS/eX42BlaNiJkD1pPOUa+oF1IYC6Yd2CEU= +github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ= +github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg= +github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= +github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= +github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= +github.com/clipperhouse/uax29/v2 v2.2.0 h1:ChwIKnQN3kcZteTXMgb1wztSgaU+ZemkgWdohwgs8tY= +github.com/clipperhouse/uax29/v2 v2.2.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM= +github.com/cockroachdb/errors v1.12.0 h1:d7oCs6vuIMUQRVbi6jWWWEJZahLCfJpnJSVobd1/sUo= +github.com/cockroachdb/errors v1.12.0/go.mod h1:SvzfYNNBshAVbZ8wzNc/UPK3w1vf0dKDUP41ucAIf7g= +github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b h1:r6VH0faHjZeQy818SGhaone5OnYfxFR/+AzdY3sf5aE= +github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= +github.com/cockroachdb/redact v1.1.6 h1:zXJBwDZ84xJNlHl1rMyCojqyIxv+7YUpQiJLQ7n4314= +github.com/cockroachdb/redact v1.1.6/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= +github.com/containerd/stargz-snapshotter/estargz v0.14.3 h1:OqlDCK3ZVUO6C3B/5FSkDwbkEETK84kQgEeFwDC+62k= +github.com/containerd/stargz-snapshotter/estargz v0.14.3/go.mod h1:KY//uOCIkSuNAHhJogcZtrNHdKrA99/FCCRjE3HD36o= +github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w= +github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/creack/pty v1.1.18 h1:n56/Zwd5o6whRC5PMGretI4IdRLlmBXYNjScPaBgsbY= +github.com/creack/pty v1.1.18/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI= +github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= +github.com/docker/cli v24.0.4+incompatible h1:Y3bYF9ekNTm2VFz5U/0BlMdJy73D+Y1iAAZ8l63Ydzw= +github.com/docker/cli v24.0.4+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8= +github.com/docker/distribution v2.8.2+incompatible h1:T3de5rq0dB1j30rp0sA2rER+m322EBzniBPB6ZIzuh8= +github.com/docker/distribution v2.8.2+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= +github.com/docker/docker v24.0.4+incompatible h1:s/LVDftw9hjblvqIeTiGYXBCD95nOEEl7qRsRrIOuQI= +github.com/docker/docker v24.0.4+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= +github.com/docker/docker-credential-helpers v0.8.0 h1:YQFtbBQb4VrpoPxhFuzEBPQ9E16qz5SpHLS+uswaCp8= +github.com/docker/docker-credential-helpers v0.8.0/go.mod h1:UGFXcuoQ5TxPiB54nHOZ32AWRqQdECoh/Mg0AlEYb40= +github.com/docker/go-connections v0.4.0 h1:El9xVISelRB7BuFusrZozjnkIM5YnzCViNKohAFqRJQ= +github.com/docker/go-connections v0.4.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5XhDvyHbTtUxmeec= +github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4= +github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= +github.com/envoyproxy/protoc-gen-validate v0.3.0-java h1:bV5JGEB1ouEzZa0hgVDFFiClrUEuGWRaAc/3mxR2QK0= +github.com/envoyproxy/protoc-gen-validate v0.3.0-java/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs= +github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw= +github.com/felixge/fgprof v0.9.3 h1:VvyZxILNuCiUCSXtPtYmmtGvb65nqXh2QFWc0Wpf2/g= +github.com/felixge/fgprof v0.9.3/go.mod h1:RdbpDgzqYVh/T9fPELJyV7EYJuHB55UTEULNun8eiPw= +github.com/getsentry/sentry-go v0.27.0 h1:Pv98CIbtB3LkMWmXi4Joa5OOcwbmnX88sF5qbK3r3Ps= +github.com/getsentry/sentry-go v0.27.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= +github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk= +github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= +github.com/go-chi/chi/v5 v5.0.10 h1:rLz5avzKpjqxrYwXNfmjkrYYXOyLJd37pz53UFHC6vk= +github.com/go-chi/chi/v5 v5.0.10/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8= +github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA= +github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og= +github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= +github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y= +github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8= +github.com/gofrs/flock v0.8.1 h1:+gYjHKf32LDeiEEFhQaotPbLuUXjY5ZqxKgXy7n59aw= +github.com/gofrs/flock v0.8.1/go.mod h1:F1TvTiK9OcQqauNUHlbJvyl9Qa1QvF/gOUDKA14jxHU= +github.com/gofrs/uuid/v5 v5.0.0 h1:p544++a97kEL+svbcFbCQVM9KFu0Yo25UoISXGNNH9M= +github.com/gofrs/uuid/v5 v5.0.0/go.mod h1:CDOjlDMVAtN56jqyRUZh58JT31Tiw7/oQyEXZV+9bD8= +github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= +github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= +github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= +github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= +github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/go-containerregistry v0.15.2 h1:MMkSh+tjSdnmJZO7ljvEqV1DjfekB6VUEAZgy3a+TQE= +github.com/google/go-containerregistry v0.15.2/go.mod h1:wWK+LnOv4jXMM23IT/F1wdYftGWGr47Is8CG+pmHK1Q= +github.com/google/gofuzz v1.1.0 h1:Hsa8mG0dQ46ij8Sl2AYJDUv1oA9/d6Vk+3LG99Oe02g= +github.com/google/gofuzz v1.1.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/pprof v0.0.0-20211214055906-6f57359322fd/go.mod h1:KgnwoLYCZ8IQu3XUZ8Nc/bM9CCZFOyjUNOSygVozoDg= +github.com/google/pprof v0.0.0-20230705174524-200ffdc848b8 h1:n6vlPhxsA+BW/XsS5+uqi7GyzaLa5MH7qlSLBZtRdiA= +github.com/google/pprof v0.0.0-20230705174524-200ffdc848b8/go.mod h1:Jh3hGz2jkYak8qXPD19ryItVnUgpgeqzdkY/D0EaeuA= +github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= +github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/gorilla/css v1.0.1 h1:ntNaBIghp6JmvWnxbZKANoLyuXTPZ4cAMlo6RyhlbO8= +github.com/gorilla/css v1.0.1/go.mod h1:BvnYkspnSzMmwRK+b8/xgNPLiIuNZr6vbZBTPQ2A3b0= +github.com/grafana/regexp v0.0.0-20250905093917-f7b3be9d1853 h1:cLN4IBkmkYZNnk7EAJ0BHIethd+J6LqxFNw5mSiI2bM= +github.com/grafana/regexp v0.0.0-20250905093917-f7b3be9d1853/go.mod h1:+JKpmjMGhpgPL+rXZ5nsZieVzvarn86asRlBg4uNGnk= +github.com/hexops/autogold v1.3.1 h1:YgxF9OHWbEIUjhDbpnLhgVsjUDsiHDTyDfy2lrfdlzo= +github.com/hexops/autogold/v2 v2.2.1 h1:JPUXuZQGkcQMv7eeDXuNMovjfoRYaa0yVcm+F3voaGY= +github.com/hexops/autogold/v2 v2.2.1/go.mod h1:IJwxtUfj1BGLm0YsR/k+dIxYi6xbeLjqGke2bzcOTMI= +github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM= +github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg= +github.com/hexops/valast v1.4.4 h1:rETyycw+/L2ZVJHHNxEBgh8KUn+87WugH9MxcEv9PGs= +github.com/hexops/valast v1.4.4/go.mod h1:Jcy1pNH7LNraVaAZDLyv21hHg2WBv9Nf9FL6fGxU7o4= +github.com/huandu/xstrings v1.0.0 h1:pO2K/gKgKaat5LdpAhxhluX2GPQMaI3W5FUz/I/UnWk= +github.com/huandu/xstrings v1.0.0/go.mod h1:4qWG/gcEcfX4z/mBDHJ++3ReCw9ibxbsNJbcucJdbSo= +github.com/ianlancetaylor/demangle v0.0.0-20210905161508-09a460cdf81d/go.mod h1:aYm2/VgdVmcIU8iMfdMvDMsRAQjcfZSKFby6HOFvi/w= +github.com/imdario/mergo v0.3.4 h1:mKkfHkZWD8dC7WxKx3N9WCF0Y+dLau45704YQmY6H94= +github.com/imdario/mergo v0.3.4/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= +github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= +github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= +github.com/jackc/chunkreader/v2 v2.0.0/go.mod h1:odVSm741yZoC3dpHEUXIqA9tQRhFrgOHwnPIn9lDKlk= +github.com/jackc/chunkreader/v2 v2.0.1 h1:i+RDz65UE+mmpjTfyz0MoVTnzeYxroil2G82ki7MGG8= +github.com/jackc/chunkreader/v2 v2.0.1/go.mod h1:odVSm741yZoC3dpHEUXIqA9tQRhFrgOHwnPIn9lDKlk= +github.com/jackc/pgconn v1.14.3 h1:bVoTr12EGANZz66nZPkMInAV/KHD2TxH9npjXXgiB3w= +github.com/jackc/pgconn v1.14.3/go.mod h1:RZbme4uasqzybK2RK5c65VsHxoyaml09lx3tXOcO/VM= +github.com/jackc/pgio v1.0.0 h1:g12B9UwVnzGhueNavwioyEEpAmqMe1E/BN9ES+8ovkE= +github.com/jackc/pgio v1.0.0/go.mod h1:oP+2QK2wFfUWgr+gxjoBH9KGBb31Eio69xUb0w5bYf8= +github.com/jackc/pgmock v0.0.0-20210724152146-4ad1a8207f65 h1:DadwsjnMwFjfWc9y5Wi/+Zz7xoE5ALHsRQlOctkOiHc= +github.com/jackc/pgmock v0.0.0-20210724152146-4ad1a8207f65/go.mod h1:5R2h2EEX+qri8jOWMbJCtaPWkrrNc7OHwsp2TCqp7ak= +github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgproto3/v2 v2.3.3 h1:1HLSx5H+tXR9pW3in3zaztoEwQYRC9SQaYUHjTSUOag= +github.com/jackc/pgproto3/v2 v2.3.3/go.mod h1:WfJCnwN3HIg9Ish/j3sgWXnAfK8A9Y0bwXYU5xKaEdA= +github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk= +github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jdxcode/netrc v0.0.0-20221124155335-4616370d1a84 h1:2uT3aivO7NVpUPGcQX7RbHijHMyWix/yCnIrCWc+5co= +github.com/jdxcode/netrc v0.0.0-20221124155335-4616370d1a84/go.mod h1:Zi/ZFkEqFHTm7qkjyNJjaWH4LQA9LQhGJyF0lTYGpxw= +github.com/jhump/protoreflect v1.15.1 h1:HUMERORf3I3ZdX05WaQ6MIpd/NJ434hTp5YiKgfCL6c= +github.com/jhump/protoreflect v1.15.1/go.mod h1:jD/2GMKKE6OqX8qTjhADU1e6DShO+gavG9e0Q693nKo= +github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= +github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= +github.com/klauspost/pgzip v1.2.6 h1:8RXeL5crjEUFnR2/Sn6GJNWtSQ3Dk8pq4CL3jvdDyjU= +github.com/klauspost/pgzip v1.2.6/go.mod h1:Ch1tH69qFZu15pkjo5kYi6mth2Zzwzt50oCQKQE9RUs= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= +github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= +github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= +github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= +github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk= +github.com/mattn/go-runewidth v0.0.19 h1:v++JhqYnZuu5jSKrk9RbgF5v4CGUjqRfBm05byFGLdw= +github.com/mattn/go-runewidth v0.0.19/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs= +github.com/microcosm-cc/bluemonday v1.0.27 h1:MpEUotklkwCSLeH+Qdx1VJgNqLlpY2KXwXFM08ygZfk= +github.com/microcosm-cc/bluemonday v1.0.27/go.mod h1:jFi9vgW+H7c3V0lb6nR74Ib/DIB5OBs92Dimizgw2cA= +github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= +github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= +github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ= +github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc= +github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A= +github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc= +github.com/muesli/reflow v0.3.0 h1:IFsN6K9NfGtjeggFP+68I4chLZV2yIKsXJFNZ+eWh6s= +github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKtnHY/8= +github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc= +github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk= +github.com/mwitkow/go-proto-validators v0.0.0-20180403085117-0950a7990007 h1:28i1IjGcx8AofiB4N3q5Yls55VEaitzuEPkFJEVgGkA= +github.com/mwitkow/go-proto-validators v0.0.0-20180403085117-0950a7990007/go.mod h1:m2XC9Qq0AlmmVksL6FktJCdTYyLk7V3fKyp0sl1yWQo= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= +github.com/nightlyone/lockfile v1.0.0 h1:RHep2cFKK4PonZJDdEl4GmkabuhbsRMgk/k3uAmxBiA= +github.com/nightlyone/lockfile v1.0.0/go.mod h1:rywoIealpdNse2r832aiD9jRk8ErCatROs6LzC841CI= +github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= +github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= +github.com/opencontainers/image-spec v1.1.0-rc4 h1:oOxKUJWnFC4YGHCCMNql1x4YaDfYBTS5Y4x/Cgeo1E0= +github.com/opencontainers/image-spec v1.1.0-rc4/go.mod h1:X4pATf0uXsnn3g5aiGIsVnJBR4mxhKzfwmvK/B2NTm8= +github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4= +github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8= +github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 h1:KoWmjvw+nsYOo29YJK9vDA65RGE3NrOnUtO7a+RF9HU= +github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8/go.mod h1:HKlIX3XHQyzLZPlr7++PzdhaXEj94dEiJgZDTsxEqUI= +github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/profile v1.7.0 h1:hnbDkaNWPCLMO9wGLdBFTIZvzDrDfBM2072E1S9gJkA= +github.com/pkg/profile v1.7.0/go.mod h1:8Uer0jas47ZQMJ7VD+OHknK4YDY07LPUC6dEvqDjvNo= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pseudomuto/protoc-gen-doc v1.5.1 h1:Ah259kcrio7Ix1Rhb6u8FCaOkzf9qRBqXnvAufg061w= +github.com/pseudomuto/protoc-gen-doc v1.5.1/go.mod h1:XpMKYg6zkcpgfpCfQ8GcWBDRtRxOmMR5w7pz4Xo+dYM= +github.com/pseudomuto/protokit v0.2.0 h1:hlnBDcy3YEDXH7kc9gV+NLaN0cDzhDvD1s7Y6FZ8RpM= +github.com/pseudomuto/protokit v0.2.0/go.mod h1:2PdH30hxVHsup8KpBTOXTBeMVhJZVio3Q8ViKSAXT0Q= +github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= +github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= +github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= +github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= +github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= +github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= +github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= +github.com/rs/cors v1.9.0 h1:l9HGsTsHJcvW14Nk7J9KFz8bzeAWXn3CG6bgt7LsrAE= +github.com/rs/cors v1.9.0/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU= +github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/shurcooL/go v0.0.0-20180423040247-9e1955d9fb6e/go.mod h1:TDJrrUr11Vxrven61rcy3hJMUqaf/CLWYhHNPmT14Lk= +github.com/shurcooL/go-goon v0.0.0-20170922171312-37c2f522c041/go.mod h1:N5mDOmsrJOB+vfqUK+7DmDyjhSLIIBnXo9lvZJj3MWQ= +github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= +github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= +github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= +github.com/sourcegraph/beaut v0.0.0-20240611013027-627e4c25335a h1:j/CQ27s679M9wRGBRJYyXGrfkYuQA6VMnD7R08mHD9c= +github.com/sourcegraph/beaut v0.0.0-20240611013027-627e4c25335a/go.mod h1:JG1sdvGTKWwe/oH3/3UKQ26vfcHIN//7fwEJhoqaBcM= +github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo= +github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0= +github.com/sourcegraph/go-diff v0.7.0 h1:9uLlrd5T46OXs5qpp8L/MTltk0zikUGi0sNNyCpA8G0= +github.com/sourcegraph/go-diff v0.7.0/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= +github.com/sourcegraph/log v0.0.0-20250923023806-517b6960b55b h1:2FQ72y5zECMu9e5z5jMnllb5n1jVK7qsvgjkVtdFV+g= +github.com/sourcegraph/log v0.0.0-20250923023806-517b6960b55b/go.mod h1:IDp09QkoqS8Z3CyN2RW6vXjgABkNpDbyjLIHNQwQ8P8= +github.com/sourcegraph/scip v0.6.1 h1:lcBrTwGjsqpMLQN4pVfJYSB+8oVoc8Lnqb4FAfU8EBM= +github.com/sourcegraph/scip v0.6.1/go.mod h1:c6d9mk1cGT6OXdHutxDakKVEPN1D+iFoYWCsrDxEhus= +github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I= +github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0= +github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= +github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/tetratelabs/wazero v1.3.0 h1:nqw7zCldxE06B8zSZAY0ACrR9OH5QCcPwYmYlwtcwtE= +github.com/tetratelabs/wazero v1.3.0/go.mod h1:wYx2gNRg8/WihJfSDxA1TIL8H+GkfLYm+bIfbblu9VQ= +github.com/urfave/cli v1.22.12/go.mod h1:sSBEIC79qR6OvcmsD4U3KABeOTxDqQtdDnaFuUN30b8= +github.com/vbatts/tar-split v0.11.3 h1:hLFqsOLQ1SsppQNTMpkpPXClLDfC2A3Zgy9OUU+RVck= +github.com/vbatts/tar-split v0.11.3/go.mod h1:9QlHN18E+fEH7RdG+QAJJcuya3rqT7eXSTY7wGrAokY= +github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f h1:J9EGpcZtP0E/raorCMxlFGSTBrsSlaDGf3jU/qvAE2c= +github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= +github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0= +github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= +github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74= +github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y= +github.com/xlab/treeprint v1.2.0 h1:HzHnuAF1plUN2zGlAFHbSQP2qJ0ZAD3XF5XD7OesXRQ= +github.com/xlab/treeprint v1.2.0/go.mod h1:gj5Gd3gPdKtR1ikdDK6fnFLdmIS0X30kTTuNd/WEJu0= +github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no= +github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM= +github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.7.1/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E= +github.com/yuin/goldmark v1.7.8 h1:iERMLn0/QJeHFhxSt3p6PeN9mGnvIKSpG9YYorDMnic= +github.com/yuin/goldmark v1.7.8/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E= +github.com/yuin/goldmark-emoji v1.0.5 h1:EMVWyCGPlXJfUXBXpuMu+ii3TIaxbVBnEX9uaDC4cIk= +github.com/yuin/goldmark-emoji v1.0.5/go.mod h1:tTkZEbwu5wkPmgTcitqddVxY9osFZiavD+r4AzQrh1U= +go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA= +go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A= +go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8= +go.opentelemetry.io/otel v1.38.0/go.mod h1:zcmtmQ1+YmQM9wrNsTGV/q/uyusom3P8RxwExxkZhjM= +go.opentelemetry.io/otel/metric v1.38.0 h1:Kl6lzIYGAh5M159u9NgiRkmoMKjvbsKtYRwgfrA6WpA= +go.opentelemetry.io/otel/metric v1.38.0/go.mod h1:kB5n/QoRM8YwmUahxvI3bO34eVtQf2i4utNVLr9gEmI= +go.opentelemetry.io/otel/sdk v1.16.0 h1:Z1Ok1YsijYL0CSJpHt4cS3wDDh7p572grzNrBMiMWgE= +go.opentelemetry.io/otel/sdk v1.16.0/go.mod h1:tMsIuKXuuIWPBAOrH+eHtvhTL+SntFtXF9QD68aP6p4= +go.opentelemetry.io/otel/sdk/metric v0.39.0 h1:Kun8i1eYf48kHH83RucG93ffz0zGV1sh46FAScOTuDI= +go.opentelemetry.io/otel/sdk/metric v0.39.0/go.mod h1:piDIRgjcK7u0HCL5pCA4e74qpK/jk3NiUoAHATVAmiI= +go.opentelemetry.io/otel/trace v1.38.0 h1:Fxk5bKrDZJUH+AMyyIXGcFAPah0oRcT+LuNtJrmcNLE= +go.opentelemetry.io/otel/trace v1.38.0/go.mod h1:j1P9ivuFsTceSWe1oY+EeW3sc+Pp42sO++GHkg4wwhs= +go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= +go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= +go.uber.org/goleak v1.1.11 h1:wy28qYRKZgnJTxGxvye5/wgWr1EKjmUDGYox5mGlRlI= +go.uber.org/goleak v1.1.11/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ= +go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= +go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= +go.uber.org/zap v1.24.0 h1:FiJd5l1UOLj0wCgbSE0rwwXHzEdAZS6hiiSnxJN/D60= +go.uber.org/zap v1.24.0/go.mod h1:2kMP+WWQ8aoFoedH3T2sq6iJ2yDWpHbP0f6MQbS9Gkg= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.42.0 h1:chiH31gIWm57EkTXpwnqf8qeuMUi0yekh6mT2AvFlqI= +golang.org/x/crypto v0.42.0/go.mod h1:4+rDnOTJhQCx2q7/j6rAN5XDw8kPjeaXEUR2eL94ix8= +golang.org/x/exp v0.0.0-20231108232855-2478ac86f678 h1:mchzmB1XO2pMaKFRqk/+MV3mgGG96aqaPXaMifQU47w= +golang.org/x/exp v0.0.0-20231108232855-2478ac86f678/go.mod h1:zk2irFbV9DP96SEBUUAy67IdHUaZuSnrz1n472HUCLE= +golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.28.0 h1:gQBtGhjxykdjY9YhZpSlZIsbnaE2+PgjfLWUQTnoZ1U= +golang.org/x/mod v0.28.0/go.mod h1:yfB/L0NOf/kmEbXjzCPOx1iK1fRutOydrCMsqRhEBxI= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.44.0 h1:evd8IRDyfNBMBTTY5XRF1vaZlD+EmWx6x8PkhR04H/I= +golang.org/x/net v0.44.0/go.mod h1:ECOoLqd5U3Lhyeyo/QDCEVQ4sNgYsqvCZ722XogGieY= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug= +golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210616045830-e2b7044e8c71/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211007075335-d3039528d8ac/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220906165534-d0df966e6959/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc= +golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/telemetry v0.0.0-20250908211612-aef8a434d053 h1:dHQOQddU4YHS5gY33/6klKjq7Gp3WwMyOXGNp5nzRj8= +golang.org/x/telemetry v0.0.0-20250908211612-aef8a434d053/go.mod h1:+nZKN+XVh4LCiA9DV3ywrzN4gumyCnKjau3NGb9SGoE= +golang.org/x/term v0.37.0 h1:8EGAD0qCmHYZg6J17DvsMy9/wJ7/D/4pV/wfnld5lTU= +golang.org/x/term v0.37.0/go.mod h1:5pB4lxRNYYVZuTLmy8oR2BH8dflOR+IbTYFD8fi3254= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk= +golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4= +golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4= +golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.37.0 h1:DVSRzp7FwePZW356yEAChSdNcQo6Nsp+fex1SUW09lE= +golang.org/x/tools v0.37.0/go.mod h1:MBN5QPQtLMHVdvsbtarmTNukZDdgwdwlO5qGacAzF0w= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 h1:KpwkzHKEF7B9Zxg18WzOa7djJ+Ha5DzthMyZYQfEn2A= +google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1/go.mod h1:nKE/iIaLqn2bQwXBg8f1g2Ylh6r5MN5CmZvuzZCgsCU= +google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= +google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= +google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gotest.tools/v3 v3.0.3 h1:4AuOwCGf4lLR9u3YOe2awrHygurzhO/HeQ6laiA6Sx0= +gotest.tools/v3 v3.0.3/go.mod h1:Z7Lb0S5l+klDB31fvDQX8ss/FlKDxtlFlw3Oa8Ymbl8= +mvdan.cc/gofumpt v0.5.0 h1:0EQ+Z56k8tXjj/6TQD25BFNKQXpCvT0rnansIc7Ug5E= +mvdan.cc/gofumpt v0.5.0/go.mod h1:HBeVDtMKRZpXyxFciAirzdKklDlGu8aAy1wEbH5Y9js= +pgregory.net/rapid v1.1.0 h1:CMa0sjHSru3puNx+J0MIAuiiEV4N0qj8/cMWGBBCsjw= +pgregory.net/rapid v1.1.0/go.mod h1:PY5XlDGj0+V1FCq0o192FdRhpKHGTRIWBgqjDBTrq04= diff --git a/lib/output/block.go b/lib/output/block.go new file mode 100644 index 0000000000..00d5d7ecbf --- /dev/null +++ b/lib/output/block.go @@ -0,0 +1,58 @@ +package output + +import ( + "bytes" + "sync" +) + +// Block represents a block of output with one status line, and then zero or +// more lines of output nested under the status line. +type Block struct { + *Output + + indent []byte + unwrapped *Output + writer *indentedWriter +} + +func newBlock(indent int, o *Output) *Block { + w := &indentedWriter{} + + // Block uses Output's implementation, but with a wrapped writer that + // indents all output lines. (Note, however, that o's lock mutex is still + // used.) + return &Block{ + Output: &Output{ + w: w, + caps: o.caps, + }, + indent: bytes.Repeat([]byte(" "), indent), + unwrapped: o, + writer: w, + } +} + +func (b *Block) Close() { + b.unwrapped.Lock() + defer b.unwrapped.Unlock() + + // This is a little tricky: output from Writer methods includes a trailing + // newline, so we need to trim that so we don't output extra blank lines. + for line := range bytes.SplitSeq(bytes.TrimRight(b.writer.buffer.Bytes(), "\n"), []byte("\n")) { + _, _ = b.unwrapped.w.Write(b.indent) + _, _ = b.unwrapped.w.Write(line) + _, _ = b.unwrapped.w.Write([]byte("\n")) + } +} + +type indentedWriter struct { + buffer bytes.Buffer + lock sync.Mutex +} + +func (w *indentedWriter) Write(p []byte) (int, error) { + w.lock.Lock() + defer w.lock.Unlock() + + return w.buffer.Write(p) +} diff --git a/lib/output/capabilities.go b/lib/output/capabilities.go new file mode 100644 index 0000000000..f789104ecd --- /dev/null +++ b/lib/output/capabilities.go @@ -0,0 +1,124 @@ +package output + +import ( + "os" + "strconv" + "sync" + + "github.com/mattn/go-isatty" + "github.com/moby/term" + "github.com/muesli/termenv" + + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +// capabilities configures everything that might require detection of the terminal +// environment to change how data is output. +// +// When adding new capabilities, make sure an option to disable running any detection at +// all is provided via OutputOpts, so that issues with detection can be avoided in edge +// cases by configuring an override. +type capabilities struct { + Color bool + Isatty bool + Height int + Width int + + DarkBackground bool +} + +// These all inspect stdout / the terminal so we hide them behind a sync.Once. +// This is because we may call detectCapabilities many times due to doing +// things like capturing output. We have observed garbled output due to +// concurrent calls to detectCapabilities. +var ( + stdoutIsAtty = sync.OnceValue(func() bool { + return isatty.IsTerminal(os.Stdout.Fd()) + }) + stdoutWinSize = sync.OnceValues(func() (*term.Winsize, error) { + return term.GetWinsize(os.Stdout.Fd()) + }) + isDarkBackground = sync.OnceValue(func() bool { + return termenv.HasDarkBackground() + }) +) + +// detectCapabilities lazily evaluates capabilities using the given options. This means +// that if an override is indicated in opts, no inference of the relevant capabilities +// is done at all. +func detectCapabilities(opts OutputOpts) (caps capabilities, err error) { + // Set atty + if opts.ForceTTY != nil { + caps.Isatty = *opts.ForceTTY + } else { + caps.Isatty = stdoutIsAtty() + } + + // Default width and height + caps.Width, caps.Height = 80, 25 + // If all dimensions are forced, detection is not needed + forceAllDimensions := opts.ForceHeight != 0 && opts.ForceWidth != 0 + if caps.Isatty && !forceAllDimensions { + var size *term.Winsize + size, err = stdoutWinSize() + if err == nil { + if size != nil { + caps.Width, caps.Height = int(size.Width), int(size.Height) + } else { + err = errors.New("unexpected nil size from GetWinsize") + } + } else { + err = errors.Wrap(err, "GetWinsize") + } + } + // Set overrides + if opts.ForceWidth != 0 { + caps.Width = opts.ForceWidth + } + if opts.ForceHeight != 0 { + caps.Height = opts.ForceHeight + } + + // detect color mode + caps.Color = opts.ForceColor + if !opts.ForceColor { + caps.Color = detectColor(caps.Isatty) + } + + // set detected background color + caps.DarkBackground = opts.ForceDarkBackground + if !opts.ForceDarkBackground { + caps.DarkBackground = isDarkBackground() + } + + return +} + +func detectColor(atty bool) bool { + if os.Getenv("NO_COLOR") != "" { + return false + } + + if color := os.Getenv("COLOR"); color != "" { + enabled, _ := strconv.ParseBool(color) + return enabled + } + + if !atty { + return false + } + + return true +} + +func (c *capabilities) formatArgs(args []any) []any { + out := make([]any, len(args)) + for i, arg := range args { + if _, ok := arg.(Style); ok && !c.Color { + out[i] = "" + } else { + out[i] = arg + } + } + return out +} diff --git a/lib/output/emoji.go b/lib/output/emoji.go new file mode 100644 index 0000000000..469e9eccb8 --- /dev/null +++ b/lib/output/emoji.go @@ -0,0 +1,32 @@ +package output + +var allEmojis = [...]string{ + EmojiFailure, + EmojiWarning, + EmojiSuccess, + EmojiInfo, + EmojiLightbulb, + EmojiAsterisk, + EmojiWarningSign, + EmojiFingerPointRight, + EmojiHourglass, + EmojiShrug, + EmojiOk, + EmojiQuestionMark, +} + +// Standard emoji for use in output. +const ( + EmojiFailure = "❌" + EmojiWarning = "❗️" + EmojiSuccess = "✅" + EmojiInfo = "ℹ️" + EmojiLightbulb = "💡" + EmojiAsterisk = "✱" + EmojiWarningSign = "⚠️" + EmojiFingerPointRight = "👉" + EmojiHourglass = "⌛" + EmojiShrug = "🤷" + EmojiOk = "👌" + EmojiQuestionMark = "❔" +) diff --git a/lib/output/line.go b/lib/output/line.go new file mode 100644 index 0000000000..ed566d0d8b --- /dev/null +++ b/lib/output/line.go @@ -0,0 +1,78 @@ +package output + +import ( + "fmt" + "io" +) + +// FancyLine is a formatted output line with an optional emoji and style. +type FancyLine struct { + emoji string + style Style + format string + args []any + + // Prefix can be set to prepend some content to this fancy line. + Prefix string + // Prompt can be set to indicate this line is a prompt (should not be followed by a + // new line). + Prompt bool +} + +// Line creates a new FancyLine without a format string. +func Line(emoji string, style Style, s string) FancyLine { + return FancyLine{ + emoji: emoji, + style: style, + format: "%s", + args: []any{s}, + } +} + +// Line creates a new FancyLine with a format string. As with Writer, the +// arguments may include Style instances with the %s specifier. +func Linef(emoji string, style Style, format string, a ...any) FancyLine { + return FancyLine{ + emoji: emoji, + style: style, + format: format, + args: a, + } +} + +// Emoji creates a new FancyLine with an emoji prefix. +func Emoji(emoji string, s string) FancyLine { + return Line(emoji, StyleReset, s) +} + +// Emoji creates a new FancyLine with an emoji prefix and format string. +func Emojif(emoji string, s string, a ...any) FancyLine { + return Linef(emoji, StyleReset, s, a...) +} + +// Styled creates a new FancyLine with style. +func Styled(style Style, s string) FancyLine { + return Line("", style, s) +} + +// Styledf creates a new FancyLine with style and format string. +func Styledf(style Style, s string, a ...any) FancyLine { + return Linef("", style, s, a...) +} + +func (fl FancyLine) write(w io.Writer, caps capabilities) { + if fl.Prefix != "" { + fmt.Fprint(w, fl.Prefix+" ") + } + if fl.emoji != "" { + fmt.Fprint(w, fl.emoji+" ") + } + + fmt.Fprintf(w, "%s"+fl.format+"%s", caps.formatArgs(append(append([]any{fl.style}, fl.args...), StyleReset))...) + if fl.Prompt { + // Add whitespace for user input + _, _ = w.Write([]byte(" ")) + } else { + _, _ = w.Write([]byte("\n")) + } +} diff --git a/lib/output/logger.go b/lib/output/logger.go new file mode 100644 index 0000000000..76f4cf1111 --- /dev/null +++ b/lib/output/logger.go @@ -0,0 +1,31 @@ +package output + +import ( + "bytes" + + "github.com/sourcegraph/log" +) + +type logFacade struct { + logger log.Logger +} + +func OutputFromLogger(logger log.Logger) *Output { + return NewOutput(&logFacade{logger}, OutputOpts{}) +} + +func (l *logFacade) Write(p []byte) (n int, err error) { + for _, emoji := range allEmojis { + if bytes.HasPrefix(p, []byte(emoji)) { + switch emoji { + case EmojiWarningSign: + l.logger.Warn(string(p[len(emoji):])) + case EmojiFailure, EmojiWarning: + l.logger.Error(string(p[len(emoji):])) + default: + l.logger.Info(string(p[len(emoji):])) + } + } + } + return len(p), nil +} diff --git a/lib/output/noop_writer.go b/lib/output/noop_writer.go new file mode 100644 index 0000000000..784bffb67d --- /dev/null +++ b/lib/output/noop_writer.go @@ -0,0 +1,10 @@ +package output + +type NoopWriter struct{} + +func (NoopWriter) Write(s string) {} +func (NoopWriter) Writef(format string, args ...any) {} +func (NoopWriter) WriteLine(line FancyLine) {} +func (NoopWriter) Verbose(s string) {} +func (NoopWriter) Verbosef(format string, args ...any) {} +func (NoopWriter) VerboseLine(line FancyLine) {} diff --git a/lib/output/output.go b/lib/output/output.go new file mode 100644 index 0000000000..f1d1305277 --- /dev/null +++ b/lib/output/output.go @@ -0,0 +1,354 @@ +// Package output provides types related to formatted terminal output. +package output + +import ( + "bytes" + "fmt" + "io" + "os" + "sync" + + "github.com/charmbracelet/glamour" + glamouransi "github.com/charmbracelet/glamour/ansi" + "github.com/charmbracelet/glamour/styles" + "github.com/mattn/go-runewidth" + "golang.org/x/term" + + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +// Writer defines a common set of methods that can be used to output status +// information. +// +// Note that the *f methods can accept Style instances in their arguments with +// the %s format specifier: if given, the detected colour support will be +// respected when outputting. +type Writer interface { + // These methods only write the given message if verbose mode is enabled. + Verbose(s string) + Verbosef(format string, args ...any) + VerboseLine(line FancyLine) + + // These methods write their messages unconditionally. + Write(s string) + Writef(format string, args ...any) + WriteLine(line FancyLine) +} + +type Context interface { + Writer + + Close() +} + +// Output encapsulates a standard set of functionality for commands that need +// to output human-readable data. +// +// Output is not appropriate for machine-readable data, such as JSON. +type Output struct { + w io.Writer + caps capabilities + verbose bool + + // Unsurprisingly, it would be bad if multiple goroutines wrote at the same + // time, so we have a basic mutex to guard against that. + lock sync.Mutex +} + +var _ sync.Locker = &Output{} + +type OutputOpts struct { + // ForceColor ignores all terminal detection and enabled coloured output. + ForceColor bool + // ForceTTY ignores all terminal detection if non-nil and sets TTY output. + ForceTTY *bool + + // ForceHeight ignores all terminal detection and sets the height to this value. + ForceHeight int + // ForceWidth ignores all terminal detection and sets the width to this value. + ForceWidth int + + // ForceDarkBackground ignores all terminal detection and sets whether the terminal + // background is dark to this value. + ForceDarkBackground bool + + Verbose bool +} + +type MarkdownStyleOpts func(style *glamouransi.StyleConfig) + +var MarkdownNoMargin MarkdownStyleOpts = func(style *glamouransi.StyleConfig) { + z := uint(0) + style.CodeBlock.Margin = &z + style.Document.Margin = &z + style.Document.BlockPrefix = "" + style.Document.BlockSuffix = "" +} + +// newOutputPlatformQuirks provides a way for conditionally compiled code to +// hook into NewOutput to perform any required setup. +var newOutputPlatformQuirks func(o *Output) error + +// newCapabilityWatcher returns a channel that receives a message when +// capabilities are updated. By default, no watching functionality is +// available. +var newCapabilityWatcher = func(opts OutputOpts) chan capabilities { return nil } + +func NewOutput(w io.Writer, opts OutputOpts) *Output { + // Not being able to detect capabilities is alright. It might mean output will look + // weird but that should not prevent us from running. + // Before, we logged an error + // "An error was returned when detecting the terminal size and capabilities" + // but it was super noisy and confused people into thinking something would be broken. + caps, _ := detectCapabilities(opts) + + o := &Output{caps: caps, verbose: opts.Verbose, w: w} + if newOutputPlatformQuirks != nil { + if err := newOutputPlatformQuirks(o); err != nil { + o.Verbosef("Error handling platform quirks: %v", err) + } + } + + // Set up a watcher so we can adjust the size of the output if the terminal + // is resized. + if c := newCapabilityWatcher(opts); c != nil { + go func() { + for caps := range c { + o.caps = caps + } + }() + } + + return o +} + +func (o *Output) Lock() { + o.lock.Lock() + + if o.caps.Isatty { + // Hide the cursor while we update: this reduces the jitteriness of the + // whole thing, and some terminals are smart enough to make the update we're + // about to render atomic if the cursor is hidden for a short length of + // time. + o.w.Write([]byte("\033[?25l")) + } +} + +func (o *Output) SetVerbose() { + o.lock.Lock() + defer o.lock.Unlock() + o.verbose = true +} + +func (o *Output) UnsetVerbose() { + o.lock.Lock() + defer o.lock.Unlock() + o.verbose = false +} + +func (o *Output) Unlock() { + if o.caps.Isatty { + // Show the cursor once more. + o.w.Write([]byte("\033[?25h")) + } + + o.lock.Unlock() +} + +func (o *Output) Verbose(s string) { + if o.verbose { + o.Write(s) + } +} + +func (o *Output) Verbosef(format string, args ...any) { + if o.verbose { + o.Writef(format, args...) + } +} + +func (o *Output) VerboseLine(line FancyLine) { + if o.verbose { + o.WriteLine(line) + } +} + +func (o *Output) Write(s string) { + o.Lock() + defer o.Unlock() + fmt.Fprintln(o.w, s) +} + +func (o *Output) Writef(format string, args ...any) { + o.Lock() + defer o.Unlock() + fmt.Fprintf(o.w, format, o.caps.formatArgs(args)...) + fmt.Fprint(o.w, "\n") +} + +func (o *Output) WriteLine(line FancyLine) { + o.Lock() + defer o.Unlock() + line.write(o.w, o.caps) +} + +// Block starts a new block context. This should not be invoked if there is an +// active Pending or Progress context. +func (o *Output) Block(summary FancyLine) *Block { + o.WriteLine(summary) + return newBlock(runewidth.StringWidth(summary.emoji)+1, o) +} + +// Pending sets up a new pending context. This should not be invoked if there +// is an active Block or Progress context. The emoji in the message will be +// ignored, as Pending will render its own spinner. +// +// A Pending instance must be disposed of via the Complete or Destroy methods. +func (o *Output) Pending(message FancyLine) Pending { + return newPending(message, o) +} + +// Progress sets up a new progress bar context. This should not be invoked if +// there is an active Block or Pending context. +// +// A Progress instance must be disposed of via the Complete or Destroy methods. +func (o *Output) Progress(bars []ProgressBar, opts *ProgressOpts) Progress { + return newProgress(bars, o, opts) +} + +// ProgressWithStatusBars sets up a new progress bar context with StatusBar +// contexts. This should not be invoked if there is an active Block or Pending +// context. +// +// A Progress instance must be disposed of via the Complete or Destroy methods. +func (o *Output) ProgressWithStatusBars(bars []ProgressBar, statusBars []*StatusBar, opts *ProgressOpts) ProgressWithStatusBars { + return newProgressWithStatusBars(bars, statusBars, o, opts) +} + +type readWriter struct { + io.Reader + io.Writer +} + +// PromptPassword tries to securely prompt a user for sensitive input. +func (o *Output) PromptPassword(input io.Reader, prompt FancyLine) (string, error) { + o.lock.Lock() + defer o.lock.Unlock() + + // Render the prompt + prompt.Prompt = true + var promptText bytes.Buffer + prompt.write(&promptText, o.caps) + + // If input is a file and terminal, read from it directly + if f, ok := input.(*os.File); ok { + fd := int(f.Fd()) + if term.IsTerminal(fd) { + _, _ = o.w.Write(promptText.Bytes()) + val, err := term.ReadPassword(fd) + _, _ = o.w.Write([]byte("\n")) // once we've read an input + return string(val), err + } + } + + // Otherwise, create a terminal + t := term.NewTerminal(&readWriter{Reader: input, Writer: o.w}, "") + _ = t.SetSize(o.caps.Width, o.caps.Height) + return t.ReadPassword(promptText.String()) +} + +func MarkdownIndent(n uint) MarkdownStyleOpts { + return func(style *glamouransi.StyleConfig) { + style.Document.Indent = &n + } +} + +// WriteCode renders the given code snippet as Markdown, unless color is disabled. +func (o *Output) WriteCode(languageName, str string) error { + return o.WriteMarkdown(fmt.Sprintf("```%s\n%s\n```", languageName, str), MarkdownNoMargin) +} + +func (o *Output) WriteMarkdown(str string, opts ...MarkdownStyleOpts) error { + o.Lock() + defer o.Unlock() + return o.RenderMarkdown(o.w, str) +} + +func (o *Output) RenderMarkdown(w io.Writer, str string, opts ...MarkdownStyleOpts) error { + if !o.caps.Color { + _, err := fmt.Fprintln(w, str) + return err + } + + style := glamourGetDefaultStyle(o.caps) + for _, opt := range opts { + opt(&style) + } + + r, err := glamour.NewTermRenderer( + // detect background color and pick either the default dark or light theme + glamour.WithStyles(style), + // wrap output at slightly less than terminal width + glamour.WithWordWrap(o.caps.Width*4/5), + glamour.WithEmoji(), + glamour.WithPreservedNewLines(), + ) + if err != nil { + return errors.Wrap(err, "renderer") + } + + rendered, err := r.Render(str) + if err != nil { + return errors.Wrap(err, "render") + } + + _, err = fmt.Fprintln(w, rendered) + return err +} + +// The utility functions below do not make checks for whether the terminal is a +// TTY, and should only be invoked from behind appropriate guards. + +func (o *Output) clearCurrentLine() { + fmt.Fprint(o.w, "\033[2K") +} + +func (o *Output) moveDown(lines int) { + fmt.Fprintf(o.w, "\033[%dB", lines) + + // Move the cursor to the leftmost column. + fmt.Fprintf(o.w, "\033[%dD", o.caps.Width+1) +} + +func (o *Output) moveUp(lines int) { + fmt.Fprintf(o.w, "\033[%dA", lines) + + // Move the cursor to the leftmost column. + fmt.Fprintf(o.w, "\033[%dD", o.caps.Width+1) +} + +func (o *Output) MoveUpLines(lines int) { + o.moveUp(lines) +} + +// writeStyle is a helper to write a style while respecting the terminal +// capabilities. +func (o *Output) writeStyle(style Style) { + fmt.Fprintf(o.w, "%s", o.caps.formatArgs([]any{style})...) +} + +func (o *Output) ClearScreen() { + fmt.Fprintf(o.w, "\033c") +} + +// from unexported method glamour.getDefaultStyle but specialized to style == +// "auto" and using our detection +func glamourGetDefaultStyle(caps capabilities) glamouransi.StyleConfig { + if !caps.Isatty { + return styles.NoTTYStyleConfig + } + if caps.DarkBackground { + return styles.DarkStyleConfig + } + return styles.LightStyleConfig +} diff --git a/lib/output/output_unix.go b/lib/output/output_unix.go new file mode 100644 index 0000000000..f55b2003b0 --- /dev/null +++ b/lib/output/output_unix.go @@ -0,0 +1,79 @@ +//go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris +// +build aix darwin dragonfly freebsd linux netbsd openbsd solaris + +package output + +import ( + "os" + "os/signal" + "sync" + "syscall" +) + +func init() { + // The platforms this file builds on support the SIGWINCH signal, which + // indicates that the terminal has been resized. When we receive that + // signal, we can use this to re-detect the terminal capabilities. + // + // We won't do any setup until the first time newCapabilityWatcher is + // invoked, but we do need some shared state to be ready. + var ( + // chans contains the listening channels that should be notified when + // capabilities are updated. + chans []chan capabilities + + // mu guards the chans variable. + mu sync.RWMutex + + // once guards the lazy initialisation, including installing the signal + // handler. + once sync.Once + ) + + newCapabilityWatcher = func(opts OutputOpts) chan capabilities { + // Lazily initialise the required global state if we haven't already. + once.Do(func() { + mu.Lock() + chans = make([]chan capabilities, 0, 1) + mu.Unlock() + + // Install the signal handler. To avoid race conditions, we should + // do this synchronously before spawning the goroutine that will + // actually listen to the channel. + c := make(chan os.Signal, 1) + signal.Notify(c, syscall.SIGWINCH) + + go func() { + for { + <-c + caps, err := detectCapabilities(opts) + // We won't bother reporting an error here; there's no harm + // in the previous capabilities being used besides possibly + // being ugly. + if err == nil { + mu.RLock() + for _, out := range chans { + go func() { + select { + case out <- caps: + // success + default: + // welp + } + }() + } + mu.RUnlock() + } + } + }() + }) + + // Now we can create and return the actual output channel. + out := make(chan capabilities) + mu.Lock() + defer mu.Unlock() + chans = append(chans, out) + + return out + } +} diff --git a/lib/output/output_windows.go b/lib/output/output_windows.go new file mode 100644 index 0000000000..794c4444d8 --- /dev/null +++ b/lib/output/output_windows.go @@ -0,0 +1,61 @@ +package output + +import ( + "time" + + "golang.org/x/sys/windows" + + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +func init() { + newOutputPlatformQuirks = func(o *Output) error { + var errs error + + if err := setConsoleMode(windows.Stdout, windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING); err != nil { + errs = errors.Append(errs, err) + } + if err := setConsoleMode(windows.Stderr, windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING); err != nil { + errs = errors.Append(errs, err) + } + + return errs + } + + // Windows doesn't have a particularly good way of notifying console + // applications that a resize has occurred. (Historically, you could hook + // the console window, but it turns out that's a security nightmare.) So + // we'll just poll every five seconds and update the capabilities from + // there. + newCapabilityWatcher = func(opts OutputOpts) chan capabilities { + c := make(chan capabilities) + + go func() { + ticker := time.NewTicker(5 * time.Second) + defer ticker.Stop() + for { + <-ticker.C + if caps, err := detectCapabilities(opts); err == nil { + c <- caps + } + } + }() + + return c + } +} + +func setConsoleMode(handle windows.Handle, flags uint32) error { + // This is shamelessly lifted from gitlab-runner, specifically + // https://gitlab.com/gitlab-org/gitlab-runner/blob/f8d87f1e3e3af1cc8aadcea3e40bbb069eee72ef/helpers/cli/init_cli_windows.go + + // First we have to get the current console mode so we can add the desired + // flags. + var mode uint32 + if err := windows.GetConsoleMode(handle, &mode); err != nil { + return err + } + + // Now we can set the console mode. + return windows.SetConsoleMode(handle, mode|flags) +} diff --git a/lib/output/pending.go b/lib/output/pending.go new file mode 100644 index 0000000000..7e33ed9c39 --- /dev/null +++ b/lib/output/pending.go @@ -0,0 +1,26 @@ +package output + +type Pending interface { + // Anything sent to the Writer methods will be displayed as a log message + // above the pending line. + Context + + // Update and Updatef change the message shown after the spinner. + Update(s string) + Updatef(format string, args ...any) + + // Complete stops the spinner and replaces the pending line with the given + // message. + Complete(message FancyLine) + + // Destroy stops the spinner and removes the pending line. + Destroy() +} + +func newPending(message FancyLine, o *Output) Pending { + if !o.caps.Isatty { + return newPendingSimple(message, o) + } + + return newPendingTTY(message, o) +} diff --git a/lib/output/pending_simple.go b/lib/output/pending_simple.go new file mode 100644 index 0000000000..7a25451095 --- /dev/null +++ b/lib/output/pending_simple.go @@ -0,0 +1,26 @@ +package output + +type pendingSimple struct { + *Output +} + +func (p *pendingSimple) Update(s string) { + p.Write(s + "...") +} + +func (p *pendingSimple) Updatef(format string, args ...any) { + p.Writef(format+"...", args...) +} + +func (p *pendingSimple) Complete(message FancyLine) { + p.WriteLine(message) +} + +func (p *pendingSimple) Close() {} +func (p *pendingSimple) Destroy() {} + +func newPendingSimple(message FancyLine, o *Output) *pendingSimple { + message.format += "..." + o.WriteLine(message) + return &pendingSimple{o} +} diff --git a/lib/output/pending_tty.go b/lib/output/pending_tty.go new file mode 100644 index 0000000000..86853edc4a --- /dev/null +++ b/lib/output/pending_tty.go @@ -0,0 +1,160 @@ +package output + +import ( + "bytes" + "fmt" + "time" + + "github.com/mattn/go-runewidth" +) + +type pendingTTY struct { + o *Output + line FancyLine + spinner *spinner +} + +func (p *pendingTTY) Verbose(s string) { + if p.o.verbose { + p.Write(s) + } +} + +func (p *pendingTTY) Verbosef(format string, args ...any) { + if p.o.verbose { + p.Writef(format, args...) + } +} + +func (p *pendingTTY) VerboseLine(line FancyLine) { + if p.o.verbose { + p.WriteLine(line) + } +} + +func (p *pendingTTY) Write(s string) { + p.o.Lock() + defer p.o.Unlock() + + p.o.moveUp(1) + p.o.clearCurrentLine() + fmt.Fprintln(p.o.w, s) + p.write(p.line) +} + +func (p *pendingTTY) Writef(format string, args ...any) { + p.o.Lock() + defer p.o.Unlock() + + p.o.moveUp(1) + p.o.clearCurrentLine() + fmt.Fprintf(p.o.w, format, p.o.caps.formatArgs(args)...) + fmt.Fprint(p.o.w, "\n") + p.write(p.line) +} + +func (p *pendingTTY) WriteLine(line FancyLine) { + p.o.Lock() + defer p.o.Unlock() + + p.o.moveUp(1) + p.o.clearCurrentLine() + line.write(p.o.w, p.o.caps) + p.write(p.line) +} + +func (p *pendingTTY) Update(s string) { + p.o.Lock() + defer p.o.Unlock() + + p.line.format = "%s" + p.line.args = []any{s} + + p.o.moveUp(1) + p.o.clearCurrentLine() + p.write(p.line) +} + +func (p *pendingTTY) Updatef(format string, args ...any) { + p.o.Lock() + defer p.o.Unlock() + + p.line.format = format + p.line.args = args + + p.o.moveUp(1) + p.o.clearCurrentLine() + p.write(p.line) +} + +func (p *pendingTTY) Complete(message FancyLine) { + p.spinner.stop() + + p.o.Lock() + defer p.o.Unlock() + + p.o.moveUp(1) + p.o.clearCurrentLine() + p.write(message) +} + +func (p *pendingTTY) Close() { p.Destroy() } + +func (p *pendingTTY) Destroy() { + p.spinner.stop() + + p.o.Lock() + defer p.o.Unlock() + + p.o.moveUp(1) + p.o.clearCurrentLine() +} + +func newPendingTTY(message FancyLine, o *Output) *pendingTTY { + p := &pendingTTY{ + o: o, + line: message, + spinner: newSpinner(100 * time.Millisecond), + } + p.updateEmoji(spinnerStrings[0]) + fmt.Fprintln(p.o.w, "") + + go func() { + for s := range p.spinner.C { + func() { + p.o.Lock() + defer p.o.Unlock() + + p.updateEmoji(s) + + p.o.moveUp(1) + p.o.clearCurrentLine() + p.write(p.line) + }() + } + }() + + return p +} + +func (p *pendingTTY) updateEmoji(emoji string) { + // We add an extra space because the Braille characters are single width, + // but emoji are generally double width and that's what will most likely be + // used in the completion message, if any. + p.line.emoji = fmt.Sprintf("%s%s ", p.o.caps.formatArgs([]any{ + p.line.style, + emoji, + })...) +} + +func (p *pendingTTY) write(message FancyLine) { + var buf bytes.Buffer + + // This appends a newline to buf, so we have to be careful to ensure that + // we also add a newline if the line is truncated. + message.write(&buf, p.o.caps) + + // FIXME: This doesn't account for escape codes right now, so we may + // truncate shorter than we mean to. + fmt.Fprint(p.o.w, runewidth.Truncate(buf.String(), p.o.caps.Width, "...\n")) +} diff --git a/lib/output/progress.go b/lib/output/progress.go new file mode 100644 index 0000000000..2b7d9688a4 --- /dev/null +++ b/lib/output/progress.go @@ -0,0 +1,60 @@ +package output + +type Progress interface { + Context + + // Complete stops the set of progress bars and marks them all as completed. + Complete() + + // Destroy stops the set of progress bars and clears them from the + // terminal. + Destroy() + + // SetLabel updates the label for the given bar. + SetLabel(i int, label string) + + // SetLabelAndRecalc updates the label for the given bar and recalculates + // the maximum width of the labels. + SetLabelAndRecalc(i int, label string) + + // SetValue updates the value for the given bar. + SetValue(i int, v float64) +} + +type ProgressBar struct { + Label string + Max float64 + Value float64 + + labelWidth int +} + +type ProgressOpts struct { + PendingStyle Style + SuccessEmoji string + SuccessStyle Style + + // NoSpinner turns of the automatic updating of the progress bar and + // spinner in a background goroutine. + // Used for testing only! + NoSpinner bool +} + +func (opt *ProgressOpts) WithNoSpinner(noSpinner bool) *ProgressOpts { + c := *opt + c.NoSpinner = noSpinner + return &c +} + +func newProgress(bars []ProgressBar, o *Output, opts *ProgressOpts) Progress { + barPtrs := make([]*ProgressBar, len(bars)) + for i := range bars { + barPtrs[i] = &bars[i] + } + + if !o.caps.Isatty { + return newProgressSimple(barPtrs, o, opts) + } + + return newProgressTTY(barPtrs, o, opts) +} diff --git a/lib/output/progress_simple.go b/lib/output/progress_simple.go new file mode 100644 index 0000000000..dadfc3086c --- /dev/null +++ b/lib/output/progress_simple.go @@ -0,0 +1,91 @@ +package output + +import ( + "math" + "time" +) + +type progressSimple struct { + *Output + + bars []*ProgressBar + done chan chan struct{} +} + +func (p *progressSimple) Complete() { + p.stop() + writeBars(p.Output, p.bars) +} + +func (p *progressSimple) Close() { p.Destroy() } +func (p *progressSimple) Destroy() { p.stop() } + +func (p *progressSimple) SetLabel(i int, label string) { + p.bars[i].Label = label +} + +func (p *progressSimple) SetLabelAndRecalc(i int, label string) { + p.bars[i].Label = label +} + +func (p *progressSimple) SetValue(i int, v float64) { + p.bars[i].Value = v +} + +func (p *progressSimple) stop() { + c := make(chan struct{}) + p.done <- c + <-c +} + +func newProgressSimple(bars []*ProgressBar, o *Output, opts *ProgressOpts) *progressSimple { + p := &progressSimple{ + Output: o, + bars: bars, + done: make(chan chan struct{}), + } + + if opts != nil && opts.NoSpinner { + if p.Output.verbose { + writeBars(p.Output, p.bars) + } + return p + } + + go func() { + ticker := time.NewTicker(1 * time.Second) + defer ticker.Stop() + + for { + select { + case <-ticker.C: + if p.Output.verbose { + writeBars(p.Output, p.bars) + } + + case c := <-p.done: + c <- struct{}{} + return + } + } + }() + + return p +} + +func writeBar(w Writer, bar *ProgressBar) { + w.Writef("%s: %d%%", bar.Label, int64(math.Round((100.0*bar.Value)/bar.Max))) +} + +func writeBars(o *Output, bars []*ProgressBar) { + if len(bars) > 1 { + block := o.Block(Line("", StyleReset, "Progress:")) + defer block.Close() + + for _, bar := range bars { + writeBar(block, bar) + } + } else if len(bars) == 1 { + writeBar(o, bars[0]) + } +} diff --git a/lib/output/progress_tty.go b/lib/output/progress_tty.go new file mode 100644 index 0000000000..f10dc18921 --- /dev/null +++ b/lib/output/progress_tty.go @@ -0,0 +1,295 @@ +package output + +import ( + "fmt" + "math" + "strings" + "time" + + "github.com/mattn/go-runewidth" +) + +var DefaultProgressTTYOpts = &ProgressOpts{ + SuccessEmoji: "\u2705", + SuccessStyle: StyleSuccess, + PendingStyle: StylePending, +} + +type progressTTY struct { + bars []*ProgressBar + + o *Output + opts ProgressOpts + + emojiWidth int + labelWidth int + pendingEmoji string + spinner *spinner +} + +func (p *progressTTY) Complete() { + p.spinner.stop() + + p.o.Lock() + defer p.o.Unlock() + + for _, bar := range p.bars { + bar.Value = bar.Max + } + p.drawInSitu() +} + +func (p *progressTTY) Close() { p.Destroy() } + +func (p *progressTTY) Destroy() { + p.spinner.stop() + + p.o.Lock() + defer p.o.Unlock() + + p.moveToOrigin() + for range len(p.bars) { + p.o.clearCurrentLine() + p.o.moveDown(1) + } + + p.moveToOrigin() +} + +func (p *progressTTY) SetLabel(i int, label string) { + p.o.Lock() + defer p.o.Unlock() + + p.bars[i].Label = label + p.bars[i].labelWidth = runewidth.StringWidth(label) + p.drawInSitu() +} + +func (p *progressTTY) SetLabelAndRecalc(i int, label string) { + p.o.Lock() + defer p.o.Unlock() + + p.bars[i].Label = label + p.bars[i].labelWidth = runewidth.StringWidth(label) + + p.labelWidth = calcLabelWidth(p.bars, p.emojiWidth, p.o.caps.Width) + p.drawInSitu() +} + +func (p *progressTTY) SetValue(i int, v float64) { + p.o.Lock() + defer p.o.Unlock() + + p.bars[i].Value = v + p.drawInSitu() +} + +func (p *progressTTY) Verbose(s string) { + if p.o.verbose { + p.Write(s) + } +} + +func (p *progressTTY) Verbosef(format string, args ...any) { + if p.o.verbose { + p.Writef(format, args...) + } +} + +func (p *progressTTY) VerboseLine(line FancyLine) { + if p.o.verbose { + p.WriteLine(line) + } +} + +func (p *progressTTY) Write(s string) { + p.o.Lock() + defer p.o.Unlock() + + p.moveToOrigin() + p.o.clearCurrentLine() + fmt.Fprintln(p.o.w, s) + p.draw() +} + +func (p *progressTTY) Writef(format string, args ...any) { + p.o.Lock() + defer p.o.Unlock() + + p.moveToOrigin() + p.o.clearCurrentLine() + fmt.Fprintf(p.o.w, format, p.o.caps.formatArgs(args)...) + fmt.Fprint(p.o.w, "\n") + p.draw() +} + +func (p *progressTTY) WriteLine(line FancyLine) { + p.o.Lock() + defer p.o.Unlock() + + p.moveToOrigin() + p.o.clearCurrentLine() + line.write(p.o.w, p.o.caps) + p.draw() +} + +func newProgressTTY(bars []*ProgressBar, o *Output, opts *ProgressOpts) *progressTTY { + p := &progressTTY{ + bars: bars, + o: o, + emojiWidth: 3, + pendingEmoji: spinnerStrings[0], + spinner: newSpinner(100 * time.Millisecond), + } + + if opts != nil { + p.opts = *opts + } else { + p.opts = *DefaultProgressTTYOpts + } + + if w := runewidth.StringWidth(p.opts.SuccessEmoji); w > p.emojiWidth { + p.emojiWidth = w + 1 + } + + p.labelWidth = calcLabelWidth(p.bars, p.emojiWidth, p.o.caps.Width) + + p.o.Lock() + defer p.o.Unlock() + + p.draw() + + if opts != nil && opts.NoSpinner { + return p + } + + go func() { + for s := range p.spinner.C { + func() { + p.pendingEmoji = s + + p.o.Lock() + defer p.o.Unlock() + + p.moveToOrigin() + p.draw() + }() + } + }() + + return p +} + +func (p *progressTTY) draw() { + for _, bar := range p.bars { + p.writeBar(bar) + } +} + +// We think this means "draw in position"? +func (p *progressTTY) drawInSitu() { + p.moveToOrigin() + p.draw() +} + +func (p *progressTTY) moveToOrigin() { + p.o.moveUp(len(p.bars)) +} + +// This is the core render function +func (p *progressTTY) writeBar(bar *ProgressBar) { + p.o.clearCurrentLine() + + value := bar.Value + if bar.Value >= bar.Max { + p.o.writeStyle(p.opts.SuccessStyle) + fmt.Fprint(p.o.w, runewidth.FillRight(p.opts.SuccessEmoji, p.emojiWidth)) + value = bar.Max + } else { + p.o.writeStyle(p.opts.PendingStyle) + fmt.Fprint(p.o.w, runewidth.FillRight(p.pendingEmoji, p.emojiWidth)) + } + + fmt.Fprint(p.o.w, runewidth.FillRight(runewidth.Truncate(bar.Label, p.labelWidth, "..."), p.labelWidth)) + + // Create a status label that represents percentage completion + statusLabel := fmt.Sprintf("%d", int(math.Floor(bar.Value/bar.Max*100))) + "%" + statusLabelWidth := len(statusLabel) + + // The bar width is the space remaining after we write the label and some emoji space... + remainingSpaceAfterLabel := floorZero(p.o.caps.Width - p.labelWidth - p.emojiWidth) + barWidth := floorZero(remainingSpaceAfterLabel - + // minus a overall status indicator... + statusLabelWidth - + // minus two spaces after the label, 2 spaces before the status label + 2 - 2) + + // Unicode box drawing gives us eight possible bar widths, so we need to + // calculate both the bar width and then the final character, if any. + var segments int + if bar.Max > 0 { + segments = int(math.Round((float64(8*barWidth) * value) / bar.Max)) + } + + fillWidth := segments / 8 + remainder := segments % 8 + if remainder == 0 { + if fillWidth > barWidth { + fillWidth = barWidth + } + } else { + if fillWidth+1 > barWidth { + fillWidth = floorZero(barWidth - 1) + } + } + + fmt.Fprintf(p.o.w, " ") + fmt.Fprint(p.o.w, strings.Repeat("█", fillWidth)) + + // The final bar character - if the remainder of the segment division is 0, we write + // no space. Otherwise we write a *single* character that represents that remainder. + fmt.Fprint(p.o.w, []string{ + "", // no remainder case + "▏", + "▎", + "▍", + "▌", + "▋", + "▊", + "▉", + }[remainder]) + + p.o.writeStyle(StyleReset) + + barSize := fillWidth + if remainder > 0 { + barSize += 1 // only a single character gets written if there is a remainder + } + consumedSpace := remainingSpaceAfterLabel - barSize - 2 // leave space for the label + fmt.Fprint(p.o.w, StyleBold, runewidth.FillLeft(statusLabel, consumedSpace), StyleReset) + + fmt.Fprintln(p.o.w) // end the line +} + +func floorZero(v int) int { + if v < 0 { + return 0 + } + return v +} + +func calcLabelWidth(bars []*ProgressBar, emojiWidth, termWidth int) int { + labelWidth := 0 + for _, bar := range bars { + bar.labelWidth = runewidth.StringWidth(bar.Label) + if bar.labelWidth > labelWidth { + labelWidth = bar.labelWidth + } + } + + if maxWidth := termWidth/2 - emojiWidth; (labelWidth + 2) > maxWidth { + labelWidth = maxWidth - 2 + } + + return labelWidth +} diff --git a/lib/output/progress_with_status_bars.go b/lib/output/progress_with_status_bars.go new file mode 100644 index 0000000000..aa8c6a5248 --- /dev/null +++ b/lib/output/progress_with_status_bars.go @@ -0,0 +1,23 @@ +package output + +type ProgressWithStatusBars interface { + Progress + + StatusBarUpdatef(i int, format string, args ...any) + StatusBarCompletef(i int, format string, args ...any) + StatusBarFailf(i int, format string, args ...any) + StatusBarResetf(i int, label, format string, args ...any) +} + +func newProgressWithStatusBars(bars []ProgressBar, statusBars []*StatusBar, o *Output, opts *ProgressOpts) ProgressWithStatusBars { + barPtrs := make([]*ProgressBar, len(bars)) + for i := range bars { + barPtrs[i] = &bars[i] + } + + if !o.caps.Isatty { + return newProgressWithStatusBarsSimple(barPtrs, statusBars, o, opts) + } + + return newProgressWithStatusBarsTTY(barPtrs, statusBars, o, opts) +} diff --git a/lib/output/progress_with_status_bars_simple.go b/lib/output/progress_with_status_bars_simple.go new file mode 100644 index 0000000000..e985c2e952 --- /dev/null +++ b/lib/output/progress_with_status_bars_simple.go @@ -0,0 +1,106 @@ +package output + +import ( + "time" +) + +type progressWithStatusBarsSimple struct { + *progressSimple + + statusBars []*StatusBar +} + +func (p *progressWithStatusBarsSimple) Complete() { + p.stop() + writeBars(p.Output, p.bars) + writeStatusBars(p.Output, p.statusBars) +} + +func (p *progressWithStatusBarsSimple) StatusBarUpdatef(i int, format string, args ...any) { + if p.statusBars[i] != nil { + p.statusBars[i].Updatef(format, args...) + } +} + +func (p *progressWithStatusBarsSimple) StatusBarCompletef(i int, format string, args ...any) { + if p.statusBars[i] != nil { + wasComplete := p.statusBars[i].completed + p.statusBars[i].Completef(format, args...) + if !wasComplete { + writeStatusBar(p.Output, p.statusBars[i]) + } + } +} + +func (p *progressWithStatusBarsSimple) StatusBarFailf(i int, format string, args ...any) { + if p.statusBars[i] != nil { + wasCompleted := p.statusBars[i].completed + p.statusBars[i].Failf(format, args...) + if !wasCompleted { + writeStatusBar(p.Output, p.statusBars[i]) + } + } +} + +func (p *progressWithStatusBarsSimple) StatusBarResetf(i int, label, format string, args ...any) { + if p.statusBars[i] != nil { + p.statusBars[i].Resetf(label, format, args...) + } +} + +func newProgressWithStatusBarsSimple(bars []*ProgressBar, statusBars []*StatusBar, o *Output, opts *ProgressOpts) *progressWithStatusBarsSimple { + p := &progressWithStatusBarsSimple{ + progressSimple: &progressSimple{ + Output: o, + bars: bars, + done: make(chan chan struct{}), + }, + statusBars: statusBars, + } + + if opts != nil && opts.NoSpinner { + if p.Output.verbose { + writeBars(p.Output, p.bars) + writeStatusBars(p.Output, p.statusBars) + } + return p + } + + go func() { + ticker := time.NewTicker(1 * time.Second) + defer ticker.Stop() + + for { + select { + case <-ticker.C: + if p.Output.verbose { + writeBars(p.Output, p.bars) + writeStatusBars(p.Output, p.statusBars) + } + + case c := <-p.done: + c <- struct{}{} + return + } + } + }() + + return p +} + +func writeStatusBar(w Writer, bar *StatusBar) { + w.Writef("%s: "+bar.format, append([]any{bar.label}, bar.args...)...) +} + +func writeStatusBars(o *Output, bars []*StatusBar) { + if len(bars) > 1 { + block := o.Block(Line("", StyleReset, "Status:")) + defer block.Close() + + for _, bar := range bars { + writeStatusBar(block, bar) + } + } else if len(bars) == 1 { + writeStatusBar(o, bars[0]) + } +} diff --git a/lib/output/progress_with_status_bars_tty.go b/lib/output/progress_with_status_bars_tty.go new file mode 100644 index 0000000000..3cfcf5834f --- /dev/null +++ b/lib/output/progress_with_status_bars_tty.go @@ -0,0 +1,309 @@ +package output + +import ( + "fmt" + "time" + + "github.com/mattn/go-runewidth" +) + +func newProgressWithStatusBarsTTY(bars []*ProgressBar, statusBars []*StatusBar, o *Output, opts *ProgressOpts) *progressWithStatusBarsTTY { + p := &progressWithStatusBarsTTY{ + progressTTY: &progressTTY{ + bars: bars, + o: o, + emojiWidth: 3, + pendingEmoji: spinnerStrings[0], + spinner: newSpinner(100 * time.Millisecond), + }, + statusBars: statusBars, + } + + if opts != nil { + p.opts = *opts + } else { + p.opts = *DefaultProgressTTYOpts + } + + if w := runewidth.StringWidth(p.opts.SuccessEmoji); w > p.emojiWidth { + p.emojiWidth = w + 1 + } + + p.labelWidth = calcLabelWidth(p.bars, p.emojiWidth, p.o.caps.Width) + p.statusBarLabelWidth = calcStatusBarLabelWidth(p.statusBars, p.o.caps.Width) + + p.o.Lock() + defer p.o.Unlock() + + p.draw() + + if opts != nil && opts.NoSpinner { + return p + } + + go func() { + for s := range p.spinner.C { + func() { + p.pendingEmoji = s + + p.o.Lock() + defer p.o.Unlock() + + p.moveToOrigin() + p.draw() + }() + } + }() + + return p +} + +type progressWithStatusBarsTTY struct { + *progressTTY + + statusBars []*StatusBar + statusBarLabelWidth int + numPrintedStatusBars int +} + +func (p *progressWithStatusBarsTTY) Close() { p.Destroy() } + +func (p *progressWithStatusBarsTTY) Destroy() { + p.spinner.stop() + + p.o.Lock() + defer p.o.Unlock() + + p.moveToOrigin() + + for range p.lines() { + p.o.clearCurrentLine() + p.o.moveDown(1) + } + + p.moveToOrigin() +} + +func (p *progressWithStatusBarsTTY) Complete() { + p.spinner.stop() + + p.o.Lock() + defer p.o.Unlock() + + // +1 because of the line between progress and status bars + for range p.numPrintedStatusBars + 1 { + p.o.moveUp(1) + p.o.clearCurrentLine() + } + + for _, bar := range p.bars { + bar.Value = bar.Max + } + + p.o.moveUp(len(p.bars)) + p.draw() +} + +func (p *progressWithStatusBarsTTY) lines() int { + return len(p.bars) + p.numPrintedStatusBars + 1 +} + +func (p *progressWithStatusBarsTTY) SetLabel(i int, label string) { + p.o.Lock() + defer p.o.Unlock() + + p.bars[i].Label = label + p.bars[i].labelWidth = runewidth.StringWidth(label) + p.drawInSitu() +} + +func (p *progressWithStatusBarsTTY) SetValue(i int, v float64) { + p.o.Lock() + defer p.o.Unlock() + + p.bars[i].Value = v + p.drawInSitu() +} + +func (p *progressWithStatusBarsTTY) StatusBarResetf(i int, label, format string, args ...any) { + p.o.Lock() + defer p.o.Unlock() + + if p.statusBars[i] != nil { + p.statusBars[i].Resetf(label, format, args...) + } + + p.statusBarLabelWidth = calcStatusBarLabelWidth(p.statusBars, p.o.caps.Width) + p.drawInSitu() +} + +func (p *progressWithStatusBarsTTY) StatusBarUpdatef(i int, format string, args ...any) { + p.o.Lock() + defer p.o.Unlock() + + if p.statusBars[i] != nil { + p.statusBars[i].Updatef(format, args...) + } + + p.drawInSitu() +} + +func (p *progressWithStatusBarsTTY) StatusBarCompletef(i int, format string, args ...any) { + p.o.Lock() + defer p.o.Unlock() + + if p.statusBars[i] != nil { + p.statusBars[i].Completef(format, args...) + } + + p.drawInSitu() +} + +func (p *progressWithStatusBarsTTY) StatusBarFailf(i int, format string, args ...any) { + p.o.Lock() + defer p.o.Unlock() + + if p.statusBars[i] != nil { + p.statusBars[i].Failf(format, args...) + } + + p.drawInSitu() +} + +func (p *progressWithStatusBarsTTY) draw() { + for _, bar := range p.bars { + p.writeBar(bar) + } + + if len(p.statusBars) > 0 { + p.o.clearCurrentLine() + fmt.Fprint(p.o.w, StylePending, "│", runewidth.FillLeft("\n", p.o.caps.Width-1)) + + } + + p.numPrintedStatusBars = 0 + for i, statusBar := range p.statusBars { + if statusBar == nil { + continue + } + if !statusBar.initialized { + continue + } + + last := i == len(p.statusBars)-1 + p.writeStatusBar(last, statusBar) + p.numPrintedStatusBars += 1 + } +} + +func (p *progressWithStatusBarsTTY) moveToOrigin() { + p.o.moveUp(p.lines()) +} + +func (p *progressWithStatusBarsTTY) drawInSitu() { + p.moveToOrigin() + p.draw() +} + +func calcStatusBarLabelWidth(statusBars []*StatusBar, termWidth int) int { + statusBarLabelWidth := 0 + for _, bar := range statusBars { + labelWidth := runewidth.StringWidth(bar.label) + if labelWidth > statusBarLabelWidth { + statusBarLabelWidth = labelWidth + } + } + + statusBarPrefixWidth := 4 // statusBars have box char and space + if maxWidth := termWidth/2 - statusBarPrefixWidth; (statusBarLabelWidth + 2) > maxWidth { + statusBarLabelWidth = maxWidth - 2 + } + + return statusBarLabelWidth + +} + +func (p *progressWithStatusBarsTTY) writeStatusBar(last bool, statusBar *StatusBar) { + style := StylePending + if statusBar.completed { + if statusBar.failed { + style = StyleWarning + } else { + style = StyleSuccess + } + } + + box := "├── " + if last { + box = "└── " + } + const boxWidth = 4 + + labelFillWidth := p.statusBarLabelWidth + 2 + label := runewidth.FillRight(runewidth.Truncate(statusBar.label, p.statusBarLabelWidth, "..."), labelFillWidth) + + duration := statusBar.runtime().String() + durationLength := runewidth.StringWidth(duration) + + textMaxLength := p.o.caps.Width - boxWidth - labelFillWidth - (durationLength + 2) + text := runewidth.Truncate(fmt.Sprintf(statusBar.format, p.o.caps.formatArgs(statusBar.args)...), textMaxLength, "...") + + // The text might contain invisible control characters, so we need to + // exclude them when counting length + textLength := visibleStringWidth(text) + + durationMaxWidth := textMaxLength - textLength + (durationLength + 2) + durationText := runewidth.FillLeft(duration, durationMaxWidth) + + p.o.clearCurrentLine() + fmt.Fprint(p.o.w, style, box, label, StyleReset, text, StyleBold, durationText, StyleReset, "\n") +} + +func (p *progressWithStatusBarsTTY) Verbose(s string) { + if p.o.verbose { + p.Write(s) + } +} + +func (p *progressWithStatusBarsTTY) Verbosef(format string, args ...any) { + if p.o.verbose { + p.Writef(format, args...) + } +} + +func (p *progressWithStatusBarsTTY) VerboseLine(line FancyLine) { + if p.o.verbose { + p.WriteLine(line) + } +} + +func (p *progressWithStatusBarsTTY) Write(s string) { + p.o.Lock() + defer p.o.Unlock() + + p.moveToOrigin() + p.o.clearCurrentLine() + fmt.Fprintln(p.o.w, s) + p.draw() +} + +func (p *progressWithStatusBarsTTY) Writef(format string, args ...any) { + p.o.Lock() + defer p.o.Unlock() + + p.moveToOrigin() + p.o.clearCurrentLine() + fmt.Fprintf(p.o.w, format, p.o.caps.formatArgs(args)...) + fmt.Fprint(p.o.w, "\n") + p.draw() +} + +func (p *progressWithStatusBarsTTY) WriteLine(line FancyLine) { + p.o.Lock() + defer p.o.Unlock() + + p.moveToOrigin() + p.o.clearCurrentLine() + line.write(p.o.w, p.o.caps) + p.draw() +} diff --git a/lib/output/spinner.go b/lib/output/spinner.go new file mode 100644 index 0000000000..b0b5b86de2 --- /dev/null +++ b/lib/output/spinner.go @@ -0,0 +1,47 @@ +package output + +import "time" + +type spinner struct { + C chan string + + done chan chan struct{} +} + +var spinnerStrings = []string{"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"} + +func newSpinner(interval time.Duration) *spinner { + c := make(chan string) + done := make(chan chan struct{}) + s := &spinner{ + C: c, + done: done, + } + + go func() { + ticker := time.NewTicker(interval) + defer ticker.Stop() + defer close(s.C) + + i := 0 + for { + select { + case <-ticker.C: + i = (i + 1) % len(spinnerStrings) + s.C <- spinnerStrings[i] + + case c := <-done: + c <- struct{}{} + return + } + } + }() + + return s +} + +func (s *spinner) stop() { + c := make(chan struct{}) + s.done <- c + <-c +} diff --git a/lib/output/status_bar.go b/lib/output/status_bar.go new file mode 100644 index 0000000000..e43868fc86 --- /dev/null +++ b/lib/output/status_bar.go @@ -0,0 +1,68 @@ +package output + +import "time" + +// StatusBar is a sub-element of a progress bar that displays the current status +// of a process. +type StatusBar struct { + completed bool + failed bool + + label string + format string + args []any + + initialized bool + startedAt time.Time + finishedAt time.Time +} + +// Completef sets the StatusBar to completed and updates its text. +func (sb *StatusBar) Completef(format string, args ...any) { + sb.completed = true + sb.format = format + sb.args = args + sb.finishedAt = time.Now() +} + +// Failf sets the StatusBar to completed and failed and updates its text. +func (sb *StatusBar) Failf(format string, args ...any) { + sb.Completef(format, args...) + sb.failed = true +} + +// Resetf sets the status of the StatusBar to incomplete and updates its label and text. +func (sb *StatusBar) Resetf(label, format string, args ...any) { + sb.initialized = true + sb.completed = false + sb.failed = false + sb.label = label + sb.format = format + sb.args = args + sb.startedAt = time.Now() + sb.finishedAt = time.Time{} +} + +// Updatef updates the StatusBar's text. +func (sb *StatusBar) Updatef(format string, args ...any) { + sb.initialized = true + sb.format = format + sb.args = args +} + +func (sb *StatusBar) runtime() time.Duration { + if sb.startedAt.IsZero() { + return 0 + } + if sb.finishedAt.IsZero() { + return time.Since(sb.startedAt).Truncate(time.Second) + } + + return sb.finishedAt.Sub(sb.startedAt).Truncate(time.Second) +} + +func NewStatusBarWithLabel(label string) *StatusBar { + return &StatusBar{label: label, startedAt: time.Now()} +} + +func NewStatusBar() *StatusBar { return &StatusBar{} } diff --git a/lib/output/style.go b/lib/output/style.go new file mode 100644 index 0000000000..f27a6d6530 --- /dev/null +++ b/lib/output/style.go @@ -0,0 +1,75 @@ +package output + +import ( + "fmt" + "strings" +) + +type Style struct{ code string } + +func (s Style) String() string { return s.code } + +// Line returns a FancyLine using this style as an alias for using output.Styledf(...) +func (s Style) Line(format string) FancyLine { return Styled(s, format) } + +// Linef returns a FancyLine using this style as an alias for using output.Styledf(...) +func (s Style) Linef(format string, args ...any) FancyLine { + return Styledf(s, format, args...) +} + +func CombineStyles(styles ...Style) Style { + sb := strings.Builder{} + for _, s := range styles { + fmt.Fprint(&sb, s) + } + return Style{sb.String()} +} + +func Fg256Color(code int) Style { return Style{fmt.Sprintf("\033[38;5;%dm", code)} } +func Bg256Color(code int) Style { return Style{fmt.Sprintf("\033[48;5;%dm", code)} } + +var ( + StyleReset = Style{"\033[0m"} + StyleLogo = Fg256Color(57) + StylePending = Fg256Color(4) + StyleWarning = Fg256Color(124) + StyleFailure = CombineStyles(StyleBold, Fg256Color(196)) + StyleSuccess = Fg256Color(2) + StyleSuggestion = Fg256Color(244) + + StyleBold = Style{"\033[1m"} + StyleItalic = Style{"\033[3m"} + StyleUnderline = Style{"\033[4m"} + + // Search-specific colors. + StyleSearchQuery = Fg256Color(68) + StyleSearchBorder = Fg256Color(239) + StyleSearchLink = Fg256Color(237) + StyleSearchRepository = Fg256Color(23) + StyleSearchFilename = Fg256Color(69) + StyleSearchMatch = CombineStyles(Fg256Color(0), Bg256Color(11)) + StyleSearchLineNumbers = Fg256Color(69) + StyleSearchCommitAuthor = Fg256Color(2) + StyleSearchCommitSubject = Fg256Color(68) + StyleSearchCommitDate = Fg256Color(23) + + StyleWhiteOnPurple = CombineStyles(Fg256Color(255), Bg256Color(55)) + StyleGreyBackground = CombineStyles(Fg256Color(0), Bg256Color(242)) + + // Search alert specific colors. + StyleSearchAlertTitle = Fg256Color(124) + StyleSearchAlertDescription = Fg256Color(124) + StyleSearchAlertProposedTitle = Style{""} + StyleSearchAlertProposedQuery = Fg256Color(69) + StyleSearchAlertProposedDescription = Style{""} + + StyleLinesDeleted = Fg256Color(196) + StyleLinesAdded = Fg256Color(2) + + // Colors + StyleGrey = Fg256Color(8) + StyleYellow = Fg256Color(220) + StyleOrange = Fg256Color(202) + StyleRed = Fg256Color(196) + StyleGreen = Fg256Color(2) +) diff --git a/lib/output/table.go b/lib/output/table.go new file mode 100644 index 0000000000..6736b30756 --- /dev/null +++ b/lib/output/table.go @@ -0,0 +1,52 @@ +package output + +import ( + "github.com/charmbracelet/lipgloss" + "github.com/charmbracelet/lipgloss/table" +) + +const ( + purple = lipgloss.Color("99") + gray = lipgloss.Color("245") + lightGray = lipgloss.Color("241") +) + +type Table struct { + tbl *table.Table + + headers []string +} + +func NewTable(headers []string) *Table { + t := table.New(). + Border(lipgloss.NormalBorder()). + BorderStyle(lipgloss.NewStyle().Foreground(purple)). + BorderRow(true). + BorderColumn(true). + StyleFunc(func(row, col int) lipgloss.Style { + s := lipgloss.NewStyle().Width(30) + + // this is the stle to use for the header row + if row == 0 { + return s.Foreground(purple).Bold(true).Align(lipgloss.Center) + } + return s + }). + Headers(headers...) + return &Table{ + tbl: t, + headers: headers, + } +} + +func (t *Table) AddRow(elems ...string) { + t.tbl.Row(elems...) +} + +func (t *Table) AddRows(elems ...[]string) { + t.tbl.Rows(elems...) +} + +func (t *Table) Render() string { + return t.tbl.Render() +} diff --git a/lib/output/visible_string_width.go b/lib/output/visible_string_width.go new file mode 100644 index 0000000000..08cb8c8e33 --- /dev/null +++ b/lib/output/visible_string_width.go @@ -0,0 +1,16 @@ +package output + +import ( + "github.com/grafana/regexp" + "github.com/mattn/go-runewidth" +) + +// This regex is taken from here: +// https://github.com/acarl005/stripansi/blob/5a71ef0e047df0427e87a79f27009029921f1f9b/stripansi.go +const ansi = "[\u001B\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[a-zA-Z\\d]*)*)?\u0007)|(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))" + +var ansiRegex = regexp.MustCompile(ansi) + +func visibleStringWidth(str string) int { + return runewidth.StringWidth(ansiRegex.ReplaceAllString(str, "")) +} diff --git a/lib/process/pipe.go b/lib/process/pipe.go new file mode 100644 index 0000000000..b7a6f9a40a --- /dev/null +++ b/lib/process/pipe.go @@ -0,0 +1,140 @@ +package process + +import ( + "bufio" + "bytes" + "context" + "fmt" + "io" + "io/fs" + + "github.com/sourcegraph/conc/pool" + + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +// initialBufSize is the initial size of the buffer that PipeOutput uses to +// read lines. +const initialBufSize = 4 * 1024 // 4k +// maxTokenSize is the max size of a token that PipeOutput reads. +const maxTokenSize = 100 * 1024 * 1024 // 100mb + +type pipe func(w io.Writer, r io.Reader) error + +type cmdPiper interface { + StdoutPipe() (io.ReadCloser, error) + StderrPipe() (io.ReadCloser, error) +} + +// NewOutputScannerWithSplit creates a new bufio.Scanner using the given split +// function with well-working defaults for the initial and max buf sizes. +func NewOutputScannerWithSplit(r io.Reader, split bufio.SplitFunc) *bufio.Scanner { + scanner := bufio.NewScanner(r) + scanner.Split(split) + buf := make([]byte, initialBufSize) + scanner.Buffer(buf, maxTokenSize) + return scanner +} + +// PipeOutput reads stdout/stderr output of the given command into the two +// io.Writers. +// +// It returns a errgroup.Group. The caller *must* call the Wait() method of the +// errgroup.Group **before** waiting for the *exec.Cmd to finish. +// +// The passed in context should be canceled when done. +// +// See this issue for more details: https://github.com/golang/go/issues/21922 +func PipeOutput(ctx context.Context, c cmdPiper, stdoutWriter, stderrWriter io.Writer) (*pool.ErrorPool, error) { + pipe := func(w io.Writer, r io.Reader) error { + scanner := NewOutputScannerWithSplit(r, scanLinesWithNewline) + + for scanner.Scan() { + if _, err := fmt.Fprint(w, scanner.Text()); err != nil { + return err + } + } + + return scanner.Err() + } + + return PipeProcessOutput(ctx, c, stdoutWriter, stderrWriter, pipe) +} + +// PipeOutputUnbuffered is the unbuffered version of PipeOutput and uses +// io.Copy instead of piping output line-based to the output. +func PipeOutputUnbuffered(ctx context.Context, c cmdPiper, stdoutWriter, stderrWriter io.Writer) (*pool.ErrorPool, error) { + pipe := func(w io.Writer, r io.Reader) error { + _, err := io.Copy(w, r) + // We can ignore ErrClosed because we get that if a process crashes + if err != nil && !errors.Is(err, fs.ErrClosed) { + return err + } + return nil + } + + return PipeProcessOutput(ctx, c, stdoutWriter, stderrWriter, pipe) +} + +func PipeProcessOutput(ctx context.Context, c cmdPiper, stdoutWriter, stderrWriter io.Writer, fn pipe) (*pool.ErrorPool, error) { + stdoutPipe, err := c.StdoutPipe() + if err != nil { + return nil, errors.Wrap(err, "failed to attach stdout pipe") + } + + stderrPipe, err := c.StderrPipe() + if err != nil { + return nil, errors.Wrap(err, "failed to attach stderr pipe") + } + + context.AfterFunc(ctx, func() { + // There is a deadlock condition due the following strange decisions: + // + // 1. The pipes attached to a command are not closed if the context + // attached to the command is canceled. The pipes are only closed + // after Wait has been called. + // 2. According to the docs, we are not meant to call cmd.Wait() until + // we have complete read the pipes attached to the command. + // + // Since we're following the expected usage, we block on a wait group + // tracking the consumption of stdout and stderr pipes in two separate + // goroutines between calls to Start and Wait. This means that if there + // is a reason the command is abandoned but the pipes are not closed + // (such as context cancellation), we will hang indefinitely. + // + // To be defensive, we'll forcibly close both pipes when the context has + // finished. These may return an ErrClosed condition, but we don't really + // care: the command package doesn't surface errors when closing the pipes + // either. + stdoutPipe.Close() + stderrPipe.Close() + }) + + eg := pool.New().WithErrors() + + eg.Go(func() error { return fn(stdoutWriter, stdoutPipe) }) + eg.Go(func() error { return fn(stderrWriter, stderrPipe) }) + + return eg, nil +} + +// scanLinesWithNewline is a modified version of bufio.ScanLines that retains +// the trailing newline byte(s) in the returned token. +func scanLinesWithNewline(data []byte, atEOF bool) (advance int, token []byte, err error) { + if atEOF && len(data) == 0 { + return 0, nil, nil + } + + if i := bytes.IndexByte(data, '\n'); i >= 0 { + // We have a full newline-terminated line. + return i + 1, data[0 : i+1], nil + } + + // If we're at EOF, we have a final, non-terminated line. Return it. + if atEOF { + return len(data), data, nil + } + + // Request more data. + return 0, nil, nil +} From 10d1e1ce0c7a5a2e149680f2d95d901870fcc60f Mon Sep 17 00:00:00 2001 From: Keegan Carruthers-Smith Date: Fri, 21 Nov 2025 13:46:56 +0200 Subject: [PATCH 501/647] chore(ci): use setup-go v6.1.0 (#1203) They have just tagged a version which includes the changes we need. So we can switch away from the dev hash we pinned to a tagged release. Test Plan: CI --- .github/workflows/go-ci.yml | 2 +- .github/workflows/go-lint.yml | 2 +- .github/workflows/goreleaser-check.yml | 2 +- .github/workflows/goreleaser.yml | 2 +- .github/workflows/scip.yml | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/go-ci.yml b/.github/workflows/go-ci.yml index bd79703fe1..fb98987d81 100644 --- a/.github/workflows/go-ci.yml +++ b/.github/workflows/go-ci.yml @@ -17,7 +17,7 @@ jobs: - name: Checkout uses: actions/checkout@v4 - name: Set up Go - uses: actions/setup-go@faf52423ec0d44c58f68e83b614bfcd99dded66f + uses: actions/setup-go@v6.1.0 with: go-version-file: '.tool-versions' - name: (Windows) Enable pulling Go modules from private sourcegraph/sourcegraph diff --git a/.github/workflows/go-lint.yml b/.github/workflows/go-lint.yml index 4fe3c4fca4..dcc6585884 100644 --- a/.github/workflows/go-lint.yml +++ b/.github/workflows/go-lint.yml @@ -14,7 +14,7 @@ jobs: - name: Checkout uses: actions/checkout@v4 - name: Set up Go - uses: actions/setup-go@faf52423ec0d44c58f68e83b614bfcd99dded66f + uses: actions/setup-go@v6.1.0 with: go-version-file: '.tool-versions' - name: Enable pulling Go modules from private sourcegraph/sourcegraph diff --git a/.github/workflows/goreleaser-check.yml b/.github/workflows/goreleaser-check.yml index 43209622cd..a3528f7848 100644 --- a/.github/workflows/goreleaser-check.yml +++ b/.github/workflows/goreleaser-check.yml @@ -17,7 +17,7 @@ jobs: with: fetch-depth: 0 - name: Set up Go - uses: actions/setup-go@faf52423ec0d44c58f68e83b614bfcd99dded66f + uses: actions/setup-go@v6.1.0 with: go-version-file: '.tool-versions' - name: Enable pulling Go modules from private sourcegraph/sourcegraph diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index 588d5e9d90..457180aae6 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -179,7 +179,7 @@ jobs: with: fetch-depth: 0 - name: Set up Go - uses: actions/setup-go@faf52423ec0d44c58f68e83b614bfcd99dded66f + uses: actions/setup-go@v6.1.0 with: go-version-file: '.tool-versions' - name: Enable pulling Go modules from private sourcegraph/sourcegraph diff --git a/.github/workflows/scip.yml b/.github/workflows/scip.yml index 2d380ae660..99982a511a 100644 --- a/.github/workflows/scip.yml +++ b/.github/workflows/scip.yml @@ -12,7 +12,7 @@ jobs: steps: - uses: actions/checkout@v4 - name: Set up Go - uses: actions/setup-go@faf52423ec0d44c58f68e83b614bfcd99dded66f + uses: actions/setup-go@v6.1.0 with: go-version-file: '.tool-versions' From ca03ac8ff8315af34a4bf40c280666ea11501e01 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Mon, 24 Nov 2025 15:21:13 +0000 Subject: [PATCH 502/647] add amp settings (#1204) --- .amp/settings.json | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 .amp/settings.json diff --git a/.amp/settings.json b/.amp/settings.json new file mode 100644 index 0000000000..05334a3fb7 --- /dev/null +++ b/.amp/settings.json @@ -0,0 +1,19 @@ +{ + "amp.experimental.fuzzySearch.enabled": true, + "amp.experimental.planMode": true, + "amp.experimental.tools": ["codemod"], + "amp.mcpServers": { + "s2": { + "command": "npx", + "args": [ + "mcp-remote", + "https://sourcegraph.sourcegraph.com/.api/mcp/v1", + "3334", + "--static-oauth-client-info", + "{\"client_id\":\"sgo_cid_019aa0a8-a62d-74e6-92bd-30fe0ff1d4d4\"}", + "--static-oauth-client-metadata", + "{\"scope\":\"user:all\"}" + ] + } + } +} From 88c7667cabb9dd434fd4a0121cb1383b355eb150 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Tue, 25 Nov 2025 10:21:52 +0000 Subject: [PATCH 503/647] add mise.toml (#1206) * add mise.toml * use mise action with cache true (#1207) --- .github/workflows/go-ci.yml | 6 +++--- .github/workflows/go-lint.yml | 6 +++--- .github/workflows/goreleaser-check.yml | 6 +++--- .github/workflows/goreleaser.yml | 6 +++--- .github/workflows/scip.yml | 6 +++--- mise.toml | 4 ++++ 6 files changed, 19 insertions(+), 15 deletions(-) create mode 100644 mise.toml diff --git a/.github/workflows/go-ci.yml b/.github/workflows/go-ci.yml index fb98987d81..a5e1ea8392 100644 --- a/.github/workflows/go-ci.yml +++ b/.github/workflows/go-ci.yml @@ -16,10 +16,10 @@ jobs: steps: - name: Checkout uses: actions/checkout@v4 - - name: Set up Go - uses: actions/setup-go@v6.1.0 + - name: Set up mise + uses: jdx/mise-action@v2 with: - go-version-file: '.tool-versions' + cache: true - name: (Windows) Enable pulling Go modules from private sourcegraph/sourcegraph if: runner.os == 'Windows' run: git config --global url."https://$env:PRIVATE_TOKEN@github.com/sourcegraph/".insteadOf "https://github.com/sourcegraph/" diff --git a/.github/workflows/go-lint.yml b/.github/workflows/go-lint.yml index dcc6585884..ca8296f524 100644 --- a/.github/workflows/go-lint.yml +++ b/.github/workflows/go-lint.yml @@ -13,10 +13,10 @@ jobs: steps: - name: Checkout uses: actions/checkout@v4 - - name: Set up Go - uses: actions/setup-go@v6.1.0 + - name: Set up mise + uses: jdx/mise-action@v2 with: - go-version-file: '.tool-versions' + cache: true - name: Enable pulling Go modules from private sourcegraph/sourcegraph run: git config --global url."https://${PRIVATE_TOKEN}@github.com/sourcegraph/".insteadOf "https://github.com/sourcegraph/" - run: ./dev/go-lint.sh diff --git a/.github/workflows/goreleaser-check.yml b/.github/workflows/goreleaser-check.yml index a3528f7848..5c89776044 100644 --- a/.github/workflows/goreleaser-check.yml +++ b/.github/workflows/goreleaser-check.yml @@ -16,10 +16,10 @@ jobs: uses: actions/checkout@v4 with: fetch-depth: 0 - - name: Set up Go - uses: actions/setup-go@v6.1.0 + - name: Set up mise + uses: jdx/mise-action@v2 with: - go-version-file: '.tool-versions' + cache: true - name: Enable pulling Go modules from private sourcegraph/sourcegraph run: git config --global url."https://${PRIVATE_TOKEN}@github.com/sourcegraph/".insteadOf "https://github.com/sourcegraph/" - name: Check GoReleaser config diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index 457180aae6..61bdce25ff 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -178,10 +178,10 @@ jobs: uses: actions/checkout@v4 with: fetch-depth: 0 - - name: Set up Go - uses: actions/setup-go@v6.1.0 + - name: Set up mise + uses: jdx/mise-action@v2 with: - go-version-file: '.tool-versions' + cache: true - name: Enable pulling Go modules from private sourcegraph/sourcegraph run: git config --global url."https://${PRIVATE_TOKEN}@github.com/sourcegraph/".insteadOf "https://github.com/sourcegraph/" - run: go test ./... diff --git a/.github/workflows/scip.yml b/.github/workflows/scip.yml index 99982a511a..29022fe7c5 100644 --- a/.github/workflows/scip.yml +++ b/.github/workflows/scip.yml @@ -11,10 +11,10 @@ jobs: container: sourcegraph/scip-go steps: - uses: actions/checkout@v4 - - name: Set up Go - uses: actions/setup-go@v6.1.0 + - name: Set up mise + uses: jdx/mise-action@v2 with: - go-version-file: '.tool-versions' + cache: true - name: Set directory to safe for git run: git config --global --add safe.directory $GITHUB_WORKSPACE diff --git a/mise.toml b/mise.toml new file mode 100644 index 0000000000..a1f15d3c03 --- /dev/null +++ b/mise.toml @@ -0,0 +1,4 @@ +[tools] +golang = "1.25.4" +shfmt = "3.8.0" +shellcheck = "0.10.0" From 7851df106870972e724bf111fba9c6a65e9e2a69 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Tue, 25 Nov 2025 10:55:58 +0000 Subject: [PATCH 504/647] switch back to using setup-go (#1209) --- .github/workflows/go-ci.yml | 10 +++++++--- .github/workflows/go-lint.yml | 9 ++++++--- .github/workflows/goreleaser-check.yml | 9 ++++++--- .github/workflows/goreleaser.yml | 9 ++++++--- .github/workflows/scip.yml | 9 ++++++--- 5 files changed, 31 insertions(+), 15 deletions(-) diff --git a/.github/workflows/go-ci.yml b/.github/workflows/go-ci.yml index a5e1ea8392..17e8ae6926 100644 --- a/.github/workflows/go-ci.yml +++ b/.github/workflows/go-ci.yml @@ -16,10 +16,14 @@ jobs: steps: - name: Checkout uses: actions/checkout@v4 - - name: Set up mise - uses: jdx/mise-action@v2 + - name: Get Go version from mise + id: mise + run: echo "go-version=$(grep 'golang' mise.toml | cut -d'"' -f2)" >> $GITHUB_OUTPUT + shell: bash + - name: Set up Go + uses: actions/setup-go@v6 with: - cache: true + go-version: ${{ steps.mise.outputs.go-version }} - name: (Windows) Enable pulling Go modules from private sourcegraph/sourcegraph if: runner.os == 'Windows' run: git config --global url."https://$env:PRIVATE_TOKEN@github.com/sourcegraph/".insteadOf "https://github.com/sourcegraph/" diff --git a/.github/workflows/go-lint.yml b/.github/workflows/go-lint.yml index ca8296f524..d4a8ee3847 100644 --- a/.github/workflows/go-lint.yml +++ b/.github/workflows/go-lint.yml @@ -13,10 +13,13 @@ jobs: steps: - name: Checkout uses: actions/checkout@v4 - - name: Set up mise - uses: jdx/mise-action@v2 + - name: Get Go version from mise + id: mise + run: echo "go-version=$(grep 'golang' mise.toml | cut -d'"' -f2)" >> $GITHUB_OUTPUT + - name: Set up Go + uses: actions/setup-go@v6 with: - cache: true + go-version: ${{ steps.mise.outputs.go-version }} - name: Enable pulling Go modules from private sourcegraph/sourcegraph run: git config --global url."https://${PRIVATE_TOKEN}@github.com/sourcegraph/".insteadOf "https://github.com/sourcegraph/" - run: ./dev/go-lint.sh diff --git a/.github/workflows/goreleaser-check.yml b/.github/workflows/goreleaser-check.yml index 5c89776044..547e6a554c 100644 --- a/.github/workflows/goreleaser-check.yml +++ b/.github/workflows/goreleaser-check.yml @@ -16,10 +16,13 @@ jobs: uses: actions/checkout@v4 with: fetch-depth: 0 - - name: Set up mise - uses: jdx/mise-action@v2 + - name: Get Go version from mise + id: mise + run: echo "go-version=$(grep 'golang' mise.toml | cut -d'"' -f2)" >> $GITHUB_OUTPUT + - name: Set up Go + uses: actions/setup-go@v6 with: - cache: true + go-version: ${{ steps.mise.outputs.go-version }} - name: Enable pulling Go modules from private sourcegraph/sourcegraph run: git config --global url."https://${PRIVATE_TOKEN}@github.com/sourcegraph/".insteadOf "https://github.com/sourcegraph/" - name: Check GoReleaser config diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index 61bdce25ff..8f305d36a7 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -178,10 +178,13 @@ jobs: uses: actions/checkout@v4 with: fetch-depth: 0 - - name: Set up mise - uses: jdx/mise-action@v2 + - name: Get Go version from mise + id: mise + run: echo "go-version=$(grep 'golang' mise.toml | cut -d'"' -f2)" >> $GITHUB_OUTPUT + - name: Set up Go + uses: actions/setup-go@v6 with: - cache: true + go-version: ${{ steps.mise.outputs.go-version }} - name: Enable pulling Go modules from private sourcegraph/sourcegraph run: git config --global url."https://${PRIVATE_TOKEN}@github.com/sourcegraph/".insteadOf "https://github.com/sourcegraph/" - run: go test ./... diff --git a/.github/workflows/scip.yml b/.github/workflows/scip.yml index 29022fe7c5..b546ea8bfa 100644 --- a/.github/workflows/scip.yml +++ b/.github/workflows/scip.yml @@ -11,10 +11,13 @@ jobs: container: sourcegraph/scip-go steps: - uses: actions/checkout@v4 - - name: Set up mise - uses: jdx/mise-action@v2 + - name: Get Go version from mise + id: mise + run: echo "go-version=$(grep 'golang' mise.toml | cut -d'"' -f2)" >> $GITHUB_OUTPUT + - name: Set up Go + uses: actions/setup-go@v6 with: - cache: true + go-version: ${{ steps.mise.outputs.go-version }} - name: Set directory to safe for git run: git config --global --add safe.directory $GITHUB_WORKSPACE From b3f6fd4c154eee0b14d2f8fa9d1a677837ec2520 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Tue, 25 Nov 2025 12:34:04 +0000 Subject: [PATCH 505/647] add tool subcommand that uses urfave/cli/v3 (#1205) * start using urfave-cli v3 - only used when SRC_INTERNAL_CLIFLAGS_V2 is 1 - add 'old' command, which runs the usual src cli commands until all commands are migrated * add tool subcommand that uses urfave-cli v3 * mark tool as experimental --- cmd/src/main.go | 10 ++++++++++ cmd/src/tool.go | 21 +++++++++++++++++++++ go.mod | 1 + go.sum | 2 ++ 4 files changed, 34 insertions(+) create mode 100644 cmd/src/tool.go diff --git a/cmd/src/main.go b/cmd/src/main.go index fa2e234138..b2826f4935 100644 --- a/cmd/src/main.go +++ b/cmd/src/main.go @@ -1,6 +1,7 @@ package main import ( + "context" "encoding/json" "flag" "io" @@ -63,6 +64,7 @@ The commands are: search search for results on Sourcegraph search-jobs manages search jobs serve-git serves your local git repositories over HTTP for Sourcegraph to pull + tool exposes tools for AI agents to interact with Sourcegraph (EXPERIMENTAL) users,user manages users codeowners manages code ownership information version display and compare the src-cli version against the recommended version for your instance @@ -90,6 +92,14 @@ func main() { log.SetFlags(0) log.SetPrefix("") + // "tool" does not use the legacy commander cli framework and uses urfave/cli v3 instead + if len(os.Args) >= 2 && os.Args[1] == "tool" { + if err := toolCmd.Run(context.Background(), os.Args[1:]); err != nil { + log.Fatal(err) + } + return + } + commands.run(flag.CommandLine, "src", usageText, normalizeDashHelp(os.Args[1:])) } diff --git a/cmd/src/tool.go b/cmd/src/tool.go new file mode 100644 index 0000000000..a0c64e1b0f --- /dev/null +++ b/cmd/src/tool.go @@ -0,0 +1,21 @@ +package main + +import ( + "context" + "fmt" + "os" + + "github.com/urfave/cli/v3" +) + +var toolCmd = &cli.Command{ + Name: "src tool", + Usage: "Exposes tools for AI agents to interact with Sourcegraph (EXPERIMENTAL)", + Description: "The tool subcommand exposes tools that can be used by AI agents to perform tasks against Sourcegraph instances.", + Commands: []*cli.Command{}, + Writer: os.Stdout, + Action: func(ctx context.Context, c *cli.Command) error { + fmt.Println("Not implemented") + return nil + }, +} diff --git a/go.mod b/go.mod index ea881257ac..63b72a5a05 100644 --- a/go.mod +++ b/go.mod @@ -29,6 +29,7 @@ require ( github.com/sourcegraph/scip v0.6.1 github.com/sourcegraph/sourcegraph/lib v0.0.0-20240709083501-1af563b61442 github.com/stretchr/testify v1.11.1 + github.com/urfave/cli/v3 v3.6.1 golang.org/x/net v0.44.0 golang.org/x/sync v0.17.0 google.golang.org/api v0.132.0 diff --git a/go.sum b/go.sum index 4a873f16a1..b03900bd3b 100644 --- a/go.sum +++ b/go.sum @@ -451,6 +451,8 @@ github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD github.com/tetratelabs/wazero v1.3.0 h1:nqw7zCldxE06B8zSZAY0ACrR9OH5QCcPwYmYlwtcwtE= github.com/tetratelabs/wazero v1.3.0/go.mod h1:wYx2gNRg8/WihJfSDxA1TIL8H+GkfLYm+bIfbblu9VQ= github.com/urfave/cli v1.22.12/go.mod h1:sSBEIC79qR6OvcmsD4U3KABeOTxDqQtdDnaFuUN30b8= +github.com/urfave/cli/v3 v3.6.1 h1:j8Qq8NyUawj/7rTYdBGrxcH7A/j7/G8Q5LhWEW4G3Mo= +github.com/urfave/cli/v3 v3.6.1/go.mod h1:ysVLtOEmg2tOy6PknnYVhDoouyC/6N42TMeoMzskhso= github.com/vbatts/tar-split v0.11.3 h1:hLFqsOLQ1SsppQNTMpkpPXClLDfC2A3Zgy9OUU+RVck= github.com/vbatts/tar-split v0.11.3/go.mod h1:9QlHN18E+fEH7RdG+QAJJcuya3rqT7eXSTY7wGrAokY= github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= From 7a36ee656fc81af52dbd5aa987092ee87b713c37 Mon Sep 17 00:00:00 2001 From: Vincent Date: Thu, 27 Nov 2025 15:41:36 +0000 Subject: [PATCH 506/647] check correct length (#1210) --- cmd/src/headers.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/src/headers.go b/cmd/src/headers.go index 98fd26369d..ced23834ee 100644 --- a/cmd/src/headers.go +++ b/cmd/src/headers.go @@ -38,7 +38,7 @@ func parseAdditionalHeadersFromEnviron(environ []string) map[string]string { for _, h := range splitHeaders { p := strings.SplitN(h, ":", 2) - if len(parts) != 2 || p[1] == "" { + if len(p) != 2 || p[1] == "" { continue } From 8f10917894f9a50e0fad201187ba5a8a5d39afd2 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Mon, 1 Dec 2025 09:00:27 +0000 Subject: [PATCH 507/647] chore: remove tool cmd --- cmd/src/main.go | 9 --------- cmd/src/tool.go | 21 --------------------- go.mod | 1 - go.sum | 2 -- 4 files changed, 33 deletions(-) delete mode 100644 cmd/src/tool.go diff --git a/cmd/src/main.go b/cmd/src/main.go index b2826f4935..58fd620b71 100644 --- a/cmd/src/main.go +++ b/cmd/src/main.go @@ -1,7 +1,6 @@ package main import ( - "context" "encoding/json" "flag" "io" @@ -92,14 +91,6 @@ func main() { log.SetFlags(0) log.SetPrefix("") - // "tool" does not use the legacy commander cli framework and uses urfave/cli v3 instead - if len(os.Args) >= 2 && os.Args[1] == "tool" { - if err := toolCmd.Run(context.Background(), os.Args[1:]); err != nil { - log.Fatal(err) - } - return - } - commands.run(flag.CommandLine, "src", usageText, normalizeDashHelp(os.Args[1:])) } diff --git a/cmd/src/tool.go b/cmd/src/tool.go deleted file mode 100644 index a0c64e1b0f..0000000000 --- a/cmd/src/tool.go +++ /dev/null @@ -1,21 +0,0 @@ -package main - -import ( - "context" - "fmt" - "os" - - "github.com/urfave/cli/v3" -) - -var toolCmd = &cli.Command{ - Name: "src tool", - Usage: "Exposes tools for AI agents to interact with Sourcegraph (EXPERIMENTAL)", - Description: "The tool subcommand exposes tools that can be used by AI agents to perform tasks against Sourcegraph instances.", - Commands: []*cli.Command{}, - Writer: os.Stdout, - Action: func(ctx context.Context, c *cli.Command) error { - fmt.Println("Not implemented") - return nil - }, -} diff --git a/go.mod b/go.mod index 63b72a5a05..ea881257ac 100644 --- a/go.mod +++ b/go.mod @@ -29,7 +29,6 @@ require ( github.com/sourcegraph/scip v0.6.1 github.com/sourcegraph/sourcegraph/lib v0.0.0-20240709083501-1af563b61442 github.com/stretchr/testify v1.11.1 - github.com/urfave/cli/v3 v3.6.1 golang.org/x/net v0.44.0 golang.org/x/sync v0.17.0 google.golang.org/api v0.132.0 diff --git a/go.sum b/go.sum index b03900bd3b..4a873f16a1 100644 --- a/go.sum +++ b/go.sum @@ -451,8 +451,6 @@ github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD github.com/tetratelabs/wazero v1.3.0 h1:nqw7zCldxE06B8zSZAY0ACrR9OH5QCcPwYmYlwtcwtE= github.com/tetratelabs/wazero v1.3.0/go.mod h1:wYx2gNRg8/WihJfSDxA1TIL8H+GkfLYm+bIfbblu9VQ= github.com/urfave/cli v1.22.12/go.mod h1:sSBEIC79qR6OvcmsD4U3KABeOTxDqQtdDnaFuUN30b8= -github.com/urfave/cli/v3 v3.6.1 h1:j8Qq8NyUawj/7rTYdBGrxcH7A/j7/G8Q5LhWEW4G3Mo= -github.com/urfave/cli/v3 v3.6.1/go.mod h1:ysVLtOEmg2tOy6PknnYVhDoouyC/6N42TMeoMzskhso= github.com/vbatts/tar-split v0.11.3 h1:hLFqsOLQ1SsppQNTMpkpPXClLDfC2A3Zgy9OUU+RVck= github.com/vbatts/tar-split v0.11.3/go.mod h1:9QlHN18E+fEH7RdG+QAJJcuya3rqT7eXSTY7wGrAokY= github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= From a97ffca9ea545f9f1b0edb0c327f82cfac445b9e Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Mon, 1 Dec 2025 09:18:33 +0000 Subject: [PATCH 508/647] fix: upgrade docker to v25.0.6 (CVE-2024-41110) (#1217) --- go.mod | 72 +++++++++----- go.sum | 275 ++++++++++++++++++++++------------------------------- lib/go.mod | 11 ++- lib/go.sum | 40 ++++++-- 4 files changed, 198 insertions(+), 200 deletions(-) diff --git a/go.mod b/go.mod index ea881257ac..818ed24368 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module github.com/sourcegraph/src-cli go 1.24.1 require ( - cloud.google.com/go/storage v1.30.1 + cloud.google.com/go/storage v1.50.0 github.com/aws/aws-sdk-go-v2/config v1.18.13 github.com/aws/aws-sdk-go-v2/service/ec2 v1.86.0 github.com/aws/aws-sdk-go-v2/service/eks v1.27.3 @@ -29,9 +29,9 @@ require ( github.com/sourcegraph/scip v0.6.1 github.com/sourcegraph/sourcegraph/lib v0.0.0-20240709083501-1af563b61442 github.com/stretchr/testify v1.11.1 - golang.org/x/net v0.44.0 - golang.org/x/sync v0.17.0 - google.golang.org/api v0.132.0 + golang.org/x/net v0.46.0 + golang.org/x/sync v0.18.0 + google.golang.org/api v0.256.0 google.golang.org/protobuf v1.36.10 gopkg.in/yaml.v3 v3.0.1 jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7 @@ -41,11 +41,20 @@ require ( ) require ( - github.com/Microsoft/go-winio v0.6.1 // indirect + cel.dev/expr v0.24.0 // indirect + cloud.google.com/go/auth v0.17.0 // indirect + cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect + cloud.google.com/go/monitoring v1.24.2 // indirect + github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.29.0 // indirect + github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.50.0 // indirect + github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.50.0 // indirect + github.com/Microsoft/go-winio v0.6.2 // indirect github.com/alecthomas/chroma/v2 v2.14.0 // indirect github.com/bufbuild/connect-go v1.9.0 // indirect github.com/bufbuild/connect-opentelemetry-go v0.4.0 // indirect github.com/bufbuild/protocompile v0.5.1 // indirect + github.com/cenkalti/backoff/v5 v5.0.3 // indirect + github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834 // indirect github.com/charmbracelet/x/ansi v0.8.0 // indirect @@ -53,22 +62,28 @@ require ( github.com/charmbracelet/x/exp/slice v0.0.0-20250327172914-2fdc97757edf // indirect github.com/charmbracelet/x/term v0.2.1 // indirect github.com/clipperhouse/uax29/v2 v2.2.0 // indirect + github.com/cncf/xds/go v0.0.0-20250501225837-2ac532fd4443 // indirect github.com/containerd/stargz-snapshotter/estargz v0.14.3 // indirect + github.com/distribution/reference v0.6.0 // indirect github.com/docker/cli v24.0.4+incompatible // indirect github.com/docker/distribution v2.8.2+incompatible // indirect - github.com/docker/docker v24.0.4+incompatible // indirect + github.com/docker/docker v25.0.6+incompatible // indirect github.com/docker/docker-credential-helpers v0.8.0 // indirect github.com/docker/go-connections v0.4.0 // indirect github.com/docker/go-units v0.5.0 // indirect + github.com/envoyproxy/go-control-plane/envoy v1.32.4 // indirect github.com/felixge/fgprof v0.9.3 // indirect + github.com/felixge/httpsnoop v1.0.4 // indirect github.com/fxamacker/cbor/v2 v2.7.0 // indirect github.com/go-chi/chi/v5 v5.0.10 // indirect + github.com/go-jose/go-jose/v4 v4.1.2 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/gofrs/uuid/v5 v5.0.0 // indirect github.com/google/gnostic-models v0.6.8 // indirect github.com/google/go-containerregistry v0.15.2 // indirect github.com/google/pprof v0.0.0-20241029153458-d1b30febd7db // indirect - github.com/google/s2a-go v0.1.4 // indirect + github.com/google/s2a-go v0.1.9 // indirect + github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2 // indirect github.com/jackc/chunkreader/v2 v2.0.1 // indirect github.com/jackc/pgconn v1.14.3 // indirect github.com/jackc/pgio v1.0.0 // indirect @@ -79,29 +94,38 @@ require ( github.com/morikuni/aec v1.0.0 // indirect github.com/opencontainers/go-digest v1.0.0 // indirect github.com/opencontainers/image-spec v1.1.0-rc4 // indirect + github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 // indirect github.com/rs/cors v1.9.0 // indirect github.com/sirupsen/logrus v1.9.3 // indirect github.com/sourcegraph/beaut v0.0.0-20240611013027-627e4c25335a // indirect + github.com/spiffe/go-spiffe/v2 v2.5.0 // indirect github.com/tetratelabs/wazero v1.3.0 // indirect github.com/vbatts/tar-split v0.11.3 // indirect github.com/x448/float16 v0.8.4 // indirect github.com/xlab/treeprint v1.2.0 // indirect github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect + github.com/zeebo/errs v1.4.0 // indirect go.opentelemetry.io/auto/sdk v1.1.0 // indirect + go.opentelemetry.io/contrib/detectors/gcp v1.36.0 // indirect + go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0 // indirect + go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0 // indirect go.opentelemetry.io/otel v1.38.0 // indirect + go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.38.0 // indirect go.opentelemetry.io/otel/metric v1.38.0 // indirect - go.opentelemetry.io/otel/sdk v1.16.0 // indirect + go.opentelemetry.io/otel/sdk v1.38.0 // indirect + go.opentelemetry.io/otel/sdk/metric v1.38.0 // indirect go.opentelemetry.io/otel/trace v1.38.0 // indirect + go.opentelemetry.io/proto/otlp v1.7.1 // indirect golang.org/x/telemetry v0.0.0-20250908211612-aef8a434d053 // indirect - google.golang.org/genproto/googleapis/api v0.0.0-20231016165738-49dd2c1f3d0b // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20231106174013-bbf56f31fb17 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20250825161204-c5933d9347a5 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20251103181224-f26f9409b101 // indirect gopkg.in/evanphx/json-patch.v4 v4.12.0 // indirect ) require ( - cloud.google.com/go v0.110.9 // indirect - cloud.google.com/go/compute/metadata v0.3.0 // indirect - cloud.google.com/go/iam v1.1.4 // indirect + cloud.google.com/go v0.120.0 // indirect + cloud.google.com/go/compute/metadata v0.9.0 // indirect + cloud.google.com/go/iam v1.5.2 // indirect github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c // indirect github.com/Masterminds/goutils v1.1.1 // indirect github.com/Masterminds/semver v1.5.0 // indirect @@ -128,7 +152,7 @@ require ( github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/dlclark/regexp2 v1.11.0 // indirect github.com/emicklei/go-restful/v3 v3.11.0 // indirect - github.com/envoyproxy/protoc-gen-validate v1.0.2 // indirect + github.com/envoyproxy/protoc-gen-validate v1.2.1 // indirect github.com/fatih/color v1.15.0 // indirect github.com/getsentry/sentry-go v0.27.0 // indirect github.com/ghodss/yaml v1.0.0 // indirect @@ -137,12 +161,11 @@ require ( github.com/go-openapi/jsonreference v0.20.2 // indirect github.com/go-openapi/swag v0.23.0 // indirect github.com/gogo/protobuf v1.3.2 // indirect - github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect github.com/golang/protobuf v1.5.4 // indirect github.com/google/gofuzz v1.2.0 // indirect github.com/google/uuid v1.6.0 // indirect - github.com/googleapis/enterprise-certificate-proxy v0.2.5 // indirect - github.com/googleapis/gax-go/v2 v2.12.0 // indirect + github.com/googleapis/enterprise-certificate-proxy v0.3.7 // indirect + github.com/googleapis/gax-go/v2 v2.15.0 // indirect github.com/gorilla/css v1.0.1 // indirect github.com/hexops/gotextdiff v1.0.3 // indirect github.com/hexops/valast v1.4.4 // indirect @@ -190,22 +213,19 @@ require ( github.com/xeipuuv/gojsonschema v1.2.0 // indirect github.com/yuin/goldmark v1.7.8 // indirect github.com/yuin/goldmark-emoji v1.0.5 // indirect - go.opencensus.io v0.24.0 // indirect go.uber.org/atomic v1.11.0 // indirect go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.24.0 // indirect - golang.org/x/crypto v0.42.0 // indirect + golang.org/x/crypto v0.43.0 // indirect golang.org/x/mod v0.28.0 // indirect - golang.org/x/oauth2 v0.28.0 // indirect + golang.org/x/oauth2 v0.33.0 // indirect golang.org/x/sys v0.38.0 // indirect golang.org/x/term v0.37.0 // indirect - golang.org/x/text v0.29.0 // indirect - golang.org/x/time v0.7.0 // indirect + golang.org/x/text v0.30.0 // indirect + golang.org/x/time v0.14.0 // indirect golang.org/x/tools v0.37.0 // indirect - golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 // indirect - google.golang.org/appengine v1.6.7 // indirect - google.golang.org/genproto v0.0.0-20231030173426-d783a09b4405 // indirect - google.golang.org/grpc v1.59.0 // indirect + google.golang.org/genproto v0.0.0-20250603155806-513f23925822 // indirect + google.golang.org/grpc v1.76.0 // indirect gopkg.in/inf.v0 v0.9.1 // indirect; direct gopkg.in/yaml.v2 v2.4.0 // indirect k8s.io/klog/v2 v2.130.1 // indirect diff --git a/go.sum b/go.sum index 4a873f16a1..8c25134d27 100644 --- a/go.sum +++ b/go.sum @@ -1,32 +1,50 @@ -cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -cloud.google.com/go v0.110.9 h1:e7ITSqGFFk4rbz/JFIqZh3G4VEHguhAL4BQcFlWtU68= -cloud.google.com/go v0.110.9/go.mod h1:rpxevX/0Lqvlbc88b7Sc1SPNdyK1riNBTUU6JXhYNpM= -cloud.google.com/go/compute/metadata v0.3.0 h1:Tz+eQXMEqDIKRsmY3cHTL6FVaynIjX2QxYC4trgAKZc= -cloud.google.com/go/compute/metadata v0.3.0/go.mod h1:zFmK7XCadkQkj6TtorcaGlCW1hT1fIilQDwofLpJ20k= -cloud.google.com/go/iam v1.1.4 h1:K6n/GZHFTtEoKT5aUG3l9diPi0VduZNQ1PfdnpkkIFk= -cloud.google.com/go/iam v1.1.4/go.mod h1:l/rg8l1AaA+VFMho/HYx2Vv6xinPSLMF8qfhRPIZ0L8= -cloud.google.com/go/storage v1.30.1 h1:uOdMxAs8HExqBlnLtnQyP0YkvbiDpdGShGKtx6U/oNM= -cloud.google.com/go/storage v1.30.1/go.mod h1:NfxhC0UJE1aXSx7CIIbCf7y9HKT7BiccwkR7+P7gN8E= +cel.dev/expr v0.24.0 h1:56OvJKSH3hDGL0ml5uSxZmz3/3Pq4tJ+fb1unVLAFcY= +cel.dev/expr v0.24.0/go.mod h1:hLPLo1W4QUmuYdA72RBX06QTs6MXw941piREPl3Yfiw= +cloud.google.com/go v0.120.0 h1:wc6bgG9DHyKqF5/vQvX1CiZrtHnxJjBlKUyF9nP6meA= +cloud.google.com/go v0.120.0/go.mod h1:/beW32s8/pGRuj4IILWQNd4uuebeT4dkOhKmkfit64Q= +cloud.google.com/go/auth v0.17.0 h1:74yCm7hCj2rUyyAocqnFzsAYXgJhrG26XCFimrc/Kz4= +cloud.google.com/go/auth v0.17.0/go.mod h1:6wv/t5/6rOPAX4fJiRjKkJCvswLwdet7G8+UGXt7nCQ= +cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIiLpZnkHRbnc= +cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c= +cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdBtwLoEkH9Zs= +cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10= +cloud.google.com/go/iam v1.5.2 h1:qgFRAGEmd8z6dJ/qyEchAuL9jpswyODjA2lS+w234g8= +cloud.google.com/go/iam v1.5.2/go.mod h1:SE1vg0N81zQqLzQEwxL2WI6yhetBdbNQuTvIKCSkUHE= +cloud.google.com/go/logging v1.13.0 h1:7j0HgAp0B94o1YRDqiqm26w4q1rDMH7XNRU34lJXHYc= +cloud.google.com/go/logging v1.13.0/go.mod h1:36CoKh6KA/M0PbhPKMq6/qety2DCAErbhXT62TuXALA= +cloud.google.com/go/longrunning v0.6.7 h1:IGtfDWHhQCgCjwQjV9iiLnUta9LBCo8R9QmAFsS/PrE= +cloud.google.com/go/longrunning v0.6.7/go.mod h1:EAFV3IZAKmM56TyiE6VAP3VoTzhZzySwI/YI1s/nRsY= +cloud.google.com/go/monitoring v1.24.2 h1:5OTsoJ1dXYIiMiuL+sYscLc9BumrL3CarVLL7dd7lHM= +cloud.google.com/go/monitoring v1.24.2/go.mod h1:x7yzPWcgDRnPEv3sI+jJGBkwl5qINf+6qY4eq0I9B4U= +cloud.google.com/go/storage v1.50.0 h1:3TbVkzTooBvnZsk7WaAQfOsNrdoM8QHusXA1cpk6QJs= +cloud.google.com/go/storage v1.50.0/go.mod h1:l7XeiD//vx5lfqE3RavfmU9yvk5Pp0Zhcv482poyafY= +cloud.google.com/go/trace v1.11.6 h1:2O2zjPzqPYAHrn3OKl029qlqG6W8ZdYaOWRyr8NgMT4= +cloud.google.com/go/trace v1.11.6/go.mod h1:GA855OeDEBiBMzcckLPE2kDunIpC72N+Pq8WFieFjnI= github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg= github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= -github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/toml v1.2.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.29.0 h1:UQUsRi8WTzhZntp5313l+CHIAT95ojUI2lpP/ExlZa4= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.29.0/go.mod h1:Cz6ft6Dkn3Et6l2v2a9/RpN7epQ1GtDlO6lj8bEcOvw= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.50.0 h1:5IT7xOdq17MtcdtL/vtl6mGfzhaq4m4vpollPRmlsBQ= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.50.0/go.mod h1:ZV4VOm0/eHR06JLrXWe09068dHpr3TRpY9Uo7T+anuA= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0.50.0 h1:nNMpRpnkWDAaqcpxMJvxa/Ud98gjbYwayJY4/9bdjiU= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0.50.0/go.mod h1:SZiPHWGOOk3bl8tkevxkoiwPgsIl6CwrWcbwjfHZpdM= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.50.0 h1:ig/FpDD2JofP/NExKQUbn7uOSZzJAQqogfqluZK4ed4= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.50.0/go.mod h1:otE2jQekW/PqXk1Awf5lmfokJx4uwuqcj1ab5SpGeW0= github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI= github.com/Masterminds/goutils v1.1.1/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU= github.com/Masterminds/semver v1.5.0 h1:H65muMkzWKEuNDnfl9d70GUjFniHKHRbFPGBuZ3QEww= github.com/Masterminds/semver v1.5.0/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y= github.com/Masterminds/sprig v2.22.0+incompatible h1:z4yfnGrZ7netVz+0EDJ0Wi+5VZCSYp4Z0m2dk6cEM60= github.com/Masterminds/sprig v2.22.0+incompatible/go.mod h1:y6hNFY5UBTIWBxnzTeuNhlNS5hqE0NB0E6fgfo2Br3o= -github.com/Microsoft/go-winio v0.6.1 h1:9/kr64B9VUZrLm5YYwbGtUJnMgqWVOdUAXu6Migciow= -github.com/Microsoft/go-winio v0.6.1/go.mod h1:LRdKpFKfdobln8UmuiYcKPot9D2v6svN5+sAH+4kjUM= +github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= +github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= github.com/alecthomas/assert/v2 v2.7.0 h1:QtqSACNS3tF7oasA8CU6A6sXZSBDqnm7RfpLl9bZqbE= github.com/alecthomas/assert/v2 v2.7.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k= github.com/alecthomas/chroma/v2 v2.14.0 h1:R3+wzpnUArGcQz7fCETQBzO5n9IMNi13iIs46aU4V9E= github.com/alecthomas/chroma/v2 v2.14.0/go.mod h1:QolEbTfmUHIMVpBqxeDnNBj2uoeI4EbYP4i6n68SG4I= github.com/alecthomas/repr v0.4.0 h1:GhI2A8MACjfegCPVq9f1FLvIBS+DrQ2KQBFZP1iFzXc= github.com/alecthomas/repr v0.4.0/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4= -github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= github.com/aws/aws-sdk-go-v2 v1.17.4/go.mod h1:uzbQtefpm44goOPmdKyAlXSNcwlRgF3ePWVW6EtJvvw= github.com/aws/aws-sdk-go-v2 v1.17.5 h1:TzCUW1Nq4H8Xscph5M/skINUitxM5UBAyvm2s7XBzL4= github.com/aws/aws-sdk-go-v2 v1.17.5/go.mod h1:uzbQtefpm44goOPmdKyAlXSNcwlRgF3ePWVW6EtJvvw= @@ -76,8 +94,10 @@ github.com/bufbuild/connect-opentelemetry-go v0.4.0 h1:6JAn10SNqlQ/URhvRNGrIlczK github.com/bufbuild/connect-opentelemetry-go v0.4.0/go.mod h1:nwPXYoDOoc2DGyKE/6pT1Q9MPSi2Et2e6BieMD0l6WU= github.com/bufbuild/protocompile v0.5.1 h1:mixz5lJX4Hiz4FpqFREJHIXLfaLBntfaJv1h+/jS+Qg= github.com/bufbuild/protocompile v0.5.1/go.mod h1:G5iLmavmF4NsYtpZFvE3B/zFch2GIY8+wjsYLR/lc40= -github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= -github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM= +github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc h1:4pZI35227imm7yK2bGPcfpFEmuY1gc2YSTShr4iJBfs= github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc/go.mod h1:X4/0JoqgTIPSFcRA/P6INZzIuyqdFY5rm8tb41s9okk= github.com/charmbracelet/glamour v0.10.0 h1:MtZvfwsYCx8jEPFJm3rIBFIMZUfUJ765oX8V6kXldcY= @@ -97,21 +117,18 @@ github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNE github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= -github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/clipperhouse/uax29/v2 v2.2.0 h1:ChwIKnQN3kcZteTXMgb1wztSgaU+ZemkgWdohwgs8tY= github.com/clipperhouse/uax29/v2 v2.2.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM= -github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= -github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= -github.com/cncf/udpa/go v0.0.0-20210930031921-04548b0d99d4/go.mod h1:6pvJx4me5XPnfI9Z40ddWsdw2W/uZgQLFXToKeRcDiI= -github.com/cncf/xds/go v0.0.0-20210805033703-aa0b78936158/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= -github.com/cncf/xds/go v0.0.0-20210922020428-25de7278fc84/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= -github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/xds/go v0.0.0-20250501225837-2ac532fd4443 h1:aQ3y1lwWyqYPiWZThqv1aFbZMiM9vblcSArJRf2Irls= +github.com/cncf/xds/go v0.0.0-20250501225837-2ac532fd4443/go.mod h1:W+zGtBO5Y1IgJhy4+A9GOqVhqLpfZi+vwmdNXUehLA8= github.com/cockroachdb/errors v1.12.0 h1:d7oCs6vuIMUQRVbi6jWWWEJZahLCfJpnJSVobd1/sUo= github.com/cockroachdb/errors v1.12.0/go.mod h1:SvzfYNNBshAVbZ8wzNc/UPK3w1vf0dKDUP41ucAIf7g= github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b h1:r6VH0faHjZeQy818SGhaone5OnYfxFR/+AzdY3sf5aE= github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= github.com/cockroachdb/redact v1.1.6 h1:zXJBwDZ84xJNlHl1rMyCojqyIxv+7YUpQiJLQ7n4314= github.com/cockroachdb/redact v1.1.6/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= +github.com/containerd/log v0.1.0 h1:TCJt7ioM2cr/tfR8GPbGf9/VRAX8D2B4PjzCpfX540I= +github.com/containerd/log v0.1.0/go.mod h1:VRRf09a7mHDIRezVKTRCrOq78v577GXq3bSa3EhrzVo= github.com/containerd/stargz-snapshotter/estargz v0.14.3 h1:OqlDCK3ZVUO6C3B/5FSkDwbkEETK84kQgEeFwDC+62k= github.com/containerd/stargz-snapshotter/estargz v0.14.3/go.mod h1:KY//uOCIkSuNAHhJogcZtrNHdKrA99/FCCRjE3HD36o= github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w= @@ -129,14 +146,16 @@ github.com/derision-test/glock v1.0.0 h1:b6sViZG+Cm6QtdpqbfWEjaBVbzNPntIS4GzsxpS github.com/derision-test/glock v1.0.0/go.mod h1:jKtLdBMrF+XQatqvg46wiWdDfDSSDjdhO4dOM2FX9H4= github.com/dineshappavoo/basex v0.0.0-20170425072625-481a6f6dc663 h1:fctNkSsavbXpt8geFWZb8n+noCqS8MrOXRJ/YfdZ2dQ= github.com/dineshappavoo/basex v0.0.0-20170425072625-481a6f6dc663/go.mod h1:Kad2hux31v/IyD4Rf4wAwIyK48995rs3qAl9IUAhc2k= +github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk= +github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E= github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI= github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= github.com/docker/cli v24.0.4+incompatible h1:Y3bYF9ekNTm2VFz5U/0BlMdJy73D+Y1iAAZ8l63Ydzw= github.com/docker/cli v24.0.4+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8= github.com/docker/distribution v2.8.2+incompatible h1:T3de5rq0dB1j30rp0sA2rER+m322EBzniBPB6ZIzuh8= github.com/docker/distribution v2.8.2+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= -github.com/docker/docker v24.0.4+incompatible h1:s/LVDftw9hjblvqIeTiGYXBCD95nOEEl7qRsRrIOuQI= -github.com/docker/docker v24.0.4+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= +github.com/docker/docker v25.0.6+incompatible h1:5cPwbwriIcsua2REJe8HqQV+6WlWc1byg2QSXzBxBGg= +github.com/docker/docker v25.0.6+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= github.com/docker/docker-credential-helpers v0.8.0 h1:YQFtbBQb4VrpoPxhFuzEBPQ9E16qz5SpHLS+uswaCp8= github.com/docker/docker-credential-helpers v0.8.0/go.mod h1:UGFXcuoQ5TxPiB54nHOZ32AWRqQdECoh/Mg0AlEYb40= github.com/docker/go-connections v0.4.0 h1:El9xVISelRB7BuFusrZozjnkIM5YnzCViNKohAFqRJQ= @@ -147,19 +166,21 @@ github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkp github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/emicklei/go-restful/v3 v3.11.0 h1:rAQeMHw1c7zTmncogyy8VvRZwtkmkZ4FxERmMY4rD+g= github.com/emicklei/go-restful/v3 v3.11.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= -github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= -github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= -github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= -github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= -github.com/envoyproxy/go-control-plane v0.9.10-0.20210907150352-cf90f659a021/go.mod h1:AFq3mo9L8Lqqiid3OhADV3RfLJnjiw63cSpi+fDTRC0= -github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= -github.com/envoyproxy/protoc-gen-validate v1.0.2 h1:QkIBuU5k+x7/QXPvPPnWXWlCdaBFApVqftFV6k087DA= -github.com/envoyproxy/protoc-gen-validate v1.0.2/go.mod h1:GpiZQP3dDbg4JouG/NNS7QWXpgx6x8QiMKdmN72jogE= +github.com/envoyproxy/go-control-plane v0.13.4 h1:zEqyPVyku6IvWCFwux4x9RxkLOMUL+1vC9xUFv5l2/M= +github.com/envoyproxy/go-control-plane v0.13.4/go.mod h1:kDfuBlDVsSj2MjrLEtRWtHlsWIFcGyB2RMO44Dc5GZA= +github.com/envoyproxy/go-control-plane/envoy v1.32.4 h1:jb83lalDRZSpPWW2Z7Mck/8kXZ5CQAFYVjQcdVIr83A= +github.com/envoyproxy/go-control-plane/envoy v1.32.4/go.mod h1:Gzjc5k8JcJswLjAx1Zm+wSYE20UrLtt7JZMWiWQXQEw= +github.com/envoyproxy/go-control-plane/ratelimit v0.1.0 h1:/G9QYbddjL25KvtKTv3an9lx6VBE2cnb8wp1vEGNYGI= +github.com/envoyproxy/go-control-plane/ratelimit v0.1.0/go.mod h1:Wk+tMFAFbCXaJPzVVHnPgRKdUdwW/KdbRt94AzgRee4= +github.com/envoyproxy/protoc-gen-validate v1.2.1 h1:DEo3O99U8j4hBFwbJfrz9VtgcDfUKS7KJ7spH3d86P8= +github.com/envoyproxy/protoc-gen-validate v1.2.1/go.mod h1:d/C80l/jxXLdfEIhX1W2TmLfsJ31lvEjwamM4DxlWXU= github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs= github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw= github.com/felixge/fgprof v0.9.3 h1:VvyZxILNuCiUCSXtPtYmmtGvb65nqXh2QFWc0Wpf2/g= github.com/felixge/fgprof v0.9.3/go.mod h1:RdbpDgzqYVh/T9fPELJyV7EYJuHB55UTEULNun8eiPw= +github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= +github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/frankban/quicktest v1.14.3/go.mod h1:mgiwOwqx65TmIk1wJ6Q7wvnVMocbUorkibMOrVTHZps= github.com/frankban/quicktest v1.14.4 h1:g2rn0vABPOOXmZUj+vbmUp0lPoXEMuhTpIluN0XL9UY= github.com/frankban/quicktest v1.14.4/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= @@ -171,6 +192,8 @@ github.com/go-chi/chi/v5 v5.0.10 h1:rLz5avzKpjqxrYwXNfmjkrYYXOyLJd37pz53UFHC6vk= github.com/go-chi/chi/v5 v5.0.10/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8= github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA= github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og= +github.com/go-jose/go-jose/v4 v4.1.2 h1:TK/7NqRQZfgAh+Td8AlsrvtPoUyiHh0LqVvokh+1vHI= +github.com/go-jose/go-jose/v4 v4.1.2/go.mod h1:22cg9HWM1pOlnRiY+9cQYJ9XHmya1bYW8OeDM6Ku6Oo= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= @@ -195,38 +218,13 @@ github.com/gofrs/uuid/v5 v5.0.0/go.mod h1:CDOjlDMVAtN56jqyRUZh58JT31Tiw7/oQyEXZV github.com/gogo/protobuf v1.3.0/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= -github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= -github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE= -github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= -github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= -github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= -github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= -github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= -github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= -github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= -github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= -github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= -github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= -github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= -github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/google/gnostic-models v0.6.8 h1:yo/ABAfM5IMRsS1VnXjTBvUb61tFIHozhlYvRgGre9I= github.com/google/gnostic-models v0.6.8/go.mod h1:5n7qKqH0f5wFt+aWF8CW6pZLLNOfYuF5OpfBSENuI8U= -github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= -github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE= github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= @@ -237,25 +235,25 @@ github.com/google/go-containerregistry v0.15.2/go.mod h1:wWK+LnOv4jXMM23IT/F1wdY github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/google/martian/v3 v3.3.2 h1:IqNFLAmvJOgVlpdEBiQbDc2EwKW77amAycfTuWKdfvw= -github.com/google/martian/v3 v3.3.2/go.mod h1:oBOf6HBosgwRXnUGWUB05QECsc6uvmMiJ3+6W4l/CUk= +github.com/google/martian/v3 v3.3.3 h1:DIhPTQrbPkgs2yJYdXU/eNACCG5DVQjySNRNlflZ9Fc= +github.com/google/martian/v3 v3.3.3/go.mod h1:iEPrYcgCF7jA9OtScMFQyAlZZ4YXTKEtJ1E6RWzmBA0= github.com/google/pprof v0.0.0-20211214055906-6f57359322fd/go.mod h1:KgnwoLYCZ8IQu3XUZ8Nc/bM9CCZFOyjUNOSygVozoDg= github.com/google/pprof v0.0.0-20241029153458-d1b30febd7db h1:097atOisP2aRj7vFgYQBbFN4U4JNXUNYpxael3UzMyo= github.com/google/pprof v0.0.0-20241029153458-d1b30febd7db/go.mod h1:vavhavw2zAxS5dIdcRluK6cSGGPlZynqzFM8NdvU144= -github.com/google/s2a-go v0.1.4 h1:1kZ/sQM3srePvKs3tXAvQzo66XfcReoqFpIpIccE7Oc= -github.com/google/s2a-go v0.1.4/go.mod h1:Ej+mSEMGRnqRzjc7VtF+jdBwYG5fuJfiZ8ELkjEwM0A= -github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0= +github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/googleapis/enterprise-certificate-proxy v0.2.5 h1:UR4rDjcgpgEnqpIEvkiqTYKBCKLNmlge2eVjoZfySzM= -github.com/googleapis/enterprise-certificate-proxy v0.2.5/go.mod h1:RxW0N9901Cko1VOCW3SXCpWP+mlIEkk2tP7jnHy9a3w= -github.com/googleapis/gax-go/v2 v2.12.0 h1:A+gCJKdRfqXkr+BIRGtZLibNXf0m1f9E4HG56etFpas= -github.com/googleapis/gax-go/v2 v2.12.0/go.mod h1:y+aIqrI5eb1YGMVJfuV3185Ts/D7qKpsEkdD5+I6QGU= +github.com/googleapis/enterprise-certificate-proxy v0.3.7 h1:zrn2Ee/nWmHulBx5sAVrGgAa0f2/R35S4DJwfFaUPFQ= +github.com/googleapis/enterprise-certificate-proxy v0.3.7/go.mod h1:MkHOF77EYAE7qfSuSS9PU6g4Nt4e11cnsDUowfwewLA= +github.com/googleapis/gax-go/v2 v2.15.0 h1:SyjDc1mGgZU5LncH8gimWo9lW1DtIfPibOG81vgd/bo= +github.com/googleapis/gax-go/v2 v2.15.0/go.mod h1:zVVkkxAQHa1RQpg9z2AUCMnKhi0Qld9rcmyfL1OZhoc= github.com/gorilla/css v1.0.1 h1:ntNaBIghp6JmvWnxbZKANoLyuXTPZ4cAMlo6RyhlbO8= github.com/gorilla/css v1.0.1/go.mod h1:BvnYkspnSzMmwRK+b8/xgNPLiIuNZr6vbZBTPQ2A3b0= github.com/grafana/regexp v0.0.0-20250905093917-f7b3be9d1853 h1:cLN4IBkmkYZNnk7EAJ0BHIethd+J6LqxFNw5mSiI2bM= github.com/grafana/regexp v0.0.0-20250905093917-f7b3be9d1853/go.mod h1:+JKpmjMGhpgPL+rXZ5nsZieVzvarn86asRlBg4uNGnk= -github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2 h1:8Tjv8EJ+pM1xP8mK6egEbD1OgnVTyacbefKhmbLhIhU= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2/go.mod h1:pkJQ2tZHJ0aFOVEEot6oZmaVEZcRme73eIFmhiVuRWs= github.com/hexops/autogold v0.8.1/go.mod h1:97HLDXyG23akzAoRYJh/2OBs3kd80eHyKPvZw0S5ZBY= github.com/hexops/autogold v1.3.1 h1:YgxF9OHWbEIUjhDbpnLhgVsjUDsiHDTyDfy2lrfdlzo= github.com/hexops/autogold v1.3.1/go.mod h1:sQO+mQUCVfxOKPht+ipDSkJ2SCJ7BNJVHZexsXqWMx4= @@ -387,10 +385,11 @@ github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/profile v1.7.0 h1:hnbDkaNWPCLMO9wGLdBFTIZvzDrDfBM2072E1S9gJkA= github.com/pkg/profile v1.7.0/go.mod h1:8Uer0jas47ZQMJ7VD+OHknK4YDY07LPUC6dEvqDjvNo= +github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 h1:GFCKgmp0tecUJ0sJuv4pzYCqS9+RGSn52M3FUwPs+uo= +github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10/go.mod h1:t/avpk3KcrXxUnYOhZhMXJlSEyie6gQbtLq5NM3loB8= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/pseudomuto/protoc-gen-doc v1.5.1 h1:Ah259kcrio7Ix1Rhb6u8FCaOkzf9qRBqXnvAufg061w= github.com/pseudomuto/protoc-gen-doc v1.5.1/go.mod h1:XpMKYg6zkcpgfpCfQ8GcWBDRtRxOmMR5w7pz4Xo+dYM= github.com/pseudomuto/protokit v0.2.0 h1:hlnBDcy3YEDXH7kc9gV+NLaN0cDzhDvD1s7Y6FZ8RpM= @@ -399,7 +398,6 @@ github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJ github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= -github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= @@ -431,6 +429,8 @@ github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I= github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spiffe/go-spiffe/v2 v2.5.0 h1:N2I01KCUkv1FAjZXJMwh95KK1ZIQLYbPfhaxw8WS0hE= +github.com/spiffe/go-spiffe/v2 v2.5.0/go.mod h1:P+NxobPc6wXhVtINNtFjNWGBTreew1GBUCwT2wPmb7g= github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf h1:pvbZ0lM0XWPBqUKqFU8cmavspvIl9nulOYwdy6IFRRo= github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf/go.mod h1:RJID2RhlZKId02nZ62WenDCkgHFerpIOmW0iT7GKmXM= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= @@ -440,7 +440,6 @@ github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= -github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= @@ -474,21 +473,34 @@ github.com/yuin/goldmark v1.7.8 h1:iERMLn0/QJeHFhxSt3p6PeN9mGnvIKSpG9YYorDMnic= github.com/yuin/goldmark v1.7.8/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E= github.com/yuin/goldmark-emoji v1.0.5 h1:EMVWyCGPlXJfUXBXpuMu+ii3TIaxbVBnEX9uaDC4cIk= github.com/yuin/goldmark-emoji v1.0.5/go.mod h1:tTkZEbwu5wkPmgTcitqddVxY9osFZiavD+r4AzQrh1U= -go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0= -go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo= +github.com/zeebo/errs v1.4.0 h1:XNdoD/RRMKP7HD0UhJnIzUy74ISdGGxURlYG8HSWSfM= +github.com/zeebo/errs v1.4.0/go.mod h1:sgbWHsvVuTPHcqJJGQ1WhI5KbWlHYz+2+2C/LSEtCw4= go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA= go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A= +go.opentelemetry.io/contrib/detectors/gcp v1.36.0 h1:F7q2tNlCaHY9nMKHR6XH9/qkp8FktLnIcy6jJNyOCQw= +go.opentelemetry.io/contrib/detectors/gcp v1.36.0/go.mod h1:IbBN8uAIIx734PTonTPxAxnjc2pQTxWNkwfstZ+6H2k= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0 h1:q4XOmH/0opmeuJtPsbFNivyl7bCt7yRBbeEm2sC/XtQ= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0/go.mod h1:snMWehoOh2wsEwnvvwtDyFCxVeDAODenXHtn5vzrKjo= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0 h1:RbKq8BG0FI8OiXhBfcRtqqHcZcka+gU3cskNuf05R18= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0/go.mod h1:h06DGIukJOevXaj/xrNjhi/2098RZzcLTbc0jDAUbsg= go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8= go.opentelemetry.io/otel v1.38.0/go.mod h1:zcmtmQ1+YmQM9wrNsTGV/q/uyusom3P8RxwExxkZhjM= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.38.0 h1:GqRJVj7UmLjCVyVJ3ZFLdPRmhDUp2zFmQe3RHIOsw24= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.38.0/go.mod h1:ri3aaHSmCTVYu2AWv44YMauwAQc0aqI9gHKIcSbI1pU= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.38.0 h1:aTL7F04bJHUlztTsNGJ2l+6he8c+y/b//eR0jjjemT4= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.38.0/go.mod h1:kldtb7jDTeol0l3ewcmd8SDvx3EmIE7lyvqbasU3QC4= +go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.29.0 h1:WDdP9acbMYjbKIyJUhTvtzj601sVJOqgWdUxSdR/Ysc= +go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.29.0/go.mod h1:BLbf7zbNIONBLPwvFnwNHGj4zge8uTCM/UPIVW1Mq2I= go.opentelemetry.io/otel/metric v1.38.0 h1:Kl6lzIYGAh5M159u9NgiRkmoMKjvbsKtYRwgfrA6WpA= go.opentelemetry.io/otel/metric v1.38.0/go.mod h1:kB5n/QoRM8YwmUahxvI3bO34eVtQf2i4utNVLr9gEmI= -go.opentelemetry.io/otel/sdk v1.16.0 h1:Z1Ok1YsijYL0CSJpHt4cS3wDDh7p572grzNrBMiMWgE= -go.opentelemetry.io/otel/sdk v1.16.0/go.mod h1:tMsIuKXuuIWPBAOrH+eHtvhTL+SntFtXF9QD68aP6p4= -go.opentelemetry.io/otel/sdk/metric v0.39.0 h1:Kun8i1eYf48kHH83RucG93ffz0zGV1sh46FAScOTuDI= -go.opentelemetry.io/otel/sdk/metric v0.39.0/go.mod h1:piDIRgjcK7u0HCL5pCA4e74qpK/jk3NiUoAHATVAmiI= +go.opentelemetry.io/otel/sdk v1.38.0 h1:l48sr5YbNf2hpCUj/FoGhW9yDkl+Ma+LrVl8qaM5b+E= +go.opentelemetry.io/otel/sdk v1.38.0/go.mod h1:ghmNdGlVemJI3+ZB5iDEuk4bWA3GkTpW+DOoZMYBVVg= +go.opentelemetry.io/otel/sdk/metric v1.38.0 h1:aSH66iL0aZqo//xXzQLYozmWrXxyFkBJ6qT5wthqPoM= +go.opentelemetry.io/otel/sdk/metric v1.38.0/go.mod h1:dg9PBnW9XdQ1Hd6ZnRz689CbtrUp0wMMs9iPcgT9EZA= go.opentelemetry.io/otel/trace v1.38.0 h1:Fxk5bKrDZJUH+AMyyIXGcFAPah0oRcT+LuNtJrmcNLE= go.opentelemetry.io/otel/trace v1.38.0/go.mod h1:j1P9ivuFsTceSWe1oY+EeW3sc+Pp42sO++GHkg4wwhs= -go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI= +go.opentelemetry.io/proto/otlp v1.7.1 h1:gTOMpGDb0WTBOP8JaO72iL3auEZhVmAQg4ipjOVAtj4= +go.opentelemetry.io/proto/otlp v1.7.1/go.mod h1:b2rVh6rfI/s2pHWNlB7ILJcRALpcNDzKhACevjI+ZnE= go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= @@ -501,63 +513,41 @@ golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACk golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.0.0-20220314234659-1baeb1ce4c0b/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= -golang.org/x/crypto v0.42.0 h1:chiH31gIWm57EkTXpwnqf8qeuMUi0yekh6mT2AvFlqI= -golang.org/x/crypto v0.42.0/go.mod h1:4+rDnOTJhQCx2q7/j6rAN5XDw8kPjeaXEUR2eL94ix8= -golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/crypto v0.43.0 h1:dduJYIi3A3KOfdGOHX8AVZ/jGiyPa3IbBozJ5kNuE04= +golang.org/x/crypto v0.43.0/go.mod h1:BFbav4mRNlXJL4wNeejLpWxB7wMbc79PdRGhWKncxR0= golang.org/x/exp v0.0.0-20231108232855-2478ac86f678 h1:mchzmB1XO2pMaKFRqk/+MV3mgGG96aqaPXaMifQU47w= golang.org/x/exp v0.0.0-20231108232855-2478ac86f678/go.mod h1:zk2irFbV9DP96SEBUUAy67IdHUaZuSnrz1n472HUCLE= -golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= -golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= -golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.7.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.28.0 h1:gQBtGhjxykdjY9YhZpSlZIsbnaE2+PgjfLWUQTnoZ1U= golang.org/x/mod v0.28.0/go.mod h1:yfB/L0NOf/kmEbXjzCPOx1iK1fRutOydrCMsqRhEBxI= -golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.3.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE= -golang.org/x/net v0.44.0 h1:evd8IRDyfNBMBTTY5XRF1vaZlD+EmWx6x8PkhR04H/I= -golang.org/x/net v0.44.0/go.mod h1:ECOoLqd5U3Lhyeyo/QDCEVQ4sNgYsqvCZ722XogGieY= -golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= -golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.28.0 h1:CrgCKl8PPAVtLnU3c+EDw6x11699EWlsDeWNWKdIOkc= -golang.org/x/oauth2 v0.28.0/go.mod h1:onh5ek6nERTohokkhCD/y2cV4Do3fxFHFuAejCkRWT8= -golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/net v0.46.0 h1:giFlY12I07fugqwPuWJi68oOnpfqFnJIJzaIIm2JVV4= +golang.org/x/net v0.46.0/go.mod h1:Q9BGdFy1y4nkUwiLvT5qtyhAnEHgnQ/zd8PfU6nc210= +golang.org/x/oauth2 v0.33.0 h1:4Q+qn+E5z8gPRJfmRy7C2gGG3T4jIprK6aSYgTXGRpo= +golang.org/x/oauth2 v0.33.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220819030929-7fc1605a5dde/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug= -golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= -golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sync v0.18.0 h1:kr88TuHDroi+UVf+0hZnirlk8o8T+4MrK6mr60WkH/I= +golang.org/x/sync v0.18.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210616045830-e2b7044e8c71/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -581,22 +571,15 @@ golang.org/x/term v0.3.0/go.mod h1:q750SLmJuPmVoN1blW3UFBPREJfb1KmY3vwxfr+nFDA= golang.org/x/term v0.37.0 h1:8EGAD0qCmHYZg6J17DvsMy9/wJ7/D/4pV/wfnld5lTU= golang.org/x/term v0.37.0/go.mod h1:5pB4lxRNYYVZuTLmy8oR2BH8dflOR+IbTYFD8fi3254= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk= -golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4= -golang.org/x/time v0.7.0 h1:ntUhktv3OPE6TgYxXWv9vKvUSJyIFJlyohwbkEwPrKQ= -golang.org/x/time v0.7.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= +golang.org/x/text v0.30.0 h1:yznKA/E9zq54KzlzBEAWn1NXSQ8DIp/NYMy88xJjl4k= +golang.org/x/text v0.30.0/go.mod h1:yDdHFIX9t+tORqspjENWgzaCVXgk0yYnYuSZ8UzzBVM= +golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI= +golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= -golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200624163319-25775e59acb7/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= @@ -609,45 +592,18 @@ golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8T golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 h1:H2TDz8ibqkAF6YGhCdN3jS9O0/s90v0rJh3X/OLHEUk= -golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2/go.mod h1:K8+ghG5WaK9qNqU5K3HdILfMLy1f3aNYFI/wnl100a8= -google.golang.org/api v0.132.0 h1:8t2/+qZ26kAOGSmOiHwVycqVaDg7q3JDILrNi/Z6rvc= -google.golang.org/api v0.132.0/go.mod h1:AeTBC6GpJnJSRJjktDcPX0QwtS8pGYZOV6MSuSCusw0= -google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= -google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= -google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c= -google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= -google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= -google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= -google.golang.org/genproto v0.0.0-20200513103714-09dca8ec2884/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= -google.golang.org/genproto v0.0.0-20231030173426-d783a09b4405 h1:I6WNifs6pF9tNdSob2W24JtyxIYjzFB9qDlpUC76q+U= -google.golang.org/genproto v0.0.0-20231030173426-d783a09b4405/go.mod h1:3WDQMjmJk36UQhjQ89emUzb1mdaHcPeeAh4SCBKznB4= -google.golang.org/genproto/googleapis/api v0.0.0-20231016165738-49dd2c1f3d0b h1:CIC2YMXmIhYw6evmhPxBKJ4fmLbOFtXQN/GV3XOZR8k= -google.golang.org/genproto/googleapis/api v0.0.0-20231016165738-49dd2c1f3d0b/go.mod h1:IBQ646DjkDkvUIsVq/cc03FUFQ9wbZu7yE396YcL870= -google.golang.org/genproto/googleapis/rpc v0.0.0-20231106174013-bbf56f31fb17 h1:Jyp0Hsi0bmHXG6k9eATXoYtjd6e2UzZ1SCn/wIupY14= -google.golang.org/genproto/googleapis/rpc v0.0.0-20231106174013-bbf56f31fb17/go.mod h1:oQ5rr10WTTMvP4A36n8JpR1OrO1BEiV4f78CneXZxkA= -google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= -google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= -google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= -google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= -google.golang.org/grpc v1.33.1/go.mod h1:fr5YgcSWrqhRRxogOsw7RzIpsmvOZ6IcH4kBYTpR3n0= -google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= -google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= -google.golang.org/grpc v1.45.0/go.mod h1:lN7owxKUQEqMfSyQikvvk5tf/6zMPsrK+ONuO11+0rQ= -google.golang.org/grpc v1.59.0 h1:Z5Iec2pjwb+LEOqzpB2MR12/eKFhDPhuqW91O+4bwUk= -google.golang.org/grpc v1.59.0/go.mod h1:aUPDwccQo6OTjy7Hct4AfBPD1GptF4fyUjIkQ9YtF98= -google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= -google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= -google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= -google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= -google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= -google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= -google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= -google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk= +gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E= +google.golang.org/api v0.256.0 h1:u6Khm8+F9sxbCTYNoBHg6/Hwv0N/i+V94MvkOSor6oI= +google.golang.org/api v0.256.0/go.mod h1:KIgPhksXADEKJlnEoRa9qAII4rXcy40vfI8HRqcU964= +google.golang.org/genproto v0.0.0-20250603155806-513f23925822 h1:rHWScKit0gvAPuOnu87KpaYtjK5zBMLcULh7gxkCXu4= +google.golang.org/genproto v0.0.0-20250603155806-513f23925822/go.mod h1:HubltRL7rMh0LfnQPkMH4NPDFEWp0jw3vixw7jEM53s= +google.golang.org/genproto/googleapis/api v0.0.0-20250825161204-c5933d9347a5 h1:BIRfGDEjiHRrk0QKZe3Xv2ieMhtgRGeLcZQ0mIVn4EY= +google.golang.org/genproto/googleapis/api v0.0.0-20250825161204-c5933d9347a5/go.mod h1:j3QtIyytwqGr1JUDtYXwtMXWPKsEa5LtzIFN1Wn5WvE= +google.golang.org/genproto/googleapis/rpc v0.0.0-20251103181224-f26f9409b101 h1:tRPGkdGHuewF4UisLzzHHr1spKw92qLM98nIzxbC0wY= +google.golang.org/genproto/googleapis/rpc v0.0.0-20251103181224-f26f9409b101/go.mod h1:7i2o+ce6H/6BluujYR+kqX3GKH+dChPTQU19wjRPiGk= +google.golang.org/grpc v1.76.0 h1:UnVkv1+uMLYXoIz6o7chp59WfQUYA2ex/BXQ9rHZu7A= +google.golang.org/grpc v1.76.0/go.mod h1:Ju12QI8M6iQJtbcsV+awF5a4hfJMLi4X0JLo94ULZ6c= google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= @@ -661,7 +617,6 @@ gopkg.in/evanphx/json-patch.v4 v4.12.0/go.mod h1:p8EYWUEYMpynmqDbY58zCKCFZw8pRWM gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc= gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= @@ -670,8 +625,6 @@ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gotest.tools/v3 v3.0.3 h1:4AuOwCGf4lLR9u3YOe2awrHygurzhO/HeQ6laiA6Sx0= gotest.tools/v3 v3.0.3/go.mod h1:Z7Lb0S5l+klDB31fvDQX8ss/FlKDxtlFlw3Oa8Ymbl8= -honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7 h1:mub0MmFLOn8XLikZOAhgLD1kXJq8jgftSrrv7m00xFo= jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7/go.mod h1:OxvTsCwKosqQ1q7B+8FwXqg4rKZ/UG9dUW+g/VL2xH4= k8s.io/api v0.32.3 h1:Hw7KqxRusq+6QSplE3NYG4MBxZw1BZnq4aP4cJVINls= diff --git a/lib/go.mod b/lib/go.mod index f84eb9e62d..2aa9407f3a 100644 --- a/lib/go.mod +++ b/lib/go.mod @@ -50,18 +50,21 @@ require ( github.com/charmbracelet/x/term v0.2.1 // indirect github.com/clipperhouse/uax29/v2 v2.2.0 // indirect github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect + github.com/containerd/log v0.1.0 // indirect github.com/containerd/stargz-snapshotter/estargz v0.14.3 // indirect github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect + github.com/distribution/reference v0.6.0 // indirect github.com/dlclark/regexp2 v1.11.0 // indirect github.com/docker/cli v24.0.4+incompatible // indirect github.com/docker/distribution v2.8.2+incompatible // indirect - github.com/docker/docker v24.0.4+incompatible // indirect + github.com/docker/docker v25.0.6+incompatible // indirect github.com/docker/docker-credential-helpers v0.8.0 // indirect github.com/docker/go-connections v0.4.0 // indirect github.com/docker/go-units v0.5.0 // indirect github.com/envoyproxy/protoc-gen-validate v0.3.0-java // indirect github.com/fatih/color v1.15.0 // indirect github.com/felixge/fgprof v0.9.3 // indirect + github.com/felixge/httpsnoop v1.0.4 // indirect github.com/getsentry/sentry-go v0.27.0 // indirect github.com/go-chi/chi/v5 v5.0.10 // indirect github.com/go-logr/logr v1.4.3 // indirect @@ -71,7 +74,7 @@ require ( github.com/golang/protobuf v1.5.3 // indirect github.com/google/go-containerregistry v0.15.2 // indirect github.com/google/pprof v0.0.0-20230705174524-200ffdc848b8 // indirect - github.com/google/uuid v1.3.0 // indirect + github.com/google/uuid v1.6.0 // indirect github.com/gorilla/css v1.0.1 // indirect github.com/huandu/xstrings v1.0.0 // indirect github.com/imdario/mergo v0.3.4 // indirect @@ -115,8 +118,10 @@ require ( github.com/yuin/goldmark v1.7.8 // indirect github.com/yuin/goldmark-emoji v1.0.5 // indirect go.opentelemetry.io/auto/sdk v1.1.0 // indirect + go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0 // indirect + go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.38.0 // indirect go.opentelemetry.io/otel/metric v1.38.0 // indirect - go.opentelemetry.io/otel/sdk v1.16.0 // indirect + go.opentelemetry.io/otel/sdk v1.38.0 // indirect go.opentelemetry.io/otel/trace v1.38.0 // indirect go.uber.org/atomic v1.11.0 // indirect go.uber.org/multierr v1.11.0 // indirect diff --git a/lib/go.sum b/lib/go.sum index 53f39986cd..1347666156 100644 --- a/lib/go.sum +++ b/lib/go.sum @@ -31,6 +31,8 @@ github.com/bufbuild/connect-opentelemetry-go v0.4.0 h1:6JAn10SNqlQ/URhvRNGrIlczK github.com/bufbuild/connect-opentelemetry-go v0.4.0/go.mod h1:nwPXYoDOoc2DGyKE/6pT1Q9MPSi2Et2e6BieMD0l6WU= github.com/bufbuild/protocompile v0.5.1 h1:mixz5lJX4Hiz4FpqFREJHIXLfaLBntfaJv1h+/jS+Qg= github.com/bufbuild/protocompile v0.5.1/go.mod h1:G5iLmavmF4NsYtpZFvE3B/zFch2GIY8+wjsYLR/lc40= +github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM= +github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw= github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc h1:4pZI35227imm7yK2bGPcfpFEmuY1gc2YSTShr4iJBfs= github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc/go.mod h1:X4/0JoqgTIPSFcRA/P6INZzIuyqdFY5rm8tb41s9okk= github.com/charmbracelet/glamour v0.10.0 h1:MtZvfwsYCx8jEPFJm3rIBFIMZUfUJ765oX8V6kXldcY= @@ -58,6 +60,8 @@ github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b h1:r6VH0faHjZe github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= github.com/cockroachdb/redact v1.1.6 h1:zXJBwDZ84xJNlHl1rMyCojqyIxv+7YUpQiJLQ7n4314= github.com/cockroachdb/redact v1.1.6/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= +github.com/containerd/log v0.1.0 h1:TCJt7ioM2cr/tfR8GPbGf9/VRAX8D2B4PjzCpfX540I= +github.com/containerd/log v0.1.0/go.mod h1:VRRf09a7mHDIRezVKTRCrOq78v577GXq3bSa3EhrzVo= github.com/containerd/stargz-snapshotter/estargz v0.14.3 h1:OqlDCK3ZVUO6C3B/5FSkDwbkEETK84kQgEeFwDC+62k= github.com/containerd/stargz-snapshotter/estargz v0.14.3/go.mod h1:KY//uOCIkSuNAHhJogcZtrNHdKrA99/FCCRjE3HD36o= github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w= @@ -68,14 +72,16 @@ github.com/creack/pty v1.1.18/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk= +github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E= github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI= github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= github.com/docker/cli v24.0.4+incompatible h1:Y3bYF9ekNTm2VFz5U/0BlMdJy73D+Y1iAAZ8l63Ydzw= github.com/docker/cli v24.0.4+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8= github.com/docker/distribution v2.8.2+incompatible h1:T3de5rq0dB1j30rp0sA2rER+m322EBzniBPB6ZIzuh8= github.com/docker/distribution v2.8.2+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= -github.com/docker/docker v24.0.4+incompatible h1:s/LVDftw9hjblvqIeTiGYXBCD95nOEEl7qRsRrIOuQI= -github.com/docker/docker v24.0.4+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= +github.com/docker/docker v25.0.6+incompatible h1:5cPwbwriIcsua2REJe8HqQV+6WlWc1byg2QSXzBxBGg= +github.com/docker/docker v25.0.6+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= github.com/docker/docker-credential-helpers v0.8.0 h1:YQFtbBQb4VrpoPxhFuzEBPQ9E16qz5SpHLS+uswaCp8= github.com/docker/docker-credential-helpers v0.8.0/go.mod h1:UGFXcuoQ5TxPiB54nHOZ32AWRqQdECoh/Mg0AlEYb40= github.com/docker/go-connections v0.4.0 h1:El9xVISelRB7BuFusrZozjnkIM5YnzCViNKohAFqRJQ= @@ -88,6 +94,8 @@ github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs= github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw= github.com/felixge/fgprof v0.9.3 h1:VvyZxILNuCiUCSXtPtYmmtGvb65nqXh2QFWc0Wpf2/g= github.com/felixge/fgprof v0.9.3/go.mod h1:RdbpDgzqYVh/T9fPELJyV7EYJuHB55UTEULNun8eiPw= +github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= +github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/getsentry/sentry-go v0.27.0 h1:Pv98CIbtB3LkMWmXi4Joa5OOcwbmnX88sF5qbK3r3Ps= github.com/getsentry/sentry-go v0.27.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk= @@ -123,12 +131,14 @@ github.com/google/gofuzz v1.1.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/ github.com/google/pprof v0.0.0-20211214055906-6f57359322fd/go.mod h1:KgnwoLYCZ8IQu3XUZ8Nc/bM9CCZFOyjUNOSygVozoDg= github.com/google/pprof v0.0.0-20230705174524-200ffdc848b8 h1:n6vlPhxsA+BW/XsS5+uqi7GyzaLa5MH7qlSLBZtRdiA= github.com/google/pprof v0.0.0-20230705174524-200ffdc848b8/go.mod h1:Jh3hGz2jkYak8qXPD19ryItVnUgpgeqzdkY/D0EaeuA= -github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= -github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/gorilla/css v1.0.1 h1:ntNaBIghp6JmvWnxbZKANoLyuXTPZ4cAMlo6RyhlbO8= github.com/gorilla/css v1.0.1/go.mod h1:BvnYkspnSzMmwRK+b8/xgNPLiIuNZr6vbZBTPQ2A3b0= github.com/grafana/regexp v0.0.0-20250905093917-f7b3be9d1853 h1:cLN4IBkmkYZNnk7EAJ0BHIethd+J6LqxFNw5mSiI2bM= github.com/grafana/regexp v0.0.0-20250905093917-f7b3be9d1853/go.mod h1:+JKpmjMGhpgPL+rXZ5nsZieVzvarn86asRlBg4uNGnk= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2 h1:8Tjv8EJ+pM1xP8mK6egEbD1OgnVTyacbefKhmbLhIhU= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2/go.mod h1:pkJQ2tZHJ0aFOVEEot6oZmaVEZcRme73eIFmhiVuRWs= github.com/hexops/autogold v1.3.1 h1:YgxF9OHWbEIUjhDbpnLhgVsjUDsiHDTyDfy2lrfdlzo= github.com/hexops/autogold/v2 v2.2.1 h1:JPUXuZQGkcQMv7eeDXuNMovjfoRYaa0yVcm+F3voaGY= github.com/hexops/autogold/v2 v2.2.1/go.mod h1:IJwxtUfj1BGLm0YsR/k+dIxYi6xbeLjqGke2bzcOTMI= @@ -285,20 +295,28 @@ github.com/yuin/goldmark-emoji v1.0.5 h1:EMVWyCGPlXJfUXBXpuMu+ii3TIaxbVBnEX9uaDC github.com/yuin/goldmark-emoji v1.0.5/go.mod h1:tTkZEbwu5wkPmgTcitqddVxY9osFZiavD+r4AzQrh1U= go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA= go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0 h1:RbKq8BG0FI8OiXhBfcRtqqHcZcka+gU3cskNuf05R18= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0/go.mod h1:h06DGIukJOevXaj/xrNjhi/2098RZzcLTbc0jDAUbsg= go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8= go.opentelemetry.io/otel v1.38.0/go.mod h1:zcmtmQ1+YmQM9wrNsTGV/q/uyusom3P8RxwExxkZhjM= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.38.0 h1:GqRJVj7UmLjCVyVJ3ZFLdPRmhDUp2zFmQe3RHIOsw24= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.38.0/go.mod h1:ri3aaHSmCTVYu2AWv44YMauwAQc0aqI9gHKIcSbI1pU= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.38.0 h1:aTL7F04bJHUlztTsNGJ2l+6he8c+y/b//eR0jjjemT4= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.38.0/go.mod h1:kldtb7jDTeol0l3ewcmd8SDvx3EmIE7lyvqbasU3QC4= go.opentelemetry.io/otel/metric v1.38.0 h1:Kl6lzIYGAh5M159u9NgiRkmoMKjvbsKtYRwgfrA6WpA= go.opentelemetry.io/otel/metric v1.38.0/go.mod h1:kB5n/QoRM8YwmUahxvI3bO34eVtQf2i4utNVLr9gEmI= -go.opentelemetry.io/otel/sdk v1.16.0 h1:Z1Ok1YsijYL0CSJpHt4cS3wDDh7p572grzNrBMiMWgE= -go.opentelemetry.io/otel/sdk v1.16.0/go.mod h1:tMsIuKXuuIWPBAOrH+eHtvhTL+SntFtXF9QD68aP6p4= -go.opentelemetry.io/otel/sdk/metric v0.39.0 h1:Kun8i1eYf48kHH83RucG93ffz0zGV1sh46FAScOTuDI= -go.opentelemetry.io/otel/sdk/metric v0.39.0/go.mod h1:piDIRgjcK7u0HCL5pCA4e74qpK/jk3NiUoAHATVAmiI= +go.opentelemetry.io/otel/sdk v1.38.0 h1:l48sr5YbNf2hpCUj/FoGhW9yDkl+Ma+LrVl8qaM5b+E= +go.opentelemetry.io/otel/sdk v1.38.0/go.mod h1:ghmNdGlVemJI3+ZB5iDEuk4bWA3GkTpW+DOoZMYBVVg= +go.opentelemetry.io/otel/sdk/metric v1.38.0 h1:aSH66iL0aZqo//xXzQLYozmWrXxyFkBJ6qT5wthqPoM= +go.opentelemetry.io/otel/sdk/metric v1.38.0/go.mod h1:dg9PBnW9XdQ1Hd6ZnRz689CbtrUp0wMMs9iPcgT9EZA= go.opentelemetry.io/otel/trace v1.38.0 h1:Fxk5bKrDZJUH+AMyyIXGcFAPah0oRcT+LuNtJrmcNLE= go.opentelemetry.io/otel/trace v1.38.0/go.mod h1:j1P9ivuFsTceSWe1oY+EeW3sc+Pp42sO++GHkg4wwhs= +go.opentelemetry.io/proto/otlp v1.7.1 h1:gTOMpGDb0WTBOP8JaO72iL3auEZhVmAQg4ipjOVAtj4= +go.opentelemetry.io/proto/otlp v1.7.1/go.mod h1:b2rVh6rfI/s2pHWNlB7ILJcRALpcNDzKhACevjI+ZnE= go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= -go.uber.org/goleak v1.1.11 h1:wy28qYRKZgnJTxGxvye5/wgWr1EKjmUDGYox5mGlRlI= -go.uber.org/goleak v1.1.11/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ= +go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= +go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= go.uber.org/zap v1.24.0 h1:FiJd5l1UOLj0wCgbSE0rwwXHzEdAZS6hiiSnxJN/D60= @@ -359,6 +377,8 @@ golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8T golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 h1:KpwkzHKEF7B9Zxg18WzOa7djJ+Ha5DzthMyZYQfEn2A= google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1/go.mod h1:nKE/iIaLqn2bQwXBg8f1g2Ylh6r5MN5CmZvuzZCgsCU= +google.golang.org/grpc v1.75.0 h1:+TW+dqTd2Biwe6KKfhE5JpiYIBWq865PhKGSXiivqt4= +google.golang.org/grpc v1.75.0/go.mod h1:JtPAzKiq4v1xcAB2hydNlWI2RnF85XXcV0mhKXr2ecQ= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= From bb458d0cd06bcdd8c0d07632aefec40f8e6c290b Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Mon, 1 Dec 2025 10:36:08 +0000 Subject: [PATCH 509/647] use npm instead of yarn (#1221) --- npm-distribution/package-lock.json | 536 +++++++++++++++++++++++++++++ npm-distribution/yarn.lock | 315 ----------------- 2 files changed, 536 insertions(+), 315 deletions(-) create mode 100644 npm-distribution/package-lock.json delete mode 100644 npm-distribution/yarn.lock diff --git a/npm-distribution/package-lock.json b/npm-distribution/package-lock.json new file mode 100644 index 0000000000..e3b36b75df --- /dev/null +++ b/npm-distribution/package-lock.json @@ -0,0 +1,536 @@ +{ + "name": "@sourcegraph/src", + "version": "0.0.0-dev", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "@sourcegraph/src", + "version": "0.0.0-dev", + "hasInstallScript": true, + "license": "Apache-2.0", + "dependencies": { + "tar": "^7.1.0" + }, + "bin": { + "src": "src.js" + }, + "devDependencies": { + "@types/tar": "6.1.13" + } + }, + "node_modules/@isaacs/cliui": { + "version": "8.0.2", + "license": "ISC", + "dependencies": { + "string-width": "^5.1.2", + "string-width-cjs": "npm:string-width@^4.2.0", + "strip-ansi": "^7.0.1", + "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", + "wrap-ansi": "^8.1.0", + "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@isaacs/cliui/node_modules/ansi-regex": { + "version": "6.0.1", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/@isaacs/cliui/node_modules/strip-ansi": { + "version": "7.1.0", + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/@isaacs/fs-minipass": { + "version": "4.0.1", + "license": "ISC", + "dependencies": { + "minipass": "^7.0.4" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@pkgjs/parseargs": { + "version": "0.11.0", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=14" + } + }, + "node_modules/@types/node": { + "version": "17.0.36", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/tar": { + "version": "6.1.13", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*", + "minipass": "^4.0.0" + } + }, + "node_modules/@types/tar/node_modules/minipass": { + "version": "4.2.8", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "license": "MIT" + }, + "node_modules/brace-expansion": { + "version": "2.0.1", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/chownr": { + "version": "3.0.0", + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "license": "MIT" + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/eastasianwidth": { + "version": "0.2.0", + "license": "MIT" + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "license": "MIT" + }, + "node_modules/foreground-child": { + "version": "3.1.1", + "license": "ISC", + "dependencies": { + "cross-spawn": "^7.0.0", + "signal-exit": "^4.0.1" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/glob": { + "version": "10.3.15", + "license": "ISC", + "dependencies": { + "foreground-child": "^3.1.0", + "jackspeak": "^2.3.6", + "minimatch": "^9.0.1", + "minipass": "^7.0.4", + "path-scurry": "^1.11.0" + }, + "bin": { + "glob": "dist/esm/bin.mjs" + }, + "engines": { + "node": ">=16 || 14 >=14.18" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/isexe": { + "version": "2.0.0", + "license": "ISC" + }, + "node_modules/jackspeak": { + "version": "2.3.6", + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/cliui": "^8.0.2" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + }, + "optionalDependencies": { + "@pkgjs/parseargs": "^0.11.0" + } + }, + "node_modules/lru-cache": { + "version": "10.2.2", + "license": "ISC", + "engines": { + "node": "14 || >=16.14" + } + }, + "node_modules/minimatch": { + "version": "9.0.4", + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/minipass": { + "version": "7.1.1", + "license": "ISC", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/minizlib": { + "version": "3.0.1", + "license": "MIT", + "dependencies": { + "minipass": "^7.0.4", + "rimraf": "^5.0.5" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/mkdirp": { + "version": "3.0.1", + "license": "MIT", + "bin": { + "mkdirp": "dist/cjs/src/bin.js" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-scurry": { + "version": "1.11.1", + "license": "BlueOak-1.0.0", + "dependencies": { + "lru-cache": "^10.2.0", + "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" + }, + "engines": { + "node": ">=16 || 14 >=14.18" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/rimraf": { + "version": "5.0.7", + "license": "ISC", + "dependencies": { + "glob": "^10.3.7" + }, + "bin": { + "rimraf": "dist/esm/bin.mjs" + }, + "engines": { + "node": ">=14.18" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/signal-exit": { + "version": "4.1.0", + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/string-width": { + "version": "5.1.2", + "license": "MIT", + "dependencies": { + "eastasianwidth": "^0.2.0", + "emoji-regex": "^9.2.2", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/string-width-cjs": { + "name": "string-width", + "version": "4.2.3", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width/node_modules/ansi-regex": { + "version": "6.0.1", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/string-width/node_modules/emoji-regex": { + "version": "9.2.2", + "license": "MIT" + }, + "node_modules/string-width/node_modules/strip-ansi": { + "version": "7.1.0", + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi-cjs": { + "name": "strip-ansi", + "version": "6.0.1", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/tar": { + "version": "7.1.0", + "license": "ISC", + "dependencies": { + "@isaacs/fs-minipass": "^4.0.0", + "chownr": "^3.0.0", + "minipass": "^7.1.0", + "minizlib": "^3.0.1", + "mkdirp": "^3.0.1", + "yallist": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/which": { + "version": "2.0.2", + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/wrap-ansi": { + "version": "8.1.0", + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.1.0", + "string-width": "^5.0.1", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs": { + "name": "wrap-ansi", + "version": "7.0.0", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/string-width": { + "version": "4.2.3", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi/node_modules/ansi-regex": { + "version": "6.0.1", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/wrap-ansi/node_modules/ansi-styles": { + "version": "6.2.1", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/wrap-ansi/node_modules/strip-ansi": { + "version": "7.1.0", + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/yallist": { + "version": "5.0.0", + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=18" + } + } + } +} diff --git a/npm-distribution/yarn.lock b/npm-distribution/yarn.lock deleted file mode 100644 index 2061882caf..0000000000 --- a/npm-distribution/yarn.lock +++ /dev/null @@ -1,315 +0,0 @@ -# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. -# yarn lockfile v1 - - -"@isaacs/cliui@^8.0.2": - version "8.0.2" - resolved "https://registry.yarnpkg.com/@isaacs/cliui/-/cliui-8.0.2.tgz#b37667b7bc181c168782259bab42474fbf52b550" - integrity sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA== - dependencies: - string-width "^5.1.2" - string-width-cjs "npm:string-width@^4.2.0" - strip-ansi "^7.0.1" - strip-ansi-cjs "npm:strip-ansi@^6.0.1" - wrap-ansi "^8.1.0" - wrap-ansi-cjs "npm:wrap-ansi@^7.0.0" - -"@isaacs/fs-minipass@^4.0.0": - version "4.0.1" - resolved "https://registry.yarnpkg.com/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz#2d59ae3ab4b38fb4270bfa23d30f8e2e86c7fe32" - integrity sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w== - dependencies: - minipass "^7.0.4" - -"@pkgjs/parseargs@^0.11.0": - version "0.11.0" - resolved "https://registry.yarnpkg.com/@pkgjs/parseargs/-/parseargs-0.11.0.tgz#a77ea742fab25775145434eb1d2328cf5013ac33" - integrity sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg== - -"@types/node@*": - version "17.0.36" - resolved "https://registry.yarnpkg.com/@types/node/-/node-17.0.36.tgz#c0d5f2fe76b47b63e0e0efc3d2049a9970d68794" - integrity sha512-V3orv+ggDsWVHP99K3JlwtH20R7J4IhI1Kksgc+64q5VxgfRkQG8Ws3MFm/FZOKDYGy9feGFlZ70/HpCNe9QaA== - -"@types/tar@6.1.13": - version "6.1.13" - resolved "https://registry.yarnpkg.com/@types/tar/-/tar-6.1.13.tgz#9b5801c02175344101b4b91086ab2bbc8e93a9b6" - integrity sha512-IznnlmU5f4WcGTh2ltRu/Ijpmk8wiWXfF0VA4s+HPjHZgvFggk1YaIkbo5krX/zUCzWF8N/l4+W/LNxnvAJ8nw== - dependencies: - "@types/node" "*" - minipass "^4.0.0" - -ansi-regex@^5.0.1: - version "5.0.1" - resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-5.0.1.tgz#082cb2c89c9fe8659a311a53bd6a4dc5301db304" - integrity sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ== - -ansi-regex@^6.0.1: - version "6.0.1" - resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-6.0.1.tgz#3183e38fae9a65d7cb5e53945cd5897d0260a06a" - integrity sha512-n5M855fKb2SsfMIiFFoVrABHJC8QtHwVx+mHWP3QcEqBHYienj5dHSgjbxtC0WEZXYt4wcD6zrQElDPhFuZgfA== - -ansi-styles@^4.0.0: - version "4.3.0" - resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-4.3.0.tgz#edd803628ae71c04c85ae7a0906edad34b648937" - integrity sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg== - dependencies: - color-convert "^2.0.1" - -ansi-styles@^6.1.0: - version "6.2.1" - resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-6.2.1.tgz#0e62320cf99c21afff3b3012192546aacbfb05c5" - integrity sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug== - -balanced-match@^1.0.0: - version "1.0.2" - resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.2.tgz#e83e3a7e3f300b34cb9d87f615fa0cbf357690ee" - integrity sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw== - -brace-expansion@^2.0.1: - version "2.0.1" - resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-2.0.1.tgz#1edc459e0f0c548486ecf9fc99f2221364b9a0ae" - integrity sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA== - dependencies: - balanced-match "^1.0.0" - -chownr@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/chownr/-/chownr-3.0.0.tgz#9855e64ecd240a9cc4267ce8a4aa5d24a1da15e4" - integrity sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g== - -color-convert@^2.0.1: - version "2.0.1" - resolved "https://registry.yarnpkg.com/color-convert/-/color-convert-2.0.1.tgz#72d3a68d598c9bdb3af2ad1e84f21d896abd4de3" - integrity sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ== - dependencies: - color-name "~1.1.4" - -color-name@~1.1.4: - version "1.1.4" - resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.4.tgz#c2a09a87acbde69543de6f63fa3995c826c536a2" - integrity sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA== - -cross-spawn@^7.0.0: - version "7.0.3" - resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-7.0.3.tgz#f73a85b9d5d41d045551c177e2882d4ac85728a6" - integrity sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w== - dependencies: - path-key "^3.1.0" - shebang-command "^2.0.0" - which "^2.0.1" - -eastasianwidth@^0.2.0: - version "0.2.0" - resolved "https://registry.yarnpkg.com/eastasianwidth/-/eastasianwidth-0.2.0.tgz#696ce2ec0aa0e6ea93a397ffcf24aa7840c827cb" - integrity sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA== - -emoji-regex@^8.0.0: - version "8.0.0" - resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-8.0.0.tgz#e818fd69ce5ccfcb404594f842963bf53164cc37" - integrity sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A== - -emoji-regex@^9.2.2: - version "9.2.2" - resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-9.2.2.tgz#840c8803b0d8047f4ff0cf963176b32d4ef3ed72" - integrity sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg== - -foreground-child@^3.1.0: - version "3.1.1" - resolved "https://registry.yarnpkg.com/foreground-child/-/foreground-child-3.1.1.tgz#1d173e776d75d2772fed08efe4a0de1ea1b12d0d" - integrity sha512-TMKDUnIte6bfb5nWv7V/caI169OHgvwjb7V4WkeUvbQQdjr5rWKqHFiKWb/fcOwB+CzBT+qbWjvj+DVwRskpIg== - dependencies: - cross-spawn "^7.0.0" - signal-exit "^4.0.1" - -glob@^10.3.7: - version "10.3.15" - resolved "https://registry.yarnpkg.com/glob/-/glob-10.3.15.tgz#e72bc61bc3038c90605f5dd48543dc67aaf3b50d" - integrity sha512-0c6RlJt1TICLyvJYIApxb8GsXoai0KUP7AxKKAtsYXdgJR1mGEUa7DgwShbdk1nly0PYoZj01xd4hzbq3fsjpw== - dependencies: - foreground-child "^3.1.0" - jackspeak "^2.3.6" - minimatch "^9.0.1" - minipass "^7.0.4" - path-scurry "^1.11.0" - -is-fullwidth-code-point@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz#f116f8064fe90b3f7844a38997c0b75051269f1d" - integrity sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg== - -isexe@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/isexe/-/isexe-2.0.0.tgz#e8fbf374dc556ff8947a10dcb0572d633f2cfa10" - integrity sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw== - -jackspeak@^2.3.6: - version "2.3.6" - resolved "https://registry.yarnpkg.com/jackspeak/-/jackspeak-2.3.6.tgz#647ecc472238aee4b06ac0e461acc21a8c505ca8" - integrity sha512-N3yCS/NegsOBokc8GAdM8UcmfsKiSS8cipheD/nivzr700H+nsMOxJjQnvwOcRYVuFkdH0wGUvW2WbXGmrZGbQ== - dependencies: - "@isaacs/cliui" "^8.0.2" - optionalDependencies: - "@pkgjs/parseargs" "^0.11.0" - -lru-cache@^10.2.0: - version "10.2.2" - resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-10.2.2.tgz#48206bc114c1252940c41b25b41af5b545aca878" - integrity sha512-9hp3Vp2/hFQUiIwKo8XCeFVnrg8Pk3TYNPIR7tJADKi5YfcF7vEaK7avFHTlSy3kOKYaJQaalfEo6YuXdceBOQ== - -minimatch@^9.0.1: - version "9.0.4" - resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-9.0.4.tgz#8e49c731d1749cbec05050ee5145147b32496a51" - integrity sha512-KqWh+VchfxcMNRAJjj2tnsSJdNbHsVgnkBhTNrW7AjVo6OvLtxw8zfT9oLw1JSohlFzJ8jCoTgaoXvJ+kHt6fw== - dependencies: - brace-expansion "^2.0.1" - -minipass@^4.0.0: - version "4.2.8" - resolved "https://registry.yarnpkg.com/minipass/-/minipass-4.2.8.tgz#f0010f64393ecfc1d1ccb5f582bcaf45f48e1a3a" - integrity sha512-fNzuVyifolSLFL4NzpF+wEF4qrgqaaKX0haXPQEdQ7NKAN+WecoKMHV09YcuL/DHxrUsYQOK3MiuDf7Ip2OXfQ== - -"minipass@^5.0.0 || ^6.0.2 || ^7.0.0", minipass@^7.0.4, minipass@^7.1.0: - version "7.1.1" - resolved "https://registry.yarnpkg.com/minipass/-/minipass-7.1.1.tgz#f7f85aff59aa22f110b20e27692465cf3bf89481" - integrity sha512-UZ7eQ+h8ywIRAW1hIEl2AqdwzJucU/Kp59+8kkZeSvafXhZjul247BvIJjEVFVeON6d7lM46XX1HXCduKAS8VA== - -minizlib@^3.0.1: - version "3.0.1" - resolved "https://registry.yarnpkg.com/minizlib/-/minizlib-3.0.1.tgz#46d5329d1eb3c83924eff1d3b858ca0a31581012" - integrity sha512-umcy022ILvb5/3Djuu8LWeqUa8D68JaBzlttKeMWen48SjabqS3iY5w/vzeMzMUNhLDifyhbOwKDSznB1vvrwg== - dependencies: - minipass "^7.0.4" - rimraf "^5.0.5" - -mkdirp@^3.0.1: - version "3.0.1" - resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-3.0.1.tgz#e44e4c5607fb279c168241713cc6e0fea9adcb50" - integrity sha512-+NsyUUAZDmo6YVHzL/stxSu3t9YS1iljliy3BSDrXJ/dkn1KYdmtZODGGjLcc9XLgVVpH4KshHB8XmZgMhaBXg== - -path-key@^3.1.0: - version "3.1.1" - resolved "https://registry.yarnpkg.com/path-key/-/path-key-3.1.1.tgz#581f6ade658cbba65a0d3380de7753295054f375" - integrity sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q== - -path-scurry@^1.11.0: - version "1.11.1" - resolved "https://registry.yarnpkg.com/path-scurry/-/path-scurry-1.11.1.tgz#7960a668888594a0720b12a911d1a742ab9f11d2" - integrity sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA== - dependencies: - lru-cache "^10.2.0" - minipass "^5.0.0 || ^6.0.2 || ^7.0.0" - -rimraf@^5.0.5: - version "5.0.7" - resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-5.0.7.tgz#27bddf202e7d89cb2e0381656380d1734a854a74" - integrity sha512-nV6YcJo5wbLW77m+8KjH8aB/7/rxQy9SZ0HY5shnwULfS+9nmTtVXAJET5NdZmCzA4fPI/Hm1wo/Po/4mopOdg== - dependencies: - glob "^10.3.7" - -shebang-command@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/shebang-command/-/shebang-command-2.0.0.tgz#ccd0af4f8835fbdc265b82461aaf0c36663f34ea" - integrity sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA== - dependencies: - shebang-regex "^3.0.0" - -shebang-regex@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/shebang-regex/-/shebang-regex-3.0.0.tgz#ae16f1644d873ecad843b0307b143362d4c42172" - integrity sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A== - -signal-exit@^4.0.1: - version "4.1.0" - resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-4.1.0.tgz#952188c1cbd546070e2dd20d0f41c0ae0530cb04" - integrity sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw== - -"string-width-cjs@npm:string-width@^4.2.0": - version "4.2.3" - resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010" - integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g== - dependencies: - emoji-regex "^8.0.0" - is-fullwidth-code-point "^3.0.0" - strip-ansi "^6.0.1" - -string-width@^4.1.0: - version "4.2.3" - resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010" - integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g== - dependencies: - emoji-regex "^8.0.0" - is-fullwidth-code-point "^3.0.0" - strip-ansi "^6.0.1" - -string-width@^5.0.1, string-width@^5.1.2: - version "5.1.2" - resolved "https://registry.yarnpkg.com/string-width/-/string-width-5.1.2.tgz#14f8daec6d81e7221d2a357e668cab73bdbca794" - integrity sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA== - dependencies: - eastasianwidth "^0.2.0" - emoji-regex "^9.2.2" - strip-ansi "^7.0.1" - -"strip-ansi-cjs@npm:strip-ansi@^6.0.1": - version "6.0.1" - resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9" - integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A== - dependencies: - ansi-regex "^5.0.1" - -strip-ansi@^6.0.0, strip-ansi@^6.0.1: - version "6.0.1" - resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9" - integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A== - dependencies: - ansi-regex "^5.0.1" - -strip-ansi@^7.0.1: - version "7.1.0" - resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-7.1.0.tgz#d5b6568ca689d8561370b0707685d22434faff45" - integrity sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ== - dependencies: - ansi-regex "^6.0.1" - -tar@^7.1.0: - version "7.1.0" - resolved "https://registry.yarnpkg.com/tar/-/tar-7.1.0.tgz#c6d4ec5b10ccdffe8bc412b206eaeaf5181f3098" - integrity sha512-ENhg4W6BmjYxl8GTaE7/h99f0aXiSWv4kikRZ9n2/JRxypZniE84ILZqimAhxxX7Zb8Px6pFdheW3EeHfhnXQQ== - dependencies: - "@isaacs/fs-minipass" "^4.0.0" - chownr "^3.0.0" - minipass "^7.1.0" - minizlib "^3.0.1" - mkdirp "^3.0.1" - yallist "^5.0.0" - -which@^2.0.1: - version "2.0.2" - resolved "https://registry.yarnpkg.com/which/-/which-2.0.2.tgz#7c6a8dd0a636a0327e10b59c9286eee93f3f51b1" - integrity sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA== - dependencies: - isexe "^2.0.0" - -"wrap-ansi-cjs@npm:wrap-ansi@^7.0.0": - version "7.0.0" - resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-7.0.0.tgz#67e145cff510a6a6984bdf1152911d69d2eb9e43" - integrity sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q== - dependencies: - ansi-styles "^4.0.0" - string-width "^4.1.0" - strip-ansi "^6.0.0" - -wrap-ansi@^8.1.0: - version "8.1.0" - resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-8.1.0.tgz#56dc22368ee570face1b49819975d9b9a5ead214" - integrity sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ== - dependencies: - ansi-styles "^6.1.0" - string-width "^5.0.1" - strip-ansi "^7.0.1" - -yallist@^5.0.0: - version "5.0.0" - resolved "https://registry.yarnpkg.com/yallist/-/yallist-5.0.0.tgz#00e2de443639ed0d78fd87de0d27469fbcffb533" - integrity sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw== From 24c43dbf1a2a84a04e110a893cd3837c084f3d93 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Mon, 1 Dec 2025 10:50:21 +0000 Subject: [PATCH 510/647] fix: upgrade cross-spawn to 7.0.6 (CVE-2024-21538) (#1219) --- npm-distribution/package.json | 3 +++ 1 file changed, 3 insertions(+) diff --git a/npm-distribution/package.json b/npm-distribution/package.json index f0e44a82bf..e3dcc5f2dd 100644 --- a/npm-distribution/package.json +++ b/npm-distribution/package.json @@ -19,6 +19,9 @@ "dependencies": { "tar": "^7.1.0" }, + "overrides": { + "cross-spawn": "^7.0.5" + }, "devDependencies": { "@types/tar": "6.1.13" }, From e000ae71a70b730b03ba191e5102c35b67d28483 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Mon, 1 Dec 2025 12:25:10 +0000 Subject: [PATCH 511/647] fix: upgrade glob to 10.5.0 (CVE-2025-64756) (#1218) --- npm-distribution/package-lock.json | 494 +++-------------------------- npm-distribution/package.json | 4 +- 2 files changed, 55 insertions(+), 443 deletions(-) diff --git a/npm-distribution/package-lock.json b/npm-distribution/package-lock.json index e3b36b75df..12d9c8dfa7 100644 --- a/npm-distribution/package-lock.json +++ b/npm-distribution/package-lock.json @@ -19,46 +19,10 @@ "@types/tar": "6.1.13" } }, - "node_modules/@isaacs/cliui": { - "version": "8.0.2", - "license": "ISC", - "dependencies": { - "string-width": "^5.1.2", - "string-width-cjs": "npm:string-width@^4.2.0", - "strip-ansi": "^7.0.1", - "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", - "wrap-ansi": "^8.1.0", - "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/@isaacs/cliui/node_modules/ansi-regex": { - "version": "6.0.1", - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/ansi-regex?sponsor=1" - } - }, - "node_modules/@isaacs/cliui/node_modules/strip-ansi": { - "version": "7.1.0", - "license": "MIT", - "dependencies": { - "ansi-regex": "^6.0.1" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/strip-ansi?sponsor=1" - } - }, "node_modules/@isaacs/fs-minipass": { "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz", + "integrity": "sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==", "license": "ISC", "dependencies": { "minipass": "^7.0.4" @@ -67,21 +31,29 @@ "node": ">=18.0.0" } }, - "node_modules/@pkgjs/parseargs": { - "version": "0.11.0", - "license": "MIT", - "optional": true, + "node_modules/@isaacs/fs-minipass/node_modules/minipass": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz", + "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==", + "license": "ISC", "engines": { - "node": ">=14" + "node": ">=16 || 14 >=14.17" } }, "node_modules/@types/node": { - "version": "17.0.36", + "version": "24.10.1", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.10.1.tgz", + "integrity": "sha512-GNWcUTRBgIRJD5zj+Tq0fKOJ5XZajIiBroOF0yvj2bSU1WvNdYS/dn9UxwsujGW4JX06dnHyjV2y9rRaybH0iQ==", "dev": true, - "license": "MIT" + "license": "MIT", + "dependencies": { + "undici-types": "~7.16.0" + } }, "node_modules/@types/tar": { "version": "6.1.13", + "resolved": "https://registry.npmjs.org/@types/tar/-/tar-6.1.13.tgz", + "integrity": "sha512-IznnlmU5f4WcGTh2ltRu/Ijpmk8wiWXfF0VA4s+HPjHZgvFggk1YaIkbo5krX/zUCzWF8N/l4+W/LNxnvAJ8nw==", "dev": true, "license": "MIT", "dependencies": { @@ -89,444 +61,82 @@ "minipass": "^4.0.0" } }, - "node_modules/@types/tar/node_modules/minipass": { - "version": "4.2.8", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=8" - } - }, - "node_modules/ansi-regex": { - "version": "5.0.1", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/ansi-styles": { - "version": "4.3.0", - "license": "MIT", - "dependencies": { - "color-convert": "^2.0.1" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, - "node_modules/balanced-match": { - "version": "1.0.2", - "license": "MIT" - }, - "node_modules/brace-expansion": { - "version": "2.0.1", - "license": "MIT", - "dependencies": { - "balanced-match": "^1.0.0" - } - }, "node_modules/chownr": { "version": "3.0.0", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz", + "integrity": "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==", "license": "BlueOak-1.0.0", "engines": { "node": ">=18" } }, - "node_modules/color-convert": { - "version": "2.0.1", - "license": "MIT", - "dependencies": { - "color-name": "~1.1.4" - }, - "engines": { - "node": ">=7.0.0" - } - }, - "node_modules/color-name": { - "version": "1.1.4", - "license": "MIT" - }, - "node_modules/cross-spawn": { - "version": "7.0.6", - "license": "MIT", - "dependencies": { - "path-key": "^3.1.0", - "shebang-command": "^2.0.0", - "which": "^2.0.1" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/eastasianwidth": { - "version": "0.2.0", - "license": "MIT" - }, - "node_modules/emoji-regex": { - "version": "8.0.0", - "license": "MIT" - }, - "node_modules/foreground-child": { - "version": "3.1.1", - "license": "ISC", - "dependencies": { - "cross-spawn": "^7.0.0", - "signal-exit": "^4.0.1" - }, - "engines": { - "node": ">=14" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/glob": { - "version": "10.3.15", - "license": "ISC", - "dependencies": { - "foreground-child": "^3.1.0", - "jackspeak": "^2.3.6", - "minimatch": "^9.0.1", - "minipass": "^7.0.4", - "path-scurry": "^1.11.0" - }, - "bin": { - "glob": "dist/esm/bin.mjs" - }, - "engines": { - "node": ">=16 || 14 >=14.18" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/is-fullwidth-code-point": { - "version": "3.0.0", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/isexe": { - "version": "2.0.0", - "license": "ISC" - }, - "node_modules/jackspeak": { - "version": "2.3.6", - "license": "BlueOak-1.0.0", - "dependencies": { - "@isaacs/cliui": "^8.0.2" - }, - "engines": { - "node": ">=14" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - }, - "optionalDependencies": { - "@pkgjs/parseargs": "^0.11.0" - } - }, - "node_modules/lru-cache": { - "version": "10.2.2", - "license": "ISC", - "engines": { - "node": "14 || >=16.14" - } - }, - "node_modules/minimatch": { - "version": "9.0.4", - "license": "ISC", - "dependencies": { - "brace-expansion": "^2.0.1" - }, - "engines": { - "node": ">=16 || 14 >=14.17" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, "node_modules/minipass": { - "version": "7.1.1", + "version": "4.2.8", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-4.2.8.tgz", + "integrity": "sha512-fNzuVyifolSLFL4NzpF+wEF4qrgqaaKX0haXPQEdQ7NKAN+WecoKMHV09YcuL/DHxrUsYQOK3MiuDf7Ip2OXfQ==", + "dev": true, "license": "ISC", "engines": { - "node": ">=16 || 14 >=14.17" + "node": ">=8" } }, "node_modules/minizlib": { - "version": "3.0.1", + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.1.0.tgz", + "integrity": "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==", "license": "MIT", "dependencies": { - "minipass": "^7.0.4", - "rimraf": "^5.0.5" + "minipass": "^7.1.2" }, "engines": { "node": ">= 18" } }, - "node_modules/mkdirp": { - "version": "3.0.1", - "license": "MIT", - "bin": { - "mkdirp": "dist/cjs/src/bin.js" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/path-key": { - "version": "3.1.1", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/path-scurry": { - "version": "1.11.1", - "license": "BlueOak-1.0.0", - "dependencies": { - "lru-cache": "^10.2.0", - "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" - }, - "engines": { - "node": ">=16 || 14 >=14.18" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/rimraf": { - "version": "5.0.7", - "license": "ISC", - "dependencies": { - "glob": "^10.3.7" - }, - "bin": { - "rimraf": "dist/esm/bin.mjs" - }, - "engines": { - "node": ">=14.18" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/shebang-command": { - "version": "2.0.0", - "license": "MIT", - "dependencies": { - "shebang-regex": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/shebang-regex": { - "version": "3.0.0", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/signal-exit": { - "version": "4.1.0", + "node_modules/minizlib/node_modules/minipass": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz", + "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==", "license": "ISC", "engines": { - "node": ">=14" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/string-width": { - "version": "5.1.2", - "license": "MIT", - "dependencies": { - "eastasianwidth": "^0.2.0", - "emoji-regex": "^9.2.2", - "strip-ansi": "^7.0.1" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/string-width-cjs": { - "name": "string-width", - "version": "4.2.3", - "license": "MIT", - "dependencies": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/string-width/node_modules/ansi-regex": { - "version": "6.0.1", - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/ansi-regex?sponsor=1" - } - }, - "node_modules/string-width/node_modules/emoji-regex": { - "version": "9.2.2", - "license": "MIT" - }, - "node_modules/string-width/node_modules/strip-ansi": { - "version": "7.1.0", - "license": "MIT", - "dependencies": { - "ansi-regex": "^6.0.1" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/strip-ansi?sponsor=1" - } - }, - "node_modules/strip-ansi": { - "version": "6.0.1", - "license": "MIT", - "dependencies": { - "ansi-regex": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/strip-ansi-cjs": { - "name": "strip-ansi", - "version": "6.0.1", - "license": "MIT", - "dependencies": { - "ansi-regex": "^5.0.1" - }, - "engines": { - "node": ">=8" + "node": ">=16 || 14 >=14.17" } }, "node_modules/tar": { - "version": "7.1.0", - "license": "ISC", + "version": "7.5.2", + "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.2.tgz", + "integrity": "sha512-7NyxrTE4Anh8km8iEy7o0QYPs+0JKBTj5ZaqHg6B39erLg0qYXN3BijtShwbsNSvQ+LN75+KV+C4QR/f6Gwnpg==", + "license": "BlueOak-1.0.0", "dependencies": { "@isaacs/fs-minipass": "^4.0.0", "chownr": "^3.0.0", - "minipass": "^7.1.0", - "minizlib": "^3.0.1", - "mkdirp": "^3.0.1", + "minipass": "^7.1.2", + "minizlib": "^3.1.0", "yallist": "^5.0.0" }, "engines": { "node": ">=18" } }, - "node_modules/which": { - "version": "2.0.2", + "node_modules/tar/node_modules/minipass": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz", + "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==", "license": "ISC", - "dependencies": { - "isexe": "^2.0.0" - }, - "bin": { - "node-which": "bin/node-which" - }, "engines": { - "node": ">= 8" - } - }, - "node_modules/wrap-ansi": { - "version": "8.1.0", - "license": "MIT", - "dependencies": { - "ansi-styles": "^6.1.0", - "string-width": "^5.0.1", - "strip-ansi": "^7.0.1" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/wrap-ansi?sponsor=1" - } - }, - "node_modules/wrap-ansi-cjs": { - "name": "wrap-ansi", - "version": "7.0.0", - "license": "MIT", - "dependencies": { - "ansi-styles": "^4.0.0", - "string-width": "^4.1.0", - "strip-ansi": "^6.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/wrap-ansi?sponsor=1" - } - }, - "node_modules/wrap-ansi-cjs/node_modules/string-width": { - "version": "4.2.3", - "license": "MIT", - "dependencies": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/wrap-ansi/node_modules/ansi-regex": { - "version": "6.0.1", - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/ansi-regex?sponsor=1" - } - }, - "node_modules/wrap-ansi/node_modules/ansi-styles": { - "version": "6.2.1", - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" + "node": ">=16 || 14 >=14.17" } }, - "node_modules/wrap-ansi/node_modules/strip-ansi": { - "version": "7.1.0", - "license": "MIT", - "dependencies": { - "ansi-regex": "^6.0.1" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/strip-ansi?sponsor=1" - } + "node_modules/undici-types": { + "version": "7.16.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz", + "integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==", + "dev": true, + "license": "MIT" }, "node_modules/yallist": { "version": "5.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz", + "integrity": "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==", "license": "BlueOak-1.0.0", "engines": { "node": ">=18" diff --git a/npm-distribution/package.json b/npm-distribution/package.json index e3dcc5f2dd..bfdc106cf4 100644 --- a/npm-distribution/package.json +++ b/npm-distribution/package.json @@ -20,7 +20,9 @@ "tar": "^7.1.0" }, "overrides": { - "cross-spawn": "^7.0.5" + "cross-spawn": "^7.0.5", + "glob": "^10.5.0", + "brace-expansion": "^2.0.2" }, "devDependencies": { "@types/tar": "6.1.13" From 08d669cb20f909304fa1cc7a8803ade7ce32e03a Mon Sep 17 00:00:00 2001 From: Vincent Date: Thu, 4 Dec 2025 16:14:40 +0000 Subject: [PATCH 512/647] security: use traversal safe os.Root for FS operations (#1222) * use os.Root to mitigate fs security issues --- cmd/src/servegit.go | 15 ++++++++--- internal/servegit/gitservice.go | 14 ++++++++++- internal/servegit/gitservice_test.go | 8 ++++++ internal/servegit/serve.go | 16 +++++++----- internal/servegit/serve_test.go | 37 ++++++++++++++++++++++------ 5 files changed, 71 insertions(+), 19 deletions(-) diff --git a/cmd/src/servegit.go b/cmd/src/servegit.go index 8a9e96d1ec..11c4c30c31 100644 --- a/cmd/src/servegit.go +++ b/cmd/src/servegit.go @@ -58,11 +58,18 @@ Documentation at https://sourcegraph.com/docs/admin/code_hosts/src_serve_git dbug = log.New(os.Stderr, "DBUG serve-git: ", log.LstdFlags) } + root, err := os.OpenRoot(repoDir) + if err != nil { + return err + } + defer root.Close() + s := &servegit.Serve{ - Addr: *addrFlag, - Root: repoDir, - Info: log.New(os.Stderr, "serve-git: ", log.LstdFlags), - Debug: dbug, + Addr: *addrFlag, + Root: repoDir, + RootFS: root, + Info: log.New(os.Stderr, "serve-git: ", log.LstdFlags), + Debug: dbug, } if *listFlag { diff --git a/internal/servegit/gitservice.go b/internal/servegit/gitservice.go index 9c815ba9ca..63778d6049 100644 --- a/internal/servegit/gitservice.go +++ b/internal/servegit/gitservice.go @@ -8,6 +8,7 @@ import ( "net/http" "os" "os/exec" + "path/filepath" "strconv" "strings" @@ -65,6 +66,10 @@ type Handler struct { // call the returned function when done executing. If the executation // failed, it will pass in a non-nil error. Trace func(ctx context.Context, svc, repo, protocol string) func(error) + + // RootFS is a traversal safe API that ensures files outside of the + // root cannot be opened. + RootFS *os.Root } func (s *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { @@ -93,7 +98,14 @@ func (s *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } - if _, err = os.Stat(dir); os.IsNotExist(err) { + // os.Root only accepts relative paths from it's root. So we trim the + // prefix. + relDir, err := filepath.Rel(s.RootFS.Name(), dir) + if err != nil { + http.Error(w, "invalid path specified: "+err.Error(), http.StatusBadRequest) + return + } + if _, err = s.RootFS.Stat(relDir); os.IsNotExist(err) { http.Error(w, "repository not found", http.StatusNotFound) return } else if err != nil { diff --git a/internal/servegit/gitservice_test.go b/internal/servegit/gitservice_test.go index e1b7b87083..0c70c8bf86 100644 --- a/internal/servegit/gitservice_test.go +++ b/internal/servegit/gitservice_test.go @@ -5,6 +5,7 @@ import ( "context" "fmt" "net/http/httptest" + "os" "os/exec" "path/filepath" "strings" @@ -31,10 +32,17 @@ func TestHandler(t *testing.T) { runCmd(t, repo, "git", "tag", fmt.Sprintf("v%d", i+1)) } + rootFS, err := os.OpenRoot(root) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { rootFS.Close() }) + ts := httptest.NewServer(&Handler{ Dir: func(_ context.Context, s string) (string, error) { return filepath.Join(root, s, ".git"), nil }, + RootFS: rootFS, }) defer ts.Close() diff --git a/internal/servegit/serve.go b/internal/servegit/serve.go index 22286531e5..33e1a0e105 100644 --- a/internal/servegit/serve.go +++ b/internal/servegit/serve.go @@ -9,6 +9,7 @@ import ( "log" "net" "net/http" + "os" "os/exec" pathpkg "path" "path/filepath" @@ -19,10 +20,11 @@ import ( ) type Serve struct { - Addr string - Root string - Info *log.Logger - Debug *log.Logger + Addr string + Root string + RootFS *os.Root + Info *log.Logger + Debug *log.Logger } func (s *Serve) Start() error { @@ -69,7 +71,7 @@ func (s *Serve) handler() http.Handler { mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html; charset=utf-8") - err := indexHTML.Execute(w, map[string]interface{}{ + err := indexHTML.Execute(w, map[string]any{ "Explain": explainAddr(s.Addr), "Links": []string{ "/v1/list-repos", @@ -100,7 +102,8 @@ func (s *Serve) handler() http.Handler { _ = enc.Encode(&resp) }) - fs := http.FileServer(http.Dir(s.Root)) + safeFS := http.FS(s.RootFS.FS()) + fs := http.FileServer(safeFS) svc := &Handler{ Dir: func(_ context.Context, name string) (string, error) { return filepath.Join(s.Root, filepath.FromSlash(name)), nil @@ -117,6 +120,7 @@ func (s *Serve) handler() http.Handler { } } }, + RootFS: s.RootFS, } mux.Handle("/repos/", http.StripPrefix("/repos/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Use git service if git is trying to clone. Otherwise show http.FileServer for convenience diff --git a/internal/servegit/serve_test.go b/internal/servegit/serve_test.go index b314b76de4..a23523fcc4 100644 --- a/internal/servegit/serve_test.go +++ b/internal/servegit/serve_test.go @@ -36,13 +36,21 @@ func TestReposHandler(t *testing.T) { }} for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { + root := gitInitRepos(t, tc.repos...) + rootFS, err := os.OpenRoot(root) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { rootFS.Close() }) + h := (&Serve{ - Info: testLogger(t), - Debug: discardLogger, - Addr: testAddress, - Root: root, + Info: testLogger(t), + Debug: discardLogger, + Addr: testAddress, + Root: root, + RootFS: rootFS, }).handler() var want []Repo @@ -132,6 +140,12 @@ func gitInit(t *testing.T, path string) { func gitInitRepos(t *testing.T, names ...string) string { root := t.TempDir() + + // We cannot os.OpenRoot on a non-existent dir so we return tmpdir + if len(names) == 0 { + return root + } + root = filepath.Join(root, "repos-root") for _, name := range names { @@ -161,10 +175,17 @@ func TestIgnoreGitSubmodules(t *testing.T) { t.Fatal(err) } + rootFS, err := os.OpenRoot(root) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { rootFS.Close() }) + repos, err := (&Serve{ - Info: testLogger(t), - Debug: discardLogger, - Root: root, + Info: testLogger(t), + Debug: discardLogger, + Root: root, + RootFS: rootFS, }).Repos() if err != nil { t.Fatal(err) @@ -201,6 +222,6 @@ type testWriter struct { } func (tw testWriter) Write(p []byte) (n int, err error) { - tw.T.Log(string(p)) + tw.Log(string(p)) return len(p), nil } From b627480e26d0e3bef1d65ea37b1df6d03c505779 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Fri, 5 Dec 2025 09:30:51 +0000 Subject: [PATCH 513/647] run modernize -fix (#1224) - 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 { From 39cf9658c6bc8659d6890526c86bdeadb64b77be Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Fri, 5 Dec 2025 13:44:55 +0000 Subject: [PATCH 514/647] remove SOC2 comment in PR template (#1226) --- .github/PULL_REQUEST_TEMPLATE.md | 8 -------- 1 file changed, 8 deletions(-) diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index a47c1642f4..f8d976a1c4 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1,9 +1 @@ ### Test plan - - From 36a33de3c91fb9fa088c75c3664e01b599bca245 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Mon, 8 Dec 2025 09:35:49 +0000 Subject: [PATCH 515/647] refactor(api): add buildTransport that uses ProxyTransport (#1225) * refactor(api): rename applyProxy to NewProxyTransport - NewProxyTransport creates a cloned transport which does the required proxy handling in dial etc. - Remove use of 'customTransport' * add test * review comments - add doc string - unexport - delete low value tests --- internal/api/api.go | 42 ++++++++++++++++++++-------------------- internal/api/api_test.go | 3 --- internal/api/proxy.go | 35 +++++++++++++++------------------ 3 files changed, 37 insertions(+), 43 deletions(-) delete mode 100644 internal/api/api_test.go diff --git a/internal/api/api.go b/internal/api/api.go index 4dfad40d3b..e0bc234558 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -87,24 +87,10 @@ type ClientOpts struct { ProxyPath string } -// NewClient creates a new API client. -func NewClient(opts ClientOpts) Client { - if opts.Out == nil { - panic("unexpected nil out option") - } - - flags := opts.Flags - if flags == nil { - flags = defaultFlags() - } - - httpClient := http.DefaultClient - +func buildTransport(opts ClientOpts, flags *Flags) *http.Transport { transport := http.DefaultTransport.(*http.Transport).Clone() - customTransport := false if flags.insecureSkipVerify != nil && *flags.insecureSkipVerify { - customTransport = true transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} } @@ -112,14 +98,28 @@ func NewClient(opts ClientOpts) Client { transport.TLSClientConfig = &tls.Config{} } - if applyProxy(transport, opts.ProxyURL, opts.ProxyPath) { - customTransport = true + if opts.ProxyURL != nil || opts.ProxyPath != "" { + transport = withProxyTransport(transport, opts.ProxyURL, opts.ProxyPath) } - if customTransport { - httpClient = &http.Client{ - Transport: transport, - } + return transport +} + +// NewClient creates a new API client. +func NewClient(opts ClientOpts) Client { + if opts.Out == nil { + panic("unexpected nil out option") + } + + flags := opts.Flags + if flags == nil { + flags = defaultFlags() + } + + transport := buildTransport(opts, flags) + + httpClient := &http.Client{ + Transport: transport, } return &client{ diff --git a/internal/api/api_test.go b/internal/api/api_test.go deleted file mode 100644 index 0aaf3ec14a..0000000000 --- a/internal/api/api_test.go +++ /dev/null @@ -1,3 +0,0 @@ -package api - -// TODO: implement a super basic GraphQL server that can return canned results. diff --git a/internal/api/proxy.go b/internal/api/proxy.go index 3cf8673829..9589b9beb5 100644 --- a/internal/api/proxy.go +++ b/internal/api/proxy.go @@ -11,11 +11,13 @@ import ( "net/url" ) -func applyProxy(transport *http.Transport, proxyURL *url.URL, proxyPath string) (applied bool) { - if proxyURL == nil && proxyPath == "" { - return false - } - +// withProxyTransport modifies the given transport to handle proxying of unix, socks5 and http connections. +// +// Note: baseTransport is considered to be a clone created with transport.Clone() +// +// - If a the proxyPath is not empty, a unix socket proxy is created. +// - Otherwise, the proxyURL is used to determine if we should proxy socks5 / http connections +func withProxyTransport(baseTransport *http.Transport, proxyURL *url.URL, proxyPath string) *http.Transport { handshakeTLS := func(ctx context.Context, conn net.Conn, addr string) (net.Conn, error) { // Extract the hostname (without the port) for TLS SNI host, _, err := net.SplitHostPort(addr) @@ -26,7 +28,7 @@ func applyProxy(transport *http.Transport, proxyURL *url.URL, proxyPath string) ServerName: host, // Pull InsecureSkipVerify from the target host transport // so that insecure-skip-verify flag settings are honored for the proxy server - InsecureSkipVerify: transport.TLSClientConfig.InsecureSkipVerify, + InsecureSkipVerify: baseTransport.TLSClientConfig.InsecureSkipVerify, }) if err := tlsConn.HandshakeContext(ctx); err != nil { return nil, err @@ -34,8 +36,6 @@ func applyProxy(transport *http.Transport, proxyURL *url.URL, proxyPath string) return tlsConn, nil } - proxyApplied := false - if proxyPath != "" { dial := func(ctx context.Context, _, _ string) (net.Conn, error) { d := net.Dialer{} @@ -48,17 +48,15 @@ func applyProxy(transport *http.Transport, proxyURL *url.URL, proxyPath string) } return handshakeTLS(ctx, conn, addr) } - transport.DialContext = dial - transport.DialTLSContext = dialTLS + baseTransport.DialContext = dial + baseTransport.DialTLSContext = dialTLS // clear out any system proxy settings - transport.Proxy = nil - proxyApplied = true + baseTransport.Proxy = nil } else if proxyURL != nil { switch proxyURL.Scheme { case "socks5", "socks5h": // SOCKS proxies work out of the box - no need to manually dial - transport.Proxy = http.ProxyURL(proxyURL) - proxyApplied = true + baseTransport.Proxy = http.ProxyURL(proxyURL) case "http", "https": dial := func(ctx context.Context, network, addr string) (net.Conn, error) { // Dial the proxy @@ -126,13 +124,12 @@ func applyProxy(transport *http.Transport, proxyURL *url.URL, proxyPath string) } return handshakeTLS(ctx, conn, addr) } - transport.DialContext = dial - transport.DialTLSContext = dialTLS + baseTransport.DialContext = dial + baseTransport.DialTLSContext = dialTLS // clear out any system proxy settings - transport.Proxy = nil - proxyApplied = true + baseTransport.Proxy = nil } } - return proxyApplied + return baseTransport } From d1a299e7158083a4c0d3d1c69362dafef78ee268 Mon Sep 17 00:00:00 2001 From: Keegan Carruthers-Smith Date: Mon, 8 Dec 2025 14:49:37 +0200 Subject: [PATCH 516/647] chore: update vulnerable packages (#1229) I did the minimal upgrades needed to resolve the CVE's reported by trivy. - CVE-2025-54410 github.com/docker/docker v25.0.6 -> v28.0.0 - GHSA-vrw8-fxc6-2r93 github.com/go-chi/chi/v5 v5.0.10 -> v5.2.2 - CVE-2025-47908 github.com/rs/cors v1.9.0 -> v1.11.0 - CVE-2025-47914 golang.org/x/crypto v0.43.0 -> v0.45.0 - CVE-2025-58181 golang.org/x/crypto Test Plan: CI --- go.mod | 19 ++++++++++--------- go.sum | 38 ++++++++++++++++++++------------------ 2 files changed, 30 insertions(+), 27 deletions(-) diff --git a/go.mod b/go.mod index 818ed24368..c0c693132e 100644 --- a/go.mod +++ b/go.mod @@ -29,7 +29,7 @@ require ( github.com/sourcegraph/scip v0.6.1 github.com/sourcegraph/sourcegraph/lib v0.0.0-20240709083501-1af563b61442 github.com/stretchr/testify v1.11.1 - golang.org/x/net v0.46.0 + golang.org/x/net v0.47.0 golang.org/x/sync v0.18.0 google.golang.org/api v0.256.0 google.golang.org/protobuf v1.36.10 @@ -67,7 +67,7 @@ require ( github.com/distribution/reference v0.6.0 // indirect github.com/docker/cli v24.0.4+incompatible // indirect github.com/docker/distribution v2.8.2+incompatible // indirect - github.com/docker/docker v25.0.6+incompatible // indirect + github.com/docker/docker v28.0.0+incompatible // indirect github.com/docker/docker-credential-helpers v0.8.0 // indirect github.com/docker/go-connections v0.4.0 // indirect github.com/docker/go-units v0.5.0 // indirect @@ -75,7 +75,7 @@ require ( github.com/felixge/fgprof v0.9.3 // indirect github.com/felixge/httpsnoop v1.0.4 // indirect github.com/fxamacker/cbor/v2 v2.7.0 // indirect - github.com/go-chi/chi/v5 v5.0.10 // indirect + github.com/go-chi/chi/v5 v5.2.2 // indirect github.com/go-jose/go-jose/v4 v4.1.2 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/gofrs/uuid/v5 v5.0.0 // indirect @@ -91,11 +91,12 @@ require ( github.com/jackc/pgproto3/v2 v2.3.3 // indirect github.com/jackc/pgservicefile v0.0.0-20231201235250-de7065d80cb9 // indirect github.com/mitchellh/go-homedir v1.1.0 // indirect + github.com/moby/docker-image-spec v1.3.1 // indirect github.com/morikuni/aec v1.0.0 // indirect github.com/opencontainers/go-digest v1.0.0 // indirect github.com/opencontainers/image-spec v1.1.0-rc4 // indirect github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 // indirect - github.com/rs/cors v1.9.0 // indirect + github.com/rs/cors v1.11.0 // indirect github.com/sirupsen/logrus v1.9.3 // indirect github.com/sourcegraph/beaut v0.0.0-20240611013027-627e4c25335a // indirect github.com/spiffe/go-spiffe/v2 v2.5.0 // indirect @@ -116,7 +117,7 @@ require ( go.opentelemetry.io/otel/sdk/metric v1.38.0 // indirect go.opentelemetry.io/otel/trace v1.38.0 // indirect go.opentelemetry.io/proto/otlp v1.7.1 // indirect - golang.org/x/telemetry v0.0.0-20250908211612-aef8a434d053 // indirect + golang.org/x/telemetry v0.0.0-20251008203120-078029d740a8 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20250825161204-c5933d9347a5 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20251103181224-f26f9409b101 // indirect gopkg.in/evanphx/json-patch.v4 v4.12.0 // indirect @@ -216,14 +217,14 @@ require ( go.uber.org/atomic v1.11.0 // indirect go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.24.0 // indirect - golang.org/x/crypto v0.43.0 // indirect - golang.org/x/mod v0.28.0 // indirect + golang.org/x/crypto v0.45.0 // indirect + golang.org/x/mod v0.29.0 // indirect golang.org/x/oauth2 v0.33.0 // indirect golang.org/x/sys v0.38.0 // indirect golang.org/x/term v0.37.0 // indirect - golang.org/x/text v0.30.0 // indirect + golang.org/x/text v0.31.0 // indirect golang.org/x/time v0.14.0 // indirect - golang.org/x/tools v0.37.0 // indirect + golang.org/x/tools v0.38.0 // indirect google.golang.org/genproto v0.0.0-20250603155806-513f23925822 // indirect google.golang.org/grpc v1.76.0 // indirect gopkg.in/inf.v0 v0.9.1 // indirect; direct diff --git a/go.sum b/go.sum index 8c25134d27..22f5dcf5a7 100644 --- a/go.sum +++ b/go.sum @@ -154,8 +154,8 @@ github.com/docker/cli v24.0.4+incompatible h1:Y3bYF9ekNTm2VFz5U/0BlMdJy73D+Y1iAA github.com/docker/cli v24.0.4+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8= github.com/docker/distribution v2.8.2+incompatible h1:T3de5rq0dB1j30rp0sA2rER+m322EBzniBPB6ZIzuh8= github.com/docker/distribution v2.8.2+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= -github.com/docker/docker v25.0.6+incompatible h1:5cPwbwriIcsua2REJe8HqQV+6WlWc1byg2QSXzBxBGg= -github.com/docker/docker v25.0.6+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= +github.com/docker/docker v28.0.0+incompatible h1:Olh0KS820sJ7nPsBKChVhk5pzqcwDR15fumfAd/p9hM= +github.com/docker/docker v28.0.0+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= github.com/docker/docker-credential-helpers v0.8.0 h1:YQFtbBQb4VrpoPxhFuzEBPQ9E16qz5SpHLS+uswaCp8= github.com/docker/docker-credential-helpers v0.8.0/go.mod h1:UGFXcuoQ5TxPiB54nHOZ32AWRqQdECoh/Mg0AlEYb40= github.com/docker/go-connections v0.4.0 h1:El9xVISelRB7BuFusrZozjnkIM5YnzCViNKohAFqRJQ= @@ -188,8 +188,8 @@ github.com/fxamacker/cbor/v2 v2.7.0 h1:iM5WgngdRBanHcxugY4JySA0nk1wZorNOpTgCMedv github.com/fxamacker/cbor/v2 v2.7.0/go.mod h1:pxXPTn3joSm21Gbwsv0w9OSA2y1HFR9qXEeXQVeNoDQ= github.com/getsentry/sentry-go v0.27.0 h1:Pv98CIbtB3LkMWmXi4Joa5OOcwbmnX88sF5qbK3r3Ps= github.com/getsentry/sentry-go v0.27.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= -github.com/go-chi/chi/v5 v5.0.10 h1:rLz5avzKpjqxrYwXNfmjkrYYXOyLJd37pz53UFHC6vk= -github.com/go-chi/chi/v5 v5.0.10/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8= +github.com/go-chi/chi/v5 v5.2.2 h1:CMwsvRVTbXVytCk1Wd72Zy1LAsAh9GxMmSNWLHCG618= +github.com/go-chi/chi/v5 v5.2.2/go.mod h1:L2yAIGWB3H+phAw1NxKwWM+7eUH/lU8pOMm5hHcoops= github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA= github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og= github.com/go-jose/go-jose/v4 v4.1.2 h1:TK/7NqRQZfgAh+Td8AlsrvtPoUyiHh0LqVvokh+1vHI= @@ -344,6 +344,8 @@ github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ= github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= +github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0= +github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo= github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ= github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -402,8 +404,8 @@ github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTE github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= -github.com/rs/cors v1.9.0 h1:l9HGsTsHJcvW14Nk7J9KFz8bzeAWXn3CG6bgt7LsrAE= -github.com/rs/cors v1.9.0/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU= +github.com/rs/cors v1.11.0 h1:0B9GE/r9Bc2UxRMMtymBkHTenPkHDv0CW4Y98GBY+po= +github.com/rs/cors v1.11.0/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU= github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/shurcooL/go v0.0.0-20180423040247-9e1955d9fb6e/go.mod h1:TDJrrUr11Vxrven61rcy3hJMUqaf/CLWYhHNPmT14Lk= @@ -513,16 +515,16 @@ golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACk golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.43.0 h1:dduJYIi3A3KOfdGOHX8AVZ/jGiyPa3IbBozJ5kNuE04= -golang.org/x/crypto v0.43.0/go.mod h1:BFbav4mRNlXJL4wNeejLpWxB7wMbc79PdRGhWKncxR0= +golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q= +golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4= golang.org/x/exp v0.0.0-20231108232855-2478ac86f678 h1:mchzmB1XO2pMaKFRqk/+MV3mgGG96aqaPXaMifQU47w= golang.org/x/exp v0.0.0-20231108232855-2478ac86f678/go.mod h1:zk2irFbV9DP96SEBUUAy67IdHUaZuSnrz1n472HUCLE= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.7.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/mod v0.28.0 h1:gQBtGhjxykdjY9YhZpSlZIsbnaE2+PgjfLWUQTnoZ1U= -golang.org/x/mod v0.28.0/go.mod h1:yfB/L0NOf/kmEbXjzCPOx1iK1fRutOydrCMsqRhEBxI= +golang.org/x/mod v0.29.0 h1:HV8lRxZC4l2cr3Zq1LvtOsi/ThTgWnUk/y64QSs8GwA= +golang.org/x/mod v0.29.0/go.mod h1:NyhrlYXJ2H4eJiRy/WDBO6HMqZQ6q9nk4JzS3NuCK+w= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= @@ -530,8 +532,8 @@ golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwY golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.3.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE= -golang.org/x/net v0.46.0 h1:giFlY12I07fugqwPuWJi68oOnpfqFnJIJzaIIm2JVV4= -golang.org/x/net v0.46.0/go.mod h1:Q9BGdFy1y4nkUwiLvT5qtyhAnEHgnQ/zd8PfU6nc210= +golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY= +golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU= golang.org/x/oauth2 v0.33.0 h1:4Q+qn+E5z8gPRJfmRy7C2gGG3T4jIprK6aSYgTXGRpo= golang.org/x/oauth2 v0.33.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -563,8 +565,8 @@ golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc= golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= -golang.org/x/telemetry v0.0.0-20250908211612-aef8a434d053 h1:dHQOQddU4YHS5gY33/6klKjq7Gp3WwMyOXGNp5nzRj8= -golang.org/x/telemetry v0.0.0-20250908211612-aef8a434d053/go.mod h1:+nZKN+XVh4LCiA9DV3ywrzN4gumyCnKjau3NGb9SGoE= +golang.org/x/telemetry v0.0.0-20251008203120-078029d740a8 h1:LvzTn0GQhWuvKH/kVRS3R3bVAsdQWI7hvfLHGgh9+lU= +golang.org/x/telemetry v0.0.0-20251008203120-078029d740a8/go.mod h1:Pi4ztBfryZoJEkyFTI5/Ocsu2jXyDr6iSdgJiYE/uwE= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.3.0/go.mod h1:q750SLmJuPmVoN1blW3UFBPREJfb1KmY3vwxfr+nFDA= @@ -574,8 +576,8 @@ golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.30.0 h1:yznKA/E9zq54KzlzBEAWn1NXSQ8DIp/NYMy88xJjl4k= -golang.org/x/text v0.30.0/go.mod h1:yDdHFIX9t+tORqspjENWgzaCVXgk0yYnYuSZ8UzzBVM= +golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM= +golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM= golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI= golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -586,8 +588,8 @@ golang.org/x/tools v0.0.0-20200624163319-25775e59acb7/go.mod h1:EkVYQZoAsY45+roY golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.4.0/go.mod h1:UE5sM2OK9E/d67R0ANs2xJizIymRP5gJU295PvKXxjQ= -golang.org/x/tools v0.37.0 h1:DVSRzp7FwePZW356yEAChSdNcQo6Nsp+fex1SUW09lE= -golang.org/x/tools v0.37.0/go.mod h1:MBN5QPQtLMHVdvsbtarmTNukZDdgwdwlO5qGacAzF0w= +golang.org/x/tools v0.38.0 h1:Hx2Xv8hISq8Lm16jvBZ2VQf+RLmbd7wVUsALibYI/IQ= +golang.org/x/tools v0.38.0/go.mod h1:yEsQ/d/YK8cjh0L6rZlY8tgtlKiBNTL14pGDJPJpYQs= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= From 2e4817063d0d27509998099185cb41576bbfcd41 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Mon, 8 Dec 2025 16:51:03 +0000 Subject: [PATCH 517/647] remove tool metion from help text (#1230) --- cmd/src/main.go | 1 - 1 file changed, 1 deletion(-) diff --git a/cmd/src/main.go b/cmd/src/main.go index 9f8ba4ca33..edfb1073d7 100644 --- a/cmd/src/main.go +++ b/cmd/src/main.go @@ -63,7 +63,6 @@ The commands are: search search for results on Sourcegraph search-jobs manages search jobs serve-git serves your local git repositories over HTTP for Sourcegraph to pull - tool exposes tools for AI agents to interact with Sourcegraph (EXPERIMENTAL) users,user manages users codeowners manages code ownership information version display and compare the src-cli version against the recommended version for your instance From 718ec6dcda8181e0b34165eb9539ebf3572d0a5f Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Tue, 9 Dec 2025 10:47:18 +0000 Subject: [PATCH 518/647] feat(mcp): add script to dump mcp tool list (#1211) * add script to dump mcp tool list * parse mcp tool json * fix parsing for when items: true * use lib/errors * temporarily ignore embedded json * move mcp files to internal/mcp * unexport and remove unused structs * rename MCPToolDef to ToolDef and move around structs * rename parser + method to decoder + decode* * simplify types fold: Schema into SchemaObject * review comments * feat(mcp): build flagset from mcp input schema to parse args (#1215) - parse input schema to build flagset for mcp command * merge fixup * fix lint * fix imports --- cmd/src/config_list.go | 3 +- cmd/src/mcp.go | 121 ++++ internal/mcp/mcp_args.go | 94 +++ internal/mcp/mcp_args_test.go | 97 +++ internal/mcp/mcp_parse.go | 168 ++++++ internal/mcp/mcp_parse_test.go | 95 +++ internal/mcp/mcp_request.go | 93 +++ internal/mcp/mcp_tools.json | 1008 ++++++++++++++++++++++++++++++++ scripts/gen-mcp-tool-json.sh | 21 + 9 files changed, 1699 insertions(+), 1 deletion(-) create mode 100644 cmd/src/mcp.go create mode 100644 internal/mcp/mcp_args.go create mode 100644 internal/mcp/mcp_args_test.go create mode 100644 internal/mcp/mcp_parse.go create mode 100644 internal/mcp/mcp_parse_test.go create mode 100644 internal/mcp/mcp_request.go create mode 100644 internal/mcp/mcp_tools.json create mode 100755 scripts/gen-mcp-tool-json.sh diff --git a/cmd/src/config_list.go b/cmd/src/config_list.go index 04d172dbf9..ea09f8066f 100644 --- a/cmd/src/config_list.go +++ b/cmd/src/config_list.go @@ -4,8 +4,9 @@ import ( "flag" "fmt" + "context" + "github.com/sourcegraph/src-cli/internal/api" - "golang.org/x/net/context" ) func init() { diff --git a/cmd/src/mcp.go b/cmd/src/mcp.go new file mode 100644 index 0000000000..4510eb320f --- /dev/null +++ b/cmd/src/mcp.go @@ -0,0 +1,121 @@ +package main + +import ( + "context" + "encoding/json" + "flag" + "fmt" + "strings" + + "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/mcp" + + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +func init() { + flagSet := flag.NewFlagSet("mcp", flag.ExitOnError) + commands = append(commands, &command{ + flagSet: flagSet, + handler: mcpMain, + }) +} +func mcpMain(args []string) error { + fmt.Println("NOTE: This command is still experimental") + tools, err := mcp.LoadDefaultToolDefinitions() + if err != nil { + return err + } + + subcmd := args[0] + if subcmd == "list-tools" { + fmt.Println("The following tools are available:") + for name := range tools { + fmt.Printf(" • %s\n", name) + } + fmt.Println("\nUSAGE:") + fmt.Printf(" • Invoke a tool\n") + fmt.Printf(" src mcp \n") + fmt.Printf("\n • View the Input / Output Schema of a tool\n") + fmt.Printf(" src mcp schema\n") + fmt.Printf("\n • List the available flags of a tool\n") + fmt.Printf(" src mcp -h\n") + fmt.Printf("\n • View the Input / Output Schema of a tool\n") + fmt.Printf(" src mcp schema\n") + return nil + } + + tool, ok := tools[subcmd] + if !ok { + return fmt.Errorf("tool definition for %q not found - run src mcp list-tools to see a list of available tools", subcmd) + } + + flagArgs := args[1:] // skip subcommand name + if len(args) > 1 && args[1] == "schema" { + return printSchemas(tool) + } + + flags, vars, err := mcp.BuildArgFlagSet(tool) + if err != nil { + return err + } + if err := flags.Parse(flagArgs); err != nil { + return err + } + mcp.DerefFlagValues(vars) + + if err := validateToolArgs(tool.InputSchema, args, vars); err != nil { + return err + } + + apiClient := cfg.apiClient(nil, flags.Output()) + return handleMcpTool(context.Background(), apiClient, tool, vars) +} + +func printSchemas(tool *mcp.ToolDef) error { + input, err := json.MarshalIndent(tool.InputSchema, "", " ") + if err != nil { + return err + } + output, err := json.MarshalIndent(tool.OutputSchema, "", " ") + if err != nil { + return err + } + + fmt.Printf("Input:\n%v\nOutput:\n%v\n", string(input), string(output)) + return nil +} + +func validateToolArgs(inputSchema mcp.SchemaObject, args []string, vars map[string]any) error { + for _, reqName := range inputSchema.Required { + if vars[reqName] == nil { + return errors.Newf("no value provided for required flag --%s", reqName) + } + } + + if len(args) < len(inputSchema.Required) { + return errors.Newf("not enough arguments provided - the following flags are required:\n%s", strings.Join(inputSchema.Required, "\n")) + } + + return nil +} + +func handleMcpTool(ctx context.Context, client api.Client, tool *mcp.ToolDef, vars map[string]any) error { + resp, err := mcp.DoToolRequest(ctx, client, tool, vars) + if err != nil { + return err + } + + result, err := mcp.DecodeToolResponse(resp) + if err != nil { + return err + } + defer resp.Body.Close() + + output, err := json.MarshalIndent(result, "", " ") + if err != nil { + return err + } + fmt.Println(string(output)) + return nil +} diff --git a/internal/mcp/mcp_args.go b/internal/mcp/mcp_args.go new file mode 100644 index 0000000000..ecfb98e2b0 --- /dev/null +++ b/internal/mcp/mcp_args.go @@ -0,0 +1,94 @@ +package mcp + +import ( + "flag" + "fmt" + "reflect" + "strings" + + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +var _ flag.Value = (*strSliceFlag)(nil) + +type strSliceFlag struct { + vals []string +} + +func (s *strSliceFlag) Set(v string) error { + s.vals = append(s.vals, v) + return nil +} + +func (s *strSliceFlag) String() string { + return strings.Join(s.vals, ",") +} + +func DerefFlagValues(vars map[string]any) { + for k, v := range vars { + rfl := reflect.ValueOf(v) + if rfl.Kind() == reflect.Pointer { + vv := rfl.Elem().Interface() + if slice, ok := vv.(strSliceFlag); ok { + vv = slice.vals + } + if isNil(vv) { + delete(vars, k) + } else { + vars[k] = vv + } + } + } +} + +func isNil(v any) bool { + if v == nil { + return true + } + rv := reflect.ValueOf(v) + switch rv.Kind() { + case reflect.Slice, reflect.Map, reflect.Pointer, reflect.Interface: + return rv.IsNil() + default: + return false + } +} + +func BuildArgFlagSet(tool *ToolDef) (*flag.FlagSet, map[string]any, error) { + if tool == nil { + return nil, nil, errors.New("cannot build flagset on nil Tool Definition") + } + fs := flag.NewFlagSet(tool.Name, flag.ContinueOnError) + flagVars := map[string]any{} + + for name, pVal := range tool.InputSchema.Properties { + switch pv := pVal.(type) { + case *SchemaPrimitive: + switch pv.Type { + case "integer": + dst := fs.Int(name, 0, pv.Description) + flagVars[name] = dst + + case "boolean": + dst := fs.Bool(name, false, pv.Description) + flagVars[name] = dst + case "string": + dst := fs.String(name, "", pv.Description) + flagVars[name] = dst + default: + return nil, nil, fmt.Errorf("unknown schema primitive kind %q", pv.Type) + + } + case *SchemaArray: + strSlice := new(strSliceFlag) + fs.Var(strSlice, name, pv.Description) + flagVars[name] = strSlice + case *SchemaObject: + // TODO(burmudar): we can support SchemaObject as part of stdin echo '{ stuff }' | sg mcp commit-search + // not supported yet + // Also support sg mcp commit-search --json '{ stuff }' + } + } + + return fs, flagVars, nil +} diff --git a/internal/mcp/mcp_args_test.go b/internal/mcp/mcp_args_test.go new file mode 100644 index 0000000000..17d5b466e0 --- /dev/null +++ b/internal/mcp/mcp_args_test.go @@ -0,0 +1,97 @@ +package mcp + +import ( + "testing" +) + +func TestFlagSetParse(t *testing.T) { + toolJSON := []byte(`{ + "tools": [ + { + "name": "sg_test_tool", + "description": "test description", + "inputSchema": { + "type": "object", + "$schema": "https://localhost/schema-draft/2025-07", + "required": ["values"], + "properties": { + "repos": { + "type": "array", + "items": { + "type": "string" + } + }, + "tag": { + "type": "string", + "items": true + }, + "count": { + "type": "integer" + }, + "boolFlag": { + "type": "boolean" + } + } + }, + "outputSchema": { + "type": "object", + "$schema": "https://localhost/schema-draft/2025-07", + "properties": { + "result": { "type": "string" } + } + } + } + ] + }`) + + defs, err := loadToolDefinitions(toolJSON) + if err != nil { + t.Fatalf("failed to load tool json: %v", err) + } + + flagSet, vars, err := BuildArgFlagSet(defs["test-tool"]) + if err != nil { + t.Fatalf("failed to build flagset from mcp tool definition: %v", err) + } + + if len(vars) == 0 { + t.Fatalf("vars from buildArgFlagSet should not be empty") + } + + args := []string{"-repos=A", "-repos=B", "-count=10", "-boolFlag", "-tag=testTag"} + + if err := flagSet.Parse(args); err != nil { + t.Fatalf("flagset parsing failed: %v", err) + } + DerefFlagValues(vars) + + if v, ok := vars["repos"].([]string); ok { + if len(v) != 2 { + t.Fatalf("expected flag 'repos' values to have length %d but got %d", 2, len(v)) + } + } else { + t.Fatalf("expected flag 'repos' to have type of []string but got %T", v) + } + if v, ok := vars["tag"].(string); ok { + if v != "testTag" { + t.Fatalf("expected flag 'tag' values to have value %q but got %q", "testTag", v) + } + } else { + t.Fatalf("expected flag 'tag' to have type of string but got %T", v) + } + if v, ok := vars["count"].(int); ok { + if v != 10 { + t.Fatalf("expected flag 'count' values to have value %d but got %d", 10, v) + } + } else { + t.Fatalf("expected flag 'count' to have type of int but got %T", v) + } + if v, ok := vars["boolFlag"].(bool); ok { + if v != true { + t.Fatalf("expected flag 'boolFlag' values to have value %v but got %v", true, v) + } + } else { + t.Fatalf("expected flag 'boolFlag' to have type of bool but got %T", v) + } + +} diff --git a/internal/mcp/mcp_parse.go b/internal/mcp/mcp_parse.go new file mode 100644 index 0000000000..31243fee70 --- /dev/null +++ b/internal/mcp/mcp_parse.go @@ -0,0 +1,168 @@ +package mcp + +import ( + _ "embed" + "encoding/json" + "strings" + + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +//go:embed mcp_tools.json +var mcpToolListJSON []byte + +type ToolDef struct { + Name string + RawName string `json:"name"` + Description string `json:"description"` + InputSchema SchemaObject `json:"inputSchema"` + OutputSchema SchemaObject `json:"outputSchema"` +} + +type rawSchema struct { + Type string `json:"type"` + Description string `json:"description"` + Required []string `json:"required,omitempty"` + Properties map[string]json.RawMessage `json:"properties"` + Items json.RawMessage `json:"items"` +} + +type SchemaValue interface { + ValueType() string +} + +type SchemaObject struct { + Type string `json:"type"` + Description string `json:"description"` + Required []string `json:"required,omitempty"` + Properties map[string]SchemaValue `json:"properties"` + + // two fields which we do not use from the schema: + // - $schema + // - additionalPropterties +} + +func (s SchemaObject) ValueType() string { return s.Type } + +type SchemaArray struct { + Type string `json:"type"` + Description string `json:"description"` + Items SchemaValue `json:"items,omitempty"` +} + +func (s SchemaArray) ValueType() string { return s.Type } + +type SchemaPrimitive struct { + Type string `json:"type"` + Description string `json:"description"` +} + +func (s SchemaPrimitive) ValueType() string { return s.Type } + +type decoder struct { + errors []error +} + +func LoadDefaultToolDefinitions() (map[string]*ToolDef, error) { + return loadToolDefinitions(mcpToolListJSON) +} + +func loadToolDefinitions(data []byte) (map[string]*ToolDef, error) { + defs := struct { + Tools []struct { + Name string `json:"name"` + Description string `json:"description"` + InputSchema rawSchema `json:"inputSchema"` + OutputSchema rawSchema `json:"outputSchema"` + } `json:"tools"` + }{} + + if err := json.Unmarshal(data, &defs); err != nil { + return nil, err + } + + tools := map[string]*ToolDef{} + decoder := &decoder{} + + for _, t := range defs.Tools { + // normalize the raw mcp tool name to be without the mcp identifiers + rawName := t.Name + name, _ := strings.CutPrefix(rawName, "sg_") + name = strings.ReplaceAll(name, "_", "-") + + tool := &ToolDef{ + Name: name, + RawName: rawName, + Description: t.Description, + InputSchema: decoder.decodeRootSchema(t.InputSchema), + OutputSchema: decoder.decodeRootSchema(t.OutputSchema), + } + tools[tool.Name] = tool + } + + if len(decoder.errors) > 0 { + return tools, errors.Append(nil, decoder.errors...) + } + + return tools, nil +} + +func (d *decoder) decodeRootSchema(r rawSchema) SchemaObject { + return SchemaObject{ + Type: r.Type, + Description: r.Description, + Required: r.Required, + Properties: d.decodeProperties(r.Properties), + } +} + +func (d *decoder) decodeSchema(r *rawSchema) SchemaValue { + switch r.Type { + case "object": + return &SchemaObject{ + Type: r.Type, + Description: r.Description, + Required: r.Required, + Properties: d.decodeProperties(r.Properties), + } + case "array": + var items SchemaValue + if len(r.Items) > 0 { + var boolItems bool + if err := json.Unmarshal(r.Items, &boolItems); err == nil { + // Sometimes items is defined as "items: true", so we handle it here and + // consider it "empty" array + } else { + var itemRaw rawSchema + if err := json.Unmarshal(r.Items, &itemRaw); err == nil { + items = d.decodeSchema(&itemRaw) + } else { + d.errors = append(d.errors, errors.Wrap(err, "failed to unmarshal array items")) + } + } + } + return &SchemaArray{ + Type: r.Type, + Description: r.Description, + Items: items, + } + default: + return &SchemaPrimitive{ + Type: r.Type, + Description: r.Description, + } + } +} + +func (d *decoder) decodeProperties(props map[string]json.RawMessage) map[string]SchemaValue { + res := make(map[string]SchemaValue) + for name, raw := range props { + var r rawSchema + if err := json.Unmarshal(raw, &r); err != nil { + d.errors = append(d.errors, errors.Wrapf(err, "failed to parse property %q: %w", name)) + continue + } + res[name] = d.decodeSchema(&r) + } + return res +} diff --git a/internal/mcp/mcp_parse_test.go b/internal/mcp/mcp_parse_test.go new file mode 100644 index 0000000000..ecaf691d16 --- /dev/null +++ b/internal/mcp/mcp_parse_test.go @@ -0,0 +1,95 @@ +package mcp + +import ( + "testing" +) + +func TestLoadToolDefinitions(t *testing.T) { + toolJSON := []byte(`{ + "tools": [ + { + "name": "test_tool", + "description": "test description", + "inputSchema": { + "type": "object", + "$schema": "https://localhost/schema-draft/2025-07", + "properties": { + "tags": { + "type": "array", + "items": { + "type": "object", + "properties": { + "key": { "type": "string" }, + "value": { "type": "string" } + } + } + } + } + }, + "outputSchema": { + "type": "object", + "$schema": "https://localhost/schema-draft/2025-07", + "properties": { + "result": { "type": "string" } + } + } + } + ] + }`) + + tools, err := loadToolDefinitions(toolJSON) + if err != nil { + t.Fatalf("Failed to load tool definitions: %v", err) + } + + if len(tools) != 1 { + t.Fatalf("Expected 1 tool, got %d", len(tools)) + } + + tool := tools["test-tool"] + if tool == nil { + t.Fatal("Tool 'test_tool' not found") + } + + if tool.RawName != "test_tool" { + t.Errorf("Expected name 'test_tool', got '%s'", tool.RawName) + } + + inputSchema := tool.InputSchema + + if len(tool.OutputSchema.Properties) == 0 { + t.Fatalf("expected tool.OutputSchema.Properties not be empty") + } + + tagsProp, ok := inputSchema.Properties["tags"] + if !ok { + t.Fatal("Property 'tags' not found in inputSchema") + } + + if tagsProp.ValueType() != "array" { + t.Errorf("Expected tags type 'array', got '%s'", tagsProp.ValueType()) + } + + arraySchema, ok := tagsProp.(*SchemaArray) + if !ok { + t.Fatal("Expected SchemaArray for tags") + } + + if arraySchema.Items == nil { + t.Fatal("Expected items schema in array, got nil") + } + + itemSchema := arraySchema.Items + if itemSchema.ValueType() != "object" { + t.Errorf("Expected item type 'object', got '%s'", itemSchema.ValueType()) + } + + objectSchema, ok := itemSchema.(*SchemaObject) + if !ok { + t.Fatal("Expected SchemaObject for item") + } + + if _, ok := objectSchema.Properties["key"]; !ok { + t.Error("Property 'key' not found in item schema") + } +} diff --git a/internal/mcp/mcp_request.go b/internal/mcp/mcp_request.go new file mode 100644 index 0000000000..dbcb0ed97b --- /dev/null +++ b/internal/mcp/mcp_request.go @@ -0,0 +1,93 @@ +package mcp + +import ( + "bytes" + "context" + "encoding/json" + "io" + "net/http" + + "github.com/sourcegraph/src-cli/internal/api" + + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +const McpURLPath = ".api/mcp/v1" + +func DoToolRequest(ctx context.Context, client api.Client, tool *ToolDef, vars map[string]any) (*http.Response, error) { + jsonRPC := struct { + Version string `json:"jsonrpc"` + ID int `json:"id"` + Method string `json:"method"` + Params any `json:"params"` + }{ + Version: "2.0", + ID: 1, + Method: "tools/call", + Params: struct { + Name string `json:"name"` + Arguments map[string]any `json:"arguments"` + }{ + Name: tool.RawName, + Arguments: vars, + }, + } + + buf := bytes.NewBuffer(nil) + data, err := json.Marshal(jsonRPC) + if err != nil { + return nil, err + } + buf.Write(data) + + req, err := client.NewHTTPRequest(ctx, http.MethodPost, McpURLPath, buf) + if err != nil { + return nil, err + } + req.Header.Add("Content-Type", "application/json") + req.Header.Add("Accept", "*/*") + + return client.Do(req) +} + +func DecodeToolResponse(resp *http.Response) (map[string]json.RawMessage, error) { + data, err := readSSEResponseData(resp) + if err != nil { + return nil, err + } + + if data == nil { + return map[string]json.RawMessage{}, nil + } + + jsonRPCResp := struct { + Version string `json:"jsonrpc"` + ID int `json:"id"` + Result struct { + Content []json.RawMessage `json:"content"` + StructuredContent map[string]json.RawMessage `json:"structuredContent"` + } `json:"result"` + }{} + if err := json.Unmarshal(data, &jsonRPCResp); err != nil { + return nil, errors.Wrapf(err, "failed to unmarshal MCP JSON-RPC response") + } + + return jsonRPCResp.Result.StructuredContent, nil +} +func readSSEResponseData(resp *http.Response) ([]byte, error) { + data, err := io.ReadAll(resp.Body) + if err != nil { + return nil, err + } + // The response is an SSE reponse + // event: + // data: + lines := bytes.SplitSeq(data, []byte("\n")) + for line := range lines { + if jsonData, ok := bytes.CutPrefix(line, []byte("data: ")); ok { + return jsonData, nil + } + } + return nil, errors.New("no data found in SSE response") + +} diff --git a/internal/mcp/mcp_tools.json b/internal/mcp/mcp_tools.json new file mode 100644 index 0000000000..e38eba472d --- /dev/null +++ b/internal/mcp/mcp_tools.json @@ -0,0 +1,1008 @@ +{ + "tools": [ + { + "description": "This is a Sourcegraph search tool and is best used with other sourcegraph search tools. A commit search tool.\nSearch for commits in the repository. Find who made changes, when features were implemented, or track code history.\n\nKey features:\n- Search commit messages for relevant terms\n- Find commits by specific authors\n- Search for changes containing specific code\n- Filter by file paths or repository\n- Filter by date ranges with before/after\n- Regex pattern support\n\nLogic: All parameter types are combined with AND, but within each parameter type, multiple values use OR.\nExample: messageTerms=[\"bug\",\"fix\"] + authors=[\"jane\"] finds commits by jane with \"bug\" OR \"fix\" in message.\n\nExamples:\n\n \n Search for commits mentioning 'implement feature' or 'create feature' in the message\n calls the commit search tool with messageTerms=[\"implement feature\", \"create feature\"] repos=[\"github.com/myorg/repo\"]\n \n\t\n Search for commits that added pandas imports\n calls the commit search tool with contentTerms=[\"import pandas\"] repos=[\"github.com/myorg/repo\"]\n \n \n Find commits by jane.doe that changed files in the ui/components directory\n calls the commit search tool with authors=[\"jane.doe\"] files=[\"ui/components/**\"] repos=[\"github.com/myorg/frontend\"]\n \n \n Find changes to authentication code in May 2025\n calls the commit search tool with contentTerms=[\"auth\"] repos=[\"github.com/myorg/auth-service\", \"github.com/myorg/user-service\"] after=\"2025-05-01\" before=\"2025-05-31\"\n \n \n What has John been working on for the past month?\n calls the commit search tool with authors=[\"John\"] repos=[\"github.com/myorg/repo1\", \"github.com/myorg/repo2\"] after=\"1 month ago\"\n \n", + "inputSchema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "repos" + ], + "properties": { + "after": { + "type": "string", + "description": "Search for commits after this date. Supports various formats including structured dates (e.g. \"YYYY-MM-DD\" or \"MM/DD/YYYY\", or \"november 2023\") and natural language (e.g. \"1 month ago\", \"last week\", or \"yesterday\")" + }, + "authors": { + "type": "array", + "description": "Authors to filter by. Multiple authors will be combined with OR logic.", + "items": { + "type": "string" + } + }, + "before": { + "type": "string", + "description": "Search for commits before this date. Supports various formats including structured dates (e.g. \"YYYY-MM-DD\", \"MM/DD/YYYY\", or \"november 2023\") and natural language (e.g. \"1 month ago\", \"last week\", or \"yesterday\")" + }, + "contentTerms": { + "type": "array", + "description": "Code content terms to search for in the actual changes. Multiple terms will be combined with OR logic.", + "items": { + "type": "string" + } + }, + "count": { + "type": "integer", + "description": "Maximum number of results to return" + }, + "files": { + "type": "array", + "description": "File paths to filter by. Multiple files will be combined with OR logic.", + "items": { + "type": "string" + } + }, + "messageTerms": { + "type": "array", + "description": "Terms to search for in commit messages. Multiple terms will be combined with OR logic by default.", + "items": { + "type": "string" + } + }, + "repos": { + "type": "array", + "description": "REQUIRED: Repositories to search in (e.g., [\"github.com/gohugoio/hugo\"] or [\"repo1\", \"repo2\"]). Multiple repositories will be combined with OR logic.", + "items": { + "type": "string" + } + }, + "useRegex": { + "type": "boolean", + "description": "Use regular expressions for searching (default: false)" + } + }, + "additionalProperties": false + }, + "name": "sg_commit_search", + "outputSchema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "query", + "totalCount", + "commits", + "limitHit" + ], + "properties": { + "commits": { + "type": "array", + "items": { + "type": "object", + "required": [ + "repository", + "commit", + "author", + "date", + "title", + "message" + ], + "properties": { + "author": { + "type": "string" + }, + "commit": { + "type": "string" + }, + "date": { + "type": "string" + }, + "message": { + "type": "string" + }, + "repository": { + "type": "string" + }, + "title": { + "type": "string" + } + }, + "additionalProperties": false + } + }, + "limitHit": { + "type": "boolean" + }, + "query": { + "type": "string" + }, + "totalCount": { + "type": "integer" + } + }, + "additionalProperties": false + } + }, + { + "description": "This is a Sourcegraph search tool and is best used with other sourcegraph search tools. A tool that compares changes between two specific revisions in a repository.\nUse this tool when you need to:\n- Compare changes between two versions (commits, branches, tags) in a single repository\n- View specific file changes between revisions in detail\n- Examine code differences in a pull request, branch or commit\n- See all files modified between two specific points in a repository\n\nTips for effective revision comparison:\n- Use specific revisions for precise comparisons\n- For very large diffs, start with a smaller \"first\" value (e.g., 5) to preview changes\n- For comparing across branches, use the branch names directly\n- To see changes from a specific commit, use commitHash~1 as base and commitHash as head\n- Use \"after\" with the provided endCursor value to paginate through large diffs\n\nExamples:\n\n \n What changed in commit abc123 in the github.com/django/django repository?\n calls the compare revisions tool with repo=\"github.com/django/django\" base=\"abc123~1\" head=\"abc123\"\n \n \n Compare the feature-auth branch with main in the github.com/microsoft/vscode repository\n calls the compare revisions tool with repo=\"github.com/microsoft/vscode\" base=\"main\" head=\"feature-auth\"\n \n \n Show me all file changes between commits abc123 and def456 in kubernetes\n calls the compare revisions tool with repo=\"github.com/kubernetes/kubernetes\" base=\"abc123\" head=\"def456\"\n \n \n What files were modified in the last 3 commits on main branch of the rails repo?\n calls the compare revisions tool with repo=\"github.com/rails/rails\" base=\"main~3\" head=\"main\"\n \n", + "inputSchema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "repo", + "base", + "head" + ], + "properties": { + "after": { + "type": "string", + "description": "Pagination cursor for fetching more results" + }, + "base": { + "type": "string", + "description": "The base revision (older version, e.g., \"main~5\", a commit hash, or a tag)" + }, + "first": { + "type": "integer", + "description": "Maximum number of file diffs to return (default: 50, max: 100)" + }, + "head": { + "type": "string", + "description": "The head revision (newer version, e.g., \"main\", a commit hash, or a tag)" + }, + "repo": { + "type": "string", + "description": "The repository name to compare revisions in (e.g., \"github.com/grafana/loki\")" + } + }, + "additionalProperties": false + }, + "name": "sg_compare_revisions", + "outputSchema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "repository", + "base", + "head", + "totalAdded", + "totalDeleted", + "totalModified", + "files", + "hasNextPage", + "endCursor" + ], + "properties": { + "base": { + "type": "string" + }, + "endCursor": { + "type": "string" + }, + "files": { + "type": "array", + "items": { + "type": "object", + "required": [ + "path", + "added", + "deleted" + ], + "properties": { + "added": { + "type": "integer" + }, + "deleted": { + "type": "integer" + }, + "hunks": { + "type": "array", + "items": { + "type": "object", + "required": [ + "oldRange", + "newRange", + "body" + ], + "properties": { + "body": { + "type": "string" + }, + "newRange": { + "type": "object", + "required": [ + "startLine", + "lines" + ], + "properties": { + "lines": { + "type": "integer" + }, + "startLine": { + "type": "integer" + } + }, + "additionalProperties": false + }, + "oldRange": { + "type": "object", + "required": [ + "startLine", + "lines" + ], + "properties": { + "lines": { + "type": "integer" + }, + "startLine": { + "type": "integer" + } + }, + "additionalProperties": false + }, + "section": { + "type": "string" + } + }, + "additionalProperties": false + } + }, + "path": { + "type": "string" + } + }, + "additionalProperties": false + } + }, + "hasNextPage": { + "type": "boolean" + }, + "head": { + "type": "string" + }, + "repository": { + "type": "string" + }, + "totalAdded": { + "type": "integer" + }, + "totalDeleted": { + "type": "integer" + }, + "totalModified": { + "type": "integer" + } + }, + "additionalProperties": false + } + }, + { + "description": "\nCreate a new deep search conversation to answer complex questions about your codebase.\n\nPowered by an agentic LLM, this deep research tool performs an in-depth investigation of your codebase\n- Performs comprehensive analysis of your question\n- Uses multiple search and analysis tools automatically\n- Provides detailed, well-researched answers with evidence\n- Generates related follow-up suggestions\n\nUse this tool when you need:\n- Comprehensive analysis of complex technical questions\n- Multi-step research across one or many remote codebases\n- Detailed explanations with supporting evidence\n- Questions that require combining information from multiple sources\n\nExamples:\n\n\n\tHow does authentication work in this codebase?\n\tcalls the deep search tool with question: \"How does authentication work in this codebase?\"\n\n\n\tFind all the security vulnerabilities related to user input validation\n\tcalls the deep search tool with question: \"Find all the security vulnerabilities related to user input validation\"\n\n\n\tExplain the architecture and data flow of the payment processing system\n\tcalls the deep search tool with question: \"Explain the architecture and data flow of the payment processing system\"\n\n", + "inputSchema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "question" + ], + "properties": { + "question": { + "type": "string", + "description": "The question to research using deep search. Should be detailed and specific about what you want to understand." + } + }, + "additionalProperties": false + }, + "name": "sg_deepsearch", + "outputSchema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "conversation_id", + "question_id" + ], + "properties": { + "answer": { + "type": "string", + "description": "The answer generated by the deep search tool." + }, + "conversation_id": { + "type": "integer", + "description": "The ID of the conversation that was created to process the question. Can be used for follow-up questions" + }, + "error": { + "type": "object", + "description": "Any error that occurred during the deep search process.", + "required": [ + "title", + "kind", + "message" + ], + "properties": { + "details": { + "type": "string" + }, + "kind": { + "type": "string" + }, + "message": { + "type": "string" + }, + "title": { + "type": "string" + } + }, + "additionalProperties": false + }, + "link": { + "type": "string", + "description": "A link to the deep search conversation app." + }, + "question_id": { + "type": "integer", + "description": "The globally unique ID of the question that was processed." + }, + "suggested_followups": { + "type": "array", + "description": "Suggested follow-up questions based on the deep search result.", + "items": { + "type": "string" + } + }, + "title": { + "type": "string", + "description": "The title or summary of the deep search result." + } + }, + "additionalProperties": false + } + }, + { + "description": "This is a Sourcegraph search tool and is best used with other sourcegraph search tools. A tool that searches for code changes (diffs) across multiple repositories.\nThis tool searches ONLY the actual code changes (added/removed lines), not commit messages.\n\nUse this tool when you need to:\n- Find specific code patterns that were added or removed across repositories\n- Search for keywords in code changes across multiple repositories\n- Find changes related to specific features or bugs\n\nTips for effective diff searches:\n- Use the 'repos' parameter to focus your search on specific repositories\n- Use 'after' and 'before' to define a time range for the changes\n- Use 'pattern' to specify what you're looking for in the changed code\n- Add 'useRegex: true' for more complex search patterns\n- Use 'added: true' or 'removed: true' to search only in added or removed code\n\nExamples:\n\n \n Find instances where console.log was added across our repos in the past month\n calls the diff search tool with pattern=\"console.log\" after=\"1 month ago\" added=true\n \n \n Search for any hardcoded passwords that were removed in our backend services\n calls the diff search tool with pattern=\"password.*=\" repos=[\"github.com/myorg/backend*\"] removed=true useRegex=true\n \n \n Look for recent changes that mention 'API key' across all our microservices\n calls the diff search tool with pattern=\"API key\" repos=[\"github.com/myorg/service-*\"] after=\"2 weeks ago\"\n \n \n Find security-related code changes by author john.doe in the last quarter\n calls the diff search tool with pattern=\"security|auth|login\" author=\"john.doe\" after=\"3 months ago\" useRegex=true\n \n \n Search for any database connection changes across all repositories recently\n calls the diff search tool with pattern=\"database|db_connect|connection\" after=\"1 week ago\" useRegex=true\n \n", + "inputSchema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "pattern", + "repos" + ], + "properties": { + "added": { + "type": "boolean", + "description": "If true, only search in added code (default: search in both added and removed code)" + }, + "after": { + "type": "string", + "description": "Only include results from changes after this time (e.g., \"2 weeks ago\", \"2023-01-01\")" + }, + "author": { + "type": "string", + "description": "Filter by the author of the changes (e.g., \"username\")" + }, + "before": { + "type": "string", + "description": "Only include results from changes before this time (e.g., \"1 week ago\", \"2023-12-31\")" + }, + "count": { + "type": "integer", + "description": "Maximum number of results to return" + }, + "pattern": { + "type": "string", + "description": "The search pattern to look for in diff content (code changes, actual added/removed lines)" + }, + "removed": { + "type": "boolean", + "description": "If true, only search in removed code (default: search in both added and removed code)" + }, + "repos": { + "type": "array", + "description": "REQUIRED: Array of repository patterns to search in (e.g., [\"github.com/myorg/repo\", \"github.com/otherorg/*\"]). Multiple repositories will be combined with OR logic.", + "items": { + "type": "string" + } + }, + "useRegex": { + "type": "boolean", + "description": "Use regular expressions for searching (default: false)" + } + }, + "additionalProperties": false + }, + "name": "sg_diff_search", + "outputSchema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "query", + "results", + "totalCount", + "limitHit" + ], + "properties": { + "limitHit": { + "type": "boolean" + }, + "query": { + "type": "string" + }, + "results": { + "type": "array", + "items": { + "type": "object", + "required": [ + "repository", + "commit", + "diffHunk", + "url", + "matchRanges" + ], + "properties": { + "authorName": { + "type": "string" + }, + "commit": { + "type": "string" + }, + "diffHunk": { + "type": "string" + }, + "matchRanges": { + "type": "array", + "items": { + "type": "object", + "required": [ + "startLine", + "endLine", + "startCharacter", + "endCharacter" + ], + "properties": { + "endCharacter": { + "type": "integer" + }, + "endLine": { + "type": "integer" + }, + "startCharacter": { + "type": "integer" + }, + "startLine": { + "type": "integer" + } + }, + "additionalProperties": false + } + }, + "message": { + "type": "string" + }, + "repository": { + "type": "string" + }, + "url": { + "type": "string" + } + }, + "additionalProperties": false + } + }, + "totalCount": { + "type": "integer" + } + }, + "additionalProperties": false + } + }, + { + "description": "This is a Sourcegraph search tool and is best used with other sourcegraph search tools. Finds references to a provided symbol in a repository.\nA symbol is any code identifier, such as a function name, variable name, or class name.\nIt handles overloading by leveraging compiler information to ensure references are to the exact symbol requested. It can even handle cross-repository references.\n\nReturns a list of usages of that symbol, specifically:\n- Where the symbol is referenced in the code\n- The file and line number of each reference\n- Surrounding context of each reference to help understand its usage\nIf the symbol is not found, returns \"Symbol not found\"\n\nThis tool is the opposite of the sg_go_to_definition tool - it finds references (usages) to a symbol given its definition.\n\nYou should use this tool when you have a specific symbol in mind (function, method, variable, class, etc.), you know where it is defined (a file path) and want to see where it is referenced / used in the codebase.\n\nYou should choose to use this tool over sg_keyword_search, sg_nls_search or sg_read_file when you have encountered the definition of a specific symbol (function, variable, class)\nand you want to see how that specific symbol is used throughout the codebase, understand code flow or performing impact analysis.\n\nExamples:\n\n\t\n\t\tFind where the AbstractPaymentProcessorClass is used. It's defined in src/processors/AbstractPaymentProcessor.ts in the ecommerce/payment-service repository.\n\t\t [calls the find references tool with repo=\"ecommerce/payment-service\", path=\"src/processors/AbstractPaymentProcessor.ts\", symbol=\"AbstractPaymentProcessor\"]\n\t\t {\n \"repo\": \"ecommerce/payment-service\",\n \"path\": \"src/processors/StripePaymentProcessor.ts\",\n \"rev\": \"HEAD\",\n \"chunks\": [\n\t\t\t\t\t{\n\t\t\t\t\t\t\"startLine\": 2,\n\t\t\t\t\t\t\"endLine\": 2,\n\t\t\t\t\t\t\"content\": \"2: import { AbstractPaymentProcessor } from './AbstractPaymentProcessor';\\n\"\n\t\t\t\t\t},\n {\n \"startLine\": 102,\n \"endLine\": 103,\n \"content\": \"102: class StripePaymentProcessor extends AbstractPaymentProcessor {\\n103: \\tprivate readonly Status status;\\n\"\n }\n ]\n }\n\t\t\n\t\n", + "inputSchema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "repo", + "path", + "symbol" + ], + "properties": { + "path": { + "type": "string", + "description": "The path to the file within the repository containing the symbol reference, e.g. \"src/utils/date.ts\"." + }, + "repo": { + "type": "string", + "description": "The name of the repository containing the file, e.g. \"github.com/tuckersoft/thronglets\"." + }, + "revision": { + "type": "string", + "description": "The revision or branch to find references in. If not specified, defaults to the HEAD of the default branch." + }, + "symbol": { + "type": "string", + "description": "The name of the symbol (function name, method name, class, variable, constant, etc) to find references for, e.g. \"handleSearch\"." + } + }, + "additionalProperties": false + }, + "name": "sg_find_references", + "outputSchema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "fileBlocks" + ], + "properties": { + "fileBlocks": { + "type": "array", + "items": { + "type": "object", + "required": [ + "type", + "repo", + "file", + "chunks" + ], + "properties": { + "chunks": { + "type": "array", + "items": { + "type": "object", + "required": [ + "startLine", + "endLine", + "content" + ], + "properties": { + "content": { + "type": "string" + }, + "endLine": { + "type": "integer" + }, + "startLine": { + "type": "integer" + } + }, + "additionalProperties": false + } + }, + "file": { + "type": "string" + }, + "repo": { + "type": "string" + }, + "rev": { + "type": "string" + }, + "type": { + "type": "string" + } + }, + "additionalProperties": false + } + } + }, + "additionalProperties": false + } + }, + { + "description": "This is a Sourcegraph search tool and is best used with other sourcegraph search tools. Find repositories where a specific contributor has made commits.\nThis tool helps identify which repositories a person has contributed to, making it useful for scoping commit searches.\n\nUse this tool when you need to:\n- Find all repositories a person has worked on\n- Scope commit or diff searches to relevant repositories\n- Understand a contributor's involvement across the codebase\n\nThe tool searches by author name or email address and returns repositories with contribution statistics.\n\nExamples:\n\n\t\n\t\tWhat repositories has Jim contributed to?\n\t\tcalls get contributor repos tool with author=\"Jim\"\n\t\n\t\n\t\tWhat has john.doe@company.com been working on?\n\t\tcalls get contributor repos tool with author=\"john.doe@company.com\"\n\t\n", + "inputSchema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "author" + ], + "properties": { + "author": { + "type": "string", + "description": "Author name or email address to search for. Case-insensitive partial matching (e.g., \"john\" will match \"john.doe@company.com\" and \"John Smith\")." + }, + "limit": { + "type": "integer", + "description": "Maximum number of repositories to return. Defaults to 20, max 100." + }, + "minCommits": { + "type": "integer", + "description": "Minimum number of commits the author must have in a repository to include it. Defaults to 1." + } + }, + "additionalProperties": false + }, + "name": "sg_get_contributor_repos", + "outputSchema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "repositories" + ], + "properties": { + "repositories": { + "type": "array", + "items": { + "type": "object", + "required": [ + "repoName", + "repoCommitCount", + "repoMostRecentCommitDate" + ], + "properties": { + "repoCommitCount": { + "type": "integer" + }, + "repoMostRecentCommitDate": { + "type": "string" + }, + "repoName": { + "type": "string" + } + }, + "additionalProperties": false + } + } + }, + "additionalProperties": false + } + }, + { + "description": "This is a Sourcegraph search tool and is best used with other sourcegraph search tools. Finds the definition of a specified symbol in a repository.\nThis tool can leverage compiler-level symbol information to provide accurate results and can handle cross-repository references.\n\nA symbol is any code identifier, such as a function or method name, variable name, or class name such as 'MyClass' or 'readFile'.\nThe symbol name should be the identifier as it appears in code (e.g., 'validateToken', 'MyClass', 'API_ENDPOINT').\nFor methods, use just the method name without the class prefix.\nFor nested symbols, use the simple name rather than fully qualified paths.\n\nThe tool will return the code snippet containing the definition of the symbol in the codebase, as well as its location - the file name and line number.\nIt will return up to 50 lines of the code snippet containing the definition of the symbol.\n\nThis tool is the opposite of the sg_find_references tool - it finds the definition to a symbol given a reference/usage symbol.\n\nYou should use this tool when you have a specific symbol in mind (function, method, variable, class, etc.), you know where it is used (a file path) and want to see its definition in the codebase.\n\nYou should choose to use this tool over sg_keyword_search, sg_nls_search or sg_read_file when you have encountered a specific symbol (function, method, variable, class, etc.)\nthat you want to understand better by seeing its definition.\n\nExamples:\n\n \n I'm working in the auth-service/backend repo, in the file src/middleware/authMiddleware.js. This code calls await validateToken(session, token). Where is the function validateToken defined?\n [calls the go to definition tool with repo=\"auth-service/backend\", path=\"src/middleware/authMiddleware.js\", symbol=\"validateToken\"]\n {\n \"repo\": \"auth-service/backend\",\n \"path\": \"src/middleware/validation.js\",\n \"rev\": \"HEAD\",\n \"chunks\": [\n {\n \"startLine\": 12,\n \"endLine\": 62,\n \"content\": \"12: function validateToken(session, token) { ... }\"\n }\n ]\n }\n \n \n", + "inputSchema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "repo", + "path", + "symbol" + ], + "properties": { + "path": { + "type": "string", + "description": "The path to the file within the repository containing the symbol reference." + }, + "repo": { + "type": "string", + "description": "The name of the repository containing the file. For example, \"github.com/burntsushi/ripgrep\"." + }, + "revision": { + "type": "string", + "description": "The revision or branch to find the definition in. If not specified, defaults to the HEAD of the default branch." + }, + "symbol": { + "type": "string", + "description": "The name of the symbol to find the definition for." + } + }, + "additionalProperties": false + }, + "name": "sg_go_to_definition", + "outputSchema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "fileBlocks" + ], + "properties": { + "fileBlocks": { + "type": "array", + "items": { + "type": "object", + "required": [ + "type", + "repo", + "file", + "chunks" + ], + "properties": { + "chunks": { + "type": "array", + "items": { + "type": "object", + "required": [ + "startLine", + "endLine", + "content" + ], + "properties": { + "content": { + "type": "string" + }, + "endLine": { + "type": "integer" + }, + "startLine": { + "type": "integer" + } + }, + "additionalProperties": false + } + }, + "file": { + "type": "string" + }, + "repo": { + "type": "string" + }, + "rev": { + "type": "string" + }, + "type": { + "type": "string" + } + }, + "additionalProperties": false + } + } + }, + "additionalProperties": false + } + }, + { + "description": "This is a Sourcegraph search tool and is best used with other sourcegraph search tools. \nA keyword code search tool that helps you find relevant code snippets across repositories. Use this tool when you need to:\n- Find specific code with exact matching\n- Verify if certain code exists in the codebase\n- Find examples of code usage\n\nSearch capabilities:\n- Basic search: Enter keywords to find code containing those terms\n- Boolean search: Use AND/OR operators to combine terms. By default, all search terms are combined with AND, meaning that all search terms must match for a result to be included.\n- Filters:\n\t* repo: to search specific repositories (supports regex) Example: repo:github.com/google will select all repositories with the matching prefix (github.com/google-gemini/cookbook and github.com/google/neuroglancer both match). Use ^ to match the start of the string and $ to match the end of the string to avoid unwanted matches. You can chain multiple repo filters with OR while putting them in parentheses.\n\t* file: to search specific file patterns (supports regex) Example: file:README.md will only search files that have README.md in their name. file:.*.ts will search all files with a .ts extension.\n\t* rev: to search specific revisions (branches, tags, commits/sha). MUST always be used together with a repo: filter. Example: repo:^foo/bar$ rev:feat/xyz will only search the branch feat/xyz of the repo foo/bar. If not specified, defaults to the HEAD of the default branch.\n\nWhen not to use this tool:\n- For semantic or conceptual searches like 'authentication implementation'\n- For queries that are similar to natural language like \"API calls to middleware in admin panel\".\n- When you are not sure if the term exists in the codebase.\n- For queries with several search terms.\n- For exploratory searching of the codebase, when you are not sure what a certain term or name means.\nImportant: In these cases, use the sg_nls_search tool instead.\n\nBest practices:\n- Use a small (1-3) number of search terms. Because we combine terms with AND by default, using too many terms may result in no results.\n- Use specific, descriptive search terms\n- Start with broader searches and narrow down using filters\n- Use repo: and file: filters to improve result relevance\n- The results are case insensitive, so you should not repeat the same search term with different capitalization.\n- Use regex (file:.*.py) instead of glob (file:*.py) for searching files with a .py extension\n- Don't use the rev: filter unless the user specifically asks for a particular branch, tag, or commit. The default behavior is to search the HEAD of the default branch.\nImportant: Use the literal OR between search terms if you are looking for code containing at least one of the terms. Do not use regex or with |.\n\nReturns the top 3 most relevant code chunks (truncated to 1024 characters) from each matching file (up to 15 files).\nIndividual lines longer than 256 characters are truncated.\n\nExamples:\n\n\n\tFind all code in the secret-fellowship organization on Github using log4j\n\tcalls the keyword search tool with query: \"repo:^github.com/secret-fellowship log4j\"\n\n\n\tFind all code in the github.com/kubernetes/autoscaler repo that uses the http.NewRequest function\n\tcalls the keyword search tool with query: \"repo:^github.com/kubernetes/autoscaler$ http.NewRequest\"\n\n\n\tFind Go code in ollama where memory mapping is used on darwin or linux\n\tcalls the keyword search tool with query: \"repo:ollama file:.*.go mmap AND (darwin OR linux)\"\n\n\n\tFind FAQs in all readme files across all repositories\n\tcalls the keyword search tool with query: \"file:README.md FAQ\"\n\n\n\tFind code in bar or foo repos that uses lodash\n\tcalls the keyword search tool with query: \"(repo:foo OR repo:bar) lodash\"\n\n\n\tFind code containing either foo or bar in the dev/docs directory\n\tcalls the keyword search tool with query: \"file:^dev/docs foo OR bar\"\n\n\n\tFind code containing foo in dev/docs directory of the repo bar/bas on branch quz/user>\n\tcalls the keyword search tool with query: \"repo:^bar/bas$ rev:quz file:^dev/docs foo\"\n\n", + "inputSchema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "query" + ], + "properties": { + "query": { + "type": "string", + "description": "The search query. Can include keywords, regex patterns, and filters." + } + }, + "additionalProperties": false + }, + "name": "sg_keyword_search", + "outputSchema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "blocks" + ], + "properties": { + "blocks": { + "type": "array", + "items": true + } + }, + "additionalProperties": false + } + }, + { + "description": "This is a Sourcegraph search tool and is best used with other sourcegraph search tools. Lists the files and subdirectories in the workspace in a given directory.\nDirect subdirectories are included and the path is returned with a trailing slash.\nThe input path is relative to the root of the repository.\n\nLists up to 1000 files or directories. If there are more, the response will be truncated.\nDirectories are listed first.\n\nExamples:\n\n\t\n\t\tList all files in the src directory of the repository.\n\t\tCalls the list files tool with path: \"src\"\n\t\t[{\"path\": \"app/\", \"isDirectory\": true}, {\"path\": \"DEV.md\", \"isDirectory\": false}]\n\t\n\n", + "inputSchema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "repo" + ], + "properties": { + "path": { + "type": "string", + "description": "The directory path within the workspace to list files from. Defaults to workspace root if not specified." + }, + "repo": { + "type": "string", + "description": "The name of the repository containing the files. For example, \"github.com/torvalds/linux\"." + }, + "revision": { + "type": "string", + "description": "The revision or branch to list files from. If not specified, defaults to the HEAD of the default branch." + } + }, + "additionalProperties": false + }, + "name": "sg_list_files", + "outputSchema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "files" + ], + "properties": { + "files": { + "type": "array", + "items": { + "type": "object", + "required": [ + "path", + "isDirectory" + ], + "properties": { + "isDirectory": { + "type": "boolean" + }, + "path": { + "type": "string" + } + }, + "additionalProperties": false + } + } + }, + "additionalProperties": false + } + }, + { + "description": "This is a Sourcegraph search tool and is best used with other sourcegraph search tools. \nLists repositories that match a search query.\nYou can use this tool to figure out the repositories the user wants to talk about.\nReturns repository names, descriptions, and other metadata.\nBy default, returns up to 50 repositories per page.\nSupports cursor-based pagination - the response will include cursor information that can be used to fetch the next or previous page of results.\nUse the \"after\" parameter with the \"endCursor\" from the previous response to get the next page, or \"before\" with \"startCursor\" to get the previous page.\n\nWhen to use this tool:\n- When you do not know the full name of a repository (e.g. the user asks to search the xyz repo, you can use this tool to get github.com/my-org/xyz)\n- When you have to find repositories by substring matching (e.g. you want to find all repositories that contain the word \"foobar\")\nThe pattern is not a regular expression, but uses substring matching on the name of the repo.\n\nExamples:\n\n\t\n\t\tFind repositories in the cool-kids-club org on Github\n\t\tCalls the list repos tool with query: \"github.com/cool-kids-club\"\n\t\n\t\n\t\tExplain the foo repository\n\t\tCalls the list repos tool with query: \"foo\"\n\t\n\t\n\t\tDo we have repositories named \"baz\" and \"qux\"?\n\t\tCalls the list repos tool with query \"baz\", calls the list repos tool with query \"qux\"\n\t\n", + "inputSchema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "query" + ], + "properties": { + "after": { + "type": "string", + "description": "Cursor to start fetching results after. Use the \"endCursor\" from the previous response." + }, + "before": { + "type": "string", + "description": "Cursor to start fetching results before. Use the \"startCursor\" from the previous response." + }, + "limit": { + "type": "integer", + "description": "Maximum number of repositories to return per page. Defaults to 50." + }, + "query": { + "type": "string", + "description": "A search query to filter repositories. For example, \"django\" to find repositories containing that term." + } + }, + "additionalProperties": false + }, + "name": "sg_list_repos", + "outputSchema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "repositories", + "pagination" + ], + "properties": { + "pagination": { + "type": "object", + "required": [ + "totalCount", + "hasNextPage", + "hasPreviousPage" + ], + "properties": { + "endCursor": { + "type": "string" + }, + "hasNextPage": { + "type": "boolean" + }, + "hasPreviousPage": { + "type": "boolean" + }, + "startCursor": { + "type": "string" + }, + "totalCount": { + "type": "integer" + } + }, + "additionalProperties": false + }, + "repositories": { + "type": "array", + "items": { + "type": "object", + "required": [ + "name", + "description", + "private", + "archived", + "fork", + "stars" + ], + "properties": { + "archived": { + "type": "boolean" + }, + "description": { + "type": "string" + }, + "fork": { + "type": "boolean" + }, + "name": { + "type": "string" + }, + "private": { + "type": "boolean" + }, + "stars": { + "type": "integer" + } + }, + "additionalProperties": false + } + } + }, + "additionalProperties": false + } + }, + { + "description": "This is a Sourcegraph search tool and is best used with other sourcegraph search tools. \nA semantic code search tool that helps find relevant code snippets using flexible linguistic matching.\n\nUse this tool over sg_keyword_search when you need to:\n- Find code related to concepts rather than exact matches\n- Get broader results with more potential matches\n- Find code when you don't know the exact keyword to search for like symbol (function or variable) names\n- When the sg_keyword_search tool returns too few results\n\nSearch capabilities:\n- The core matching is also keyword-based, but it's more flexible and can match more terms\n- Uses stemming and OR binding between terms for broader matching (e.g. \"auth impl\" matches on either term)\n- Filters: same as sg_keyword_search tool\n\nWhen not to use this tool:\n- When you need exact string matches (use the sg_keyword_search tool instead)\n- When you're looking for specific function names or variables\n\nBest practices:\n- IMPORTANT: Extract relevant keywords from a natural language query and search with only the keywords - if a user asks \"How are database connections created or closed in the codebase?\", search with \"database connection create close\", not \"how are database connections created closed\"\n- For complex topics with multiple aspects, do separate searches for each main concept\n- Use repo: and file: filters to improve result relevance\n- If results seem off-target, try refining your query to be more specific or use filters to avoid unwanted results\n- The results are case insensitive, so you should not repeat the same search term with different capitalization\n\nReturns the top 3 most relevant code chunks (truncated to 1024 characters) from each matching file (up to 15 files).\nIndividual lines longer than 256 characters are truncated.\n\nExamples:\n\n\n\tFind where event listener handlers are set up in the codebase\n\tcalls the nls search tool with query: \"event listen handler\"\n\n\n\tExplain the code that controls the chat view in barfoo repo\n\tcalls the nls search tool with query: \"repo:barfoo$ view controller chat\"\n\n\n\tHow are database connections managed in the github.com/django/django repo?\n\tcalls the nls search tool with query: \"repo:^github.com/django/django$ database connection manage\"\n\n\n", + "inputSchema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "query" + ], + "properties": { + "query": { + "type": "string", + "description": "The search query. Can include keywords, regex patterns, and filters." + } + }, + "additionalProperties": false + }, + "name": "sg_nls_search", + "outputSchema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "blocks" + ], + "properties": { + "blocks": { + "type": "array", + "items": true + } + }, + "additionalProperties": false + } + }, + { + "description": "This is a Sourcegraph search tool and is best used with other sourcegraph search tools. \nReads the content of a file in the workspace.\nReturns the file content as a string.\nEach line is prefixed with its actual line number from the file. The line numbers are 1-indexed. If a file contains \"abc\\\\ndef\", you will receive \"1: abc\\\\n2: def\".\nYou can optionally specify a line range to read only a portion of the file.\nIf you attempt to read a file that is too large (limit is 128 KB), you will receive an error. In that case, retry with a smaller line range.\n\nIMPORTANT: Use this tool ONLY when you have already located the specific file.\nBefore using this tool:\n- ALWAYS verify both the repository and file exist by using sg_list_repos, sg_list_files, sg_keyword_search, or sg_nls_search first\n- NEVER try to read a file without first confirming it exists at the exact path\n- NEVER guess file paths or assume common structures like \"lib/shared/src\" exist - always verify\n\nExamples:\n\n\n\tSummarize the readme in the pytorch/torcheval repository\n\t[First checks that the repository exists by calling sg_list_repos]\n\t[Then verifies README.md exists using sg_list_files with repo: \"pytorch/torcheval\"]\n\tCalls the read file tool with repo: \"pytorch/torcheval\", path: \"README.md\"\n\n\n\tRead the first 100 lines of the code in cli/build.rs in the tokio-rs/tokio repository\n\t[First confirms the file exists using sg_list_files or sg_keyword_search]\n\tCalls the read file tool with repo: \"tokio-rs/tokio\", path: \"cli/build.rs\", startLine: 1, endLine: 100\n\n\n\tRead the first 100 lines of the code in cli/build.rs in the tokio-rs/tokio repository at commit 1234567890\n\t[First confirms the file exists using sg_list_files or sg_keyword_search]\n\tCalls the read file tool with repo: \"tokio-rs/tokio\", path: \"cli/build.rs\", startLine: 1, endLine: 100, revision: \"1234567890\"\n\n\n\tRead the first 100 lines of the code in cli/build.rs in the tokio-rs/tokio repository at branch feat/xzy\n\t[First confirms the file exists using sg_list_files or sg_keyword_search]\n\tCalls the read file tool with repo: \"tokio-rs/tokio\", path: \"cli/build.rs\", startLine: 1, endLine: 100, revision: \"feat/xzy\"\n\n", + "inputSchema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "repo", + "path" + ], + "properties": { + "endLine": { + "type": "integer", + "description": "The 1-based line number to end reading at. If not specified, reads to the end of the file." + }, + "path": { + "type": "string", + "description": "The path to the file within the repository." + }, + "repo": { + "type": "string", + "description": "The name of the repository containing the file. For example, \"github.com/sveltejs/svelte\"." + }, + "revision": { + "type": "string", + "description": "The revision to read the file from. If not specified, reads from the default branch. This can be a commit hash or a branch name" + }, + "startLine": { + "type": "integer", + "description": "The 1-based line number to start reading from. If not specified, starts from the beginning of the file." + } + }, + "additionalProperties": false + }, + "name": "sg_read_file", + "outputSchema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "content" + ], + "properties": { + "content": { + "type": "string" + } + }, + "additionalProperties": false + } + } + ] +} diff --git a/scripts/gen-mcp-tool-json.sh b/scripts/gen-mcp-tool-json.sh new file mode 100755 index 0000000000..82430a0e55 --- /dev/null +++ b/scripts/gen-mcp-tool-json.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash + +DST=$1 + +if [[ -z "${SRC_ACCESS_TOKEN}" ]]; then + echo "SRC_ACCESS_TOKEN is not set. Please set a access token for S2 (sourcegraph.sourcegraph.com)" + exit 1 +fi + +if [[ -z "$DST" ]]; then + echo "Usage: $0 " + exit 1 +fi + +curl \ + -H "Content-Type: application/json" \ + -H "Authorization: token ${SRC_ACCESS_TOKEN}" \ + -X POST \ + -d '{ "jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {}}' \ + https://sourcegraph.sourcegraph.com/.api/mcp/v1 | grep 'data:' | cut -b 6- | jq '.result' > ${DST} + From b10b4efa2420f175400c1fa7f6edb4c54f62c1e8 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Tue, 9 Dec 2025 13:03:29 +0000 Subject: [PATCH 519/647] feat(mcp): load mcp tool defintions on demand (#1231) * add FetchToolDefinitions method - refactor DoToolRequest to DoToolCall - add doJSONRPC call * remove embedding of mcp tools json * load tools definition ondemand in mcp cmd * read SSE response into json rpc result and load tool def * lint * handle http errors / rpc errors * inline jsonRPCError --- cmd/src/mcp.go | 16 ++++--- internal/mcp/mcp_parse.go | 7 --- internal/mcp/mcp_request.go | 84 +++++++++++++++++++++++++++++------- scripts/gen-mcp-tool-json.sh | 21 --------- 4 files changed, 77 insertions(+), 51 deletions(-) delete mode 100755 scripts/gen-mcp-tool-json.sh diff --git a/cmd/src/mcp.go b/cmd/src/mcp.go index 4510eb320f..b6934b466c 100644 --- a/cmd/src/mcp.go +++ b/cmd/src/mcp.go @@ -13,16 +13,20 @@ import ( "github.com/sourcegraph/sourcegraph/lib/errors" ) +var mcpFlagSet = flag.NewFlagSet("mcp", flag.ExitOnError) + func init() { - flagSet := flag.NewFlagSet("mcp", flag.ExitOnError) commands = append(commands, &command{ - flagSet: flagSet, + flagSet: mcpFlagSet, handler: mcpMain, }) } func mcpMain(args []string) error { fmt.Println("NOTE: This command is still experimental") - tools, err := mcp.LoadDefaultToolDefinitions() + apiClient := cfg.apiClient(nil, mcpFlagSet.Output()) + + ctx := context.Background() + tools, err := mcp.FetchToolDefinitions(ctx, apiClient) if err != nil { return err } @@ -44,10 +48,9 @@ func mcpMain(args []string) error { fmt.Printf(" src mcp schema\n") return nil } - tool, ok := tools[subcmd] if !ok { - return fmt.Errorf("tool definition for %q not found - run src mcp list-tools to see a list of available tools", subcmd) + return errors.Newf("tool definition for %q not found - run src mcp list-tools to see a list of available tools", subcmd) } flagArgs := args[1:] // skip subcommand name @@ -68,7 +71,6 @@ func mcpMain(args []string) error { return err } - apiClient := cfg.apiClient(nil, flags.Output()) return handleMcpTool(context.Background(), apiClient, tool, vars) } @@ -101,7 +103,7 @@ func validateToolArgs(inputSchema mcp.SchemaObject, args []string, vars map[stri } func handleMcpTool(ctx context.Context, client api.Client, tool *mcp.ToolDef, vars map[string]any) error { - resp, err := mcp.DoToolRequest(ctx, client, tool, vars) + resp, err := mcp.DoToolCall(ctx, client, tool.RawName, vars) if err != nil { return err } diff --git a/internal/mcp/mcp_parse.go b/internal/mcp/mcp_parse.go index 31243fee70..1a5fae1dc9 100644 --- a/internal/mcp/mcp_parse.go +++ b/internal/mcp/mcp_parse.go @@ -8,9 +8,6 @@ import ( "github.com/sourcegraph/sourcegraph/lib/errors" ) -//go:embed mcp_tools.json -var mcpToolListJSON []byte - type ToolDef struct { Name string RawName string `json:"name"` @@ -63,10 +60,6 @@ type decoder struct { errors []error } -func LoadDefaultToolDefinitions() (map[string]*ToolDef, error) { - return loadToolDefinitions(mcpToolListJSON) -} - func loadToolDefinitions(data []byte) (map[string]*ToolDef, error) { defs := struct { Tools []struct { diff --git a/internal/mcp/mcp_request.go b/internal/mcp/mcp_request.go index dbcb0ed97b..4b41db1570 100644 --- a/internal/mcp/mcp_request.go +++ b/internal/mcp/mcp_request.go @@ -6,6 +6,7 @@ import ( "encoding/json" "io" "net/http" + "strings" "github.com/sourcegraph/src-cli/internal/api" @@ -14,25 +15,59 @@ import ( const McpURLPath = ".api/mcp/v1" -func DoToolRequest(ctx context.Context, client api.Client, tool *ToolDef, vars map[string]any) (*http.Response, error) { +func FetchToolDefinitions(ctx context.Context, client api.Client) (map[string]*ToolDef, error) { + resp, err := doJSONRPC(ctx, client, "tools/list", nil) + if err != nil { + return nil, errors.Wrap(err, "failed to list tools from mcp endpoint") + } + defer resp.Body.Close() + + data, err := readSSEResponseData(resp) + if err != nil { + return nil, errors.Wrap(err, "failed to read list tools SSE response") + } + + var rpcResp struct { + Result json.RawMessage `json:"result"` + Error *struct { + Code int `json:"code"` + Message string `json:"message"` + } `json:"error,omitempty"` + } + if err := json.Unmarshal(data, &rpcResp); err != nil { + return nil, errors.Wrap(err, "failed to unmarshal JSON-RPC response") + } + if rpcResp.Error != nil { + return nil, errors.Newf("MCP tools/list failed: %d %s", rpcResp.Error.Code, rpcResp.Error.Message) + } + + return loadToolDefinitions(rpcResp.Result) +} + +func DoToolCall(ctx context.Context, client api.Client, tool string, vars map[string]any) (*http.Response, error) { + params := struct { + Name string `json:"name"` + Arguments map[string]any `json:"arguments"` + }{ + Name: tool, + Arguments: vars, + } + + return doJSONRPC(ctx, client, "tools/call", params) +} + +func doJSONRPC(ctx context.Context, client api.Client, method string, params any) (*http.Response, error) { jsonRPC := struct { Version string `json:"jsonrpc"` ID int `json:"id"` Method string `json:"method"` - Params any `json:"params"` + Params any `json:"params,omitempty"` }{ Version: "2.0", ID: 1, - Method: "tools/call", - Params: struct { - Name string `json:"name"` - Arguments map[string]any `json:"arguments"` - }{ - Name: tool.RawName, - Arguments: vars, - }, + Method: method, + Params: params, } - buf := bytes.NewBuffer(nil) data, err := json.Marshal(jsonRPC) if err != nil { @@ -45,9 +80,21 @@ func DoToolRequest(ctx context.Context, client api.Client, tool *ToolDef, vars m return nil, err } req.Header.Add("Content-Type", "application/json") - req.Header.Add("Accept", "*/*") + req.Header.Add("Accept", "application/json, text/event-stream") + + resp, err := client.Do(req) + if err != nil { + return nil, err + } + + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) + resp.Body.Close() + return nil, errors.Newf("MCP endpoint %s returned %d: %s", + McpURLPath, resp.StatusCode, strings.TrimSpace(string(body))) + } - return client.Do(req) + return resp, nil } func DecodeToolResponse(resp *http.Response) (map[string]json.RawMessage, error) { @@ -61,16 +108,21 @@ func DecodeToolResponse(resp *http.Response) (map[string]json.RawMessage, error) } jsonRPCResp := struct { - Version string `json:"jsonrpc"` - ID int `json:"id"` - Result struct { + Result struct { Content []json.RawMessage `json:"content"` StructuredContent map[string]json.RawMessage `json:"structuredContent"` } `json:"result"` + Error *struct { + Code int `json:"code"` + Message string `json:"message"` + } `json:"error,omitempty"` }{} if err := json.Unmarshal(data, &jsonRPCResp); err != nil { return nil, errors.Wrapf(err, "failed to unmarshal MCP JSON-RPC response") } + if jsonRPCResp.Error != nil { + return nil, errors.Newf("MCP tools/call failed: %d %s", jsonRPCResp.Error.Code, jsonRPCResp.Error.Message) + } return jsonRPCResp.Result.StructuredContent, nil } diff --git a/scripts/gen-mcp-tool-json.sh b/scripts/gen-mcp-tool-json.sh deleted file mode 100755 index 82430a0e55..0000000000 --- a/scripts/gen-mcp-tool-json.sh +++ /dev/null @@ -1,21 +0,0 @@ -#!/usr/bin/env bash - -DST=$1 - -if [[ -z "${SRC_ACCESS_TOKEN}" ]]; then - echo "SRC_ACCESS_TOKEN is not set. Please set a access token for S2 (sourcegraph.sourcegraph.com)" - exit 1 -fi - -if [[ -z "$DST" ]]; then - echo "Usage: $0 " - exit 1 -fi - -curl \ - -H "Content-Type: application/json" \ - -H "Authorization: token ${SRC_ACCESS_TOKEN}" \ - -X POST \ - -d '{ "jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {}}' \ - https://sourcegraph.sourcegraph.com/.api/mcp/v1 | grep 'data:' | cut -b 6- | jq '.result' > ${DST} - From 81fac140e72a4d006039988beb4eb6045b596659 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Tue, 9 Dec 2025 15:07:33 +0000 Subject: [PATCH 520/647] check args before use in mcp (#1232) if no subcommands given print usage --- cmd/src/mcp.go | 33 ++++++++++++++++++++++----------- 1 file changed, 22 insertions(+), 11 deletions(-) diff --git a/cmd/src/mcp.go b/cmd/src/mcp.go index b6934b466c..5dbcd81841 100644 --- a/cmd/src/mcp.go +++ b/cmd/src/mcp.go @@ -17,10 +17,21 @@ var mcpFlagSet = flag.NewFlagSet("mcp", flag.ExitOnError) func init() { commands = append(commands, &command{ - flagSet: mcpFlagSet, - handler: mcpMain, + flagSet: mcpFlagSet, + handler: mcpMain, + usageFunc: mcpUsage, }) } + +func mcpUsage() { + fmt.Println("The 'mcp' command exposes MCP tools as subcommands for agents to use.") + fmt.Println("\nUSAGE:") + fmt.Println(" src mcp list-tools List available tools") + fmt.Println(" src mcp schema View the input/output schema of a tool") + fmt.Println(" src mcp Invoke a tool with the given flags") + fmt.Println(" src mcp -h List the available flags of a tool") +} + func mcpMain(args []string) error { fmt.Println("NOTE: This command is still experimental") apiClient := cfg.apiClient(nil, mcpFlagSet.Output()) @@ -31,21 +42,21 @@ func mcpMain(args []string) error { return err } + if len(args) == 0 { + mcpUsage() + return nil + } + subcmd := args[0] if subcmd == "list-tools" { fmt.Println("The following tools are available:") for name := range tools { - fmt.Printf(" • %s\n", name) + fmt.Printf(" %s\n", name) } fmt.Println("\nUSAGE:") - fmt.Printf(" • Invoke a tool\n") - fmt.Printf(" src mcp \n") - fmt.Printf("\n • View the Input / Output Schema of a tool\n") - fmt.Printf(" src mcp schema\n") - fmt.Printf("\n • List the available flags of a tool\n") - fmt.Printf(" src mcp -h\n") - fmt.Printf("\n • View the Input / Output Schema of a tool\n") - fmt.Printf(" src mcp schema\n") + fmt.Println(" src mcp schema View the input/output schema of a tool") + fmt.Println(" src mcp Invoke a tool with the given flags") + fmt.Println(" src mcp -h List the available flags of a tool") return nil } tool, ok := tools[subcmd] From 4baaca0a9b450e2a932ff4d753604d4b89e7f213 Mon Sep 17 00:00:00 2001 From: Keegan Carruthers-Smith Date: Tue, 9 Dec 2025 17:17:44 +0200 Subject: [PATCH 521/647] feat(mcp): only set variables for set flags (#1234) Previously we had code which tried to detect nil values. But for example if a flag is an integer that wouldn't work. Instead we use a more robust approach of only setting variables if the flag was passed in as an argument. Test Plan: this command actually returns results now. Previously it wouldn't since it would have limit set to 0. go run ./cmd/src -v mcp list-repos -query 'cloud' --- cmd/src/mcp.go | 2 +- internal/mcp/mcp_args.go | 30 +++++++++++------------------- internal/mcp/mcp_args_test.go | 2 +- 3 files changed, 13 insertions(+), 21 deletions(-) diff --git a/cmd/src/mcp.go b/cmd/src/mcp.go index 5dbcd81841..33dbd8f99d 100644 --- a/cmd/src/mcp.go +++ b/cmd/src/mcp.go @@ -76,7 +76,7 @@ func mcpMain(args []string) error { if err := flags.Parse(flagArgs); err != nil { return err } - mcp.DerefFlagValues(vars) + mcp.DerefFlagValues(flags, vars) if err := validateToolArgs(tool.InputSchema, args, vars); err != nil { return err diff --git a/internal/mcp/mcp_args.go b/internal/mcp/mcp_args.go index ecfb98e2b0..863f51af9d 100644 --- a/internal/mcp/mcp_args.go +++ b/internal/mcp/mcp_args.go @@ -24,36 +24,28 @@ func (s *strSliceFlag) String() string { return strings.Join(s.vals, ",") } -func DerefFlagValues(vars map[string]any) { +func DerefFlagValues(fs *flag.FlagSet, vars map[string]any) { + setFlags := make(map[string]bool) + fs.Visit(func(f *flag.Flag) { + setFlags[f.Name] = true + }) + for k, v := range vars { + if !setFlags[k] { + delete(vars, k) + continue + } rfl := reflect.ValueOf(v) if rfl.Kind() == reflect.Pointer { vv := rfl.Elem().Interface() if slice, ok := vv.(strSliceFlag); ok { vv = slice.vals } - if isNil(vv) { - delete(vars, k) - } else { - vars[k] = vv - } + vars[k] = vv } } } -func isNil(v any) bool { - if v == nil { - return true - } - rv := reflect.ValueOf(v) - switch rv.Kind() { - case reflect.Slice, reflect.Map, reflect.Pointer, reflect.Interface: - return rv.IsNil() - default: - return false - } -} - func BuildArgFlagSet(tool *ToolDef) (*flag.FlagSet, map[string]any, error) { if tool == nil { return nil, nil, errors.New("cannot build flagset on nil Tool Definition") diff --git a/internal/mcp/mcp_args_test.go b/internal/mcp/mcp_args_test.go index 17d5b466e0..ca40c246ad 100644 --- a/internal/mcp/mcp_args_test.go +++ b/internal/mcp/mcp_args_test.go @@ -63,7 +63,7 @@ func TestFlagSetParse(t *testing.T) { if err := flagSet.Parse(args); err != nil { t.Fatalf("flagset parsing failed: %v", err) } - DerefFlagValues(vars) + DerefFlagValues(flagSet, vars) if v, ok := vars["repos"].([]string); ok { if len(v) != 2 { From 2f0b82f34a0649ece705aecd3cb4b2fcfa864ce1 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Tue, 9 Dec 2025 18:43:10 +0000 Subject: [PATCH 522/647] handle -repos flag values that are JSON arrays (#1235) --- internal/mcp/mcp_args.go | 11 +++++++++++ internal/mcp/mcp_args_test.go | 17 ++++++++++------- 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/internal/mcp/mcp_args.go b/internal/mcp/mcp_args.go index 863f51af9d..bdd7af6ef7 100644 --- a/internal/mcp/mcp_args.go +++ b/internal/mcp/mcp_args.go @@ -1,6 +1,7 @@ package mcp import ( + "encoding/json" "flag" "fmt" "reflect" @@ -16,6 +17,16 @@ type strSliceFlag struct { } func (s *strSliceFlag) Set(v string) error { + // The MCP Array properties accept JSON arrays so, if we get a value starting with "[" + // it's probably a JSON array + if strings.HasPrefix(v, "[") { + var arr []string + if err := json.Unmarshal([]byte(v), &arr); err == nil { + s.vals = append(s.vals, arr...) + return nil + } + } + // Otherwise treat as a single value s.vals = append(s.vals, v) return nil } diff --git a/internal/mcp/mcp_args_test.go b/internal/mcp/mcp_args_test.go index ca40c246ad..829e6dbf55 100644 --- a/internal/mcp/mcp_args_test.go +++ b/internal/mcp/mcp_args_test.go @@ -1,6 +1,7 @@ package mcp import ( + "slices" "testing" ) @@ -58,20 +59,22 @@ func TestFlagSetParse(t *testing.T) { t.Fatalf("vars from buildArgFlagSet should not be empty") } - args := []string{"-repos=A", "-repos=B", "-count=10", "-boolFlag", "-tag=testTag"} + args := []string{"-repos=A", "-repos=B", `-repos=["repo1", "repo2"]`, "-count=10", "-boolFlag", "-tag=testTag"} if err := flagSet.Parse(args); err != nil { t.Fatalf("flagset parsing failed: %v", err) } DerefFlagValues(flagSet, vars) - if v, ok := vars["repos"].([]string); ok { - if len(v) != 2 { - t.Fatalf("expected flag 'repos' values to have length %d but got %d", 2, len(v)) - } - } else { - t.Fatalf("expected flag 'repos' to have type of []string but got %T", v) + expectedRepos := []string{"A", "B", "repo1", "repo2"} + actualRepos, ok := vars["repos"].([]string) + if !ok { + t.Fatalf("failed to cast repos to []string, got %T", actualRepos) } + if !slices.Equal(expectedRepos, actualRepos) { + t.Fatalf("expected repos %v, got %v", expectedRepos, vars["repos"]) + } + if v, ok := vars["tag"].(string); ok { if v != "testTag" { t.Fatalf("expected flag 'tag' values to have value %q but got %q", "testTag", v) From ee83af19e7a44a6d976b03cd3ffbaffadb786ab8 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Wed, 10 Dec 2025 09:20:43 +0000 Subject: [PATCH 523/647] remove experimental notice (#1233) not neeed since command isn't advertised so experimental is implied --- cmd/src/mcp.go | 1 - 1 file changed, 1 deletion(-) diff --git a/cmd/src/mcp.go b/cmd/src/mcp.go index 33dbd8f99d..005036607b 100644 --- a/cmd/src/mcp.go +++ b/cmd/src/mcp.go @@ -33,7 +33,6 @@ func mcpUsage() { } func mcpMain(args []string) error { - fmt.Println("NOTE: This command is still experimental") apiClient := cfg.apiClient(nil, mcpFlagSet.Output()) ctx := context.Background() From 97c300413327ec134b15a4229e7008ec3a9a230d Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Wed, 10 Dec 2025 12:23:54 +0000 Subject: [PATCH 524/647] Handle MCP isError response flag (#1236) --- internal/mcp/mcp_request.go | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/internal/mcp/mcp_request.go b/internal/mcp/mcp_request.go index 4b41db1570..05b4552e49 100644 --- a/internal/mcp/mcp_request.go +++ b/internal/mcp/mcp_request.go @@ -111,6 +111,7 @@ func DecodeToolResponse(resp *http.Response) (map[string]json.RawMessage, error) Result struct { Content []json.RawMessage `json:"content"` StructuredContent map[string]json.RawMessage `json:"structuredContent"` + IsError bool `json:"isError"` } `json:"result"` Error *struct { Code int `json:"code"` @@ -124,6 +125,19 @@ func DecodeToolResponse(resp *http.Response) (map[string]json.RawMessage, error) return nil, errors.Newf("MCP tools/call failed: %d %s", jsonRPCResp.Error.Code, jsonRPCResp.Error.Message) } + if jsonRPCResp.Result.IsError { + if len(jsonRPCResp.Result.Content) > 0 { + var textContent struct { + Text string `json:"text"` + } + if err := json.Unmarshal(jsonRPCResp.Result.Content[0], &textContent); err == nil && textContent.Text != "" { + return nil, errors.Newf("MCP tool error: %s", textContent.Text) + } + return nil, errors.Newf("MCP tool error: %s", string(jsonRPCResp.Result.Content[0])) + } + return nil, errors.New("MCP tool returned an error") + } + return jsonRPCResp.Result.StructuredContent, nil } func readSSEResponseData(resp *http.Response) ([]byte, error) { From c8a9dce43a9f01505c0287782a1f9d2fb1014354 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Wed, 10 Dec 2025 12:48:40 +0000 Subject: [PATCH 525/647] feat(mcp): add tool registry to handle tools from different endpoints (#1237) * add tool registry registry tracks tools and from which endpoints they originated from * unexport DoToolCall and DecodeToolResponse * use tool registry in mcp command for tool execution * fix MCP casing --- cmd/src/mcp.go | 41 +++++++------------ internal/mcp/mcp_request.go | 19 ++++----- internal/mcp/registry.go | 81 +++++++++++++++++++++++++++++++++++++ 3 files changed, 106 insertions(+), 35 deletions(-) create mode 100644 internal/mcp/registry.go diff --git a/cmd/src/mcp.go b/cmd/src/mcp.go index 005036607b..af88ae8a74 100644 --- a/cmd/src/mcp.go +++ b/cmd/src/mcp.go @@ -7,7 +7,6 @@ import ( "fmt" "strings" - "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/mcp" "github.com/sourcegraph/sourcegraph/lib/errors" @@ -36,8 +35,8 @@ func mcpMain(args []string) error { apiClient := cfg.apiClient(nil, mcpFlagSet.Output()) ctx := context.Background() - tools, err := mcp.FetchToolDefinitions(ctx, apiClient) - if err != nil { + registry := mcp.NewToolRegistry() + if err := registry.LoadTools(ctx, apiClient); err != nil { return err } @@ -49,7 +48,7 @@ func mcpMain(args []string) error { subcmd := args[0] if subcmd == "list-tools" { fmt.Println("The following tools are available:") - for name := range tools { + for name := range registry.All() { fmt.Printf(" %s\n", name) } fmt.Println("\nUSAGE:") @@ -58,7 +57,7 @@ func mcpMain(args []string) error { fmt.Println(" src mcp -h List the available flags of a tool") return nil } - tool, ok := tools[subcmd] + tool, ok := registry.Get(subcmd) if !ok { return errors.Newf("tool definition for %q not found - run src mcp list-tools to see a list of available tools", subcmd) } @@ -81,7 +80,17 @@ func mcpMain(args []string) error { return err } - return handleMcpTool(context.Background(), apiClient, tool, vars) + result, err := registry.CallTool(ctx, apiClient, tool.Name, vars) + if err != nil { + return err + } + + output, err := json.MarshalIndent(result, "", " ") + if err != nil { + return err + } + fmt.Println(string(output)) + return nil } func printSchemas(tool *mcp.ToolDef) error { @@ -111,23 +120,3 @@ func validateToolArgs(inputSchema mcp.SchemaObject, args []string, vars map[stri return nil } - -func handleMcpTool(ctx context.Context, client api.Client, tool *mcp.ToolDef, vars map[string]any) error { - resp, err := mcp.DoToolCall(ctx, client, tool.RawName, vars) - if err != nil { - return err - } - - result, err := mcp.DecodeToolResponse(resp) - if err != nil { - return err - } - defer resp.Body.Close() - - output, err := json.MarshalIndent(result, "", " ") - if err != nil { - return err - } - fmt.Println(string(output)) - return nil -} diff --git a/internal/mcp/mcp_request.go b/internal/mcp/mcp_request.go index 05b4552e49..980bfbe680 100644 --- a/internal/mcp/mcp_request.go +++ b/internal/mcp/mcp_request.go @@ -13,10 +13,11 @@ import ( "github.com/sourcegraph/sourcegraph/lib/errors" ) -const McpURLPath = ".api/mcp/v1" +const MCPURLPath = ".api/mcp/v1" +const MCPDeepSearchURLPath = ".api/mcp/deepsearch" -func FetchToolDefinitions(ctx context.Context, client api.Client) (map[string]*ToolDef, error) { - resp, err := doJSONRPC(ctx, client, "tools/list", nil) +func fetchToolDefinitions(ctx context.Context, client api.Client, endpoint string) (map[string]*ToolDef, error) { + resp, err := doJSONRPC(ctx, client, endpoint, "tools/list", nil) if err != nil { return nil, errors.Wrap(err, "failed to list tools from mcp endpoint") } @@ -44,7 +45,7 @@ func FetchToolDefinitions(ctx context.Context, client api.Client) (map[string]*T return loadToolDefinitions(rpcResp.Result) } -func DoToolCall(ctx context.Context, client api.Client, tool string, vars map[string]any) (*http.Response, error) { +func doToolCall(ctx context.Context, client api.Client, endpoint string, tool string, vars map[string]any) (*http.Response, error) { params := struct { Name string `json:"name"` Arguments map[string]any `json:"arguments"` @@ -53,10 +54,10 @@ func DoToolCall(ctx context.Context, client api.Client, tool string, vars map[st Arguments: vars, } - return doJSONRPC(ctx, client, "tools/call", params) + return doJSONRPC(ctx, client, endpoint, "tools/call", params) } -func doJSONRPC(ctx context.Context, client api.Client, method string, params any) (*http.Response, error) { +func doJSONRPC(ctx context.Context, client api.Client, endpoint string, method string, params any) (*http.Response, error) { jsonRPC := struct { Version string `json:"jsonrpc"` ID int `json:"id"` @@ -75,7 +76,7 @@ func doJSONRPC(ctx context.Context, client api.Client, method string, params any } buf.Write(data) - req, err := client.NewHTTPRequest(ctx, http.MethodPost, McpURLPath, buf) + req, err := client.NewHTTPRequest(ctx, http.MethodPost, endpoint, buf) if err != nil { return nil, err } @@ -91,13 +92,13 @@ func doJSONRPC(ctx context.Context, client api.Client, method string, params any body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) resp.Body.Close() return nil, errors.Newf("MCP endpoint %s returned %d: %s", - McpURLPath, resp.StatusCode, strings.TrimSpace(string(body))) + endpoint, resp.StatusCode, strings.TrimSpace(string(body))) } return resp, nil } -func DecodeToolResponse(resp *http.Response) (map[string]json.RawMessage, error) { +func decodeToolResponse(resp *http.Response) (map[string]json.RawMessage, error) { data, err := readSSEResponseData(resp) if err != nil { return nil, err diff --git a/internal/mcp/registry.go b/internal/mcp/registry.go new file mode 100644 index 0000000000..d428c48e4f --- /dev/null +++ b/internal/mcp/registry.go @@ -0,0 +1,81 @@ +package mcp + +import ( + "context" + "encoding/json" + "iter" + + "github.com/sourcegraph/src-cli/internal/api" + + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +// ToolRegistry keeps track of tools and the endpoints they originated from +type ToolRegistry struct { + tools map[string]*ToolDef + endpoints map[string]string +} + +func NewToolRegistry() *ToolRegistry { + return &ToolRegistry{ + tools: make(map[string]*ToolDef), + endpoints: make(map[string]string), + } +} + +// LoadTools loads the tool definitions from the Mcp tool endpoints constants McpURLPath and McpDeepSearchURLPath +func (r *ToolRegistry) LoadTools(ctx context.Context, client api.Client) error { + endpoints := []string{MCPURLPath, MCPDeepSearchURLPath} + + var errs []error + for _, endpoint := range endpoints { + tools, err := fetchToolDefinitions(ctx, client, endpoint) + if err != nil { + errs = append(errs, errors.Wrapf(err, "failed to load tools from %s", endpoint)) + continue + } + r.register(endpoint, tools) + } + + if len(errs) > 0 { + return errors.Append(nil, errs...) + } + return nil +} + +// register associates a collection of tools with the given endpoint +func (r *ToolRegistry) register(endpoint string, tools map[string]*ToolDef) { + for name, def := range tools { + r.tools[name] = def + r.endpoints[name] = endpoint + } +} + +// Get returns the tool definition for the given name +func (r *ToolRegistry) Get(name string) (*ToolDef, bool) { + tool, ok := r.tools[name] + return tool, ok +} + +// CallTool calls the given tool with the given arguments. It constructs the Tool request and decodes the Tool response +func (r *ToolRegistry) CallTool(ctx context.Context, client api.Client, name string, args map[string]any) (map[string]json.RawMessage, error) { + tool := r.tools[name] + endpoint := r.endpoints[name] + resp, err := doToolCall(ctx, client, endpoint, tool.RawName, args) + if err != nil { + return nil, err + } + defer resp.Body.Close() + return decodeToolResponse(resp) +} + +// All returns an iterator that yields the name and Tool definition of all registered tools +func (r *ToolRegistry) All() iter.Seq2[string, *ToolDef] { + return func(yield func(string, *ToolDef) bool) { + for name, def := range r.tools { + if !yield(name, def) { + return + } + } + } +} From fcce499e32392f36f55b8ddedd96a30eadf7e4cc Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Wed, 10 Dec 2025 19:08:55 +0000 Subject: [PATCH 526/647] make sure the tools from the All iterator are sorted (#1238) --- internal/mcp/registry.go | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/internal/mcp/registry.go b/internal/mcp/registry.go index d428c48e4f..3777fd28aa 100644 --- a/internal/mcp/registry.go +++ b/internal/mcp/registry.go @@ -4,6 +4,8 @@ import ( "context" "encoding/json" "iter" + "maps" + "slices" "github.com/sourcegraph/src-cli/internal/api" @@ -71,9 +73,10 @@ func (r *ToolRegistry) CallTool(ctx context.Context, client api.Client, name str // All returns an iterator that yields the name and Tool definition of all registered tools func (r *ToolRegistry) All() iter.Seq2[string, *ToolDef] { + keys := slices.Sorted(maps.Keys(r.tools)) return func(yield func(string, *ToolDef) bool) { - for name, def := range r.tools { - if !yield(name, def) { + for _, key := range keys { + if !yield(key, r.tools[key]) { return } } From be2e759a7a28ca535e2375717e71d7ef3f4b8ae8 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Thu, 11 Dec 2025 08:47:15 +0000 Subject: [PATCH 527/647] remove loading of tools from .api/mcp/deepsearch (#1239) --- internal/mcp/mcp_request.go | 1 - internal/mcp/registry.go | 39 ++++++++----------------------------- 2 files changed, 8 insertions(+), 32 deletions(-) diff --git a/internal/mcp/mcp_request.go b/internal/mcp/mcp_request.go index 980bfbe680..4edd00948a 100644 --- a/internal/mcp/mcp_request.go +++ b/internal/mcp/mcp_request.go @@ -14,7 +14,6 @@ import ( ) const MCPURLPath = ".api/mcp/v1" -const MCPDeepSearchURLPath = ".api/mcp/deepsearch" func fetchToolDefinitions(ctx context.Context, client api.Client, endpoint string) (map[string]*ToolDef, error) { resp, err := doJSONRPC(ctx, client, endpoint, "tools/list", nil) diff --git a/internal/mcp/registry.go b/internal/mcp/registry.go index 3777fd28aa..6797c3e829 100644 --- a/internal/mcp/registry.go +++ b/internal/mcp/registry.go @@ -8,51 +8,29 @@ import ( "slices" "github.com/sourcegraph/src-cli/internal/api" - - "github.com/sourcegraph/sourcegraph/lib/errors" ) // ToolRegistry keeps track of tools and the endpoints they originated from type ToolRegistry struct { - tools map[string]*ToolDef - endpoints map[string]string + tools map[string]*ToolDef } func NewToolRegistry() *ToolRegistry { return &ToolRegistry{ - tools: make(map[string]*ToolDef), - endpoints: make(map[string]string), + tools: make(map[string]*ToolDef), } } -// LoadTools loads the tool definitions from the Mcp tool endpoints constants McpURLPath and McpDeepSearchURLPath +// LoadTools loads the tool definitions from the Mcp tool endpoints constants McpURLPath func (r *ToolRegistry) LoadTools(ctx context.Context, client api.Client) error { - endpoints := []string{MCPURLPath, MCPDeepSearchURLPath} - - var errs []error - for _, endpoint := range endpoints { - tools, err := fetchToolDefinitions(ctx, client, endpoint) - if err != nil { - errs = append(errs, errors.Wrapf(err, "failed to load tools from %s", endpoint)) - continue - } - r.register(endpoint, tools) - } - - if len(errs) > 0 { - return errors.Append(nil, errs...) + tools, err := fetchToolDefinitions(ctx, client, MCPURLPath) + if err != nil { + return err } + r.tools = tools return nil } -// register associates a collection of tools with the given endpoint -func (r *ToolRegistry) register(endpoint string, tools map[string]*ToolDef) { - for name, def := range tools { - r.tools[name] = def - r.endpoints[name] = endpoint - } -} - // Get returns the tool definition for the given name func (r *ToolRegistry) Get(name string) (*ToolDef, bool) { tool, ok := r.tools[name] @@ -62,8 +40,7 @@ func (r *ToolRegistry) Get(name string) (*ToolDef, bool) { // CallTool calls the given tool with the given arguments. It constructs the Tool request and decodes the Tool response func (r *ToolRegistry) CallTool(ctx context.Context, client api.Client, name string, args map[string]any) (map[string]json.RawMessage, error) { tool := r.tools[name] - endpoint := r.endpoints[name] - resp, err := doToolCall(ctx, client, endpoint, tool.RawName, args) + resp, err := doToolCall(ctx, client, MCPURLPath, tool.RawName, args) if err != nil { return nil, err } From e8e768e233d95264d0d08a0e35f301cd398e6228 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Thu, 11 Dec 2025 09:03:32 +0000 Subject: [PATCH 528/647] remove marshal indent (#1240) --- cmd/src/mcp.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cmd/src/mcp.go b/cmd/src/mcp.go index af88ae8a74..812d181b54 100644 --- a/cmd/src/mcp.go +++ b/cmd/src/mcp.go @@ -85,7 +85,7 @@ func mcpMain(args []string) error { return err } - output, err := json.MarshalIndent(result, "", " ") + output, err := json.Marshal(result) if err != nil { return err } @@ -94,11 +94,11 @@ func mcpMain(args []string) error { } func printSchemas(tool *mcp.ToolDef) error { - input, err := json.MarshalIndent(tool.InputSchema, "", " ") + input, err := json.Marshal(tool.InputSchema) if err != nil { return err } - output, err := json.MarshalIndent(tool.OutputSchema, "", " ") + output, err := json.Marshal(tool.OutputSchema) if err != nil { return err } From 2835e8c248490cd41fa261864a45a61e6f19be39 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Thu, 11 Dec 2025 12:26:32 +0000 Subject: [PATCH 529/647] better mcp error message wording (#1241) --- internal/mcp/mcp_request.go | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/internal/mcp/mcp_request.go b/internal/mcp/mcp_request.go index 4edd00948a..e1b8d69c3d 100644 --- a/internal/mcp/mcp_request.go +++ b/internal/mcp/mcp_request.go @@ -18,13 +18,13 @@ const MCPURLPath = ".api/mcp/v1" func fetchToolDefinitions(ctx context.Context, client api.Client, endpoint string) (map[string]*ToolDef, error) { resp, err := doJSONRPC(ctx, client, endpoint, "tools/list", nil) if err != nil { - return nil, errors.Wrap(err, "failed to list tools from mcp endpoint") + return nil, errors.Wrapf(err, "JSON-RPC tools/list request failed to %q", MCPURLPath) } defer resp.Body.Close() data, err := readSSEResponseData(resp) if err != nil { - return nil, errors.Wrap(err, "failed to read list tools SSE response") + return nil, errors.Wrap(err, "failed to read tools/list SSE response") } var rpcResp struct { @@ -53,7 +53,11 @@ func doToolCall(ctx context.Context, client api.Client, endpoint string, tool st Arguments: vars, } - return doJSONRPC(ctx, client, endpoint, "tools/call", params) + resp, err := doJSONRPC(ctx, client, endpoint, "tools/call", params) + if err != nil { + return nil, errors.Wrapf(err, "JSON-RPC tools/call request failed to %q", MCPURLPath) + } + return resp, err } func doJSONRPC(ctx context.Context, client api.Client, endpoint string, method string, params any) (*http.Response, error) { @@ -122,18 +126,19 @@ func decodeToolResponse(resp *http.Response) (map[string]json.RawMessage, error) return nil, errors.Wrapf(err, "failed to unmarshal MCP JSON-RPC response") } if jsonRPCResp.Error != nil { - return nil, errors.Newf("MCP tools/call failed: %d %s", jsonRPCResp.Error.Code, jsonRPCResp.Error.Message) + return nil, errors.Newf("MCP JSON-RPC error: %d %s", jsonRPCResp.Error.Code, jsonRPCResp.Error.Message) } if jsonRPCResp.Result.IsError { - if len(jsonRPCResp.Result.Content) > 0 { + content := jsonRPCResp.Result.Content[0] + if len(content) > 0 { var textContent struct { Text string `json:"text"` } - if err := json.Unmarshal(jsonRPCResp.Result.Content[0], &textContent); err == nil && textContent.Text != "" { + if err := json.Unmarshal(content, &textContent); err == nil && textContent.Text != "" { return nil, errors.Newf("MCP tool error: %s", textContent.Text) } - return nil, errors.Newf("MCP tool error: %s", string(jsonRPCResp.Result.Content[0])) + return nil, errors.Newf("MCP tool error: %s", string(content)) } return nil, errors.New("MCP tool returned an error") } From 5d1e21174ee663143c92a4a6c9e1550f45478b23 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Tue, 6 Jan 2026 17:20:47 +0200 Subject: [PATCH 530/647] mcp - output mcp tool schema as raw json (#1246) --- cmd/src/mcp.go | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/cmd/src/mcp.go b/cmd/src/mcp.go index 812d181b54..4a3eba10fc 100644 --- a/cmd/src/mcp.go +++ b/cmd/src/mcp.go @@ -94,16 +94,20 @@ func mcpMain(args []string) error { } func printSchemas(tool *mcp.ToolDef) error { - input, err := json.Marshal(tool.InputSchema) - if err != nil { - return err + var schema = struct { + Name string `json:"tool"` + Input any `json:"inputSchema"` + Output any `json:"outputSchema"` + }{ + Name: tool.Name, + Input: tool.InputSchema, + Output: tool.OutputSchema, } - output, err := json.Marshal(tool.OutputSchema) + jsonVal, err := json.Marshal(schema) if err != nil { return err } - - fmt.Printf("Input:\n%v\nOutput:\n%v\n", string(input), string(output)) + fmt.Println(string(jsonVal)) return nil } From 7393a822718b7b8615459eb660fa5d6c5e4d0d7f Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Wed, 7 Jan 2026 16:35:08 +0200 Subject: [PATCH 531/647] mcp: add `--json` flag to all tool calls to provide args as a json object (#1245) * add -json flag for all tools * initial version of accepting args as json * update usage for --json flag - include note section where we mention the precedence * add comments --- cmd/src/mcp.go | 21 +++++++++++++++++++++ internal/mcp/mcp_args.go | 2 ++ 2 files changed, 23 insertions(+) diff --git a/cmd/src/mcp.go b/cmd/src/mcp.go index 4a3eba10fc..3878fe24b6 100644 --- a/cmd/src/mcp.go +++ b/cmd/src/mcp.go @@ -5,6 +5,7 @@ import ( "encoding/json" "flag" "fmt" + "maps" "strings" "github.com/sourcegraph/src-cli/internal/mcp" @@ -29,6 +30,12 @@ func mcpUsage() { fmt.Println(" src mcp schema View the input/output schema of a tool") fmt.Println(" src mcp Invoke a tool with the given flags") fmt.Println(" src mcp -h List the available flags of a tool") + fmt.Println("\nCOMMON FLAGS:") + fmt.Println(" --json '{...}' Provide all tool arguments as a JSON object (recommended for agents)") + fmt.Println("\nNOTE:") + fmt.Println(" When both --json and explicit flags are provided, values from --json take precedence.") + fmt.Println("\nEXAMPLE:") + fmt.Println(" src mcp --json '{\"arg1\": \"value1\", \"arg2\": \"value2\"}'") } func mcpMain(args []string) error { @@ -76,6 +83,20 @@ func mcpMain(args []string) error { } mcp.DerefFlagValues(flags, vars) + // arguments provided via a JSON object take precedence over explicit values provided from flags + if val, ok := vars["json"]; ok { + if jsonVal, ok := val.(string); ok && len(jsonVal) > 0 { + m := make(map[string]any) + if err := json.Unmarshal([]byte(jsonVal), &m); err != nil { + return err + } + // copy overrides existing keys + maps.Copy(vars, m) + } + // we delete "json" from vars, otherwise it will be sent as a argument to the tool call + delete(vars, "json") + } + if err := validateToolArgs(tool.InputSchema, args, vars); err != nil { return err } diff --git a/internal/mcp/mcp_args.go b/internal/mcp/mcp_args.go index bdd7af6ef7..e492a645ef 100644 --- a/internal/mcp/mcp_args.go +++ b/internal/mcp/mcp_args.go @@ -93,5 +93,7 @@ func BuildArgFlagSet(tool *ToolDef) (*flag.FlagSet, map[string]any, error) { } } + flagVars["json"] = fs.String("json", "", "provide all arguments as a JSON object") + return fs, flagVars, nil } From c921cc5f31286284644d60cdb267091d3b2fc91f Mon Sep 17 00:00:00 2001 From: Vincent Date: Thu, 8 Jan 2026 15:42:49 +0000 Subject: [PATCH 532/647] set content-type json on API requests (#1247) --- internal/api/api.go | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/internal/api/api.go b/internal/api/api.go index e0bc234558..5f750c1d4a 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -174,6 +174,10 @@ func (c *client) createHTTPRequest(ctx context.Context, method, p string, body i if *c.opts.Flags.trace { req.Header.Set("X-Sourcegraph-Should-Trace", "true") } + + // Set before additional headers, in case of an override. + req.Header.Set("Content-Type", "application/json") + for k, v := range c.opts.AdditionalHeaders { req.Header.Set(k, v) } @@ -322,6 +326,10 @@ func (r *request) curlCmd() (string, error) { if r.client.opts.AccessToken != "" { s += fmt.Sprintf(" %s \\\n", shellquote.Join("-H", "Authorization: token "+r.client.opts.AccessToken)) } + // Preserve overrides if Content-Type is set + if r.client.opts.AdditionalHeaders["Content-Type"] == "" { + r.client.opts.AdditionalHeaders["Content-Type"] = "application/json" + } for k, v := range r.client.opts.AdditionalHeaders { s += fmt.Sprintf(" %s \\\n", shellquote.Join("-H", k+": "+v)) } From 9657119f296299723948a6fd79d7ae523af4d1b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Kie=C5=82bowicz?= Date: Fri, 9 Jan 2026 15:58:16 +0100 Subject: [PATCH 533/647] feat(lsp): expose Sourcegraph Precise code navigation through LSP (#1243) Implements an LSP server that proxies requests to Sourcegraph's code intelligence backend via GraphQL. The server communicates over stdio and is designed for use with editors like Neovim or coding agents like Claude Code. --- cmd/src/lsp.go | 70 +++++++ go.mod | 34 ++-- go.sum | 69 ++++--- internal/codeintel/gitutil.go | 10 + internal/lsp/query.go | 290 +++++++++++++++++++++++++++ internal/lsp/query_test.go | 361 ++++++++++++++++++++++++++++++++++ internal/lsp/server.go | 322 ++++++++++++++++++++++++++++++ internal/lsp/server_test.go | 284 ++++++++++++++++++++++++++ 8 files changed, 1405 insertions(+), 35 deletions(-) create mode 100644 cmd/src/lsp.go create mode 100644 internal/lsp/query.go create mode 100644 internal/lsp/query_test.go create mode 100644 internal/lsp/server.go create mode 100644 internal/lsp/server_test.go diff --git a/cmd/src/lsp.go b/cmd/src/lsp.go new file mode 100644 index 0000000000..e6d5608f13 --- /dev/null +++ b/cmd/src/lsp.go @@ -0,0 +1,70 @@ +package main + +import ( + "flag" + "fmt" + "io" + + "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/lsp" +) + +func init() { + usage := ` +'src lsp' runs a Language Server Protocol server that proxies LSP +requests to Sourcegraph's code intelligence backend. + +The server communicates over stdio (stdin/stdout) and is designed +to be used with editors like Neovim. + +Prerequisites: + - The working directory must be inside a Git repository + - The repository must be indexed on your Sourcegraph instance + - SRC_ENDPOINT and SRC_ACCESS_TOKEN environment variables must be set + +Supported LSP methods: + - textDocument/definition + - textDocument/references + - textDocument/hover + - textDocument/documentHighlight + +Example Neovim configuration (0.11+): + + vim.lsp.config['src-lsp'] = { + cmd = { 'src', 'lsp' }, + root_markers = { '.git' }, + filetypes = { 'go', 'typescript', 'python' }, + } + vim.lsp.enable('src-lsp') +` + + flagSet := flag.NewFlagSet("lsp", flag.ExitOnError) + apiFlags := api.NewFlags(flagSet) + + usageFunc := func() { + fmt.Println(usage) + fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src %s':\n", flagSet.Name()) + flagSet.PrintDefaults() + } + + handler := func(args []string) error { + if err := flagSet.Parse(args); err != nil { + return err + } + + client := cfg.apiClient(apiFlags, io.Discard) + + srv, err := lsp.NewServer(client) + if err != nil { + return err + } + + return srv.Run() + } + + commands = append(commands, &command{ + flagSet: flagSet, + handler: handler, + usageFunc: usageFunc, + }) +} diff --git a/go.mod b/go.mod index c0c693132e..3c9e3eb338 100644 --- a/go.mod +++ b/go.mod @@ -29,15 +29,15 @@ require ( github.com/sourcegraph/scip v0.6.1 github.com/sourcegraph/sourcegraph/lib v0.0.0-20240709083501-1af563b61442 github.com/stretchr/testify v1.11.1 - golang.org/x/net v0.47.0 + github.com/tliron/glsp v0.2.2 golang.org/x/sync v0.18.0 google.golang.org/api v0.256.0 google.golang.org/protobuf v1.36.10 gopkg.in/yaml.v3 v3.0.1 jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7 - k8s.io/api v0.32.3 - k8s.io/apimachinery v0.32.3 - k8s.io/client-go v0.32.3 + k8s.io/api v0.33.2 + k8s.io/apimachinery v0.33.2 + k8s.io/client-go v0.33.2 ) require ( @@ -79,11 +79,13 @@ require ( github.com/go-jose/go-jose/v4 v4.1.2 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/gofrs/uuid/v5 v5.0.0 // indirect - github.com/google/gnostic-models v0.6.8 // indirect - github.com/google/go-containerregistry v0.15.2 // indirect + github.com/google/gnostic-models v0.6.9 // indirect + github.com/google/go-containerregistry v0.19.1 // indirect github.com/google/pprof v0.0.0-20241029153458-d1b30febd7db // indirect github.com/google/s2a-go v0.1.9 // indirect + github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2 // indirect + github.com/iancoleman/strcase v0.3.0 // indirect github.com/jackc/chunkreader/v2 v2.0.1 // indirect github.com/jackc/pgconn v1.14.3 // indirect github.com/jackc/pgio v1.0.0 // indirect @@ -95,12 +97,18 @@ require ( github.com/morikuni/aec v1.0.0 // indirect github.com/opencontainers/go-digest v1.0.0 // indirect github.com/opencontainers/image-spec v1.1.0-rc4 // indirect + github.com/petermattis/goid v0.0.0-20240813172612-4fcff4a6cae7 // indirect github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 // indirect github.com/rs/cors v1.11.0 // indirect + github.com/sasha-s/go-deadlock v0.3.5 // indirect + github.com/segmentio/ksuid v1.0.4 // indirect github.com/sirupsen/logrus v1.9.3 // indirect github.com/sourcegraph/beaut v0.0.0-20240611013027-627e4c25335a // indirect + github.com/sourcegraph/jsonrpc2 v0.2.0 // indirect github.com/spiffe/go-spiffe/v2 v2.5.0 // indirect github.com/tetratelabs/wazero v1.3.0 // indirect + github.com/tliron/commonlog v0.2.19 // indirect + github.com/tliron/kutil v0.3.27 // indirect github.com/vbatts/tar-split v0.11.3 // indirect github.com/x448/float16 v0.8.4 // indirect github.com/xlab/treeprint v1.2.0 // indirect @@ -117,10 +125,12 @@ require ( go.opentelemetry.io/otel/sdk/metric v1.38.0 // indirect go.opentelemetry.io/otel/trace v1.38.0 // indirect go.opentelemetry.io/proto/otlp v1.7.1 // indirect + golang.org/x/net v0.47.0 // indirect golang.org/x/telemetry v0.0.0-20251008203120-078029d740a8 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20250825161204-c5933d9347a5 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20251103181224-f26f9409b101 // indirect gopkg.in/evanphx/json-patch.v4 v4.12.0 // indirect + sigs.k8s.io/randfill v1.0.0 // indirect ) require ( @@ -149,12 +159,12 @@ require ( github.com/cockroachdb/errors v1.12.0 // indirect github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect github.com/cockroachdb/redact v1.1.6 // indirect - github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect + github.com/cpuguy83/go-md2man/v2 v2.0.6 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/dlclark/regexp2 v1.11.0 // indirect github.com/emicklei/go-restful/v3 v3.11.0 // indirect github.com/envoyproxy/protoc-gen-validate v1.2.1 // indirect - github.com/fatih/color v1.15.0 // indirect + github.com/fatih/color v1.16.0 // indirect github.com/getsentry/sentry-go v0.27.0 // indirect github.com/ghodss/yaml v1.0.0 // indirect github.com/go-logr/logr v1.4.3 // indirect @@ -205,8 +215,8 @@ require ( github.com/rogpeppe/go-internal v1.13.1 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect github.com/sourcegraph/log v0.0.0-20250923023806-517b6960b55b // indirect - github.com/spf13/cobra v1.7.0 // indirect - github.com/spf13/pflag v1.0.5 // indirect + github.com/spf13/cobra v1.9.1 // indirect + github.com/spf13/pflag v1.0.6 // indirect github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect github.com/stretchr/objx v0.5.2 // indirect github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect @@ -230,11 +240,11 @@ require ( gopkg.in/inf.v0 v0.9.1 // indirect; direct gopkg.in/yaml.v2 v2.4.0 // indirect k8s.io/klog/v2 v2.130.1 // indirect - k8s.io/kube-openapi v0.0.0-20241105132330-32ad38e42d3f // indirect + k8s.io/kube-openapi v0.0.0-20250318190949-c8a335a9a2ff // indirect k8s.io/utils v0.0.0-20241104100929-3ea5e8cea738 // indirect mvdan.cc/gofumpt v0.5.0 // indirect sigs.k8s.io/json v0.0.0-20241010143419-9aa6b5e7a4b3 // indirect - sigs.k8s.io/structured-merge-diff/v4 v4.4.2 // indirect + sigs.k8s.io/structured-merge-diff/v4 v4.6.0 // indirect sigs.k8s.io/yaml v1.4.0 // indirect ) diff --git a/go.sum b/go.sum index 22f5dcf5a7..f47d1d10c9 100644 --- a/go.sum +++ b/go.sum @@ -131,13 +131,14 @@ github.com/containerd/log v0.1.0 h1:TCJt7ioM2cr/tfR8GPbGf9/VRAX8D2B4PjzCpfX540I= github.com/containerd/log v0.1.0/go.mod h1:VRRf09a7mHDIRezVKTRCrOq78v577GXq3bSa3EhrzVo= github.com/containerd/stargz-snapshotter/estargz v0.14.3 h1:OqlDCK3ZVUO6C3B/5FSkDwbkEETK84kQgEeFwDC+62k= github.com/containerd/stargz-snapshotter/estargz v0.14.3/go.mod h1:KY//uOCIkSuNAHhJogcZtrNHdKrA99/FCCRjE3HD36o= -github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w= github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= +github.com/cpuguy83/go-md2man/v2 v2.0.6 h1:XJtiaUW6dEEqVuZiMTn1ldk455QWwEIsMIJlo5vtkx0= +github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= github.com/creack/goselect v0.1.2 h1:2DNy14+JPjRBgPzAd1thbQp4BSIihxcBf0IXhQXDRa0= github.com/creack/goselect v0.1.2/go.mod h1:a/NhLweNvqIYMuxcMOuWY516Cimucms3DglDzQP3hKY= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= -github.com/creack/pty v1.1.18 h1:n56/Zwd5o6whRC5PMGretI4IdRLlmBXYNjScPaBgsbY= -github.com/creack/pty v1.1.18/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4= +github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s= +github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= @@ -175,8 +176,8 @@ github.com/envoyproxy/go-control-plane/ratelimit v0.1.0/go.mod h1:Wk+tMFAFbCXaJP github.com/envoyproxy/protoc-gen-validate v1.2.1 h1:DEo3O99U8j4hBFwbJfrz9VtgcDfUKS7KJ7spH3d86P8= github.com/envoyproxy/protoc-gen-validate v1.2.1/go.mod h1:d/C80l/jxXLdfEIhX1W2TmLfsJ31lvEjwamM4DxlWXU= github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= -github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs= -github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw= +github.com/fatih/color v1.16.0 h1:zmkK9Ngbjj+K0yRhTVONQh1p/HknKYSlNT+vZCzyokM= +github.com/fatih/color v1.16.0/go.mod h1:fL2Sau1YI5c0pdGEVCbKQbLXB6edEj1ZgiY4NijnWvE= github.com/felixge/fgprof v0.9.3 h1:VvyZxILNuCiUCSXtPtYmmtGvb65nqXh2QFWc0Wpf2/g= github.com/felixge/fgprof v0.9.3/go.mod h1:RdbpDgzqYVh/T9fPELJyV7EYJuHB55UTEULNun8eiPw= github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= @@ -221,8 +222,8 @@ github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69 github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= -github.com/google/gnostic-models v0.6.8 h1:yo/ABAfM5IMRsS1VnXjTBvUb61tFIHozhlYvRgGre9I= -github.com/google/gnostic-models v0.6.8/go.mod h1:5n7qKqH0f5wFt+aWF8CW6pZLLNOfYuF5OpfBSENuI8U= +github.com/google/gnostic-models v0.6.9 h1:MU/8wDLif2qCXZmzncUQ/BOfxWfthHi63KqpoNbWqVw= +github.com/google/gnostic-models v0.6.9/go.mod h1:CiWsm0s6BSQd1hRn8/QmxqB6BesYcbSZxsz9b0KuDBw= github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE= @@ -230,8 +231,8 @@ github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeN github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= -github.com/google/go-containerregistry v0.15.2 h1:MMkSh+tjSdnmJZO7ljvEqV1DjfekB6VUEAZgy3a+TQE= -github.com/google/go-containerregistry v0.15.2/go.mod h1:wWK+LnOv4jXMM23IT/F1wdYftGWGr47Is8CG+pmHK1Q= +github.com/google/go-containerregistry v0.19.1 h1:yMQ62Al6/V0Z7CqIrrS1iYoA5/oQCm88DeNujc7C1KY= +github.com/google/go-containerregistry v0.19.1/go.mod h1:YCMFNQeeXeLF+dnhhWkqDItx/JSkH01j1Kis4PsjzFI= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= @@ -250,6 +251,9 @@ github.com/googleapis/gax-go/v2 v2.15.0 h1:SyjDc1mGgZU5LncH8gimWo9lW1DtIfPibOG81 github.com/googleapis/gax-go/v2 v2.15.0/go.mod h1:zVVkkxAQHa1RQpg9z2AUCMnKhi0Qld9rcmyfL1OZhoc= github.com/gorilla/css v1.0.1 h1:ntNaBIghp6JmvWnxbZKANoLyuXTPZ4cAMlo6RyhlbO8= github.com/gorilla/css v1.0.1/go.mod h1:BvnYkspnSzMmwRK+b8/xgNPLiIuNZr6vbZBTPQ2A3b0= +github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 h1:JeSE6pjso5THxAzdVpqr6/geYxZytqFMBCOtn/ujyeo= +github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674/go.mod h1:r4w70xmWCQKmi1ONH4KIaBptdivuRPyosB9RmPlGEwA= github.com/grafana/regexp v0.0.0-20250905093917-f7b3be9d1853 h1:cLN4IBkmkYZNnk7EAJ0BHIethd+J6LqxFNw5mSiI2bM= github.com/grafana/regexp v0.0.0-20250905093917-f7b3be9d1853/go.mod h1:+JKpmjMGhpgPL+rXZ5nsZieVzvarn86asRlBg4uNGnk= github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2 h1:8Tjv8EJ+pM1xP8mK6egEbD1OgnVTyacbefKhmbLhIhU= @@ -266,6 +270,8 @@ github.com/hexops/valast v1.4.4 h1:rETyycw+/L2ZVJHHNxEBgh8KUn+87WugH9MxcEv9PGs= github.com/hexops/valast v1.4.4/go.mod h1:Jcy1pNH7LNraVaAZDLyv21hHg2WBv9Nf9FL6fGxU7o4= github.com/huandu/xstrings v1.3.2 h1:L18LIDzqlW6xN2rEkpdV8+oL/IXWJ1APd+vsdYy4Wdw= github.com/huandu/xstrings v1.3.2/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE= +github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI= +github.com/iancoleman/strcase v0.3.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho= github.com/ianlancetaylor/demangle v0.0.0-20210905161508-09a460cdf81d/go.mod h1:aYm2/VgdVmcIU8iMfdMvDMsRAQjcfZSKFby6HOFvi/w= github.com/imdario/mergo v0.3.16 h1:wwQJbIsHYGMUyLSPrEq1CT16AhnhNJQ51+4fdHUnCl4= github.com/imdario/mergo v0.3.16/go.mod h1:WBLT9ZmE3lPoWsEzCh9LPo3TiwVN+ZKEjmz+hD27ysY= @@ -378,6 +384,8 @@ github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8 github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= github.com/opencontainers/image-spec v1.1.0-rc4 h1:oOxKUJWnFC4YGHCCMNql1x4YaDfYBTS5Y4x/Cgeo1E0= github.com/opencontainers/image-spec v1.1.0-rc4/go.mod h1:X4pATf0uXsnn3g5aiGIsVnJBR4mxhKzfwmvK/B2NTm8= +github.com/petermattis/goid v0.0.0-20240813172612-4fcff4a6cae7 h1:Dx7Ovyv/SFnMFw3fD4oEoeorXc6saIiQ23LrGLth0Gw= +github.com/petermattis/goid v0.0.0-20240813172612-4fcff4a6cae7/go.mod h1:pxMtw7cyUw6B2bRH0ZBANSPg+AoSud1I1iyJHI69jH4= github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4= github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8= github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 h1:KoWmjvw+nsYOo29YJK9vDA65RGE3NrOnUtO7a+RF9HU= @@ -408,6 +416,10 @@ github.com/rs/cors v1.11.0 h1:0B9GE/r9Bc2UxRMMtymBkHTenPkHDv0CW4Y98GBY+po= github.com/rs/cors v1.11.0/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU= github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/sasha-s/go-deadlock v0.3.5 h1:tNCOEEDG6tBqrNDOX35j/7hL5FcFViG6awUGROb2NsU= +github.com/sasha-s/go-deadlock v0.3.5/go.mod h1:bugP6EGbdGYObIlx7pUZtWqlvo8k9H6vCBBsiChJQ5U= +github.com/segmentio/ksuid v1.0.4 h1:sBo2BdShXjmcugAMwjugoGUdUV0pcxY5mW4xKRn3v4c= +github.com/segmentio/ksuid v1.0.4/go.mod h1:/XUiZBD3kVx5SmUOl55voK5yeAbBNNIed+2O73XgrPE= github.com/shurcooL/go v0.0.0-20180423040247-9e1955d9fb6e/go.mod h1:TDJrrUr11Vxrven61rcy3hJMUqaf/CLWYhHNPmT14Lk= github.com/shurcooL/go-goon v0.0.0-20170922171312-37c2f522c041/go.mod h1:N5mDOmsrJOB+vfqUK+7DmDyjhSLIIBnXo9lvZJj3MWQ= github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= @@ -419,6 +431,8 @@ github.com/sourcegraph/conc v0.3.1-0.20240108182409-4afefce20f9b h1:0FsjN+u9fNXT github.com/sourcegraph/conc v0.3.1-0.20240108182409-4afefce20f9b/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0= github.com/sourcegraph/go-diff v0.7.0 h1:9uLlrd5T46OXs5qpp8L/MTltk0zikUGi0sNNyCpA8G0= github.com/sourcegraph/go-diff v0.7.0/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= +github.com/sourcegraph/jsonrpc2 v0.2.0 h1:KjN/dC4fP6aN9030MZCJs9WQbTOjWHhrtKVpzzSrr/U= +github.com/sourcegraph/jsonrpc2 v0.2.0/go.mod h1:ZafdZgk/axhT1cvZAPOhw+95nz2I/Ra5qMlU4gTRwIo= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= github.com/sourcegraph/log v0.0.0-20250923023806-517b6960b55b h1:2FQ72y5zECMu9e5z5jMnllb5n1jVK7qsvgjkVtdFV+g= @@ -427,10 +441,10 @@ github.com/sourcegraph/scip v0.6.1 h1:lcBrTwGjsqpMLQN4pVfJYSB+8oVoc8Lnqb4FAfU8EB github.com/sourcegraph/scip v0.6.1/go.mod h1:c6d9mk1cGT6OXdHutxDakKVEPN1D+iFoYWCsrDxEhus= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= -github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I= -github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0= -github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= -github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/cobra v1.9.1 h1:CXSaggrXdbHK9CF+8ywj8Amf7PBRmPCOJugH954Nnlo= +github.com/spf13/cobra v1.9.1/go.mod h1:nDyEzZ8ogv936Cinf6g1RU9MRY64Ir93oCnqb9wxYW0= +github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o= +github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spiffe/go-spiffe/v2 v2.5.0 h1:N2I01KCUkv1FAjZXJMwh95KK1ZIQLYbPfhaxw8WS0hE= github.com/spiffe/go-spiffe/v2 v2.5.0/go.mod h1:P+NxobPc6wXhVtINNtFjNWGBTreew1GBUCwT2wPmb7g= github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf h1:pvbZ0lM0XWPBqUKqFU8cmavspvIl9nulOYwdy6IFRRo= @@ -451,6 +465,12 @@ github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/tetratelabs/wazero v1.3.0 h1:nqw7zCldxE06B8zSZAY0ACrR9OH5QCcPwYmYlwtcwtE= github.com/tetratelabs/wazero v1.3.0/go.mod h1:wYx2gNRg8/WihJfSDxA1TIL8H+GkfLYm+bIfbblu9VQ= +github.com/tliron/commonlog v0.2.19 h1:v1mOH1TyzFLqkshR03khw7ENAZPjAyZTQBQrqN+vX9c= +github.com/tliron/commonlog v0.2.19/go.mod h1:AcdhfcUqlAWukDrzTGyaPhUgYiNdZhS4dKzD/e0tjcY= +github.com/tliron/glsp v0.2.2 h1:IKPfwpE8Lu8yB6Dayta+IyRMAbTVunudeauEgjXBt+c= +github.com/tliron/glsp v0.2.2/go.mod h1:GMVWDNeODxHzmDPvYbYTCs7yHVaEATfYtXiYJ9w1nBg= +github.com/tliron/kutil v0.3.27 h1:Wb0V5jdbTci6Let1tiGY741J/9FIynmV/pCsPDPsjcM= +github.com/tliron/kutil v0.3.27/go.mod h1:AHeLNIFBSKBU39ELVHZdkw2f/ez2eKGAAGoxwBlhMi8= github.com/urfave/cli v1.22.12/go.mod h1:sSBEIC79qR6OvcmsD4U3KABeOTxDqQtdDnaFuUN30b8= github.com/vbatts/tar-split v0.11.3 h1:hLFqsOLQ1SsppQNTMpkpPXClLDfC2A3Zgy9OUU+RVck= github.com/vbatts/tar-split v0.11.3/go.mod h1:9QlHN18E+fEH7RdG+QAJJcuya3rqT7eXSTY7wGrAokY= @@ -629,16 +649,16 @@ gotest.tools/v3 v3.0.3 h1:4AuOwCGf4lLR9u3YOe2awrHygurzhO/HeQ6laiA6Sx0= gotest.tools/v3 v3.0.3/go.mod h1:Z7Lb0S5l+klDB31fvDQX8ss/FlKDxtlFlw3Oa8Ymbl8= jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7 h1:mub0MmFLOn8XLikZOAhgLD1kXJq8jgftSrrv7m00xFo= jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7/go.mod h1:OxvTsCwKosqQ1q7B+8FwXqg4rKZ/UG9dUW+g/VL2xH4= -k8s.io/api v0.32.3 h1:Hw7KqxRusq+6QSplE3NYG4MBxZw1BZnq4aP4cJVINls= -k8s.io/api v0.32.3/go.mod h1:2wEDTXADtm/HA7CCMD8D8bK4yuBUptzaRhYcYEEYA3k= -k8s.io/apimachinery v0.32.3 h1:JmDuDarhDmA/Li7j3aPrwhpNBA94Nvk5zLeOge9HH1U= -k8s.io/apimachinery v0.32.3/go.mod h1:GpHVgxoKlTxClKcteaeuF1Ul/lDVb74KpZcxcmLDElE= -k8s.io/client-go v0.32.3 h1:RKPVltzopkSgHS7aS98QdscAgtgah/+zmpAogooIqVU= -k8s.io/client-go v0.32.3/go.mod h1:3v0+3k4IcT9bXTc4V2rt+d2ZPPG700Xy6Oi0Gdl2PaY= +k8s.io/api v0.33.2 h1:YgwIS5jKfA+BZg//OQhkJNIfie/kmRsO0BmNaVSimvY= +k8s.io/api v0.33.2/go.mod h1:fhrbphQJSM2cXzCWgqU29xLDuks4mu7ti9vveEnpSXs= +k8s.io/apimachinery v0.33.2 h1:IHFVhqg59mb8PJWTLi8m1mAoepkUNYmptHsV+Z1m5jY= +k8s.io/apimachinery v0.33.2/go.mod h1:BHW0YOu7n22fFv/JkYOEfkUYNRN0fj0BlvMFWA7b+SM= +k8s.io/client-go v0.33.2 h1:z8CIcc0P581x/J1ZYf4CNzRKxRvQAwoAolYPbtQes+E= +k8s.io/client-go v0.33.2/go.mod h1:9mCgT4wROvL948w6f6ArJNb7yQd7QsvqavDeZHvNmHo= k8s.io/klog/v2 v2.130.1 h1:n9Xl7H1Xvksem4KFG4PYbdQCQxqc/tTUyrgXaOhHSzk= k8s.io/klog/v2 v2.130.1/go.mod h1:3Jpz1GvMt720eyJH1ckRHK1EDfpxISzJ7I9OYgaDtPE= -k8s.io/kube-openapi v0.0.0-20241105132330-32ad38e42d3f h1:GA7//TjRY9yWGy1poLzYYJJ4JRdzg3+O6e8I+e+8T5Y= -k8s.io/kube-openapi v0.0.0-20241105132330-32ad38e42d3f/go.mod h1:R/HEjbvWI0qdfb8viZUeVZm0X6IZnxAydC7YU42CMw4= +k8s.io/kube-openapi v0.0.0-20250318190949-c8a335a9a2ff h1:/usPimJzUKKu+m+TE36gUyGcf03XZEP0ZIKgKj35LS4= +k8s.io/kube-openapi v0.0.0-20250318190949-c8a335a9a2ff/go.mod h1:5jIi+8yX4RIb8wk3XwBo5Pq2ccx4FP10ohkbSKCZoK8= k8s.io/utils v0.0.0-20241104100929-3ea5e8cea738 h1:M3sRQVHv7vB20Xc2ybTt7ODCeFj6JSWYFzOFnYeS6Ro= k8s.io/utils v0.0.0-20241104100929-3ea5e8cea738/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= mvdan.cc/gofumpt v0.4.0/go.mod h1:PljLOHDeZqgS8opHRKLzp2It2VBuSdteAgqUfzMTxlQ= @@ -648,7 +668,10 @@ pgregory.net/rapid v1.1.0 h1:CMa0sjHSru3puNx+J0MIAuiiEV4N0qj8/cMWGBBCsjw= pgregory.net/rapid v1.1.0/go.mod h1:PY5XlDGj0+V1FCq0o192FdRhpKHGTRIWBgqjDBTrq04= sigs.k8s.io/json v0.0.0-20241010143419-9aa6b5e7a4b3 h1:/Rv+M11QRah1itp8VhT6HoVx1Ray9eB4DBr+K+/sCJ8= sigs.k8s.io/json v0.0.0-20241010143419-9aa6b5e7a4b3/go.mod h1:18nIHnGi6636UCz6m8i4DhaJ65T6EruyzmoQqI2BVDo= -sigs.k8s.io/structured-merge-diff/v4 v4.4.2 h1:MdmvkGuXi/8io6ixD5wud3vOLwc1rj0aNqRlpuvjmwA= -sigs.k8s.io/structured-merge-diff/v4 v4.4.2/go.mod h1:N8f93tFZh9U6vpxwRArLiikrE5/2tiu1w1AGfACIGE4= +sigs.k8s.io/randfill v0.0.0-20250304075658-069ef1bbf016/go.mod h1:XeLlZ/jmk4i1HRopwe7/aU3H5n1zNUcX6TM94b3QxOY= +sigs.k8s.io/randfill v1.0.0 h1:JfjMILfT8A6RbawdsK2JXGBR5AQVfd+9TbzrlneTyrU= +sigs.k8s.io/randfill v1.0.0/go.mod h1:XeLlZ/jmk4i1HRopwe7/aU3H5n1zNUcX6TM94b3QxOY= +sigs.k8s.io/structured-merge-diff/v4 v4.6.0 h1:IUA9nvMmnKWcj5jl84xn+T5MnlZKThmUW1TdblaLVAc= +sigs.k8s.io/structured-merge-diff/v4 v4.6.0/go.mod h1:dDy58f92j70zLsuZVuUX5Wp9vtxXpaZnkPGWeqDfCps= sigs.k8s.io/yaml v1.4.0 h1:Mk1wCc2gy/F0THH0TAp1QYyJNzRm2KCLy3o5ASXVI5E= sigs.k8s.io/yaml v1.4.0/go.mod h1:Ejl7/uTz7PSA4eKMyQCUTnhZYNmLIl+5c2lQPGR2BPY= diff --git a/internal/codeintel/gitutil.go b/internal/codeintel/gitutil.go index 7fc6bad55f..81672adf16 100644 --- a/internal/codeintel/gitutil.go +++ b/internal/codeintel/gitutil.go @@ -43,6 +43,16 @@ func InferCommit() (string, error) { return runGitCommand("rev-parse", "HEAD") } +// InferMergeBase returns the merge-base between HEAD and origin/HEAD. +func InferMergeBase() (string, error) { + return runGitCommand("merge-base", "HEAD", "origin/HEAD") +} + +// GitRoot returns the absolute path to the root of the git repository. +func GitRoot() (string, error) { + return runGitCommand("rev-parse", "--show-toplevel") +} + // InferRoot gets the path relative to the root of the git clone enclosing the given file path. func InferRoot(file string) (string, error) { topLevel, err := runGitCommand("rev-parse", "--show-toplevel") diff --git a/internal/lsp/query.go b/internal/lsp/query.go new file mode 100644 index 0000000000..6665549483 --- /dev/null +++ b/internal/lsp/query.go @@ -0,0 +1,290 @@ +package lsp + +import "context" + +type Position struct { + Line int `json:"line"` + Character int `json:"character"` +} + +type RangeResult struct { + Start Position `json:"start"` + End Position `json:"end"` +} + +type LocationNode struct { + Resource struct { + Path string `json:"path"` + Repository struct { + Name string `json:"name"` + } `json:"repository"` + Commit struct { + OID string `json:"oid"` + } `json:"commit"` + } `json:"resource"` + Range RangeResult `json:"range"` +} + +// Hover + +const hoverQuery = ` +query Hover( + $repository: String! + $commit: String! + $path: String! + $line: Int! + $character: Int! +) { + repository(name: $repository) { + commit(rev: $commit) { + blob(path: $path) { + lsif { + hover(line: $line, character: $character) { + markdown { + text + } + range { + start { + line + character + } + end { + line + character + } + } + } + } + } + } + } +} +` + +type HoverResult struct { + Markdown struct { + Text string `json:"text"` + } `json:"markdown"` + Range *RangeResult `json:"range"` +} + +type hoverResponse struct { + Repository *struct { + Commit *struct { + Blob *struct { + LSIF *struct { + Hover *HoverResult `json:"hover"` + } `json:"lsif"` + } `json:"blob"` + } `json:"commit"` + } `json:"repository"` +} + +func (s *Server) queryHover( + ctx context.Context, path string, line, character int, +) (*HoverResult, error) { + vars := map[string]any{ + "repository": s.repoName, + "commit": s.commit, + "path": path, + "line": line, + "character": character, + } + + var result hoverResponse + ok, err := s.apiClient.NewRequest(hoverQuery, vars).Do(ctx, &result) + if err != nil { + return nil, err + } + if !ok { + return nil, nil + } + + if result.Repository == nil || + result.Repository.Commit == nil || + result.Repository.Commit.Blob == nil || + result.Repository.Commit.Blob.LSIF == nil || + result.Repository.Commit.Blob.LSIF.Hover == nil { + return nil, nil + } + + return result.Repository.Commit.Blob.LSIF.Hover, nil +} + +// Definitions + +const definitionsQuery = ` +query Definitions( + $repository: String! + $commit: String! + $path: String! + $line: Int! + $character: Int! +) { + repository(name: $repository) { + commit(rev: $commit) { + blob(path: $path) { + lsif { + definitions(line: $line, character: $character) { + nodes { + resource { + path + repository { + name + } + commit { + oid + } + } + range { + start { + line + character + } + end { + line + character + } + } + } + } + } + } + } + } +} +` + +type definitionsResponse struct { + Repository *struct { + Commit *struct { + Blob *struct { + LSIF *struct { + Definitions *struct { + Nodes []LocationNode `json:"nodes"` + } `json:"definitions"` + } `json:"lsif"` + } `json:"blob"` + } `json:"commit"` + } `json:"repository"` +} + +func (s *Server) queryDefinitions( + ctx context.Context, path string, line, character int, +) ([]LocationNode, error) { + vars := map[string]any{ + "repository": s.repoName, + "commit": s.commit, + "path": path, + "line": line, + "character": character, + } + + var result definitionsResponse + ok, err := s.apiClient.NewRequest(definitionsQuery, vars).Do(ctx, &result) + if err != nil { + return nil, err + } + if !ok { + return nil, nil + } + + if result.Repository == nil || + result.Repository.Commit == nil || + result.Repository.Commit.Blob == nil || + result.Repository.Commit.Blob.LSIF == nil || + result.Repository.Commit.Blob.LSIF.Definitions == nil { + return nil, nil + } + + return result.Repository.Commit.Blob.LSIF.Definitions.Nodes, nil +} + +// References + +const referencesQuery = ` +query References( + $repository: String! + $commit: String! + $path: String! + $line: Int! + $character: Int! +) { + repository(name: $repository) { + commit(rev: $commit) { + blob(path: $path) { + lsif { + references(line: $line, character: $character, first: 100) { + nodes { + resource { + path + repository { + name + } + commit { + oid + } + } + range { + start { + line + character + } + end { + line + character + } + } + } + } + } + } + } + } +} +` + +type referencesResponse struct { + Repository *struct { + Commit *struct { + Blob *struct { + LSIF *struct { + References *struct { + Nodes []LocationNode `json:"nodes"` + } `json:"references"` + } `json:"lsif"` + } `json:"blob"` + } `json:"commit"` + } `json:"repository"` +} + +func (s *Server) queryReferences( + ctx context.Context, path string, line, character int, +) ([]LocationNode, error) { + vars := map[string]any{ + "repository": s.repoName, + "commit": s.commit, + "path": path, + "line": line, + "character": character, + } + + var result referencesResponse + ok, err := s.apiClient.NewRequest(referencesQuery, vars).Do(ctx, &result) + if err != nil { + return nil, err + } + if !ok { + return nil, nil + } + + if result.Repository == nil || + result.Repository.Commit == nil || + result.Repository.Commit.Blob == nil || + result.Repository.Commit.Blob.LSIF == nil || + result.Repository.Commit.Blob.LSIF.References == nil { + return nil, nil + } + + return result.Repository.Commit.Blob.LSIF.References.Nodes, nil +} diff --git a/internal/lsp/query_test.go b/internal/lsp/query_test.go new file mode 100644 index 0000000000..40653dadbb --- /dev/null +++ b/internal/lsp/query_test.go @@ -0,0 +1,361 @@ +package lsp + +import ( + "context" + "testing" + + "github.com/sourcegraph/src-cli/internal/api/mock" + "github.com/stretchr/testify/require" +) + +func TestQueryHover(t *testing.T) { + tests := []struct { + name string + response string + wantText string + wantRange *RangeResult + wantNil bool + }{ + { + name: "successful hover with range", + response: `{ + "repository": { + "commit": { + "blob": { + "lsif": { + "hover": { + "markdown": {"text": "func main()"}, + "range": { + "start": {"line": 10, "character": 5}, + "end": {"line": 10, "character": 9} + } + } + } + } + } + } + }`, + wantText: "func main()", + wantRange: &RangeResult{ + Start: Position{Line: 10, Character: 5}, + End: Position{Line: 10, Character: 9}, + }, + }, + { + name: "hover without range", + response: `{ + "repository": { + "commit": { + "blob": { + "lsif": { + "hover": { + "markdown": {"text": "type Config struct"} + } + } + } + } + } + }`, + wantText: "type Config struct", + wantRange: nil, + }, + { + name: "no hover data", + response: `{ + "repository": { + "commit": { + "blob": { + "lsif": { + "hover": null + } + } + } + } + }`, + wantNil: true, + }, + { + name: "no lsif data", + response: `{ + "repository": { + "commit": { + "blob": { + "lsif": null + } + } + } + }`, + wantNil: true, + }, + { + name: "empty response", + response: `{"repository": null}`, + wantNil: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + mockClient := &mock.Client{} + mockRequest := &mock.Request{Response: tt.response} + mockRequest.On("Do", context.Background(), &hoverResponse{}). + Return(true, nil) + mockClient.On("NewRequest", hoverQuery, map[string]any{ + "repository": "github.com/test/repo", + "commit": "abc123", + "path": "main.go", + "line": 10, + "character": 5, + }).Return(mockRequest) + + s := &Server{ + apiClient: mockClient, + repoName: "github.com/test/repo", + commit: "abc123", + } + + result, err := s.queryHover(context.Background(), "main.go", 10, 5) + require.NoError(t, err) + + if tt.wantNil { + require.Nil(t, result) + return + } + + require.NotNil(t, result) + require.Equal(t, tt.wantText, result.Markdown.Text) + if tt.wantRange != nil { + require.NotNil(t, result.Range) + require.Equal(t, tt.wantRange.Start.Line, result.Range.Start.Line) + require.Equal(t, tt.wantRange.Start.Character, result.Range.Start.Character) + require.Equal(t, tt.wantRange.End.Line, result.Range.End.Line) + require.Equal(t, tt.wantRange.End.Character, result.Range.End.Character) + } else { + require.Nil(t, result.Range) + } + }) + } +} + +func TestQueryDefinitions(t *testing.T) { + tests := []struct { + name string + response string + wantCount int + wantNil bool + }{ + { + name: "single definition", + response: `{ + "repository": { + "commit": { + "blob": { + "lsif": { + "definitions": { + "nodes": [{ + "resource": { + "path": "pkg/utils.go", + "repository": {"name": "github.com/test/repo"}, + "commit": {"oid": "abc123"} + }, + "range": { + "start": {"line": 20, "character": 0}, + "end": {"line": 20, "character": 10} + } + }] + } + } + } + } + } + }`, + wantCount: 1, + }, + { + name: "multiple definitions", + response: `{ + "repository": { + "commit": { + "blob": { + "lsif": { + "definitions": { + "nodes": [ + { + "resource": { + "path": "pkg/a.go", + "repository": {"name": "github.com/test/repo"}, + "commit": {"oid": "abc123"} + }, + "range": { + "start": {"line": 10, "character": 0}, + "end": {"line": 10, "character": 5} + } + }, + { + "resource": { + "path": "pkg/b.go", + "repository": {"name": "github.com/test/repo"}, + "commit": {"oid": "abc123"} + }, + "range": { + "start": {"line": 20, "character": 0}, + "end": {"line": 20, "character": 5} + } + } + ] + } + } + } + } + } + }`, + wantCount: 2, + }, + { + name: "no definitions", + response: `{ + "repository": { + "commit": { + "blob": { + "lsif": { + "definitions": null + } + } + } + } + }`, + wantNil: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + mockClient := &mock.Client{} + mockRequest := &mock.Request{Response: tt.response} + mockRequest.On("Do", context.Background(), &definitionsResponse{}). + Return(true, nil) + mockClient.On("NewRequest", definitionsQuery, map[string]any{ + "repository": "github.com/test/repo", + "commit": "abc123", + "path": "main.go", + "line": 10, + "character": 5, + }).Return(mockRequest) + + s := &Server{ + apiClient: mockClient, + repoName: "github.com/test/repo", + commit: "abc123", + } + + result, err := s.queryDefinitions(context.Background(), "main.go", 10, 5) + require.NoError(t, err) + + if tt.wantNil { + require.Nil(t, result) + return + } + + require.Len(t, result, tt.wantCount) + }) + } +} + +func TestQueryReferences(t *testing.T) { + tests := []struct { + name string + response string + wantCount int + wantNil bool + }{ + { + name: "multiple references", + response: `{ + "repository": { + "commit": { + "blob": { + "lsif": { + "references": { + "nodes": [ + { + "resource": { + "path": "cmd/main.go", + "repository": {"name": "github.com/test/repo"}, + "commit": {"oid": "abc123"} + }, + "range": { + "start": {"line": 15, "character": 2}, + "end": {"line": 15, "character": 8} + } + }, + { + "resource": { + "path": "pkg/handler.go", + "repository": {"name": "github.com/test/repo"}, + "commit": {"oid": "abc123"} + }, + "range": { + "start": {"line": 42, "character": 10}, + "end": {"line": 42, "character": 16} + } + } + ] + } + } + } + } + } + }`, + wantCount: 2, + }, + { + name: "no references", + response: `{ + "repository": { + "commit": { + "blob": { + "lsif": { + "references": { + "nodes": [] + } + } + } + } + } + }`, + wantCount: 0, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + mockClient := &mock.Client{} + mockRequest := &mock.Request{Response: tt.response} + mockRequest.On("Do", context.Background(), &referencesResponse{}). + Return(true, nil) + mockClient.On("NewRequest", referencesQuery, map[string]any{ + "repository": "github.com/test/repo", + "commit": "abc123", + "path": "main.go", + "line": 10, + "character": 5, + }).Return(mockRequest) + + s := &Server{ + apiClient: mockClient, + repoName: "github.com/test/repo", + commit: "abc123", + } + + result, err := s.queryReferences(context.Background(), "main.go", 10, 5) + require.NoError(t, err) + + if tt.wantNil { + require.Nil(t, result) + return + } + + require.Len(t, result, tt.wantCount) + }) + } +} diff --git a/internal/lsp/server.go b/internal/lsp/server.go new file mode 100644 index 0000000000..6494d2dca8 --- /dev/null +++ b/internal/lsp/server.go @@ -0,0 +1,322 @@ +package lsp + +import ( + "context" + "net/url" + "path/filepath" + + "github.com/tliron/glsp" + protocol "github.com/tliron/glsp/protocol_3_16" + "github.com/tliron/glsp/server" + + "github.com/sourcegraph/sourcegraph/lib/errors" + + "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/codeintel" + "github.com/sourcegraph/src-cli/internal/version" +) + +const serverName = "Sourcegraph LSP" + +type Server struct { + apiClient api.Client + repoName string + commit string + gitRoot string +} + +func NewServer(apiClient api.Client) (*Server, error) { + repoName, err := codeintel.InferRepo() + if err != nil { + return nil, errors.Wrap(err, "failed to infer repository name") + } + + commit, err := codeintel.InferMergeBase() + if err != nil { + return nil, errors.Wrap(err, "failed to infer merge-base commit") + } + + gitRoot, err := codeintel.GitRoot() + if err != nil { + return nil, errors.Wrap(err, "failed to get git root") + } + + return &Server{ + apiClient: apiClient, + repoName: repoName, + commit: commit, + gitRoot: gitRoot, + }, nil +} + +func (s *Server) Run() error { + handler := protocol.Handler{ + Initialize: s.handleInitialize, + Initialized: s.handleInitialized, + Shutdown: s.handleShutdown, + SetTrace: s.handleSetTrace, + TextDocumentDidOpen: s.handleTextDocumentDidOpen, + TextDocumentDidClose: s.handleTextDocumentDidClose, + TextDocumentDefinition: s.handleTextDocumentDefinition, + TextDocumentReferences: s.handleTextDocumentReferences, + TextDocumentHover: s.handleTextDocumentHover, + TextDocumentDocumentHighlight: s.handleTextDocumentDocumentHighlight, + } + + srv := server.NewServer(&handler, serverName, false) + return srv.RunStdio() +} + +func (s *Server) handleInitialize( + _ *glsp.Context, _ *protocol.InitializeParams, +) (any, error) { + return protocol.InitializeResult{ + Capabilities: protocol.ServerCapabilities{ + TextDocumentSync: &protocol.TextDocumentSyncOptions{ + OpenClose: &protocol.True, + }, + DefinitionProvider: true, + ReferencesProvider: true, + HoverProvider: true, + DocumentHighlightProvider: true, + }, + ServerInfo: &protocol.InitializeResultServerInfo{ + Name: serverName, + Version: &version.BuildTag, + }, + }, nil +} + +func (s *Server) handleInitialized( + _ *glsp.Context, _ *protocol.InitializedParams, +) error { + return nil +} + +func (s *Server) handleShutdown(_ *glsp.Context) error { + protocol.SetTraceValue(protocol.TraceValueOff) + return nil +} + +func (s *Server) handleSetTrace( + _ *glsp.Context, params *protocol.SetTraceParams, +) error { + protocol.SetTraceValue(params.Value) + return nil +} + +func (s *Server) handleTextDocumentDidOpen( + _ *glsp.Context, _ *protocol.DidOpenTextDocumentParams, +) error { + return nil +} + +func (s *Server) handleTextDocumentDidClose( + _ *glsp.Context, _ *protocol.DidCloseTextDocumentParams, +) error { + return nil +} + +func (s *Server) handleTextDocumentDefinition( + _ *glsp.Context, params *protocol.DefinitionParams, +) (any, error) { + path, err := s.uriToRepoPath(params.TextDocument.URI) + if err != nil { + return nil, err + } + + nodes, err := s.queryDefinitions( + context.Background(), + path, + int(params.Position.Line), + int(params.Position.Character)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, nil + } + + locations := s.nodesToLocations(nodes) + if len(locations) == 0 { + return nil, nil + } + + return locations, nil +} + +func (s *Server) handleTextDocumentReferences( + _ *glsp.Context, params *protocol.ReferenceParams, +) ([]protocol.Location, error) { + path, err := s.uriToRepoPath(params.TextDocument.URI) + if err != nil { + return nil, err + } + + nodes, err := s.queryReferences( + context.Background(), + path, + int(params.Position.Line), + int(params.Position.Character)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, nil + } + + locations := s.nodesToLocations(nodes) + if len(locations) == 0 { + return nil, nil + } + + return locations, nil +} + +func (s *Server) handleTextDocumentHover( + _ *glsp.Context, params *protocol.HoverParams, +) (*protocol.Hover, error) { + path, err := s.uriToRepoPath(params.TextDocument.URI) + if err != nil { + return nil, err + } + + result, err := s.queryHover( + context.Background(), + path, + int(params.Position.Line), + int(params.Position.Character)) + if err != nil { + return nil, err + } + if result == nil { + return nil, nil + } + + hover := &protocol.Hover{ + Contents: protocol.MarkupContent{ + Kind: protocol.MarkupKindMarkdown, + Value: result.Markdown.Text, + }, + } + + if result.Range != nil { + hover.Range = &protocol.Range{ + Start: protocol.Position{ + Line: protocol.UInteger(result.Range.Start.Line), + Character: protocol.UInteger(result.Range.Start.Character), + }, + End: protocol.Position{ + Line: protocol.UInteger(result.Range.End.Line), + Character: protocol.UInteger(result.Range.End.Character), + }, + } + } + + return hover, nil +} + +func (s *Server) handleTextDocumentDocumentHighlight( + _ *glsp.Context, params *protocol.DocumentHighlightParams, +) ([]protocol.DocumentHighlight, error) { + path, err := s.uriToRepoPath(params.TextDocument.URI) + if err != nil { + return nil, err + } + + nodes, err := s.queryReferences( + context.Background(), + path, + int(params.Position.Line), + int(params.Position.Character)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, nil + } + + var highlights []protocol.DocumentHighlight + for _, node := range nodes { + if node.Resource.Repository.Name != s.repoName { + continue + } + if node.Resource.Path != path { + continue + } + + highlights = append(highlights, protocol.DocumentHighlight{ + Range: protocol.Range{ + Start: protocol.Position{ + Line: protocol.UInteger(node.Range.Start.Line), + Character: protocol.UInteger(node.Range.Start.Character), + }, + End: protocol.Position{ + Line: protocol.UInteger(node.Range.End.Line), + Character: protocol.UInteger(node.Range.End.Character), + }, + }, + }) + } + + if len(highlights) == 0 { + return nil, nil + } + + return highlights, nil +} + +func (s *Server) nodesToLocations(nodes []LocationNode) []protocol.Location { + var locations []protocol.Location + for _, node := range nodes { + if node.Resource.Repository.Name != s.repoName { + continue + } + + absPath := filepath.Join(s.gitRoot, node.Resource.Path) + uri := "file://" + absPath + + locations = append(locations, protocol.Location{ + URI: uri, + Range: protocol.Range{ + Start: protocol.Position{ + Line: protocol.UInteger(node.Range.Start.Line), + Character: protocol.UInteger(node.Range.Start.Character), + }, + End: protocol.Position{ + Line: protocol.UInteger(node.Range.End.Line), + Character: protocol.UInteger(node.Range.End.Character), + }, + }, + }) + } + return locations +} + +func (s *Server) uriToRepoPath(uri string) (string, error) { + parsed, err := url.Parse(uri) + if err != nil { + return "", errors.Wrap(err, "failed to parse URI") + } + + if parsed.Scheme != "file" { + return "", errors.Newf("unsupported URI scheme %q", parsed.Scheme) + } + + absPath := parsed.Path + // On Windows, file URIs like file:///C:/path produce a path like "/C:/path". + // We need to strip the leading slash to get a valid Windows path. + if len(absPath) >= 3 && absPath[0] == '/' && absPath[2] == ':' { + absPath = absPath[1:] + } + // Convert forward slashes to the native path separator + absPath = filepath.FromSlash(absPath) + + relPath, err := filepath.Rel(s.gitRoot, absPath) + if err != nil { + return "", errors.Wrap(err, "failed to compute relative path") + } + + // Ensure we always return forward slashes for consistency + return filepath.ToSlash(relPath), nil +} diff --git a/internal/lsp/server_test.go b/internal/lsp/server_test.go new file mode 100644 index 0000000000..13a57e9857 --- /dev/null +++ b/internal/lsp/server_test.go @@ -0,0 +1,284 @@ +package lsp + +import ( + "context" + "net/url" + "path/filepath" + "testing" + + protocol "github.com/tliron/glsp/protocol_3_16" + + "github.com/sourcegraph/src-cli/internal/api/mock" + "github.com/sourcegraph/src-cli/internal/codeintel" + "github.com/stretchr/testify/require" +) + +// pathToFileURI converts a file path to a proper file:// URI that works on all platforms. +// On Windows, this properly handles drive letters (e.g., C:\path -> file:///C:/path). +func pathToFileURI(path string) string { + // Convert to forward slashes + path = filepath.ToSlash(path) + // On Windows, absolute paths like "C:/path" need a leading slash for proper file URIs + if len(path) >= 2 && path[1] == ':' { + path = "/" + path + } + u := url.URL{ + Scheme: "file", + Path: path, + } + return u.String() +} + +func TestUriToRepoPath(t *testing.T) { + gitRoot, err := codeintel.GitRoot() + require.NoError(t, err) + + tests := []struct { + name string + uri string + wantPath string + }{ + { + name: "simple file URI", + uri: pathToFileURI(filepath.Join(gitRoot, "cmd/src/main.go")), + wantPath: "cmd/src/main.go", + }, + { + name: "nested path", + uri: pathToFileURI(filepath.Join(gitRoot, "internal/lsp/server.go")), + wantPath: "internal/lsp/server.go", + }, + { + name: "root file", + uri: pathToFileURI(filepath.Join(gitRoot, "go.mod")), + wantPath: "go.mod", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + s := &Server{gitRoot: gitRoot} + got, err := s.uriToRepoPath(tt.uri) + require.NoError(t, err) + require.Equal(t, tt.wantPath, got) + }) + } +} + +func TestUriToRepoPathErrors(t *testing.T) { + tests := []struct { + name string + uri string + wantErr string + }{ + { + name: "invalid URI", + uri: "://invalid", + wantErr: "failed to parse URI", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + s := &Server{gitRoot: "/tmp"} + _, err := s.uriToRepoPath(tt.uri) + require.Error(t, err) + require.Contains(t, err.Error(), tt.wantErr) + }) + } +} + +func TestHandleTextDocumentDocumentHighlight(t *testing.T) { + gitRoot, err := codeintel.GitRoot() + require.NoError(t, err) + + tests := []struct { + name string + path string + response string + wantCount int + wantNil bool + }{ + { + name: "filters to same file only", + path: "main.go", + response: `{ + "repository": { + "commit": { + "blob": { + "lsif": { + "references": { + "nodes": [ + { + "resource": { + "path": "main.go", + "repository": {"name": "github.com/test/repo"}, + "commit": {"oid": "abc123"} + }, + "range": { + "start": {"line": 10, "character": 0}, + "end": {"line": 10, "character": 5} + } + }, + { + "resource": { + "path": "main.go", + "repository": {"name": "github.com/test/repo"}, + "commit": {"oid": "abc123"} + }, + "range": { + "start": {"line": 20, "character": 0}, + "end": {"line": 20, "character": 5} + } + }, + { + "resource": { + "path": "other.go", + "repository": {"name": "github.com/test/repo"}, + "commit": {"oid": "abc123"} + }, + "range": { + "start": {"line": 5, "character": 0}, + "end": {"line": 5, "character": 5} + } + } + ] + } + } + } + } + } + }`, + wantCount: 2, + }, + { + name: "filters out other repositories", + path: "main.go", + response: `{ + "repository": { + "commit": { + "blob": { + "lsif": { + "references": { + "nodes": [ + { + "resource": { + "path": "main.go", + "repository": {"name": "github.com/test/repo"}, + "commit": {"oid": "abc123"} + }, + "range": { + "start": {"line": 10, "character": 0}, + "end": {"line": 10, "character": 5} + } + }, + { + "resource": { + "path": "main.go", + "repository": {"name": "github.com/other/repo"}, + "commit": {"oid": "def456"} + }, + "range": { + "start": {"line": 15, "character": 0}, + "end": {"line": 15, "character": 5} + } + } + ] + } + } + } + } + } + }`, + wantCount: 1, + }, + { + name: "no references returns nil", + path: "main.go", + response: `{ + "repository": { + "commit": { + "blob": { + "lsif": { + "references": { + "nodes": [] + } + } + } + } + } + }`, + wantNil: true, + }, + { + name: "all references in other files returns nil", + path: "main.go", + response: `{ + "repository": { + "commit": { + "blob": { + "lsif": { + "references": { + "nodes": [ + { + "resource": { + "path": "other.go", + "repository": {"name": "github.com/test/repo"}, + "commit": {"oid": "abc123"} + }, + "range": { + "start": {"line": 10, "character": 0}, + "end": {"line": 10, "character": 5} + } + } + ] + } + } + } + } + } + }`, + wantNil: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + mockClient := &mock.Client{} + mockRequest := &mock.Request{Response: tt.response} + mockRequest.On("Do", context.Background(), &referencesResponse{}).Return(true, nil) + mockClient.On("NewRequest", referencesQuery, map[string]any{ + "repository": "github.com/test/repo", + "commit": "abc123", + "path": tt.path, + "line": 10, + "character": 5, + }).Return(mockRequest) + + s := &Server{ + apiClient: mockClient, + repoName: "github.com/test/repo", + commit: "abc123", + gitRoot: gitRoot, + } + + uri := pathToFileURI(filepath.Join(gitRoot, tt.path)) + params := &protocol.DocumentHighlightParams{ + TextDocumentPositionParams: protocol.TextDocumentPositionParams{ + TextDocument: protocol.TextDocumentIdentifier{URI: uri}, + Position: protocol.Position{Line: 10, Character: 5}, + }, + } + + result, err := s.handleTextDocumentDocumentHighlight(nil, params) + require.NoError(t, err) + + if tt.wantNil { + require.Nil(t, result) + return + } + + require.Len(t, result, tt.wantCount) + }) + } +} From 341290f91accf621e1a1059c78c9dfe64a0e7b33 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Mon, 12 Jan 2026 15:07:20 +0000 Subject: [PATCH 534/647] remove mcp experiment (#1250) closes CPL-141 --- cmd/src/mcp.go | 147 ----- internal/mcp/mcp_args.go | 99 ---- internal/mcp/mcp_args_test.go | 100 ---- internal/mcp/mcp_parse.go | 161 ----- internal/mcp/mcp_parse_test.go | 95 --- internal/mcp/mcp_request.go | 164 ------ internal/mcp/mcp_tools.json | 1008 -------------------------------- internal/mcp/registry.go | 61 -- 8 files changed, 1835 deletions(-) delete mode 100644 cmd/src/mcp.go delete mode 100644 internal/mcp/mcp_args.go delete mode 100644 internal/mcp/mcp_args_test.go delete mode 100644 internal/mcp/mcp_parse.go delete mode 100644 internal/mcp/mcp_parse_test.go delete mode 100644 internal/mcp/mcp_request.go delete mode 100644 internal/mcp/mcp_tools.json delete mode 100644 internal/mcp/registry.go diff --git a/cmd/src/mcp.go b/cmd/src/mcp.go deleted file mode 100644 index 3878fe24b6..0000000000 --- a/cmd/src/mcp.go +++ /dev/null @@ -1,147 +0,0 @@ -package main - -import ( - "context" - "encoding/json" - "flag" - "fmt" - "maps" - "strings" - - "github.com/sourcegraph/src-cli/internal/mcp" - - "github.com/sourcegraph/sourcegraph/lib/errors" -) - -var mcpFlagSet = flag.NewFlagSet("mcp", flag.ExitOnError) - -func init() { - commands = append(commands, &command{ - flagSet: mcpFlagSet, - handler: mcpMain, - usageFunc: mcpUsage, - }) -} - -func mcpUsage() { - fmt.Println("The 'mcp' command exposes MCP tools as subcommands for agents to use.") - fmt.Println("\nUSAGE:") - fmt.Println(" src mcp list-tools List available tools") - fmt.Println(" src mcp schema View the input/output schema of a tool") - fmt.Println(" src mcp Invoke a tool with the given flags") - fmt.Println(" src mcp -h List the available flags of a tool") - fmt.Println("\nCOMMON FLAGS:") - fmt.Println(" --json '{...}' Provide all tool arguments as a JSON object (recommended for agents)") - fmt.Println("\nNOTE:") - fmt.Println(" When both --json and explicit flags are provided, values from --json take precedence.") - fmt.Println("\nEXAMPLE:") - fmt.Println(" src mcp --json '{\"arg1\": \"value1\", \"arg2\": \"value2\"}'") -} - -func mcpMain(args []string) error { - apiClient := cfg.apiClient(nil, mcpFlagSet.Output()) - - ctx := context.Background() - registry := mcp.NewToolRegistry() - if err := registry.LoadTools(ctx, apiClient); err != nil { - return err - } - - if len(args) == 0 { - mcpUsage() - return nil - } - - subcmd := args[0] - if subcmd == "list-tools" { - fmt.Println("The following tools are available:") - for name := range registry.All() { - fmt.Printf(" %s\n", name) - } - fmt.Println("\nUSAGE:") - fmt.Println(" src mcp schema View the input/output schema of a tool") - fmt.Println(" src mcp Invoke a tool with the given flags") - fmt.Println(" src mcp -h List the available flags of a tool") - return nil - } - tool, ok := registry.Get(subcmd) - if !ok { - return errors.Newf("tool definition for %q not found - run src mcp list-tools to see a list of available tools", subcmd) - } - - flagArgs := args[1:] // skip subcommand name - if len(args) > 1 && args[1] == "schema" { - return printSchemas(tool) - } - - flags, vars, err := mcp.BuildArgFlagSet(tool) - if err != nil { - return err - } - if err := flags.Parse(flagArgs); err != nil { - return err - } - mcp.DerefFlagValues(flags, vars) - - // arguments provided via a JSON object take precedence over explicit values provided from flags - if val, ok := vars["json"]; ok { - if jsonVal, ok := val.(string); ok && len(jsonVal) > 0 { - m := make(map[string]any) - if err := json.Unmarshal([]byte(jsonVal), &m); err != nil { - return err - } - // copy overrides existing keys - maps.Copy(vars, m) - } - // we delete "json" from vars, otherwise it will be sent as a argument to the tool call - delete(vars, "json") - } - - if err := validateToolArgs(tool.InputSchema, args, vars); err != nil { - return err - } - - result, err := registry.CallTool(ctx, apiClient, tool.Name, vars) - if err != nil { - return err - } - - output, err := json.Marshal(result) - if err != nil { - return err - } - fmt.Println(string(output)) - return nil -} - -func printSchemas(tool *mcp.ToolDef) error { - var schema = struct { - Name string `json:"tool"` - Input any `json:"inputSchema"` - Output any `json:"outputSchema"` - }{ - Name: tool.Name, - Input: tool.InputSchema, - Output: tool.OutputSchema, - } - jsonVal, err := json.Marshal(schema) - if err != nil { - return err - } - fmt.Println(string(jsonVal)) - return nil -} - -func validateToolArgs(inputSchema mcp.SchemaObject, args []string, vars map[string]any) error { - for _, reqName := range inputSchema.Required { - if vars[reqName] == nil { - return errors.Newf("no value provided for required flag --%s", reqName) - } - } - - if len(args) < len(inputSchema.Required) { - return errors.Newf("not enough arguments provided - the following flags are required:\n%s", strings.Join(inputSchema.Required, "\n")) - } - - return nil -} diff --git a/internal/mcp/mcp_args.go b/internal/mcp/mcp_args.go deleted file mode 100644 index e492a645ef..0000000000 --- a/internal/mcp/mcp_args.go +++ /dev/null @@ -1,99 +0,0 @@ -package mcp - -import ( - "encoding/json" - "flag" - "fmt" - "reflect" - "strings" - - "github.com/sourcegraph/sourcegraph/lib/errors" -) - -var _ flag.Value = (*strSliceFlag)(nil) - -type strSliceFlag struct { - vals []string -} - -func (s *strSliceFlag) Set(v string) error { - // The MCP Array properties accept JSON arrays so, if we get a value starting with "[" - // it's probably a JSON array - if strings.HasPrefix(v, "[") { - var arr []string - if err := json.Unmarshal([]byte(v), &arr); err == nil { - s.vals = append(s.vals, arr...) - return nil - } - } - // Otherwise treat as a single value - s.vals = append(s.vals, v) - return nil -} - -func (s *strSliceFlag) String() string { - return strings.Join(s.vals, ",") -} - -func DerefFlagValues(fs *flag.FlagSet, vars map[string]any) { - setFlags := make(map[string]bool) - fs.Visit(func(f *flag.Flag) { - setFlags[f.Name] = true - }) - - for k, v := range vars { - if !setFlags[k] { - delete(vars, k) - continue - } - rfl := reflect.ValueOf(v) - if rfl.Kind() == reflect.Pointer { - vv := rfl.Elem().Interface() - if slice, ok := vv.(strSliceFlag); ok { - vv = slice.vals - } - vars[k] = vv - } - } -} - -func BuildArgFlagSet(tool *ToolDef) (*flag.FlagSet, map[string]any, error) { - if tool == nil { - return nil, nil, errors.New("cannot build flagset on nil Tool Definition") - } - fs := flag.NewFlagSet(tool.Name, flag.ContinueOnError) - flagVars := map[string]any{} - - for name, pVal := range tool.InputSchema.Properties { - switch pv := pVal.(type) { - case *SchemaPrimitive: - switch pv.Type { - case "integer": - dst := fs.Int(name, 0, pv.Description) - flagVars[name] = dst - - case "boolean": - dst := fs.Bool(name, false, pv.Description) - flagVars[name] = dst - case "string": - dst := fs.String(name, "", pv.Description) - flagVars[name] = dst - default: - return nil, nil, fmt.Errorf("unknown schema primitive kind %q", pv.Type) - - } - case *SchemaArray: - strSlice := new(strSliceFlag) - fs.Var(strSlice, name, pv.Description) - flagVars[name] = strSlice - case *SchemaObject: - // TODO(burmudar): we can support SchemaObject as part of stdin echo '{ stuff }' | sg mcp commit-search - // not supported yet - // Also support sg mcp commit-search --json '{ stuff }' - } - } - - flagVars["json"] = fs.String("json", "", "provide all arguments as a JSON object") - - return fs, flagVars, nil -} diff --git a/internal/mcp/mcp_args_test.go b/internal/mcp/mcp_args_test.go deleted file mode 100644 index 829e6dbf55..0000000000 --- a/internal/mcp/mcp_args_test.go +++ /dev/null @@ -1,100 +0,0 @@ -package mcp - -import ( - "slices" - "testing" -) - -func TestFlagSetParse(t *testing.T) { - toolJSON := []byte(`{ - "tools": [ - { - "name": "sg_test_tool", - "description": "test description", - "inputSchema": { - "type": "object", - "$schema": "https://localhost/schema-draft/2025-07", - "required": ["values"], - "properties": { - "repos": { - "type": "array", - "items": { - "type": "string" - } - }, - "tag": { - "type": "string", - "items": true - }, - "count": { - "type": "integer" - }, - "boolFlag": { - "type": "boolean" - } - } - }, - "outputSchema": { - "type": "object", - "$schema": "https://localhost/schema-draft/2025-07", - "properties": { - "result": { "type": "string" } - } - } - } - ] - }`) - - defs, err := loadToolDefinitions(toolJSON) - if err != nil { - t.Fatalf("failed to load tool json: %v", err) - } - - flagSet, vars, err := BuildArgFlagSet(defs["test-tool"]) - if err != nil { - t.Fatalf("failed to build flagset from mcp tool definition: %v", err) - } - - if len(vars) == 0 { - t.Fatalf("vars from buildArgFlagSet should not be empty") - } - - args := []string{"-repos=A", "-repos=B", `-repos=["repo1", "repo2"]`, "-count=10", "-boolFlag", "-tag=testTag"} - - if err := flagSet.Parse(args); err != nil { - t.Fatalf("flagset parsing failed: %v", err) - } - DerefFlagValues(flagSet, vars) - - expectedRepos := []string{"A", "B", "repo1", "repo2"} - actualRepos, ok := vars["repos"].([]string) - if !ok { - t.Fatalf("failed to cast repos to []string, got %T", actualRepos) - } - if !slices.Equal(expectedRepos, actualRepos) { - t.Fatalf("expected repos %v, got %v", expectedRepos, vars["repos"]) - } - - if v, ok := vars["tag"].(string); ok { - if v != "testTag" { - t.Fatalf("expected flag 'tag' values to have value %q but got %q", "testTag", v) - } - } else { - t.Fatalf("expected flag 'tag' to have type of string but got %T", v) - } - if v, ok := vars["count"].(int); ok { - if v != 10 { - t.Fatalf("expected flag 'count' values to have value %d but got %d", 10, v) - } - } else { - t.Fatalf("expected flag 'count' to have type of int but got %T", v) - } - if v, ok := vars["boolFlag"].(bool); ok { - if v != true { - t.Fatalf("expected flag 'boolFlag' values to have value %v but got %v", true, v) - } - } else { - t.Fatalf("expected flag 'boolFlag' to have type of bool but got %T", v) - } - -} diff --git a/internal/mcp/mcp_parse.go b/internal/mcp/mcp_parse.go deleted file mode 100644 index 1a5fae1dc9..0000000000 --- a/internal/mcp/mcp_parse.go +++ /dev/null @@ -1,161 +0,0 @@ -package mcp - -import ( - _ "embed" - "encoding/json" - "strings" - - "github.com/sourcegraph/sourcegraph/lib/errors" -) - -type ToolDef struct { - Name string - RawName string `json:"name"` - Description string `json:"description"` - InputSchema SchemaObject `json:"inputSchema"` - OutputSchema SchemaObject `json:"outputSchema"` -} - -type rawSchema struct { - Type string `json:"type"` - Description string `json:"description"` - Required []string `json:"required,omitempty"` - Properties map[string]json.RawMessage `json:"properties"` - Items json.RawMessage `json:"items"` -} - -type SchemaValue interface { - ValueType() string -} - -type SchemaObject struct { - Type string `json:"type"` - Description string `json:"description"` - Required []string `json:"required,omitempty"` - Properties map[string]SchemaValue `json:"properties"` - - // two fields which we do not use from the schema: - // - $schema - // - additionalPropterties -} - -func (s SchemaObject) ValueType() string { return s.Type } - -type SchemaArray struct { - Type string `json:"type"` - Description string `json:"description"` - Items SchemaValue `json:"items,omitempty"` -} - -func (s SchemaArray) ValueType() string { return s.Type } - -type SchemaPrimitive struct { - Type string `json:"type"` - Description string `json:"description"` -} - -func (s SchemaPrimitive) ValueType() string { return s.Type } - -type decoder struct { - errors []error -} - -func loadToolDefinitions(data []byte) (map[string]*ToolDef, error) { - defs := struct { - Tools []struct { - Name string `json:"name"` - Description string `json:"description"` - InputSchema rawSchema `json:"inputSchema"` - OutputSchema rawSchema `json:"outputSchema"` - } `json:"tools"` - }{} - - if err := json.Unmarshal(data, &defs); err != nil { - return nil, err - } - - tools := map[string]*ToolDef{} - decoder := &decoder{} - - for _, t := range defs.Tools { - // normalize the raw mcp tool name to be without the mcp identifiers - rawName := t.Name - name, _ := strings.CutPrefix(rawName, "sg_") - name = strings.ReplaceAll(name, "_", "-") - - tool := &ToolDef{ - Name: name, - RawName: rawName, - Description: t.Description, - InputSchema: decoder.decodeRootSchema(t.InputSchema), - OutputSchema: decoder.decodeRootSchema(t.OutputSchema), - } - tools[tool.Name] = tool - } - - if len(decoder.errors) > 0 { - return tools, errors.Append(nil, decoder.errors...) - } - - return tools, nil -} - -func (d *decoder) decodeRootSchema(r rawSchema) SchemaObject { - return SchemaObject{ - Type: r.Type, - Description: r.Description, - Required: r.Required, - Properties: d.decodeProperties(r.Properties), - } -} - -func (d *decoder) decodeSchema(r *rawSchema) SchemaValue { - switch r.Type { - case "object": - return &SchemaObject{ - Type: r.Type, - Description: r.Description, - Required: r.Required, - Properties: d.decodeProperties(r.Properties), - } - case "array": - var items SchemaValue - if len(r.Items) > 0 { - var boolItems bool - if err := json.Unmarshal(r.Items, &boolItems); err == nil { - // Sometimes items is defined as "items: true", so we handle it here and - // consider it "empty" array - } else { - var itemRaw rawSchema - if err := json.Unmarshal(r.Items, &itemRaw); err == nil { - items = d.decodeSchema(&itemRaw) - } else { - d.errors = append(d.errors, errors.Wrap(err, "failed to unmarshal array items")) - } - } - } - return &SchemaArray{ - Type: r.Type, - Description: r.Description, - Items: items, - } - default: - return &SchemaPrimitive{ - Type: r.Type, - Description: r.Description, - } - } -} - -func (d *decoder) decodeProperties(props map[string]json.RawMessage) map[string]SchemaValue { - res := make(map[string]SchemaValue) - for name, raw := range props { - var r rawSchema - if err := json.Unmarshal(raw, &r); err != nil { - d.errors = append(d.errors, errors.Wrapf(err, "failed to parse property %q: %w", name)) - continue - } - res[name] = d.decodeSchema(&r) - } - return res -} diff --git a/internal/mcp/mcp_parse_test.go b/internal/mcp/mcp_parse_test.go deleted file mode 100644 index ecaf691d16..0000000000 --- a/internal/mcp/mcp_parse_test.go +++ /dev/null @@ -1,95 +0,0 @@ -package mcp - -import ( - "testing" -) - -func TestLoadToolDefinitions(t *testing.T) { - toolJSON := []byte(`{ - "tools": [ - { - "name": "test_tool", - "description": "test description", - "inputSchema": { - "type": "object", - "$schema": "https://localhost/schema-draft/2025-07", - "properties": { - "tags": { - "type": "array", - "items": { - "type": "object", - "properties": { - "key": { "type": "string" }, - "value": { "type": "string" } - } - } - } - } - }, - "outputSchema": { - "type": "object", - "$schema": "https://localhost/schema-draft/2025-07", - "properties": { - "result": { "type": "string" } - } - } - } - ] - }`) - - tools, err := loadToolDefinitions(toolJSON) - if err != nil { - t.Fatalf("Failed to load tool definitions: %v", err) - } - - if len(tools) != 1 { - t.Fatalf("Expected 1 tool, got %d", len(tools)) - } - - tool := tools["test-tool"] - if tool == nil { - t.Fatal("Tool 'test_tool' not found") - } - - if tool.RawName != "test_tool" { - t.Errorf("Expected name 'test_tool', got '%s'", tool.RawName) - } - - inputSchema := tool.InputSchema - - if len(tool.OutputSchema.Properties) == 0 { - t.Fatalf("expected tool.OutputSchema.Properties not be empty") - } - - tagsProp, ok := inputSchema.Properties["tags"] - if !ok { - t.Fatal("Property 'tags' not found in inputSchema") - } - - if tagsProp.ValueType() != "array" { - t.Errorf("Expected tags type 'array', got '%s'", tagsProp.ValueType()) - } - - arraySchema, ok := tagsProp.(*SchemaArray) - if !ok { - t.Fatal("Expected SchemaArray for tags") - } - - if arraySchema.Items == nil { - t.Fatal("Expected items schema in array, got nil") - } - - itemSchema := arraySchema.Items - if itemSchema.ValueType() != "object" { - t.Errorf("Expected item type 'object', got '%s'", itemSchema.ValueType()) - } - - objectSchema, ok := itemSchema.(*SchemaObject) - if !ok { - t.Fatal("Expected SchemaObject for item") - } - - if _, ok := objectSchema.Properties["key"]; !ok { - t.Error("Property 'key' not found in item schema") - } -} diff --git a/internal/mcp/mcp_request.go b/internal/mcp/mcp_request.go deleted file mode 100644 index e1b8d69c3d..0000000000 --- a/internal/mcp/mcp_request.go +++ /dev/null @@ -1,164 +0,0 @@ -package mcp - -import ( - "bytes" - "context" - "encoding/json" - "io" - "net/http" - "strings" - - "github.com/sourcegraph/src-cli/internal/api" - - "github.com/sourcegraph/sourcegraph/lib/errors" -) - -const MCPURLPath = ".api/mcp/v1" - -func fetchToolDefinitions(ctx context.Context, client api.Client, endpoint string) (map[string]*ToolDef, error) { - resp, err := doJSONRPC(ctx, client, endpoint, "tools/list", nil) - if err != nil { - return nil, errors.Wrapf(err, "JSON-RPC tools/list request failed to %q", MCPURLPath) - } - defer resp.Body.Close() - - data, err := readSSEResponseData(resp) - if err != nil { - return nil, errors.Wrap(err, "failed to read tools/list SSE response") - } - - var rpcResp struct { - Result json.RawMessage `json:"result"` - Error *struct { - Code int `json:"code"` - Message string `json:"message"` - } `json:"error,omitempty"` - } - if err := json.Unmarshal(data, &rpcResp); err != nil { - return nil, errors.Wrap(err, "failed to unmarshal JSON-RPC response") - } - if rpcResp.Error != nil { - return nil, errors.Newf("MCP tools/list failed: %d %s", rpcResp.Error.Code, rpcResp.Error.Message) - } - - return loadToolDefinitions(rpcResp.Result) -} - -func doToolCall(ctx context.Context, client api.Client, endpoint string, tool string, vars map[string]any) (*http.Response, error) { - params := struct { - Name string `json:"name"` - Arguments map[string]any `json:"arguments"` - }{ - Name: tool, - Arguments: vars, - } - - resp, err := doJSONRPC(ctx, client, endpoint, "tools/call", params) - if err != nil { - return nil, errors.Wrapf(err, "JSON-RPC tools/call request failed to %q", MCPURLPath) - } - return resp, err -} - -func doJSONRPC(ctx context.Context, client api.Client, endpoint string, method string, params any) (*http.Response, error) { - jsonRPC := struct { - Version string `json:"jsonrpc"` - ID int `json:"id"` - Method string `json:"method"` - Params any `json:"params,omitempty"` - }{ - Version: "2.0", - ID: 1, - Method: method, - Params: params, - } - buf := bytes.NewBuffer(nil) - data, err := json.Marshal(jsonRPC) - if err != nil { - return nil, err - } - buf.Write(data) - - req, err := client.NewHTTPRequest(ctx, http.MethodPost, endpoint, buf) - if err != nil { - return nil, err - } - req.Header.Add("Content-Type", "application/json") - req.Header.Add("Accept", "application/json, text/event-stream") - - resp, err := client.Do(req) - if err != nil { - return nil, err - } - - if resp.StatusCode < 200 || resp.StatusCode >= 300 { - body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) - resp.Body.Close() - return nil, errors.Newf("MCP endpoint %s returned %d: %s", - endpoint, resp.StatusCode, strings.TrimSpace(string(body))) - } - - return resp, nil -} - -func decodeToolResponse(resp *http.Response) (map[string]json.RawMessage, error) { - data, err := readSSEResponseData(resp) - if err != nil { - return nil, err - } - - if data == nil { - return map[string]json.RawMessage{}, nil - } - - jsonRPCResp := struct { - Result struct { - Content []json.RawMessage `json:"content"` - StructuredContent map[string]json.RawMessage `json:"structuredContent"` - IsError bool `json:"isError"` - } `json:"result"` - Error *struct { - Code int `json:"code"` - Message string `json:"message"` - } `json:"error,omitempty"` - }{} - if err := json.Unmarshal(data, &jsonRPCResp); err != nil { - return nil, errors.Wrapf(err, "failed to unmarshal MCP JSON-RPC response") - } - if jsonRPCResp.Error != nil { - return nil, errors.Newf("MCP JSON-RPC error: %d %s", jsonRPCResp.Error.Code, jsonRPCResp.Error.Message) - } - - if jsonRPCResp.Result.IsError { - content := jsonRPCResp.Result.Content[0] - if len(content) > 0 { - var textContent struct { - Text string `json:"text"` - } - if err := json.Unmarshal(content, &textContent); err == nil && textContent.Text != "" { - return nil, errors.Newf("MCP tool error: %s", textContent.Text) - } - return nil, errors.Newf("MCP tool error: %s", string(content)) - } - return nil, errors.New("MCP tool returned an error") - } - - return jsonRPCResp.Result.StructuredContent, nil -} -func readSSEResponseData(resp *http.Response) ([]byte, error) { - data, err := io.ReadAll(resp.Body) - if err != nil { - return nil, err - } - // The response is an SSE reponse - // event: - // data: - lines := bytes.SplitSeq(data, []byte("\n")) - for line := range lines { - if jsonData, ok := bytes.CutPrefix(line, []byte("data: ")); ok { - return jsonData, nil - } - } - return nil, errors.New("no data found in SSE response") - -} diff --git a/internal/mcp/mcp_tools.json b/internal/mcp/mcp_tools.json deleted file mode 100644 index e38eba472d..0000000000 --- a/internal/mcp/mcp_tools.json +++ /dev/null @@ -1,1008 +0,0 @@ -{ - "tools": [ - { - "description": "This is a Sourcegraph search tool and is best used with other sourcegraph search tools. A commit search tool.\nSearch for commits in the repository. Find who made changes, when features were implemented, or track code history.\n\nKey features:\n- Search commit messages for relevant terms\n- Find commits by specific authors\n- Search for changes containing specific code\n- Filter by file paths or repository\n- Filter by date ranges with before/after\n- Regex pattern support\n\nLogic: All parameter types are combined with AND, but within each parameter type, multiple values use OR.\nExample: messageTerms=[\"bug\",\"fix\"] + authors=[\"jane\"] finds commits by jane with \"bug\" OR \"fix\" in message.\n\nExamples:\n\n \n Search for commits mentioning 'implement feature' or 'create feature' in the message\n calls the commit search tool with messageTerms=[\"implement feature\", \"create feature\"] repos=[\"github.com/myorg/repo\"]\n \n\t\n Search for commits that added pandas imports\n calls the commit search tool with contentTerms=[\"import pandas\"] repos=[\"github.com/myorg/repo\"]\n \n \n Find commits by jane.doe that changed files in the ui/components directory\n calls the commit search tool with authors=[\"jane.doe\"] files=[\"ui/components/**\"] repos=[\"github.com/myorg/frontend\"]\n \n \n Find changes to authentication code in May 2025\n calls the commit search tool with contentTerms=[\"auth\"] repos=[\"github.com/myorg/auth-service\", \"github.com/myorg/user-service\"] after=\"2025-05-01\" before=\"2025-05-31\"\n \n \n What has John been working on for the past month?\n calls the commit search tool with authors=[\"John\"] repos=[\"github.com/myorg/repo1\", \"github.com/myorg/repo2\"] after=\"1 month ago\"\n \n", - "inputSchema": { - "type": "object", - "$schema": "https://json-schema.org/draft/2020-12/schema", - "required": [ - "repos" - ], - "properties": { - "after": { - "type": "string", - "description": "Search for commits after this date. Supports various formats including structured dates (e.g. \"YYYY-MM-DD\" or \"MM/DD/YYYY\", or \"november 2023\") and natural language (e.g. \"1 month ago\", \"last week\", or \"yesterday\")" - }, - "authors": { - "type": "array", - "description": "Authors to filter by. Multiple authors will be combined with OR logic.", - "items": { - "type": "string" - } - }, - "before": { - "type": "string", - "description": "Search for commits before this date. Supports various formats including structured dates (e.g. \"YYYY-MM-DD\", \"MM/DD/YYYY\", or \"november 2023\") and natural language (e.g. \"1 month ago\", \"last week\", or \"yesterday\")" - }, - "contentTerms": { - "type": "array", - "description": "Code content terms to search for in the actual changes. Multiple terms will be combined with OR logic.", - "items": { - "type": "string" - } - }, - "count": { - "type": "integer", - "description": "Maximum number of results to return" - }, - "files": { - "type": "array", - "description": "File paths to filter by. Multiple files will be combined with OR logic.", - "items": { - "type": "string" - } - }, - "messageTerms": { - "type": "array", - "description": "Terms to search for in commit messages. Multiple terms will be combined with OR logic by default.", - "items": { - "type": "string" - } - }, - "repos": { - "type": "array", - "description": "REQUIRED: Repositories to search in (e.g., [\"github.com/gohugoio/hugo\"] or [\"repo1\", \"repo2\"]). Multiple repositories will be combined with OR logic.", - "items": { - "type": "string" - } - }, - "useRegex": { - "type": "boolean", - "description": "Use regular expressions for searching (default: false)" - } - }, - "additionalProperties": false - }, - "name": "sg_commit_search", - "outputSchema": { - "type": "object", - "$schema": "https://json-schema.org/draft/2020-12/schema", - "required": [ - "query", - "totalCount", - "commits", - "limitHit" - ], - "properties": { - "commits": { - "type": "array", - "items": { - "type": "object", - "required": [ - "repository", - "commit", - "author", - "date", - "title", - "message" - ], - "properties": { - "author": { - "type": "string" - }, - "commit": { - "type": "string" - }, - "date": { - "type": "string" - }, - "message": { - "type": "string" - }, - "repository": { - "type": "string" - }, - "title": { - "type": "string" - } - }, - "additionalProperties": false - } - }, - "limitHit": { - "type": "boolean" - }, - "query": { - "type": "string" - }, - "totalCount": { - "type": "integer" - } - }, - "additionalProperties": false - } - }, - { - "description": "This is a Sourcegraph search tool and is best used with other sourcegraph search tools. A tool that compares changes between two specific revisions in a repository.\nUse this tool when you need to:\n- Compare changes between two versions (commits, branches, tags) in a single repository\n- View specific file changes between revisions in detail\n- Examine code differences in a pull request, branch or commit\n- See all files modified between two specific points in a repository\n\nTips for effective revision comparison:\n- Use specific revisions for precise comparisons\n- For very large diffs, start with a smaller \"first\" value (e.g., 5) to preview changes\n- For comparing across branches, use the branch names directly\n- To see changes from a specific commit, use commitHash~1 as base and commitHash as head\n- Use \"after\" with the provided endCursor value to paginate through large diffs\n\nExamples:\n\n \n What changed in commit abc123 in the github.com/django/django repository?\n calls the compare revisions tool with repo=\"github.com/django/django\" base=\"abc123~1\" head=\"abc123\"\n \n \n Compare the feature-auth branch with main in the github.com/microsoft/vscode repository\n calls the compare revisions tool with repo=\"github.com/microsoft/vscode\" base=\"main\" head=\"feature-auth\"\n \n \n Show me all file changes between commits abc123 and def456 in kubernetes\n calls the compare revisions tool with repo=\"github.com/kubernetes/kubernetes\" base=\"abc123\" head=\"def456\"\n \n \n What files were modified in the last 3 commits on main branch of the rails repo?\n calls the compare revisions tool with repo=\"github.com/rails/rails\" base=\"main~3\" head=\"main\"\n \n", - "inputSchema": { - "type": "object", - "$schema": "https://json-schema.org/draft/2020-12/schema", - "required": [ - "repo", - "base", - "head" - ], - "properties": { - "after": { - "type": "string", - "description": "Pagination cursor for fetching more results" - }, - "base": { - "type": "string", - "description": "The base revision (older version, e.g., \"main~5\", a commit hash, or a tag)" - }, - "first": { - "type": "integer", - "description": "Maximum number of file diffs to return (default: 50, max: 100)" - }, - "head": { - "type": "string", - "description": "The head revision (newer version, e.g., \"main\", a commit hash, or a tag)" - }, - "repo": { - "type": "string", - "description": "The repository name to compare revisions in (e.g., \"github.com/grafana/loki\")" - } - }, - "additionalProperties": false - }, - "name": "sg_compare_revisions", - "outputSchema": { - "type": "object", - "$schema": "https://json-schema.org/draft/2020-12/schema", - "required": [ - "repository", - "base", - "head", - "totalAdded", - "totalDeleted", - "totalModified", - "files", - "hasNextPage", - "endCursor" - ], - "properties": { - "base": { - "type": "string" - }, - "endCursor": { - "type": "string" - }, - "files": { - "type": "array", - "items": { - "type": "object", - "required": [ - "path", - "added", - "deleted" - ], - "properties": { - "added": { - "type": "integer" - }, - "deleted": { - "type": "integer" - }, - "hunks": { - "type": "array", - "items": { - "type": "object", - "required": [ - "oldRange", - "newRange", - "body" - ], - "properties": { - "body": { - "type": "string" - }, - "newRange": { - "type": "object", - "required": [ - "startLine", - "lines" - ], - "properties": { - "lines": { - "type": "integer" - }, - "startLine": { - "type": "integer" - } - }, - "additionalProperties": false - }, - "oldRange": { - "type": "object", - "required": [ - "startLine", - "lines" - ], - "properties": { - "lines": { - "type": "integer" - }, - "startLine": { - "type": "integer" - } - }, - "additionalProperties": false - }, - "section": { - "type": "string" - } - }, - "additionalProperties": false - } - }, - "path": { - "type": "string" - } - }, - "additionalProperties": false - } - }, - "hasNextPage": { - "type": "boolean" - }, - "head": { - "type": "string" - }, - "repository": { - "type": "string" - }, - "totalAdded": { - "type": "integer" - }, - "totalDeleted": { - "type": "integer" - }, - "totalModified": { - "type": "integer" - } - }, - "additionalProperties": false - } - }, - { - "description": "\nCreate a new deep search conversation to answer complex questions about your codebase.\n\nPowered by an agentic LLM, this deep research tool performs an in-depth investigation of your codebase\n- Performs comprehensive analysis of your question\n- Uses multiple search and analysis tools automatically\n- Provides detailed, well-researched answers with evidence\n- Generates related follow-up suggestions\n\nUse this tool when you need:\n- Comprehensive analysis of complex technical questions\n- Multi-step research across one or many remote codebases\n- Detailed explanations with supporting evidence\n- Questions that require combining information from multiple sources\n\nExamples:\n\n\n\tHow does authentication work in this codebase?\n\tcalls the deep search tool with question: \"How does authentication work in this codebase?\"\n\n\n\tFind all the security vulnerabilities related to user input validation\n\tcalls the deep search tool with question: \"Find all the security vulnerabilities related to user input validation\"\n\n\n\tExplain the architecture and data flow of the payment processing system\n\tcalls the deep search tool with question: \"Explain the architecture and data flow of the payment processing system\"\n\n", - "inputSchema": { - "type": "object", - "$schema": "https://json-schema.org/draft/2020-12/schema", - "required": [ - "question" - ], - "properties": { - "question": { - "type": "string", - "description": "The question to research using deep search. Should be detailed and specific about what you want to understand." - } - }, - "additionalProperties": false - }, - "name": "sg_deepsearch", - "outputSchema": { - "type": "object", - "$schema": "https://json-schema.org/draft/2020-12/schema", - "required": [ - "conversation_id", - "question_id" - ], - "properties": { - "answer": { - "type": "string", - "description": "The answer generated by the deep search tool." - }, - "conversation_id": { - "type": "integer", - "description": "The ID of the conversation that was created to process the question. Can be used for follow-up questions" - }, - "error": { - "type": "object", - "description": "Any error that occurred during the deep search process.", - "required": [ - "title", - "kind", - "message" - ], - "properties": { - "details": { - "type": "string" - }, - "kind": { - "type": "string" - }, - "message": { - "type": "string" - }, - "title": { - "type": "string" - } - }, - "additionalProperties": false - }, - "link": { - "type": "string", - "description": "A link to the deep search conversation app." - }, - "question_id": { - "type": "integer", - "description": "The globally unique ID of the question that was processed." - }, - "suggested_followups": { - "type": "array", - "description": "Suggested follow-up questions based on the deep search result.", - "items": { - "type": "string" - } - }, - "title": { - "type": "string", - "description": "The title or summary of the deep search result." - } - }, - "additionalProperties": false - } - }, - { - "description": "This is a Sourcegraph search tool and is best used with other sourcegraph search tools. A tool that searches for code changes (diffs) across multiple repositories.\nThis tool searches ONLY the actual code changes (added/removed lines), not commit messages.\n\nUse this tool when you need to:\n- Find specific code patterns that were added or removed across repositories\n- Search for keywords in code changes across multiple repositories\n- Find changes related to specific features or bugs\n\nTips for effective diff searches:\n- Use the 'repos' parameter to focus your search on specific repositories\n- Use 'after' and 'before' to define a time range for the changes\n- Use 'pattern' to specify what you're looking for in the changed code\n- Add 'useRegex: true' for more complex search patterns\n- Use 'added: true' or 'removed: true' to search only in added or removed code\n\nExamples:\n\n \n Find instances where console.log was added across our repos in the past month\n calls the diff search tool with pattern=\"console.log\" after=\"1 month ago\" added=true\n \n \n Search for any hardcoded passwords that were removed in our backend services\n calls the diff search tool with pattern=\"password.*=\" repos=[\"github.com/myorg/backend*\"] removed=true useRegex=true\n \n \n Look for recent changes that mention 'API key' across all our microservices\n calls the diff search tool with pattern=\"API key\" repos=[\"github.com/myorg/service-*\"] after=\"2 weeks ago\"\n \n \n Find security-related code changes by author john.doe in the last quarter\n calls the diff search tool with pattern=\"security|auth|login\" author=\"john.doe\" after=\"3 months ago\" useRegex=true\n \n \n Search for any database connection changes across all repositories recently\n calls the diff search tool with pattern=\"database|db_connect|connection\" after=\"1 week ago\" useRegex=true\n \n", - "inputSchema": { - "type": "object", - "$schema": "https://json-schema.org/draft/2020-12/schema", - "required": [ - "pattern", - "repos" - ], - "properties": { - "added": { - "type": "boolean", - "description": "If true, only search in added code (default: search in both added and removed code)" - }, - "after": { - "type": "string", - "description": "Only include results from changes after this time (e.g., \"2 weeks ago\", \"2023-01-01\")" - }, - "author": { - "type": "string", - "description": "Filter by the author of the changes (e.g., \"username\")" - }, - "before": { - "type": "string", - "description": "Only include results from changes before this time (e.g., \"1 week ago\", \"2023-12-31\")" - }, - "count": { - "type": "integer", - "description": "Maximum number of results to return" - }, - "pattern": { - "type": "string", - "description": "The search pattern to look for in diff content (code changes, actual added/removed lines)" - }, - "removed": { - "type": "boolean", - "description": "If true, only search in removed code (default: search in both added and removed code)" - }, - "repos": { - "type": "array", - "description": "REQUIRED: Array of repository patterns to search in (e.g., [\"github.com/myorg/repo\", \"github.com/otherorg/*\"]). Multiple repositories will be combined with OR logic.", - "items": { - "type": "string" - } - }, - "useRegex": { - "type": "boolean", - "description": "Use regular expressions for searching (default: false)" - } - }, - "additionalProperties": false - }, - "name": "sg_diff_search", - "outputSchema": { - "type": "object", - "$schema": "https://json-schema.org/draft/2020-12/schema", - "required": [ - "query", - "results", - "totalCount", - "limitHit" - ], - "properties": { - "limitHit": { - "type": "boolean" - }, - "query": { - "type": "string" - }, - "results": { - "type": "array", - "items": { - "type": "object", - "required": [ - "repository", - "commit", - "diffHunk", - "url", - "matchRanges" - ], - "properties": { - "authorName": { - "type": "string" - }, - "commit": { - "type": "string" - }, - "diffHunk": { - "type": "string" - }, - "matchRanges": { - "type": "array", - "items": { - "type": "object", - "required": [ - "startLine", - "endLine", - "startCharacter", - "endCharacter" - ], - "properties": { - "endCharacter": { - "type": "integer" - }, - "endLine": { - "type": "integer" - }, - "startCharacter": { - "type": "integer" - }, - "startLine": { - "type": "integer" - } - }, - "additionalProperties": false - } - }, - "message": { - "type": "string" - }, - "repository": { - "type": "string" - }, - "url": { - "type": "string" - } - }, - "additionalProperties": false - } - }, - "totalCount": { - "type": "integer" - } - }, - "additionalProperties": false - } - }, - { - "description": "This is a Sourcegraph search tool and is best used with other sourcegraph search tools. Finds references to a provided symbol in a repository.\nA symbol is any code identifier, such as a function name, variable name, or class name.\nIt handles overloading by leveraging compiler information to ensure references are to the exact symbol requested. It can even handle cross-repository references.\n\nReturns a list of usages of that symbol, specifically:\n- Where the symbol is referenced in the code\n- The file and line number of each reference\n- Surrounding context of each reference to help understand its usage\nIf the symbol is not found, returns \"Symbol not found\"\n\nThis tool is the opposite of the sg_go_to_definition tool - it finds references (usages) to a symbol given its definition.\n\nYou should use this tool when you have a specific symbol in mind (function, method, variable, class, etc.), you know where it is defined (a file path) and want to see where it is referenced / used in the codebase.\n\nYou should choose to use this tool over sg_keyword_search, sg_nls_search or sg_read_file when you have encountered the definition of a specific symbol (function, variable, class)\nand you want to see how that specific symbol is used throughout the codebase, understand code flow or performing impact analysis.\n\nExamples:\n\n\t\n\t\tFind where the AbstractPaymentProcessorClass is used. It's defined in src/processors/AbstractPaymentProcessor.ts in the ecommerce/payment-service repository.\n\t\t [calls the find references tool with repo=\"ecommerce/payment-service\", path=\"src/processors/AbstractPaymentProcessor.ts\", symbol=\"AbstractPaymentProcessor\"]\n\t\t {\n \"repo\": \"ecommerce/payment-service\",\n \"path\": \"src/processors/StripePaymentProcessor.ts\",\n \"rev\": \"HEAD\",\n \"chunks\": [\n\t\t\t\t\t{\n\t\t\t\t\t\t\"startLine\": 2,\n\t\t\t\t\t\t\"endLine\": 2,\n\t\t\t\t\t\t\"content\": \"2: import { AbstractPaymentProcessor } from './AbstractPaymentProcessor';\\n\"\n\t\t\t\t\t},\n {\n \"startLine\": 102,\n \"endLine\": 103,\n \"content\": \"102: class StripePaymentProcessor extends AbstractPaymentProcessor {\\n103: \\tprivate readonly Status status;\\n\"\n }\n ]\n }\n\t\t\n\t\n", - "inputSchema": { - "type": "object", - "$schema": "https://json-schema.org/draft/2020-12/schema", - "required": [ - "repo", - "path", - "symbol" - ], - "properties": { - "path": { - "type": "string", - "description": "The path to the file within the repository containing the symbol reference, e.g. \"src/utils/date.ts\"." - }, - "repo": { - "type": "string", - "description": "The name of the repository containing the file, e.g. \"github.com/tuckersoft/thronglets\"." - }, - "revision": { - "type": "string", - "description": "The revision or branch to find references in. If not specified, defaults to the HEAD of the default branch." - }, - "symbol": { - "type": "string", - "description": "The name of the symbol (function name, method name, class, variable, constant, etc) to find references for, e.g. \"handleSearch\"." - } - }, - "additionalProperties": false - }, - "name": "sg_find_references", - "outputSchema": { - "type": "object", - "$schema": "https://json-schema.org/draft/2020-12/schema", - "required": [ - "fileBlocks" - ], - "properties": { - "fileBlocks": { - "type": "array", - "items": { - "type": "object", - "required": [ - "type", - "repo", - "file", - "chunks" - ], - "properties": { - "chunks": { - "type": "array", - "items": { - "type": "object", - "required": [ - "startLine", - "endLine", - "content" - ], - "properties": { - "content": { - "type": "string" - }, - "endLine": { - "type": "integer" - }, - "startLine": { - "type": "integer" - } - }, - "additionalProperties": false - } - }, - "file": { - "type": "string" - }, - "repo": { - "type": "string" - }, - "rev": { - "type": "string" - }, - "type": { - "type": "string" - } - }, - "additionalProperties": false - } - } - }, - "additionalProperties": false - } - }, - { - "description": "This is a Sourcegraph search tool and is best used with other sourcegraph search tools. Find repositories where a specific contributor has made commits.\nThis tool helps identify which repositories a person has contributed to, making it useful for scoping commit searches.\n\nUse this tool when you need to:\n- Find all repositories a person has worked on\n- Scope commit or diff searches to relevant repositories\n- Understand a contributor's involvement across the codebase\n\nThe tool searches by author name or email address and returns repositories with contribution statistics.\n\nExamples:\n\n\t\n\t\tWhat repositories has Jim contributed to?\n\t\tcalls get contributor repos tool with author=\"Jim\"\n\t\n\t\n\t\tWhat has john.doe@company.com been working on?\n\t\tcalls get contributor repos tool with author=\"john.doe@company.com\"\n\t\n", - "inputSchema": { - "type": "object", - "$schema": "https://json-schema.org/draft/2020-12/schema", - "required": [ - "author" - ], - "properties": { - "author": { - "type": "string", - "description": "Author name or email address to search for. Case-insensitive partial matching (e.g., \"john\" will match \"john.doe@company.com\" and \"John Smith\")." - }, - "limit": { - "type": "integer", - "description": "Maximum number of repositories to return. Defaults to 20, max 100." - }, - "minCommits": { - "type": "integer", - "description": "Minimum number of commits the author must have in a repository to include it. Defaults to 1." - } - }, - "additionalProperties": false - }, - "name": "sg_get_contributor_repos", - "outputSchema": { - "type": "object", - "$schema": "https://json-schema.org/draft/2020-12/schema", - "required": [ - "repositories" - ], - "properties": { - "repositories": { - "type": "array", - "items": { - "type": "object", - "required": [ - "repoName", - "repoCommitCount", - "repoMostRecentCommitDate" - ], - "properties": { - "repoCommitCount": { - "type": "integer" - }, - "repoMostRecentCommitDate": { - "type": "string" - }, - "repoName": { - "type": "string" - } - }, - "additionalProperties": false - } - } - }, - "additionalProperties": false - } - }, - { - "description": "This is a Sourcegraph search tool and is best used with other sourcegraph search tools. Finds the definition of a specified symbol in a repository.\nThis tool can leverage compiler-level symbol information to provide accurate results and can handle cross-repository references.\n\nA symbol is any code identifier, such as a function or method name, variable name, or class name such as 'MyClass' or 'readFile'.\nThe symbol name should be the identifier as it appears in code (e.g., 'validateToken', 'MyClass', 'API_ENDPOINT').\nFor methods, use just the method name without the class prefix.\nFor nested symbols, use the simple name rather than fully qualified paths.\n\nThe tool will return the code snippet containing the definition of the symbol in the codebase, as well as its location - the file name and line number.\nIt will return up to 50 lines of the code snippet containing the definition of the symbol.\n\nThis tool is the opposite of the sg_find_references tool - it finds the definition to a symbol given a reference/usage symbol.\n\nYou should use this tool when you have a specific symbol in mind (function, method, variable, class, etc.), you know where it is used (a file path) and want to see its definition in the codebase.\n\nYou should choose to use this tool over sg_keyword_search, sg_nls_search or sg_read_file when you have encountered a specific symbol (function, method, variable, class, etc.)\nthat you want to understand better by seeing its definition.\n\nExamples:\n\n \n I'm working in the auth-service/backend repo, in the file src/middleware/authMiddleware.js. This code calls await validateToken(session, token). Where is the function validateToken defined?\n [calls the go to definition tool with repo=\"auth-service/backend\", path=\"src/middleware/authMiddleware.js\", symbol=\"validateToken\"]\n {\n \"repo\": \"auth-service/backend\",\n \"path\": \"src/middleware/validation.js\",\n \"rev\": \"HEAD\",\n \"chunks\": [\n {\n \"startLine\": 12,\n \"endLine\": 62,\n \"content\": \"12: function validateToken(session, token) { ... }\"\n }\n ]\n }\n \n \n", - "inputSchema": { - "type": "object", - "$schema": "https://json-schema.org/draft/2020-12/schema", - "required": [ - "repo", - "path", - "symbol" - ], - "properties": { - "path": { - "type": "string", - "description": "The path to the file within the repository containing the symbol reference." - }, - "repo": { - "type": "string", - "description": "The name of the repository containing the file. For example, \"github.com/burntsushi/ripgrep\"." - }, - "revision": { - "type": "string", - "description": "The revision or branch to find the definition in. If not specified, defaults to the HEAD of the default branch." - }, - "symbol": { - "type": "string", - "description": "The name of the symbol to find the definition for." - } - }, - "additionalProperties": false - }, - "name": "sg_go_to_definition", - "outputSchema": { - "type": "object", - "$schema": "https://json-schema.org/draft/2020-12/schema", - "required": [ - "fileBlocks" - ], - "properties": { - "fileBlocks": { - "type": "array", - "items": { - "type": "object", - "required": [ - "type", - "repo", - "file", - "chunks" - ], - "properties": { - "chunks": { - "type": "array", - "items": { - "type": "object", - "required": [ - "startLine", - "endLine", - "content" - ], - "properties": { - "content": { - "type": "string" - }, - "endLine": { - "type": "integer" - }, - "startLine": { - "type": "integer" - } - }, - "additionalProperties": false - } - }, - "file": { - "type": "string" - }, - "repo": { - "type": "string" - }, - "rev": { - "type": "string" - }, - "type": { - "type": "string" - } - }, - "additionalProperties": false - } - } - }, - "additionalProperties": false - } - }, - { - "description": "This is a Sourcegraph search tool and is best used with other sourcegraph search tools. \nA keyword code search tool that helps you find relevant code snippets across repositories. Use this tool when you need to:\n- Find specific code with exact matching\n- Verify if certain code exists in the codebase\n- Find examples of code usage\n\nSearch capabilities:\n- Basic search: Enter keywords to find code containing those terms\n- Boolean search: Use AND/OR operators to combine terms. By default, all search terms are combined with AND, meaning that all search terms must match for a result to be included.\n- Filters:\n\t* repo: to search specific repositories (supports regex) Example: repo:github.com/google will select all repositories with the matching prefix (github.com/google-gemini/cookbook and github.com/google/neuroglancer both match). Use ^ to match the start of the string and $ to match the end of the string to avoid unwanted matches. You can chain multiple repo filters with OR while putting them in parentheses.\n\t* file: to search specific file patterns (supports regex) Example: file:README.md will only search files that have README.md in their name. file:.*.ts will search all files with a .ts extension.\n\t* rev: to search specific revisions (branches, tags, commits/sha). MUST always be used together with a repo: filter. Example: repo:^foo/bar$ rev:feat/xyz will only search the branch feat/xyz of the repo foo/bar. If not specified, defaults to the HEAD of the default branch.\n\nWhen not to use this tool:\n- For semantic or conceptual searches like 'authentication implementation'\n- For queries that are similar to natural language like \"API calls to middleware in admin panel\".\n- When you are not sure if the term exists in the codebase.\n- For queries with several search terms.\n- For exploratory searching of the codebase, when you are not sure what a certain term or name means.\nImportant: In these cases, use the sg_nls_search tool instead.\n\nBest practices:\n- Use a small (1-3) number of search terms. Because we combine terms with AND by default, using too many terms may result in no results.\n- Use specific, descriptive search terms\n- Start with broader searches and narrow down using filters\n- Use repo: and file: filters to improve result relevance\n- The results are case insensitive, so you should not repeat the same search term with different capitalization.\n- Use regex (file:.*.py) instead of glob (file:*.py) for searching files with a .py extension\n- Don't use the rev: filter unless the user specifically asks for a particular branch, tag, or commit. The default behavior is to search the HEAD of the default branch.\nImportant: Use the literal OR between search terms if you are looking for code containing at least one of the terms. Do not use regex or with |.\n\nReturns the top 3 most relevant code chunks (truncated to 1024 characters) from each matching file (up to 15 files).\nIndividual lines longer than 256 characters are truncated.\n\nExamples:\n\n\n\tFind all code in the secret-fellowship organization on Github using log4j\n\tcalls the keyword search tool with query: \"repo:^github.com/secret-fellowship log4j\"\n\n\n\tFind all code in the github.com/kubernetes/autoscaler repo that uses the http.NewRequest function\n\tcalls the keyword search tool with query: \"repo:^github.com/kubernetes/autoscaler$ http.NewRequest\"\n\n\n\tFind Go code in ollama where memory mapping is used on darwin or linux\n\tcalls the keyword search tool with query: \"repo:ollama file:.*.go mmap AND (darwin OR linux)\"\n\n\n\tFind FAQs in all readme files across all repositories\n\tcalls the keyword search tool with query: \"file:README.md FAQ\"\n\n\n\tFind code in bar or foo repos that uses lodash\n\tcalls the keyword search tool with query: \"(repo:foo OR repo:bar) lodash\"\n\n\n\tFind code containing either foo or bar in the dev/docs directory\n\tcalls the keyword search tool with query: \"file:^dev/docs foo OR bar\"\n\n\n\tFind code containing foo in dev/docs directory of the repo bar/bas on branch quz/user>\n\tcalls the keyword search tool with query: \"repo:^bar/bas$ rev:quz file:^dev/docs foo\"\n\n", - "inputSchema": { - "type": "object", - "$schema": "https://json-schema.org/draft/2020-12/schema", - "required": [ - "query" - ], - "properties": { - "query": { - "type": "string", - "description": "The search query. Can include keywords, regex patterns, and filters." - } - }, - "additionalProperties": false - }, - "name": "sg_keyword_search", - "outputSchema": { - "type": "object", - "$schema": "https://json-schema.org/draft/2020-12/schema", - "required": [ - "blocks" - ], - "properties": { - "blocks": { - "type": "array", - "items": true - } - }, - "additionalProperties": false - } - }, - { - "description": "This is a Sourcegraph search tool and is best used with other sourcegraph search tools. Lists the files and subdirectories in the workspace in a given directory.\nDirect subdirectories are included and the path is returned with a trailing slash.\nThe input path is relative to the root of the repository.\n\nLists up to 1000 files or directories. If there are more, the response will be truncated.\nDirectories are listed first.\n\nExamples:\n\n\t\n\t\tList all files in the src directory of the repository.\n\t\tCalls the list files tool with path: \"src\"\n\t\t[{\"path\": \"app/\", \"isDirectory\": true}, {\"path\": \"DEV.md\", \"isDirectory\": false}]\n\t\n\n", - "inputSchema": { - "type": "object", - "$schema": "https://json-schema.org/draft/2020-12/schema", - "required": [ - "repo" - ], - "properties": { - "path": { - "type": "string", - "description": "The directory path within the workspace to list files from. Defaults to workspace root if not specified." - }, - "repo": { - "type": "string", - "description": "The name of the repository containing the files. For example, \"github.com/torvalds/linux\"." - }, - "revision": { - "type": "string", - "description": "The revision or branch to list files from. If not specified, defaults to the HEAD of the default branch." - } - }, - "additionalProperties": false - }, - "name": "sg_list_files", - "outputSchema": { - "type": "object", - "$schema": "https://json-schema.org/draft/2020-12/schema", - "required": [ - "files" - ], - "properties": { - "files": { - "type": "array", - "items": { - "type": "object", - "required": [ - "path", - "isDirectory" - ], - "properties": { - "isDirectory": { - "type": "boolean" - }, - "path": { - "type": "string" - } - }, - "additionalProperties": false - } - } - }, - "additionalProperties": false - } - }, - { - "description": "This is a Sourcegraph search tool and is best used with other sourcegraph search tools. \nLists repositories that match a search query.\nYou can use this tool to figure out the repositories the user wants to talk about.\nReturns repository names, descriptions, and other metadata.\nBy default, returns up to 50 repositories per page.\nSupports cursor-based pagination - the response will include cursor information that can be used to fetch the next or previous page of results.\nUse the \"after\" parameter with the \"endCursor\" from the previous response to get the next page, or \"before\" with \"startCursor\" to get the previous page.\n\nWhen to use this tool:\n- When you do not know the full name of a repository (e.g. the user asks to search the xyz repo, you can use this tool to get github.com/my-org/xyz)\n- When you have to find repositories by substring matching (e.g. you want to find all repositories that contain the word \"foobar\")\nThe pattern is not a regular expression, but uses substring matching on the name of the repo.\n\nExamples:\n\n\t\n\t\tFind repositories in the cool-kids-club org on Github\n\t\tCalls the list repos tool with query: \"github.com/cool-kids-club\"\n\t\n\t\n\t\tExplain the foo repository\n\t\tCalls the list repos tool with query: \"foo\"\n\t\n\t\n\t\tDo we have repositories named \"baz\" and \"qux\"?\n\t\tCalls the list repos tool with query \"baz\", calls the list repos tool with query \"qux\"\n\t\n", - "inputSchema": { - "type": "object", - "$schema": "https://json-schema.org/draft/2020-12/schema", - "required": [ - "query" - ], - "properties": { - "after": { - "type": "string", - "description": "Cursor to start fetching results after. Use the \"endCursor\" from the previous response." - }, - "before": { - "type": "string", - "description": "Cursor to start fetching results before. Use the \"startCursor\" from the previous response." - }, - "limit": { - "type": "integer", - "description": "Maximum number of repositories to return per page. Defaults to 50." - }, - "query": { - "type": "string", - "description": "A search query to filter repositories. For example, \"django\" to find repositories containing that term." - } - }, - "additionalProperties": false - }, - "name": "sg_list_repos", - "outputSchema": { - "type": "object", - "$schema": "https://json-schema.org/draft/2020-12/schema", - "required": [ - "repositories", - "pagination" - ], - "properties": { - "pagination": { - "type": "object", - "required": [ - "totalCount", - "hasNextPage", - "hasPreviousPage" - ], - "properties": { - "endCursor": { - "type": "string" - }, - "hasNextPage": { - "type": "boolean" - }, - "hasPreviousPage": { - "type": "boolean" - }, - "startCursor": { - "type": "string" - }, - "totalCount": { - "type": "integer" - } - }, - "additionalProperties": false - }, - "repositories": { - "type": "array", - "items": { - "type": "object", - "required": [ - "name", - "description", - "private", - "archived", - "fork", - "stars" - ], - "properties": { - "archived": { - "type": "boolean" - }, - "description": { - "type": "string" - }, - "fork": { - "type": "boolean" - }, - "name": { - "type": "string" - }, - "private": { - "type": "boolean" - }, - "stars": { - "type": "integer" - } - }, - "additionalProperties": false - } - } - }, - "additionalProperties": false - } - }, - { - "description": "This is a Sourcegraph search tool and is best used with other sourcegraph search tools. \nA semantic code search tool that helps find relevant code snippets using flexible linguistic matching.\n\nUse this tool over sg_keyword_search when you need to:\n- Find code related to concepts rather than exact matches\n- Get broader results with more potential matches\n- Find code when you don't know the exact keyword to search for like symbol (function or variable) names\n- When the sg_keyword_search tool returns too few results\n\nSearch capabilities:\n- The core matching is also keyword-based, but it's more flexible and can match more terms\n- Uses stemming and OR binding between terms for broader matching (e.g. \"auth impl\" matches on either term)\n- Filters: same as sg_keyword_search tool\n\nWhen not to use this tool:\n- When you need exact string matches (use the sg_keyword_search tool instead)\n- When you're looking for specific function names or variables\n\nBest practices:\n- IMPORTANT: Extract relevant keywords from a natural language query and search with only the keywords - if a user asks \"How are database connections created or closed in the codebase?\", search with \"database connection create close\", not \"how are database connections created closed\"\n- For complex topics with multiple aspects, do separate searches for each main concept\n- Use repo: and file: filters to improve result relevance\n- If results seem off-target, try refining your query to be more specific or use filters to avoid unwanted results\n- The results are case insensitive, so you should not repeat the same search term with different capitalization\n\nReturns the top 3 most relevant code chunks (truncated to 1024 characters) from each matching file (up to 15 files).\nIndividual lines longer than 256 characters are truncated.\n\nExamples:\n\n\n\tFind where event listener handlers are set up in the codebase\n\tcalls the nls search tool with query: \"event listen handler\"\n\n\n\tExplain the code that controls the chat view in barfoo repo\n\tcalls the nls search tool with query: \"repo:barfoo$ view controller chat\"\n\n\n\tHow are database connections managed in the github.com/django/django repo?\n\tcalls the nls search tool with query: \"repo:^github.com/django/django$ database connection manage\"\n\n\n", - "inputSchema": { - "type": "object", - "$schema": "https://json-schema.org/draft/2020-12/schema", - "required": [ - "query" - ], - "properties": { - "query": { - "type": "string", - "description": "The search query. Can include keywords, regex patterns, and filters." - } - }, - "additionalProperties": false - }, - "name": "sg_nls_search", - "outputSchema": { - "type": "object", - "$schema": "https://json-schema.org/draft/2020-12/schema", - "required": [ - "blocks" - ], - "properties": { - "blocks": { - "type": "array", - "items": true - } - }, - "additionalProperties": false - } - }, - { - "description": "This is a Sourcegraph search tool and is best used with other sourcegraph search tools. \nReads the content of a file in the workspace.\nReturns the file content as a string.\nEach line is prefixed with its actual line number from the file. The line numbers are 1-indexed. If a file contains \"abc\\\\ndef\", you will receive \"1: abc\\\\n2: def\".\nYou can optionally specify a line range to read only a portion of the file.\nIf you attempt to read a file that is too large (limit is 128 KB), you will receive an error. In that case, retry with a smaller line range.\n\nIMPORTANT: Use this tool ONLY when you have already located the specific file.\nBefore using this tool:\n- ALWAYS verify both the repository and file exist by using sg_list_repos, sg_list_files, sg_keyword_search, or sg_nls_search first\n- NEVER try to read a file without first confirming it exists at the exact path\n- NEVER guess file paths or assume common structures like \"lib/shared/src\" exist - always verify\n\nExamples:\n\n\n\tSummarize the readme in the pytorch/torcheval repository\n\t[First checks that the repository exists by calling sg_list_repos]\n\t[Then verifies README.md exists using sg_list_files with repo: \"pytorch/torcheval\"]\n\tCalls the read file tool with repo: \"pytorch/torcheval\", path: \"README.md\"\n\n\n\tRead the first 100 lines of the code in cli/build.rs in the tokio-rs/tokio repository\n\t[First confirms the file exists using sg_list_files or sg_keyword_search]\n\tCalls the read file tool with repo: \"tokio-rs/tokio\", path: \"cli/build.rs\", startLine: 1, endLine: 100\n\n\n\tRead the first 100 lines of the code in cli/build.rs in the tokio-rs/tokio repository at commit 1234567890\n\t[First confirms the file exists using sg_list_files or sg_keyword_search]\n\tCalls the read file tool with repo: \"tokio-rs/tokio\", path: \"cli/build.rs\", startLine: 1, endLine: 100, revision: \"1234567890\"\n\n\n\tRead the first 100 lines of the code in cli/build.rs in the tokio-rs/tokio repository at branch feat/xzy\n\t[First confirms the file exists using sg_list_files or sg_keyword_search]\n\tCalls the read file tool with repo: \"tokio-rs/tokio\", path: \"cli/build.rs\", startLine: 1, endLine: 100, revision: \"feat/xzy\"\n\n", - "inputSchema": { - "type": "object", - "$schema": "https://json-schema.org/draft/2020-12/schema", - "required": [ - "repo", - "path" - ], - "properties": { - "endLine": { - "type": "integer", - "description": "The 1-based line number to end reading at. If not specified, reads to the end of the file." - }, - "path": { - "type": "string", - "description": "The path to the file within the repository." - }, - "repo": { - "type": "string", - "description": "The name of the repository containing the file. For example, \"github.com/sveltejs/svelte\"." - }, - "revision": { - "type": "string", - "description": "The revision to read the file from. If not specified, reads from the default branch. This can be a commit hash or a branch name" - }, - "startLine": { - "type": "integer", - "description": "The 1-based line number to start reading from. If not specified, starts from the beginning of the file." - } - }, - "additionalProperties": false - }, - "name": "sg_read_file", - "outputSchema": { - "type": "object", - "$schema": "https://json-schema.org/draft/2020-12/schema", - "required": [ - "content" - ], - "properties": { - "content": { - "type": "string" - } - }, - "additionalProperties": false - } - } - ] -} diff --git a/internal/mcp/registry.go b/internal/mcp/registry.go deleted file mode 100644 index 6797c3e829..0000000000 --- a/internal/mcp/registry.go +++ /dev/null @@ -1,61 +0,0 @@ -package mcp - -import ( - "context" - "encoding/json" - "iter" - "maps" - "slices" - - "github.com/sourcegraph/src-cli/internal/api" -) - -// ToolRegistry keeps track of tools and the endpoints they originated from -type ToolRegistry struct { - tools map[string]*ToolDef -} - -func NewToolRegistry() *ToolRegistry { - return &ToolRegistry{ - tools: make(map[string]*ToolDef), - } -} - -// LoadTools loads the tool definitions from the Mcp tool endpoints constants McpURLPath -func (r *ToolRegistry) LoadTools(ctx context.Context, client api.Client) error { - tools, err := fetchToolDefinitions(ctx, client, MCPURLPath) - if err != nil { - return err - } - r.tools = tools - return nil -} - -// Get returns the tool definition for the given name -func (r *ToolRegistry) Get(name string) (*ToolDef, bool) { - tool, ok := r.tools[name] - return tool, ok -} - -// CallTool calls the given tool with the given arguments. It constructs the Tool request and decodes the Tool response -func (r *ToolRegistry) CallTool(ctx context.Context, client api.Client, name string, args map[string]any) (map[string]json.RawMessage, error) { - tool := r.tools[name] - resp, err := doToolCall(ctx, client, MCPURLPath, tool.RawName, args) - if err != nil { - return nil, err - } - defer resp.Body.Close() - return decodeToolResponse(resp) -} - -// All returns an iterator that yields the name and Tool definition of all registered tools -func (r *ToolRegistry) All() iter.Seq2[string, *ToolDef] { - keys := slices.Sorted(maps.Keys(r.tools)) - return func(yield func(string, *ToolDef) bool) { - for _, key := range keys { - if !yield(key, r.tools[key]) { - return - } - } - } -} From e7408e04fcf1baf2f5445a71d4850c9830b18fd6 Mon Sep 17 00:00:00 2001 From: Bolaji Olajide <25608335+BolajiOlajide@users.noreply.github.com> Date: Wed, 14 Jan 2026 13:35:44 +0100 Subject: [PATCH 535/647] chore(logs): add verbose logging for batch changes steps (#1242) * batches/ui: add verbose logging to step execution Add detailed verbose logging to stepsExecTUI for batch changes execution. When -v flag is passed, users now see logs for: - Archive download start/completion/failure - Workspace initialization - Step caching (skipped steps) - Step preparation and execution - Step completion with diff size and file change counts - Step failures with exit codes * batches/ui: add verbose logging to pre-execution phases Add verbose logging to TUI for batch changes pre-execution steps: - Namespace resolution: show resolved namespace ID - Container images: log successful preparation - Workspace resolution: show workspace/repo counts and unsupported/ignored counts - Cache check: show cached specs and tasks to execute --- internal/batches/ui/task_exec_tui.go | 67 +++++++++++++++++++++++++--- internal/batches/ui/tui.go | 8 +++- 2 files changed, 67 insertions(+), 8 deletions(-) diff --git a/internal/batches/ui/task_exec_tui.go b/internal/batches/ui/task_exec_tui.go index b90df64fe9..080107036d 100644 --- a/internal/batches/ui/task_exec_tui.go +++ b/internal/batches/ui/task_exec_tui.go @@ -236,6 +236,7 @@ func (ui *taskExecTUI) StepsExecutionUI(task *executor.Task) executor.StepsExecu } return &stepsExecTUI{ + out: ui.out, task: task, updateStatusBar: func(message string) { ts.currentlyExecuting = message @@ -427,41 +428,68 @@ func diffStatDiagram(stat diff.Stat) string { } type stepsExecTUI struct { + out *output.Output task *executor.Task updateStatusBar func(string) } func (ui stepsExecTUI) ArchiveDownloadStarted() { ui.updateStatusBar("Downloading archive") + ui.out.Verbosef("[%s] Downloading repository archive...", ui.task.Repository.Name) } -func (ui stepsExecTUI) ArchiveDownloadFinished(err error) {} + +func (ui stepsExecTUI) ArchiveDownloadFinished(err error) { + if err != nil { + ui.out.Verbosef("[%s] Archive download failed: %v", ui.task.Repository.Name, err) + } else { + ui.out.Verbosef("[%s] Archive download completed", ui.task.Repository.Name) + } +} + func (ui stepsExecTUI) WorkspaceInitializationStarted() { ui.updateStatusBar("Initializing workspace") + ui.out.Verbosef("[%s] Initializing workspace...", ui.task.Repository.Name) +} + +func (ui stepsExecTUI) WorkspaceInitializationFinished() { + ui.out.Verbosef("[%s] Workspace initialization completed", ui.task.Repository.Name) } -func (ui stepsExecTUI) WorkspaceInitializationFinished() {} + func (ui stepsExecTUI) SkippingStepsUpto(startStep int) { switch startStep { case 1: ui.updateStatusBar("Skipping step 1. Found cached result.") + ui.out.Verbosef("[%s] Skipping step 1 (cached result found)", ui.task.Repository.Name) default: ui.updateStatusBar(fmt.Sprintf("Skipping steps 1 to %d. Found cached results.", startStep)) + ui.out.Verbosef("[%s] Skipping steps 1 to %d (cached results found)", ui.task.Repository.Name, startStep) } } func (ui stepsExecTUI) StepSkipped(step int) { ui.updateStatusBar(fmt.Sprintf("Skipping step %d", step)) + ui.out.Verbosef("[%s] Step %d skipped", ui.task.Repository.Name, step) } + func (ui stepsExecTUI) StepPreparingStart(step int) { ui.updateStatusBar(fmt.Sprintf("Preparing step %d", step)) + ui.out.Verbosef("[%s] Preparing step %d...", ui.task.Repository.Name, step) } + func (ui stepsExecTUI) StepPreparingSuccess(step int) { - // noop right now + ui.out.Verbosef("[%s] Step %d preparation completed", ui.task.Repository.Name, step) } + func (ui stepsExecTUI) StepPreparingFailed(step int, err error) { - // noop right now + ui.out.Verbosef("[%s] Step %d preparation failed: %v", ui.task.Repository.Name, step, err) } -func (ui stepsExecTUI) StepStarted(step int, runScript string, _ map[string]string) { + +func (ui stepsExecTUI) StepStarted(step int, runScript string, env map[string]string) { ui.updateStatusBar(runScript) + ui.out.Verbosef("[%s] Step %d started: %s", ui.task.Repository.Name, step, truncateScript(runScript, 100)) + if len(env) > 0 { + ui.out.Verbosef("[%s] Step %d environment variables: %d set", ui.task.Repository.Name, step, len(env)) + } } func (ui stepsExecTUI) StepOutputWriter(ctx context.Context, task *executor.Task, step int) executor.StepOutputWriter { @@ -469,8 +497,33 @@ func (ui stepsExecTUI) StepOutputWriter(ctx context.Context, task *executor.Task } func (ui stepsExecTUI) StepFinished(idx int, diff []byte, changes git.Changes, outputs map[string]any) { - // noop right now + ui.out.Verbosef("[%s] Step %d finished successfully", ui.task.Repository.Name, idx) + if len(diff) > 0 { + ui.out.Verbosef("[%s] Step %d produced %d bytes of diff", ui.task.Repository.Name, idx, len(diff)) + } + if len(changes.Modified)+len(changes.Added)+len(changes.Deleted)+len(changes.Renamed) > 0 { + ui.out.Verbosef("[%s] Step %d changes: %d modified, %d added, %d deleted, %d renamed", + ui.task.Repository.Name, idx, + len(changes.Modified), len(changes.Added), len(changes.Deleted), len(changes.Renamed)) + } + if len(outputs) > 0 { + ui.out.Verbosef("[%s] Step %d outputs: %d variables set", ui.task.Repository.Name, idx, len(outputs)) + } } + func (ui stepsExecTUI) StepFailed(idx int, err error, exitCode int) { - // noop right now + ui.out.Verbosef("[%s] Step %d failed (exit code %d): %v", ui.task.Repository.Name, idx, exitCode, err) +} + +// truncateScript truncates a script string for display purposes +func truncateScript(script string, maxLen int) string { + lines := strings.Split(script, "\n") + firstLine := lines[0] + if len(firstLine) > maxLen { + return firstLine[:maxLen] + "..." + } + if len(lines) > 1 { + return firstLine + " ..." + } + return firstLine } diff --git a/internal/batches/ui/tui.go b/internal/batches/ui/tui.go index 94724909b1..405918909e 100644 --- a/internal/batches/ui/tui.go +++ b/internal/batches/ui/tui.go @@ -63,8 +63,9 @@ func (ui *TUI) ResolvingNamespace() { ui.pending = batchCreatePending(ui.Out, "Resolving namespace") } -func (ui *TUI) ResolvingNamespaceSuccess(_namespace string) { +func (ui *TUI) ResolvingNamespaceSuccess(namespace string) { batchCompletePending(ui.pending, "Resolving namespace") + ui.Out.Verbosef("Resolved namespace: %s", namespace) } func (ui *TUI) PreparingContainerImages() { @@ -80,6 +81,7 @@ func (ui *TUI) PreparingContainerImagesProgress(done, total int) { func (ui *TUI) PreparingContainerImagesSuccess() { ui.progress.Complete() + ui.Out.Verbosef("Container images prepared successfully") } func (ui *TUI) DeterminingWorkspaceCreatorType() { @@ -104,13 +106,16 @@ func (ui *TUI) DeterminingWorkspaces() { func (ui *TUI) DeterminingWorkspacesSuccess(workspacesCount, reposCount int, unsupported batches.UnsupportedRepoSet, ignored batches.IgnoredRepoSet) { batchCompletePending(ui.pending, fmt.Sprintf("Resolved %d workspaces from %d repositories", workspacesCount, reposCount)) + ui.Out.Verbosef("Workspace resolution: %d workspaces across %d repositories", workspacesCount, reposCount) if len(unsupported) != 0 { + ui.Out.Verbosef("Unsupported repositories: %d", len(unsupported)) block := ui.Out.Block(output.Line(" ", output.StyleWarning, "Some repositories are hosted on unsupported code hosts and will be skipped. Use the -allow-unsupported flag to avoid skipping them.")) for repo := range unsupported { block.Write(repo.Name) } block.Close() } else if len(ignored) != 0 { + ui.Out.Verbosef("Ignored repositories (have .batchignore): %d", len(ignored)) block := ui.Out.Block(output.Line(" ", output.StyleWarning, "The repositories listed below contain .batchignore files and will be skipped. Use the -force-override-ignore flag to avoid skipping them.")) for repo := range ignored { block.Write(repo.Name) @@ -163,6 +168,7 @@ func (ui *TUI) CheckingCacheSuccess(cachedSpecsFound int, uncachedTasks int) { default: batchCompletePending(ui.pending, fmt.Sprintf("%s; %d tasks need to be executed", specsFoundMessage, uncachedTasks)) } + ui.Out.Verbosef("Cache check: %d cached specs found, %d tasks to execute", cachedSpecsFound, uncachedTasks) } func (ui *TUI) ExecutingTasks(verbose bool, parallelism int) executor.TaskExecutionUI { From 1ecebe64f543b7d52b624b81e97a41ec5fe0a4f5 Mon Sep 17 00:00:00 2001 From: Felix Kling Date: Thu, 19 Feb 2026 14:51:19 +0100 Subject: [PATCH 536/647] Disable team management from v7 on (#1257) --- cmd/src/teams.go | 29 ++++++++++++++++++++ internal/api/version.go | 17 ++++++++++++ internal/batches/features.go | 48 +++------------------------------ internal/features/features.go | 50 +++++++++++++++++++++++++++++++++++ 4 files changed, 99 insertions(+), 45 deletions(-) create mode 100644 internal/api/version.go create mode 100644 internal/features/features.go diff --git a/cmd/src/teams.go b/cmd/src/teams.go index 98708dc1ee..1f3f5b2622 100644 --- a/cmd/src/teams.go +++ b/cmd/src/teams.go @@ -1,8 +1,13 @@ package main import ( + "context" "flag" "fmt" + "os" + + "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/features" ) var teamsCommands commander @@ -27,6 +32,9 @@ Use "src teams [command] -h" for more information about a command. flagSet := flag.NewFlagSet("teams", flag.ExitOnError) handler := func(args []string) error { + if err := checkTeamsAvailability(); err != nil { + return err + } teamsCommands.run(flagSet, "src teams", usage, args) return nil } @@ -42,6 +50,27 @@ Use "src teams [command] -h" for more information about a command. }) } +// checkTeamsAvailability verifies that the connected Sourcegraph instance +// supports teams. Teams were removed in Sourcegraph 7.0. +func checkTeamsAvailability() error { + client := cfg.apiClient(api.NewFlags(flag.NewFlagSet("", flag.ContinueOnError)), os.Stderr) + + version, err := api.GetSourcegraphVersion(context.Background(), client) + if err != nil || version == "" { + // If we can't determine the version, let the command proceed. + return nil + } + + var ffs features.FeatureFlags + if err := ffs.SetFromVersion(version, true); err != nil { + return nil + } + if ffs.Sourcegraph70 { + return fmt.Errorf("the 'src teams' commands are not available for Sourcegraph versions 7.0 and later (detected version: %s). Teams have been removed", version) + } + return nil +} + const teamFragment = ` fragment TeamFields on Team { id diff --git a/internal/api/version.go b/internal/api/version.go new file mode 100644 index 0000000000..dbbf1ffefd --- /dev/null +++ b/internal/api/version.go @@ -0,0 +1,17 @@ +package api + +import "context" + +// GetSourcegraphVersion queries the Sourcegraph instance for its product version. +func GetSourcegraphVersion(ctx context.Context, client Client) (string, error) { + var result struct { + Site struct { + ProductVersion string + } + } + ok, err := client.NewQuery(`query { site { productVersion } }`).Do(ctx, &result) + if err != nil || !ok { + return "", err + } + return result.Site.ProductVersion, nil +} diff --git a/internal/batches/features.go b/internal/batches/features.go index 228775f66a..6084777b48 100644 --- a/internal/batches/features.go +++ b/internal/batches/features.go @@ -1,48 +1,6 @@ package batches -import ( - "fmt" - "log" +import "github.com/sourcegraph/src-cli/internal/features" - "github.com/sourcegraph/sourcegraph/lib/api" - "github.com/sourcegraph/sourcegraph/lib/errors" -) - -// FeatureFlags represent features that are only available on certain -// Sourcegraph versions and we therefore have to detect at runtime. -type FeatureFlags struct { - Sourcegraph40 bool - BinaryDiffs bool -} - -func (ff *FeatureFlags) SetFromVersion(version string, skipErrors bool) error { - for _, feature := range []struct { - flag *bool - constraint string - minDate string - }{ - // NOTE: It's necessary to include a "-0" prerelease suffix on each constraint so that - // prereleases of future versions are still considered to satisfy the constraint. - // - // For example, the version "3.35.1-rc.3" is not considered to satisfy the constraint - // ">= 3.23.0". However, the same version IS considered to satisfy the constraint - // "3.23.0-0". See - // https://github.com/Masterminds/semver#working-with-prerelease-versions for more. - // Example usage: - // {&ff.FlagName, ">= 3.23.0-0", "2020-11-24"}, - {&ff.Sourcegraph40, ">= 4.0.0-0", "2022-08-24"}, - {&ff.BinaryDiffs, ">= 4.3.0-0", "2022-11-29"}, - } { - value, err := api.CheckSourcegraphVersion(version, feature.constraint, feature.minDate) - if err != nil { - if skipErrors { - log.Printf("failed to check version returned by Sourcegraph: %s. Assuming no feature flags.", version) - } else { - return errors.Wrap(err, fmt.Sprintf("failed to check version returned by Sourcegraph: %s", version)) - } - } - *feature.flag = value - } - - return nil -} +// FeatureFlags is an alias for features.FeatureFlags for backwards compatibility. +type FeatureFlags = features.FeatureFlags diff --git a/internal/features/features.go b/internal/features/features.go new file mode 100644 index 0000000000..657ece2f14 --- /dev/null +++ b/internal/features/features.go @@ -0,0 +1,50 @@ +package features + +import ( + "fmt" + "log" + + "github.com/sourcegraph/sourcegraph/lib/api" + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +// FeatureFlags represent features that are only available on certain +// Sourcegraph versions and we therefore have to detect at runtime. +type FeatureFlags struct { + Sourcegraph40 bool + BinaryDiffs bool + Sourcegraph70 bool +} + +func (ff *FeatureFlags) SetFromVersion(version string, skipErrors bool) error { + for _, feature := range []struct { + flag *bool + constraint string + minDate string + }{ + // NOTE: It's necessary to include a "-0" prerelease suffix on each constraint so that + // prereleases of future versions are still considered to satisfy the constraint. + // + // For example, the version "3.35.1-rc.3" is not considered to satisfy the constraint + // ">= 3.23.0". However, the same version IS considered to satisfy the constraint + // "3.23.0-0". See + // https://github.com/Masterminds/semver#working-with-prerelease-versions for more. + // Example usage: + // {&ff.FlagName, ">= 3.23.0-0", "2020-11-24"}, + {&ff.Sourcegraph40, ">= 4.0.0-0", "2022-08-24"}, + {&ff.BinaryDiffs, ">= 4.3.0-0", "2022-11-29"}, + {&ff.Sourcegraph70, ">= 7.0.0-0", "2026-02-25"}, + } { + value, err := api.CheckSourcegraphVersion(version, feature.constraint, feature.minDate) + if err != nil { + if skipErrors { + log.Printf("failed to check version returned by Sourcegraph: %s. Assuming no feature flags.", version) + } else { + return errors.Wrap(err, fmt.Sprintf("failed to check version returned by Sourcegraph: %s", version)) + } + } + *feature.flag = value + } + + return nil +} From f404049771a58369b803e20d1eb541bdc4c5376d Mon Sep 17 00:00:00 2001 From: natehessler Date: Thu, 19 Feb 2026 08:51:37 -0600 Subject: [PATCH 537/647] Refactor client initialization for code intel upload (#1256) Will share update here from the customer after they test this * Refactor client initialization for code intel upload ### Problem The `src code-intel upload` command does not respect the `SRC_PROXY` environment variable, preventing uploads through corporate proxies. This also means standard `HTTP_PROXY`/`HTTPS_PROXY` environment variables are not honored. **Customer Impact**: Dropbox reported they can successfully upload code intelligence indexes from local machines, but uploads fail from their CI system which requires outbound proxy configuration. The `SRC_PROXY` environment variable works for `src search` and other commands, but not for `src code-intel upload`. ### Root Cause In `cmd/src/code_intel_upload.go:79-82`, the API client was constructed directly with `api.NewClient()`, passing only `Out` and `Flags`. This bypassed the global configuration object which contains: - Endpoint - Access token - Additional headers - **Proxy URL and proxy path** (parsed from `SRC_PROXY` environment variable) Other commands use the `cfg.apiClient()` helper method which properly includes all configuration. ### Fix Replace the manual `api.NewClient()` construction with `cfg.apiClient()`, ensuring the code-intel upload command uses the same fully-configured client as all other commands. * fixup --------- Co-authored-by: William Bezuidenhout --- cmd/src/code_intel_upload.go | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/cmd/src/code_intel_upload.go b/cmd/src/code_intel_upload.go index 8030b31a9a..dfc7a9190e 100644 --- a/cmd/src/code_intel_upload.go +++ b/cmd/src/code_intel_upload.go @@ -18,8 +18,6 @@ import ( "github.com/sourcegraph/sourcegraph/lib/codeintel/upload" "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/sourcegraph/lib/output" - - "github.com/sourcegraph/src-cli/internal/api" ) func init() { @@ -76,10 +74,7 @@ func handleCodeIntelUpload(args []string) error { return handleUploadError(cfg.AccessToken, err) } - client := api.NewClient(api.ClientOpts{ - Out: io.Discard, - Flags: codeintelUploadFlags.apiFlags, - }) + client := cfg.apiClient(codeintelUploadFlags.apiFlags, io.Discard) uploadOptions := codeintelUploadOptions(out) var uploadID int From ad16cda6acc1558c1e57dd5a347556776862a4e9 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Thu, 26 Feb 2026 10:44:25 +0200 Subject: [PATCH 538/647] chore: use sourcegraph/actions/go-setup and upgrade mise go to 1.25.6 (#1251) * upgrade go to 1.26 * Use sourcegraph/actions/go-setup for Go setup * remove use of private access token * bump golanci lint and fix issues * set golang version to 1.26 --- .github/workflows/go-ci.yml | 12 +----------- .github/workflows/go-lint.yml | 7 +------ .github/workflows/goreleaser-check.yml | 8 +------- .github/workflows/goreleaser.yml | 8 +------- .github/workflows/scip.yml | 8 +------- dev/golangci-lint.sh | 2 +- internal/batches/executor/run_steps.go | 6 +++--- mise.toml | 2 +- 8 files changed, 10 insertions(+), 43 deletions(-) diff --git a/.github/workflows/go-ci.yml b/.github/workflows/go-ci.yml index 17e8ae6926..5f7d9e63c8 100644 --- a/.github/workflows/go-ci.yml +++ b/.github/workflows/go-ci.yml @@ -3,10 +3,6 @@ name: Go CI on: workflow_dispatch: push: -env: - GOPRIVATE: "github.com/sourcegraph/*" - PRIVATE_TOKEN: "${{ secrets.PRIVATE_SG_ACCESS_TOKEN }}" - jobs: go-test: strategy: @@ -21,15 +17,9 @@ jobs: run: echo "go-version=$(grep 'golang' mise.toml | cut -d'"' -f2)" >> $GITHUB_OUTPUT shell: bash - name: Set up Go - uses: actions/setup-go@v6 + uses: sourcegraph/actions/go-setup@main with: go-version: ${{ steps.mise.outputs.go-version }} - - name: (Windows) Enable pulling Go modules from private sourcegraph/sourcegraph - if: runner.os == 'Windows' - run: git config --global url."https://$env:PRIVATE_TOKEN@github.com/sourcegraph/".insteadOf "https://github.com/sourcegraph/" - - name: (Default) Enable pulling Go modules from private sourcegraph/sourcegraph - if: runner.os != 'Windows' - run: git config --global url."https://${PRIVATE_TOKEN}@github.com/sourcegraph/".insteadOf "https://github.com/sourcegraph/" - run: | go test -race -v ./... go test -v ./... diff --git a/.github/workflows/go-lint.yml b/.github/workflows/go-lint.yml index d4a8ee3847..2a851b2a1b 100644 --- a/.github/workflows/go-lint.yml +++ b/.github/workflows/go-lint.yml @@ -3,9 +3,6 @@ name: Go Lint on: workflow_dispatch: push: -env: - GOPRIVATE: "github.com/sourcegraph/*" - PRIVATE_TOKEN: "${{ secrets.PRIVATE_SG_ACCESS_TOKEN }}" jobs: go-lint: @@ -17,9 +14,7 @@ jobs: id: mise run: echo "go-version=$(grep 'golang' mise.toml | cut -d'"' -f2)" >> $GITHUB_OUTPUT - name: Set up Go - uses: actions/setup-go@v6 + uses: sourcegraph/actions/go-setup@main with: go-version: ${{ steps.mise.outputs.go-version }} - - name: Enable pulling Go modules from private sourcegraph/sourcegraph - run: git config --global url."https://${PRIVATE_TOKEN}@github.com/sourcegraph/".insteadOf "https://github.com/sourcegraph/" - run: ./dev/go-lint.sh diff --git a/.github/workflows/goreleaser-check.yml b/.github/workflows/goreleaser-check.yml index 547e6a554c..780a6ba76b 100644 --- a/.github/workflows/goreleaser-check.yml +++ b/.github/workflows/goreleaser-check.yml @@ -3,10 +3,6 @@ name: GoReleaser check on: push: workflow_dispatch: -env: - GOPRIVATE: "github.com/sourcegraph/*" - PRIVATE_TOKEN: "${{ secrets.PRIVATE_SG_ACCESS_TOKEN }}" - jobs: goreleaser: name: check @@ -20,11 +16,9 @@ jobs: id: mise run: echo "go-version=$(grep 'golang' mise.toml | cut -d'"' -f2)" >> $GITHUB_OUTPUT - name: Set up Go - uses: actions/setup-go@v6 + uses: sourcegraph/actions/go-setup@main with: go-version: ${{ steps.mise.outputs.go-version }} - - name: Enable pulling Go modules from private sourcegraph/sourcegraph - run: git config --global url."https://${PRIVATE_TOKEN}@github.com/sourcegraph/".insteadOf "https://github.com/sourcegraph/" - name: Check GoReleaser config uses: goreleaser/goreleaser-action@v5 with: diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index 8f305d36a7..e7231900b5 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -5,10 +5,6 @@ on: push: tags: - '*' -env: - GOPRIVATE: "github.com/sourcegraph/*" - PRIVATE_TOKEN: "${{ secrets.PRIVATE_SG_ACCESS_TOKEN }}" - # There are two cases where this GitHub action will run: # # 1. We are releasing a new latest version for src-cli, as a major, minor, or patch @@ -182,11 +178,9 @@ jobs: id: mise run: echo "go-version=$(grep 'golang' mise.toml | cut -d'"' -f2)" >> $GITHUB_OUTPUT - name: Set up Go - uses: actions/setup-go@v6 + uses: sourcegraph/actions/go-setup@main with: go-version: ${{ steps.mise.outputs.go-version }} - - name: Enable pulling Go modules from private sourcegraph/sourcegraph - run: git config --global url."https://${PRIVATE_TOKEN}@github.com/sourcegraph/".insteadOf "https://github.com/sourcegraph/" - run: go test ./... - run: go test -race -v ./... - run: echo "${DOCKER_PASSWORD}" | docker login -u=$DOCKER_USERNAME --password-stdin diff --git a/.github/workflows/scip.yml b/.github/workflows/scip.yml index b546ea8bfa..91d467626a 100644 --- a/.github/workflows/scip.yml +++ b/.github/workflows/scip.yml @@ -2,9 +2,6 @@ name: SCIP on: workflow_dispatch: push: -env: - GOPRIVATE: "github.com/sourcegraph/*" - PRIVATE_TOKEN: "${{ secrets.PRIVATE_SG_ACCESS_TOKEN }}" jobs: scip-go: runs-on: ubuntu-latest @@ -15,7 +12,7 @@ jobs: id: mise run: echo "go-version=$(grep 'golang' mise.toml | cut -d'"' -f2)" >> $GITHUB_OUTPUT - name: Set up Go - uses: actions/setup-go@v6 + uses: sourcegraph/actions/go-setup@main with: go-version: ${{ steps.mise.outputs.go-version }} @@ -25,9 +22,6 @@ jobs: - name: Build src-cli run: go build -o ./src-cli ./cmd/src - - name: Enable pulling Go modules from private sourcegraph/sourcegraph - run: git config --global url."https://${PRIVATE_TOKEN}@github.com/sourcegraph/".insteadOf "https://github.com/sourcegraph/" - - name: Generate SCIP data run: scip-go diff --git a/dev/golangci-lint.sh b/dev/golangci-lint.sh index dffeb31b2f..e7adad08b2 100755 --- a/dev/golangci-lint.sh +++ b/dev/golangci-lint.sh @@ -6,7 +6,7 @@ pushd "$(dirname "${BASH_SOURCE[0]}")/.." >/dev/null mkdir -p dev/.bin -version="2.6.1" +version="2.10.1" suffix="${version}-$(go env GOOS)-$(go env GOARCH)" target="$PWD/dev/.bin/golangci-lint-${suffix}" url="https://github.com/golangci/golangci-lint/releases/download/v${version}/golangci-lint-${suffix}.tar.gz" diff --git a/internal/batches/executor/run_steps.go b/internal/batches/executor/run_steps.go index 92d1966dd7..97e952be71 100644 --- a/internal/batches/executor/run_steps.go +++ b/internal/batches/executor/run_steps.go @@ -660,7 +660,7 @@ func (e stepFailedErr) Error() string { return lines[0] + fmt.Sprintf("\n\t(... and %d more lines)", len(lines)-1) } - out.WriteString(fmt.Sprintf("run: %s\ncontainer: %s\n", fmtRun(e.Run), e.Container)) + fmt.Fprintf(&out, "run: %s\ncontainer: %s\n", fmtRun(e.Run), e.Container) printOutput := func(output string) { for line := range strings.SplitSeq(output, "\n") { @@ -682,9 +682,9 @@ func (e stepFailedErr) Error() string { } if e.ExitCode != -1 { - out.WriteString(fmt.Sprintf("\nCommand failed with exit code %d.", e.ExitCode)) + fmt.Fprintf(&out, "\nCommand failed with exit code %d.", e.ExitCode) } else { - out.WriteString(fmt.Sprintf("\nCommand failed: %s", e.Err)) + fmt.Fprintf(&out, "\nCommand failed: %s", e.Err) } return out.String() diff --git a/mise.toml b/mise.toml index a1f15d3c03..74bb884ee3 100644 --- a/mise.toml +++ b/mise.toml @@ -1,4 +1,4 @@ [tools] -golang = "1.25.4" +golang = "1.26.0" shfmt = "3.8.0" shellcheck = "0.10.0" From eb830b0069df77972a97b1be960bf23c76181439 Mon Sep 17 00:00:00 2001 From: Adam Chrapkowski Date: Fri, 27 Feb 2026 11:49:16 +0100 Subject: [PATCH 539/647] fix(codeintel): improve upload error hints for auth and permission failures When upload of a scip index fails, the error message may be misleading or incomplete. The complexity comes from two aspects. First that we have 2 tokens - sourcegraph access token and code host token. This PR makes sure that whenever a token is invalid we get most probable causes. Second part is that even if a token is valid on its own, the user may not have sufficient permission. sourcegraph/sourcegraph#10077 makes the error codes and messages more consistent on the server side. This way user gets a hint if token was wrong or there was a permission problem. To summarise. First of all user gets error message from the server which often is specific (ex. upload failed: must provide gitlab_token). However basing text returned by the server (server does not return structured response like JSON) is IMO fragile so except this error message user gets hints about possible problems. I believe those two together should eliminate confusion and point user in the right direction how to remediate the issue. We also always show the link to the documentation. Additionally existing code was deducing used code host based on the repository URL hostname, here we also check the specified command line parameter. Those hints which are displayed to the user is not a new invention, those were just improved to provide user with more accurate information and to utilise information from the server which effectively is best source of truth what the problem was. --- cmd/src/code_intel_upload.go | 169 ++++++++----- cmd/src/code_intel_upload_test.go | 352 ++++++++++++++++++++++++++ cmd/src/code_intel_upload_vendored.go | 28 +- 3 files changed, 475 insertions(+), 74 deletions(-) create mode 100644 cmd/src/code_intel_upload_test.go diff --git a/cmd/src/code_intel_upload.go b/cmd/src/code_intel_upload.go index dfc7a9190e..303e2199e0 100644 --- a/cmd/src/code_intel_upload.go +++ b/cmd/src/code_intel_upload.go @@ -71,7 +71,7 @@ func handleCodeIntelUpload(args []string) error { } } if err != nil { - return handleUploadError(cfg.AccessToken, err) + return err } client := cfg.apiClient(codeintelUploadFlags.apiFlags, io.Discard) @@ -212,17 +212,22 @@ func (e errorWithHint) Error() string { return fmt.Sprintf("%s\n\n%s\n", e.err, e.hint) } -// handleUploadError writes the given error to the given output. If the -// given output object is nil then the error will be written to standard out. -// -// This method returns the error that should be passed back up to the runner. +// handleUploadError attaches actionable hints to upload errors and returns +// the enriched error. Only called for actual upload failures (not flag validation). func handleUploadError(accessToken string, err error) error { - if errors.Is(err, upload.ErrUnauthorized) { - err = attachHintsForAuthorizationError(accessToken, err) + if httpErr := findAuthError(err); httpErr != nil { + isUnauthorized := httpErr.Code == 401 + isForbidden := httpErr.Code == 403 + + displayErr := errors.Newf("upload failed: %s", uploadFailureReason(httpErr)) + + err = errorWithHint{ + err: displayErr, + hint: uploadHints(accessToken, isUnauthorized, isForbidden), + } } if codeintelUploadFlags.ignoreUploadFailures { - // Report but don't return the error fmt.Println(err.Error()) return nil } @@ -230,76 +235,112 @@ func handleUploadError(accessToken string, err error) error { return err } -func attachHintsForAuthorizationError(accessToken string, originalError error) error { - var actionableHints []string +// findAuthError searches the error chain (including multi-errors from retries) +// for a 401 or 403 ErrUnexpectedStatusCode. Returns nil if none is found. +func findAuthError(err error) *ErrUnexpectedStatusCode { + // Check if it's a multi-error and scan all children. + if multi, ok := err.(errors.MultiError); ok { + for _, e := range multi.Errors() { + if found := findAuthError(e); found != nil { + return found + } + } + return nil + } + + var httpErr *ErrUnexpectedStatusCode + if errors.As(err, &httpErr) && (httpErr.Code == 401 || httpErr.Code == 403) { + return httpErr + } + return nil +} + +// uploadHints builds hint paragraphs for the Sourcegraph access token, +// code host tokens, and a docs link. +func uploadHints(accessToken string, isUnauthorized, isForbidden bool) string { + var causes []string - likelyTokenError := accessToken == "" - if _, parseErr := accesstoken.ParsePersonalAccessToken(accessToken); accessToken != "" && parseErr != nil { - likelyTokenError = true - actionableHints = append(actionableHints, - "However, the provided access token does not match expected format; was it truncated?", - "Typically the access token looks like sgp_<40 hex chars> or sgp__<40 hex chars>.") + if h := sourcegraphAccessTokenHint(accessToken, isUnauthorized, isForbidden); h != "" { + causes = append(causes, "- "+h) } - if likelyTokenError { - return errorWithHint{err: originalError, hint: strings.Join(mergeStringSlices( - []string{"A Sourcegraph access token must be provided via SRC_ACCESS_TOKEN for uploading SCIP data."}, - actionableHints, - []string{"For more details, see https://sourcegraph.com/docs/cli/how-tos/creating_an_access_token."}, - ), "\n")} + for _, h := range codeHostTokenHints(isUnauthorized) { + causes = append(causes, "- "+h) } - needsGitHubToken := strings.HasPrefix(codeintelUploadFlags.repo, "github.com") - needsGitLabToken := strings.HasPrefix(codeintelUploadFlags.repo, "gitlab.com") + var parts []string + parts = append(parts, "Possible causes:\n"+strings.Join(causes, "\n")) + parts = append(parts, "For more details on uploading SCIP indexes, see https://sourcegraph.com/docs/cli/references/code-intel/upload.") - if needsGitHubToken { - if codeintelUploadFlags.gitHubToken != "" { - actionableHints = append(actionableHints, - fmt.Sprintf("The supplied -github-token does not indicate that you have collaborator access to %s.", codeintelUploadFlags.repo), - "Please check the value of the supplied token and its permissions on the code host and try again.", - ) - } else { - actionableHints = append(actionableHints, - fmt.Sprintf("Please retry your request with a -github-token=XXX with collaborator access to %s.", codeintelUploadFlags.repo), - "This token will be used to check with the code host that the uploading user has write access to the target repository.", - ) + return strings.Join(parts, "\n\n") +} + +// sourcegraphAccessTokenHint returns a hint about the Sourcegraph access token +// based on the error type and token state. +func sourcegraphAccessTokenHint(accessToken string, isUnauthorized, isForbidden bool) string { + if isUnauthorized { + if accessToken == "" { + return "No Sourcegraph access token was provided. Set the SRC_ACCESS_TOKEN environment variable to a valid token." } - } else if needsGitLabToken { - if codeintelUploadFlags.gitLabToken != "" { - actionableHints = append(actionableHints, - fmt.Sprintf("The supplied -gitlab-token does not indicate that you have write access to %s.", codeintelUploadFlags.repo), - "Please check the value of the supplied token and its permissions on the code host and try again.", - ) - } else { - actionableHints = append(actionableHints, - fmt.Sprintf("Please retry your request with a -gitlab-token=XXX with write access to %s.", codeintelUploadFlags.repo), - "This token will be used to check with the code host that the uploading user has write access to the target repository.", - ) + if _, parseErr := accesstoken.ParsePersonalAccessToken(accessToken); parseErr != nil { + return "The provided Sourcegraph access token does not match the expected format (sgp_<40 hex chars> or sgp__<40 hex chars>). Was it copied incorrectly or truncated?" } - } else { - actionableHints = append(actionableHints, - "Verification is supported for the following code hosts: github.com, gitlab.com.", - "Please request support for additional code host verification at https://github.com/sourcegraph/sourcegraph/issues/4967.", - ) + return "The Sourcegraph access token may be invalid, expired, or you may be connecting to the wrong Sourcegraph instance." + } + if isForbidden { + return "You may not have sufficient permissions on this Sourcegraph instance." } + return "" +} - return errorWithHint{err: originalError, hint: strings.Join(mergeStringSlices( - []string{"This Sourcegraph instance has enforced auth for SCIP uploads."}, - actionableHints, - []string{"For more details, see https://docs.sourcegraph.com/cli/references/code-intel/upload."}, - ), "\n")} +// codeHostTokenHints returns hints about GitHub or GitLab tokens. +func codeHostTokenHints(isUnauthorized bool) []string { + if codeintelUploadFlags.gitHubToken != "" || strings.HasPrefix(codeintelUploadFlags.repo, "github.com") { + return []string{gitHubTokenHint(isUnauthorized)} + } + if codeintelUploadFlags.gitLabToken != "" || strings.HasPrefix(codeintelUploadFlags.repo, "gitlab.com") { + return []string{gitLabTokenHint(isUnauthorized)} + } + return []string{"Code host verification is supported for github.com and gitlab.com repositories."} } -// emergencyOutput creates a default Output object writing to standard out. -func emergencyOutput() *output.Output { - return output.NewOutput(os.Stdout, output.OutputOpts{}) +// gitHubTokenHint returns a hint about the GitHub token. +// Only called when gitHubToken is set or repo starts with "github.com". +func gitHubTokenHint(isUnauthorized bool) string { + if codeintelUploadFlags.gitHubToken == "" { + return fmt.Sprintf("No -github-token was provided. If this Sourcegraph instance enforces code host authentication, retry with -github-token= for a token with access to %s.", codeintelUploadFlags.repo) + } + if isUnauthorized { + return "The supplied -github-token may be invalid." + } + return "The supplied -github-token may lack the required permissions." } -func mergeStringSlices(ss ...[]string) []string { - var combined []string - for _, s := range ss { - combined = append(combined, s...) +// gitLabTokenHint returns a hint about the GitLab token. +// Only called when gitLabToken is set or repo starts with "gitlab.com". +func gitLabTokenHint(isUnauthorized bool) string { + if codeintelUploadFlags.gitLabToken == "" { + return fmt.Sprintf("No -gitlab-token was provided. If this Sourcegraph instance enforces code host authentication, retry with -gitlab-token= for a token with access to %s.", codeintelUploadFlags.repo) + } + if isUnauthorized { + return "The supplied -gitlab-token may be invalid." } + return "The supplied -gitlab-token may lack the required permissions." +} + +// uploadFailureReason returns the server's response body if available, or a +// generic reason derived from the HTTP status code. +func uploadFailureReason(httpErr *ErrUnexpectedStatusCode) string { + if httpErr.Body != "" { + return httpErr.Body + } + if httpErr.Code == 401 { + return "unauthorized" + } + return "forbidden" +} - return combined +// emergencyOutput creates a default Output object writing to standard out. +func emergencyOutput() *output.Output { + return output.NewOutput(os.Stdout, output.OutputOpts{}) } diff --git a/cmd/src/code_intel_upload_test.go b/cmd/src/code_intel_upload_test.go new file mode 100644 index 0000000000..fd8c390c94 --- /dev/null +++ b/cmd/src/code_intel_upload_test.go @@ -0,0 +1,352 @@ +package main + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +// validSGToken is a well-formed (but not real) Sourcegraph personal access token. +const validSGToken = "sgp_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + +func TestUploadFailureReason(t *testing.T) { + tests := []struct { + name string + err *ErrUnexpectedStatusCode + want string + }{ + {"401 with body", &ErrUnexpectedStatusCode{Code: 401, Body: "Invalid access token."}, "Invalid access token."}, + {"401 without body", &ErrUnexpectedStatusCode{Code: 401}, "unauthorized"}, + {"403 with body", &ErrUnexpectedStatusCode{Code: 403, Body: "no write permission"}, "no write permission"}, + {"403 without body", &ErrUnexpectedStatusCode{Code: 403}, "forbidden"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.want, uploadFailureReason(tt.err)) + }) + } +} + +func TestSourcegraphAccessTokenHint(t *testing.T) { + tests := []struct { + name string + accessToken string + isUnauthorized bool + isForbidden bool + wantContains string + }{ + { + name: "401 no token", + isUnauthorized: true, + wantContains: "No Sourcegraph access token was provided", + }, + { + name: "401 malformed token", + accessToken: "not-a-valid-token", + isUnauthorized: true, + wantContains: "does not match the expected format", + }, + { + name: "401 valid format token", + accessToken: validSGToken, + isUnauthorized: true, + wantContains: "may be invalid, expired", + }, + { + name: "403", + isForbidden: true, + wantContains: "may not have sufficient permissions", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := sourcegraphAccessTokenHint(tt.accessToken, tt.isUnauthorized, tt.isForbidden) + assert.Contains(t, got, tt.wantContains) + }) + } +} + +func TestCodeHostTokenHints(t *testing.T) { + tests := []struct { + name string + repo string + gitHubToken string + gitLabToken string + isUnauthorized bool + wantContains []string + }{ + { + name: "github repo no token 401", + repo: "github.com/org/repo", + isUnauthorized: true, + wantContains: []string{"No -github-token was provided", "github.com/org/repo"}, + }, + { + name: "github repo no token 403", + repo: "github.com/org/repo", + isUnauthorized: false, + wantContains: []string{"No -github-token was provided"}, + }, + { + name: "github repo with token 401", + repo: "github.com/org/repo", + gitHubToken: "ghp_xxx", + isUnauthorized: true, + wantContains: []string{"-github-token may be invalid"}, + }, + { + name: "github repo with token 403", + repo: "github.com/org/repo", + gitHubToken: "ghp_xxx", + isUnauthorized: false, + wantContains: []string{"-github-token may lack the required permissions"}, + }, + { + name: "gitlab repo no token 401", + repo: "gitlab.com/org/repo", + isUnauthorized: true, + wantContains: []string{"No -gitlab-token was provided", "gitlab.com/org/repo"}, + }, + { + name: "gitlab repo no token 403", + repo: "gitlab.com/org/repo", + isUnauthorized: false, + wantContains: []string{"No -gitlab-token was provided"}, + }, + { + name: "gitlab repo with token 401", + repo: "gitlab.com/org/repo", + gitLabToken: "glpat-xxx", + isUnauthorized: true, + wantContains: []string{"-gitlab-token may be invalid"}, + }, + { + name: "gitlab repo with token 403", + repo: "gitlab.com/org/repo", + gitLabToken: "glpat-xxx", + isUnauthorized: false, + wantContains: []string{"-gitlab-token may lack the required permissions"}, + }, + { + name: "other repo no tokens", + repo: "bitbucket.org/org/repo", + isUnauthorized: true, + wantContains: []string{"Code host verification is supported for github.com and gitlab.com"}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + saved := codeintelUploadFlags + defer func() { codeintelUploadFlags = saved }() + + codeintelUploadFlags.repo = tt.repo + codeintelUploadFlags.gitHubToken = tt.gitHubToken + codeintelUploadFlags.gitLabToken = tt.gitLabToken + + hints := codeHostTokenHints(tt.isUnauthorized) + joined := strings.Join(hints, "\n") + for _, s := range tt.wantContains { + assert.Contains(t, joined, s) + } + }) + } +} + +func TestUploadHints(t *testing.T) { + tests := []struct { + name string + accessToken string + repo string + gitHubToken string + gitLabToken string + isUnauthorized bool + isForbidden bool + wantContains []string + }{ + { + name: "401 no SG token github repo", + repo: "github.com/org/repo", + isUnauthorized: true, + wantContains: []string{ + "Possible causes:", + "- No Sourcegraph access token was provided", + "- No -github-token was provided", + "sourcegraph.com/docs/cli/references/code-intel/upload", + }, + }, + { + name: "401 valid SG token github token supplied", + accessToken: validSGToken, + repo: "github.com/org/repo", + gitHubToken: "ghp_xxx", + isUnauthorized: true, + wantContains: []string{ + "Possible causes:", + "- The Sourcegraph access token may be invalid, expired", + "- The supplied -github-token may be invalid", + "sourcegraph.com/docs/cli/references/code-intel/upload", + }, + }, + { + name: "403 gitlab token supplied", + accessToken: validSGToken, + repo: "gitlab.com/org/repo", + gitLabToken: "glpat-xxx", + isForbidden: true, + wantContains: []string{ + "Possible causes:", + "- You may not have sufficient permissions", + "- The supplied -gitlab-token may lack the required permissions", + "sourcegraph.com/docs/cli/references/code-intel/upload", + }, + }, + { + name: "401 bitbucket repo catch-all", + accessToken: validSGToken, + repo: "bitbucket.org/org/repo", + isUnauthorized: true, + wantContains: []string{ + "Possible causes:", + "- The Sourcegraph access token may be invalid, expired", + "- Code host verification is supported for github.com and gitlab.com", + "sourcegraph.com/docs/cli/references/code-intel/upload", + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + saved := codeintelUploadFlags + defer func() { codeintelUploadFlags = saved }() + + codeintelUploadFlags.repo = tt.repo + codeintelUploadFlags.gitHubToken = tt.gitHubToken + codeintelUploadFlags.gitLabToken = tt.gitLabToken + + got := uploadHints(tt.accessToken, tt.isUnauthorized, tt.isForbidden) + for _, s := range tt.wantContains { + assert.Contains(t, got, s) + } + }) + } +} + +func TestHandleUploadError(t *testing.T) { + tests := []struct { + name string + accessToken string + repo string + gitHubToken string + err error + wantContains []string + wantNil bool + }{ + { + name: "401 with server body", + accessToken: validSGToken, + repo: "github.com/org/repo", + err: &ErrUnexpectedStatusCode{Code: 401, Body: "Invalid access token."}, + wantContains: []string{ + "upload failed: Invalid access token.", + "Possible causes:", + "- The Sourcegraph access token may be invalid, expired", + }, + }, + { + name: "401 without body", + accessToken: "", + repo: "github.com/org/repo", + err: &ErrUnexpectedStatusCode{Code: 401}, + wantContains: []string{ + "upload failed: unauthorized", + "Possible causes:", + "- No Sourcegraph access token was provided", + }, + }, + { + name: "403 with server body", + accessToken: validSGToken, + repo: "github.com/org/repo", + gitHubToken: "ghp_xxx", + err: &ErrUnexpectedStatusCode{Code: 403, Body: "no write permission"}, + wantContains: []string{ + "upload failed: no write permission", + "Possible causes:", + "- You may not have sufficient permissions", + }, + }, + { + name: "500 passthrough", + accessToken: validSGToken, + repo: "github.com/org/repo", + err: &ErrUnexpectedStatusCode{Code: 500, Body: "internal error"}, + wantContains: []string{"unexpected status code: 500"}, + }, + { + name: "non-http error passthrough", + accessToken: validSGToken, + repo: "github.com/org/repo", + err: errors.New("connection refused"), + wantContains: []string{"connection refused"}, + }, + { + name: "combined 502 + 403 from retries", + accessToken: validSGToken, + repo: "github.com/org/repo", + gitHubToken: "ghp_xxx", + err: errors.CombineErrors( + &ErrUnexpectedStatusCode{Code: 502}, + &ErrUnexpectedStatusCode{Code: 403, Body: "no write permission"}, + ), + wantContains: []string{ + "upload failed: no write permission", + "Possible causes:", + "- You may not have sufficient permissions", + }, + }, + { + name: "combined 502 + 401 from retries", + accessToken: validSGToken, + repo: "github.com/org/repo", + err: errors.CombineErrors( + &ErrUnexpectedStatusCode{Code: 502}, + &ErrUnexpectedStatusCode{Code: 401, Body: "Invalid access token."}, + ), + wantContains: []string{ + "upload failed: Invalid access token.", + "Possible causes:", + "- The Sourcegraph access token may be invalid, expired", + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + saved := codeintelUploadFlags + defer func() { codeintelUploadFlags = saved }() + + codeintelUploadFlags.repo = tt.repo + codeintelUploadFlags.gitHubToken = tt.gitHubToken + codeintelUploadFlags.ignoreUploadFailures = false + + got := handleUploadError(tt.accessToken, tt.err) + require.NotNil(t, got) + for _, s := range tt.wantContains { + assert.Contains(t, got.Error(), s) + } + }) + } +} + +func TestHandleUploadErrorIgnoreFailures(t *testing.T) { + saved := codeintelUploadFlags + defer func() { codeintelUploadFlags = saved }() + + codeintelUploadFlags.repo = "github.com/org/repo" + codeintelUploadFlags.ignoreUploadFailures = true + + got := handleUploadError(validSGToken, &ErrUnexpectedStatusCode{Code: 401, Body: "bad token"}) + assert.Nil(t, got) +} diff --git a/cmd/src/code_intel_upload_vendored.go b/cmd/src/code_intel_upload_vendored.go index b5e4897af0..a1a98fe86a 100644 --- a/cmd/src/code_intel_upload_vendored.go +++ b/cmd/src/code_intel_upload_vendored.go @@ -339,8 +339,20 @@ type uploadRequestOptions struct { Done bool // Whether the request is a multipart finalize } -// ErrUnauthorized occurs when the upload endpoint returns a 401 response. -var ErrUnauthorized = errors.New("unauthorized upload") +// ErrUnexpectedStatusCode is returned for HTTP error responses from the upload +// endpoint. It carries the status code and response body so callers can inspect +// them without parsing the error string. +type ErrUnexpectedStatusCode struct { + Code int + Body string +} + +func (e *ErrUnexpectedStatusCode) Error() string { + if e.Body != "" { + return fmt.Sprintf("unexpected status code: %d (%s)", e.Code, e.Body) + } + return fmt.Sprintf("unexpected status code: %d", e.Code) +} // performUploadRequest performs an HTTP POST to the upload endpoint. The query string of the request // is constructed from the given request options and the body of the request is the unmodified reader. @@ -419,17 +431,13 @@ func performRequest(ctx context.Context, req *http.Request, httpClient upload.Cl // returns a boolean flag indicating if the function can be retried on failure (error-dependent). func decodeUploadPayload(resp *http.Response, body []byte, target *int) (bool, error) { if resp.StatusCode >= 300 { - if resp.StatusCode == http.StatusUnauthorized { - return false, ErrUnauthorized - } - - suffix := "" - if !bytes.HasPrefix(bytes.TrimSpace(body), []byte{'<'}) { - suffix = fmt.Sprintf(" (%s)", bytes.TrimSpace(body)) + detail := "" + if trimmed := bytes.TrimSpace(body); len(trimmed) > 0 && trimmed[0] != '<' { + detail = string(trimmed) } // Do not retry client errors - return resp.StatusCode >= 500, errors.Errorf("unexpected status code: %d%s", resp.StatusCode, suffix) + return resp.StatusCode >= 500, &ErrUnexpectedStatusCode{Code: resp.StatusCode, Body: detail} } if target == nil { From 794c96faf0d1fb55880b3b630f6e2424027d316d Mon Sep 17 00:00:00 2001 From: Keegan Carruthers-Smith Date: Mon, 2 Mar 2026 11:19:46 +0200 Subject: [PATCH 540/647] chore: remove amp workspace settings (#1263) It was outdated, can just stick with default settings. Additionally removed cody codebase setting from vscode config. --- .amp/settings.json | 19 ------------------- .vscode/settings.json | 3 +-- 2 files changed, 1 insertion(+), 21 deletions(-) delete mode 100644 .amp/settings.json diff --git a/.amp/settings.json b/.amp/settings.json deleted file mode 100644 index 05334a3fb7..0000000000 --- a/.amp/settings.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "amp.experimental.fuzzySearch.enabled": true, - "amp.experimental.planMode": true, - "amp.experimental.tools": ["codemod"], - "amp.mcpServers": { - "s2": { - "command": "npx", - "args": [ - "mcp-remote", - "https://sourcegraph.sourcegraph.com/.api/mcp/v1", - "3334", - "--static-oauth-client-info", - "{\"client_id\":\"sgo_cid_019aa0a8-a62d-74e6-92bd-30fe0ff1d4d4\"}", - "--static-oauth-client-metadata", - "{\"scope\":\"user:all\"}" - ] - } - } -} diff --git a/.vscode/settings.json b/.vscode/settings.json index 5cb6acc364..8b2f950a82 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -8,6 +8,5 @@ "go.useLanguageServer": true, "gopls": { "local": "github.com/sourcegraph/src-cli" - }, - "cody.codebase": "github.com/sourcegraph/src-cli", + } } From e9c26fba337a3af0b23af05f1b581dc096abd359 Mon Sep 17 00:00:00 2001 From: Keegan Carruthers-Smith Date: Mon, 2 Mar 2026 13:37:25 +0200 Subject: [PATCH 541/647] feat/dev: introduce integration smoke tests (#1265) This is something lightweight you can run to ensure no major breakages to "src" when speaking to a sourcegraph instance. --- DEVELOPMENT.md | 10 ++++++++++ dev/smoke.sh | 29 +++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) create mode 100755 dev/smoke.sh diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index 825427c0f5..18daf7ba8e 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -52,6 +52,16 @@ Or just a single package with: go test ./internal/batches/workspace ``` +### Manual smoke test script + +For quick end-to-end CLI sanity checks against a live Sourcegraph instance, run: + +```sh +./dev/smoke.sh +``` + +This script intentionally uses your currently exported `SRC_*` environment variables, is not hooked up to CI, and is meant for manual regression checks (for example, to catch issues like `src users list` failing unexpectedly). + We adhere to the [general Sourcegraph principles for testing](https://docs.sourcegraph.com/dev/background-information/testing_principles), as well as [the Go specific directions](https://docs.sourcegraph.com/dev/background-information/languages/testing_go_code), at least to the extent they apply to a standalone tool like `src`. ## Releasing diff --git a/dev/smoke.sh b/dev/smoke.sh new file mode 100755 index 0000000000..0448fe9619 --- /dev/null +++ b/dev/smoke.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash + +set -euo pipefail + +unset CDPATH +cd "$(dirname "${BASH_SOURCE[0]}")/.." + +SRC_CMD=(go run ./cmd/src) + +run() { + echo + echo "+ $*" + "$@" +} + +# This script intentionally relies on the currently exported SRC_* envvars. + +echo "Running src-cli smoke checks with current SRC_* environment" + +run "${SRC_CMD[@]}" version +run "${SRC_CMD[@]}" api -query 'query { site { buildVersion } }' +run "${SRC_CMD[@]}" api -query 'query { currentUser { username } }' +run "${SRC_CMD[@]}" users list -first=1 -f '{{.Username}}' +run "${SRC_CMD[@]}" orgs list -first=1 -f '{{.Name}}' +run "${SRC_CMD[@]}" repos list -first=1 -f '{{.Name}}' +run "${SRC_CMD[@]}" search -less=false -json 'type:repo count:1' + +echo +echo "Smoke checks completed successfully." From fcfad36b95c0dbc5a49f91be36d743dd70a6b0d2 Mon Sep 17 00:00:00 2001 From: Keegan Carruthers-Smith Date: Mon, 2 Mar 2026 13:51:19 +0200 Subject: [PATCH 542/647] fix/users: remove query for usageStatistics (#1264) This field was deprecated in March last year and was removed November last year. Before this change any user subcommand just failed. Will be adding some integration smoke tests to catch these sort of issues. Additionally found one place we didn't set Content-Type which Sourcegraph also recently started enforcing. --- cmd/src/users.go | 14 ++------------ internal/users/admin.go | 1 + 2 files changed, 3 insertions(+), 12 deletions(-) diff --git a/cmd/src/users.go b/cmd/src/users.go index d02304e005..3b915d75e1 100644 --- a/cmd/src/users.go +++ b/cmd/src/users.go @@ -60,10 +60,6 @@ fragment UserFields on User { email verified } - usageStatistics { - lastActiveTime - lastActiveCodeHostIntegrationTime - } url } ` @@ -76,9 +72,8 @@ type User struct { Organizations struct { Nodes []Org } - Emails []UserEmail - UsageStatistics UserUsageStatistics - URL string + Emails []UserEmail + URL string } type UserEmail struct { @@ -86,11 +81,6 @@ type UserEmail struct { Verified bool } -type UserUsageStatistics struct { - LastActiveTime string - LastActiveCodeHostIntegrationTime string -} - type SiteUser struct { ID string Username string diff --git a/internal/users/admin.go b/internal/users/admin.go index dad8584989..03a8696bc5 100644 --- a/internal/users/admin.go +++ b/internal/users/admin.go @@ -252,6 +252,7 @@ func (c *Client) GraphQL(token, query string, variables map[string]any, target a if err != nil { return err } + req.Header.Set("Content-Type", "application/json") if token != "" { req.Header.Set("Authorization", fmt.Sprintf("token %s", token)) } else { From 0bc535e9f5d967babdd2e7db1404fb34f9344ef6 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Mon, 9 Mar 2026 12:12:43 +0200 Subject: [PATCH 543/647] feat(oauth): use oauth flow to authenticate with predefined src-cli OAuth client (#1223) * removed unused func * add refresh token to device response unmarshall * make NewClient take ClientID as param * add oauth flow and use oauth token when SRC_ACCESS_TOKEN is empty * feat(oauth): Add refresh to oauthdevice.Client (#1227) * add refresh to oauthdevice.Client * oauthdevice: add RefreshToken field and Refresh method * feat(oauth): Use keyring to store oauth token (#1228) * add refresh to oauthdevice.Client * add OAuth Transport and use it if no access token * secrets: switch to zalando/go-keyring and add context support * secrets: scope keyring by endpoint --- cmd/src/login.go | 132 +++++- cmd/src/login_test.go | 17 +- cmd/src/main.go | 15 +- go.mod | 4 + go.sum | 10 + internal/api/api.go | 52 ++- internal/oauth/flow.go | 429 +++++++++++++++++++ internal/oauth/flow_test.go | 573 ++++++++++++++++++++++++++ internal/oauth/http_transport.go | 87 ++++ internal/oauth/http_transport_test.go | 172 ++++++++ internal/secrets/keyring.go | 77 ++++ internal/secrets/keyring_test.go | 58 +++ 12 files changed, 1600 insertions(+), 26 deletions(-) create mode 100644 internal/oauth/flow.go create mode 100644 internal/oauth/flow_test.go create mode 100644 internal/oauth/http_transport.go create mode 100644 internal/oauth/http_transport_test.go create mode 100644 internal/secrets/keyring.go create mode 100644 internal/secrets/keyring_test.go diff --git a/cmd/src/login.go b/cmd/src/login.go index ab5a097c71..5a73ef4cc8 100644 --- a/cmd/src/login.go +++ b/cmd/src/login.go @@ -6,10 +6,14 @@ import ( "fmt" "io" "os" + "os/exec" + "runtime" "strings" + "time" "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/cmderrors" + "github.com/sourcegraph/src-cli/internal/oauth" ) func init() { @@ -17,7 +21,7 @@ func init() { Usage: - src login SOURCEGRAPH_URL + src login [flags] SOURCEGRAPH_URL Examples: @@ -28,6 +32,15 @@ Examples: Authenticate to Sourcegraph.com: $ src login https://sourcegraph.com + + Use OAuth device flow to authenticate: + + $ src login --oauth https://sourcegraph.com + + + Override the default client id used during device flow when authenticating: + + $ src login --oauth https://sourcegraph.com ` flagSet := flag.NewFlagSet("login", flag.ExitOnError) @@ -38,6 +51,7 @@ Examples: var ( apiFlags = api.NewFlags(flagSet) + useOAuth = flagSet.Bool("oauth", false, "Use OAuth device flow to obtain an access token interactively") ) handler := func(args []string) error { @@ -54,7 +68,15 @@ Examples: client := cfg.apiClient(apiFlags, io.Discard) - return loginCmd(context.Background(), cfg, client, endpoint, os.Stdout) + return loginCmd(context.Background(), loginParams{ + cfg: cfg, + client: client, + endpoint: endpoint, + out: os.Stdout, + useOAuth: *useOAuth, + apiFlags: apiFlags, + deviceFlowClient: oauth.NewClient(oauth.DefaultClientID), + }) } commands = append(commands, &command{ @@ -64,8 +86,21 @@ Examples: }) } -func loginCmd(ctx context.Context, cfg *config, client api.Client, endpointArg string, out io.Writer) error { - endpointArg = cleanEndpoint(endpointArg) +type loginParams struct { + cfg *config + client api.Client + endpoint string + out io.Writer + useOAuth bool + apiFlags *api.Flags + deviceFlowClient oauth.Client +} + +func loginCmd(ctx context.Context, p loginParams) error { + endpointArg := cleanEndpoint(p.endpoint) + cfg := p.cfg + client := p.client + out := p.out printProblem := func(problem string) { fmt.Fprintf(out, "❌ Problem: %s\n", problem) @@ -77,7 +112,9 @@ func loginCmd(ctx context.Context, cfg *config, client api.Client, endpointArg s export SRC_ACCESS_TOKEN=(your access token) To verify that it's working, run the login command again. -`, endpointArg, endpointArg) + + Alternatively, you can try logging in using OAuth by running: src login --oauth %s +`, endpointArg, endpointArg, endpointArg) if cfg.ConfigFilePath != "" { fmt.Fprintln(out) @@ -86,7 +123,7 @@ func loginCmd(ctx context.Context, cfg *config, client api.Client, endpointArg s noToken := cfg.AccessToken == "" endpointConflict := endpointArg != cfg.Endpoint - if noToken || endpointConflict { + if !p.useOAuth && (noToken || endpointConflict) { fmt.Fprintln(out) switch { case noToken: @@ -98,6 +135,30 @@ func loginCmd(ctx context.Context, cfg *config, client api.Client, endpointArg s return cmderrors.ExitCode1 } + if p.useOAuth { + token, err := runOAuthDeviceFlow(ctx, endpointArg, out, p.deviceFlowClient) + if err != nil { + printProblem(fmt.Sprintf("OAuth Device flow authentication failed: %s", err)) + fmt.Fprintln(out, createAccessTokenMessage) + return cmderrors.ExitCode1 + } + + if err := oauth.StoreToken(ctx, token); err != nil { + fmt.Fprintln(out) + fmt.Fprintf(out, "⚠️ Warning: Failed to store token in keyring store: %q. Continuing with this session only.\n", err) + } + + client = api.NewClient(api.ClientOpts{ + Endpoint: cfg.Endpoint, + AdditionalHeaders: cfg.AdditionalHeaders, + Flags: p.apiFlags, + Out: out, + ProxyURL: cfg.ProxyURL, + ProxyPath: cfg.ProxyPath, + OAuthToken: token, + }) + } + // See if the user is already authenticated. query := `query CurrentUser { currentUser { username } }` var result struct { @@ -122,6 +183,65 @@ func loginCmd(ctx context.Context, cfg *config, client api.Client, endpointArg s } fmt.Fprintln(out) fmt.Fprintf(out, "✔️ Authenticated as %s on %s\n", result.CurrentUser.Username, endpointArg) + + if p.useOAuth { + fmt.Fprintln(out) + fmt.Fprintf(out, "Authenticated with OAuth credentials") + } + fmt.Fprintln(out) return nil } + +func runOAuthDeviceFlow(ctx context.Context, endpoint string, out io.Writer, client oauth.Client) (*oauth.Token, error) { + authResp, err := client.Start(ctx, endpoint, nil) + if err != nil { + return nil, err + } + + authURL := authResp.VerificationURIComplete + msg := fmt.Sprintf("If your browser did not open automatically, visit %s.", authURL) + if authURL == "" { + authURL = authResp.VerificationURI + msg = fmt.Sprintf("If your browser did not open automatically, visit %s and enter the user code %s", authURL, authResp.DeviceCode) + } + _ = openInBrowser(authURL) + fmt.Fprintln(out) + fmt.Fprint(out, msg) + + fmt.Fprintln(out) + fmt.Fprint(out, "Waiting for authorization...") + defer fmt.Fprintf(out, "DONE\n\n") + + interval := time.Duration(authResp.Interval) * time.Second + if interval <= 0 { + interval = 5 * time.Second + } + + resp, err := client.Poll(ctx, endpoint, authResp.DeviceCode, interval, authResp.ExpiresIn) + if err != nil { + return nil, err + } + + token := resp.Token(endpoint) + token.ClientID = client.ClientID() + return token, nil +} + +func openInBrowser(url string) error { + if url == "" { + return nil + } + + var cmd *exec.Cmd + switch runtime.GOOS { + case "darwin": + cmd = exec.Command("open", url) + case "windows": + // "start" is a cmd.exe built-in; the empty string is the window title. + cmd = exec.Command("cmd", "/c", "start", "", url) + default: + cmd = exec.Command("xdg-open", url) + } + return cmd.Run() +} diff --git a/cmd/src/login_test.go b/cmd/src/login_test.go index 37fbf7a703..ab7a15056a 100644 --- a/cmd/src/login_test.go +++ b/cmd/src/login_test.go @@ -11,6 +11,7 @@ import ( "testing" "github.com/sourcegraph/src-cli/internal/cmderrors" + "github.com/sourcegraph/src-cli/internal/oauth" ) func TestLogin(t *testing.T) { @@ -18,7 +19,13 @@ func TestLogin(t *testing.T) { t.Helper() var out bytes.Buffer - err = loginCmd(context.Background(), cfg, cfg.apiClient(nil, io.Discard), endpointArg, &out) + err = loginCmd(context.Background(), loginParams{ + cfg: cfg, + client: cfg.apiClient(nil, io.Discard), + endpoint: endpointArg, + out: &out, + deviceFlowClient: oauth.NewClient(oauth.DefaultClientID), + }) return strings.TrimSpace(out.String()), err } @@ -27,7 +34,7 @@ func TestLogin(t *testing.T) { if err != cmderrors.ExitCode1 { t.Fatal(err) } - wantOut := "❌ Problem: No access token is configured.\n\n🛠 To fix: Create an access token by going to https://sourcegraph.example.com/user/settings/tokens, then set the following environment variables in your terminal:\n\n export SRC_ENDPOINT=https://sourcegraph.example.com\n export SRC_ACCESS_TOKEN=(your access token)\n\n To verify that it's working, run the login command again." + wantOut := "❌ Problem: No access token is configured.\n\n🛠 To fix: Create an access token by going to https://sourcegraph.example.com/user/settings/tokens, then set the following environment variables in your terminal:\n\n export SRC_ENDPOINT=https://sourcegraph.example.com\n export SRC_ACCESS_TOKEN=(your access token)\n\n To verify that it's working, run the login command again.\n\n Alternatively, you can try logging in using OAuth by running: src login --oauth https://sourcegraph.example.com" if out != wantOut { t.Errorf("got output %q, want %q", out, wantOut) } @@ -38,7 +45,7 @@ func TestLogin(t *testing.T) { if err != cmderrors.ExitCode1 { t.Fatal(err) } - wantOut := "❌ Problem: No access token is configured.\n\n🛠 To fix: Create an access token by going to https://sourcegraph.example.com/user/settings/tokens, then set the following environment variables in your terminal:\n\n export SRC_ENDPOINT=https://sourcegraph.example.com\n export SRC_ACCESS_TOKEN=(your access token)\n\n To verify that it's working, run the login command again." + wantOut := "❌ Problem: No access token is configured.\n\n🛠 To fix: Create an access token by going to https://sourcegraph.example.com/user/settings/tokens, then set the following environment variables in your terminal:\n\n export SRC_ENDPOINT=https://sourcegraph.example.com\n export SRC_ACCESS_TOKEN=(your access token)\n\n To verify that it's working, run the login command again.\n\n Alternatively, you can try logging in using OAuth by running: src login --oauth https://sourcegraph.example.com" if out != wantOut { t.Errorf("got output %q, want %q", out, wantOut) } @@ -49,7 +56,7 @@ func TestLogin(t *testing.T) { if err != cmderrors.ExitCode1 { t.Fatal(err) } - wantOut := "⚠️ Warning: Configuring src with a JSON file is deprecated. Please migrate to using the env vars SRC_ENDPOINT, SRC_ACCESS_TOKEN, and SRC_PROXY instead, and then remove f. See https://github.com/sourcegraph/src-cli#readme for more information.\n\n❌ Problem: No access token is configured.\n\n🛠 To fix: Create an access token by going to https://example.com/user/settings/tokens, then set the following environment variables in your terminal:\n\n export SRC_ENDPOINT=https://example.com\n export SRC_ACCESS_TOKEN=(your access token)\n\n To verify that it's working, run the login command again." + wantOut := "⚠️ Warning: Configuring src with a JSON file is deprecated. Please migrate to using the env vars SRC_ENDPOINT, SRC_ACCESS_TOKEN, and SRC_PROXY instead, and then remove f. See https://github.com/sourcegraph/src-cli#readme for more information.\n\n❌ Problem: No access token is configured.\n\n🛠 To fix: Create an access token by going to https://example.com/user/settings/tokens, then set the following environment variables in your terminal:\n\n export SRC_ENDPOINT=https://example.com\n export SRC_ACCESS_TOKEN=(your access token)\n\n To verify that it's working, run the login command again.\n\n Alternatively, you can try logging in using OAuth by running: src login --oauth https://example.com" if out != wantOut { t.Errorf("got output %q, want %q", out, wantOut) } @@ -67,7 +74,7 @@ func TestLogin(t *testing.T) { if err != cmderrors.ExitCode1 { t.Fatal(err) } - wantOut := "❌ Problem: Invalid access token.\n\n🛠 To fix: Create an access token by going to $ENDPOINT/user/settings/tokens, then set the following environment variables in your terminal:\n\n export SRC_ENDPOINT=$ENDPOINT\n export SRC_ACCESS_TOKEN=(your access token)\n\n To verify that it's working, run the login command again.\n\n (If you need to supply custom HTTP request headers, see information about SRC_HEADER_* and SRC_HEADERS env vars at https://github.com/sourcegraph/src-cli/blob/main/AUTH_PROXY.md)" + wantOut := "❌ Problem: Invalid access token.\n\n🛠 To fix: Create an access token by going to $ENDPOINT/user/settings/tokens, then set the following environment variables in your terminal:\n\n export SRC_ENDPOINT=$ENDPOINT\n export SRC_ACCESS_TOKEN=(your access token)\n\n To verify that it's working, run the login command again.\n\n Alternatively, you can try logging in using OAuth by running: src login --oauth $ENDPOINT\n\n (If you need to supply custom HTTP request headers, see information about SRC_HEADER_* and SRC_HEADERS env vars at https://github.com/sourcegraph/src-cli/blob/main/AUTH_PROXY.md)" wantOut = strings.ReplaceAll(wantOut, "$ENDPOINT", endpoint) if out != wantOut { t.Errorf("got output %q, want %q", out, wantOut) diff --git a/cmd/src/main.go b/cmd/src/main.go index edfb1073d7..41e5c55cd0 100644 --- a/cmd/src/main.go +++ b/cmd/src/main.go @@ -1,6 +1,7 @@ package main import ( + "context" "encoding/json" "flag" "io" @@ -15,6 +16,7 @@ import ( "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/oauth" ) const usageText = `src is a tool that provides access to Sourcegraph instances. @@ -122,7 +124,7 @@ type config struct { // apiClient returns an api.Client built from the configuration. func (c *config) apiClient(flags *api.Flags, out io.Writer) api.Client { - return api.NewClient(api.ClientOpts{ + opts := api.ClientOpts{ Endpoint: c.Endpoint, AccessToken: c.AccessToken, AdditionalHeaders: c.AdditionalHeaders, @@ -130,7 +132,16 @@ func (c *config) apiClient(flags *api.Flags, out io.Writer) api.Client { Out: out, ProxyURL: c.ProxyURL, ProxyPath: c.ProxyPath, - }) + } + + // Only use OAuth if we do not have SRC_ACCESS_TOKEN set + if c.AccessToken == "" { + if t, err := oauth.LoadToken(context.Background(), c.Endpoint); err == nil { + opts.OAuthToken = t + } + } + + return api.NewClient(opts) } // readConfig reads the config file from the given path. diff --git a/go.mod b/go.mod index 3c9e3eb338..0a04972e5a 100644 --- a/go.mod +++ b/go.mod @@ -30,6 +30,7 @@ require ( github.com/sourcegraph/sourcegraph/lib v0.0.0-20240709083501-1af563b61442 github.com/stretchr/testify v1.11.1 github.com/tliron/glsp v0.2.2 + github.com/zalando/go-keyring v0.2.6 golang.org/x/sync v0.18.0 google.golang.org/api v0.256.0 google.golang.org/protobuf v1.36.10 @@ -41,6 +42,7 @@ require ( ) require ( + al.essio.dev/pkg/shellescape v1.5.1 // indirect cel.dev/expr v0.24.0 // indirect cloud.google.com/go/auth v0.17.0 // indirect cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect @@ -64,6 +66,7 @@ require ( github.com/clipperhouse/uax29/v2 v2.2.0 // indirect github.com/cncf/xds/go v0.0.0-20250501225837-2ac532fd4443 // indirect github.com/containerd/stargz-snapshotter/estargz v0.14.3 // indirect + github.com/danieljoos/wincred v1.2.2 // indirect github.com/distribution/reference v0.6.0 // indirect github.com/docker/cli v24.0.4+incompatible // indirect github.com/docker/distribution v2.8.2+incompatible // indirect @@ -78,6 +81,7 @@ require ( github.com/go-chi/chi/v5 v5.2.2 // indirect github.com/go-jose/go-jose/v4 v4.1.2 // indirect github.com/go-logr/stdr v1.2.2 // indirect + github.com/godbus/dbus/v5 v5.1.0 // indirect github.com/gofrs/uuid/v5 v5.0.0 // indirect github.com/google/gnostic-models v0.6.9 // indirect github.com/google/go-containerregistry v0.19.1 // indirect diff --git a/go.sum b/go.sum index f47d1d10c9..6cbdc71412 100644 --- a/go.sum +++ b/go.sum @@ -1,3 +1,5 @@ +al.essio.dev/pkg/shellescape v1.5.1 h1:86HrALUujYS/h+GtqoB26SBEdkWfmMI6FubjXlsXyho= +al.essio.dev/pkg/shellescape v1.5.1/go.mod h1:6sIqp7X2P6mThCQ7twERpZTuigpr6KbZWtls1U8I890= cel.dev/expr v0.24.0 h1:56OvJKSH3hDGL0ml5uSxZmz3/3Pq4tJ+fb1unVLAFcY= cel.dev/expr v0.24.0/go.mod h1:hLPLo1W4QUmuYdA72RBX06QTs6MXw941piREPl3Yfiw= cloud.google.com/go v0.120.0 h1:wc6bgG9DHyKqF5/vQvX1CiZrtHnxJjBlKUyF9nP6meA= @@ -139,6 +141,8 @@ github.com/creack/goselect v0.1.2/go.mod h1:a/NhLweNvqIYMuxcMOuWY516Cimucms3DglD github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s= github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE= +github.com/danieljoos/wincred v1.2.2 h1:774zMFJrqaeYCK2W57BgAem/MLi6mtSE47MB6BOJ0i0= +github.com/danieljoos/wincred v1.2.2/go.mod h1:w7w4Utbrz8lqeMbDAK0lkNJUv5sAOkFi7nd/ogr0Uh8= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= @@ -212,6 +216,8 @@ github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1v github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y= github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8= +github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk= +github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/gofrs/flock v0.8.1 h1:+gYjHKf32LDeiEEFhQaotPbLuUXjY5ZqxKgXy7n59aw= github.com/gofrs/flock v0.8.1/go.mod h1:F1TvTiK9OcQqauNUHlbJvyl9Qa1QvF/gOUDKA14jxHU= github.com/gofrs/uuid/v5 v5.0.0 h1:p544++a97kEL+svbcFbCQVM9KFu0Yo25UoISXGNNH9M= @@ -243,6 +249,8 @@ github.com/google/pprof v0.0.0-20241029153458-d1b30febd7db h1:097atOisP2aRj7vFgY github.com/google/pprof v0.0.0-20241029153458-d1b30febd7db/go.mod h1:vavhavw2zAxS5dIdcRluK6cSGGPlZynqzFM8NdvU144= github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0= github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM= +github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaUGG7oYTSPP8MxqL4YI3kZKwcP4= +github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/googleapis/enterprise-certificate-proxy v0.3.7 h1:zrn2Ee/nWmHulBx5sAVrGgAa0f2/R35S4DJwfFaUPFQ= @@ -495,6 +503,8 @@ github.com/yuin/goldmark v1.7.8 h1:iERMLn0/QJeHFhxSt3p6PeN9mGnvIKSpG9YYorDMnic= github.com/yuin/goldmark v1.7.8/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E= github.com/yuin/goldmark-emoji v1.0.5 h1:EMVWyCGPlXJfUXBXpuMu+ii3TIaxbVBnEX9uaDC4cIk= github.com/yuin/goldmark-emoji v1.0.5/go.mod h1:tTkZEbwu5wkPmgTcitqddVxY9osFZiavD+r4AzQrh1U= +github.com/zalando/go-keyring v0.2.6 h1:r7Yc3+H+Ux0+M72zacZoItR3UDxeWfKTcabvkI8ua9s= +github.com/zalando/go-keyring v0.2.6/go.mod h1:2TCrxYrbUNYfNS/Kgy/LSrkSQzZ5UPVH85RwfczwvcI= github.com/zeebo/errs v1.4.0 h1:XNdoD/RRMKP7HD0UhJnIzUy74ISdGGxURlYG8HSWSfM= github.com/zeebo/errs v1.4.0/go.mod h1:sgbWHsvVuTPHcqJJGQ1WhI5KbWlHYz+2+2C/LSEtCw4= go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA= diff --git a/internal/api/api.go b/internal/api/api.go index 5f750c1d4a..ef9f822a7a 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -18,6 +18,7 @@ import ( "github.com/kballard/go-shellquote" "github.com/mattn/go-isatty" + "github.com/sourcegraph/src-cli/internal/oauth" "github.com/sourcegraph/src-cli/internal/version" ) @@ -85,21 +86,35 @@ type ClientOpts struct { ProxyURL *url.URL ProxyPath string + + OAuthToken *oauth.Token } -func buildTransport(opts ClientOpts, flags *Flags) *http.Transport { - transport := http.DefaultTransport.(*http.Transport).Clone() +func buildTransport(opts ClientOpts, flags *Flags) http.RoundTripper { + var transport http.RoundTripper + { + tp := http.DefaultTransport.(*http.Transport).Clone() - if flags.insecureSkipVerify != nil && *flags.insecureSkipVerify { - transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} - } + if flags.insecureSkipVerify != nil && *flags.insecureSkipVerify { + tp.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} + } - if transport.TLSClientConfig == nil { - transport.TLSClientConfig = &tls.Config{} + if tp.TLSClientConfig == nil { + tp.TLSClientConfig = &tls.Config{} + } + + if opts.ProxyURL != nil || opts.ProxyPath != "" { + tp = withProxyTransport(tp, opts.ProxyURL, opts.ProxyPath) + } + + transport = tp } - if opts.ProxyURL != nil || opts.ProxyPath != "" { - transport = withProxyTransport(transport, opts.ProxyURL, opts.ProxyPath) + if opts.AccessToken == "" && opts.OAuthToken != nil { + transport = &oauth.Transport{ + Base: transport, + Token: opts.OAuthToken, + } } return transport @@ -168,6 +183,7 @@ func (c *client) createHTTPRequest(ctx context.Context, method, p string, body i } else { req.Header.Set("User-Agent", "src-cli/"+version.BuildTag) } + if c.opts.AccessToken != "" { req.Header.Set("Authorization", "token "+c.opts.AccessToken) } @@ -249,10 +265,20 @@ func (r *request) do(ctx context.Context, result any) (bool, error) { // confirm the status code. You can test this easily with e.g. an invalid // endpoint like -endpoint=https://google.com if resp.StatusCode != http.StatusOK { - if resp.StatusCode == http.StatusUnauthorized && isatty.IsCygwinTerminal(os.Stdout.Fd()) { - fmt.Println("You may need to specify or update your access token to use this endpoint.") - fmt.Println("See https://github.com/sourcegraph/src-cli#readme") - fmt.Println("") + if resp.StatusCode == http.StatusUnauthorized { + if oauth.IsOAuthTransport(r.client.httpClient.Transport) { + fmt.Println("The OAuth token is invalid. Please check that the Sourcegraph CLI client is still authorized.") + fmt.Println("") + fmt.Printf("To re-authorize, run: src login --oauth %s\n", r.client.opts.Endpoint) + fmt.Println("") + fmt.Println("Learn more at https://github.com/sourcegraph/src-cli#readme") + fmt.Println("") + } + if isatty.IsCygwinTerminal(os.Stdout.Fd()) { + fmt.Println("You may need to specify or update your access token to use this endpoint.") + fmt.Println("See https://github.com/sourcegraph/src-cli#readme") + fmt.Println("") + } } body, err := io.ReadAll(resp.Body) if err != nil { diff --git a/internal/oauth/flow.go b/internal/oauth/flow.go new file mode 100644 index 0000000000..f34d9ae656 --- /dev/null +++ b/internal/oauth/flow.go @@ -0,0 +1,429 @@ +// Package oauthimplements the OAuth 2.0 Device Authorization Grant (RFC 8628) +// for authenticating with Sourcegraph instances. +package oauth + +import ( + "cmp" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "strings" + "testing" + "time" + + "github.com/sourcegraph/src-cli/internal/secrets" + + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +const ( + // DefaultClientID is a predefined Client ID built into Sourcegraph + DefaultClientID = "sgo_cid_sourcegraph-cli" + + // wellKnownPath is the path on the sourcegraph server where clients can discover OAuth configuration + wellKnownPath = "/.well-known/openid-configuration" + + GrantTypeDeviceCode string = "urn:ietf:params:oauth:grant-type:device_code" + + ScopeOpenID string = "openid" + ScopeProfile string = "profile" + ScopeEmail string = "email" + ScopeOfflineAccess string = "offline_access" + ScopeUserAll string = "user:all" + + oauthKey string = "src:oauth" +) + +var defaultScopes = []string{ScopeEmail, ScopeOfflineAccess, ScopeOpenID, ScopeProfile, ScopeUserAll} + +// OIDCConfiguration represents the relevant fields from the OpenID Connect +// Discovery document at /.well-known/openid-configuration +type OIDCConfiguration struct { + Issuer string `json:"issuer,omitempty"` + TokenEndpoint string `json:"token_endpoint,omitempty"` + DeviceAuthorizationEndpoint string `json:"device_authorization_endpoint,omitempty"` +} + +type DeviceAuthResponse struct { + DeviceCode string `json:"device_code"` + UserCode string `json:"user_code"` + VerificationURI string `json:"verification_uri"` + VerificationURIComplete string `json:"verification_uri_complete,omitempty"` + ExpiresIn int `json:"expires_in"` + Interval int `json:"interval"` +} + +type TokenResponse struct { + AccessToken string `json:"access_token"` + RefreshToken string `json:"refresh_token,omitempty"` + ExpiresIn int `json:"expires_in,omitempty"` + TokenType string `json:"token_type"` + Scope string `json:"scope,omitempty"` +} + +type Token struct { + Endpoint string `json:"endpoint"` + ClientID string `json:"client_id,omitempty"` + AccessToken string `json:"access_token"` + RefreshToken string `json:"refresh_token,omitempty"` + ExpiresAt time.Time `json:"expires_at"` +} + +type ErrorResponse struct { + Error string `json:"error"` + ErrorDescription string `json:"error_description,omitempty"` +} + +type Client interface { + ClientID() string + Discover(ctx context.Context, endpoint string) (*OIDCConfiguration, error) + Start(ctx context.Context, endpoint string, scopes []string) (*DeviceAuthResponse, error) + Poll(ctx context.Context, endpoint, deviceCode string, interval time.Duration, expiresIn int) (*TokenResponse, error) + Refresh(ctx context.Context, token *Token) (*TokenResponse, error) +} + +type httpClient struct { + clientID string + client *http.Client + // cached OIDC configuration per endpoint + configCache map[string]*OIDCConfiguration +} + +func NewClient(clientID string) Client { + return NewClientWithHTTPClient(clientID, &http.Client{ + Timeout: 30 * time.Second, + }) +} + +func NewClientWithHTTPClient(clientID string, c *http.Client) Client { + return &httpClient{ + clientID: cmp.Or(clientID, DefaultClientID), + client: c, + configCache: make(map[string]*OIDCConfiguration), + } +} + +func (c *httpClient) ClientID() string { + return c.clientID +} + +// Discover fetches the openid-configuration which contains all the routes a client should +// use for authorization, device flows, tokens etc. +// +// Before making any requests, the configCache is checked and if there is a cache hit, the +// cached config is returned. +func (c *httpClient) Discover(ctx context.Context, endpoint string) (*OIDCConfiguration, error) { + endpoint = strings.TrimRight(endpoint, "/") + + if config, ok := c.configCache[endpoint]; ok { + return config, nil + } + + reqURL := endpoint + wellKnownPath + + req, err := http.NewRequestWithContext(ctx, "GET", reqURL, nil) + if err != nil { + return nil, errors.Wrap(err, "creating discovery request") + } + req.Header.Set("Accept", "application/json") + + resp, err := c.client.Do(req) + if err != nil { + return nil, errors.Wrap(err, "discovery request failed") + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, errors.Wrap(err, "reading discovery response") + } + + if resp.StatusCode != http.StatusOK { + return nil, errors.Newf("discovery failed with status %d: %s", resp.StatusCode, string(body)) + } + + var config OIDCConfiguration + if err := json.Unmarshal(body, &config); err != nil { + return nil, errors.Wrap(err, "parsing discovery response") + } + + c.configCache[endpoint] = &config + + return &config, nil +} + +// Start starts the OAuth device flow with the given endpoint. If no scopes are given the default scopes are used. +// +// Default Scopes: "openid" "profile" "email" "offline_access" "user:all" +func (c *httpClient) Start(ctx context.Context, endpoint string, scopes []string) (*DeviceAuthResponse, error) { + endpoint = strings.TrimRight(endpoint, "/") + + // Discover OIDC configuration - caches on first call + config, err := c.Discover(ctx, endpoint) + if err != nil { + return nil, errors.Wrap(err, "OIDC discovery failed") + } + + if config.DeviceAuthorizationEndpoint == "" { + return nil, errors.New("device authorization endpoint not found in OIDC configuration; the server may not support device flow") + } + + data := url.Values{} + data.Set("client_id", c.clientID) + if len(scopes) > 0 { + data.Set("scope", strings.Join(scopes, " ")) + } else { + data.Set("scope", strings.Join(defaultScopes, " ")) + } + + req, err := http.NewRequestWithContext(ctx, "POST", config.DeviceAuthorizationEndpoint, strings.NewReader(data.Encode())) + if err != nil { + return nil, errors.Wrap(err, "creating device auth request") + } + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.Header.Set("Accept", "application/json") + + resp, err := c.client.Do(req) + if err != nil { + return nil, errors.Wrap(err, "device auth request failed") + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, errors.Wrap(err, "reading device auth response") + } + + if resp.StatusCode != http.StatusOK { + var errResp ErrorResponse + if err := json.Unmarshal(body, &errResp); err == nil && errResp.Error != "" { + return nil, errors.Newf("device auth failed: %s: %s", errResp.Error, errResp.ErrorDescription) + } + return nil, errors.Newf("device auth failed with status %d: %s", resp.StatusCode, string(body)) + } + + var authResp DeviceAuthResponse + if err := json.Unmarshal(body, &authResp); err != nil { + return nil, errors.Wrap(err, "parsing device auth response") + } + + return &authResp, nil +} + +// Poll polls the OAuth token endpoint until the device has been authorized or not +// +// We poll as long as the authorization is pending. If the server tells us to slow down, we will wait 5 secs extra. +// +// Polling will stop when: +// - Device is authorized, and a token is returned +// - Device code has expried +// - User denied authorization +func (c *httpClient) Poll(ctx context.Context, endpoint, deviceCode string, interval time.Duration, expiresIn int) (*TokenResponse, error) { + endpoint = strings.TrimRight(endpoint, "/") + + // Discover OIDC configuration - caches on first call + config, err := c.Discover(ctx, endpoint) + if err != nil { + return nil, errors.Wrap(err, "OIDC discovery failed") + } + + if config.TokenEndpoint == "" { + return nil, errors.New("token endpoint not found in OIDC configuration") + } + + deadline := time.Now().Add(time.Duration(expiresIn) * time.Second) + + for { + if time.Now().After(deadline) { + return nil, errors.New("device code expired") + } + + if !testing.Testing() { + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-time.After(interval): + } + } + + tokenResp, err := c.pollOnce(ctx, config.TokenEndpoint, deviceCode) + if err != nil { + var pollErr *PollError + if errors.As(err, &pollErr) { + switch pollErr.Code { + case "authorization_pending": + continue + case "slow_down": + interval += 5 * time.Second + continue + case "expired_token": + return nil, errors.New("device code expired") + case "access_denied": + return nil, errors.New("authorization was denied by the user") + } + } + return nil, err + } + + return tokenResp, nil + } +} + +type PollError struct { + Code string + Description string +} + +func (e *PollError) Error() string { + if e.Description != "" { + return fmt.Sprintf("%s: %s", e.Code, e.Description) + } + return e.Code +} + +func (c *httpClient) pollOnce(ctx context.Context, tokenEndpoint, deviceCode string) (*TokenResponse, error) { + data := url.Values{} + data.Set("client_id", c.clientID) + data.Set("device_code", deviceCode) + data.Set("grant_type", GrantTypeDeviceCode) + + req, err := http.NewRequestWithContext(ctx, "POST", tokenEndpoint, strings.NewReader(data.Encode())) + if err != nil { + return nil, errors.Wrap(err, "creating token request") + } + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.Header.Set("Accept", "application/json") + + resp, err := c.client.Do(req) + if err != nil { + return nil, errors.Wrap(err, "token request failed") + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, errors.Wrap(err, "reading token response") + } + + if resp.StatusCode != http.StatusOK { + var errResp ErrorResponse + if err := json.Unmarshal(body, &errResp); err == nil && errResp.Error != "" { + return nil, &PollError{Code: errResp.Error, Description: errResp.ErrorDescription} + } + return nil, errors.Newf("token request failed with status %d: %s", resp.StatusCode, string(body)) + } + + var tokenResp TokenResponse + if err := json.Unmarshal(body, &tokenResp); err != nil { + return nil, errors.Wrap(err, "parsing token response") + } + + return &tokenResp, nil +} + +// Refresh exchanges a refresh token for a new access token. +func (c *httpClient) Refresh(ctx context.Context, token *Token) (*TokenResponse, error) { + config, err := c.Discover(ctx, token.Endpoint) + if err != nil { + return nil, errors.Wrap(err, "failed to discover OIDC configuration") + } + + if config.TokenEndpoint == "" { + return nil, errors.New("OIDC configuration has no token endpoint") + } + + data := url.Values{} + data.Set("client_id", c.clientID) + data.Set("grant_type", "refresh_token") + data.Set("refresh_token", token.RefreshToken) + + req, err := http.NewRequestWithContext(ctx, "POST", config.TokenEndpoint, strings.NewReader(data.Encode())) + if err != nil { + return nil, errors.Wrap(err, "creating refresh token request") + } + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.Header.Set("Accept", "application/json") + + resp, err := c.client.Do(req) + if err != nil { + return nil, errors.Wrap(err, "refresh token request failed") + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, errors.Wrap(err, "reading refresh token response") + } + + if resp.StatusCode != http.StatusOK { + var errResp ErrorResponse + if err := json.Unmarshal(body, &errResp); err == nil && errResp.Error != "" { + return nil, errors.Newf("refresh token failed: %s: %s", errResp.Error, errResp.ErrorDescription) + } + return nil, errors.Newf("refresh token failed with status %d: %s", resp.StatusCode, string(body)) + } + + var tokenResp TokenResponse + if err := json.Unmarshal(body, &tokenResp); err != nil { + return nil, errors.Wrap(err, "parsing refresh token response") + } + + return &tokenResp, err +} + +func (t *TokenResponse) Token(endpoint string) *Token { + return &Token{ + Endpoint: strings.TrimRight(endpoint, "/"), + RefreshToken: t.RefreshToken, + AccessToken: t.AccessToken, + ExpiresAt: time.Now().Add(time.Second * time.Duration(t.ExpiresIn)), + } +} + +func (t *Token) HasExpired() bool { + return time.Now().After(t.ExpiresAt) +} + +func (t *Token) ExpiringIn(d time.Duration) bool { + future := time.Now().Add(d) + return future.After(t.ExpiresAt) +} + +func StoreToken(ctx context.Context, token *Token) error { + if token.Endpoint == "" { + return errors.New("token endpoint cannot be empty when storing the token") + } + + store, err := secrets.Open(ctx, token.Endpoint) + if err != nil { + return err + } + data, err := json.Marshal(token) + if err != nil { + return errors.Wrap(err, "failed to marshal token") + } + + return store.Put(oauthKey, data) +} + +func LoadToken(ctx context.Context, endpoint string) (*Token, error) { + store, err := secrets.Open(ctx, endpoint) + if err != nil { + return nil, err + } + + data, err := store.Get(oauthKey) + if err != nil { + return nil, err + } + + var t Token + if err := json.Unmarshal(data, &t); err != nil { + return nil, errors.Wrap(err, "failed to unmarshal token") + } + + return &t, nil +} diff --git a/internal/oauth/flow_test.go b/internal/oauth/flow_test.go new file mode 100644 index 0000000000..0b1ad5dc93 --- /dev/null +++ b/internal/oauth/flow_test.go @@ -0,0 +1,573 @@ +package oauth + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" +) + +const ( + testDeviceAuthPath = "/device/code" + testTokenPath = "/token" +) + +type testServerOptions struct { + handlers map[string]http.HandlerFunc + wellKnownFunc func(w http.ResponseWriter, r *http.Request) +} + +func newTestServer(t *testing.T, opts testServerOptions) *httptest.Server { + return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case wellKnownPath: + if opts.wellKnownFunc != nil { + opts.wellKnownFunc(w, r) + } else { + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(OIDCConfiguration{ + Issuer: "https://" + r.Host, + DeviceAuthorizationEndpoint: "https://" + r.Host + testDeviceAuthPath, + TokenEndpoint: "https://" + r.Host + testTokenPath, + }) + } + default: + if handler, ok := opts.handlers[r.URL.Path]; ok { + handler(w, r) + } else { + t.Errorf("unexpected path: %s", r.URL.Path) + http.Error(w, "not found", http.StatusNotFound) + } + } + })) +} + +func TestDiscover_Success(t *testing.T) { + server := newTestServer(t, testServerOptions{}) + defer server.Close() + + client := NewClient(DefaultClientID) + config, err := client.Discover(context.Background(), server.URL) + if err != nil { + t.Fatalf("Discover() error = %v", err) + } + + if config.DeviceAuthorizationEndpoint != server.URL+testDeviceAuthPath { + t.Errorf("DeviceAuthorizationEndpoint = %q, want %q", config.DeviceAuthorizationEndpoint, server.URL+testDeviceAuthPath) + } + if config.TokenEndpoint != server.URL+testTokenPath { + t.Errorf("TokenEndpoint = %q, want %q", config.TokenEndpoint, server.URL+testTokenPath) + } +} + +func TestDiscover_Caching(t *testing.T) { + var callCount int32 + server := newTestServer(t, testServerOptions{ + wellKnownFunc: func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt32(&callCount, 1) + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(OIDCConfiguration{ + DeviceAuthorizationEndpoint: "http://example.com/device", + TokenEndpoint: "http://example.com/token", + }) + }, + }) + defer server.Close() + + client := NewClient(DefaultClientID) + + // Populate the cache + _, err := client.Discover(context.Background(), server.URL) + if err != nil { + t.Fatalf("Discover() error = %v", err) + } + + // Second call should use cache + _, err = client.Discover(context.Background(), server.URL) + if err != nil { + t.Fatalf("Discover() error = %v", err) + } + + if atomic.LoadInt32(&callCount) != 1 { + t.Errorf("callCount = %d, want 1 (second call should use cache)", callCount) + } +} + +func TestDiscover_Error(t *testing.T) { + server := newTestServer(t, testServerOptions{ + wellKnownFunc: func(w http.ResponseWriter, r *http.Request) { + http.Error(w, "not found", http.StatusNotFound) + }, + }) + defer server.Close() + + client := NewClient(DefaultClientID) + _, err := client.Discover(context.Background(), server.URL) + if err == nil { + t.Fatal("Discover() expected error, got nil") + } + + if !strings.Contains(err.Error(), "404") { + t.Errorf("error = %q, want to contain '404'", err.Error()) + } +} + +func TestStart_Success(t *testing.T) { + wantResponse := DeviceAuthResponse{ + DeviceCode: "test-device-code", + UserCode: "ABCD-1234", + VerificationURI: "https://example.com/device", + VerificationURIComplete: "https://example.com/device?user_code=ABCD-1234", + ExpiresIn: 1800, + Interval: 5, + } + + server := newTestServer(t, testServerOptions{ + handlers: map[string]http.HandlerFunc{ + testDeviceAuthPath: func(w http.ResponseWriter, r *http.Request) { + if r.Method != "POST" { + t.Errorf("unexpected method: %s", r.Method) + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + + if err := r.ParseForm(); err != nil { + t.Errorf("failed to parse form: %v", err) + http.Error(w, "bad request", http.StatusBadRequest) + return + } + + if got := r.FormValue("client_id"); got != DefaultClientID { + t.Errorf("unexpected client_id: got %q, want %q", got, DefaultClientID) + } + + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(wantResponse) + }, + }, + }) + defer server.Close() + + client := NewClient(DefaultClientID) + resp, err := client.Start(context.Background(), server.URL, nil) + if err != nil { + t.Fatalf("Start() error = %v", err) + } + + if resp.DeviceCode != wantResponse.DeviceCode { + t.Errorf("DeviceCode = %q, want %q", resp.DeviceCode, wantResponse.DeviceCode) + } + if resp.UserCode != wantResponse.UserCode { + t.Errorf("UserCode = %q, want %q", resp.UserCode, wantResponse.UserCode) + } + if resp.VerificationURI != wantResponse.VerificationURI { + t.Errorf("VerificationURI = %q, want %q", resp.VerificationURI, wantResponse.VerificationURI) + } + if resp.VerificationURIComplete != wantResponse.VerificationURIComplete { + t.Errorf("VerificationURIComplete = %q, want %q", resp.VerificationURIComplete, wantResponse.VerificationURIComplete) + } + if resp.ExpiresIn != wantResponse.ExpiresIn { + t.Errorf("ExpiresIn = %d, want %d", resp.ExpiresIn, wantResponse.ExpiresIn) + } + if resp.Interval != wantResponse.Interval { + t.Errorf("Interval = %d, want %d", resp.Interval, wantResponse.Interval) + } +} + +func TestStart_WithScopes(t *testing.T) { + var receivedScope string + + server := newTestServer(t, testServerOptions{ + handlers: map[string]http.HandlerFunc{ + testDeviceAuthPath: func(w http.ResponseWriter, r *http.Request) { + if err := r.ParseForm(); err != nil { + t.Errorf("failed to parse form: %v", err) + http.Error(w, "bad request", http.StatusBadRequest) + return + } + receivedScope = r.FormValue("scope") + + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(DeviceAuthResponse{ + DeviceCode: "test-device-code", + UserCode: "ABCD-1234", + VerificationURI: "https://example.com/device", + ExpiresIn: 1800, + Interval: 5, + }) + }, + }, + }) + defer server.Close() + + client := NewClient(DefaultClientID) + _, err := client.Start(context.Background(), server.URL, []string{"read", "write"}) + if err != nil { + t.Fatalf("Start() error = %v", err) + } + + if receivedScope != "read write" { + t.Errorf("scope = %q, want %q", receivedScope, "read write") + } +} + +func TestStart_Error(t *testing.T) { + server := newTestServer(t, testServerOptions{ + handlers: map[string]http.HandlerFunc{ + testDeviceAuthPath: func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + json.NewEncoder(w).Encode(ErrorResponse{ + Error: "invalid_client", + ErrorDescription: "Unknown client", + }) + }, + }, + }) + defer server.Close() + + client := NewClient(DefaultClientID) + _, err := client.Start(context.Background(), server.URL, nil) + if err == nil { + t.Fatal("Start() expected error, got nil") + } + + wantErr := "device auth failed: invalid_client: Unknown client" + if err.Error() != wantErr { + t.Errorf("error = %q, want %q", err.Error(), wantErr) + } +} + +func TestStart_NoDeviceEndpoint(t *testing.T) { + server := newTestServer(t, testServerOptions{ + wellKnownFunc: func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(OIDCConfiguration{ + TokenEndpoint: "http://example.com/token", + }) + }, + }) + defer server.Close() + + client := NewClient(DefaultClientID) + _, err := client.Start(context.Background(), server.URL, nil) + if err == nil { + t.Fatal("Start() expected error, got nil") + } + + if !strings.Contains(err.Error(), "device authorization endpoint not found") { + t.Errorf("error = %q, want to contain 'device authorization endpoint not found'", err.Error()) + } +} + +func TestPoll_Success(t *testing.T) { + wantToken := TokenResponse{ + AccessToken: "test-access-token", + ExpiresIn: 3600, + Scope: "read write", + TokenType: "Bearer", + } + + server := newTestServer(t, testServerOptions{ + handlers: map[string]http.HandlerFunc{ + testTokenPath: func(w http.ResponseWriter, r *http.Request) { + if r.Method != "POST" { + t.Errorf("unexpected method: %s", r.Method) + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + + if err := r.ParseForm(); err != nil { + t.Errorf("failed to parse form: %v", err) + http.Error(w, "bad request", http.StatusBadRequest) + return + } + + if got := r.FormValue("client_id"); got != DefaultClientID { + t.Errorf("unexpected client_id: got %q, want %q", got, DefaultClientID) + } + if got := r.FormValue("grant_type"); got != GrantTypeDeviceCode { + t.Errorf("unexpected grant_type: got %q", got) + } + + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(wantToken) + }, + }, + }) + defer server.Close() + + client := NewClient(DefaultClientID).(*httpClient) + resp, err := client.Poll(context.Background(), server.URL, "test-device-code", 10*time.Millisecond, 60) + if err != nil { + t.Fatalf("Poll() error = %v", err) + } + + if resp.AccessToken != wantToken.AccessToken { + t.Errorf("AccessToken = %q, want %q", resp.AccessToken, wantToken.AccessToken) + } + if resp.TokenType != wantToken.TokenType { + t.Errorf("TokenType = %q, want %q", resp.TokenType, wantToken.TokenType) + } + +} + +func TestPoll_AuthorizationPending(t *testing.T) { + var callCount int32 + + server := newTestServer(t, testServerOptions{ + handlers: map[string]http.HandlerFunc{ + testTokenPath: func(w http.ResponseWriter, r *http.Request) { + count := atomic.AddInt32(&callCount, 1) + + w.Header().Set("Content-Type", "application/json") + + if count < 3 { + w.WriteHeader(http.StatusBadRequest) + json.NewEncoder(w).Encode(ErrorResponse{ + Error: "authorization_pending", + ErrorDescription: "The user has not yet completed authorization", + }) + return + } + + json.NewEncoder(w).Encode(TokenResponse{ + AccessToken: "test-access-token", + TokenType: "Bearer", + }) + }, + }, + }) + defer server.Close() + + client := NewClient(DefaultClientID).(*httpClient) + resp, err := client.Poll(context.Background(), server.URL, "test-device-code", 10*time.Millisecond, 60) + if err != nil { + t.Fatalf("Poll() error = %v", err) + } + + if resp.AccessToken != "test-access-token" { + t.Errorf("AccessToken = %q, want %q", resp.AccessToken, "test-access-token") + } + + if atomic.LoadInt32(&callCount) != 3 { + t.Errorf("callCount = %d, want 3", callCount) + } +} + +func TestPoll_SlowDown(t *testing.T) { + var callCount int32 + + server := newTestServer(t, testServerOptions{ + handlers: map[string]http.HandlerFunc{ + testTokenPath: func(w http.ResponseWriter, r *http.Request) { + count := atomic.AddInt32(&callCount, 1) + + w.Header().Set("Content-Type", "application/json") + + if count == 1 { + w.WriteHeader(http.StatusBadRequest) + json.NewEncoder(w).Encode(ErrorResponse{ + Error: "slow_down", + }) + return + } + + json.NewEncoder(w).Encode(TokenResponse{ + AccessToken: "test-access-token", + TokenType: "Bearer", + }) + }, + }, + }) + defer server.Close() + + client := NewClient(DefaultClientID).(*httpClient) + resp, err := client.Poll(context.Background(), server.URL, "test-device-code", 10*time.Millisecond, 60) + if err != nil { + t.Fatalf("Poll() error = %v", err) + } + + if resp.AccessToken != "test-access-token" { + t.Errorf("AccessToken = %q, want %q", resp.AccessToken, "test-access-token") + } + + if atomic.LoadInt32(&callCount) != 2 { + t.Errorf("callCount = %d, want 2", callCount) + } +} + +func TestPoll_ExpiredToken(t *testing.T) { + server := newTestServer(t, testServerOptions{ + handlers: map[string]http.HandlerFunc{ + testTokenPath: func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + json.NewEncoder(w).Encode(ErrorResponse{ + Error: "expired_token", + ErrorDescription: "The device code has expired", + }) + }, + }, + }) + defer server.Close() + + client := NewClient(DefaultClientID).(*httpClient) + _, err := client.Poll(context.Background(), server.URL, "test-device-code", 10*time.Millisecond, 60) + if err == nil { + t.Fatal("Poll() expected error, got nil") + } + + wantErr := "device code expired" + if err.Error() != wantErr { + t.Errorf("error = %q, want %q", err.Error(), wantErr) + } +} + +func TestPoll_AccessDenied(t *testing.T) { + server := newTestServer(t, testServerOptions{ + handlers: map[string]http.HandlerFunc{ + testTokenPath: func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + json.NewEncoder(w).Encode(ErrorResponse{ + Error: "access_denied", + ErrorDescription: "The user denied the request", + }) + }, + }, + }) + defer server.Close() + + client := NewClient(DefaultClientID).(*httpClient) + _, err := client.Poll(context.Background(), server.URL, "test-device-code", 10*time.Millisecond, 60) + if err == nil { + t.Fatal("Poll() expected error, got nil") + } + + wantErr := "authorization was denied by the user" + if err.Error() != wantErr { + t.Errorf("error = %q, want %q", err.Error(), wantErr) + } +} + +func TestPoll_Timeout(t *testing.T) { + server := newTestServer(t, testServerOptions{ + handlers: map[string]http.HandlerFunc{ + testTokenPath: func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + json.NewEncoder(w).Encode(ErrorResponse{ + Error: "authorization_pending", + }) + }, + }, + }) + defer server.Close() + + client := NewClient(DefaultClientID).(*httpClient) + _, err := client.Poll(context.Background(), server.URL, "test-device-code", 10*time.Millisecond, 0) + if err == nil { + t.Fatal("Poll() expected error, got nil") + } + + wantErr := "device code expired" + if err.Error() != wantErr { + t.Errorf("error = %q, want %q", err.Error(), wantErr) + } +} + +func TestPoll_ContextCancellation(t *testing.T) { + server := newTestServer(t, testServerOptions{ + handlers: map[string]http.HandlerFunc{ + testTokenPath: func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + json.NewEncoder(w).Encode(ErrorResponse{ + Error: "authorization_pending", + }) + }, + }, + }) + defer server.Close() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + client := NewClient(DefaultClientID).(*httpClient) + _, err := client.Poll(ctx, server.URL, "test-device-code", 10*time.Millisecond, 3600) + if err == nil { + t.Fatal("Poll() expected error, got nil") + } + + if err != context.Canceled && !strings.Contains(err.Error(), "context canceled") { + t.Errorf("error = %v, want context.Canceled or wrapped context canceled error", err) + } +} + +func TestRefresh_Success(t *testing.T) { + server := newTestServer(t, testServerOptions{ + handlers: map[string]http.HandlerFunc{ + testTokenPath: func(w http.ResponseWriter, r *http.Request) { + if err := r.ParseForm(); err != nil { + http.Error(w, "bad request", http.StatusBadRequest) + return + } + if got := r.FormValue("grant_type"); got != "refresh_token" { + t.Errorf("grant_type = %q, want %q", got, "refresh_token") + } + if got := r.FormValue("refresh_token"); got != "test-refresh-token" { + t.Errorf("refresh_token = %q, want %q", got, "test-refresh-token") + } + + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(TokenResponse{ + AccessToken: "new-access-token", + RefreshToken: "new-refresh-token", + ExpiresIn: 3600, + TokenType: "Bearer", + }) + }, + }, + }) + defer server.Close() + + client := NewClient(DefaultClientID) + token := &Token{ + Endpoint: server.URL, + AccessToken: "new-access-token", + RefreshToken: "test-refresh-token", + ExpiresAt: time.Now().Add(time.Second * time.Duration(3600)), + } + resp, err := client.Refresh(context.Background(), token) + if err != nil { + t.Fatalf("Refresh() error = %v", err) + } + + if resp.AccessToken != "new-access-token" { + t.Errorf("AccessToken = %q, want %q", resp.AccessToken, "new-access-token") + } + if resp.RefreshToken != "new-refresh-token" { + t.Errorf("RefreshToken = %q, want %q", resp.RefreshToken, "new-refresh-token") + } +} + +func TestRefresh_DiscoverFailure(t *testing.T) { + client := NewClient(DefaultClientID) + token := &Token{ + Endpoint: "http://127.0.0.1:1", + RefreshToken: "test-refresh-token", + } + + _, err := client.Refresh(context.Background(), token) + if err == nil { + t.Fatal("Refresh() expected error, got nil") + } + if !strings.Contains(err.Error(), "failed to discover OIDC configuration") { + t.Errorf("error = %q, want discovery failure context", err.Error()) + } +} diff --git a/internal/oauth/http_transport.go b/internal/oauth/http_transport.go new file mode 100644 index 0000000000..8aea3d75a4 --- /dev/null +++ b/internal/oauth/http_transport.go @@ -0,0 +1,87 @@ +package oauth + +import ( + "context" + "net/http" + "sync" + "time" +) + +var _ http.Transport + +var _ http.RoundTripper = (*Transport)(nil) + +type Transport struct { + Base http.RoundTripper + Token *Token + + mu sync.Mutex +} + +// storeRefreshedTokenFn is the function the transport should use to persist the token - mainly used during +// tests to swap out the implementation out with a mock +var storeRefreshedTokenFn = StoreToken + +// RoundTrip implements http.RoundTripper. +func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) { + ctx := req.Context() + + if err := t.refreshToken(ctx); err != nil { + return nil, err + } + + req2 := req.Clone(req.Context()) + req2.Header.Set("Authorization", "Bearer "+t.Token.AccessToken) + + if t.Base != nil { + return t.Base.RoundTrip(req2) + } + return http.DefaultTransport.RoundTrip(req2) +} + +// refreshToken checks if the token has expired or expiring soon and refreshes it. Once the token is +// refreshed, the in-memory token is updated and a best effort is made to store the token. +// If storing the token fails, no error is returned. +func (t *Transport) refreshToken(ctx context.Context) error { + t.mu.Lock() + defer t.mu.Unlock() + + prevToken := t.Token + token, err := maybeRefresh(ctx, t.Token) + if err != nil { + return err + } + t.Token = token + if token != prevToken { + // try to save the token if we fail let the request continue with in memory token + _ = storeRefreshedTokenFn(ctx, token) + } + + return nil +} + +// maybeRefresh conditionally refreshes the token. If the token has expired or is expriing in the next 30s +// it will be refreshed and the updated token will be returned. Otherwise, no refresh occurs and the original +// token is returned. +func maybeRefresh(ctx context.Context, token *Token) (*Token, error) { + // token has NOT expired and is NOT about to expire in 30s + if !(token.HasExpired() || token.ExpiringIn(time.Duration(30)*time.Second)) { + return token, nil + } + client := NewClient(token.ClientID) + + resp, err := client.Refresh(ctx, token) + if err != nil { + return nil, err + } + + next := resp.Token(token.Endpoint) + next.ClientID = token.ClientID + return next, nil +} + +// IsOAuthTransport checks wether the underlying type of the given RoundTripper is a OAuthTransport +func IsOAuthTransport(trp http.RoundTripper) bool { + _, ok := trp.(*Transport) + return ok +} diff --git a/internal/oauth/http_transport_test.go b/internal/oauth/http_transport_test.go new file mode 100644 index 0000000000..4dac832d05 --- /dev/null +++ b/internal/oauth/http_transport_test.go @@ -0,0 +1,172 @@ +package oauth + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +type roundTripperFunc func(*http.Request) (*http.Response, error) + +func (f roundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error) { + return f(req) +} + +func newRefreshServer(t *testing.T, accessToken string) *httptest.Server { + t.Helper() + return newTestServer(t, testServerOptions{ + handlers: map[string]http.HandlerFunc{ + testTokenPath: func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"access_token":"` + accessToken + `","refresh_token":"new-refresh","expires_in":3600}`)) + }, + }, + }) +} + +func TestMaybeRefresh(t *testing.T) { + server := newRefreshServer(t, "new-token") + defer server.Close() + + tests := []struct { + name string + token *Token + wantAccess string + wantSame bool + }{ + { + name: "unchanged when still valid", + token: &Token{ + AccessToken: "valid-token", + ExpiresAt: time.Now().Add(time.Hour), + }, + wantAccess: "valid-token", + wantSame: true, + }, + { + name: "refreshes expired token", + token: &Token{ + Endpoint: server.URL, + AccessToken: "expired-token", + RefreshToken: "refresh-token", + ExpiresAt: time.Now().Add(-time.Hour), + }, + wantAccess: "new-token", + }, + { + name: "refreshes token expiring soon", + token: &Token{ + Endpoint: server.URL, + AccessToken: "expiring-soon-token", + RefreshToken: "refresh-token", + ExpiresAt: time.Now().Add(10 * time.Second), + }, + wantAccess: "new-token", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := maybeRefresh(context.Background(), tt.token) + if err != nil { + t.Fatalf("maybeRefresh() error = %v", err) + } + if got.AccessToken != tt.wantAccess { + t.Errorf("AccessToken = %q, want %q", got.AccessToken, tt.wantAccess) + } + if tt.wantSame && got != tt.token { + t.Errorf("token pointer changed for unexpired token") + } + }) + } +} + +func TestTransportRoundTrip(t *testing.T) { + tests := []struct { + name string + token *Token + persistErr error + wantAuthHeader string + wantStoreCalls int + }{ + { + name: "uses existing token without persisting", + token: &Token{ + AccessToken: "valid-token", + ExpiresAt: time.Now().Add(time.Hour), + }, + wantAuthHeader: "Bearer valid-token", + wantStoreCalls: 0, + }, + { + name: "persists refreshed token", + token: &Token{ + AccessToken: "expired-token", + RefreshToken: "refresh-token", + ExpiresAt: time.Now().Add(-time.Hour), + }, + wantAuthHeader: "Bearer new-token", + wantStoreCalls: 1, + }, + { + name: "ignores persist failures", + token: &Token{ + AccessToken: "expired-token", + RefreshToken: "refresh-token", + ExpiresAt: time.Now().Add(-time.Hour), + }, + persistErr: errors.New("persist failed"), + wantAuthHeader: "Bearer new-token", + wantStoreCalls: 1, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if tt.wantStoreCalls > 0 { + server := newRefreshServer(t, "new-token") + defer server.Close() + tt.token.Endpoint = server.URL + } + + originalStoreFn := storeRefreshedTokenFn + defer func() { storeRefreshedTokenFn = originalStoreFn }() + + var storeCalls int + var storedToken *Token + storeRefreshedTokenFn = func(_ context.Context, token *Token) error { + storeCalls++ + storedToken = token + return tt.persistErr + } + + var capturedAuth string + tr := &Transport{ + Base: roundTripperFunc(func(req *http.Request) (*http.Response, error) { + capturedAuth = req.Header.Get("Authorization") + return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody}, nil + }), + Token: tt.token, + } + + _, err := tr.RoundTrip(httptest.NewRequest(http.MethodGet, "http://example.com", nil)) + if err != nil { + t.Fatalf("RoundTrip() error = %v", err) + } + + if capturedAuth != tt.wantAuthHeader { + t.Errorf("Authorization = %q, want %q", capturedAuth, tt.wantAuthHeader) + } + if storeCalls != tt.wantStoreCalls { + t.Errorf("store calls = %d, want %d", storeCalls, tt.wantStoreCalls) + } + if tt.wantStoreCalls > 0 && (storedToken == nil || storedToken.AccessToken != "new-token") { + t.Errorf("stored token = %#v, want access token %q", storedToken, "new-token") + } + }) + } +} diff --git a/internal/secrets/keyring.go b/internal/secrets/keyring.go new file mode 100644 index 0000000000..9464b1054c --- /dev/null +++ b/internal/secrets/keyring.go @@ -0,0 +1,77 @@ +package secrets + +import ( + "context" + "strings" + + "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/zalando/go-keyring" +) + +var ErrSecretNotFound = errors.New("secret not found") + +const serviceNamePrefix = "Sourcegraph CLI" + +type keyringStore struct { + ctx context.Context + serviceName string +} + +// Open opens the system keyring for the Sourcegraph CLI. +func Open(ctx context.Context, endpoint string) (*keyringStore, error) { + endpoint = strings.TrimRight(strings.TrimSpace(endpoint), "/") + if endpoint == "" { + return nil, errors.New("endpoint cannot be empty") + } + + serviceName := serviceNamePrefix + " <" + endpoint + ">" + + return &keyringStore{ctx: ctx, serviceName: serviceName}, nil +} + +// withContext runs fn in a goroutine and returns its result, or ctx.Err() if the context is cancelled first. +func withContext[T any](ctx context.Context, fn func() (T, error)) (T, error) { + type result struct { + val T + err error + } + ch := make(chan result, 1) + go func() { + val, err := fn() + ch <- result{val, err} + }() + + select { + case <-ctx.Done(): + var zero T + return zero, ctx.Err() + case r := <-ch: + return r.val, r.err + } +} + +// Put stores a key-value pair in the keyring. +func (k *keyringStore) Put(key string, data []byte) error { + _, err := withContext(k.ctx, func() (struct{}, error) { + err := keyring.Set(k.serviceName, key, string(data)) + if err != nil { + return struct{}{}, errors.Wrap(err, "storing item in keyring") + } + return struct{}{}, nil + }) + return err +} + +// Get retrieves a value by key from the keyring. +func (k *keyringStore) Get(key string) ([]byte, error) { + return withContext(k.ctx, func() ([]byte, error) { + secret, err := keyring.Get(k.serviceName, key) + if err != nil { + if err == keyring.ErrNotFound { + return nil, ErrSecretNotFound + } + return nil, errors.Wrap(err, "getting item from keyring") + } + return []byte(secret), nil + }) +} diff --git a/internal/secrets/keyring_test.go b/internal/secrets/keyring_test.go new file mode 100644 index 0000000000..65d2002782 --- /dev/null +++ b/internal/secrets/keyring_test.go @@ -0,0 +1,58 @@ +package secrets + +import ( + "context" + "testing" +) + +func TestOpen(t *testing.T) { + tests := []struct { + name string + endpoint string + wantServiceName string + wantErr bool + }{ + { + name: "normalized endpoint", + endpoint: " https://sourcegraph.example.com/ ", + wantServiceName: "Sourcegraph CLI ", + }, + { + name: "normalized endpoint with path", + endpoint: " https://sourcegraph.example.com/sourcegraph/ ", + wantServiceName: "Sourcegraph CLI ", + }, + { + name: "normalized endpoint with nested path", + endpoint: "https://sourcegraph.example.com/custom/path///", + wantServiceName: "Sourcegraph CLI ", + }, + { + name: "empty endpoint", + endpoint: " / ", + wantErr: true, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + store, err := Open(context.Background(), test.endpoint) + if test.wantErr { + if err == nil { + t.Fatal("Open() error = nil, want non-nil") + } + if store != nil { + t.Fatalf("Open() store = %v, want nil", store) + } + return + } + + if err != nil { + t.Fatalf("Open() error = %v, want nil", err) + } + if got := store.serviceName; got != test.wantServiceName { + t.Fatalf("Open() serviceName = %q, want %q", got, test.wantServiceName) + } + }) + } +} From 871147300f45107ba16600ad85d140bb317de279 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Mon, 9 Mar 2026 15:48:08 +0200 Subject: [PATCH 544/647] oauth: fix oauth token race in http_transport (#1269) --- internal/oauth/http_transport.go | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/internal/oauth/http_transport.go b/internal/oauth/http_transport.go index 8aea3d75a4..d63d40ca44 100644 --- a/internal/oauth/http_transport.go +++ b/internal/oauth/http_transport.go @@ -12,9 +12,12 @@ var _ http.Transport var _ http.RoundTripper = (*Transport)(nil) type Transport struct { - Base http.RoundTripper + Base http.RoundTripper + //Token is a OAuth token (which has a refresh token) that should be used during roundtrip to automatically + //refresh the OAuth access token once the current one has expired or is soon to expire Token *Token + //mu is a mutex that should be acquired whenever token used mu sync.Mutex } @@ -29,9 +32,10 @@ func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) { if err := t.refreshToken(ctx); err != nil { return nil, err } + token := t.getToken() req2 := req.Clone(req.Context()) - req2.Header.Set("Authorization", "Bearer "+t.Token.AccessToken) + req2.Header.Set("Authorization", "Bearer "+token.AccessToken) if t.Base != nil { return t.Base.RoundTrip(req2) @@ -39,6 +43,14 @@ func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) { return http.DefaultTransport.RoundTrip(req2) } +// getToken returns a value copy of token and is guarded by a mutex +func (t *Transport) getToken() Token { + t.mu.Lock() + defer t.mu.Unlock() + + return *t.Token +} + // refreshToken checks if the token has expired or expiring soon and refreshes it. Once the token is // refreshed, the in-memory token is updated and a best effort is made to store the token. // If storing the token fails, no error is returned. From c6de254903a217912df95928ceaf6ff6947cd580 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Mon, 9 Mar 2026 16:41:50 +0200 Subject: [PATCH 545/647] refactor: login (#1268) - split login into distinct flows - add specific flow for oauth - add specific flows for error conditions - update tests --- cmd/src/login.go | 203 +++++++++++--------------------------- cmd/src/login_oauth.go | 108 ++++++++++++++++++++ cmd/src/login_test.go | 94 ++++++++++++++++-- cmd/src/login_validate.go | 61 ++++++++++++ 4 files changed, 314 insertions(+), 152 deletions(-) create mode 100644 cmd/src/login_oauth.go create mode 100644 cmd/src/login_validate.go diff --git a/cmd/src/login.go b/cmd/src/login.go index 5a73ef4cc8..c4989605f4 100644 --- a/cmd/src/login.go +++ b/cmd/src/login.go @@ -6,10 +6,6 @@ import ( "fmt" "io" "os" - "os/exec" - "runtime" - "strings" - "time" "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/cmderrors" @@ -69,13 +65,13 @@ Examples: client := cfg.apiClient(apiFlags, io.Discard) return loginCmd(context.Background(), loginParams{ - cfg: cfg, - client: client, - endpoint: endpoint, - out: os.Stdout, - useOAuth: *useOAuth, - apiFlags: apiFlags, - deviceFlowClient: oauth.NewClient(oauth.DefaultClientID), + cfg: cfg, + client: client, + endpoint: endpoint, + out: os.Stdout, + useOAuth: *useOAuth, + apiFlags: apiFlags, + oauthClient: oauth.NewClient(oauth.DefaultClientID), }) } @@ -87,161 +83,80 @@ Examples: } type loginParams struct { - cfg *config - client api.Client - endpoint string - out io.Writer - useOAuth bool - apiFlags *api.Flags - deviceFlowClient oauth.Client + cfg *config + client api.Client + endpoint string + out io.Writer + useOAuth bool + apiFlags *api.Flags + oauthClient oauth.Client } -func loginCmd(ctx context.Context, p loginParams) error { - endpointArg := cleanEndpoint(p.endpoint) - cfg := p.cfg - client := p.client - out := p.out - - printProblem := func(problem string) { - fmt.Fprintf(out, "❌ Problem: %s\n", problem) - } - - createAccessTokenMessage := fmt.Sprintf("\n"+`🛠 To fix: Create an access token by going to %s/user/settings/tokens, then set the following environment variables in your terminal: +type loginFlow func(context.Context, loginParams) error - export SRC_ENDPOINT=%s - export SRC_ACCESS_TOKEN=(your access token) +type loginFlowKind int - To verify that it's working, run the login command again. - - Alternatively, you can try logging in using OAuth by running: src login --oauth %s -`, endpointArg, endpointArg, endpointArg) +const ( + loginFlowOAuth loginFlowKind = iota + loginFlowMissingAuth + loginFlowEndpointConflict + loginFlowValidate +) - if cfg.ConfigFilePath != "" { - fmt.Fprintln(out) - fmt.Fprintf(out, "⚠️ Warning: Configuring src with a JSON file is deprecated. Please migrate to using the env vars SRC_ENDPOINT, SRC_ACCESS_TOKEN, and SRC_PROXY instead, and then remove %s. See https://github.com/sourcegraph/src-cli#readme for more information.\n", cfg.ConfigFilePath) - } +var loadStoredOAuthToken = oauth.LoadToken - noToken := cfg.AccessToken == "" - endpointConflict := endpointArg != cfg.Endpoint - if !p.useOAuth && (noToken || endpointConflict) { - fmt.Fprintln(out) - switch { - case noToken: - printProblem("No access token is configured.") - case endpointConflict: - printProblem(fmt.Sprintf("The configured endpoint is %s, not %s.", cfg.Endpoint, endpointArg)) - } - fmt.Fprintln(out, createAccessTokenMessage) - return cmderrors.ExitCode1 +func loginCmd(ctx context.Context, p loginParams) error { + if p.cfg.ConfigFilePath != "" { + fmt.Fprintln(p.out) + fmt.Fprintf(p.out, "⚠️ Warning: Configuring src with a JSON file is deprecated. Please migrate to using the env vars SRC_ENDPOINT, SRC_ACCESS_TOKEN, and SRC_PROXY instead, and then remove %s. See https://github.com/sourcegraph/src-cli#readme for more information.\n", p.cfg.ConfigFilePath) } - if p.useOAuth { - token, err := runOAuthDeviceFlow(ctx, endpointArg, out, p.deviceFlowClient) - if err != nil { - printProblem(fmt.Sprintf("OAuth Device flow authentication failed: %s", err)) - fmt.Fprintln(out, createAccessTokenMessage) - return cmderrors.ExitCode1 - } - - if err := oauth.StoreToken(ctx, token); err != nil { - fmt.Fprintln(out) - fmt.Fprintf(out, "⚠️ Warning: Failed to store token in keyring store: %q. Continuing with this session only.\n", err) - } + _, flow := selectLoginFlow(ctx, p) + return flow(ctx, p) +} - client = api.NewClient(api.ClientOpts{ - Endpoint: cfg.Endpoint, - AdditionalHeaders: cfg.AdditionalHeaders, - Flags: p.apiFlags, - Out: out, - ProxyURL: cfg.ProxyURL, - ProxyPath: cfg.ProxyPath, - OAuthToken: token, - }) - } +// selectLoginFlow decides what login flow to run based on flags and config. +func selectLoginFlow(ctx context.Context, p loginParams) (loginFlowKind, loginFlow) { + endpointArg := cleanEndpoint(p.endpoint) - // See if the user is already authenticated. - query := `query CurrentUser { currentUser { username } }` - var result struct { - CurrentUser *struct{ Username string } - } - if _, err := client.NewRequest(query, nil).Do(ctx, &result); err != nil { - if strings.HasPrefix(err.Error(), "error: 401 Unauthorized") || strings.HasPrefix(err.Error(), "error: 403 Forbidden") { - printProblem("Invalid access token.") - } else { - printProblem(fmt.Sprintf("Error communicating with %s: %s", endpointArg, err)) - } - fmt.Fprintln(out, createAccessTokenMessage) - fmt.Fprintln(out, " (If you need to supply custom HTTP request headers, see information about SRC_HEADER_* and SRC_HEADERS env vars at https://github.com/sourcegraph/src-cli/blob/main/AUTH_PROXY.md)") - return cmderrors.ExitCode1 + if p.useOAuth { + return loginFlowOAuth, runOAuthLogin } - - if result.CurrentUser == nil { - // This should never happen; we verified there is an access token, so there should always be - // a user. - printProblem(fmt.Sprintf("Unable to determine user on %s.", endpointArg)) - return cmderrors.ExitCode1 + if !hasEffectiveAuth(ctx, p.cfg, endpointArg) { + return loginFlowMissingAuth, runMissingAuthLogin } - fmt.Fprintln(out) - fmt.Fprintf(out, "✔️ Authenticated as %s on %s\n", result.CurrentUser.Username, endpointArg) - - if p.useOAuth { - fmt.Fprintln(out) - fmt.Fprintf(out, "Authenticated with OAuth credentials") + if endpointArg != p.cfg.Endpoint { + return loginFlowEndpointConflict, runEndpointConflictLogin } - - fmt.Fprintln(out) - return nil + return loginFlowValidate, runValidatedLogin } -func runOAuthDeviceFlow(ctx context.Context, endpoint string, out io.Writer, client oauth.Client) (*oauth.Token, error) { - authResp, err := client.Start(ctx, endpoint, nil) - if err != nil { - return nil, err +// hasEffectiveAuth determines whether we have auth credentials to continue. It first checks for a resolved Access Token in +// config, then it checks for a stored OAuth token. +func hasEffectiveAuth(ctx context.Context, cfg *config, resolvedEndpoint string) bool { + if cfg.AccessToken != "" { + return true } - authURL := authResp.VerificationURIComplete - msg := fmt.Sprintf("If your browser did not open automatically, visit %s.", authURL) - if authURL == "" { - authURL = authResp.VerificationURI - msg = fmt.Sprintf("If your browser did not open automatically, visit %s and enter the user code %s", authURL, authResp.DeviceCode) + if _, err := loadStoredOAuthToken(ctx, resolvedEndpoint); err == nil { + return true } - _ = openInBrowser(authURL) - fmt.Fprintln(out) - fmt.Fprint(out, msg) - fmt.Fprintln(out) - fmt.Fprint(out, "Waiting for authorization...") - defer fmt.Fprintf(out, "DONE\n\n") + return false +} - interval := time.Duration(authResp.Interval) * time.Second - if interval <= 0 { - interval = 5 * time.Second - } +func printLoginProblem(out io.Writer, problem string) { + fmt.Fprintf(out, "❌ Problem: %s\n", problem) +} - resp, err := client.Poll(ctx, endpoint, authResp.DeviceCode, interval, authResp.ExpiresIn) - if err != nil { - return nil, err - } +func loginAccessTokenMessage(endpoint string) string { + return fmt.Sprintf("\n"+`🛠 To fix: Create an access token by going to %s/user/settings/tokens, then set the following environment variables in your terminal: - token := resp.Token(endpoint) - token.ClientID = client.ClientID() - return token, nil -} + export SRC_ENDPOINT=%s + export SRC_ACCESS_TOKEN=(your access token) -func openInBrowser(url string) error { - if url == "" { - return nil - } + To verify that it's working, run the login command again. - var cmd *exec.Cmd - switch runtime.GOOS { - case "darwin": - cmd = exec.Command("open", url) - case "windows": - // "start" is a cmd.exe built-in; the empty string is the window title. - cmd = exec.Command("cmd", "/c", "start", "", url) - default: - cmd = exec.Command("xdg-open", url) - } - return cmd.Run() + Alternatively, you can try logging in using OAuth by running: src login --oauth %s +`, endpoint, endpoint, endpoint) } diff --git a/cmd/src/login_oauth.go b/cmd/src/login_oauth.go new file mode 100644 index 0000000000..df3f912f62 --- /dev/null +++ b/cmd/src/login_oauth.go @@ -0,0 +1,108 @@ +package main + +import ( + "context" + "fmt" + "io" + "os/exec" + "runtime" + "time" + + "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/cmderrors" + "github.com/sourcegraph/src-cli/internal/oauth" +) + +func runOAuthLogin(ctx context.Context, p loginParams) error { + endpointArg := cleanEndpoint(p.endpoint) + client, err := oauthLoginClient(ctx, p, endpointArg) + if err != nil { + printLoginProblem(p.out, fmt.Sprintf("OAuth Device flow authentication failed: %s", err)) + fmt.Fprintln(p.out, loginAccessTokenMessage(endpointArg)) + return cmderrors.ExitCode1 + } + + if err := validateCurrentUser(ctx, client, p.out, endpointArg); err != nil { + return err + } + + fmt.Fprintln(p.out) + fmt.Fprint(p.out, "✔︎ Authenticated with OAuth credentials") + fmt.Fprintln(p.out) + return nil +} + +func oauthLoginClient(ctx context.Context, p loginParams, endpoint string) (api.Client, error) { + token, err := runOAuthDeviceFlow(ctx, endpoint, p.out, p.oauthClient) + if err != nil { + return nil, err + } + + if err := oauth.StoreToken(ctx, token); err != nil { + fmt.Fprintln(p.out) + fmt.Fprintf(p.out, "⚠️ Warning: Failed to store token in keyring store: %q. Continuing with this session only.\n", err) + } + + return api.NewClient(api.ClientOpts{ + Endpoint: p.cfg.Endpoint, + AdditionalHeaders: p.cfg.AdditionalHeaders, + Flags: p.apiFlags, + Out: p.out, + ProxyURL: p.cfg.ProxyURL, + ProxyPath: p.cfg.ProxyPath, + OAuthToken: token, + }), nil +} + +func runOAuthDeviceFlow(ctx context.Context, endpoint string, out io.Writer, client oauth.Client) (*oauth.Token, error) { + authResp, err := client.Start(ctx, endpoint, nil) + if err != nil { + return nil, err + } + + authURL := authResp.VerificationURIComplete + msg := fmt.Sprintf("If your browser did not open automatically, visit %s.", authURL) + if authURL == "" { + authURL = authResp.VerificationURI + msg = fmt.Sprintf("If your browser did not open automatically, visit %s and enter the user code %s", authURL, authResp.DeviceCode) + } + _ = openInBrowser(authURL) + fmt.Fprintln(out) + fmt.Fprint(out, msg) + + fmt.Fprintln(out) + fmt.Fprint(out, "Waiting for authorization... ") + defer fmt.Fprintf(out, "DONE\n\n") + + interval := time.Duration(authResp.Interval) * time.Second + if interval <= 0 { + interval = 5 * time.Second + } + + resp, err := client.Poll(ctx, endpoint, authResp.DeviceCode, interval, authResp.ExpiresIn) + if err != nil { + return nil, err + } + + token := resp.Token(endpoint) + token.ClientID = client.ClientID() + return token, nil +} + +func openInBrowser(url string) error { + if url == "" { + return nil + } + + var cmd *exec.Cmd + switch runtime.GOOS { + case "darwin": + cmd = exec.Command("open", url) + case "windows": + // "start" is a cmd.exe built-in; the empty string is the window title. + cmd = exec.Command("cmd", "/c", "start", "", url) + default: + cmd = exec.Command("xdg-open", url) + } + return cmd.Run() +} diff --git a/cmd/src/login_test.go b/cmd/src/login_test.go index ab7a15056a..a34288576f 100644 --- a/cmd/src/login_test.go +++ b/cmd/src/login_test.go @@ -18,13 +18,17 @@ func TestLogin(t *testing.T) { check := func(t *testing.T, cfg *config, endpointArg string) (output string, err error) { t.Helper() + restoreStoredOAuthLoader(t, func(context.Context, string) (*oauth.Token, error) { + return nil, fmt.Errorf("not found") + }) + var out bytes.Buffer err = loginCmd(context.Background(), loginParams{ - cfg: cfg, - client: cfg.apiClient(nil, io.Discard), - endpoint: endpointArg, - out: &out, - deviceFlowClient: oauth.NewClient(oauth.DefaultClientID), + cfg: cfg, + client: cfg.apiClient(nil, io.Discard), + endpoint: endpointArg, + out: &out, + oauthClient: oauth.NewClient(oauth.DefaultClientID), }) return strings.TrimSpace(out.String()), err } @@ -63,7 +67,6 @@ func TestLogin(t *testing.T) { }) t.Run("invalid access token", func(t *testing.T) { - // Dummy HTTP server to return HTTP 401/403. s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Error(w, "", http.StatusUnauthorized) })) @@ -82,7 +85,6 @@ func TestLogin(t *testing.T) { }) t.Run("valid", func(t *testing.T) { - // Dummy HTTP server to return JSON response with currentUser. s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, `{"data":{"currentUser":{"username":"alice"}}}`) })) @@ -93,10 +95,86 @@ func TestLogin(t *testing.T) { if err != nil { t.Fatal(err) } - wantOut := "✔️ Authenticated as alice on $ENDPOINT" + wantOut := "✔︎ Authenticated as alice on $ENDPOINT" wantOut = strings.ReplaceAll(wantOut, "$ENDPOINT", endpoint) if out != wantOut { t.Errorf("got output %q, want %q", out, wantOut) } }) } + +func TestSelectLoginFlow(t *testing.T) { + restoreStoredOAuthLoader(t, func(context.Context, string) (*oauth.Token, error) { + return nil, fmt.Errorf("not found") + }) + + t.Run("uses oauth flow when oauth flag is set", func(t *testing.T) { + params := loginParams{ + cfg: &config{Endpoint: "https://example.com"}, + endpoint: "https://example.com", + useOAuth: true, + } + + if got, _ := selectLoginFlow(context.Background(), params); got != loginFlowOAuth { + t.Fatalf("flow = %v, want %v", got, loginFlowOAuth) + } + }) + + t.Run("uses missing auth flow when auth is unavailable", func(t *testing.T) { + params := loginParams{ + cfg: &config{Endpoint: "https://example.com"}, + endpoint: "https://sourcegraph.example.com", + } + + if got, _ := selectLoginFlow(context.Background(), params); got != loginFlowMissingAuth { + t.Fatalf("flow = %v, want %v", got, loginFlowMissingAuth) + } + }) + + t.Run("uses endpoint conflict flow when auth exists for a different endpoint", func(t *testing.T) { + params := loginParams{ + cfg: &config{Endpoint: "https://example.com", AccessToken: "x"}, + endpoint: "https://sourcegraph.example.com", + } + + if got, _ := selectLoginFlow(context.Background(), params); got != loginFlowEndpointConflict { + t.Fatalf("flow = %v, want %v", got, loginFlowEndpointConflict) + } + }) + + t.Run("uses validation flow when auth exists for the selected endpoint", func(t *testing.T) { + params := loginParams{ + cfg: &config{Endpoint: "https://example.com", AccessToken: "x"}, + endpoint: "https://example.com", + } + + if got, _ := selectLoginFlow(context.Background(), params); got != loginFlowValidate { + t.Fatalf("flow = %v, want %v", got, loginFlowValidate) + } + }) + + t.Run("treats stored oauth as effective auth", func(t *testing.T) { + restoreStoredOAuthLoader(t, func(context.Context, string) (*oauth.Token, error) { + return &oauth.Token{AccessToken: "oauth-token"}, nil + }) + + params := loginParams{ + cfg: &config{Endpoint: "https://example.com"}, + endpoint: "https://example.com", + } + + if got, _ := selectLoginFlow(context.Background(), params); got != loginFlowValidate { + t.Fatalf("flow = %v, want %v", got, loginFlowValidate) + } + }) +} + +func restoreStoredOAuthLoader(t *testing.T, loader func(context.Context, string) (*oauth.Token, error)) { + t.Helper() + + prev := loadStoredOAuthToken + loadStoredOAuthToken = loader + t.Cleanup(func() { + loadStoredOAuthToken = prev + }) +} diff --git a/cmd/src/login_validate.go b/cmd/src/login_validate.go new file mode 100644 index 0000000000..1a0ddfa050 --- /dev/null +++ b/cmd/src/login_validate.go @@ -0,0 +1,61 @@ +package main + +import ( + "context" + "fmt" + "io" + "strings" + + "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/cmderrors" +) + +func runMissingAuthLogin(_ context.Context, p loginParams) error { + endpointArg := cleanEndpoint(p.endpoint) + + fmt.Fprintln(p.out) + printLoginProblem(p.out, "No access token is configured.") + fmt.Fprintln(p.out, loginAccessTokenMessage(endpointArg)) + return cmderrors.ExitCode1 +} + +func runEndpointConflictLogin(_ context.Context, p loginParams) error { + endpointArg := cleanEndpoint(p.endpoint) + + fmt.Fprintln(p.out) + printLoginProblem(p.out, fmt.Sprintf("The configured endpoint is %s, not %s.", p.cfg.Endpoint, endpointArg)) + fmt.Fprintln(p.out, loginAccessTokenMessage(endpointArg)) + return cmderrors.ExitCode1 +} + +func runValidatedLogin(ctx context.Context, p loginParams) error { + return validateCurrentUser(ctx, p.client, p.out, cleanEndpoint(p.endpoint)) +} + +func validateCurrentUser(ctx context.Context, client api.Client, out io.Writer, endpointArg string) error { + query := `query CurrentUser { currentUser { username } }` + var result struct { + CurrentUser *struct{ Username string } + } + if _, err := client.NewRequest(query, nil).Do(ctx, &result); err != nil { + if strings.HasPrefix(err.Error(), "error: 401 Unauthorized") || strings.HasPrefix(err.Error(), "error: 403 Forbidden") { + printLoginProblem(out, "Invalid access token.") + } else { + printLoginProblem(out, fmt.Sprintf("Error communicating with %s: %s", endpointArg, err)) + } + fmt.Fprintln(out, loginAccessTokenMessage(endpointArg)) + fmt.Fprintln(out, " (If you need to supply custom HTTP request headers, see information about SRC_HEADER_* and SRC_HEADERS env vars at https://github.com/sourcegraph/src-cli/blob/main/AUTH_PROXY.md)") + return cmderrors.ExitCode1 + } + + if result.CurrentUser == nil { + // This should never happen; we verified there is an access token, so there should always be + // a user. + printLoginProblem(out, fmt.Sprintf("Unable to determine user on %s.", endpointArg)) + return cmderrors.ExitCode1 + } + fmt.Fprintln(out) + fmt.Fprintf(out, "✔︎ Authenticated as %s on %s\n", result.CurrentUser.Username, endpointArg) + fmt.Fprintln(out) + return nil +} From b5a055212ddc9f0796fbc40533dc269a81664a54 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Tue, 10 Mar 2026 10:47:33 +0200 Subject: [PATCH 546/647] refactor: refreshToken -> getToken (#1270) - fold getToken and refreshToken into one so that we reduce locking --- internal/oauth/http_transport.go | 26 ++++++++++---------------- 1 file changed, 10 insertions(+), 16 deletions(-) diff --git a/internal/oauth/http_transport.go b/internal/oauth/http_transport.go index d63d40ca44..1664c711f0 100644 --- a/internal/oauth/http_transport.go +++ b/internal/oauth/http_transport.go @@ -29,10 +29,10 @@ var storeRefreshedTokenFn = StoreToken func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) { ctx := req.Context() - if err := t.refreshToken(ctx); err != nil { + token, err := t.getToken(ctx) + if err != nil { return nil, err } - token := t.getToken() req2 := req.Clone(req.Context()) req2.Header.Set("Authorization", "Bearer "+token.AccessToken) @@ -43,25 +43,19 @@ func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) { return http.DefaultTransport.RoundTrip(req2) } -// getToken returns a value copy of token and is guarded by a mutex -func (t *Transport) getToken() Token { - t.mu.Lock() - defer t.mu.Unlock() - - return *t.Token -} - -// refreshToken checks if the token has expired or expiring soon and refreshes it. Once the token is -// refreshed, the in-memory token is updated and a best effort is made to store the token. -// If storing the token fails, no error is returned. -func (t *Transport) refreshToken(ctx context.Context) error { +// getToken returns a value copy of the token. If the token has expired or expiring soon it will be refreshed before returning. +// Once the token is refreshed, the in-memory token is updated and a best effort is made to store the token. +// +// If storing the token fails, no error is returned. An error is only returned if refreshing the token +// fails. +func (t *Transport) getToken(ctx context.Context) (Token, error) { t.mu.Lock() defer t.mu.Unlock() prevToken := t.Token token, err := maybeRefresh(ctx, t.Token) if err != nil { - return err + return Token{}, err } t.Token = token if token != prevToken { @@ -69,7 +63,7 @@ func (t *Transport) refreshToken(ctx context.Context) error { _ = storeRefreshedTokenFn(ctx, token) } - return nil + return *t.Token, nil } // maybeRefresh conditionally refreshes the token. If the token has expired or is expriing in the next 30s From 4c3f35653678631406ac18d3f68fec6a4ef4f833 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Tue, 10 Mar 2026 14:50:37 +0200 Subject: [PATCH 547/647] feat: dynamically start oauth flow if no SRC_ACCESS_TOKEN (#1271) * add AuthMode to config - AuthModeAccessToken and AuthModeOAuth - And check for CI and required AuthModeAccessToken * decide loginFlow based on config AuthMode * remove oauth flag * check for OAuth token precense before starting a new OAuth flow * remove unused ctx --- cmd/src/login.go | 51 ++++---------- cmd/src/login_oauth.go | 18 ++++- cmd/src/login_test.go | 139 ++++++++++++++++++++++++-------------- cmd/src/login_validate.go | 10 +-- cmd/src/main.go | 24 +++++++ cmd/src/main_test.go | 34 ++++++++++ internal/api/api.go | 2 +- 7 files changed, 181 insertions(+), 97 deletions(-) diff --git a/cmd/src/login.go b/cmd/src/login.go index c4989605f4..37e8bbe1bd 100644 --- a/cmd/src/login.go +++ b/cmd/src/login.go @@ -29,14 +29,9 @@ Examples: $ src login https://sourcegraph.com - Use OAuth device flow to authenticate: + If no access token is configured, 'src login' uses OAuth device flow automatically: - $ src login --oauth https://sourcegraph.com - - - Override the default client id used during device flow when authenticating: - - $ src login --oauth https://sourcegraph.com + $ src login https://sourcegraph.com ` flagSet := flag.NewFlagSet("login", flag.ExitOnError) @@ -47,7 +42,6 @@ Examples: var ( apiFlags = api.NewFlags(flagSet) - useOAuth = flagSet.Bool("oauth", false, "Use OAuth device flow to obtain an access token interactively") ) handler := func(args []string) error { @@ -69,7 +63,6 @@ Examples: client: client, endpoint: endpoint, out: os.Stdout, - useOAuth: *useOAuth, apiFlags: apiFlags, oauthClient: oauth.NewClient(oauth.DefaultClientID), }) @@ -87,7 +80,6 @@ type loginParams struct { client api.Client endpoint string out io.Writer - useOAuth bool apiFlags *api.Flags oauthClient oauth.Client } @@ -103,46 +95,31 @@ const ( loginFlowValidate ) -var loadStoredOAuthToken = oauth.LoadToken - func loginCmd(ctx context.Context, p loginParams) error { if p.cfg.ConfigFilePath != "" { fmt.Fprintln(p.out) fmt.Fprintf(p.out, "⚠️ Warning: Configuring src with a JSON file is deprecated. Please migrate to using the env vars SRC_ENDPOINT, SRC_ACCESS_TOKEN, and SRC_PROXY instead, and then remove %s. See https://github.com/sourcegraph/src-cli#readme for more information.\n", p.cfg.ConfigFilePath) } - _, flow := selectLoginFlow(ctx, p) + _, flow := selectLoginFlow(p) return flow(ctx, p) } -// selectLoginFlow decides what login flow to run based on flags and config. -func selectLoginFlow(ctx context.Context, p loginParams) (loginFlowKind, loginFlow) { +// selectLoginFlow decides what login flow to run based on configured AuthMode. +func selectLoginFlow(p loginParams) (loginFlowKind, loginFlow) { endpointArg := cleanEndpoint(p.endpoint) - if p.useOAuth { + switch p.cfg.AuthMode() { + case AuthModeOAuth: return loginFlowOAuth, runOAuthLogin - } - if !hasEffectiveAuth(ctx, p.cfg, endpointArg) { + case AuthModeAccessToken: + if endpointArg != p.cfg.Endpoint { + return loginFlowEndpointConflict, runEndpointConflictLogin + } + return loginFlowValidate, runValidatedLogin + default: return loginFlowMissingAuth, runMissingAuthLogin } - if endpointArg != p.cfg.Endpoint { - return loginFlowEndpointConflict, runEndpointConflictLogin - } - return loginFlowValidate, runValidatedLogin -} - -// hasEffectiveAuth determines whether we have auth credentials to continue. It first checks for a resolved Access Token in -// config, then it checks for a stored OAuth token. -func hasEffectiveAuth(ctx context.Context, cfg *config, resolvedEndpoint string) bool { - if cfg.AccessToken != "" { - return true - } - - if _, err := loadStoredOAuthToken(ctx, resolvedEndpoint); err == nil { - return true - } - - return false } func printLoginProblem(out io.Writer, problem string) { @@ -157,6 +134,6 @@ func loginAccessTokenMessage(endpoint string) string { To verify that it's working, run the login command again. - Alternatively, you can try logging in using OAuth by running: src login --oauth %s + Alternatively, you can try logging in interactively by running: src login %s `, endpoint, endpoint, endpoint) } diff --git a/cmd/src/login_oauth.go b/cmd/src/login_oauth.go index df3f912f62..95cf01a5bd 100644 --- a/cmd/src/login_oauth.go +++ b/cmd/src/login_oauth.go @@ -13,6 +13,8 @@ import ( "github.com/sourcegraph/src-cli/internal/oauth" ) +var loadStoredOAuthToken = oauth.LoadToken + func runOAuthLogin(ctx context.Context, p loginParams) error { endpointArg := cleanEndpoint(p.endpoint) client, err := oauthLoginClient(ctx, p, endpointArg) @@ -32,7 +34,15 @@ func runOAuthLogin(ctx context.Context, p loginParams) error { return nil } +// oauthLoginClient returns a api.Client with the OAuth token set. It will check secret storage for a token +// and use it if one is present. +// If no token is found, it will start a OAuth Device flow to get a token and storage in secret storage. func oauthLoginClient(ctx context.Context, p loginParams, endpoint string) (api.Client, error) { + // if we have a stored token, used it. Otherwise run the device flow + if token, err := loadStoredOAuthToken(ctx, endpoint); err == nil { + return newOAuthAPIClient(p, endpoint, token), nil + } + token, err := runOAuthDeviceFlow(ctx, endpoint, p.out, p.oauthClient) if err != nil { return nil, err @@ -43,15 +53,19 @@ func oauthLoginClient(ctx context.Context, p loginParams, endpoint string) (api. fmt.Fprintf(p.out, "⚠️ Warning: Failed to store token in keyring store: %q. Continuing with this session only.\n", err) } + return newOAuthAPIClient(p, endpoint, token), nil +} + +func newOAuthAPIClient(p loginParams, endpoint string, token *oauth.Token) api.Client { return api.NewClient(api.ClientOpts{ - Endpoint: p.cfg.Endpoint, + Endpoint: endpoint, AdditionalHeaders: p.cfg.AdditionalHeaders, Flags: p.apiFlags, Out: p.out, ProxyURL: p.cfg.ProxyURL, ProxyPath: p.cfg.ProxyPath, OAuthToken: token, - }), nil + }) } func runOAuthDeviceFlow(ctx context.Context, endpoint string, out io.Writer, client oauth.Client) (*oauth.Token, error) { diff --git a/cmd/src/login_test.go b/cmd/src/login_test.go index a34288576f..e909ff7310 100644 --- a/cmd/src/login_test.go +++ b/cmd/src/login_test.go @@ -9,6 +9,7 @@ import ( "net/http/httptest" "strings" "testing" + "time" "github.com/sourcegraph/src-cli/internal/cmderrors" "github.com/sourcegraph/src-cli/internal/oauth" @@ -18,51 +19,47 @@ func TestLogin(t *testing.T) { check := func(t *testing.T, cfg *config, endpointArg string) (output string, err error) { t.Helper() - restoreStoredOAuthLoader(t, func(context.Context, string) (*oauth.Token, error) { - return nil, fmt.Errorf("not found") - }) - var out bytes.Buffer err = loginCmd(context.Background(), loginParams{ cfg: cfg, client: cfg.apiClient(nil, io.Discard), endpoint: endpointArg, out: &out, - oauthClient: oauth.NewClient(oauth.DefaultClientID), + oauthClient: fakeOAuthClient{startErr: fmt.Errorf("oauth unavailable")}, }) return strings.TrimSpace(out.String()), err } t.Run("different endpoint in config vs. arg", func(t *testing.T) { out, err := check(t, &config{Endpoint: "https://example.com"}, "https://sourcegraph.example.com") - if err != cmderrors.ExitCode1 { + if err == nil { t.Fatal(err) } - wantOut := "❌ Problem: No access token is configured.\n\n🛠 To fix: Create an access token by going to https://sourcegraph.example.com/user/settings/tokens, then set the following environment variables in your terminal:\n\n export SRC_ENDPOINT=https://sourcegraph.example.com\n export SRC_ACCESS_TOKEN=(your access token)\n\n To verify that it's working, run the login command again.\n\n Alternatively, you can try logging in using OAuth by running: src login --oauth https://sourcegraph.example.com" - if out != wantOut { - t.Errorf("got output %q, want %q", out, wantOut) + if !strings.Contains(out, "OAuth Device flow authentication failed:") { + t.Errorf("got output %q, want oauth failure output", out) } }) - t.Run("no access token", func(t *testing.T) { + t.Run("no access token triggers oauth flow", func(t *testing.T) { out, err := check(t, &config{Endpoint: "https://example.com"}, "https://sourcegraph.example.com") - if err != cmderrors.ExitCode1 { + if err == nil { t.Fatal(err) } - wantOut := "❌ Problem: No access token is configured.\n\n🛠 To fix: Create an access token by going to https://sourcegraph.example.com/user/settings/tokens, then set the following environment variables in your terminal:\n\n export SRC_ENDPOINT=https://sourcegraph.example.com\n export SRC_ACCESS_TOKEN=(your access token)\n\n To verify that it's working, run the login command again.\n\n Alternatively, you can try logging in using OAuth by running: src login --oauth https://sourcegraph.example.com" - if out != wantOut { - t.Errorf("got output %q, want %q", out, wantOut) + if !strings.Contains(out, "OAuth Device flow authentication failed:") { + t.Errorf("got output %q, want oauth failure output", out) } }) t.Run("warning when using config file", func(t *testing.T) { out, err := check(t, &config{Endpoint: "https://example.com", ConfigFilePath: "f"}, "https://example.com") - if err != cmderrors.ExitCode1 { + if err == nil { t.Fatal(err) } - wantOut := "⚠️ Warning: Configuring src with a JSON file is deprecated. Please migrate to using the env vars SRC_ENDPOINT, SRC_ACCESS_TOKEN, and SRC_PROXY instead, and then remove f. See https://github.com/sourcegraph/src-cli#readme for more information.\n\n❌ Problem: No access token is configured.\n\n🛠 To fix: Create an access token by going to https://example.com/user/settings/tokens, then set the following environment variables in your terminal:\n\n export SRC_ENDPOINT=https://example.com\n export SRC_ACCESS_TOKEN=(your access token)\n\n To verify that it's working, run the login command again.\n\n Alternatively, you can try logging in using OAuth by running: src login --oauth https://example.com" - if out != wantOut { - t.Errorf("got output %q, want %q", out, wantOut) + if !strings.Contains(out, "Configuring src with a JSON file is deprecated") { + t.Errorf("got output %q, want deprecation warning", out) + } + if !strings.Contains(out, "OAuth Device flow authentication failed:") { + t.Errorf("got output %q, want oauth failure output", out) } }) @@ -77,7 +74,7 @@ func TestLogin(t *testing.T) { if err != cmderrors.ExitCode1 { t.Fatal(err) } - wantOut := "❌ Problem: Invalid access token.\n\n🛠 To fix: Create an access token by going to $ENDPOINT/user/settings/tokens, then set the following environment variables in your terminal:\n\n export SRC_ENDPOINT=$ENDPOINT\n export SRC_ACCESS_TOKEN=(your access token)\n\n To verify that it's working, run the login command again.\n\n Alternatively, you can try logging in using OAuth by running: src login --oauth $ENDPOINT\n\n (If you need to supply custom HTTP request headers, see information about SRC_HEADER_* and SRC_HEADERS env vars at https://github.com/sourcegraph/src-cli/blob/main/AUTH_PROXY.md)" + wantOut := "❌ Problem: Invalid access token.\n\n🛠 To fix: Create an access token by going to $ENDPOINT/user/settings/tokens, then set the following environment variables in your terminal:\n\n export SRC_ENDPOINT=$ENDPOINT\n export SRC_ACCESS_TOKEN=(your access token)\n\n To verify that it's working, run the login command again.\n\n Alternatively, you can try logging in interactively by running: src login $ENDPOINT\n\n (If you need to supply custom HTTP request headers, see information about SRC_HEADER_* and SRC_HEADERS env vars at https://github.com/sourcegraph/src-cli/blob/main/AUTH_PROXY.md)" wantOut = strings.ReplaceAll(wantOut, "$ENDPOINT", endpoint) if out != wantOut { t.Errorf("got output %q, want %q", out, wantOut) @@ -101,33 +98,86 @@ func TestLogin(t *testing.T) { t.Errorf("got output %q, want %q", out, wantOut) } }) -} -func TestSelectLoginFlow(t *testing.T) { - restoreStoredOAuthLoader(t, func(context.Context, string) (*oauth.Token, error) { - return nil, fmt.Errorf("not found") - }) + t.Run("reuses stored oauth token before device flow", func(t *testing.T) { + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fmt.Fprintln(w, `{"data":{"currentUser":{"username":"alice"}}}`) + })) + defer s.Close() - t.Run("uses oauth flow when oauth flag is set", func(t *testing.T) { - params := loginParams{ - cfg: &config{Endpoint: "https://example.com"}, - endpoint: "https://example.com", - useOAuth: true, - } + restoreStoredOAuthLoader(t, func(context.Context, string) (*oauth.Token, error) { + return &oauth.Token{ + Endpoint: s.URL, + ClientID: oauth.DefaultClientID, + AccessToken: "oauth-token", + ExpiresAt: time.Now().Add(time.Hour), + }, nil + }) - if got, _ := selectLoginFlow(context.Background(), params); got != loginFlowOAuth { - t.Fatalf("flow = %v, want %v", got, loginFlowOAuth) + startCalled := false + var out bytes.Buffer + err := loginCmd(context.Background(), loginParams{ + cfg: &config{Endpoint: s.URL}, + client: (&config{Endpoint: s.URL}).apiClient(nil, io.Discard), + endpoint: s.URL, + out: &out, + oauthClient: fakeOAuthClient{ + startErr: fmt.Errorf("unexpected call to Start"), + startCalled: &startCalled, + }, + }) + if err != nil { + t.Fatal(err) + } + if startCalled { + t.Fatal("expected stored oauth token to avoid device flow") + } + gotOut := strings.TrimSpace(out.String()) + wantOut := "✔︎ Authenticated as alice on $ENDPOINT\n\n\n✔︎ Authenticated with OAuth credentials" + wantOut = strings.ReplaceAll(wantOut, "$ENDPOINT", s.URL) + if gotOut != wantOut { + t.Errorf("got output %q, want %q", gotOut, wantOut) } }) +} + +type fakeOAuthClient struct { + startErr error + startCalled *bool +} + +func (f fakeOAuthClient) ClientID() string { + return oauth.DefaultClientID +} + +func (f fakeOAuthClient) Discover(context.Context, string) (*oauth.OIDCConfiguration, error) { + return nil, fmt.Errorf("unexpected call to Discover") +} + +func (f fakeOAuthClient) Start(context.Context, string, []string) (*oauth.DeviceAuthResponse, error) { + if f.startCalled != nil { + *f.startCalled = true + } + return nil, f.startErr +} + +func (f fakeOAuthClient) Poll(context.Context, string, string, time.Duration, int) (*oauth.TokenResponse, error) { + return nil, fmt.Errorf("unexpected call to Poll") +} + +func (f fakeOAuthClient) Refresh(context.Context, *oauth.Token) (*oauth.TokenResponse, error) { + return nil, fmt.Errorf("unexpected call to Refresh") +} - t.Run("uses missing auth flow when auth is unavailable", func(t *testing.T) { +func TestSelectLoginFlow(t *testing.T) { + t.Run("uses oauth flow when no access token is configured", func(t *testing.T) { params := loginParams{ cfg: &config{Endpoint: "https://example.com"}, endpoint: "https://sourcegraph.example.com", } - if got, _ := selectLoginFlow(context.Background(), params); got != loginFlowMissingAuth { - t.Fatalf("flow = %v, want %v", got, loginFlowMissingAuth) + if got, _ := selectLoginFlow(params); got != loginFlowOAuth { + t.Fatalf("flow = %v, want %v", got, loginFlowOAuth) } }) @@ -137,7 +187,7 @@ func TestSelectLoginFlow(t *testing.T) { endpoint: "https://sourcegraph.example.com", } - if got, _ := selectLoginFlow(context.Background(), params); got != loginFlowEndpointConflict { + if got, _ := selectLoginFlow(params); got != loginFlowEndpointConflict { t.Fatalf("flow = %v, want %v", got, loginFlowEndpointConflict) } }) @@ -148,22 +198,7 @@ func TestSelectLoginFlow(t *testing.T) { endpoint: "https://example.com", } - if got, _ := selectLoginFlow(context.Background(), params); got != loginFlowValidate { - t.Fatalf("flow = %v, want %v", got, loginFlowValidate) - } - }) - - t.Run("treats stored oauth as effective auth", func(t *testing.T) { - restoreStoredOAuthLoader(t, func(context.Context, string) (*oauth.Token, error) { - return &oauth.Token{AccessToken: "oauth-token"}, nil - }) - - params := loginParams{ - cfg: &config{Endpoint: "https://example.com"}, - endpoint: "https://example.com", - } - - if got, _ := selectLoginFlow(context.Background(), params); got != loginFlowValidate { + if got, _ := selectLoginFlow(params); got != loginFlowValidate { t.Fatalf("flow = %v, want %v", got, loginFlowValidate) } }) diff --git a/cmd/src/login_validate.go b/cmd/src/login_validate.go index 1a0ddfa050..c54a6df421 100644 --- a/cmd/src/login_validate.go +++ b/cmd/src/login_validate.go @@ -32,7 +32,7 @@ func runValidatedLogin(ctx context.Context, p loginParams) error { return validateCurrentUser(ctx, p.client, p.out, cleanEndpoint(p.endpoint)) } -func validateCurrentUser(ctx context.Context, client api.Client, out io.Writer, endpointArg string) error { +func validateCurrentUser(ctx context.Context, client api.Client, out io.Writer, endpoint string) error { query := `query CurrentUser { currentUser { username } }` var result struct { CurrentUser *struct{ Username string } @@ -41,9 +41,9 @@ func validateCurrentUser(ctx context.Context, client api.Client, out io.Writer, if strings.HasPrefix(err.Error(), "error: 401 Unauthorized") || strings.HasPrefix(err.Error(), "error: 403 Forbidden") { printLoginProblem(out, "Invalid access token.") } else { - printLoginProblem(out, fmt.Sprintf("Error communicating with %s: %s", endpointArg, err)) + printLoginProblem(out, fmt.Sprintf("Error communicating with %s: %s", endpoint, err)) } - fmt.Fprintln(out, loginAccessTokenMessage(endpointArg)) + fmt.Fprintln(out, loginAccessTokenMessage(endpoint)) fmt.Fprintln(out, " (If you need to supply custom HTTP request headers, see information about SRC_HEADER_* and SRC_HEADERS env vars at https://github.com/sourcegraph/src-cli/blob/main/AUTH_PROXY.md)") return cmderrors.ExitCode1 } @@ -51,11 +51,11 @@ func validateCurrentUser(ctx context.Context, client api.Client, out io.Writer, if result.CurrentUser == nil { // This should never happen; we verified there is an access token, so there should always be // a user. - printLoginProblem(out, fmt.Sprintf("Unable to determine user on %s.", endpointArg)) + printLoginProblem(out, fmt.Sprintf("Unable to determine user on %s.", endpoint)) return cmderrors.ExitCode1 } fmt.Fprintln(out) - fmt.Fprintf(out, "✔︎ Authenticated as %s on %s\n", result.CurrentUser.Username, endpointArg) + fmt.Fprintf(out, "✔︎ Authenticated as %s on %s\n", result.CurrentUser.Username, endpoint) fmt.Fprintln(out) return nil } diff --git a/cmd/src/main.go b/cmd/src/main.go index 41e5c55cd0..c7f2ff450c 100644 --- a/cmd/src/main.go +++ b/cmd/src/main.go @@ -82,6 +82,7 @@ var ( errConfigMerge = errors.New("when using a configuration file, zero or all environment variables must be set") errConfigAuthorizationConflict = errors.New("when passing an 'Authorization' additional headers, SRC_ACCESS_TOKEN must never be set") + errCIAccessTokenRequired = errors.New("SRC_ACCESS_TOKEN must be set in CI") ) // commands contains all registered subcommands. @@ -122,6 +123,20 @@ type config struct { ConfigFilePath string } +type AuthMode int + +const ( + AuthModeOAuth AuthMode = iota + AuthModeAccessToken +) + +func (c *config) AuthMode() AuthMode { + if c.AccessToken != "" { + return AuthModeAccessToken + } + return AuthModeOAuth +} + // apiClient returns an api.Client built from the configuration. func (c *config) apiClient(flags *api.Flags, out io.Writer) api.Client { opts := api.ClientOpts{ @@ -260,9 +275,18 @@ func readConfig() (*config, error) { cfg.Endpoint = cleanEndpoint(cfg.Endpoint) + if isCI() && cfg.AccessToken == "" { + return nil, errCIAccessTokenRequired + } + return &cfg, nil } +func isCI() bool { + value, ok := os.LookupEnv("CI") + return ok && value != "" +} + func cleanEndpoint(urlStr string) string { return strings.TrimSuffix(urlStr, "/") } diff --git a/cmd/src/main_test.go b/cmd/src/main_test.go index c37c36792a..a2656b1929 100644 --- a/cmd/src/main_test.go +++ b/cmd/src/main_test.go @@ -30,6 +30,7 @@ func TestReadConfig(t *testing.T) { tests := []struct { name string fileContents *config + envCI string envToken string envFooHeader string envHeaders string @@ -283,6 +284,24 @@ func TestReadConfig(t *testing.T) { envHeaders: "Authorization:Bearer", wantErr: errConfigAuthorizationConflict.Error(), }, + { + name: "CI requires access token", + envCI: "1", + wantErr: errCIAccessTokenRequired.Error(), + }, + { + name: "CI allows access token from config file", + envCI: "1", + fileContents: &config{ + Endpoint: "https://example.com/", + AccessToken: "deadbeef", + }, + want: &config{ + Endpoint: "https://example.com", + AccessToken: "deadbeef", + AdditionalHeaders: map[string]string{}, + }, + }, } for _, test := range tests { @@ -297,6 +316,7 @@ func TestReadConfig(t *testing.T) { setEnv("SRC_ACCESS_TOKEN", test.envToken) setEnv("SRC_ENDPOINT", test.envEndpoint) setEnv("SRC_PROXY", test.envProxy) + setEnv("CI", test.envCI) tmpDir := t.TempDir() testHomeDir = tmpDir @@ -345,3 +365,17 @@ func TestReadConfig(t *testing.T) { }) } } + +func TestConfigAuthMode(t *testing.T) { + t.Run("oauth when access token is empty", func(t *testing.T) { + if got := (&config{}).AuthMode(); got != AuthModeOAuth { + t.Fatalf("AuthMode() = %v, want %v", got, AuthModeOAuth) + } + }) + + t.Run("access token when configured", func(t *testing.T) { + if got := (&config{AccessToken: "token"}).AuthMode(); got != AuthModeAccessToken { + t.Fatalf("AuthMode() = %v, want %v", got, AuthModeAccessToken) + } + }) +} diff --git a/internal/api/api.go b/internal/api/api.go index ef9f822a7a..adc6af53d5 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -269,7 +269,7 @@ func (r *request) do(ctx context.Context, result any) (bool, error) { if oauth.IsOAuthTransport(r.client.httpClient.Transport) { fmt.Println("The OAuth token is invalid. Please check that the Sourcegraph CLI client is still authorized.") fmt.Println("") - fmt.Printf("To re-authorize, run: src login --oauth %s\n", r.client.opts.Endpoint) + fmt.Printf("To re-authorize, run: src login %s\n", r.client.opts.Endpoint) fmt.Println("") fmt.Println("Learn more at https://github.com/sourcegraph/src-cli#readme") fmt.Println("") From 22191a7a1d67918c62ed56b3bbde819ac3a07010 Mon Sep 17 00:00:00 2001 From: Vincent Date: Tue, 10 Mar 2026 16:41:34 +0000 Subject: [PATCH 548/647] fix/security: prevent command injection on windows (#1272) --- cmd/src/login_oauth.go | 33 +++++++++++++++++---- cmd/src/login_test.go | 66 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 93 insertions(+), 6 deletions(-) diff --git a/cmd/src/login_oauth.go b/cmd/src/login_oauth.go index 95cf01a5bd..5074083da8 100644 --- a/cmd/src/login_oauth.go +++ b/cmd/src/login_oauth.go @@ -4,10 +4,12 @@ import ( "context" "fmt" "io" + "net/url" "os/exec" "runtime" "time" + "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/cmderrors" "github.com/sourcegraph/src-cli/internal/oauth" @@ -103,20 +105,39 @@ func runOAuthDeviceFlow(ctx context.Context, endpoint string, out io.Writer, cli return token, nil } -func openInBrowser(url string) error { - if url == "" { +// validateBrowserURL checks that rawURL is a valid HTTP(S) URL to prevent +// command injection via malicious URLs returned by an OAuth server. +func validateBrowserURL(rawURL string) error { + u, err := url.Parse(rawURL) + if err != nil { + return errors.Wrapf(err, "invalid URL: %s", rawURL) + } + if u.Scheme != "http" && u.Scheme != "https" { + return errors.Newf("unsupported URL scheme %q: only http and https are allowed", u.Scheme) + } + if u.Host == "" { + return errors.New("URL has no host") + } + return nil +} + +func openInBrowser(rawURL string) error { + if rawURL == "" { return nil } + if err := validateBrowserURL(rawURL); err != nil { + return err + } + var cmd *exec.Cmd switch runtime.GOOS { case "darwin": - cmd = exec.Command("open", url) + cmd = exec.Command("open", rawURL) case "windows": - // "start" is a cmd.exe built-in; the empty string is the window title. - cmd = exec.Command("cmd", "/c", "start", "", url) + cmd = exec.Command("rundll32", "url.dll,OpenURL", rawURL) default: - cmd = exec.Command("xdg-open", url) + cmd = exec.Command("xdg-open", rawURL) } return cmd.Run() } diff --git a/cmd/src/login_test.go b/cmd/src/login_test.go index e909ff7310..6577c19f9e 100644 --- a/cmd/src/login_test.go +++ b/cmd/src/login_test.go @@ -204,6 +204,72 @@ func TestSelectLoginFlow(t *testing.T) { }) } +func TestValidateBrowserURL(t *testing.T) { + tests := []struct { + name string + url string + wantErr bool + }{ + {name: "valid https", url: "https://example.com/device?code=ABC", wantErr: false}, + {name: "valid http", url: "http://localhost:3080/auth", wantErr: false}, + {name: "command injection ampersand", url: "https://example.com & calc.exe", wantErr: true}, + {name: "command injection pipe", url: "https://x | powershell -enc ZABp", wantErr: true}, + {name: "file scheme", url: "file:///etc/passwd", wantErr: true}, + {name: "javascript scheme", url: "javascript:alert(1)", wantErr: true}, + {name: "empty scheme", url: "://no-scheme", wantErr: true}, + {name: "no host", url: "https://", wantErr: true}, + {name: "relative path", url: "/https/github.com/just/a/path", wantErr: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := validateBrowserURL(tt.url) + if (err != nil) != tt.wantErr { + t.Errorf("validateBrowserURL(%q) error = %v, wantErr %v", tt.url, err, tt.wantErr) + } + }) + } +} + +// TestValidateBrowserURL_WindowsRundll32Escape tests that validateBrowserURL blocks +// payloads that could abuse the Windows "rundll32 url.dll,OpenURL" browser opener +// (LOLBAS T1218.011). If any of these cases pass validation, an attacker-controlled +// URL could execute arbitrary files via rundll32. +// Reference: https://lolbas-project.github.io/lolbas/Libraries/Url/ +func TestValidateBrowserURL_WindowsRundll32Escape(t *testing.T) { + tests := []struct { + name string + url string + }{ + // url.dll OpenURL can launch .hta payloads via mshta.exe + {name: "hta via file protocol", url: "file:///C:/Temp/payload.hta"}, + // url.dll OpenURL can launch executables from .url shortcut files + {name: "url shortcut file", url: "file:///C:/Temp/launcher.url"}, + // url.dll OpenURL / FileProtocolHandler can run executables directly + {name: "exe via file protocol", url: "file:///C:/Windows/System32/calc.exe"}, + // Obfuscated file protocol handler variant + {name: "obfuscated file handler", url: "file:///C:/Temp/payload.exe"}, + // UNC path via file scheme to remote payload + {name: "unc path file scheme", url: "file://attacker.com/share/payload.exe"}, + // data: URI could be passed through to a handler + {name: "data uri", url: "data:text/html,"}, + // vbscript scheme + {name: "vbscript scheme", url: "vbscript:Execute(\"MsgBox(1)\")"}, + // about scheme + {name: "about scheme", url: "about:blank"}, + // ms-msdt protocol handler (Follina-style) + {name: "ms-msdt handler", url: "ms-msdt:/id PCWDiagnostic /skip force /param"}, + // search-ms protocol handler + {name: "search-ms handler", url: "search-ms:query=calc&crumb=location:\\\\attacker.com\\share"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if err := validateBrowserURL(tt.url); err == nil { + t.Errorf("validateBrowserURL(%q) = nil; want error (payload must be blocked to prevent rundll32 url.dll,OpenURL abuse)", tt.url) + } + }) + } +} + func restoreStoredOAuthLoader(t *testing.T, loader func(context.Context, string) (*oauth.Token, error)) { t.Helper() From 0e7f657eaca307dbae5b26280161cd7001690b86 Mon Sep 17 00:00:00 2001 From: Peter Guy Date: Thu, 12 Mar 2026 22:24:56 -0700 Subject: [PATCH 549/647] refactor: validate and parse the endpoint and proxy at program load (#1267) * refactor: validate and parse the endpoint and proxy at program load Amp-Thread-ID: https://ampcode.com/threads/T-019cdb3f-f7de-750b-b4c3-13762c7dfc11 Co-authored-by: Amp * Update internal/oauth/flow.go Co-authored-by: William Bezuidenhout --------- Co-authored-by: Amp Co-authored-by: William Bezuidenhout --- cmd/src/batch_common.go | 4 +- cmd/src/batch_remote.go | 16 +- cmd/src/batch_repositories.go | 2 +- cmd/src/code_intel_upload.go | 26 +-- cmd/src/debug_compose.go | 2 +- cmd/src/debug_kube.go | 2 +- cmd/src/debug_server.go | 2 +- cmd/src/login.go | 54 +++--- cmd/src/login_oauth.go | 35 ++-- cmd/src/login_test.go | 76 ++++---- cmd/src/login_validate.go | 23 +-- cmd/src/main.go | 123 +++++++----- cmd/src/main_test.go | 215 ++++++++++++--------- cmd/src/search.go | 2 +- cmd/src/search_jobs.go | 4 +- cmd/src/search_jobs_logs.go | 2 +- cmd/src/search_jobs_results.go | 2 +- cmd/src/search_stream.go | 6 +- cmd/src/search_stream_test.go | 4 +- cmd/src/users_prune.go | 4 +- internal/api/api.go | 12 +- internal/batches/executor/executor_test.go | 7 +- internal/batches/repozip/fetcher_test.go | 16 +- internal/oauth/flow.go | 50 +++-- internal/oauth/flow_test.go | 40 ++-- internal/oauth/http_transport.go | 14 +- internal/secrets/keyring.go | 6 +- internal/secrets/keyring_test.go | 17 +- 28 files changed, 441 insertions(+), 325 deletions(-) diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index 21fdce2e21..e294347dcf 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -537,7 +537,7 @@ func executeBatchSpec(ctx context.Context, opts executeBatchSpecOpts) (err error if err != nil { return execUI.CreatingBatchSpecError(lr.MaxUnlicensedChangesets, err) } - previewURL := cfg.Endpoint + url + previewURL := cfg.endpointURL.JoinPath(url).String() execUI.CreatingBatchSpecSuccess(previewURL) hasWorkspaceFiles := false @@ -567,7 +567,7 @@ func executeBatchSpec(ctx context.Context, opts executeBatchSpecOpts) (err error if err != nil { return err } - execUI.ApplyingBatchSpecSuccess(cfg.Endpoint + batch.URL) + execUI.ApplyingBatchSpecSuccess(cfg.endpointURL.JoinPath(batch.URL).String()) return nil } diff --git a/cmd/src/batch_remote.go b/cmd/src/batch_remote.go index 7dd7628c03..c1d7209675 100644 --- a/cmd/src/batch_remote.go +++ b/cmd/src/batch_remote.go @@ -5,7 +5,6 @@ import ( "flag" "fmt" cliLog "log" - "strings" "time" "github.com/sourcegraph/sourcegraph/lib/errors" @@ -155,13 +154,14 @@ Examples: } ui.ExecutingBatchSpecSuccess() - executionURL := fmt.Sprintf( - "%s/%s/batch-changes/%s/executions/%s", - strings.TrimSuffix(cfg.Endpoint, "/"), - strings.TrimPrefix(namespace.URL, "/"), - batchChangeName, - batchSpecID, - ) + executionURL := cfg.endpointURL.JoinPath( + fmt.Sprintf( + "%s/batch-changes/%s/executions/%s", + namespace.URL, + batchChangeName, + batchSpecID, + ), + ).String() ui.RemoteSuccess(executionURL) return nil diff --git a/cmd/src/batch_repositories.go b/cmd/src/batch_repositories.go index b02a4f5e58..97a7ea6cfe 100644 --- a/cmd/src/batch_repositories.go +++ b/cmd/src/batch_repositories.go @@ -131,7 +131,7 @@ Examples: Max: max, RepoCount: len(repos), Repos: repos, - SourcegraphEndpoint: cfg.Endpoint, + SourcegraphEndpoint: cfg.endpointURL.String(), }); err != nil { return err } diff --git a/cmd/src/code_intel_upload.go b/cmd/src/code_intel_upload.go index 303e2199e0..d5e686babc 100644 --- a/cmd/src/code_intel_upload.go +++ b/cmd/src/code_intel_upload.go @@ -7,7 +7,6 @@ import ( "flag" "fmt" "io" - "net/url" "os" "strings" "time" @@ -87,10 +86,7 @@ func handleCodeIntelUpload(args []string) error { return handleUploadError(uploadOptions.SourcegraphInstanceOptions.AccessToken, err) } - uploadURL, err := makeCodeIntelUploadURL(uploadID) - if err != nil { - return err - } + uploadURL := makeCodeIntelUploadURL(uploadID) if codeintelUploadFlags.json { serialized, err := json.Marshal(map[string]any{ @@ -132,7 +128,7 @@ func codeintelUploadOptions(out *output.Output) upload.UploadOptions { associatedIndexID = &codeintelUploadFlags.associatedIndexID } - cfg.AdditionalHeaders["Content-Type"] = "application/x-protobuf+scip" + cfg.additionalHeaders["Content-Type"] = "application/x-protobuf+scip" logger := upload.NewRequestLogger( os.Stdout, @@ -153,9 +149,9 @@ func codeintelUploadOptions(out *output.Output) upload.UploadOptions { AssociatedIndexID: associatedIndexID, }, SourcegraphInstanceOptions: upload.SourcegraphInstanceOptions{ - SourcegraphURL: cfg.Endpoint, - AccessToken: cfg.AccessToken, - AdditionalHeaders: cfg.AdditionalHeaders, + SourcegraphURL: cfg.endpointURL.String(), + AccessToken: cfg.accessToken, + AdditionalHeaders: cfg.additionalHeaders, MaxRetries: 5, RetryInterval: time.Second, Path: codeintelUploadFlags.uploadRoute, @@ -191,16 +187,12 @@ func printInferredArguments(out *output.Output) { // makeCodeIntelUploadURL constructs a URL to the upload with the given internal identifier. // The base of the URL is constructed from the configured Sourcegraph instance. -func makeCodeIntelUploadURL(uploadID int) (string, error) { - url, err := url.Parse(cfg.Endpoint) - if err != nil { - return "", err - } - +func makeCodeIntelUploadURL(uploadID int) string { + // Careful: copy by dereference makes a shallow copy, so User is not duplicated. + url := *cfg.endpointURL 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 + return url.String() } type errorWithHint struct { diff --git a/cmd/src/debug_compose.go b/cmd/src/debug_compose.go index 8e26d95b04..32c746065d 100644 --- a/cmd/src/debug_compose.go +++ b/cmd/src/debug_compose.go @@ -75,7 +75,7 @@ Examples: return errors.Wrap(err, "failed to get containers for subcommand with err") } // Safety check user knows what they are targeting with this debug command - log.Printf("This command will archive docker-cli data for %d containers\n SRC_ENDPOINT: %v\n Output filename: %v", len(containers), cfg.Endpoint, base) + log.Printf("This command will archive docker-cli data for %d containers\n SRC_ENDPOINT: %v\n Output filename: %v", len(containers), cfg.endpointURL, base) if verified, _ := verify("Do you want to start writing to an archive?"); !verified { return nil } diff --git a/cmd/src/debug_kube.go b/cmd/src/debug_kube.go index 69af7571e9..24f0b955c0 100644 --- a/cmd/src/debug_kube.go +++ b/cmd/src/debug_kube.go @@ -84,7 +84,7 @@ Examples: return errors.Wrapf(err, "failed to get current-context") } // Safety check user knows what they've targeted with this command - log.Printf("Archiving kubectl data for %d pods\n SRC_ENDPOINT: %v\n Context: %s Namespace: %v\n Output filename: %v", len(pods.Items), cfg.Endpoint, kubectx, namespace, base) + log.Printf("Archiving kubectl data for %d pods\n SRC_ENDPOINT: %v\n Context: %s Namespace: %v\n Output filename: %v", len(pods.Items), cfg.endpointURL, kubectx, namespace, base) if verified, _ := verify("Do you want to start writing to an archive?"); !verified { return nil } diff --git a/cmd/src/debug_server.go b/cmd/src/debug_server.go index 8ef59fc02a..d219ec7fdb 100644 --- a/cmd/src/debug_server.go +++ b/cmd/src/debug_server.go @@ -72,7 +72,7 @@ Examples: defer zw.Close() // Safety check user knows what they are targeting with this debug command - log.Printf("This command will archive docker-cli data for container: %s\n SRC_ENDPOINT: %s\n Output filename: %s", container, cfg.Endpoint, base) + log.Printf("This command will archive docker-cli data for container: %s\n SRC_ENDPOINT: %s\n Output filename: %s", container, cfg.endpointURL, base) if verified, _ := verify("Do you want to start writing to an archive?"); !verified { return nil } diff --git a/cmd/src/login.go b/cmd/src/login.go index 37e8bbe1bd..60cc1698b6 100644 --- a/cmd/src/login.go +++ b/cmd/src/login.go @@ -5,6 +5,7 @@ import ( "flag" "fmt" "io" + "net/url" "os" "github.com/sourcegraph/src-cli/internal/api" @@ -48,23 +49,26 @@ Examples: if err := flagSet.Parse(args); err != nil { return err } - endpoint := cfg.Endpoint + + var loginEndpointURL *url.URL if flagSet.NArg() >= 1 { - endpoint = flagSet.Arg(0) - } - if endpoint == "" { - return cmderrors.Usage("expected exactly one argument: the Sourcegraph URL, or SRC_ENDPOINT to be set") + arg := flagSet.Arg(0) + u, err := parseEndpoint(arg) + if err != nil { + return cmderrors.Usage(fmt.Sprintf("invalid endpoint URL: %s", arg)) + } + loginEndpointURL = u } client := cfg.apiClient(apiFlags, io.Discard) return loginCmd(context.Background(), loginParams{ - cfg: cfg, - client: client, - endpoint: endpoint, - out: os.Stdout, - apiFlags: apiFlags, - oauthClient: oauth.NewClient(oauth.DefaultClientID), + cfg: cfg, + client: client, + out: os.Stdout, + apiFlags: apiFlags, + oauthClient: oauth.NewClient(oauth.DefaultClientID), + loginEndpointURL: loginEndpointURL, }) } @@ -76,12 +80,12 @@ Examples: } type loginParams struct { - cfg *config - client api.Client - endpoint string - out io.Writer - apiFlags *api.Flags - oauthClient oauth.Client + cfg *config + client api.Client + out io.Writer + apiFlags *api.Flags + oauthClient oauth.Client + loginEndpointURL *url.URL } type loginFlow func(context.Context, loginParams) error @@ -96,9 +100,9 @@ const ( ) func loginCmd(ctx context.Context, p loginParams) error { - if p.cfg.ConfigFilePath != "" { + if p.cfg.configFilePath != "" { fmt.Fprintln(p.out) - fmt.Fprintf(p.out, "⚠️ Warning: Configuring src with a JSON file is deprecated. Please migrate to using the env vars SRC_ENDPOINT, SRC_ACCESS_TOKEN, and SRC_PROXY instead, and then remove %s. See https://github.com/sourcegraph/src-cli#readme for more information.\n", p.cfg.ConfigFilePath) + fmt.Fprintf(p.out, "⚠️ Warning: Configuring src with a JSON file is deprecated. Please migrate to using the env vars SRC_ENDPOINT, SRC_ACCESS_TOKEN, and SRC_PROXY instead, and then remove %s. See https://github.com/sourcegraph/src-cli#readme for more information.\n", p.cfg.configFilePath) } _, flow := selectLoginFlow(p) @@ -107,15 +111,13 @@ func loginCmd(ctx context.Context, p loginParams) error { // selectLoginFlow decides what login flow to run based on configured AuthMode. func selectLoginFlow(p loginParams) (loginFlowKind, loginFlow) { - endpointArg := cleanEndpoint(p.endpoint) - + if p.loginEndpointURL != nil && p.loginEndpointURL.String() != p.cfg.endpointURL.String() { + return loginFlowEndpointConflict, runEndpointConflictLogin + } switch p.cfg.AuthMode() { case AuthModeOAuth: return loginFlowOAuth, runOAuthLogin case AuthModeAccessToken: - if endpointArg != p.cfg.Endpoint { - return loginFlowEndpointConflict, runEndpointConflictLogin - } return loginFlowValidate, runValidatedLogin default: return loginFlowMissingAuth, runMissingAuthLogin @@ -126,7 +128,7 @@ func printLoginProblem(out io.Writer, problem string) { fmt.Fprintf(out, "❌ Problem: %s\n", problem) } -func loginAccessTokenMessage(endpoint string) string { +func loginAccessTokenMessage(endpointURL *url.URL) string { return fmt.Sprintf("\n"+`🛠 To fix: Create an access token by going to %s/user/settings/tokens, then set the following environment variables in your terminal: export SRC_ENDPOINT=%s @@ -135,5 +137,5 @@ func loginAccessTokenMessage(endpoint string) string { To verify that it's working, run the login command again. Alternatively, you can try logging in interactively by running: src login %s -`, endpoint, endpoint, endpoint) +`, endpointURL, endpointURL, endpointURL) } diff --git a/cmd/src/login_oauth.go b/cmd/src/login_oauth.go index 5074083da8..1e404d6447 100644 --- a/cmd/src/login_oauth.go +++ b/cmd/src/login_oauth.go @@ -18,15 +18,14 @@ import ( var loadStoredOAuthToken = oauth.LoadToken func runOAuthLogin(ctx context.Context, p loginParams) error { - endpointArg := cleanEndpoint(p.endpoint) - client, err := oauthLoginClient(ctx, p, endpointArg) + client, err := oauthLoginClient(ctx, p) if err != nil { printLoginProblem(p.out, fmt.Sprintf("OAuth Device flow authentication failed: %s", err)) - fmt.Fprintln(p.out, loginAccessTokenMessage(endpointArg)) + fmt.Fprintln(p.out, loginAccessTokenMessage(p.cfg.endpointURL)) return cmderrors.ExitCode1 } - if err := validateCurrentUser(ctx, client, p.out, endpointArg); err != nil { + if err := validateCurrentUser(ctx, client, p.out, p.cfg.endpointURL); err != nil { return err } @@ -39,13 +38,13 @@ func runOAuthLogin(ctx context.Context, p loginParams) error { // oauthLoginClient returns a api.Client with the OAuth token set. It will check secret storage for a token // and use it if one is present. // If no token is found, it will start a OAuth Device flow to get a token and storage in secret storage. -func oauthLoginClient(ctx context.Context, p loginParams, endpoint string) (api.Client, error) { +func oauthLoginClient(ctx context.Context, p loginParams) (api.Client, error) { // if we have a stored token, used it. Otherwise run the device flow - if token, err := loadStoredOAuthToken(ctx, endpoint); err == nil { - return newOAuthAPIClient(p, endpoint, token), nil + if token, err := loadStoredOAuthToken(ctx, p.cfg.endpointURL); err == nil { + return newOAuthAPIClient(p, token), nil } - token, err := runOAuthDeviceFlow(ctx, endpoint, p.out, p.oauthClient) + token, err := runOAuthDeviceFlow(ctx, p.cfg.endpointURL, p.out, p.oauthClient) if err != nil { return nil, err } @@ -55,23 +54,23 @@ func oauthLoginClient(ctx context.Context, p loginParams, endpoint string) (api. fmt.Fprintf(p.out, "⚠️ Warning: Failed to store token in keyring store: %q. Continuing with this session only.\n", err) } - return newOAuthAPIClient(p, endpoint, token), nil + return newOAuthAPIClient(p, token), nil } -func newOAuthAPIClient(p loginParams, endpoint string, token *oauth.Token) api.Client { +func newOAuthAPIClient(p loginParams, token *oauth.Token) api.Client { return api.NewClient(api.ClientOpts{ - Endpoint: endpoint, - AdditionalHeaders: p.cfg.AdditionalHeaders, + EndpointURL: p.cfg.endpointURL, + AdditionalHeaders: p.cfg.additionalHeaders, Flags: p.apiFlags, Out: p.out, - ProxyURL: p.cfg.ProxyURL, - ProxyPath: p.cfg.ProxyPath, + ProxyURL: p.cfg.proxyURL, + ProxyPath: p.cfg.proxyPath, OAuthToken: token, }) } -func runOAuthDeviceFlow(ctx context.Context, endpoint string, out io.Writer, client oauth.Client) (*oauth.Token, error) { - authResp, err := client.Start(ctx, endpoint, nil) +func runOAuthDeviceFlow(ctx context.Context, endpointURL *url.URL, out io.Writer, client oauth.Client) (*oauth.Token, error) { + authResp, err := client.Start(ctx, endpointURL, nil) if err != nil { return nil, err } @@ -95,12 +94,12 @@ func runOAuthDeviceFlow(ctx context.Context, endpoint string, out io.Writer, cli interval = 5 * time.Second } - resp, err := client.Poll(ctx, endpoint, authResp.DeviceCode, interval, authResp.ExpiresIn) + resp, err := client.Poll(ctx, endpointURL, authResp.DeviceCode, interval, authResp.ExpiresIn) if err != nil { return nil, err } - token := resp.Token(endpoint) + token := resp.Token(endpointURL) token.ClientID = client.ClientID() return token, nil } diff --git a/cmd/src/login_test.go b/cmd/src/login_test.go index 6577c19f9e..85e79816b2 100644 --- a/cmd/src/login_test.go +++ b/cmd/src/login_test.go @@ -7,6 +7,7 @@ import ( "io" "net/http" "net/http/httptest" + "net/url" "strings" "testing" "time" @@ -15,33 +16,43 @@ import ( "github.com/sourcegraph/src-cli/internal/oauth" ) +func mustParseURL(t *testing.T, raw string) *url.URL { + t.Helper() + u, err := url.Parse(raw) + if err != nil { + t.Fatalf("failed to parse URL %q: %v", raw, err) + } + return u +} + func TestLogin(t *testing.T) { - check := func(t *testing.T, cfg *config, endpointArg string) (output string, err error) { + check := func(t *testing.T, cfg *config, endpointArgURL *url.URL) (output string, err error) { t.Helper() var out bytes.Buffer err = loginCmd(context.Background(), loginParams{ - cfg: cfg, - client: cfg.apiClient(nil, io.Discard), - endpoint: endpointArg, - out: &out, - oauthClient: fakeOAuthClient{startErr: fmt.Errorf("oauth unavailable")}, + cfg: cfg, + client: cfg.apiClient(nil, io.Discard), + out: &out, + oauthClient: fakeOAuthClient{startErr: fmt.Errorf("oauth unavailable")}, + loginEndpointURL: endpointArgURL, }) return strings.TrimSpace(out.String()), err } t.Run("different endpoint in config vs. arg", func(t *testing.T) { - out, err := check(t, &config{Endpoint: "https://example.com"}, "https://sourcegraph.example.com") + out, err := check(t, &config{endpointURL: &url.URL{Scheme: "https", Host: "example.com"}}, &url.URL{Scheme: "https", Host: "sourcegraph.example.com"}) if err == nil { t.Fatal(err) } - if !strings.Contains(out, "OAuth Device flow authentication failed:") { - t.Errorf("got output %q, want oauth failure output", out) + if !strings.Contains(out, "The configured endpoint is https://example.com, not https://sourcegraph.example.com.") { + t.Errorf("got output %q, want configured endpoint error", out) } }) t.Run("no access token triggers oauth flow", func(t *testing.T) { - out, err := check(t, &config{Endpoint: "https://example.com"}, "https://sourcegraph.example.com") + u := &url.URL{Scheme: "https", Host: "example.com"} + out, err := check(t, &config{endpointURL: u}, u) if err == nil { t.Fatal(err) } @@ -51,8 +62,9 @@ func TestLogin(t *testing.T) { }) t.Run("warning when using config file", func(t *testing.T) { - out, err := check(t, &config{Endpoint: "https://example.com", ConfigFilePath: "f"}, "https://example.com") - if err == nil { + endpoint := &url.URL{Scheme: "https", Host: "example.com"} + out, err := check(t, &config{endpointURL: endpoint, configFilePath: "f"}, endpoint) + if err != cmderrors.ExitCode1 { t.Fatal(err) } if !strings.Contains(out, "Configuring src with a JSON file is deprecated") { @@ -69,13 +81,13 @@ func TestLogin(t *testing.T) { })) defer s.Close() - endpoint := s.URL - out, err := check(t, &config{Endpoint: endpoint, AccessToken: "x"}, endpoint) + u := mustParseURL(t, s.URL) + out, err := check(t, &config{endpointURL: u, accessToken: "x"}, u) if err != cmderrors.ExitCode1 { t.Fatal(err) } wantOut := "❌ Problem: Invalid access token.\n\n🛠 To fix: Create an access token by going to $ENDPOINT/user/settings/tokens, then set the following environment variables in your terminal:\n\n export SRC_ENDPOINT=$ENDPOINT\n export SRC_ACCESS_TOKEN=(your access token)\n\n To verify that it's working, run the login command again.\n\n Alternatively, you can try logging in interactively by running: src login $ENDPOINT\n\n (If you need to supply custom HTTP request headers, see information about SRC_HEADER_* and SRC_HEADERS env vars at https://github.com/sourcegraph/src-cli/blob/main/AUTH_PROXY.md)" - wantOut = strings.ReplaceAll(wantOut, "$ENDPOINT", endpoint) + wantOut = strings.ReplaceAll(wantOut, "$ENDPOINT", s.URL) if out != wantOut { t.Errorf("got output %q, want %q", out, wantOut) } @@ -87,13 +99,13 @@ func TestLogin(t *testing.T) { })) defer s.Close() - endpoint := s.URL - out, err := check(t, &config{Endpoint: endpoint, AccessToken: "x"}, endpoint) + u := mustParseURL(t, s.URL) + out, err := check(t, &config{endpointURL: u, accessToken: "x"}, u) if err != nil { t.Fatal(err) } wantOut := "✔︎ Authenticated as alice on $ENDPOINT" - wantOut = strings.ReplaceAll(wantOut, "$ENDPOINT", endpoint) + wantOut = strings.ReplaceAll(wantOut, "$ENDPOINT", s.URL) if out != wantOut { t.Errorf("got output %q, want %q", out, wantOut) } @@ -105,7 +117,7 @@ func TestLogin(t *testing.T) { })) defer s.Close() - restoreStoredOAuthLoader(t, func(context.Context, string) (*oauth.Token, error) { + restoreStoredOAuthLoader(t, func(_ context.Context, _ *url.URL) (*oauth.Token, error) { return &oauth.Token{ Endpoint: s.URL, ClientID: oauth.DefaultClientID, @@ -114,13 +126,13 @@ func TestLogin(t *testing.T) { }, nil }) + u, _ := url.ParseRequestURI(s.URL) startCalled := false var out bytes.Buffer err := loginCmd(context.Background(), loginParams{ - cfg: &config{Endpoint: s.URL}, - client: (&config{Endpoint: s.URL}).apiClient(nil, io.Discard), - endpoint: s.URL, - out: &out, + cfg: &config{endpointURL: u}, + client: (&config{endpointURL: u}).apiClient(nil, io.Discard), + out: &out, oauthClient: fakeOAuthClient{ startErr: fmt.Errorf("unexpected call to Start"), startCalled: &startCalled, @@ -150,18 +162,18 @@ func (f fakeOAuthClient) ClientID() string { return oauth.DefaultClientID } -func (f fakeOAuthClient) Discover(context.Context, string) (*oauth.OIDCConfiguration, error) { +func (f fakeOAuthClient) Discover(context.Context, *url.URL) (*oauth.OIDCConfiguration, error) { return nil, fmt.Errorf("unexpected call to Discover") } -func (f fakeOAuthClient) Start(context.Context, string, []string) (*oauth.DeviceAuthResponse, error) { +func (f fakeOAuthClient) Start(context.Context, *url.URL, []string) (*oauth.DeviceAuthResponse, error) { if f.startCalled != nil { *f.startCalled = true } return nil, f.startErr } -func (f fakeOAuthClient) Poll(context.Context, string, string, time.Duration, int) (*oauth.TokenResponse, error) { +func (f fakeOAuthClient) Poll(context.Context, *url.URL, string, time.Duration, int) (*oauth.TokenResponse, error) { return nil, fmt.Errorf("unexpected call to Poll") } @@ -172,8 +184,7 @@ func (f fakeOAuthClient) Refresh(context.Context, *oauth.Token) (*oauth.TokenRes func TestSelectLoginFlow(t *testing.T) { t.Run("uses oauth flow when no access token is configured", func(t *testing.T) { params := loginParams{ - cfg: &config{Endpoint: "https://example.com"}, - endpoint: "https://sourcegraph.example.com", + cfg: &config{endpointURL: mustParseURL(t, "https://example.com")}, } if got, _ := selectLoginFlow(params); got != loginFlowOAuth { @@ -183,8 +194,8 @@ func TestSelectLoginFlow(t *testing.T) { t.Run("uses endpoint conflict flow when auth exists for a different endpoint", func(t *testing.T) { params := loginParams{ - cfg: &config{Endpoint: "https://example.com", AccessToken: "x"}, - endpoint: "https://sourcegraph.example.com", + cfg: &config{endpointURL: mustParseURL(t, "https://example.com"), accessToken: "x"}, + loginEndpointURL: mustParseURL(t, "https://sourcegraph.example.com"), } if got, _ := selectLoginFlow(params); got != loginFlowEndpointConflict { @@ -194,8 +205,7 @@ func TestSelectLoginFlow(t *testing.T) { t.Run("uses validation flow when auth exists for the selected endpoint", func(t *testing.T) { params := loginParams{ - cfg: &config{Endpoint: "https://example.com", AccessToken: "x"}, - endpoint: "https://example.com", + cfg: &config{endpointURL: mustParseURL(t, "https://example.com"), accessToken: "x"}, } if got, _ := selectLoginFlow(params); got != loginFlowValidate { @@ -270,7 +280,7 @@ func TestValidateBrowserURL_WindowsRundll32Escape(t *testing.T) { } } -func restoreStoredOAuthLoader(t *testing.T, loader func(context.Context, string) (*oauth.Token, error)) { +func restoreStoredOAuthLoader(t *testing.T, loader func(context.Context, *url.URL) (*oauth.Token, error)) { t.Helper() prev := loadStoredOAuthToken diff --git a/cmd/src/login_validate.go b/cmd/src/login_validate.go index c54a6df421..9aa65cdcef 100644 --- a/cmd/src/login_validate.go +++ b/cmd/src/login_validate.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "io" + "net/url" "strings" "github.com/sourcegraph/src-cli/internal/api" @@ -11,28 +12,24 @@ import ( ) func runMissingAuthLogin(_ context.Context, p loginParams) error { - endpointArg := cleanEndpoint(p.endpoint) - fmt.Fprintln(p.out) printLoginProblem(p.out, "No access token is configured.") - fmt.Fprintln(p.out, loginAccessTokenMessage(endpointArg)) + fmt.Fprintln(p.out, loginAccessTokenMessage(p.cfg.endpointURL)) return cmderrors.ExitCode1 } func runEndpointConflictLogin(_ context.Context, p loginParams) error { - endpointArg := cleanEndpoint(p.endpoint) - fmt.Fprintln(p.out) - printLoginProblem(p.out, fmt.Sprintf("The configured endpoint is %s, not %s.", p.cfg.Endpoint, endpointArg)) - fmt.Fprintln(p.out, loginAccessTokenMessage(endpointArg)) + printLoginProblem(p.out, fmt.Sprintf("The configured endpoint is %s, not %s.", p.cfg.endpointURL, p.loginEndpointURL)) + fmt.Fprintln(p.out, loginAccessTokenMessage(p.loginEndpointURL)) return cmderrors.ExitCode1 } func runValidatedLogin(ctx context.Context, p loginParams) error { - return validateCurrentUser(ctx, p.client, p.out, cleanEndpoint(p.endpoint)) + return validateCurrentUser(ctx, p.client, p.out, p.cfg.endpointURL) } -func validateCurrentUser(ctx context.Context, client api.Client, out io.Writer, endpoint string) error { +func validateCurrentUser(ctx context.Context, client api.Client, out io.Writer, endpointURL *url.URL) error { query := `query CurrentUser { currentUser { username } }` var result struct { CurrentUser *struct{ Username string } @@ -41,9 +38,9 @@ func validateCurrentUser(ctx context.Context, client api.Client, out io.Writer, if strings.HasPrefix(err.Error(), "error: 401 Unauthorized") || strings.HasPrefix(err.Error(), "error: 403 Forbidden") { printLoginProblem(out, "Invalid access token.") } else { - printLoginProblem(out, fmt.Sprintf("Error communicating with %s: %s", endpoint, err)) + printLoginProblem(out, fmt.Sprintf("Error communicating with %s: %s", endpointURL, err)) } - fmt.Fprintln(out, loginAccessTokenMessage(endpoint)) + fmt.Fprintln(out, loginAccessTokenMessage(endpointURL)) fmt.Fprintln(out, " (If you need to supply custom HTTP request headers, see information about SRC_HEADER_* and SRC_HEADERS env vars at https://github.com/sourcegraph/src-cli/blob/main/AUTH_PROXY.md)") return cmderrors.ExitCode1 } @@ -51,11 +48,11 @@ func validateCurrentUser(ctx context.Context, client api.Client, out io.Writer, if result.CurrentUser == nil { // This should never happen; we verified there is an access token, so there should always be // a user. - printLoginProblem(out, fmt.Sprintf("Unable to determine user on %s.", endpoint)) + printLoginProblem(out, fmt.Sprintf("Unable to determine user on %s.", endpointURL)) return cmderrors.ExitCode1 } fmt.Fprintln(out) - fmt.Fprintf(out, "✔︎ Authenticated as %s on %s\n", result.CurrentUser.Username, endpoint) + fmt.Fprintf(out, "✔︎ Authenticated as %s on %s\n", result.CurrentUser.Username, endpointURL) fmt.Fprintln(out) return nil } diff --git a/cmd/src/main.go b/cmd/src/main.go index c7f2ff450c..00f0366781 100644 --- a/cmd/src/main.go +++ b/cmd/src/main.go @@ -77,8 +77,8 @@ var ( verbose = flag.Bool("v", false, "print verbose output") // The following arguments are deprecated which is why they are no longer documented - configPath = flag.String("config", "", "") - endpoint = flag.String("endpoint", "", "") + configPath = flag.String("config", "", "") + endpointFlag = flag.String("endpoint", "", "") errConfigMerge = errors.New("when using a configuration file, zero or all environment variables must be set") errConfigAuthorizationConflict = errors.New("when passing an 'Authorization' additional headers, SRC_ACCESS_TOKEN must never be set") @@ -110,17 +110,42 @@ func normalizeDashHelp(args []string) []string { return args } +func parseEndpoint(endpoint string) (*url.URL, error) { + u, err := url.ParseRequestURI(strings.TrimSuffix(endpoint, "/")) + if err != nil { + return nil, err + } + if !(u.Scheme == "http" || u.Scheme == "https") { + return nil, errors.Newf("invalid scheme %s: require http or https", u.Scheme) + } + if u.Host == "" { + return nil, errors.Newf("empty host") + } + // auth in the URL is not used, and could be explosed in log output. + // Explicitly clear it in case it's accidentally set in SRC_ENDPOINT or the config file. + u.User = nil + return u, nil +} + var cfg *config -// config represents the config format. +// config holds the resolved configuration used at runtime. type config struct { + accessToken string + additionalHeaders map[string]string + proxyURL *url.URL + proxyPath string + configFilePath string + endpointURL *url.URL // always non-nil; defaults to https://sourcegraph.com via readConfig +} + +// configFromFile holds the config as read from the config file, +// which is validated and parsed into the config struct. +type configFromFile struct { Endpoint string `json:"endpoint"` AccessToken string `json:"accessToken"` AdditionalHeaders map[string]string `json:"additionalHeaders"` Proxy string `json:"proxy"` - ProxyURL *url.URL - ProxyPath string - ConfigFilePath string } type AuthMode int @@ -131,7 +156,7 @@ const ( ) func (c *config) AuthMode() AuthMode { - if c.AccessToken != "" { + if c.accessToken != "" { return AuthModeAccessToken } return AuthModeOAuth @@ -140,18 +165,18 @@ func (c *config) AuthMode() AuthMode { // apiClient returns an api.Client built from the configuration. func (c *config) apiClient(flags *api.Flags, out io.Writer) api.Client { opts := api.ClientOpts{ - Endpoint: c.Endpoint, - AccessToken: c.AccessToken, - AdditionalHeaders: c.AdditionalHeaders, + EndpointURL: c.endpointURL, + AccessToken: c.accessToken, + AdditionalHeaders: c.additionalHeaders, Flags: flags, Out: out, - ProxyURL: c.ProxyURL, - ProxyPath: c.ProxyPath, + ProxyURL: c.proxyURL, + ProxyPath: c.proxyPath, } // Only use OAuth if we do not have SRC_ACCESS_TOKEN set - if c.AccessToken == "" { - if t, err := oauth.LoadToken(context.Background(), c.Endpoint); err == nil { + if c.accessToken == "" { + if t, err := oauth.LoadToken(context.Background(), c.endpointURL); err == nil { opts.OAuthToken = t } } @@ -177,12 +202,20 @@ func readConfig() (*config, error) { if err != nil && (!os.IsNotExist(err) || userSpecified) { return nil, err } + + var cfgFromFile configFromFile var cfg config + var endpointStr string + var proxyStr string if err == nil { - cfg.ConfigFilePath = cfgPath - if err := json.Unmarshal(data, &cfg); err != nil { + cfg.configFilePath = cfgPath + if err := json.Unmarshal(data, &cfgFromFile); err != nil { return nil, err } + endpointStr = cfgFromFile.Endpoint + cfg.accessToken = cfgFromFile.AccessToken + cfg.additionalHeaders = cfgFromFile.AdditionalHeaders + proxyStr = cfgFromFile.Proxy } envToken := os.Getenv("SRC_ACCESS_TOKEN") @@ -203,21 +236,32 @@ func readConfig() (*config, error) { // Apply config overrides. if envToken != "" { - cfg.AccessToken = envToken + cfg.accessToken = envToken } if envEndpoint != "" { - cfg.Endpoint = envEndpoint + endpointStr = envEndpoint } - if cfg.Endpoint == "" { - cfg.Endpoint = "https://sourcegraph.com" + if endpointStr == "" { + endpointStr = "https://sourcegraph.com" } if envProxy != "" { - cfg.Proxy = envProxy + proxyStr = envProxy } - if cfg.Proxy != "" { + // Lastly, apply endpoint flag if set + if endpointFlag != nil && *endpointFlag != "" { + endpointStr = *endpointFlag + } + + if endpointURL, err := parseEndpoint(endpointStr); err != nil { + return nil, errors.Newf("invalid endpoint: %s", endpointStr) + } else { + cfg.endpointURL = endpointURL + } - parseEndpoint := func(endpoint string) (scheme string, address string) { + if proxyStr != "" { + + parseProxyEndpoint := func(endpoint string) (scheme string, address string) { parts := strings.SplitN(endpoint, "://", 2) if len(parts) == 2 { return parts[0], parts[1] @@ -231,15 +275,15 @@ func readConfig() (*config, error) { return slices.Contains(urlSchemes, scheme) } - scheme, address := parseEndpoint(cfg.Proxy) + scheme, address := parseProxyEndpoint(proxyStr) if isURLScheme(scheme) { - endpoint := cfg.Proxy + endpoint := proxyStr // assume socks means socks5, because that's all we support if scheme == "socks" { endpoint = "socks5://" + address } - cfg.ProxyURL, err = url.Parse(endpoint) + cfg.proxyURL, err = url.Parse(endpoint) if err != nil { return nil, err } @@ -250,32 +294,25 @@ func readConfig() (*config, error) { } isValidUDS, err := isValidUnixSocket(path) if err != nil { - return nil, errors.Newf("Invalid proxy configuration: %w", err) + return nil, errors.Newf("invalid proxy configuration: %w", err) } if !isValidUDS { return nil, errors.Newf("invalid proxy socket: %s", path) } - cfg.ProxyPath = path + cfg.proxyPath = path } else { - return nil, errors.Newf("invalid proxy endpoint: %s", cfg.Proxy) + return nil, errors.Newf("invalid proxy endpoint: %s", proxyStr) } } - cfg.AdditionalHeaders = parseAdditionalHeaders() + cfg.additionalHeaders = parseAdditionalHeaders() // Ensure that we're not clashing additonal headers - _, hasAuthorizationAdditonalHeader := cfg.AdditionalHeaders["authorization"] - if cfg.AccessToken != "" && hasAuthorizationAdditonalHeader { + _, hasAuthorizationAdditonalHeader := cfg.additionalHeaders["authorization"] + if cfg.accessToken != "" && hasAuthorizationAdditonalHeader { return nil, errConfigAuthorizationConflict } - // Lastly, apply endpoint flag if set - if endpoint != nil && *endpoint != "" { - cfg.Endpoint = *endpoint - } - - cfg.Endpoint = cleanEndpoint(cfg.Endpoint) - - if isCI() && cfg.AccessToken == "" { + if isCI() && cfg.accessToken == "" { return nil, errCIAccessTokenRequired } @@ -287,10 +324,6 @@ func isCI() bool { return ok && value != "" } -func cleanEndpoint(urlStr string) string { - return strings.TrimSuffix(urlStr, "/") -} - // isValidUnixSocket checks if the given path is a valid Unix socket. // // Parameters: @@ -310,7 +343,7 @@ func isValidUnixSocket(path string) (bool, error) { if os.IsNotExist(err) { return false, nil } - return false, errors.Newf("Not a UNIX Domain Socket: %v: %w", path, err) + return false, errors.Newf("not a UNIX Domain Socket: %v: %w", path, err) } defer conn.Close() diff --git a/cmd/src/main_test.go b/cmd/src/main_test.go index a2656b1929..ee95616796 100644 --- a/cmd/src/main_test.go +++ b/cmd/src/main_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" "github.com/sourcegraph/src-cli/internal/api" ) @@ -29,7 +30,7 @@ func TestReadConfig(t *testing.T) { tests := []struct { name string - fileContents *config + fileContents *configFromFile envCI string envToken string envFooHeader string @@ -43,24 +44,29 @@ func TestReadConfig(t *testing.T) { { name: "defaults", want: &config{ - Endpoint: "https://sourcegraph.com", - AdditionalHeaders: map[string]string{}, + endpointURL: &url.URL{ + Scheme: "https", + Host: "sourcegraph.com", + }, + additionalHeaders: map[string]string{}, }, }, { name: "config file, no overrides, trim slash", - fileContents: &config{ + fileContents: &configFromFile{ Endpoint: "https://example.com/", AccessToken: "deadbeef", Proxy: "https://proxy.com:8080", }, want: &config{ - Endpoint: "https://example.com", - AccessToken: "deadbeef", - AdditionalHeaders: map[string]string{}, - Proxy: "https://proxy.com:8080", - ProxyPath: "", - ProxyURL: &url.URL{ + endpointURL: &url.URL{ + Scheme: "https", + Host: "example.com", + }, + accessToken: "deadbeef", + additionalHeaders: map[string]string{}, + proxyPath: "", + proxyURL: &url.URL{ Scheme: "https", Host: "proxy.com:8080", }, @@ -68,7 +74,7 @@ func TestReadConfig(t *testing.T) { }, { name: "config file, token override only", - fileContents: &config{ + fileContents: &configFromFile{ Endpoint: "https://example.com/", AccessToken: "deadbeef", }, @@ -78,7 +84,7 @@ func TestReadConfig(t *testing.T) { }, { name: "config file, endpoint override only", - fileContents: &config{ + fileContents: &configFromFile{ Endpoint: "https://example.com/", AccessToken: "deadbeef", }, @@ -88,27 +94,29 @@ func TestReadConfig(t *testing.T) { }, { name: "config file, proxy override only (allow)", - fileContents: &config{ + fileContents: &configFromFile{ Endpoint: "https://example.com/", AccessToken: "deadbeef", Proxy: "https://proxy.com:8080", }, envProxy: "socks5://other.proxy.com:9999", want: &config{ - Endpoint: "https://example.com", - AccessToken: "deadbeef", - Proxy: "socks5://other.proxy.com:9999", - ProxyPath: "", - ProxyURL: &url.URL{ + endpointURL: &url.URL{ + Scheme: "https", + Host: "example.com", + }, + accessToken: "deadbeef", + proxyPath: "", + proxyURL: &url.URL{ Scheme: "socks5", Host: "other.proxy.com:9999", }, - AdditionalHeaders: map[string]string{}, + additionalHeaders: map[string]string{}, }, }, { name: "config file, all override", - fileContents: &config{ + fileContents: &configFromFile{ Endpoint: "https://example.com/", AccessToken: "deadbeef", Proxy: "https://proxy.com:8080", @@ -117,48 +125,58 @@ func TestReadConfig(t *testing.T) { envEndpoint: "https://override.com", envProxy: "socks5://other.proxy.com:9999", want: &config{ - Endpoint: "https://override.com", - AccessToken: "abc", - Proxy: "socks5://other.proxy.com:9999", - ProxyPath: "", - ProxyURL: &url.URL{ + endpointURL: &url.URL{ + Scheme: "https", + Host: "override.com", + }, + accessToken: "abc", + proxyPath: "", + proxyURL: &url.URL{ Scheme: "socks5", Host: "other.proxy.com:9999", }, - AdditionalHeaders: map[string]string{}, + additionalHeaders: map[string]string{}, }, }, { name: "no config file, token from environment", envToken: "abc", want: &config{ - Endpoint: "https://sourcegraph.com", - AccessToken: "abc", - AdditionalHeaders: map[string]string{}, + endpointURL: &url.URL{ + Scheme: "https", + Host: "sourcegraph.com", + }, + accessToken: "abc", + additionalHeaders: map[string]string{}, }, }, { name: "no config file, endpoint from environment", envEndpoint: "https://example.com", want: &config{ - Endpoint: "https://example.com", - AccessToken: "", - AdditionalHeaders: map[string]string{}, + endpointURL: &url.URL{ + Scheme: "https", + Host: "example.com", + }, + accessToken: "", + additionalHeaders: map[string]string{}, }, }, { name: "no config file, proxy from environment", envProxy: "https://proxy.com:8080", want: &config{ - Endpoint: "https://sourcegraph.com", - AccessToken: "", - Proxy: "https://proxy.com:8080", - ProxyPath: "", - ProxyURL: &url.URL{ + endpointURL: &url.URL{ + Scheme: "https", + Host: "sourcegraph.com", + }, + accessToken: "", + proxyPath: "", + proxyURL: &url.URL{ Scheme: "https", Host: "proxy.com:8080", }, - AdditionalHeaders: map[string]string{}, + additionalHeaders: map[string]string{}, }, }, { @@ -167,79 +185,92 @@ func TestReadConfig(t *testing.T) { envToken: "abc", envProxy: "https://proxy.com:8080", want: &config{ - Endpoint: "https://example.com", - AccessToken: "abc", - Proxy: "https://proxy.com:8080", - ProxyPath: "", - ProxyURL: &url.URL{ + endpointURL: &url.URL{ + Scheme: "https", + Host: "example.com", + }, + accessToken: "abc", + proxyPath: "", + proxyURL: &url.URL{ Scheme: "https", Host: "proxy.com:8080", }, - AdditionalHeaders: map[string]string{}, + additionalHeaders: map[string]string{}, }, }, { name: "UNIX Domain Socket proxy using scheme and absolute path", envProxy: "unix://" + socketPath, want: &config{ - Endpoint: "https://sourcegraph.com", - Proxy: "unix://" + socketPath, - ProxyPath: socketPath, - ProxyURL: nil, - AdditionalHeaders: map[string]string{}, + endpointURL: &url.URL{ + Scheme: "https", + Host: "sourcegraph.com", + }, + proxyPath: socketPath, + proxyURL: nil, + additionalHeaders: map[string]string{}, }, }, { name: "UNIX Domain Socket proxy with absolute path", envProxy: socketPath, want: &config{ - Endpoint: "https://sourcegraph.com", - Proxy: socketPath, - ProxyPath: socketPath, - ProxyURL: nil, - AdditionalHeaders: map[string]string{}, + endpointURL: &url.URL{ + Scheme: "https", + Host: "sourcegraph.com", + }, + proxyPath: socketPath, + proxyURL: nil, + additionalHeaders: map[string]string{}, }, }, { name: "socks --> socks5", envProxy: "socks://localhost:1080", want: &config{ - Endpoint: "https://sourcegraph.com", - Proxy: "socks://localhost:1080", - ProxyPath: "", - ProxyURL: &url.URL{ + endpointURL: &url.URL{ + Scheme: "https", + Host: "sourcegraph.com", + }, + proxyPath: "", + proxyURL: &url.URL{ Scheme: "socks5", Host: "localhost:1080", }, - AdditionalHeaders: map[string]string{}, + additionalHeaders: map[string]string{}, }, }, { name: "socks5h", envProxy: "socks5h://localhost:1080", want: &config{ - Endpoint: "https://sourcegraph.com", - Proxy: "socks5h://localhost:1080", - ProxyPath: "", - ProxyURL: &url.URL{ + endpointURL: &url.URL{ + Scheme: "https", + Host: "sourcegraph.com", + }, + proxyPath: "", + proxyURL: &url.URL{ Scheme: "socks5h", Host: "localhost:1080", }, - AdditionalHeaders: map[string]string{}, + additionalHeaders: map[string]string{}, }, }, { name: "endpoint flag should override config", flagEndpoint: "https://override.com/", - fileContents: &config{ + fileContents: &configFromFile{ Endpoint: "https://example.com/", AccessToken: "deadbeef", AdditionalHeaders: map[string]string{}, }, want: &config{ - Endpoint: "https://override.com", - AccessToken: "deadbeef", - AdditionalHeaders: map[string]string{}, + endpointURL: &url.URL{ + Scheme: "https", + Host: "override.com", + }, + accessToken: "deadbeef", + additionalHeaders: map[string]string{}, }, }, { @@ -248,9 +279,12 @@ func TestReadConfig(t *testing.T) { envEndpoint: "https://example.com", envToken: "abc", want: &config{ - Endpoint: "https://override.com", - AccessToken: "abc", - AdditionalHeaders: map[string]string{}, + endpointURL: &url.URL{ + Scheme: "https", + Host: "override.com", + }, + accessToken: "abc", + additionalHeaders: map[string]string{}, }, }, { @@ -260,9 +294,12 @@ func TestReadConfig(t *testing.T) { envToken: "abc", envFooHeader: "bar", want: &config{ - Endpoint: "https://override.com", - AccessToken: "abc", - AdditionalHeaders: map[string]string{"foo": "bar"}, + endpointURL: &url.URL{ + Scheme: "https", + Host: "override.com", + }, + accessToken: "abc", + additionalHeaders: map[string]string{"foo": "bar"}, }, }, { @@ -272,9 +309,12 @@ func TestReadConfig(t *testing.T) { envToken: "abc", envHeaders: "foo:bar\nfoo-bar:bar-baz", want: &config{ - Endpoint: "https://override.com", - AccessToken: "abc", - AdditionalHeaders: map[string]string{"foo-bar": "bar-baz", "foo": "bar"}, + endpointURL: &url.URL{ + Scheme: "https", + Host: "override.com", + }, + accessToken: "abc", + additionalHeaders: map[string]string{"foo-bar": "bar-baz", "foo": "bar"}, }, }, { @@ -292,14 +332,14 @@ func TestReadConfig(t *testing.T) { { name: "CI allows access token from config file", envCI: "1", - fileContents: &config{ + fileContents: &configFromFile{ Endpoint: "https://example.com/", AccessToken: "deadbeef", }, want: &config{ - Endpoint: "https://example.com", - AccessToken: "deadbeef", - AdditionalHeaders: map[string]string{}, + endpointURL: &url.URL{Scheme: "https", Host: "example.com"}, + accessToken: "deadbeef", + additionalHeaders: map[string]string{}, }, }, } @@ -323,8 +363,8 @@ func TestReadConfig(t *testing.T) { if test.flagEndpoint != "" { val := test.flagEndpoint - endpoint = &val - t.Cleanup(func() { endpoint = nil }) + endpointFlag = &val + t.Cleanup(func() { endpointFlag = nil }) } if test.fileContents != nil { @@ -351,8 +391,11 @@ func TestReadConfig(t *testing.T) { t.Fatal(err) } - config, err := readConfig() - if diff := cmp.Diff(test.want, config); diff != "" { + got, err := readConfig() + if diff := cmp.Diff(test.want, got, + cmp.AllowUnexported(config{}), + cmpopts.IgnoreFields(config{}, "configFilePath"), + ); diff != "" { t.Errorf("config: %v", diff) } var errMsg string @@ -374,7 +417,7 @@ func TestConfigAuthMode(t *testing.T) { }) t.Run("access token when configured", func(t *testing.T) { - if got := (&config{AccessToken: "token"}).AuthMode(); got != AuthModeAccessToken { + if got := (&config{accessToken: "token"}).AuthMode(); got != AuthModeAccessToken { t.Fatalf("AuthMode() = %v, want %v", got, AuthModeAccessToken) } }) diff --git a/cmd/src/search.go b/cmd/src/search.go index 385ac7c72d..a2cd1a0bbe 100644 --- a/cmd/src/search.go +++ b/cmd/src/search.go @@ -266,7 +266,7 @@ Other tips: } improved := searchResultsImproved{ - SourcegraphEndpoint: cfg.Endpoint, + SourcegraphEndpoint: cfg.endpointURL.String(), Query: queryString, Site: result.Site, searchResults: result.Search.Results, diff --git a/cmd/src/search_jobs.go b/cmd/src/search_jobs.go index 96c5d9070a..15bf5d8a25 100644 --- a/cmd/src/search_jobs.go +++ b/cmd/src/search_jobs.go @@ -156,8 +156,8 @@ func parseColumns(columnsFlag string) []string { // createSearchJobsClient creates a reusable API client for search jobs commands func createSearchJobsClient(out *flag.FlagSet, apiFlags *api.Flags) api.Client { return api.NewClient(api.ClientOpts{ - Endpoint: cfg.Endpoint, - AccessToken: cfg.AccessToken, + EndpointURL: cfg.endpointURL, + AccessToken: cfg.accessToken, Out: out.Output(), Flags: apiFlags, }) diff --git a/cmd/src/search_jobs_logs.go b/cmd/src/search_jobs_logs.go index 2fe9b6bfee..6327a609ab 100644 --- a/cmd/src/search_jobs_logs.go +++ b/cmd/src/search_jobs_logs.go @@ -22,7 +22,7 @@ func fetchJobLogs(jobID string, logURL string) (io.ReadCloser, error) { return nil, err } - req.Header.Add("Authorization", "token "+cfg.AccessToken) + req.Header.Add("Authorization", "token "+cfg.accessToken) resp, err := http.DefaultClient.Do(req) if err != nil { diff --git a/cmd/src/search_jobs_results.go b/cmd/src/search_jobs_results.go index 2e45f8219f..9d8bc7a9ab 100644 --- a/cmd/src/search_jobs_results.go +++ b/cmd/src/search_jobs_results.go @@ -22,7 +22,7 @@ func fetchJobResults(jobID string, resultsURL string) (io.ReadCloser, error) { return nil, err } - req.Header.Add("Authorization", "token "+cfg.AccessToken) + req.Header.Add("Authorization", "token "+cfg.accessToken) resp, err := http.DefaultClient.Do(req) if err != nil { diff --git a/cmd/src/search_stream.go b/cmd/src/search_stream.go index 512e7f9f75..9b5415851a 100644 --- a/cmd/src/search_stream.go +++ b/cmd/src/search_stream.go @@ -160,7 +160,7 @@ func textDecoder(query string, t *template.Template, w io.Writer) streaming.Deco SourcegraphEndpoint string *streaming.EventRepoMatch }{ - SourcegraphEndpoint: cfg.Endpoint, + SourcegraphEndpoint: cfg.endpointURL.String(), EventRepoMatch: match, }) if err != nil { @@ -172,7 +172,7 @@ func textDecoder(query string, t *template.Template, w io.Writer) streaming.Deco SourcegraphEndpoint string *streaming.EventCommitMatch }{ - SourcegraphEndpoint: cfg.Endpoint, + SourcegraphEndpoint: cfg.endpointURL.String(), EventCommitMatch: match, }) if err != nil { @@ -184,7 +184,7 @@ func textDecoder(query string, t *template.Template, w io.Writer) streaming.Deco SourcegraphEndpoint string *streaming.EventSymbolMatch }{ - SourcegraphEndpoint: cfg.Endpoint, + SourcegraphEndpoint: cfg.endpointURL.String(), EventSymbolMatch: match, }, ) diff --git a/cmd/src/search_stream_test.go b/cmd/src/search_stream_test.go index 1653b273ac..71b099abb9 100644 --- a/cmd/src/search_stream_test.go +++ b/cmd/src/search_stream_test.go @@ -6,6 +6,7 @@ import ( "net" "net/http" "net/http/httptest" + "net/url" "os" "testing" @@ -126,8 +127,9 @@ func TestSearchStream(t *testing.T) { s := testServer(t, http.HandlerFunc(mockStreamHandler)) defer s.Close() + u, _ := url.ParseRequestURI(s.URL) cfg = &config{ - Endpoint: s.URL, + endpointURL: u, } defer func() { cfg = nil }() diff --git a/cmd/src/users_prune.go b/cmd/src/users_prune.go index 90de530c68..d67fff6be0 100644 --- a/cmd/src/users_prune.go +++ b/cmd/src/users_prune.go @@ -225,7 +225,7 @@ type UserToDelete struct { // Verify user wants to remove users with table of users and a command prompt for [y/N] func confirmUserRemoval(usersToDelete []UserToDelete, daysThreshold int, displayUsers bool) (bool, error) { if displayUsers { - fmt.Printf("Users to remove from %s\n", cfg.Endpoint) + fmt.Printf("Users to remove from %s\n", cfg.endpointURL) t := table.NewWriter() t.SetOutputMirror(os.Stdout) t.AppendHeader(table.Row{"Username", "Email", "Days Since Last Active"}) @@ -243,7 +243,7 @@ func confirmUserRemoval(usersToDelete []UserToDelete, daysThreshold int, display } input := "" for strings.ToLower(input) != "y" && strings.ToLower(input) != "n" { - fmt.Printf("%v users were inactive for more than %v days on %v.\nDo you wish to proceed with user removal [y/N]: ", len(usersToDelete), daysThreshold, cfg.Endpoint) + fmt.Printf("%v users were inactive for more than %v days on %v.\nDo you wish to proceed with user removal [y/N]: ", len(usersToDelete), daysThreshold, cfg.endpointURL) if _, err := fmt.Scanln(&input); err != nil { return false, err } diff --git a/internal/api/api.go b/internal/api/api.go index adc6af53d5..a824fae1a5 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -12,7 +12,6 @@ import ( "net/url" "os" "runtime" - "strings" ioaux "github.com/jig/teereadcloser" "github.com/kballard/go-shellquote" @@ -72,7 +71,7 @@ type request struct { // ClientOpts encapsulates the options given to NewClient. type ClientOpts struct { - Endpoint string + EndpointURL *url.URL AccessToken string AdditionalHeaders map[string]string @@ -139,7 +138,7 @@ func NewClient(opts ClientOpts) Client { return &client{ opts: ClientOpts{ - Endpoint: opts.Endpoint, + EndpointURL: opts.EndpointURL, AccessToken: opts.AccessToken, AdditionalHeaders: opts.AdditionalHeaders, Flags: flags, @@ -174,7 +173,8 @@ func (c *client) NewHTTPRequest(ctx context.Context, method, p string, body io.R } func (c *client) createHTTPRequest(ctx context.Context, method, p string, body io.Reader) (*http.Request, error) { - req, err := http.NewRequestWithContext(ctx, method, strings.TrimRight(c.opts.Endpoint, "/")+"/"+p, body) + // Can't use c.opts.EndpointURL.JoinPath(p) here because `p` could contain a query string + req, err := http.NewRequestWithContext(ctx, method, c.opts.EndpointURL.String()+"/"+p, body) if err != nil { return nil, err } @@ -269,7 +269,7 @@ func (r *request) do(ctx context.Context, result any) (bool, error) { if oauth.IsOAuthTransport(r.client.httpClient.Transport) { fmt.Println("The OAuth token is invalid. Please check that the Sourcegraph CLI client is still authorized.") fmt.Println("") - fmt.Printf("To re-authorize, run: src login %s\n", r.client.opts.Endpoint) + fmt.Printf("To re-authorize, run: src login %s\n", r.client.opts.EndpointURL) fmt.Println("") fmt.Println("Learn more at https://github.com/sourcegraph/src-cli#readme") fmt.Println("") @@ -360,6 +360,6 @@ func (r *request) curlCmd() (string, error) { s += fmt.Sprintf(" %s \\\n", shellquote.Join("-H", k+": "+v)) } s += fmt.Sprintf(" %s \\\n", shellquote.Join("-d", string(data))) - s += fmt.Sprintf(" %s", shellquote.Join(r.client.opts.Endpoint+"/.api/graphql")) + s += fmt.Sprintf(" %s", shellquote.Join(r.client.opts.EndpointURL.JoinPath(".api/graphql").String())) return s, nil } diff --git a/internal/batches/executor/executor_test.go b/internal/batches/executor/executor_test.go index 9fc96d927d..03f25e08a8 100644 --- a/internal/batches/executor/executor_test.go +++ b/internal/batches/executor/executor_test.go @@ -6,6 +6,7 @@ import ( "fmt" "net/http" "net/http/httptest" + "net/url" "os" "path/filepath" "runtime" @@ -406,7 +407,8 @@ func TestExecutor_Integration(t *testing.T) { // Setup an api.Client that points to this test server var clientBuffer bytes.Buffer - client := api.NewClient(api.ClientOpts{Endpoint: ts.URL, Out: &clientBuffer}) + u, _ := url.ParseRequestURI(ts.URL) + client := api.NewClient(api.ClientOpts{EndpointURL: u, Out: &clientBuffer}) // Temp dir for log files and downloaded archives testTempDir := t.TempDir() @@ -827,7 +829,8 @@ func testExecuteTasks(t *testing.T, tasks []*Task, archives ...mock.RepoArchive) t.Cleanup(ts.Close) var clientBuffer bytes.Buffer - client := api.NewClient(api.ClientOpts{Endpoint: ts.URL, Out: &clientBuffer}) + u, _ := url.ParseRequestURI(ts.URL) + client := api.NewClient(api.ClientOpts{EndpointURL: u, Out: &clientBuffer}) // Prepare images // diff --git a/internal/batches/repozip/fetcher_test.go b/internal/batches/repozip/fetcher_test.go index f871237e45..56d03d85a6 100644 --- a/internal/batches/repozip/fetcher_test.go +++ b/internal/batches/repozip/fetcher_test.go @@ -5,6 +5,7 @@ import ( "context" "net/http" "net/http/httptest" + "net/url" "os" "path" "path/filepath" @@ -44,7 +45,8 @@ func TestArchive_Ensure(t *testing.T) { defer ts.Close() var clientBuffer bytes.Buffer - client := api.NewClient(api.ClientOpts{Endpoint: ts.URL, Out: &clientBuffer}) + u, _ := url.ParseRequestURI(ts.URL) + client := api.NewClient(api.ClientOpts{EndpointURL: u, Out: &clientBuffer}) rf := &archiveRegistry{ client: client, @@ -89,7 +91,8 @@ func TestArchive_Ensure(t *testing.T) { defer ts.Close() var clientBuffer bytes.Buffer - client := api.NewClient(api.ClientOpts{Endpoint: ts.URL, Out: &clientBuffer}) + u, _ := url.ParseRequestURI(ts.URL) + client := api.NewClient(api.ClientOpts{EndpointURL: u, Out: &clientBuffer}) rf := &archiveRegistry{ client: client, @@ -153,7 +156,8 @@ func TestArchive_Ensure(t *testing.T) { defer ts.Close() var clientBuffer bytes.Buffer - client := api.NewClient(api.ClientOpts{Endpoint: ts.URL, Out: &clientBuffer}) + u, _ := url.ParseRequestURI(ts.URL) + client := api.NewClient(api.ClientOpts{EndpointURL: u, Out: &clientBuffer}) rf := &archiveRegistry{ client: client, @@ -193,7 +197,8 @@ func TestArchive_Ensure(t *testing.T) { defer ts.Close() var clientBuffer bytes.Buffer - client := api.NewClient(api.ClientOpts{Endpoint: ts.URL, Out: &clientBuffer}) + u, _ := url.ParseRequestURI(ts.URL) + client := api.NewClient(api.ClientOpts{EndpointURL: u, Out: &clientBuffer}) rf := &archiveRegistry{ client: client, @@ -262,7 +267,8 @@ func TestArchive_Ensure(t *testing.T) { defer ts.Close() var clientBuffer bytes.Buffer - client := api.NewClient(api.ClientOpts{Endpoint: ts.URL, Out: &clientBuffer}) + u, _ := url.ParseRequestURI(ts.URL) + client := api.NewClient(api.ClientOpts{EndpointURL: u, Out: &clientBuffer}) rf := &archiveRegistry{ client: client, diff --git a/internal/oauth/flow.go b/internal/oauth/flow.go index f34d9ae656..5357466f57 100644 --- a/internal/oauth/flow.go +++ b/internal/oauth/flow.go @@ -72,6 +72,10 @@ type Token struct { ExpiresAt time.Time `json:"expires_at"` } +func (t *Token) EndpointURL() (*url.URL, error) { + return url.ParseRequestURI(t.Endpoint) +} + type ErrorResponse struct { Error string `json:"error"` ErrorDescription string `json:"error_description,omitempty"` @@ -79,9 +83,9 @@ type ErrorResponse struct { type Client interface { ClientID() string - Discover(ctx context.Context, endpoint string) (*OIDCConfiguration, error) - Start(ctx context.Context, endpoint string, scopes []string) (*DeviceAuthResponse, error) - Poll(ctx context.Context, endpoint, deviceCode string, interval time.Duration, expiresIn int) (*TokenResponse, error) + Discover(ctx context.Context, endpointURL *url.URL) (*OIDCConfiguration, error) + Start(ctx context.Context, endpointURL *url.URL, scopes []string) (*DeviceAuthResponse, error) + Poll(ctx context.Context, endpointURL *url.URL, deviceCode string, interval time.Duration, expiresIn int) (*TokenResponse, error) Refresh(ctx context.Context, token *Token) (*TokenResponse, error) } @@ -115,14 +119,14 @@ func (c *httpClient) ClientID() string { // // Before making any requests, the configCache is checked and if there is a cache hit, the // cached config is returned. -func (c *httpClient) Discover(ctx context.Context, endpoint string) (*OIDCConfiguration, error) { - endpoint = strings.TrimRight(endpoint, "/") +func (c *httpClient) Discover(ctx context.Context, endpointURL *url.URL) (*OIDCConfiguration, error) { + endpoint := endpointURL.String() if config, ok := c.configCache[endpoint]; ok { return config, nil } - reqURL := endpoint + wellKnownPath + reqURL := endpointURL.JoinPath(wellKnownPath).String() req, err := http.NewRequestWithContext(ctx, "GET", reqURL, nil) if err != nil { @@ -158,11 +162,9 @@ func (c *httpClient) Discover(ctx context.Context, endpoint string) (*OIDCConfig // Start starts the OAuth device flow with the given endpoint. If no scopes are given the default scopes are used. // // Default Scopes: "openid" "profile" "email" "offline_access" "user:all" -func (c *httpClient) Start(ctx context.Context, endpoint string, scopes []string) (*DeviceAuthResponse, error) { - endpoint = strings.TrimRight(endpoint, "/") - +func (c *httpClient) Start(ctx context.Context, endpointURL *url.URL, scopes []string) (*DeviceAuthResponse, error) { // Discover OIDC configuration - caches on first call - config, err := c.Discover(ctx, endpoint) + config, err := c.Discover(ctx, endpointURL) if err != nil { return nil, errors.Wrap(err, "OIDC discovery failed") } @@ -221,11 +223,9 @@ func (c *httpClient) Start(ctx context.Context, endpoint string, scopes []string // - Device is authorized, and a token is returned // - Device code has expried // - User denied authorization -func (c *httpClient) Poll(ctx context.Context, endpoint, deviceCode string, interval time.Duration, expiresIn int) (*TokenResponse, error) { - endpoint = strings.TrimRight(endpoint, "/") - +func (c *httpClient) Poll(ctx context.Context, endpointURL *url.URL, deviceCode string, interval time.Duration, expiresIn int) (*TokenResponse, error) { // Discover OIDC configuration - caches on first call - config, err := c.Discover(ctx, endpoint) + config, err := c.Discover(ctx, endpointURL) if err != nil { return nil, errors.Wrap(err, "OIDC discovery failed") } @@ -326,7 +326,12 @@ func (c *httpClient) pollOnce(ctx context.Context, tokenEndpoint, deviceCode str // Refresh exchanges a refresh token for a new access token. func (c *httpClient) Refresh(ctx context.Context, token *Token) (*TokenResponse, error) { - config, err := c.Discover(ctx, token.Endpoint) + endpointURL, err := token.EndpointURL() + if err != nil { + return nil, errors.Wrap(err, "invalid token endpoint") + } + + config, err := c.Discover(ctx, endpointURL) if err != nil { return nil, errors.Wrap(err, "failed to discover OIDC configuration") } @@ -374,9 +379,9 @@ func (c *httpClient) Refresh(ctx context.Context, token *Token) (*TokenResponse, return &tokenResp, err } -func (t *TokenResponse) Token(endpoint string) *Token { +func (t *TokenResponse) Token(endpointURL *url.URL) *Token { return &Token{ - Endpoint: strings.TrimRight(endpoint, "/"), + Endpoint: endpointURL.String(), RefreshToken: t.RefreshToken, AccessToken: t.AccessToken, ExpiresAt: time.Now().Add(time.Second * time.Duration(t.ExpiresIn)), @@ -397,7 +402,12 @@ func StoreToken(ctx context.Context, token *Token) error { return errors.New("token endpoint cannot be empty when storing the token") } - store, err := secrets.Open(ctx, token.Endpoint) + u, err := token.EndpointURL() + if err != nil { + return errors.Wrap(err, "invalid token endpoint") + } + + store, err := secrets.Open(ctx, u) if err != nil { return err } @@ -409,8 +419,8 @@ func StoreToken(ctx context.Context, token *Token) error { return store.Put(oauthKey, data) } -func LoadToken(ctx context.Context, endpoint string) (*Token, error) { - store, err := secrets.Open(ctx, endpoint) +func LoadToken(ctx context.Context, endpointURL *url.URL) (*Token, error) { + store, err := secrets.Open(ctx, endpointURL) if err != nil { return nil, err } diff --git a/internal/oauth/flow_test.go b/internal/oauth/flow_test.go index 0b1ad5dc93..a6312e1a6c 100644 --- a/internal/oauth/flow_test.go +++ b/internal/oauth/flow_test.go @@ -5,12 +5,22 @@ import ( "encoding/json" "net/http" "net/http/httptest" + "net/url" "strings" "sync/atomic" "testing" "time" ) +func mustParseURL(t *testing.T, raw string) *url.URL { + t.Helper() + u, err := url.Parse(raw) + if err != nil { + t.Fatalf("failed to parse URL %q: %v", raw, err) + } + return u +} + const ( testDeviceAuthPath = "/device/code" testTokenPath = "/token" @@ -51,7 +61,7 @@ func TestDiscover_Success(t *testing.T) { defer server.Close() client := NewClient(DefaultClientID) - config, err := client.Discover(context.Background(), server.URL) + config, err := client.Discover(context.Background(), mustParseURL(t, server.URL)) if err != nil { t.Fatalf("Discover() error = %v", err) } @@ -81,13 +91,13 @@ func TestDiscover_Caching(t *testing.T) { client := NewClient(DefaultClientID) // Populate the cache - _, err := client.Discover(context.Background(), server.URL) + _, err := client.Discover(context.Background(), mustParseURL(t, server.URL)) if err != nil { t.Fatalf("Discover() error = %v", err) } // Second call should use cache - _, err = client.Discover(context.Background(), server.URL) + _, err = client.Discover(context.Background(), mustParseURL(t, server.URL)) if err != nil { t.Fatalf("Discover() error = %v", err) } @@ -106,7 +116,7 @@ func TestDiscover_Error(t *testing.T) { defer server.Close() client := NewClient(DefaultClientID) - _, err := client.Discover(context.Background(), server.URL) + _, err := client.Discover(context.Background(), mustParseURL(t, server.URL)) if err == nil { t.Fatal("Discover() expected error, got nil") } @@ -153,7 +163,7 @@ func TestStart_Success(t *testing.T) { defer server.Close() client := NewClient(DefaultClientID) - resp, err := client.Start(context.Background(), server.URL, nil) + resp, err := client.Start(context.Background(), mustParseURL(t, server.URL), nil) if err != nil { t.Fatalf("Start() error = %v", err) } @@ -205,7 +215,7 @@ func TestStart_WithScopes(t *testing.T) { defer server.Close() client := NewClient(DefaultClientID) - _, err := client.Start(context.Background(), server.URL, []string{"read", "write"}) + _, err := client.Start(context.Background(), mustParseURL(t, server.URL), []string{"read", "write"}) if err != nil { t.Fatalf("Start() error = %v", err) } @@ -231,7 +241,7 @@ func TestStart_Error(t *testing.T) { defer server.Close() client := NewClient(DefaultClientID) - _, err := client.Start(context.Background(), server.URL, nil) + _, err := client.Start(context.Background(), mustParseURL(t, server.URL), nil) if err == nil { t.Fatal("Start() expected error, got nil") } @@ -254,7 +264,7 @@ func TestStart_NoDeviceEndpoint(t *testing.T) { defer server.Close() client := NewClient(DefaultClientID) - _, err := client.Start(context.Background(), server.URL, nil) + _, err := client.Start(context.Background(), mustParseURL(t, server.URL), nil) if err == nil { t.Fatal("Start() expected error, got nil") } @@ -302,7 +312,7 @@ func TestPoll_Success(t *testing.T) { defer server.Close() client := NewClient(DefaultClientID).(*httpClient) - resp, err := client.Poll(context.Background(), server.URL, "test-device-code", 10*time.Millisecond, 60) + resp, err := client.Poll(context.Background(), mustParseURL(t, server.URL), "test-device-code", 10*time.Millisecond, 60) if err != nil { t.Fatalf("Poll() error = %v", err) } @@ -345,7 +355,7 @@ func TestPoll_AuthorizationPending(t *testing.T) { defer server.Close() client := NewClient(DefaultClientID).(*httpClient) - resp, err := client.Poll(context.Background(), server.URL, "test-device-code", 10*time.Millisecond, 60) + resp, err := client.Poll(context.Background(), mustParseURL(t, server.URL), "test-device-code", 10*time.Millisecond, 60) if err != nil { t.Fatalf("Poll() error = %v", err) } @@ -387,7 +397,7 @@ func TestPoll_SlowDown(t *testing.T) { defer server.Close() client := NewClient(DefaultClientID).(*httpClient) - resp, err := client.Poll(context.Background(), server.URL, "test-device-code", 10*time.Millisecond, 60) + resp, err := client.Poll(context.Background(), mustParseURL(t, server.URL), "test-device-code", 10*time.Millisecond, 60) if err != nil { t.Fatalf("Poll() error = %v", err) } @@ -417,7 +427,7 @@ func TestPoll_ExpiredToken(t *testing.T) { defer server.Close() client := NewClient(DefaultClientID).(*httpClient) - _, err := client.Poll(context.Background(), server.URL, "test-device-code", 10*time.Millisecond, 60) + _, err := client.Poll(context.Background(), mustParseURL(t, server.URL), "test-device-code", 10*time.Millisecond, 60) if err == nil { t.Fatal("Poll() expected error, got nil") } @@ -444,7 +454,7 @@ func TestPoll_AccessDenied(t *testing.T) { defer server.Close() client := NewClient(DefaultClientID).(*httpClient) - _, err := client.Poll(context.Background(), server.URL, "test-device-code", 10*time.Millisecond, 60) + _, err := client.Poll(context.Background(), mustParseURL(t, server.URL), "test-device-code", 10*time.Millisecond, 60) if err == nil { t.Fatal("Poll() expected error, got nil") } @@ -470,7 +480,7 @@ func TestPoll_Timeout(t *testing.T) { defer server.Close() client := NewClient(DefaultClientID).(*httpClient) - _, err := client.Poll(context.Background(), server.URL, "test-device-code", 10*time.Millisecond, 0) + _, err := client.Poll(context.Background(), mustParseURL(t, server.URL), "test-device-code", 10*time.Millisecond, 0) if err == nil { t.Fatal("Poll() expected error, got nil") } @@ -499,7 +509,7 @@ func TestPoll_ContextCancellation(t *testing.T) { cancel() client := NewClient(DefaultClientID).(*httpClient) - _, err := client.Poll(ctx, server.URL, "test-device-code", 10*time.Millisecond, 3600) + _, err := client.Poll(ctx, mustParseURL(t, server.URL), "test-device-code", 10*time.Millisecond, 3600) if err == nil { t.Fatal("Poll() expected error, got nil") } diff --git a/internal/oauth/http_transport.go b/internal/oauth/http_transport.go index 1664c711f0..854dd61138 100644 --- a/internal/oauth/http_transport.go +++ b/internal/oauth/http_transport.go @@ -5,6 +5,8 @@ import ( "net/http" "sync" "time" + + "github.com/sourcegraph/sourcegraph/lib/errors" ) var _ http.Transport @@ -22,7 +24,7 @@ type Transport struct { } // storeRefreshedTokenFn is the function the transport should use to persist the token - mainly used during -// tests to swap out the implementation out with a mock +// tests to swap out the implementation with a mock var storeRefreshedTokenFn = StoreToken // RoundTrip implements http.RoundTripper. @@ -59,7 +61,8 @@ func (t *Transport) getToken(ctx context.Context) (Token, error) { } t.Token = token if token != prevToken { - // try to save the token if we fail let the request continue with in memory token + // Try to save the token. + // If we fail let the request continue with the in-memory token _ = storeRefreshedTokenFn(ctx, token) } @@ -81,7 +84,12 @@ func maybeRefresh(ctx context.Context, token *Token) (*Token, error) { return nil, err } - next := resp.Token(token.Endpoint) + endpointURL, err := token.EndpointURL() + if err != nil { + return nil, errors.Wrap(err, "invalid token endpoint") + } + + next := resp.Token(endpointURL) next.ClientID = token.ClientID return next, nil } diff --git a/internal/secrets/keyring.go b/internal/secrets/keyring.go index 9464b1054c..e9bd8fbeb1 100644 --- a/internal/secrets/keyring.go +++ b/internal/secrets/keyring.go @@ -2,7 +2,7 @@ package secrets import ( "context" - "strings" + "net/url" "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/zalando/go-keyring" @@ -18,8 +18,8 @@ type keyringStore struct { } // Open opens the system keyring for the Sourcegraph CLI. -func Open(ctx context.Context, endpoint string) (*keyringStore, error) { - endpoint = strings.TrimRight(strings.TrimSpace(endpoint), "/") +func Open(ctx context.Context, endpointURL *url.URL) (*keyringStore, error) { + endpoint := endpointURL.String() if endpoint == "" { return nil, errors.New("endpoint cannot be empty") } diff --git a/internal/secrets/keyring_test.go b/internal/secrets/keyring_test.go index 65d2002782..a8910318e6 100644 --- a/internal/secrets/keyring_test.go +++ b/internal/secrets/keyring_test.go @@ -2,34 +2,35 @@ package secrets import ( "context" + "net/url" "testing" ) func TestOpen(t *testing.T) { tests := []struct { name string - endpoint string + endpoint *url.URL wantServiceName string wantErr bool }{ { - name: "normalized endpoint", - endpoint: " https://sourcegraph.example.com/ ", + name: "simple endpoint", + endpoint: &url.URL{Scheme: "https", Host: "sourcegraph.example.com"}, wantServiceName: "Sourcegraph CLI ", }, { - name: "normalized endpoint with path", - endpoint: " https://sourcegraph.example.com/sourcegraph/ ", + name: "endpoint with path", + endpoint: &url.URL{Scheme: "https", Host: "sourcegraph.example.com", Path: "/sourcegraph"}, wantServiceName: "Sourcegraph CLI ", }, { - name: "normalized endpoint with nested path", - endpoint: "https://sourcegraph.example.com/custom/path///", + name: "endpoint with nested path", + endpoint: &url.URL{Scheme: "https", Host: "sourcegraph.example.com", Path: "/custom/path"}, wantServiceName: "Sourcegraph CLI ", }, { name: "empty endpoint", - endpoint: " / ", + endpoint: &url.URL{Scheme: "", Host: ""}, wantErr: true, }, } From 882a0745316e135a33dc48fc30ce168d093b6275 Mon Sep 17 00:00:00 2001 From: Warren Gifford Date: Fri, 13 Mar 2026 10:09:58 -0700 Subject: [PATCH 550/647] remove sbom dependent commands (#1273) --- .gitignore | 1 - CHANGELOG.md | 4 + cmd/src/main.go | 1 - cmd/src/sbom.go | 36 ----- cmd/src/sbom_fetch.go | 295 ----------------------------------- cmd/src/sbom_utils.go | 310 ------------------------------------- cmd/src/signature.go | 36 ----- cmd/src/signature_fetch.go | 202 ------------------------ 8 files changed, 4 insertions(+), 881 deletions(-) delete mode 100644 cmd/src/sbom.go delete mode 100644 cmd/src/sbom_fetch.go delete mode 100644 cmd/src/sbom_utils.go delete mode 100644 cmd/src/signature.go delete mode 100644 cmd/src/signature_fetch.go diff --git a/.gitignore b/.gitignore index 5a3d0f8b09..e0f1fba3a9 100644 --- a/.gitignore +++ b/.gitignore @@ -14,4 +14,3 @@ bazel-zoekt bazel-src-cli .DS_Store samples -sourcegraph-sboms/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 409805aa3e..0f87c3d286 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,10 @@ All notable changes to `src-cli` are documented in this file. ### Changed +### Removed + +- Removed `src sbom` and `src signature` commands. SBOMs and container signatures are no longer published as of Sourcegraph 7.1.0. + ## 6.7.1104 ### Added diff --git a/cmd/src/main.go b/cmd/src/main.go index 00f0366781..fa308072b7 100644 --- a/cmd/src/main.go +++ b/cmd/src/main.go @@ -61,7 +61,6 @@ The commands are: orgs,org manages organizations teams,team manages teams repos,repo manages repositories - sbom manages SBOM (Software Bill of Materials) data search search for results on Sourcegraph search-jobs manages search jobs serve-git serves your local git repositories over HTTP for Sourcegraph to pull diff --git a/cmd/src/sbom.go b/cmd/src/sbom.go deleted file mode 100644 index ff1a0a5c33..0000000000 --- a/cmd/src/sbom.go +++ /dev/null @@ -1,36 +0,0 @@ -package main - -import ( - "flag" - "fmt" -) - -var sbomCommands commander - -func init() { - usage := `'src sbom' fetches and verifies SBOM (Software Bill of Materials) data for Sourcegraph containers. - -Usage: - - src sbom command [command options] - -The commands are: - - fetch fetch SBOMs for a released version of Sourcegraph -` - flagSet := flag.NewFlagSet("sbom", flag.ExitOnError) - handler := func(args []string) error { - sbomCommands.run(flagSet, "src sbom", usage, args) - return nil - } - - // Register the command. - commands = append(commands, &command{ - flagSet: flagSet, - aliases: []string{"sbom"}, - handler: handler, - usageFunc: func() { - fmt.Println(usage) - }, - }) -} diff --git a/cmd/src/sbom_fetch.go b/cmd/src/sbom_fetch.go deleted file mode 100644 index 6a8ad4aa85..0000000000 --- a/cmd/src/sbom_fetch.go +++ /dev/null @@ -1,295 +0,0 @@ -package main - -import ( - "bytes" - "encoding/base64" - "encoding/json" - "flag" - "fmt" - "os" - "os/exec" - "path/filepath" - "strings" - "unicode" - - "github.com/sourcegraph/sourcegraph/lib/output" - - "github.com/sourcegraph/src-cli/internal/cmderrors" -) - -const sbomPublicKey = "https://storage.googleapis.com/sourcegraph-release-sboms/keys/cosign_keyring-cosign-1.pub" - -func init() { - usage := ` -'src sbom fetch' fetches and verifies SBOMs for the given release version of Sourcegraph. - -Usage: - - src sbom fetch -v [--image ] [--exclude-image ] - -Examples: - - $ src sbom fetch -v 5.8.0 # Fetch all SBOMs for the 5.8.0 release - - $ src sbom fetch -v 5.8.0 --image frontend # Fetch SBOM only for the frontend image - - $ src sbom fetch -v 5.8.0 --image "redis*" # Fetch SBOMs for all images with names beginning with 'redis' - - $ src sbom fetch -v 5.8.0 --image "frontend,redis*" # Fetch SBOMs for frontend, and all redis images - - $ src sbom fetch -v 5.8.0 --exclude-image "sg,*redis*" # Fetch SBOMs for all images, except sg and redis - - $ src sbom fetch -v 5.8.0 --image "postgres*" --exclude-image "*exporter*" # Fetch SBOMs for all postgres images, except exporters - - $ src sbom fetch -v 5.8.123 -internal -d /tmp/sboms # Fetch all SBOMs for the internal 5.8.123 release and store them in /tmp/sboms -` - - flagSet := flag.NewFlagSet("fetch", flag.ExitOnError) - versionFlag := flagSet.String("v", "", "The version of Sourcegraph to fetch SBOMs for.") - outputDirFlag := flagSet.String("d", "sourcegraph-sboms", "The directory to store validated SBOMs in.") - internalReleaseFlag := flagSet.Bool("internal", false, "Fetch SBOMs for an internal release. Defaults to false.") - insecureIgnoreTransparencyLogFlag := flagSet.Bool("insecure-ignore-tlog", false, "Disable transparency log verification. Defaults to false.") - imageFlag := flagSet.String("image", "", "Filter list of image names, to only fetch SBOMs for Docker images with names matching these patterns. Supports literal names, like frontend, and glob patterns like '*postgres*'. Multiple patterns can be specified as a comma-separated list (e.g., 'frontend,*postgres-1?-*'). The 'sourcegraph/' prefix is optional. If not specified, SBOMs for all images are fetched.") - excludeImageFlag := flagSet.String("exclude-image", "", "Exclude Docker images with names matching these patterns from being fetched. Supports the same formats as --image. Takes precedence over --image filters.") - - handler := func(args []string) error { - c := cosignConfig{ - publicKey: sbomPublicKey, - } - - if err := flagSet.Parse(args); err != nil { - return err - } - - if len(flagSet.Args()) != 0 { - return cmderrors.Usage("additional arguments not allowed") - } - - if versionFlag == nil || *versionFlag == "" { - return cmderrors.Usage("version is required") - } - c.version = sanitizeVersion(*versionFlag) - - if outputDirFlag == nil || *outputDirFlag == "" { - return cmderrors.Usage("output directory is required") - } - c.outputDir = getOutputDir(*outputDirFlag, c.version) - - if internalReleaseFlag == nil || !*internalReleaseFlag { - c.internalRelease = false - } else { - c.internalRelease = true - } - - if insecureIgnoreTransparencyLogFlag != nil && *insecureIgnoreTransparencyLogFlag { - c.insecureIgnoreTransparencyLog = true - } - - if imageFlag != nil && *imageFlag != "" { - // Parse comma-separated patterns - patterns := strings.Split(*imageFlag, ",") - for i, pattern := range patterns { - patterns[i] = strings.TrimSpace(pattern) - } - c.imageFilters = patterns - } - - if excludeImageFlag != nil && *excludeImageFlag != "" { - // Parse comma-separated exclude patterns - patterns := strings.Split(*excludeImageFlag, ",") - for i, pattern := range patterns { - patterns[i] = strings.TrimSpace(pattern) - } - c.excludeImageFilters = patterns - } - - out := output.NewOutput(flagSet.Output(), output.OutputOpts{Verbose: *verbose}) - - if err := verifyCosign(); err != nil { - return cmderrors.ExitCode(1, err) - } - - images, err := c.getImageList() - if err != nil { - return err - } - - out.Writef("Fetching SBOMs and validating signatures for all %d images in the Sourcegraph %s release...\n", len(images), c.version) - - if c.insecureIgnoreTransparencyLog { - out.WriteLine(output.Line("⚠️", output.StyleWarning, "WARNING: Transparency log verification is disabled, increasing the risk that SBOMs may have been tampered with.")) - out.WriteLine(output.Line("️", output.StyleWarning, " This setting should only be used for testing or under explicit instruction from Sourcegraph.\n")) - } - - var successCount, failureCount int - for _, image := range images { - stopSpinner := make(chan bool) - go spinner(image, stopSpinner) - - _, err = c.getSBOMForImageVersion(image, c.version) - - stopSpinner <- true - - if err != nil { - out.WriteLine(output.Line(output.EmojiFailure, output.StyleWarning, - fmt.Sprintf("\r%s: error fetching and validating SBOM:\n %v", image, err))) - failureCount += 1 - } else { - out.WriteLine(output.Line("\r\u2705", output.StyleSuccess, image)) - successCount += 1 - } - } - - out.Write("") - if failureCount == 0 && successCount == 0 { - out.WriteLine(output.Line("🔴", output.StyleWarning, "Failed to fetch SBOMs for any images")) - } - if failureCount > 0 { - out.WriteLine(output.Line("🟠", output.StyleOrange, fmt.Sprintf("Fetched verified SBOMs for %d images, but failed to fetch SBOMs for %d images", successCount, failureCount))) - } else if successCount > 0 { - out.WriteLine(output.Line("🟢", output.StyleSuccess, fmt.Sprintf("Fetched verified SBOMs for %d images", successCount))) - } - - out.Writef("\nFetched and validated SBOMs have been written to `%s`.\n", c.outputDir) - out.WriteLine(output.Linef("", output.StyleBold, "Your Sourcegraph deployment may not use all of these images. Please check your deployment to confirm which images are used.\n")) - - if failureCount > 0 || successCount == 0 { - return cmderrors.ExitCode1 - } - - return nil - } - - sbomCommands = append(sbomCommands, &command{ - flagSet: flagSet, - handler: handler, - usageFunc: func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src sbom %s':\n", flagSet.Name()) - flagSet.PrintDefaults() - fmt.Println(usage) - }, - }) -} - -func (c cosignConfig) getSBOMForImageVersion(image string, version string) (string, error) { - hash, err := getImageDigest(image, version) - if err != nil { - return "", err - } - - sbom, err := c.getSBOMForImageHash(image, hash) - if err != nil { - return "", err - } - - return sbom, nil -} - -func (c cosignConfig) getSBOMForImageHash(image string, hash string) (string, error) { - tempDir, err := os.MkdirTemp("", "sbom-") - if err != nil { - return "", fmt.Errorf("failed to create temporary directory: %w", err) - } - defer os.RemoveAll(tempDir) - - outputFile := filepath.Join(tempDir, "attestation.json") - - cosignArgs := []string{ - "verify-attestation", - "--key", c.publicKey, - "--type", "cyclonedx", - fmt.Sprintf("%s@%s", image, hash), - "--output-file", outputFile, - } - - if c.insecureIgnoreTransparencyLog { - cosignArgs = append(cosignArgs, "--insecure-ignore-tlog") - } - - cmd := exec.Command("cosign", cosignArgs...) - - output, err := cmd.CombinedOutput() - if err != nil { - return "", fmt.Errorf("SBOM fetching or validation failed: %w\nOutput: %s", err, output) - } - - attestation, err := os.ReadFile(outputFile) - if err != nil { - return "", fmt.Errorf("failed to read SBOM file: %w", err) - } - - sbom, err := extractSBOM(attestation) - if err != nil { - return "", fmt.Errorf("failed to extract SBOM from attestation: %w", err) - } - - c.storeSBOM(sbom, image) - - return sbom, nil -} - -type attestation struct { - PayloadType string `json:"payloadType"` - Base64Payload string `json:"payload"` -} - -func extractSBOM(attestationBytes []byte) (string, error) { - // Ensure we only use the first line - occasionally Cosign includes multiple lines - lines := bytes.Split(attestationBytes, []byte("\n")) - if len(lines) == 0 { - return "", fmt.Errorf("attestation is empty") - } - - var a attestation - if err := json.Unmarshal(lines[0], &a); err != nil { - return "", fmt.Errorf("failed to unmarshal attestation: %w", err) - } - - if a.PayloadType != "application/vnd.in-toto+json" { - return "", fmt.Errorf("unexpected payload type: %s", a.PayloadType) - } - - decodedPayload, err := base64.StdEncoding.DecodeString(a.Base64Payload) - if err != nil { - return "", fmt.Errorf("failed to decode payload: %w", err) - } - - // Unmarshal the decoded payload to extract predicate - var payload map[string]json.RawMessage - if err := json.Unmarshal(decodedPayload, &payload); err != nil { - return "", fmt.Errorf("failed to unmarshal decoded payload: %w", err) - } - - // Extract just the predicate field - predicate, ok := payload["predicate"] - if !ok { - return "", fmt.Errorf("no predicate field found in payload") - } - - return string(predicate), nil -} - -func (c cosignConfig) storeSBOM(sbom string, image string) error { - // Make the image name safe for use as a filename - safeImageName := strings.Map(func(r rune) rune { - if unicode.IsLetter(r) || unicode.IsDigit(r) || r == '-' || r == '_' { - return r - } - return '_' - }, image) - - // Create the output file path - outputFile := filepath.Join(c.outputDir, safeImageName+".cdx.json") - - // Ensure the output directory exists - if err := os.MkdirAll(c.outputDir, 0755); err != nil { - return fmt.Errorf("failed to create output directory: %w", err) - } - - // Write the SBOM to the file - if err := os.WriteFile(outputFile, []byte(sbom), 0644); err != nil { - return fmt.Errorf("failed to write SBOM file: %w", err) - } - - return nil -} diff --git a/cmd/src/sbom_utils.go b/cmd/src/sbom_utils.go deleted file mode 100644 index 5bae2c970c..0000000000 --- a/cmd/src/sbom_utils.go +++ /dev/null @@ -1,310 +0,0 @@ -package main - -// Utility functions used by the SBOM and Signature commands. - -import ( - "bufio" - "encoding/json" - "fmt" - "io" - "net/http" - "os/exec" - "path" - "path/filepath" - "regexp" - "strings" - "time" - - "github.com/sourcegraph/sourcegraph/lib/errors" -) - -const imageListBaseURL = "https://storage.googleapis.com/sourcegraph-release-sboms" -const imageListFilename = "release-image-list.txt" - -type cosignConfig struct { - publicKey string - outputDir string - version string - internalRelease bool - insecureIgnoreTransparencyLog bool - imageFilters []string - excludeImageFilters []string -} - -// TokenResponse represents the JSON response from dockerHub's token service -type dockerHubTokenResponse struct { - Token string `json:"token"` -} - -// getImageDigest returns the sha256 hash for the given image and tag -// It supports multiple registries -func getImageDigest(image string, tag string) (string, error) { - if strings.HasPrefix(image, "sourcegraph/") { - return getImageDigestDockerHub(image, tag) - } else if strings.HasPrefix(image, "us-central1-docker.pkg.dev/") { - return getImageDigestGcloud(image, tag) - } else { - return "", fmt.Errorf("unsupported image registry: %s", image) - } -} - -// -// Implement functionality for Docker Hub - -// getImageDigestDockerHub returns the sha256 digest for the given image and tag from DockerHub -func getImageDigestDockerHub(image string, tag string) (string, error) { - // Construct the DockerHub manifest URL - url := fmt.Sprintf("https://registry-1.docker.io/v2/%s/manifests/%s", image, tag) - - token, err := getDockerHubAuthToken(image) - if err != nil { - return "", err - } - - // Create a new HTTP request with the authorization header - req, err := http.NewRequest("GET", url, nil) - if err != nil { - return "", err - } - req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token)) - req.Header.Add("Accept", "application/vnd.docker.distribution.manifest.v2+json, application/vnd.oci.image.manifest.v1+json") - - // Make the HTTP request - resp, err := http.DefaultClient.Do(req) - if err != nil { - return "", fmt.Errorf("failed to fetch image manifest: %v", err) - } - defer resp.Body.Close() - - // Check for a successful response - if resp.StatusCode != http.StatusOK { - return "", fmt.Errorf("failed to get manifest - check %s is a valid Sourcegraph release, status code: %d", tag, resp.StatusCode) - } - - // Get the image digest from the `Docker-Content-Digest` header - digest := resp.Header.Get("Docker-Content-Digest") - if digest == "" { - return "", fmt.Errorf("digest not found in response headers") - } - // Return the image's digest (hash) - return digest, nil -} - -// getDockerHubAuthToken returns an auth token with scope to pull the given image -// Note that the token has a short validity so it should be used immediately -func getDockerHubAuthToken(image string) (string, error) { - // Set the DockerHub authentication URL - url := fmt.Sprintf("https://auth.docker.io/token?service=registry.docker.io&scope=repository:%s:pull", image) - - // Create a new HTTP request - resp, err := http.Get(url) - if err != nil { - return "", fmt.Errorf("failed to get token: %v", err) - } - defer resp.Body.Close() - - // Check if the response status is 200 OK - if resp.StatusCode != http.StatusOK { - return "", fmt.Errorf("failed to get token, status code: %d", resp.StatusCode) - } - - // Read the response body - body, err := io.ReadAll(resp.Body) - if err != nil { - return "", fmt.Errorf("failed to read response body: %v", err) - } - - // Unmarshal the JSON response - var tokenResponse dockerHubTokenResponse - if err := json.Unmarshal(body, &tokenResponse); err != nil { - return "", fmt.Errorf("failed to parse token response: %v", err) - } - - // Return the token - return tokenResponse.Token, nil -} - -// -// Implement functionality for GCP Artifact Registry - -// getImageDigestGcloud fetches the OCI image manifest from GCP Artifact Registry and returns the image digest -func getImageDigestGcloud(image string, tag string) (string, error) { - // Validate image path to ensure it's a valid GCP Artifact Registry image - if !strings.HasPrefix(image, "us-central1-docker.pkg.dev/") { - return "", fmt.Errorf("invalid image format: %s", image) - } - - // Get the GCP access token - token, err := getGcloudAccessToken() - if err != nil { - return "", fmt.Errorf("error getting access token: %v", err) - } - - parts := strings.SplitN(image, "/", 2) - if len(parts) != 2 { - return "", fmt.Errorf("invalid image format: %s", image) - } - domain := parts[0] - repositoryPath := parts[1] - - // Create the URL to fetch the manifest for the specific image and tag - url := fmt.Sprintf("https://%s/v2/%s/manifests/%s", domain, repositoryPath, tag) - - // Create a new HTTP GET request - req, err := http.NewRequest("GET", url, nil) - if err != nil { - return "", fmt.Errorf("failed to create HTTP request: %v", err) - } - - // Add the Authorization and Accept headers - req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token)) - req.Header.Add("Accept", "application/vnd.docker.distribution.manifest.v2+json, application/vnd.oci.image.manifest.v1+json") - - // Perform the HTTP request - resp, err := http.DefaultClient.Do(req) - if err != nil { - return "", fmt.Errorf("failed to fetch manifest: %v", err) - } - defer resp.Body.Close() - - // Check if the request was successful - if resp.StatusCode != http.StatusOK { - body, _ := io.ReadAll(resp.Body) - return "", fmt.Errorf("failed to get manifest, status code: %d, response: %s", resp.StatusCode, string(body)) - } - - // Get the image digest from the `Docker-Content-Digest` header - digest := resp.Header.Get("Docker-Content-Digest") - if digest == "" { - return "", fmt.Errorf("digest not found in response headers") - } - - return digest, nil -} - -// getGcloudAccessToken runs 'gcloud auth print-access-token' and returns the access token -func getGcloudAccessToken() (string, error) { - // Execute the gcloud command to get the access token - cmd := exec.Command("gcloud", "auth", "print-access-token") - out, err := cmd.Output() - if err != nil { - return "", fmt.Errorf("failed to retrieve access token using `gcloud auth`. Ensure that gcloud is installed and you have authenticated: %v", err) - } - - // Trim any extra whitespace or newlines - token := strings.TrimSpace(string(out)) - return token, nil -} - -var spinnerChars = []rune{'⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'} - -func spinner(name string, stop chan bool) { - i := 0 - for { - select { - case <-stop: - return - default: - fmt.Printf("\r%s %s", string(spinnerChars[i%len(spinnerChars)]), name) - i++ - time.Sleep(100 * time.Millisecond) - } - } -} - -func getOutputDir(parentDir, version string) string { - return path.Join(parentDir, "sourcegraph-"+version) -} - -// sanitizeVersion removes any leading "v" from the version string -func sanitizeVersion(version string) string { - return strings.TrimPrefix(version, "v") -} - -func verifyCosign() error { - _, err := exec.LookPath("cosign") - if err != nil { - return errors.New("SBOM verification requires 'cosign' to be installed and available in $PATH. See https://docs.sigstore.dev/cosign/system_config/installation/") - } - return nil -} - -func (c cosignConfig) getImageList() ([]string, error) { - imageReleaseListURL := c.getImageReleaseListURL() - - resp, err := http.Get(imageReleaseListURL) - if err != nil { - return nil, fmt.Errorf("failed to fetch image list: %w", err) - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - // Compare version number against a regex that matches versions up to and including 5.8.0 - versionRegex := regexp.MustCompile(`^v?[0-5]\.([0-7]\.[0-9]+|8\.0)$`) - if versionRegex.MatchString(c.version) { - return nil, fmt.Errorf("unsupported version %s: SBOMs are only available for Sourcegraph releases after 5.8.0", c.version) - } - return nil, fmt.Errorf("failed to fetch list of images - check that %s is a valid Sourcegraph release: HTTP status %d", c.version, resp.StatusCode) - } - - scanner := bufio.NewScanner(resp.Body) - var images []string - for scanner.Scan() { - image := strings.TrimSpace(scanner.Text()) - if image != "" { - // Strip off a version suffix if present - parts := strings.SplitN(image, ":", 2) - imageName := parts[0] - - // If the --image arg was provided, and if the image name doesn't match any of the filters - // then skip this image - if len(c.imageFilters) > 0 && !matchesImageFilter(c.imageFilters, imageName) { - continue - } - - // If the --exclude-image arg was provided, and if the image name does match any of the filters - // then skip this image - if len(c.excludeImageFilters) > 0 && matchesImageFilter(c.excludeImageFilters, imageName) { - continue - } - - images = append(images, imageName) - } - } - - if err := scanner.Err(); err != nil { - return nil, fmt.Errorf("error reading image list: %w", err) - } - - return images, nil -} - -// getImageReleaseListURL returns the URL for the list of images in a release, based on the version and whether it's an internal release. -func (c *cosignConfig) getImageReleaseListURL() string { - if c.internalRelease { - return fmt.Sprintf("%s/release-internal/%s/%s", imageListBaseURL, c.version, imageListFilename) - } else { - return fmt.Sprintf("%s/release/%s/%s", imageListBaseURL, c.version, imageListFilename) - } -} - -// matchesImageFilter checks if the image name from the list of published images -// matches any user-provided --image or --exclude-image glob patterns -// It matches against both the full image name, and the image name without the "sourcegraph/" prefix. -func matchesImageFilter(patterns []string, imageName string) bool { - for _, pattern := range patterns { - // Try matching against the full image name - if matched, _ := filepath.Match(pattern, imageName); matched { - return true - } - - // Try matching against the image name without "sourcegraph/" prefix - if after, ok := strings.CutPrefix(imageName, "sourcegraph/"); ok { - shortName := after - if matched, _ := filepath.Match(pattern, shortName); matched { - return true - } - } - } - return false -} diff --git a/cmd/src/signature.go b/cmd/src/signature.go deleted file mode 100644 index 0d61014aec..0000000000 --- a/cmd/src/signature.go +++ /dev/null @@ -1,36 +0,0 @@ -package main - -import ( - "flag" - "fmt" -) - -var signatureCommands commander - -func init() { - usage := `'src signature' verifies published signatures for Sourcegraph containers. - -Usage: - - src signature command [command options] - -The commands are: - - verify verify signatures for a Sourcegraph release -` - flagSet := flag.NewFlagSet("signature", flag.ExitOnError) - handler := func(args []string) error { - signatureCommands.run(flagSet, "src signature", usage, args) - return nil - } - - // Register the command. - commands = append(commands, &command{ - flagSet: flagSet, - aliases: []string{"signature", "sig"}, - handler: handler, - usageFunc: func() { - fmt.Println(usage) - }, - }) -} diff --git a/cmd/src/signature_fetch.go b/cmd/src/signature_fetch.go deleted file mode 100644 index 4b9fd03a16..0000000000 --- a/cmd/src/signature_fetch.go +++ /dev/null @@ -1,202 +0,0 @@ -package main - -import ( - "flag" - "fmt" - "os" - "os/exec" - "path/filepath" - "strings" - - "github.com/sourcegraph/sourcegraph/lib/output" - - "github.com/sourcegraph/src-cli/internal/cmderrors" -) - -const signaturePublicKey = "https://storage.googleapis.com/sourcegraph-release-sboms/keys/cosign_keyring-cosign_image_signing_key-1.pub" - -func init() { - usage := ` -'src signature verify' verifies signatures for the given release version of Sourcegraph. - -Usage: - - src signature verify -v - -Examples: - - $ src signature verify -v 5.11.4013 # Verify all signatures for the 5.11.4013 release - - $ src signature verify -v 6.0.0 -d /tmp/signatures # Verify all signatures for the 6.0.0 release and write verified image digests under /tmp/signatures -` - - flagSet := flag.NewFlagSet("verify", flag.ExitOnError) - versionFlag := flagSet.String("v", "", "The version of Sourcegraph to verify signatures for.") - outputDirFlag := flagSet.String("d", "", "The directory to store verified image digests in.") - insecureIgnoreTransparencyLogFlag := flagSet.Bool("insecure-ignore-tlog", false, "Disable transparency log verification. Defaults to false.") - - handler := func(args []string) error { - c := cosignConfig{ - publicKey: signaturePublicKey, - internalRelease: false, - } - - if err := flagSet.Parse(args); err != nil { - return err - } - - if len(flagSet.Args()) != 0 { - return cmderrors.Usage("additional arguments not allowed") - } - - if versionFlag == nil || *versionFlag == "" { - return cmderrors.Usage("version is required") - } - c.version = sanitizeVersion(*versionFlag) - - if outputDirFlag != nil && *outputDirFlag != "" { - c.outputDir = getOutputDir(*outputDirFlag, c.version) - } - - if insecureIgnoreTransparencyLogFlag != nil && *insecureIgnoreTransparencyLogFlag { - c.insecureIgnoreTransparencyLog = true - } - - out := output.NewOutput(flagSet.Output(), output.OutputOpts{Verbose: *verbose}) - - if err := verifyCosign(); err != nil { - return cmderrors.ExitCode(1, err) - } - - images, err := c.getImageList() - if err != nil { - return err - } - - out.Writef("Verifying signatures for all %d images in the Sourcegraph %s release...\n", len(images), c.version) - - if c.insecureIgnoreTransparencyLog { - out.WriteLine(output.Line("⚠️", output.StyleWarning, "WARNING: Transparency log verification is disabled, increasing the risk that images may have been tampered with.")) - out.WriteLine(output.Line("️", output.StyleWarning, " This setting should only be used for testing or under explicit instruction from Sourcegraph.\n")) - } - - var successCount, failureCount int - var verifiedDigests []string - for _, image := range images { - stopSpinner := make(chan bool) - go spinner(image, stopSpinner) - - verifiedDigest, err := c.verifySignatureForImageVersion(image, c.version) - verifiedDigests = append(verifiedDigests, image+"@"+verifiedDigest) - - stopSpinner <- true - - if err != nil { - out.WriteLine(output.Line(output.EmojiFailure, output.StyleWarning, - fmt.Sprintf("\r%s: error verifying signature:\n %v", image, err))) - failureCount += 1 - } else { - out.WriteLine(output.Line("\r\u2705", output.StyleSuccess, image+"@"+verifiedDigest)) - successCount += 1 - } - } - - out.Write("") - if successCount > 0 && failureCount > 0 { - out.WriteLine(output.Line("🟠", output.StyleOrange, fmt.Sprintf("Verified signatures and digests for %d images, but failed to verify signatures for %d images", successCount, failureCount))) - } else if successCount > 0 && failureCount == 0 { - out.WriteLine(output.Line("🟢", output.StyleSuccess, fmt.Sprintf("Verified signatures and digests for %d images", successCount))) - } else { - out.WriteLine(output.Line("🔴", output.StyleWarning, "Failed to verify signatures for any images")) - - } - - if c.outputDir != "" { - if err = c.writeVerifiedDigests(verifiedDigests); err != nil { - out.WriteLine(output.Line("🔴", output.StyleWarning, err.Error())) - return cmderrors.ExitCode1 - } - out.Writef("\nVerified digests have been written to `%s`.\n", c.getOutputFilepath()) - } - out.WriteLine(output.Linef("", output.StyleBold, "Your Sourcegraph deployment may not use all of these images. Please check your deployment to confirm which images are used.\n")) - - if failureCount > 0 || successCount == 0 { - return cmderrors.ExitCode1 - } - - return nil - } - - signatureCommands = append(signatureCommands, &command{ - flagSet: flagSet, - handler: handler, - usageFunc: func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src signature %s':\n", flagSet.Name()) - flagSet.PrintDefaults() - fmt.Println(usage) - }, - }) -} - -func (c cosignConfig) verifySignatureForImageVersion(image string, version string) (string, error) { - digest, err := getImageDigest(image, version) - if err != nil { - return "", err - } - - err = c.verifySignatureForImageHash(image, digest) - if err != nil { - return "", err - } - - // Only return the digest if the signature is verified - return digest, nil -} - -func (c cosignConfig) verifySignatureForImageHash(image string, hash string) error { - tempDir, err := os.MkdirTemp("", "signature-") - if err != nil { - return fmt.Errorf("failed to create temporary directory: %w", err) - } - defer os.RemoveAll(tempDir) - - cosignArgs := []string{ - "verify", - "--key", c.publicKey, - fmt.Sprintf("%s@%s", image, hash), - } - - if c.insecureIgnoreTransparencyLog { - cosignArgs = append(cosignArgs, "--insecure-ignore-tlog") - } - - cmd := exec.Command("cosign", cosignArgs...) - - output, err := cmd.CombinedOutput() - if err != nil { - return fmt.Errorf("signature verification failed: %w\nOutput: %s", err, output) - } - - return nil -} - -func (c cosignConfig) writeVerifiedDigests(verifiedDigests []string) error { - // Create the output file - outputFile := c.getOutputFilepath() - err := os.MkdirAll(c.outputDir, 0755) - if err != nil { - return fmt.Errorf("failed to create output directory: %w", err) - } - - // Write the verified digests to the file, one per line - err = os.WriteFile(outputFile, []byte(strings.Join(verifiedDigests, "\n")+"\n"), 0644) - if err != nil { - return fmt.Errorf("failed to write verified digests to file: %w", err) - } - - return nil -} - -func (c cosignConfig) getOutputFilepath() string { - return filepath.Join(c.outputDir, "verified-digests.txt") -} From d206288080aa7949ad6aad26617c7185a0ce51c7 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Tue, 17 Mar 2026 16:31:21 +0200 Subject: [PATCH 551/647] feat/auth: add `src auth token` (#1275) * add TokenRefresher and NewTransport - TokenRefresher centralizes refreshing of OAuth tokens - NewTransport creates an OAuth transport while making sure it is initialized with a TokenRefresher * add cmd `src auth token` that prints access token or oauth token * set refresh window to 5 min --- cmd/src/auth.go | 37 ++++++++ cmd/src/auth_token.go | 68 ++++++++++++++ cmd/src/auth_token_test.go | 128 ++++++++++++++++++++++++++ cmd/src/main.go | 1 + internal/api/api.go | 5 +- internal/oauth/http_transport.go | 55 ++++++----- internal/oauth/http_transport_test.go | 24 ++--- 7 files changed, 282 insertions(+), 36 deletions(-) create mode 100644 cmd/src/auth.go create mode 100644 cmd/src/auth_token.go create mode 100644 cmd/src/auth_token_test.go diff --git a/cmd/src/auth.go b/cmd/src/auth.go new file mode 100644 index 0000000000..e2147787d6 --- /dev/null +++ b/cmd/src/auth.go @@ -0,0 +1,37 @@ +package main + +import ( + "flag" + "fmt" +) + +var authCommands commander + +func init() { + usage := `'src auth' provides authentication-related helper commands. + +Usage: + + src auth command [command options] + +The commands are: + + token prints the current authentication token + +Use "src auth [command] -h" for more information about a command. +` + + flagSet := flag.NewFlagSet("auth", flag.ExitOnError) + handler := func(args []string) error { + authCommands.run(flagSet, "src auth", usage, args) + return nil + } + + commands = append(commands, &command{ + flagSet: flagSet, + handler: handler, + usageFunc: func() { + fmt.Println(usage) + }, + }) +} diff --git a/cmd/src/auth_token.go b/cmd/src/auth_token.go new file mode 100644 index 0000000000..3b78499593 --- /dev/null +++ b/cmd/src/auth_token.go @@ -0,0 +1,68 @@ +package main + +import ( + "context" + "flag" + "fmt" + + "github.com/sourcegraph/sourcegraph/lib/errors" + + "github.com/sourcegraph/src-cli/internal/oauth" +) + +var ( + loadOAuthToken = oauth.LoadToken + newOAuthTokenRefresher = func(token *oauth.Token) oauthTokenRefresher { + return oauth.NewTokenRefresher(token) + } +) + +type oauthTokenRefresher interface { + GetToken(ctx context.Context) (oauth.Token, error) +} + +func init() { + flagSet := flag.NewFlagSet("token", flag.ExitOnError) + usageFunc := func() { + fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src auth token':\n") + flagSet.PrintDefaults() + } + + handler := func(args []string) error { + if err := flagSet.Parse(args); err != nil { + return err + } + + token, err := resolveAuthToken(context.Background(), cfg) + if err != nil { + return err + } + + fmt.Println(token) + return nil + } + + authCommands = append(authCommands, &command{ + flagSet: flagSet, + handler: handler, + usageFunc: usageFunc, + }) +} + +func resolveAuthToken(ctx context.Context, cfg *config) (string, error) { + if cfg.accessToken != "" { + return cfg.accessToken, nil + } + + oauthToken, err := loadOAuthToken(ctx, cfg.endpointURL) + if err != nil { + return "", errors.Wrap(err, "error loading OAuth token; set SRC_ACCESS_TOKEN or run `src login`") + } + + token, err := newOAuthTokenRefresher(oauthToken).GetToken(ctx) + if err != nil { + return "", errors.Wrap(err, "refreshing OAuth token") + } + + return token.AccessToken, nil +} diff --git a/cmd/src/auth_token_test.go b/cmd/src/auth_token_test.go new file mode 100644 index 0000000000..8471be37f2 --- /dev/null +++ b/cmd/src/auth_token_test.go @@ -0,0 +1,128 @@ +package main + +import ( + "context" + "fmt" + "net/url" + "testing" + + "github.com/sourcegraph/src-cli/internal/oauth" +) + +func TestResolveAuthToken(t *testing.T) { + t.Run("uses configured access token before keyring", func(t *testing.T) { + reset := stubAuthTokenDependencies(t) + defer reset() + + newRefresherCalled := false + newOAuthTokenRefresher = func(*oauth.Token) oauthTokenRefresher { + newRefresherCalled = true + return fakeOAuthTokenRefresher{} + } + + token, err := resolveAuthToken(context.Background(), &config{ + accessToken: "access-token", + endpointURL: mustParseURL(t, "https://example.com"), + }) + if err != nil { + t.Fatal(err) + } + if token != "access-token" { + t.Fatalf("token = %q, want %q", token, "access-token") + } + if newRefresherCalled { + t.Fatal("expected OAuth token refresher not to be created") + } + }) + + t.Run("uses stored oauth token", func(t *testing.T) { + reset := stubAuthTokenDependencies(t) + defer reset() + + loadOAuthToken = func(context.Context, *url.URL) (*oauth.Token, error) { + return &oauth.Token{ + AccessToken: "oauth-token", + }, nil + } + + newOAuthTokenRefresher = func(*oauth.Token) oauthTokenRefresher { + return fakeOAuthTokenRefresher{token: oauth.Token{AccessToken: "oauth-token"}} + } + + token, err := resolveAuthToken(context.Background(), &config{ + endpointURL: mustParseURL(t, "https://example.com"), + }) + if err != nil { + t.Fatal(err) + } + if token != "oauth-token" { + t.Fatalf("token = %q, want %q", token, "oauth-token") + } + }) + + t.Run("refreshes expiring oauth token", func(t *testing.T) { + reset := stubAuthTokenDependencies(t) + defer reset() + + loadOAuthToken = func(context.Context, *url.URL) (*oauth.Token, error) { + return &oauth.Token{AccessToken: "old-token"}, nil + } + + newOAuthTokenRefresher = func(*oauth.Token) oauthTokenRefresher { + return fakeOAuthTokenRefresher{token: oauth.Token{AccessToken: "new-token"}} + } + + token, err := resolveAuthToken(context.Background(), &config{ + endpointURL: mustParseURL(t, "https://example.com"), + }) + if err != nil { + t.Fatal(err) + } + if token != "new-token" { + t.Fatalf("token = %q, want %q", token, "new-token") + } + }) + + t.Run("returns refresh error when shared refresh logic fails", func(t *testing.T) { + reset := stubAuthTokenDependencies(t) + defer reset() + + loadOAuthToken = func(context.Context, *url.URL) (*oauth.Token, error) { + return &oauth.Token{AccessToken: "old-token"}, nil + } + newOAuthTokenRefresher = func(*oauth.Token) oauthTokenRefresher { + return fakeOAuthTokenRefresher{err: fmt.Errorf("refresh failed")} + } + + _, err := resolveAuthToken(context.Background(), &config{ + endpointURL: mustParseURL(t, "https://example.com"), + }) + if err == nil { + t.Fatal("expected error") + } + }) +} + +func stubAuthTokenDependencies(t *testing.T) func() { + t.Helper() + + prevLoad := loadOAuthToken + prevNewRefresher := newOAuthTokenRefresher + + return func() { + loadOAuthToken = prevLoad + newOAuthTokenRefresher = prevNewRefresher + } +} + +type fakeOAuthTokenRefresher struct { + token oauth.Token + err error +} + +func (r fakeOAuthTokenRefresher) GetToken(context.Context) (oauth.Token, error) { + if r.err != nil { + return oauth.Token{}, r.err + } + return r.token, nil +} diff --git a/cmd/src/main.go b/cmd/src/main.go index fa308072b7..0e42c2f465 100644 --- a/cmd/src/main.go +++ b/cmd/src/main.go @@ -50,6 +50,7 @@ The options are: The commands are: + auth authentication helper commands api interacts with the Sourcegraph GraphQL API batch manages batch changes code-intel manages code intelligence data diff --git a/internal/api/api.go b/internal/api/api.go index a824fae1a5..73a0416097 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -110,10 +110,7 @@ func buildTransport(opts ClientOpts, flags *Flags) http.RoundTripper { } if opts.AccessToken == "" && opts.OAuthToken != nil { - transport = &oauth.Transport{ - Base: transport, - Token: opts.OAuthToken, - } + transport = oauth.NewTransport(transport, opts.OAuthToken) } return transport diff --git a/internal/oauth/http_transport.go b/internal/oauth/http_transport.go index 854dd61138..adbc16d546 100644 --- a/internal/oauth/http_transport.go +++ b/internal/oauth/http_transport.go @@ -13,14 +13,24 @@ var _ http.Transport var _ http.RoundTripper = (*Transport)(nil) +const defaultRefreshWindow = 5 * time.Minute + type Transport struct { - Base http.RoundTripper - //Token is a OAuth token (which has a refresh token) that should be used during roundtrip to automatically - //refresh the OAuth access token once the current one has expired or is soon to expire - Token *Token + Base http.RoundTripper + refresher *TokenRefresher +} - //mu is a mutex that should be acquired whenever token used - mu sync.Mutex +type TokenRefresher struct { + token *Token + mu sync.Mutex +} + +func NewTokenRefresher(token *Token) *TokenRefresher { + return &TokenRefresher{token: token} +} + +func NewTransport(base http.RoundTripper, token *Token) *Transport { + return &Transport{Base: base, refresher: NewTokenRefresher(token)} } // storeRefreshedTokenFn is the function the transport should use to persist the token - mainly used during @@ -30,8 +40,7 @@ var storeRefreshedTokenFn = StoreToken // RoundTrip implements http.RoundTripper. func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) { ctx := req.Context() - - token, err := t.getToken(ctx) + token, err := t.refresher.GetToken(ctx) if err != nil { return nil, err } @@ -45,36 +54,40 @@ func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) { return http.DefaultTransport.RoundTrip(req2) } -// getToken returns a value copy of the token. If the token has expired or expiring soon it will be refreshed before returning. +// GetToken returns a value copy of the token. If the token has expired or expiring soon it will be refreshed before returning. // Once the token is refreshed, the in-memory token is updated and a best effort is made to store the token. // // If storing the token fails, no error is returned. An error is only returned if refreshing the token // fails. -func (t *Transport) getToken(ctx context.Context) (Token, error) { - t.mu.Lock() - defer t.mu.Unlock() +func (r *TokenRefresher) GetToken(ctx context.Context) (Token, error) { + r.mu.Lock() + defer r.mu.Unlock() - prevToken := t.Token - token, err := maybeRefresh(ctx, t.Token) + prevToken := r.token + token, err := maybeRefreshToken(ctx, r.token) if err != nil { return Token{}, err } - t.Token = token + r.token = token if token != prevToken { // Try to save the token. // If we fail let the request continue with the in-memory token _ = storeRefreshedTokenFn(ctx, token) } - return *t.Token, nil + return *r.token, nil } -// maybeRefresh conditionally refreshes the token. If the token has expired or is expriing in the next 30s -// it will be refreshed and the updated token will be returned. Otherwise, no refresh occurs and the original -// token is returned. -func maybeRefresh(ctx context.Context, token *Token) (*Token, error) { +// maybeRefreshToken conditionally refreshes the token. If the token has expired or is +// expiring within the default refresh window, it will be refreshed and the updated token returned. +// Otherwise, no refresh occurs and the original token is returned. +func maybeRefreshToken(ctx context.Context, token *Token) (*Token, error) { + if token == nil { + return nil, errors.New("token is nil") + } + // token has NOT expired and is NOT about to expire in 30s - if !(token.HasExpired() || token.ExpiringIn(time.Duration(30)*time.Second)) { + if !(token.HasExpired() || token.ExpiringIn(defaultRefreshWindow)) { return token, nil } client := NewClient(token.ClientID) diff --git a/internal/oauth/http_transport_test.go b/internal/oauth/http_transport_test.go index 4dac832d05..47cb2b0dac 100644 --- a/internal/oauth/http_transport_test.go +++ b/internal/oauth/http_transport_test.go @@ -28,10 +28,14 @@ func newRefreshServer(t *testing.T, accessToken string) *httptest.Server { }) } -func TestMaybeRefresh(t *testing.T) { +func TestTokenRefresherGetToken(t *testing.T) { server := newRefreshServer(t, "new-token") defer server.Close() + originalStoreFn := storeRefreshedTokenFn + storeRefreshedTokenFn = func(context.Context, *Token) error { return nil } + defer func() { storeRefreshedTokenFn = originalStoreFn }() + tests := []struct { name string token *Token @@ -71,14 +75,15 @@ func TestMaybeRefresh(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - got, err := maybeRefresh(context.Background(), tt.token) + refresher := NewTokenRefresher(tt.token) + got, err := refresher.GetToken(context.Background()) if err != nil { - t.Fatalf("maybeRefresh() error = %v", err) + t.Fatalf("GetToken() error = %v", err) } if got.AccessToken != tt.wantAccess { t.Errorf("AccessToken = %q, want %q", got.AccessToken, tt.wantAccess) } - if tt.wantSame && got != tt.token { + if tt.wantSame && refresher.token != tt.token { t.Errorf("token pointer changed for unexpired token") } }) @@ -145,13 +150,10 @@ func TestTransportRoundTrip(t *testing.T) { } var capturedAuth string - tr := &Transport{ - Base: roundTripperFunc(func(req *http.Request) (*http.Response, error) { - capturedAuth = req.Header.Get("Authorization") - return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody}, nil - }), - Token: tt.token, - } + tr := NewTransport(roundTripperFunc(func(req *http.Request) (*http.Response, error) { + capturedAuth = req.Header.Get("Authorization") + return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody}, nil + }), tt.token) _, err := tr.RoundTrip(httptest.NewRequest(http.MethodGet, "http://example.com", nil)) if err != nil { From 21fa1321b7945505e67530736157d66ad10186ce Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Tue, 17 Mar 2026 17:06:53 +0200 Subject: [PATCH 552/647] add --header flag to src auth token to print auth header (#1276) * add --header flag to src auth token to print auth header - for access token print `Authorization: token ` - for oauth token print `Authorization: Bearer ` * update help --- cmd/src/auth.go | 2 +- cmd/src/auth_token.go | 18 ++++++++++++++- cmd/src/auth_token_test.go | 47 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 65 insertions(+), 2 deletions(-) diff --git a/cmd/src/auth.go b/cmd/src/auth.go index e2147787d6..eff5f4bbec 100644 --- a/cmd/src/auth.go +++ b/cmd/src/auth.go @@ -16,7 +16,7 @@ Usage: The commands are: - token prints the current authentication token + token prints the current authentication token or Authorization header Use "src auth [command] -h" for more information about a command. ` diff --git a/cmd/src/auth_token.go b/cmd/src/auth_token.go index 3b78499593..6112799f03 100644 --- a/cmd/src/auth_token.go +++ b/cmd/src/auth_token.go @@ -23,8 +23,11 @@ type oauthTokenRefresher interface { func init() { flagSet := flag.NewFlagSet("token", flag.ExitOnError) + header := flagSet.Bool("header", false, "print the token as an Authorization header") usageFunc := func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src auth token':\n") + fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src auth token':\n\n") + fmt.Fprintf(flag.CommandLine.Output(), "Print the current authentication token.\n") + fmt.Fprintf(flag.CommandLine.Output(), "Use --header to print a complete Authorization header instead.\n\n") flagSet.PrintDefaults() } @@ -38,6 +41,7 @@ func init() { return err } + token = formatAuthTokenOutput(token, cfg.AuthMode(), *header) fmt.Println(token) return nil } @@ -66,3 +70,15 @@ func resolveAuthToken(ctx context.Context, cfg *config) (string, error) { return token.AccessToken, nil } + +func formatAuthTokenOutput(token string, mode AuthMode, header bool) string { + if !header { + return token + } + + if mode == AuthModeAccessToken { + return fmt.Sprintf("Authorization: token %s", token) + } + + return fmt.Sprintf("Authorization: Bearer %s", token) +} diff --git a/cmd/src/auth_token_test.go b/cmd/src/auth_token_test.go index 8471be37f2..f1884263b3 100644 --- a/cmd/src/auth_token_test.go +++ b/cmd/src/auth_token_test.go @@ -103,6 +103,53 @@ func TestResolveAuthToken(t *testing.T) { }) } +func TestFormatAuthTokenOutput(t *testing.T) { + tests := []struct { + name string + token string + mode AuthMode + header bool + want string + }{ + { + name: "raw access token", + token: "access-token", + mode: AuthModeAccessToken, + header: false, + want: "access-token", + }, + { + name: "raw oauth token", + token: "oauth-token", + mode: AuthModeOAuth, + header: false, + want: "oauth-token", + }, + { + name: "authorization header for access token", + token: "access-token", + mode: AuthModeAccessToken, + header: true, + want: "Authorization: token access-token", + }, + { + name: "authorization header for oauth token", + token: "oauth-token", + mode: AuthModeOAuth, + header: true, + want: "Authorization: Bearer oauth-token", + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if got := formatAuthTokenOutput(test.token, test.mode, test.header); got != test.want { + t.Fatalf("formatAuthTokenOutput(%q, %v, %v) = %q, want %q", test.token, test.mode, test.header, got, test.want) + } + }) + } +} + func stubAuthTokenDependencies(t *testing.T) func() { t.Helper() From 0267380bb2cd44b1773934fbe9b607885fa5c191 Mon Sep 17 00:00:00 2001 From: Vincent Date: Tue, 24 Mar 2026 11:25:46 +0000 Subject: [PATCH 553/647] chore: bump Go and vulnerable dependencies (#1277) * bump go and dependencies * bump otel * tidy lib * reduce version constraint --- .tool-versions | 2 +- go.mod | 25 +++++++++----------- go.sum | 52 ++++++++++++++++++------------------------ lib/errors/postgres.go | 2 +- lib/go.mod | 9 +++----- lib/go.sum | 21 +++++------------ 6 files changed, 44 insertions(+), 67 deletions(-) diff --git a/.tool-versions b/.tool-versions index 2dc1382b79..f549b5d819 100644 --- a/.tool-versions +++ b/.tool-versions @@ -1,3 +1,3 @@ -golang 1.25.4 +golang 1.26.1 shfmt 3.8.0 shellcheck 0.10.0 diff --git a/go.mod b/go.mod index 0a04972e5a..fb23779f6a 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/sourcegraph/src-cli -go 1.24.1 +go 1.25.1 require ( cloud.google.com/go/storage v1.50.0 @@ -90,12 +90,9 @@ require ( github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2 // indirect github.com/iancoleman/strcase v0.3.0 // indirect - github.com/jackc/chunkreader/v2 v2.0.1 // indirect - github.com/jackc/pgconn v1.14.3 // indirect - github.com/jackc/pgio v1.0.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect - github.com/jackc/pgproto3/v2 v2.3.3 // indirect - github.com/jackc/pgservicefile v0.0.0-20231201235250-de7065d80cb9 // indirect + github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect + github.com/jackc/pgx/v5 v5.9.1 // indirect github.com/mitchellh/go-homedir v1.1.0 // indirect github.com/moby/docker-image-spec v1.3.1 // indirect github.com/morikuni/aec v1.0.0 // indirect @@ -118,16 +115,16 @@ require ( github.com/xlab/treeprint v1.2.0 // indirect github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect github.com/zeebo/errs v1.4.0 // indirect - go.opentelemetry.io/auto/sdk v1.1.0 // indirect + go.opentelemetry.io/auto/sdk v1.2.1 // indirect go.opentelemetry.io/contrib/detectors/gcp v1.36.0 // indirect go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0 // indirect go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0 // indirect - go.opentelemetry.io/otel v1.38.0 // indirect + go.opentelemetry.io/otel v1.40.0 // indirect go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.38.0 // indirect - go.opentelemetry.io/otel/metric v1.38.0 // indirect - go.opentelemetry.io/otel/sdk v1.38.0 // indirect - go.opentelemetry.io/otel/sdk/metric v1.38.0 // indirect - go.opentelemetry.io/otel/trace v1.38.0 // indirect + go.opentelemetry.io/otel/metric v1.40.0 // indirect + go.opentelemetry.io/otel/sdk v1.40.0 // indirect + go.opentelemetry.io/otel/sdk/metric v1.40.0 // indirect + go.opentelemetry.io/otel/trace v1.40.0 // indirect go.opentelemetry.io/proto/otlp v1.7.1 // indirect golang.org/x/net v0.47.0 // indirect golang.org/x/telemetry v0.0.0-20251008203120-078029d740a8 // indirect @@ -216,7 +213,7 @@ require ( github.com/pseudomuto/protoc-gen-doc v1.5.1 // indirect github.com/pseudomuto/protokit v0.2.0 // indirect github.com/rivo/uniseg v0.4.7 // indirect - github.com/rogpeppe/go-internal v1.13.1 // indirect + github.com/rogpeppe/go-internal v1.14.1 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect github.com/sourcegraph/log v0.0.0-20250923023806-517b6960b55b // indirect github.com/spf13/cobra v1.9.1 // indirect @@ -234,7 +231,7 @@ require ( golang.org/x/crypto v0.45.0 // indirect golang.org/x/mod v0.29.0 // indirect golang.org/x/oauth2 v0.33.0 // indirect - golang.org/x/sys v0.38.0 // indirect + golang.org/x/sys v0.40.0 // indirect golang.org/x/term v0.37.0 // indirect golang.org/x/text v0.31.0 // indirect golang.org/x/time v0.14.0 // indirect diff --git a/go.sum b/go.sum index 6cbdc71412..176d0813ac 100644 --- a/go.sum +++ b/go.sum @@ -285,21 +285,14 @@ github.com/imdario/mergo v0.3.16 h1:wwQJbIsHYGMUyLSPrEq1CT16AhnhNJQ51+4fdHUnCl4= github.com/imdario/mergo v0.3.16/go.mod h1:WBLT9ZmE3lPoWsEzCh9LPo3TiwVN+ZKEjmz+hD27ysY= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= -github.com/jackc/chunkreader/v2 v2.0.0/go.mod h1:odVSm741yZoC3dpHEUXIqA9tQRhFrgOHwnPIn9lDKlk= -github.com/jackc/chunkreader/v2 v2.0.1 h1:i+RDz65UE+mmpjTfyz0MoVTnzeYxroil2G82ki7MGG8= -github.com/jackc/chunkreader/v2 v2.0.1/go.mod h1:odVSm741yZoC3dpHEUXIqA9tQRhFrgOHwnPIn9lDKlk= -github.com/jackc/pgconn v1.14.3 h1:bVoTr12EGANZz66nZPkMInAV/KHD2TxH9npjXXgiB3w= -github.com/jackc/pgconn v1.14.3/go.mod h1:RZbme4uasqzybK2RK5c65VsHxoyaml09lx3tXOcO/VM= -github.com/jackc/pgio v1.0.0 h1:g12B9UwVnzGhueNavwioyEEpAmqMe1E/BN9ES+8ovkE= -github.com/jackc/pgio v1.0.0/go.mod h1:oP+2QK2wFfUWgr+gxjoBH9KGBb31Eio69xUb0w5bYf8= -github.com/jackc/pgmock v0.0.0-20210724152146-4ad1a8207f65 h1:DadwsjnMwFjfWc9y5Wi/+Zz7xoE5ALHsRQlOctkOiHc= -github.com/jackc/pgmock v0.0.0-20210724152146-4ad1a8207f65/go.mod h1:5R2h2EEX+qri8jOWMbJCtaPWkrrNc7OHwsp2TCqp7ak= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= -github.com/jackc/pgproto3/v2 v2.3.3 h1:1HLSx5H+tXR9pW3in3zaztoEwQYRC9SQaYUHjTSUOag= -github.com/jackc/pgproto3/v2 v2.3.3/go.mod h1:WfJCnwN3HIg9Ish/j3sgWXnAfK8A9Y0bwXYU5xKaEdA= -github.com/jackc/pgservicefile v0.0.0-20231201235250-de7065d80cb9 h1:L0QtFUgDarD7Fpv9jeVMgy/+Ec0mtnmYuImjTz6dtDA= -github.com/jackc/pgservicefile v0.0.0-20231201235250-de7065d80cb9/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.9.1 h1:uwrxJXBnx76nyISkhr33kQLlUqjv7et7b9FjCen/tdc= +github.com/jackc/pgx/v5 v5.9.1/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= +github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= +github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/jdxcode/netrc v0.0.0-20221124155335-4616370d1a84 h1:2uT3aivO7NVpUPGcQX7RbHijHMyWix/yCnIrCWc+5co= github.com/jdxcode/netrc v0.0.0-20221124155335-4616370d1a84/go.mod h1:Zi/ZFkEqFHTm7qkjyNJjaWH4LQA9LQhGJyF0lTYGpxw= github.com/jedib0t/go-pretty/v6 v6.6.3 h1:nGqgS0tgIO1Hto47HSaaK4ac/I/Bu7usmdD3qvs0WvM= @@ -418,8 +411,8 @@ github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= -github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= -github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= +github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= +github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/rs/cors v1.11.0 h1:0B9GE/r9Bc2UxRMMtymBkHTenPkHDv0CW4Y98GBY+po= github.com/rs/cors v1.11.0/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU= github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= @@ -463,7 +456,6 @@ github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpE github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= @@ -507,30 +499,30 @@ github.com/zalando/go-keyring v0.2.6 h1:r7Yc3+H+Ux0+M72zacZoItR3UDxeWfKTcabvkI8u github.com/zalando/go-keyring v0.2.6/go.mod h1:2TCrxYrbUNYfNS/Kgy/LSrkSQzZ5UPVH85RwfczwvcI= github.com/zeebo/errs v1.4.0 h1:XNdoD/RRMKP7HD0UhJnIzUy74ISdGGxURlYG8HSWSfM= github.com/zeebo/errs v1.4.0/go.mod h1:sgbWHsvVuTPHcqJJGQ1WhI5KbWlHYz+2+2C/LSEtCw4= -go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA= -go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A= +go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= +go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= go.opentelemetry.io/contrib/detectors/gcp v1.36.0 h1:F7q2tNlCaHY9nMKHR6XH9/qkp8FktLnIcy6jJNyOCQw= go.opentelemetry.io/contrib/detectors/gcp v1.36.0/go.mod h1:IbBN8uAIIx734PTonTPxAxnjc2pQTxWNkwfstZ+6H2k= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0 h1:q4XOmH/0opmeuJtPsbFNivyl7bCt7yRBbeEm2sC/XtQ= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0/go.mod h1:snMWehoOh2wsEwnvvwtDyFCxVeDAODenXHtn5vzrKjo= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0 h1:RbKq8BG0FI8OiXhBfcRtqqHcZcka+gU3cskNuf05R18= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0/go.mod h1:h06DGIukJOevXaj/xrNjhi/2098RZzcLTbc0jDAUbsg= -go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8= -go.opentelemetry.io/otel v1.38.0/go.mod h1:zcmtmQ1+YmQM9wrNsTGV/q/uyusom3P8RxwExxkZhjM= +go.opentelemetry.io/otel v1.40.0 h1:oA5YeOcpRTXq6NN7frwmwFR0Cn3RhTVZvXsP4duvCms= +go.opentelemetry.io/otel v1.40.0/go.mod h1:IMb+uXZUKkMXdPddhwAHm6UfOwJyh4ct1ybIlV14J0g= go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.38.0 h1:GqRJVj7UmLjCVyVJ3ZFLdPRmhDUp2zFmQe3RHIOsw24= go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.38.0/go.mod h1:ri3aaHSmCTVYu2AWv44YMauwAQc0aqI9gHKIcSbI1pU= go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.38.0 h1:aTL7F04bJHUlztTsNGJ2l+6he8c+y/b//eR0jjjemT4= go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.38.0/go.mod h1:kldtb7jDTeol0l3ewcmd8SDvx3EmIE7lyvqbasU3QC4= go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.29.0 h1:WDdP9acbMYjbKIyJUhTvtzj601sVJOqgWdUxSdR/Ysc= go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.29.0/go.mod h1:BLbf7zbNIONBLPwvFnwNHGj4zge8uTCM/UPIVW1Mq2I= -go.opentelemetry.io/otel/metric v1.38.0 h1:Kl6lzIYGAh5M159u9NgiRkmoMKjvbsKtYRwgfrA6WpA= -go.opentelemetry.io/otel/metric v1.38.0/go.mod h1:kB5n/QoRM8YwmUahxvI3bO34eVtQf2i4utNVLr9gEmI= -go.opentelemetry.io/otel/sdk v1.38.0 h1:l48sr5YbNf2hpCUj/FoGhW9yDkl+Ma+LrVl8qaM5b+E= -go.opentelemetry.io/otel/sdk v1.38.0/go.mod h1:ghmNdGlVemJI3+ZB5iDEuk4bWA3GkTpW+DOoZMYBVVg= -go.opentelemetry.io/otel/sdk/metric v1.38.0 h1:aSH66iL0aZqo//xXzQLYozmWrXxyFkBJ6qT5wthqPoM= -go.opentelemetry.io/otel/sdk/metric v1.38.0/go.mod h1:dg9PBnW9XdQ1Hd6ZnRz689CbtrUp0wMMs9iPcgT9EZA= -go.opentelemetry.io/otel/trace v1.38.0 h1:Fxk5bKrDZJUH+AMyyIXGcFAPah0oRcT+LuNtJrmcNLE= -go.opentelemetry.io/otel/trace v1.38.0/go.mod h1:j1P9ivuFsTceSWe1oY+EeW3sc+Pp42sO++GHkg4wwhs= +go.opentelemetry.io/otel/metric v1.40.0 h1:rcZe317KPftE2rstWIBitCdVp89A2HqjkxR3c11+p9g= +go.opentelemetry.io/otel/metric v1.40.0/go.mod h1:ib/crwQH7N3r5kfiBZQbwrTge743UDc7DTFVZrrXnqc= +go.opentelemetry.io/otel/sdk v1.40.0 h1:KHW/jUzgo6wsPh9At46+h4upjtccTmuZCFAc9OJ71f8= +go.opentelemetry.io/otel/sdk v1.40.0/go.mod h1:Ph7EFdYvxq72Y8Li9q8KebuYUr2KoeyHx0DRMKrYBUE= +go.opentelemetry.io/otel/sdk/metric v1.40.0 h1:mtmdVqgQkeRxHgRv4qhyJduP3fYJRMX4AtAlbuWdCYw= +go.opentelemetry.io/otel/sdk/metric v1.40.0/go.mod h1:4Z2bGMf0KSK3uRjlczMOeMhKU2rhUqdWNoKcYrtcBPg= +go.opentelemetry.io/otel/trace v1.40.0 h1:WA4etStDttCSYuhwvEa8OP8I5EWu24lkOzp+ZYblVjw= +go.opentelemetry.io/otel/trace v1.40.0/go.mod h1:zeAhriXecNGP/s2SEG3+Y8X9ujcJOTqQ5RgdEJcawiA= go.opentelemetry.io/proto/otlp v1.7.1 h1:gTOMpGDb0WTBOP8JaO72iL3auEZhVmAQg4ipjOVAtj4= go.opentelemetry.io/proto/otlp v1.7.1/go.mod h1:b2rVh6rfI/s2pHWNlB7ILJcRALpcNDzKhACevjI+ZnE= go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= @@ -593,8 +585,8 @@ golang.org/x/sys v0.0.0-20220829200755-d48e67d00261/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220906165534-d0df966e6959/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc= -golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ= +golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= golang.org/x/telemetry v0.0.0-20251008203120-078029d740a8 h1:LvzTn0GQhWuvKH/kVRS3R3bVAsdQWI7hvfLHGgh9+lU= golang.org/x/telemetry v0.0.0-20251008203120-078029d740a8/go.mod h1:Pi4ztBfryZoJEkyFTI5/Ocsu2jXyDr6iSdgJiYE/uwE= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= diff --git a/lib/errors/postgres.go b/lib/errors/postgres.go index a9696a2d0d..c9a7827c96 100644 --- a/lib/errors/postgres.go +++ b/lib/errors/postgres.go @@ -1,7 +1,7 @@ package errors import ( - "github.com/jackc/pgconn" + "github.com/jackc/pgx/v5/pgconn" ) // HasPostgresCode checks whether any of the errors in the chain diff --git a/lib/go.mod b/lib/go.mod index 2aa9407f3a..018111d005 100644 --- a/lib/go.mod +++ b/lib/go.mod @@ -1,6 +1,6 @@ module github.com/sourcegraph/sourcegraph/lib -go 1.24.1 +go 1.25.1 require ( github.com/Masterminds/semver v1.5.0 @@ -12,7 +12,7 @@ require ( github.com/gobwas/glob v0.2.3 github.com/google/go-cmp v0.7.0 github.com/grafana/regexp v0.0.0-20250905093917-f7b3be9d1853 - github.com/jackc/pgconn v1.14.3 + github.com/jackc/pgx/v5 v5.9.1 github.com/klauspost/pgzip v1.2.6 github.com/mattn/go-isatty v0.0.20 github.com/mattn/go-runewidth v0.0.19 @@ -79,11 +79,8 @@ require ( github.com/huandu/xstrings v1.0.0 // indirect github.com/imdario/mergo v0.3.4 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect - github.com/jackc/chunkreader/v2 v2.0.1 // indirect - github.com/jackc/pgio v1.0.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect - github.com/jackc/pgproto3/v2 v2.3.3 // indirect - github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect + github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jdxcode/netrc v0.0.0-20221124155335-4616370d1a84 // indirect github.com/klauspost/compress v1.18.0 // indirect github.com/kr/pretty v0.3.1 // indirect diff --git a/lib/go.sum b/lib/go.sum index 1347666156..0e42dec098 100644 --- a/lib/go.sum +++ b/lib/go.sum @@ -153,21 +153,14 @@ github.com/imdario/mergo v0.3.4 h1:mKkfHkZWD8dC7WxKx3N9WCF0Y+dLau45704YQmY6H94= github.com/imdario/mergo v0.3.4/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= -github.com/jackc/chunkreader/v2 v2.0.0/go.mod h1:odVSm741yZoC3dpHEUXIqA9tQRhFrgOHwnPIn9lDKlk= -github.com/jackc/chunkreader/v2 v2.0.1 h1:i+RDz65UE+mmpjTfyz0MoVTnzeYxroil2G82ki7MGG8= -github.com/jackc/chunkreader/v2 v2.0.1/go.mod h1:odVSm741yZoC3dpHEUXIqA9tQRhFrgOHwnPIn9lDKlk= -github.com/jackc/pgconn v1.14.3 h1:bVoTr12EGANZz66nZPkMInAV/KHD2TxH9npjXXgiB3w= -github.com/jackc/pgconn v1.14.3/go.mod h1:RZbme4uasqzybK2RK5c65VsHxoyaml09lx3tXOcO/VM= -github.com/jackc/pgio v1.0.0 h1:g12B9UwVnzGhueNavwioyEEpAmqMe1E/BN9ES+8ovkE= -github.com/jackc/pgio v1.0.0/go.mod h1:oP+2QK2wFfUWgr+gxjoBH9KGBb31Eio69xUb0w5bYf8= -github.com/jackc/pgmock v0.0.0-20210724152146-4ad1a8207f65 h1:DadwsjnMwFjfWc9y5Wi/+Zz7xoE5ALHsRQlOctkOiHc= -github.com/jackc/pgmock v0.0.0-20210724152146-4ad1a8207f65/go.mod h1:5R2h2EEX+qri8jOWMbJCtaPWkrrNc7OHwsp2TCqp7ak= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= -github.com/jackc/pgproto3/v2 v2.3.3 h1:1HLSx5H+tXR9pW3in3zaztoEwQYRC9SQaYUHjTSUOag= -github.com/jackc/pgproto3/v2 v2.3.3/go.mod h1:WfJCnwN3HIg9Ish/j3sgWXnAfK8A9Y0bwXYU5xKaEdA= -github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk= -github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.9.1 h1:uwrxJXBnx76nyISkhr33kQLlUqjv7et7b9FjCen/tdc= +github.com/jackc/pgx/v5 v5.9.1/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= +github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= +github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/jdxcode/netrc v0.0.0-20221124155335-4616370d1a84 h1:2uT3aivO7NVpUPGcQX7RbHijHMyWix/yCnIrCWc+5co= github.com/jdxcode/netrc v0.0.0-20221124155335-4616370d1a84/go.mod h1:Zi/ZFkEqFHTm7qkjyNJjaWH4LQA9LQhGJyF0lTYGpxw= github.com/jhump/protoreflect v1.15.1 h1:HUMERORf3I3ZdX05WaQ6MIpd/NJ434hTp5YiKgfCL6c= @@ -264,7 +257,6 @@ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+ github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= @@ -387,7 +379,6 @@ gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8 gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= -gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= From 0e5e006e8f98b5c8ec47e4fac9fa8f56e3d06bc7 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Thu, 26 Mar 2026 09:49:06 +0000 Subject: [PATCH 554/647] bug: only require CI=true and AccessToken when making API requests (#1278) * check when inCI and whether we required Access Token * fast fail in APIClient when CI=true and no Access Token * use apiClient constructor in search_jobs * fail fast in login / auth token when CI=true and AccessToken not set * add comment * review feedback - rename `RequireAccessToken` to `checkIfCIAccessTokenRequired` - provide more context in error on why it happened * use sentinel error * use lib errors --- cmd/src/auth_token.go | 4 ++++ cmd/src/auth_token_test.go | 22 ++++++++++++++++++ cmd/src/login.go | 4 ++++ cmd/src/login_test.go | 11 +++++++++ cmd/src/main.go | 38 ++++++++++++++++++++---------- cmd/src/main_test.go | 47 +++++++++++++++++++++++++++++++++++--- cmd/src/search_jobs.go | 7 +----- internal/api/api.go | 42 +++++++++++++++++++++++++++------- 8 files changed, 146 insertions(+), 29 deletions(-) diff --git a/cmd/src/auth_token.go b/cmd/src/auth_token.go index 6112799f03..fdd6d03a42 100644 --- a/cmd/src/auth_token.go +++ b/cmd/src/auth_token.go @@ -54,6 +54,10 @@ func init() { } func resolveAuthToken(ctx context.Context, cfg *config) (string, error) { + if err := cfg.requireCIAccessToken(); err != nil { + return "", err + } + if cfg.accessToken != "" { return cfg.accessToken, nil } diff --git a/cmd/src/auth_token_test.go b/cmd/src/auth_token_test.go index f1884263b3..c351d06d75 100644 --- a/cmd/src/auth_token_test.go +++ b/cmd/src/auth_token_test.go @@ -35,6 +35,28 @@ func TestResolveAuthToken(t *testing.T) { } }) + t.Run("requires access token in CI", func(t *testing.T) { + reset := stubAuthTokenDependencies(t) + defer reset() + + loadCalled := false + loadOAuthToken = func(context.Context, *url.URL) (*oauth.Token, error) { + loadCalled = true + return nil, nil + } + + _, err := resolveAuthToken(context.Background(), &config{ + inCI: true, + endpointURL: mustParseURL(t, "https://example.com"), + }) + if err != errCIAccessTokenRequired { + t.Fatalf("err = %v, want %v", err, errCIAccessTokenRequired) + } + if loadCalled { + t.Fatal("expected OAuth token loader not to be called") + } + }) + t.Run("uses stored oauth token", func(t *testing.T) { reset := stubAuthTokenDependencies(t) defer reset() diff --git a/cmd/src/login.go b/cmd/src/login.go index 60cc1698b6..43ccfe0347 100644 --- a/cmd/src/login.go +++ b/cmd/src/login.go @@ -100,6 +100,10 @@ const ( ) func loginCmd(ctx context.Context, p loginParams) error { + if err := p.cfg.requireCIAccessToken(); err != nil { + return err + } + if p.cfg.configFilePath != "" { fmt.Fprintln(p.out) fmt.Fprintf(p.out, "⚠️ Warning: Configuring src with a JSON file is deprecated. Please migrate to using the env vars SRC_ENDPOINT, SRC_ACCESS_TOKEN, and SRC_PROXY instead, and then remove %s. See https://github.com/sourcegraph/src-cli#readme for more information.\n", p.cfg.configFilePath) diff --git a/cmd/src/login_test.go b/cmd/src/login_test.go index 85e79816b2..6a286c4b5a 100644 --- a/cmd/src/login_test.go +++ b/cmd/src/login_test.go @@ -61,6 +61,17 @@ func TestLogin(t *testing.T) { } }) + t.Run("CI requires access token", func(t *testing.T) { + u := &url.URL{Scheme: "https", Host: "example.com"} + out, err := check(t, &config{endpointURL: u, inCI: true}, u) + if err != errCIAccessTokenRequired { + t.Fatalf("err = %v, want %v", err, errCIAccessTokenRequired) + } + if out != "" { + t.Fatalf("output = %q, want empty output", out) + } + }) + t.Run("warning when using config file", func(t *testing.T) { endpoint := &url.URL{Scheme: "https", Host: "example.com"} out, err := check(t, &config{endpointURL: endpoint, configFilePath: "f"}, endpoint) diff --git a/cmd/src/main.go b/cmd/src/main.go index 0e42c2f465..93be07c4bf 100644 --- a/cmd/src/main.go +++ b/cmd/src/main.go @@ -82,7 +82,7 @@ var ( errConfigMerge = errors.New("when using a configuration file, zero or all environment variables must be set") errConfigAuthorizationConflict = errors.New("when passing an 'Authorization' additional headers, SRC_ACCESS_TOKEN must never be set") - errCIAccessTokenRequired = errors.New("SRC_ACCESS_TOKEN must be set in CI") + errCIAccessTokenRequired = errors.New("CI is true and SRC_ACCESS_TOKEN is not set or empty. When running in CI OAuth tokens cannot be used, only SRC_ACCESS_TOKEN. Either set CI=false or define a SRC_ACCESS_TOKEN") ) // commands contains all registered subcommands. @@ -137,6 +137,7 @@ type config struct { proxyPath string configFilePath string endpointURL *url.URL // always non-nil; defaults to https://sourcegraph.com via readConfig + inCI bool } // configFromFile holds the config as read from the config file, @@ -162,16 +163,32 @@ func (c *config) AuthMode() AuthMode { return AuthModeOAuth } +func (c *config) InCI() bool { + return c.inCI +} + +func (c *config) requireCIAccessToken() error { + // In CI we typically do not have access to the keyring and the machine is also typically headless + // we therefore require SRC_ACCESS_TOKEN to be set when in CI. + // If someone really wants to run with OAuth in CI they can temporarily do CI=false + if c.InCI() && c.AuthMode() != AuthModeAccessToken { + return errCIAccessTokenRequired + } + + return nil +} + // apiClient returns an api.Client built from the configuration. func (c *config) apiClient(flags *api.Flags, out io.Writer) api.Client { opts := api.ClientOpts{ - EndpointURL: c.endpointURL, - AccessToken: c.accessToken, - AdditionalHeaders: c.additionalHeaders, - Flags: flags, - Out: out, - ProxyURL: c.proxyURL, - ProxyPath: c.proxyPath, + EndpointURL: c.endpointURL, + AccessToken: c.accessToken, + AdditionalHeaders: c.additionalHeaders, + Flags: flags, + Out: out, + ProxyURL: c.proxyURL, + ProxyPath: c.proxyPath, + RequireAccessTokenInCI: c.InCI(), } // Only use OAuth if we do not have SRC_ACCESS_TOKEN set @@ -205,6 +222,7 @@ func readConfig() (*config, error) { var cfgFromFile configFromFile var cfg config + cfg.inCI = isCI() var endpointStr string var proxyStr string if err == nil { @@ -312,10 +330,6 @@ func readConfig() (*config, error) { return nil, errConfigAuthorizationConflict } - if isCI() && cfg.accessToken == "" { - return nil, errCIAccessTokenRequired - } - return &cfg, nil } diff --git a/cmd/src/main_test.go b/cmd/src/main_test.go index ee95616796..c0b29822b0 100644 --- a/cmd/src/main_test.go +++ b/cmd/src/main_test.go @@ -1,7 +1,9 @@ package main import ( + "context" "encoding/json" + "io" "net/url" "os" "path/filepath" @@ -10,6 +12,7 @@ import ( "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" + "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/api" ) @@ -325,9 +328,13 @@ func TestReadConfig(t *testing.T) { wantErr: errConfigAuthorizationConflict.Error(), }, { - name: "CI requires access token", - envCI: "1", - wantErr: errCIAccessTokenRequired.Error(), + name: "CI does not require access token during config read", + envCI: "1", + want: &config{ + endpointURL: &url.URL{Scheme: "https", Host: "sourcegraph.com"}, + additionalHeaders: map[string]string{}, + inCI: true, + }, }, { name: "CI allows access token from config file", @@ -340,6 +347,7 @@ func TestReadConfig(t *testing.T) { endpointURL: &url.URL{Scheme: "https", Host: "example.com"}, accessToken: "deadbeef", additionalHeaders: map[string]string{}, + inCI: true, }, }, } @@ -422,3 +430,36 @@ func TestConfigAuthMode(t *testing.T) { } }) } + +func TestConfigAPIClientCIAccessTokenGate(t *testing.T) { + endpointURL := &url.URL{Scheme: "https", Host: "example.com"} + + t.Run("requires access token in CI", func(t *testing.T) { + client := (&config{endpointURL: endpointURL, inCI: true}).apiClient(nil, io.Discard) + + _, err := client.NewHTTPRequest(context.Background(), "GET", ".api/src-cli/version", nil) + if !errors.Is(err, api.ErrCIAccessTokenRequired) { + t.Fatalf("NewHTTPRequest() error = %v, want %v", err, api.ErrCIAccessTokenRequired) + } + }) + + t.Run("allows access token in CI", func(t *testing.T) { + client := (&config{endpointURL: endpointURL, inCI: true, accessToken: "abc"}).apiClient(nil, io.Discard) + + req, err := client.NewHTTPRequest(context.Background(), "GET", ".api/src-cli/version", nil) + if err != nil { + t.Fatalf("NewHTTPRequest() unexpected error: %s", err) + } + if got := req.Header.Get("Authorization"); got != "token abc" { + t.Fatalf("Authorization header = %q, want %q", got, "token abc") + } + }) + + t.Run("allows oauth mode outside CI", func(t *testing.T) { + client := (&config{endpointURL: endpointURL}).apiClient(nil, io.Discard) + + if _, err := client.NewHTTPRequest(context.Background(), "GET", ".api/src-cli/version", nil); err != nil { + t.Fatalf("NewHTTPRequest() unexpected error: %s", err) + } + }) +} diff --git a/cmd/src/search_jobs.go b/cmd/src/search_jobs.go index 15bf5d8a25..d8f513efcd 100644 --- a/cmd/src/search_jobs.go +++ b/cmd/src/search_jobs.go @@ -155,12 +155,7 @@ func parseColumns(columnsFlag string) []string { // createSearchJobsClient creates a reusable API client for search jobs commands func createSearchJobsClient(out *flag.FlagSet, apiFlags *api.Flags) api.Client { - return api.NewClient(api.ClientOpts{ - EndpointURL: cfg.endpointURL, - AccessToken: cfg.accessToken, - Out: out.Output(), - Flags: apiFlags, - }) + return cfg.apiClient(apiFlags, out.Output()) } // parseSearchJobsArgs parses command arguments with the provided flag set diff --git a/internal/api/api.go b/internal/api/api.go index 73a0416097..800d8d41a2 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -19,6 +19,8 @@ import ( "github.com/sourcegraph/src-cli/internal/oauth" "github.com/sourcegraph/src-cli/internal/version" + + "github.com/sourcegraph/sourcegraph/lib/errors" ) // Client instances provide methods to create API requests. @@ -71,9 +73,10 @@ type request struct { // ClientOpts encapsulates the options given to NewClient. type ClientOpts struct { - EndpointURL *url.URL - AccessToken string - AdditionalHeaders map[string]string + EndpointURL *url.URL + AccessToken string + AdditionalHeaders map[string]string + RequireAccessTokenInCI bool // Flags are the standard API client flags provided by NewFlags. If nil, // default values will be used. @@ -89,6 +92,9 @@ type ClientOpts struct { OAuthToken *oauth.Token } +// ErrCIAccessTokenRequired indicates SRC_ACCESS_TOKEN must be set when CI=true. +var ErrCIAccessTokenRequired = errors.New("SRC_ACCESS_TOKEN must be set when CI=true") + func buildTransport(opts ClientOpts, flags *Flags) http.RoundTripper { var transport http.RoundTripper { @@ -109,6 +115,9 @@ func buildTransport(opts ClientOpts, flags *Flags) http.RoundTripper { transport = tp } + // not we do not fail here if requireAccessToken is true, because that would + // mean returning an error on construction which we want to avoid for now + // TODO(burmudar): allow returning of an error upon client construction if opts.AccessToken == "" && opts.OAuthToken != nil { transport = oauth.NewTransport(transport, opts.OAuthToken) } @@ -135,15 +144,24 @@ func NewClient(opts ClientOpts) Client { return &client{ opts: ClientOpts{ - EndpointURL: opts.EndpointURL, - AccessToken: opts.AccessToken, - AdditionalHeaders: opts.AdditionalHeaders, - Flags: flags, - Out: opts.Out, + EndpointURL: opts.EndpointURL, + AccessToken: opts.AccessToken, + AdditionalHeaders: opts.AdditionalHeaders, + RequireAccessTokenInCI: opts.RequireAccessTokenInCI, + Flags: flags, + Out: opts.Out, }, httpClient: httpClient, } } + +func (c *client) checkIfCIAccessTokenRequired() error { + if c.opts.RequireAccessTokenInCI && c.opts.AccessToken == "" { + return ErrCIAccessTokenRequired + } + + return nil +} func (c *client) NewQuery(query string) Request { return c.NewRequest(query, nil) } @@ -170,6 +188,10 @@ func (c *client) NewHTTPRequest(ctx context.Context, method, p string, body io.R } func (c *client) createHTTPRequest(ctx context.Context, method, p string, body io.Reader) (*http.Request, error) { + if err := c.checkIfCIAccessTokenRequired(); err != nil { + return nil, err + } + // Can't use c.opts.EndpointURL.JoinPath(p) here because `p` could contain a query string req, err := http.NewRequestWithContext(ctx, method, c.opts.EndpointURL.String()+"/"+p, body) if err != nil { @@ -199,6 +221,10 @@ func (c *client) createHTTPRequest(ctx context.Context, method, p string, body i } func (r *request) do(ctx context.Context, result any) (bool, error) { + if err := r.client.checkIfCIAccessTokenRequired(); err != nil { + return false, err + } + if *r.client.opts.Flags.getCurl { curl, err := r.curlCmd() if err != nil { From 5e4aec26c4e6910e7ab563e680b01a5fc4813fa1 Mon Sep 17 00:00:00 2001 From: Carter Brainerd Date: Fri, 27 Mar 2026 14:19:22 -0400 Subject: [PATCH 555/647] security: use os.Root API for file path logic (#1279) --- internal/batches/executor/executor_test.go | 21 +++--- internal/batches/executor/run_steps.go | 34 ++++++---- internal/batches/service/remote.go | 40 ++++++++---- internal/batches/service/service.go | 34 ++++++++-- internal/batches/service/service_test.go | 74 ++++++++++++++++++++++ 5 files changed, 165 insertions(+), 38 deletions(-) diff --git a/internal/batches/executor/executor_test.go b/internal/batches/executor/executor_test.go index 03f25e08a8..b507302f9c 100644 --- a/internal/batches/executor/executor_test.go +++ b/internal/batches/executor/executor_test.go @@ -50,7 +50,7 @@ func TestExecutor_Integration(t *testing.T) { // create a temp directory with a simple shell file tempDir := t.TempDir() - mountScript := fmt.Sprintf("%s/sample.sh", tempDir) + mountScript := filepath.Join(tempDir, "sample.sh") err := os.WriteFile(mountScript, []byte(`echo -e "foobar\n" >> README.md`), 0777) require.NoError(t, err) @@ -80,7 +80,8 @@ func TestExecutor_Integration(t *testing.T) { wantCacheCount int - failFast bool + failFast bool + workingDirectory string }{ { name: "success", @@ -362,7 +363,7 @@ func TestExecutor_Integration(t *testing.T) { steps: []batcheslib.Step{ { Run: mountScript, - Mount: []batcheslib.Mount{{Path: mountScript, Mountpoint: mountScript}}, + Mount: []batcheslib.Mount{{Path: "sample.sh", Mountpoint: mountScript}}, }, }, tasks: []*Task{ @@ -373,8 +374,9 @@ func TestExecutor_Integration(t *testing.T) { rootPath: []string{"README.md"}, }, }, - wantFinished: 1, - wantCacheCount: 1, + wantFinished: 1, + wantCacheCount: 1, + workingDirectory: tempDir, }, } @@ -426,10 +428,11 @@ func TestExecutor_Integration(t *testing.T) { Logger: mock.LogNoOpManager{}, EnsureImage: imageMapEnsurer(images), - TempDir: testTempDir, - Parallelism: runtime.GOMAXPROCS(parallelism), - Timeout: tc.executorTimeout, - FailFast: tc.failFast, + TempDir: testTempDir, + Parallelism: runtime.GOMAXPROCS(parallelism), + Timeout: tc.executorTimeout, + FailFast: tc.failFast, + WorkingDirectory: tc.workingDirectory, } if opts.Timeout == 0 { diff --git a/internal/batches/executor/run_steps.go b/internal/batches/executor/run_steps.go index 97e952be71..47b5715887 100644 --- a/internal/batches/executor/run_steps.go +++ b/internal/batches/executor/run_steps.go @@ -610,26 +610,38 @@ func createCidFile(ctx context.Context, tempDir string, repoSlug string) (string } func getAbsoluteMountPath(batchSpecDir string, mountPath string) (string, error) { + // Use OpenRoot to prevent path traversal and symlink attacks via mount paths + root, err := os.OpenRoot(batchSpecDir) + if err != nil { + return "", errors.Wrap(err, "opening batch spec directory") + } + defer root.Close() + p := mountPath - if !filepath.IsAbs(p) { - // Try to build the absolute path since Docker will only mount absolute paths - p = filepath.Join(batchSpecDir, p) + if filepath.IsAbs(p) { + rel, err := filepath.Rel(batchSpecDir, p) + if err != nil || strings.HasPrefix(rel, "..") { + return "", errors.Newf("mount path %s is not in the same directory or subdirectory as the batch spec", mountPath) + } + p = rel } - pathInfo, err := os.Stat(p) + + pathInfo, err := root.Stat(p) if os.IsNotExist(err) { - return "", errors.Newf("mount path %s does not exist", p) + return "", errors.Newf("mount path %s does not exist", mountPath) } else if err != nil { - return "", errors.Wrap(err, "mount path validation") - } - if !strings.HasPrefix(p, batchSpecDir) { return "", errors.Newf("mount path %s is not in the same directory or subdirectory as the batch spec", mountPath) } + + // Build the absolute path for Docker bind mount. + absPath := filepath.Join(batchSpecDir, p) + // Mounting a directory on Docker must end with the separator. So, append the file separator to make // users' lives easier. - if pathInfo.IsDir() && !strings.HasSuffix(p, string(filepath.Separator)) { - p += string(filepath.Separator) + if pathInfo.IsDir() && !strings.HasSuffix(absPath, string(filepath.Separator)) { + absPath += string(filepath.Separator) } - return p, nil + return absPath, nil } type stepFailedErr struct { diff --git a/internal/batches/service/remote.go b/internal/batches/service/remote.go index 71678ff898..89b3cd56c8 100644 --- a/internal/batches/service/remote.go +++ b/internal/batches/service/remote.go @@ -129,31 +129,43 @@ func (svc *Service) UploadBatchSpecWorkspaceFiles(ctx context.Context, workingDi } func getFilePaths(workingDir, filePath string) ([]string, error) { + root, err := os.OpenRoot(workingDir) + if err != nil { + return nil, errors.Wrap(err, "opening working directory") + } + defer root.Close() + return getFilePathsInRoot(root, filePath) +} + +func getFilePathsInRoot(root *os.Root, filePath string) ([]string, error) { + // Clean the path to resolve any ".." segments before accessing the root. + filePath = filepath.Clean(filePath) + var filePaths []string - actualFilePath := filepath.Join(workingDir, filePath) - info, err := os.Stat(actualFilePath) + info, err := root.Stat(filePath) if err != nil { return nil, err } if info.IsDir() { - dir, err := os.ReadDir(actualFilePath) + dir, err := root.Open(filePath) + if err != nil { + return nil, err + } + entries, err := dir.ReadDir(-1) + dir.Close() if err != nil { return nil, err } - for _, dirEntry := range dir { - paths, err := getFilePaths(workingDir, filepath.Join(filePath, dirEntry.Name())) + for _, dirEntry := range entries { + paths, err := getFilePathsInRoot(root, filepath.Join(filePath, dirEntry.Name())) if err != nil { return nil, err } filePaths = append(filePaths, paths...) } } else { - relPath, err := filepath.Rel(workingDir, actualFilePath) - if err != nil { - return nil, err - } - filePaths = append(filePaths, relPath) + filePaths = append(filePaths, filePath) } return filePaths, nil } @@ -201,7 +213,13 @@ func (svc *Service) uploadFile(ctx context.Context, workingDir, filePath, batchS const maxFileSize = 10 << 20 // 10MB func createFormFile(w *multipart.Writer, workingDir string, mountPath string) error { - f, err := os.Open(filepath.Join(workingDir, mountPath)) + root, err := os.OpenRoot(workingDir) + if err != nil { + return errors.Wrap(err, "opening working directory") + } + defer root.Close() + + f, err := root.Open(mountPath) if err != nil { return err } diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index 031788ef9a..a21de45903 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -486,19 +486,39 @@ func (svc *Service) ParseBatchSpec(dir string, data []byte) (*batcheslib.BatchSp } func validateMount(batchSpecDir string, spec *batcheslib.BatchSpec) error { + // Check if any step has mounts before opening the root directory. + hasMounts := false + for _, step := range spec.Steps { + if len(step.Mount) > 0 { + hasMounts = true + break + } + } + if !hasMounts { + return nil + } + + root, err := os.OpenRoot(batchSpecDir) + if err != nil { + return errors.Wrap(err, "opening batch spec directory") + } + defer root.Close() + for i, step := range spec.Steps { for _, mount := range step.Mount { - if !filepath.IsAbs(mount.Path) { - // Try to build the absolute path since Docker will only mount absolute paths - mount.Path = filepath.Join(batchSpecDir, mount.Path) + mountPath := mount.Path + if filepath.IsAbs(mountPath) { + // Convert absolute paths to relative paths within the root. + rel, err := filepath.Rel(batchSpecDir, mountPath) + if err != nil || strings.HasPrefix(rel, "..") { + return errors.Newf("step %d mount path is not in the same directory or subdirectory as the batch spec", i+1) + } + mountPath = rel } - _, err := os.Stat(mount.Path) + _, err := root.Stat(mountPath) if os.IsNotExist(err) { return errors.Newf("step %d mount path %s does not exist", i+1, mount.Path) } else if err != nil { - return errors.Wrapf(err, "step %d mount path validation", i+1) - } - if !strings.HasPrefix(mount.Path, batchSpecDir) { return errors.Newf("step %d mount path is not in the same directory or subdirectory as the batch spec", i+1) } } diff --git a/internal/batches/service/service_test.go b/internal/batches/service/service_test.go index 14afc7e002..c550cafd6d 100644 --- a/internal/batches/service/service_test.go +++ b/internal/batches/service/service_test.go @@ -230,6 +230,17 @@ func TestService_ParseBatchSpec(t *testing.T) { _, err = os.Create(filepath.Join(tempDir, "another.sh")) require.NoError(t, err) + // Create a sibling directory whose name shares a prefix with tempDir (e.g. /tmp/specdir-123 vs /tmp/specdir-123-outside) + prefixBypassDir := tempDir + "-outside" + require.NoError(t, os.MkdirAll(prefixBypassDir, 0o755)) + t.Cleanup(func() { os.RemoveAll(prefixBypassDir) }) + secretFile := filepath.Join(prefixBypassDir, "secret.txt") + require.NoError(t, os.WriteFile(secretFile, []byte("SECRET"), 0o644)) + + // Create a symlink inside tempDir that points outside it + symlinkPath := filepath.Join(tempDir, "leak") + require.NoError(t, os.Symlink(secretFile, symlinkPath)) + tests := []struct { name string batchSpecDir string @@ -541,6 +552,69 @@ changesetTemplate: `, tempOutsideDir), expectedErr: errors.New("handling mount: step 1 mount path is not in the same directory or subdirectory as the batch spec"), }, + { + name: "mount path prefix confusion bypass", + batchSpecDir: tempDir, + rawSpec: fmt.Sprintf(` +name: test-spec +description: A test spec +steps: + - run: cat /tmp/mounted + container: alpine:3 + mount: + - path: %s + mountpoint: /tmp/mounted +changesetTemplate: + title: Test Mount + body: Test a mounted path + branch: test + commit: + message: Test +`, secretFile), + expectedErr: errors.New("handling mount: step 1 mount path is not in the same directory or subdirectory as the batch spec"), + }, + { + name: "mount path symlink escape", + batchSpecDir: tempDir, + rawSpec: ` +name: test-spec +description: A test spec +steps: + - run: cat /tmp/mounted + container: alpine:3 + mount: + - path: ./leak + mountpoint: /tmp/mounted +changesetTemplate: + title: Test Mount + body: Test a mounted path + branch: test + commit: + message: Test +`, + expectedErr: errors.New("handling mount: step 1 mount path is not in the same directory or subdirectory as the batch spec"), + }, + { + name: "mount path dot-dot traversal", + batchSpecDir: tempDir, + rawSpec: ` +name: test-spec +description: A test spec +steps: + - run: cat /tmp/mounted + container: alpine:3 + mount: + - path: ../../../etc/passwd + mountpoint: /tmp/mounted +changesetTemplate: + title: Test Mount + body: Test a mounted path + branch: test + commit: + message: Test +`, + expectedErr: errors.New("handling mount: step 1 mount path is not in the same directory or subdirectory as the batch spec"), + }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { From d9d7b510442d378386797860006c166f1f475681 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Kie=C5=82bowicz?= Date: Mon, 30 Mar 2026 12:08:49 +0200 Subject: [PATCH 556/647] Fix `.gitignore` being misinterpreted by ripgrep (#1280) --- .gitignore | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index e0f1fba3a9..2d73227cc4 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,8 @@ -./src +/src cmd/src/src *.zip release -./vendor +/vendor .idea .env .envrc From 955cc2459d610c4212c43f292148bb0fa0d528ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Kie=C5=82bowicz?= Date: Mon, 30 Mar 2026 14:07:24 +0200 Subject: [PATCH 557/647] Migrate sourcegraph/scip dependency to scip-code/scip v0.7.0 (#1281) --- cmd/src/code_intel_upload_flags.go | 2 +- cmd/src/code_intel_upload_flags_test.go | 2 +- go.mod | 57 +------ go.sum | 143 ++--------------- lib/codeintel/upload/indexer_name.go | 2 +- lib/go.mod | 71 +-------- lib/go.sum | 200 +++--------------------- 7 files changed, 47 insertions(+), 430 deletions(-) diff --git a/cmd/src/code_intel_upload_flags.go b/cmd/src/code_intel_upload_flags.go index 6a1f3031a0..defb819a72 100644 --- a/cmd/src/code_intel_upload_flags.go +++ b/cmd/src/code_intel_upload_flags.go @@ -10,7 +10,7 @@ import ( "path" "strings" - "github.com/sourcegraph/scip/bindings/go/scip" + "github.com/scip-code/scip/bindings/go/scip" "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/sourcegraph/lib/output" diff --git a/cmd/src/code_intel_upload_flags_test.go b/cmd/src/code_intel_upload_flags_test.go index cf675ddeb2..cd5cbe88dc 100644 --- a/cmd/src/code_intel_upload_flags_test.go +++ b/cmd/src/code_intel_upload_flags_test.go @@ -8,7 +8,7 @@ import ( "github.com/stretchr/testify/require" "google.golang.org/protobuf/proto" - "github.com/sourcegraph/scip/bindings/go/scip" + "github.com/scip-code/scip/bindings/go/scip" ) var exampleSCIPIndex = scip.Index{ diff --git a/go.mod b/go.mod index fb23779f6a..53eb6f6c97 100644 --- a/go.mod +++ b/go.mod @@ -23,10 +23,10 @@ require ( github.com/mattn/go-isatty v0.0.20 github.com/neelance/parallel v0.0.0-20160708114440-4de9ce63d14c github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 + github.com/scip-code/scip/bindings/go/scip v0.7.0 github.com/sourcegraph/conc v0.3.1-0.20240108182409-4afefce20f9b github.com/sourcegraph/go-diff v0.7.0 github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf - github.com/sourcegraph/scip v0.6.1 github.com/sourcegraph/sourcegraph/lib v0.0.0-20240709083501-1af563b61442 github.com/stretchr/testify v1.11.1 github.com/tliron/glsp v0.2.2 @@ -50,12 +50,7 @@ require ( github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.29.0 // indirect github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.50.0 // indirect github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.50.0 // indirect - github.com/Microsoft/go-winio v0.6.2 // indirect github.com/alecthomas/chroma/v2 v2.14.0 // indirect - github.com/bufbuild/connect-go v1.9.0 // indirect - github.com/bufbuild/connect-opentelemetry-go v0.4.0 // indirect - github.com/bufbuild/protocompile v0.5.1 // indirect - github.com/cenkalti/backoff/v5 v5.0.3 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834 // indirect @@ -65,52 +60,29 @@ require ( github.com/charmbracelet/x/term v0.2.1 // indirect github.com/clipperhouse/uax29/v2 v2.2.0 // indirect github.com/cncf/xds/go v0.0.0-20250501225837-2ac532fd4443 // indirect - github.com/containerd/stargz-snapshotter/estargz v0.14.3 // indirect github.com/danieljoos/wincred v1.2.2 // indirect - github.com/distribution/reference v0.6.0 // indirect - github.com/docker/cli v24.0.4+incompatible // indirect - github.com/docker/distribution v2.8.2+incompatible // indirect - github.com/docker/docker v28.0.0+incompatible // indirect - github.com/docker/docker-credential-helpers v0.8.0 // indirect - github.com/docker/go-connections v0.4.0 // indirect - github.com/docker/go-units v0.5.0 // indirect github.com/envoyproxy/go-control-plane/envoy v1.32.4 // indirect - github.com/felixge/fgprof v0.9.3 // indirect github.com/felixge/httpsnoop v1.0.4 // indirect github.com/fxamacker/cbor/v2 v2.7.0 // indirect - github.com/go-chi/chi/v5 v5.2.2 // indirect github.com/go-jose/go-jose/v4 v4.1.2 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/godbus/dbus/v5 v5.1.0 // indirect - github.com/gofrs/uuid/v5 v5.0.0 // indirect github.com/google/gnostic-models v0.6.9 // indirect - github.com/google/go-containerregistry v0.19.1 // indirect - github.com/google/pprof v0.0.0-20241029153458-d1b30febd7db // indirect github.com/google/s2a-go v0.1.9 // indirect github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 // indirect - github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2 // indirect github.com/iancoleman/strcase v0.3.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/pgx/v5 v5.9.1 // indirect - github.com/mitchellh/go-homedir v1.1.0 // indirect - github.com/moby/docker-image-spec v1.3.1 // indirect - github.com/morikuni/aec v1.0.0 // indirect - github.com/opencontainers/go-digest v1.0.0 // indirect - github.com/opencontainers/image-spec v1.1.0-rc4 // indirect github.com/petermattis/goid v0.0.0-20240813172612-4fcff4a6cae7 // indirect github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 // indirect - github.com/rs/cors v1.11.0 // indirect github.com/sasha-s/go-deadlock v0.3.5 // indirect github.com/segmentio/ksuid v1.0.4 // indirect - github.com/sirupsen/logrus v1.9.3 // indirect github.com/sourcegraph/beaut v0.0.0-20240611013027-627e4c25335a // indirect github.com/sourcegraph/jsonrpc2 v0.2.0 // indirect github.com/spiffe/go-spiffe/v2 v2.5.0 // indirect - github.com/tetratelabs/wazero v1.3.0 // indirect github.com/tliron/commonlog v0.2.19 // indirect github.com/tliron/kutil v0.3.27 // indirect - github.com/vbatts/tar-split v0.11.3 // indirect github.com/x448/float16 v0.8.4 // indirect github.com/xlab/treeprint v1.2.0 // indirect github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect @@ -120,14 +92,11 @@ require ( go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0 // indirect go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0 // indirect go.opentelemetry.io/otel v1.40.0 // indirect - go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.38.0 // indirect go.opentelemetry.io/otel/metric v1.40.0 // indirect go.opentelemetry.io/otel/sdk v1.40.0 // indirect go.opentelemetry.io/otel/sdk/metric v1.40.0 // indirect go.opentelemetry.io/otel/trace v1.40.0 // indirect - go.opentelemetry.io/proto/otlp v1.7.1 // indirect golang.org/x/net v0.47.0 // indirect - golang.org/x/telemetry v0.0.0-20251008203120-078029d740a8 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20250825161204-c5933d9347a5 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20251103181224-f26f9409b101 // indirect gopkg.in/evanphx/json-patch.v4 v4.12.0 // indirect @@ -139,9 +108,7 @@ require ( cloud.google.com/go/compute/metadata v0.9.0 // indirect cloud.google.com/go/iam v1.5.2 // indirect github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c // indirect - github.com/Masterminds/goutils v1.1.1 // indirect github.com/Masterminds/semver v1.5.0 // indirect - github.com/Masterminds/sprig v2.22.0+incompatible // indirect github.com/aws/aws-sdk-go-v2 v1.17.5 // indirect github.com/aws/aws-sdk-go-v2/credentials v1.13.13 // indirect github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.12.22 // indirect @@ -155,17 +122,15 @@ require ( github.com/aws/smithy-go v1.13.5 // indirect github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect github.com/aymerick/douceur v0.2.0 // indirect - github.com/bufbuild/buf v1.25.0 // indirect github.com/charmbracelet/glamour v0.10.0 // indirect github.com/cockroachdb/errors v1.12.0 // indirect github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect github.com/cockroachdb/redact v1.1.6 // indirect - github.com/cpuguy83/go-md2man/v2 v2.0.6 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/dlclark/regexp2 v1.11.0 // indirect github.com/emicklei/go-restful/v3 v3.11.0 // indirect github.com/envoyproxy/protoc-gen-validate v1.2.1 // indirect - github.com/fatih/color v1.16.0 // indirect + github.com/fatih/color v1.18.0 // indirect github.com/getsentry/sentry-go v0.27.0 // indirect github.com/ghodss/yaml v1.0.0 // indirect github.com/go-logr/logr v1.4.3 // indirect @@ -173,18 +138,12 @@ require ( github.com/go-openapi/jsonreference v0.20.2 // indirect github.com/go-openapi/swag v0.23.0 // indirect github.com/gogo/protobuf v1.3.2 // indirect - github.com/golang/protobuf v1.5.4 // indirect - github.com/google/gofuzz v1.2.0 // indirect github.com/google/uuid v1.6.0 // indirect github.com/googleapis/enterprise-certificate-proxy v0.3.7 // indirect github.com/googleapis/gax-go/v2 v2.15.0 // indirect github.com/gorilla/css v1.0.1 // indirect github.com/hexops/gotextdiff v1.0.3 // indirect github.com/hexops/valast v1.4.4 // indirect - github.com/huandu/xstrings v1.3.2 // indirect - github.com/imdario/mergo v0.3.16 // indirect - github.com/inconshreveable/mousetrap v1.1.0 // indirect - github.com/jdxcode/netrc v0.0.0-20221124155335-4616370d1a84 // indirect github.com/jmespath/go-jmespath v0.4.0 // indirect github.com/josharian/intern v1.0.0 // indirect github.com/klauspost/compress v1.18.0 // indirect @@ -193,30 +152,22 @@ require ( github.com/kr/text v0.2.0 // indirect github.com/lucasb-eyer/go-colorful v1.2.0 // indirect github.com/mailru/easyjson v0.7.7 // indirect - github.com/mattn/go-colorable v0.1.13 // indirect + github.com/mattn/go-colorable v0.1.14 // indirect github.com/mattn/go-runewidth v0.0.19 // indirect github.com/microcosm-cc/bluemonday v1.0.27 // indirect - github.com/mitchellh/copystructure v1.2.0 // indirect - github.com/mitchellh/reflectwalk v1.0.2 // indirect github.com/moby/term v0.5.2 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect github.com/muesli/reflow v0.3.0 // indirect github.com/muesli/termenv v0.16.0 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect - github.com/mwitkow/go-proto-validators v0.3.2 // indirect github.com/nightlyone/lockfile v1.0.0 // indirect github.com/olekukonko/tablewriter v0.0.5 // indirect github.com/pkg/errors v0.9.1 // indirect - github.com/pkg/profile v1.7.0 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect - github.com/pseudomuto/protoc-gen-doc v1.5.1 // indirect - github.com/pseudomuto/protokit v0.2.0 // indirect github.com/rivo/uniseg v0.4.7 // indirect github.com/rogpeppe/go-internal v1.14.1 // indirect - github.com/russross/blackfriday/v2 v2.1.0 // indirect github.com/sourcegraph/log v0.0.0-20250923023806-517b6960b55b // indirect - github.com/spf13/cobra v1.9.1 // indirect github.com/spf13/pflag v1.0.6 // indirect github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect github.com/stretchr/objx v0.5.2 // indirect @@ -231,7 +182,7 @@ require ( golang.org/x/crypto v0.45.0 // indirect golang.org/x/mod v0.29.0 // indirect golang.org/x/oauth2 v0.33.0 // indirect - golang.org/x/sys v0.40.0 // indirect + golang.org/x/sys v0.41.0 // indirect golang.org/x/term v0.37.0 // indirect golang.org/x/text v0.31.0 // indirect golang.org/x/time v0.14.0 // indirect diff --git a/go.sum b/go.sum index 176d0813ac..5d5a1be53e 100644 --- a/go.sum +++ b/go.sum @@ -24,7 +24,6 @@ cloud.google.com/go/trace v1.11.6 h1:2O2zjPzqPYAHrn3OKl029qlqG6W8ZdYaOWRyr8NgMT4 cloud.google.com/go/trace v1.11.6/go.mod h1:GA855OeDEBiBMzcckLPE2kDunIpC72N+Pq8WFieFjnI= github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg= github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= -github.com/BurntSushi/toml v1.2.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.29.0 h1:UQUsRi8WTzhZntp5313l+CHIAT95ojUI2lpP/ExlZa4= github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.29.0/go.mod h1:Cz6ft6Dkn3Et6l2v2a9/RpN7epQ1GtDlO6lj8bEcOvw= github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.50.0 h1:5IT7xOdq17MtcdtL/vtl6mGfzhaq4m4vpollPRmlsBQ= @@ -33,14 +32,8 @@ github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0 github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0.50.0/go.mod h1:SZiPHWGOOk3bl8tkevxkoiwPgsIl6CwrWcbwjfHZpdM= github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.50.0 h1:ig/FpDD2JofP/NExKQUbn7uOSZzJAQqogfqluZK4ed4= github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.50.0/go.mod h1:otE2jQekW/PqXk1Awf5lmfokJx4uwuqcj1ab5SpGeW0= -github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI= -github.com/Masterminds/goutils v1.1.1/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU= github.com/Masterminds/semver v1.5.0 h1:H65muMkzWKEuNDnfl9d70GUjFniHKHRbFPGBuZ3QEww= github.com/Masterminds/semver v1.5.0/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y= -github.com/Masterminds/sprig v2.22.0+incompatible h1:z4yfnGrZ7netVz+0EDJ0Wi+5VZCSYp4Z0m2dk6cEM60= -github.com/Masterminds/sprig v2.22.0+incompatible/go.mod h1:y6hNFY5UBTIWBxnzTeuNhlNS5hqE0NB0E6fgfo2Br3o= -github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= -github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= github.com/alecthomas/assert/v2 v2.7.0 h1:QtqSACNS3tF7oasA8CU6A6sXZSBDqnm7RfpLl9bZqbE= github.com/alecthomas/assert/v2 v2.7.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k= github.com/alecthomas/chroma/v2 v2.14.0 h1:R3+wzpnUArGcQz7fCETQBzO5n9IMNi13iIs46aU4V9E= @@ -88,16 +81,6 @@ github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuP github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4= github.com/benbjohnson/clock v1.3.5 h1:VvXlSJBzZpA/zum6Sj74hxwYI2DIxRWuNIoXAzHZz5o= github.com/benbjohnson/clock v1.3.5/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= -github.com/bufbuild/buf v1.25.0 h1:HFxKrR8wFcZwrBInN50K/oJX/WOtPVq24rHb/ArjfBA= -github.com/bufbuild/buf v1.25.0/go.mod h1:GCKZ5bAP6Ht4MF7KcfaGVgBEXGumwAz2hXjjLVxx8ZU= -github.com/bufbuild/connect-go v1.9.0 h1:JIgAeNuFpo+SUPfU19Yt5TcWlznsN5Bv10/gI/6Pjoc= -github.com/bufbuild/connect-go v1.9.0/go.mod h1:CAIePUgkDR5pAFaylSMtNK45ANQjp9JvpluG20rhpV8= -github.com/bufbuild/connect-opentelemetry-go v0.4.0 h1:6JAn10SNqlQ/URhvRNGrIlczKw1wEXknBUUtmWqOiak= -github.com/bufbuild/connect-opentelemetry-go v0.4.0/go.mod h1:nwPXYoDOoc2DGyKE/6pT1Q9MPSi2Et2e6BieMD0l6WU= -github.com/bufbuild/protocompile v0.5.1 h1:mixz5lJX4Hiz4FpqFREJHIXLfaLBntfaJv1h+/jS+Qg= -github.com/bufbuild/protocompile v0.5.1/go.mod h1:G5iLmavmF4NsYtpZFvE3B/zFch2GIY8+wjsYLR/lc40= -github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM= -github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc h1:4pZI35227imm7yK2bGPcfpFEmuY1gc2YSTShr4iJBfs= @@ -116,9 +99,6 @@ github.com/charmbracelet/x/exp/slice v0.0.0-20250327172914-2fdc97757edf h1:rLG0Y github.com/charmbracelet/x/exp/slice v0.0.0-20250327172914-2fdc97757edf/go.mod h1:B3UgsnsBZS/eX42BlaNiJkD1pPOUa+oF1IYC6Yd2CEU= github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ= github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg= -github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= -github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= -github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= github.com/clipperhouse/uax29/v2 v2.2.0 h1:ChwIKnQN3kcZteTXMgb1wztSgaU+ZemkgWdohwgs8tY= github.com/clipperhouse/uax29/v2 v2.2.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM= github.com/cncf/xds/go v0.0.0-20250501225837-2ac532fd4443 h1:aQ3y1lwWyqYPiWZThqv1aFbZMiM9vblcSArJRf2Irls= @@ -129,13 +109,6 @@ github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b h1:r6VH0faHjZe github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= github.com/cockroachdb/redact v1.1.6 h1:zXJBwDZ84xJNlHl1rMyCojqyIxv+7YUpQiJLQ7n4314= github.com/cockroachdb/redact v1.1.6/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= -github.com/containerd/log v0.1.0 h1:TCJt7ioM2cr/tfR8GPbGf9/VRAX8D2B4PjzCpfX540I= -github.com/containerd/log v0.1.0/go.mod h1:VRRf09a7mHDIRezVKTRCrOq78v577GXq3bSa3EhrzVo= -github.com/containerd/stargz-snapshotter/estargz v0.14.3 h1:OqlDCK3ZVUO6C3B/5FSkDwbkEETK84kQgEeFwDC+62k= -github.com/containerd/stargz-snapshotter/estargz v0.14.3/go.mod h1:KY//uOCIkSuNAHhJogcZtrNHdKrA99/FCCRjE3HD36o= -github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= -github.com/cpuguy83/go-md2man/v2 v2.0.6 h1:XJtiaUW6dEEqVuZiMTn1ldk455QWwEIsMIJlo5vtkx0= -github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= github.com/creack/goselect v0.1.2 h1:2DNy14+JPjRBgPzAd1thbQp4BSIihxcBf0IXhQXDRa0= github.com/creack/goselect v0.1.2/go.mod h1:a/NhLweNvqIYMuxcMOuWY516Cimucms3DglDzQP3hKY= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= @@ -151,22 +124,8 @@ github.com/derision-test/glock v1.0.0 h1:b6sViZG+Cm6QtdpqbfWEjaBVbzNPntIS4GzsxpS github.com/derision-test/glock v1.0.0/go.mod h1:jKtLdBMrF+XQatqvg46wiWdDfDSSDjdhO4dOM2FX9H4= github.com/dineshappavoo/basex v0.0.0-20170425072625-481a6f6dc663 h1:fctNkSsavbXpt8geFWZb8n+noCqS8MrOXRJ/YfdZ2dQ= github.com/dineshappavoo/basex v0.0.0-20170425072625-481a6f6dc663/go.mod h1:Kad2hux31v/IyD4Rf4wAwIyK48995rs3qAl9IUAhc2k= -github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk= -github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E= github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI= github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= -github.com/docker/cli v24.0.4+incompatible h1:Y3bYF9ekNTm2VFz5U/0BlMdJy73D+Y1iAAZ8l63Ydzw= -github.com/docker/cli v24.0.4+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8= -github.com/docker/distribution v2.8.2+incompatible h1:T3de5rq0dB1j30rp0sA2rER+m322EBzniBPB6ZIzuh8= -github.com/docker/distribution v2.8.2+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= -github.com/docker/docker v28.0.0+incompatible h1:Olh0KS820sJ7nPsBKChVhk5pzqcwDR15fumfAd/p9hM= -github.com/docker/docker v28.0.0+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= -github.com/docker/docker-credential-helpers v0.8.0 h1:YQFtbBQb4VrpoPxhFuzEBPQ9E16qz5SpHLS+uswaCp8= -github.com/docker/docker-credential-helpers v0.8.0/go.mod h1:UGFXcuoQ5TxPiB54nHOZ32AWRqQdECoh/Mg0AlEYb40= -github.com/docker/go-connections v0.4.0 h1:El9xVISelRB7BuFusrZozjnkIM5YnzCViNKohAFqRJQ= -github.com/docker/go-connections v0.4.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5XhDvyHbTtUxmeec= -github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4= -github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/emicklei/go-restful/v3 v3.11.0 h1:rAQeMHw1c7zTmncogyy8VvRZwtkmkZ4FxERmMY4rD+g= @@ -180,10 +139,8 @@ github.com/envoyproxy/go-control-plane/ratelimit v0.1.0/go.mod h1:Wk+tMFAFbCXaJP github.com/envoyproxy/protoc-gen-validate v1.2.1 h1:DEo3O99U8j4hBFwbJfrz9VtgcDfUKS7KJ7spH3d86P8= github.com/envoyproxy/protoc-gen-validate v1.2.1/go.mod h1:d/C80l/jxXLdfEIhX1W2TmLfsJ31lvEjwamM4DxlWXU= github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= -github.com/fatih/color v1.16.0 h1:zmkK9Ngbjj+K0yRhTVONQh1p/HknKYSlNT+vZCzyokM= -github.com/fatih/color v1.16.0/go.mod h1:fL2Sau1YI5c0pdGEVCbKQbLXB6edEj1ZgiY4NijnWvE= -github.com/felixge/fgprof v0.9.3 h1:VvyZxILNuCiUCSXtPtYmmtGvb65nqXh2QFWc0Wpf2/g= -github.com/felixge/fgprof v0.9.3/go.mod h1:RdbpDgzqYVh/T9fPELJyV7EYJuHB55UTEULNun8eiPw= +github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM= +github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU= github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/frankban/quicktest v1.14.3/go.mod h1:mgiwOwqx65TmIk1wJ6Q7wvnVMocbUorkibMOrVTHZps= @@ -193,8 +150,6 @@ github.com/fxamacker/cbor/v2 v2.7.0 h1:iM5WgngdRBanHcxugY4JySA0nk1wZorNOpTgCMedv github.com/fxamacker/cbor/v2 v2.7.0/go.mod h1:pxXPTn3joSm21Gbwsv0w9OSA2y1HFR9qXEeXQVeNoDQ= github.com/getsentry/sentry-go v0.27.0 h1:Pv98CIbtB3LkMWmXi4Joa5OOcwbmnX88sF5qbK3r3Ps= github.com/getsentry/sentry-go v0.27.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= -github.com/go-chi/chi/v5 v5.2.2 h1:CMwsvRVTbXVytCk1Wd72Zy1LAsAh9GxMmSNWLHCG618= -github.com/go-chi/chi/v5 v5.2.2/go.mod h1:L2yAIGWB3H+phAw1NxKwWM+7eUH/lU8pOMm5hHcoops= github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA= github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og= github.com/go-jose/go-jose/v4 v4.1.2 h1:TK/7NqRQZfgAh+Td8AlsrvtPoUyiHh0LqVvokh+1vHI= @@ -218,14 +173,8 @@ github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y= github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8= github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk= github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= -github.com/gofrs/flock v0.8.1 h1:+gYjHKf32LDeiEEFhQaotPbLuUXjY5ZqxKgXy7n59aw= -github.com/gofrs/flock v0.8.1/go.mod h1:F1TvTiK9OcQqauNUHlbJvyl9Qa1QvF/gOUDKA14jxHU= -github.com/gofrs/uuid/v5 v5.0.0 h1:p544++a97kEL+svbcFbCQVM9KFu0Yo25UoISXGNNH9M= -github.com/gofrs/uuid/v5 v5.0.0/go.mod h1:CDOjlDMVAtN56jqyRUZh58JT31Tiw7/oQyEXZV+9bD8= -github.com/gogo/protobuf v1.3.0/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= -github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/google/gnostic-models v0.6.9 h1:MU/8wDLif2qCXZmzncUQ/BOfxWfthHi63KqpoNbWqVw= @@ -237,14 +186,11 @@ github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeN github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= -github.com/google/go-containerregistry v0.19.1 h1:yMQ62Al6/V0Z7CqIrrS1iYoA5/oQCm88DeNujc7C1KY= -github.com/google/go-containerregistry v0.19.1/go.mod h1:YCMFNQeeXeLF+dnhhWkqDItx/JSkH01j1Kis4PsjzFI= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/martian/v3 v3.3.3 h1:DIhPTQrbPkgs2yJYdXU/eNACCG5DVQjySNRNlflZ9Fc= github.com/google/martian/v3 v3.3.3/go.mod h1:iEPrYcgCF7jA9OtScMFQyAlZZ4YXTKEtJ1E6RWzmBA0= -github.com/google/pprof v0.0.0-20211214055906-6f57359322fd/go.mod h1:KgnwoLYCZ8IQu3XUZ8Nc/bM9CCZFOyjUNOSygVozoDg= github.com/google/pprof v0.0.0-20241029153458-d1b30febd7db h1:097atOisP2aRj7vFgYQBbFN4U4JNXUNYpxael3UzMyo= github.com/google/pprof v0.0.0-20241029153458-d1b30febd7db/go.mod h1:vavhavw2zAxS5dIdcRluK6cSGGPlZynqzFM8NdvU144= github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0= @@ -264,27 +210,18 @@ github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 h1:JeSE6pjso5T github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674/go.mod h1:r4w70xmWCQKmi1ONH4KIaBptdivuRPyosB9RmPlGEwA= github.com/grafana/regexp v0.0.0-20250905093917-f7b3be9d1853 h1:cLN4IBkmkYZNnk7EAJ0BHIethd+J6LqxFNw5mSiI2bM= github.com/grafana/regexp v0.0.0-20250905093917-f7b3be9d1853/go.mod h1:+JKpmjMGhpgPL+rXZ5nsZieVzvarn86asRlBg4uNGnk= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2 h1:8Tjv8EJ+pM1xP8mK6egEbD1OgnVTyacbefKhmbLhIhU= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2/go.mod h1:pkJQ2tZHJ0aFOVEEot6oZmaVEZcRme73eIFmhiVuRWs= github.com/hexops/autogold v0.8.1/go.mod h1:97HLDXyG23akzAoRYJh/2OBs3kd80eHyKPvZw0S5ZBY= github.com/hexops/autogold v1.3.1 h1:YgxF9OHWbEIUjhDbpnLhgVsjUDsiHDTyDfy2lrfdlzo= github.com/hexops/autogold v1.3.1/go.mod h1:sQO+mQUCVfxOKPht+ipDSkJ2SCJ7BNJVHZexsXqWMx4= -github.com/hexops/autogold/v2 v2.2.1 h1:JPUXuZQGkcQMv7eeDXuNMovjfoRYaa0yVcm+F3voaGY= -github.com/hexops/autogold/v2 v2.2.1/go.mod h1:IJwxtUfj1BGLm0YsR/k+dIxYi6xbeLjqGke2bzcOTMI= +github.com/hexops/autogold/v2 v2.0.3 h1:zyrfTlNfyxLpX/zuk8wjTeTYP5AXaFeeRYFEZfHPwao= +github.com/hexops/autogold/v2 v2.0.3/go.mod h1:cYVc0tJn6v9Uf9xMOHvmH6scuTxsVJSxGcKR/yOVPzY= github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM= github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg= github.com/hexops/valast v1.4.3/go.mod h1:Iqx2kLj3Jn47wuXpj3wX40xn6F93QNFBHuiKBerkTGA= github.com/hexops/valast v1.4.4 h1:rETyycw+/L2ZVJHHNxEBgh8KUn+87WugH9MxcEv9PGs= github.com/hexops/valast v1.4.4/go.mod h1:Jcy1pNH7LNraVaAZDLyv21hHg2WBv9Nf9FL6fGxU7o4= -github.com/huandu/xstrings v1.3.2 h1:L18LIDzqlW6xN2rEkpdV8+oL/IXWJ1APd+vsdYy4Wdw= -github.com/huandu/xstrings v1.3.2/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE= github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI= github.com/iancoleman/strcase v0.3.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho= -github.com/ianlancetaylor/demangle v0.0.0-20210905161508-09a460cdf81d/go.mod h1:aYm2/VgdVmcIU8iMfdMvDMsRAQjcfZSKFby6HOFvi/w= -github.com/imdario/mergo v0.3.16 h1:wwQJbIsHYGMUyLSPrEq1CT16AhnhNJQ51+4fdHUnCl4= -github.com/imdario/mergo v0.3.16/go.mod h1:WBLT9ZmE3lPoWsEzCh9LPo3TiwVN+ZKEjmz+hD27ysY= -github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= -github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= @@ -293,12 +230,8 @@ github.com/jackc/pgx/v5 v5.9.1 h1:uwrxJXBnx76nyISkhr33kQLlUqjv7et7b9FjCen/tdc= github.com/jackc/pgx/v5 v5.9.1/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= -github.com/jdxcode/netrc v0.0.0-20221124155335-4616370d1a84 h1:2uT3aivO7NVpUPGcQX7RbHijHMyWix/yCnIrCWc+5co= -github.com/jdxcode/netrc v0.0.0-20221124155335-4616370d1a84/go.mod h1:Zi/ZFkEqFHTm7qkjyNJjaWH4LQA9LQhGJyF0lTYGpxw= github.com/jedib0t/go-pretty/v6 v6.6.3 h1:nGqgS0tgIO1Hto47HSaaK4ac/I/Bu7usmdD3qvs0WvM= github.com/jedib0t/go-pretty/v6 v6.6.3/go.mod h1:zbn98qrYlh95FIhwwsbIip0LYpwSG8SUOScs+v9/t0E= -github.com/jhump/protoreflect v1.15.1 h1:HUMERORf3I3ZdX05WaQ6MIpd/NJ434hTp5YiKgfCL6c= -github.com/jhump/protoreflect v1.15.1/go.mod h1:jD/2GMKKE6OqX8qTjhADU1e6DShO+gavG9e0Q693nKo= github.com/jig/teereadcloser v0.0.0-20181016160506-953720c48e05 h1:dSwwtWuwMyarzsbVWOq4QJ8xVy9wgcNomvWyGtrKe+E= github.com/jig/teereadcloser v0.0.0-20181016160506-953720c48e05/go.mod h1:sRUFlj+HCejvoCRpuhU0EYnNw5FG+YJpz8UFfCf0F2U= github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg= @@ -311,7 +244,6 @@ github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnr github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 h1:Z9n2FFNUXsshfwJMBgNA0RU6/i7WVaAegv3PtuIHPMs= github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51/go.mod h1:CzGEWj7cYgsdH8dAjBGEr58BoE7ScuLd+fwFZ44+/x8= -github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= @@ -332,8 +264,9 @@ github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= -github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= +github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE= +github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= @@ -345,14 +278,6 @@ github.com/mattn/go-runewidth v0.0.19 h1:v++JhqYnZuu5jSKrk9RbgF5v4CGUjqRfBm05byF github.com/mattn/go-runewidth v0.0.19/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs= github.com/microcosm-cc/bluemonday v1.0.27 h1:MpEUotklkwCSLeH+Qdx1VJgNqLlpY2KXwXFM08ygZfk= github.com/microcosm-cc/bluemonday v1.0.27/go.mod h1:jFi9vgW+H7c3V0lb6nR74Ib/DIB5OBs92Dimizgw2cA= -github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw= -github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s= -github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= -github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= -github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ= -github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= -github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0= -github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo= github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ= github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -360,19 +285,14 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= -github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A= -github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc= github.com/muesli/reflow v0.3.0 h1:IFsN6K9NfGtjeggFP+68I4chLZV2yIKsXJFNZ+eWh6s= github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKtnHY/8= github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc= github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= -github.com/mwitkow/go-proto-validators v0.3.2 h1:qRlmpTzm2pstMKKzTdvwPCF5QfBNURSlAgN/R+qbKos= -github.com/mwitkow/go-proto-validators v0.3.2/go.mod h1:ej0Qp0qMgHN/KtDyUt+Q1/tA7a5VarXUOUxD+oeD30w= github.com/neelance/parallel v0.0.0-20160708114440-4de9ce63d14c h1:NZOii9TDGRAfCS5VM16XnF4K7afoLQmIiZX8EkKnxtE= github.com/neelance/parallel v0.0.0-20160708114440-4de9ce63d14c/go.mod h1:eTBvSIlRgLo+CNFFQRQTwUGTZOEdvXIKeZS/xG+D2yU= -github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/nightlyone/lockfile v1.0.0 h1:RHep2cFKK4PonZJDdEl4GmkabuhbsRMgk/k3uAmxBiA= github.com/nightlyone/lockfile v1.0.0/go.mod h1:rywoIealpdNse2r832aiD9jRk8ErCatROs6LzC841CI= github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec= @@ -381,10 +301,6 @@ github.com/onsi/ginkgo/v2 v2.21.0 h1:7rg/4f3rB88pb5obDgNZrNHrQ4e6WpjonchcpuBRnZM github.com/onsi/ginkgo/v2 v2.21.0/go.mod h1:7Du3c42kxCUegi0IImZ1wUQzMBVecgIHjR1C+NkhLQo= github.com/onsi/gomega v1.35.1 h1:Cwbd75ZBPxFSuZ6T+rN/WCb/gOc6YgFBXLlZLhC7Ds4= github.com/onsi/gomega v1.35.1/go.mod h1:PvZbdDc8J6XJEpDK4HCuRBm8a6Fzp9/DmhC9C7yFlog= -github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= -github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= -github.com/opencontainers/image-spec v1.1.0-rc4 h1:oOxKUJWnFC4YGHCCMNql1x4YaDfYBTS5Y4x/Cgeo1E0= -github.com/opencontainers/image-spec v1.1.0-rc4/go.mod h1:X4pATf0uXsnn3g5aiGIsVnJBR4mxhKzfwmvK/B2NTm8= github.com/petermattis/goid v0.0.0-20240813172612-4fcff4a6cae7 h1:Dx7Ovyv/SFnMFw3fD4oEoeorXc6saIiQ23LrGLth0Gw= github.com/petermattis/goid v0.0.0-20240813172612-4fcff4a6cae7/go.mod h1:pxMtw7cyUw6B2bRH0ZBANSPg+AoSud1I1iyJHI69jH4= github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4= @@ -394,17 +310,11 @@ github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8/go.mod h1:HKlIX3XHQyzL github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pkg/profile v1.7.0 h1:hnbDkaNWPCLMO9wGLdBFTIZvzDrDfBM2072E1S9gJkA= -github.com/pkg/profile v1.7.0/go.mod h1:8Uer0jas47ZQMJ7VD+OHknK4YDY07LPUC6dEvqDjvNo= github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 h1:GFCKgmp0tecUJ0sJuv4pzYCqS9+RGSn52M3FUwPs+uo= github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10/go.mod h1:t/avpk3KcrXxUnYOhZhMXJlSEyie6gQbtLq5NM3loB8= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/pseudomuto/protoc-gen-doc v1.5.1 h1:Ah259kcrio7Ix1Rhb6u8FCaOkzf9qRBqXnvAufg061w= -github.com/pseudomuto/protoc-gen-doc v1.5.1/go.mod h1:XpMKYg6zkcpgfpCfQ8GcWBDRtRxOmMR5w7pz4Xo+dYM= -github.com/pseudomuto/protokit v0.2.0 h1:hlnBDcy3YEDXH7kc9gV+NLaN0cDzhDvD1s7Y6FZ8RpM= -github.com/pseudomuto/protokit v0.2.0/go.mod h1:2PdH30hxVHsup8KpBTOXTBeMVhJZVio3Q8ViKSAXT0Q= github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= @@ -413,19 +323,14 @@ github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTE github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= -github.com/rs/cors v1.11.0 h1:0B9GE/r9Bc2UxRMMtymBkHTenPkHDv0CW4Y98GBY+po= -github.com/rs/cors v1.11.0/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU= -github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= -github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/sasha-s/go-deadlock v0.3.5 h1:tNCOEEDG6tBqrNDOX35j/7hL5FcFViG6awUGROb2NsU= github.com/sasha-s/go-deadlock v0.3.5/go.mod h1:bugP6EGbdGYObIlx7pUZtWqlvo8k9H6vCBBsiChJQ5U= +github.com/scip-code/scip/bindings/go/scip v0.7.0 h1:on80ynl7eSovvMUy3uxWkJm+kepsVjIwI2byIeMZego= +github.com/scip-code/scip/bindings/go/scip v0.7.0/go.mod h1:XC4dP3um0lKaSDRFIMwYlkBjFxKy1Rw7xFt6KDtRjAk= github.com/segmentio/ksuid v1.0.4 h1:sBo2BdShXjmcugAMwjugoGUdUV0pcxY5mW4xKRn3v4c= github.com/segmentio/ksuid v1.0.4/go.mod h1:/XUiZBD3kVx5SmUOl55voK5yeAbBNNIed+2O73XgrPE= github.com/shurcooL/go v0.0.0-20180423040247-9e1955d9fb6e/go.mod h1:TDJrrUr11Vxrven61rcy3hJMUqaf/CLWYhHNPmT14Lk= github.com/shurcooL/go-goon v0.0.0-20170922171312-37c2f522c041/go.mod h1:N5mDOmsrJOB+vfqUK+7DmDyjhSLIIBnXo9lvZJj3MWQ= -github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= -github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= -github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/sourcegraph/beaut v0.0.0-20240611013027-627e4c25335a h1:j/CQ27s679M9wRGBRJYyXGrfkYuQA6VMnD7R08mHD9c= github.com/sourcegraph/beaut v0.0.0-20240611013027-627e4c25335a/go.mod h1:JG1sdvGTKWwe/oH3/3UKQ26vfcHIN//7fwEJhoqaBcM= github.com/sourcegraph/conc v0.3.1-0.20240108182409-4afefce20f9b h1:0FsjN+u9fNXTS2C1JnJ6G/gkgcUg8dscyyfu3PwHWUQ= @@ -438,12 +343,8 @@ github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWii github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= github.com/sourcegraph/log v0.0.0-20250923023806-517b6960b55b h1:2FQ72y5zECMu9e5z5jMnllb5n1jVK7qsvgjkVtdFV+g= github.com/sourcegraph/log v0.0.0-20250923023806-517b6960b55b/go.mod h1:IDp09QkoqS8Z3CyN2RW6vXjgABkNpDbyjLIHNQwQ8P8= -github.com/sourcegraph/scip v0.6.1 h1:lcBrTwGjsqpMLQN4pVfJYSB+8oVoc8Lnqb4FAfU8EBM= -github.com/sourcegraph/scip v0.6.1/go.mod h1:c6d9mk1cGT6OXdHutxDakKVEPN1D+iFoYWCsrDxEhus= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= -github.com/spf13/cobra v1.9.1 h1:CXSaggrXdbHK9CF+8ywj8Amf7PBRmPCOJugH954Nnlo= -github.com/spf13/cobra v1.9.1/go.mod h1:nDyEzZ8ogv936Cinf6g1RU9MRY64Ir93oCnqb9wxYW0= github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o= github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spiffe/go-spiffe/v2 v2.5.0 h1:N2I01KCUkv1FAjZXJMwh95KK1ZIQLYbPfhaxw8WS0hE= @@ -463,17 +364,12 @@ github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= -github.com/tetratelabs/wazero v1.3.0 h1:nqw7zCldxE06B8zSZAY0ACrR9OH5QCcPwYmYlwtcwtE= -github.com/tetratelabs/wazero v1.3.0/go.mod h1:wYx2gNRg8/WihJfSDxA1TIL8H+GkfLYm+bIfbblu9VQ= github.com/tliron/commonlog v0.2.19 h1:v1mOH1TyzFLqkshR03khw7ENAZPjAyZTQBQrqN+vX9c= github.com/tliron/commonlog v0.2.19/go.mod h1:AcdhfcUqlAWukDrzTGyaPhUgYiNdZhS4dKzD/e0tjcY= github.com/tliron/glsp v0.2.2 h1:IKPfwpE8Lu8yB6Dayta+IyRMAbTVunudeauEgjXBt+c= github.com/tliron/glsp v0.2.2/go.mod h1:GMVWDNeODxHzmDPvYbYTCs7yHVaEATfYtXiYJ9w1nBg= github.com/tliron/kutil v0.3.27 h1:Wb0V5jdbTci6Let1tiGY741J/9FIynmV/pCsPDPsjcM= github.com/tliron/kutil v0.3.27/go.mod h1:AHeLNIFBSKBU39ELVHZdkw2f/ez2eKGAAGoxwBlhMi8= -github.com/urfave/cli v1.22.12/go.mod h1:sSBEIC79qR6OvcmsD4U3KABeOTxDqQtdDnaFuUN30b8= -github.com/vbatts/tar-split v0.11.3 h1:hLFqsOLQ1SsppQNTMpkpPXClLDfC2A3Zgy9OUU+RVck= -github.com/vbatts/tar-split v0.11.3/go.mod h1:9QlHN18E+fEH7RdG+QAJJcuya3rqT7eXSTY7wGrAokY= github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= @@ -509,10 +405,6 @@ go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0 h1:RbKq8BG go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0/go.mod h1:h06DGIukJOevXaj/xrNjhi/2098RZzcLTbc0jDAUbsg= go.opentelemetry.io/otel v1.40.0 h1:oA5YeOcpRTXq6NN7frwmwFR0Cn3RhTVZvXsP4duvCms= go.opentelemetry.io/otel v1.40.0/go.mod h1:IMb+uXZUKkMXdPddhwAHm6UfOwJyh4ct1ybIlV14J0g= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.38.0 h1:GqRJVj7UmLjCVyVJ3ZFLdPRmhDUp2zFmQe3RHIOsw24= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.38.0/go.mod h1:ri3aaHSmCTVYu2AWv44YMauwAQc0aqI9gHKIcSbI1pU= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.38.0 h1:aTL7F04bJHUlztTsNGJ2l+6he8c+y/b//eR0jjjemT4= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.38.0/go.mod h1:kldtb7jDTeol0l3ewcmd8SDvx3EmIE7lyvqbasU3QC4= go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.29.0 h1:WDdP9acbMYjbKIyJUhTvtzj601sVJOqgWdUxSdR/Ysc= go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.29.0/go.mod h1:BLbf7zbNIONBLPwvFnwNHGj4zge8uTCM/UPIVW1Mq2I= go.opentelemetry.io/otel/metric v1.40.0 h1:rcZe317KPftE2rstWIBitCdVp89A2HqjkxR3c11+p9g= @@ -523,8 +415,6 @@ go.opentelemetry.io/otel/sdk/metric v1.40.0 h1:mtmdVqgQkeRxHgRv4qhyJduP3fYJRMX4A go.opentelemetry.io/otel/sdk/metric v1.40.0/go.mod h1:4Z2bGMf0KSK3uRjlczMOeMhKU2rhUqdWNoKcYrtcBPg= go.opentelemetry.io/otel/trace v1.40.0 h1:WA4etStDttCSYuhwvEa8OP8I5EWu24lkOzp+ZYblVjw= go.opentelemetry.io/otel/trace v1.40.0/go.mod h1:zeAhriXecNGP/s2SEG3+Y8X9ujcJOTqQ5RgdEJcawiA= -go.opentelemetry.io/proto/otlp v1.7.1 h1:gTOMpGDb0WTBOP8JaO72iL3auEZhVmAQg4ipjOVAtj4= -go.opentelemetry.io/proto/otlp v1.7.1/go.mod h1:b2rVh6rfI/s2pHWNlB7ILJcRALpcNDzKhACevjI+ZnE= go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= @@ -539,8 +429,8 @@ golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPh golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q= golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4= -golang.org/x/exp v0.0.0-20231108232855-2478ac86f678 h1:mchzmB1XO2pMaKFRqk/+MV3mgGG96aqaPXaMifQU47w= -golang.org/x/exp v0.0.0-20231108232855-2478ac86f678/go.mod h1:zk2irFbV9DP96SEBUUAy67IdHUaZuSnrz1n472HUCLE= +golang.org/x/exp v0.0.0-20230713183714-613f0c0eb8a1 h1:MGwJjxBy0HJshjDNfLsYO8xppfqWlA5ZT9OhtUUhTNw= +golang.org/x/exp v0.0.0-20230713183714-613f0c0eb8a1/go.mod h1:FXUEEKJgO7OQYeo8N01OfiKP8RXMtf6e8aTskBGqWdc= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= @@ -576,19 +466,14 @@ golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20210616045830-e2b7044e8c71/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20211007075335-d3039528d8ac/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220829200755-d48e67d00261/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220906165534-d0df966e6959/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ= -golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= -golang.org/x/telemetry v0.0.0-20251008203120-078029d740a8 h1:LvzTn0GQhWuvKH/kVRS3R3bVAsdQWI7hvfLHGgh9+lU= -golang.org/x/telemetry v0.0.0-20251008203120-078029d740a8/go.mod h1:Pi4ztBfryZoJEkyFTI5/Ocsu2jXyDr6iSdgJiYE/uwE= +golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k= +golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.3.0/go.mod h1:q750SLmJuPmVoN1blW3UFBPREJfb1KmY3vwxfr+nFDA= @@ -603,7 +488,6 @@ golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM= golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI= golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200624163319-25775e59acb7/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= @@ -632,7 +516,6 @@ google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aO google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= @@ -647,8 +530,6 @@ gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gotest.tools/v3 v3.0.3 h1:4AuOwCGf4lLR9u3YOe2awrHygurzhO/HeQ6laiA6Sx0= -gotest.tools/v3 v3.0.3/go.mod h1:Z7Lb0S5l+klDB31fvDQX8ss/FlKDxtlFlw3Oa8Ymbl8= jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7 h1:mub0MmFLOn8XLikZOAhgLD1kXJq8jgftSrrv7m00xFo= jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7/go.mod h1:OxvTsCwKosqQ1q7B+8FwXqg4rKZ/UG9dUW+g/VL2xH4= k8s.io/api v0.33.2 h1:YgwIS5jKfA+BZg//OQhkJNIfie/kmRsO0BmNaVSimvY= diff --git a/lib/codeintel/upload/indexer_name.go b/lib/codeintel/upload/indexer_name.go index 7a1c084765..318dc6f82b 100644 --- a/lib/codeintel/upload/indexer_name.go +++ b/lib/codeintel/upload/indexer_name.go @@ -6,7 +6,7 @@ import ( "encoding/json" "io" - "github.com/sourcegraph/scip/bindings/go/scip" + "github.com/scip-code/scip/bindings/go/scip" "google.golang.org/protobuf/proto" "github.com/sourcegraph/sourcegraph/lib/errors" diff --git a/lib/go.mod b/lib/go.mod index 018111d005..4018fc8f27 100644 --- a/lib/go.mod +++ b/lib/go.mod @@ -18,14 +18,14 @@ require ( github.com/mattn/go-runewidth v0.0.19 github.com/moby/term v0.5.2 github.com/muesli/termenv v0.16.0 + github.com/scip-code/scip/bindings/go/scip v0.7.0 github.com/sourcegraph/conc v0.3.0 github.com/sourcegraph/go-diff v0.7.0 github.com/sourcegraph/log v0.0.0-20250923023806-517b6960b55b - github.com/sourcegraph/scip v0.6.1 github.com/xeipuuv/gojsonschema v1.2.0 github.com/xlab/treeprint v1.2.0 go.opentelemetry.io/otel v1.38.0 - golang.org/x/sys v0.38.0 + golang.org/x/sys v0.41.0 golang.org/x/term v0.37.0 google.golang.org/protobuf v1.36.10 gopkg.in/yaml.v3 v3.0.1 @@ -33,16 +33,10 @@ require ( require ( github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c // indirect - github.com/Masterminds/sprig v2.15.0+incompatible // indirect - github.com/Microsoft/go-winio v0.6.1 // indirect github.com/alecthomas/chroma/v2 v2.14.0 // indirect - github.com/aokoli/goutils v1.0.1 // indirect github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect github.com/aymerick/douceur v0.2.0 // indirect - github.com/bufbuild/buf v1.25.0 // indirect - github.com/bufbuild/connect-go v1.9.0 // indirect - github.com/bufbuild/connect-opentelemetry-go v0.4.0 // indirect - github.com/bufbuild/protocompile v0.5.1 // indirect + github.com/benbjohnson/clock v1.3.5 // indirect github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect github.com/charmbracelet/x/ansi v0.8.0 // indirect github.com/charmbracelet/x/cellbuf v0.0.13 // indirect @@ -50,86 +44,37 @@ require ( github.com/charmbracelet/x/term v0.2.1 // indirect github.com/clipperhouse/uax29/v2 v2.2.0 // indirect github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect - github.com/containerd/log v0.1.0 // indirect - github.com/containerd/stargz-snapshotter/estargz v0.14.3 // indirect - github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect - github.com/distribution/reference v0.6.0 // indirect github.com/dlclark/regexp2 v1.11.0 // indirect - github.com/docker/cli v24.0.4+incompatible // indirect - github.com/docker/distribution v2.8.2+incompatible // indirect - github.com/docker/docker v25.0.6+incompatible // indirect - github.com/docker/docker-credential-helpers v0.8.0 // indirect - github.com/docker/go-connections v0.4.0 // indirect - github.com/docker/go-units v0.5.0 // indirect - github.com/envoyproxy/protoc-gen-validate v0.3.0-java // indirect - github.com/fatih/color v1.15.0 // indirect - github.com/felixge/fgprof v0.9.3 // indirect - github.com/felixge/httpsnoop v1.0.4 // indirect + github.com/fatih/color v1.18.0 // indirect github.com/getsentry/sentry-go v0.27.0 // indirect - github.com/go-chi/chi/v5 v5.0.10 // indirect - github.com/go-logr/logr v1.4.3 // indirect - github.com/go-logr/stdr v1.2.2 // indirect - github.com/gofrs/uuid/v5 v5.0.0 // indirect github.com/gogo/protobuf v1.3.2 // indirect - github.com/golang/protobuf v1.5.3 // indirect - github.com/google/go-containerregistry v0.15.2 // indirect - github.com/google/pprof v0.0.0-20230705174524-200ffdc848b8 // indirect github.com/google/uuid v1.6.0 // indirect github.com/gorilla/css v1.0.1 // indirect - github.com/huandu/xstrings v1.0.0 // indirect - github.com/imdario/mergo v0.3.4 // indirect - github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect - github.com/jdxcode/netrc v0.0.0-20221124155335-4616370d1a84 // indirect github.com/klauspost/compress v1.18.0 // indirect github.com/kr/pretty v0.3.1 // indirect github.com/kr/text v0.2.0 // indirect github.com/lucasb-eyer/go-colorful v1.2.0 // indirect - github.com/mattn/go-colorable v0.1.13 // indirect + github.com/mattn/go-colorable v0.1.14 // indirect github.com/microcosm-cc/bluemonday v1.0.27 // indirect - github.com/mitchellh/go-homedir v1.1.0 // indirect - github.com/morikuni/aec v1.0.0 // indirect github.com/muesli/reflow v0.3.0 // indirect - github.com/mwitkow/go-proto-validators v0.0.0-20180403085117-0950a7990007 // indirect - github.com/opencontainers/go-digest v1.0.0 // indirect - github.com/opencontainers/image-spec v1.1.0-rc4 // indirect - github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 // indirect github.com/pkg/errors v0.9.1 // indirect - github.com/pkg/profile v1.7.0 // indirect - github.com/pseudomuto/protoc-gen-doc v1.5.1 // indirect - github.com/pseudomuto/protokit v0.2.0 // indirect github.com/rivo/uniseg v0.4.7 // indirect - github.com/rogpeppe/go-internal v1.13.1 // indirect - github.com/rs/cors v1.9.0 // indirect - github.com/russross/blackfriday/v2 v2.1.0 // indirect - github.com/sirupsen/logrus v1.9.3 // indirect + github.com/rogpeppe/go-internal v1.14.1 // indirect github.com/sourcegraph/beaut v0.0.0-20240611013027-627e4c25335a // indirect - github.com/spf13/cobra v1.7.0 // indirect - github.com/spf13/pflag v1.0.5 // indirect - github.com/tetratelabs/wazero v1.3.0 // indirect - github.com/vbatts/tar-split v0.11.3 // indirect github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f // indirect github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect github.com/yuin/goldmark v1.7.8 // indirect github.com/yuin/goldmark-emoji v1.0.5 // indirect - go.opentelemetry.io/auto/sdk v1.1.0 // indirect - go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0 // indirect - go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.38.0 // indirect - go.opentelemetry.io/otel/metric v1.38.0 // indirect - go.opentelemetry.io/otel/sdk v1.38.0 // indirect - go.opentelemetry.io/otel/trace v1.38.0 // indirect go.uber.org/atomic v1.11.0 // indirect + go.uber.org/goleak v1.3.0 // indirect go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.24.0 // indirect - golang.org/x/crypto v0.42.0 // indirect - golang.org/x/mod v0.28.0 // indirect + golang.org/x/exp v0.0.0-20230713183714-613f0c0eb8a1 // indirect golang.org/x/net v0.44.0 // indirect - golang.org/x/sync v0.17.0 // indirect - golang.org/x/telemetry v0.0.0-20250908211612-aef8a434d053 // indirect golang.org/x/text v0.29.0 // indirect golang.org/x/tools v0.37.0 // indirect - google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect ) diff --git a/lib/go.sum b/lib/go.sum index 0e42dec098..6806c7b1d0 100644 --- a/lib/go.sum +++ b/lib/go.sum @@ -1,20 +1,13 @@ github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg= github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= -github.com/BurntSushi/toml v1.2.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= github.com/Masterminds/semver v1.5.0 h1:H65muMkzWKEuNDnfl9d70GUjFniHKHRbFPGBuZ3QEww= github.com/Masterminds/semver v1.5.0/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y= -github.com/Masterminds/sprig v2.15.0+incompatible h1:0gSxPGWS9PAr7U2NsQ2YQg6juRDINkUyuvbb4b2Xm8w= -github.com/Masterminds/sprig v2.15.0+incompatible/go.mod h1:y6hNFY5UBTIWBxnzTeuNhlNS5hqE0NB0E6fgfo2Br3o= -github.com/Microsoft/go-winio v0.6.1 h1:9/kr64B9VUZrLm5YYwbGtUJnMgqWVOdUAXu6Migciow= -github.com/Microsoft/go-winio v0.6.1/go.mod h1:LRdKpFKfdobln8UmuiYcKPot9D2v6svN5+sAH+4kjUM= github.com/alecthomas/assert/v2 v2.7.0 h1:QtqSACNS3tF7oasA8CU6A6sXZSBDqnm7RfpLl9bZqbE= github.com/alecthomas/assert/v2 v2.7.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k= github.com/alecthomas/chroma/v2 v2.14.0 h1:R3+wzpnUArGcQz7fCETQBzO5n9IMNi13iIs46aU4V9E= github.com/alecthomas/chroma/v2 v2.14.0/go.mod h1:QolEbTfmUHIMVpBqxeDnNBj2uoeI4EbYP4i6n68SG4I= github.com/alecthomas/repr v0.4.0 h1:GhI2A8MACjfegCPVq9f1FLvIBS+DrQ2KQBFZP1iFzXc= github.com/alecthomas/repr v0.4.0/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4= -github.com/aokoli/goutils v1.0.1 h1:7fpzNGoJ3VA8qcrm++XEE1QUe0mIwNeLa02Nwq7RDkg= -github.com/aokoli/goutils v1.0.1/go.mod h1:SijmP0QR8LtwsmDs8Yii5Z/S4trXFGFC2oO5g9DP+DQ= github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k= github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8= github.com/aymanbagabas/go-udiff v0.2.0 h1:TK0fH4MteXUDspT88n8CKzvK0X9O2xu9yQjWpi6yML8= @@ -23,16 +16,6 @@ github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuP github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4= github.com/benbjohnson/clock v1.3.5 h1:VvXlSJBzZpA/zum6Sj74hxwYI2DIxRWuNIoXAzHZz5o= github.com/benbjohnson/clock v1.3.5/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= -github.com/bufbuild/buf v1.25.0 h1:HFxKrR8wFcZwrBInN50K/oJX/WOtPVq24rHb/ArjfBA= -github.com/bufbuild/buf v1.25.0/go.mod h1:GCKZ5bAP6Ht4MF7KcfaGVgBEXGumwAz2hXjjLVxx8ZU= -github.com/bufbuild/connect-go v1.9.0 h1:JIgAeNuFpo+SUPfU19Yt5TcWlznsN5Bv10/gI/6Pjoc= -github.com/bufbuild/connect-go v1.9.0/go.mod h1:CAIePUgkDR5pAFaylSMtNK45ANQjp9JvpluG20rhpV8= -github.com/bufbuild/connect-opentelemetry-go v0.4.0 h1:6JAn10SNqlQ/URhvRNGrIlczKw1wEXknBUUtmWqOiak= -github.com/bufbuild/connect-opentelemetry-go v0.4.0/go.mod h1:nwPXYoDOoc2DGyKE/6pT1Q9MPSi2Et2e6BieMD0l6WU= -github.com/bufbuild/protocompile v0.5.1 h1:mixz5lJX4Hiz4FpqFREJHIXLfaLBntfaJv1h+/jS+Qg= -github.com/bufbuild/protocompile v0.5.1/go.mod h1:G5iLmavmF4NsYtpZFvE3B/zFch2GIY8+wjsYLR/lc40= -github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM= -github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw= github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc h1:4pZI35227imm7yK2bGPcfpFEmuY1gc2YSTShr4iJBfs= github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc/go.mod h1:X4/0JoqgTIPSFcRA/P6INZzIuyqdFY5rm8tb41s9okk= github.com/charmbracelet/glamour v0.10.0 h1:MtZvfwsYCx8jEPFJm3rIBFIMZUfUJ765oX8V6kXldcY= @@ -49,9 +32,6 @@ github.com/charmbracelet/x/exp/slice v0.0.0-20250327172914-2fdc97757edf h1:rLG0Y github.com/charmbracelet/x/exp/slice v0.0.0-20250327172914-2fdc97757edf/go.mod h1:B3UgsnsBZS/eX42BlaNiJkD1pPOUa+oF1IYC6Yd2CEU= github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ= github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg= -github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= -github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= -github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= github.com/clipperhouse/uax29/v2 v2.2.0 h1:ChwIKnQN3kcZteTXMgb1wztSgaU+ZemkgWdohwgs8tY= github.com/clipperhouse/uax29/v2 v2.2.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM= github.com/cockroachdb/errors v1.12.0 h1:d7oCs6vuIMUQRVbi6jWWWEJZahLCfJpnJSVobd1/sUo= @@ -60,99 +40,44 @@ github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b h1:r6VH0faHjZe github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= github.com/cockroachdb/redact v1.1.6 h1:zXJBwDZ84xJNlHl1rMyCojqyIxv+7YUpQiJLQ7n4314= github.com/cockroachdb/redact v1.1.6/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= -github.com/containerd/log v0.1.0 h1:TCJt7ioM2cr/tfR8GPbGf9/VRAX8D2B4PjzCpfX540I= -github.com/containerd/log v0.1.0/go.mod h1:VRRf09a7mHDIRezVKTRCrOq78v577GXq3bSa3EhrzVo= -github.com/containerd/stargz-snapshotter/estargz v0.14.3 h1:OqlDCK3ZVUO6C3B/5FSkDwbkEETK84kQgEeFwDC+62k= -github.com/containerd/stargz-snapshotter/estargz v0.14.3/go.mod h1:KY//uOCIkSuNAHhJogcZtrNHdKrA99/FCCRjE3HD36o= -github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w= -github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/creack/pty v1.1.18 h1:n56/Zwd5o6whRC5PMGretI4IdRLlmBXYNjScPaBgsbY= github.com/creack/pty v1.1.18/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk= -github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E= github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI= github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= -github.com/docker/cli v24.0.4+incompatible h1:Y3bYF9ekNTm2VFz5U/0BlMdJy73D+Y1iAAZ8l63Ydzw= -github.com/docker/cli v24.0.4+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8= -github.com/docker/distribution v2.8.2+incompatible h1:T3de5rq0dB1j30rp0sA2rER+m322EBzniBPB6ZIzuh8= -github.com/docker/distribution v2.8.2+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= -github.com/docker/docker v25.0.6+incompatible h1:5cPwbwriIcsua2REJe8HqQV+6WlWc1byg2QSXzBxBGg= -github.com/docker/docker v25.0.6+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= -github.com/docker/docker-credential-helpers v0.8.0 h1:YQFtbBQb4VrpoPxhFuzEBPQ9E16qz5SpHLS+uswaCp8= -github.com/docker/docker-credential-helpers v0.8.0/go.mod h1:UGFXcuoQ5TxPiB54nHOZ32AWRqQdECoh/Mg0AlEYb40= -github.com/docker/go-connections v0.4.0 h1:El9xVISelRB7BuFusrZozjnkIM5YnzCViNKohAFqRJQ= -github.com/docker/go-connections v0.4.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5XhDvyHbTtUxmeec= -github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4= -github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= -github.com/envoyproxy/protoc-gen-validate v0.3.0-java h1:bV5JGEB1ouEzZa0hgVDFFiClrUEuGWRaAc/3mxR2QK0= -github.com/envoyproxy/protoc-gen-validate v0.3.0-java/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= -github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs= -github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw= -github.com/felixge/fgprof v0.9.3 h1:VvyZxILNuCiUCSXtPtYmmtGvb65nqXh2QFWc0Wpf2/g= -github.com/felixge/fgprof v0.9.3/go.mod h1:RdbpDgzqYVh/T9fPELJyV7EYJuHB55UTEULNun8eiPw= -github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= -github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= +github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM= +github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU= github.com/getsentry/sentry-go v0.27.0 h1:Pv98CIbtB3LkMWmXi4Joa5OOcwbmnX88sF5qbK3r3Ps= github.com/getsentry/sentry-go v0.27.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= -github.com/go-chi/chi/v5 v5.0.10 h1:rLz5avzKpjqxrYwXNfmjkrYYXOyLJd37pz53UFHC6vk= -github.com/go-chi/chi/v5 v5.0.10/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8= github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA= github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og= -github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= -github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= -github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= -github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y= github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8= -github.com/gofrs/flock v0.8.1 h1:+gYjHKf32LDeiEEFhQaotPbLuUXjY5ZqxKgXy7n59aw= -github.com/gofrs/flock v0.8.1/go.mod h1:F1TvTiK9OcQqauNUHlbJvyl9Qa1QvF/gOUDKA14jxHU= -github.com/gofrs/uuid/v5 v5.0.0 h1:p544++a97kEL+svbcFbCQVM9KFu0Yo25UoISXGNNH9M= -github.com/gofrs/uuid/v5 v5.0.0/go.mod h1:CDOjlDMVAtN56jqyRUZh58JT31Tiw7/oQyEXZV+9bD8= github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= -github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= -github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= -github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= -github.com/google/go-containerregistry v0.15.2 h1:MMkSh+tjSdnmJZO7ljvEqV1DjfekB6VUEAZgy3a+TQE= -github.com/google/go-containerregistry v0.15.2/go.mod h1:wWK+LnOv4jXMM23IT/F1wdYftGWGr47Is8CG+pmHK1Q= -github.com/google/gofuzz v1.1.0 h1:Hsa8mG0dQ46ij8Sl2AYJDUv1oA9/d6Vk+3LG99Oe02g= -github.com/google/gofuzz v1.1.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/google/pprof v0.0.0-20211214055906-6f57359322fd/go.mod h1:KgnwoLYCZ8IQu3XUZ8Nc/bM9CCZFOyjUNOSygVozoDg= -github.com/google/pprof v0.0.0-20230705174524-200ffdc848b8 h1:n6vlPhxsA+BW/XsS5+uqi7GyzaLa5MH7qlSLBZtRdiA= -github.com/google/pprof v0.0.0-20230705174524-200ffdc848b8/go.mod h1:Jh3hGz2jkYak8qXPD19ryItVnUgpgeqzdkY/D0EaeuA= +github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= +github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/gorilla/css v1.0.1 h1:ntNaBIghp6JmvWnxbZKANoLyuXTPZ4cAMlo6RyhlbO8= github.com/gorilla/css v1.0.1/go.mod h1:BvnYkspnSzMmwRK+b8/xgNPLiIuNZr6vbZBTPQ2A3b0= github.com/grafana/regexp v0.0.0-20250905093917-f7b3be9d1853 h1:cLN4IBkmkYZNnk7EAJ0BHIethd+J6LqxFNw5mSiI2bM= github.com/grafana/regexp v0.0.0-20250905093917-f7b3be9d1853/go.mod h1:+JKpmjMGhpgPL+rXZ5nsZieVzvarn86asRlBg4uNGnk= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2 h1:8Tjv8EJ+pM1xP8mK6egEbD1OgnVTyacbefKhmbLhIhU= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2/go.mod h1:pkJQ2tZHJ0aFOVEEot6oZmaVEZcRme73eIFmhiVuRWs= github.com/hexops/autogold v1.3.1 h1:YgxF9OHWbEIUjhDbpnLhgVsjUDsiHDTyDfy2lrfdlzo= -github.com/hexops/autogold/v2 v2.2.1 h1:JPUXuZQGkcQMv7eeDXuNMovjfoRYaa0yVcm+F3voaGY= -github.com/hexops/autogold/v2 v2.2.1/go.mod h1:IJwxtUfj1BGLm0YsR/k+dIxYi6xbeLjqGke2bzcOTMI= +github.com/hexops/autogold/v2 v2.0.3 h1:zyrfTlNfyxLpX/zuk8wjTeTYP5AXaFeeRYFEZfHPwao= +github.com/hexops/autogold/v2 v2.0.3/go.mod h1:cYVc0tJn6v9Uf9xMOHvmH6scuTxsVJSxGcKR/yOVPzY= github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM= github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg= -github.com/hexops/valast v1.4.4 h1:rETyycw+/L2ZVJHHNxEBgh8KUn+87WugH9MxcEv9PGs= -github.com/hexops/valast v1.4.4/go.mod h1:Jcy1pNH7LNraVaAZDLyv21hHg2WBv9Nf9FL6fGxU7o4= -github.com/huandu/xstrings v1.0.0 h1:pO2K/gKgKaat5LdpAhxhluX2GPQMaI3W5FUz/I/UnWk= -github.com/huandu/xstrings v1.0.0/go.mod h1:4qWG/gcEcfX4z/mBDHJ++3ReCw9ibxbsNJbcucJdbSo= -github.com/ianlancetaylor/demangle v0.0.0-20210905161508-09a460cdf81d/go.mod h1:aYm2/VgdVmcIU8iMfdMvDMsRAQjcfZSKFby6HOFvi/w= -github.com/imdario/mergo v0.3.4 h1:mKkfHkZWD8dC7WxKx3N9WCF0Y+dLau45704YQmY6H94= -github.com/imdario/mergo v0.3.4/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= -github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= -github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= +github.com/hexops/valast v1.4.3 h1:oBoGERMJh6UZdRc6cduE1CTPK+VAdXA59Y1HFgu3sm0= +github.com/hexops/valast v1.4.3/go.mod h1:Iqx2kLj3Jn47wuXpj3wX40xn6F93QNFBHuiKBerkTGA= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= @@ -161,10 +86,6 @@ github.com/jackc/pgx/v5 v5.9.1 h1:uwrxJXBnx76nyISkhr33kQLlUqjv7et7b9FjCen/tdc= github.com/jackc/pgx/v5 v5.9.1/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= -github.com/jdxcode/netrc v0.0.0-20221124155335-4616370d1a84 h1:2uT3aivO7NVpUPGcQX7RbHijHMyWix/yCnIrCWc+5co= -github.com/jdxcode/netrc v0.0.0-20221124155335-4616370d1a84/go.mod h1:Zi/ZFkEqFHTm7qkjyNJjaWH4LQA9LQhGJyF0lTYGpxw= -github.com/jhump/protoreflect v1.15.1 h1:HUMERORf3I3ZdX05WaQ6MIpd/NJ434hTp5YiKgfCL6c= -github.com/jhump/protoreflect v1.15.1/go.mod h1:jD/2GMKKE6OqX8qTjhADU1e6DShO+gavG9e0Q693nKo= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= @@ -173,15 +94,12 @@ github.com/klauspost/pgzip v1.2.6 h1:8RXeL5crjEUFnR2/Sn6GJNWtSQ3Dk8pq4CL3jvdDyjU github.com/klauspost/pgzip v1.2.6/go.mod h1:Ch1tH69qFZu15pkjo5kYi6mth2Zzwzt50oCQKQE9RUs= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= -github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= -github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= -github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= -github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE= +github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk= @@ -189,56 +107,32 @@ github.com/mattn/go-runewidth v0.0.19 h1:v++JhqYnZuu5jSKrk9RbgF5v4CGUjqRfBm05byF github.com/mattn/go-runewidth v0.0.19/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs= github.com/microcosm-cc/bluemonday v1.0.27 h1:MpEUotklkwCSLeH+Qdx1VJgNqLlpY2KXwXFM08ygZfk= github.com/microcosm-cc/bluemonday v1.0.27/go.mod h1:jFi9vgW+H7c3V0lb6nR74Ib/DIB5OBs92Dimizgw2cA= -github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= -github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ= github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc= -github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A= -github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc= github.com/muesli/reflow v0.3.0 h1:IFsN6K9NfGtjeggFP+68I4chLZV2yIKsXJFNZ+eWh6s= github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKtnHY/8= github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc= github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk= -github.com/mwitkow/go-proto-validators v0.0.0-20180403085117-0950a7990007 h1:28i1IjGcx8AofiB4N3q5Yls55VEaitzuEPkFJEVgGkA= -github.com/mwitkow/go-proto-validators v0.0.0-20180403085117-0950a7990007/go.mod h1:m2XC9Qq0AlmmVksL6FktJCdTYyLk7V3fKyp0sl1yWQo= -github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/nightlyone/lockfile v1.0.0 h1:RHep2cFKK4PonZJDdEl4GmkabuhbsRMgk/k3uAmxBiA= github.com/nightlyone/lockfile v1.0.0/go.mod h1:rywoIealpdNse2r832aiD9jRk8ErCatROs6LzC841CI= -github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= -github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= -github.com/opencontainers/image-spec v1.1.0-rc4 h1:oOxKUJWnFC4YGHCCMNql1x4YaDfYBTS5Y4x/Cgeo1E0= -github.com/opencontainers/image-spec v1.1.0-rc4/go.mod h1:X4pATf0uXsnn3g5aiGIsVnJBR4mxhKzfwmvK/B2NTm8= github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4= github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8= -github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 h1:KoWmjvw+nsYOo29YJK9vDA65RGE3NrOnUtO7a+RF9HU= -github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8/go.mod h1:HKlIX3XHQyzLZPlr7++PzdhaXEj94dEiJgZDTsxEqUI= github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pkg/profile v1.7.0 h1:hnbDkaNWPCLMO9wGLdBFTIZvzDrDfBM2072E1S9gJkA= -github.com/pkg/profile v1.7.0/go.mod h1:8Uer0jas47ZQMJ7VD+OHknK4YDY07LPUC6dEvqDjvNo= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/pseudomuto/protoc-gen-doc v1.5.1 h1:Ah259kcrio7Ix1Rhb6u8FCaOkzf9qRBqXnvAufg061w= -github.com/pseudomuto/protoc-gen-doc v1.5.1/go.mod h1:XpMKYg6zkcpgfpCfQ8GcWBDRtRxOmMR5w7pz4Xo+dYM= -github.com/pseudomuto/protokit v0.2.0 h1:hlnBDcy3YEDXH7kc9gV+NLaN0cDzhDvD1s7Y6FZ8RpM= -github.com/pseudomuto/protokit v0.2.0/go.mod h1:2PdH30hxVHsup8KpBTOXTBeMVhJZVio3Q8ViKSAXT0Q= github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= -github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= -github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= -github.com/rs/cors v1.9.0 h1:l9HGsTsHJcvW14Nk7J9KFz8bzeAWXn3CG6bgt7LsrAE= -github.com/rs/cors v1.9.0/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU= -github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= -github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= +github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= +github.com/scip-code/scip/bindings/go/scip v0.7.0 h1:on80ynl7eSovvMUy3uxWkJm+kepsVjIwI2byIeMZego= +github.com/scip-code/scip/bindings/go/scip v0.7.0/go.mod h1:XC4dP3um0lKaSDRFIMwYlkBjFxKy1Rw7xFt6KDtRjAk= github.com/shurcooL/go v0.0.0-20180423040247-9e1955d9fb6e/go.mod h1:TDJrrUr11Vxrven61rcy3hJMUqaf/CLWYhHNPmT14Lk= github.com/shurcooL/go-goon v0.0.0-20170922171312-37c2f522c041/go.mod h1:N5mDOmsrJOB+vfqUK+7DmDyjhSLIIBnXo9lvZJj3MWQ= -github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= -github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= -github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/sourcegraph/beaut v0.0.0-20240611013027-627e4c25335a h1:j/CQ27s679M9wRGBRJYyXGrfkYuQA6VMnD7R08mHD9c= github.com/sourcegraph/beaut v0.0.0-20240611013027-627e4c25335a/go.mod h1:JG1sdvGTKWwe/oH3/3UKQ26vfcHIN//7fwEJhoqaBcM= github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo= @@ -247,27 +141,11 @@ github.com/sourcegraph/go-diff v0.7.0 h1:9uLlrd5T46OXs5qpp8L/MTltk0zikUGi0sNNyCp github.com/sourcegraph/go-diff v0.7.0/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/log v0.0.0-20250923023806-517b6960b55b h1:2FQ72y5zECMu9e5z5jMnllb5n1jVK7qsvgjkVtdFV+g= github.com/sourcegraph/log v0.0.0-20250923023806-517b6960b55b/go.mod h1:IDp09QkoqS8Z3CyN2RW6vXjgABkNpDbyjLIHNQwQ8P8= -github.com/sourcegraph/scip v0.6.1 h1:lcBrTwGjsqpMLQN4pVfJYSB+8oVoc8Lnqb4FAfU8EBM= -github.com/sourcegraph/scip v0.6.1/go.mod h1:c6d9mk1cGT6OXdHutxDakKVEPN1D+iFoYWCsrDxEhus= -github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I= -github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0= -github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= -github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= -github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= -github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= -github.com/tetratelabs/wazero v1.3.0 h1:nqw7zCldxE06B8zSZAY0ACrR9OH5QCcPwYmYlwtcwtE= -github.com/tetratelabs/wazero v1.3.0/go.mod h1:wYx2gNRg8/WihJfSDxA1TIL8H+GkfLYm+bIfbblu9VQ= -github.com/urfave/cli v1.22.12/go.mod h1:sSBEIC79qR6OvcmsD4U3KABeOTxDqQtdDnaFuUN30b8= -github.com/vbatts/tar-split v0.11.3 h1:hLFqsOLQ1SsppQNTMpkpPXClLDfC2A3Zgy9OUU+RVck= -github.com/vbatts/tar-split v0.11.3/go.mod h1:9QlHN18E+fEH7RdG+QAJJcuya3rqT7eXSTY7wGrAokY= github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f h1:J9EGpcZtP0E/raorCMxlFGSTBrsSlaDGf3jU/qvAE2c= github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0= @@ -285,26 +163,8 @@ github.com/yuin/goldmark v1.7.8 h1:iERMLn0/QJeHFhxSt3p6PeN9mGnvIKSpG9YYorDMnic= github.com/yuin/goldmark v1.7.8/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E= github.com/yuin/goldmark-emoji v1.0.5 h1:EMVWyCGPlXJfUXBXpuMu+ii3TIaxbVBnEX9uaDC4cIk= github.com/yuin/goldmark-emoji v1.0.5/go.mod h1:tTkZEbwu5wkPmgTcitqddVxY9osFZiavD+r4AzQrh1U= -go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA= -go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0 h1:RbKq8BG0FI8OiXhBfcRtqqHcZcka+gU3cskNuf05R18= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0/go.mod h1:h06DGIukJOevXaj/xrNjhi/2098RZzcLTbc0jDAUbsg= go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8= go.opentelemetry.io/otel v1.38.0/go.mod h1:zcmtmQ1+YmQM9wrNsTGV/q/uyusom3P8RxwExxkZhjM= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.38.0 h1:GqRJVj7UmLjCVyVJ3ZFLdPRmhDUp2zFmQe3RHIOsw24= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.38.0/go.mod h1:ri3aaHSmCTVYu2AWv44YMauwAQc0aqI9gHKIcSbI1pU= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.38.0 h1:aTL7F04bJHUlztTsNGJ2l+6he8c+y/b//eR0jjjemT4= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.38.0/go.mod h1:kldtb7jDTeol0l3ewcmd8SDvx3EmIE7lyvqbasU3QC4= -go.opentelemetry.io/otel/metric v1.38.0 h1:Kl6lzIYGAh5M159u9NgiRkmoMKjvbsKtYRwgfrA6WpA= -go.opentelemetry.io/otel/metric v1.38.0/go.mod h1:kB5n/QoRM8YwmUahxvI3bO34eVtQf2i4utNVLr9gEmI= -go.opentelemetry.io/otel/sdk v1.38.0 h1:l48sr5YbNf2hpCUj/FoGhW9yDkl+Ma+LrVl8qaM5b+E= -go.opentelemetry.io/otel/sdk v1.38.0/go.mod h1:ghmNdGlVemJI3+ZB5iDEuk4bWA3GkTpW+DOoZMYBVVg= -go.opentelemetry.io/otel/sdk/metric v1.38.0 h1:aSH66iL0aZqo//xXzQLYozmWrXxyFkBJ6qT5wthqPoM= -go.opentelemetry.io/otel/sdk/metric v1.38.0/go.mod h1:dg9PBnW9XdQ1Hd6ZnRz689CbtrUp0wMMs9iPcgT9EZA= -go.opentelemetry.io/otel/trace v1.38.0 h1:Fxk5bKrDZJUH+AMyyIXGcFAPah0oRcT+LuNtJrmcNLE= -go.opentelemetry.io/otel/trace v1.38.0/go.mod h1:j1P9ivuFsTceSWe1oY+EeW3sc+Pp42sO++GHkg4wwhs= -go.opentelemetry.io/proto/otlp v1.7.1 h1:gTOMpGDb0WTBOP8JaO72iL3auEZhVmAQg4ipjOVAtj4= -go.opentelemetry.io/proto/otlp v1.7.1/go.mod h1:b2rVh6rfI/s2pHWNlB7ILJcRALpcNDzKhACevjI+ZnE= go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= @@ -316,10 +176,8 @@ go.uber.org/zap v1.24.0/go.mod h1:2kMP+WWQ8aoFoedH3T2sq6iJ2yDWpHbP0f6MQbS9Gkg= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.42.0 h1:chiH31gIWm57EkTXpwnqf8qeuMUi0yekh6mT2AvFlqI= -golang.org/x/crypto v0.42.0/go.mod h1:4+rDnOTJhQCx2q7/j6rAN5XDw8kPjeaXEUR2eL94ix8= -golang.org/x/exp v0.0.0-20231108232855-2478ac86f678 h1:mchzmB1XO2pMaKFRqk/+MV3mgGG96aqaPXaMifQU47w= -golang.org/x/exp v0.0.0-20231108232855-2478ac86f678/go.mod h1:zk2irFbV9DP96SEBUUAy67IdHUaZuSnrz1n472HUCLE= +golang.org/x/exp v0.0.0-20230713183714-613f0c0eb8a1 h1:MGwJjxBy0HJshjDNfLsYO8xppfqWlA5ZT9OhtUUhTNw= +golang.org/x/exp v0.0.0-20230713183714-613f0c0eb8a1/go.mod h1:FXUEEKJgO7OQYeo8N01OfiKP8RXMtf6e8aTskBGqWdc= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.28.0 h1:gQBtGhjxykdjY9YhZpSlZIsbnaE2+PgjfLWUQTnoZ1U= @@ -338,25 +196,16 @@ golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210616045830-e2b7044e8c71/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20211007075335-d3039528d8ac/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220906165534-d0df966e6959/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc= -golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= -golang.org/x/telemetry v0.0.0-20250908211612-aef8a434d053 h1:dHQOQddU4YHS5gY33/6klKjq7Gp3WwMyOXGNp5nzRj8= -golang.org/x/telemetry v0.0.0-20250908211612-aef8a434d053/go.mod h1:+nZKN+XVh4LCiA9DV3ywrzN4gumyCnKjau3NGb9SGoE= +golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k= +golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= golang.org/x/term v0.37.0 h1:8EGAD0qCmHYZg6J17DvsMy9/wJ7/D/4pV/wfnld5lTU= golang.org/x/term v0.37.0/go.mod h1:5pB4lxRNYYVZuTLmy8oR2BH8dflOR+IbTYFD8fi3254= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk= golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4= -golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4= -golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= @@ -367,16 +216,9 @@ golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8T golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 h1:KpwkzHKEF7B9Zxg18WzOa7djJ+Ha5DzthMyZYQfEn2A= -google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1/go.mod h1:nKE/iIaLqn2bQwXBg8f1g2Ylh6r5MN5CmZvuzZCgsCU= -google.golang.org/grpc v1.75.0 h1:+TW+dqTd2Biwe6KKfhE5JpiYIBWq865PhKGSXiivqt4= -google.golang.org/grpc v1.75.0/go.mod h1:JtPAzKiq4v1xcAB2hydNlWI2RnF85XXcV0mhKXr2ecQ= -google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= -google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= @@ -384,9 +226,7 @@ gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gotest.tools/v3 v3.0.3 h1:4AuOwCGf4lLR9u3YOe2awrHygurzhO/HeQ6laiA6Sx0= -gotest.tools/v3 v3.0.3/go.mod h1:Z7Lb0S5l+klDB31fvDQX8ss/FlKDxtlFlw3Oa8Ymbl8= -mvdan.cc/gofumpt v0.5.0 h1:0EQ+Z56k8tXjj/6TQD25BFNKQXpCvT0rnansIc7Ug5E= -mvdan.cc/gofumpt v0.5.0/go.mod h1:HBeVDtMKRZpXyxFciAirzdKklDlGu8aAy1wEbH5Y9js= +mvdan.cc/gofumpt v0.4.0 h1:JVf4NN1mIpHogBj7ABpgOyZc65/UUOkKQFkoURsz4MM= +mvdan.cc/gofumpt v0.4.0/go.mod h1:PljLOHDeZqgS8opHRKLzp2It2VBuSdteAgqUfzMTxlQ= pgregory.net/rapid v1.1.0 h1:CMa0sjHSru3puNx+J0MIAuiiEV4N0qj8/cMWGBBCsjw= pgregory.net/rapid v1.1.0/go.mod h1:PY5XlDGj0+V1FCq0o192FdRhpKHGTRIWBgqjDBTrq04= From 78c41d45c739afa5b990517c07dedd1283b48b26 Mon Sep 17 00:00:00 2001 From: Andre Eleuterio <11207474+andreeleuterio@users.noreply.github.com> Date: Fri, 3 Apr 2026 15:11:52 -0300 Subject: [PATCH 558/647] chore: bump go and deps (#1285) --- go.mod | 41 +++++++++++++-------------- go.sum | 82 ++++++++++++++++++++++++++---------------------------- lib/go.mod | 2 +- mise.toml | 2 +- 4 files changed, 62 insertions(+), 65 deletions(-) diff --git a/go.mod b/go.mod index 53eb6f6c97..274db0a7c8 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/sourcegraph/src-cli -go 1.25.1 +go 1.25.8 require ( cloud.google.com/go/storage v1.50.0 @@ -31,7 +31,7 @@ require ( github.com/stretchr/testify v1.11.1 github.com/tliron/glsp v0.2.2 github.com/zalando/go-keyring v0.2.6 - golang.org/x/sync v0.18.0 + golang.org/x/sync v0.19.0 google.golang.org/api v0.256.0 google.golang.org/protobuf v1.36.10 gopkg.in/yaml.v3 v3.0.1 @@ -43,11 +43,11 @@ require ( require ( al.essio.dev/pkg/shellescape v1.5.1 // indirect - cel.dev/expr v0.24.0 // indirect + cel.dev/expr v0.25.1 // indirect cloud.google.com/go/auth v0.17.0 // indirect cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect cloud.google.com/go/monitoring v1.24.2 // indirect - github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.29.0 // indirect + github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.30.0 // indirect github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.50.0 // indirect github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.50.0 // indirect github.com/alecthomas/chroma/v2 v2.14.0 // indirect @@ -59,12 +59,12 @@ require ( github.com/charmbracelet/x/exp/slice v0.0.0-20250327172914-2fdc97757edf // indirect github.com/charmbracelet/x/term v0.2.1 // indirect github.com/clipperhouse/uax29/v2 v2.2.0 // indirect - github.com/cncf/xds/go v0.0.0-20250501225837-2ac532fd4443 // indirect + github.com/cncf/xds/go v0.0.0-20251210132809-ee656c7534f5 // indirect github.com/danieljoos/wincred v1.2.2 // indirect - github.com/envoyproxy/go-control-plane/envoy v1.32.4 // indirect + github.com/envoyproxy/go-control-plane/envoy v1.36.0 // indirect github.com/felixge/httpsnoop v1.0.4 // indirect github.com/fxamacker/cbor/v2 v2.7.0 // indirect - github.com/go-jose/go-jose/v4 v4.1.2 // indirect + github.com/go-jose/go-jose/v4 v4.1.3 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/godbus/dbus/v5 v5.1.0 // indirect github.com/google/gnostic-models v0.6.9 // indirect @@ -80,15 +80,14 @@ require ( github.com/segmentio/ksuid v1.0.4 // indirect github.com/sourcegraph/beaut v0.0.0-20240611013027-627e4c25335a // indirect github.com/sourcegraph/jsonrpc2 v0.2.0 // indirect - github.com/spiffe/go-spiffe/v2 v2.5.0 // indirect + github.com/spiffe/go-spiffe/v2 v2.6.0 // indirect github.com/tliron/commonlog v0.2.19 // indirect github.com/tliron/kutil v0.3.27 // indirect github.com/x448/float16 v0.8.4 // indirect github.com/xlab/treeprint v1.2.0 // indirect github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect - github.com/zeebo/errs v1.4.0 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect - go.opentelemetry.io/contrib/detectors/gcp v1.36.0 // indirect + go.opentelemetry.io/contrib/detectors/gcp v1.39.0 // indirect go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0 // indirect go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0 // indirect go.opentelemetry.io/otel v1.40.0 // indirect @@ -96,9 +95,9 @@ require ( go.opentelemetry.io/otel/sdk v1.40.0 // indirect go.opentelemetry.io/otel/sdk/metric v1.40.0 // indirect go.opentelemetry.io/otel/trace v1.40.0 // indirect - golang.org/x/net v0.47.0 // indirect - google.golang.org/genproto/googleapis/api v0.0.0-20250825161204-c5933d9347a5 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20251103181224-f26f9409b101 // indirect + golang.org/x/net v0.48.0 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 // indirect gopkg.in/evanphx/json-patch.v4 v4.12.0 // indirect sigs.k8s.io/randfill v1.0.0 // indirect ) @@ -129,7 +128,7 @@ require ( github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/dlclark/regexp2 v1.11.0 // indirect github.com/emicklei/go-restful/v3 v3.11.0 // indirect - github.com/envoyproxy/protoc-gen-validate v1.2.1 // indirect + github.com/envoyproxy/protoc-gen-validate v1.3.0 // indirect github.com/fatih/color v1.18.0 // indirect github.com/getsentry/sentry-go v0.27.0 // indirect github.com/ghodss/yaml v1.0.0 // indirect @@ -179,16 +178,16 @@ require ( go.uber.org/atomic v1.11.0 // indirect go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.24.0 // indirect - golang.org/x/crypto v0.45.0 // indirect - golang.org/x/mod v0.29.0 // indirect - golang.org/x/oauth2 v0.33.0 // indirect + golang.org/x/crypto v0.46.0 // indirect + golang.org/x/mod v0.30.0 // indirect + golang.org/x/oauth2 v0.34.0 // indirect golang.org/x/sys v0.41.0 // indirect - golang.org/x/term v0.37.0 // indirect - golang.org/x/text v0.31.0 // indirect + golang.org/x/term v0.38.0 // indirect + golang.org/x/text v0.32.0 // indirect golang.org/x/time v0.14.0 // indirect - golang.org/x/tools v0.38.0 // indirect + golang.org/x/tools v0.39.0 // indirect google.golang.org/genproto v0.0.0-20250603155806-513f23925822 // indirect - google.golang.org/grpc v1.76.0 // indirect + google.golang.org/grpc v1.79.3 // indirect gopkg.in/inf.v0 v0.9.1 // indirect; direct gopkg.in/yaml.v2 v2.4.0 // indirect k8s.io/klog/v2 v2.130.1 // indirect diff --git a/go.sum b/go.sum index 5d5a1be53e..e85cdd9f5a 100644 --- a/go.sum +++ b/go.sum @@ -1,7 +1,7 @@ al.essio.dev/pkg/shellescape v1.5.1 h1:86HrALUujYS/h+GtqoB26SBEdkWfmMI6FubjXlsXyho= al.essio.dev/pkg/shellescape v1.5.1/go.mod h1:6sIqp7X2P6mThCQ7twERpZTuigpr6KbZWtls1U8I890= -cel.dev/expr v0.24.0 h1:56OvJKSH3hDGL0ml5uSxZmz3/3Pq4tJ+fb1unVLAFcY= -cel.dev/expr v0.24.0/go.mod h1:hLPLo1W4QUmuYdA72RBX06QTs6MXw941piREPl3Yfiw= +cel.dev/expr v0.25.1 h1:1KrZg61W6TWSxuNZ37Xy49ps13NUovb66QLprthtwi4= +cel.dev/expr v0.25.1/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4= cloud.google.com/go v0.120.0 h1:wc6bgG9DHyKqF5/vQvX1CiZrtHnxJjBlKUyF9nP6meA= cloud.google.com/go v0.120.0/go.mod h1:/beW32s8/pGRuj4IILWQNd4uuebeT4dkOhKmkfit64Q= cloud.google.com/go/auth v0.17.0 h1:74yCm7hCj2rUyyAocqnFzsAYXgJhrG26XCFimrc/Kz4= @@ -24,8 +24,8 @@ cloud.google.com/go/trace v1.11.6 h1:2O2zjPzqPYAHrn3OKl029qlqG6W8ZdYaOWRyr8NgMT4 cloud.google.com/go/trace v1.11.6/go.mod h1:GA855OeDEBiBMzcckLPE2kDunIpC72N+Pq8WFieFjnI= github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg= github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.29.0 h1:UQUsRi8WTzhZntp5313l+CHIAT95ojUI2lpP/ExlZa4= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.29.0/go.mod h1:Cz6ft6Dkn3Et6l2v2a9/RpN7epQ1GtDlO6lj8bEcOvw= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.30.0 h1:sBEjpZlNHzK1voKq9695PJSX2o5NEXl7/OL3coiIY0c= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.30.0/go.mod h1:P4WPRUkOhJC13W//jWpyfJNDAIpvRbAUIYLX/4jtlE0= github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.50.0 h1:5IT7xOdq17MtcdtL/vtl6mGfzhaq4m4vpollPRmlsBQ= github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.50.0/go.mod h1:ZV4VOm0/eHR06JLrXWe09068dHpr3TRpY9Uo7T+anuA= github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0.50.0 h1:nNMpRpnkWDAaqcpxMJvxa/Ud98gjbYwayJY4/9bdjiU= @@ -101,8 +101,8 @@ github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQ github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg= github.com/clipperhouse/uax29/v2 v2.2.0 h1:ChwIKnQN3kcZteTXMgb1wztSgaU+ZemkgWdohwgs8tY= github.com/clipperhouse/uax29/v2 v2.2.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM= -github.com/cncf/xds/go v0.0.0-20250501225837-2ac532fd4443 h1:aQ3y1lwWyqYPiWZThqv1aFbZMiM9vblcSArJRf2Irls= -github.com/cncf/xds/go v0.0.0-20250501225837-2ac532fd4443/go.mod h1:W+zGtBO5Y1IgJhy4+A9GOqVhqLpfZi+vwmdNXUehLA8= +github.com/cncf/xds/go v0.0.0-20251210132809-ee656c7534f5 h1:6xNmx7iTtyBRev0+D/Tv1FZd4SCg8axKApyNyRsAt/w= +github.com/cncf/xds/go v0.0.0-20251210132809-ee656c7534f5/go.mod h1:KdCmV+x/BuvyMxRnYBlmVaq4OLiKW6iRQfvC62cvdkI= github.com/cockroachdb/errors v1.12.0 h1:d7oCs6vuIMUQRVbi6jWWWEJZahLCfJpnJSVobd1/sUo= github.com/cockroachdb/errors v1.12.0/go.mod h1:SvzfYNNBshAVbZ8wzNc/UPK3w1vf0dKDUP41ucAIf7g= github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b h1:r6VH0faHjZeQy818SGhaone5OnYfxFR/+AzdY3sf5aE= @@ -130,14 +130,14 @@ github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkp github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/emicklei/go-restful/v3 v3.11.0 h1:rAQeMHw1c7zTmncogyy8VvRZwtkmkZ4FxERmMY4rD+g= github.com/emicklei/go-restful/v3 v3.11.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= -github.com/envoyproxy/go-control-plane v0.13.4 h1:zEqyPVyku6IvWCFwux4x9RxkLOMUL+1vC9xUFv5l2/M= -github.com/envoyproxy/go-control-plane v0.13.4/go.mod h1:kDfuBlDVsSj2MjrLEtRWtHlsWIFcGyB2RMO44Dc5GZA= -github.com/envoyproxy/go-control-plane/envoy v1.32.4 h1:jb83lalDRZSpPWW2Z7Mck/8kXZ5CQAFYVjQcdVIr83A= -github.com/envoyproxy/go-control-plane/envoy v1.32.4/go.mod h1:Gzjc5k8JcJswLjAx1Zm+wSYE20UrLtt7JZMWiWQXQEw= +github.com/envoyproxy/go-control-plane v0.14.0 h1:hbG2kr4RuFj222B6+7T83thSPqLjwBIfQawTkC++2HA= +github.com/envoyproxy/go-control-plane v0.14.0/go.mod h1:NcS5X47pLl/hfqxU70yPwL9ZMkUlwlKxtAohpi2wBEU= +github.com/envoyproxy/go-control-plane/envoy v1.36.0 h1:yg/JjO5E7ubRyKX3m07GF3reDNEnfOboJ0QySbH736g= +github.com/envoyproxy/go-control-plane/envoy v1.36.0/go.mod h1:ty89S1YCCVruQAm9OtKeEkQLTb+Lkz0k8v9W0Oxsv98= github.com/envoyproxy/go-control-plane/ratelimit v0.1.0 h1:/G9QYbddjL25KvtKTv3an9lx6VBE2cnb8wp1vEGNYGI= github.com/envoyproxy/go-control-plane/ratelimit v0.1.0/go.mod h1:Wk+tMFAFbCXaJPzVVHnPgRKdUdwW/KdbRt94AzgRee4= -github.com/envoyproxy/protoc-gen-validate v1.2.1 h1:DEo3O99U8j4hBFwbJfrz9VtgcDfUKS7KJ7spH3d86P8= -github.com/envoyproxy/protoc-gen-validate v1.2.1/go.mod h1:d/C80l/jxXLdfEIhX1W2TmLfsJ31lvEjwamM4DxlWXU= +github.com/envoyproxy/protoc-gen-validate v1.3.0 h1:TvGH1wof4H33rezVKWSpqKz5NXWg5VPuZ0uONDT6eb4= +github.com/envoyproxy/protoc-gen-validate v1.3.0/go.mod h1:HvYl7zwPa5mffgyeTUHA9zHIH36nmrm7oCbo4YKoSWA= github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM= github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU= @@ -152,8 +152,8 @@ github.com/getsentry/sentry-go v0.27.0 h1:Pv98CIbtB3LkMWmXi4Joa5OOcwbmnX88sF5qbK github.com/getsentry/sentry-go v0.27.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA= github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og= -github.com/go-jose/go-jose/v4 v4.1.2 h1:TK/7NqRQZfgAh+Td8AlsrvtPoUyiHh0LqVvokh+1vHI= -github.com/go-jose/go-jose/v4 v4.1.2/go.mod h1:22cg9HWM1pOlnRiY+9cQYJ9XHmya1bYW8OeDM6Ku6Oo= +github.com/go-jose/go-jose/v4 v4.1.3 h1:CVLmWDhDVRa6Mi/IgCgaopNosCaHz7zrMeF9MlZRkrs= +github.com/go-jose/go-jose/v4 v4.1.3/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= @@ -347,8 +347,8 @@ github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6 github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o= github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= -github.com/spiffe/go-spiffe/v2 v2.5.0 h1:N2I01KCUkv1FAjZXJMwh95KK1ZIQLYbPfhaxw8WS0hE= -github.com/spiffe/go-spiffe/v2 v2.5.0/go.mod h1:P+NxobPc6wXhVtINNtFjNWGBTreew1GBUCwT2wPmb7g= +github.com/spiffe/go-spiffe/v2 v2.6.0 h1:l+DolpxNWYgruGQVV0xsfeya3CsC7m8iBzDnMpsbLuo= +github.com/spiffe/go-spiffe/v2 v2.6.0/go.mod h1:gm2SeUoMZEtpnzPNs2Csc0D/gX33k1xIx7lEzqblHEs= github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf h1:pvbZ0lM0XWPBqUKqFU8cmavspvIl9nulOYwdy6IFRRo= github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf/go.mod h1:RJID2RhlZKId02nZ62WenDCkgHFerpIOmW0iT7GKmXM= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= @@ -393,12 +393,10 @@ github.com/yuin/goldmark-emoji v1.0.5 h1:EMVWyCGPlXJfUXBXpuMu+ii3TIaxbVBnEX9uaDC github.com/yuin/goldmark-emoji v1.0.5/go.mod h1:tTkZEbwu5wkPmgTcitqddVxY9osFZiavD+r4AzQrh1U= github.com/zalando/go-keyring v0.2.6 h1:r7Yc3+H+Ux0+M72zacZoItR3UDxeWfKTcabvkI8ua9s= github.com/zalando/go-keyring v0.2.6/go.mod h1:2TCrxYrbUNYfNS/Kgy/LSrkSQzZ5UPVH85RwfczwvcI= -github.com/zeebo/errs v1.4.0 h1:XNdoD/RRMKP7HD0UhJnIzUy74ISdGGxURlYG8HSWSfM= -github.com/zeebo/errs v1.4.0/go.mod h1:sgbWHsvVuTPHcqJJGQ1WhI5KbWlHYz+2+2C/LSEtCw4= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= -go.opentelemetry.io/contrib/detectors/gcp v1.36.0 h1:F7q2tNlCaHY9nMKHR6XH9/qkp8FktLnIcy6jJNyOCQw= -go.opentelemetry.io/contrib/detectors/gcp v1.36.0/go.mod h1:IbBN8uAIIx734PTonTPxAxnjc2pQTxWNkwfstZ+6H2k= +go.opentelemetry.io/contrib/detectors/gcp v1.39.0 h1:kWRNZMsfBHZ+uHjiH4y7Etn2FK26LAGkNFw7RHv1DhE= +go.opentelemetry.io/contrib/detectors/gcp v1.39.0/go.mod h1:t/OGqzHBa5v6RHZwrDBJ2OirWc+4q/w2fTbLZwAKjTk= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0 h1:q4XOmH/0opmeuJtPsbFNivyl7bCt7yRBbeEm2sC/XtQ= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0/go.mod h1:snMWehoOh2wsEwnvvwtDyFCxVeDAODenXHtn5vzrKjo= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0 h1:RbKq8BG0FI8OiXhBfcRtqqHcZcka+gU3cskNuf05R18= @@ -427,16 +425,16 @@ golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACk golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q= -golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4= +golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU= +golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0= golang.org/x/exp v0.0.0-20230713183714-613f0c0eb8a1 h1:MGwJjxBy0HJshjDNfLsYO8xppfqWlA5ZT9OhtUUhTNw= golang.org/x/exp v0.0.0-20230713183714-613f0c0eb8a1/go.mod h1:FXUEEKJgO7OQYeo8N01OfiKP8RXMtf6e8aTskBGqWdc= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.7.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/mod v0.29.0 h1:HV8lRxZC4l2cr3Zq1LvtOsi/ThTgWnUk/y64QSs8GwA= -golang.org/x/mod v0.29.0/go.mod h1:NyhrlYXJ2H4eJiRy/WDBO6HMqZQ6q9nk4JzS3NuCK+w= +golang.org/x/mod v0.30.0 h1:fDEXFVZ/fmCKProc/yAXXUijritrDzahmwwefnjoPFk= +golang.org/x/mod v0.30.0/go.mod h1:lAsf5O2EvJeSFMiBxXDki7sCgAxEUcZHXoXMKT4GJKc= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= @@ -444,18 +442,18 @@ golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwY golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.3.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE= -golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY= -golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU= -golang.org/x/oauth2 v0.33.0 h1:4Q+qn+E5z8gPRJfmRy7C2gGG3T4jIprK6aSYgTXGRpo= -golang.org/x/oauth2 v0.33.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= +golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU= +golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY= +golang.org/x/oauth2 v0.34.0 h1:hqK/t4AKgbqWkdkcAeI8XLmbK+4m4G5YeQRrmiotGlw= +golang.org/x/oauth2 v0.34.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220819030929-7fc1605a5dde/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.18.0 h1:kr88TuHDroi+UVf+0hZnirlk8o8T+4MrK6mr60WkH/I= -golang.org/x/sync v0.18.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= +golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4= +golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -477,14 +475,14 @@ golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.3.0/go.mod h1:q750SLmJuPmVoN1blW3UFBPREJfb1KmY3vwxfr+nFDA= -golang.org/x/term v0.37.0 h1:8EGAD0qCmHYZg6J17DvsMy9/wJ7/D/4pV/wfnld5lTU= -golang.org/x/term v0.37.0/go.mod h1:5pB4lxRNYYVZuTLmy8oR2BH8dflOR+IbTYFD8fi3254= +golang.org/x/term v0.38.0 h1:PQ5pkm/rLO6HnxFR7N2lJHOZX6Kez5Y1gDSJla6jo7Q= +golang.org/x/term v0.38.0/go.mod h1:bSEAKrOT1W+VSu9TSCMtoGEOUcKxOKgl3LE5QEF/xVg= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM= -golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM= +golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU= +golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY= golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI= golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -494,8 +492,8 @@ golang.org/x/tools v0.0.0-20200624163319-25775e59acb7/go.mod h1:EkVYQZoAsY45+roY golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.4.0/go.mod h1:UE5sM2OK9E/d67R0ANs2xJizIymRP5gJU295PvKXxjQ= -golang.org/x/tools v0.38.0 h1:Hx2Xv8hISq8Lm16jvBZ2VQf+RLmbd7wVUsALibYI/IQ= -golang.org/x/tools v0.38.0/go.mod h1:yEsQ/d/YK8cjh0L6rZlY8tgtlKiBNTL14pGDJPJpYQs= +golang.org/x/tools v0.39.0 h1:ik4ho21kwuQln40uelmciQPp9SipgNDdrafrYA4TmQQ= +golang.org/x/tools v0.39.0/go.mod h1:JnefbkDPyD8UU2kI5fuf8ZX4/yUeh9W877ZeBONxUqQ= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -506,12 +504,12 @@ google.golang.org/api v0.256.0 h1:u6Khm8+F9sxbCTYNoBHg6/Hwv0N/i+V94MvkOSor6oI= google.golang.org/api v0.256.0/go.mod h1:KIgPhksXADEKJlnEoRa9qAII4rXcy40vfI8HRqcU964= google.golang.org/genproto v0.0.0-20250603155806-513f23925822 h1:rHWScKit0gvAPuOnu87KpaYtjK5zBMLcULh7gxkCXu4= google.golang.org/genproto v0.0.0-20250603155806-513f23925822/go.mod h1:HubltRL7rMh0LfnQPkMH4NPDFEWp0jw3vixw7jEM53s= -google.golang.org/genproto/googleapis/api v0.0.0-20250825161204-c5933d9347a5 h1:BIRfGDEjiHRrk0QKZe3Xv2ieMhtgRGeLcZQ0mIVn4EY= -google.golang.org/genproto/googleapis/api v0.0.0-20250825161204-c5933d9347a5/go.mod h1:j3QtIyytwqGr1JUDtYXwtMXWPKsEa5LtzIFN1Wn5WvE= -google.golang.org/genproto/googleapis/rpc v0.0.0-20251103181224-f26f9409b101 h1:tRPGkdGHuewF4UisLzzHHr1spKw92qLM98nIzxbC0wY= -google.golang.org/genproto/googleapis/rpc v0.0.0-20251103181224-f26f9409b101/go.mod h1:7i2o+ce6H/6BluujYR+kqX3GKH+dChPTQU19wjRPiGk= -google.golang.org/grpc v1.76.0 h1:UnVkv1+uMLYXoIz6o7chp59WfQUYA2ex/BXQ9rHZu7A= -google.golang.org/grpc v1.76.0/go.mod h1:Ju12QI8M6iQJtbcsV+awF5a4hfJMLi4X0JLo94ULZ6c= +google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217 h1:fCvbg86sFXwdrl5LgVcTEvNC+2txB5mgROGmRL5mrls= +google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217/go.mod h1:+rXWjjaukWZun3mLfjmVnQi18E1AsFbDN9QdJ5YXLto= +google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 h1:gRkg/vSppuSQoDjxyiGfN4Upv/h/DQmIR10ZU8dh4Ww= +google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217/go.mod h1:7i2o+ce6H/6BluujYR+kqX3GKH+dChPTQU19wjRPiGk= +google.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE= +google.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ= google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/lib/go.mod b/lib/go.mod index 4018fc8f27..42bc822948 100644 --- a/lib/go.mod +++ b/lib/go.mod @@ -1,6 +1,6 @@ module github.com/sourcegraph/sourcegraph/lib -go 1.25.1 +go 1.25.8 require ( github.com/Masterminds/semver v1.5.0 diff --git a/mise.toml b/mise.toml index 74bb884ee3..23dcc8805c 100644 --- a/mise.toml +++ b/mise.toml @@ -1,4 +1,4 @@ [tools] -golang = "1.26.0" +golang = "1.26.1" shfmt = "3.8.0" shellcheck = "0.10.0" From d859abfa558ab3c7ca74e2b94653c33ebf93697d Mon Sep 17 00:00:00 2001 From: Carter Brainerd Date: Mon, 6 Apr 2026 10:50:11 -0400 Subject: [PATCH 559/647] security: validate batch spec mount name (#1284) --- internal/batches/service/service_test.go | 20 ++++++++++++++++++++ lib/batches/batch_spec.go | 13 +++++++++---- 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/internal/batches/service/service_test.go b/internal/batches/service/service_test.go index c550cafd6d..da877edc33 100644 --- a/internal/batches/service/service_test.go +++ b/internal/batches/service/service_test.go @@ -594,6 +594,26 @@ changesetTemplate: `, expectedErr: errors.New("handling mount: step 1 mount path is not in the same directory or subdirectory as the batch spec"), }, + { + name: "files target path with comma", + batchSpecDir: tempDir, + rawSpec: ` +name: test-spec +description: A test spec +steps: + - run: echo "hello" + container: alpine:3 + files: + "/tmp/x,source=/var/run/docker.sock,target=/var/run/docker.sock": "IGNORED" +changesetTemplate: + title: Test Files + body: Test files target path with comma + branch: test + commit: + message: Test +`, + expectedErr: errors.New("parsing batch spec: step 1 files target path contains invalid characters"), + }, { name: "mount path dot-dot traversal", batchSpecDir: tempDir, diff --git a/lib/batches/batch_spec.go b/lib/batches/batch_spec.go index e558c286f4..a9ccc6e146 100644 --- a/lib/batches/batch_spec.go +++ b/lib/batches/batch_spec.go @@ -169,19 +169,24 @@ func parseBatchSpec(schema string, data []byte) (*BatchSpec, error) { for i, step := range spec.Steps { for _, mount := range step.Mount { - if strings.Contains(mount.Path, invalidMountCharacters) { + if strings.ContainsAny(mount.Path, invalidMountCharacters) { errs = errors.Append(errs, NewValidationError(errors.Newf("step %d mount path contains invalid characters", i+1))) } - if strings.Contains(mount.Mountpoint, invalidMountCharacters) { + if strings.ContainsAny(mount.Mountpoint, invalidMountCharacters) { errs = errors.Append(errs, NewValidationError(errors.Newf("step %d mount mountpoint contains invalid characters", i+1))) } } + for name := range step.Files { + if strings.ContainsAny(name, invalidMountCharacters) { + errs = errors.Append(errs, NewValidationError(errors.Newf("step %d files target path contains invalid characters", i+1))) + } + } } return &spec, errs } - -const invalidMountCharacters = "," +// docker uses Golang's `encoding/csv` library to parse arguments passed to `--mount` +const invalidMountCharacters = ",\"\n\r" func (on *OnQueryOrRepository) String() string { if on.RepositoriesMatchingQuery != "" { From c9cbde00ca97f8f21960818b6a6b4c6d314a4e16 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Wed, 8 Apr 2026 13:00:34 +0000 Subject: [PATCH 560/647] fix/repo-list: print partial data when there are graphql errors (#1282) * update GraphQLErrors to have constructor + handle paths * add test for repo list with some repos failing but not all * update src repo list to handle graphql errors - errors are treated as warnings when getting partial data - if we have no data and just errors that is a fatal error * add comment * Handle partial repo list warnings --- cmd/src/repos_list.go | 207 +++++++++++++++++++++++++++-------- cmd/src/repos_list_test.go | 213 +++++++++++++++++++++++++++++++++++++ internal/api/errors.go | 47 ++++++++ 3 files changed, 424 insertions(+), 43 deletions(-) create mode 100644 cmd/src/repos_list_test.go diff --git a/cmd/src/repos_list.go b/cmd/src/repos_list.go index 575c48dda9..64a17c95f1 100644 --- a/cmd/src/repos_list.go +++ b/cmd/src/repos_list.go @@ -2,6 +2,7 @@ package main import ( "context" + "encoding/json" "flag" "fmt" "strings" @@ -9,6 +10,149 @@ import ( "github.com/sourcegraph/src-cli/internal/api" ) +type reposListOptions struct { + first int + query string + cloned bool + notCloned bool + indexed bool + notIndexed bool + orderBy string + descending bool +} + +type repositoriesListResult struct { + Data struct { + Repositories struct { + Nodes []Repository `json:"nodes"` + } `json:"repositories"` + } `json:"data"` + Errors []json.RawMessage `json:"errors,omitempty"` +} + +// listRepositories returns the repositories from the response, any GraphQL +// errors returned alongside data (should be treated as warnings), and +// a hard error when the query fails without usable repository data. +func listRepositories(ctx context.Context, client api.Client, params reposListOptions) ([]Repository, api.GraphQlErrors, error) { + query := `query Repositories( + $first: Int, + $query: String, + $cloned: Boolean, + $notCloned: Boolean, + $indexed: Boolean, + $notIndexed: Boolean, + $orderBy: RepositoryOrderBy, + $descending: Boolean, +) { + repositories( + first: $first, + query: $query, + cloned: $cloned, + notCloned: $notCloned, + indexed: $indexed, + notIndexed: $notIndexed, + orderBy: $orderBy, + descending: $descending, + ) { + nodes { + ...RepositoryFields + } + } +} +` + repositoryFragment + + var result repositoriesListResult + ok, err := client.NewRequest(query, map[string]any{ + "first": api.NullInt(params.first), + "query": api.NullString(params.query), + "cloned": params.cloned, + "notCloned": params.notCloned, + "indexed": params.indexed, + "notIndexed": params.notIndexed, + "orderBy": params.orderBy, + "descending": params.descending, + }).DoRaw(ctx, &result) + if err != nil || !ok { + return nil, nil, err + } + repos := result.Data.Repositories.Nodes + if len(result.Errors) == 0 { + return repos, nil, nil + } + + errors := api.NewGraphQlErrors(result.Errors) + if len(repos) > 0 { + return repos, errors, nil + } + + return nil, nil, errors +} + +func gqlErrorPathString(pathSegment any) (string, bool) { + value, ok := pathSegment.(string) + return value, ok +} + +func gqlErrorIndex(pathSegment any) (int, bool) { + switch value := pathSegment.(type) { + case float64: + index := int(value) + return index, float64(index) == value && index >= 0 + case int: + return value, value >= 0 + default: + return 0, false + } +} + +func gqlWarningPath(graphQLError *api.GraphQlError) string { + path, err := graphQLError.Path() + if err != nil || len(path) == 0 { + return "" + } + + var b strings.Builder + for _, pathSegment := range path { + if segment, ok := gqlErrorPathString(pathSegment); ok { + if b.Len() > 0 { + b.WriteByte('.') + } + b.WriteString(segment) + continue + } + + if index, ok := gqlErrorIndex(pathSegment); ok { + fmt.Fprintf(&b, "[%d]", index) + } + } + + return b.String() +} + +func gqlWarningMessage(graphQLError *api.GraphQlError) string { + message, err := graphQLError.Message() + if err != nil || message == "" { + return graphQLError.Error() + } + return message +} + +func formatRepositoryListWarnings(warnings api.GraphQlErrors) string { + var b strings.Builder + fmt.Fprintf(&b, "warnings: %d errors during listing\n", len(warnings)) + for _, warning := range warnings { + path := gqlWarningPath(warning) + message := gqlWarningMessage(warning) + if path != "" { + fmt.Fprintf(&b, "%s - %s\n", path, message) + } else { + fmt.Fprintf(&b, "%s\n", message) + } + fmt.Fprintf(&b, "%s\n", warning.Error()) + } + return b.String() +} + func init() { usage := ` Examples: @@ -64,33 +208,6 @@ Examples: return err } - query := `query Repositories( - $first: Int, - $query: String, - $cloned: Boolean, - $notCloned: Boolean, - $indexed: Boolean, - $notIndexed: Boolean, - $orderBy: RepositoryOrderBy, - $descending: Boolean, -) { - repositories( - first: $first, - query: $query, - cloned: $cloned, - notCloned: $notCloned, - indexed: $indexed, - notIndexed: $notIndexed, - orderBy: $orderBy, - descending: $descending, - ) { - nodes { - ...RepositoryFields - } - } -} -` + repositoryFragment - var orderBy string switch *orderByFlag { case "name": @@ -101,25 +218,22 @@ Examples: return fmt.Errorf("invalid -order-by flag value: %q", *orderByFlag) } - var result struct { - Repositories struct { - Nodes []Repository - } - } - if ok, err := client.NewRequest(query, map[string]any{ - "first": api.NullInt(*firstFlag), - "query": api.NullString(*queryFlag), - "cloned": *clonedFlag, - "notCloned": *notClonedFlag, - "indexed": *indexedFlag, - "notIndexed": *notIndexedFlag, - "orderBy": orderBy, - "descending": *descendingFlag, - }).Do(context.Background(), &result); err != nil || !ok { + // if we get repos and errors during a listing, we consider the errors as warnings and the data partially complete + repos, warnings, err := listRepositories(context.Background(), client, reposListOptions{ + first: *firstFlag, + query: *queryFlag, + cloned: *clonedFlag, + notCloned: *notClonedFlag, + indexed: *indexedFlag, + notIndexed: *notIndexedFlag, + orderBy: orderBy, + descending: *descendingFlag, + }) + if err != nil { return err } - for _, repo := range result.Repositories.Nodes { + for _, repo := range repos { if *namesWithoutHostFlag { firstSlash := strings.Index(repo.Name, "/") fmt.Println(repo.Name[firstSlash+len("/"):]) @@ -130,6 +244,13 @@ Examples: return err } } + if len(warnings) > 0 { + if *verbose { + fmt.Fprint(flagSet.Output(), formatRepositoryListWarnings(warnings)) + } else { + fmt.Fprintf(flagSet.Output(), "warning: %d errors during listing; rerun with -v to inspect them\n", len(warnings)) + } + } return nil } diff --git a/cmd/src/repos_list_test.go b/cmd/src/repos_list_test.go new file mode 100644 index 0000000000..86f3e748be --- /dev/null +++ b/cmd/src/repos_list_test.go @@ -0,0 +1,213 @@ +package main + +import ( + "context" + "encoding/json" + "testing" + + "github.com/sourcegraph/src-cli/internal/api" + mockapi "github.com/sourcegraph/src-cli/internal/api/mock" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" +) + +type expectedRepository struct { + name string + defaultBranch GitRef +} + +func TestListRepositoriesHandlesGraphQLErrors(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + response map[string]any + wantRepos []expectedRepository + wantWarnings []string + wantErr string + }{ + { + name: "default branch warning preserves repositories", + response: listRepositoriesResponse( + []map[string]any{ + repositoryNode("github.com/sourcegraph/ok", gitRefNode("refs/heads/main", "main")), + repositoryNode("github.com/sourcegraph/broken", nil), + }, + graphqlError("failed to resolve HEAD for github.com/sourcegraph/broken", "repositories", "nodes", 1, "defaultBranch"), + ), + wantRepos: []expectedRepository{ + {name: "github.com/sourcegraph/ok", defaultBranch: GitRef{Name: "refs/heads/main", DisplayName: "main"}}, + {name: "github.com/sourcegraph/broken", defaultBranch: GitRef{}}, + }, + wantWarnings: []string{"failed to resolve HEAD for github.com/sourcegraph/broken"}, + }, + { + name: "top-level warning with data is preserved as warning", + response: listRepositoriesResponse( + []map[string]any{ + repositoryNode("github.com/sourcegraph/ok", gitRefNode("refs/heads/main", "main")), + }, + graphqlError("listing timed out", "repositories"), + ), + wantRepos: []expectedRepository{ + {name: "github.com/sourcegraph/ok", defaultBranch: GitRef{Name: "refs/heads/main", DisplayName: "main"}}, + }, + wantWarnings: []string{"listing timed out"}, + }, + { + name: "errors without repositories are returned as hard errors", + response: listRepositoriesResponse( + nil, + graphqlError("listing timed out", "repositories"), + ), + wantErr: "listing timed out", + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + + repos, warnings, err := runListRepositories(t, test.response) + if test.wantErr != "" { + require.ErrorContains(t, err, test.wantErr) + require.Nil(t, repos) + require.Nil(t, warnings) + return + } + + require.NoError(t, err) + require.Len(t, warnings, len(test.wantWarnings)) + require.Len(t, repos, len(test.wantRepos)) + for i, want := range test.wantRepos { + require.Equal(t, want.name, repos[i].Name) + require.Equal(t, want.defaultBranch, repos[i].DefaultBranch) + } + for i, want := range test.wantWarnings { + require.ErrorContains(t, warnings[i], want) + } + }) + } +} + +func TestFormatRepositoryListWarnings(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + warnings api.GraphQlErrors + want string + }{ + { + name: "with path", + warnings: api.NewGraphQlErrors([]json.RawMessage{ + mustRawJSON(t, graphqlError("failed to resolve HEAD for github.com/sourcegraph/broken", "repositories", "nodes", 1, "defaultBranch")), + }), + want: `warnings: 1 errors during listing +repositories.nodes[1].defaultBranch - failed to resolve HEAD for github.com/sourcegraph/broken +{ + "message": "failed to resolve HEAD for github.com/sourcegraph/broken", + "path": [ + "repositories", + "nodes", + 1, + "defaultBranch" + ] +} +`, + }, + { + name: "without path", + warnings: api.NewGraphQlErrors([]json.RawMessage{ + mustRawJSON(t, graphqlError("listing timed out")), + }), + want: `warnings: 1 errors during listing +listing timed out +{ + "message": "listing timed out" +} +`, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + require.Equal(t, test.want, formatRepositoryListWarnings(test.warnings)) + }) + } +} + +func runListRepositories(t *testing.T, response map[string]any) ([]Repository, api.GraphQlErrors, error) { + t.Helper() + + client := new(mockapi.Client) + request := &mockapi.Request{Response: mustJSON(t, response)} + + client.On("NewRequest", mock.Anything, mock.Anything).Return(request).Once() + request.On("DoRaw", context.Background(), mock.Anything).Return(true, nil).Once() + + repos, warnings, err := listRepositories(context.Background(), client, reposListOptions{ + first: 1000, + cloned: true, + notCloned: true, + indexed: true, + notIndexed: false, + orderBy: "REPOSITORY_NAME", + }) + + client.AssertExpectations(t) + request.AssertExpectations(t) + + return repos, warnings, err +} + +func listRepositoriesResponse(nodes []map[string]any, graphqlErrors ...map[string]any) map[string]any { + response := map[string]any{ + "data": map[string]any{ + "repositories": map[string]any{ + "nodes": nodes, + }, + }, + } + if len(graphqlErrors) > 0 { + response["errors"] = graphqlErrors + } + return response +} + +func repositoryNode(name string, defaultBranch any) map[string]any { + return map[string]any{ + "name": name, + "defaultBranch": defaultBranch, + } +} + +func gitRefNode(name, displayName string) map[string]any { + return map[string]any{ + "name": name, + "displayName": displayName, + } +} + +func graphqlError(message string, path ...any) map[string]any { + err := map[string]any{"message": message} + if len(path) > 0 { + err["path"] = path + } + return err +} + +func mustJSON(t *testing.T, v any) string { + t.Helper() + + data, err := json.Marshal(v) + require.NoError(t, err) + return string(data) +} + +func mustRawJSON(t *testing.T, v any) json.RawMessage { + t.Helper() + + return json.RawMessage(mustJSON(t, v)) +} diff --git a/internal/api/errors.go b/internal/api/errors.go index e5ff8193ce..9e60ab20d2 100644 --- a/internal/api/errors.go +++ b/internal/api/errors.go @@ -9,6 +9,19 @@ import ( // GraphQlErrors contains one or more GraphQlError instances. type GraphQlErrors []*GraphQlError +// NewGraphQlErrors wraps raw GraphQL error payloads in GraphQlError values. +func NewGraphQlErrors(graphQLErrorPayloads []json.RawMessage) GraphQlErrors { + errs := make(GraphQlErrors, 0, len(graphQLErrorPayloads)) + for _, graphQLErrorPayload := range graphQLErrorPayloads { + var value any + if err := json.Unmarshal(graphQLErrorPayload, &value); err != nil { + value = map[string]any{"message": string(graphQLErrorPayload)} + } + errs = append(errs, &GraphQlError{v: value}) + } + return errs +} + func (gg GraphQlErrors) Error() string { // This slightly convoluted implementation is used to ensure that output // remains stable with earlier versions of src-cli, which returned a wrapped @@ -30,6 +43,23 @@ func (gg GraphQlErrors) Error() string { // GraphQlError wraps a raw JSON error returned from a GraphQL endpoint. type GraphQlError struct{ v any } +// Message returns the GraphQL error message, if one was set on the error. +func (g *GraphQlError) Message() (string, error) { + e, ok := g.v.(map[string]any) + if !ok { + return "", errors.Errorf("unexpected GraphQL error of type %T", g.v) + } + + if e["message"] == nil { + return "", nil + } + message, ok := e["message"].(string) + if !ok { + return "", errors.Errorf("unexpected message of type %T", e["message"]) + } + return message, nil +} + // Code returns the GraphQL error code, if one was set on the error. func (g *GraphQlError) Code() (string, error) { ext, err := g.Extensions() @@ -48,6 +78,23 @@ func (g *GraphQlError) Code() (string, error) { return "", nil } +// Path returns the GraphQL error path, if one was set on the error. +func (g *GraphQlError) Path() ([]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["path"] == nil { + return nil, nil + } + path, ok := e["path"].([]any) + if !ok { + return nil, errors.Errorf("unexpected path of type %T", e["path"]) + } + return path, nil +} + func (g *GraphQlError) Error() string { j, _ := json.MarshalIndent(g.v, "", " ") return string(j) From 81ef50c88a538ba242c407e03efba7ec5345d5c5 Mon Sep 17 00:00:00 2001 From: Keegan Carruthers-Smith Date: Wed, 8 Apr 2026 15:24:16 +0200 Subject: [PATCH 561/647] repos: remove unread fields from graphql query (#1288) We didn't actually read the majority of fields on the graphql query for repositories. So we remove all unread fields. In particular this removes the field "Language" which is expensive to compute if not cached. In practice I suspect this will dramatically improve the performance of "src repos list" command. --- cmd/src/repos.go | 41 ++--------------------------------------- 1 file changed, 2 insertions(+), 39 deletions(-) diff --git a/cmd/src/repos.go b/cmd/src/repos.go index d7131c6f87..c1347f5889 100644 --- a/cmd/src/repos.go +++ b/cmd/src/repos.go @@ -4,7 +4,6 @@ import ( "context" "flag" "fmt" - "time" "github.com/sourcegraph/sourcegraph/lib/errors" @@ -51,53 +50,17 @@ Use "src repos [command] -h" for more information about a command. const repositoryFragment = ` fragment RepositoryFields on Repository { - id name - url - description - language - createdAt - updatedAt - externalRepository { - id - serviceType - serviceID - } defaultBranch { name displayName } - viewerCanAdminister - keyValuePairs { - key - value - } } ` type Repository struct { - ID string `json:"id"` - Name string `json:"name"` - URL string `json:"url"` - Description string `json:"description"` - Language string `json:"language"` - CreatedAt time.Time `json:"createdAt"` - UpdatedAt *time.Time `json:"updatedAt"` - ExternalRepository ExternalRepository `json:"externalRepository"` - DefaultBranch GitRef `json:"defaultBranch"` - ViewerCanAdminister bool `json:"viewerCanAdminister"` - KeyValuePairs []KeyValuePair `json:"keyValuePairs"` -} - -type KeyValuePair struct { - Key string `json:"key"` - Value *string `json:"value"` -} - -type ExternalRepository struct { - ID string `json:"id"` - ServiceType string `json:"serviceType"` - ServiceID string `json:"serviceID"` + Name string `json:"name"` + DefaultBranch GitRef `json:"defaultBranch"` } type GitRef struct { From 0ec60de344615cb9f02f11dce524ba14a52e88a4 Mon Sep 17 00:00:00 2001 From: Dan Adler Date: Wed, 8 Apr 2026 06:39:23 -0700 Subject: [PATCH 562/647] Add tip to set env var after login (#1286) --- cmd/src/login.go | 6 +++++- cmd/src/login_test.go | 4 ++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/cmd/src/login.go b/cmd/src/login.go index 43ccfe0347..9818c245b6 100644 --- a/cmd/src/login.go +++ b/cmd/src/login.go @@ -110,7 +110,11 @@ func loginCmd(ctx context.Context, p loginParams) error { } _, flow := selectLoginFlow(p) - return flow(ctx, p) + if err := flow(ctx, p); err != nil { + return err + } + fmt.Fprintf(p.out, "\n💡 Tip: To use this endpoint in your shell, run:\n\n export SRC_ENDPOINT=%s\n\n", p.cfg.endpointURL) + return nil } // selectLoginFlow decides what login flow to run based on configured AuthMode. diff --git a/cmd/src/login_test.go b/cmd/src/login_test.go index 6a286c4b5a..1250d1adb9 100644 --- a/cmd/src/login_test.go +++ b/cmd/src/login_test.go @@ -115,7 +115,7 @@ func TestLogin(t *testing.T) { if err != nil { t.Fatal(err) } - wantOut := "✔︎ Authenticated as alice on $ENDPOINT" + wantOut := "✔︎ Authenticated as alice on $ENDPOINT\n\n\n💡 Tip: To use this endpoint in your shell, run:\n\n export SRC_ENDPOINT=$ENDPOINT" wantOut = strings.ReplaceAll(wantOut, "$ENDPOINT", s.URL) if out != wantOut { t.Errorf("got output %q, want %q", out, wantOut) @@ -156,7 +156,7 @@ func TestLogin(t *testing.T) { t.Fatal("expected stored oauth token to avoid device flow") } gotOut := strings.TrimSpace(out.String()) - wantOut := "✔︎ Authenticated as alice on $ENDPOINT\n\n\n✔︎ Authenticated with OAuth credentials" + wantOut := "✔︎ Authenticated as alice on $ENDPOINT\n\n\n✔︎ Authenticated with OAuth credentials\n\n💡 Tip: To use this endpoint in your shell, run:\n\n export SRC_ENDPOINT=$ENDPOINT" wantOut = strings.ReplaceAll(wantOut, "$ENDPOINT", s.URL) if gotOut != wantOut { t.Errorf("got output %q, want %q", gotOut, wantOut) From af9956ca84e94ab6cc3d3a7cb603f9c3307523e3 Mon Sep 17 00:00:00 2001 From: Keegan Carruthers-Smith Date: Wed, 8 Apr 2026 15:48:50 +0200 Subject: [PATCH 563/647] all: we no longer support -1 for pagination (#1289) Remove references that first=-1 will list everything. Additionally we also don't support setting the value to a very large number, since graphql will error out that the query is too complex. --- cmd/src/extsvc_list.go | 5 +---- cmd/src/orgs_list.go | 6 +----- cmd/src/repos_list.go | 6 +----- cmd/src/users_list.go | 6 +----- 4 files changed, 4 insertions(+), 19 deletions(-) diff --git a/cmd/src/extsvc_list.go b/cmd/src/extsvc_list.go index fbe6836c37..f1b22d2bd9 100644 --- a/cmd/src/extsvc_list.go +++ b/cmd/src/extsvc_list.go @@ -29,7 +29,7 @@ Examples: fmt.Println(usage) } var ( - firstFlag = flagSet.Int("first", -1, "Return only the first n external services. (use -1 for unlimited)") + firstFlag = flagSet.Int("first", 1000, "Return only the first n external services.") formatFlag = flagSet.String("f", "", `Format for the output, using the syntax of Go package text/template. (e.g. "{{.|json}}")`) apiFlags = api.NewFlags(flagSet) ) @@ -40,9 +40,6 @@ Examples: } first := *firstFlag - if first == -1 { - first = 9999999 // GraphQL API doesn't support negative for unlimited query - } var formatStr string if *formatFlag != "" { diff --git a/cmd/src/orgs_list.go b/cmd/src/orgs_list.go index fdcc7d5348..3ad611b473 100644 --- a/cmd/src/orgs_list.go +++ b/cmd/src/orgs_list.go @@ -16,10 +16,6 @@ Examples: $ src orgs list - List *all* organizations (may be slow!): - - $ src orgs list -first='-1' - List organizations whose names match the query: $ src orgs list -query='myquery' @@ -33,7 +29,7 @@ Examples: fmt.Println(usage) } var ( - firstFlag = flagSet.Int("first", 1000, "Returns the first n organizations from the list. (use -1 for unlimited)") + firstFlag = flagSet.Int("first", 1000, "Returns the first n organizations from the list.") queryFlag = flagSet.String("query", "", `Returns organizations whose names match the query. (e.g. "alice")`) formatFlag = flagSet.String("f", "{{.Name}}", `Format for the output, using the syntax of Go package text/template. (e.g. "{{.ID}}: {{.Name}} ({{.DisplayName}})" or "{{.|json}}")`) apiFlags = api.NewFlags(flagSet) diff --git a/cmd/src/repos_list.go b/cmd/src/repos_list.go index 64a17c95f1..cf2e7fca11 100644 --- a/cmd/src/repos_list.go +++ b/cmd/src/repos_list.go @@ -165,10 +165,6 @@ Examples: $ src repos list -f '{{.|json}}' - List *all* repositories (may be slow!): - - $ src repos list -first='-1' - List repositories whose names match the query: $ src repos list -query='myquery' @@ -182,7 +178,7 @@ Examples: fmt.Println(usage) } var ( - firstFlag = flagSet.Int("first", 1000, "Returns the first n repositories from the list. (use -1 for unlimited)") + firstFlag = flagSet.Int("first", 1000, "Returns the first n repositories from the list.") queryFlag = flagSet.String("query", "", `Returns repositories whose names match the query. (e.g. "myorg/")`) // TODO: add support for "names" field. clonedFlag = flagSet.Bool("cloned", true, "Include cloned repositories.") diff --git a/cmd/src/users_list.go b/cmd/src/users_list.go index 728b447917..a72e1d8a3e 100644 --- a/cmd/src/users_list.go +++ b/cmd/src/users_list.go @@ -16,10 +16,6 @@ Examples: $ src users list - List *all* users (may be slow!): - - $ src users list -first='-1' - List users whose names match the query: $ src users list -query='myquery' @@ -37,7 +33,7 @@ Examples: fmt.Println(usage) } var ( - firstFlag = flagSet.Int("first", 1000, "Returns the first n users from the list. (use -1 for unlimited)") + firstFlag = flagSet.Int("first", 1000, "Returns the first n users from the list.") queryFlag = flagSet.String("query", "", `Returns users whose names match the query. (e.g. "alice")`) tagFlag = flagSet.String("tag", "", `Returns users with the given tag.`) formatFlag = flagSet.String("f", "{{.Username}}", `Format for the output, using the syntax of Go package text/template. (e.g. "{{.ID}}: {{.Username}} ({{.DisplayName}})" or "{{.|json}}")`) From cdb00caf48dcfd74f812a2cbcca013d522648b82 Mon Sep 17 00:00:00 2001 From: Keegan Carruthers-Smith Date: Wed, 8 Apr 2026 15:55:13 +0200 Subject: [PATCH 564/647] repos: add back all fields except Langauge (#1290) --- cmd/src/repos.go | 39 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/cmd/src/repos.go b/cmd/src/repos.go index c1347f5889..b839f6d1e8 100644 --- a/cmd/src/repos.go +++ b/cmd/src/repos.go @@ -4,6 +4,7 @@ import ( "context" "flag" "fmt" + "time" "github.com/sourcegraph/sourcegraph/lib/errors" @@ -50,17 +51,51 @@ Use "src repos [command] -h" for more information about a command. const repositoryFragment = ` fragment RepositoryFields on Repository { + id name + url + description + createdAt + updatedAt + externalRepository { + id + serviceType + serviceID + } defaultBranch { name displayName } + viewerCanAdminister + keyValuePairs { + key + value + } } ` type Repository struct { - Name string `json:"name"` - DefaultBranch GitRef `json:"defaultBranch"` + ID string `json:"id"` + Name string `json:"name"` + URL string `json:"url"` + Description string `json:"description"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt *time.Time `json:"updatedAt"` + ExternalRepository ExternalRepository `json:"externalRepository"` + DefaultBranch GitRef `json:"defaultBranch"` + ViewerCanAdminister bool `json:"viewerCanAdminister"` + KeyValuePairs []KeyValuePair `json:"keyValuePairs"` +} + +type KeyValuePair struct { + Key string `json:"key"` + Value *string `json:"value"` +} + +type ExternalRepository struct { + ID string `json:"id"` + ServiceType string `json:"serviceType"` + ServiceID string `json:"serviceID"` } type GitRef struct { From 056be8b85ca84dd44360b6440afe0db404c72b4d Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Wed, 15 Apr 2026 10:41:18 +0200 Subject: [PATCH 565/647] feat/cli: migrate version subcommand to use urface/cli (#1292) * add runLegacy * use go 1.26 * add util methods to work urfave/cli flags in api * tweak help template to match legacy help * split command runner into legacy and migrated * migrate version to use urface cli * add onUsageError func and rename funcs to be 'Wrap*' * use Wrap from clicompat instead * remove init * update comments and method names of clicompat api flags * move runMigrated to be in main and work with os.Args * fix lint --- cmd/src/cmd.go | 32 ++-------- cmd/src/main.go | 13 +++- cmd/src/run_migration_compat.go | 102 ++++++++++++++++++++++++++++++++ cmd/src/version.go | 82 ++++++++++++++----------- go.mod | 3 +- go.sum | 2 + internal/api/flags.go | 13 ++++ internal/clicompat/api_flags.go | 49 +++++++++++++++ internal/clicompat/errors.go | 16 +++++ internal/clicompat/help.go | 56 ++++++++++++++++++ 10 files changed, 304 insertions(+), 64 deletions(-) create mode 100644 cmd/src/run_migration_compat.go create mode 100644 internal/clicompat/api_flags.go create mode 100644 internal/clicompat/errors.go create mode 100644 internal/clicompat/help.go diff --git a/cmd/src/cmd.go b/cmd/src/cmd.go index 93d0accbe3..9182dc57ea 100644 --- a/cmd/src/cmd.go +++ b/cmd/src/cmd.go @@ -6,8 +6,6 @@ import ( "log" "os" "slices" - - "github.com/sourcegraph/src-cli/internal/cmderrors" ) // command is a subcommand handler and its flag set. @@ -68,11 +66,12 @@ func (c commander) run(flagSet *flag.FlagSet, cmdName, usageText string, args [] // Find the subcommand to execute. name := flagSet.Arg(0) + + // Command is legacy, so lets execute the old way for _, cmd := range c { if !cmd.matches(name) { continue } - // Read global configuration now. var err error cfg, err = readConfig() @@ -80,31 +79,12 @@ func (c commander) run(flagSet *flag.FlagSet, cmdName, usageText string, args [] log.Fatal("reading config: ", err) } - // Parse subcommand flags. - args := flagSet.Args()[1:] - if err := cmd.flagSet.Parse(args); err != nil { - fmt.Printf("Error parsing subcommand flags: %s\n", err) - panic(fmt.Sprintf("all registered commands should use flag.ExitOnError: error: %s", err)) - } - - // Execute the subcommand. - if err := cmd.handler(flagSet.Args()[1:]); err != nil { - if _, ok := err.(*cmderrors.UsageError); ok { - log.Printf("error: %s\n\n", err) - cmd.flagSet.SetOutput(os.Stderr) - flag.CommandLine.SetOutput(os.Stderr) - cmd.flagSet.Usage() - os.Exit(2) - } - if e, ok := err.(*cmderrors.ExitCodeError); ok { - if e.HasError() { - log.Println(e) - } - os.Exit(e.Code()) - } + exitCode, err := runLegacy(cmd, flagSet) + if err != nil { log.Fatal(err) } - os.Exit(0) + os.Exit(exitCode) + } log.Printf("%s: unknown subcommand %q", cmdName, name) log.Fatalf("Run '%s help' for usage.", cmdName) diff --git a/cmd/src/main.go b/cmd/src/main.go index 93be07c4bf..1bc131c0eb 100644 --- a/cmd/src/main.go +++ b/cmd/src/main.go @@ -93,7 +93,18 @@ func main() { log.SetFlags(0) log.SetPrefix("") - commands.run(flag.CommandLine, "src", usageText, normalizeDashHelp(os.Args[1:])) + ranMigratedCmd, exitCode, err := maybeRunMigratedCommand() + if ranMigratedCmd { + if err != nil { + log.Println(err) + } + os.Exit(exitCode) + } + + // if we didn't run a migrated command, then lets try running the legacy version + if !ranMigratedCmd { + commands.run(flag.CommandLine, "src", usageText, normalizeDashHelp(os.Args[1:])) + } } // normalizeDashHelp converts --help to -help since Go's flag parser only supports single dash. diff --git a/cmd/src/run_migration_compat.go b/cmd/src/run_migration_compat.go new file mode 100644 index 0000000000..c50f2cd34a --- /dev/null +++ b/cmd/src/run_migration_compat.go @@ -0,0 +1,102 @@ +package main + +import ( + "context" + "flag" + "fmt" + "log" + "os" + "sort" + + "github.com/sourcegraph/src-cli/internal/clicompat" + "github.com/sourcegraph/src-cli/internal/cmderrors" + "github.com/urfave/cli/v3" + + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +var migratedCommands = map[string]*cli.Command{ + "version": versionCommand, +} + +func maybeRunMigratedCommand() (isMigrated bool, exitCode int, err error) { + // need to figure out if a migrated command has been requested + flag.Parse() + subCommand := flag.CommandLine.Arg(0) + _, isMigrated = migratedCommands[subCommand] + if !isMigrated { + return + } + cfg, err = readConfig() + if err != nil { + log.Fatal("reading config: ", err) + } + + exitCode, err = runMigrated() + return +} + +// migratedRootCommand constructs a root 'src' command and adds +// MigratedCommands as subcommands to it +func migratedRootCommand() *cli.Command { + names := make([]string, 0, len(migratedCommands)) + for name := range migratedCommands { + names = append(names, name) + } + sort.Strings(names) + + commands := make([]*cli.Command, 0, len(names)) + for _, name := range names { + commands = append(commands, migratedCommands[name]) + } + + return clicompat.WrapRoot(&cli.Command{ + Name: "src", + HideVersion: true, + Commands: commands, + }) +} + +// runMigrated runs the command within urfave/cli framework +func runMigrated() (int, error) { + ctx := context.Background() + + err := migratedRootCommand().Run(ctx, os.Args) + if errors.HasType[*cmderrors.UsageError](err) { + return 2, nil + } + var exitErr cli.ExitCoder + if errors.AsInterface(err, &exitErr) { + return exitErr.ExitCode(), err + } + return 0, err +} + +// runLegacy runs the command using the original commander framework +func runLegacy(cmd *command, flagSet *flag.FlagSet) (int, error) { + // Parse subcommand flags. + args := flagSet.Args()[1:] + if err := cmd.flagSet.Parse(args); err != nil { + fmt.Printf("Error parsing subcommand flags: %s\n", err) + panic(fmt.Sprintf("all registered commands should use flag.ExitOnError: error: %s", err)) + } + + // Execute the subcommand. + if err := cmd.handler(flagSet.Args()[1:]); err != nil { + if _, ok := err.(*cmderrors.UsageError); ok { + log.Printf("error: %s\n\n", err) + cmd.flagSet.SetOutput(os.Stderr) + flag.CommandLine.SetOutput(os.Stderr) + cmd.flagSet.Usage() + return 2, nil + } + if e, ok := err.(*cmderrors.ExitCodeError); ok { + if e.HasError() { + log.Println(e) + } + return e.Code(), nil + } + return 1, err + } + return 0, nil +} diff --git a/cmd/src/version.go b/cmd/src/version.go index 024ab0600e..6186159368 100644 --- a/cmd/src/version.go +++ b/cmd/src/version.go @@ -3,63 +3,73 @@ package main import ( "context" "encoding/json" - "flag" "fmt" "io" "net/http" + "os" "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/clicompat" "github.com/sourcegraph/src-cli/internal/version" + + "github.com/urfave/cli/v3" ) -func init() { - usage := ` -Examples: +const versionExamples = `Examples: Get the src-cli version and the Sourcegraph instance's recommended version: $ src version ` - flagSet := flag.NewFlagSet("version", flag.ExitOnError) - - var ( - clientOnly = flagSet.Bool("client-only", false, "If true, only the client version will be printed.") - apiFlags = api.NewFlags(flagSet) - ) - - handler := func(args []string) error { - fmt.Printf("Current version: %s\n", version.BuildTag) - if clientOnly != nil && *clientOnly { - return nil +var versionCommand = clicompat.Wrap(&cli.Command{ + Name: "version", + Usage: "display and compare the src-cli version against the recommended version for your instance", + UsageText: "src version [options]", + OnUsageError: clicompat.OnUsageError, + Description: ` +` + versionExamples, + Flags: clicompat.WithAPIFlags( + &cli.BoolFlag{ + Name: "client-only", + Usage: "If true, only the client version will be printed.", + }, + ), + HideVersion: true, + Action: func(ctx context.Context, c *cli.Command) error { + args := VersionArgs{ + Client: cfg.apiClient(clicompat.APIFlagsFromCmd(c), os.Stdout), + ClientOnly: c.Bool("client-only"), } + return versionHandler(args) + }, +}) + +type VersionArgs struct { + ClientOnly bool + Client api.Client + Output io.Writer +} - client := cfg.apiClient(apiFlags, flagSet.Output()) - recommendedVersion, err := getRecommendedVersion(context.Background(), client) - if err != nil { - return errors.Wrap(err, "failed to get recommended version for Sourcegraph deployment") - } - if recommendedVersion == "" { - fmt.Println("Recommended version: ") - fmt.Println("This Sourcegraph instance does not support this feature.") - return nil - } - fmt.Printf("Recommended version: %s or later\n", recommendedVersion) +func versionHandler(args VersionArgs) error { + fmt.Printf("Current version: %s\n", version.BuildTag) + if args.ClientOnly { return nil } - // Register the command. - commands = append(commands, &command{ - flagSet: flagSet, - handler: handler, - usageFunc: func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src %s':\n", flagSet.Name()) - flagSet.PrintDefaults() - fmt.Println(usage) - }, - }) + recommendedVersion, err := getRecommendedVersion(context.Background(), args.Client) + if err != nil { + return errors.Wrap(err, "failed to get recommended version for Sourcegraph deployment") + } + if recommendedVersion == "" { + fmt.Println("Recommended version: ") + fmt.Println("This Sourcegraph instance does not support this feature.") + return nil + } + fmt.Printf("Recommended version: %s or later\n", recommendedVersion) + return nil } func getRecommendedVersion(ctx context.Context, client api.Client) (string, error) { diff --git a/go.mod b/go.mod index 274db0a7c8..75f66dfa62 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/sourcegraph/src-cli -go 1.25.8 +go 1.26 require ( cloud.google.com/go/storage v1.50.0 @@ -83,6 +83,7 @@ require ( github.com/spiffe/go-spiffe/v2 v2.6.0 // indirect github.com/tliron/commonlog v0.2.19 // indirect github.com/tliron/kutil v0.3.27 // indirect + github.com/urfave/cli/v3 v3.8.0 // indirect github.com/x448/float16 v0.8.4 // indirect github.com/xlab/treeprint v1.2.0 // indirect github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect diff --git a/go.sum b/go.sum index e85cdd9f5a..eda4224b98 100644 --- a/go.sum +++ b/go.sum @@ -370,6 +370,8 @@ github.com/tliron/glsp v0.2.2 h1:IKPfwpE8Lu8yB6Dayta+IyRMAbTVunudeauEgjXBt+c= github.com/tliron/glsp v0.2.2/go.mod h1:GMVWDNeODxHzmDPvYbYTCs7yHVaEATfYtXiYJ9w1nBg= github.com/tliron/kutil v0.3.27 h1:Wb0V5jdbTci6Let1tiGY741J/9FIynmV/pCsPDPsjcM= github.com/tliron/kutil v0.3.27/go.mod h1:AHeLNIFBSKBU39ELVHZdkw2f/ez2eKGAAGoxwBlhMi8= +github.com/urfave/cli/v3 v3.8.0 h1:XqKPrm0q4P0q5JpoclYoCAv0/MIvH/jZ2umzuf8pNTI= +github.com/urfave/cli/v3 v3.8.0/go.mod h1:ysVLtOEmg2tOy6PknnYVhDoouyC/6N42TMeoMzskhso= github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= diff --git a/internal/api/flags.go b/internal/api/flags.go index 32a255e371..be2397e818 100644 --- a/internal/api/flags.go +++ b/internal/api/flags.go @@ -48,6 +48,19 @@ func NewFlags(flagSet *flag.FlagSet) *Flags { } } +// NewFlagsFromValues instantiates a new Flags structure from explicit values. +// This is used by cli/v3 compatibility adapters that do not operate on a +// standard flag.FlagSet. +func NewFlagsFromValues(dump, getCurl, trace, insecureSkipVerify, userAgentTelemetry bool) *Flags { + return &Flags{ + dump: new(dump), + getCurl: new(getCurl), + trace: new(trace), + insecureSkipVerify: new(insecureSkipVerify), + userAgentTelemetry: new(userAgentTelemetry), + } +} + func defaultFlags() *Flags { telemetry := defaultUserAgentTelemetry() d := false diff --git a/internal/clicompat/api_flags.go b/internal/clicompat/api_flags.go new file mode 100644 index 0000000000..736d9997cb --- /dev/null +++ b/internal/clicompat/api_flags.go @@ -0,0 +1,49 @@ +package clicompat + +import ( + "os" + + "github.com/sourcegraph/src-cli/internal/api" + "github.com/urfave/cli/v3" +) + +// WithAPIFlags appends the standard API-related flags used by legacy src +func WithAPIFlags(baseFlags ...cli.Flag) []cli.Flag { + var flagTable = []struct { + name string + value bool + text string + }{ + {"dump-requests", false, "Log GraphQL requests and responses to stdout"}, + {"get-curl", false, "Print the curl command for executing this query and exit (WARNING: includes printing your access token!)"}, + {"trace", false, "Log the trace ID for requests. See https://docs.sourcegraph.com/admin/observability/tracing"}, + {"insecure-skip-verify", false, "Skip validation of TLS certificates against trusted chains"}, + {"user-agent-telemetry", defaultAPIUserAgentTelemetry(), "Include the operating system and architecture in the User-Agent sent with requests to Sourcegraph"}, + } + + flags := append([]cli.Flag{}, baseFlags...) + for _, item := range flagTable { + flags = append(flags, &cli.BoolFlag{ + Name: item.name, + Value: item.value, + Usage: item.text, + }) + } + + return flags +} + +// APIFlagsFromCmd reads the shared API-related flags from a command into api.Flags +func APIFlagsFromCmd(cmd *cli.Command) *api.Flags { + return api.NewFlagsFromValues( + cmd.Bool("dump-requests"), + cmd.Bool("get-curl"), + cmd.Bool("trace"), + cmd.Bool("insecure-skip-verify"), + cmd.Bool("user-agent-telemetry"), + ) +} + +func defaultAPIUserAgentTelemetry() bool { + return os.Getenv("SRC_DISABLE_USER_AGENT_TELEMETRY") == "" +} diff --git a/internal/clicompat/errors.go b/internal/clicompat/errors.go new file mode 100644 index 0000000000..f06886b4bf --- /dev/null +++ b/internal/clicompat/errors.go @@ -0,0 +1,16 @@ +package clicompat + +import ( + "context" + "fmt" + "os" + + "github.com/sourcegraph/src-cli/internal/cmderrors" + "github.com/urfave/cli/v3" +) + +func OnUsageError(ctx context.Context, cmd *cli.Command, err error, isSubCommand bool) error { + fmt.Fprintf(os.Stderr, "error: %s\n", err.Error()) + cli.DefaultPrintHelp(os.Stderr, cmd.CustomHelpTemplate, cmd) + return cmderrors.Usage(err.Error()) +} diff --git a/internal/clicompat/help.go b/internal/clicompat/help.go new file mode 100644 index 0000000000..f458ad6fbb --- /dev/null +++ b/internal/clicompat/help.go @@ -0,0 +1,56 @@ +package clicompat + +import "github.com/urfave/cli/v3" + +// LegacyCommandHelpTemplate formats leaf command help in a style closer to the +// existing flag.FlagSet-based help output. +const LegacyCommandHelpTemplate = `Usage of '{{.FullName}}': +{{range .VisibleFlags}} {{printf " -%s\n\t\t\t\t%s\n" .Name .Usage}}{{end}}{{if .Description}} + {{trim .Description}} +{{end}} +` + +// LegacyRootCommandHelpTemplate formats root command help while preserving a +// command's UsageText when it is provided. +const LegacyRootCommandHelpTemplate = `{{if .UsageText}}{{trim .UsageText}} +{{else}}Usage of '{{.FullName}}': +{{end}}{{if .VisibleFlags}}{{range .VisibleFlags}}{{println .}}{{end}}{{end}}{{if .VisibleCommands}} +{{range .VisibleCommands}}{{printf "\t%s\t%s\n" .Name .Usage}}{{end}}{{end}}{{if .Description}} +{{trim .Description}} +{{end}} +` + +// Wrap sets common options on a sub commands to ensure consistency for help and error handling +func Wrap(cmd *cli.Command) *cli.Command { + if cmd == nil { + return nil + } + + cmd.CustomHelpTemplate = LegacyCommandHelpTemplate + cmd.OnUsageError = OnUsageError + return cmd +} + +// WrapRoot sets common options on a root command to ensure consistency for help and error handling +func WrapRoot(cmd *cli.Command) *cli.Command { + if cmd == nil { + return nil + } + + cmd.CustomRootCommandHelpTemplate = LegacyRootCommandHelpTemplate + cmd.OnUsageError = OnUsageError + return cmd +} + +// WithLegacyHelp applies both root and leaf legacy help templates. +func WithLegacyHelp(cmd *cli.Command) *cli.Command { + if cmd == nil { + return nil + } + + cmd.CustomHelpTemplate = LegacyCommandHelpTemplate + cmd.CustomRootCommandHelpTemplate = LegacyRootCommandHelpTemplate + cmd.OnUsageError = OnUsageError + + return cmd +} From 2c8c401ff30c57223a0fd8e9b398483162e11fdc Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Wed, 15 Apr 2026 14:12:06 +0200 Subject: [PATCH 566/647] remove pointless condition due to os.Exit (#1294) --- cmd/src/main.go | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/cmd/src/main.go b/cmd/src/main.go index 1bc131c0eb..8499d6465f 100644 --- a/cmd/src/main.go +++ b/cmd/src/main.go @@ -102,9 +102,7 @@ func main() { } // if we didn't run a migrated command, then lets try running the legacy version - if !ranMigratedCmd { - commands.run(flag.CommandLine, "src", usageText, normalizeDashHelp(os.Args[1:])) - } + commands.run(flag.CommandLine, "src", usageText, normalizeDashHelp(os.Args[1:])) } // normalizeDashHelp converts --help to -help since Go's flag parser only supports single dash. From f71cf56652632fcdabe886c6a46c7a4d759f269a Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Wed, 15 Apr 2026 16:23:23 +0200 Subject: [PATCH 567/647] add AGENTS.md guidance to use urfave/cli when adding new commands (#1295) --- AGENTS.md | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 AGENTS.md diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000000..a499626f38 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,4 @@ +# Command Guidelines + +- When adding new commands, use `urfave/cli` instead of the legacy `commander` pattern. +- Register new `urfave/cli` commands in the `migratedCommands` map in `cmd/src/run_migration_compat.go`. From 80417af2d2a9352565a015cb16b68478d2d626fb Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Thu, 16 Apr 2026 11:43:48 +0200 Subject: [PATCH 568/647] chore: remove clicompat help templates and use urfave/cli defaults (#1296) - fixup version command to have better help formatting with urfave defaults --- cmd/src/run_migration_compat.go | 2 +- cmd/src/version.go | 13 +++++----- internal/clicompat/help.go | 43 --------------------------------- 3 files changed, 8 insertions(+), 50 deletions(-) diff --git a/cmd/src/run_migration_compat.go b/cmd/src/run_migration_compat.go index c50f2cd34a..399cab11f6 100644 --- a/cmd/src/run_migration_compat.go +++ b/cmd/src/run_migration_compat.go @@ -50,7 +50,7 @@ func migratedRootCommand() *cli.Command { commands = append(commands, migratedCommands[name]) } - return clicompat.WrapRoot(&cli.Command{ + return clicompat.Wrap(&cli.Command{ Name: "src", HideVersion: true, Commands: commands, diff --git a/cmd/src/version.go b/cmd/src/version.go index 6186159368..646ac6b6e1 100644 --- a/cmd/src/version.go +++ b/cmd/src/version.go @@ -17,20 +17,21 @@ import ( "github.com/urfave/cli/v3" ) -const versionExamples = `Examples: +const versionExamples = ` +Display and compare the src-cli version against the recommended version for your instance - Get the src-cli version and the Sourcegraph instance's recommended version: +Examples: - $ src version +Get the src-cli version and the Sourcegraph instance's recommended version: + +$ src version ` var versionCommand = clicompat.Wrap(&cli.Command{ Name: "version", - Usage: "display and compare the src-cli version against the recommended version for your instance", UsageText: "src version [options]", OnUsageError: clicompat.OnUsageError, - Description: ` -` + versionExamples, + Description: versionExamples, Flags: clicompat.WithAPIFlags( &cli.BoolFlag{ Name: "client-only", diff --git a/internal/clicompat/help.go b/internal/clicompat/help.go index f458ad6fbb..02cf15b66b 100644 --- a/internal/clicompat/help.go +++ b/internal/clicompat/help.go @@ -2,55 +2,12 @@ package clicompat import "github.com/urfave/cli/v3" -// LegacyCommandHelpTemplate formats leaf command help in a style closer to the -// existing flag.FlagSet-based help output. -const LegacyCommandHelpTemplate = `Usage of '{{.FullName}}': -{{range .VisibleFlags}} {{printf " -%s\n\t\t\t\t%s\n" .Name .Usage}}{{end}}{{if .Description}} - {{trim .Description}} -{{end}} -` - -// LegacyRootCommandHelpTemplate formats root command help while preserving a -// command's UsageText when it is provided. -const LegacyRootCommandHelpTemplate = `{{if .UsageText}}{{trim .UsageText}} -{{else}}Usage of '{{.FullName}}': -{{end}}{{if .VisibleFlags}}{{range .VisibleFlags}}{{println .}}{{end}}{{end}}{{if .VisibleCommands}} -{{range .VisibleCommands}}{{printf "\t%s\t%s\n" .Name .Usage}}{{end}}{{end}}{{if .Description}} -{{trim .Description}} -{{end}} -` - // Wrap sets common options on a sub commands to ensure consistency for help and error handling func Wrap(cmd *cli.Command) *cli.Command { if cmd == nil { return nil } - cmd.CustomHelpTemplate = LegacyCommandHelpTemplate - cmd.OnUsageError = OnUsageError - return cmd -} - -// WrapRoot sets common options on a root command to ensure consistency for help and error handling -func WrapRoot(cmd *cli.Command) *cli.Command { - if cmd == nil { - return nil - } - - cmd.CustomRootCommandHelpTemplate = LegacyRootCommandHelpTemplate cmd.OnUsageError = OnUsageError return cmd } - -// WithLegacyHelp applies both root and leaf legacy help templates. -func WithLegacyHelp(cmd *cli.Command) *cli.Command { - if cmd == nil { - return nil - } - - cmd.CustomHelpTemplate = LegacyCommandHelpTemplate - cmd.CustomRootCommandHelpTemplate = LegacyRootCommandHelpTemplate - cmd.OnUsageError = OnUsageError - - return cmd -} From 462bb96633771784012b0bbc2793e99962dfe4f2 Mon Sep 17 00:00:00 2001 From: Michael Bahr <1830132+bahrmichael@users.noreply.github.com> Date: Thu, 16 Apr 2026 15:20:07 +0200 Subject: [PATCH 569/647] feat(abc): src abc variables command (#1293) This PR introduces a src abc variables command for setting and deleting variables on workflow instances using the update variables api from Sourcegraph. --- cmd/src/abc.go | 29 +++++ cmd/src/abc_variables_delete.go | 76 +++++++++++++ cmd/src/abc_variables_delete_test.go | 71 ++++++++++++ cmd/src/abc_variables_set.go | 155 +++++++++++++++++++++++++++ cmd/src/abc_variables_set_test.go | 120 +++++++++++++++++++++ cmd/src/main.go | 1 + cmd/src/run_migration_compat.go | 1 + internal/clicompat/help.go | 25 ++++- 8 files changed, 477 insertions(+), 1 deletion(-) create mode 100644 cmd/src/abc.go create mode 100644 cmd/src/abc_variables_delete.go create mode 100644 cmd/src/abc_variables_delete_test.go create mode 100644 cmd/src/abc_variables_set.go create mode 100644 cmd/src/abc_variables_set_test.go diff --git a/cmd/src/abc.go b/cmd/src/abc.go new file mode 100644 index 0000000000..5d2b019556 --- /dev/null +++ b/cmd/src/abc.go @@ -0,0 +1,29 @@ +package main + +import ( + "context" + + "github.com/sourcegraph/src-cli/internal/clicompat" + "github.com/urfave/cli/v3" +) + +var abcCommand = clicompat.Wrap(&cli.Command{ + Name: "abc", + Usage: "manages agentic batch changes", + Commands: []*cli.Command{ + clicompat.Wrap(&cli.Command{ + Name: "variables", + Usage: "manage workflow instance variables", + Commands: []*cli.Command{ + abcVariablesSetCommand, + abcVariablesDeleteCommand, + }, + Action: func(ctx context.Context, cmd *cli.Command) error { + return cli.ShowSubcommandHelp(cmd) + }, + }), + }, + Action: func(ctx context.Context, cmd *cli.Command) error { + return cli.ShowSubcommandHelp(cmd) + }, +}) diff --git a/cmd/src/abc_variables_delete.go b/cmd/src/abc_variables_delete.go new file mode 100644 index 0000000000..764d57991c --- /dev/null +++ b/cmd/src/abc_variables_delete.go @@ -0,0 +1,76 @@ +package main + +import ( + "context" + "fmt" + "io" + "slices" + + "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/clicompat" + "github.com/sourcegraph/src-cli/internal/cmderrors" + "github.com/urfave/cli/v3" +) + +var abcVariablesDeleteCommand = clicompat.Wrap(&cli.Command{ + Name: "delete", + Usage: "Delete variables on a workflow instance", + UsageText: "src abc variables delete [options] [ ...]", + DisableSliceFlagSeparator: true, + Description: ` +Delete workflow instance variables + +Examples: + + Delete a variable from a workflow instance: + + $ src abc variables delete QWdlbnRpY1dvcmtmbG93SW5zdGFuY2U6MQ== approval + + Delete multiple variables in one request: + + $ src abc variables delete QWdlbnRpY1dvcmtmbG93SW5zdGFuY2U6MQ== --var approval --var checkpoints +`, + Flags: clicompat.WithAPIFlags( + &cli.StringSliceFlag{ + Name: "var", + Usage: "Variable name to delete. Repeat for multiple names.", + }, + ), + Action: func(ctx context.Context, cmd *cli.Command) error { + if !cmd.Args().Present() { + return cmderrors.Usage("must provide a workflow instance ID") + } + + instanceID := cmd.Args().First() + client := cfg.apiClient(clicompat.APIFlagsFromCmd(cmd), cmd.Writer) + variableNames := append(cmd.Args().Tail(), cmd.StringSlice("var")...) + + return runABCVariablesDelete(ctx, client, instanceID, variableNames, cmd.Writer) + }, +}) + +func runABCVariablesDelete(ctx context.Context, client api.Client, instanceID string, variableNames []string, output io.Writer) error { + if len(variableNames) == 0 { + return cmderrors.Usage("must provide at least one variable name") + } + + if slices.Contains(variableNames, "") { + return cmderrors.Usage("variable names must not be empty") + } + + variables := make([]map[string]string, 0, len(variableNames)) + for _, key := range variableNames { + variables = append(variables, map[string]string{ + "key": key, + "value": "null", + }) + } + + ok, err := updateABCWorkflowInstanceVariables(ctx, client, instanceID, variables) + if err != nil || !ok { + return err + } + + _, err = fmt.Fprintf(output, "Removed variables %q from workflow instance %q.\n", variableNames, instanceID) + return err +} diff --git a/cmd/src/abc_variables_delete_test.go b/cmd/src/abc_variables_delete_test.go new file mode 100644 index 0000000000..fdad13f72e --- /dev/null +++ b/cmd/src/abc_variables_delete_test.go @@ -0,0 +1,71 @@ +package main + +import ( + "bytes" + "context" + "io" + "testing" + + mockapi "github.com/sourcegraph/src-cli/internal/api/mock" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" +) + +func TestRunABCVariablesDelete(t *testing.T) { + t.Parallel() + + client := new(mockapi.Client) + request := &mockapi.Request{Response: `{"data":{"updateAgenticWorkflowInstanceVariables":{"id":"workflow"}}}`} + output := &bytes.Buffer{} + variableNames := []string{"approval", "checkpoints", "prompt"} + + client.On("NewRequest", updateABCWorkflowInstanceVariablesMutation, map[string]any{ + "instanceID": "QWdlbnRpY1dvcmtmbG93SW5zdGFuY2U6MQ==", + "variables": []map[string]string{ + {"key": "approval", "value": "null"}, + {"key": "checkpoints", "value": "null"}, + {"key": "prompt", "value": "null"}, + }, + }).Return(request).Once() + request.On("Do", context.Background(), mock.Anything).Return(true, nil).Once() + + err := runABCVariablesDelete(context.Background(), client, "QWdlbnRpY1dvcmtmbG93SW5zdGFuY2U6MQ==", variableNames, output) + require.NoError(t, err) + require.Equal(t, "Removed variables [\"approval\" \"checkpoints\" \"prompt\"] from workflow instance \"QWdlbnRpY1dvcmtmbG93SW5zdGFuY2U6MQ==\".\n", output.String()) + + client.AssertExpectations(t) + request.AssertExpectations(t) +} + +func TestRunABCVariablesDeleteRejectsEmptyVariableName(t *testing.T) { + t.Parallel() + + err := runABCVariablesDelete(context.Background(), nil, "QWdlbnRpY1dvcmtmbG93SW5zdGFuY2U6MQ==", []string{"approval", ""}, io.Discard) + require.ErrorContains(t, err, "variable names must not be empty") +} + +func TestRunABCVariablesDeleteSuppressesSuccessMessageWhenRequestDoesNotExecute(t *testing.T) { + t.Parallel() + + client := new(mockapi.Client) + request := &mockapi.Request{} + output := &bytes.Buffer{} + variableNames := []string{"approval", "checkpoints", "prompt"} + + client.On("NewRequest", updateABCWorkflowInstanceVariablesMutation, map[string]any{ + "instanceID": "QWdlbnRpY1dvcmtmbG93SW5zdGFuY2U6MQ==", + "variables": []map[string]string{ + {"key": "approval", "value": "null"}, + {"key": "checkpoints", "value": "null"}, + {"key": "prompt", "value": "null"}, + }, + }).Return(request).Once() + request.On("Do", context.Background(), mock.Anything).Return(false, nil).Once() + + err := runABCVariablesDelete(context.Background(), client, "QWdlbnRpY1dvcmtmbG93SW5zdGFuY2U6MQ==", variableNames, output) + require.NoError(t, err) + require.Empty(t, output.String()) + + client.AssertExpectations(t) + request.AssertExpectations(t) +} diff --git a/cmd/src/abc_variables_set.go b/cmd/src/abc_variables_set.go new file mode 100644 index 0000000000..ea5d43c5a8 --- /dev/null +++ b/cmd/src/abc_variables_set.go @@ -0,0 +1,155 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "sort" + "strings" + + "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/clicompat" + "github.com/sourcegraph/src-cli/internal/cmderrors" + "github.com/urfave/cli/v3" +) + +const updateABCWorkflowInstanceVariablesMutation = `mutation UpdateAgenticWorkflowInstanceVariables( + $instanceID: ID!, + $variables: [AgenticWorkflowInstanceVariableInput!]!, +) { + updateAgenticWorkflowInstanceVariables(instanceID: $instanceID, variables: $variables) { + id + } +}` + +var abcVariablesSetCommand = clicompat.Wrap(&cli.Command{ + Name: "set", + UsageText: "src abc variables set [options] [= ...]", + Usage: "Set variables on a workflow instance", + DisableSliceFlagSeparator: true, + Description: ` +Set workflow instance variables + +Examples: + + Set a string variable on a workflow instance: + + $ src abc variables set QWdlbnRpY1dvcmtmbG93SW5zdGFuY2U6MQ== prompt="tighten the review criteria" + + Set multiple variables in one request: + + $ src abc variables set QWdlbnRpY1dvcmtmbG93SW5zdGFuY2U6MQ== --var prompt="tighten the review criteria" --var checkpoints='[1,2,3]' + + Set a structured JSON value: + + $ src abc variables set QWdlbnRpY1dvcmtmbG93SW5zdGFuY2U6MQ== checkpoints='[1,2,3]' + +NOTE: Values are interpreted as JSON literals when valid. Otherwise they are sent as plain strings. +`, + Flags: clicompat.WithAPIFlags( + &cli.StringSliceFlag{ + Name: "var", + Usage: "Variable assignment in = form. Repeat to set multiple variables.", + }, + ), + Action: func(ctx context.Context, cmd *cli.Command) error { + if !cmd.Args().Present() { + return cmderrors.Usage("must provide a workflow instance ID") + } + + instanceID := cmd.Args().First() + client := cfg.apiClient(clicompat.APIFlagsFromCmd(cmd), cmd.Writer) + abcVariables, err := parseABCVariables(cmd.Args().Tail(), cmd.StringSlice("var")) + if err != nil { + return err + } + return runABCVariablesSet(ctx, client, instanceID, abcVariables, cmd.Writer) + }, +}) + +func parseABCVariables(positional []string, flagged []string) (map[string]string, error) { + rawVariables := append(positional, flagged...) + if len(rawVariables) == 0 { + return nil, cmderrors.Usage("must provide at least one variable assignment") + } + + variables := make(map[string]string, len(rawVariables)) + for _, v := range rawVariables { + name, rawValue, ok := strings.Cut(v, "=") + if !ok || name == "" { + return nil, cmderrors.Usagef("invalid variable assignment %q: must be in = form", v) + } + + value, remove, err := marshalABCVariableValue(rawValue) + if err != nil { + return nil, err + } + if remove { + return nil, cmderrors.Usagef("invalid variable assignment %q: use 'src abc variables delete %s' to remove a variable", rawValue, name) + } + + variables[name] = value + } + + return variables, nil +} + +func runABCVariablesSet(ctx context.Context, client api.Client, instanceID string, variables map[string]string, output io.Writer) error { + graphqlVariables := make([]map[string]string, 0, len(variables)) + keys := make([]string, 0, len(variables)) + for k := range variables { + keys = append(keys, k) + } + sort.Strings(keys) + + for _, k := range keys { + graphqlVariables = append(graphqlVariables, map[string]string{ + "key": k, + "value": variables[k], + }) + } + + ok, err := updateABCWorkflowInstanceVariables(ctx, client, instanceID, graphqlVariables) + if err != nil || !ok { + return err + } + + _, err = fmt.Fprintf(output, "Updated %d variables on workflow instance %q.\n", len(variables), instanceID) + return err +} + +func updateABCWorkflowInstanceVariables(ctx context.Context, client api.Client, instanceID string, variables []map[string]string) (bool, error) { + var result struct { + UpdateAgenticWorkflowInstanceVariables struct { + ID string `json:"id"` + } `json:"updateAgenticWorkflowInstanceVariables"` + } + if ok, err := client.NewRequest(updateABCWorkflowInstanceVariablesMutation, map[string]any{ + "instanceID": instanceID, + "variables": variables, + }).Do(ctx, &result); err != nil || !ok { + return ok, err + } + + return true, nil +} + +func marshalABCVariableValue(raw string) (value string, remove bool, err error) { + // Try to compact valid JSON literals first so numbers, arrays, and objects are sent unchanged. + // A bare null is detected separately so the CLI can require the explicit delete command. + // If compacting doesn't work for the given value, fall back to string encoding. + var compact bytes.Buffer + if err := json.Compact(&compact, []byte(raw)); err == nil { + value := compact.String() + return value, value == "null", nil + } + + encoded, err := json.Marshal(raw) + if err != nil { + return "", false, err + } + + return string(encoded), false, nil +} diff --git a/cmd/src/abc_variables_set_test.go b/cmd/src/abc_variables_set_test.go new file mode 100644 index 0000000000..744234161e --- /dev/null +++ b/cmd/src/abc_variables_set_test.go @@ -0,0 +1,120 @@ +package main + +import ( + "bytes" + "context" + "testing" + + "github.com/google/go-cmp/cmp" + mockapi "github.com/sourcegraph/src-cli/internal/api/mock" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + "github.com/urfave/cli/v3" +) + +// If we were to do a json marshalling roundtrip, it may break large integer literals. +// This test is here to demonstrate that the compaction approach is working well. +func TestMarshalABCVariableValuePreservesLargeIntegerLiteral(t *testing.T) { + t.Parallel() + + value, remove, err := marshalABCVariableValue("9007199254740993") + if err != nil { + t.Fatalf("marshalABCVariableValue returned error: %v", err) + } + if remove { + t.Fatal("marshalABCVariableValue unexpectedly marked value for removal") + } + if value != "9007199254740993" { + t.Fatalf("marshalABCVariableValue = %q, want %q", value, "9007199254740993") + } +} + +func TestParseABCVariables(t *testing.T) { + t.Parallel() + + variables, err := parseABCVariables( + []string{"prompt=tighten the review criteria", `title="test"`}, + []string{"checkpoints=[1,2,3]"}, + ) + if err != nil { + t.Fatalf("parseABCVariables returned error: %v", err) + } + + if diff := cmp.Diff(variables, map[string]string{ + "prompt": "\"tighten the review criteria\"", + "title": "\"test\"", + "checkpoints": "[1,2,3]", + }); diff != "" { + t.Errorf("err: %v", diff) + } +} + +func TestABCVariablesSetVarFlagPreservesCommas(t *testing.T) { + t.Parallel() + + var got []string + cmd := &cli.Command{ + Name: "set", + DisableSliceFlagSeparator: abcVariablesSetCommand.DisableSliceFlagSeparator, + Flags: []cli.Flag{ + &cli.StringSliceFlag{Name: "var"}, + }, + Action: func(ctx context.Context, cmd *cli.Command) error { + got = cmd.StringSlice("var") + return nil + }, + } + + err := cmd.Run(context.Background(), []string{"set", "--var", "checkpoints=[1,2,3]"}) + require.NoError(t, err) + require.Equal(t, []string{"checkpoints=[1,2,3]"}, got) +} + +func TestRunABCVariablesSet(t *testing.T) { + t.Parallel() + + client := new(mockapi.Client) + request := &mockapi.Request{Response: `{"data":{"updateAgenticWorkflowInstanceVariables":{"id":"workflow"}}}`} + output := &bytes.Buffer{} + variables := map[string]string{ + "prompt": `"tighten the review criteria"`, + "checkpoints": "[1,2,3]", + } + + client.On("NewRequest", updateABCWorkflowInstanceVariablesMutation, map[string]any{ + "instanceID": "QWdlbnRpY1dvcmtmbG93SW5zdGFuY2U6MQ==", + "variables": []map[string]string{ + {"key": "checkpoints", "value": "[1,2,3]"}, + {"key": "prompt", "value": `"tighten the review criteria"`}, + }, + }).Return(request).Once() + request.On("Do", context.Background(), mock.Anything).Return(true, nil).Once() + + err := runABCVariablesSet(context.Background(), client, "QWdlbnRpY1dvcmtmbG93SW5zdGFuY2U6MQ==", variables, output) + require.NoError(t, err) + require.Equal(t, "Updated 2 variables on workflow instance \"QWdlbnRpY1dvcmtmbG93SW5zdGFuY2U6MQ==\".\n", output.String()) + + client.AssertExpectations(t) + request.AssertExpectations(t) +} + +func TestRunABCVariablesSetSuppressesSuccessMessageWhenRequestDoesNotExecute(t *testing.T) { + t.Parallel() + + client := new(mockapi.Client) + request := &mockapi.Request{} + output := &bytes.Buffer{} + + client.On("NewRequest", updateABCWorkflowInstanceVariablesMutation, map[string]any{ + "instanceID": "QWdlbnRpY1dvcmtmbG93SW5zdGFuY2U6MQ==", + "variables": []map[string]string{{"key": "prompt", "value": `"tighten the review criteria"`}}, + }).Return(request).Once() + request.On("Do", context.Background(), mock.Anything).Return(false, nil).Once() + + err := runABCVariablesSet(context.Background(), client, "QWdlbnRpY1dvcmtmbG93SW5zdGFuY2U6MQ==", map[string]string{"prompt": `"tighten the review criteria"`}, output) + require.NoError(t, err) + require.Empty(t, output.String()) + + client.AssertExpectations(t) + request.AssertExpectations(t) +} diff --git a/cmd/src/main.go b/cmd/src/main.go index 8499d6465f..68478c9276 100644 --- a/cmd/src/main.go +++ b/cmd/src/main.go @@ -50,6 +50,7 @@ The options are: The commands are: + abc manages agentic batch changes auth authentication helper commands api interacts with the Sourcegraph GraphQL API batch manages batch changes diff --git a/cmd/src/run_migration_compat.go b/cmd/src/run_migration_compat.go index 399cab11f6..36d4fae9f0 100644 --- a/cmd/src/run_migration_compat.go +++ b/cmd/src/run_migration_compat.go @@ -16,6 +16,7 @@ import ( ) var migratedCommands = map[string]*cli.Command{ + "abc": abcCommand, "version": versionCommand, } diff --git a/internal/clicompat/help.go b/internal/clicompat/help.go index 02cf15b66b..fa9235572d 100644 --- a/internal/clicompat/help.go +++ b/internal/clicompat/help.go @@ -1,6 +1,13 @@ package clicompat -import "github.com/urfave/cli/v3" +import ( + "context" + "fmt" + + "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/src-cli/internal/cmderrors" + "github.com/urfave/cli/v3" +) // Wrap sets common options on a sub commands to ensure consistency for help and error handling func Wrap(cmd *cli.Command) *cli.Command { @@ -9,5 +16,21 @@ func Wrap(cmd *cli.Command) *cli.Command { } cmd.OnUsageError = OnUsageError + cmd.Action = wrapWithHelpOnUsageError(cmd.Action) return cmd } + +func wrapWithHelpOnUsageError(action cli.ActionFunc) cli.ActionFunc { + if action == nil { + return nil + } + + return func(ctx context.Context, cmd *cli.Command) error { + err := action(ctx, cmd) + if err != nil && errors.HasType[*cmderrors.UsageError](err) { + _, _ = fmt.Fprintf(cmd.Root().ErrWriter, "error: %s\n---\n", err) + cli.DefaultPrintHelp(cmd.Root().ErrWriter, cmd.CustomHelpTemplate, cmd) + } + return err + } +} From b071e59d2dbe8b6d273b50f64fdf25c817c08295 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Fri, 17 Apr 2026 13:15:19 +0200 Subject: [PATCH 570/647] migrate src auth to urfave/cli (#1298) --- cmd/src/auth.go | 51 +++++++++++++------------ cmd/src/auth_token.go | 68 ++++++++++++++++++++------------- cmd/src/auth_token_test.go | 27 +++++++++++++ cmd/src/run_migration_compat.go | 1 + 4 files changed, 96 insertions(+), 51 deletions(-) diff --git a/cmd/src/auth.go b/cmd/src/auth.go index eff5f4bbec..5c843ad700 100644 --- a/cmd/src/auth.go +++ b/cmd/src/auth.go @@ -1,37 +1,38 @@ package main import ( - "flag" - "fmt" -) + "context" -var authCommands commander + "github.com/sourcegraph/src-cli/internal/clicompat" + "github.com/urfave/cli/v3" +) -func init() { - usage := `'src auth' provides authentication-related helper commands. +const authExamples = ` +Authentication-related helper commands. -Usage: +Examples: - src auth command [command options] +Print the active auth token: -The commands are: +$ src auth token +sgp_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx - token prints the current authentication token or Authorization header +Print the current Authorization header: -Use "src auth [command] -h" for more information about a command. +$ src auth token --header +Authorization: token sgp_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ` - flagSet := flag.NewFlagSet("auth", flag.ExitOnError) - handler := func(args []string) error { - authCommands.run(flagSet, "src auth", usage, args) - return nil - } - - commands = append(commands, &command{ - flagSet: flagSet, - handler: handler, - usageFunc: func() { - fmt.Println(usage) - }, - }) -} +var authCommand = clicompat.Wrap(&cli.Command{ + Name: "auth", + Usage: "authentication helper commands", + UsageText: "src auth [command options]", + Description: authExamples, + HideVersion: true, + Commands: []*cli.Command{ + authTokenCommand, + }, + Action: func(ctx context.Context, cmd *cli.Command) error { + return cli.ShowSubcommandHelp(cmd) + }, +}) diff --git a/cmd/src/auth_token.go b/cmd/src/auth_token.go index fdd6d03a42..9ae9c75330 100644 --- a/cmd/src/auth_token.go +++ b/cmd/src/auth_token.go @@ -2,12 +2,13 @@ package main import ( "context" - "flag" "fmt" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/src-cli/internal/clicompat" "github.com/sourcegraph/src-cli/internal/oauth" + "github.com/urfave/cli/v3" ) var ( @@ -21,37 +22,52 @@ type oauthTokenRefresher interface { GetToken(ctx context.Context) (oauth.Token, error) } -func init() { - flagSet := flag.NewFlagSet("token", flag.ExitOnError) - header := flagSet.Bool("header", false, "print the token as an Authorization header") - usageFunc := func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src auth token':\n\n") - fmt.Fprintf(flag.CommandLine.Output(), "Print the current authentication token.\n") - fmt.Fprintf(flag.CommandLine.Output(), "Use --header to print a complete Authorization header instead.\n\n") - flagSet.PrintDefaults() - } +const authTokenExamples = ` +Print the current authentication token. - handler := func(args []string) error { - if err := flagSet.Parse(args); err != nil { - return err - } +Use --header to print a complete Authorization header instead. + +Examples: + +Raw token output: + +$ src auth token +sgp_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx + +Authorization header output: - token, err := resolveAuthToken(context.Background(), cfg) +$ src auth token --header +Authorization: token sgp_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx + +If you are authenticated with OAuth instead of SRC_ACCESS_TOKEN, the header uses the Bearer scheme: + +$ src auth token --header +Authorization: Bearer eyJhbGciOi... +` + +var authTokenCommand = clicompat.Wrap(&cli.Command{ + Name: "token", + Usage: "prints the current authentication token or Authorization header", + UsageText: "src auth token [options]", + Description: authTokenExamples, + HideVersion: true, + Flags: []cli.Flag{ + &cli.BoolFlag{ + Name: "header", + Usage: "print the token as an Authorization header", + }, + }, + Action: func(ctx context.Context, cmd *cli.Command) error { + token, err := resolveAuthToken(ctx, cfg) if err != nil { return err } - token = formatAuthTokenOutput(token, cfg.AuthMode(), *header) - fmt.Println(token) - return nil - } - - authCommands = append(authCommands, &command{ - flagSet: flagSet, - handler: handler, - usageFunc: usageFunc, - }) -} + token = formatAuthTokenOutput(token, cfg.AuthMode(), cmd.Bool("header")) + _, err = fmt.Fprintln(cmd.Writer, token) + return err + }, +}) func resolveAuthToken(ctx context.Context, cfg *config) (string, error) { if err := cfg.requireCIAccessToken(); err != nil { diff --git a/cmd/src/auth_token_test.go b/cmd/src/auth_token_test.go index c351d06d75..1a5bfbcbaa 100644 --- a/cmd/src/auth_token_test.go +++ b/cmd/src/auth_token_test.go @@ -1,6 +1,7 @@ package main import ( + "bytes" "context" "fmt" "net/url" @@ -125,6 +126,32 @@ func TestResolveAuthToken(t *testing.T) { }) } +func TestAuthTokenCommand(t *testing.T) { + reset := stubAuthTokenDependencies(t) + defer reset() + + prevCfg := cfg + defer func() { cfg = prevCfg }() + + cfg = &config{ + accessToken: "access-token", + endpointURL: mustParseURL(t, "https://example.com"), + } + + var out bytes.Buffer + cmd := *authTokenCommand + cmd.Writer = &out + cmd.ErrWriter = &out + + err := cmd.Run(context.Background(), []string{"token", "--header"}) + if err != nil { + t.Fatal(err) + } + if out.String() != "Authorization: token access-token\n" { + t.Fatalf("output = %q, want %q", out.String(), "Authorization: token access-token\n") + } +} + func TestFormatAuthTokenOutput(t *testing.T) { tests := []struct { name string diff --git a/cmd/src/run_migration_compat.go b/cmd/src/run_migration_compat.go index 36d4fae9f0..fde21bd5ee 100644 --- a/cmd/src/run_migration_compat.go +++ b/cmd/src/run_migration_compat.go @@ -17,6 +17,7 @@ import ( var migratedCommands = map[string]*cli.Command{ "abc": abcCommand, + "auth": authCommand, "version": versionCommand, } From fd610544b7abb7177c28729008c4bab1d61def81 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Tue, 21 Apr 2026 11:53:54 +0200 Subject: [PATCH 571/647] fix/login: override config endpoint if endpoint positional argument is given (#1300) * determine if we are using the Default endpoint or not * move notifce of config file deprecation earlier * Move endpoint validation to happen before running loginCmd - update config endpointURL if endpointURL is set either as a flag or positional argument - warn the user about endpoint conflict or that the default endpoint is being used * fix tests and remove unused login funcs * move DefaultEndpointConfigured to be attr on struct * fix tests --- cmd/src/login.go | 80 +++++++++++++++++++-------------------- cmd/src/login_test.go | 80 ++++++--------------------------------- cmd/src/login_validate.go | 14 ------- cmd/src/main.go | 20 ++++++---- cmd/src/main_test.go | 40 ++++++++++++-------- 5 files changed, 85 insertions(+), 149 deletions(-) diff --git a/cmd/src/login.go b/cmd/src/login.go index 9818c245b6..889994af51 100644 --- a/cmd/src/login.go +++ b/cmd/src/login.go @@ -50,25 +50,43 @@ Examples: return err } - var loginEndpointURL *url.URL + if cfg.configFilePath != "" { + fmt.Fprintln(os.Stderr) + fmt.Fprintf(os.Stderr, "⚠️ Warning: Configuring src with a JSON file is deprecated. Please migrate to using the env vars SRC_ENDPOINT, SRC_ACCESS_TOKEN, and SRC_PROXY instead, and then remove %s. See https://github.com/sourcegraph/src-cli#readme for more information.\n", cfg.configFilePath) + } + if flagSet.NArg() >= 1 { arg := flagSet.Arg(0) - u, err := parseEndpoint(arg) + loginEndpointURL, err := parseEndpoint(arg) if err != nil { return cmderrors.Usage(fmt.Sprintf("invalid endpoint URL: %s", arg)) } - loginEndpointURL = u + + hasEndpointURLConflict := cfg.endpointURL.String() != loginEndpointURL.String() + + if hasEndpointURLConflict { + // If the default is configured it means SRC_ENDPOINT is not set + if cfg.usingDefaultEndpoint { + fmt.Fprintf(os.Stderr, "⚠️ Warning: No SRC_ENDPOINT is configured in the environment. Logging in using %q.\n", loginEndpointURL) + fmt.Fprintf(os.Stderr, "\n💡 Tip: To use this endpoint in your shell, run:\n\n export SRC_ENDPOINT=%s\n\nNOTE: By default src will use %q if SRC_ENDPOINT is not set.\n", loginEndpointURL, SGDotComEndpoint) + } else { + fmt.Fprintf(os.Stderr, "⚠️ Warning: Logging into %s instead of the configured endpoint %s.\n", loginEndpointURL, cfg.endpointURL) + fmt.Fprintf(os.Stderr, "\n💡 Tip: To use this endpoint in your shell, run:\n\n export SRC_ENDPOINT=%s\n\n", loginEndpointURL) + } + } + + // An explicit endpoint on the CLI overrides the configured endpoint for this login. + cfg.endpointURL = loginEndpointURL } client := cfg.apiClient(apiFlags, io.Discard) return loginCmd(context.Background(), loginParams{ - cfg: cfg, - client: client, - out: os.Stdout, - apiFlags: apiFlags, - oauthClient: oauth.NewClient(oauth.DefaultClientID), - loginEndpointURL: loginEndpointURL, + cfg: cfg, + client: client, + out: os.Stdout, + apiFlags: apiFlags, + oauthClient: oauth.NewClient(oauth.DefaultClientID), }) } @@ -80,56 +98,34 @@ Examples: } type loginParams struct { - cfg *config - client api.Client - out io.Writer - apiFlags *api.Flags - oauthClient oauth.Client - loginEndpointURL *url.URL + cfg *config + client api.Client + out io.Writer + apiFlags *api.Flags + oauthClient oauth.Client } type loginFlow func(context.Context, loginParams) error -type loginFlowKind int - -const ( - loginFlowOAuth loginFlowKind = iota - loginFlowMissingAuth - loginFlowEndpointConflict - loginFlowValidate -) - func loginCmd(ctx context.Context, p loginParams) error { if err := p.cfg.requireCIAccessToken(); err != nil { return err } - if p.cfg.configFilePath != "" { - fmt.Fprintln(p.out) - fmt.Fprintf(p.out, "⚠️ Warning: Configuring src with a JSON file is deprecated. Please migrate to using the env vars SRC_ENDPOINT, SRC_ACCESS_TOKEN, and SRC_PROXY instead, and then remove %s. See https://github.com/sourcegraph/src-cli#readme for more information.\n", p.cfg.configFilePath) - } - - _, flow := selectLoginFlow(p) + flow := selectLoginFlow(p) if err := flow(ctx, p); err != nil { return err } - fmt.Fprintf(p.out, "\n💡 Tip: To use this endpoint in your shell, run:\n\n export SRC_ENDPOINT=%s\n\n", p.cfg.endpointURL) return nil } // selectLoginFlow decides what login flow to run based on configured AuthMode. -func selectLoginFlow(p loginParams) (loginFlowKind, loginFlow) { - if p.loginEndpointURL != nil && p.loginEndpointURL.String() != p.cfg.endpointURL.String() { - return loginFlowEndpointConflict, runEndpointConflictLogin - } - switch p.cfg.AuthMode() { - case AuthModeOAuth: - return loginFlowOAuth, runOAuthLogin - case AuthModeAccessToken: - return loginFlowValidate, runValidatedLogin - default: - return loginFlowMissingAuth, runMissingAuthLogin + +func selectLoginFlow(p loginParams) loginFlow { + if p.cfg.AuthMode() == AuthModeAccessToken { + return runValidatedLogin } + return runOAuthLogin } func printLoginProblem(out io.Writer, problem string) { diff --git a/cmd/src/login_test.go b/cmd/src/login_test.go index 1250d1adb9..5dba8b464b 100644 --- a/cmd/src/login_test.go +++ b/cmd/src/login_test.go @@ -26,33 +26,22 @@ func mustParseURL(t *testing.T, raw string) *url.URL { } func TestLogin(t *testing.T) { - check := func(t *testing.T, cfg *config, endpointArgURL *url.URL) (output string, err error) { + check := func(t *testing.T, cfg *config) (output string, err error) { t.Helper() var out bytes.Buffer err = loginCmd(context.Background(), loginParams{ - cfg: cfg, - client: cfg.apiClient(nil, io.Discard), - out: &out, - oauthClient: fakeOAuthClient{startErr: fmt.Errorf("oauth unavailable")}, - loginEndpointURL: endpointArgURL, + cfg: cfg, + client: cfg.apiClient(nil, io.Discard), + out: &out, + oauthClient: fakeOAuthClient{startErr: fmt.Errorf("oauth unavailable")}, }) return strings.TrimSpace(out.String()), err } - t.Run("different endpoint in config vs. arg", func(t *testing.T) { - out, err := check(t, &config{endpointURL: &url.URL{Scheme: "https", Host: "example.com"}}, &url.URL{Scheme: "https", Host: "sourcegraph.example.com"}) - if err == nil { - t.Fatal(err) - } - if !strings.Contains(out, "The configured endpoint is https://example.com, not https://sourcegraph.example.com.") { - t.Errorf("got output %q, want configured endpoint error", out) - } - }) - t.Run("no access token triggers oauth flow", func(t *testing.T) { u := &url.URL{Scheme: "https", Host: "example.com"} - out, err := check(t, &config{endpointURL: u}, u) + out, err := check(t, &config{endpointURL: u}) if err == nil { t.Fatal(err) } @@ -63,7 +52,7 @@ func TestLogin(t *testing.T) { t.Run("CI requires access token", func(t *testing.T) { u := &url.URL{Scheme: "https", Host: "example.com"} - out, err := check(t, &config{endpointURL: u, inCI: true}, u) + out, err := check(t, &config{endpointURL: u, inCI: true}) if err != errCIAccessTokenRequired { t.Fatalf("err = %v, want %v", err, errCIAccessTokenRequired) } @@ -72,20 +61,6 @@ func TestLogin(t *testing.T) { } }) - t.Run("warning when using config file", func(t *testing.T) { - endpoint := &url.URL{Scheme: "https", Host: "example.com"} - out, err := check(t, &config{endpointURL: endpoint, configFilePath: "f"}, endpoint) - if err != cmderrors.ExitCode1 { - t.Fatal(err) - } - if !strings.Contains(out, "Configuring src with a JSON file is deprecated") { - t.Errorf("got output %q, want deprecation warning", out) - } - if !strings.Contains(out, "OAuth Device flow authentication failed:") { - t.Errorf("got output %q, want oauth failure output", out) - } - }) - t.Run("invalid access token", func(t *testing.T) { s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Error(w, "", http.StatusUnauthorized) @@ -93,7 +68,7 @@ func TestLogin(t *testing.T) { defer s.Close() u := mustParseURL(t, s.URL) - out, err := check(t, &config{endpointURL: u, accessToken: "x"}, u) + out, err := check(t, &config{endpointURL: u, accessToken: "x"}) if err != cmderrors.ExitCode1 { t.Fatal(err) } @@ -111,11 +86,11 @@ func TestLogin(t *testing.T) { defer s.Close() u := mustParseURL(t, s.URL) - out, err := check(t, &config{endpointURL: u, accessToken: "x"}, u) + out, err := check(t, &config{endpointURL: u, accessToken: "x"}) if err != nil { t.Fatal(err) } - wantOut := "✔︎ Authenticated as alice on $ENDPOINT\n\n\n💡 Tip: To use this endpoint in your shell, run:\n\n export SRC_ENDPOINT=$ENDPOINT" + wantOut := "✔︎ Authenticated as alice on $ENDPOINT" wantOut = strings.ReplaceAll(wantOut, "$ENDPOINT", s.URL) if out != wantOut { t.Errorf("got output %q, want %q", out, wantOut) @@ -156,7 +131,7 @@ func TestLogin(t *testing.T) { t.Fatal("expected stored oauth token to avoid device flow") } gotOut := strings.TrimSpace(out.String()) - wantOut := "✔︎ Authenticated as alice on $ENDPOINT\n\n\n✔︎ Authenticated with OAuth credentials\n\n💡 Tip: To use this endpoint in your shell, run:\n\n export SRC_ENDPOINT=$ENDPOINT" + wantOut := "✔︎ Authenticated as alice on $ENDPOINT\n\n\n✔︎ Authenticated with OAuth credentials" wantOut = strings.ReplaceAll(wantOut, "$ENDPOINT", s.URL) if gotOut != wantOut { t.Errorf("got output %q, want %q", gotOut, wantOut) @@ -192,39 +167,6 @@ func (f fakeOAuthClient) Refresh(context.Context, *oauth.Token) (*oauth.TokenRes return nil, fmt.Errorf("unexpected call to Refresh") } -func TestSelectLoginFlow(t *testing.T) { - t.Run("uses oauth flow when no access token is configured", func(t *testing.T) { - params := loginParams{ - cfg: &config{endpointURL: mustParseURL(t, "https://example.com")}, - } - - if got, _ := selectLoginFlow(params); got != loginFlowOAuth { - t.Fatalf("flow = %v, want %v", got, loginFlowOAuth) - } - }) - - t.Run("uses endpoint conflict flow when auth exists for a different endpoint", func(t *testing.T) { - params := loginParams{ - cfg: &config{endpointURL: mustParseURL(t, "https://example.com"), accessToken: "x"}, - loginEndpointURL: mustParseURL(t, "https://sourcegraph.example.com"), - } - - if got, _ := selectLoginFlow(params); got != loginFlowEndpointConflict { - t.Fatalf("flow = %v, want %v", got, loginFlowEndpointConflict) - } - }) - - t.Run("uses validation flow when auth exists for the selected endpoint", func(t *testing.T) { - params := loginParams{ - cfg: &config{endpointURL: mustParseURL(t, "https://example.com"), accessToken: "x"}, - } - - if got, _ := selectLoginFlow(params); got != loginFlowValidate { - t.Fatalf("flow = %v, want %v", got, loginFlowValidate) - } - }) -} - func TestValidateBrowserURL(t *testing.T) { tests := []struct { name string diff --git a/cmd/src/login_validate.go b/cmd/src/login_validate.go index 9aa65cdcef..095ea7ab22 100644 --- a/cmd/src/login_validate.go +++ b/cmd/src/login_validate.go @@ -11,20 +11,6 @@ import ( "github.com/sourcegraph/src-cli/internal/cmderrors" ) -func runMissingAuthLogin(_ context.Context, p loginParams) error { - fmt.Fprintln(p.out) - printLoginProblem(p.out, "No access token is configured.") - fmt.Fprintln(p.out, loginAccessTokenMessage(p.cfg.endpointURL)) - return cmderrors.ExitCode1 -} - -func runEndpointConflictLogin(_ context.Context, p loginParams) error { - fmt.Fprintln(p.out) - printLoginProblem(p.out, fmt.Sprintf("The configured endpoint is %s, not %s.", p.cfg.endpointURL, p.loginEndpointURL)) - fmt.Fprintln(p.out, loginAccessTokenMessage(p.loginEndpointURL)) - return cmderrors.ExitCode1 -} - func runValidatedLogin(ctx context.Context, p loginParams) error { return validateCurrentUser(ctx, p.client, p.out, p.cfg.endpointURL) } diff --git a/cmd/src/main.go b/cmd/src/main.go index 68478c9276..fd217ba51f 100644 --- a/cmd/src/main.go +++ b/cmd/src/main.go @@ -19,6 +19,8 @@ import ( "github.com/sourcegraph/src-cli/internal/oauth" ) +const SGDotComEndpoint = "https://sourcegraph.com" + const usageText = `src is a tool that provides access to Sourcegraph instances. For more information, see https://github.com/sourcegraph/src-cli @@ -141,13 +143,14 @@ var cfg *config // config holds the resolved configuration used at runtime. type config struct { - accessToken string - additionalHeaders map[string]string - proxyURL *url.URL - proxyPath string - configFilePath string - endpointURL *url.URL // always non-nil; defaults to https://sourcegraph.com via readConfig - inCI bool + accessToken string + additionalHeaders map[string]string + proxyURL *url.URL + proxyPath string + configFilePath string + endpointURL *url.URL // always non-nil; defaults to https://sourcegraph.com via readConfig + usingDefaultEndpoint bool + inCI bool } // configFromFile holds the config as read from the config file, @@ -270,7 +273,8 @@ func readConfig() (*config, error) { endpointStr = envEndpoint } if endpointStr == "" { - endpointStr = "https://sourcegraph.com" + endpointStr = SGDotComEndpoint + cfg.usingDefaultEndpoint = true } if envProxy != "" { proxyStr = envProxy diff --git a/cmd/src/main_test.go b/cmd/src/main_test.go index c0b29822b0..0b23cb9938 100644 --- a/cmd/src/main_test.go +++ b/cmd/src/main_test.go @@ -51,7 +51,8 @@ func TestReadConfig(t *testing.T) { Scheme: "https", Host: "sourcegraph.com", }, - additionalHeaders: map[string]string{}, + usingDefaultEndpoint: true, + additionalHeaders: map[string]string{}, }, }, { @@ -149,8 +150,9 @@ func TestReadConfig(t *testing.T) { Scheme: "https", Host: "sourcegraph.com", }, - accessToken: "abc", - additionalHeaders: map[string]string{}, + usingDefaultEndpoint: true, + accessToken: "abc", + additionalHeaders: map[string]string{}, }, }, { @@ -173,8 +175,9 @@ func TestReadConfig(t *testing.T) { Scheme: "https", Host: "sourcegraph.com", }, - accessToken: "", - proxyPath: "", + usingDefaultEndpoint: true, + accessToken: "", + proxyPath: "", proxyURL: &url.URL{ Scheme: "https", Host: "proxy.com:8080", @@ -209,9 +212,10 @@ func TestReadConfig(t *testing.T) { Scheme: "https", Host: "sourcegraph.com", }, - proxyPath: socketPath, - proxyURL: nil, - additionalHeaders: map[string]string{}, + usingDefaultEndpoint: true, + proxyPath: socketPath, + proxyURL: nil, + additionalHeaders: map[string]string{}, }, }, { @@ -222,9 +226,10 @@ func TestReadConfig(t *testing.T) { Scheme: "https", Host: "sourcegraph.com", }, - proxyPath: socketPath, - proxyURL: nil, - additionalHeaders: map[string]string{}, + usingDefaultEndpoint: true, + proxyPath: socketPath, + proxyURL: nil, + additionalHeaders: map[string]string{}, }, }, { @@ -235,7 +240,8 @@ func TestReadConfig(t *testing.T) { Scheme: "https", Host: "sourcegraph.com", }, - proxyPath: "", + usingDefaultEndpoint: true, + proxyPath: "", proxyURL: &url.URL{ Scheme: "socks5", Host: "localhost:1080", @@ -251,7 +257,8 @@ func TestReadConfig(t *testing.T) { Scheme: "https", Host: "sourcegraph.com", }, - proxyPath: "", + usingDefaultEndpoint: true, + proxyPath: "", proxyURL: &url.URL{ Scheme: "socks5h", Host: "localhost:1080", @@ -331,9 +338,10 @@ func TestReadConfig(t *testing.T) { name: "CI does not require access token during config read", envCI: "1", want: &config{ - endpointURL: &url.URL{Scheme: "https", Host: "sourcegraph.com"}, - additionalHeaders: map[string]string{}, - inCI: true, + endpointURL: &url.URL{Scheme: "https", Host: "sourcegraph.com"}, + usingDefaultEndpoint: true, + additionalHeaders: map[string]string{}, + inCI: true, }, }, { From dfaa4dd216cf45a62bfda06fe7199abf37bebb19 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Wed, 22 Apr 2026 10:10:24 +0200 Subject: [PATCH 572/647] chore: migrate login to urfave/cli (#1299) * migrate login to urfave/cli * fix merge issues --- cmd/src/login.go | 44 ++++++++++++--------------------- cmd/src/run_migration_compat.go | 1 + 2 files changed, 17 insertions(+), 28 deletions(-) diff --git a/cmd/src/login.go b/cmd/src/login.go index 889994af51..b5e1862b5f 100644 --- a/cmd/src/login.go +++ b/cmd/src/login.go @@ -2,19 +2,19 @@ package main import ( "context" - "flag" "fmt" "io" "net/url" "os" "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/clicompat" "github.com/sourcegraph/src-cli/internal/cmderrors" "github.com/sourcegraph/src-cli/internal/oauth" + "github.com/urfave/cli/v3" ) -func init() { - usage := `'src login' helps you authenticate 'src' to access a Sourcegraph instance with your user credentials. +const loginExamples = `'src login' helps you authenticate 'src' to access a Sourcegraph instance with your user credentials. Usage: @@ -35,28 +35,21 @@ Examples: $ src login https://sourcegraph.com ` - flagSet := flag.NewFlagSet("login", flag.ExitOnError) - usageFunc := func() { - fmt.Fprintln(flag.CommandLine.Output(), usage) - flagSet.PrintDefaults() - } - - var ( - apiFlags = api.NewFlags(flagSet) - ) - - handler := func(args []string) error { - if err := flagSet.Parse(args); err != nil { - return err - } - +var loginCommand = clicompat.Wrap(&cli.Command{ + Name: "login", + Usage: "authenticate to a Sourcegraph instance with your user credentials", + UsageText: "src login [command options] [SOURCEGRAPH_URL]", + Description: loginExamples, + HideVersion: true, + Flags: clicompat.WithAPIFlags(), + Action: func(ctx context.Context, cmd *cli.Command) error { if cfg.configFilePath != "" { fmt.Fprintln(os.Stderr) fmt.Fprintf(os.Stderr, "⚠️ Warning: Configuring src with a JSON file is deprecated. Please migrate to using the env vars SRC_ENDPOINT, SRC_ACCESS_TOKEN, and SRC_PROXY instead, and then remove %s. See https://github.com/sourcegraph/src-cli#readme for more information.\n", cfg.configFilePath) } - if flagSet.NArg() >= 1 { - arg := flagSet.Arg(0) + if cmd.Args().Present() { + arg := cmd.Args().First() loginEndpointURL, err := parseEndpoint(arg) if err != nil { return cmderrors.Usage(fmt.Sprintf("invalid endpoint URL: %s", arg)) @@ -79,6 +72,7 @@ Examples: cfg.endpointURL = loginEndpointURL } + apiFlags := clicompat.APIFlagsFromCmd(cmd) client := cfg.apiClient(apiFlags, io.Discard) return loginCmd(context.Background(), loginParams{ @@ -88,14 +82,8 @@ Examples: apiFlags: apiFlags, oauthClient: oauth.NewClient(oauth.DefaultClientID), }) - } - - commands = append(commands, &command{ - flagSet: flagSet, - handler: handler, - usageFunc: usageFunc, - }) -} + }, +}) type loginParams struct { cfg *config diff --git a/cmd/src/run_migration_compat.go b/cmd/src/run_migration_compat.go index fde21bd5ee..eada89896c 100644 --- a/cmd/src/run_migration_compat.go +++ b/cmd/src/run_migration_compat.go @@ -18,6 +18,7 @@ import ( var migratedCommands = map[string]*cli.Command{ "abc": abcCommand, "auth": authCommand, + "login": loginCommand, "version": versionCommand, } From 16c82f15e757edfdbd722a22ba09fbcef21e890f Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Tue, 28 Apr 2026 15:31:21 +0200 Subject: [PATCH 573/647] add cliutil/docgen from sourcegraph and adapted for v3 (#1303) --- lib/docgen/default.go | 19 ++++ lib/docgen/markdown.go | 193 +++++++++++++++++++++++++++++++++++++++++ lib/go.mod | 4 + lib/go.sum | 7 +- 4 files changed, 221 insertions(+), 2 deletions(-) create mode 100644 lib/docgen/default.go create mode 100644 lib/docgen/markdown.go diff --git a/lib/docgen/default.go b/lib/docgen/default.go new file mode 100644 index 0000000000..de71edeb9d --- /dev/null +++ b/lib/docgen/default.go @@ -0,0 +1,19 @@ +package docgen + +import ( + "bytes" + + "github.com/urfave/cli/v3" +) + +// Default renders help text for the app using urfave/cli's default help format. +func Default(cmd *cli.Command) (string, error) { + tpl := cmd.CustomRootCommandHelpTemplate + if tpl == "" { + tpl = cli.RootCommandHelpTemplate + } + + var w bytes.Buffer + cli.HelpPrinterCustom(&w, tpl, cmd, nil) + return w.String(), nil +} diff --git a/lib/docgen/markdown.go b/lib/docgen/markdown.go new file mode 100644 index 0000000000..dd1f20a8dc --- /dev/null +++ b/lib/docgen/markdown.go @@ -0,0 +1,193 @@ +package docgen + +import ( + "bytes" + "fmt" + "io" + "sort" + "strings" + "text/template" + + "github.com/urfave/cli/v3" +) + +// Markdown renders a Markdown reference for the app. +// +// It is adapted from https://sourcegraph.com/github.com/urfave/cli-docs/-/blob/docs.go?L16 +func Markdown(root *cli.Command) (string, error) { + var w bytes.Buffer + if err := writeDocTemplate(root, &w); err != nil { + return "", err + } + return w.String(), nil +} + +type cliTemplate struct { + App *cli.Command + Commands []string + GlobalArgs []string +} + +func writeDocTemplate(root *cli.Command, w io.Writer) error { + const name = "cli" + t, err := template.New(name).Parse(markdownDocTemplate) + if err != nil { + return err + } + return t.ExecuteTemplate(w, name, &cliTemplate{ + App: root, + Commands: prepareCommands(root.Name, root.Commands, 0), + GlobalArgs: prepareArgsWithValues(root.VisibleFlags()), + }) +} + +func prepareCommands(lineage string, commands []*cli.Command, level int) []string { + var coms []string + for _, command := range commands { + if command.Hidden { + continue + } + + var commandDoc strings.Builder + commandDoc.WriteString(strings.Repeat("#", level+2)) + commandDoc.WriteString(" ") + commandDoc.WriteString(fmt.Sprintf("%s %s", lineage, command.Name)) + commandDoc.WriteString("\n\n") + commandDoc.WriteString(prepareUsage(command)) + commandDoc.WriteString("\n\n") + + if len(command.Description) > 0 { + commandDoc.WriteString(fmt.Sprintf("%s\n\n", command.Description)) + } + + commandDoc.WriteString(prepareUsageText(command)) + + flags := prepareArgsWithValues(command.Flags) + if len(flags) > 0 { + commandDoc.WriteString("\nFlags:\n\n") + for _, f := range flags { + commandDoc.WriteString("* " + f) + } + } + + coms = append(coms, commandDoc.String()) + + // recursevly iterate subcommands + if len(command.Commands) > 0 { + coms = append( + coms, + prepareCommands(lineage+" "+command.Name, command.Commands, level+1)..., + ) + } + } + + return coms +} + +func prepareArgsWithValues(flags []cli.Flag) []string { + return prepareFlags(flags, ", ", "`", "`", `""`, true) +} + +func prepareFlags( + flags []cli.Flag, + sep, opener, closer, value string, + addDetails bool, +) []string { + args := []string{} + for _, f := range flags { + flag, ok := f.(cli.DocGenerationFlag) + if !ok { + continue + } + modifiedArg := opener + + for _, s := range f.Names() { + trimmed := strings.TrimSpace(s) + if len(modifiedArg) > len(opener) { + modifiedArg += sep + } + if len(trimmed) > 1 { + modifiedArg += fmt.Sprintf("--%s", trimmed) + } else { + modifiedArg += fmt.Sprintf("-%s", trimmed) + } + } + + if flag.TakesValue() { + modifiedArg += fmt.Sprintf("=%s", value) + } + + modifiedArg += closer + + if addDetails { + modifiedArg += flagDetails(flag) + } + + args = append(args, modifiedArg+"\n") + + } + sort.Strings(args) + return args +} + +// flagDetails returns a string containing the flags metadata +func flagDetails(flag cli.DocGenerationFlag) string { + description := flag.GetUsage() + value := flag.GetValue() + if value != "" { + description += " (default: " + value + ")" + } + return ": " + description +} + +func prepareUsageText(command *cli.Command) string { + if command.UsageText == "" { + if strings.TrimSpace(command.ArgsUsage) != "" { + return fmt.Sprintf("Arguments: `%s`\n", command.ArgsUsage) + } + return "" + } + + // Write all usage examples as a big shell code block + var usageText strings.Builder + usageText.WriteString("```sh") + for line := range strings.SplitSeq(strings.TrimSpace(command.UsageText), "\n") { + usageText.WriteByte('\n') + + line = strings.TrimSpace(line) + if strings.HasPrefix(line, "# ") { + usageText.WriteString(line) + } else if len(line) > 0 { + usageText.WriteString(fmt.Sprintf("$ %s", line)) + } + } + usageText.WriteString("\n```\n") + + return usageText.String() +} + +func prepareUsage(command *cli.Command) string { + if command.Usage == "" { + return "" + } + + return command.Usage + "." +} + +var markdownDocTemplate = `# {{ .App.Name }} reference + +{{ .App.Name }}{{ if .App.Usage }} - {{ .App.Usage }}{{ end }} +{{ if .App.Description }} +{{ .App.Description }} +{{ end }} +` + "```sh" + `{{ if .App.UsageText }} +{{ .App.UsageText }} +{{ else }} +{{ .App.Name }} [GLOBAL FLAGS] command [COMMAND FLAGS] [ARGUMENTS...] +{{ end }}` + "```" + ` +{{ if .GlobalArgs }} +Global flags: + +{{ range $v := .GlobalArgs }}* {{ $v }}{{ end }}{{ end }}{{ if .Commands }} +{{ range $v := .Commands }} +{{ $v }}{{ end }}{{ end }}` diff --git a/lib/go.mod b/lib/go.mod index 42bc822948..95f5d34705 100644 --- a/lib/go.mod +++ b/lib/go.mod @@ -22,6 +22,7 @@ require ( github.com/sourcegraph/conc v0.3.0 github.com/sourcegraph/go-diff v0.7.0 github.com/sourcegraph/log v0.0.0-20250923023806-517b6960b55b + github.com/urfave/cli/v3 v3.8.0 github.com/xeipuuv/gojsonschema v1.2.0 github.com/xlab/treeprint v1.2.0 go.opentelemetry.io/otel v1.38.0 @@ -78,3 +79,6 @@ require ( golang.org/x/tools v0.37.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect ) + +// See: https://github.com/ghodss/yaml/pull/65 +replace github.com/ghodss/yaml => github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 diff --git a/lib/go.sum b/lib/go.sum index 6806c7b1d0..a2b0d73ad3 100644 --- a/lib/go.sum +++ b/lib/go.sum @@ -52,8 +52,6 @@ github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM= github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU= github.com/getsentry/sentry-go v0.27.0 h1:Pv98CIbtB3LkMWmXi4Joa5OOcwbmnX88sF5qbK3r3Ps= github.com/getsentry/sentry-go v0.27.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= -github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk= -github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA= github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og= github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y= @@ -141,11 +139,15 @@ github.com/sourcegraph/go-diff v0.7.0 h1:9uLlrd5T46OXs5qpp8L/MTltk0zikUGi0sNNyCp github.com/sourcegraph/go-diff v0.7.0/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/sourcegraph/log v0.0.0-20250923023806-517b6960b55b h1:2FQ72y5zECMu9e5z5jMnllb5n1jVK7qsvgjkVtdFV+g= github.com/sourcegraph/log v0.0.0-20250923023806-517b6960b55b/go.mod h1:IDp09QkoqS8Z3CyN2RW6vXjgABkNpDbyjLIHNQwQ8P8= +github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= +github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/urfave/cli/v3 v3.8.0 h1:XqKPrm0q4P0q5JpoclYoCAv0/MIvH/jZ2umzuf8pNTI= +github.com/urfave/cli/v3 v3.8.0/go.mod h1:ysVLtOEmg2tOy6PknnYVhDoouyC/6N42TMeoMzskhso= github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f h1:J9EGpcZtP0E/raorCMxlFGSTBrsSlaDGf3jU/qvAE2c= github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0= @@ -221,6 +223,7 @@ google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= From 04f81b4574cd49765341382d957fc3736f54635b Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Tue, 28 Apr 2026 15:38:57 +0200 Subject: [PATCH 574/647] update mise golang to 1.26.2 (#1302) --- mise.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mise.toml b/mise.toml index 23dcc8805c..f788ae6e0a 100644 --- a/mise.toml +++ b/mise.toml @@ -1,4 +1,4 @@ [tools] -golang = "1.26.1" +golang = "1.26.2" shfmt = "3.8.0" shellcheck = "0.10.0" From 36657d020af791327565ec58635139ee7a21b070 Mon Sep 17 00:00:00 2001 From: Keegan Carruthers-Smith Date: Tue, 28 Apr 2026 19:12:18 +0200 Subject: [PATCH 575/647] fix/deps: bump vulnerable Go modules to patched releases (#1305) Raise the indirect go-jose, pgx, and OpenTelemetry module versions to the first fixed releases flagged by Trivy so the CLI no longer resolves known vulnerable dependency versions. Keep the split OpenTelemetry modules aligned at v1.43.0 to avoid mixing versions across that dependency set, and record the corresponding checksum updates from the resolver. --- go.mod | 18 +++++++++--------- go.sum | 32 ++++++++++++++++---------------- 2 files changed, 25 insertions(+), 25 deletions(-) diff --git a/go.mod b/go.mod index 75f66dfa62..5d4f6d2b08 100644 --- a/go.mod +++ b/go.mod @@ -30,6 +30,7 @@ require ( github.com/sourcegraph/sourcegraph/lib v0.0.0-20240709083501-1af563b61442 github.com/stretchr/testify v1.11.1 github.com/tliron/glsp v0.2.2 + github.com/urfave/cli/v3 v3.8.0 github.com/zalando/go-keyring v0.2.6 golang.org/x/sync v0.19.0 google.golang.org/api v0.256.0 @@ -64,7 +65,7 @@ require ( github.com/envoyproxy/go-control-plane/envoy v1.36.0 // indirect github.com/felixge/httpsnoop v1.0.4 // indirect github.com/fxamacker/cbor/v2 v2.7.0 // indirect - github.com/go-jose/go-jose/v4 v4.1.3 // indirect + github.com/go-jose/go-jose/v4 v4.1.4 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/godbus/dbus/v5 v5.1.0 // indirect github.com/google/gnostic-models v0.6.9 // indirect @@ -73,7 +74,7 @@ require ( github.com/iancoleman/strcase v0.3.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect - github.com/jackc/pgx/v5 v5.9.1 // indirect + github.com/jackc/pgx/v5 v5.9.2 // indirect github.com/petermattis/goid v0.0.0-20240813172612-4fcff4a6cae7 // indirect github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 // indirect github.com/sasha-s/go-deadlock v0.3.5 // indirect @@ -83,7 +84,6 @@ require ( github.com/spiffe/go-spiffe/v2 v2.6.0 // indirect github.com/tliron/commonlog v0.2.19 // indirect github.com/tliron/kutil v0.3.27 // indirect - github.com/urfave/cli/v3 v3.8.0 // indirect github.com/x448/float16 v0.8.4 // indirect github.com/xlab/treeprint v1.2.0 // indirect github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect @@ -91,11 +91,11 @@ require ( go.opentelemetry.io/contrib/detectors/gcp v1.39.0 // indirect go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0 // indirect go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0 // indirect - go.opentelemetry.io/otel v1.40.0 // indirect - go.opentelemetry.io/otel/metric v1.40.0 // indirect - go.opentelemetry.io/otel/sdk v1.40.0 // indirect - go.opentelemetry.io/otel/sdk/metric v1.40.0 // indirect - go.opentelemetry.io/otel/trace v1.40.0 // indirect + go.opentelemetry.io/otel v1.43.0 // indirect + go.opentelemetry.io/otel/metric v1.43.0 // indirect + go.opentelemetry.io/otel/sdk v1.43.0 // indirect + go.opentelemetry.io/otel/sdk/metric v1.43.0 // indirect + go.opentelemetry.io/otel/trace v1.43.0 // indirect golang.org/x/net v0.48.0 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 // indirect @@ -182,7 +182,7 @@ require ( golang.org/x/crypto v0.46.0 // indirect golang.org/x/mod v0.30.0 // indirect golang.org/x/oauth2 v0.34.0 // indirect - golang.org/x/sys v0.41.0 // indirect + golang.org/x/sys v0.42.0 // indirect golang.org/x/term v0.38.0 // indirect golang.org/x/text v0.32.0 // indirect golang.org/x/time v0.14.0 // indirect diff --git a/go.sum b/go.sum index eda4224b98..bb29dbd1a3 100644 --- a/go.sum +++ b/go.sum @@ -152,8 +152,8 @@ github.com/getsentry/sentry-go v0.27.0 h1:Pv98CIbtB3LkMWmXi4Joa5OOcwbmnX88sF5qbK github.com/getsentry/sentry-go v0.27.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA= github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og= -github.com/go-jose/go-jose/v4 v4.1.3 h1:CVLmWDhDVRa6Mi/IgCgaopNosCaHz7zrMeF9MlZRkrs= -github.com/go-jose/go-jose/v4 v4.1.3/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= +github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA= +github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= @@ -226,8 +226,8 @@ github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsI github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= -github.com/jackc/pgx/v5 v5.9.1 h1:uwrxJXBnx76nyISkhr33kQLlUqjv7et7b9FjCen/tdc= -github.com/jackc/pgx/v5 v5.9.1/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= +github.com/jackc/pgx/v5 v5.9.2 h1:3ZhOzMWnR4yJ+RW1XImIPsD1aNSz4T4fyP7zlQb56hw= +github.com/jackc/pgx/v5 v5.9.2/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/jedib0t/go-pretty/v6 v6.6.3 h1:nGqgS0tgIO1Hto47HSaaK4ac/I/Bu7usmdD3qvs0WvM= @@ -403,18 +403,18 @@ go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.6 go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0/go.mod h1:snMWehoOh2wsEwnvvwtDyFCxVeDAODenXHtn5vzrKjo= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0 h1:RbKq8BG0FI8OiXhBfcRtqqHcZcka+gU3cskNuf05R18= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0/go.mod h1:h06DGIukJOevXaj/xrNjhi/2098RZzcLTbc0jDAUbsg= -go.opentelemetry.io/otel v1.40.0 h1:oA5YeOcpRTXq6NN7frwmwFR0Cn3RhTVZvXsP4duvCms= -go.opentelemetry.io/otel v1.40.0/go.mod h1:IMb+uXZUKkMXdPddhwAHm6UfOwJyh4ct1ybIlV14J0g= +go.opentelemetry.io/otel v1.43.0 h1:mYIM03dnh5zfN7HautFE4ieIig9amkNANT+xcVxAj9I= +go.opentelemetry.io/otel v1.43.0/go.mod h1:JuG+u74mvjvcm8vj8pI5XiHy1zDeoCS2LB1spIq7Ay0= go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.29.0 h1:WDdP9acbMYjbKIyJUhTvtzj601sVJOqgWdUxSdR/Ysc= go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.29.0/go.mod h1:BLbf7zbNIONBLPwvFnwNHGj4zge8uTCM/UPIVW1Mq2I= -go.opentelemetry.io/otel/metric v1.40.0 h1:rcZe317KPftE2rstWIBitCdVp89A2HqjkxR3c11+p9g= -go.opentelemetry.io/otel/metric v1.40.0/go.mod h1:ib/crwQH7N3r5kfiBZQbwrTge743UDc7DTFVZrrXnqc= -go.opentelemetry.io/otel/sdk v1.40.0 h1:KHW/jUzgo6wsPh9At46+h4upjtccTmuZCFAc9OJ71f8= -go.opentelemetry.io/otel/sdk v1.40.0/go.mod h1:Ph7EFdYvxq72Y8Li9q8KebuYUr2KoeyHx0DRMKrYBUE= -go.opentelemetry.io/otel/sdk/metric v1.40.0 h1:mtmdVqgQkeRxHgRv4qhyJduP3fYJRMX4AtAlbuWdCYw= -go.opentelemetry.io/otel/sdk/metric v1.40.0/go.mod h1:4Z2bGMf0KSK3uRjlczMOeMhKU2rhUqdWNoKcYrtcBPg= -go.opentelemetry.io/otel/trace v1.40.0 h1:WA4etStDttCSYuhwvEa8OP8I5EWu24lkOzp+ZYblVjw= -go.opentelemetry.io/otel/trace v1.40.0/go.mod h1:zeAhriXecNGP/s2SEG3+Y8X9ujcJOTqQ5RgdEJcawiA= +go.opentelemetry.io/otel/metric v1.43.0 h1:d7638QeInOnuwOONPp4JAOGfbCEpYb+K6DVWvdxGzgM= +go.opentelemetry.io/otel/metric v1.43.0/go.mod h1:RDnPtIxvqlgO8GRW18W6Z/4P462ldprJtfxHxyKd2PY= +go.opentelemetry.io/otel/sdk v1.43.0 h1:pi5mE86i5rTeLXqoF/hhiBtUNcrAGHLKQdhg4h4V9Dg= +go.opentelemetry.io/otel/sdk v1.43.0/go.mod h1:P+IkVU3iWukmiit/Yf9AWvpyRDlUeBaRg6Y+C58QHzg= +go.opentelemetry.io/otel/sdk/metric v1.43.0 h1:S88dyqXjJkuBNLeMcVPRFXpRw2fuwdvfCGLEo89fDkw= +go.opentelemetry.io/otel/sdk/metric v1.43.0/go.mod h1:C/RJtwSEJ5hzTiUz5pXF1kILHStzb9zFlIEe85bhj6A= +go.opentelemetry.io/otel/trace v1.43.0 h1:BkNrHpup+4k4w+ZZ86CZoHHEkohws8AY+WTX09nk+3A= +go.opentelemetry.io/otel/trace v1.43.0/go.mod h1:/QJhyVBUUswCphDVxq+8mld+AvhXZLhe+8WVFxiFff0= go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= @@ -472,8 +472,8 @@ golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220829200755-d48e67d00261/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k= -golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo= +golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.3.0/go.mod h1:q750SLmJuPmVoN1blW3UFBPREJfb1KmY3vwxfr+nFDA= From 7cf08b15723ca9ac7a9ae3ded840a4cf72b66920 Mon Sep 17 00:00:00 2001 From: Michael Bahr <1830132+bahrmichael@users.noreply.github.com> Date: Thu, 30 Apr 2026 10:58:50 +0200 Subject: [PATCH 576/647] chore: handle batch spec v3 (#1306) --- .gitignore | 1 + cmd/src/batch_common.go | 4 ++++ internal/batches/service/service_test.go | 2 +- lib/batches/schema/batch_spec_stringdata.go | 2 +- 4 files changed, 7 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index 2d73227cc4..0091b7092a 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,4 @@ bazel-zoekt bazel-src-cli .DS_Store samples +.amp diff --git a/cmd/src/batch_common.go b/cmd/src/batch_common.go index e294347dcf..59b462ba96 100644 --- a/cmd/src/batch_common.go +++ b/cmd/src/batch_common.go @@ -373,6 +373,10 @@ func executeBatchSpec(ctx context.Context, opts executeBatchSpecOpts) (err error } execUI.ParsingBatchSpecSuccess() + if batchSpec.Version == 3 { + return errors.New("batch spec version 3 is not supported for local execution, please run server-side") + } + execUI.ResolvingNamespace() namespace, err := svc.ResolveNamespace(ctx, opts.flags.namespace) if err != nil { diff --git a/internal/batches/service/service_test.go b/internal/batches/service/service_test.go index da877edc33..bdff83acfc 100644 --- a/internal/batches/service/service_test.go +++ b/internal/batches/service/service_test.go @@ -282,7 +282,7 @@ version: 99 name: test-spec description: A test spec `, - expectedErr: errors.New("parsing batch spec: version: version must be one of the following: 1, 2"), + expectedErr: errors.New("parsing batch spec: version: version must be one of the following: 1, 2, 3"), }, { name: "mount absolute file", diff --git a/lib/batches/schema/batch_spec_stringdata.go b/lib/batches/schema/batch_spec_stringdata.go index 6d412a0a33..1123970faf 100644 --- a/lib/batches/schema/batch_spec_stringdata.go +++ b/lib/batches/schema/batch_spec_stringdata.go @@ -15,7 +15,7 @@ const BatchSpecJSON = `{ "version": { "type": "number", "description": "The version of the batch spec schema. Defaults to 1.", - "enum": [1, 2] + "enum": [1, 2, 3] }, "name": { "type": "string", From 0d9c9dbf01373fb32cac4a6cd425e401a456cf81 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Thu, 30 Apr 2026 14:20:27 +0200 Subject: [PATCH 577/647] feat/docgen: generate docs for legacy and urfave commands (#1304) --- cmd/src/doc.go | 54 +++++++- lib/docgen/markdown.go | 289 ++++++++++++++++++++++++++--------------- 2 files changed, 234 insertions(+), 109 deletions(-) diff --git a/cmd/src/doc.go b/cmd/src/doc.go index 0bcb7b9d1a..43ea72944d 100644 --- a/cmd/src/doc.go +++ b/cmd/src/doc.go @@ -5,11 +5,13 @@ import ( "flag" "fmt" "io" + "maps" "os" "path" "strings" "text/template" + "github.com/sourcegraph/sourcegraph/lib/docgen" "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/sourcegraph/lib/output" @@ -29,7 +31,7 @@ documentation used within Sourcegraph. Usage: src doc -o DIR - + Examples: $ src doc -o ~/sourcegraph/doc/integration/cli/reference @@ -47,6 +49,8 @@ Examples: return cmderrors.ExitCode(1, nil) } + dstDir := *outputFlag + dr, err := newDocRenderer() if err != nil { return err @@ -66,6 +70,7 @@ Examples: pending := out.Pending(output.Line("", output.StylePending, "Rendering Markdown...")) count := 0 + rootSubcommands := map[string]string{} defer func() { pending.Complete(output.Linef(output.EmojiSuccess, output.StyleSuccess, "%d files rendered under %s", count, *outputFlag)) }() @@ -94,7 +99,7 @@ Examples: return err } - file, err := openDocFile(*outputFlag, fqcn) + file, err := openDocFile(dstDir, fqcn) if err != nil { return err } @@ -110,12 +115,17 @@ Examples: } } + if groupName == "" { + maps.Copy(subcommands, rootSubcommands) + continue + } + content, err := dr.RenderGroup(groupName, subcommands) if err != nil { return err } - file, err := openDocFile(*outputFlag, groupName+" index") + file, err := openDocFile(dstDir, groupName+" index") if err != nil { return err } @@ -127,6 +137,44 @@ Examples: count++ } + root := migratedRootCommand() + mdFiles, err := docgen.Markdown(root) + if err != nil { + return err + } + + for _, cmd := range docgen.VisibleCommands(root.Commands) { + rootSubcommands[cmd.Name] = docgen.SubcommandDocPath(cmd) + } + + for _, md := range mdFiles { + pending.Update(md.Name) + docPath := path.Join(dstDir, md.Name) + if err := os.MkdirAll(path.Dir(docPath), 0755); err != nil { + return err + } + if err := os.WriteFile(docPath, []byte(md.Content), 0644); err != nil { + return err + } + count++ + } + + content, err := dr.RenderGroup("", rootSubcommands) + if err != nil { + return err + } + + file, err := openDocFile(dstDir, " index") + if err != nil { + return err + } + defer file.Close() + + if _, err := file.WriteString(content); err != nil { + return err + } + count++ + return nil } diff --git a/lib/docgen/markdown.go b/lib/docgen/markdown.go index dd1f20a8dc..1b499ce452 100644 --- a/lib/docgen/markdown.go +++ b/lib/docgen/markdown.go @@ -2,163 +2,190 @@ package docgen import ( "bytes" + "cmp" "fmt" "io" + "path" + "slices" "sort" "strings" "text/template" "github.com/urfave/cli/v3" + + "github.com/sourcegraph/sourcegraph/lib/errors" ) +type MarkdownFile struct { + Name string + Content string +} + // Markdown renders a Markdown reference for the app. // // It is adapted from https://sourcegraph.com/github.com/urfave/cli-docs/-/blob/docs.go?L16 -func Markdown(root *cli.Command) (string, error) { - var w bytes.Buffer - if err := writeDocTemplate(root, &w); err != nil { - return "", err +func Markdown(root *cli.Command) ([]MarkdownFile, error) { + files := make([]MarkdownFile, 0, len(root.Commands)) + var errs error + for _, sub := range VisibleCommands(root.Commands) { + subFiles, err := markdownFiles(root.Name, []string{sub.Name}, sub) + if err != nil { + errs = errors.Append(errs, err) + } + files = append(files, subFiles...) } - return w.String(), nil + return files, errs } type cliTemplate struct { - App *cli.Command - Commands []string - GlobalArgs []string + Title string + Usage string + Description string + UsageText string + Flags []flagRow + Subcommands []subcommand } -func writeDocTemplate(root *cli.Command, w io.Writer) error { - const name = "cli" - t, err := template.New(name).Parse(markdownDocTemplate) - if err != nil { - return err - } - return t.ExecuteTemplate(w, name, &cliTemplate{ - App: root, - Commands: prepareCommands(root.Name, root.Commands, 0), - GlobalArgs: prepareArgsWithValues(root.VisibleFlags()), - }) +type subcommand struct { + Name string + Link string } -func prepareCommands(lineage string, commands []*cli.Command, level int) []string { - var coms []string - for _, command := range commands { - if command.Hidden { - continue - } - - var commandDoc strings.Builder - commandDoc.WriteString(strings.Repeat("#", level+2)) - commandDoc.WriteString(" ") - commandDoc.WriteString(fmt.Sprintf("%s %s", lineage, command.Name)) - commandDoc.WriteString("\n\n") - commandDoc.WriteString(prepareUsage(command)) - commandDoc.WriteString("\n\n") +type flagRow struct { + Name string + Desc string + Default string +} - if len(command.Description) > 0 { - commandDoc.WriteString(fmt.Sprintf("%s\n\n", command.Description)) - } +// markdownFiles recursively walks over cmd commands and sub commands to build a list of MarkdownFiles +// that contain the name and content for a command +func markdownFiles(rootName string, lineage []string, cmd *cli.Command) ([]MarkdownFile, error) { + var w bytes.Buffer + err := writeDocTemplate(rootName, lineage, cmd, &w) - commandDoc.WriteString(prepareUsageText(command)) + files := []MarkdownFile{{ + Name: docPath(lineage, hasVisibleCommands(cmd.Commands)), + Content: w.String(), + }} - flags := prepareArgsWithValues(command.Flags) - if len(flags) > 0 { - commandDoc.WriteString("\nFlags:\n\n") - for _, f := range flags { - commandDoc.WriteString("* " + f) - } + for _, sub := range VisibleCommands(cmd.Commands) { + subFiles, subErr := markdownFiles(rootName, append(lineage, sub.Name), sub) + if subErr != nil { + err = errors.Append(err, subErr) } + files = append(files, subFiles...) + } - coms = append(coms, commandDoc.String()) + return files, err +} - // recursevly iterate subcommands - if len(command.Commands) > 0 { - coms = append( - coms, - prepareCommands(lineage+" "+command.Name, command.Commands, level+1)..., - ) - } +func writeDocTemplate(rootName string, lineage []string, cmd *cli.Command, w io.Writer) error { + const name = "cli" + t, err := template.New(name).Parse(markdownDocTemplate) + if err != nil { + return err } - return coms + title := strings.Join(append([]string{rootName}, lineage...), " ") + return t.ExecuteTemplate(w, name, &cliTemplate{ + Title: title, + Usage: prepareUsage(cmd), + Description: strings.TrimSpace(cmd.Description), + UsageText: prepareUsageText(title, cmd), + Flags: prepareArgsWithValues(cmd.Flags), + Subcommands: prepareSubcommands(cmd.Commands), + }) +} + +func prepareSubcommands(commands []*cli.Command) []subcommand { + links := make([]subcommand, 0, len(commands)) + for _, command := range VisibleCommands(commands) { + links = append(links, subcommand{ + Name: command.Name, + Link: SubcommandDocPath(command), + }) + } + return links } -func prepareArgsWithValues(flags []cli.Flag) []string { - return prepareFlags(flags, ", ", "`", "`", `""`, true) +func prepareArgsWithValues(flags []cli.Flag) []flagRow { + return prepareFlags(flags) } func prepareFlags( flags []cli.Flag, - sep, opener, closer, value string, - addDetails bool, -) []string { - args := []string{} +) []flagRow { + rows := []flagRow{} for _, f := range flags { flag, ok := f.(cli.DocGenerationFlag) if !ok { continue } - modifiedArg := opener - + names := make([]string, 0, len(f.Names())) for _, s := range f.Names() { trimmed := strings.TrimSpace(s) - if len(modifiedArg) > len(opener) { - modifiedArg += sep + if trimmed == "" { + continue } if len(trimmed) > 1 { - modifiedArg += fmt.Sprintf("--%s", trimmed) + names = append(names, fmt.Sprintf("--%s", trimmed)) } else { - modifiedArg += fmt.Sprintf("-%s", trimmed) + names = append(names, fmt.Sprintf("-%s", trimmed)) } } - if flag.TakesValue() { - modifiedArg += fmt.Sprintf("=%s", value) - } - - modifiedArg += closer - - if addDetails { - modifiedArg += flagDetails(flag) + name := strings.Join(names, ", ") + if len(name) > 0 { + rows = append(rows, flagRow{ + Name: name, + Desc: flag.GetUsage(), + Default: flag.GetValue(), + }) } - args = append(args, modifiedArg+"\n") - } - sort.Strings(args) - return args -} - -// flagDetails returns a string containing the flags metadata -func flagDetails(flag cli.DocGenerationFlag) string { - description := flag.GetUsage() - value := flag.GetValue() - if value != "" { - description += " (default: " + value + ")" - } - return ": " + description + slices.SortFunc(rows, func(a, b flagRow) int { + return cmp.Compare(a.Name, b.Name) + }) + return rows } -func prepareUsageText(command *cli.Command) string { +func prepareUsageText(lineage string, command *cli.Command) string { if command.UsageText == "" { + if hasVisibleCommands(command.Commands) { + return renderUsageBlock(lineage + " [command options]") + } + if len(command.Flags) > 0 { + return renderUsageBlock(lineage + " [options]") + } if strings.TrimSpace(command.ArgsUsage) != "" { return fmt.Sprintf("Arguments: `%s`\n", command.ArgsUsage) } return "" } - // Write all usage examples as a big shell code block + // Write all usage examples as a big shell code block. + lines := make([]string, 0, strings.Count(command.UsageText, "\n")+1) + for line := range strings.SplitSeq(strings.TrimSpace(command.UsageText), "\n") { + line = strings.TrimSpace(line) + if len(line) == 0 { + continue + } + lines = append(lines, line) + } + return renderUsageBlock(lines...) +} + +func renderUsageBlock(lines ...string) string { var usageText strings.Builder usageText.WriteString("```sh") - for line := range strings.SplitSeq(strings.TrimSpace(command.UsageText), "\n") { + for _, line := range lines { usageText.WriteByte('\n') - line = strings.TrimSpace(line) if strings.HasPrefix(line, "# ") { usageText.WriteString(line) } else if len(line) > 0 { - usageText.WriteString(fmt.Sprintf("$ %s", line)) + fmt.Fprintf(&usageText, "$ %s", line) } } usageText.WriteString("\n```\n") @@ -174,20 +201,70 @@ func prepareUsage(command *cli.Command) string { return command.Usage + "." } -var markdownDocTemplate = `# {{ .App.Name }} reference +// VisibleCommands returns the non-hidden commands sorted by name. +func VisibleCommands(commands []*cli.Command) []*cli.Command { + visible := make([]*cli.Command, 0, len(commands)) + for _, command := range commands { + if command.Hidden { + continue + } + visible = append(visible, command) + } + + sort.Slice(visible, func(i, j int) bool { + return visible[i].Name < visible[j].Name + }) + + return visible +} + +// SubcommandDocPath returns the relative doc path for a direct child command. +func SubcommandDocPath(command *cli.Command) string { + return docPath([]string{command.Name}, hasVisibleCommands(command.Commands)) +} + +func hasVisibleCommands(commands []*cli.Command) bool { + for _, command := range commands { + if !command.Hidden { + return true + } + } + return false +} + +func docPath(lineage []string, isGroup bool) string { + if len(lineage) == 0 { + return "index.md" + } + if isGroup { + return path.Join(path.Join(lineage...), "index.md") + } + if len(lineage) == 1 { + return lineage[0] + ".md" + } + return path.Join(path.Join(lineage[:len(lineage)-1]...), lineage[len(lineage)-1]+".md") +} + +var markdownDocTemplate = `# ` + "`" + `{{ .Title }}` + "`" + ` + +{{ if .Usage }}{{ .Usage }} + +{{ end }}{{ if .Description }}{{ .Description }} +{{- end }} + +{{ if .UsageText }}## Usage + +{{ .UsageText }} +{{- end }} +{{ if .Flags }}## Flags -{{ .App.Name }}{{ if .App.Usage }} - {{ .App.Usage }}{{ end }} -{{ if .App.Description }} -{{ .App.Description }} -{{ end }} -` + "```sh" + `{{ if .App.UsageText }} -{{ .App.UsageText }} -{{ else }} -{{ .App.Name }} [GLOBAL FLAGS] command [COMMAND FLAGS] [ARGUMENTS...] -{{ end }}` + "```" + ` -{{ if .GlobalArgs }} -Global flags: +| Name | Description | Default Value | +|------|-------------|---------------| +{{- range .Flags -}} +{{- "\n" -}} +| ` + "`" + `{{ .Name }}` + "`" + ` | {{ .Desc }} | ` + "`" + `{{ .Default }}` + "`" + `| +{{- end }}{{- end }} +{{- if .Subcommands }}## Subcommands -{{ range $v := .GlobalArgs }}* {{ $v }}{{ end }}{{ end }}{{ if .Commands }} -{{ range $v := .Commands }} -{{ $v }}{{ end }}{{ end }}` +{{ range $v := .Subcommands }}* [` + "`" + `{{ $v.Name }}` + "`" + `]({{ $v.Link }}) +{{ end }}{{ end }}` From 28a22034626b11d888af1336991c0320cdf58ed4 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Mon, 4 May 2026 12:24:14 +0200 Subject: [PATCH 578/647] remove admin command that was added for appliance (#1309) --- cmd/src/admin.go | 38 ---------------- cmd/src/admin_create.go | 97 ----------------------------------------- 2 files changed, 135 deletions(-) delete mode 100644 cmd/src/admin.go delete mode 100644 cmd/src/admin_create.go diff --git a/cmd/src/admin.go b/cmd/src/admin.go deleted file mode 100644 index ac8af95205..0000000000 --- a/cmd/src/admin.go +++ /dev/null @@ -1,38 +0,0 @@ -package main - -import ( - "flag" - "fmt" -) - -var adminCommands commander - -func init() { - usage := `'src admin' is a tool that manages an initial admin user on a new Sourcegraph instance. - -Usage: - - src admin create [command options] - -The commands are: - - create create an initial admin user - -Use "src admin [command] -h" for more information about a command. -` - - flagSet := flag.NewFlagSet("admin", flag.ExitOnError) - handler := func(args []string) error { - adminCommands.run(flagSet, "srv admin", usage, args) - return nil - } - - commands = append(commands, &command{ - flagSet: flagSet, - aliases: []string{"admin"}, - handler: handler, - usageFunc: func() { - fmt.Println(usage) - }, - }) -} diff --git a/cmd/src/admin_create.go b/cmd/src/admin_create.go deleted file mode 100644 index 8fdf719647..0000000000 --- a/cmd/src/admin_create.go +++ /dev/null @@ -1,97 +0,0 @@ -package main - -import ( - "flag" - "fmt" - "os" - - "github.com/sourcegraph/src-cli/internal/users" - - "github.com/sourcegraph/sourcegraph/lib/errors" -) - -func init() { - usage := ` -Examples: - - Create an initial admin user on a new Sourcegraph deployment: - - $ src admin create -url https://your-sourcegraph-url -username admin -email admin@yourcompany.com -with-token - - Create an initial admin user on a new Sourcegraph deployment using '-password' flag. - WARNING: for security purposes we strongly recommend using the SRC_ADMIN_PASS environment variable when possible. - - $ src admin create -url https://your-sourcegraph-url -username admin -email admin@yourcompany.com -password p@55w0rd -with-token - -Environmental variables - - SRC_ADMIN_PASS The new admin user's password -` - - flagSet := flag.NewFlagSet("create", flag.ExitOnError) - usageFunc := func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src users %s':\n", flagSet.Name()) - flagSet.PrintDefaults() - fmt.Println(usage) - } - - var ( - urlFlag = flagSet.String("url", "", "The base URL for the Sourcegraph instance.") - usernameFlag = flagSet.String("username", "", "The new admin user's username.") - emailFlag = flagSet.String("email", "", "The new admin user's email address.") - passwordFlag = flagSet.String("password", "", "The new admin user's password.") - tokenFlag = flagSet.Bool("with-token", false, "Optionally create and output an admin access token.") - ) - - handler := func(args []string) error { - if err := flagSet.Parse(args); err != nil { - return err - } - - ok, _, err := users.NeedsSiteInit(*urlFlag) - if err != nil { - return err - } - if !ok { - return errors.New("failed to create admin, site already initialized") - } - - envAdminPass := os.Getenv("SRC_ADMIN_PASS") - - var client *users.Client - - switch { - case envAdminPass != "" && *passwordFlag == "": - client, err = users.SiteAdminInit(*urlFlag, *emailFlag, *usernameFlag, envAdminPass) - if err != nil { - return err - } - case envAdminPass == "" && *passwordFlag != "": - client, err = users.SiteAdminInit(*urlFlag, *emailFlag, *usernameFlag, *passwordFlag) - if err != nil { - return err - } - case envAdminPass != "" && *passwordFlag != "": - return errors.New("failed to read admin password: environment variable and -password flag both set") - case envAdminPass == "" && *passwordFlag == "": - return errors.New("failed to read admin password from 'SRC_ADMIN_PASS' environment variable or -password flag") - } - - if *tokenFlag { - token, err := client.CreateAccessToken("", []string{"user:all", "site-admin:sudo"}, "src-cli") - if err != nil { - return err - } - - fmt.Println(token) - } - - return nil - } - - adminCommands = append(adminCommands, &command{ - flagSet: flagSet, - handler: handler, - usageFunc: usageFunc, - }) -} From d954157ed72f16f22c359dc71c89b6a310ed625a Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Mon, 4 May 2026 12:51:48 +0200 Subject: [PATCH 579/647] chore/dev: add the pr commit writing skill from sourcegraph (#1307) --- .../skills/writing-prs-and-commits/SKILL.md | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 .agents/skills/writing-prs-and-commits/SKILL.md diff --git a/.agents/skills/writing-prs-and-commits/SKILL.md b/.agents/skills/writing-prs-and-commits/SKILL.md new file mode 100644 index 0000000000..a722b1b0d2 --- /dev/null +++ b/.agents/skills/writing-prs-and-commits/SKILL.md @@ -0,0 +1,58 @@ +--- +name: writing-prs-and-commits +description: Writes and revises Sourcegraph pull request titles, descriptions, and single-PR commit messages. Use when creating or updating a pull request, or when preparing a commit that should stand on its own as the eventual PR. +--- + +# Writing PRs and commits + +Use this skill when the user asks to create a PR, update an existing PR title or body, or write a commit message for a change that maps cleanly to one PR. + +## Resolve the target + +- If the user names a PR number or URL, use that. +- Otherwise, inspect the current branch and use `gh pr view --json number,title,body,baseRefName,headRefName,url` to find the associated PR. +- If no PR exists and the user wants one created, use `gh pr create`, then immediately verify or adjust the title and body. +- If the user wants text only, provide the draft without mutating GitHub. +- When a PR is part of a stack, describe only the net change between the PR head and its base branch. Do not describe the full stack relative to `main`. + +## Core writing rules + +- Lead with _why_. The first paragraph or sentence should explain the problem, motivation, or user impact. +- Follow with _what_ changed. Once the reader understands why the change exists, describe the solution and any important constraints or tradeoffs. +- Write the net change only. Do not document abandoned experiments, reverted approaches, or temporary dead ends. +- Prefer natural prose over rigid `Summary` / `Problem` / `Solution` headings unless the user explicitly asks for that format. +- Keep references repo-relative. Do not mention absolute local filesystem paths. +- Preserve valuable existing PR content such as screenshots, images, rollout notes, and manually written context unless the user asks to remove it. +- Use Markdown cleanly: inline code in backticks, fenced blocks when needed, and GitHub permalinks when citing specific code. + +## PR titles + +- Keep titles short, specific, and verb-first. +- Prefer Sourcegraph's changelog-friendly shape when it fits the change: `type/domain: title`. +- Use conventional prefixes like `feat`, `fix`, `remove`, and `chore` when they match the change. +- Make the title describe the improvement or behavior change, not just the bug report. +- If the PR is user-visible and likely to feed the changelog, choose a domain that reflects the product or feature area rather than an implementation detail. + +## PR descriptions + +- Write the opening prose in this order: + 1. Why this change is needed. + 2. What changed. + 3. Any important tradeoffs, rollout notes, or follow-up context. +- When relevant, reference linked Linear issues or related Slack threads. +- If docs or handbook follow-up is needed, mention it in the prose before the verification section. +- Include `## Test Plan` near the end when there is meaningful validation to report. +- The test plan should mention intentional verification such as focused tests, manual flows, or reproduction steps. Do not pad it with routine formatting or CI work the repository already expects. +- Include `## Changelog` only for end-user-visible changes worth communicating outside the PR. Keep it as the last section. Omit it for refactors, tooling, internal cleanup, or other changes with no user-facing impact. + +## Commit messages for single-PR changes + +Treat a single commit that is intended to become one PR as a PR. GitHub by default will use the title and body from the commit. + +## Workflow + +1. Inspect the diff, linked context, and any existing PR title, body, or commit message. +2. Decide whether you are creating a new PR, editing an existing PR, or writing a stand-alone commit message. +3. Draft the title and body so the motivation is clear before the implementation details. +4. Check that the text matches the net change, preserves important existing content, and follows Sourcegraph conventions for `Test Plan` and `Changelog`. +5. Apply the final text with `gh pr create`, `gh pr edit`, or `git commit` as requested. From 653c378e979528ac05e168a22b3592abbdc0bb72 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Mon, 4 May 2026 12:59:30 +0200 Subject: [PATCH 580/647] set cmd.Action to default ShowCommandHelp when nil (#1308) --- cmd/src/abc.go | 8 -------- cmd/src/auth.go | 5 ----- internal/clicompat/help.go | 12 +++++++----- 3 files changed, 7 insertions(+), 18 deletions(-) diff --git a/cmd/src/abc.go b/cmd/src/abc.go index 5d2b019556..86513722ce 100644 --- a/cmd/src/abc.go +++ b/cmd/src/abc.go @@ -1,8 +1,6 @@ package main import ( - "context" - "github.com/sourcegraph/src-cli/internal/clicompat" "github.com/urfave/cli/v3" ) @@ -18,12 +16,6 @@ var abcCommand = clicompat.Wrap(&cli.Command{ abcVariablesSetCommand, abcVariablesDeleteCommand, }, - Action: func(ctx context.Context, cmd *cli.Command) error { - return cli.ShowSubcommandHelp(cmd) - }, }), }, - Action: func(ctx context.Context, cmd *cli.Command) error { - return cli.ShowSubcommandHelp(cmd) - }, }) diff --git a/cmd/src/auth.go b/cmd/src/auth.go index 5c843ad700..573f752174 100644 --- a/cmd/src/auth.go +++ b/cmd/src/auth.go @@ -1,8 +1,6 @@ package main import ( - "context" - "github.com/sourcegraph/src-cli/internal/clicompat" "github.com/urfave/cli/v3" ) @@ -32,7 +30,4 @@ var authCommand = clicompat.Wrap(&cli.Command{ Commands: []*cli.Command{ authTokenCommand, }, - Action: func(ctx context.Context, cmd *cli.Command) error { - return cli.ShowSubcommandHelp(cmd) - }, }) diff --git a/internal/clicompat/help.go b/internal/clicompat/help.go index fa9235572d..bdb5e1fbda 100644 --- a/internal/clicompat/help.go +++ b/internal/clicompat/help.go @@ -16,15 +16,17 @@ func Wrap(cmd *cli.Command) *cli.Command { } cmd.OnUsageError = OnUsageError - cmd.Action = wrapWithHelpOnUsageError(cmd.Action) + if cmd.Action == nil { + cmd.Action = func(ctx context.Context, cmd *cli.Command) error { + return cli.ShowSubcommandHelp(cmd) + } + } else { + cmd.Action = wrapWithHelpOnUsageError(cmd.Action) + } return cmd } func wrapWithHelpOnUsageError(action cli.ActionFunc) cli.ActionFunc { - if action == nil { - return nil - } - return func(ctx context.Context, cmd *cli.Command) error { err := action(ctx, cmd) if err != nil && errors.HasType[*cmderrors.UsageError](err) { From b743fba3d81022de7ec7165c047ded1f60dd6858 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Mon, 4 May 2026 15:18:00 +0200 Subject: [PATCH 581/647] chore: migrate api command to urfave/cli (#1301) * chore: migrate api command to urfave/cli * run goimports --- cmd/src/api.go | 91 ++++++++++++++++----------------- cmd/src/run_migration_compat.go | 7 +++ internal/clicompat/errors.go | 6 +-- internal/clicompat/help.go | 31 ++++++++++- 4 files changed, 82 insertions(+), 53 deletions(-) diff --git a/cmd/src/api.go b/cmd/src/api.go index e8788424ed..f2d0d1151a 100644 --- a/cmd/src/api.go +++ b/cmd/src/api.go @@ -3,20 +3,19 @@ package main import ( "context" "encoding/json" - "flag" "fmt" "io" "os" "strings" - "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/clicompat" "github.com/sourcegraph/src-cli/internal/cmderrors" "github.com/mattn/go-isatty" + "github.com/urfave/cli/v3" ) -func init() { - usage := ` +const apiExamples = ` Exit codes: 0: Success @@ -43,28 +42,26 @@ Examples: $ src api -get-curl -query='query { currentUser { username } }' ` - flagSet := flag.NewFlagSet("api", flag.ExitOnError) - usageFunc := func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src %s':\n", flagSet.Name()) - flagSet.PrintDefaults() - fmt.Println(usage) - } - var ( - queryFlag = flagSet.String("query", "", "GraphQL query to execute, e.g. 'query { currentUser { username } }' (stdin otherwise)") - varsFlag = flagSet.String("vars", "", `GraphQL query variables to include as JSON string, e.g. '{"var": "val", "var2": "val2"}'`) - apiFlags = api.NewFlags(flagSet) - ) - - handler := func(args []string) error { - err := flagSet.Parse(args) - if err != nil { - return err - } - - // Build the GraphQL request. - query := *queryFlag +var apiCommand = clicompat.Wrap(&cli.Command{ + Name: "api", + Usage: "interacts with the Sourcegraph GraphQL API", + UsageText: "src api [options] [variable=value ...]", + Description: apiExamples, + HideVersion: true, + DisableSliceFlagSeparator: true, + Flags: clicompat.WithAPIFlags( + &cli.StringFlag{ + Name: "query", + Usage: "GraphQL query to execute, e.g. 'query { currentUser { username } }' (stdin otherwise)", + }, + &cli.StringFlag{ + Name: "vars", + Usage: `GraphQL query variables to include as JSON string, e.g. '{"var": "val", "var2": "val2"}'`, + }, + ), + Action: func(ctx context.Context, cmd *cli.Command) error { + query := cmd.String("query") if query == "" { - // Read query from stdin instead. if isatty.IsTerminal(os.Stdin.Fd()) { return cmderrors.Usage("expected query to be piped into 'src api' or -query flag to be specified") } @@ -75,42 +72,40 @@ Examples: query = string(data) } - // Determine which variables to use in the request. vars := map[string]any{} - if *varsFlag != "" { - if err := json.Unmarshal([]byte(*varsFlag), &vars); err != nil { + if raw := cmd.String("vars"); raw != "" { + if err := json.Unmarshal([]byte(raw), &vars); err != nil { return err } } - for _, arg := range flagSet.Args() { - idx := strings.Index(arg, "=") - if idx == -1 { + for _, arg := range cmd.Args().Slice() { + key, value, ok := strings.Cut(arg, "=") + if !ok { return cmderrors.Usagef("parsing argument %q expected 'variable=value' syntax (missing equals)", arg) } - key := arg[:idx] - value := arg[idx+1:] vars[key] = value } - // Perform the request. - var result any - if ok, err := cfg.apiClient(apiFlags, flagSet.Output()).NewRequest(query, vars).DoRaw(context.Background(), &result); err != nil || !ok { + var result struct { + Data any `json:"data,omitempty"` + Errors []json.RawMessage `json:"errors,omitempty"` + } + client := cfg.apiClient(clicompat.APIFlagsFromCmd(cmd), cmd.Writer) + if ok, err := client.NewRequest(query, vars).DoRaw(ctx, &result); err != nil || !ok { return err } - // Print the formatted JSON. - f, err := marshalIndent(result) + formatted, err := marshalIndent(result) if err != nil { return err } - fmt.Println(string(f)) + _, err = fmt.Fprintln(cmd.Writer, string(formatted)) + if err != nil { + return err + } + if len(result.Errors) > 0 { + return cmderrors.ExitCode(cmderrors.GraphqlErrorsExitCode, nil) + } return nil - } - - // Register the command. - commands = append(commands, &command{ - flagSet: flagSet, - handler: handler, - usageFunc: usageFunc, - }) -} + }, +}) diff --git a/cmd/src/run_migration_compat.go b/cmd/src/run_migration_compat.go index eada89896c..52baca0fc5 100644 --- a/cmd/src/run_migration_compat.go +++ b/cmd/src/run_migration_compat.go @@ -17,6 +17,7 @@ import ( var migratedCommands = map[string]*cli.Command{ "abc": abcCommand, + "api": apiCommand, "auth": authCommand, "login": loginCommand, "version": versionCommand, @@ -68,6 +69,12 @@ func runMigrated() (int, error) { if errors.HasType[*cmderrors.UsageError](err) { return 2, nil } + if e, ok := err.(*cmderrors.ExitCodeError); ok { + if e.HasError() { + return e.Code(), e + } + return e.Code(), nil + } var exitErr cli.ExitCoder if errors.AsInterface(err, &exitErr) { return exitErr.ExitCode(), err diff --git a/internal/clicompat/errors.go b/internal/clicompat/errors.go index f06886b4bf..dd7a84553b 100644 --- a/internal/clicompat/errors.go +++ b/internal/clicompat/errors.go @@ -3,14 +3,14 @@ package clicompat import ( "context" "fmt" - "os" "github.com/sourcegraph/src-cli/internal/cmderrors" "github.com/urfave/cli/v3" ) func OnUsageError(ctx context.Context, cmd *cli.Command, err error, isSubCommand bool) error { - fmt.Fprintf(os.Stderr, "error: %s\n", err.Error()) - cli.DefaultPrintHelp(os.Stderr, cmd.CustomHelpTemplate, cmd) + out := errWriter(cmd) + fmt.Fprintf(out, "error: %s\n", err.Error()) + printCommandHelp(out, cmd) return cmderrors.Usage(err.Error()) } diff --git a/internal/clicompat/help.go b/internal/clicompat/help.go index bdb5e1fbda..b92676961d 100644 --- a/internal/clicompat/help.go +++ b/internal/clicompat/help.go @@ -3,6 +3,8 @@ package clicompat import ( "context" "fmt" + "io" + "os" "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/cmderrors" @@ -30,9 +32,34 @@ func wrapWithHelpOnUsageError(action cli.ActionFunc) cli.ActionFunc { return func(ctx context.Context, cmd *cli.Command) error { err := action(ctx, cmd) if err != nil && errors.HasType[*cmderrors.UsageError](err) { - _, _ = fmt.Fprintf(cmd.Root().ErrWriter, "error: %s\n---\n", err) - cli.DefaultPrintHelp(cmd.Root().ErrWriter, cmd.CustomHelpTemplate, cmd) + out := errWriter(cmd) + _, _ = fmt.Fprintf(out, "error: %s\n---\n", err) + printCommandHelp(out, cmd) } return err } } + +func errWriter(cmd *cli.Command) io.Writer { + if cmd == nil || cmd.Root() == nil || cmd.Root().ErrWriter == nil { + return os.Stderr + } + return cmd.Root().ErrWriter +} + +func printCommandHelp(out io.Writer, cmd *cli.Command) { + if cmd == nil { + return + } + + tmpl := cmd.CustomHelpTemplate + if tmpl == "" { + if len(cmd.Commands) == 0 { + tmpl = cli.CommandHelpTemplate + } else { + tmpl = cli.SubcommandHelpTemplate + } + } + + cli.HelpPrinter(out, tmpl, cmd) +} From 284f08b797414d355307c3dd3fd1e95475eb94ed Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Mon, 4 May 2026 17:28:35 +0200 Subject: [PATCH 582/647] remove/cli: drop unused validate commands (#1310) The legacy `src validate` entrypoint is unused, so keeping it around adds dead code and extra maintenance surface in the CLI. This removes the top-level `src validate` command and its `install` and `kube` subcommands, which were still wired through the older command registration path. For more context, see https://sourcegraph.slack.com/archives/C022SPMNR0W/p1777905299691889 ## Test Plan - go test ./cmd/src/... --- cmd/src/validate.go | 44 ------------- cmd/src/validate_install.go | 109 -------------------------------- cmd/src/validate_kube.go | 121 ------------------------------------ 3 files changed, 274 deletions(-) delete mode 100644 cmd/src/validate.go delete mode 100644 cmd/src/validate_install.go delete mode 100644 cmd/src/validate_kube.go diff --git a/cmd/src/validate.go b/cmd/src/validate.go deleted file mode 100644 index ee67f5fa9a..0000000000 --- a/cmd/src/validate.go +++ /dev/null @@ -1,44 +0,0 @@ -package main - -import ( - "flag" - "fmt" -) - -var validateCommands commander - -func init() { - usage := `'src validate' is a tool that validates a Sourcegraph instance. - -EXPERIMENTAL: 'validate' is an experimental command in the 'src' tool. - -Please visit https://docs.sourcegraph.com/admin/validation for documentation of the validate command. - -Usage: - - src validate command [command options] - -The commands are: - - install validates a Sourcegraph installation - kube validates a Sourcegraph deployment on a Kubernetes cluster - -Use "src validate [command] -h" for more information about a command. -` - - flagSet := flag.NewFlagSet("validate", flag.ExitOnError) - handler := func(args []string) error { - validateCommands.run(flagSet, "src validate", usage, args) - return nil - } - - // Register the command - commands = append(commands, &command{ - flagSet: flagSet, - aliases: []string{"validate"}, - handler: handler, - usageFunc: func() { - fmt.Println(usage) - }, - }) -} diff --git a/cmd/src/validate_install.go b/cmd/src/validate_install.go deleted file mode 100644 index b298543f3d..0000000000 --- a/cmd/src/validate_install.go +++ /dev/null @@ -1,109 +0,0 @@ -package main - -import ( - "context" - "flag" - "fmt" - "io" - "os" - "strings" - - "github.com/mattn/go-isatty" - - "github.com/sourcegraph/src-cli/internal/api" - "github.com/sourcegraph/src-cli/internal/validate/install" - - "github.com/sourcegraph/sourcegraph/lib/errors" -) - -func init() { - usage := `'src validate install' is a tool that validates a Sourcegraph installation. - -Examples: - - Run default checks: - - $ src validate install - - Provide a YAML configuration file: - - $ src validate install config.yml - - Provide a JSON configuration file: - - $ src validate install config.json - -Environmental variables - - SRC_GITHUB_TOKEN GitHub access token for validation features - -` - - flagSet := flag.NewFlagSet("install", flag.ExitOnError) - usageFunc := func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src validate %s':\n", flagSet.Name()) - flagSet.PrintDefaults() - fmt.Println(usage) - } - var ( - apiFlags = api.NewFlags(flagSet) - ) - - handler := func(args []string) error { - if err := flagSet.Parse(args); err != nil { - return err - } - - client := cfg.apiClient(apiFlags, flagSet.Output()) - - var validationSpec *install.ValidationSpec - - if len(flagSet.Args()) == 1 { - fileName := flagSet.Arg(0) - f, err := os.ReadFile(fileName) - if err != nil { - return errors.Wrap(err, "failed to read installation validation config from file") - } - - if strings.HasSuffix(fileName, ".yaml") || strings.HasSuffix(fileName, ".yml") { - validationSpec, err = install.LoadYamlConfig(f) - if err != nil { - return err - } - } - - if strings.HasSuffix(fileName, ".json") { - validationSpec, err = install.LoadJsonConfig(f) - if err != nil { - return err - } - } - } - - if !isatty.IsTerminal(os.Stdin.Fd()) { - // stdin is a pipe not a terminal - input, err := io.ReadAll(os.Stdin) - if err != nil { - return errors.Wrap(err, "failed to read installation validation config from pipe") - } - validationSpec, err = install.LoadYamlConfig(input) - if err != nil { - return err - } - } - - if validationSpec == nil { - validationSpec = install.DefaultConfig() - } - - validationSpec.ExternalService.Config.GitHub.Token = os.Getenv("SRC_GITHUB_TOKEN") - - return install.Validate(context.Background(), client, validationSpec) - } - - validateCommands = append(validateCommands, &command{ - flagSet: flagSet, - handler: handler, - usageFunc: usageFunc, - }) -} diff --git a/cmd/src/validate_kube.go b/cmd/src/validate_kube.go deleted file mode 100644 index 46f9374f42..0000000000 --- a/cmd/src/validate_kube.go +++ /dev/null @@ -1,121 +0,0 @@ -package main - -import ( - "context" - "flag" - "fmt" - "path/filepath" - - "k8s.io/client-go/kubernetes" - _ "k8s.io/client-go/plugin/pkg/client/auth/azure" - _ "k8s.io/client-go/plugin/pkg/client/auth/gcp" - "k8s.io/client-go/tools/clientcmd" - "k8s.io/client-go/util/homedir" - - "github.com/sourcegraph/src-cli/internal/validate/kube" - - "github.com/sourcegraph/sourcegraph/lib/errors" -) - -func init() { - usage := `'src validate kube' is a tool that validates a Kubernetes based Sourcegraph deployment - -Examples: - - Run default deployment validation: - $ src validate kube - - Specify Kubernetes namespace: - $ src validate kube --namespace sourcegraph - - Specify the kubeconfig file())) location: - $ src validate kube --kubeconfig ~/.kube/config - - Suppress output (useful for CI/CD pipelines) - $ src validate kube --quiet - - Validate EKS cluster: - $ src validate kube --eks - - Validate GKE cluster: - $ src validate kube --gke - - Validate AKS cluster: - $ src validate kube --aks -` - - flagSet := flag.NewFlagSet("kube", flag.ExitOnError) - usageFunc := func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src validate %s':\n", flagSet.Name()) - flagSet.PrintDefaults() - fmt.Println(usage) - } - - var ( - kubeConfig *string - namespace = flagSet.String("namespace", "", "(optional) specify the kubernetes namespace to use") - quiet = flagSet.Bool("quiet", false, "(optional) suppress output and return exit status only") - eks = flagSet.Bool("eks", false, "(optional) validate EKS cluster") - gke = flagSet.Bool("gke", false, "(optional) validate GKE cluster") - aks = flagSet.Bool("aks", false, "(optional) validate AKS cluster") - ) - - if home := homedir.HomeDir(); home != "" { - kubeConfig = flagSet.String( - "kubeconfig", - filepath.Join(home, ".kube", "config"), - "(optional) absolute path to the kubeconfig file", - ) - } else { - kubeConfig = flagSet.String("kubeconfig", "", "absolute path to the kubeconfig file") - } - - handler := func(args []string) error { - ctx := context.Background() - if err := flagSet.Parse(args); err != nil { - return err - } - - // use the current context in kubeConfig - config, err := clientcmd.BuildConfigFromFlags("", *kubeConfig) - if err != nil { - return errors.Wrap(err, "failed to load kubernetes config") - } - - clientSet, err := kubernetes.NewForConfig(config) - if err != nil { - return errors.Wrap(err, "failed to create kubernetes client") - } - - // parse through flag options - var options []kube.Option - - if *namespace != "" { - options = append(options, kube.WithNamespace(*namespace)) - } - - if *quiet { - options = append(options, kube.Quiet()) - } - - if *eks { - options = append(options, kube.GenerateAWSClients(ctx)) - } - - if *gke { - options = append(options, kube.Gke()) - } - - if *aks { - options = append(options, kube.Aks()) - } - - return kube.Validate(context.Background(), clientSet, config, options...) - } - - validateCommands = append(validateCommands, &command{ - flagSet: flagSet, - handler: handler, - usageFunc: usageFunc, - }) -} From 82de26854f6493605c9ec735916c07e0f96591c1 Mon Sep 17 00:00:00 2001 From: Peter Guy Date: Mon, 4 May 2026 23:48:00 -0700 Subject: [PATCH 583/647] feature: Add support for HTTP_PROXY, HTTPS_PROXY, and NO_PROXY (#1260) --- internal/api/proxy.go | 96 +-------- internal/api/proxy_test.go | 407 +++++++++++++++++++++++++++++++++++++ 2 files changed, 416 insertions(+), 87 deletions(-) create mode 100644 internal/api/proxy_test.go diff --git a/internal/api/proxy.go b/internal/api/proxy.go index 9589b9beb5..38b489367f 100644 --- a/internal/api/proxy.go +++ b/internal/api/proxy.go @@ -1,11 +1,8 @@ package api import ( - "bufio" "context" "crypto/tls" - "encoding/base64" - "fmt" "net" "net/http" "net/url" @@ -15,8 +12,8 @@ import ( // // Note: baseTransport is considered to be a clone created with transport.Clone() // -// - If a the proxyPath is not empty, a unix socket proxy is created. -// - Otherwise, the proxyURL is used to determine if we should proxy socks5 / http connections +// - If proxyPath is not empty, a unix socket proxy is created. +// - Otherwise, proxyURL is used to determine if we should proxy socks5 / http connections func withProxyTransport(baseTransport *http.Transport, proxyURL *url.URL, proxyPath string) *http.Transport { handshakeTLS := func(ctx context.Context, conn net.Conn, addr string) (net.Conn, error) { // Extract the hostname (without the port) for TLS SNI @@ -24,13 +21,13 @@ func withProxyTransport(baseTransport *http.Transport, proxyURL *url.URL, proxyP if err != nil { return nil, err } - tlsConn := tls.Client(conn, &tls.Config{ - ServerName: host, - // Pull InsecureSkipVerify from the target host transport - // so that insecure-skip-verify flag settings are honored for the proxy server - InsecureSkipVerify: baseTransport.TLSClientConfig.InsecureSkipVerify, - }) + cfg := baseTransport.TLSClientConfig.Clone() + if cfg.ServerName == "" { + cfg.ServerName = host + } + tlsConn := tls.Client(conn, cfg) if err := tlsConn.HandshakeContext(ctx); err != nil { + tlsConn.Close() return nil, err } return tlsConn, nil @@ -53,82 +50,7 @@ func withProxyTransport(baseTransport *http.Transport, proxyURL *url.URL, proxyP // clear out any system proxy settings baseTransport.Proxy = nil } else if proxyURL != nil { - switch proxyURL.Scheme { - case "socks5", "socks5h": - // SOCKS proxies work out of the box - no need to manually dial - baseTransport.Proxy = http.ProxyURL(proxyURL) - case "http", "https": - dial := func(ctx context.Context, network, addr string) (net.Conn, error) { - // Dial the proxy - d := net.Dialer{} - conn, err := d.DialContext(ctx, "tcp", proxyURL.Host) - if err != nil { - return nil, err - } - - // this is the whole point of manually dialing the HTTP(S) proxy: - // being able to force HTTP/1. - // When relying on Transport.Proxy, the protocol is always HTTP/2, - // but many proxy servers don't support HTTP/2. - // We don't want to disable HTTP/2 in general because we want to use it when - // connecting to the Sourcegraph API, using HTTP/1 for the proxy connection only. - protocol := "HTTP/1.1" - - // CONNECT is the HTTP method used to set up a tunneling connection with a proxy - method := "CONNECT" - - // Manually writing out the HTTP commands because it's not complicated, - // and http.Request has some janky behavior: - // - ignores the Proto field and hard-codes the protocol to HTTP/1.1 - // - ignores the Host Header (Header.Set("Host", host)) and uses URL.Host instead. - // - When the Host field is set, overrides the URL field - connectReq := fmt.Sprintf("%s %s %s\r\n", method, addr, protocol) - - // A Host header is required per RFC 2616, section 14.23 - connectReq += fmt.Sprintf("Host: %s\r\n", addr) - - // use authentication if proxy credentials are present - if proxyURL.User != nil { - password, _ := proxyURL.User.Password() - auth := base64.StdEncoding.EncodeToString([]byte(proxyURL.User.Username() + ":" + password)) - connectReq += fmt.Sprintf("Proxy-Authorization: Basic %s\r\n", auth) - } - - // finish up with an extra carriage return + newline, as per RFC 7230, section 3 - connectReq += "\r\n" - - // Send the CONNECT request to the proxy to establish the tunnel - if _, err := conn.Write([]byte(connectReq)); err != nil { - conn.Close() - return nil, err - } - - // Read and check the response from the proxy - resp, err := http.ReadResponse(bufio.NewReader(conn), nil) - if err != nil { - conn.Close() - return nil, err - } - if resp.StatusCode != http.StatusOK { - conn.Close() - return nil, fmt.Errorf("failed to connect to proxy %v: %v", proxyURL, resp.Status) - } - resp.Body.Close() - return conn, nil - } - dialTLS := func(ctx context.Context, network, addr string) (net.Conn, error) { - // Dial the underlying connection through the proxy - conn, err := dial(ctx, network, addr) - if err != nil { - return nil, err - } - return handshakeTLS(ctx, conn, addr) - } - baseTransport.DialContext = dial - baseTransport.DialTLSContext = dialTLS - // clear out any system proxy settings - baseTransport.Proxy = nil - } + baseTransport.Proxy = http.ProxyURL(proxyURL) } return baseTransport diff --git a/internal/api/proxy_test.go b/internal/api/proxy_test.go new file mode 100644 index 0000000000..4b2980e712 --- /dev/null +++ b/internal/api/proxy_test.go @@ -0,0 +1,407 @@ +package api + +import ( + "crypto/tls" + "fmt" + "io" + "net" + "net/http" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "runtime" + "strings" + "sync" + "sync/atomic" + "testing" + "time" +) + +// startTargetServer starts an HTTPS server that responds with "ok". +func startTargetServer(t *testing.T) *httptest.Server { + t.Helper() + srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fmt.Fprintln(w, "ok") + })) + srv.EnableHTTP2 = true + srv.StartTLS() + t.Cleanup(srv.Close) + return srv +} + +// newTestTransport creates a base transport with TLS verification disabled. +func newTestTransport() *http.Transport { + transport := http.DefaultTransport.(*http.Transport).Clone() + transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} + return transport +} + +// startCONNECTProxy starts an HTTP CONNECT proxy. If useTLS is true, the proxy +// itself listens over TLS. The returned *atomic.Bool is set to true when the +// proxy handles a request. +func startCONNECTProxy(t *testing.T, useTLS bool) (proxyURL *url.URL, used *atomic.Bool) { + t.Helper() + + used = &atomic.Bool{} + + srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + used.Store(true) + + if r.Method != http.MethodConnect { + http.Error(w, "expected CONNECT", http.StatusMethodNotAllowed) + return + } + + destConn, err := net.DialTimeout("tcp", r.Host, 10*time.Second) + if err != nil { + http.Error(w, err.Error(), http.StatusBadGateway) + return + } + defer destConn.Close() + + hijacker, ok := w.(http.Hijacker) + if !ok { + http.Error(w, "hijacking not supported", http.StatusInternalServerError) + return + } + + w.WriteHeader(http.StatusOK) + clientConn, bufrw, err := hijacker.Hijack() + if err != nil { + return + } + + var wg sync.WaitGroup + var once sync.Once + closeBoth := func() { + clientConn.Close() + destConn.Close() + } + defer once.Do(closeBoth) + + wg.Add(2) + go func() { + defer wg.Done() + io.Copy(destConn, bufrw) + once.Do(closeBoth) + }() + go func() { + defer wg.Done() + io.Copy(clientConn, destConn) + once.Do(closeBoth) + }() + wg.Wait() + })) + + if useTLS { + srv.StartTLS() + } else { + srv.Start() + } + t.Cleanup(srv.Close) + + pURL, _ := url.Parse(srv.URL) + return pURL, used +} + +// startUDSForwarder creates a unix domain socket that forwards TCP traffic +// to the given target address. Returns the socket path and an *atomic.Bool +// that indicates whether the socket was used. +func startUDSForwarder(t *testing.T, targetAddr string) (socketPath string, used *atomic.Bool) { + t.Helper() + + socketPath = filepath.Join("/tmp", fmt.Sprintf("src-cli-test-%d.sock", time.Now().UnixNano())) + t.Cleanup(func() { os.Remove(socketPath) }) + + ln, err := net.Listen("unix", socketPath) + if err != nil { + t.Fatalf("listen unix: %v", err) + } + t.Cleanup(func() { ln.Close() }) + + used = &atomic.Bool{} + + go func() { + for { + conn, err := ln.Accept() + if err != nil { + return + } + used.Store(true) + go func() { + defer conn.Close() + dest, err := net.DialTimeout("tcp", targetAddr, 10*time.Second) + if err != nil { + return + } + defer dest.Close() + var wg sync.WaitGroup + wg.Add(2) + go func() { defer wg.Done(); io.Copy(dest, conn) }() + go func() { defer wg.Done(); io.Copy(conn, dest) }() + wg.Wait() + }() + } + }() + + return socketPath, used +} + +func doGET(t *testing.T, transport *http.Transport, targetURL string) { + t.Helper() + transport.CloseIdleConnections() + t.Cleanup(transport.CloseIdleConnections) + client := &http.Client{Transport: transport, Timeout: 10 * time.Second} + + resp, err := client.Get(targetURL) + if err != nil { + t.Fatalf("GET: %v", err) + } + defer resp.Body.Close() + body, _ := io.ReadAll(resp.Body) + + if resp.StatusCode != http.StatusOK { + t.Errorf("expected status 200, got %d", resp.StatusCode) + } + if got := strings.TrimSpace(string(body)); got != "ok" { + t.Errorf("expected body 'ok', got %q", got) + } +} + +func TestWithProxyTransport_HTTPProxy(t *testing.T) { + target := startTargetServer(t) + proxyURL, used := startCONNECTProxy(t, false) + + transport := withProxyTransport(newTestTransport(), proxyURL, "") + doGET(t, transport, target.URL) + + if !used.Load() { + t.Fatal("HTTP proxy was never used") + } +} + +func TestWithProxyTransport_HTTPSProxy(t *testing.T) { + target := startTargetServer(t) + proxyURL, used := startCONNECTProxy(t, true) + + transport := withProxyTransport(newTestTransport(), proxyURL, "") + doGET(t, transport, target.URL) + + if !used.Load() { + t.Fatal("HTTPS proxy was never used") + } +} + +func TestWithProxyTransport_UDSProxy(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("Unix domain sockets are not supported on Windows") + } + target := startTargetServer(t) + targetURL, _ := url.Parse(target.URL) + + socketPath, used := startUDSForwarder(t, targetURL.Host) + + transport := withProxyTransport(newTestTransport(), nil, socketPath) + doGET(t, transport, target.URL) + + if !used.Load() { + t.Fatal("unix socket proxy was never used") + } +} + +func TestWithProxyTransport_UDSClearsSystemProxy(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("Unix domain sockets are not supported on Windows") + } + target := startTargetServer(t) + targetURL, _ := url.Parse(target.URL) + + // Start a real proxy so we can verify it is NOT used. + envProxyURL, envProxyUsed := startCONNECTProxy(t, false) + t.Setenv("HTTPS_PROXY", envProxyURL.String()) + + socketPath, udsUsed := startUDSForwarder(t, targetURL.Host) + + // proxyPath should win: Proxy must be set to nil (disabling + // HTTPS_PROXY) and traffic must go through the unix socket. + transport := withProxyTransport(newTestTransport(), nil, socketPath) + + if transport.Proxy != nil { + t.Fatal("expected Proxy to be nil when proxyPath is set") + } + + doGET(t, transport, target.URL) + + if envProxyUsed.Load() { + t.Fatal("HTTPS_PROXY was used despite proxyPath being set") + } + if !udsUsed.Load() { + t.Fatal("unix socket proxy was never used") + } +} + +func TestWithProxyTransport_NilProxyPreservesDefault(t *testing.T) { + transport := newTestTransport() + originalProxy := transport.Proxy + + result := withProxyTransport(transport, nil, "") + + // When neither proxyURL nor proxyPath is set, the function should + // not modify the transport at all — the default Proxy function + // (which reads HTTPS_PROXY/NO_PROXY) should remain. + if result != transport { + t.Fatal("expected same transport to be returned") + } + // Proxy should remain at whatever the default was (http.ProxyFromEnvironment) + if originalProxy != nil && result.Proxy == nil { + t.Fatal("Proxy function was unexpectedly cleared") + } +} + +func TestBuildTransport_WithProxyURL(t *testing.T) { + target := startTargetServer(t) + proxyURL, used := startCONNECTProxy(t, false) + + insecure := true + flags := &Flags{ + insecureSkipVerify: &insecure, + dump: boolPtr(false), + getCurl: boolPtr(false), + trace: boolPtr(false), + userAgentTelemetry: boolPtr(false), + } + opts := ClientOpts{ + ProxyURL: proxyURL, + } + + transport := buildTransport(opts, flags) + httpTransport := transport.(*http.Transport) + doGET(t, httpTransport, target.URL) + + if !used.Load() { + t.Fatal("proxy was not used via buildTransport") + } +} + +func TestBuildTransport_WithProxyPath(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("Unix domain sockets are not supported on Windows") + } + target := startTargetServer(t) + targetURL, _ := url.Parse(target.URL) + + socketPath, used := startUDSForwarder(t, targetURL.Host) + + insecure := true + flags := &Flags{ + insecureSkipVerify: &insecure, + dump: boolPtr(false), + getCurl: boolPtr(false), + trace: boolPtr(false), + userAgentTelemetry: boolPtr(false), + } + opts := ClientOpts{ + ProxyPath: socketPath, + } + + transport := buildTransport(opts, flags) + httpTransport := transport.(*http.Transport) + doGET(t, httpTransport, target.URL) + + if !used.Load() { + t.Fatal("UDS proxy was not used via buildTransport") + } +} + +func TestBuildTransport_NoProxyPreservesProxyFunc(t *testing.T) { + // When no ProxyURL/ProxyPath is set, buildTransport should not + // override the transport's Proxy function. This means Go's default + // http.ProxyFromEnvironment (reading HTTPS_PROXY/NO_PROXY) remains active. + // + // We verify this structurally: the Proxy field should still be set + // (not nil), meaning environment-based proxy resolution is preserved. + insecure := true + flags := &Flags{ + insecureSkipVerify: &insecure, + dump: boolPtr(false), + getCurl: boolPtr(false), + trace: boolPtr(false), + userAgentTelemetry: boolPtr(false), + } + opts := ClientOpts{} // no ProxyURL or ProxyPath + + transport := buildTransport(opts, flags) + httpTransport := transport.(*http.Transport) + + if httpTransport.Proxy == nil { + t.Fatal("expected Proxy function to be preserved (for HTTPS_PROXY/NO_PROXY support)") + } +} + +func TestBuildTransport_NOPROXYOverridesHTTPSPROXY(t *testing.T) { + target := startTargetServer(t) + targetURL, _ := url.Parse(target.URL) + host, _, _ := net.SplitHostPort(targetURL.Host) + + proxyURL, used := startCONNECTProxy(t, false) + + // Set HTTPS_PROXY and also NO_PROXY for the target host. + t.Setenv("HTTPS_PROXY", proxyURL.String()) + t.Setenv("NO_PROXY", host) + + insecure := true + flags := &Flags{ + insecureSkipVerify: &insecure, + dump: boolPtr(false), + getCurl: boolPtr(false), + trace: boolPtr(false), + userAgentTelemetry: boolPtr(false), + } + opts := ClientOpts{} // no ProxyURL or ProxyPath + + transport := buildTransport(opts, flags) + httpTransport := transport.(*http.Transport) + doGET(t, httpTransport, target.URL) + + // The proxy should NOT have been used because NO_PROXY matches the target. + if used.Load() { + t.Fatal("proxy was used despite NO_PROXY matching the target host") + } +} + +func TestBuildTransport_ExplicitProxyURLOverridesNOPROXY(t *testing.T) { + // When ProxyURL is explicitly set (as readConfig does when SRC_PROXY is + // set), it takes precedence over NO_PROXY because withProxyTransport + // replaces transport.Proxy with http.ProxyURL, bypassing ProxyFromEnvironment. + target := startTargetServer(t) + targetURL, _ := url.Parse(target.URL) + host, _, _ := net.SplitHostPort(targetURL.Host) + + proxyURL, used := startCONNECTProxy(t, false) + + // NO_PROXY matches the target, but SRC_PROXY (via ProxyURL) should override. + t.Setenv("NO_PROXY", host) + + insecure := true + flags := &Flags{ + insecureSkipVerify: &insecure, + dump: boolPtr(false), + getCurl: boolPtr(false), + trace: boolPtr(false), + userAgentTelemetry: boolPtr(false), + } + opts := ClientOpts{ + ProxyURL: proxyURL, + } + + transport := buildTransport(opts, flags) + httpTransport := transport.(*http.Transport) + doGET(t, httpTransport, target.URL) + + if !used.Load() { + t.Fatal("explicit ProxyURL did not override NO_PROXY") + } +} + +func boolPtr(b bool) *bool { return &b } From cacf3c0ce7305269627c7d07ca5f214483e3c23d Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Wed, 6 May 2026 10:55:06 +0200 Subject: [PATCH 584/647] fix: still exit with non-zero when there is an unknown err (#1312) --- cmd/src/run_migration_compat.go | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/cmd/src/run_migration_compat.go b/cmd/src/run_migration_compat.go index 52baca0fc5..b27b04f0ac 100644 --- a/cmd/src/run_migration_compat.go +++ b/cmd/src/run_migration_compat.go @@ -66,19 +66,24 @@ func runMigrated() (int, error) { ctx := context.Background() err := migratedRootCommand().Run(ctx, os.Args) - if errors.HasType[*cmderrors.UsageError](err) { - return 2, nil - } - if e, ok := err.(*cmderrors.ExitCodeError); ok { - if e.HasError() { - return e.Code(), e + if err != nil { + if errors.HasType[*cmderrors.UsageError](err) { + return 2, nil } - return e.Code(), nil - } - var exitErr cli.ExitCoder - if errors.AsInterface(err, &exitErr) { - return exitErr.ExitCode(), err + if e, ok := err.(*cmderrors.ExitCodeError); ok { + if e.HasError() { + return e.Code(), e + } + return e.Code(), nil + } + var exitErr cli.ExitCoder + if errors.AsInterface(err, &exitErr) { + return exitErr.ExitCode(), err + } + + return 1, err } + return 0, err } From f9222093b540748841f029f03250c7e0bdf18475 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Wed, 6 May 2026 11:02:49 +0200 Subject: [PATCH 585/647] fix: print command help and provide an error for unknown command (#1311) --- internal/clicompat/help.go | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/internal/clicompat/help.go b/internal/clicompat/help.go index b92676961d..5fc1b87219 100644 --- a/internal/clicompat/help.go +++ b/internal/clicompat/help.go @@ -20,7 +20,13 @@ func Wrap(cmd *cli.Command) *cli.Command { cmd.OnUsageError = OnUsageError if cmd.Action == nil { cmd.Action = func(ctx context.Context, cmd *cli.Command) error { - return cli.ShowSubcommandHelp(cmd) + if err := cli.ShowSubcommandHelp(cmd); err != nil { + return err + } + if cmd.Args().Len() > 0 { + return errors.Newf("Unknown subcommand: %s", cmd.Args().First()) + } + return nil } } else { cmd.Action = wrapWithHelpOnUsageError(cmd.Action) From fcb99398452e78a473f3cf30776b0cf4eeaceb1e Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Wed, 6 May 2026 11:14:01 +0200 Subject: [PATCH 586/647] feat: migrate codeowners to urfave/cli (#1313) --- cmd/src/codeowners.go | 72 +++++++++++----------- cmd/src/codeowners_create.go | 104 ++++++++++++-------------------- cmd/src/codeowners_delete.go | 70 +++++++++------------ cmd/src/codeowners_get.go | 78 ++++++++++-------------- cmd/src/codeowners_update.go | 103 ++++++++++++------------------- cmd/src/run_migration_compat.go | 13 ++-- 6 files changed, 187 insertions(+), 253 deletions(-) diff --git a/cmd/src/codeowners.go b/cmd/src/codeowners.go index 47b9cee19b..bf0074327a 100644 --- a/cmd/src/codeowners.go +++ b/cmd/src/codeowners.go @@ -1,48 +1,28 @@ package main import ( - "flag" - "fmt" "io" "os" -) -var codeownersCommands commander + "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/src-cli/internal/clicompat" + "github.com/urfave/cli/v3" +) -func init() { - usage := `'src codeowners' is a tool that manages ingested code ownership data in a Sourcegraph instance. +const codeownersExamples = `'src codeowners' manages ingested code ownership data in a Sourcegraph instance. Usage: - src codeowners command [command options] + src codeowners [command options] -The commands are: +Examples: - get returns the codeowners file for a repository, if exists - create create a codeowners file - update update a codeowners file - delete delete a codeowners file - -Use "src codeowners [command] -h" for more information about a command. + $ src codeowners get -repo='github.com/sourcegraph/sourcegraph' + $ src codeowners create -repo='github.com/sourcegraph/sourcegraph' -f CODEOWNERS + $ src codeowners update -repo='github.com/sourcegraph/sourcegraph' -f CODEOWNERS + $ src codeowners delete -repo='github.com/sourcegraph/sourcegraph' ` - flagSet := flag.NewFlagSet("codeowners", flag.ExitOnError) - handler := func(args []string) error { - codeownersCommands.run(flagSet, "src codeowners", usage, args) - return nil - } - - // Register the command. - commands = append(commands, &command{ - flagSet: flagSet, - aliases: []string{"codeowner"}, - handler: handler, - usageFunc: func() { - fmt.Println(usage) - }, - }) -} - const codeownersFragment = ` fragment CodeownersFileFields on CodeownersIngestedFile { contents @@ -59,9 +39,33 @@ type CodeownersIngestedFile struct { } `json:"repository"` } -func readFile(f string) (io.Reader, error) { +var codeownersCommand = clicompat.Wrap(&cli.Command{ + Name: "codeowners", + Aliases: []string{"codeowner"}, + Usage: "manages ingested code ownership data", + UsageText: "src codeowners [command options]", + Description: codeownersExamples, + HideVersion: true, + Commands: []*cli.Command{ + codeownersGetCommand, + codeownersCreateCommand, + codeownersUpdateCommand, + codeownersDeleteCommand, + }, +}) + +func readFile(f string) ([]byte, error) { if f == "-" { - return os.Stdin, nil + return io.ReadAll(os.Stdin) + } + return os.ReadFile(f) +} + +func requiresNotEmpty(errMsg string) func(string) error { + return func(value string) error { + if value == "" { + return errors.New(errMsg) + } + return nil } - return os.Open(f) } diff --git a/cmd/src/codeowners_create.go b/cmd/src/codeowners_create.go index cb489b0695..b446743896 100644 --- a/cmd/src/codeowners_create.go +++ b/cmd/src/codeowners_create.go @@ -2,74 +2,57 @@ package main import ( "context" - "flag" - "fmt" - "io" "strings" "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/clicompat" "github.com/sourcegraph/src-cli/internal/cmderrors" + "github.com/urfave/cli/v3" ) -func init() { - usage := ` -Examples: - - Create a codeowners file for the repository "github.com/sourcegraph/sourcegraph": - - $ src codeowners create -repo='github.com/sourcegraph/sourcegraph' -f CODEOWNERS +const codeownersCreateExamples = ` +Create a codeowners file for a repository. - Create a codeowners file for the repository "github.com/sourcegraph/sourcegraph" from stdin: +Examples: - $ src codeowners create -repo='github.com/sourcegraph/sourcegraph' -f - + $ src codeowners create -repo='github.com/sourcegraph/sourcegraph' -f CODEOWNERS + $ src codeowners create -repo='github.com/sourcegraph/sourcegraph' -f - ` - flagSet := flag.NewFlagSet("create", flag.ExitOnError) - usageFunc := func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src codeowners %s':\n", flagSet.Name()) - flagSet.PrintDefaults() - fmt.Println(usage) - } - var ( - repoFlag = flagSet.String("repo", "", "The repository to attach the data to") - fileFlag = flagSet.String("file", "", "File path to read ownership information from (- for stdin)") - fileShortFlag = flagSet.String("f", "", "File path to read ownership information from (- for stdin). Alias for -file") - - apiFlags = api.NewFlags(flagSet) - ) - - handler := func(args []string) error { - if err := flagSet.Parse(args); err != nil { - return err - } - - if *repoFlag == "" { - return errors.New("provide a repo name using -repo") - } - - if *fileFlag == "" && *fileShortFlag == "" { - return errors.New("provide a file using -file") - } - if *fileFlag != "" && *fileShortFlag != "" { - return errors.New("have to provide either -file or -f") - } - if *fileShortFlag != "" { - *fileFlag = *fileShortFlag - } - - file, err := readFile(*fileFlag) +var codeownersCreateCommand = clicompat.Wrap(&cli.Command{ + Name: "create", + Usage: "create a codeowners file", + UsageText: "src codeowners create [options]", + Description: codeownersCreateExamples, + HideVersion: true, + Flags: clicompat.WithAPIFlags( + &cli.StringFlag{ + Name: "repo", + Usage: "The repository to attach the data to", + Required: true, + Validator: requiresNotEmpty("provide a repo name using -repo"), + }, + &cli.StringFlag{ + Name: "file", + Aliases: []string{"f"}, + Usage: "File path to read ownership information from (- for stdin)", + TakesFile: true, + Required: true, + Validator: requiresNotEmpty("provide a file using -file"), + }, + ), + Action: func(ctx context.Context, cmd *cli.Command) error { + repoName := cmd.String("repo") + fileName := cmd.String("file") + + content, err := readFile(fileName) if err != nil { return err } - content, err := io.ReadAll(file) - if err != nil { - return err - } - - client := cfg.apiClient(apiFlags, flagSet.Output()) + client := cfg.apiClient(clicompat.APIFlagsFromCmd(cmd), cmd.Writer) query := `mutation CreateCodeownersFile( $repoName: String!, @@ -89,14 +72,14 @@ Examples: AddCodeownersFile CodeownersIngestedFile } if ok, err := client.NewRequest(query, map[string]any{ - "repoName": *repoFlag, + "repoName": repoName, "content": string(content), - }).Do(context.Background(), &result); err != nil || !ok { + }).Do(ctx, &result); err != nil || !ok { var gqlErr api.GraphQlErrors if errors.As(err, &gqlErr) { for _, e := range gqlErr { if strings.Contains(e.Error(), "repo not found:") { - return cmderrors.ExitCode(2, errors.Newf("repository %q not found", *repoFlag)) + return cmderrors.ExitCode(2, errors.Newf("repository %q not found", repoName)) } if strings.Contains(e.Error(), "codeowners file has already been ingested for this repository") { return cmderrors.ExitCode(2, errors.New("codeowners file has already been ingested for this repository")) @@ -107,12 +90,5 @@ Examples: } return nil - } - - // Register the command. - codeownersCommands = append(codeownersCommands, &command{ - flagSet: flagSet, - handler: handler, - usageFunc: usageFunc, - }) -} + }, +}) diff --git a/cmd/src/codeowners_delete.go b/cmd/src/codeowners_delete.go index f6655c30e7..11e1e901e7 100644 --- a/cmd/src/codeowners_delete.go +++ b/cmd/src/codeowners_delete.go @@ -2,46 +2,41 @@ package main import ( "context" - "flag" - "fmt" "strings" "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/clicompat" "github.com/sourcegraph/src-cli/internal/cmderrors" + "github.com/urfave/cli/v3" ) -func init() { - usage := ` -Examples: +const codeownersDeleteExamples = ` +Delete a codeowners file for a repository. - Delete a codeowners file for the repository "github.com/sourcegraph/sourcegraph": +Examples: - $ src codeowners delete -repo='github.com/sourcegraph/sourcegraph' + $ src codeowners delete -repo='github.com/sourcegraph/sourcegraph' ` - flagSet := flag.NewFlagSet("delete", flag.ExitOnError) - usageFunc := func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src codeowners %s':\n", flagSet.Name()) - flagSet.PrintDefaults() - fmt.Println(usage) - } - var ( - repoFlag = flagSet.String("repo", "", "The repository to delete the data for") - apiFlags = api.NewFlags(flagSet) - ) - - handler := func(args []string) error { - if err := flagSet.Parse(args); err != nil { - return err - } - - if *repoFlag == "" { - return errors.New("provide a repo name using -repo") - } - - client := cfg.apiClient(apiFlags, flagSet.Output()) +var codeownersDeleteCommand = clicompat.Wrap(&cli.Command{ + Name: "delete", + Usage: "delete a codeowners file", + UsageText: "src codeowners delete [options]", + Description: codeownersDeleteExamples, + HideVersion: true, + Flags: clicompat.WithAPIFlags( + &cli.StringFlag{ + Name: "repo", + Usage: "The repository to delete the data for", + Required: true, + Validator: requiresNotEmpty("provide a repo name using -repo"), + }, + ), + Action: func(ctx context.Context, cmd *cli.Command) error { + repoName := cmd.String("repo") + client := cfg.apiClient(clicompat.APIFlagsFromCmd(cmd), cmd.Writer) query := `mutation DeleteCodeownersFile( $repoName: String!, @@ -58,16 +53,16 @@ Examples: DeleteCodeownersFile CodeownersIngestedFile } if ok, err := client.NewRequest(query, map[string]any{ - "repoName": *repoFlag, - }).Do(context.Background(), &result); err != nil || !ok { + "repoName": repoName, + }).Do(ctx, &result); err != nil || !ok { var gqlErr api.GraphQlErrors if errors.As(err, &gqlErr) { for _, e := range gqlErr { if strings.Contains(e.Error(), "repo not found:") { - return cmderrors.ExitCode(2, errors.Newf("repository %q not found", *repoFlag)) + return cmderrors.ExitCode(2, errors.Newf("repository %q not found", repoName)) } if strings.Contains(e.Error(), "codeowners file not found:") { - return cmderrors.ExitCode(2, errors.Newf("no data found for repository %q", *repoFlag)) + return cmderrors.ExitCode(2, errors.Newf("no data found for repository %q", repoName)) } } } @@ -75,12 +70,5 @@ Examples: } return nil - } - - // Register the command. - codeownersCommands = append(codeownersCommands, &command{ - flagSet: flagSet, - handler: handler, - usageFunc: usageFunc, - }) -} + }, +}) diff --git a/cmd/src/codeowners_get.go b/cmd/src/codeowners_get.go index e1e1e2fa03..c781f427c6 100644 --- a/cmd/src/codeowners_get.go +++ b/cmd/src/codeowners_get.go @@ -2,53 +2,47 @@ package main import ( "context" - "flag" "fmt" - "os" "github.com/sourcegraph/sourcegraph/lib/errors" - "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/clicompat" "github.com/sourcegraph/src-cli/internal/cmderrors" + "github.com/urfave/cli/v3" ) -func init() { - usage := ` -Examples: +const codeownersGetExamples = ` +Read the current codeowners file for a repository. - Read the current codeowners file for the repository "github.com/sourcegraph/sourcegraph": +Examples: - $ src codeowners get -repo='github.com/sourcegraph/sourcegraph' + $ src codeowners get -repo='github.com/sourcegraph/sourcegraph' ` - flagSet := flag.NewFlagSet("get", flag.ExitOnError) - usageFunc := func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src codeowners %s':\n", flagSet.Name()) - flagSet.PrintDefaults() - fmt.Println(usage) - } - var ( - repoFlag = flagSet.String("repo", "", "The repository to attach the data to") - apiFlags = api.NewFlags(flagSet) - ) - - handler := func(args []string) error { - if err := flagSet.Parse(args); err != nil { - return err - } - - if *repoFlag == "" { - return errors.New("provide a repo name using -repo") - } - - client := cfg.apiClient(apiFlags, flagSet.Output()) +var codeownersGetCommand = clicompat.Wrap(&cli.Command{ + Name: "get", + Usage: "returns the codeowners file for a repository, if it exists", + UsageText: "src codeowners get [options]", + Description: codeownersGetExamples, + HideVersion: true, + Flags: clicompat.WithAPIFlags( + &cli.StringFlag{ + Name: "repo", + Usage: "The repository to attach the data to", + Required: true, + Validator: requiresNotEmpty("provide a repo name using -repo"), + }, + ), + Action: func(ctx context.Context, cmd *cli.Command) error { + repoName := cmd.String("repo") + client := cfg.apiClient(clicompat.APIFlagsFromCmd(cmd), cmd.Writer) query := `query GetCodeownersFile( $repoName: String! ) { repository(name: $repoName) { ingestedCodeowners { - ...CodeownersFileFields + ...CodeownersFileFields } } } @@ -60,28 +54,20 @@ Examples: } } if ok, err := client.NewRequest(query, map[string]any{ - "repoName": *repoFlag, - }).Do(context.Background(), &result); err != nil || !ok { + "repoName": repoName, + }).Do(ctx, &result); err != nil || !ok { return err } if result.Repository == nil { - return cmderrors.ExitCode(2, errors.Newf("repository %q not found", *repoFlag)) + return cmderrors.ExitCode(2, errors.Newf("repository %q not found", repoName)) } if result.Repository.IngestedCodeowners == nil { - return cmderrors.ExitCode(2, errors.Newf("no codeowners data found for %q", *repoFlag)) + return cmderrors.ExitCode(2, errors.Newf("no codeowners data found for %q", repoName)) } - fmt.Fprintf(os.Stdout, "%s", result.Repository.IngestedCodeowners.Contents) - - return nil - } - - // Register the command. - codeownersCommands = append(codeownersCommands, &command{ - flagSet: flagSet, - handler: handler, - usageFunc: usageFunc, - }) -} + _, err := fmt.Fprint(cmd.Writer, result.Repository.IngestedCodeowners.Contents) + return err + }, +}) diff --git a/cmd/src/codeowners_update.go b/cmd/src/codeowners_update.go index 222482e656..c0c7c01ed0 100644 --- a/cmd/src/codeowners_update.go +++ b/cmd/src/codeowners_update.go @@ -2,73 +2,57 @@ package main import ( "context" - "flag" - "fmt" - "io" "strings" "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/clicompat" "github.com/sourcegraph/src-cli/internal/cmderrors" + "github.com/urfave/cli/v3" ) -func init() { - usage := ` -Examples: - - Update a codeowners file for the repository "github.com/sourcegraph/sourcegraph": - - $ src codeowners update -repo='github.com/sourcegraph/sourcegraph' -f CODEOWNERS +const codeownersUpdateExamples = ` +Update a codeowners file for a repository. - Update a codeowners file for the repository "github.com/sourcegraph/sourcegraph" from stdin: +Examples: - $ src codeowners update -repo='github.com/sourcegraph/sourcegraph' -f - + $ src codeowners update -repo='github.com/sourcegraph/sourcegraph' -f CODEOWNERS + $ src codeowners update -repo='github.com/sourcegraph/sourcegraph' -f - ` - flagSet := flag.NewFlagSet("update", flag.ExitOnError) - usageFunc := func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src codeowners %s':\n", flagSet.Name()) - flagSet.PrintDefaults() - fmt.Println(usage) - } - var ( - repoFlag = flagSet.String("repo", "", "The repository to attach the data to") - fileFlag = flagSet.String("file", "", "File path to read ownership information from (- for stdin)") - fileShortFlag = flagSet.String("f", "", "File path to read ownership information from (- for stdin). Alias for -file") - apiFlags = api.NewFlags(flagSet) - ) - - handler := func(args []string) error { - if err := flagSet.Parse(args); err != nil { - return err - } - - if *repoFlag == "" { - return errors.New("provide a repo name using -repo") - } - - if *fileFlag == "" && *fileShortFlag == "" { - return errors.New("provide a file using -file") - } - if *fileFlag != "" && *fileShortFlag != "" { - return errors.New("have to provide either -file or -f") - } - if *fileShortFlag != "" { - *fileFlag = *fileShortFlag - } - - file, err := readFile(*fileFlag) +var codeownersUpdateCommand = clicompat.Wrap(&cli.Command{ + Name: "update", + Usage: "update a codeowners file", + UsageText: "src codeowners update [options]", + Description: codeownersUpdateExamples, + HideVersion: true, + Flags: clicompat.WithAPIFlags( + &cli.StringFlag{ + Name: "repo", + Usage: "The repository to attach the data to", + Required: true, + Validator: requiresNotEmpty("provide a repo name using -repo"), + }, + &cli.StringFlag{ + Name: "file", + Aliases: []string{"f"}, + Usage: "File path to read ownership information from (- for stdin)", + TakesFile: true, + Required: true, + Validator: requiresNotEmpty("provide a file using -file"), + }, + ), + Action: func(ctx context.Context, cmd *cli.Command) error { + repoName := cmd.String("repo") + fileName := cmd.String("file") + + content, err := readFile(fileName) if err != nil { return err } - content, err := io.ReadAll(file) - if err != nil { - return err - } - - client := cfg.apiClient(apiFlags, flagSet.Output()) + client := cfg.apiClient(clicompat.APIFlagsFromCmd(cmd), cmd.Writer) query := `mutation UpdateCodeownersFile( $repoName: String!, @@ -87,14 +71,14 @@ Examples: UpdateCodeownersFile CodeownersIngestedFile } if ok, err := client.NewRequest(query, map[string]any{ - "repoName": *repoFlag, + "repoName": repoName, "content": string(content), - }).Do(context.Background(), &result); err != nil || !ok { + }).Do(ctx, &result); err != nil || !ok { var gqlErr api.GraphQlErrors if errors.As(err, &gqlErr) { for _, e := range gqlErr { if strings.Contains(e.Error(), "repo not found:") { - return cmderrors.ExitCode(2, errors.Newf("repository %q not found", *repoFlag)) + return cmderrors.ExitCode(2, errors.Newf("repository %q not found", repoName)) } if strings.Contains(e.Error(), "could not update codeowners file: codeowners file not found:") { return cmderrors.ExitCode(2, errors.New("no codeowners data has been found for this repository")) @@ -105,12 +89,5 @@ Examples: } return nil - } - - // Register the command. - codeownersCommands = append(codeownersCommands, &command{ - flagSet: flagSet, - handler: handler, - usageFunc: usageFunc, - }) -} + }, +}) diff --git a/cmd/src/run_migration_compat.go b/cmd/src/run_migration_compat.go index b27b04f0ac..d4f8b55011 100644 --- a/cmd/src/run_migration_compat.go +++ b/cmd/src/run_migration_compat.go @@ -16,11 +16,14 @@ import ( ) var migratedCommands = map[string]*cli.Command{ - "abc": abcCommand, - "api": apiCommand, - "auth": authCommand, - "login": loginCommand, - "version": versionCommand, + "abc": abcCommand, + "api": apiCommand, + "auth": authCommand, + "codeowners": codeownersCommand, + // instead of writing lots of plumbing to handle an alias, lets just register it explicitly for now + "codeowner": codeownersCommand, + "login": loginCommand, + "version": versionCommand, } func maybeRunMigratedCommand() (isMigrated bool, exitCode int, err error) { From 618d03876796b9ad1b763481015fe9bda9e6c407 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Wed, 6 May 2026 12:52:36 +0200 Subject: [PATCH 587/647] dedupe migrated root commands (#1315) --- cmd/src/run_migration_compat.go | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/cmd/src/run_migration_compat.go b/cmd/src/run_migration_compat.go index d4f8b55011..6d3bdb7778 100644 --- a/cmd/src/run_migration_compat.go +++ b/cmd/src/run_migration_compat.go @@ -1,12 +1,14 @@ package main import ( + "cmp" "context" "flag" "fmt" "log" + "maps" "os" - "sort" + "slices" "github.com/sourcegraph/src-cli/internal/clicompat" "github.com/sourcegraph/src-cli/internal/cmderrors" @@ -46,16 +48,13 @@ func maybeRunMigratedCommand() (isMigrated bool, exitCode int, err error) { // migratedRootCommand constructs a root 'src' command and adds // MigratedCommands as subcommands to it func migratedRootCommand() *cli.Command { - names := make([]string, 0, len(migratedCommands)) - for name := range migratedCommands { - names = append(names, name) - } - sort.Strings(names) - - commands := make([]*cli.Command, 0, len(names)) - for _, name := range names { - commands = append(commands, migratedCommands[name]) + uniqueCommands := make(map[string]*cli.Command, len(migratedCommands)) + for _, cmd := range migratedCommands { + uniqueCommands[cmd.Name] = cmd } + commands := slices.SortedFunc(maps.Values(uniqueCommands), func(a, b *cli.Command) int { + return cmp.Compare(a.Name, b.Name) + }) return clicompat.Wrap(&cli.Command{ Name: "src", From b1f2001e4f8be6683135fa897cea41a3494a61ae Mon Sep 17 00:00:00 2001 From: Andre Eleuterio <11207474+andreeleuterio@users.noreply.github.com> Date: Thu, 7 May 2026 21:49:24 -0300 Subject: [PATCH 588/647] chore: old gh action cleanup (#1316) --- .github/workflows/semgrep.yml | 37 ----------------------------------- 1 file changed, 37 deletions(-) delete mode 100644 .github/workflows/semgrep.yml diff --git a/.github/workflows/semgrep.yml b/.github/workflows/semgrep.yml deleted file mode 100644 index 3812ab18fc..0000000000 --- a/.github/workflows/semgrep.yml +++ /dev/null @@ -1,37 +0,0 @@ -name: Semgrep - SAST Scan - -on: - pull_request_target: - types: [ closed, edited, opened, synchronize, ready_for_review ] - -jobs: - semgrep: - permissions: - contents: read # for actions/checkout to fetch code - security-events: write # for github/codeql-action/upload-sarif to upload SARIF results - actions: read # only required for a private repository by github/codeql-action/upload-sarif to get the Action run status - runs-on: ubuntu-latest - container: - image: returntocorp/semgrep - - steps: - - uses: actions/checkout@v4 - with: - ref: ${{ github.event.pull_request.head.ref }} - repository: ${{ github.event.pull_request.head.repo.full_name }} - - - name: Checkout semgrep-rules repo - uses: actions/checkout@v4 - with: - repository: sourcegraph/security-semgrep-rules - token: ${{ secrets.GH_SEMGREP_SAST_TOKEN }} - path: semgrep-rules - - - name: Run Semgrep SAST Scan - run: | - mv semgrep-rules ../ - semgrep ci -f ../semgrep-rules/semgrep-rules/ --metrics=off --oss-only --suppress-errors --sarif -o results.sarif --exclude='semgrep-rules' --baseline-commit "$(git merge-base main HEAD)" || true - - name: Upload SARIF file - uses: github/codeql-action/upload-sarif@v3 - with: - sarif_file: results.sarif From e1a9e41372dad0c0d38bd9d4700950e95097200f Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Fri, 8 May 2026 10:24:48 +0200 Subject: [PATCH 589/647] chore/cli: migrate orgs to urfave/cli (#1314) * migrate orgs to urfave/cli * remove legacy orgs command registrations --- cmd/src/doc.go | 16 +++---- cmd/src/orgs.go | 42 +++++++++--------- cmd/src/orgs_create.go | 65 +++++++++++++--------------- cmd/src/orgs_delete.go | 58 +++++++++++-------------- cmd/src/orgs_get.go | 67 ++++++++++++++--------------- cmd/src/orgs_list.go | 75 +++++++++++++++++---------------- cmd/src/orgs_members.go | 39 +++++++---------- cmd/src/orgs_members_add.go | 65 +++++++++++++--------------- cmd/src/orgs_members_remove.go | 65 +++++++++++++--------------- cmd/src/run_migration_compat.go | 2 + 10 files changed, 227 insertions(+), 267 deletions(-) diff --git a/cmd/src/doc.go b/cmd/src/doc.go index 43ea72944d..d433aa24cb 100644 --- a/cmd/src/doc.go +++ b/cmd/src/doc.go @@ -57,15 +57,13 @@ Examples: } commanders := map[string]*commander{ - "": &commands, - "batch": &batchCommands, - "config": &configCommands, - "extsvc": &extsvcCommands, - "code-intel": &codeintelCommands, - "orgs": &orgsCommands, - "orgs members": &orgsMembersCommands, - "repos": &reposCommands, - "users": &usersCommands, + "": &commands, + "batch": &batchCommands, + "config": &configCommands, + "extsvc": &extsvcCommands, + "code-intel": &codeintelCommands, + "repos": &reposCommands, + "users": &usersCommands, } pending := out.Pending(output.Line("", output.StylePending, "Rendering Markdown...")) diff --git a/cmd/src/orgs.go b/cmd/src/orgs.go index 755fe5615c..b5c4ed473e 100644 --- a/cmd/src/orgs.go +++ b/cmd/src/orgs.go @@ -1,14 +1,27 @@ package main import ( - "flag" - "fmt" + "github.com/sourcegraph/src-cli/internal/clicompat" + "github.com/urfave/cli/v3" ) -var orgsCommands commander - -func init() { - usage := `'src orgs' is a tool that manages organizations on a Sourcegraph instance. +var orgsCommand = clicompat.Wrap(&cli.Command{ + Name: "orgs", + Aliases: []string{"org"}, + Usage: "manages organizations", + UsageText: "src orgs [command options]", + Description: orgsExamples, + HideVersion: true, + Commands: []*cli.Command{ + orgsListCommand, + orgsGetCommand, + orgsCreateCommand, + orgsDeleteCommand, + orgsMembersCommand, + }, +}) + +const orgsExamples = `'src orgs' is a tool that manages organizations on a Sourcegraph instance. Usage: @@ -25,23 +38,6 @@ The commands are: Use "src orgs [command] -h" for more information about a command. ` - flagSet := flag.NewFlagSet("orgs", flag.ExitOnError) - handler := func(args []string) error { - orgsCommands.run(flagSet, "src orgs", usage, args) - return nil - } - - // Register the command. - commands = append(commands, &command{ - flagSet: flagSet, - aliases: []string{"org"}, - handler: handler, - usageFunc: func() { - fmt.Println(usage) - }, - }) -} - const orgFragment = ` fragment OrgFields on Org { id diff --git a/cmd/src/orgs_create.go b/cmd/src/orgs_create.go index af00c0fd38..ced6e9fd92 100644 --- a/cmd/src/orgs_create.go +++ b/cmd/src/orgs_create.go @@ -2,14 +2,13 @@ package main import ( "context" - "flag" "fmt" - "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/clicompat" + "github.com/urfave/cli/v3" ) -func init() { - usage := ` +const orgsCreateExamples = ` Examples: Create an organization: @@ -18,24 +17,27 @@ Examples: ` - flagSet := flag.NewFlagSet("create", flag.ExitOnError) - usageFunc := func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src orgs %s':\n", flagSet.Name()) - flagSet.PrintDefaults() - fmt.Println(usage) - } - var ( - nameFlag = flagSet.String("name", "", `The new organization's name. (required)`) - displayNameFlag = flagSet.String("display-name", "", `The new organization's display name. Defaults to organization name if unspecified.`) - apiFlags = api.NewFlags(flagSet) - ) +var orgsCreateCommand = clicompat.Wrap(&cli.Command{ + Name: "create", + Usage: "creates an organization", + UsageText: "src orgs create [options]", + Description: orgsCreateExamples, + HideVersion: true, + Flags: clicompat.WithAPIFlags( + &cli.StringFlag{ + Name: "name", + Usage: "The new organization's name. (required)", + }, + &cli.StringFlag{ + Name: "display-name", + Usage: "The new organization's display name. Defaults to organization name if unspecified.", + }, + ), + Action: func(ctx context.Context, cmd *cli.Command) error { + name := cmd.String("name") + displayName := cmd.String("display-name") - handler := func(args []string) error { - if err := flagSet.Parse(args); err != nil { - return err - } - - client := cfg.apiClient(apiFlags, flagSet.Output()) + client := cfg.apiClient(clicompat.APIFlagsFromCmd(cmd), cmd.Writer) query := `mutation CreateOrg( $name: String!, @@ -53,20 +55,13 @@ Examples: CreateOrg Org } if ok, err := client.NewRequest(query, map[string]any{ - "name": *nameFlag, - "displayName": *displayNameFlag, - }).Do(context.Background(), &result); err != nil || !ok { + "name": name, + "displayName": displayName, + }).Do(ctx, &result); err != nil || !ok { return err } - fmt.Printf("Organization %q created.\n", *nameFlag) - return nil - } - - // Register the command. - orgsCommands = append(orgsCommands, &command{ - flagSet: flagSet, - handler: handler, - usageFunc: usageFunc, - }) -} + _, err := fmt.Fprintf(cmd.Writer, "Organization %q created.\n", name) + return err + }, +}) diff --git a/cmd/src/orgs_delete.go b/cmd/src/orgs_delete.go index 7a00aa4478..49a3d6201f 100644 --- a/cmd/src/orgs_delete.go +++ b/cmd/src/orgs_delete.go @@ -2,14 +2,13 @@ package main import ( "context" - "flag" "fmt" - "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/clicompat" + "github.com/urfave/cli/v3" ) -func init() { - usage := ` +const orgsDeleteExamples = ` Examples: Delete an organization by ID: @@ -26,23 +25,21 @@ Examples: ` - flagSet := flag.NewFlagSet("delete", flag.ExitOnError) - usageFunc := func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src orgs %s':\n", flagSet.Name()) - flagSet.PrintDefaults() - fmt.Println(usage) - } - var ( - orgIDFlag = flagSet.String("id", "", `The ID of the organization to delete.`) - apiFlags = api.NewFlags(flagSet) - ) - - handler := func(args []string) error { - if err := flagSet.Parse(args); err != nil { - return err - } - - client := cfg.apiClient(apiFlags, flagSet.Output()) +var orgsDeleteCommand = clicompat.Wrap(&cli.Command{ + Name: "delete", + Usage: "deletes an organization", + UsageText: "src orgs delete [options]", + Description: orgsDeleteExamples, + HideVersion: true, + Flags: clicompat.WithAPIFlags( + &cli.StringFlag{ + Name: "id", + Usage: "The ID of the organization to delete.", + }, + ), + Action: func(ctx context.Context, cmd *cli.Command) error { + orgID := cmd.String("id") + client := cfg.apiClient(clicompat.APIFlagsFromCmd(cmd), cmd.Writer) query := `mutation DeleteOrganization( $organization: ID! @@ -58,19 +55,12 @@ Examples: DeleteOrganization struct{} } if ok, err := client.NewRequest(query, map[string]any{ - "organization": *orgIDFlag, - }).Do(context.Background(), &result); err != nil || !ok { + "organization": orgID, + }).Do(ctx, &result); err != nil || !ok { return err } - fmt.Printf("Organization with ID %q deleted.\n", *orgIDFlag) - return nil - } - - // Register the command. - orgsCommands = append(orgsCommands, &command{ - flagSet: flagSet, - handler: handler, - usageFunc: usageFunc, - }) -} + _, err := fmt.Fprintf(cmd.Writer, "Organization with ID %q deleted.\n", orgID) + return err + }, +}) diff --git a/cmd/src/orgs_get.go b/cmd/src/orgs_get.go index 39a1f508db..3a5a9189c2 100644 --- a/cmd/src/orgs_get.go +++ b/cmd/src/orgs_get.go @@ -2,14 +2,12 @@ package main import ( "context" - "flag" - "fmt" - "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/clicompat" + "github.com/urfave/cli/v3" ) -func init() { - usage := ` +const orgsGetExamples = ` Examples: Get organization named abc-org: @@ -22,26 +20,30 @@ Examples: ` - flagSet := flag.NewFlagSet("get", flag.ExitOnError) - usageFunc := func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src orgs %s':\n", flagSet.Name()) - flagSet.PrintDefaults() - fmt.Println(usage) - } - var ( - nameFlag = flagSet.String("name", "", `Look up organization by name. (e.g. "abc-org")`) - formatFlag = flagSet.String("f", "{{.|json}}", `Format for the output, using the syntax of Go package text/template. (e.g. "{{.ID}}: {{.Name}} ({{.DisplayName}})")`) - apiFlags = api.NewFlags(flagSet) - ) - - handler := func(args []string) error { - if err := flagSet.Parse(args); err != nil { - return err - } - - client := cfg.apiClient(apiFlags, flagSet.Output()) - - tmpl, err := parseTemplate(*formatFlag) +var orgsGetCommand = clicompat.Wrap(&cli.Command{ + Name: "get", + Usage: "gets an organization", + UsageText: "src orgs get [options]", + Description: orgsGetExamples, + HideVersion: true, + Flags: clicompat.WithAPIFlags( + &cli.StringFlag{ + Name: "name", + Usage: `Look up organization by name. (e.g. "abc-org")`, + }, + &cli.StringFlag{ + Name: "f", + Value: "{{.|json}}", + Usage: `Format for the output, using the syntax of Go package text/template. (e.g. "{{.ID}}: {{.Name}} ({{.DisplayName}})")`, + }, + ), + Action: func(ctx context.Context, cmd *cli.Command) error { + name := cmd.String("name") + format := cmd.String("f") + + client := cfg.apiClient(clicompat.APIFlagsFromCmd(cmd), cmd.Writer) + + tmpl, err := parseTemplate(format) if err != nil { return err } @@ -60,18 +62,11 @@ Examples: Organization *Org } if ok, err := client.NewRequest(query, map[string]any{ - "name": *nameFlag, - }).Do(context.Background(), &result); err != nil || !ok { + "name": name, + }).Do(ctx, &result); err != nil || !ok { return err } return execTemplate(tmpl, result.Organization) - } - - // Register the command. - orgsCommands = append(orgsCommands, &command{ - flagSet: flagSet, - handler: handler, - usageFunc: usageFunc, - }) -} + }, +}) diff --git a/cmd/src/orgs_list.go b/cmd/src/orgs_list.go index 3ad611b473..a4b643ef8d 100644 --- a/cmd/src/orgs_list.go +++ b/cmd/src/orgs_list.go @@ -2,14 +2,13 @@ package main import ( "context" - "flag" - "fmt" "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/clicompat" + "github.com/urfave/cli/v3" ) -func init() { - usage := ` +const orgsListExamples = ` Examples: List organizations: @@ -22,27 +21,36 @@ Examples: ` - flagSet := flag.NewFlagSet("list", flag.ExitOnError) - usageFunc := func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src orgs %s':\n", flagSet.Name()) - flagSet.PrintDefaults() - fmt.Println(usage) - } - var ( - firstFlag = flagSet.Int("first", 1000, "Returns the first n organizations from the list.") - queryFlag = flagSet.String("query", "", `Returns organizations whose names match the query. (e.g. "alice")`) - formatFlag = flagSet.String("f", "{{.Name}}", `Format for the output, using the syntax of Go package text/template. (e.g. "{{.ID}}: {{.Name}} ({{.DisplayName}})" or "{{.|json}}")`) - apiFlags = api.NewFlags(flagSet) - ) - - handler := func(args []string) error { - if err := flagSet.Parse(args); err != nil { - return err - } - - client := cfg.apiClient(apiFlags, flagSet.Output()) - - tmpl, err := parseTemplate(*formatFlag) +var orgsListCommand = clicompat.Wrap(&cli.Command{ + Name: "list", + Usage: "lists organizations", + UsageText: "src orgs list [options]", + Description: orgsListExamples, + HideVersion: true, + Flags: clicompat.WithAPIFlags( + &cli.IntFlag{ + Name: "first", + Value: 1000, + Usage: "Returns the first n organizations from the list.", + }, + &cli.StringFlag{ + Name: "query", + Usage: `Returns organizations whose names match the query. (e.g. "alice")`, + }, + &cli.StringFlag{ + Name: "f", + Value: "{{.Name}}", + Usage: `Format for the output, using the syntax of Go package text/template. (e.g. "{{.ID}}: {{.Name}} ({{.DisplayName}})" or "{{.|json}}")`, + }, + ), + Action: func(ctx context.Context, cmd *cli.Command) error { + first := cmd.Int("first") + queryValue := cmd.String("query") + format := cmd.String("f") + + client := cfg.apiClient(clicompat.APIFlagsFromCmd(cmd), cmd.Writer) + + tmpl, err := parseTemplate(format) if err != nil { return err } @@ -67,9 +75,9 @@ Examples: } } if ok, err := client.NewRequest(query, map[string]any{ - "first": api.NullInt(*firstFlag), - "query": api.NullString(*queryFlag), - }).Do(context.Background(), &result); err != nil || !ok { + "first": api.NullInt(first), + "query": api.NullString(queryValue), + }).Do(ctx, &result); err != nil || !ok { return err } @@ -79,12 +87,5 @@ Examples: } } return nil - } - - // Register the command. - orgsCommands = append(orgsCommands, &command{ - flagSet: flagSet, - handler: handler, - usageFunc: usageFunc, - }) -} + }, +}) diff --git a/cmd/src/orgs_members.go b/cmd/src/orgs_members.go index 443c5b01ad..bf033644ff 100644 --- a/cmd/src/orgs_members.go +++ b/cmd/src/orgs_members.go @@ -1,14 +1,24 @@ package main import ( - "flag" - "fmt" + "github.com/sourcegraph/src-cli/internal/clicompat" + "github.com/urfave/cli/v3" ) -var orgsMembersCommands commander - -func init() { - usage := `'src orgs members' is a tool that manages organization members on a Sourcegraph instance. +var orgsMembersCommand = clicompat.Wrap(&cli.Command{ + Name: "members", + Aliases: []string{"member"}, + Usage: "manages organization members", + UsageText: "src orgs members [command options]", + Description: orgsMembersExamples, + HideVersion: true, + Commands: []*cli.Command{ + orgsMembersAddCommand, + orgsMembersRemoveCommand, + }, +}) + +const orgsMembersExamples = `'src orgs members' is a tool that manages organization members on a Sourcegraph instance. Usage: @@ -21,20 +31,3 @@ The commands are: Use "src orgs members [command] -h" for more information about a command. ` - - flagSet := flag.NewFlagSet("members", flag.ExitOnError) - handler := func(args []string) error { - orgsMembersCommands.run(flagSet, "src orgs members", usage, args) - return nil - } - - // Register the command. - orgsCommands = append(orgsCommands, &command{ - flagSet: flagSet, - aliases: []string{"member"}, - handler: handler, - usageFunc: func() { - fmt.Println(usage) - }, - }) -} diff --git a/cmd/src/orgs_members_add.go b/cmd/src/orgs_members_add.go index cf09f5c0d1..f6fa691f87 100644 --- a/cmd/src/orgs_members_add.go +++ b/cmd/src/orgs_members_add.go @@ -2,14 +2,13 @@ package main import ( "context" - "flag" "fmt" - "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/clicompat" + "github.com/urfave/cli/v3" ) -func init() { - usage := ` +const orgsMembersAddExamples = ` Examples: Add a member (alice) to an organization (abc-org): @@ -18,24 +17,27 @@ Examples: ` - flagSet := flag.NewFlagSet("add", flag.ExitOnError) - usageFunc := func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src orgs members %s':\n", flagSet.Name()) - flagSet.PrintDefaults() - fmt.Println(usage) - } - var ( - orgIDFlag = flagSet.String("org-id", "", "ID of organization to which to add member. (required)") - usernameFlag = flagSet.String("username", "", "Username of user to add as member. (required)") - apiFlags = api.NewFlags(flagSet) - ) +var orgsMembersAddCommand = clicompat.Wrap(&cli.Command{ + Name: "add", + Usage: "adds a user as a member to an organization", + UsageText: "src orgs members add [options]", + Description: orgsMembersAddExamples, + HideVersion: true, + Flags: clicompat.WithAPIFlags( + &cli.StringFlag{ + Name: "org-id", + Usage: "ID of organization to which to add member. (required)", + }, + &cli.StringFlag{ + Name: "username", + Usage: "Username of user to add as member. (required)", + }, + ), + Action: func(ctx context.Context, cmd *cli.Command) error { + orgID := cmd.String("org-id") + username := cmd.String("username") - handler := func(args []string) error { - if err := flagSet.Parse(args); err != nil { - return err - } - - client := cfg.apiClient(apiFlags, flagSet.Output()) + client := cfg.apiClient(clicompat.APIFlagsFromCmd(cmd), cmd.Writer) query := `mutation AddUserToOrganization( $organization: ID!, @@ -53,20 +55,13 @@ Examples: AddUserToOrganization struct{} } if ok, err := client.NewRequest(query, map[string]any{ - "organization": *orgIDFlag, - "username": *usernameFlag, - }).Do(context.Background(), &result); err != nil || !ok { + "organization": orgID, + "username": username, + }).Do(ctx, &result); err != nil || !ok { return err } - fmt.Printf("User %q added as member to organization with ID %q.\n", *usernameFlag, *orgIDFlag) - return nil - } - - // Register the command. - orgsMembersCommands = append(orgsMembersCommands, &command{ - flagSet: flagSet, - handler: handler, - usageFunc: usageFunc, - }) -} + _, err := fmt.Fprintf(cmd.Writer, "User %q added as member to organization with ID %q.\n", username, orgID) + return err + }, +}) diff --git a/cmd/src/orgs_members_remove.go b/cmd/src/orgs_members_remove.go index 6f6eb3171f..9eac9f0fd0 100644 --- a/cmd/src/orgs_members_remove.go +++ b/cmd/src/orgs_members_remove.go @@ -2,14 +2,13 @@ package main import ( "context" - "flag" "fmt" - "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/clicompat" + "github.com/urfave/cli/v3" ) -func init() { - usage := ` +const orgsMembersRemoveExamples = ` Examples: Remove a member (alice) from an organization (abc-org): @@ -17,24 +16,27 @@ Examples: $ src orgs members remove -org-id=$(src org get -f '{{.ID}}' -name=abc-org) -user-id=$(src users get -f '{{.ID}}' -username=alice) ` - flagSet := flag.NewFlagSet("remove", flag.ExitOnError) - usageFunc := func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src orgs members %s':\n", flagSet.Name()) - flagSet.PrintDefaults() - fmt.Println(usage) - } - var ( - orgIDFlag = flagSet.String("org-id", "", "ID of organization from which to remove member. (required)") - userIDFlag = flagSet.String("user-id", "", "ID of user to remove as member. (required)") - apiFlags = api.NewFlags(flagSet) - ) +var orgsMembersRemoveCommand = clicompat.Wrap(&cli.Command{ + Name: "remove", + Usage: "removes a user as a member from an organization", + UsageText: "src orgs members remove [options]", + Description: orgsMembersRemoveExamples, + HideVersion: true, + Flags: clicompat.WithAPIFlags( + &cli.StringFlag{ + Name: "org-id", + Usage: "ID of organization from which to remove member. (required)", + }, + &cli.StringFlag{ + Name: "user-id", + Usage: "ID of user to remove as member. (required)", + }, + ), + Action: func(ctx context.Context, cmd *cli.Command) error { + orgID := cmd.String("org-id") + userID := cmd.String("user-id") - handler := func(args []string) error { - if err := flagSet.Parse(args); err != nil { - return err - } - - client := cfg.apiClient(apiFlags, flagSet.Output()) + client := cfg.apiClient(clicompat.APIFlagsFromCmd(cmd), cmd.Writer) query := `mutation RemoveUserFromOrg( $orgID: ID!, @@ -52,20 +54,13 @@ Examples: RemoveUserFromOrg struct{} } if ok, err := client.NewRequest(query, map[string]any{ - "orgID": *orgIDFlag, - "userID": *userIDFlag, - }).Do(context.Background(), &result); err != nil || !ok { + "orgID": orgID, + "userID": userID, + }).Do(ctx, &result); err != nil || !ok { return err } - fmt.Printf("User %q removed as member from organization with ID %q.\n", *userIDFlag, *orgIDFlag) - return nil - } - - // Register the command. - orgsMembersCommands = append(orgsMembersCommands, &command{ - flagSet: flagSet, - handler: handler, - usageFunc: usageFunc, - }) -} + _, err := fmt.Fprintf(cmd.Writer, "User %q removed as member from organization with ID %q.\n", userID, orgID) + return err + }, +}) diff --git a/cmd/src/run_migration_compat.go b/cmd/src/run_migration_compat.go index 6d3bdb7778..5a9296d5e9 100644 --- a/cmd/src/run_migration_compat.go +++ b/cmd/src/run_migration_compat.go @@ -25,6 +25,8 @@ var migratedCommands = map[string]*cli.Command{ // instead of writing lots of plumbing to handle an alias, lets just register it explicitly for now "codeowner": codeownersCommand, "login": loginCommand, + "orgs": orgsCommand, + "org": orgsCommand, "version": versionCommand, } From f3d5edfbed1255e027db97f996e365360a22ebcc Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Fri, 8 May 2026 12:05:55 +0200 Subject: [PATCH 590/647] chore: update Go to 1.26.3 (#1318) --- .tool-versions | 3 --- Dockerfile | 2 +- dev/vendor-lib.sh | 2 +- go.mod | 2 +- lib/go.mod | 2 +- mise.toml | 2 +- 6 files changed, 5 insertions(+), 8 deletions(-) delete mode 100644 .tool-versions diff --git a/.tool-versions b/.tool-versions deleted file mode 100644 index f549b5d819..0000000000 --- a/.tool-versions +++ /dev/null @@ -1,3 +0,0 @@ -golang 1.26.1 -shfmt 3.8.0 -shellcheck 0.10.0 diff --git a/Dockerfile b/Dockerfile index a3c6ff8fb7..7da0c2dd95 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,7 +4,7 @@ # # Nothing fancy here: we copy in the source code and build on the Alpine Go # image. Refer to .dockerignore to get a sense of what we're not going to copy. -FROM golang:1.25.4-alpine3.22@sha256:d3f0cf7723f3429e3f9ed846243970b20a2de7bae6a5b66fc5914e228d831bbb AS builder +FROM golang:1.26.3-alpine3.22@sha256:be93003ee861b3b91b6ebcb22678524947e0cd786c2df3f32af520006b1e54f5 AS builder COPY . /src WORKDIR /src diff --git a/dev/vendor-lib.sh b/dev/vendor-lib.sh index ef53800ab7..e4267183cb 100755 --- a/dev/vendor-lib.sh +++ b/dev/vendor-lib.sh @@ -128,7 +128,7 @@ echo "Creating go.mod file..." cat > "$DEST_LIB/go.mod" < Date: Fri, 8 May 2026 14:55:36 +0200 Subject: [PATCH 591/647] chore/security: update deps for CVEs reported by trivy (#1319) --- lib/go.mod | 10 ++++++++-- lib/go.sum | 17 +++++++++++++++++ npm-distribution/package-lock.json | 8 ++++---- npm-distribution/package.json | 2 +- 4 files changed, 30 insertions(+), 7 deletions(-) diff --git a/lib/go.mod b/lib/go.mod index 323943b701..44fdc19356 100644 --- a/lib/go.mod +++ b/lib/go.mod @@ -12,7 +12,7 @@ require ( github.com/gobwas/glob v0.2.3 github.com/google/go-cmp v0.7.0 github.com/grafana/regexp v0.0.0-20250905093917-f7b3be9d1853 - github.com/jackc/pgx/v5 v5.9.1 + github.com/jackc/pgx/v5 v5.9.2 github.com/klauspost/pgzip v1.2.6 github.com/mattn/go-isatty v0.0.20 github.com/mattn/go-runewidth v0.0.19 @@ -25,7 +25,7 @@ require ( github.com/urfave/cli/v3 v3.8.0 github.com/xeipuuv/gojsonschema v1.2.0 github.com/xlab/treeprint v1.2.0 - go.opentelemetry.io/otel v1.38.0 + go.opentelemetry.io/otel v1.43.0 golang.org/x/sys v0.41.0 golang.org/x/term v0.37.0 google.golang.org/protobuf v1.36.10 @@ -38,6 +38,7 @@ require ( github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect github.com/aymerick/douceur v0.2.0 // indirect github.com/benbjohnson/clock v1.3.5 // indirect + github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect github.com/charmbracelet/x/ansi v0.8.0 // indirect github.com/charmbracelet/x/cellbuf v0.0.13 // indirect @@ -48,6 +49,8 @@ require ( github.com/dlclark/regexp2 v1.11.0 // indirect github.com/fatih/color v1.18.0 // indirect github.com/getsentry/sentry-go v0.27.0 // indirect + github.com/go-logr/logr v1.4.3 // indirect + github.com/go-logr/stdr v1.2.2 // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/google/uuid v1.6.0 // indirect github.com/gorilla/css v1.0.1 // indirect @@ -69,6 +72,9 @@ require ( github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect github.com/yuin/goldmark v1.7.8 // indirect github.com/yuin/goldmark-emoji v1.0.5 // indirect + go.opentelemetry.io/auto/sdk v1.2.1 // indirect + go.opentelemetry.io/otel/metric v1.43.0 // indirect + go.opentelemetry.io/otel/trace v1.43.0 // indirect go.uber.org/atomic v1.11.0 // indirect go.uber.org/goleak v1.3.0 // indirect go.uber.org/multierr v1.11.0 // indirect diff --git a/lib/go.sum b/lib/go.sum index a2b0d73ad3..434c58adc8 100644 --- a/lib/go.sum +++ b/lib/go.sum @@ -16,6 +16,8 @@ github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuP github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4= github.com/benbjohnson/clock v1.3.5 h1:VvXlSJBzZpA/zum6Sj74hxwYI2DIxRWuNIoXAzHZz5o= github.com/benbjohnson/clock v1.3.5/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc h1:4pZI35227imm7yK2bGPcfpFEmuY1gc2YSTShr4iJBfs= github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc/go.mod h1:X4/0JoqgTIPSFcRA/P6INZzIuyqdFY5rm8tb41s9okk= github.com/charmbracelet/glamour v0.10.0 h1:MtZvfwsYCx8jEPFJm3rIBFIMZUfUJ765oX8V6kXldcY= @@ -54,6 +56,11 @@ github.com/getsentry/sentry-go v0.27.0 h1:Pv98CIbtB3LkMWmXi4Joa5OOcwbmnX88sF5qbK github.com/getsentry/sentry-go v0.27.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA= github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og= +github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= +github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y= github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8= github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= @@ -82,6 +89,8 @@ github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7Ulw github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= github.com/jackc/pgx/v5 v5.9.1 h1:uwrxJXBnx76nyISkhr33kQLlUqjv7et7b9FjCen/tdc= github.com/jackc/pgx/v5 v5.9.1/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= +github.com/jackc/pgx/v5 v5.9.2 h1:3ZhOzMWnR4yJ+RW1XImIPsD1aNSz4T4fyP7zlQb56hw= +github.com/jackc/pgx/v5 v5.9.2/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= @@ -165,8 +174,16 @@ github.com/yuin/goldmark v1.7.8 h1:iERMLn0/QJeHFhxSt3p6PeN9mGnvIKSpG9YYorDMnic= github.com/yuin/goldmark v1.7.8/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E= github.com/yuin/goldmark-emoji v1.0.5 h1:EMVWyCGPlXJfUXBXpuMu+ii3TIaxbVBnEX9uaDC4cIk= github.com/yuin/goldmark-emoji v1.0.5/go.mod h1:tTkZEbwu5wkPmgTcitqddVxY9osFZiavD+r4AzQrh1U= +go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= +go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8= go.opentelemetry.io/otel v1.38.0/go.mod h1:zcmtmQ1+YmQM9wrNsTGV/q/uyusom3P8RxwExxkZhjM= +go.opentelemetry.io/otel v1.43.0 h1:mYIM03dnh5zfN7HautFE4ieIig9amkNANT+xcVxAj9I= +go.opentelemetry.io/otel v1.43.0/go.mod h1:JuG+u74mvjvcm8vj8pI5XiHy1zDeoCS2LB1spIq7Ay0= +go.opentelemetry.io/otel/metric v1.43.0 h1:d7638QeInOnuwOONPp4JAOGfbCEpYb+K6DVWvdxGzgM= +go.opentelemetry.io/otel/metric v1.43.0/go.mod h1:RDnPtIxvqlgO8GRW18W6Z/4P462ldprJtfxHxyKd2PY= +go.opentelemetry.io/otel/trace v1.43.0 h1:BkNrHpup+4k4w+ZZ86CZoHHEkohws8AY+WTX09nk+3A= +go.opentelemetry.io/otel/trace v1.43.0/go.mod h1:/QJhyVBUUswCphDVxq+8mld+AvhXZLhe+8WVFxiFff0= go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= diff --git a/npm-distribution/package-lock.json b/npm-distribution/package-lock.json index 12d9c8dfa7..b6f627a88b 100644 --- a/npm-distribution/package-lock.json +++ b/npm-distribution/package-lock.json @@ -10,7 +10,7 @@ "hasInstallScript": true, "license": "Apache-2.0", "dependencies": { - "tar": "^7.1.0" + "tar": "^7.5.15" }, "bin": { "src": "src.js" @@ -102,9 +102,9 @@ } }, "node_modules/tar": { - "version": "7.5.2", - "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.2.tgz", - "integrity": "sha512-7NyxrTE4Anh8km8iEy7o0QYPs+0JKBTj5ZaqHg6B39erLg0qYXN3BijtShwbsNSvQ+LN75+KV+C4QR/f6Gwnpg==", + "version": "7.5.15", + "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.15.tgz", + "integrity": "sha512-dzGK0boVlC4W5QFuQN1EFSl3bIDYsk7Tj40U6eIBnK2k/8ml7TZ5agbI5j5+qnoVcAA+rNtBml8SEiLxZpNqRQ==", "license": "BlueOak-1.0.0", "dependencies": { "@isaacs/fs-minipass": "^4.0.0", diff --git a/npm-distribution/package.json b/npm-distribution/package.json index bfdc106cf4..fb8fddb0b8 100644 --- a/npm-distribution/package.json +++ b/npm-distribution/package.json @@ -17,7 +17,7 @@ "sourcegraph" ], "dependencies": { - "tar": "^7.1.0" + "tar": "^7.5.15" }, "overrides": { "cross-spawn": "^7.0.5", From 30270f5590944086b7368834d8c34d6a241c0828 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Mon, 11 May 2026 12:04:55 +0200 Subject: [PATCH 592/647] chore/cli: migrate users to urfave/cli (#1317) The command migration is moving legacy commander commands onto urfave/cli so they share the same help, flag, and dispatch behavior as newly migrated commands. Migrate src users and its list, get, create, delete, prune, and tag subcommands to cli.Command definitions. Register both users and user in the migrated command map, and remove users from the legacy docs path so generated docs come from the migrated root command. Test Plan: - go test ./cmd/src - go test ./... - go run ./cmd/src users -h - go run ./cmd/src user -h - go run ./cmd/src users list -h --- cmd/src/doc.go | 1 - cmd/src/run_migration_compat.go | 4 +- cmd/src/users.go | 41 +++++++------- cmd/src/users_create.go | 84 +++++++++++++++------------- cmd/src/users_delete.go | 72 +++++++++++------------- cmd/src/users_get.go | 76 ++++++++++++------------- cmd/src/users_list.go | 82 ++++++++++++++------------- cmd/src/users_prune.go | 98 ++++++++++++++++++--------------- cmd/src/users_tag.go | 76 ++++++++++++------------- lib/batches/batch_spec.go | 1 + 10 files changed, 275 insertions(+), 260 deletions(-) diff --git a/cmd/src/doc.go b/cmd/src/doc.go index d433aa24cb..8132189c87 100644 --- a/cmd/src/doc.go +++ b/cmd/src/doc.go @@ -63,7 +63,6 @@ Examples: "extsvc": &extsvcCommands, "code-intel": &codeintelCommands, "repos": &reposCommands, - "users": &usersCommands, } pending := out.Pending(output.Line("", output.StylePending, "Rendering Markdown...")) diff --git a/cmd/src/run_migration_compat.go b/cmd/src/run_migration_compat.go index 5a9296d5e9..6671b07da3 100644 --- a/cmd/src/run_migration_compat.go +++ b/cmd/src/run_migration_compat.go @@ -25,8 +25,10 @@ var migratedCommands = map[string]*cli.Command{ // instead of writing lots of plumbing to handle an alias, lets just register it explicitly for now "codeowner": codeownersCommand, "login": loginCommand, - "orgs": orgsCommand, + "orgs": orgsCommand, "org": orgsCommand, + "users": usersCommand, + "user": usersCommand, "version": versionCommand, } diff --git a/cmd/src/users.go b/cmd/src/users.go index 3b915d75e1..5fa4c99c49 100644 --- a/cmd/src/users.go +++ b/cmd/src/users.go @@ -1,14 +1,28 @@ package main import ( - "flag" - "fmt" + "github.com/sourcegraph/src-cli/internal/clicompat" + "github.com/urfave/cli/v3" ) -var usersCommands commander +var usersCommand = clicompat.Wrap(&cli.Command{ + Name: "users", + Aliases: []string{"user"}, + Usage: "manages users", + UsageText: "src users [command options]", + Description: usersExamples, + HideVersion: true, + Commands: []*cli.Command{ + usersListCommand, + usersGetCommand, + usersCreateCommand, + usersDeleteCommand, + usersPruneCommand, + usersTagCommand, + }, +}) -func init() { - usage := `'src users' is a tool that manages users on a Sourcegraph instance. +const usersExamples = `'src users' is a tool that manages users on a Sourcegraph instance. Usage: @@ -26,23 +40,6 @@ The commands are: Use "src users [command] -h" for more information about a command. ` - flagSet := flag.NewFlagSet("users", flag.ExitOnError) - handler := func(args []string) error { - usersCommands.run(flagSet, "src users", usage, args) - return nil - } - - // Register the command. - commands = append(commands, &command{ - flagSet: flagSet, - aliases: []string{"user"}, - handler: handler, - usageFunc: func() { - fmt.Println(usage) - }, - }) -} - const userFragment = ` fragment UserFields on User { id diff --git a/cmd/src/users_create.go b/cmd/src/users_create.go index b33b5808ba..71ebe7dad8 100644 --- a/cmd/src/users_create.go +++ b/cmd/src/users_create.go @@ -2,14 +2,13 @@ package main import ( "context" - "flag" "fmt" - "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/clicompat" + "github.com/urfave/cli/v3" ) -func init() { - usage := ` +const usersCreateExamples = ` Examples: Create a user account: @@ -18,25 +17,36 @@ Examples: ` - flagSet := flag.NewFlagSet("create", flag.ExitOnError) - usageFunc := func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src users %s':\n", flagSet.Name()) - flagSet.PrintDefaults() - fmt.Println(usage) - } - var ( - usernameFlag = flagSet.String("username", "", `The new user's username. (required)`) - emailFlag = flagSet.String("email", "", `The new user's email address. (required)`) - resetPasswordURLFlag = flagSet.Bool("reset-password-url", false, `Print the reset password URL to manually send to the new user.`) - apiFlags = api.NewFlags(flagSet) - ) +var usersCreateCommand = clicompat.Wrap(&cli.Command{ + Name: "create", + Usage: "creates a user account", + UsageText: "src users create [options]", + Description: usersCreateExamples, + HideVersion: true, + Flags: clicompat.WithAPIFlags( + &cli.StringFlag{ + Name: "username", + Usage: "The new user's username.", + Required: true, + Validator: requiresNotEmpty("provide a username name using -username"), + }, + &cli.StringFlag{ + Name: "email", + Usage: "The new user's email address", + Required: true, + Validator: requiresNotEmpty("provide a email name using -email"), + }, + &cli.BoolFlag{ + Name: "reset-password-url", + Usage: "Print the reset password URL to manually send to the new user.", + }, + ), + Action: func(ctx context.Context, cmd *cli.Command) error { + username := cmd.String("username") + email := cmd.String("email") + resetPasswordURL := cmd.Bool("reset-password-url") - handler := func(args []string) error { - if err := flagSet.Parse(args); err != nil { - return err - } - - client := cfg.apiClient(apiFlags, flagSet.Output()) + client := cfg.apiClient(clicompat.APIFlagsFromCmd(cmd), cmd.Writer) query := `mutation CreateUser( $username: String!, @@ -56,24 +66,22 @@ Examples: } } if ok, err := client.NewRequest(query, map[string]any{ - "username": *usernameFlag, - "email": *emailFlag, - }).Do(context.Background(), &result); err != nil || !ok { + "username": username, + "email": email, + }).Do(ctx, &result); err != nil || !ok { return err } - fmt.Printf("User %q created.\n", *usernameFlag) - if *resetPasswordURLFlag && result.CreateUser.ResetPasswordURL != "" { - fmt.Println() - fmt.Printf("\tReset pasword URL: %s\n", result.CreateUser.ResetPasswordURL) + if _, err := fmt.Fprintf(cmd.Writer, "User %q created.\n", username); err != nil { + return err + } + if resetPasswordURL && result.CreateUser.ResetPasswordURL != "" { + if _, err := fmt.Fprintln(cmd.Writer); err != nil { + return err + } + _, err := fmt.Fprintf(cmd.Writer, "\tReset pasword URL: %s\n", result.CreateUser.ResetPasswordURL) + return err } return nil - } - - // Register the command. - usersCommands = append(usersCommands, &command{ - flagSet: flagSet, - handler: handler, - usageFunc: usageFunc, - }) -} + }, +}) diff --git a/cmd/src/users_delete.go b/cmd/src/users_delete.go index c4b59b6c3f..47f46503ad 100644 --- a/cmd/src/users_delete.go +++ b/cmd/src/users_delete.go @@ -3,17 +3,16 @@ package main import ( "bufio" "context" - "flag" "fmt" "os" "strconv" "strings" - "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/clicompat" + "github.com/urfave/cli/v3" ) -func init() { - usage := ` +const usersDeleteExamples = ` Examples: Delete a user account by ID: @@ -30,25 +29,23 @@ Examples: ` - flagSet := flag.NewFlagSet("delete", flag.ExitOnError) - usageFunc := func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src users %s':\n", flagSet.Name()) - flagSet.PrintDefaults() - fmt.Println(usage) - } - var ( - userIDFlag = flagSet.String("id", "", `The ID of the user to delete.`) - apiFlags = api.NewFlags(flagSet) - ) - - handler := func(args []string) error { - if err := flagSet.Parse(args); err != nil { - return err - } - - client := cfg.apiClient(apiFlags, flagSet.Output()) - - if *userIDFlag == "" { +var usersDeleteCommand = clicompat.Wrap(&cli.Command{ + Name: "delete", + Usage: "deletes a user account", + UsageText: "src users delete [options]", + Description: usersDeleteExamples, + HideVersion: true, + Flags: clicompat.WithAPIFlags( + &cli.StringFlag{ + Name: "id", + Usage: "The ID of the user to delete.", + }, + ), + Action: func(ctx context.Context, cmd *cli.Command) error { + userID := cmd.String("id") + client := cfg.apiClient(clicompat.APIFlagsFromCmd(cmd), cmd.Writer) + + if userID == "" { query := `query UsersTotalCountCountUsers { users { totalCount } }` var result struct { @@ -56,12 +53,14 @@ Examples: TotalCount int } } - ok, err := client.NewQuery(query).Do(context.Background(), &result) + ok, err := client.NewQuery(query).Do(ctx, &result) if err != nil || !ok { return err } - fmt.Printf("No user ID specified. This would delete %d users.\nType in this number to confirm and hit return: ", result.Users.TotalCount) + if _, err := fmt.Fprintf(cmd.Writer, "No user ID specified. This would delete %d users.\nType in this number to confirm and hit return: ", result.Users.TotalCount); err != nil { + return err + } reader := bufio.NewReader(os.Stdin) text, err := reader.ReadString('\n') if err != nil { @@ -74,8 +73,8 @@ Examples: } if count != result.Users.TotalCount { - fmt.Println("Number does not match. Aborting.") - return nil + _, err := fmt.Fprintln(cmd.Writer, "Number does not match. Aborting.") + return err } } @@ -93,19 +92,12 @@ Examples: DeleteUser struct{} } if ok, err := client.NewRequest(query, map[string]any{ - "user": *userIDFlag, - }).Do(context.Background(), &result); err != nil || !ok { + "user": userID, + }).Do(ctx, &result); err != nil || !ok { return err } - fmt.Printf("User with ID %q deleted.\n", *userIDFlag) - return nil - } - - // Register the command. - usersCommands = append(usersCommands, &command{ - flagSet: flagSet, - handler: handler, - usageFunc: usageFunc, - }) -} + _, err := fmt.Fprintf(cmd.Writer, "User with ID %q deleted.\n", userID) + return err + }, +}) diff --git a/cmd/src/users_get.go b/cmd/src/users_get.go index 6b27865f19..cf496a04a4 100644 --- a/cmd/src/users_get.go +++ b/cmd/src/users_get.go @@ -2,16 +2,15 @@ package main import ( "context" - "flag" - "fmt" "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/clicompat" + "github.com/urfave/cli/v3" ) -func init() { - usage := ` +const usersGetExamples = ` Examples: Get user with username alice: @@ -20,31 +19,39 @@ Examples: ` - flagSet := flag.NewFlagSet("get", flag.ExitOnError) - usageFunc := func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src users %s':\n", flagSet.Name()) - flagSet.PrintDefaults() - fmt.Println(usage) - } - var ( - usernameFlag = flagSet.String("username", "", `Look up user by username. (e.g. "alice")`) - emailFlag = flagSet.String("email", "", `Look up user by email. (e.g. "alice@sourcegraph.com")`) - formatFlag = flagSet.String("f", "{{.|json}}", `Format for the output, using the syntax of Go package text/template. (e.g. "{{.ID}}: {{.Username}} ({{.DisplayName}})")`) - apiFlags = api.NewFlags(flagSet) - ) - - handler := func(args []string) error { - if err := flagSet.Parse(args); err != nil { - return err - } - - client := cfg.apiClient(apiFlags, flagSet.Output()) - - if usernameFlag != nil && *usernameFlag != "" && emailFlag != nil && *emailFlag != "" { +var usersGetCommand = clicompat.Wrap(&cli.Command{ + Name: "get", + Usage: "gets a user", + UsageText: "src users get [options]", + Description: usersGetExamples, + HideVersion: true, + Flags: clicompat.WithAPIFlags( + &cli.StringFlag{ + Name: "username", + Usage: `Look up user by username. (e.g. "alice")`, + }, + &cli.StringFlag{ + Name: "email", + Usage: `Look up user by email. (e.g. "alice@sourcegraph.com")`, + }, + &cli.StringFlag{ + Name: "f", + Value: "{{.|json}}", + Usage: `Format for the output, using the syntax of Go package text/template. (e.g. "{{.ID}}: {{.Username}} ({{.DisplayName}})")`, + }, + ), + Action: func(ctx context.Context, cmd *cli.Command) error { + username := cmd.String("username") + email := cmd.String("email") + format := cmd.String("f") + + client := cfg.apiClient(clicompat.APIFlagsFromCmd(cmd), cmd.Writer) + + if username != "" && email != "" { return errors.New("cannot specify both email and username") } - tmpl, err := parseTemplate(*formatFlag) + tmpl, err := parseTemplate(format) if err != nil { return err } @@ -65,19 +72,12 @@ Examples: User *User } if ok, err := client.NewRequest(query, map[string]any{ - "username": api.NullString(*usernameFlag), - "email": api.NullString(*emailFlag), - }).Do(context.Background(), &result); err != nil || !ok { + "username": api.NullString(username), + "email": api.NullString(email), + }).Do(ctx, &result); err != nil || !ok { return err } return execTemplate(tmpl, result.User) - } - - // Register the command. - usersCommands = append(usersCommands, &command{ - flagSet: flagSet, - handler: handler, - usageFunc: usageFunc, - }) -} + }, +}) diff --git a/cmd/src/users_list.go b/cmd/src/users_list.go index a72e1d8a3e..93dae9601c 100644 --- a/cmd/src/users_list.go +++ b/cmd/src/users_list.go @@ -2,14 +2,13 @@ package main import ( "context" - "flag" - "fmt" "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/clicompat" + "github.com/urfave/cli/v3" ) -func init() { - usage := ` +const usersListExamples = ` Examples: List users: @@ -26,36 +25,48 @@ Examples: ` - flagSet := flag.NewFlagSet("list", flag.ExitOnError) - usageFunc := func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src users %s':\n", flagSet.Name()) - flagSet.PrintDefaults() - fmt.Println(usage) - } - var ( - firstFlag = flagSet.Int("first", 1000, "Returns the first n users from the list.") - queryFlag = flagSet.String("query", "", `Returns users whose names match the query. (e.g. "alice")`) - tagFlag = flagSet.String("tag", "", `Returns users with the given tag.`) - formatFlag = flagSet.String("f", "{{.Username}}", `Format for the output, using the syntax of Go package text/template. (e.g. "{{.ID}}: {{.Username}} ({{.DisplayName}})" or "{{.|json}}")`) - apiFlags = api.NewFlags(flagSet) - ) - - handler := func(args []string) error { - if err := flagSet.Parse(args); err != nil { - return err - } - - ctx := context.Background() - client := cfg.apiClient(apiFlags, flagSet.Output()) - - tmpl, err := parseTemplate(*formatFlag) +var usersListCommand = clicompat.Wrap(&cli.Command{ + Name: "list", + Usage: "lists users", + UsageText: "src users list [options]", + Description: usersListExamples, + HideVersion: true, + Flags: clicompat.WithAPIFlags( + &cli.IntFlag{ + Name: "first", + Value: 1000, + Usage: "Returns the first n users from the list.", + }, + &cli.StringFlag{ + Name: "query", + Usage: `Returns users whose names match the query. (e.g. "alice")`, + }, + &cli.StringFlag{ + Name: "tag", + Usage: `Returns users with the given tag.`, + }, + &cli.StringFlag{ + Name: "f", + Value: "{{.Username}}", + Usage: `Format for the output, using the syntax of Go package text/template. (e.g. "{{.ID}}: {{.Username}} ({{.DisplayName}})" or "{{.|json}}")`, + }, + ), + Action: func(ctx context.Context, cmd *cli.Command) error { + first := cmd.Int("first") + queryValue := cmd.String("query") + tag := cmd.String("tag") + format := cmd.String("f") + + client := cfg.apiClient(clicompat.APIFlagsFromCmd(cmd), cmd.Writer) + + tmpl, err := parseTemplate(format) if err != nil { return err } vars := map[string]any{ - "first": api.NullInt(*firstFlag), - "query": api.NullString(*queryFlag), - "tag": api.NullString(*tagFlag), + "first": api.NullInt(first), + "query": api.NullString(queryValue), + "tag": api.NullString(tag), } queryTagVar := "" queryTag := "" @@ -94,12 +105,5 @@ first: $first, } } return nil - } - - // Register the command. - usersCommands = append(usersCommands, &command{ - flagSet: flagSet, - handler: handler, - usageFunc: usageFunc, - }) -} + }, +}) diff --git a/cmd/src/users_prune.go b/cmd/src/users_prune.go index d67fff6be0..c4bf3a044e 100644 --- a/cmd/src/users_prune.go +++ b/cmd/src/users_prune.go @@ -2,7 +2,6 @@ package main import ( "context" - "flag" "fmt" "os" "strings" @@ -11,10 +10,11 @@ import ( "github.com/jedib0t/go-pretty/v6/table" "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/clicompat" + "github.com/urfave/cli/v3" ) -func init() { - usage := ` +const usersPruneExamples = ` This command removes users from a Sourcegraph instance who have been inactive for 60 or more days. Admin accounts are omitted by default. Examples: @@ -24,32 +24,49 @@ Examples: $ src users prune -remove-admin -remove-null-users ` - flagSet := flag.NewFlagSet("prune", flag.ExitOnError) - usageFunc := func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src users %s':\n", flagSet.Name()) - flagSet.PrintDefaults() - fmt.Println(usage) - } - var ( - daysToDelete = flagSet.Int("days", 60, "Days threshold on which to remove users, must be 60 days or greater and defaults to this value ") - removeAdmin = flagSet.Bool("remove-admin", false, "prune admin accounts") - removeNoLastActive = flagSet.Bool("remove-null-users", false, "removes users with no last active value") - skipConfirmation = flagSet.Bool("force", false, "skips user confirmation step allowing programmatic use") - displayUsersToDelete = flagSet.Bool("display-users", false, "display table of users to be deleted by prune") - apiFlags = api.NewFlags(flagSet) - ) - - handler := func(args []string) error { - if err := flagSet.Parse(args); err != nil { +var usersPruneCommand = clicompat.Wrap(&cli.Command{ + Name: "prune", + Usage: "deletes inactive users", + UsageText: "src users prune [options]", + Description: usersPruneExamples, + HideVersion: true, + Flags: clicompat.WithAPIFlags( + &cli.IntFlag{ + Name: "days", + Value: 60, + Usage: "Days threshold on which to remove users, must be 60 days or greater and defaults to this value ", + }, + &cli.BoolFlag{ + Name: "remove-admin", + Usage: "prune admin accounts", + }, + &cli.BoolFlag{ + Name: "remove-null-users", + Usage: "removes users with no last active value", + }, + &cli.BoolFlag{ + Name: "force", + Usage: "skips user confirmation step allowing programmatic use", + }, + &cli.BoolFlag{ + Name: "display-users", + Usage: "display table of users to be deleted by prune", + }, + ), + Action: func(ctx context.Context, cmd *cli.Command) error { + daysToDelete := cmd.Int("days") + removeAdmin := cmd.Bool("remove-admin") + removeNoLastActive := cmd.Bool("remove-null-users") + skipConfirmation := cmd.Bool("force") + displayUsersToDelete := cmd.Bool("display-users") + + if daysToDelete < 60 { + _, err := fmt.Fprintln(cmd.Writer, "-days flag must be set to 60 or greater") return err } - if *daysToDelete < 60 { - fmt.Println("-days flag must be set to 60 or greater") - return nil - } - ctx := context.Background() - client := cfg.apiClient(apiFlags, flagSet.Output()) + apiFlags := clicompat.APIFlagsFromCmd(cmd) + client := cfg.apiClient(apiFlags, cmd.Writer) // get current user so as not to delete issuer of the prune request currentUserQuery := `query getCurrentUser { currentUser { username }}` @@ -58,7 +75,7 @@ Examples: Username string } } - if ok, err := cfg.apiClient(apiFlags, flagSet.Output()).NewRequest(currentUserQuery, nil).Do(context.Background(), ¤tUserResult); err != nil || !ok { + if ok, err := client.NewRequest(currentUserQuery, nil).Do(ctx, ¤tUserResult); err != nil || !ok { return err } @@ -71,7 +88,7 @@ Examples: } } } - if ok, err := cfg.apiClient(apiFlags, flagSet.Output()).NewRequest(totalUsersQuery, nil).Do(context.Background(), &totalUsers); err != nil || !ok { + if ok, err := client.NewRequest(totalUsersQuery, nil).Do(ctx, &totalUsers); err != nil || !ok { return err } @@ -140,15 +157,15 @@ Examples: return err } // don't remove users with no last active value unless option flag is set - if !hasLastActive && !*removeNoLastActive { + if !hasLastActive && !removeNoLastActive { continue } // don't remove admins unless option flag is set - if !*removeAdmin && user.SiteAdmin { + if !removeAdmin && user.SiteAdmin { continue } // remove users who have been inactive for longer than the threshold set by the -days flag - if daysSinceLastUse <= *daysToDelete && hasLastActive { + if daysSinceLastUse <= daysToDelete && hasLastActive { continue } // serialize user to print in table as part of confirmUserRemoval, add to delete slice @@ -156,7 +173,7 @@ Examples: usersToDelete = append(usersToDelete, userToDelete) } - if *skipConfirmation { + if skipConfirmation { for _, user := range usersToDelete { if err := removeUser(user.User, client, ctx); err != nil { return err @@ -166,11 +183,11 @@ Examples: } // confirm and remove users - if confirmed, _ := confirmUserRemoval(usersToDelete, *daysToDelete, *displayUsersToDelete); !confirmed { - fmt.Println("Aborting removal") + if confirmed, _ := confirmUserRemoval(usersToDelete, daysToDelete, displayUsersToDelete); !confirmed { + fmt.Fprintln(cmd.Writer, "Aborting removal") return nil } else { - fmt.Println("REMOVING USERS") + fmt.Fprintln(cmd.Writer, "REMOVING USERS") for _, user := range usersToDelete { if err := removeUser(user.User, client, ctx); err != nil { return err @@ -179,15 +196,8 @@ Examples: } return nil - } - - // Register the command. - usersCommands = append(usersCommands, &command{ - flagSet: flagSet, - handler: handler, - usageFunc: usageFunc, - }) -} + }, +}) // computes days since last usage from current day and time and aggregated_user_statistics.lastActiveAt, uses time.Parse func computeDaysSinceLastUse(user SiteUser) (timeDiff int, hasLastActive bool, _ error) { diff --git a/cmd/src/users_tag.go b/cmd/src/users_tag.go index 4404c88c19..d18b0c0f13 100644 --- a/cmd/src/users_tag.go +++ b/cmd/src/users_tag.go @@ -2,14 +2,12 @@ package main import ( "context" - "flag" - "fmt" - "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/clicompat" + "github.com/urfave/cli/v3" ) -func init() { - usage := ` +const usersTagExamples = ` Examples: Add a tag "foo" to a user: @@ -28,25 +26,36 @@ Related examples: ` - flagSet := flag.NewFlagSet("tag", flag.ExitOnError) - usageFunc := func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src users %s':\n", flagSet.Name()) - flagSet.PrintDefaults() - fmt.Println(usage) - } - var ( - userIDFlag = flagSet.String("user-id", "", `The ID of the user to tag. (required)`) - tagFlag = flagSet.String("tag", "", `The tag to set on the user. (required)`) - removeFlag = flagSet.Bool("remove", false, `Remove the tag. (default: add the tag`) - apiFlags = api.NewFlags(flagSet) - ) - - handler := func(args []string) error { - if err := flagSet.Parse(args); err != nil { - return err - } - - client := cfg.apiClient(apiFlags, flagSet.Output()) +var usersTagCommand = clicompat.Wrap(&cli.Command{ + Name: "tag", + Usage: "add/remove a tag on a user", + UsageText: "src users tag [options]", + Description: usersTagExamples, + HideVersion: true, + Flags: clicompat.WithAPIFlags( + &cli.StringFlag{ + Name: "user-id", + Usage: "The ID of the user to tag.", + Required: true, + Validator: requiresNotEmpty("provide a user ID by using -user-id"), + }, + &cli.StringFlag{ + Name: "tag", + Usage: "The tag to set on the user.", + Required: true, + Validator: requiresNotEmpty("provide a tag by using -tag"), + }, + &cli.BoolFlag{ + Name: "remove", + Usage: "Remove the tag. (default: add the tag)", + }, + ), + Action: func(ctx context.Context, cmd *cli.Command) error { + userID := cmd.String("user-id") + tag := cmd.String("tag") + remove := cmd.Bool("remove") + + client := cfg.apiClient(clicompat.APIFlagsFromCmd(cmd), cmd.Writer) query := `mutation SetUserTag( $user: ID!, @@ -63,17 +72,10 @@ Related examples: }` _, err := client.NewRequest(query, map[string]any{ - "user": *userIDFlag, - "tag": *tagFlag, - "present": !*removeFlag, - }).Do(context.Background(), &struct{}{}) + "user": userID, + "tag": tag, + "present": !remove, + }).Do(ctx, &struct{}{}) return err - } - - // Register the command. - usersCommands = append(usersCommands, &command{ - flagSet: flagSet, - handler: handler, - usageFunc: usageFunc, - }) -} + }, +}) diff --git a/lib/batches/batch_spec.go b/lib/batches/batch_spec.go index a9ccc6e146..269093a82d 100644 --- a/lib/batches/batch_spec.go +++ b/lib/batches/batch_spec.go @@ -185,6 +185,7 @@ func parseBatchSpec(schema string, data []byte) (*BatchSpec, error) { return &spec, errs } + // docker uses Golang's `encoding/csv` library to parse arguments passed to `--mount` const invalidMountCharacters = ",\"\n\r" From 47598b0875e4ca37138c04014677bf0bca7898c1 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Mon, 11 May 2026 16:19:46 +0200 Subject: [PATCH 593/647] Add release skill (#1320) --- .agents/skills/release/SKILL.md | 128 ++++++++++++++++++++++++++++++++ 1 file changed, 128 insertions(+) create mode 100644 .agents/skills/release/SKILL.md diff --git a/.agents/skills/release/SKILL.md b/.agents/skills/release/SKILL.md new file mode 100644 index 0000000000..de27183f0d --- /dev/null +++ b/.agents/skills/release/SKILL.md @@ -0,0 +1,128 @@ +--- +name: release +description: Guides Sourcegraph CLI patch, minor, and major releases. Use when preparing release branches, selecting patch commits, running Trivy checks, creating release tags, or managing local/pushed release artifacts. +--- + +# Release + +## Infer the release plan + +Gather only the information that is actually missing. Do not ask questions whose answers can be derived safely from tags, release branches, repository conventions, or the user's wording. + +Before asking the user anything, derive the release plan: + +- `release_type`: from user wording or semver shape. +- `version`: from the explicit user version, otherwise from existing tags. +- `release_branch`: use the existing matching release branch when present; otherwise infer from recent branch convention. In this repository, use `release/..x`, for example `release/7.2.x` for `7.2.2`. +- `source`: user-provided source, otherwise the repository default branch. +- `tag`: repository's existing release tag format. In this repository, use the bare version as a signed annotated tag with message `Release v`, for example `git tag -s 7.2.2 -m "Release v7.2.2"`. +- `push_mode`: local-only unless the user explicitly asks to push. +- `worktree_mode`: prefer temporary git worktrees when handling multiple release trains or when the current checkout is detached or managed by `jj`. + +Ask a narrow question only when a field cannot be inferred safely or the missing answer would change release artifacts or risk pushing/tagging the wrong thing: + +1. Release type, if not clear from the request or version number. +2. Exact version, if it cannot be inferred from existing tags. +3. Source branch, if it is not the default branch. +4. Commit selection, only if the user has not provided commits/PRs and has not asked you to inspect history and decide. +5. Whether to push, only after local branches/tags are ready. + +For version inference: + +- Inspect existing tags with `git tag --list --sort=-v:refname`. +- Inspect release branches with `git branch -a --list '*release*'`. +- For patch releases, increment the latest patch tag on the target release train. +- For minor and major releases, increment the requested component from the latest released version and reset lower components to zero. +- "One minor back" means the previous minor release branch; increment the latest patch tag on that line. +- Confirm inferred versions in progress updates, but keep working unless the user asked for confirmation before mutation. + +## Hard stops + +Stop and ask before continuing if: + +- The working tree is dirty in a way not caused by this release work. +- A release branch or tag would be pushed without explicit approval. +- A force-push or tag replacement would be needed. +- Trivy or required tests fail before tagging or pushing. +- Cherry-pick conflicts remain unresolved. +- The target branch for an existing patch train is missing. + +Never tag with a dirty working tree, unresolved conflicts, failed validation, or while checked out on the wrong branch. + +## Validation + +Before starting the release work: + +1. Make sure the working tree is clean with `git status`. +2. Fetch current refs and tags with `git fetch --all --tags --prune`. +3. Run Trivy before creating final release artifacts, and earlier when the release is vulnerability-driven. + - For this repository, use `mise x trivy -- trivy fs --exit-code 1 --severity HIGH,CRITICAL`. + - Use a different documented Trivy command only if the repository adds one. + - If running from a temporary worktree, `mise` may require trusting that worktree's `mise.toml`. Run `mise trust -y /mise.toml` when needed, then remove or untrust temporary state during cleanup. + +This repository is commonly used with `jj`, so `git status` may report `HEAD (no branch)`. Treat that as normal if the worktree is otherwise clean. + +## Execute the release + +Use the same workflow for patch, minor, and major releases. The release type mainly changes which commits from the source branch are included. + +1. Inspect refreshed refs/tags and existing release branches. +2. Infer and state the release plan. +3. Validate the source and target as required. +4. Create or check out the target release branch: + - For a new release line, create the release branch from the source branch. + - For an existing release line, use the existing release branch. +5. Apply the release-type commit selection rules; use `git cherry-pick -x ` for commits ported onto an existing release branch. +6. Resolve conflicts carefully and keep the release branch limited to selected commits and release-process changes. +7. Validate every release branch after porting changes. +8. Before tagging, show the release contents summary and ask `Proceed?`. +9. Tag locally on the release branch. +10. Push the release branch and tag only when requested or required by the release process and approved by the user. + +Use this pre-tag summary format: + +```md +### Included in +- - PR # + +### Excluded +- - PR # (reason: ) + +Proceed? +``` + +## Commit selection by release type + +For patch releases, infer the selection from the purpose of a patch release: include only low-risk fixes needed for the release line, and exclude features, broad refactors, cleanup-only work, and unrelated dependency churn unless the user explicitly asks otherwise. + +For vulnerability-driven patch releases, include the full remediation closure, not just commits whose messages mention a CVE, scanner, or vulnerability. Toolchain, runtime, base-image, dependency-manifest, lockfile, scanner-configuration, and build/release-definition changes may be required prerequisites even when their commit messages are generic. + +For minor and major releases, include the normal release-train contents from the source branch, respecting any user-requested exclusions or intentionally breaking-change boundaries. + +When the user asks you to inspect history and decide what to port, compare the target release branch to the source branch and inspect likely candidates: + +- `git log --oneline --reverse origin/release/7.2.x..origin/main` +- `git show --stat --patch ` +- `git cherry -v origin/release/7.2.x ` to notice already-applied equivalent changes + +Do not rely on commit messages alone. Inspect nearby commits, parent/child relationships, and file-level dependencies so prerequisite fixes are not missed. Before finalizing candidate selection, summarize any excluded adjacent prerequisite commits and why they are excluded. + +## Tagging rules + +- Always tag on the release branch. +- State the inferred tag before creating it; ask only if the format cannot be inferred or the operation will push. +- Prefer the repository's existing tag format. Inspect existing tags if unsure. +- Verify the checked-out branch before tagging with `git branch --show-current`. +- After tagging, show the created tag and the commit it points to. +- Summarize every mutation: branch creation, cherry-picks, version changes, commits, pushes, and tags. + +## Local-only release summary + +When local release artifacts are ready, report: + +- Versions created and target branches. +- Cherry-picked source commits and resulting branch-tip commits. +- Tag names, tag targets, and whether tags are annotated/signed. +- Validation commands and outcomes. +- Ahead counts versus origin, for example `git rev-list --left-right --count origin/release/7.2.x...release/7.2.x`. +- That no pushes were performed, unless pushes were explicitly requested. From ed8850d04feaf43fa6c8d94c66fda8aba3bf7fb2 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Wed, 20 May 2026 14:54:05 +0200 Subject: [PATCH 594/647] remove progress bar for doc generation. (#1323) We only print now when the verbose flag `-v` is given. Otherwise we print nothing and exit 0 --- cmd/src/doc.go | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/cmd/src/doc.go b/cmd/src/doc.go index 8132189c87..ed4021bb5c 100644 --- a/cmd/src/doc.go +++ b/cmd/src/doc.go @@ -65,12 +65,8 @@ Examples: "repos": &reposCommands, } - pending := out.Pending(output.Line("", output.StylePending, "Rendering Markdown...")) - count := 0 rootSubcommands := map[string]string{} - defer func() { - pending.Complete(output.Linef(output.EmojiSuccess, output.StyleSuccess, "%d files rendered under %s", count, *outputFlag)) - }() + count := 0 for groupName, cmdr := range commanders { subcommands := map[string]string{} @@ -86,7 +82,6 @@ Examples: if fqcn == "doc" || fqcn == "publish" { continue } - pending.Update(fqcn) // If this name appears in our commanders map, then this isn't a // real command, and we'll handle it differently. @@ -145,7 +140,7 @@ Examples: } for _, md := range mdFiles { - pending.Update(md.Name) + out.Verbosef("writing: %s", md.Name) docPath := path.Join(dstDir, md.Name) if err := os.MkdirAll(path.Dir(docPath), 0755); err != nil { return err @@ -171,6 +166,7 @@ Examples: return err } count++ + out.VerboseLine(output.Linef(output.EmojiSuccess, output.StyleSuccess, "%d files rendered under %s", count, *outputFlag)) return nil } From e3e7712002f8af1eeb022d1fb97e52455319e9df Mon Sep 17 00:00:00 2001 From: Taras Yemets Date: Fri, 29 May 2026 21:23:33 +0300 Subject: [PATCH 595/647] fix/batch-changes: ignore per-job env vars in cache key (#1326) --- lib/batches/execution/cache/cache.go | 12 +++++++++ lib/batches/execution/cache/cache_test.go | 31 +++++++++++++++++++++++ lib/go.mod | 3 +++ 3 files changed, 46 insertions(+) create mode 100644 lib/batches/execution/cache/cache_test.go diff --git a/lib/batches/execution/cache/cache.go b/lib/batches/execution/cache/cache.go index 9392cd2c31..f77d5ab92d 100644 --- a/lib/batches/execution/cache/cache.go +++ b/lib/batches/execution/cache/cache.go @@ -47,6 +47,15 @@ func (key CacheKey) mountsMetadata() ([]MountMetadata, error) { return nil, nil } +// perRunEnvVars resolve to per-job or per-executor values that change on +// every dequeue and must be stripped from cache keys. Mirrored in +// sourcegraph/sourcegraph/lib/batches/execution/cache/cache.go. +var perRunEnvVars = []string{ + "SRC_EXECUTOR_JOB_TOKEN", + "SRC_EXECUTOR_JOB_ID", + "SRC_EXECUTOR_NAME", +} + // resolveStepsEnvironment returns a slice of environments for each of the steps, // containing only the env vars that are actually used. func resolveStepsEnvironment(globalEnv []string, steps []batches.Step) ([]map[string]string, error) { @@ -64,6 +73,9 @@ func resolveStepsEnvironment(globalEnv []string, steps []batches.Step) ([]map[st if err != nil { return nil, errors.Wrapf(err, "resolving environment for step %d", i) } + for _, name := range perRunEnvVars { + delete(env, name) + } envs[i] = env } return envs, nil diff --git a/lib/batches/execution/cache/cache_test.go b/lib/batches/execution/cache/cache_test.go new file mode 100644 index 0000000000..c416fe024f --- /dev/null +++ b/lib/batches/execution/cache/cache_test.go @@ -0,0 +1,31 @@ +package cache + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/sourcegraph/sourcegraph/lib/batches" + "github.com/sourcegraph/sourcegraph/lib/batches/env" +) + +func TestKeyer_Key_PerRunEnvVarsIgnored(t *testing.T) { + var stepEnv env.Environment + require.NoError(t, json.Unmarshal( + []byte(`["SRC_EXECUTOR_JOB_TOKEN", "SRC_EXECUTOR_JOB_ID", "SRC_EXECUTOR_NAME"]`), + &stepEnv, + )) + step := batches.Step{Run: "foo", Env: stepEnv} + repo := batches.Repository{ID: "r", Name: "r"} + + unset, err := (&CacheKey{Repository: repo, Steps: []batches.Step{step}, StepIndex: 0}).Key() + require.NoError(t, err) + resolved, err := (&CacheKey{Repository: repo, Steps: []batches.Step{step}, StepIndex: 0, GlobalEnv: []string{ + "SRC_EXECUTOR_JOB_TOKEN=tok", + "SRC_EXECUTOR_JOB_ID=42", + "SRC_EXECUTOR_NAME=executor-abc", + }}).Key() + require.NoError(t, err) + require.Equal(t, unset, resolved) +} diff --git a/lib/go.mod b/lib/go.mod index 44fdc19356..00f3d2d6df 100644 --- a/lib/go.mod +++ b/lib/go.mod @@ -22,6 +22,7 @@ require ( github.com/sourcegraph/conc v0.3.0 github.com/sourcegraph/go-diff v0.7.0 github.com/sourcegraph/log v0.0.0-20250923023806-517b6960b55b + github.com/stretchr/testify v1.11.1 github.com/urfave/cli/v3 v3.8.0 github.com/xeipuuv/gojsonschema v1.2.0 github.com/xlab/treeprint v1.2.0 @@ -46,6 +47,7 @@ require ( github.com/charmbracelet/x/term v0.2.1 // indirect github.com/clipperhouse/uax29/v2 v2.2.0 // indirect github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect + github.com/davecgh/go-spew v1.1.1 // indirect github.com/dlclark/regexp2 v1.11.0 // indirect github.com/fatih/color v1.18.0 // indirect github.com/getsentry/sentry-go v0.27.0 // indirect @@ -64,6 +66,7 @@ require ( github.com/microcosm-cc/bluemonday v1.0.27 // indirect github.com/muesli/reflow v0.3.0 // indirect github.com/pkg/errors v0.9.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect github.com/rivo/uniseg v0.4.7 // indirect github.com/rogpeppe/go-internal v1.14.1 // indirect github.com/sourcegraph/beaut v0.0.0-20240611013027-627e4c25335a // indirect From 06cd2cd0ebeb7161d3b370420b532d5b34c91457 Mon Sep 17 00:00:00 2001 From: Michael Bahr <1830132+bahrmichael@users.noreply.github.com> Date: Mon, 1 Jun 2026 11:51:01 +0200 Subject: [PATCH 596/647] chore: update vendored Sourcegraph lib (#1328) * chore: update vendored Sourcegraph lib Vendor github.com/sourcegraph/sourcegraph/lib at bdc2f4bb8b59f78f4fa8868b2690b673b41948d4 and restore src-cli compatibility for APIs still used locally. Test Plan: go test ./... Amp-Thread-ID: https://ampcode.com/threads/T-019e8206-7c7d-76cb-9b08-b6e0df454e15 Co-authored-by: Amp * revert cache change * revert cache test deletion --------- Co-authored-by: Amp --- lib/README.md | 4 +- lib/batches/batch_spec.go | 151 ++++++++++++++++-- lib/batches/changeset_spec.go | 6 - lib/batches/overridable/bool.go | 7 - lib/batches/template/partial_eval.go | 3 +- lib/batches/template/template.go | 9 +- lib/batches/template/templating.go | 7 +- lib/codeintel/upload/indexer_name.go | 3 - lib/codeintel/upload/request.go | 25 ++- lib/codeintel/upload/upload.go | 2 - lib/errors/client_error.go | 6 +- lib/errors/cockroach.go | 34 ++-- lib/errors/multi_error.go | 6 +- lib/errors/rich_error.go | 9 +- lib/go.mod | 90 ----------- lib/output/capabilities.go | 8 +- lib/output/emoji.go | 4 +- lib/output/line.go | 5 +- lib/output/output.go | 13 +- lib/output/output_unix.go | 1 - lib/output/pending_tty.go | 6 +- lib/output/progress.go | 8 +- lib/output/progress_simple.go | 8 +- lib/output/progress_tty.go | 8 +- .../progress_with_status_bars_simple.go | 6 +- lib/output/progress_with_status_bars_tty.go | 9 +- lib/output/spinner.go | 3 + lib/output/table.go | 8 +- lib/process/pipe.go | 8 +- 29 files changed, 251 insertions(+), 206 deletions(-) diff --git a/lib/README.md b/lib/README.md index 0b478e3cd1..e9bb62031c 100644 --- a/lib/README.md +++ b/lib/README.md @@ -5,8 +5,8 @@ This directory contains vendored packages from `github.com/sourcegraph/sourcegra ## Source - **Repository**: https://github.com/sourcegraph/sourcegraph -- **Commit**: 2ee2b8e77de9663b08ce5f6e5a2c7d2217ce721a -- **Date**: 2025-11-17 19:49:42 -0800 +- **Commit**: bdc2f4bb8b59f78f4fa8868b2690b673b41948d4 +- **Date**: 2026-06-01 07:34:50 +0100 ## Updating diff --git a/lib/batches/batch_spec.go b/lib/batches/batch_spec.go index 269093a82d..30ef50d4a9 100644 --- a/lib/batches/batch_spec.go +++ b/lib/batches/batch_spec.go @@ -1,6 +1,7 @@ package batches import ( + "encoding/json" "fmt" "strings" @@ -38,8 +39,31 @@ type BatchSpec struct { TransformChanges *TransformChanges `json:"transformChanges,omitempty" yaml:"transformChanges,omitempty"` ImportChangesets []ImportChangeset `json:"importChangesets,omitempty" yaml:"importChangesets"` ChangesetTemplate *ChangesetTemplate `json:"changesetTemplate,omitempty" yaml:"changesetTemplate"` + ChangesetHooks *ChangesetHooks `json:"changesetHooks,omitempty" yaml:"hooks,omitempty"` } +// Hooks declares side-effect actions to run at well-defined changeset +// lifecycle events. Only allowed when Version is 3. +type ChangesetHooks struct { + OnCIFailure ChangesetHookAction `json:"onCIFailure,omitempty" yaml:"onCIFailure,omitempty"` + OnMergeConflict ChangesetHookAction `json:"onMergeConflict,omitempty" yaml:"onMergeConflict,omitempty"` +} + +// HookAction is a single action attached to a changeset lifecycle event. +// +// Hook actions reuse the Step shape from the top-level steps block. +type ChangesetHookAction struct { + Steps []Step `json:"steps,omitempty" yaml:"steps,omitempty"` +} + +type changesetHookEvent string + +// Hook event names. Kept here so callers don't pass typoed strings. +const ( + ChangesetHookEventOnCIFailure changesetHookEvent = "onCIFailure" + ChangesetHookEventOnMergeConflict changesetHookEvent = "onMergeConflict" +) + type ChangesetTemplate struct { Title string `json:"title,omitempty" yaml:"title"` Body string `json:"body,omitempty" yaml:"body"` @@ -90,13 +114,46 @@ func (oqor *OnQueryOrRepository) GetBranches() ([]string, error) { } type Step struct { - Run string `json:"run,omitempty" yaml:"run"` - Container string `json:"container,omitempty" yaml:"container"` - Env env.Environment `json:"env" yaml:"env"` - Files map[string]string `json:"files,omitempty" yaml:"files,omitempty"` - Outputs Outputs `json:"outputs,omitempty" yaml:"outputs,omitempty"` - Mount []Mount `json:"mount,omitempty" yaml:"mount,omitempty"` - If any `json:"if,omitempty" yaml:"if,omitempty"` + Run string `json:"run,omitempty" yaml:"run"` + CodingAgent *CodingAgentStep `json:"codingAgent,omitempty" yaml:"codingAgent,omitempty"` + BuildImage *BuildImageStep `json:"buildImage,omitempty" yaml:"buildImage,omitempty"` + Container string `json:"container,omitempty" yaml:"container"` + Image string `json:"image,omitempty" yaml:"image"` + MaxAttempts int `json:"maxAttempts,omitempty" yaml:"maxAttempts,omitempty"` + Env env.Environment `json:"env" yaml:"env"` + Files map[string]string `json:"files,omitempty" yaml:"files,omitempty"` + Outputs Outputs `json:"outputs,omitempty" yaml:"outputs,omitempty"` + Mount []Mount `json:"mount,omitempty" yaml:"mount,omitempty"` + If any `json:"if,omitempty" yaml:"if,omitempty"` +} + +type CodingAgentStep struct { + Type string `json:"type,omitempty" yaml:"type"` + Prompt string `json:"prompt,omitempty" yaml:"prompt"` +} + +type BuildImageStep struct { + Run string `json:"run" yaml:"run"` + BaseImage string `json:"baseImage" yaml:"baseImage"` +} + +// MarshalJSON canonicalizes the v3 `image:` field into `container:` on the +// wire. Both fields exist on Step for ergonomic reasons (v3 specs use +// `image:`, v1/v2 specs use `container:`), but src-cli's Step has only +// `Container`. Without canonicalization, the prep-side cache key — computed +// by JSON-marshaling Step — would include `image` while the executor side +// (which round-trips through src-cli) would not, producing divergent keys +// and silent cache misses for any v3 spec. See the regression test in +// lib/batches/execution/cache. +func (s Step) MarshalJSON() ([]byte, error) { + // Use an alias type to avoid infinite recursion through MarshalJSON. + type stepAlias Step + canon := stepAlias(s) + if canon.Container == "" { + canon.Container = canon.Image + } + canon.Image = "" + return json.Marshal(canon) } func (s *Step) IfCondition() string { @@ -161,33 +218,97 @@ func parseBatchSpec(schema string, data []byte) (*BatchSpec, error) { return nil, err } - var errs error + if spec.Version == 3 { + // Mirror v3 `image:` into `container:` so in-memory consumers that + // read step.Container (e.g. the executor transform) keep working. + // JSON serialization is canonicalized separately in Step.MarshalJSON + // so prep-side cache hashing matches src-cli/executor serialization. + for i := range spec.Steps { + spec.Steps[i].Container = spec.Steps[i].Image + } + } + var errs error if len(spec.Steps) != 0 && spec.ChangesetTemplate == nil { errs = errors.Append(errs, NewValidationError(errors.New("batch spec includes steps but no changesetTemplate"))) } + // v3 specs do not support changesetTemplate.published — publication is + // driven exclusively via the batchchangeagent tools. Reject the field at + // parse time. + if spec.Version == 3 && spec.ChangesetTemplate != nil && spec.ChangesetTemplate.Published != nil { + errs = errors.Append(errs, NewValidationError(errors.New("changesetTemplate.published is not supported in batch spec version 3; drive publication via the publish_changesets tool instead"))) + } + for i, step := range spec.Steps { for _, mount := range step.Mount { - if strings.ContainsAny(mount.Path, invalidMountCharacters) { + if strings.Contains(mount.Path, invalidMountCharacters) { errs = errors.Append(errs, NewValidationError(errors.Newf("step %d mount path contains invalid characters", i+1))) } - if strings.ContainsAny(mount.Mountpoint, invalidMountCharacters) { + if strings.Contains(mount.Mountpoint, invalidMountCharacters) { errs = errors.Append(errs, NewValidationError(errors.Newf("step %d mount mountpoint contains invalid characters", i+1))) } } + if step.CodingAgent != nil && step.Run != "" { + errs = errors.Append(errs, NewValidationError(errors.Newf("step %d: codingAgent and run cannot be combined in the same step", i+1))) + } + if step.BuildImage != nil && step.Run != "" { + errs = errors.Append(errs, NewValidationError(errors.Newf("step %d: buildImage and run cannot be combined in the same step", i+1))) + } for name := range step.Files { - if strings.ContainsAny(name, invalidMountCharacters) { + if strings.Contains(name, invalidMountCharacters) { errs = errors.Append(errs, NewValidationError(errors.Newf("step %d files target path contains invalid characters", i+1))) } } } + if hookErr := validateHooks(&spec); hookErr != nil { + errs = errors.Append(errs, hookErr) + } + return &spec, errs } -// docker uses Golang's `encoding/csv` library to parse arguments passed to `--mount` -const invalidMountCharacters = ",\"\n\r" +// validateHooks performs Go-level validation of spec.Hooks beyond what the +// JSON schema enforces. The schema already gates `hooks:` on `version: 3` and +// rejects unknown event names. We re-check the version invariant here so +// non-schema callers (and any future schema drift) still fail safely, and we +// run the per-step mount-character validator that the schema cannot express. +func validateHooks(spec *BatchSpec) error { + if spec.ChangesetHooks == nil { + return nil + } + + var errs error + + if spec.Version != 3 { + errs = errors.Append(errs, NewValidationError(errors.New("batch spec hooks require version: 3"))) + } + + validate := func(event changesetHookEvent, action ChangesetHookAction) { + for i, step := range action.Steps { + for _, mount := range step.Mount { + if strings.Contains(mount.Path, invalidMountCharacters) { + errs = errors.Append(errs, NewValidationError(errors.Newf( + "hooks.%s step %d mount path contains invalid characters", event, i+1, + ))) + } + if strings.Contains(mount.Mountpoint, invalidMountCharacters) { + errs = errors.Append(errs, NewValidationError(errors.Newf( + "hooks.%s step %d mount mountpoint contains invalid characters", event, i+1, + ))) + } + } + } + } + + validate(ChangesetHookEventOnCIFailure, spec.ChangesetHooks.OnCIFailure) + validate(ChangesetHookEventOnMergeConflict, spec.ChangesetHooks.OnMergeConflict) + + return errs +} + +const invalidMountCharacters = "," func (on *OnQueryOrRepository) String() string { if on.RepositoriesMatchingQuery != "" { @@ -212,10 +333,6 @@ func (e BatchSpecValidationError) Error() string { return e.err.Error() } -func IsValidationError(err error) bool { - return errors.HasType[*BatchSpecValidationError](err) -} - // SkippedStepsForRepo calculates the steps required to run on the given repo. func SkippedStepsForRepo(spec *BatchSpec, repoName string, fileMatches []string) (skipped map[int]struct{}, err error) { skipped = map[int]struct{}{} diff --git a/lib/batches/changeset_spec.go b/lib/batches/changeset_spec.go index 4b64f670a1..16e917e311 100644 --- a/lib/batches/changeset_spec.go +++ b/lib/batches/changeset_spec.go @@ -203,12 +203,6 @@ func (d *ChangesetSpec) IsImportingExisting() bool { return d.Type() == ChangesetSpecDescriptionTypeExisting } -// IsBranch returns whether the description is of type -// ChangesetSpecDescriptionTypeBranch. -func (d *ChangesetSpec) IsBranch() bool { - return d.Type() == ChangesetSpecDescriptionTypeBranch -} - // ChangesetSpecDescriptionType tells the consumer what the type of a // ChangesetSpecDescription is without having to look into the description. // Useful in the GraphQL when a HiddenChangesetSpec is returned. diff --git a/lib/batches/overridable/bool.go b/lib/batches/overridable/bool.go index 411e466071..8d90d6a073 100644 --- a/lib/batches/overridable/bool.go +++ b/lib/batches/overridable/bool.go @@ -7,13 +7,6 @@ type Bool struct { rules rules } -// FromBool creates a Bool representing a static, scalar value. -func FromBool(b bool) Bool { - return Bool{ - rules: rules{simpleRule(b)}, - } -} - // Value returns the bool value for the given repository. func (b *Bool) Value(name string) bool { v := b.rules.Match(name) diff --git a/lib/batches/template/partial_eval.go b/lib/batches/template/partial_eval.go index 905ece71d5..e38c328e90 100644 --- a/lib/batches/template/partial_eval.go +++ b/lib/batches/template/partial_eval.go @@ -69,7 +69,6 @@ func parseAndPartialEval(input string, ctx *StepContext) (*template.Template, er Funcs(builtins). Funcs(ctx.ToFuncMap()). Parse(input) - if err != nil { return nil, err } @@ -329,7 +328,7 @@ func isTrue(val reflect.Value) (truth bool) { return val.Bool() case reflect.Complex64, reflect.Complex128: return val.Complex() != 0 - case reflect.Chan, reflect.Func, reflect.Ptr, reflect.Interface: + case reflect.Chan, reflect.Func, reflect.Pointer, reflect.Interface: return !val.IsNil() case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return val.Int() != 0 diff --git a/lib/batches/template/template.go b/lib/batches/template/template.go index 0591ee8870..0b04518f7f 100644 --- a/lib/batches/template/template.go +++ b/lib/batches/template/template.go @@ -1,6 +1,9 @@ package template -import "text/template" +import ( + "strings" + "text/template" +) func New(name, tmpl, option string, ctxs ...template.FuncMap) (*template.Template, error) { t := template.New(name).Delims(startDelim, endDelim) @@ -16,3 +19,7 @@ func New(name, tmpl, option string, ctxs ...template.FuncMap) (*template.Templat return t.Parse(tmpl) } + +func ContainsTemplateAction(tmpl string) bool { + return strings.Contains(tmpl, startDelim) +} diff --git a/lib/batches/template/templating.go b/lib/batches/template/templating.go index eae6547860..2ff1d641d4 100644 --- a/lib/batches/template/templating.go +++ b/lib/batches/template/templating.go @@ -16,8 +16,10 @@ import ( "github.com/sourcegraph/sourcegraph/lib/errors" ) -const startDelim = "${{" -const endDelim = "}}" +const ( + startDelim = "${{" + endDelim = "}}" +) var builtins = template.FuncMap{ "join": strings.Join, @@ -74,7 +76,6 @@ func ValidateBatchSpecTemplate(spec string) (bool, error) { // option "missingkey=error". See https://pkg.go.dev/text/template#Template.Option for // more. t, err := New("validateBatchSpecTemplate", spec, "missingkey=error", sfm, cstfm) - if err != nil { // Attempt to extract the specific template variable field that caused the error // to provide a clearer message. diff --git a/lib/codeintel/upload/indexer_name.go b/lib/codeintel/upload/indexer_name.go index 318dc6f82b..c534e6f7d3 100644 --- a/lib/codeintel/upload/indexer_name.go +++ b/lib/codeintel/upload/indexer_name.go @@ -20,9 +20,6 @@ import ( // is 10639 characters long. const MaxBufferSize = 128 * 1024 -// ErrMetadataExceedsBuffer occurs when the first line of an LSIF index is too long to read. -var ErrMetadataExceedsBuffer = errors.New("metaData vertex exceeds buffer") - // ErrInvalidMetaDataVertex occurs when the first line of an LSIF index is not a valid metadata vertex. var ErrInvalidMetaDataVertex = errors.New("invalid metaData vertex") diff --git a/lib/codeintel/upload/request.go b/lib/codeintel/upload/request.go index db571435ea..9de1a799ae 100644 --- a/lib/codeintel/upload/request.go +++ b/lib/codeintel/upload/request.go @@ -30,6 +30,9 @@ type uploadRequestOptions struct { // ErrUnauthorized occurs when the upload endpoint returns a 401 response. var ErrUnauthorized = errors.New("unauthorized upload") +// ErrForbidden occurs when the upload endpoint returns a 403 response. +var ErrForbidden = errors.New("insufficient permissions") + // performUploadRequest performs an HTTP POST to the upload endpoint. The query string of the request // is constructed from the given request options and the body of the request is the unmodified reader. // If target is a non-nil pointer, it will be assigned the value of the upload identifier present @@ -105,17 +108,17 @@ func performRequest(ctx context.Context, req *http.Request, httpClient Client, l // returns a boolean flag indicating if the function can be retried on failure (error-dependent). func decodeUploadPayload(resp *http.Response, body []byte, target *int) (bool, error) { if resp.StatusCode >= 300 { + detail := extractBodyDetail(body) + if resp.StatusCode == http.StatusUnauthorized { - return false, ErrUnauthorized + return false, errors.Wrap(ErrUnauthorized, detail) } - - suffix := "" - if !bytes.HasPrefix(bytes.TrimSpace(body), []byte{'<'}) { - suffix = fmt.Sprintf(" (%s)", bytes.TrimSpace(body)) + if resp.StatusCode == http.StatusForbidden { + return false, errors.Wrap(ErrForbidden, detail) } // Do not retry client errors - return resp.StatusCode >= 500, errors.Errorf("unexpected status code: %d%s", resp.StatusCode, suffix) + return resp.StatusCode >= 500, errors.Errorf("unexpected status code: %d: %s", resp.StatusCode, detail) } if target == nil { @@ -199,6 +202,16 @@ func makeUploadURL(opts uploadRequestOptions) (*url.URL, error) { return parsedUrl, nil } +// extractBodyDetail returns the response body as a suffix string for error messages. +// Returns an empty string if the body is empty or appears to be HTML. +func extractBodyDetail(body []byte) string { + trimmed := bytes.TrimSpace(body) + if len(trimmed) == 0 || bytes.HasPrefix(trimmed, []byte{'<'}) { + return "" + } + return string(trimmed) +} + func formatInt(v int) string { return strconv.FormatInt(int64(v), 10) } diff --git a/lib/codeintel/upload/upload.go b/lib/codeintel/upload/upload.go index 097990d1b8..55a977c358 100644 --- a/lib/codeintel/upload/upload.go +++ b/lib/codeintel/upload/upload.go @@ -218,8 +218,6 @@ func uploadMultipartIndexParts(ctx context.Context, httpClient Client, opts Uplo } for i, reader := range readers { - i, reader := i, reader - pool.Go(func(ctx context.Context) error { // Determine size of this reader. If we're not the last reader in the slice, // then we're the maximum payload size. Otherwise, we're whatever is left. diff --git a/lib/errors/client_error.go b/lib/errors/client_error.go index 505646a1cf..a6b39493ab 100644 --- a/lib/errors/client_error.go +++ b/lib/errors/client_error.go @@ -14,8 +14,10 @@ type ClientError struct { Err error } -var _ error = ClientError{nil} -var _ Wrapper = ClientError{nil} +var ( + _ error = ClientError{nil} + _ Wrapper = ClientError{nil} +) func (e ClientError) Error() string { return e.Err.Error() diff --git a/lib/errors/cockroach.go b/lib/errors/cockroach.go index 7a8632722d..6a1ac6dcc3 100644 --- a/lib/errors/cockroach.go +++ b/lib/errors/cockroach.go @@ -102,7 +102,7 @@ func AsInterface[I any](err error, target *I) bool { if target == nil { panic("Expected non-nil pointer to interface") } - if typ := reflect.TypeOf(target); typ.Elem().Kind() != reflect.Interface { + if typ := reflect.TypeFor[*I](); typ.Elem().Kind() != reflect.Interface { panic("Expected pointer to interface") } return errors.As(err, target) @@ -164,23 +164,23 @@ func registerCockroachSafeTypes() { // We consider booleans and numeric values to be always safe for // reporting. A log call can opt out by using redact.Unsafe() around // a value that would be otherwise considered safe. - redact.RegisterSafeType(reflect.TypeOf(true)) // bool - redact.RegisterSafeType(reflect.TypeOf(123)) // int - redact.RegisterSafeType(reflect.TypeOf(int8(0))) - redact.RegisterSafeType(reflect.TypeOf(int16(0))) - redact.RegisterSafeType(reflect.TypeOf(int32(0))) - redact.RegisterSafeType(reflect.TypeOf(int64(0))) - redact.RegisterSafeType(reflect.TypeOf(uint8(0))) - redact.RegisterSafeType(reflect.TypeOf(uint16(0))) - redact.RegisterSafeType(reflect.TypeOf(uint32(0))) - redact.RegisterSafeType(reflect.TypeOf(uint64(0))) - redact.RegisterSafeType(reflect.TypeOf(float32(0))) - redact.RegisterSafeType(reflect.TypeOf(float64(0))) - redact.RegisterSafeType(reflect.TypeOf(complex64(0))) - redact.RegisterSafeType(reflect.TypeOf(complex128(0))) + redact.RegisterSafeType(reflect.TypeFor[bool]()) // bool + redact.RegisterSafeType(reflect.TypeFor[int]()) // int + redact.RegisterSafeType(reflect.TypeFor[int8]()) + redact.RegisterSafeType(reflect.TypeFor[int16]()) + redact.RegisterSafeType(reflect.TypeFor[int32]()) + redact.RegisterSafeType(reflect.TypeFor[int64]()) + redact.RegisterSafeType(reflect.TypeFor[uint8]()) + redact.RegisterSafeType(reflect.TypeFor[uint16]()) + redact.RegisterSafeType(reflect.TypeFor[uint32]()) + redact.RegisterSafeType(reflect.TypeFor[uint64]()) + redact.RegisterSafeType(reflect.TypeFor[float32]()) + redact.RegisterSafeType(reflect.TypeFor[float64]()) + redact.RegisterSafeType(reflect.TypeFor[complex64]()) + redact.RegisterSafeType(reflect.TypeFor[complex128]()) // Signal names are also safe for reporting. redact.RegisterSafeType(reflect.TypeOf(os.Interrupt)) // Times and durations too. - redact.RegisterSafeType(reflect.TypeOf(time.Time{})) - redact.RegisterSafeType(reflect.TypeOf(time.Duration(0))) + redact.RegisterSafeType(reflect.TypeFor[time.Time]()) + redact.RegisterSafeType(reflect.TypeFor[time.Duration]()) } diff --git a/lib/errors/multi_error.go b/lib/errors/multi_error.go index 452061473e..86824eb6fa 100644 --- a/lib/errors/multi_error.go +++ b/lib/errors/multi_error.go @@ -22,8 +22,10 @@ type multiError struct { errs []error } -var _ MultiError = (*multiError)(nil) -var _ Typed = (*multiError)(nil) +var ( + _ MultiError = (*multiError)(nil) + _ Typed = (*multiError)(nil) +) func combineNonNilErrors(err1 error, err2 error) MultiError { multi1, ok1 := err1.(MultiError) diff --git a/lib/errors/rich_error.go b/lib/errors/rich_error.go index 6315f3e7e1..b4d7a53e6b 100644 --- a/lib/errors/rich_error.go +++ b/lib/errors/rich_error.go @@ -46,7 +46,7 @@ func UnpackRichErrorPtr(richErr *RichError) (error, []attribute.KeyValue) { if richErr == nil || *richErr == nil { return nil, nil } - if val := reflect.ValueOf(*richErr); val.Kind() == reflect.Ptr && val.IsNil() { + if val := reflect.ValueOf(*richErr); val.Kind() == reflect.Pointer && val.IsNil() { return nil, nil } data := (*richErr).Unpack() @@ -57,11 +57,6 @@ type ErrorPtr[A any, T PtrRichError[A]] struct { ptr2 **A } -// nolint:unused -func typeAssertion[A any, T PtrRichError[A]]() { - var _ RichError = (*ErrorPtr[A, T])(nil) -} - // NewErrorPtr is the only way to create an ErrorPtr. func NewErrorPtr[A any, T PtrRichError[A]](ptr2 **A) ErrorPtr[A, T] { if ptr2 == nil { @@ -94,7 +89,7 @@ func (p ErrorPtr[A, T]) Unpack() RichErrorData { if val == nil { return empty } - if inner := reflect.ValueOf(val); inner.Kind() == reflect.Ptr && inner.IsNil() { + if inner := reflect.ValueOf(val); inner.Kind() == reflect.Pointer && inner.IsNil() { return empty } return val.Unpack() diff --git a/lib/go.mod b/lib/go.mod index 00f3d2d6df..e57ef54d53 100644 --- a/lib/go.mod +++ b/lib/go.mod @@ -1,93 +1,3 @@ module github.com/sourcegraph/sourcegraph/lib go 1.26.3 - -require ( - github.com/Masterminds/semver v1.5.0 - github.com/charmbracelet/glamour v0.10.0 - github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834 - github.com/cockroachdb/errors v1.12.0 - github.com/cockroachdb/redact v1.1.6 - github.com/ghodss/yaml v1.0.0 - github.com/gobwas/glob v0.2.3 - github.com/google/go-cmp v0.7.0 - github.com/grafana/regexp v0.0.0-20250905093917-f7b3be9d1853 - github.com/jackc/pgx/v5 v5.9.2 - github.com/klauspost/pgzip v1.2.6 - github.com/mattn/go-isatty v0.0.20 - github.com/mattn/go-runewidth v0.0.19 - github.com/moby/term v0.5.2 - github.com/muesli/termenv v0.16.0 - github.com/scip-code/scip/bindings/go/scip v0.7.0 - github.com/sourcegraph/conc v0.3.0 - github.com/sourcegraph/go-diff v0.7.0 - github.com/sourcegraph/log v0.0.0-20250923023806-517b6960b55b - github.com/stretchr/testify v1.11.1 - github.com/urfave/cli/v3 v3.8.0 - github.com/xeipuuv/gojsonschema v1.2.0 - github.com/xlab/treeprint v1.2.0 - go.opentelemetry.io/otel v1.43.0 - golang.org/x/sys v0.41.0 - golang.org/x/term v0.37.0 - google.golang.org/protobuf v1.36.10 - gopkg.in/yaml.v3 v3.0.1 -) - -require ( - github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c // indirect - github.com/alecthomas/chroma/v2 v2.14.0 // indirect - github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect - github.com/aymerick/douceur v0.2.0 // indirect - github.com/benbjohnson/clock v1.3.5 // indirect - github.com/cespare/xxhash/v2 v2.3.0 // indirect - github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect - github.com/charmbracelet/x/ansi v0.8.0 // indirect - github.com/charmbracelet/x/cellbuf v0.0.13 // indirect - github.com/charmbracelet/x/exp/slice v0.0.0-20250327172914-2fdc97757edf // indirect - github.com/charmbracelet/x/term v0.2.1 // indirect - github.com/clipperhouse/uax29/v2 v2.2.0 // indirect - github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect - github.com/davecgh/go-spew v1.1.1 // indirect - github.com/dlclark/regexp2 v1.11.0 // indirect - github.com/fatih/color v1.18.0 // indirect - github.com/getsentry/sentry-go v0.27.0 // indirect - github.com/go-logr/logr v1.4.3 // indirect - github.com/go-logr/stdr v1.2.2 // indirect - github.com/gogo/protobuf v1.3.2 // indirect - github.com/google/uuid v1.6.0 // indirect - github.com/gorilla/css v1.0.1 // indirect - github.com/jackc/pgpassfile v1.0.0 // indirect - github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect - github.com/klauspost/compress v1.18.0 // indirect - github.com/kr/pretty v0.3.1 // indirect - github.com/kr/text v0.2.0 // indirect - github.com/lucasb-eyer/go-colorful v1.2.0 // indirect - github.com/mattn/go-colorable v0.1.14 // indirect - github.com/microcosm-cc/bluemonday v1.0.27 // indirect - github.com/muesli/reflow v0.3.0 // indirect - github.com/pkg/errors v0.9.1 // indirect - github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/rivo/uniseg v0.4.7 // indirect - github.com/rogpeppe/go-internal v1.14.1 // indirect - github.com/sourcegraph/beaut v0.0.0-20240611013027-627e4c25335a // indirect - github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f // indirect - github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect - github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect - github.com/yuin/goldmark v1.7.8 // indirect - github.com/yuin/goldmark-emoji v1.0.5 // indirect - go.opentelemetry.io/auto/sdk v1.2.1 // indirect - go.opentelemetry.io/otel/metric v1.43.0 // indirect - go.opentelemetry.io/otel/trace v1.43.0 // indirect - go.uber.org/atomic v1.11.0 // indirect - go.uber.org/goleak v1.3.0 // indirect - go.uber.org/multierr v1.11.0 // indirect - go.uber.org/zap v1.24.0 // indirect - golang.org/x/exp v0.0.0-20230713183714-613f0c0eb8a1 // indirect - golang.org/x/net v0.44.0 // indirect - golang.org/x/text v0.29.0 // indirect - golang.org/x/tools v0.37.0 // indirect - gopkg.in/yaml.v2 v2.4.0 // indirect -) - -// See: https://github.com/ghodss/yaml/pull/65 -replace github.com/ghodss/yaml => github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 diff --git a/lib/output/capabilities.go b/lib/output/capabilities.go index f789104ecd..1bca2bd56e 100644 --- a/lib/output/capabilities.go +++ b/lib/output/capabilities.go @@ -82,7 +82,13 @@ func detectCapabilities(opts OutputOpts) (caps capabilities, err error) { // detect color mode caps.Color = opts.ForceColor if !opts.ForceColor { - caps.Color = detectColor(caps.Isatty) + // If ForceTTY is explicitly false, we also disable colors since non-TTY + // mode shouldn't have colors (and detection might be affected by env vars). + if opts.ForceTTY != nil && !*opts.ForceTTY { + caps.Color = false + } else { + caps.Color = detectColor(caps.Isatty) + } } // set detected background color diff --git a/lib/output/emoji.go b/lib/output/emoji.go index 469e9eccb8..b0c8740140 100644 --- a/lib/output/emoji.go +++ b/lib/output/emoji.go @@ -17,9 +17,9 @@ var allEmojis = [...]string{ // Standard emoji for use in output. const ( - EmojiFailure = "❌" + EmojiFailure = " ⨯" EmojiWarning = "❗️" - EmojiSuccess = "✅" + EmojiSuccess = " ✓" EmojiInfo = "ℹ️" EmojiLightbulb = "💡" EmojiAsterisk = "✱" diff --git a/lib/output/line.go b/lib/output/line.go index ed566d0d8b..2fdc21a28b 100644 --- a/lib/output/line.go +++ b/lib/output/line.go @@ -64,11 +64,12 @@ func (fl FancyLine) write(w io.Writer, caps capabilities) { if fl.Prefix != "" { fmt.Fprint(w, fl.Prefix+" ") } + emojiPrefix := "" if fl.emoji != "" { - fmt.Fprint(w, fl.emoji+" ") + emojiPrefix = fl.emoji + " " } - fmt.Fprintf(w, "%s"+fl.format+"%s", caps.formatArgs(append(append([]any{fl.style}, fl.args...), StyleReset))...) + fmt.Fprintf(w, "%s"+emojiPrefix+fl.format+"%s", caps.formatArgs(append(append([]any{fl.style}, fl.args...), StyleReset))...) if fl.Prompt { // Add whitespace for user input _, _ = w.Write([]byte(" ")) diff --git a/lib/output/output.go b/lib/output/output.go index f1d1305277..93e0f4306a 100644 --- a/lib/output/output.go +++ b/lib/output/output.go @@ -92,7 +92,7 @@ var newOutputPlatformQuirks func(o *Output) error // newCapabilityWatcher returns a channel that receives a message when // capabilities are updated. By default, no watching functionality is // available. -var newCapabilityWatcher = func(opts OutputOpts) chan capabilities { return nil } +var newCapabilityWatcher = func(_ OutputOpts) chan capabilities { return nil } func NewOutput(w io.Writer, opts OutputOpts) *Output { // Not being able to detect capabilities is alright. It might mean output will look @@ -146,6 +146,17 @@ func (o *Output) UnsetVerbose() { o.verbose = false } +func (o *Output) IsVerbose() bool { + o.lock.Lock() + defer o.lock.Unlock() + return o.verbose +} + +// IsTTY reports whether this output is configured to render to a TTY. +func (o *Output) IsTTY() bool { + return o.caps.Isatty +} + func (o *Output) Unlock() { if o.caps.Isatty { // Show the cursor once more. diff --git a/lib/output/output_unix.go b/lib/output/output_unix.go index f55b2003b0..11c2a143d5 100644 --- a/lib/output/output_unix.go +++ b/lib/output/output_unix.go @@ -1,5 +1,4 @@ //go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris -// +build aix darwin dragonfly freebsd linux netbsd openbsd solaris package output diff --git a/lib/output/pending_tty.go b/lib/output/pending_tty.go index 86853edc4a..c16258bce2 100644 --- a/lib/output/pending_tty.go +++ b/lib/output/pending_tty.go @@ -95,7 +95,11 @@ func (p *pendingTTY) Complete(message FancyLine) { p.o.moveUp(1) p.o.clearCurrentLine() - p.write(message) + // Write directly without truncation (unlike p.write, which truncates to + // terminal width to keep spinner animation frames on a single line). + // Completion messages may contain multi-line output such as URLs and must + // be displayed in full. + message.write(p.o.w, p.o.caps) } func (p *pendingTTY) Close() { p.Destroy() } diff --git a/lib/output/progress.go b/lib/output/progress.go index 2b7d9688a4..6490666656 100644 --- a/lib/output/progress.go +++ b/lib/output/progress.go @@ -34,9 +34,11 @@ type ProgressOpts struct { SuccessEmoji string SuccessStyle Style - // NoSpinner turns of the automatic updating of the progress bar and - // spinner in a background goroutine. - // Used for testing only! + // NoSpinner disables the background goroutine that updates progress bars + // and spinners. In TTY mode this stops the spinner animation; in non-TTY + // (simple) mode this suppresses the periodic ticker that dumps progress + // bars, which is useful when output cannot be overwritten in place (e.g. + // CI log files). Completion and failure events still print. NoSpinner bool } diff --git a/lib/output/progress_simple.go b/lib/output/progress_simple.go index dadfc3086c..6b55683f49 100644 --- a/lib/output/progress_simple.go +++ b/lib/output/progress_simple.go @@ -33,6 +33,9 @@ func (p *progressSimple) SetValue(i int, v float64) { } func (p *progressSimple) stop() { + if p.done == nil { + return + } c := make(chan struct{}) p.done <- c <-c @@ -46,9 +49,7 @@ func newProgressSimple(bars []*ProgressBar, o *Output, opts *ProgressOpts) *prog } if opts != nil && opts.NoSpinner { - if p.Output.verbose { - writeBars(p.Output, p.bars) - } + p.done = nil return p } @@ -62,7 +63,6 @@ func newProgressSimple(bars []*ProgressBar, o *Output, opts *ProgressOpts) *prog if p.Output.verbose { writeBars(p.Output, p.bars) } - case c := <-p.done: c <- struct{}{} return diff --git a/lib/output/progress_tty.go b/lib/output/progress_tty.go index f10dc18921..0f7421d1e9 100644 --- a/lib/output/progress_tty.go +++ b/lib/output/progress_tty.go @@ -139,13 +139,11 @@ func newProgressTTY(bars []*ProgressBar, o *Output, opts *ProgressOpts) *progres o: o, emojiWidth: 3, pendingEmoji: spinnerStrings[0], - spinner: newSpinner(100 * time.Millisecond), } + p.opts = *DefaultProgressTTYOpts if opts != nil { - p.opts = *opts - } else { - p.opts = *DefaultProgressTTYOpts + p.opts.NoSpinner = opts.NoSpinner } if w := runewidth.StringWidth(p.opts.SuccessEmoji); w > p.emojiWidth { @@ -163,6 +161,8 @@ func newProgressTTY(bars []*ProgressBar, o *Output, opts *ProgressOpts) *progres return p } + p.spinner = newSpinner(100 * time.Millisecond) + go func() { for s := range p.spinner.C { func() { diff --git a/lib/output/progress_with_status_bars_simple.go b/lib/output/progress_with_status_bars_simple.go index e985c2e952..b06be8dcca 100644 --- a/lib/output/progress_with_status_bars_simple.go +++ b/lib/output/progress_with_status_bars_simple.go @@ -59,10 +59,7 @@ func newProgressWithStatusBarsSimple(bars []*ProgressBar, statusBars []*StatusBa } if opts != nil && opts.NoSpinner { - if p.Output.verbose { - writeBars(p.Output, p.bars) - writeStatusBars(p.Output, p.statusBars) - } + p.done = nil return p } @@ -77,7 +74,6 @@ func newProgressWithStatusBarsSimple(bars []*ProgressBar, statusBars []*StatusBa writeBars(p.Output, p.bars) writeStatusBars(p.Output, p.statusBars) } - case c := <-p.done: c <- struct{}{} return diff --git a/lib/output/progress_with_status_bars_tty.go b/lib/output/progress_with_status_bars_tty.go index 3cfcf5834f..254eeac007 100644 --- a/lib/output/progress_with_status_bars_tty.go +++ b/lib/output/progress_with_status_bars_tty.go @@ -14,15 +14,13 @@ func newProgressWithStatusBarsTTY(bars []*ProgressBar, statusBars []*StatusBar, o: o, emojiWidth: 3, pendingEmoji: spinnerStrings[0], - spinner: newSpinner(100 * time.Millisecond), }, statusBars: statusBars, } + p.opts = *DefaultProgressTTYOpts if opts != nil { - p.opts = *opts - } else { - p.opts = *DefaultProgressTTYOpts + p.opts.NoSpinner = opts.NoSpinner } if w := runewidth.StringWidth(p.opts.SuccessEmoji); w > p.emojiWidth { @@ -41,6 +39,8 @@ func newProgressWithStatusBarsTTY(bars []*ProgressBar, statusBars []*StatusBar, return p } + p.spinner = newSpinner(100 * time.Millisecond) + go func() { for s := range p.spinner.C { func() { @@ -220,7 +220,6 @@ func calcStatusBarLabelWidth(statusBars []*StatusBar, termWidth int) int { } return statusBarLabelWidth - } func (p *progressWithStatusBarsTTY) writeStatusBar(last bool, statusBar *StatusBar) { diff --git a/lib/output/spinner.go b/lib/output/spinner.go index b0b5b86de2..23220224df 100644 --- a/lib/output/spinner.go +++ b/lib/output/spinner.go @@ -41,6 +41,9 @@ func newSpinner(interval time.Duration) *spinner { } func (s *spinner) stop() { + if s == nil { + return + } c := make(chan struct{}) s.done <- c <-c diff --git a/lib/output/table.go b/lib/output/table.go index 6736b30756..8388ed5ee6 100644 --- a/lib/output/table.go +++ b/lib/output/table.go @@ -6,9 +6,7 @@ import ( ) const ( - purple = lipgloss.Color("99") - gray = lipgloss.Color("245") - lightGray = lipgloss.Color("241") + purple = lipgloss.Color("99") ) type Table struct { @@ -43,10 +41,6 @@ func (t *Table) AddRow(elems ...string) { t.tbl.Row(elems...) } -func (t *Table) AddRows(elems ...[]string) { - t.tbl.Rows(elems...) -} - func (t *Table) Render() string { return t.tbl.Render() } diff --git a/lib/process/pipe.go b/lib/process/pipe.go index b7a6f9a40a..b06364cc44 100644 --- a/lib/process/pipe.go +++ b/lib/process/pipe.go @@ -15,9 +15,11 @@ import ( // initialBufSize is the initial size of the buffer that PipeOutput uses to // read lines. -const initialBufSize = 4 * 1024 // 4k -// maxTokenSize is the max size of a token that PipeOutput reads. -const maxTokenSize = 100 * 1024 * 1024 // 100mb +const ( + initialBufSize = 4 * 1024 // 4k + // maxTokenSize is the max size of a token that PipeOutput reads. + maxTokenSize = 100 * 1024 * 1024 // 100mb +) type pipe func(w io.Writer, r io.Reader) error From c538ad1f037221c2323bf0f982c785eb2bf12787 Mon Sep 17 00:00:00 2001 From: Michael Bahr <1830132+bahrmichael@users.noreply.github.com> Date: Mon, 1 Jun 2026 13:37:21 +0200 Subject: [PATCH 597/647] chore: update batch spec stringdata (#1329) --- dev/vendor-lib.sh | 8 + lib/batches/schema/batch_spec_stringdata.go | 477 +++++++++++++++----- 2 files changed, 362 insertions(+), 123 deletions(-) diff --git a/dev/vendor-lib.sh b/dev/vendor-lib.sh index e4267183cb..a849b42ae3 100755 --- a/dev/vendor-lib.sh +++ b/dev/vendor-lib.sh @@ -122,6 +122,14 @@ for pkg in $ALL_PACKAGES; do done done +# Keep the generated batch spec schema in sync with the source repository. +# This file can be missed by package discovery, but src-cli validates batch +# specs against it at runtime. +echo "" +echo "Copying generated batch spec schema..." +mkdir -p "$DEST_LIB/batches/schema" +cp "$SRC_LIB/batches/schema/batch_spec_stringdata.go" "$DEST_LIB/batches/schema/" + # Create go.mod file echo "" echo "Creating go.mod file..." diff --git a/lib/batches/schema/batch_spec_stringdata.go b/lib/batches/schema/batch_spec_stringdata.go index 1123970faf..8215beae93 100644 --- a/lib/batches/schema/batch_spec_stringdata.go +++ b/lib/batches/schema/batch_spec_stringdata.go @@ -11,6 +11,341 @@ const BatchSpecJSON = `{ "type": "object", "additionalProperties": false, "required": ["name"], + "allOf": [ + { + "if": { "properties": { "version": { "const": 3 } }, "required": ["version"] }, + "then": { + "properties": { + "steps": { + "items": { + "anyOf": [ + { "required": ["run", "image"] }, + { "required": ["buildImage"] }, + { "required": ["codingAgent"] } + ] + } + } + } + }, + "else": { + "properties": { + "steps": { + "items": { + "required": ["run", "container"], + "allOf": [{ "not": { "required": ["codingAgent"] } }, { "not": { "required": ["buildImage"] } }] + } + } + } + } + }, + { + "$comment": "The ` + "`" + `changesetHooks` + "`" + ` property is only allowed when ` + "`" + `version: 3` + "`" + ` is set.", + "if": { + "required": ["changesetHooks"] + }, + "then": { + "required": ["version"], + "properties": { + "version": { + "const": 3 + } + } + } + } + ], + "definitions": { + "OutputVariable": { + "title": "OutputVariable", + "type": "object", + "required": ["value"], + "properties": { + "value": { + "type": "string", + "description": "The value of the output, which can be a template string.", + "examples": ["hello world", "${{ step.stdout }}", "${{ repository.name }}"] + }, + "format": { + "type": "string", + "description": "The expected format of the output. If set, the output is being parsed in that format before being stored in the var. If not set, 'text' is assumed to the format.", + "enum": ["json", "yaml", "text"] + } + } + }, + "Mount": { + "title": "Mount", + "type": "object", + "additionalProperties": false, + "required": ["path", "mountpoint"], + "properties": { + "path": { + "type": "string", + "description": "The path on the local machine to mount. The path must be in the same directory or a subdirectory of the batch spec.", + "examples": ["local/path/to/file.text", "local/path/to/directory"] + }, + "mountpoint": { + "type": "string", + "description": "The path in the container to mount the path on the local machine to.", + "examples": ["path/to/file.txt", "path/to/directory"] + } + } + }, + "CodingAgent": { + "title": "CodingAgent", + "type": "object", + "description": "An out-of-the-box coding agent step that runs the given prompt inside a managed container. Mutually exclusive with run. Only supported in version 3 batch specs. Use the step's top-level container/image field to override the default agent image.", + "additionalProperties": false, + "required": ["type", "prompt"], + "properties": { + "type": { + "type": "string", + "description": "The coding agent to use.", + "enum": ["codex", "claude-code"] + }, + "prompt": { + "type": "string", + "description": "The prompt to send to the agent." + } + } + }, + "BuildImage": { + "type": "object", + "description": "A step that creates a local image by running a shell command in a base image using buildah. Later steps can use the generated image via ${{ outputs.imageName }}. The generated image name is deterministic for the exact baseImage and run values.", + "additionalProperties": false, + "required": ["run", "baseImage"], + "properties": { + "run": { + "type": "string", + "description": "The shell command to run in the base image before committing the result as a new image." + }, + "baseImage": { + "type": "string", + "description": "The base image to modify.", + "examples": ["alpine:3"] + } + } + }, + "Step": { + "title": "Step", + "type": "object", + "description": "A command to run (as part of a sequence) in a repository branch to produce the required changes.", + "additionalProperties": false, + "properties": { + "run": { + "type": "string", + "description": "The shell command to run in the container. It can also be a multi-line shell script. The working directory is the root directory of the repository checkout." + }, + "container": { + "type": "string", + "description": "The Docker image used to launch the Docker container in which the shell command is run.", + "examples": ["alpine:3"] + }, + "image": { + "type": "string", + "description": "The Docker image used to launch the Docker container in which the shell command is run.", + "examples": ["alpine:3"] + }, + "codingAgent": { + "$ref": "#/definitions/CodingAgent" + }, + "buildImage": { + "$ref": "#/definitions/BuildImage" + }, + "outputs": { + "type": ["object", "null"], + "description": "Output variables of this step that can be referenced in the changesetTemplate or other steps via outputs.", + "additionalProperties": { + "$ref": "#/definitions/OutputVariable" + } + }, + "env": { + "description": "Environment variables to set in the step environment.", + "oneOf": [ + { + "type": "null" + }, + { + "type": "object", + "description": "Environment variables to set in the step environment.", + "additionalProperties": { + "type": "string" + } + }, + { + "type": "array", + "items": { + "oneOf": [ + { + "type": "string", + "description": "An environment variable to set in the step environment: the value will be passed through from the environment src is running within." + }, + { + "type": "object", + "description": "An environment variable to set in the step environment: the key is used as the environment variable name and the value as the value.", + "additionalProperties": { + "type": "string" + }, + "minProperties": 1, + "maxProperties": 1 + } + ] + } + } + ] + }, + "files": { + "type": ["object", "null"], + "description": "Files that should be mounted into or be created inside the Docker container.", + "additionalProperties": { + "type": "string" + } + }, + "if": { + "oneOf": [ + { + "type": "boolean" + }, + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "A condition to check before executing steps. Supports templating. The value 'true' is interpreted as true.", + "examples": [ + "true", + "${{ matches repository.name \"github.com/my-org/my-repo*\" }}", + "${{ outputs.goModFileExists }}", + "${{ eq previous_step.stdout \"success\" }}" + ] + }, + "mount": { + "description": "Files that are mounted to the Docker container.", + "type": ["array", "null"], + "items": { + "$ref": "#/definitions/Mount" + } + } + } + }, + "HookStep": { + "title": "HookStep", + "type": "object", + "description": "A command to run (as part of a sequence) inside a changeset hook action. Uses the version 3 step shape and supports additional hook-only fields such as maxAttempts.", + "additionalProperties": false, + "properties": { + "run": { + "type": "string", + "description": "The shell command to run in the container. It can also be a multi-line shell script. The working directory is the root directory of the repository checkout." + }, + "image": { + "type": "string", + "description": "The Docker image used to launch the Docker container in which the shell command is run.", + "examples": ["alpine:3"] + }, + "codingAgent": { + "$ref": "#/definitions/CodingAgent" + }, + "outputs": { + "type": ["object", "null"], + "description": "Output variables of this step that can be referenced in the changesetTemplate or other steps via outputs.", + "additionalProperties": { + "$ref": "#/definitions/OutputVariable" + } + }, + "env": { + "description": "Environment variables to set in the step environment.", + "oneOf": [ + { + "type": "null" + }, + { + "type": "object", + "description": "Environment variables to set in the step environment.", + "additionalProperties": { + "type": "string" + } + }, + { + "type": "array", + "items": { + "oneOf": [ + { + "type": "string", + "description": "An environment variable to set in the step environment: the value will be passed through from the environment src is running within." + }, + { + "type": "object", + "description": "An environment variable to set in the step environment: the key is used as the environment variable name and the value as the value.", + "additionalProperties": { + "type": "string" + }, + "minProperties": 1, + "maxProperties": 1 + } + ] + } + } + ] + }, + "files": { + "type": ["object", "null"], + "description": "Files that should be mounted into or be created inside the Docker container.", + "additionalProperties": { + "type": "string" + } + }, + "if": { + "oneOf": [ + { + "type": "boolean" + }, + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "A condition to check before executing steps. Supports templating. The value 'true' is interpreted as true.", + "examples": [ + "true", + "${{ matches repository.name \"github.com/my-org/my-repo*\" }}", + "${{ outputs.goModFileExists }}", + "${{ eq previous_step.stdout \"success\" }}" + ] + }, + "mount": { + "description": "Files that are mounted to the Docker container.", + "type": ["array", "null"], + "items": { + "$ref": "#/definitions/Mount" + } + }, + "maxAttempts": { + "type": "integer", + "description": "The maximum number of times this step will be attempted before the hook action is considered failed. Defaults to 1 (no retries).", + "minimum": 1 + } + } + }, + "ChangesetHookAction": { + "title": "ChangesetHookAction", + "type": "object", + "description": "A side-effect action to run at a changeset lifecycle event. Hook actions run in an executor.", + "additionalProperties": false, + "required": ["steps"], + "properties": { + "steps": { + "type": "array", + "description": "The sequence of steps to execute when the hook fires. Uses the version 3 step shape, with additional hook-only fields.", + "items": { + "$ref": "#/definitions/HookStep" + } + } + } + } + }, "properties": { "version": { "type": "number", @@ -28,20 +363,20 @@ const BatchSpecJSON = `{ }, "on": { "type": ["array", "null"], - "description": "The set of repositories (and branches) to run the batch change on, specified as a list of search queries (that match repositories) and/or specific repositories.", + "description": "The set of repositories to run the batch change on, specified as a list of search queries (that match repositories) and/or specific repositories. Repositories matched by repositoriesMatchingQuery use each repository's default branch unless overridden by an explicit repository entry with branch or branches.", "items": { "title": "OnQueryOrRepository", "oneOf": [ { "title": "OnQuery", "type": "object", - "description": "A Sourcegraph search query that matches a set of repositories (and branches). Each matched repository branch is added to the list of repositories that the batch change will be run on.", + "description": "A Sourcegraph search query that matches a set of repositories. Each matched repository is added to the list of repositories that the batch change will be run on using the repository's default branch.", "additionalProperties": false, "required": ["repositoriesMatchingQuery"], "properties": { "repositoriesMatchingQuery": { "type": "string", - "description": "A Sourcegraph search query that matches a set of repositories (and branches). If the query matches files, symbols, or some other object inside a repository, the object's repository is included.", + "description": "A Sourcegraph search query that matches a set of repositories. If the query matches files, symbols, or some other object inside a repository, the object's repository is included. Matched repositories are run on their default branch; use explicit repository entries with branch or branches to target non-default branches.", "examples": ["file:README.md"] } } @@ -124,126 +459,7 @@ const BatchSpecJSON = `{ "type": ["array", "null"], "description": "The sequence of commands to run (for each repository branch matched in the ` + "`" + `on` + "`" + ` property) to produce the workspace changes that will be included in the batch change.", "items": { - "title": "Step", - "type": "object", - "description": "A command to run (as part of a sequence) in a repository branch to produce the required changes.", - "additionalProperties": false, - "required": ["run", "container"], - "properties": { - "run": { - "type": "string", - "description": "The shell command to run in the container. It can also be a multi-line shell script. The working directory is the root directory of the repository checkout." - }, - "container": { - "type": "string", - "description": "The Docker image used to launch the Docker container in which the shell command is run.", - "examples": ["alpine:3"] - }, - "outputs": { - "type": ["object", "null"], - "description": "Output variables of this step that can be referenced in the changesetTemplate or other steps via outputs.", - "additionalProperties": { - "title": "OutputVariable", - "type": "object", - "required": ["value"], - "properties": { - "value": { - "type": "string", - "description": "The value of the output, which can be a template string.", - "examples": ["hello world", "${{ step.stdout }}", "${{ repository.name }}"] - }, - "format": { - "type": "string", - "description": "The expected format of the output. If set, the output is being parsed in that format before being stored in the var. If not set, 'text' is assumed to the format.", - "enum": ["json", "yaml", "text"] - } - } - } - }, - "env": { - "description": "Environment variables to set in the step environment.", - "oneOf": [ - { - "type": "null" - }, - { - "type": "object", - "description": "Environment variables to set in the step environment.", - "additionalProperties": { - "type": "string" - } - }, - { - "type": "array", - "items": { - "oneOf": [ - { - "type": "string", - "description": "An environment variable to set in the step environment: the value will be passed through from the environment src is running within." - }, - { - "type": "object", - "description": "An environment variable to set in the step environment: the key is used as the environment variable name and the value as the value.", - "additionalProperties": { - "type": "string" - }, - "minProperties": 1, - "maxProperties": 1 - } - ] - } - } - ] - }, - "files": { - "type": ["object", "null"], - "description": "Files that should be mounted into or be created inside the Docker container.", - "additionalProperties": { - "type": "string" - } - }, - "if": { - "oneOf": [ - { - "type": "boolean" - }, - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "A condition to check before executing steps. Supports templating. The value 'true' is interpreted as true.", - "examples": [ - "true", - "${{ matches repository.name \"github.com/my-org/my-repo*\" }}", - "${{ outputs.goModFileExists }}", - "${{ eq previous_step.stdout \"success\" }}" - ] - }, - "mount": { - "description": "Files that are mounted to the Docker container.", - "type": ["array", "null"], - "items": { - "type": "object", - "additionalProperties": false, - "required": ["path", "mountpoint"], - "properties": { - "path": { - "type": "string", - "description": "The path on the local machine to mount. The path must be in the same directory or a subdirectory of the batch spec.", - "examples": ["local/path/to/file.text", "local/path/to/directory"] - }, - "mountpoint": { - "type": "string", - "description": "The path in the container to mount the path on the local machine to.", - "examples": ["path/to/file.txt", "path/to/directory"] - } - } - } - } - } + "$ref": "#/definitions/Step" } }, "transformChanges": { @@ -406,6 +622,21 @@ const BatchSpecJSON = `{ ] } } + }, + "changesetHooks": { + "type": "object", + "description": "Side-effect actions to run at well-defined changeset lifecycle events. Only allowed when ` + "`" + `version: 3` + "`" + ` is set.", + "additionalProperties": false, + "properties": { + "onCIFailure": { + "description": "Action to run when the changeset's combined check state transitions into ` + "`" + `failed` + "`" + ` for a given head SHA.", + "$ref": "#/definitions/ChangesetHookAction" + }, + "onMergeConflict": { + "description": "Action to run when the changeset's external mergeability transitions into ` + "`" + `conflicting` + "`" + ` for a given (base, head) SHA pair.", + "$ref": "#/definitions/ChangesetHookAction" + } + } } } } From 9120eead9d31297064334a58510cd064397a64cf Mon Sep 17 00:00:00 2001 From: Keegan Carruthers-Smith Date: Mon, 1 Jun 2026 15:04:38 +0200 Subject: [PATCH 598/647] restore lib/go.mod (#1330) The vendor-lib script needs updating to rather preserve it. But for now unblock the breakage we will get by not using our version of the yaml lib. --- lib/go.mod | 85 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ lib/go.sum | 15 ---------- 2 files changed, 85 insertions(+), 15 deletions(-) diff --git a/lib/go.mod b/lib/go.mod index e57ef54d53..99a466ba2d 100644 --- a/lib/go.mod +++ b/lib/go.mod @@ -1,3 +1,88 @@ module github.com/sourcegraph/sourcegraph/lib go 1.26.3 + +require ( + github.com/Masterminds/semver v1.5.0 + github.com/charmbracelet/glamour v0.10.0 + github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834 + github.com/cockroachdb/errors v1.12.0 + github.com/cockroachdb/redact v1.1.6 + github.com/ghodss/yaml v1.0.0 + github.com/gobwas/glob v0.2.3 + github.com/google/go-cmp v0.7.0 + github.com/grafana/regexp v0.0.0-20250905093917-f7b3be9d1853 + github.com/jackc/pgx/v5 v5.9.2 + github.com/klauspost/pgzip v1.2.6 + github.com/mattn/go-isatty v0.0.20 + github.com/mattn/go-runewidth v0.0.19 + github.com/moby/term v0.5.2 + github.com/muesli/termenv v0.16.0 + github.com/scip-code/scip/bindings/go/scip v0.7.0 + github.com/sourcegraph/conc v0.3.0 + github.com/sourcegraph/go-diff v0.7.0 + github.com/sourcegraph/log v0.0.0-20250923023806-517b6960b55b + github.com/stretchr/testify v1.11.1 + github.com/urfave/cli/v3 v3.8.0 + github.com/xeipuuv/gojsonschema v1.2.0 + github.com/xlab/treeprint v1.2.0 + go.opentelemetry.io/otel v1.43.0 + golang.org/x/sys v0.41.0 + golang.org/x/term v0.37.0 + google.golang.org/protobuf v1.36.10 + gopkg.in/yaml.v3 v3.0.1 +) + +require ( + github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c // indirect + github.com/alecthomas/chroma/v2 v2.14.0 // indirect + github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect + github.com/aymerick/douceur v0.2.0 // indirect + github.com/benbjohnson/clock v1.3.5 // indirect + github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect + github.com/charmbracelet/x/ansi v0.8.0 // indirect + github.com/charmbracelet/x/cellbuf v0.0.13 // indirect + github.com/charmbracelet/x/exp/slice v0.0.0-20250327172914-2fdc97757edf // indirect + github.com/charmbracelet/x/term v0.2.1 // indirect + github.com/clipperhouse/uax29/v2 v2.2.0 // indirect + github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/dlclark/regexp2 v1.11.0 // indirect + github.com/fatih/color v1.18.0 // indirect + github.com/getsentry/sentry-go v0.27.0 // indirect + github.com/gogo/protobuf v1.3.2 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/gorilla/css v1.0.1 // indirect + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect + github.com/klauspost/compress v1.18.0 // indirect + github.com/kr/pretty v0.3.1 // indirect + github.com/kr/text v0.2.0 // indirect + github.com/lucasb-eyer/go-colorful v1.2.0 // indirect + github.com/mattn/go-colorable v0.1.14 // indirect + github.com/microcosm-cc/bluemonday v1.0.27 // indirect + github.com/muesli/reflow v0.3.0 // indirect + github.com/pkg/errors v0.9.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/rivo/uniseg v0.4.7 // indirect + github.com/rogpeppe/go-internal v1.14.1 // indirect + github.com/sourcegraph/beaut v0.0.0-20240611013027-627e4c25335a // indirect + github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f // indirect + github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect + github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect + github.com/yuin/goldmark v1.7.8 // indirect + github.com/yuin/goldmark-emoji v1.0.5 // indirect + go.uber.org/atomic v1.11.0 // indirect + go.uber.org/goleak v1.3.0 // indirect + go.uber.org/multierr v1.11.0 // indirect + go.uber.org/zap v1.24.0 // indirect + golang.org/x/exp v0.0.0-20230713183714-613f0c0eb8a1 // indirect + golang.org/x/net v0.44.0 // indirect + golang.org/x/text v0.29.0 // indirect + golang.org/x/tools v0.37.0 // indirect + gopkg.in/yaml.v2 v2.4.0 // indirect +) + +// See: https://github.com/ghodss/yaml/pull/65 +replace github.com/ghodss/yaml => github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 diff --git a/lib/go.sum b/lib/go.sum index 434c58adc8..7a5acf0f7e 100644 --- a/lib/go.sum +++ b/lib/go.sum @@ -56,11 +56,6 @@ github.com/getsentry/sentry-go v0.27.0 h1:Pv98CIbtB3LkMWmXi4Joa5OOcwbmnX88sF5qbK github.com/getsentry/sentry-go v0.27.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA= github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og= -github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= -github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= -github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= -github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y= github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8= github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= @@ -87,8 +82,6 @@ github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsI github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= -github.com/jackc/pgx/v5 v5.9.1 h1:uwrxJXBnx76nyISkhr33kQLlUqjv7et7b9FjCen/tdc= -github.com/jackc/pgx/v5 v5.9.1/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= github.com/jackc/pgx/v5 v5.9.2 h1:3ZhOzMWnR4yJ+RW1XImIPsD1aNSz4T4fyP7zlQb56hw= github.com/jackc/pgx/v5 v5.9.2/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= @@ -174,16 +167,8 @@ github.com/yuin/goldmark v1.7.8 h1:iERMLn0/QJeHFhxSt3p6PeN9mGnvIKSpG9YYorDMnic= github.com/yuin/goldmark v1.7.8/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E= github.com/yuin/goldmark-emoji v1.0.5 h1:EMVWyCGPlXJfUXBXpuMu+ii3TIaxbVBnEX9uaDC4cIk= github.com/yuin/goldmark-emoji v1.0.5/go.mod h1:tTkZEbwu5wkPmgTcitqddVxY9osFZiavD+r4AzQrh1U= -go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= -go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= -go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8= -go.opentelemetry.io/otel v1.38.0/go.mod h1:zcmtmQ1+YmQM9wrNsTGV/q/uyusom3P8RxwExxkZhjM= go.opentelemetry.io/otel v1.43.0 h1:mYIM03dnh5zfN7HautFE4ieIig9amkNANT+xcVxAj9I= go.opentelemetry.io/otel v1.43.0/go.mod h1:JuG+u74mvjvcm8vj8pI5XiHy1zDeoCS2LB1spIq7Ay0= -go.opentelemetry.io/otel/metric v1.43.0 h1:d7638QeInOnuwOONPp4JAOGfbCEpYb+K6DVWvdxGzgM= -go.opentelemetry.io/otel/metric v1.43.0/go.mod h1:RDnPtIxvqlgO8GRW18W6Z/4P462ldprJtfxHxyKd2PY= -go.opentelemetry.io/otel/trace v1.43.0 h1:BkNrHpup+4k4w+ZZ86CZoHHEkohws8AY+WTX09nk+3A= -go.opentelemetry.io/otel/trace v1.43.0/go.mod h1:/QJhyVBUUswCphDVxq+8mld+AvhXZLhe+8WVFxiFff0= go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= From 4bcd4ce9f7063031b7879bad77d0b0fe0124409a Mon Sep 17 00:00:00 2001 From: Michael Bahr <1830132+bahrmichael@users.noreply.github.com> Date: Mon, 1 Jun 2026 17:24:12 +0200 Subject: [PATCH 599/647] feat: support container variables (#1327) * feat: support container variables * chore: update vendored Sourcegraph lib Vendor github.com/sourcegraph/sourcegraph/lib at bdc2f4bb8b59f78f4fa8868b2690b673b41948d4 and restore src-cli compatibility for APIs still used locally. Test Plan: go test ./... Amp-Thread-ID: https://ampcode.com/threads/T-019e8206-7c7d-76cb-9b08-b6e0df454e15 Co-authored-by: Amp * revert cache change * revert cache test deletion * Revert "revert cache test deletion" This reverts commit 07042c4796afd838867296978bf5cc05fef54cac. * Revert "revert cache change" This reverts commit dae54d432e40078e4d35c6e88b78a4a34ad63011. * Revert "chore: update vendored Sourcegraph lib" This reverts commit cca7abe9a63b42c4beb3bc933d6189a0254f8347. * clean up --------- Co-authored-by: Amp --- internal/batches/executor/run_steps.go | 29 +++++++++++++++++++- internal/batches/executor/run_steps_test.go | 30 +++++++++++++++++++++ internal/batches/service/service.go | 13 +++++++-- internal/batches/service/service_test.go | 5 ++-- lib/batches/template/partial_eval.go | 20 ++++++++++++++ 5 files changed, 92 insertions(+), 5 deletions(-) create mode 100644 internal/batches/executor/run_steps_test.go diff --git a/internal/batches/executor/run_steps.go b/internal/batches/executor/run_steps.go index 47b5715887..67ccbfcb0b 100644 --- a/internal/batches/executor/run_steps.go +++ b/internal/batches/executor/run_steps.go @@ -165,10 +165,16 @@ func RunSteps(ctx context.Context, opts *RunStepsOpts) (stepResults []execution. continue } + resolvedContainer, err := renderStepContainer(step.Container, &stepContext) + if err != nil { + return nil, errors.Wrapf(err, "failed to resolve image for step %d", i+1) + } + step.Container = resolvedContainer + // We need to grab the digest for the exact image we're using. img, err := opts.EnsureImage(ctx, step.Container) if err != nil { - return nil, err + return nil, errors.Wrapf(err, "failed to pull image for step %d: %s", i+1, step.Container) } digest, err := img.Digest(ctx) if err != nil { @@ -241,6 +247,27 @@ func RunSteps(ctx context.Context, opts *RunStepsOpts) (stepResults []execution. return stepResults, err } +func renderStepContainer(container string, stepContext *template.StepContext) (string, error) { + if container == "" { + return "", nil + } + + var out bytes.Buffer + if err := template.RenderStepTemplate("step-container", container, &out, stepContext); err != nil { + return "", err + } + + resolved := out.String() + if strings.TrimSpace(resolved) == "" { + return "", errors.New("empty image") + } + if strings.Contains(resolved, "${{") { + return "", errors.Errorf("unresolved template in image %q", resolved) + } + + return resolved, nil +} + const workDir = "/work" func executeSingleStep( diff --git a/internal/batches/executor/run_steps_test.go b/internal/batches/executor/run_steps_test.go new file mode 100644 index 0000000000..7b8dc6e356 --- /dev/null +++ b/internal/batches/executor/run_steps_test.go @@ -0,0 +1,30 @@ +package executor + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/sourcegraph/sourcegraph/lib/batches/template" +) + +func TestRenderStepContainer(t *testing.T) { + t.Run("static image", func(t *testing.T) { + got, err := renderStepContainer("alpine:3", &template.StepContext{}) + require.NoError(t, err) + require.Equal(t, "alpine:3", got) + }) + + t.Run("output image", func(t *testing.T) { + got, err := renderStepContainer("${{ outputs.imageName }}", &template.StepContext{ + Outputs: map[string]any{"imageName": "alpine:3"}, + }) + require.NoError(t, err) + require.Equal(t, "alpine:3", got) + }) + + t.Run("missing output", func(t *testing.T) { + _, err := renderStepContainer("${{ outputs.imageName }}", &template.StepContext{}) + require.Error(t, err) + }) +} diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index a21de45903..dc44e31bac 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -295,10 +295,19 @@ func (svc *Service) EnsureDockerImages( parallelism int, progress func(done, total int), ) (map[string]docker.Image, error) { - // Figure out the image names used in the batch spec. + // Figure out the concrete image names used in the batch spec. Images that + // still depend on runtime values, such as outputs from earlier steps, are + // resolved and pulled just-in-time by the executor. names := map[string]struct{}{} for i := range steps { - names[steps[i].Container] = struct{}{} + isStatic, name, err := templatelib.IsStaticString(steps[i].Container, &templatelib.StepContext{}) + if err != nil { + return nil, err + } + if !isStatic { + continue + } + names[name] = struct{}{} } total := len(names) diff --git a/internal/batches/service/service_test.go b/internal/batches/service/service_test.go index bdff83acfc..b341ab8aeb 100644 --- a/internal/batches/service/service_test.go +++ b/internal/batches/service/service_test.go @@ -113,8 +113,9 @@ func TestEnsureDockerImages(t *testing.T) { } for name, steps := range map[string][]batcheslib.Step{ - "single step": {{Container: "image"}}, - "multiple steps": {{Container: "image"}, {Container: "image"}}, + "single step": {{Container: "image"}}, + "multiple steps": {{Container: "image"}, {Container: "image"}}, + "dynamic deferred": {{Container: "${{ outputs.imageName }}"}, {Container: "image"}}, } { t.Run(name, func(t *testing.T) { for _, parallelism := range parallelCases { diff --git a/lib/batches/template/partial_eval.go b/lib/batches/template/partial_eval.go index e38c328e90..cdffbc96c6 100644 --- a/lib/batches/template/partial_eval.go +++ b/lib/batches/template/partial_eval.go @@ -42,6 +42,26 @@ func IsStaticBool(input string, ctx *StepContext) (isStatic bool, boolVal bool, return true, isTrueOutput(t.Tree.Root), nil } +// IsStaticString parses the input as a text/template and attempts to evaluate it +// with only the information currently available in StepContext. If any template +// actions remain after partial evaluation, the first return value is false. +func IsStaticString(input string, ctx *StepContext) (isStatic bool, value string, err error) { + t, err := parseAndPartialEval(input, ctx) + if err != nil { + return false, "", err + } + + var out bytes.Buffer + for _, n := range t.Tree.Root.Nodes { + if n.Type() != parse.NodeText { + return false, "", nil + } + out.WriteString(n.String()) + } + + return true, out.String(), nil +} + // parseAndPartialEval parses input as a text/template and then attempts to // partially evaluate the parts of the template it can evaluate ahead of time // (meaning: before we've executed any batch spec steps and have a full From 65e12ede57d1211c3ea22e618c3cf7867a2f3a98 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Tue, 2 Jun 2026 17:29:15 +0200 Subject: [PATCH 600/647] validate keyring oauth creds and re-auth if needed (#1331) --- cmd/src/login_oauth.go | 41 ++++++++++++++--- cmd/src/login_test.go | 93 ++++++++++++++++++++++++++++++++++++++- cmd/src/login_validate.go | 31 +++++++++---- 3 files changed, 150 insertions(+), 15 deletions(-) diff --git a/cmd/src/login_oauth.go b/cmd/src/login_oauth.go index 1e404d6447..a1005a1684 100644 --- a/cmd/src/login_oauth.go +++ b/cmd/src/login_oauth.go @@ -15,16 +15,40 @@ import ( "github.com/sourcegraph/src-cli/internal/oauth" ) -var loadStoredOAuthToken = oauth.LoadToken +var ( + loadStoredOAuthToken = oauth.LoadToken + storeOAuthToken = oauth.StoreToken +) func runOAuthLogin(ctx context.Context, p loginParams) error { - client, err := oauthLoginClient(ctx, p) + client, loadedFromStore, err := oauthLoginClient(ctx, p) if err != nil { printLoginProblem(p.out, fmt.Sprintf("OAuth Device flow authentication failed: %s", err)) fmt.Fprintln(p.out, loginAccessTokenMessage(p.cfg.endpointURL)) return cmderrors.ExitCode1 } + if loadedFromStore { + username, validateErr := currentUsername(ctx, client) + if validateErr == nil && username != "" { + printAuthenticatedUser(p.out, username, p.cfg.endpointURL) + fmt.Fprintln(p.out) + fmt.Fprint(p.out, "✔︎ Authenticated with OAuth credentials") + fmt.Fprintln(p.out) + return nil + } + + fmt.Fprintln(p.out) + fmt.Fprintln(p.out, "⚠️ Warning: Stored OAuth credentials could not be verified. Starting a new OAuth device flow.") + + client, err = newOAuthLoginClient(ctx, p) + if err != nil { + printLoginProblem(p.out, fmt.Sprintf("OAuth Device flow authentication failed: %s", err)) + fmt.Fprintln(p.out, loginAccessTokenMessage(p.cfg.endpointURL)) + return cmderrors.ExitCode1 + } + } + if err := validateCurrentUser(ctx, client, p.out, p.cfg.endpointURL); err != nil { return err } @@ -38,18 +62,23 @@ func runOAuthLogin(ctx context.Context, p loginParams) error { // oauthLoginClient returns a api.Client with the OAuth token set. It will check secret storage for a token // and use it if one is present. // If no token is found, it will start a OAuth Device flow to get a token and storage in secret storage. -func oauthLoginClient(ctx context.Context, p loginParams) (api.Client, error) { - // if we have a stored token, used it. Otherwise run the device flow +func oauthLoginClient(ctx context.Context, p loginParams) (api.Client, bool, error) { + // if we have a stored token, use it. Otherwise run the device flow if token, err := loadStoredOAuthToken(ctx, p.cfg.endpointURL); err == nil { - return newOAuthAPIClient(p, token), nil + return newOAuthAPIClient(p, token), true, nil } + client, err := newOAuthLoginClient(ctx, p) + return client, false, err +} + +func newOAuthLoginClient(ctx context.Context, p loginParams) (api.Client, error) { token, err := runOAuthDeviceFlow(ctx, p.cfg.endpointURL, p.out, p.oauthClient) if err != nil { return nil, err } - if err := oauth.StoreToken(ctx, token); err != nil { + if err := storeOAuthToken(ctx, token); err != nil { fmt.Fprintln(p.out) fmt.Fprintf(p.out, "⚠️ Warning: Failed to store token in keyring store: %q. Continuing with this session only.\n", err) } diff --git a/cmd/src/login_test.go b/cmd/src/login_test.go index 5dba8b464b..ac1e73c609 100644 --- a/cmd/src/login_test.go +++ b/cmd/src/login_test.go @@ -137,11 +137,80 @@ func TestLogin(t *testing.T) { t.Errorf("got output %q, want %q", gotOut, wantOut) } }) + + t.Run("invalid stored oauth token restarts device flow", func(t *testing.T) { + var authHeaders []string + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + authHeaders = append(authHeaders, r.Header.Get("Authorization")) + if r.Header.Get("Authorization") != "Bearer new-oauth-token" { + http.Error(w, "", http.StatusUnauthorized) + return + } + fmt.Fprintln(w, `{"data":{"currentUser":{"username":"alice"}}}`) + })) + defer s.Close() + + restoreStoredOAuthLoader(t, func(_ context.Context, _ *url.URL) (*oauth.Token, error) { + return &oauth.Token{ + Endpoint: s.URL, + ClientID: oauth.DefaultClientID, + AccessToken: "old-oauth-token", + ExpiresAt: time.Now().Add(time.Hour), + }, nil + }) + restoreOAuthTokenStore(t, func(context.Context, *oauth.Token) error { return nil }) + + u, _ := url.ParseRequestURI(s.URL) + startCalled := false + pollCalled := false + var out bytes.Buffer + err := loginCmd(context.Background(), loginParams{ + cfg: &config{endpointURL: u}, + client: (&config{endpointURL: u}).apiClient(nil, io.Discard), + out: &out, + oauthClient: fakeOAuthClient{ + startCalled: &startCalled, + deviceResp: &oauth.DeviceAuthResponse{ + DeviceCode: "device-code", + ExpiresIn: 60, + }, + pollCalled: &pollCalled, + pollResp: &oauth.TokenResponse{ + AccessToken: "new-oauth-token", + ExpiresIn: 3600, + TokenType: "Bearer", + }, + }, + }) + if err != nil { + t.Fatal(err) + } + if !startCalled || !pollCalled { + t.Fatal("expected invalid stored oauth token to restart device flow") + } + if len(authHeaders) != 2 || authHeaders[0] != "Bearer old-oauth-token" || authHeaders[1] != "Bearer new-oauth-token" { + t.Fatalf("Authorization headers = %q, want old token then new token", authHeaders) + } + gotOut := out.String() + for _, want := range []string{ + "⚠️ Warning: Stored OAuth credentials could not be verified. Starting a new OAuth device flow.", + "Waiting for authorization... DONE", + "✔︎ Authenticated as alice on " + s.URL, + "✔︎ Authenticated with OAuth credentials", + } { + if !strings.Contains(gotOut, want) { + t.Errorf("got output %q, want it to contain %q", gotOut, want) + } + } + }) } type fakeOAuthClient struct { startErr error startCalled *bool + deviceResp *oauth.DeviceAuthResponse + pollCalled *bool + pollResp *oauth.TokenResponse } func (f fakeOAuthClient) ClientID() string { @@ -156,10 +225,22 @@ func (f fakeOAuthClient) Start(context.Context, *url.URL, []string) (*oauth.Devi if f.startCalled != nil { *f.startCalled = true } - return nil, f.startErr + if f.startErr != nil { + return nil, f.startErr + } + if f.deviceResp != nil { + return f.deviceResp, nil + } + return nil, fmt.Errorf("unexpected call to Start") } func (f fakeOAuthClient) Poll(context.Context, *url.URL, string, time.Duration, int) (*oauth.TokenResponse, error) { + if f.pollCalled != nil { + *f.pollCalled = true + } + if f.pollResp != nil { + return f.pollResp, nil + } return nil, fmt.Errorf("unexpected call to Poll") } @@ -242,3 +323,13 @@ func restoreStoredOAuthLoader(t *testing.T, loader func(context.Context, *url.UR loadStoredOAuthToken = prev }) } + +func restoreOAuthTokenStore(t *testing.T, store func(context.Context, *oauth.Token) error) { + t.Helper() + + prev := storeOAuthToken + storeOAuthToken = store + t.Cleanup(func() { + storeOAuthToken = prev + }) +} diff --git a/cmd/src/login_validate.go b/cmd/src/login_validate.go index 095ea7ab22..384e0c534a 100644 --- a/cmd/src/login_validate.go +++ b/cmd/src/login_validate.go @@ -16,11 +16,8 @@ func runValidatedLogin(ctx context.Context, p loginParams) error { } func validateCurrentUser(ctx context.Context, client api.Client, out io.Writer, endpointURL *url.URL) error { - query := `query CurrentUser { currentUser { username } }` - var result struct { - CurrentUser *struct{ Username string } - } - if _, err := client.NewRequest(query, nil).Do(ctx, &result); err != nil { + username, err := currentUsername(ctx, client) + if err != nil { if strings.HasPrefix(err.Error(), "error: 401 Unauthorized") || strings.HasPrefix(err.Error(), "error: 403 Forbidden") { printLoginProblem(out, "Invalid access token.") } else { @@ -31,14 +28,32 @@ func validateCurrentUser(ctx context.Context, client api.Client, out io.Writer, return cmderrors.ExitCode1 } - if result.CurrentUser == nil { + if username == "" { // This should never happen; we verified there is an access token, so there should always be // a user. printLoginProblem(out, fmt.Sprintf("Unable to determine user on %s.", endpointURL)) return cmderrors.ExitCode1 } + printAuthenticatedUser(out, username, endpointURL) + return nil +} + +func printAuthenticatedUser(out io.Writer, username string, endpointURL *url.URL) { fmt.Fprintln(out) - fmt.Fprintf(out, "✔︎ Authenticated as %s on %s\n", result.CurrentUser.Username, endpointURL) + fmt.Fprintf(out, "✔︎ Authenticated as %s on %s\n", username, endpointURL) fmt.Fprintln(out) - return nil +} + +func currentUsername(ctx context.Context, client api.Client) (string, error) { + query := `query CurrentUser { currentUser { username } }` + var result struct { + CurrentUser *struct{ Username string } + } + if _, err := client.NewRequest(query, nil).Do(ctx, &result); err != nil { + return "", err + } + if result.CurrentUser == nil { + return "", nil + } + return result.CurrentUser.Username, nil } From c7458639db3c2751b70368facbb1a38aff1ae033 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Wed, 10 Jun 2026 15:35:18 +0200 Subject: [PATCH 601/647] set node version to 24.16.0 in goreleaser action (#1334) --- .github/workflows/goreleaser.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index e7231900b5..614915f0c0 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -247,9 +247,9 @@ jobs: uses: actions/checkout@v4 with: fetch-depth: 0 - - uses: actions/setup-node@v4 + - uses: actions/setup-node@v6 with: - node-version: 16 + node-version: 24.16.0 registry-url: 'https://registry.npmjs.org' - run: echo "VERSION=${GITHUB_REF/refs\/tags\//}" >> $GITHUB_ENV - run: echo "Releasing version ${{ env.version }}" From 65413c2eb780bbad16cd497287a7ab791c88d4c5 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Wed, 10 Jun 2026 15:44:24 +0200 Subject: [PATCH 602/647] update go to 1.26.4 (#1333) --- Dockerfile | 2 +- dev/vendor-lib.sh | 2 +- go.mod | 2 +- lib/go.mod | 2 +- mise.toml | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Dockerfile b/Dockerfile index 7da0c2dd95..79886b234a 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,7 +4,7 @@ # # Nothing fancy here: we copy in the source code and build on the Alpine Go # image. Refer to .dockerignore to get a sense of what we're not going to copy. -FROM golang:1.26.3-alpine3.22@sha256:be93003ee861b3b91b6ebcb22678524947e0cd786c2df3f32af520006b1e54f5 AS builder +FROM golang:1.26.4-alpine3.22@sha256:727cfc3c40be55cd1bc9a4a059406b28a059857e3be752aa9d09531e12c20c56 AS builder COPY . /src WORKDIR /src diff --git a/dev/vendor-lib.sh b/dev/vendor-lib.sh index a849b42ae3..8e22f43238 100755 --- a/dev/vendor-lib.sh +++ b/dev/vendor-lib.sh @@ -136,7 +136,7 @@ echo "Creating go.mod file..." cat > "$DEST_LIB/go.mod" < Date: Thu, 11 Jun 2026 05:13:19 -0700 Subject: [PATCH 603/647] nit: correct doc (#1335) --- DEVELOPMENT.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index 18daf7ba8e..29a600ba71 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -82,10 +82,9 @@ We adhere to the [general Sourcegraph principles for testing](https://docs.sourc 5. Make the necessary updates to the main Sourcegraph repo: 1. Update the `MinimumVersion` constant in the [src-cli package](https://github.com/sourcegraph/sourcegraph/tree/main/internal/src-cli/consts.go). 2. Update the `SRC_CLI_VERSION` in [tool_deps.bzl](https://sourcegraph.sourcegraph.com/github.com/sourcegraph/sourcegraph@f88ee515885e1761f002f8adcc73560bcb2573ee/-/blob/dev/tool_deps.bzl?L6) - 3. Update the sha256 hashes for the three `src-cli-*` targets in [tool_deps.bzl](https://sourcegraph.sourcegraph.com/github.com/sourcegraph/sourcegraph@f88ee515885e1761f002f8adcc73560bcb2573ee/-/blob/dev/tool_deps.bzl?L113-133). The easiest way to do this is to run the following command after updating `SRC_CLI_VERSION`, and extract the correct checksums for each target from the error message: + 3. Update the sha256 hashes for the two `src-cli-*` targets in [tool_deps.bzl](https://sourcegraph.sourcegraph.com/github.com/sourcegraph/sourcegraph/-/blob/dev/tool_deps.bzl). The easiest way to do this is to run the following command after updating `SRC_CLI_VERSION`, and extract the correct checksums for each target from the error message: ```shell $ bazel build @src-cli-linux-amd64//:src-cli-linux-amd64 \ - @src-cli-darwin-amd64//:src-cli-darwin-amd64 \ @src-cli-darwin-arm64//:src-cli-darwin-arm64 ERROR: java.io.IOException: Error downloading [...]_linux-amd64.tar.gz [...] Checksum was From e6945cf8ba7e6ad751848123c985bcc37f9e33e0 Mon Sep 17 00:00:00 2001 From: Carter Brainerd Date: Wed, 8 Jul 2026 13:57:35 -0400 Subject: [PATCH 604/647] fix/security: do not serve arbitrary files over network with serve-git (#1350) --- internal/servegit/serve.go | 9 +++++---- internal/servegit/serve_test.go | 17 +++++++++-------- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/internal/servegit/serve.go b/internal/servegit/serve.go index 33e1a0e105..99c4f84405 100644 --- a/internal/servegit/serve.go +++ b/internal/servegit/serve.go @@ -102,8 +102,6 @@ func (s *Serve) handler() http.Handler { _ = enc.Encode(&resp) }) - safeFS := http.FS(s.RootFS.FS()) - fs := http.FileServer(safeFS) svc := &Handler{ Dir: func(_ context.Context, name string) (string, error) { return filepath.Join(s.Root, filepath.FromSlash(name)), nil @@ -123,14 +121,17 @@ func (s *Serve) handler() http.Handler { RootFS: s.RootFS, } mux.Handle("/repos/", http.StripPrefix("/repos/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - // Use git service if git is trying to clone. Otherwise show http.FileServer for convenience + // Only serve the smart Git HTTP endpoints used for cloning/fetching. + // We deliberately do not fall back to a file server: doing so would + // expose arbitrary files under the served root to unauthenticated + // clients (see VULN-99 / HackerOne #3814799). for _, suffix := range []string{"/info/refs", "/git-upload-pack"} { if strings.HasSuffix(r.URL.Path, suffix) { svc.ServeHTTP(w, r) return } } - fs.ServeHTTP(w, r) + http.NotFound(w, r) }))) return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { diff --git a/internal/servegit/serve_test.go b/internal/servegit/serve_test.go index a23523fcc4..8ae6bc6644 100644 --- a/internal/servegit/serve_test.go +++ b/internal/servegit/serve_test.go @@ -97,14 +97,15 @@ func testReposHandler(t *testing.T, h http.Handler, repos []Repo) { } } - // repos page will list the top-level dirs - list := get("/repos/") - for _, repo := range repos { - if path.Dir(repo.URI) != "/repos" { - continue - } - if !strings.Contains(repo.Name, "/") && !strings.Contains(list, repo.Name) { - t.Errorf("repos page does not contain substring %q", repo.Name) + // Directory browsing under /repos/ is intentionally disabled to avoid + // exposing arbitrary files (VULN-99). Only smart Git HTTP endpoints are + // served; anything else returns 404. + if res, err := http.Get(ts.URL + "/repos/"); err != nil { + t.Fatal(err) + } else { + res.Body.Close() + if res.StatusCode != http.StatusNotFound { + t.Errorf("GET /repos/ status = %d, want %d", res.StatusCode, http.StatusNotFound) } } From b917d53e39fcd0bc2289a2c910532c88ddfdfb78 Mon Sep 17 00:00:00 2001 From: Carter Brainerd Date: Wed, 8 Jul 2026 15:12:03 -0400 Subject: [PATCH 605/647] fix/snapshot: prevent OS command injection via targets file (#1351) --- cmd/src/snapshot_databases.go | 22 ++- cmd/src/snapshot_restore.go | 12 +- internal/pgdump/pgdump.go | 211 +++++++++++++++++++++---- internal/pgdump/pgdump_command_test.go | 110 +++++++++++++ 4 files changed, 310 insertions(+), 45 deletions(-) create mode 100644 internal/pgdump/pgdump_command_test.go diff --git a/cmd/src/snapshot_databases.go b/cmd/src/snapshot_databases.go index c614f3d21e..ae880cca9a 100644 --- a/cmd/src/snapshot_databases.go +++ b/cmd/src/snapshot_databases.go @@ -4,7 +4,6 @@ import ( "flag" "fmt" "os" - "os/exec" "strings" "github.com/sourcegraph/sourcegraph/lib/errors" @@ -14,6 +13,16 @@ import ( "github.com/sourcegraph/src-cli/internal/pgdump" ) +// renderCommands renders a set of commands for display as copy-pasteable, +// safely shell-quoted strings. +func renderCommands(commands []pgdump.Command) []string { + lines := make([]string, len(commands)) + for i, c := range commands { + lines[i] = c.String() + } + return lines +} + func init() { usage := `'src snapshot databases' generates commands to export Sourcegraph database dumps. Note that these commands are intended for use as reference - you may need to adjust the commands for your deployment. @@ -83,19 +92,18 @@ TARGETS FILES if *run { for _, c := range commands { - out.WriteLine(output.Emojif(output.EmojiInfo, "Running command: %q", c)) - command := exec.Command("bash", "-c", c) - output, err := command.CombinedOutput() - out.Write(string(output)) + out.WriteLine(output.Emojif(output.EmojiInfo, "Running command: %q", c.String())) + combined, err := c.Run() + out.Write(string(combined)) if err != nil { - return errors.Wrapf(err, "failed to run command: %q", c) + return errors.Wrapf(err, "failed to run command: %q", c.String()) } } out.WriteLine(output.Emoji(output.EmojiSuccess, "Successfully completed dump commands")) } else { b := out.Block(output.Emoji(output.EmojiSuccess, "Run these commands to generate the required database dumps:")) - b.Write("\n" + strings.Join(commands, "\n")) + b.Write("\n" + strings.Join(renderCommands(commands), "\n")) b.Close() out.WriteLine(output.Styledf(output.StyleSuggestion, "Note that you may need to do some additional setup, such as authentication, beforehand.")) diff --git a/cmd/src/snapshot_restore.go b/cmd/src/snapshot_restore.go index 9ae941e609..7acc979e50 100644 --- a/cmd/src/snapshot_restore.go +++ b/cmd/src/snapshot_restore.go @@ -4,7 +4,6 @@ import ( "flag" "fmt" "os" - "os/exec" "strings" "github.com/sourcegraph/sourcegraph/lib/errors" @@ -81,12 +80,11 @@ TARGETS FILES } if *run { for _, c := range commands { - out.WriteLine(output.Emojif(output.EmojiInfo, "Running command: %q", c)) - command := exec.Command("bash", "-c", c) - output, err := command.CombinedOutput() - out.Write(string(output)) + out.WriteLine(output.Emojif(output.EmojiInfo, "Running command: %q", c.String())) + combined, err := c.Run() + out.Write(string(combined)) if err != nil { - return errors.Wrapf(err, "failed to run command: %q", c) + return errors.Wrapf(err, "failed to run command: %q", c.String()) } } @@ -94,7 +92,7 @@ TARGETS FILES out.WriteLine(output.Styledf(output.StyleSuggestion, "It may be necessary to restart your Sourcegraph instance after restoring")) } else { b := out.Block(output.Emoji(output.EmojiSuccess, "Run these commands to restore the databases:")) - b.Write("\n" + strings.Join(commands, "\n")) + b.Write("\n" + strings.Join(renderCommands(commands), "\n")) b.Close() out.WriteLine(output.Styledf(output.StyleSuggestion, "Note that you may need to do some additional setup, such as authentication, beforehand.")) diff --git a/internal/pgdump/pgdump.go b/internal/pgdump/pgdump.go index 05d916b16b..7a7b81c4a8 100644 --- a/internal/pgdump/pgdump.go +++ b/internal/pgdump/pgdump.go @@ -1,8 +1,11 @@ package pgdump import ( - "fmt" + "bytes" + "os" + "os/exec" "path/filepath" + "strings" "github.com/sourcegraph/sourcegraph/lib/errors" ) @@ -30,24 +33,114 @@ type Target struct { Password string `yaml:"password"` } -// RestoreCommand generates a psql command that can be used for migrations. -func RestoreCommand(t Target) string { - dump := fmt.Sprintf("psql --username=%s --dbname=%s 1>/dev/null", - t.Username, t.DBName) - if t.Password == "" { - return dump +// Command represents a command to run as an argv array rather than a shell +// string. Values that originate from user-controlled targets are always passed +// as discrete arguments (or safely shell-quoted when they must be embedded in a +// nested shell command), never interpolated into a string that is handed to +// "bash -c". This prevents shell injection via malicious targets files. +type Command struct { + // Env holds additional environment variables in "KEY=value" form. + Env []string + // Args is the argv to execute; Args[0] is the executable. + Args []string + // InputFile, if set, is opened and connected to the command's stdin. + InputFile string + // OutputFile, if set, receives the command's stdout. When empty, stdout is + // discarded (matching the original "1>/dev/null" behaviour for restores). + OutputFile string +} + +// Run executes the command safely (without a shell), wiring up any input/output +// file redirection, and returns the combined stderr (and stdout when it is not +// redirected to a file) output. +func (c Command) Run() ([]byte, error) { + if len(c.Args) == 0 { + return nil, errors.New("no command to run") + } + + cmd := exec.Command(c.Args[0], c.Args[1:]...) + cmd.Env = append(os.Environ(), c.Env...) + + var combined bytes.Buffer + cmd.Stderr = &combined + + if c.InputFile != "" { + f, err := os.Open(c.InputFile) + if err != nil { + return nil, errors.Wrapf(err, "opening input file %q", c.InputFile) + } + defer f.Close() + cmd.Stdin = f + } + + if c.OutputFile != "" { + f, err := os.Create(c.OutputFile) + if err != nil { + return nil, errors.Wrapf(err, "creating output file %q", c.OutputFile) + } + defer f.Close() + cmd.Stdout = f + } else { + // No output file means stdout is not of interest (e.g. restores), so + // capture it alongside stderr for diagnostics. + cmd.Stdout = &combined + } + + err := cmd.Run() + return combined.Bytes(), err +} + +// String renders the command as a copy-pasteable, safely shell-quoted string. +// It is intended for display only; execution always goes through Run. +func (c Command) String() string { + var parts []string + for _, e := range c.Env { + parts = append(parts, shellQuoteEnv(e)) + } + for _, a := range c.Args { + parts = append(parts, shellQuote(a)) + } + s := strings.Join(parts, " ") + if c.OutputFile != "" { + s += " > " + shellQuote(c.OutputFile) } - return fmt.Sprintf("PGPASSWORD=%s %s", t.Password, dump) + if c.InputFile != "" { + s += " < " + shellQuote(c.InputFile) + } + return s } -// DumpCommand generates a pg_dump command that can be used for on-prem-to-Cloud migrations. -func DumpCommand(t Target) string { - dump := fmt.Sprintf("pg_dump --clean --format=plain --if-exists --no-acl --no-owner --quote-all-identifiers --username=%s --dbname=%s", - t.Username, t.DBName) - if t.Password == "" { - return dump +// RestoreCommand generates a psql invocation that can be used for migrations. +func RestoreCommand(t Target) (args []string, env []string) { + args = []string{ + "psql", + "--username=" + t.Username, + "--dbname=" + t.DBName, + } + if t.Password != "" { + env = append(env, "PGPASSWORD="+t.Password) } - return fmt.Sprintf("PGPASSWORD=%s %s", t.Password, dump) + return args, env +} + +// DumpCommand generates a pg_dump invocation that can be used for +// on-prem-to-Cloud migrations. +func DumpCommand(t Target) (args []string, env []string) { + args = []string{ + "pg_dump", + "--clean", + "--format=plain", + "--if-exists", + "--no-acl", + "--no-owner", + "--quote-all-identifiers", + "--username=" + t.Username, + "--dbname=" + t.DBName, + } + if t.Password != "" { + env = append(env, "PGPASSWORD="+t.Password) + } + return args, env } type Output struct { @@ -70,30 +163,37 @@ func Outputs(dir string, targets Targets) []Output { }} } -type CommandBuilder func(Target) (string, error) -type PGCommand func(Target) string +type CommandBuilder func(Target) (Command, error) + +// PGCommand generates the argv and environment for a base Postgres command +// (pg_dump or psql) targeting the given Target. +type PGCommand func(Target) (args []string, env []string) // Builder generates the CommandBuilder and targetKey for a given builder and PGCommand func Builder(builder string, command PGCommand) (commandBuilder CommandBuilder, targetKey string) { switch builder { case "pg_dump", "": targetKey = "local" - commandBuilder = func(t Target) (string, error) { - cmd := command(t) + commandBuilder = func(t Target) (Command, error) { + args, env := command(t) if t.Target != "" { - return fmt.Sprintf("%s --host=%s", cmd, t.Target), nil + args = append(args, "--host="+t.Target) } - return cmd, nil + return Command{Env: env, Args: args}, nil } case "docker": targetKey = "docker" - commandBuilder = func(t Target) (string, error) { - return fmt.Sprintf("docker exec -i %s sh -c '%s'", t.Target, command(t)), nil + commandBuilder = func(t Target) (Command, error) { + args, env := command(t) + inner := shellCommand(env, args) + return Command{Args: []string{"docker", "exec", "-i", t.Target, "sh", "-c", inner}}, nil } case "kubectl": targetKey = "k8s" - commandBuilder = func(t Target) (string, error) { - return fmt.Sprintf("kubectl exec -i %s -- bash -c '%s'", t.Target, command(t)), nil + commandBuilder = func(t Target) (Command, error) { + args, env := command(t) + inner := shellCommand(env, args) + return Command{Args: []string{"kubectl", "exec", "-i", t.Target, "--", "bash", "-c", inner}}, nil } default: return commandBuilder, targetKey @@ -103,8 +203,8 @@ func Builder(builder string, command PGCommand) (commandBuilder CommandBuilder, // BuildCommands generates commands that output Postgres dumps and sends them to predefined // files for each target database. -func BuildCommands(outDir string, commandBuilder CommandBuilder, targets Targets, dump bool) ([]string, error) { - var commands []string +func BuildCommands(outDir string, commandBuilder CommandBuilder, targets Targets, dump bool) ([]Command, error) { + var commands []Command for _, t := range Outputs(outDir, targets) { c, err := commandBuilder(t.Target) if err != nil { @@ -112,12 +212,61 @@ func BuildCommands(outDir string, commandBuilder CommandBuilder, targets Targets } if dump { - // When dumping use output redirection to dump command stdout to target file - commands = append(commands, fmt.Sprintf("%s > %s", c, t.Output)) + // When dumping, redirect command stdout to the target file. + c.OutputFile = t.Output } else { - // When restoring use input redirection to pass target file to command stdin - commands = append(commands, fmt.Sprintf("%s < %s", c, t.Output)) + // When restoring, feed the target file to the command's stdin. + c.InputFile = t.Output } + commands = append(commands, c) } return commands, nil } + +// shellCommand renders env and args as a single, safely shell-quoted string for +// use as the argument to a nested "sh -c"/"bash -c" (e.g. inside a container). +func shellCommand(env, args []string) string { + var parts []string + for _, e := range env { + parts = append(parts, shellQuoteEnv(e)) + } + for _, a := range args { + parts = append(parts, shellQuote(a)) + } + return strings.Join(parts, " ") +} + +// shellQuoteEnv quotes a "KEY=value" assignment, leaving the KEY= prefix +// unquoted (so the shell still treats it as an assignment) and quoting only the +// value. +func shellQuoteEnv(assignment string) string { + i := strings.IndexByte(assignment, '=') + if i < 0 { + return shellQuote(assignment) + } + return assignment[:i+1] + shellQuote(assignment[i+1:]) +} + +// shellQuote returns s quoted such that a POSIX shell will treat it as a single +// literal argument. +func shellQuote(s string) string { + if s == "" { + return "''" + } + safe := true + for _, r := range s { + if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') { + continue + } + switch r { + case '-', '_', '.', '/', ':', '=', '@', '%', '+', ',': + continue + } + safe = false + break + } + if safe { + return s + } + return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" +} diff --git a/internal/pgdump/pgdump_command_test.go b/internal/pgdump/pgdump_command_test.go new file mode 100644 index 0000000000..808a265546 --- /dev/null +++ b/internal/pgdump/pgdump_command_test.go @@ -0,0 +1,110 @@ +package pgdump + +import ( + "path/filepath" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// maliciousTarget is a target whose fields contain shell metacharacters, +// mirroring the injection payloads described in VULN-100. +func maliciousTarget() Target { + return Target{ + Target: "localhost; touch /tmp/pwned #", + DBName: "sg; rm -rf /", + Username: "sg`whoami`", + Password: "sg$(id)", + } +} + +func TestLocalCommandNoInjection(t *testing.T) { + builder, key := Builder("pg_dump", DumpCommand) + require.Equal(t, "local", key) + + cmd, err := builder(maliciousTarget()) + require.NoError(t, err) + + // Every untrusted value must be carried as a discrete argv element, never + // merged into another token where the shell could reinterpret it. + assert.Contains(t, cmd.Args, "--host=localhost; touch /tmp/pwned #") + assert.Contains(t, cmd.Args, "--dbname=sg; rm -rf /") + assert.Contains(t, cmd.Args, "--username=sg`whoami`") + assert.Contains(t, cmd.Env, "PGPASSWORD=sg$(id)") + + // pg_dump is invoked directly, not via a shell. + assert.Equal(t, "pg_dump", cmd.Args[0]) +} + +func TestDockerCommandNoInjection(t *testing.T) { + builder, key := Builder("docker", DumpCommand) + require.Equal(t, "docker", key) + + cmd, err := builder(maliciousTarget()) + require.NoError(t, err) + + // The target is passed as a discrete argv element to docker, so it cannot + // break out into the calling shell. + assert.Equal(t, []string{"docker", "exec", "-i"}, cmd.Args[:3]) + assert.Equal(t, "localhost; touch /tmp/pwned #", cmd.Args[3]) + assert.Equal(t, []string{"sh", "-c"}, cmd.Args[4:6]) + + // The nested "sh -c" command embeds values, but they are shell-quoted so + // they cannot alter control flow inside the container. + inner := cmd.Args[6] + assert.Contains(t, inner, `'--dbname=sg; rm -rf /'`) + assert.Contains(t, inner, "'--username=sg`whoami`'") + assert.Contains(t, inner, `PGPASSWORD='sg$(id)'`) +} + +func TestKubectlCommandNoInjection(t *testing.T) { + builder, key := Builder("kubectl", RestoreCommand) + require.Equal(t, "k8s", key) + + cmd, err := builder(maliciousTarget()) + require.NoError(t, err) + + assert.Equal(t, []string{"kubectl", "exec", "-i"}, cmd.Args[:3]) + assert.Equal(t, "localhost; touch /tmp/pwned #", cmd.Args[3]) + assert.Equal(t, []string{"--", "bash", "-c"}, cmd.Args[4:7]) + + inner := cmd.Args[7] + assert.Contains(t, inner, `'--dbname=sg; rm -rf /'`) +} + +func TestBuildCommandsRedirection(t *testing.T) { + builder, _ := Builder("pg_dump", DumpCommand) + targets := Targets{Pgsql: Target{DBName: "sg", Username: "sg"}} + + wantPath := filepath.Join("out", "pgsql.sql") + + dumps, err := BuildCommands("out", builder, targets, true) + require.NoError(t, err) + require.NotEmpty(t, dumps) + // Dump commands write to the output file; nothing is read from stdin. + assert.Equal(t, wantPath, dumps[0].OutputFile) + assert.Empty(t, dumps[0].InputFile) + + restores, err := BuildCommands("out", builder, targets, false) + require.NoError(t, err) + require.NotEmpty(t, restores) + // Restore commands read from the input file; no shell redirection is used. + assert.Equal(t, wantPath, restores[0].InputFile) + assert.Empty(t, restores[0].OutputFile) +} + +func TestCommandStringQuotesMaliciousValues(t *testing.T) { + builder, _ := Builder("pg_dump", DumpCommand) + cmd, err := builder(maliciousTarget()) + require.NoError(t, err) + cmd.OutputFile = "out/pgsql.sql" + + s := cmd.String() + // The rendered (display-only) string quotes dangerous tokens so that even a + // copy-paste into a shell would not execute the injected commands. + assert.False(t, strings.Contains(s, "; touch /tmp/pwned # >"), + "unquoted injection leaked into rendered command: %s", s) + assert.Contains(t, s, `'--host=localhost; touch /tmp/pwned #'`) +} From 747e920b8fc31212e5e99d76ad54444e5ebd6902 Mon Sep 17 00:00:00 2001 From: Carter Brainerd Date: Thu, 9 Jul 2026 12:45:51 -0400 Subject: [PATCH 606/647] fix/batch-changes: validate files target paths in changeset hooks and executor (#1352) --- internal/batches/executor/run_steps.go | 10 ++++++++++ internal/batches/executor/run_steps_test.go | 16 ++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/internal/batches/executor/run_steps.go b/internal/batches/executor/run_steps.go index 67ccbfcb0b..543a2b591c 100644 --- a/internal/batches/executor/run_steps.go +++ b/internal/batches/executor/run_steps.go @@ -540,6 +540,16 @@ func createFilesToMount(tempDir string, step batcheslib.Step, stepContext *templ // can mount them into the container. filesToMount := make(map[string]*os.File, len(files)) for name, content := range files { + // Defense-in-depth: the mount target name is concatenated directly + // into a Docker `--mount type=bind,...,target=` argument. A comma + // in the name would let an attacker break out of the mount spec and + // inject arbitrary source=/target= pairs (e.g. /var/run/docker.sock). + // Parse-time validation rejects this, but the executor receives + // pre-parsed steps via JSON and never re-runs that validation, so we + // re-check here at the sink. + if strings.Contains(name, ",") { + return nil, cleanup, errors.Newf("files target path %q contains invalid characters", name) + } fp, err := os.CreateTemp(tempDir, "") if err != nil { return nil, cleanup, errors.Wrap(err, "creating temporary file") diff --git a/internal/batches/executor/run_steps_test.go b/internal/batches/executor/run_steps_test.go index 7b8dc6e356..9af78eea0e 100644 --- a/internal/batches/executor/run_steps_test.go +++ b/internal/batches/executor/run_steps_test.go @@ -5,9 +5,25 @@ import ( "github.com/stretchr/testify/require" + batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/template" ) +func TestCreateFilesToMount_RejectsCommaInTargetPath(t *testing.T) { + step := batcheslib.Step{ + Files: map[string]string{ + "/tmp/x,source=/var/run/docker.sock,target=/var/run/docker.sock": "IGNORED", + }, + } + + _, cleanup, err := createFilesToMount(t.TempDir(), step, &template.StepContext{}) + if cleanup != nil { + cleanup() + } + require.Error(t, err) + require.Contains(t, err.Error(), "contains invalid characters") +} + func TestRenderStepContainer(t *testing.T) { t.Run("static image", func(t *testing.T) { got, err := renderStepContainer("alpine:3", &template.StepContext{}) From 9f9bda6fcb2f25ef6fa059db1ba8f15789e5f82c Mon Sep 17 00:00:00 2001 From: Andre Eleuterio <11207474+andreeleuterio@users.noreply.github.com> Date: Mon, 27 Jul 2026 19:54:08 -0300 Subject: [PATCH 607/647] chore: update Go to 1.26.5 (#1355) Go 1.26.5 fixes CVE-2026-39822 (os: root escape via symlink plus trailing slash on Unix) and CVE-2026-42505 (crypto/tls), both of which are flagged by image scans against binaries built with Go 1.26.4. Updates the Go version in mise.toml (which CI derives its Go version from), go.mod, lib/go.mod, dev/vendor-lib.sh, and the Dockerfile builder image. The golang:1.26.5 Alpine image is only published on Alpine 3.23, so the builder stage moves from alpine3.22 to alpine3.23; the runtime stage is unchanged. ## Test Plan - go build ./cmd/src - go test ./... passes with Go 1.26.5 --- Dockerfile | 2 +- dev/vendor-lib.sh | 2 +- go.mod | 2 +- lib/go.mod | 2 +- mise.toml | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Dockerfile b/Dockerfile index 79886b234a..6a1d6bf01d 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,7 +4,7 @@ # # Nothing fancy here: we copy in the source code and build on the Alpine Go # image. Refer to .dockerignore to get a sense of what we're not going to copy. -FROM golang:1.26.4-alpine3.22@sha256:727cfc3c40be55cd1bc9a4a059406b28a059857e3be752aa9d09531e12c20c56 AS builder +FROM golang:1.26.5-alpine3.23@sha256:622e56dbc11a8cfe87cafa2331e9a201877271cbff918af53d3be315f3da88cc AS builder COPY . /src WORKDIR /src diff --git a/dev/vendor-lib.sh b/dev/vendor-lib.sh index 8e22f43238..06db251bd9 100755 --- a/dev/vendor-lib.sh +++ b/dev/vendor-lib.sh @@ -136,7 +136,7 @@ echo "Creating go.mod file..." cat > "$DEST_LIB/go.mod" < Date: Thu, 30 Jul 2026 08:59:27 -0700 Subject: [PATCH 608/647] docs/auth: clarify OAuth and access token setup (#1356) Explain endpoint configuration, OAuth keyring credentials, and personal access token authentication for non-interactive use. Document the src auth token commands and preserve the previous section anchor. --- README.md | 58 +++++++++++++++++++++++++++++++++---------------------- 1 file changed, 35 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index 46ee3f42d1..415b56caf6 100644 --- a/README.md +++ b/README.md @@ -103,54 +103,65 @@ See [Sourcegraph CLI for Windows](WINDOWS.md). docker run --rm=true sourcegraph/src-cli:latest search 'hello world' ``` -## Log into your Sourcegraph instance + -Run src login SOURCEGRAPH-URL to authenticate `src` to access your Sourcegraph instance with your user credentials. +## Connect to your Sourcegraph instance -
+`src` needs the URL of your Sourcegraph instance. Set `SRC_ENDPOINT` in your shell environment, replacing `https://sourcegraph.example.com` with your instance URL: -**Examples** -`src login https://sourcegraph.example.com` -`src login https://sourcegraph.com` +```sh +export SRC_ENDPOINT=https://sourcegraph.example.com +``` -
+For PowerShell on Windows: -`src` consults the following environment variables: +```powershell +$env:SRC_ENDPOINT = 'https://sourcegraph.example.com' +``` -- `SRC_ENDPOINT`: the URL to your Sourcegraph instance (such as `https://sourcegraph.example.com`) -- `SRC_ACCESS_TOKEN`: your Sourcegraph access token (on your Sourcegraph instance, click your user menu in the top right, then select **Settings > Access tokens** to create one) +For convenience, add this environment variable to your terminal profile or system environment variables. On Mac OS and Linux, the terminal profile is typically `~/.bash_profile` for Bash or `~/.zprofile` for Zsh. On Windows, you can add it through the *System Properties* window. See [these instructions](https://www.computerhope.com/issues/ch000549.htm) for details. -For convenience, you can add these environment variables persistently. +If `SRC_ENDPOINT` is not set, `src` defaults to `https://sourcegraph.com`. -### Configuration: Mac OS / Linux +### OAuth login -Add the following to your terminal profile file, typically accessible at `~/.bash_profile` (if using Bash) or `~/.zprofile` (if using Zsh): +Run `src login` to authenticate interactively with OAuth: -``` -export SRC_ACCESS_TOKEN=my-token -export SRC_ENDPOINT=https://sourcegraph.example.com +```sh +src login ``` -Replace `my-token` and `https://sourcegraph.example.com` with the appropriate values for your account and instance. +OAuth does not require you to create or export `SRC_ACCESS_TOKEN`. The OAuth credential is stored in your operating system's native keyring. Keep `SRC_ENDPOINT` set when running subsequent commands because `src` uses the endpoint to load the matching OAuth credential. -You can also inline them in a single command with: +You can also pass the instance URL directly to `src login`, but this only selects the endpoint for that login command. You must still set `SRC_ENDPOINT` when running subsequent commands: ```sh -SRC_ENDPOINT=https://sourcegraph.example.com SRC_ACCESS_TOKEN=my-token src search 'foo' +src login https://sourcegraph.example.com ``` -### Configuration: Windows +To use the active credential in another command, `src auth token` prints the raw token and `src auth token --header` prints a complete `Authorization` header for the active authentication mode. -Type the following on your PowerShell terminal: +### Personal access token login +For non-interactive authentication, such as in CI or scripts, create an access token on your Sourcegraph instance under **Settings > Access tokens**, then set both `SRC_ENDPOINT` and `SRC_ACCESS_TOKEN`: + +```sh +export SRC_ENDPOINT=https://sourcegraph.example.com +export SRC_ACCESS_TOKEN=my-token ``` + +For PowerShell on Windows: + +```powershell $env:SRC_ENDPOINT = 'https://sourcegraph.example.com' $env:SRC_ACCESS_TOKEN = 'my-token' ``` -Replace `my-token` and `https://sourcegraph.example.com` with the appropriate values for your account and instance. +When `SRC_ACCESS_TOKEN` is set, `src` uses it instead of an OAuth credential and running `src login` is not necessary. You can also set both variables for a single command: -You can also manually add them via the *System Properties* windows. Check [this post](https://www.computerhope.com/issues/ch000549.htm) for details. +```sh +SRC_ENDPOINT=https://sourcegraph.example.com SRC_ACCESS_TOKEN=my-token src search 'foo' +``` Is your Sourcegraph instance behind a custom auth proxy? See [auth proxy configuration](./AUTH_PROXY.md) docs. @@ -159,6 +170,7 @@ Is your Sourcegraph instance behind a custom auth proxy? See [auth proxy configu `src` provides different subcommands to interact with different parts of Sourcegraph: - `src login` - authenticate to a Sourcegraph instance with your user credentials + - `src auth` - print the active authentication token or authorization header - `src search` - perform searches and get results in your terminal or as JSON - `src api` - run Sourcegraph GraphQL API requests - `src batch` - execute and manage [batch changes](https://docs.sourcegraph.com/batch_changes) From cadb64a67c2ece9dff4d36ddac6eedbc45cc57d7 Mon Sep 17 00:00:00 2001 From: Andre Eleuterio <11207474+andreeleuterio@users.noreply.github.com> Date: Thu, 30 Jul 2026 20:16:52 -0300 Subject: [PATCH 609/647] chore/deps: bump vulnerable dependencies (#1357) Bumps vulnerable deps --- go.mod | 38 +++++++------- go.sum | 80 +++++++++++++++--------------- lib/go.mod | 9 ++-- lib/go.sum | 28 +++++------ npm-distribution/package-lock.json | 8 +-- npm-distribution/package.json | 2 +- 6 files changed, 82 insertions(+), 83 deletions(-) diff --git a/go.mod b/go.mod index 66ba88e145..3a97776d6e 100644 --- a/go.mod +++ b/go.mod @@ -32,9 +32,9 @@ require ( github.com/tliron/glsp v0.2.2 github.com/urfave/cli/v3 v3.8.0 github.com/zalando/go-keyring v0.2.6 - golang.org/x/sync v0.19.0 + golang.org/x/sync v0.22.0 google.golang.org/api v0.256.0 - google.golang.org/protobuf v1.36.10 + google.golang.org/protobuf v1.36.11 gopkg.in/yaml.v3 v3.0.1 jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7 k8s.io/api v0.33.2 @@ -48,7 +48,7 @@ require ( cloud.google.com/go/auth v0.17.0 // indirect cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect cloud.google.com/go/monitoring v1.24.2 // indirect - github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.30.0 // indirect + github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.32.0 // indirect github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.50.0 // indirect github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.50.0 // indirect github.com/alecthomas/chroma/v2 v2.14.0 // indirect @@ -60,9 +60,9 @@ require ( github.com/charmbracelet/x/exp/slice v0.0.0-20250327172914-2fdc97757edf // indirect github.com/charmbracelet/x/term v0.2.1 // indirect github.com/clipperhouse/uax29/v2 v2.2.0 // indirect - github.com/cncf/xds/go v0.0.0-20251210132809-ee656c7534f5 // indirect + github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2 // indirect github.com/danieljoos/wincred v1.2.2 // indirect - github.com/envoyproxy/go-control-plane/envoy v1.36.0 // indirect + github.com/envoyproxy/go-control-plane/envoy v1.37.0 // indirect github.com/felixge/httpsnoop v1.0.4 // indirect github.com/fxamacker/cbor/v2 v2.7.0 // indirect github.com/go-jose/go-jose/v4 v4.1.4 // indirect @@ -88,7 +88,7 @@ require ( github.com/xlab/treeprint v1.2.0 // indirect github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect - go.opentelemetry.io/contrib/detectors/gcp v1.39.0 // indirect + go.opentelemetry.io/contrib/detectors/gcp v1.43.0 // indirect go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0 // indirect go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0 // indirect go.opentelemetry.io/otel v1.43.0 // indirect @@ -96,9 +96,9 @@ require ( go.opentelemetry.io/otel/sdk v1.43.0 // indirect go.opentelemetry.io/otel/sdk/metric v1.43.0 // indirect go.opentelemetry.io/otel/trace v1.43.0 // indirect - golang.org/x/net v0.48.0 // indirect - google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 // indirect + golang.org/x/net v0.57.0 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20260414002931-afd174a4e478 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20260414002931-afd174a4e478 // indirect gopkg.in/evanphx/json-patch.v4 v4.12.0 // indirect sigs.k8s.io/randfill v1.0.0 // indirect ) @@ -129,7 +129,7 @@ require ( github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/dlclark/regexp2 v1.11.0 // indirect github.com/emicklei/go-restful/v3 v3.11.0 // indirect - github.com/envoyproxy/protoc-gen-validate v1.3.0 // indirect + github.com/envoyproxy/protoc-gen-validate v1.3.3 // indirect github.com/fatih/color v1.18.0 // indirect github.com/getsentry/sentry-go v0.27.0 // indirect github.com/ghodss/yaml v1.0.0 // indirect @@ -174,21 +174,21 @@ require ( github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect github.com/xeipuuv/gojsonschema v1.2.0 // indirect - github.com/yuin/goldmark v1.7.8 // indirect + github.com/yuin/goldmark v1.7.17 // indirect github.com/yuin/goldmark-emoji v1.0.5 // indirect go.uber.org/atomic v1.11.0 // indirect go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.24.0 // indirect - golang.org/x/crypto v0.46.0 // indirect - golang.org/x/mod v0.30.0 // indirect - golang.org/x/oauth2 v0.34.0 // indirect - golang.org/x/sys v0.42.0 // indirect - golang.org/x/term v0.38.0 // indirect - golang.org/x/text v0.32.0 // indirect + golang.org/x/crypto v0.54.0 // indirect + golang.org/x/mod v0.37.0 // indirect + golang.org/x/oauth2 v0.36.0 // indirect + golang.org/x/sys v0.47.0 // indirect + golang.org/x/term v0.45.0 // indirect + golang.org/x/text v0.40.0 // indirect golang.org/x/time v0.14.0 // indirect - golang.org/x/tools v0.39.0 // indirect + golang.org/x/tools v0.47.0 // indirect google.golang.org/genproto v0.0.0-20250603155806-513f23925822 // indirect - google.golang.org/grpc v1.79.3 // indirect + google.golang.org/grpc v1.82.1 // indirect gopkg.in/inf.v0 v0.9.1 // indirect; direct gopkg.in/yaml.v2 v2.4.0 // indirect k8s.io/klog/v2 v2.130.1 // indirect diff --git a/go.sum b/go.sum index bb29dbd1a3..a3ab138c99 100644 --- a/go.sum +++ b/go.sum @@ -24,8 +24,8 @@ cloud.google.com/go/trace v1.11.6 h1:2O2zjPzqPYAHrn3OKl029qlqG6W8ZdYaOWRyr8NgMT4 cloud.google.com/go/trace v1.11.6/go.mod h1:GA855OeDEBiBMzcckLPE2kDunIpC72N+Pq8WFieFjnI= github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg= github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.30.0 h1:sBEjpZlNHzK1voKq9695PJSX2o5NEXl7/OL3coiIY0c= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.30.0/go.mod h1:P4WPRUkOhJC13W//jWpyfJNDAIpvRbAUIYLX/4jtlE0= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.32.0 h1:rIkQfkCOVKc1OiRCNcSDD8ml5RJlZbH/Xsq7lbpynwc= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.32.0/go.mod h1:RD2SsorTmYhF6HkTmDw7KmPYQk8OBYwTkuasChwv7R4= github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.50.0 h1:5IT7xOdq17MtcdtL/vtl6mGfzhaq4m4vpollPRmlsBQ= github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.50.0/go.mod h1:ZV4VOm0/eHR06JLrXWe09068dHpr3TRpY9Uo7T+anuA= github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0.50.0 h1:nNMpRpnkWDAaqcpxMJvxa/Ud98gjbYwayJY4/9bdjiU= @@ -101,8 +101,8 @@ github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQ github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg= github.com/clipperhouse/uax29/v2 v2.2.0 h1:ChwIKnQN3kcZteTXMgb1wztSgaU+ZemkgWdohwgs8tY= github.com/clipperhouse/uax29/v2 v2.2.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM= -github.com/cncf/xds/go v0.0.0-20251210132809-ee656c7534f5 h1:6xNmx7iTtyBRev0+D/Tv1FZd4SCg8axKApyNyRsAt/w= -github.com/cncf/xds/go v0.0.0-20251210132809-ee656c7534f5/go.mod h1:KdCmV+x/BuvyMxRnYBlmVaq4OLiKW6iRQfvC62cvdkI= +github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2 h1:aBangftG7EVZoUb69Os8IaYg++6uMOdKK83QtkkvJik= +github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2/go.mod h1:qwXFYgsP6T7XnJtbKlf1HP8AjxZZyzxMmc+Lq5GjlU4= github.com/cockroachdb/errors v1.12.0 h1:d7oCs6vuIMUQRVbi6jWWWEJZahLCfJpnJSVobd1/sUo= github.com/cockroachdb/errors v1.12.0/go.mod h1:SvzfYNNBshAVbZ8wzNc/UPK3w1vf0dKDUP41ucAIf7g= github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b h1:r6VH0faHjZeQy818SGhaone5OnYfxFR/+AzdY3sf5aE= @@ -132,12 +132,12 @@ github.com/emicklei/go-restful/v3 v3.11.0 h1:rAQeMHw1c7zTmncogyy8VvRZwtkmkZ4FxER github.com/emicklei/go-restful/v3 v3.11.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= github.com/envoyproxy/go-control-plane v0.14.0 h1:hbG2kr4RuFj222B6+7T83thSPqLjwBIfQawTkC++2HA= github.com/envoyproxy/go-control-plane v0.14.0/go.mod h1:NcS5X47pLl/hfqxU70yPwL9ZMkUlwlKxtAohpi2wBEU= -github.com/envoyproxy/go-control-plane/envoy v1.36.0 h1:yg/JjO5E7ubRyKX3m07GF3reDNEnfOboJ0QySbH736g= -github.com/envoyproxy/go-control-plane/envoy v1.36.0/go.mod h1:ty89S1YCCVruQAm9OtKeEkQLTb+Lkz0k8v9W0Oxsv98= +github.com/envoyproxy/go-control-plane/envoy v1.37.0 h1:u3riX6BoYRfF4Dr7dwSOroNfdSbEPe9Yyl09/B6wBrQ= +github.com/envoyproxy/go-control-plane/envoy v1.37.0/go.mod h1:DReE9MMrmecPy+YvQOAOHNYMALuowAnbjjEMkkWOi6A= github.com/envoyproxy/go-control-plane/ratelimit v0.1.0 h1:/G9QYbddjL25KvtKTv3an9lx6VBE2cnb8wp1vEGNYGI= github.com/envoyproxy/go-control-plane/ratelimit v0.1.0/go.mod h1:Wk+tMFAFbCXaJPzVVHnPgRKdUdwW/KdbRt94AzgRee4= -github.com/envoyproxy/protoc-gen-validate v1.3.0 h1:TvGH1wof4H33rezVKWSpqKz5NXWg5VPuZ0uONDT6eb4= -github.com/envoyproxy/protoc-gen-validate v1.3.0/go.mod h1:HvYl7zwPa5mffgyeTUHA9zHIH36nmrm7oCbo4YKoSWA= +github.com/envoyproxy/protoc-gen-validate v1.3.3 h1:MVQghNeW+LZcmXe7SY1V36Z+WFMDjpqGAGacLe2T0ds= +github.com/envoyproxy/protoc-gen-validate v1.3.3/go.mod h1:TsndJ/ngyIdQRhMcVVGDDHINPLWB7C82oDArY51KfB0= github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM= github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU= @@ -389,16 +389,16 @@ github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9de github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= github.com/yuin/goldmark v1.7.1/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E= -github.com/yuin/goldmark v1.7.8 h1:iERMLn0/QJeHFhxSt3p6PeN9mGnvIKSpG9YYorDMnic= -github.com/yuin/goldmark v1.7.8/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E= +github.com/yuin/goldmark v1.7.17 h1:p36OVWwRb246iHxA/U4p8OPEpOTESm4n+g+8t0EE5uA= +github.com/yuin/goldmark v1.7.17/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg= github.com/yuin/goldmark-emoji v1.0.5 h1:EMVWyCGPlXJfUXBXpuMu+ii3TIaxbVBnEX9uaDC4cIk= github.com/yuin/goldmark-emoji v1.0.5/go.mod h1:tTkZEbwu5wkPmgTcitqddVxY9osFZiavD+r4AzQrh1U= github.com/zalando/go-keyring v0.2.6 h1:r7Yc3+H+Ux0+M72zacZoItR3UDxeWfKTcabvkI8ua9s= github.com/zalando/go-keyring v0.2.6/go.mod h1:2TCrxYrbUNYfNS/Kgy/LSrkSQzZ5UPVH85RwfczwvcI= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= -go.opentelemetry.io/contrib/detectors/gcp v1.39.0 h1:kWRNZMsfBHZ+uHjiH4y7Etn2FK26LAGkNFw7RHv1DhE= -go.opentelemetry.io/contrib/detectors/gcp v1.39.0/go.mod h1:t/OGqzHBa5v6RHZwrDBJ2OirWc+4q/w2fTbLZwAKjTk= +go.opentelemetry.io/contrib/detectors/gcp v1.43.0 h1:62yY3dT7/ShwOxzA0RsKRgshBmfElKI4d/Myu2OxDFU= +go.opentelemetry.io/contrib/detectors/gcp v1.43.0/go.mod h1:RyaZMFY7yi1kAs45S6mbFGz8O8rqB0dTY14uzvG4LCs= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0 h1:q4XOmH/0opmeuJtPsbFNivyl7bCt7yRBbeEm2sC/XtQ= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0/go.mod h1:snMWehoOh2wsEwnvvwtDyFCxVeDAODenXHtn5vzrKjo= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0 h1:RbKq8BG0FI8OiXhBfcRtqqHcZcka+gU3cskNuf05R18= @@ -427,16 +427,16 @@ golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACk golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU= -golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0= +golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw= +golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk= golang.org/x/exp v0.0.0-20230713183714-613f0c0eb8a1 h1:MGwJjxBy0HJshjDNfLsYO8xppfqWlA5ZT9OhtUUhTNw= golang.org/x/exp v0.0.0-20230713183714-613f0c0eb8a1/go.mod h1:FXUEEKJgO7OQYeo8N01OfiKP8RXMtf6e8aTskBGqWdc= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.7.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/mod v0.30.0 h1:fDEXFVZ/fmCKProc/yAXXUijritrDzahmwwefnjoPFk= -golang.org/x/mod v0.30.0/go.mod h1:lAsf5O2EvJeSFMiBxXDki7sCgAxEUcZHXoXMKT4GJKc= +golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ= +golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= @@ -444,18 +444,18 @@ golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwY golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.3.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE= -golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU= -golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY= -golang.org/x/oauth2 v0.34.0 h1:hqK/t4AKgbqWkdkcAeI8XLmbK+4m4G5YeQRrmiotGlw= -golang.org/x/oauth2 v0.34.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= +golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE= +golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU= +golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs= +golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220819030929-7fc1605a5dde/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4= -golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= +golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= +golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -472,19 +472,19 @@ golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220829200755-d48e67d00261/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo= -golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= +golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.3.0/go.mod h1:q750SLmJuPmVoN1blW3UFBPREJfb1KmY3vwxfr+nFDA= -golang.org/x/term v0.38.0 h1:PQ5pkm/rLO6HnxFR7N2lJHOZX6Kez5Y1gDSJla6jo7Q= -golang.org/x/term v0.38.0/go.mod h1:bSEAKrOT1W+VSu9TSCMtoGEOUcKxOKgl3LE5QEF/xVg= +golang.org/x/term v0.45.0 h1:NwWyBmoJCbfTHpxrWoZ9C6/VxOf7ic219I8xZZFdrf0= +golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU= -golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY= +golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs= +golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY= golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI= golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -494,26 +494,26 @@ golang.org/x/tools v0.0.0-20200624163319-25775e59acb7/go.mod h1:EkVYQZoAsY45+roY golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.4.0/go.mod h1:UE5sM2OK9E/d67R0ANs2xJizIymRP5gJU295PvKXxjQ= -golang.org/x/tools v0.39.0 h1:ik4ho21kwuQln40uelmciQPp9SipgNDdrafrYA4TmQQ= -golang.org/x/tools v0.39.0/go.mod h1:JnefbkDPyD8UU2kI5fuf8ZX4/yUeh9W877ZeBONxUqQ= +golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q= +golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk= -gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E= +gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= +gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= google.golang.org/api v0.256.0 h1:u6Khm8+F9sxbCTYNoBHg6/Hwv0N/i+V94MvkOSor6oI= google.golang.org/api v0.256.0/go.mod h1:KIgPhksXADEKJlnEoRa9qAII4rXcy40vfI8HRqcU964= google.golang.org/genproto v0.0.0-20250603155806-513f23925822 h1:rHWScKit0gvAPuOnu87KpaYtjK5zBMLcULh7gxkCXu4= google.golang.org/genproto v0.0.0-20250603155806-513f23925822/go.mod h1:HubltRL7rMh0LfnQPkMH4NPDFEWp0jw3vixw7jEM53s= -google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217 h1:fCvbg86sFXwdrl5LgVcTEvNC+2txB5mgROGmRL5mrls= -google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217/go.mod h1:+rXWjjaukWZun3mLfjmVnQi18E1AsFbDN9QdJ5YXLto= -google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 h1:gRkg/vSppuSQoDjxyiGfN4Upv/h/DQmIR10ZU8dh4Ww= -google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217/go.mod h1:7i2o+ce6H/6BluujYR+kqX3GKH+dChPTQU19wjRPiGk= -google.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE= -google.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ= -google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= -google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +google.golang.org/genproto/googleapis/api v0.0.0-20260414002931-afd174a4e478 h1:yQugLulqltosq0B/f8l4w9VryjV+N/5gcW0jQ3N8Qec= +google.golang.org/genproto/googleapis/api v0.0.0-20260414002931-afd174a4e478/go.mod h1:C6ADNqOxbgdUUeRTU+LCHDPB9ttAMCTff6auwCVa4uc= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260414002931-afd174a4e478 h1:RmoJA1ujG+/lRGNfUnOMfhCy5EipVMyvUE+KNbPbTlw= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260414002931-afd174a4e478/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= +google.golang.org/grpc v1.82.1 h1:NnAxzGRA0677vCa4BUkOAnO5+FfQqVl9iUXeD0IqcGE= +google.golang.org/grpc v1.82.1/go.mod h1:yzTZ1TB1Z3SG+LIYaI+WiE8D5+PZ3ArnrSp8zF3+/ZA= +google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= +google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= diff --git a/lib/go.mod b/lib/go.mod index 09188ef33b..a55ba1bc9f 100644 --- a/lib/go.mod +++ b/lib/go.mod @@ -27,8 +27,8 @@ require ( github.com/xeipuuv/gojsonschema v1.2.0 github.com/xlab/treeprint v1.2.0 go.opentelemetry.io/otel v1.43.0 - golang.org/x/sys v0.41.0 - golang.org/x/term v0.37.0 + golang.org/x/sys v0.47.0 + golang.org/x/term v0.45.0 google.golang.org/protobuf v1.36.10 gopkg.in/yaml.v3 v3.0.1 ) @@ -78,9 +78,8 @@ require ( go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.24.0 // indirect golang.org/x/exp v0.0.0-20230713183714-613f0c0eb8a1 // indirect - golang.org/x/net v0.44.0 // indirect - golang.org/x/text v0.29.0 // indirect - golang.org/x/tools v0.37.0 // indirect + golang.org/x/net v0.57.0 // indirect + golang.org/x/text v0.40.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect ) diff --git a/lib/go.sum b/lib/go.sum index 7a5acf0f7e..39d3e6cd12 100644 --- a/lib/go.sum +++ b/lib/go.sum @@ -184,38 +184,38 @@ golang.org/x/exp v0.0.0-20230713183714-613f0c0eb8a1 h1:MGwJjxBy0HJshjDNfLsYO8xpp golang.org/x/exp v0.0.0-20230713183714-613f0c0eb8a1/go.mod h1:FXUEEKJgO7OQYeo8N01OfiKP8RXMtf6e8aTskBGqWdc= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.28.0 h1:gQBtGhjxykdjY9YhZpSlZIsbnaE2+PgjfLWUQTnoZ1U= -golang.org/x/mod v0.28.0/go.mod h1:yfB/L0NOf/kmEbXjzCPOx1iK1fRutOydrCMsqRhEBxI= +golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ= +golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.44.0 h1:evd8IRDyfNBMBTTY5XRF1vaZlD+EmWx6x8PkhR04H/I= -golang.org/x/net v0.44.0/go.mod h1:ECOoLqd5U3Lhyeyo/QDCEVQ4sNgYsqvCZ722XogGieY= +golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE= +golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug= -golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= +golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= +golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k= -golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= -golang.org/x/term v0.37.0 h1:8EGAD0qCmHYZg6J17DvsMy9/wJ7/D/4pV/wfnld5lTU= -golang.org/x/term v0.37.0/go.mod h1:5pB4lxRNYYVZuTLmy8oR2BH8dflOR+IbTYFD8fi3254= +golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= +golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/term v0.45.0 h1:NwWyBmoJCbfTHpxrWoZ9C6/VxOf7ic219I8xZZFdrf0= +golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk= -golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4= +golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs= +golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.37.0 h1:DVSRzp7FwePZW356yEAChSdNcQo6Nsp+fex1SUW09lE= -golang.org/x/tools v0.37.0/go.mod h1:MBN5QPQtLMHVdvsbtarmTNukZDdgwdwlO5qGacAzF0w= +golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q= +golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/npm-distribution/package-lock.json b/npm-distribution/package-lock.json index b6f627a88b..8a11a72602 100644 --- a/npm-distribution/package-lock.json +++ b/npm-distribution/package-lock.json @@ -10,7 +10,7 @@ "hasInstallScript": true, "license": "Apache-2.0", "dependencies": { - "tar": "^7.5.15" + "tar": "^7.5.22" }, "bin": { "src": "src.js" @@ -102,9 +102,9 @@ } }, "node_modules/tar": { - "version": "7.5.15", - "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.15.tgz", - "integrity": "sha512-dzGK0boVlC4W5QFuQN1EFSl3bIDYsk7Tj40U6eIBnK2k/8ml7TZ5agbI5j5+qnoVcAA+rNtBml8SEiLxZpNqRQ==", + "version": "7.5.22", + "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.22.tgz", + "integrity": "sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA==", "license": "BlueOak-1.0.0", "dependencies": { "@isaacs/fs-minipass": "^4.0.0", diff --git a/npm-distribution/package.json b/npm-distribution/package.json index fb8fddb0b8..c65849dac4 100644 --- a/npm-distribution/package.json +++ b/npm-distribution/package.json @@ -17,7 +17,7 @@ "sourcegraph" ], "dependencies": { - "tar": "^7.5.15" + "tar": "^7.5.22" }, "overrides": { "cross-spawn": "^7.0.5", From 23e836ac0046b78ed8c27cfb4ae74ee55275cd8c Mon Sep 17 00:00:00 2001 From: Bolaji Olajide <25608335+BolajiOlajide@users.noreply.github.com> Date: Tue, 4 Aug 2026 15:30:34 +0100 Subject: [PATCH 610/647] fix/config: merge env additional headers over config file headers (#1359) * fix/config: merge env additional headers over config file headers Previously env-derived additional headers overwrote any additionalHeaders loaded from the config file entirely. Merge them instead, with env headers taking precedence, consistent with how the access token and endpoint are overridden. Config-file keys are normalized to lowercase to match the env-header convention, so env values correctly override differently-cased config keys and the authorization-conflict check catches them. * chore/config: condense additional-headers merge comment --- cmd/src/main.go | 11 ++++++++- cmd/src/main_test.go | 57 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+), 1 deletion(-) diff --git a/cmd/src/main.go b/cmd/src/main.go index fd217ba51f..7bb75e6211 100644 --- a/cmd/src/main.go +++ b/cmd/src/main.go @@ -337,7 +337,16 @@ func readConfig() (*config, error) { } } - cfg.additionalHeaders = parseAdditionalHeaders() + // Merge config-file headers under the env headers (which take precedence), + // lowercasing config keys to match the env-header convention. + envHeaders := parseAdditionalHeaders() + for k, v := range cfg.additionalHeaders { + lk := strings.ToLower(k) + if _, ok := envHeaders[lk]; !ok { + envHeaders[lk] = v + } + } + cfg.additionalHeaders = envHeaders // Ensure that we're not clashing additonal headers _, hasAuthorizationAdditonalHeader := cfg.additionalHeaders["authorization"] if cfg.accessToken != "" && hasAuthorizationAdditonalHeader { diff --git a/cmd/src/main_test.go b/cmd/src/main_test.go index 0b23cb9938..277285b1db 100644 --- a/cmd/src/main_test.go +++ b/cmd/src/main_test.go @@ -358,6 +358,63 @@ func TestReadConfig(t *testing.T) { inCI: true, }, }, + { + name: "config file additional headers preserved when endpoint/token from environment", + fileContents: &configFromFile{ + Endpoint: "https://example.com/", + AccessToken: "deadbeef", + AdditionalHeaders: map[string]string{"x-proxy-token": "secret"}, + }, + envToken: "abc", + envEndpoint: "https://override.com", + want: &config{ + endpointURL: &url.URL{Scheme: "https", Host: "override.com"}, + accessToken: "abc", + additionalHeaders: map[string]string{"x-proxy-token": "secret"}, + }, + }, + { + name: "config file additional headers merged with environment headers", + fileContents: &configFromFile{ + Endpoint: "https://example.com/", + AccessToken: "deadbeef", + AdditionalHeaders: map[string]string{"x-proxy-token": "secret"}, + }, + envFooHeader: "bar", + want: &config{ + endpointURL: &url.URL{Scheme: "https", Host: "example.com"}, + accessToken: "deadbeef", + additionalHeaders: map[string]string{"x-proxy-token": "secret", "foo": "bar"}, + }, + }, + { + name: "environment headers override config file headers", + fileContents: &configFromFile{ + Endpoint: "https://example.com/", + AccessToken: "deadbeef", + AdditionalHeaders: map[string]string{"foo": "from-config"}, + }, + envFooHeader: "from-env", + want: &config{ + endpointURL: &url.URL{Scheme: "https", Host: "example.com"}, + accessToken: "deadbeef", + additionalHeaders: map[string]string{"foo": "from-env"}, + }, + }, + { + name: "environment headers override differently-cased config file headers", + fileContents: &configFromFile{ + Endpoint: "https://example.com/", + AccessToken: "deadbeef", + AdditionalHeaders: map[string]string{"Foo": "from-config"}, + }, + envFooHeader: "from-env", + want: &config{ + endpointURL: &url.URL{Scheme: "https", Host: "example.com"}, + accessToken: "deadbeef", + additionalHeaders: map[string]string{"foo": "from-env"}, + }, + }, } for _, test := range tests { From 2027d7855e51c4c85df85b4a459d93a58cbacdc5 Mon Sep 17 00:00:00 2001 From: Carter Brainerd Date: Thu, 13 Aug 2026 16:16:36 -0500 Subject: [PATCH 611/647] fix/security: strip auth headers on cross-host redirect (#1361) --- internal/api/api.go | 10 ++- internal/api/redirect_test.go | 124 ++++++++++++++++++++++++++++++++++ 2 files changed, 133 insertions(+), 1 deletion(-) create mode 100644 internal/api/redirect_test.go diff --git a/internal/api/api.go b/internal/api/api.go index 800d8d41a2..8e1578d60d 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -139,7 +139,8 @@ func NewClient(opts ClientOpts) Client { transport := buildTransport(opts, flags) httpClient := &http.Client{ - Transport: transport, + Transport: transport, + CheckRedirect: checkRedirect, } return &client{ @@ -155,6 +156,13 @@ func NewClient(opts ClientOpts) Client { } } +func checkRedirect(req *http.Request, via []*http.Request) error { + if len(via) > 0 && req.URL.Host != via[0].URL.Host { + return http.ErrUseLastResponse + } + return nil +} + func (c *client) checkIfCIAccessTokenRequired() error { if c.opts.RequireAccessTokenInCI && c.opts.AccessToken == "" { return ErrCIAccessTokenRequired diff --git a/internal/api/redirect_test.go b/internal/api/redirect_test.go new file mode 100644 index 0000000000..d2dd84de78 --- /dev/null +++ b/internal/api/redirect_test.go @@ -0,0 +1,124 @@ +package api + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "net/url" + "sync/atomic" + "testing" + "time" + + "github.com/sourcegraph/src-cli/internal/oauth" +) + +func TestCredentialsAreNotSentOnCrossHostRedirect(t *testing.T) { + tests := []struct { + name string + header string + value string + configure func(*ClientOpts, string) + }{ + { + name: "OAuth token", + header: "Authorization", + value: "Bearer oauth-secret-token", + configure: func(opts *ClientOpts, endpoint string) { + opts.OAuthToken = &oauth.Token{ + Endpoint: endpoint, + AccessToken: "oauth-secret-token", + ExpiresAt: time.Now().Add(time.Hour), + } + }, + }, + { + name: "custom auth-proxy header", + header: "X-Dbx-Auth-Token", + value: "proxy-secret-token", + configure: func(opts *ClientOpts, _ string) { + opts.AdditionalHeaders = map[string]string{ + "X-Dbx-Auth-Token": "proxy-secret-token", + } + }, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + var redirectTargetRequests atomic.Int32 + redirectTarget := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + redirectTargetRequests.Add(1) + w.WriteHeader(http.StatusOK) + })) + defer redirectTarget.Close() + + var initialHeader string + redirector := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + initialHeader = r.Header.Get(test.header) + http.Redirect(w, r, redirectTarget.URL, http.StatusFound) + })) + defer redirector.Close() + + endpointURL, err := url.Parse(redirector.URL) + if err != nil { + t.Fatal(err) + } + opts := ClientOpts{EndpointURL: endpointURL, Out: io.Discard} + test.configure(&opts, redirector.URL) + client := NewClient(opts) + + req, err := client.NewHTTPRequest(context.Background(), http.MethodGet, "", nil) + if err != nil { + t.Fatal(err) + } + resp, err := client.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusFound { + t.Fatalf("got status %d, want %d", resp.StatusCode, http.StatusFound) + } + if initialHeader != test.value { + t.Fatalf("initial request %s header = %q, want %q", test.header, initialHeader, test.value) + } + if got := redirectTargetRequests.Load(); got != 0 { + t.Fatalf("cross-host redirect target received %d requests, want 0", got) + } + }) + } +} + +func TestClientFollowsSameHostRedirect(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, "/target", http.StatusFound) + }) + mux.HandleFunc("/target", func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusNoContent) + }) + server := httptest.NewServer(mux) + defer server.Close() + + endpointURL, err := url.Parse(server.URL) + if err != nil { + t.Fatal(err) + } + client := NewClient(ClientOpts{EndpointURL: endpointURL, Out: io.Discard}) + + req, err := client.NewHTTPRequest(context.Background(), http.MethodGet, "", nil) + if err != nil { + t.Fatal(err) + } + resp, err := client.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusNoContent { + t.Fatalf("got status %d, want %d", resp.StatusCode, http.StatusNoContent) + } +} From 0636daca3b30a5f332bfb9749b50e07511380faf Mon Sep 17 00:00:00 2001 From: Michael Bahr <1830132+bahrmichael@users.noreply.github.com> Date: Tue, 25 Aug 2026 10:55:33 +0200 Subject: [PATCH 612/647] feat: add timeout for slow instances (#1362) * improved timeouts handling * default 1 minute --- CHANGELOG.md | 3 + README.md | 4 ++ cmd/src/search_jobs.go | 27 +++++++++ cmd/src/search_jobs_logs.go | 19 +----- cmd/src/search_jobs_results.go | 19 +----- cmd/src/search_jobs_test.go | 67 +++++++++++++++++++++ internal/api/api.go | 33 +++++++++- internal/api/timeout_test.go | 107 +++++++++++++++++++++++++++++++++ internal/users/admin.go | 13 ++-- 9 files changed, 255 insertions(+), 37 deletions(-) create mode 100644 cmd/src/search_jobs_test.go create mode 100644 internal/api/timeout_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 0f87c3d286..87221c00fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,9 @@ All notable changes to `src-cli` are documented in this file. ### Changed +- HTTP requests now fail instead of hanging forever if the server does not start responding within 1 minute. Set the `SRC_RESPONSE_HEADER_TIMEOUT` environment variable to change this timeout, or to `0` to disable it. Responses that stream data for a long time (for example, large search job results) are not affected. +- `src search-jobs logs` and `src search-jobs results` now use the standard API client, gaining proxy support, `-insecure-skip-verify`, and cross-host redirect protection, and now report an error on non-200 responses instead of writing the error page into the output. + ### Removed - Removed `src sbom` and `src signature` commands. SBOMs and container signatures are no longer published as of Sourcegraph 7.1.0. diff --git a/README.md b/README.md index 415b56caf6..653942aed1 100644 --- a/README.md +++ b/README.md @@ -197,6 +197,10 @@ mv /usr/local/bin/src /usr/local/bin/src-cli You can then invoke it via `src-cli`. +## Timeouts + +`src` waits up to 1 minute for the server to start responding to a request. To change this, set the `SRC_RESPONSE_HEADER_TIMEOUT` environment variable to a duration such as `30s` or `10m`, or to `0` to disable the timeout. This timeout only applies until the server sends its response headers — responses that stream data for a long time, such as large search job results, are not interrupted. + ## Telemetry `src` includes the operating system and architecture in the `User-Agent` header sent to Sourcegraph. For example, running `src` version 3.21.10 on an x86-64 Linux host will result in this header: diff --git a/cmd/src/search_jobs.go b/cmd/src/search_jobs.go index d8f513efcd..986aaf1603 100644 --- a/cmd/src/search_jobs.go +++ b/cmd/src/search_jobs.go @@ -4,6 +4,8 @@ import ( "encoding/json" "flag" "fmt" + "io" + "net/http" "strings" "github.com/sourcegraph/src-cli/internal/api" @@ -167,6 +169,31 @@ func parseSearchJobsArgs(flagSet *flag.FlagSet, args []string) error { return nil } +// fetchSearchJobFile downloads a file (logs or results) belonging to a search +// job. The request goes through the API client so that it picks up the +// configured transport (timeouts, proxy, TLS and redirect handling). +func fetchSearchJobFile(client api.Client, fileURL string) (io.ReadCloser, error) { + req, err := http.NewRequest("GET", fileURL, nil) + if err != nil { + return nil, err + } + + req.Header.Add("Authorization", "token "+cfg.accessToken) + + resp, err := client.Do(req) + if err != nil { + return nil, err + } + + if resp.StatusCode != http.StatusOK { + body, _ := io.ReadAll(io.LimitReader(resp.Body, 1024)) + resp.Body.Close() + return nil, fmt.Errorf("error: %s\n\n%s", resp.Status, body) + } + + return resp.Body, nil +} + // validateJobID validates that a job ID was provided func validateJobID(args []string) (string, error) { if len(args) != 1 { diff --git a/cmd/src/search_jobs_logs.go b/cmd/src/search_jobs_logs.go index 6327a609ab..31a4dec26f 100644 --- a/cmd/src/search_jobs_logs.go +++ b/cmd/src/search_jobs_logs.go @@ -4,7 +4,6 @@ import ( "flag" "fmt" "io" - "net/http" "os" "github.com/sourcegraph/src-cli/internal/api" @@ -12,24 +11,12 @@ import ( ) // fetchJobLogs retrieves logs for a search job from its log URL -func fetchJobLogs(jobID string, logURL string) (io.ReadCloser, error) { +func fetchJobLogs(client api.Client, jobID string, logURL string) (io.ReadCloser, error) { if logURL == "" { return nil, fmt.Errorf("no logs URL found for search job %s", jobID) } - req, err := http.NewRequest("GET", logURL, nil) - if err != nil { - return nil, err - } - - req.Header.Add("Authorization", "token "+cfg.accessToken) - - resp, err := http.DefaultClient.Do(req) - if err != nil { - return nil, err - } - - return resp.Body, nil + return fetchSearchJobFile(client, logURL) } func outputLogs(logs io.Reader, outputPath string) error { @@ -88,7 +75,7 @@ func init() { return fmt.Errorf("no job found with ID %s", jobID) } - logsData, err := fetchJobLogs(jobID, job.LogURL) + logsData, err := fetchJobLogs(client, jobID, job.LogURL) if err != nil { return err } diff --git a/cmd/src/search_jobs_results.go b/cmd/src/search_jobs_results.go index 9d8bc7a9ab..4e06cf27a1 100644 --- a/cmd/src/search_jobs_results.go +++ b/cmd/src/search_jobs_results.go @@ -4,7 +4,6 @@ import ( "flag" "fmt" "io" - "net/http" "os" "github.com/sourcegraph/src-cli/internal/api" @@ -12,24 +11,12 @@ import ( ) // fetchJobResults retrieves results for a search job from its results URL -func fetchJobResults(jobID string, resultsURL string) (io.ReadCloser, error) { +func fetchJobResults(client api.Client, jobID string, resultsURL string) (io.ReadCloser, error) { if resultsURL == "" { return nil, fmt.Errorf("no results URL found for search job %s", jobID) } - req, err := http.NewRequest("GET", resultsURL, nil) - if err != nil { - return nil, err - } - - req.Header.Add("Authorization", "token "+cfg.accessToken) - - resp, err := http.DefaultClient.Do(req) - if err != nil { - return nil, err - } - - return resp.Body, nil + return fetchSearchJobFile(client, resultsURL) } // outputResults writes results to either a file or stdout @@ -90,7 +77,7 @@ func init() { return fmt.Errorf("no job found with ID %s", jobID) } - resultsData, err := fetchJobResults(jobID, job.URL) + resultsData, err := fetchJobResults(client, jobID, job.URL) if err != nil { return err } diff --git a/cmd/src/search_jobs_test.go b/cmd/src/search_jobs_test.go new file mode 100644 index 0000000000..cd573fd92d --- /dev/null +++ b/cmd/src/search_jobs_test.go @@ -0,0 +1,67 @@ +package main + +import ( + "io" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + + "github.com/sourcegraph/src-cli/internal/api" +) + +func TestFetchSearchJobFile(t *testing.T) { + var gotAuth string + mux := http.NewServeMux() + mux.HandleFunc("/ok", func(w http.ResponseWriter, r *http.Request) { + gotAuth = r.Header.Get("Authorization") + _, _ = w.Write([]byte("results data")) + }) + mux.HandleFunc("/fail", func(w http.ResponseWriter, r *http.Request) { + http.Error(w, "something went wrong", http.StatusInternalServerError) + }) + server := httptest.NewServer(mux) + defer server.Close() + + endpointURL, err := url.Parse(server.URL) + if err != nil { + t.Fatal(err) + } + cfg = &config{ + endpointURL: endpointURL, + accessToken: "test-token", + } + defer func() { cfg = nil }() + + client := api.NewClient(api.ClientOpts{EndpointURL: endpointURL, Out: io.Discard}) + + t.Run("success", func(t *testing.T) { + body, err := fetchSearchJobFile(client, server.URL+"/ok") + if err != nil { + t.Fatal(err) + } + defer body.Close() + + data, err := io.ReadAll(body) + if err != nil { + t.Fatal(err) + } + if string(data) != "results data" { + t.Fatalf("got body %q, want %q", data, "results data") + } + if gotAuth != "token test-token" { + t.Fatalf("got Authorization header %q, want %q", gotAuth, "token test-token") + } + }) + + t.Run("non-200 response", func(t *testing.T) { + _, err := fetchSearchJobFile(client, server.URL+"/fail") + if err == nil { + t.Fatal("expected an error for a non-200 response, got nil") + } + if !strings.Contains(err.Error(), "something went wrong") { + t.Fatalf("error %q does not contain the response body", err) + } + }) +} diff --git a/internal/api/api.go b/internal/api/api.go index 8e1578d60d..d34ccf4c93 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -12,6 +12,7 @@ import ( "net/url" "os" "runtime" + "time" ioaux "github.com/jig/teereadcloser" "github.com/kballard/go-shellquote" @@ -95,10 +96,36 @@ type ClientOpts struct { // ErrCIAccessTokenRequired indicates SRC_ACCESS_TOKEN must be set when CI=true. var ErrCIAccessTokenRequired = errors.New("SRC_ACCESS_TOKEN must be set when CI=true") +// defaultResponseHeaderTimeout bounds how long we wait for a server to start +// responding. It is deliberately generous because some GraphQL queries take a +// long time server-side before the first response byte is written. +const defaultResponseHeaderTimeout = 1 * time.Minute + +// responseHeaderTimeout returns the timeout to wait for a server's response +// headers, honoring the SRC_RESPONSE_HEADER_TIMEOUT environment variable (a Go +// duration string; "0" disables the timeout). +func responseHeaderTimeout() time.Duration { + if v := os.Getenv("SRC_RESPONSE_HEADER_TIMEOUT"); v != "" { + if d, err := time.ParseDuration(v); err == nil && d >= 0 { + return d + } + } + return defaultResponseHeaderTimeout +} + +// BaseTransport returns a clone of http.DefaultTransport (which carries dial +// and TLS handshake timeouts) with a response header timeout applied, so that +// an unresponsive server cannot stall requests indefinitely. +func BaseTransport() *http.Transport { + tp := http.DefaultTransport.(*http.Transport).Clone() + tp.ResponseHeaderTimeout = responseHeaderTimeout() + return tp +} + func buildTransport(opts ClientOpts, flags *Flags) http.RoundTripper { var transport http.RoundTripper { - tp := http.DefaultTransport.(*http.Transport).Clone() + tp := BaseTransport() if flags.insecureSkipVerify != nil && *flags.insecureSkipVerify { tp.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} @@ -138,6 +165,10 @@ func NewClient(opts ClientOpts) Client { transport := buildTransport(opts, flags) + // Note: no Client.Timeout is set on purpose. It would cap the entire + // request including reading the response body, but downloads (search job + // results, batch change archives, ...) may legitimately stream for a very + // long time. The transport's connection-phase timeouts bound the rest. httpClient := &http.Client{ Transport: transport, CheckRedirect: checkRedirect, diff --git a/internal/api/timeout_test.go b/internal/api/timeout_test.go new file mode 100644 index 0000000000..8bd5a89ef8 --- /dev/null +++ b/internal/api/timeout_test.go @@ -0,0 +1,107 @@ +package api + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "net/url" + "testing" + "time" +) + +func newTestClient(t *testing.T, serverURL string) Client { + t.Helper() + endpointURL, err := url.Parse(serverURL) + if err != nil { + t.Fatal(err) + } + return NewClient(ClientOpts{EndpointURL: endpointURL, Out: io.Discard}) +} + +func TestUnresponsiveServerTimesOut(t *testing.T) { + t.Setenv("SRC_RESPONSE_HEADER_TIMEOUT", "100ms") + + block := make(chan struct{}) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + <-block + })) + defer server.Close() + defer close(block) + + client := newTestClient(t, server.URL) + req, err := client.NewHTTPRequest(context.Background(), http.MethodGet, "", nil) + if err != nil { + t.Fatal(err) + } + + start := time.Now() + resp, err := client.Do(req) + if err == nil { + resp.Body.Close() + t.Fatal("expected a timeout error, got nil") + } + if elapsed := time.Since(start); elapsed > 5*time.Second { + t.Fatalf("request took %s, expected it to fail within the response header timeout", elapsed) + } +} + +func TestSlowStreamingDownloadSucceeds(t *testing.T) { + t.Setenv("SRC_RESPONSE_HEADER_TIMEOUT", "200ms") + + const chunks = 5 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + flusher := w.(http.Flusher) + w.WriteHeader(http.StatusOK) + flusher.Flush() + // Stream the body for much longer than the response header timeout. + for range chunks { + time.Sleep(100 * time.Millisecond) + _, _ = w.Write([]byte("chunk")) + flusher.Flush() + } + })) + defer server.Close() + + client := newTestClient(t, server.URL) + req, err := client.NewHTTPRequest(context.Background(), http.MethodGet, "", nil) + if err != nil { + t.Fatal(err) + } + + resp, err := client.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + t.Fatalf("reading a slow streaming body failed: %v", err) + } + if want := len("chunk") * chunks; len(body) != want { + t.Fatalf("got %d body bytes, want %d", len(body), want) + } +} + +func TestResponseHeaderTimeoutEnv(t *testing.T) { + tests := []struct { + value string + want time.Duration + }{ + {value: "", want: defaultResponseHeaderTimeout}, + {value: "30s", want: 30 * time.Second}, + {value: "0", want: 0}, + {value: "garbage", want: defaultResponseHeaderTimeout}, + {value: "-5s", want: defaultResponseHeaderTimeout}, + } + + for _, test := range tests { + t.Run(test.value, func(t *testing.T) { + t.Setenv("SRC_RESPONSE_HEADER_TIMEOUT", test.value) + if got := responseHeaderTimeout(); got != test.want { + t.Fatalf("got %s, want %s", got, test.want) + } + }) + } +} diff --git a/internal/users/admin.go b/internal/users/admin.go index 03a8696bc5..6840f9f22c 100644 --- a/internal/users/admin.go +++ b/internal/users/admin.go @@ -8,14 +8,19 @@ import ( "strings" jsoniter "github.com/json-iterator/go" + "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/lazyregexp" "github.com/sourcegraph/sourcegraph/lib/errors" ) +// httpClient bounds the connection phase (dial, TLS handshake, response +// headers) so an unresponsive instance cannot stall requests indefinitely. +var httpClient = &http.Client{Transport: api.BaseTransport()} + // NeedsSiteInit returns true if the instance hasn't done "Site admin init" step. func NeedsSiteInit(baseURL string) (bool, string, error) { - resp, err := http.Get(baseURL + "/sign-in") + resp, err := httpClient.Get(baseURL + "/sign-in") if err != nil { return false, "", errors.Wrap(err, "sign-in page") } @@ -83,7 +88,7 @@ func NewClient(baseURL string, requestLogger, responseLogger logFunc) (*Client, responseLogger = noopLog } - resp, err := http.Get(baseURL) + resp, err := httpClient.Get(baseURL) if err != nil { return nil, errors.Wrap(err, "get URL") } @@ -133,7 +138,7 @@ func (c *Client) authenticate(path string, body any) error { req.AddCookie(c.csrfCookie) } - resp, err := http.DefaultClient.Do(req) + resp, err := httpClient.Do(req) if err != nil { return errors.Wrap(err, "do request") } @@ -269,7 +274,7 @@ func (c *Client) GraphQL(token, query string, variables map[string]any, target a c.requestLogger(body) - resp, err := http.DefaultClient.Do(req) + resp, err := httpClient.Do(req) if err != nil { return err } From c4030b57f0e3c77f8915a57fd9b41d0bc88b0b92 Mon Sep 17 00:00:00 2001 From: Carter Brainerd Date: Thu, 3 Sep 2026 10:15:08 -0400 Subject: [PATCH 613/647] fix/batches: validate shell probe paths (#1363) --- internal/batches/executor/run_steps.go | 66 +++++++++++++++++-- internal/batches/executor/run_steps_test.go | 52 +++++++++++++++ .../executor/testdata/dummydocker/docker | 2 +- 3 files changed, 115 insertions(+), 5 deletions(-) diff --git a/internal/batches/executor/run_steps.go b/internal/batches/executor/run_steps.go index 543a2b591c..6b6a61788e 100644 --- a/internal/batches/executor/run_steps.go +++ b/internal/batches/executor/run_steps.go @@ -9,7 +9,9 @@ import ( "maps" "os" "os/exec" + "path" "path/filepath" + "regexp" "strings" "time" @@ -348,13 +350,21 @@ func executeSingleStep( scriptWorkDir = workDir + "/" + opts.Task.Path } + if err := validateContainerTempPath(containerTemp); err != nil { + return bytes.Buffer{}, bytes.Buffer{}, errors.Wrap(err, "validating run script target") + } + runScriptMount, err := dockerBindMount(runScriptFile, containerTemp) + if err != nil { + return bytes.Buffer{}, bytes.Buffer{}, errors.Wrap(err, "creating run script mount") + } + args := append([]string{ "run", "--rm", "--init", "--cidfile", cidFile, "--workdir", scriptWorkDir, - "--mount", fmt.Sprintf("type=bind,source=%s,target=%s,ro", runScriptFile, containerTemp), + "--mount", runScriptMount, }, workspaceOpts...) if opts.ForceRoot { @@ -362,7 +372,11 @@ func executeSingleStep( } for target, source := range filesToMount { - args = append(args, "--mount", fmt.Sprintf("type=bind,source=%s,target=%s,ro", source.Name(), target)) + mountArg, err := dockerBindMount(source.Name(), target) + if err != nil { + return bytes.Buffer{}, bytes.Buffer{}, errors.Wrap(err, "creating files mount") + } + args = append(args, "--mount", mountArg) } // Mount any paths on the local system to the docker container. The paths have already been validated during parsing. @@ -371,7 +385,11 @@ func executeSingleStep( if err != nil { return bytes.Buffer{}, bytes.Buffer{}, err } - args = append(args, "--mount", fmt.Sprintf("type=bind,source=%s,target=%s,ro", workspaceFilePath, mount.Mountpoint)) + mountArg, err := dockerBindMount(workspaceFilePath, mount.Mountpoint) + if err != nil { + return bytes.Buffer{}, bytes.Buffer{}, errors.Wrap(err, "creating host mount") + } + args = append(args, "--mount", mountArg) } for k, v := range env { @@ -479,6 +497,8 @@ func setOutputs(stepOutputs batcheslib.Outputs, global map[string]any, stepCtx * return nil } +var containerTempPathPattern = regexp.MustCompile(`^/[A-Za-z0-9_./-]+$`) + func probeImageForShell(ctx context.Context, image string) (shell, tempfile string, err error) { // We need to know two things to be able to run a shell script: // @@ -508,9 +528,14 @@ func probeImageForShell(ctx context.Context, image string) (shell, tempfile stri if runErr := cmd.Run(); runErr != nil { err = errors.Append(err, errors.Wrapf(runErr, "probing shell %q:\n%s", shell, stderr.String())) } else { + tempfile, runErr = parseContainerTempPath(stdout.String()) + if runErr != nil { + err = errors.Append(err, errors.Wrapf(runErr, "probing shell %q", shell)) + continue + } + // Even if there were previous errors, we can now ignore them. err = nil - tempfile = strings.TrimSpace(stdout.String()) return } } @@ -520,6 +545,39 @@ func probeImageForShell(ctx context.Context, image string) (shell, tempfile stri return } +func parseContainerTempPath(output string) (string, error) { + // mktemp writes one path followed by a newline. Remove that one expected + // delimiter, then reject any additional output rather than allowing the + // image to inject Docker's comma-delimited mount grammar. + tempfile := strings.TrimSuffix(output, "\n") + if tempfile == "" { + return "", errors.New("mktemp returned an empty path") + } + if strings.ContainsAny(tempfile, "\r\n") { + return "", errors.New("mktemp returned more than one line") + } + if err := validateContainerTempPath(tempfile); err != nil { + return "", err + } + return tempfile, nil +} + +func validateContainerTempPath(tempfile string) error { + if !path.IsAbs(tempfile) || !containerTempPathPattern.MatchString(tempfile) { + return errors.Newf("mktemp returned invalid path %q", tempfile) + } + return nil +} + +func dockerBindMount(source, target string) (string, error) { + for name, value := range map[string]string{"source": source, "target": target} { + if value == "" || strings.ContainsAny(value, ",\r\n\x00") { + return "", errors.Newf("invalid Docker mount %s %q", name, value) + } + } + return fmt.Sprintf("type=bind,source=%s,target=%s,ro", source, target), nil +} + // createFilesToMount creates temporary files with the contents of Step.Files // that are to be mounted into the container that executes the step. func createFilesToMount(tempDir string, step batcheslib.Step, stepContext *template.StepContext) (map[string]*os.File, func(), error) { diff --git a/internal/batches/executor/run_steps_test.go b/internal/batches/executor/run_steps_test.go index 9af78eea0e..6b072d55c9 100644 --- a/internal/batches/executor/run_steps_test.go +++ b/internal/batches/executor/run_steps_test.go @@ -1,6 +1,10 @@ package executor import ( + "context" + "os" + "path/filepath" + "runtime" "testing" "github.com/stretchr/testify/require" @@ -9,6 +13,54 @@ import ( "github.com/sourcegraph/sourcegraph/lib/batches/template" ) +func TestParseContainerTempPath(t *testing.T) { + for _, valid := range []string{"/tmp/tmp.abc-123_456", "/tmp/tmp.abc-123_456\n"} { + t.Run("valid_"+valid, func(t *testing.T) { + got, err := parseContainerTempPath(valid) + require.NoError(t, err) + require.Equal(t, "/tmp/tmp.abc-123_456", got) + }) + } + + for _, invalid := range []string{ + "", + "\n", + "relative/path\n", + "/tmp/first\n/tmp/second\n", + "/tmp/path\r\n", + "/tmp/x,source=/var/run/docker.sock,target=/var/run/docker.sock\n", + "/tmp/path with spaces\n", + `/tmp/path"quoted`, + `/tmp/path\backslash`, + } { + t.Run("invalid_"+invalid, func(t *testing.T) { + _, err := parseContainerTempPath(invalid) + require.Error(t, err) + }) + } +} + +func TestProbeImageForShellRejectsMountInjection(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("test uses a shell script as a fake docker executable") + } + + dir := t.TempDir() + docker := filepath.Join(dir, "docker") + err := os.WriteFile(docker, []byte("#!/bin/sh\nprintf '%s\\n' '/tmp/x,source=/var/run/docker.sock,target=/var/run/docker.sock'\n"), 0o755) + require.NoError(t, err) + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) + + _, _, err = probeImageForShell(context.Background(), "malicious-image") + require.Error(t, err) + require.Contains(t, err.Error(), "mktemp returned invalid path") +} + +func TestDockerBindMountRejectsMountGrammar(t *testing.T) { + _, err := dockerBindMount("/tmp/script", "/tmp/x,source=/var/run/docker.sock") + require.Error(t, err) +} + func TestCreateFilesToMount_RejectsCommaInTargetPath(t *testing.T) { step := batcheslib.Step{ Files: map[string]string{ diff --git a/internal/batches/executor/testdata/dummydocker/docker b/internal/batches/executor/testdata/dummydocker/docker index b21ba30c29..0a82ca6a4b 100755 --- a/internal/batches/executor/testdata/dummydocker/docker +++ b/internal/batches/executor/testdata/dummydocker/docker @@ -7,7 +7,7 @@ # created a tempfile, or it executes the script supplied as the last arg to # "run". -dummy_temp_file="DUMMYDOCKER-TEMP-FILE" +dummy_temp_file="/tmp/DUMMYDOCKER-TEMP-FILE" workdir_prefix="/work/" From 1bb13627c9adb96c758ca8d47309c8c7dc2b69aa Mon Sep 17 00:00:00 2001 From: Carter Brainerd Date: Thu, 3 Sep 2026 13:55:27 -0400 Subject: [PATCH 614/647] fix/batches: reject Git metadata in repository archives (#1366) --- internal/batches/workspace/bind_workspace.go | 9 ++++++++ .../batches/workspace/bind_workspace_test.go | 23 +++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/internal/batches/workspace/bind_workspace.go b/internal/batches/workspace/bind_workspace.go index 3519e6f13c..c76a30ba60 100644 --- a/internal/batches/workspace/bind_workspace.go +++ b/internal/batches/workspace/bind_workspace.go @@ -206,6 +206,15 @@ func unzip(ctx context.Context, zipFile, dest string) error { return fmt.Errorf("%s: illegal file path", fpath) } + relativePath, err := filepath.Rel(dest, fpath) + if err != nil { + return err + } + firstPathElement, _, _ := strings.Cut(relativePath, string(os.PathSeparator)) + if strings.EqualFold(firstPathElement, ".git") { + return fmt.Errorf("%s: repository archive contains Git metadata", f.Name) + } + if f.FileInfo().IsDir() { if err := mkdirAll(dest, f.Name, 0777); err != nil { return err diff --git a/internal/batches/workspace/bind_workspace_test.go b/internal/batches/workspace/bind_workspace_test.go index 5fe05c2edf..c120eb0c11 100644 --- a/internal/batches/workspace/bind_workspace_test.go +++ b/internal/batches/workspace/bind_workspace_test.go @@ -143,6 +143,29 @@ func TestDockerBindWorkspaceCreator_Create(t *testing.T) { }) } +func TestUnzipRejectsGitMetadata(t *testing.T) { + for _, name := range []string{ + ".git/config", + ".git/hooks/pre-commit", + "dir/../.git/config", + ".GIT/config", + } { + t.Run(name, func(t *testing.T) { + archivePath := zipUpFiles(t, t.TempDir(), map[string]string{name: "malicious"}) + dest := t.TempDir() + + err := unzip(context.Background(), archivePath, dest) + if err == nil || !strings.Contains(err.Error(), "repository archive contains Git metadata") { + t.Fatalf("expected Git metadata error, got %v", err) + } + + if _, err := os.Stat(filepath.Join(dest, ".git")); !os.IsNotExist(err) { + t.Fatalf("expected .git not to be extracted, got %v", err) + } + }) + } +} + func TestDockerBindWorkspace_ApplyDiff(t *testing.T) { // Create a zip file for all the other tests to use. fakeFilesTmpDir := t.TempDir() From 3812c347fc053a7882ce5db752716bfdc1420143 Mon Sep 17 00:00:00 2001 From: Carter Brainerd Date: Thu, 3 Sep 2026 14:03:00 -0400 Subject: [PATCH 615/647] fix/batches: prevent repository archives from enabling Git hooks (#1367) --- internal/batches/workspace/bind_workspace.go | 9 ++++ .../batches/workspace/bind_workspace_test.go | 48 +++++++++++++++++++ internal/batches/workspace/git.go | 3 ++ internal/batches/workspace/git_test.go | 46 ++++++++++++++++++ 4 files changed, 106 insertions(+) create mode 100644 internal/batches/workspace/git_test.go diff --git a/internal/batches/workspace/bind_workspace.go b/internal/batches/workspace/bind_workspace.go index c76a30ba60..3068ec2240 100644 --- a/internal/batches/workspace/bind_workspace.go +++ b/internal/batches/workspace/bind_workspace.go @@ -190,6 +190,15 @@ func unzip(ctx context.Context, zipFile, dest string) error { } defer r.Close() + for _, f := range r.File { + // ZIP paths use forward slashes on every platform. Reject backslashes + // rather than letting Windows reinterpret a filename from a Unix + // repository as a directory hierarchy. + if strings.ContainsRune(f.Name, '\\') { + return fmt.Errorf("%q: illegal file path", f.Name) + } + } + outputBase := filepath.Clean(dest) + string(os.PathSeparator) for _, f := range r.File { diff --git a/internal/batches/workspace/bind_workspace_test.go b/internal/batches/workspace/bind_workspace_test.go index c120eb0c11..80ae000c03 100644 --- a/internal/batches/workspace/bind_workspace_test.go +++ b/internal/batches/workspace/bind_workspace_test.go @@ -166,6 +166,54 @@ func TestUnzipRejectsGitMetadata(t *testing.T) { } } +func TestUnzipRejectsUnsafeArchivePaths(t *testing.T) { + tests := []string{ + `.git\config`, + `hooks\pre-commit`, + } + + for _, name := range tests { + t.Run(name, func(t *testing.T) { + archivePath := zipUpFiles(t, t.TempDir(), map[string]string{name: "malicious"}) + dest := t.TempDir() + + if err := unzip(context.Background(), archivePath, dest); err == nil { + t.Fatal("expected unsafe archive path to be rejected") + } + + entries, err := os.ReadDir(dest) + if err != nil { + t.Fatal(err) + } + if len(entries) != 0 { + t.Fatalf("archive was partially extracted: %v", entries) + } + }) + } +} + +func TestUnzipAllowsSafeControlPaths(t *testing.T) { + files := map[string]string{ + ".git_config": "config", + "hooks_pre-commit": "hook", + } + archivePath := zipUpFiles(t, t.TempDir(), files) + dest := t.TempDir() + + if err := unzip(context.Background(), archivePath, dest); err != nil { + t.Fatal(err) + } + for name, want := range files { + have, err := os.ReadFile(filepath.Join(dest, name)) + if err != nil { + t.Fatal(err) + } + if string(have) != want { + t.Errorf("%s: got %q, want %q", name, have, want) + } + } +} + func TestDockerBindWorkspace_ApplyDiff(t *testing.T) { // Create a zip file for all the other tests to use. fakeFilesTmpDir := t.TempDir() diff --git a/internal/batches/workspace/git.go b/internal/batches/workspace/git.go index 20c20d1b07..8f59a282b6 100644 --- a/internal/batches/workspace/git.go +++ b/internal/batches/workspace/git.go @@ -9,6 +9,9 @@ import ( ) func runGitCmd(ctx context.Context, dir string, args ...string) ([]byte, error) { + // Repository contents are untrusted. Keep hooks disabled even if a command + // encounters an attacker-controlled local Git configuration. + args = append([]string{"-c", "core.hooksPath=/dev/null"}, args...) cmd := exec.CommandContext(ctx, "git", args...) cmd.Env = []string{ // Don't use the system wide git config. diff --git a/internal/batches/workspace/git_test.go b/internal/batches/workspace/git_test.go new file mode 100644 index 0000000000..f4cd887ca1 --- /dev/null +++ b/internal/batches/workspace/git_test.go @@ -0,0 +1,46 @@ +package workspace + +import ( + "context" + "os" + "path/filepath" + "testing" +) + +func TestRunGitCmdDisablesHooks(t *testing.T) { + dir := t.TempDir() + ctx := context.Background() + + if _, err := runGitCmd(ctx, dir, "init", "--quiet"); err != nil { + t.Fatal(err) + } + config, err := os.OpenFile(filepath.Join(dir, ".git", "config"), os.O_APPEND|os.O_WRONLY, 0) + if err != nil { + t.Fatal(err) + } + if _, err := config.WriteString("[core]\n\thooksPath = hooks\n"); err != nil { + t.Fatal(err) + } + if err := config.Close(); err != nil { + t.Fatal(err) + } + if err := os.Mkdir(filepath.Join(dir, "hooks"), 0755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "hooks", "pre-commit"), []byte("#!/bin/sh\necho hook-ran > hook-ran\n"), 0755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "README.md"), []byte("test\n"), 0644); err != nil { + t.Fatal(err) + } + + if _, err := runGitCmd(ctx, dir, "add", "README.md"); err != nil { + t.Fatal(err) + } + if _, err := runGitCmd(ctx, dir, "commit", "--quiet", "-m", "test"); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(filepath.Join(dir, "hook-ran")); !os.IsNotExist(err) { + t.Fatalf("pre-commit hook ran: %v", err) + } +} From e270bbe3781ea78356557c3d2668524c94ca4763 Mon Sep 17 00:00:00 2001 From: Carter Brainerd Date: Thu, 3 Sep 2026 14:53:12 -0400 Subject: [PATCH 616/647] fix/batch: prevent host execution through Git config (#1368) --- internal/batches/workspace/bind_workspace.go | 21 +++- .../batches/workspace/bind_workspace_test.go | 49 +++++++++ .../batches/workspace/executor_workspace.go | 10 +- internal/batches/workspace/git.go | 104 ++++++++++++++++++ 4 files changed, 180 insertions(+), 4 deletions(-) diff --git a/internal/batches/workspace/bind_workspace.go b/internal/batches/workspace/bind_workspace.go index 3068ec2240..8297c148c9 100644 --- a/internal/batches/workspace/bind_workspace.go +++ b/internal/batches/workspace/bind_workspace.go @@ -34,7 +34,12 @@ func (wc *dockerBindWorkspaceCreator) Create(ctx context.Context, repo *graphql. return nil, errors.Wrap(err, "copying additional files into workspace") } - return w, errors.Wrap(wc.prepareGitRepo(ctx, w), "preparing local git repo") + if err := wc.prepareGitRepo(ctx, w); err != nil { + return nil, errors.Wrap(err, "preparing local git repo") + } + + w.gitMetadata, err = snapshotGitMetadata(w.dir) + return w, errors.Wrap(err, "snapshotting local git metadata") } func (*dockerBindWorkspaceCreator) prepareGitRepo(ctx context.Context, w *dockerBindWorkspace) error { @@ -111,6 +116,10 @@ type dockerBindWorkspace struct { // This is also the path that is directly mounted into the docker // containers. dir string + // gitMetadata contains the trusted Git control files from before repository + // code runs. The bind-mounted repository can modify its Git metadata, so the + // snapshot must be restored before Git is run on the host. + gitMetadata *gitMetadataSnapshot } var _ Workspace = &dockerBindWorkspace{} @@ -129,6 +138,10 @@ func (w *dockerBindWorkspace) DockerRunOpts(ctx context.Context, target string) func (w *dockerBindWorkspace) WorkDir() *string { return &w.dir } func (w *dockerBindWorkspace) Diff(ctx context.Context) ([]byte, error) { + if err := w.gitMetadata.restore(w.dir); err != nil { + return nil, errors.Wrap(err, "restoring trusted git metadata") + } + if _, err := runGitCmd(ctx, w.dir, "add", "--all"); err != nil { return nil, errors.Wrap(err, "git add failed") } @@ -141,10 +154,14 @@ func (w *dockerBindWorkspace) Diff(ctx context.Context) ([]byte, error) { // // ATTENTION: When you change the options here, be sure to also update the // ApplyDiff method accordingly. - return runGitCmd(ctx, w.dir, "diff", "--cached", "--no-prefix", "--binary") + return runGitCmd(ctx, w.dir, "diff", "--cached", "--no-ext-diff", "--no-prefix", "--binary") } func (w *dockerBindWorkspace) ApplyDiff(ctx context.Context, diff []byte) error { + if err := w.gitMetadata.restore(w.dir); err != nil { + return errors.Wrap(err, "restoring trusted git metadata") + } + // Write the diff to a temp file so we can pass it to `git apply` tmp, err := os.CreateTemp(w.tempDir, "bind-workspace-test-*") if err != nil { diff --git a/internal/batches/workspace/bind_workspace_test.go b/internal/batches/workspace/bind_workspace_test.go index 80ae000c03..781cff8261 100644 --- a/internal/batches/workspace/bind_workspace_test.go +++ b/internal/batches/workspace/bind_workspace_test.go @@ -143,6 +143,55 @@ func TestDockerBindWorkspaceCreator_Create(t *testing.T) { }) } +func TestDockerBindWorkspace_DiffRestoresTrustedGitConfig(t *testing.T) { + archivePath := zipUpFiles(t, t.TempDir(), map[string]string{ + "tracked.txt": "before\n", + }) + creator := &dockerBindWorkspaceCreator{Dir: t.TempDir()} + workspace, err := creator.Create(context.Background(), repo, nil, &fakeRepoArchive{mockPath: archivePath}) + if err != nil { + t.Fatal(err) + } + + dir := *workspace.WorkDir() + configPath := filepath.Join(dir, ".git", "config") + trustedConfig, err := os.ReadFile(configPath) + if err != nil { + t.Fatal(err) + } + config, err := os.OpenFile(configPath, os.O_APPEND|os.O_WRONLY, 0) + if err != nil { + t.Fatal(err) + } + if _, err := config.WriteString("[diff]\n\texternal = command-that-must-not-run\n[filter \"attack\"]\n\tclean = command-that-must-not-run\n"); err != nil { + t.Fatal(err) + } + if err := config.Close(); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, ".gitattributes"), []byte("*.txt filter=attack\n"), 0644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "tracked.txt"), []byte("after\n"), 0644); err != nil { + t.Fatal(err) + } + + diff, err := workspace.Diff(context.Background()) + if err != nil { + t.Fatalf("Diff executed untrusted Git configuration: %s", err) + } + if !strings.Contains(string(diff), "+after") { + t.Fatalf("diff does not contain tracked change:\n%s", diff) + } + restoredConfig, err := os.ReadFile(configPath) + if err != nil { + t.Fatal(err) + } + if !cmp.Equal(restoredConfig, trustedConfig) { + t.Fatalf("Git config was not restored:\n%s", cmp.Diff(string(trustedConfig), string(restoredConfig))) + } +} + func TestUnzipRejectsGitMetadata(t *testing.T) { for _, name := range []string{ ".git/config", diff --git a/internal/batches/workspace/executor_workspace.go b/internal/batches/workspace/executor_workspace.go index d682d46578..f6c4366755 100644 --- a/internal/batches/workspace/executor_workspace.go +++ b/internal/batches/workspace/executor_workspace.go @@ -24,10 +24,16 @@ type executorWorkspaceCreator struct { var _ Creator = &executorWorkspaceCreator{} func (wc *executorWorkspaceCreator) Create(ctx context.Context, repo *graphql.Repository, steps []batcheslib.Step, archive repozip.Archive) (Workspace, error) { + gitMetadata, err := snapshotGitMetadata(wc.RepoDir) + if err != nil { + return nil, err + } + return &dockerBindExecutorWorkspace{ dockerBindWorkspace: dockerBindWorkspace{ - tempDir: wc.TempDir, - dir: wc.RepoDir, + tempDir: wc.TempDir, + dir: wc.RepoDir, + gitMetadata: gitMetadata, }, }, nil } diff --git a/internal/batches/workspace/git.go b/internal/batches/workspace/git.go index 8f59a282b6..43c1c8ba70 100644 --- a/internal/batches/workspace/git.go +++ b/internal/batches/workspace/git.go @@ -2,12 +2,116 @@ package workspace import ( "context" + "fmt" + "os" "os/exec" + "path/filepath" "strings" "github.com/sourcegraph/sourcegraph/lib/errors" ) +type gitMetadataSnapshot struct { + dotGit *gitControlFile + config *gitControlFile + configWorktree *gitControlFile +} + +type gitControlFile struct { + contents []byte + mode os.FileMode +} + +func snapshotGitMetadata(dir string) (*gitMetadataSnapshot, error) { + dotGit := filepath.Join(dir, ".git") + info, err := os.Lstat(dotGit) + if err != nil { + return nil, err + } + + snapshot := &gitMetadataSnapshot{} + switch { + case info.Mode().IsRegular(): + snapshot.dotGit, err = snapshotGitControlFile(dotGit) + case info.IsDir(): + snapshot.config, err = snapshotGitControlFile(filepath.Join(dotGit, "config")) + if err == nil { + snapshot.configWorktree, err = snapshotOptionalGitControlFile(filepath.Join(dotGit, "config.worktree")) + } + default: + return nil, fmt.Errorf("%s is not a regular file or directory", dotGit) + } + if err != nil { + return nil, err + } + return snapshot, nil +} + +func snapshotOptionalGitControlFile(path string) (*gitControlFile, error) { + file, err := snapshotGitControlFile(path) + if os.IsNotExist(err) { + return nil, nil + } + return file, err +} + +func snapshotGitControlFile(path string) (*gitControlFile, error) { + info, err := os.Lstat(path) + if err != nil { + return nil, err + } + if !info.Mode().IsRegular() { + return nil, fmt.Errorf("%s is not a regular file", path) + } + contents, err := os.ReadFile(path) + if err != nil { + return nil, err + } + return &gitControlFile{contents: contents, mode: info.Mode()}, nil +} + +func (s *gitMetadataSnapshot) restore(dir string) error { + if s == nil { + return nil + } + + dotGit := filepath.Join(dir, ".git") + if s.dotGit != nil { + return restoreGitControlFile(dotGit, s.dotGit) + } + + info, err := os.Lstat(dotGit) + if err != nil { + return err + } + if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { + return fmt.Errorf("%s is no longer a directory", dotGit) + } + if err := restoreGitControlFile(filepath.Join(dotGit, "config"), s.config); err != nil { + return err + } + return restoreGitControlFile(filepath.Join(dotGit, "config.worktree"), s.configWorktree) +} + +func restoreGitControlFile(path string, snapshot *gitControlFile) error { + if err := os.Remove(path); err != nil && !os.IsNotExist(err) { + return err + } + if snapshot == nil { + return nil + } + + file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, snapshot.mode.Perm()) + if err != nil { + return err + } + if _, err := file.Write(snapshot.contents); err != nil { + file.Close() + return err + } + return file.Close() +} + func runGitCmd(ctx context.Context, dir string, args ...string) ([]byte, error) { // Repository contents are untrusted. Keep hooks disabled even if a command // encounters an attacker-controlled local Git configuration. From 0adbf30c8f6f2517b456cd387a27d84c9f593353 Mon Sep 17 00:00:00 2001 From: Michael Bahr <1830132+bahrmichael@users.noreply.github.com> Date: Fri, 4 Sep 2026 13:03:19 +0200 Subject: [PATCH 617/647] Point stale docs.sourcegraph.com links at sourcegraph.com/docs (#1364) * Rewrite docs.sourcegraph.com links to sourcegraph.com/docs * Remove dead links to deleted Sourcegraph dev docs The testing principles, Go testing, telemetry, and CSRF security model pages no longer exist on sourcegraph.com/docs. Replace the links with plain text and inline the relevant context in the code comment. Co-Authored-By: Claude Fable 5.1 --------- Co-authored-by: Claude Fable 5.1 --- DEVELOPMENT.md | 2 +- README.md | 8 ++++---- cmd/src/search.go | 2 +- internal/api/flags.go | 2 +- internal/batches/ui/tui.go | 2 +- internal/clicompat/api_flags.go | 2 +- internal/users/admin.go | 5 +++-- 7 files changed, 12 insertions(+), 11 deletions(-) diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index 29a600ba71..7b005e24de 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -62,7 +62,7 @@ For quick end-to-end CLI sanity checks against a live Sourcegraph instance, run: This script intentionally uses your currently exported `SRC_*` environment variables, is not hooked up to CI, and is meant for manual regression checks (for example, to catch issues like `src users list` failing unexpectedly). -We adhere to the [general Sourcegraph principles for testing](https://docs.sourcegraph.com/dev/background-information/testing_principles), as well as [the Go specific directions](https://docs.sourcegraph.com/dev/background-information/languages/testing_go_code), at least to the extent they apply to a standalone tool like `src`. +We adhere to the general Sourcegraph principles for testing, as well as the Go specific directions used in the main Sourcegraph repository, at least to the extent they apply to a standalone tool like `src`. ## Releasing diff --git a/README.md b/README.md index 653942aed1..37100691a3 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ - **Search & get results in your terminal** - **Search & get JSON** for programmatic consumption - Make **GraphQL API requests** with auth easily & get JSON back fast -- Execute **[batch changes](https://docs.sourcegraph.com/batch_changes)** +- Execute **[batch changes](https://sourcegraph.com/docs/batch_changes)** - **Manage & administrate** repositories, users, and more - **Easily convert src-CLI commands to equivalent curl commands**, just add --get-curl! @@ -173,7 +173,7 @@ Is your Sourcegraph instance behind a custom auth proxy? See [auth proxy configu - `src auth` - print the active authentication token or authorization header - `src search` - perform searches and get results in your terminal or as JSON - `src api` - run Sourcegraph GraphQL API requests - - `src batch` - execute and manage [batch changes](https://docs.sourcegraph.com/batch_changes) + - `src batch` - execute and manage [batch changes](https://sourcegraph.com/docs/batch_changes) - `src repos` - manage repositories - `src users` - manage users - `src orgs` - manages organization @@ -185,7 +185,7 @@ Is your Sourcegraph instance behind a custom auth proxy? See [auth proxy configu - `src version` - check version and guaranteed-compatible version for your Sourcegraph instance Run `src -h` and `src -h` for more detailed usage information. -You can also read the [usage docs for the latest version of `src-cli`](https://docs.sourcegraph.com/cli/references) online. +You can also read the [usage docs for the latest version of `src-cli`](https://sourcegraph.com/docs/cli/references) online. #### Optional: Renaming `src` @@ -211,7 +211,7 @@ src-cli/3.21.10 linux amd64 To disable this and _only_ send the version, you can set `-user-agent-telemetry=false` for a single command, or set the `SRC_DISABLE_USER_AGENT_TELEMETRY` environment variable to any non-blank string. -As with [other Sourcegraph telemetry](https://docs.sourcegraph.com/dev/background-information/telemetry), any collected data is only sent to Sourcegraph.com in aggregate form. +As with other Sourcegraph telemetry, any collected data is only sent to Sourcegraph.com in aggregate form. ## Development diff --git a/cmd/src/search.go b/cmd/src/search.go index a2cd1a0bbe..9cbb050a4d 100644 --- a/cmd/src/search.go +++ b/cmd/src/search.go @@ -48,7 +48,7 @@ Other tips: Force color output on (not on by default when piped to other programs) by setting COLOR=t - Query syntax: https://docs.sourcegraph.com/code_search/reference/queries + Query syntax: https://sourcegraph.com/docs/code_search/reference/queries Be careful with search strings including negation: a search with an initial negated term may be parsed as a flag rather than as a search string. You can diff --git a/internal/api/flags.go b/internal/api/flags.go index be2397e818..3954982e75 100644 --- a/internal/api/flags.go +++ b/internal/api/flags.go @@ -42,7 +42,7 @@ func NewFlags(flagSet *flag.FlagSet) *Flags { return &Flags{ dump: flagSet.Bool("dump-requests", false, "Log GraphQL requests and responses to stdout"), getCurl: flagSet.Bool("get-curl", false, "Print the curl command for executing this query and exit (WARNING: includes printing your access token!)"), - trace: flagSet.Bool("trace", false, "Log the trace ID for requests. See https://docs.sourcegraph.com/admin/observability/tracing"), + trace: flagSet.Bool("trace", false, "Log the trace ID for requests. See https://sourcegraph.com/docs/admin/observability/tracing"), insecureSkipVerify: flagSet.Bool("insecure-skip-verify", false, "Skip validation of TLS certificates against trusted chains"), userAgentTelemetry: flagSet.Bool("user-agent-telemetry", defaultUserAgentTelemetry(), "Include the operating system and architecture in the User-Agent sent with requests to Sourcegraph"), } diff --git a/internal/batches/ui/tui.go b/internal/batches/ui/tui.go index 405918909e..9666349a14 100644 --- a/internal/batches/ui/tui.go +++ b/internal/batches/ui/tui.go @@ -400,7 +400,7 @@ func printExecutionError(out *output.Output, err error) { out.Write("") block := out.Block(output.Line(output.EmojiLightbulb, output.StyleSuggestion, "The troubleshooting documentation can help to narrow down the cause of the errors:")) - block.WriteLine(output.Line("", output.StyleSuggestion, "https://docs.sourcegraph.com/batch_changes/references/troubleshooting")) + block.WriteLine(output.Line("", output.StyleSuggestion, "https://sourcegraph.com/docs/batch_changes/references/troubleshooting")) block.Close() } diff --git a/internal/clicompat/api_flags.go b/internal/clicompat/api_flags.go index 736d9997cb..0cc627ce59 100644 --- a/internal/clicompat/api_flags.go +++ b/internal/clicompat/api_flags.go @@ -16,7 +16,7 @@ func WithAPIFlags(baseFlags ...cli.Flag) []cli.Flag { }{ {"dump-requests", false, "Log GraphQL requests and responses to stdout"}, {"get-curl", false, "Print the curl command for executing this query and exit (WARNING: includes printing your access token!)"}, - {"trace", false, "Log the trace ID for requests. See https://docs.sourcegraph.com/admin/observability/tracing"}, + {"trace", false, "Log the trace ID for requests. See https://sourcegraph.com/docs/admin/observability/tracing"}, {"insecure-skip-verify", false, "Skip validation of TLS certificates against trusted chains"}, {"user-agent-telemetry", defaultAPIUserAgentTelemetry(), "Include the operating system and architecture in the User-Agent sent with requests to Sourcegraph"}, } diff --git a/internal/users/admin.go b/internal/users/admin.go index 6840f9f22c..8ba706b5af 100644 --- a/internal/users/admin.go +++ b/internal/users/admin.go @@ -261,8 +261,9 @@ func (c *Client) GraphQL(token, query string, variables map[string]any, target a if token != "" { req.Header.Set("Authorization", fmt.Sprintf("token %s", token)) } else { - // NOTE: This header is required to authenticate our session with a session cookie, see: - // https://docs.sourcegraph.com/dev/security/csrf_security_model#authentication-in-api-endpoints + // NOTE: This header is required to authenticate our session with a session + // cookie. Sourcegraph's CSRF protection rejects cookie-authenticated API + // requests that do not carry this header. req.Header.Set("X-Requested-With", "Sourcegraph") req.AddCookie(c.sessionCookie) From 2b1394e61aa248470eb4930a73dd89fc447d3baf Mon Sep 17 00:00:00 2001 From: Carter Brainerd Date: Fri, 4 Sep 2026 10:43:24 -0400 Subject: [PATCH 618/647] fix/batches: discard extracted Git metadata before Git initialization (#1370) --- internal/batches/workspace/bind_workspace.go | 7 ++++ .../batches/workspace/bind_workspace_test.go | 41 +++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/internal/batches/workspace/bind_workspace.go b/internal/batches/workspace/bind_workspace.go index 8297c148c9..b925c57080 100644 --- a/internal/batches/workspace/bind_workspace.go +++ b/internal/batches/workspace/bind_workspace.go @@ -43,6 +43,13 @@ func (wc *dockerBindWorkspaceCreator) Create(ctx context.Context, repo *graphql. } func (*dockerBindWorkspaceCreator) prepareGitRepo(ctx context.Context, w *dockerBindWorkspace) error { + // Windows can normalize archive entry names such as ".git." to ".git". + // Always discard extracted Git metadata before running Git so repository + // contents cannot configure commands that execute on the host. + if err := os.RemoveAll(filepath.Join(w.dir, ".git")); err != nil { + return errors.Wrap(err, "removing extracted git metadata") + } + if _, err := runGitCmd(ctx, w.dir, "init"); err != nil { return errors.Wrap(err, "git init failed") } diff --git a/internal/batches/workspace/bind_workspace_test.go b/internal/batches/workspace/bind_workspace_test.go index 781cff8261..1048276c69 100644 --- a/internal/batches/workspace/bind_workspace_test.go +++ b/internal/batches/workspace/bind_workspace_test.go @@ -143,6 +143,47 @@ func TestDockerBindWorkspaceCreator_Create(t *testing.T) { }) } +func TestPrepareGitRepoRemovesUntrustedGitMetadata(t *testing.T) { + dir := t.TempDir() + dotGit := filepath.Join(dir, ".git") + if err := os.Mkdir(dotGit, 0755); err != nil { + t.Fatal(err) + } + maliciousConfig := "[core]\n\trepositoryformatversion = 0\n\tbare = false\n\tfsmonitor = ./fsmonitor\n" + if err := os.WriteFile(filepath.Join(dotGit, "config"), []byte(maliciousConfig), 0644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dotGit, "attacker-controlled"), nil, 0644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "fsmonitor"), []byte("#!/bin/sh\ntouch fsmonitor-ran\n"), 0755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "tracked.txt"), []byte("tracked\n"), 0644); err != nil { + t.Fatal(err) + } + + creator := &dockerBindWorkspaceCreator{} + workspace := &dockerBindWorkspace{dir: dir} + if err := creator.prepareGitRepo(context.Background(), workspace); err != nil { + t.Fatal(err) + } + + if _, err := os.Stat(filepath.Join(dir, "fsmonitor-ran")); !os.IsNotExist(err) { + t.Fatalf("fsmonitor command ran on the host: %v", err) + } + if _, err := os.Stat(filepath.Join(dotGit, "attacker-controlled")); !os.IsNotExist(err) { + t.Fatalf("untrusted Git metadata was preserved: %v", err) + } + config, err := os.ReadFile(filepath.Join(dotGit, "config")) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(config), "fsmonitor") { + t.Fatalf("untrusted Git config was preserved:\n%s", config) + } +} + func TestDockerBindWorkspace_DiffRestoresTrustedGitConfig(t *testing.T) { archivePath := zipUpFiles(t, t.TempDir(), map[string]string{ "tracked.txt": "before\n", From 695e69c4ee0579454df6f7182edffa65a7bb0b4c Mon Sep 17 00:00:00 2001 From: Marc <7050295+marcleblanc2@users.noreply.github.com> Date: Fri, 4 Sep 2026 08:52:01 -0600 Subject: [PATCH 619/647] fix/docs: Fix spelling errors in the documentation (#1369) Corrects prose typos found by codespell. Code samples, CLI flags, config keys, YAML keys and values, URLs, identifiers, and quoted output are unchanged, and generated or vendored files are skipped. Co-authored-by: sourcegraph-commit-signing-s2[bot] <292215795+sourcegraph-commit-signing-s2[bot]@users.noreply.github.com> --- CHANGELOG.md | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 87221c00fc..7caabd95d7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -46,7 +46,7 @@ All notable changes to `src-cli` are documented in this file. ### Added -- SBOM support: Added `--image` and `--exclude-image` flags to `src sbom fetch` for filtering which docker images SBOMs are fetched for. Both flags support glob patterns (e.g., `frontend`, `*api*`) and comma-separated lists. The `sourcegraph/` image name prefix is optional. +- SBOM support: Added `--image` and `--exclude-image` flags to `src sbom fetch` for filtering which Docker images SBOMs are fetched for. Both flags support glob patterns (e.g., `frontend`, `*api*`) and comma-separated lists. The `sourcegraph/` image name prefix is optional. ### Changed @@ -88,7 +88,7 @@ All notable changes to `src-cli` are documented in this file. ## 5.10.0 - cody gateway benchmark changes -- fix local builds for non sourcegraph team [1121](https://github.com/sourcegraph/src-cli/pull/1121) +- fix local builds for non Sourcegraph team [1121](https://github.com/sourcegraph/src-cli/pull/1121) ## 5.9.1 @@ -166,7 +166,7 @@ All notable changes to `src-cli` are documented in this file. ### Fixed -- The fork attribute in changesetTemplate is now acknowleged when creating a batch change via `src-cli`. [#58156](https://github.com/sourcegraph/sourcegraph/pull/58156) +- The fork attribute in changesetTemplate is now acknowledged when creating a batch change via `src-cli`. [#58156](https://github.com/sourcegraph/sourcegraph/pull/58156) ## 5.2.0 @@ -182,7 +182,7 @@ All notable changes to `src-cli` are documented in this file. ### Fixed -- The temporary docker volume created during workspace preparation is now cleaned up when failure occurs. [#1021](https://github.com/sourcegraph/src-cli/pull/1021). +- The temporary Docker volume created during workspace preparation is now cleaned up when failure occurs. [#1021](https://github.com/sourcegraph/src-cli/pull/1021). ## 5.1.1 @@ -268,7 +268,7 @@ No noteworthy changes, mechanical release to match Sourcegraph release. ### Fixed -- Fix network timeout in `src users clean` occuring in instances with many users [#901](https://github.com/sourcegraph/src-cli/pull/901) +- Fix network timeout in `src users clean` occurring in instances with many users [#901](https://github.com/sourcegraph/src-cli/pull/901) - Aligned parsing of spec file parameter of `src batch repos` with other commands. [#919](https://github.com/sourcegraph/src-cli/pull/919) - Remove empty log outputs during batch spec execution. [#923](https://github.com/sourcegraph/src-cli/pull/923) @@ -280,7 +280,7 @@ No noteworthy changes, mechanical release to match Sourcegraph release. ### Added -- Batch Changes: Watchdog that checks for docker responsiveness while running commands has been added. [#898](https://github.com/sourcegraph/src-cli/pull/898) +- Batch Changes: Watchdog that checks for Docker responsiveness while running commands has been added. [#898](https://github.com/sourcegraph/src-cli/pull/898) ## 4.2.1 @@ -309,7 +309,7 @@ No noteworthy changes, mechanical release to match Sourcegraph release. ### Changed -- Improved output for failing docker pulls in batch change execution. [#880](https://github.com/sourcegraph/src-cli/pull/880) +- Improved output for failing Docker pulls in batch change execution. [#880](https://github.com/sourcegraph/src-cli/pull/880) ## 4.1.0 @@ -796,7 +796,7 @@ Re-release of 3.29.3 for Sourcegraph 3.30. ### Fixed -- When specifying `-skip-errors`, the batch spec would always be empty. This ix fixed and the intended behavior has been restored. [#539](https://github.com/sourcegraph/src-cli/pull/539) +- When specifying `-skip-errors`, the batch spec would always be empty. This is fixed and the intended behavior has been restored. [#539](https://github.com/sourcegraph/src-cli/pull/539) ## 3.27.0 @@ -871,13 +871,13 @@ Re-release of 3.29.3 for Sourcegraph 3.30. ### Fixed -- The homebrew recipe for `src-cli` contained the wrong binary name. +- The Homebrew recipe for `src-cli` contained the wrong binary name. ## 3.24.6 ### Fixed -- Workspaces could sometimes fail with docker bind mount errors, due to a race condition of multiple workspaces accessing the same auxilliary files. [#468](https://github.com/sourcegraph/src-cli/pull/468) +- Workspaces could sometimes fail with Docker bind mount errors, due to a race condition of multiple workspaces accessing the same auxiliary files. [#468](https://github.com/sourcegraph/src-cli/pull/468) ## 3.24.5 @@ -1153,7 +1153,7 @@ Re-release of 3.29.3 for Sourcegraph 3.30. - Add `--no-progress` flag to the `lsif upload` command to disable verbose output in non-TTY environments. - `SRC_HEADER_AUTHORIZATION="Bearer $(...)"` is now supported for authenticating `src` with custom auth proxies. See [auth proxy configuration docs](AUTH_PROXY.md) for more information. [#239](https://github.com/sourcegraph/src-cli/pull/239) -- Pull missing docker images automatically. [#191](https://github.com/sourcegraph/src-cli/pull/191) +- Pull missing Docker images automatically. [#191](https://github.com/sourcegraph/src-cli/pull/191) - Searches that result in errors will now display any alerts returned by Sourcegraph, including suggestions for how the search could be corrected. [#221](https://github.com/sourcegraph/src-cli/pull/221) ### Changed From ba67acb76365ed8342b5428f195c58b69b7fe801 Mon Sep 17 00:00:00 2001 From: Carter Brainerd Date: Tue, 8 Sep 2026 13:02:57 -0400 Subject: [PATCH 620/647] fix/serve-git: reject gitdir file repository targets (#1365) --- internal/servegit/gitservice.go | 7 ++++- internal/servegit/serve_test.go | 46 +++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) diff --git a/internal/servegit/gitservice.go b/internal/servegit/gitservice.go index 63778d6049..f7c161a6e0 100644 --- a/internal/servegit/gitservice.go +++ b/internal/servegit/gitservice.go @@ -105,13 +105,18 @@ func (s *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { http.Error(w, "invalid path specified: "+err.Error(), http.StatusBadRequest) return } - if _, err = s.RootFS.Stat(relDir); os.IsNotExist(err) { + info, err := s.RootFS.Stat(relDir) + if os.IsNotExist(err) { http.Error(w, "repository not found", http.StatusNotFound) return } else if err != nil { http.Error(w, "failed to stat repo: "+err.Error(), http.StatusInternalServerError) return } + if !info.IsDir() { + http.Error(w, "repository not found", http.StatusNotFound) + return + } body := r.Body defer body.Close() diff --git a/internal/servegit/serve_test.go b/internal/servegit/serve_test.go index 8ae6bc6644..7cc7a29ac0 100644 --- a/internal/servegit/serve_test.go +++ b/internal/servegit/serve_test.go @@ -69,6 +69,52 @@ func TestReposHandler(t *testing.T) { } } +func TestHandlerRejectsGitdirFile(t *testing.T) { + root := t.TempDir() + servedRoot := filepath.Join(root, "served") + publicRepo := filepath.Join(servedRoot, "public") + privateRepo := filepath.Join(root, "private") + for _, repo := range []string{publicRepo, privateRepo} { + if err := os.MkdirAll(repo, 0755); err != nil { + t.Fatal(err) + } + } + gitInit(t, publicRepo) + gitInit(t, privateRepo) + + pointer := filepath.Join(publicRepo, "gitdir-pointer") + if err := os.WriteFile(pointer, []byte("gitdir: ../../private/.git\n"), 0644); err != nil { + t.Fatal(err) + } + runCmd(t, publicRepo, "git", "add", "gitdir-pointer") + runCmd(t, publicRepo, "git", "commit", "-m", "add gitdir pointer") + runCmd(t, privateRepo, "git", "commit", "--allow-empty", "-m", "private commit") + // Git accepts this ordinary tracked file as a repository and follows its + // gitdir pointer outside servedRoot. + runCmd(t, publicRepo, "git", "upload-pack", "--strict", "--advertise-refs", pointer) + + rootFS, err := os.OpenRoot(servedRoot) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { rootFS.Close() }) + + h := (&Serve{ + Info: testLogger(t), + Debug: discardLogger, + Addr: testAddress, + Root: servedRoot, + RootFS: rootFS, + }).handler() + req := httptest.NewRequest(http.MethodGet, "/repos/public/gitdir-pointer/info/refs?service=git-upload-pack", nil) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + + if rec.Code != http.StatusNotFound { + t.Fatalf("gitdir file status = %d, want %d; body: %s", rec.Code, http.StatusNotFound, rec.Body.String()) + } +} + func testReposHandler(t *testing.T, h http.Handler, repos []Repo) { ts := httptest.NewServer(h) t.Cleanup(ts.Close) From 4d07a319c882022b37120bd75cf5f25f69e688ca Mon Sep 17 00:00:00 2001 From: Carter Brainerd Date: Wed, 9 Sep 2026 09:33:31 -0400 Subject: [PATCH 621/647] fix/batches: prevent Git commondir config bypass (#1371) ## Problem A batch container can create a `.git/commondir` file that points Git to an attacker-controlled directory. The existing metadata restoration only restores `.git/config` and `.git/config.worktree`, so host-side Git commands can still read malicious configuration from the redirected directory. A malicious clean filter can then run code on the host outside the container. This fixes [VULN-153](https://linear.app/sourcegraph/issue/VULN-153/gitcommondir-bypasses-git-config-restoration-and-achieves-host-rce). ## Solution Snapshot `.git/commondir` with the other trusted Git control files and restore it before every host-side Git command. If the original repository did not have a `commondir` file, an injected file is removed before Git runs. The regression test creates an attacker-controlled common directory with a malicious clean filter and verifies that diff generation uses the trusted Git configuration instead. ## Verification Evidence - `go test ./internal/batches/workspace -count=1` - `go test ./internal/batches/...` - `git diff --check` --- .../batches/workspace/bind_workspace_test.go | 26 ++++++++++++++++++- internal/batches/workspace/git.go | 11 +++++++- 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/internal/batches/workspace/bind_workspace_test.go b/internal/batches/workspace/bind_workspace_test.go index 1048276c69..b8c32e929c 100644 --- a/internal/batches/workspace/bind_workspace_test.go +++ b/internal/batches/workspace/bind_workspace_test.go @@ -195,7 +195,8 @@ func TestDockerBindWorkspace_DiffRestoresTrustedGitConfig(t *testing.T) { } dir := *workspace.WorkDir() - configPath := filepath.Join(dir, ".git", "config") + dotGit := filepath.Join(dir, ".git") + configPath := filepath.Join(dotGit, "config") trustedConfig, err := os.ReadFile(configPath) if err != nil { t.Fatal(err) @@ -210,6 +211,26 @@ func TestDockerBindWorkspace_DiffRestoresTrustedGitConfig(t *testing.T) { if err := config.Close(); err != nil { t.Fatal(err) } + + // A commondir file redirects Git to the config in another directory. That + // config must not survive metadata restoration and reach host-side Git. + attackerCommon := filepath.Join(dir, "attacker-common") + if err := os.CopyFS(attackerCommon, os.DirFS(dotGit)); err != nil { + t.Fatal(err) + } + attackerConfig, err := os.OpenFile(filepath.Join(attackerCommon, "config"), os.O_APPEND|os.O_WRONLY, 0) + if err != nil { + t.Fatal(err) + } + if _, err := attackerConfig.WriteString("[filter \"attack\"]\n\tclean = command-that-must-not-run\n\trequired = true\n"); err != nil { + t.Fatal(err) + } + if err := attackerConfig.Close(); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dotGit, "commondir"), []byte("../attacker-common\n"), 0644); err != nil { + t.Fatal(err) + } if err := os.WriteFile(filepath.Join(dir, ".gitattributes"), []byte("*.txt filter=attack\n"), 0644); err != nil { t.Fatal(err) } @@ -231,6 +252,9 @@ func TestDockerBindWorkspace_DiffRestoresTrustedGitConfig(t *testing.T) { if !cmp.Equal(restoredConfig, trustedConfig) { t.Fatalf("Git config was not restored:\n%s", cmp.Diff(string(trustedConfig), string(restoredConfig))) } + if _, err := os.Stat(filepath.Join(dotGit, "commondir")); !os.IsNotExist(err) { + t.Fatalf("untrusted commondir was not removed: %v", err) + } } func TestUnzipRejectsGitMetadata(t *testing.T) { diff --git a/internal/batches/workspace/git.go b/internal/batches/workspace/git.go index 43c1c8ba70..c028759f72 100644 --- a/internal/batches/workspace/git.go +++ b/internal/batches/workspace/git.go @@ -13,6 +13,7 @@ import ( type gitMetadataSnapshot struct { dotGit *gitControlFile + commonDir *gitControlFile config *gitControlFile configWorktree *gitControlFile } @@ -34,7 +35,10 @@ func snapshotGitMetadata(dir string) (*gitMetadataSnapshot, error) { case info.Mode().IsRegular(): snapshot.dotGit, err = snapshotGitControlFile(dotGit) case info.IsDir(): - snapshot.config, err = snapshotGitControlFile(filepath.Join(dotGit, "config")) + snapshot.commonDir, err = snapshotOptionalGitControlFile(filepath.Join(dotGit, "commondir")) + if err == nil { + snapshot.config, err = snapshotGitControlFile(filepath.Join(dotGit, "config")) + } if err == nil { snapshot.configWorktree, err = snapshotOptionalGitControlFile(filepath.Join(dotGit, "config.worktree")) } @@ -87,6 +91,11 @@ func (s *gitMetadataSnapshot) restore(dir string) error { if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { return fmt.Errorf("%s is no longer a directory", dotGit) } + // commondir changes which repository config Git reads. Restore it before + // any host-side Git command can follow an attacker-controlled redirect. + if err := restoreGitControlFile(filepath.Join(dotGit, "commondir"), s.commonDir); err != nil { + return err + } if err := restoreGitControlFile(filepath.Join(dotGit, "config"), s.config); err != nil { return err } From ed0828d7bcf8f4c1740d9a93bc42c899e3bd1a7e Mon Sep 17 00:00:00 2001 From: Carter Brainerd Date: Wed, 9 Sep 2026 09:42:42 -0400 Subject: [PATCH 622/647] fix/batches: prevent executor environment leakage to steps (#1374) ## Problem Batch steps can request environment variables by name. The executor passed its full process environment into this resolver, so a step could request reserved `SRC_EXECUTOR_*` values. These values include executor control credentials that must not be available inside an ordinary batch step. This fixes [VULN-141](https://linear.app/sourcegraph/issue/VULN-141/i-can-use-a-reserved-executor-bearer-from-a-normal-v2-batch-step-to). ## Solution Filter the reserved `SRC_EXECUTOR_*` namespace from the outer environment before resolving step variables. The filter is applied at the step execution boundary, so it covers every caller and also protects future variables in the reserved namespace. Normal environment variables and explicit step values continue to work. ## Verification Evidence - Added a regression test showing that normal outer variables still resolve. - Added coverage showing that current and future `SRC_EXECUTOR_*` outer variables resolve to empty values. - `go test ./internal/batches/...` - `go test ./cmd/src` --- internal/batches/executor/run_steps.go | 16 +++++++++-- internal/batches/executor/run_steps_test.go | 32 +++++++++++++++++++++ 2 files changed, 46 insertions(+), 2 deletions(-) diff --git a/internal/batches/executor/run_steps.go b/internal/batches/executor/run_steps.go index 6b6a61788e..4dfeb14e63 100644 --- a/internal/batches/executor/run_steps.go +++ b/internal/batches/executor/run_steps.go @@ -316,8 +316,9 @@ func executeSingleStep( } defer cleanup() - // Resolve step.Env given the current environment. - stepEnv, err := step.Env.Resolve(opts.GlobalEnv) + // Resolve step.Env given the current environment. Executor control values + // must never be selectable by an author-controlled step. + stepEnv, err := step.Env.Resolve(withoutReservedExecutorEnv(opts.GlobalEnv)) if err != nil { err = errors.Wrap(err, "resolving step environment") opts.UI.StepPreparingFailed(stepIdx+1, err) @@ -464,6 +465,17 @@ func executeSingleStep( return stdout, stderr, nil } +func withoutReservedExecutorEnv(env []string) []string { + filtered := make([]string, 0, len(env)) + for _, variable := range env { + name, _, found := strings.Cut(variable, "=") + if !found || !strings.HasPrefix(name, "SRC_EXECUTOR_") { + filtered = append(filtered, variable) + } + } + return filtered +} + func setOutputs(stepOutputs batcheslib.Outputs, global map[string]any, stepCtx *template.StepContext) error { for name, output := range stepOutputs { var value bytes.Buffer diff --git a/internal/batches/executor/run_steps_test.go b/internal/batches/executor/run_steps_test.go index 6b072d55c9..ccdab14c9d 100644 --- a/internal/batches/executor/run_steps_test.go +++ b/internal/batches/executor/run_steps_test.go @@ -2,6 +2,7 @@ package executor import ( "context" + "encoding/json" "os" "path/filepath" "runtime" @@ -10,9 +11,40 @@ import ( "github.com/stretchr/testify/require" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" + batchenv "github.com/sourcegraph/sourcegraph/lib/batches/env" "github.com/sourcegraph/sourcegraph/lib/batches/template" ) +func TestWithoutReservedExecutorEnv(t *testing.T) { + env := []string{ + "ALLOWED=value", + "SRC_EXECUTOR_JOB_TOKEN=secret", + "SRC_EXECUTOR_FUTURE_SECRET=secret", + "VALUE=contains-SRC_EXECUTOR_JOB_TOKEN", + "MALFORMED", + } + + require.Equal(t, []string{ + "ALLOWED=value", + "VALUE=contains-SRC_EXECUTOR_JOB_TOKEN", + "MALFORMED", + }, withoutReservedExecutorEnv(env)) + + var stepEnv batchenv.Environment + require.NoError(t, json.Unmarshal([]byte(`[ + "ALLOWED", + "SRC_EXECUTOR_JOB_TOKEN", + "SRC_EXECUTOR_FUTURE_SECRET" + ]`), &stepEnv)) + resolved, err := stepEnv.Resolve(withoutReservedExecutorEnv(env[:4])) + require.NoError(t, err) + require.Equal(t, map[string]string{ + "ALLOWED": "value", + "SRC_EXECUTOR_JOB_TOKEN": "", + "SRC_EXECUTOR_FUTURE_SECRET": "", + }, resolved) +} + func TestParseContainerTempPath(t *testing.T) { for _, valid := range []string{"/tmp/tmp.abc-123_456", "/tmp/tmp.abc-123_456\n"} { t.Run("valid_"+valid, func(t *testing.T) { From bc8db51c519895fdebfafccbf0071441d4809016 Mon Sep 17 00:00:00 2001 From: Carter Brainerd Date: Wed, 9 Sep 2026 14:31:43 -0400 Subject: [PATCH 623/647] fix/batches: prevent workspace path injection (#1372) --- internal/batches/docker/mount.go | 24 +++++++ internal/batches/docker/mount_test.go | 56 +++++++++++++++ internal/batches/executor/run_steps.go | 16 ++--- internal/batches/executor/run_steps_test.go | 5 -- internal/batches/workspace/bind_workspace.go | 26 ++++++- .../batches/workspace/bind_workspace_test.go | 39 +++++++++++ .../batches/workspace/volume_workspace.go | 37 +++++++--- .../workspace/volume_workspace_test.go | 68 ++++++++++++++++++- 8 files changed, 241 insertions(+), 30 deletions(-) create mode 100644 internal/batches/docker/mount.go create mode 100644 internal/batches/docker/mount_test.go diff --git a/internal/batches/docker/mount.go b/internal/batches/docker/mount.go new file mode 100644 index 0000000000..95919a6497 --- /dev/null +++ b/internal/batches/docker/mount.go @@ -0,0 +1,24 @@ +package docker + +import ( + "fmt" + "strings" + + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +// BindMount returns a Docker bind mount specification after checking that its +// values cannot inject fields into Docker's comma-delimited mount grammar. +func BindMount(source, target string, readOnly bool) (string, error) { + for name, value := range map[string]string{"source": source, "target": target} { + if value == "" || strings.ContainsAny(value, ",\r\n\x00") { + return "", errors.Newf("invalid Docker mount %s %q", name, value) + } + } + + mount := fmt.Sprintf("type=bind,source=%s,target=%s", source, target) + if readOnly { + mount += ",ro" + } + return mount, nil +} diff --git a/internal/batches/docker/mount_test.go b/internal/batches/docker/mount_test.go new file mode 100644 index 0000000000..e4cd3eebde --- /dev/null +++ b/internal/batches/docker/mount_test.go @@ -0,0 +1,56 @@ +package docker + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestBindMount(t *testing.T) { + tests := []struct { + name string + source string + target string + readOnly bool + want string + wantErr bool + }{ + { + name: "writable", + source: "/tmp/workspace", + target: "/work", + want: "type=bind,source=/tmp/workspace,target=/work", + }, + { + name: "read-only", + source: "/tmp/archive", + target: "/tmp/archive", + readOnly: true, + want: "type=bind,source=/tmp/archive,target=/tmp/archive,ro", + }, + { + name: "source injection", + source: "/tmp/archive,source=/etc", + target: "/tmp/archive", + wantErr: true, + }, + { + name: "target injection", + source: "/tmp/archive", + target: "/tmp/archive,source=/etc", + wantErr: true, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + got, err := BindMount(test.source, test.target, test.readOnly) + if test.wantErr { + require.Error(t, err) + return + } + require.NoError(t, err) + require.Equal(t, test.want, got) + }) + } +} diff --git a/internal/batches/executor/run_steps.go b/internal/batches/executor/run_steps.go index 4dfeb14e63..11a9f2b774 100644 --- a/internal/batches/executor/run_steps.go +++ b/internal/batches/executor/run_steps.go @@ -21,6 +21,7 @@ import ( "github.com/sourcegraph/sourcegraph/lib/batches/template" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/src-cli/internal/batches/docker" "github.com/sourcegraph/src-cli/internal/batches/log" "github.com/sourcegraph/src-cli/internal/batches/repozip" "github.com/sourcegraph/src-cli/internal/batches/util" @@ -354,7 +355,7 @@ func executeSingleStep( if err := validateContainerTempPath(containerTemp); err != nil { return bytes.Buffer{}, bytes.Buffer{}, errors.Wrap(err, "validating run script target") } - runScriptMount, err := dockerBindMount(runScriptFile, containerTemp) + runScriptMount, err := docker.BindMount(runScriptFile, containerTemp, true) if err != nil { return bytes.Buffer{}, bytes.Buffer{}, errors.Wrap(err, "creating run script mount") } @@ -373,7 +374,7 @@ func executeSingleStep( } for target, source := range filesToMount { - mountArg, err := dockerBindMount(source.Name(), target) + mountArg, err := docker.BindMount(source.Name(), target, true) if err != nil { return bytes.Buffer{}, bytes.Buffer{}, errors.Wrap(err, "creating files mount") } @@ -386,7 +387,7 @@ func executeSingleStep( if err != nil { return bytes.Buffer{}, bytes.Buffer{}, err } - mountArg, err := dockerBindMount(workspaceFilePath, mount.Mountpoint) + mountArg, err := docker.BindMount(workspaceFilePath, mount.Mountpoint, true) if err != nil { return bytes.Buffer{}, bytes.Buffer{}, errors.Wrap(err, "creating host mount") } @@ -581,15 +582,6 @@ func validateContainerTempPath(tempfile string) error { return nil } -func dockerBindMount(source, target string) (string, error) { - for name, value := range map[string]string{"source": source, "target": target} { - if value == "" || strings.ContainsAny(value, ",\r\n\x00") { - return "", errors.Newf("invalid Docker mount %s %q", name, value) - } - } - return fmt.Sprintf("type=bind,source=%s,target=%s,ro", source, target), nil -} - // createFilesToMount creates temporary files with the contents of Step.Files // that are to be mounted into the container that executes the step. func createFilesToMount(tempDir string, step batcheslib.Step, stepContext *template.StepContext) (map[string]*os.File, func(), error) { diff --git a/internal/batches/executor/run_steps_test.go b/internal/batches/executor/run_steps_test.go index ccdab14c9d..684273ed45 100644 --- a/internal/batches/executor/run_steps_test.go +++ b/internal/batches/executor/run_steps_test.go @@ -88,11 +88,6 @@ func TestProbeImageForShellRejectsMountInjection(t *testing.T) { require.Contains(t, err.Error(), "mktemp returned invalid path") } -func TestDockerBindMountRejectsMountGrammar(t *testing.T) { - _, err := dockerBindMount("/tmp/script", "/tmp/x,source=/var/run/docker.sock") - require.Error(t, err) -} - func TestCreateFilesToMount_RejectsCommaInTargetPath(t *testing.T) { step := batcheslib.Step{ Files: map[string]string{ diff --git a/internal/batches/workspace/bind_workspace.go b/internal/batches/workspace/bind_workspace.go index b925c57080..176277f920 100644 --- a/internal/batches/workspace/bind_workspace.go +++ b/internal/batches/workspace/bind_workspace.go @@ -13,6 +13,7 @@ import ( batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/src-cli/internal/batches/docker" "github.com/sourcegraph/src-cli/internal/batches/graphql" "github.com/sourcegraph/src-cli/internal/batches/repozip" "github.com/sourcegraph/src-cli/internal/batches/util" @@ -77,6 +78,10 @@ func (wc *dockerBindWorkspaceCreator) unzipToWorkspace(ctx context.Context, repo func (wc *dockerBindWorkspaceCreator) copyToWorkspace(ctx context.Context, w *dockerBindWorkspace, files map[string]string) error { for name, src := range files { + if err := validateWorkspaceFileName(name); err != nil { + return err + } + srcStat, err := os.Stat(src) if err != nil { return err @@ -91,7 +96,7 @@ func (wc *dockerBindWorkspaceCreator) copyToWorkspace(ctx context.Context, w *do return err } - destPath := path.Join(w.dir, name) + destPath := filepath.Join(w.dir, filepath.FromSlash(name)) destFile, err := prepareCopyDestinationFile(srcStat, destPath) if err != nil { @@ -136,12 +141,29 @@ func (w *dockerBindWorkspace) Close(ctx context.Context) error { } func (w *dockerBindWorkspace) DockerRunOpts(ctx context.Context, target string) ([]string, error) { + mount, err := docker.BindMount(w.dir, target, false) + if err != nil { + return nil, err + } return []string{ "--mount", - fmt.Sprintf("type=bind,source=%s,target=%s", w.dir, target), + mount, }, nil } +func validateWorkspaceFileName(name string) error { + clean := path.Clean(name) + if path.IsAbs(name) || clean == ".." || strings.HasPrefix(clean, "../") { + return errors.Newf("workspace file path %q is outside the workspace", name) + } + + native := filepath.Clean(filepath.FromSlash(name)) + if filepath.IsAbs(native) || filepath.VolumeName(native) != "" || native == ".." || strings.HasPrefix(native, ".."+string(os.PathSeparator)) { + return errors.Newf("workspace file path %q is outside the workspace", name) + } + return nil +} + func (w *dockerBindWorkspace) WorkDir() *string { return &w.dir } func (w *dockerBindWorkspace) Diff(ctx context.Context) ([]byte, error) { diff --git a/internal/batches/workspace/bind_workspace_test.go b/internal/batches/workspace/bind_workspace_test.go index b8c32e929c..71d5291ea7 100644 --- a/internal/batches/workspace/bind_workspace_test.go +++ b/internal/batches/workspace/bind_workspace_test.go @@ -143,6 +143,45 @@ func TestDockerBindWorkspaceCreator_Create(t *testing.T) { }) } +func TestCopyToWorkspaceRejectsPathTraversal(t *testing.T) { + root := t.TempDir() + workspaceDir := filepath.Join(root, "workspace") + if err := os.Mkdir(workspaceDir, 0755); err != nil { + t.Fatal(err) + } + victimDir := filepath.Join(root, "victim") + if err := os.Mkdir(victimDir, 0700); err != nil { + t.Fatal(err) + } + before, err := os.Stat(victimDir) + if err != nil { + t.Fatal(err) + } + source := filepath.Join(root, "source") + if err := os.WriteFile(source, []byte("attacker content"), 0600); err != nil { + t.Fatal(err) + } + + creator := &dockerBindWorkspaceCreator{} + workspace := &dockerBindWorkspace{dir: workspaceDir} + err = creator.copyToWorkspace(context.Background(), workspace, map[string]string{ + "../victim/.gitignore": source, + }) + if err == nil || !strings.Contains(err.Error(), "outside the workspace") { + t.Fatalf("expected path traversal error, got %v", err) + } + if _, err := os.Stat(filepath.Join(victimDir, ".gitignore")); !os.IsNotExist(err) { + t.Fatalf("file was written outside the workspace: %v", err) + } + info, err := os.Stat(victimDir) + if err != nil { + t.Fatal(err) + } + if got, want := info.Mode().Perm(), before.Mode().Perm(); got != want { + t.Fatalf("outside directory permissions changed: got %o, want %o", got, want) + } +} + func TestPrepareGitRepoRemovesUntrustedGitMetadata(t *testing.T) { dir := t.TempDir() dotGit := filepath.Join(dir, ".git") diff --git a/internal/batches/workspace/volume_workspace.go b/internal/batches/workspace/volume_workspace.go index b161090b77..011ffb436c 100644 --- a/internal/batches/workspace/volume_workspace.go +++ b/internal/batches/workspace/volume_workspace.go @@ -8,7 +8,6 @@ import ( "fmt" "os" "sort" - "strings" "github.com/sourcegraph/sourcegraph/lib/errors" @@ -112,6 +111,10 @@ git commit --quiet --all --allow-empty -m src-action-exec func (wc *dockerVolumeWorkspaceCreator) unzipRepoIntoVolume(ctx context.Context, w *dockerVolumeWorkspace, zip string) error { // We want to mount that temporary file into a Docker container that has the // workspace volume attached, and unzip it into the volume. + zipMount, err := docker.BindMount(zip, "/tmp/zip", true) + if err != nil { + return errors.Wrap(err, "creating archive mount") + } // We need to keep a temporary file in the volume before unzipping for the // permissions to persist because... reasons. Rather than reading the @@ -157,7 +160,7 @@ func (wc *dockerVolumeWorkspaceCreator) unzipRepoIntoVolume(ctx context.Context, "--rm", "--init", "--workdir", "/work", - "--mount", "type=bind,source=" + zip + ",target=/tmp/zip,ro", + "--mount", zipMount, }, w.dockerRunOptsWithUser(w.uidGid, "/work")...) opts = append( opts, @@ -177,6 +180,7 @@ func (wc *dockerVolumeWorkspaceCreator) copyFilesIntoVolumes(ctx context.Context if len(files) == 0 { return nil } + const copyScript = `while test "$#" -gt 0; do cp "$1" "$2" || exit; shift 2; done` opts := append([]string{ "run", @@ -192,22 +196,34 @@ func (wc *dockerVolumeWorkspaceCreator) copyFilesIntoVolumes(ctx context.Context } sort.Strings(names) - var copyCmds []string - for _, name := range names { + var copyArgs []string + for i, name := range names { + if err := validateWorkspaceFileName(name); err != nil { + return err + } localPath := files[name] + // Names originate from the Sourcegraph instance. Keep them out of both + // Docker's comma-delimited mount grammar and the shell program. + mountTarget := fmt.Sprintf("/tmp/src-additional-file-%d", i) + mount, err := docker.BindMount(localPath, mountTarget, true) + if err != nil { + return errors.Wrap(err, "creating additional file mount") + } opts = append(opts, []string{ - "--mount", "type=bind,source=" + localPath + ",target=/tmp/" + name + ",ro", + "--mount", mount, }...) - copyCmds = append(copyCmds, "cp /tmp/"+name+" /work/"+name) + copyArgs = append(copyArgs, mountTarget, "/work/"+name) } opts = append( opts, DockerVolumeWorkspaceImage, "sh", "-c", - strings.Join(copyCmds, " && ")+";", + copyScript, + "copy-additional-files", ) + opts = append(opts, copyArgs...) if out, err := exec.CommandContext(ctx, "docker", opts...).CombinedOutput(); err != nil { return errors.Wrapf(err, "unzip output:\n\n%s\n\n", string(out)) @@ -327,12 +343,17 @@ func (w *dockerVolumeWorkspace) runScript(ctx context.Context, target, script st return nil, errors.Wrap(err, "generating run options") } + scriptMount, err := docker.BindMount(name, "/run.sh", true) + if err != nil { + return nil, errors.Wrap(err, "creating run script mount") + } + opts := append([]string{ "run", "--rm", "--init", "--workdir", target, - "--mount", "type=bind,source=" + name + ",target=/run.sh,ro", + "--mount", scriptMount, }, common...) opts = append(opts, DockerVolumeWorkspaceImage, "sh", "/run.sh") diff --git a/internal/batches/workspace/volume_workspace_test.go b/internal/batches/workspace/volume_workspace_test.go index 9f6706741c..cc879614ac 100644 --- a/internal/batches/workspace/volume_workspace_test.go +++ b/internal/batches/workspace/volume_workspace_test.go @@ -338,10 +338,13 @@ func TestVolumeWorkspaceCreator(t *testing.T) { "--workdir", "/work", "--user", "0:0", "--mount", "type=volume,source="+volumeID+",target=/work", - "--mount", "type=bind,source="+archiveWithAdditionalFiles.mockAdditionalFilePaths[".gitignore"]+",target=/tmp/.gitignore,ro", - "--mount", "type=bind,source="+archiveWithAdditionalFiles.mockAdditionalFilePaths["another-file"]+",target=/tmp/another-file,ro", + "--mount", "type=bind,source="+archiveWithAdditionalFiles.mockAdditionalFilePaths[".gitignore"]+",target=/tmp/src-additional-file-0,ro", + "--mount", "type=bind,source="+archiveWithAdditionalFiles.mockAdditionalFilePaths["another-file"]+",target=/tmp/src-additional-file-1,ro", DockerVolumeWorkspaceImage, - "sh", "-c", "cp /tmp/.gitignore /work/.gitignore && cp /tmp/another-file /work/another-file;", + "sh", "-c", `while test "$#" -gt 0; do cp "$1" "$2" || exit; shift 2; done`, + "copy-additional-files", + "/tmp/src-additional-file-0", "/work/.gitignore", + "/tmp/src-additional-file-1", "/work/another-file", ), expect.NewGlob( expect.Success, @@ -385,6 +388,65 @@ func TestVolumeWorkspaceCreator(t *testing.T) { } } +func TestCopyFilesIntoVolumesDoesNotInterpolateNames(t *testing.T) { + const maliciousName = "x,ro,type=bind,source=/var/run/docker.sock,target=/h1sock;touch /work/injected;/.gitignore" + + expect.Commands( + t, + expect.NewGlob( + expect.Success, + "docker", "run", "--rm", "--init", "--workdir", "/work", + "--user", "0:0", + "--mount", "type=volume,source="+volumeID+",target=/work", + "--mount", "type=bind,source=/tmp/additional-file,target=/tmp/src-additional-file-0,ro", + DockerVolumeWorkspaceImage, + "sh", "-c", `while test "$#" -gt 0; do cp "$1" "$2" || exit; shift 2; done`, + "copy-additional-files", + "/tmp/src-additional-file-0", "/work/"+maliciousName, + ), + ) + + wc := &dockerVolumeWorkspaceCreator{} + w := &dockerVolumeWorkspace{volume: volumeID} + err := wc.copyFilesIntoVolumes(context.Background(), w, map[string]string{ + maliciousName: "/tmp/additional-file", + }) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } +} + +func TestCopyFilesIntoVolumesRejectsUnsafePaths(t *testing.T) { + tests := map[string]map[string]string{ + "workspace traversal": { + "../etc/.gitignore": "/tmp/additional-file", + }, + "mount source injection": { + ".gitignore": "/tmp/additional-file,source=/etc", + }, + } + + for name, files := range tests { + t.Run(name, func(t *testing.T) { + expect.Commands(t) + wc := &dockerVolumeWorkspaceCreator{} + w := &dockerVolumeWorkspace{volume: volumeID} + if err := wc.copyFilesIntoVolumes(context.Background(), w, files); err == nil { + t.Fatal("expected unsafe path to be rejected") + } + }) + } +} + +func TestUnzipRepoIntoVolumeRejectsMountSourceInjection(t *testing.T) { + expect.Commands(t) + wc := &dockerVolumeWorkspaceCreator{} + w := &dockerVolumeWorkspace{volume: volumeID} + if err := wc.unzipRepoIntoVolume(context.Background(), w, "/tmp/archive,source=/etc"); err == nil { + t.Fatal("expected unsafe mount source to be rejected") + } +} + func TestVolumeWorkspace_Close(t *testing.T) { ctx := context.Background() w := &dockerVolumeWorkspace{volume: volumeID} From 8a793e32a111e3ad15591d0b354b5c613286bd8f Mon Sep 17 00:00:00 2001 From: Carter Brainerd Date: Thu, 10 Sep 2026 10:27:08 -0400 Subject: [PATCH 624/647] fix/batches: prevent command injection from repository paths (#1373) --- .../batches/workspace/volume_workspace.go | 107 +++++++++++++----- .../workspace/volume_workspace_test.go | 102 ++++++++--------- 2 files changed, 129 insertions(+), 80 deletions(-) diff --git a/internal/batches/workspace/volume_workspace.go b/internal/batches/workspace/volume_workspace.go index 011ffb436c..a2c9427b5e 100644 --- a/internal/batches/workspace/volume_workspace.go +++ b/internal/batches/workspace/volume_workspace.go @@ -1,12 +1,15 @@ package workspace import ( + "archive/tar" "bytes" "context" "crypto/rand" "encoding/hex" "fmt" + "io" "os" + "path" "sort" "github.com/sourcegraph/sourcegraph/lib/errors" @@ -180,55 +183,105 @@ func (wc *dockerVolumeWorkspaceCreator) copyFilesIntoVolumes(ctx context.Context if len(files) == 0 { return nil } - const copyScript = `while test "$#" -gt 0; do cp "$1" "$2" || exit; shift 2; done` + + archive, err := wc.archiveAdditionalFiles(files) + if err != nil { + return err + } + defer os.Remove(archive) + archiveMount, err := docker.BindMount(archive, "/tmp/additional-files.tar", true) + if err != nil { + return errors.Wrap(err, "creating additional files archive mount") + } opts := append([]string{ "run", "--rm", "--init", "--workdir", "/work", + "--mount", archiveMount, }, w.dockerRunOptsWithUser(w.uidGid, "/work")...) - // We sort these so our tests don't break. Sorry. + opts = append( + opts, + DockerVolumeWorkspaceImage, + "tar", "-xf", "/tmp/additional-files.tar", "-C", "/work", + ) + + if out, err := exec.CommandContext(ctx, "docker", opts...).CombinedOutput(); err != nil { + return errors.Wrapf(err, "additional files output:\n\n%s\n\n", string(out)) + } + return nil +} + +func (wc *dockerVolumeWorkspaceCreator) archiveAdditionalFiles(files map[string]string) (archivePath string, err error) { + f, err := os.CreateTemp(wc.tempDir, "src-additional-files-*.tar") + if err != nil { + return "", errors.Wrap(err, "creating additional files archive") + } + archivePath = f.Name() + defer func() { + if err != nil { + f.Close() + os.Remove(archivePath) + } + }() + + tw := tar.NewWriter(f) var names []string for name := range files { names = append(names, name) } sort.Strings(names) - var copyArgs []string - for i, name := range names { + for _, name := range names { if err := validateWorkspaceFileName(name); err != nil { - return err + return "", err } - localPath := files[name] - // Names originate from the Sourcegraph instance. Keep them out of both - // Docker's comma-delimited mount grammar and the shell program. - mountTarget := fmt.Sprintf("/tmp/src-additional-file-%d", i) - mount, err := docker.BindMount(localPath, mountTarget, true) + if name == "" || path.Clean(name) != name { + return "", errors.Errorf("invalid additional file path %q", name) + } + + file, err := os.Open(files[name]) + if err != nil { + return "", errors.Wrapf(err, "opening additional file %q", name) + } + info, err := file.Stat() if err != nil { - return errors.Wrap(err, "creating additional file mount") + file.Close() + return "", errors.Wrapf(err, "stating additional file %q", name) + } + if !info.Mode().IsRegular() { + file.Close() + return "", errors.Errorf("additional file %q is not a regular file", name) } - opts = append(opts, []string{ - "--mount", mount, - }...) - copyArgs = append(copyArgs, mountTarget, "/work/"+name) + header, err := tar.FileInfoHeader(info, "") + if err != nil { + file.Close() + return "", errors.Wrapf(err, "creating archive header for additional file %q", name) + } + header.Name = name + if err := tw.WriteHeader(header); err != nil { + file.Close() + return "", errors.Wrapf(err, "writing archive header for additional file %q", name) + } + if _, err := io.Copy(tw, file); err != nil { + file.Close() + return "", errors.Wrapf(err, "archiving additional file %q", name) + } + if err := file.Close(); err != nil { + return "", errors.Wrapf(err, "closing additional file %q", name) + } } - opts = append( - opts, - DockerVolumeWorkspaceImage, - "sh", "-c", - copyScript, - "copy-additional-files", - ) - opts = append(opts, copyArgs...) - - if out, err := exec.CommandContext(ctx, "docker", opts...).CombinedOutput(); err != nil { - return errors.Wrapf(err, "unzip output:\n\n%s\n\n", string(out)) + if err := tw.Close(); err != nil { + return "", errors.Wrap(err, "closing additional files archive") } - return nil + if err := f.Close(); err != nil { + return "", errors.Wrap(err, "closing additional files archive file") + } + return archivePath, nil } // dockerVolumeWorkspace workspaces are placed on Docker volumes (surprise!), diff --git a/internal/batches/workspace/volume_workspace_test.go b/internal/batches/workspace/volume_workspace_test.go index cc879614ac..f23b5e5312 100644 --- a/internal/batches/workspace/volume_workspace_test.go +++ b/internal/batches/workspace/volume_workspace_test.go @@ -1,7 +1,9 @@ package workspace import ( + "archive/tar" "context" + "io" "os" "path/filepath" "strings" @@ -39,13 +41,10 @@ func TestVolumeWorkspaceCreator(t *testing.T) { mockAdditionalFilePaths: map[string]string{}, } for _, name := range []string{".gitignore", "another-file"} { - // Since we don't read the files and mock the Docker commands, - // we don't need to create them. - path := filepath.Join(os.TempDir(), "additional-file"+name) - // Instead we create a real-looking path that we sanitize so - // it doesn't trip up the globbing expecations below: - path = strings.ReplaceAll(path, string(os.PathSeparator), "-") - + path := filepath.Join(t.TempDir(), "additional-file"+name) + if err := os.WriteFile(path, []byte(name), 0600); err != nil { + t.Fatal(err) + } archiveWithAdditionalFiles.mockAdditionalFilePaths[name] = path } @@ -336,15 +335,11 @@ func TestVolumeWorkspaceCreator(t *testing.T) { expect.Success, "docker", "run", "--rm", "--init", "--workdir", "/work", + "--mount", "type=bind,source=*,target=/tmp/additional-files.tar,ro", "--user", "0:0", "--mount", "type=volume,source="+volumeID+",target=/work", - "--mount", "type=bind,source="+archiveWithAdditionalFiles.mockAdditionalFilePaths[".gitignore"]+",target=/tmp/src-additional-file-0,ro", - "--mount", "type=bind,source="+archiveWithAdditionalFiles.mockAdditionalFilePaths["another-file"]+",target=/tmp/src-additional-file-1,ro", DockerVolumeWorkspaceImage, - "sh", "-c", `while test "$#" -gt 0; do cp "$1" "$2" || exit; shift 2; done`, - "copy-additional-files", - "/tmp/src-additional-file-0", "/work/.gitignore", - "/tmp/src-additional-file-1", "/work/another-file", + "tar", "-xf", "/tmp/additional-files.tar", "-C", "/work", ), expect.NewGlob( expect.Success, @@ -388,53 +383,54 @@ func TestVolumeWorkspaceCreator(t *testing.T) { } } -func TestCopyFilesIntoVolumesDoesNotInterpolateNames(t *testing.T) { - const maliciousName = "x,ro,type=bind,source=/var/run/docker.sock,target=/h1sock;touch /work/injected;/.gitignore" +func TestArchiveAdditionalFilesTreatsRepositoryPathsAsData(t *testing.T) { + const maliciousName = "x;touch${IFS}/tmp/pwned,source=.,target=/x/.gitignore" + source := filepath.Join(t.TempDir(), "additional-file") + if err := os.WriteFile(source, []byte("contents"), 0600); err != nil { + t.Fatal(err) + } - expect.Commands( - t, - expect.NewGlob( - expect.Success, - "docker", "run", "--rm", "--init", "--workdir", "/work", - "--user", "0:0", - "--mount", "type=volume,source="+volumeID+",target=/work", - "--mount", "type=bind,source=/tmp/additional-file,target=/tmp/src-additional-file-0,ro", - DockerVolumeWorkspaceImage, - "sh", "-c", `while test "$#" -gt 0; do cp "$1" "$2" || exit; shift 2; done`, - "copy-additional-files", - "/tmp/src-additional-file-0", "/work/"+maliciousName, - ), - ) + wc := &dockerVolumeWorkspaceCreator{tempDir: t.TempDir()} + archive, err := wc.archiveAdditionalFiles(map[string]string{maliciousName: source}) + if err != nil { + t.Fatal(err) + } + defer os.Remove(archive) - wc := &dockerVolumeWorkspaceCreator{} - w := &dockerVolumeWorkspace{volume: volumeID} - err := wc.copyFilesIntoVolumes(context.Background(), w, map[string]string{ - maliciousName: "/tmp/additional-file", - }) + f, err := os.Open(archive) if err != nil { - t.Fatalf("unexpected error: %v", err) + t.Fatal(err) } -} + defer f.Close() -func TestCopyFilesIntoVolumesRejectsUnsafePaths(t *testing.T) { - tests := map[string]map[string]string{ - "workspace traversal": { - "../etc/.gitignore": "/tmp/additional-file", - }, - "mount source injection": { - ".gitignore": "/tmp/additional-file,source=/etc", - }, + r := tar.NewReader(f) + header, err := r.Next() + if err != nil { + t.Fatal(err) + } + if header.Name != maliciousName { + t.Fatalf("unexpected archived path: have=%q want=%q", header.Name, maliciousName) + } + contents, err := io.ReadAll(r) + if err != nil { + t.Fatal(err) } + if string(contents) != "contents" { + t.Fatalf("unexpected archived contents: %q", contents) + } + if _, err := r.Next(); err != io.EOF { + t.Fatalf("unexpected second archive entry: %v", err) + } +} - for name, files := range tests { - t.Run(name, func(t *testing.T) { - expect.Commands(t) - wc := &dockerVolumeWorkspaceCreator{} - w := &dockerVolumeWorkspace{volume: volumeID} - if err := wc.copyFilesIntoVolumes(context.Background(), w, files); err == nil { - t.Fatal("expected unsafe path to be rejected") - } - }) +func TestCopyFilesIntoVolumesRejectsWorkspaceTraversal(t *testing.T) { + expect.Commands(t) + wc := &dockerVolumeWorkspaceCreator{} + w := &dockerVolumeWorkspace{volume: volumeID} + if err := wc.copyFilesIntoVolumes(context.Background(), w, map[string]string{ + "../etc/.gitignore": "/tmp/additional-file", + }); err == nil { + t.Fatal("expected workspace traversal to be rejected") } } From 0204585dab08d3a139602a659320e92cd6a276ca Mon Sep 17 00:00:00 2001 From: Marc <7050295+marcleblanc2@users.noreply.github.com> Date: Wed, 23 Sep 2026 18:02:11 -0600 Subject: [PATCH 625/647] chore/ci: Add DiffTour link to PRs (#1379) Adding the shared sourcegraph/actions/diff-tour action to comment on PRs with the Diff Tour link. Please make any needed improvements to the shared action, so all of our repos using it benefit. Co-authored-by: sourcegraph-commit-signing-s2[bot] <292215795+sourcegraph-commit-signing-s2[bot]@users.noreply.github.com> Co-authored-by: marcleblanc2 --- .github/workflows/diff-tour.yml | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 .github/workflows/diff-tour.yml diff --git a/.github/workflows/diff-tour.yml b/.github/workflows/diff-tour.yml new file mode 100644 index 0000000000..78abbc7c51 --- /dev/null +++ b/.github/workflows/diff-tour.yml @@ -0,0 +1,27 @@ +# This GitHub Action imported from the shared action +# https://github.com/sourcegraph/actions/blob/main/diff-tour/ +# Please make fixes / enhancements in the shared action, +# so all of our repos get the benefits + +name: Diff Tour link + +on: + pull_request: + # `edited` fires when the base branch changes; `synchronize` does not + # `closed` fires on merge and on plain close; either way the comment is + # updated to a link that survives deleting the head branch + types: [closed, edited, opened, reopened, synchronize] + +# The only permission needed. The action does not check out your repo, so +# `contents: read` is not required, even for private repos +permissions: + pull-requests: write + +jobs: + diff-tour: + name: Comment + runs-on: ubuntu-latest + # Diff Tour resolves branch names against the base repo, so skip fork PRs + if: github.event.pull_request.head.repo.full_name == github.repository + steps: + - uses: sourcegraph/actions/diff-tour@main From f2d6be0d1182281cdf84b643c96fb2dffe93f0dd Mon Sep 17 00:00:00 2001 From: Marc <7050295+marcleblanc2@users.noreply.github.com> Date: Mon, 28 Sep 2026 03:38:04 -0600 Subject: [PATCH 626/647] fix/doc: document search-jobs, debug, snapshot subcommands; list legacy commands in root index (#1375) --- CHANGELOG.md | 4 + cmd/src/doc.go | 17 ++-- cmd/src/doc_test.go | 217 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 231 insertions(+), 7 deletions(-) create mode 100644 cmd/src/doc_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 7caabd95d7..d46f8fc6da 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,10 @@ All notable changes to `src-cli` are documented in this file. - HTTP requests now fail instead of hanging forever if the server does not start responding within 1 minute. Set the `SRC_RESPONSE_HEADER_TIMEOUT` environment variable to change this timeout, or to `0` to disable it. Responses that stream data for a long time (for example, large search job results) are not affected. - `src search-jobs logs` and `src search-jobs results` now use the standard API client, gaining proxy support, `-insecure-skip-verify`, and cross-host redirect protection, and now report an error on non-200 responses instead of writing the error page into the output. +### Fixed + +- `src doc` now generates reference pages for the `search-jobs`, `debug`, and `snapshot` subcommands, and the root `index.md` again lists legacy commands (`batch`, `repos`, `search`, ...) alongside the `urfave/cli` ones. + ### Removed - Removed `src sbom` and `src signature` commands. SBOMs and container signatures are no longer published as of Sourcegraph 7.1.0. diff --git a/cmd/src/doc.go b/cmd/src/doc.go index ed4021bb5c..ebc3018dba 100644 --- a/cmd/src/doc.go +++ b/cmd/src/doc.go @@ -57,12 +57,15 @@ Examples: } commanders := map[string]*commander{ - "": &commands, - "batch": &batchCommands, - "config": &configCommands, - "extsvc": &extsvcCommands, - "code-intel": &codeintelCommands, - "repos": &reposCommands, + "": &commands, + "batch": &batchCommands, + "config": &configCommands, + "extsvc": &extsvcCommands, + "code-intel": &codeintelCommands, + "repos": &reposCommands, + "search-jobs": &searchJobsCommands, + "debug": &debugCommands, + "snapshot": &snapshotCommands, } rootSubcommands := map[string]string{} @@ -108,7 +111,7 @@ Examples: } if groupName == "" { - maps.Copy(subcommands, rootSubcommands) + maps.Copy(rootSubcommands, subcommands) continue } diff --git a/cmd/src/doc_test.go b/cmd/src/doc_test.go new file mode 100644 index 0000000000..f99fea6e18 --- /dev/null +++ b/cmd/src/doc_test.go @@ -0,0 +1,217 @@ +package main + +import ( + "io/fs" + "os" + "path/filepath" + "slices" + "sort" + "strings" + "testing" + + "github.com/google/go-cmp/cmp" +) + +// legacyGroupsWithoutSubcommandPages lists legacy command groups that are +// deliberately left out of the commanders map in doc.go, so they render as a +// single page instead of a directory of subcommand pages. Every entry needs a +// reason. +var legacyGroupsWithoutSubcommandPages = map[string]string{ + "teams.md": "teams were removed in Sourcegraph 7.0 (see checkTeamsAvailability); don't expand docs for a removed feature", +} + +// expectedDocFiles is the full set of files 'src doc' is expected to write, +// relative to the output directory. Update it deliberately when adding or +// removing commands; sourcegraph/sourcegraph's doc/cli/references/BUILD.bazel +// OUTPUT_FILES must be kept in sync with this list. +var expectedDocFiles = []string{ + "abc/index.md", + "abc/variables/delete.md", + "abc/variables/index.md", + "abc/variables/set.md", + "api.md", + "auth/index.md", + "auth/token.md", + "batch/apply.md", + "batch/exec.md", + "batch/index.md", + "batch/new.md", + "batch/preview.md", + "batch/remote.md", + "batch/repositories.md", + "batch/validate.md", + "code-intel/index.md", + "code-intel/upload.md", + "codeowners/create.md", + "codeowners/delete.md", + "codeowners/get.md", + "codeowners/index.md", + "codeowners/update.md", + "config/edit.md", + "config/get.md", + "config/index.md", + "config/list.md", + "debug/compose.md", + "debug/index.md", + "debug/kube.md", + "debug/server.md", + "extsvc/create.md", + "extsvc/edit.md", + "extsvc/index.md", + "extsvc/list.md", + "index.md", + "login.md", + "lsp.md", + "orgs/create.md", + "orgs/delete.md", + "orgs/get.md", + "orgs/index.md", + "orgs/list.md", + "orgs/members/add.md", + "orgs/members/index.md", + "orgs/members/remove.md", + "repos/add-metadata.md", + "repos/delete-metadata.md", + "repos/delete.md", + "repos/get.md", + "repos/index.md", + "repos/list.md", + "repos/update-metadata.md", + "search-jobs/cancel.md", + "search-jobs/create.md", + "search-jobs/delete.md", + "search-jobs/get.md", + "search-jobs/index.md", + "search-jobs/list.md", + "search-jobs/logs.md", + "search-jobs/restart.md", + "search-jobs/results.md", + "search.md", + "serve-git.md", + "snapshot/databases.md", + "snapshot/index.md", + "snapshot/restore.md", + "snapshot/summary.md", + "snapshot/test.md", + "snapshot/upload.md", + "teams.md", + "users/create.md", + "users/delete.md", + "users/get.md", + "users/index.md", + "users/list.md", + "users/prune.md", + "users/tag.md", + "version.md", +} + +func runDocCommand(t *testing.T) (dir string, files []string) { + t.Helper() + + var docCmd *command + for _, cmd := range commands { + if cmd.flagSet.Name() == "doc" { + docCmd = cmd + break + } + } + if docCmd == nil { + t.Fatal("'doc' command not registered") + } + + dir = t.TempDir() + if err := docCmd.handler([]string{"-o", dir}); err != nil { + t.Fatalf("src doc: %v", err) + } + + err := filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() { + return nil + } + rel, err := filepath.Rel(dir, path) + if err != nil { + return err + } + files = append(files, filepath.ToSlash(rel)) + return nil + }) + if err != nil { + t.Fatal(err) + } + sort.Strings(files) + return dir, files +} + +func TestDocGeneratesExpectedFiles(t *testing.T) { + _, got := runDocCommand(t) + + want := append([]string(nil), expectedDocFiles...) + sort.Strings(want) + + if diff := cmp.Diff(want, got); diff != "" { + t.Errorf("generated file list mismatch (-want +got):\n%s\n"+ + "If you added or removed a command, update expectedDocFiles here and "+ + "OUTPUT_FILES in sourcegraph/sourcegraph doc/cli/references/BUILD.bazel.", diff) + } +} + +// A legacy command group that is not registered in the commanders map in +// doc.go is rendered as a single leaf page containing only its group help, +// and none of its subcommands get a page. Legacy group help text lists +// subcommands under "The commands are:", so a leaf page containing that +// phrase means a group was missed. +func TestDocLegacyGroupsHaveSubcommandPages(t *testing.T) { + dir, files := runDocCommand(t) + + for _, rel := range files { + if strings.HasSuffix(rel, "/index.md") || rel == "index.md" { + continue + } + if _, ok := legacyGroupsWithoutSubcommandPages[rel]; ok { + continue + } + content, err := os.ReadFile(filepath.Join(dir, rel)) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(content), "The commands are:") { + t.Errorf("%s is a leaf page but lists subcommands: add its command group to the commanders map in doc.go "+ + "(or, if intentional, to legacyGroupsWithoutSubcommandPages with a reason)", rel) + } + } + + for rel := range legacyGroupsWithoutSubcommandPages { + if !slices.Contains(files, rel) { + t.Errorf("legacyGroupsWithoutSubcommandPages entry %q was not generated; remove the stale entry", rel) + } + } +} + +// The root index must link every top-level command, both legacy (commander) +// and migrated (urfave/cli) ones. +func TestDocRootIndexListsAllCommands(t *testing.T) { + dir, _ := runDocCommand(t) + + index, err := os.ReadFile(filepath.Join(dir, "index.md")) + if err != nil { + t.Fatal(err) + } + + var missing []string + for _, cmd := range commands { + name := cmd.flagSet.Name() + if name == "doc" || name == "publish" { + continue + } + if !strings.Contains(string(index), "[`"+name+"`](") { + missing = append(missing, name) + } + } + if len(missing) > 0 { + sort.Strings(missing) + t.Errorf("root index.md is missing legacy commands: %v", missing) + } +} From 4d486584cfecd007f5a50a08b596acecd0af29e0 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Mon, 28 Sep 2026 13:47:05 +0200 Subject: [PATCH 627/647] remove/batches: Remove batch exec command (#1381) Server-side Batch Changes execution now uses the batch-exec binary in the Sourcegraph monorepo, so src-cli no longer needs its internal executor entrypoint. Remove the command, its executor-only workspace implementation and vendored execution-input model, and update the generated documentation inventory. Amp-Thread-ID: https://ampcode.com/threads/T-01a0e79c-fa8d-73d8-bd66-3a3b34315141 Co-authored-by: Amp --- CHANGELOG.md | 1 + cmd/src/batch_exec.go | 284 ------------------ cmd/src/doc_test.go | 1 - .../batches/workspace/executor_workspace.go | 55 ---- lib/batches/workspaces_execution_input.go | 39 --- 5 files changed, 1 insertion(+), 379 deletions(-) delete mode 100644 cmd/src/batch_exec.go delete mode 100644 internal/batches/workspace/executor_workspace.go delete mode 100644 lib/batches/workspaces_execution_input.go diff --git a/CHANGELOG.md b/CHANGELOG.md index d46f8fc6da..a0a93b625e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,7 @@ All notable changes to `src-cli` are documented in this file. ### Removed - Removed `src sbom` and `src signature` commands. SBOMs and container signatures are no longer published as of Sourcegraph 7.1.0. +- Removed the internal `src batch exec` command. Server-side Batch Changes execution now uses the `batch-exec` binary in the Sourcegraph repository. ## 6.7.1104 diff --git a/cmd/src/batch_exec.go b/cmd/src/batch_exec.go deleted file mode 100644 index 11aadf39e3..0000000000 --- a/cmd/src/batch_exec.go +++ /dev/null @@ -1,284 +0,0 @@ -package main - -import ( - "context" - "encoding/json" - "flag" - "fmt" - "io" - "os" - "path/filepath" - "time" - - "github.com/sourcegraph/src-cli/internal/batches/docker" - "github.com/sourcegraph/src-cli/internal/batches/log" - "github.com/sourcegraph/src-cli/internal/batches/repozip" - "github.com/sourcegraph/src-cli/internal/batches/workspace" - - "github.com/sourcegraph/sourcegraph/lib/errors" - - "github.com/sourcegraph/src-cli/internal/batches/executor" - "github.com/sourcegraph/src-cli/internal/batches/graphql" - "github.com/sourcegraph/src-cli/internal/batches/service" - "github.com/sourcegraph/src-cli/internal/batches/ui" - "github.com/sourcegraph/src-cli/internal/cmderrors" - - batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" -) - -const ( - execPullParallelism = 4 -) - -type executorModeFlags struct { - timeout time.Duration - file string - runAsImageUser bool - tempDir string - repoDir string - workspaceFilesDir string - binaryDiffs bool -} - -func newExecutorModeFlags(flagSet *flag.FlagSet) (f *executorModeFlags) { - f = &executorModeFlags{} - flagSet.DurationVar(&f.timeout, "timeout", 60*time.Minute, "The maximum duration a single batch spec step can take.") - flagSet.StringVar(&f.file, "f", "", "The workspace execution input file to read.") - flagSet.BoolVar(&f.runAsImageUser, "run-as-image-user", false, "True to run step containers as the default image user; if false or omitted, containers are always run as root.") - flagSet.StringVar(&f.tempDir, "tmp", "", "Directory for storing temporary data.") - flagSet.StringVar(&f.repoDir, "repo", "", "Path of the checked out repo on disk.") - flagSet.StringVar(&f.workspaceFilesDir, "workspaceFiles", "", "Path of workspace files on disk.") - flagSet.BoolVar(&f.binaryDiffs, "binaryDiffs", false, "Whether to encode diffs as base64.") - - return f -} - -func validateExecutorModeFlags(f *executorModeFlags) error { - if f.file == "" { - return errors.New("input file parameter missing") - } - if f.tempDir == "" { - return errors.New("tempDir parameter missing") - } - if f.repoDir == "" { - return errors.New("repoDir parameter missing") - } - - return nil -} - -func init() { - usage := ` -INTERNAL USE ONLY: 'src batch exec' executes the given raw batch spec in the given workspaces. - -The input file contains a JSON dump of the WorkspacesExecutionInput struct in -github.com/sourcegraph/sourcegraph/lib/batches. - -Usage: - - src batch exec -f FILE -repo DIR -workspaceFiles DIR [command options] - -Examples: - - $ src batch exec -f batch-spec-with-workspaces.json - -` - - flagSet := flag.NewFlagSet("exec", flag.ExitOnError) - flags := newExecutorModeFlags(flagSet) - - handler := func(args []string) error { - if err := flagSet.Parse(args); err != nil { - return err - } - - if len(flagSet.Args()) != 0 { - return cmderrors.Usage("additional arguments not allowed") - } - - if err := validateExecutorModeFlags(flags); err != nil { - return cmderrors.ExitCode(1, err) - } - - ctx, cancel := contextCancelOnInterrupt(context.Background()) - defer cancel() - - err := executeBatchSpecInWorkspaces(ctx, flags) - if err != nil { - return cmderrors.ExitCode(1, err) - } - - return nil - } - - batchCommands = append(batchCommands, &command{ - flagSet: flagSet, - handler: handler, - usageFunc: func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src batch %s':\n", flagSet.Name()) - flagSet.PrintDefaults() - fmt.Println(usage) - }, - }) -} - -func executeBatchSpecInWorkspaces(ctx context.Context, flags *executorModeFlags) (err error) { - ui := &ui.JSONLines{BinaryDiffs: flags.binaryDiffs} - - // Ensure the temp dir exists. - tempDir := flags.tempDir - if !filepath.IsAbs(tempDir) { - tempDir, err = filepath.Abs(tempDir) - if err != nil { - return errors.Wrap(err, "getting absolute path for temp dir") - } - - if err := os.Mkdir(tempDir, os.ModePerm); err != nil { - return errors.Wrap(err, "creating temp directory") - } - } - - // Grab the absolute path to the repo contents. - repoDir := flags.repoDir - if !filepath.IsAbs(repoDir) { - repoDir, err = filepath.Abs(repoDir) - if err != nil { - return errors.Wrap(err, "getting absolute path for repo dir") - } - } - - // Grab the absolute path to the workspace files contents. - workspaceFilesDir, err := filepath.Abs(flags.workspaceFilesDir) - if err != nil { - return errors.Wrap(err, "getting absolute path for workspace files dir") - } - - // Test if git is available. - if err := checkExecutable("git", "version"); err != nil { - return err - } - // Test if docker is available. - if err := checkExecutable("docker", "version"); err != nil { - return err - } - - // Read the input file that contains the raw spec and the workspaces in - // which to execute it. - input, err := loadWorkspaceExecutionInput(flags.file) - if err != nil { - return err - } - task := convertWorkspace(input) - - if len(task.Steps) == 0 { - return errors.New("invalid execution, no steps to process") - } - - imageCache := docker.NewImageCache() - - ui.PreparingContainerImages() - _, err = service.New(&service.Opts{}).EnsureDockerImages( - ctx, - imageCache, - task.Steps, - execPullParallelism, - ui.PreparingContainerImagesProgress, - ) - if err != nil { - return err - } - ui.PreparingContainerImagesSuccess() - - // Set up the execution UI. - taskExecUI := ui.ExecutingTasks(false, 1) - taskExecUI.Start([]*executor.Task{task}) - taskExecUI.TaskStarted(task) - - // Pass the os.Environ to run steps to allow access to the secrets set - // in the executor environment. - // The executor runtime takes care of not forwarding any sensitive secrets - // from the host, so this is safe. - globalEnv := os.Environ() - - opts := &executor.RunStepsOpts{ - Logger: &log.NoopTaskLogger{}, - WC: workspace.NewExecutorWorkspaceCreator(tempDir, repoDir), - EnsureImage: imageCache.Ensure, - Task: task, - // TODO: Should be slightly less than the executor timeout. Can we somehow read that? - Timeout: flags.timeout, - TempDir: tempDir, - WorkingDirectory: workspaceFilesDir, - GlobalEnv: globalEnv, - RepoArchive: &repozip.NoopArchive{}, - UI: taskExecUI.StepsExecutionUI(task), - ForceRoot: !flags.runAsImageUser, - BinaryDiffs: flags.binaryDiffs, - } - results, err := executor.RunSteps(ctx, opts) - - // Write all step cache results for all results. - for _, stepRes := range results { - cacheKey := task.CacheKey(globalEnv, workspaceFilesDir, stepRes.StepIndex) - k, err := cacheKey.Key() - if err != nil { - return errors.Wrap(err, "calculating step cache key") - } - ui.WriteAfterStepResult(k, stepRes) - } - - taskExecUI.TaskFinished(task, err) - - return err -} - -func loadWorkspaceExecutionInput(file string) (input batcheslib.WorkspacesExecutionInput, err error) { - f, err := batchOpenFileFlag(file) - if err != nil { - return input, err - } - defer f.Close() - - data, err := io.ReadAll(f) - if err != nil { - return input, errors.Wrap(err, "reading workspace execution input file") - } - - if err := json.Unmarshal(data, &input); err != nil { - return input, errors.Wrap(err, "unmarshaling workspace execution input file") - } - - return input, nil -} - -// convertWorkspace takes the WorkspacesExecutionInput and restructures it into -// an executor.Task. -func convertWorkspace(w batcheslib.WorkspacesExecutionInput) *executor.Task { - fileMatches := make(map[string]bool) - for _, path := range w.SearchResultPaths { - fileMatches[path] = true - } - - task := &executor.Task{ - Repository: &graphql.Repository{ - ID: w.Repository.ID, - Name: w.Repository.Name, - Branch: graphql.Branch{ - Name: w.Branch.Name, - Target: graphql.Target{ - OID: w.Branch.Target.OID, - }, - }, - Commit: graphql.Target{OID: w.Branch.Target.OID}, - FileMatches: fileMatches, - }, - Path: w.Path, - Steps: w.Steps, - OnlyFetchWorkspace: w.OnlyFetchWorkspace, - BatchChangeAttributes: &w.BatchChangeAttributes, - CachedStepResultFound: w.CachedStepResultFound, - CachedStepResult: w.CachedStepResult, - } - - return task -} diff --git a/cmd/src/doc_test.go b/cmd/src/doc_test.go index f99fea6e18..64d30ff1a7 100644 --- a/cmd/src/doc_test.go +++ b/cmd/src/doc_test.go @@ -33,7 +33,6 @@ var expectedDocFiles = []string{ "auth/index.md", "auth/token.md", "batch/apply.md", - "batch/exec.md", "batch/index.md", "batch/new.md", "batch/preview.md", diff --git a/internal/batches/workspace/executor_workspace.go b/internal/batches/workspace/executor_workspace.go deleted file mode 100644 index f6c4366755..0000000000 --- a/internal/batches/workspace/executor_workspace.go +++ /dev/null @@ -1,55 +0,0 @@ -package workspace - -import ( - "context" - - batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" - - "github.com/sourcegraph/src-cli/internal/batches/graphql" - "github.com/sourcegraph/src-cli/internal/batches/repozip" -) - -func NewExecutorWorkspaceCreator(tempDir, repoDir string) Creator { - return &executorWorkspaceCreator{ - TempDir: tempDir, - RepoDir: repoDir, - } -} - -type executorWorkspaceCreator struct { - TempDir string - RepoDir string -} - -var _ Creator = &executorWorkspaceCreator{} - -func (wc *executorWorkspaceCreator) Create(ctx context.Context, repo *graphql.Repository, steps []batcheslib.Step, archive repozip.Archive) (Workspace, error) { - gitMetadata, err := snapshotGitMetadata(wc.RepoDir) - if err != nil { - return nil, err - } - - return &dockerBindExecutorWorkspace{ - dockerBindWorkspace: dockerBindWorkspace{ - tempDir: wc.TempDir, - dir: wc.RepoDir, - gitMetadata: gitMetadata, - }, - }, nil -} - -// dockerBindExecutorWorkspace implements a workspace that operates on the host FS -// and is mounted into the docker containers using a bind mount in the end. -// It is based on the dockerBindWorkspace implementation, but does no cleanup -// as that's handled by the executor, and we want to honor it's `keepWorkspaces` -// setting. -type dockerBindExecutorWorkspace struct { - dockerBindWorkspace -} - -var _ Workspace = &dockerBindExecutorWorkspace{} - -func (w *dockerBindExecutorWorkspace) Close(ctx context.Context) error { - // Nothing to do here, executor cleanup will handle this. - return nil -} diff --git a/lib/batches/workspaces_execution_input.go b/lib/batches/workspaces_execution_input.go deleted file mode 100644 index 76a5a8cb18..0000000000 --- a/lib/batches/workspaces_execution_input.go +++ /dev/null @@ -1,39 +0,0 @@ -package batches - -import ( - "github.com/sourcegraph/sourcegraph/lib/batches/execution" - "github.com/sourcegraph/sourcegraph/lib/batches/template" -) - -type WorkspacesExecutionInput struct { - BatchChangeAttributes template.BatchChangeAttributes - Repository WorkspaceRepo `json:"repository"` - Branch WorkspaceBranch `json:"branch"` - Path string `json:"path"` - OnlyFetchWorkspace bool `json:"onlyFetchWorkspace"` - Steps []Step `json:"steps"` - SearchResultPaths []string `json:"searchResultPaths"` - // CachedStepResultFound is only required for V1 executions. - // TODO: Remove me once V2 is the only execution format. - CachedStepResultFound bool `json:"cachedStepResultFound"` - // CachedStepResult is only required for V1 executions. - // TODO: Remove me once V2 is the only execution format. - CachedStepResult execution.AfterStepResult `json:"cachedStepResult"` - // SkippedSteps determines which steps are skipped in the execution. - SkippedSteps map[int]struct{} `json:"skippedSteps"` -} - -type WorkspaceRepo struct { - // ID is the GraphQL ID of the repository. - ID string `json:"id"` - Name string `json:"name"` -} - -type WorkspaceBranch struct { - Name string `json:"name"` - Target Commit `json:"target"` -} - -type Commit struct { - OID string `json:"oid"` -} From 4c967dd91edb3876eca4a597ff76001c42949bb5 Mon Sep 17 00:00:00 2001 From: Marc <7050295+marcleblanc2@users.noreply.github.com> Date: Mon, 28 Sep 2026 13:27:10 -0600 Subject: [PATCH 628/647] chore: Remove deprecated `src teams` commands (#1376) * remove: `src teams` commands Teams were removed in Sourcegraph 7.0. Since #1257 (src-cli 7.0.0) the command has refused to run against 7.x instances, so it only works against instances that are no longer supported. Remove it and its reference page. Drops the "teams.md" entry from the doc golden list and the legacyGroupsWithoutSubcommandPages exemption added in #1375, so every remaining legacy group is now expanded into subcommand pages. Part of https://linear.app/sourcegraph/issue/FE-502 Amp-Thread-ID: https://ampcode.com/threads/T-01a08410-86ca-72be-9928-2810e837fae1 Co-authored-by: Amp * remove Sourcegraph70 feature flag and stale extensions/gateway help entries Sourcegraph70 was only used by the teams version gate. The `extensions` and `gateway` commands were removed in #1173 and earlier but were still listed in `src help`. Part of https://linear.app/sourcegraph/issue/FE-502 Amp-Thread-ID: https://ampcode.com/threads/T-01a08410-86ca-72be-9928-2810e837fae1 Co-authored-by: Amp --------- Co-authored-by: Amp --- CHANGELOG.md | 1 + cmd/src/doc_test.go | 5 +- cmd/src/main.go | 3 - cmd/src/team_members_list.go | 111 --------------------------- cmd/src/teams.go | 88 --------------------- cmd/src/teams_create.go | 96 ----------------------- cmd/src/teams_delete.go | 74 ------------------ cmd/src/teams_list.go | 130 -------------------------------- cmd/src/teams_members.go | 55 -------------- cmd/src/teams_members_add.go | 108 -------------------------- cmd/src/teams_members_remove.go | 108 -------------------------- cmd/src/teams_update.go | 92 ---------------------- internal/features/features.go | 2 - 13 files changed, 2 insertions(+), 871 deletions(-) delete mode 100644 cmd/src/team_members_list.go delete mode 100644 cmd/src/teams.go delete mode 100644 cmd/src/teams_create.go delete mode 100644 cmd/src/teams_delete.go delete mode 100644 cmd/src/teams_list.go delete mode 100644 cmd/src/teams_members.go delete mode 100644 cmd/src/teams_members_add.go delete mode 100644 cmd/src/teams_members_remove.go delete mode 100644 cmd/src/teams_update.go diff --git a/CHANGELOG.md b/CHANGELOG.md index a0a93b625e..e437c99c89 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,7 @@ All notable changes to `src-cli` are documented in this file. - Removed `src sbom` and `src signature` commands. SBOMs and container signatures are no longer published as of Sourcegraph 7.1.0. - Removed the internal `src batch exec` command. Server-side Batch Changes execution now uses the `batch-exec` binary in the Sourcegraph repository. +- Removed the `src teams` (`src team`) commands. Teams were removed in Sourcegraph 7.0 and the commands have refused to run against 7.x instances since src-cli 7.0.0. ## 6.7.1104 diff --git a/cmd/src/doc_test.go b/cmd/src/doc_test.go index 64d30ff1a7..e5615054ed 100644 --- a/cmd/src/doc_test.go +++ b/cmd/src/doc_test.go @@ -16,9 +16,7 @@ import ( // deliberately left out of the commanders map in doc.go, so they render as a // single page instead of a directory of subcommand pages. Every entry needs a // reason. -var legacyGroupsWithoutSubcommandPages = map[string]string{ - "teams.md": "teams were removed in Sourcegraph 7.0 (see checkTeamsAvailability); don't expand docs for a removed feature", -} +var legacyGroupsWithoutSubcommandPages = map[string]string{} // expectedDocFiles is the full set of files 'src doc' is expected to write, // relative to the output directory. Update it deliberately when adding or @@ -93,7 +91,6 @@ var expectedDocFiles = []string{ "snapshot/summary.md", "snapshot/test.md", "snapshot/upload.md", - "teams.md", "users/create.md", "users/delete.md", "users/get.md", diff --git a/cmd/src/main.go b/cmd/src/main.go index 7bb75e6211..9cc205a7ec 100644 --- a/cmd/src/main.go +++ b/cmd/src/main.go @@ -58,12 +58,9 @@ The commands are: batch manages batch changes code-intel manages code intelligence data config manages global, org, and user settings - extensions,ext manages extensions (experimental) extsvc manages external services - gateway interacts with Cody Gateway login authenticate to a Sourcegraph instance with your user credentials orgs,org manages organizations - teams,team manages teams repos,repo manages repositories search search for results on Sourcegraph search-jobs manages search jobs diff --git a/cmd/src/team_members_list.go b/cmd/src/team_members_list.go deleted file mode 100644 index eb69d57719..0000000000 --- a/cmd/src/team_members_list.go +++ /dev/null @@ -1,111 +0,0 @@ -package main - -import ( - "context" - "encoding/json" - "flag" - "fmt" - "os" - - "github.com/sourcegraph/sourcegraph/lib/errors" - - "github.com/sourcegraph/src-cli/internal/api" -) - -func init() { - usage := ` -Examples: - - List team members: - - $ src team members list -name= - - List team members whose names match the query: - - $ src team members list -name= -query='myquery' -` - - flagSet := flag.NewFlagSet("list", flag.ExitOnError) - usageFunc := func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src team members %s':\n", flagSet.Name()) - flagSet.PrintDefaults() - fmt.Println(usage) - } - var ( - nameFlag = flagSet.String("name", "", "The team of which to return members") - firstFlag = flagSet.Int("first", 1000, "Returns the first n teams from the list") - queryFlag = flagSet.String("query", "", `Returns teams whose name or displayname match the query. (e.g. "engineering")`) - formatFlag = flagSet.String("f", "{{.Username}}", `Format for the output, using the syntax of Go package text/template. (e.g. "{{.Name}}: {{.DisplayName}}" or "{{.|json}}")`) - jsonFlag = flagSet.Bool("json", false, `Format for the output as json`) - apiFlags = api.NewFlags(flagSet) - ) - - handler := func(args []string) error { - if err := flagSet.Parse(args); err != nil { - return err - } - - if *nameFlag == "" { - return errors.New("must provide -name") - } - - tmpl, err := parseTemplate(*formatFlag) - if err != nil { - return err - } - - client := cfg.apiClient(apiFlags, flagSet.Output()) - - query := `query TeamMembers( - $name: String!, - $first: Int, - $search: String -) { - team(name: $name) { - members ( - first: $first, - search: $search - ) { - nodes { - ...TeamMemberFields - } - } - } -} -` + teamMemberFragment - - var result struct { - Team struct { - Members struct { - Nodes []TeamMember - } - } - } - if ok, err := client.NewRequest(query, map[string]any{ - "name": *nameFlag, - "first": api.NullInt(*firstFlag), - "search": api.NullString(*queryFlag), - }).Do(context.Background(), &result); err != nil || !ok { - return err - } - - if jsonFlag != nil && *jsonFlag { - json.NewEncoder(os.Stdout).Encode(result.Team.Members.Nodes) - return nil - } - - for _, t := range result.Team.Members.Nodes { - if err := execTemplate(tmpl, t); err != nil { - return err - } - } - return nil - } - - // Register the command. - teamMembersCommands = append(teamMembersCommands, &command{ - flagSet: flagSet, - handler: handler, - usageFunc: usageFunc, - }) -} diff --git a/cmd/src/teams.go b/cmd/src/teams.go deleted file mode 100644 index 1f3f5b2622..0000000000 --- a/cmd/src/teams.go +++ /dev/null @@ -1,88 +0,0 @@ -package main - -import ( - "context" - "flag" - "fmt" - "os" - - "github.com/sourcegraph/src-cli/internal/api" - "github.com/sourcegraph/src-cli/internal/features" -) - -var teamsCommands commander - -func init() { - usage := `'src teams' is a tool that manages teams in a Sourcegraph instance. - -Usage: - - src teams command [command options] - -The commands are: - - list lists teams - create create a team - update update a team - delete delete a team - members manage team members, use "src teams members [command] -h" for more information. - -Use "src teams [command] -h" for more information about a command. -` - - flagSet := flag.NewFlagSet("teams", flag.ExitOnError) - handler := func(args []string) error { - if err := checkTeamsAvailability(); err != nil { - return err - } - teamsCommands.run(flagSet, "src teams", usage, args) - return nil - } - - // Register the command. - commands = append(commands, &command{ - flagSet: flagSet, - aliases: []string{"team"}, - handler: handler, - usageFunc: func() { - fmt.Println(usage) - }, - }) -} - -// checkTeamsAvailability verifies that the connected Sourcegraph instance -// supports teams. Teams were removed in Sourcegraph 7.0. -func checkTeamsAvailability() error { - client := cfg.apiClient(api.NewFlags(flag.NewFlagSet("", flag.ContinueOnError)), os.Stderr) - - version, err := api.GetSourcegraphVersion(context.Background(), client) - if err != nil || version == "" { - // If we can't determine the version, let the command proceed. - return nil - } - - var ffs features.FeatureFlags - if err := ffs.SetFromVersion(version, true); err != nil { - return nil - } - if ffs.Sourcegraph70 { - return fmt.Errorf("the 'src teams' commands are not available for Sourcegraph versions 7.0 and later (detected version: %s). Teams have been removed", version) - } - return nil -} - -const teamFragment = ` -fragment TeamFields on Team { - id - name - displayName - readonly -} -` - -type Team struct { - ID string `json:"id"` - Name string `json:"name"` - DisplayName string `json:"displayName"` - Readonly bool `json:"readonly"` -} diff --git a/cmd/src/teams_create.go b/cmd/src/teams_create.go deleted file mode 100644 index fd64fded4e..0000000000 --- a/cmd/src/teams_create.go +++ /dev/null @@ -1,96 +0,0 @@ -package main - -import ( - "context" - "flag" - "fmt" - "strings" - - "github.com/sourcegraph/sourcegraph/lib/errors" - - "github.com/sourcegraph/src-cli/internal/api" - "github.com/sourcegraph/src-cli/internal/cmderrors" -) - -func init() { - usage := ` -Examples: - - Create a team "engineering": - - $ src teams create -name='engineering' [-display-name='Engineering Team'] [-parent-team='engineering-leadership'] [-read-only] - -` - - flagSet := flag.NewFlagSet("create", flag.ExitOnError) - usageFunc := func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src teams %s':\n", flagSet.Name()) - flagSet.PrintDefaults() - fmt.Println(usage) - } - var ( - nameFlag = flagSet.String("name", "", "The team name") - displayNameFlag = flagSet.String("display-name", "", "Optional additional display name for a more human-readable UI") - parentTeamFlag = flagSet.String("parent-team", "", "Optional name or ID of the parent team") - readonlyFlag = flagSet.Bool("read-only", false, "Optionally create the team as read-only marking it as externally managed in this UI") - apiFlags = api.NewFlags(flagSet) - ) - - handler := func(args []string) error { - if err := flagSet.Parse(args); err != nil { - return err - } - - if *nameFlag == "" { - return errors.New("provide a name") - } - - client := cfg.apiClient(apiFlags, flagSet.Output()) - - query := `mutation CreateTeam( - $name: String!, - $displayName: String, - $parentTeam: String, - $readonly: Boolean -) { - createTeam( - name: $name, - displayName: $displayName, - parentTeamName: $parentTeam, - readonly: $readonly, - ) { - ...TeamFields - } -} -` + teamFragment - - var result struct { - CreateTeam Team - } - if ok, err := client.NewRequest(query, map[string]any{ - "name": *nameFlag, - "displayName": api.NullString(*displayNameFlag), - "parentTeam": api.NullString(*parentTeamFlag), - "readonly": *readonlyFlag, - }).Do(context.Background(), &result); err != nil || !ok { - var gqlErr api.GraphQlErrors - if errors.As(err, &gqlErr) { - for _, e := range gqlErr { - if strings.Contains(e.Error(), "team name is already taken") { - return cmderrors.ExitCode(3, err) - } - } - } - return err - } - - return nil - } - - // Register the command. - teamsCommands = append(teamsCommands, &command{ - flagSet: flagSet, - handler: handler, - usageFunc: usageFunc, - }) -} diff --git a/cmd/src/teams_delete.go b/cmd/src/teams_delete.go deleted file mode 100644 index ce89f19b9f..0000000000 --- a/cmd/src/teams_delete.go +++ /dev/null @@ -1,74 +0,0 @@ -package main - -import ( - "context" - "flag" - "fmt" - - "github.com/sourcegraph/sourcegraph/lib/errors" - - "github.com/sourcegraph/src-cli/internal/api" -) - -func init() { - usage := ` -Examples: - - Delete the team "engineering": - - $ src teams delete -name='engineering' - -` - - flagSet := flag.NewFlagSet("delete", flag.ExitOnError) - usageFunc := func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src teams %s':\n", flagSet.Name()) - flagSet.PrintDefaults() - fmt.Println(usage) - } - var ( - nameFlag = flagSet.String("name", "", "The team name") - apiFlags = api.NewFlags(flagSet) - ) - - handler := func(args []string) error { - if err := flagSet.Parse(args); err != nil { - return err - } - - if *nameFlag == "" { - return errors.New("provide a name") - } - - client := cfg.apiClient(apiFlags, flagSet.Output()) - - query := `mutation DeleteTeam( - $name: String!, -) { - deleteTeam( - name: $name, - ) { - alwaysNil - } -} -` - - var result struct { - DeleteTeam any - } - if ok, err := client.NewRequest(query, map[string]any{ - "name": *nameFlag, - }).Do(context.Background(), &result); err != nil || !ok { - return err - } - - return nil - } - - // Register the command. - teamsCommands = append(teamsCommands, &command{ - flagSet: flagSet, - handler: handler, - usageFunc: usageFunc, - }) -} diff --git a/cmd/src/teams_list.go b/cmd/src/teams_list.go deleted file mode 100644 index 37efd25bfc..0000000000 --- a/cmd/src/teams_list.go +++ /dev/null @@ -1,130 +0,0 @@ -package main - -import ( - "context" - "encoding/json" - "flag" - "fmt" - "os" - - "github.com/sourcegraph/src-cli/internal/api" -) - -func init() { - usage := ` -Examples: - - List teams: - - $ src teams list - - List teams whose names match the query: - - $ src teams list -query='myquery' -` - - flagSet := flag.NewFlagSet("list", flag.ExitOnError) - usageFunc := func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src teams %s':\n", flagSet.Name()) - flagSet.PrintDefaults() - fmt.Println(usage) - } - var ( - firstFlag = flagSet.Int("first", 1000, "Returns the first n teams from the list") - parentTeamFlag = flagSet.String("parent-team", "", "Get child teams of the given team") - queryFlag = flagSet.String("query", "", `Returns teams whose name or displayname match the query. (e.g. "engineering")`) - formatFlag = flagSet.String("f", "{{.Name}} {{if .DisplayName}}({{.DisplayName}}){{end}}", `Format for the output, using the syntax of Go package text/template. (e.g. "{{.Name}}: {{.DisplayName}}" or "{{.|json}}")`) - jsonFlag = flagSet.Bool("json", false, `Format for the output as json`) - apiFlags = api.NewFlags(flagSet) - ) - - handler := func(args []string) error { - if err := flagSet.Parse(args); err != nil { - return err - } - - tmpl, err := parseTemplate(*formatFlag) - if err != nil { - return err - } - - client := cfg.apiClient(apiFlags, flagSet.Output()) - - query := `query Teams( - $first: Int, - $search: String -) { - teams( - first: $first, - search: $search - ) { - nodes { - ...TeamFields - } - - } -}` + teamFragment - - if *parentTeamFlag != "" { - query = `query ChildTeams( - $first: Int, - $search: String, - $parentTeamName: String! - ) { - team(name: $parentTeamName) { - childTeams( - first: $first, - search: $search - ) { - nodes { - ...TeamFields - } - - } - } - }` + teamFragment - } - - var result struct { - Teams struct { - Nodes []Team - } - Team struct { - ChildTeams struct { - Nodes []Team - } - } - } - if ok, err := client.NewRequest(query, map[string]any{ - "first": api.NullInt(*firstFlag), - "search": api.NullString(*queryFlag), - "parentTeamName": api.NullString(*parentTeamFlag), - }).Do(context.Background(), &result); err != nil || !ok { - return err - } - - nodes := result.Teams.Nodes - if *parentTeamFlag != "" { - nodes = result.Team.ChildTeams.Nodes - } - - if jsonFlag != nil && *jsonFlag { - json.NewEncoder(os.Stdout).Encode(nodes) - return nil - } - - for _, t := range nodes { - if err := execTemplate(tmpl, t); err != nil { - return err - } - } - return nil - } - - // Register the command. - teamsCommands = append(teamsCommands, &command{ - flagSet: flagSet, - handler: handler, - usageFunc: usageFunc, - }) -} diff --git a/cmd/src/teams_members.go b/cmd/src/teams_members.go deleted file mode 100644 index 15be1b5331..0000000000 --- a/cmd/src/teams_members.go +++ /dev/null @@ -1,55 +0,0 @@ -package main - -import ( - "flag" - "fmt" -) - -var teamMembersCommands commander - -func init() { - usage := `'src teams members' is a tool that manages team membership in a Sourcegraph instance. - -Usage: - - src team members command [command options] - -The commands are: - - list lists team members - add add team members - remove remove team members - -Use "src team members [command] -h" for more information about a command. -` - - flagSet := flag.NewFlagSet("members", flag.ExitOnError) - handler := func(args []string) error { - teamMembersCommands.run(flagSet, "src teams members", usage, args) - return nil - } - - // Register the command. - teamsCommands = append(teamsCommands, &command{ - flagSet: flagSet, - aliases: []string{"member"}, - handler: handler, - usageFunc: func() { - fmt.Println(usage) - }, - }) -} - -const teamMemberFragment = ` -fragment TeamMemberFields on TeamMember { - ... on User { - id - username - } -} -` - -type TeamMember struct { - ID string `json:"id"` - Username string `json:"username"` -} diff --git a/cmd/src/teams_members_add.go b/cmd/src/teams_members_add.go deleted file mode 100644 index ebc530cb4a..0000000000 --- a/cmd/src/teams_members_add.go +++ /dev/null @@ -1,108 +0,0 @@ -package main - -import ( - "context" - "flag" - "fmt" - - "github.com/sourcegraph/sourcegraph/lib/errors" - - "github.com/sourcegraph/src-cli/internal/api" -) - -func init() { - usage := ` -Examples: - - Add a team member: - - $ src teams members add -team-name='engineering' [-email='alice@sourcegraph.com'] [-username='alice'] [-id='VXNlcjox'] [-external-account-service-id='https://github.com/' -external-account-service-type='github' [-external-account-account-id='123123123'] [-external-account-login='alice']] - -` - - flagSet := flag.NewFlagSet("add", flag.ExitOnError) - usageFunc := func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src teams %s':\n", flagSet.Name()) - flagSet.PrintDefaults() - fmt.Println(usage) - } - var ( - teamNameFlag = flagSet.String("team-name", "", "The team name") - skipUnmatchedMembersFlag = flagSet.Bool("skip-unmatched-members", false, "If true, members that don't match a Sourcegraph user or team will be silently skipped") - emailFlag = flagSet.String("email", "", "Email to match the user by") - usernameFlag = flagSet.String("username", "", "Username to match the user by") - idFlag = flagSet.String("id", "", "Sourcegraph user ID to match the user by") - externalAccountServiceIDFlag = flagSet.String("external-account-service-id", "", "External account service ID to match the user by, must specify all of externalAccount*") - externalAccountServiceTypeFlag = flagSet.String("external-account-service-type", "", "External account service type to match the user by, must specify all of externalAccount*") - externalAccountAccountIDFlag = flagSet.String("external-account-account-id", "", "External account account ID to match the user by, must specify all of externalAccount*") - externalAccountLoginFlag = flagSet.String("external-account-login", "", "External account login ID to match the user by, must specify all of externalAccount*") - apiFlags = api.NewFlags(flagSet) - ) - - handler := func(args []string) error { - if err := flagSet.Parse(args); err != nil { - return err - } - - if *teamNameFlag == "" { - return errors.New("provide a team name") - } - - client := cfg.apiClient(apiFlags, flagSet.Output()) - - query := `mutation AddTeamMember( - $teamName: String! - $id: ID, - $email: String, - $username: String, - $externalAccountServiceID: String, - $externalAccountServiceType: String, - $externalAccountAccountID: String, - $externalAccountLogin: String, - $skipUnmatchedMembers: Boolean, -) { - addTeamMembers( - teamName: $teamName, - members: [{ - userID: $id, - email: $email, - username: $username, - externalAccountServiceID: $externalAccountServiceID, - externalAccountServiceType: $externalAccountServiceType, - externalAccountAccountID: $externalAccountAccountID, - externalAccountLogin: $externalAccountLogin, - }], - skipUnmatchedMembers: $skipUnmatchedMembers, - ) { - ...TeamFields - } -} -` + teamFragment - - var result struct { - AddTeamMembers Team - } - if ok, err := client.NewRequest(query, map[string]any{ - "teamName": *teamNameFlag, - "skipUnmatchedMembers": *skipUnmatchedMembersFlag, - "id": api.NullString(*idFlag), - "email": api.NullString(*emailFlag), - "username": api.NullString(*usernameFlag), - "externalAccountServiceID": api.NullString(*externalAccountServiceIDFlag), - "externalAccountServiceType": api.NullString(*externalAccountServiceTypeFlag), - "externalAccountAccountID": api.NullString(*externalAccountAccountIDFlag), - "externalAccountLogin": api.NullString(*externalAccountLoginFlag), - }).Do(context.Background(), &result); err != nil || !ok { - return err - } - - return nil - } - - // Register the command. - teamMembersCommands = append(teamMembersCommands, &command{ - flagSet: flagSet, - handler: handler, - usageFunc: usageFunc, - }) -} diff --git a/cmd/src/teams_members_remove.go b/cmd/src/teams_members_remove.go deleted file mode 100644 index fc52c32c34..0000000000 --- a/cmd/src/teams_members_remove.go +++ /dev/null @@ -1,108 +0,0 @@ -package main - -import ( - "context" - "flag" - "fmt" - - "github.com/sourcegraph/sourcegraph/lib/errors" - - "github.com/sourcegraph/src-cli/internal/api" -) - -func init() { - usage := ` -Examples: - - Remove a team member: - - $ src teams members remove -team-name='engineering' [-email='alice@sourcegraph.com'] [-username='alice'] [-id='VXNlcjox'] [-external-account-service-id='https://github.com/' -external-account-service-type='github' [-external-account-account-id='123123123'] [-external-account-login='alice']] - -` - - flagSet := flag.NewFlagSet("remove", flag.ExitOnError) - usageFunc := func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src teams %s':\n", flagSet.Name()) - flagSet.PrintDefaults() - fmt.Println(usage) - } - var ( - teamNameFlag = flagSet.String("team-name", "", "The team name") - skipUnmatchedMembersFlag = flagSet.Bool("skip-unmatched-members", false, "If true, members that don't match a Sourcegraph user or team will be silently skipped") - emailFlag = flagSet.String("email", "", "Email to match the user by") - usernameFlag = flagSet.String("username", "", "Username to match the user by") - idFlag = flagSet.String("id", "", "Sourcegraph user ID to match the user by") - externalAccountServiceIDFlag = flagSet.String("external-account-service-id", "", "External account service ID to match the user by, must specify all of externalAccount*") - externalAccountServiceTypeFlag = flagSet.String("external-account-service-type", "", "External account service type to match the user by, must specify all of externalAccount*") - externalAccountAccountIDFlag = flagSet.String("external-account-account-id", "", "External account account ID to match the user by, must specify all of externalAccount*") - externalAccountLoginFlag = flagSet.String("external-account-login", "", "External account login ID to match the user by, must specify all of externalAccount*") - apiFlags = api.NewFlags(flagSet) - ) - - handler := func(args []string) error { - if err := flagSet.Parse(args); err != nil { - return err - } - - if *teamNameFlag == "" { - return errors.New("provide a team name") - } - - client := cfg.apiClient(apiFlags, flagSet.Output()) - - query := `mutation RemoveTeamMember( - $teamName: String! - $id: ID, - $email: String, - $username: String, - $externalAccountServiceID: String, - $externalAccountServiceType: String, - $externalAccountAccountID: String, - $externalAccountLogin: String, - $skipUnmatchedMembers: Boolean, -) { - removeTeamMembers( - teamName: $teamName, - members: [{ - userID: $id, - email: $email, - username: $username, - externalAccountServiceID: $externalAccountServiceID, - externalAccountServiceType: $externalAccountServiceType, - externalAccountAccountID: $externalAccountAccountID, - externalAccountLogin: $externalAccountLogin, - }], - skipUnmatchedMembers: $skipUnmatchedMembers, - ) { - ...TeamFields - } -} -` + teamFragment - - var result struct { - RemoveTeamMembers Team - } - if ok, err := client.NewRequest(query, map[string]any{ - "teamName": *teamNameFlag, - "skipUnmatchedMembers": *skipUnmatchedMembersFlag, - "id": api.NullString(*idFlag), - "email": api.NullString(*emailFlag), - "username": api.NullString(*usernameFlag), - "externalAccountServiceID": api.NullString(*externalAccountServiceIDFlag), - "externalAccountServiceType": api.NullString(*externalAccountServiceTypeFlag), - "externalAccountAccountID": api.NullString(*externalAccountAccountIDFlag), - "externalAccountLogin": api.NullString(*externalAccountLoginFlag), - }).Do(context.Background(), &result); err != nil || !ok { - return err - } - - return nil - } - - // Register the command. - teamMembersCommands = append(teamMembersCommands, &command{ - flagSet: flagSet, - handler: handler, - usageFunc: usageFunc, - }) -} diff --git a/cmd/src/teams_update.go b/cmd/src/teams_update.go deleted file mode 100644 index ae5bdb2331..0000000000 --- a/cmd/src/teams_update.go +++ /dev/null @@ -1,92 +0,0 @@ -package main - -import ( - "context" - "flag" - "fmt" - "strings" - - "github.com/sourcegraph/sourcegraph/lib/errors" - - "github.com/sourcegraph/src-cli/internal/api" - "github.com/sourcegraph/src-cli/internal/cmderrors" -) - -func init() { - usage := ` -Examples: - - Update the team "engineering": - - $ src teams update -name='engineering' [-display-name='Engineering Team'] [-parent-team='engineering-leadership'] - -` - - flagSet := flag.NewFlagSet("update", flag.ExitOnError) - usageFunc := func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src teams %s':\n", flagSet.Name()) - flagSet.PrintDefaults() - fmt.Println(usage) - } - var ( - nameFlag = flagSet.String("name", "", "The team name") - displayNameFlag = flagSet.String("display-name", "", "Optional additional display name for a more human-readable UI") - parentTeamFlag = flagSet.String("parent-team", "", "Optional name or ID of the parent team") - apiFlags = api.NewFlags(flagSet) - ) - - handler := func(args []string) error { - if err := flagSet.Parse(args); err != nil { - return err - } - - if *nameFlag == "" { - return errors.New("provide a name") - } - - client := cfg.apiClient(apiFlags, flagSet.Output()) - - query := `mutation UpdateTeam( - $name: String!, - $displayName: String, - $parentTeam: String -) { - updateTeam( - name: $name, - displayName: $displayName, - parentTeamName: $parentTeam, - ) { - ...TeamFields - } -} -` + teamFragment - - var result struct { - UpdateTeam Team - } - if ok, err := client.NewRequest(query, map[string]any{ - "name": *nameFlag, - "displayName": api.NullString(*displayNameFlag), - "parentTeam": api.NullString(*parentTeamFlag), - }).Do(context.Background(), &result); err != nil || !ok { - var gqlErr api.GraphQlErrors - if errors.As(err, &gqlErr) { - for _, e := range gqlErr { - if strings.Contains(e.Error(), "team name is already taken") { - return cmderrors.ExitCode(3, err) - } - } - } - return err - } - - return nil - } - - // Register the command. - teamsCommands = append(teamsCommands, &command{ - flagSet: flagSet, - handler: handler, - usageFunc: usageFunc, - }) -} diff --git a/internal/features/features.go b/internal/features/features.go index 657ece2f14..52fcd1d5c9 100644 --- a/internal/features/features.go +++ b/internal/features/features.go @@ -13,7 +13,6 @@ import ( type FeatureFlags struct { Sourcegraph40 bool BinaryDiffs bool - Sourcegraph70 bool } func (ff *FeatureFlags) SetFromVersion(version string, skipErrors bool) error { @@ -33,7 +32,6 @@ func (ff *FeatureFlags) SetFromVersion(version string, skipErrors bool) error { // {&ff.FlagName, ">= 3.23.0-0", "2020-11-24"}, {&ff.Sourcegraph40, ">= 4.0.0-0", "2022-08-24"}, {&ff.BinaryDiffs, ">= 4.3.0-0", "2022-11-29"}, - {&ff.Sourcegraph70, ">= 7.0.0-0", "2026-02-25"}, } { value, err := api.CheckSourcegraphVersion(version, feature.constraint, feature.minDate) if err != nil { From 2fc111e9c2f446785e7d9a00be85512083390962 Mon Sep 17 00:00:00 2001 From: Marc <7050295+marcleblanc2@users.noreply.github.com> Date: Mon, 28 Sep 2026 13:34:56 -0600 Subject: [PATCH 629/647] help: generate the 'src help' command list from the registered commands (#1377) The "The commands are:" block in 'src help' was a hand-maintained string in main.go. It had drifted from the registered commands: 'debug', 'snapshot', and 'lsp' were never added, and the codeowners description differed from the command's own Usage. Build the list at runtime from both registries (legacy 'commands' and urfave/cli 'migratedCommands'). Legacy commands get a 'description' field and a 'hidden' flag; 'src doc' uses the same flag instead of hard-coding the names to skip. 'version' gets a Usage so it has a description. Tests keep the three lists apples-to-apples: - 'src help' == registered commands (TestHelpListsAllRegisteredCommands) - 'src doc' root index == 'src help' == registered (TestDocRootIndexMatchesHelp) - every visible command has a description (TestRootCommandsAreWellFormed) Amp-Thread-ID: https://ampcode.com/threads/T-01a08410-86ca-72be-9928-2810e837fae1 Co-authored-by: Amp --- CHANGELOG.md | 1 + cmd/src/batch.go | 3 +- cmd/src/cmd.go | 8 +++ cmd/src/code_intel.go | 7 ++- cmd/src/config.go | 5 +- cmd/src/debug.go | 8 +-- cmd/src/doc.go | 3 +- cmd/src/doc_test.go | 32 ++++++----- cmd/src/extsvc.go | 7 ++- cmd/src/help.go | 121 +++++++++++++++++++++++++++++++++++++++++ cmd/src/help_test.go | 113 ++++++++++++++++++++++++++++++++++++++ cmd/src/lsp.go | 7 ++- cmd/src/main.go | 54 +----------------- cmd/src/repos.go | 7 ++- cmd/src/search.go | 5 +- cmd/src/search_jobs.go | 7 ++- cmd/src/servegit.go | 9 +-- cmd/src/snapshot.go | 3 +- cmd/src/version.go | 1 + 19 files changed, 305 insertions(+), 96 deletions(-) create mode 100644 cmd/src/help.go create mode 100644 cmd/src/help_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index e437c99c89..7cd8ccb416 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,7 @@ All notable changes to `src-cli` are documented in this file. - HTTP requests now fail instead of hanging forever if the server does not start responding within 1 minute. Set the `SRC_RESPONSE_HEADER_TIMEOUT` environment variable to change this timeout, or to `0` to disable it. Responses that stream data for a long time (for example, large search job results) are not affected. - `src search-jobs logs` and `src search-jobs results` now use the standard API client, gaining proxy support, `-insecure-skip-verify`, and cross-host redirect protection, and now report an error on non-200 responses instead of writing the error page into the output. +- The command list in `src help` is now generated from the registered commands instead of being maintained by hand. `src debug`, `src snapshot`, and `src lsp` now appear in it; aliases are shown after each description. ### Fixed diff --git a/cmd/src/batch.go b/cmd/src/batch.go index fd42257f7d..82ecaba9a3 100644 --- a/cmd/src/batch.go +++ b/cmd/src/batch.go @@ -37,7 +37,8 @@ Use "src batch [command] -h" for more information about a command. // Register the command. commands = append(commands, &command{ - flagSet: flagSet, + flagSet: flagSet, + description: "manages batch changes", aliases: []string{ "batchchange", "batch-change", diff --git a/cmd/src/cmd.go b/cmd/src/cmd.go index 9182dc57ea..65d1d9982a 100644 --- a/cmd/src/cmd.go +++ b/cmd/src/cmd.go @@ -22,6 +22,14 @@ type command struct { // flagSet.Usage function to invoke on e.g. -h flag. If nil, a default one is // used. usageFunc func() + + // description is the one-line summary shown next to the command in + // 'src help'. Required for top-level commands unless hidden is set. + description string + + // hidden excludes the command from 'src help' and from the reference + // documentation generated by 'src doc'. It can still be run. + hidden bool } // matches tells if the given name matches this command or one of its aliases. diff --git a/cmd/src/code_intel.go b/cmd/src/code_intel.go index 3dc3f28d8c..7e11db9a4d 100644 --- a/cmd/src/code_intel.go +++ b/cmd/src/code_intel.go @@ -28,9 +28,10 @@ Use "src code-intel [command] -h" for more information about a command. // Register the command. commands = append(commands, &command{ - flagSet: flagSet, - aliases: []string{"code-intel"}, - handler: handler, + flagSet: flagSet, + description: "manages code intelligence data", + aliases: []string{"code-intel"}, + handler: handler, usageFunc: func() { fmt.Println(usage) }, diff --git a/cmd/src/config.go b/cmd/src/config.go index f04966b972..e6e7dfc937 100644 --- a/cmd/src/config.go +++ b/cmd/src/config.go @@ -45,8 +45,9 @@ Use "src config [command] -h" for more information about a command. // Register the command. commands = append(commands, &command{ - flagSet: flagSet, - handler: handler, + flagSet: flagSet, + description: "manages global, org, and user settings", + handler: handler, usageFunc: func() { fmt.Println(usage) }, diff --git a/cmd/src/debug.go b/cmd/src/debug.go index 2a513cb1c4..4ee47d3781 100644 --- a/cmd/src/debug.go +++ b/cmd/src/debug.go @@ -34,9 +34,9 @@ src debug has access to flags on src -- Ex: src -v kube -o foo.zip // Register the command. commands = append(commands, &command{ - flagSet: flagSet, - aliases: []string{}, - handler: handler, - usageFunc: func() { fmt.Println(usage) }, + flagSet: flagSet, + description: "gathers and bundles debug data from a Sourcegraph deployment for troubleshooting", + handler: handler, + usageFunc: func() { fmt.Println(usage) }, }) } diff --git a/cmd/src/doc.go b/cmd/src/doc.go index ebc3018dba..d8108c4aa1 100644 --- a/cmd/src/doc.go +++ b/cmd/src/doc.go @@ -82,7 +82,7 @@ Examples: name, }, " ")) - if fqcn == "doc" || fqcn == "publish" { + if cmd.hidden { continue } @@ -176,6 +176,7 @@ Examples: commands = append(commands, &command{ flagSet: flagSet, + hidden: true, handler: handler, usageFunc: func() { fmt.Fprintln(flag.CommandLine.Output(), usage) diff --git a/cmd/src/doc_test.go b/cmd/src/doc_test.go index e5615054ed..4f886405cb 100644 --- a/cmd/src/doc_test.go +++ b/cmd/src/doc_test.go @@ -186,9 +186,10 @@ func TestDocLegacyGroupsHaveSubcommandPages(t *testing.T) { } } -// The root index must link every top-level command, both legacy (commander) -// and migrated (urfave/cli) ones. -func TestDocRootIndexListsAllCommands(t *testing.T) { +// The root index.md written by 'src doc' must link exactly the commands that +// 'src help' lists, which in turn must be exactly the registered commands. +// A command that is registered but missing from either is a bug. +func TestDocRootIndexMatchesHelp(t *testing.T) { dir, _ := runDocCommand(t) index, err := os.ReadFile(filepath.Join(dir, "index.md")) @@ -196,18 +197,23 @@ func TestDocRootIndexListsAllCommands(t *testing.T) { t.Fatal(err) } - var missing []string - for _, cmd := range commands { - name := cmd.flagSet.Name() - if name == "doc" || name == "publish" { + var indexed []string + for _, line := range strings.Split(string(index), "\n") { + // Lines look like: * [`name`](name.md) or * [`name`](name/index.md) + rest, ok := strings.CutPrefix(strings.TrimSpace(line), "* [`") + if !ok { continue } - if !strings.Contains(string(index), "[`"+name+"`](") { - missing = append(missing, name) - } + name, _, _ := strings.Cut(rest, "`") + indexed = append(indexed, name) + } + sort.Strings(indexed) + + registered := registeredRootCommandNames() + if diff := cmp.Diff(registered, indexed); diff != "" { + t.Errorf("'src doc' root index does not match the registered commands (-registered +index):\n%s", diff) } - if len(missing) > 0 { - sort.Strings(missing) - t.Errorf("root index.md is missing legacy commands: %v", missing) + if diff := cmp.Diff(helpCommandNames(t, usageText()), indexed); diff != "" { + t.Errorf("'src doc' root index does not match 'src help' (-help +index):\n%s", diff) } } diff --git a/cmd/src/extsvc.go b/cmd/src/extsvc.go index c3a9aed37f..3b068162e8 100644 --- a/cmd/src/extsvc.go +++ b/cmd/src/extsvc.go @@ -36,9 +36,10 @@ Use "src extsvc [command] -h" for more information about a command. // Register the command. commands = append(commands, &command{ - flagSet: flagSet, - aliases: []string{"extsvc", "external-service"}, - handler: handler, + flagSet: flagSet, + description: "manages external services", + aliases: []string{"extsvc", "external-service"}, + handler: handler, usageFunc: func() { fmt.Println(usage) }, diff --git a/cmd/src/help.go b/cmd/src/help.go new file mode 100644 index 0000000000..5c104e8001 --- /dev/null +++ b/cmd/src/help.go @@ -0,0 +1,121 @@ +package main + +import ( + "cmp" + "fmt" + "slices" + "strings" + + "github.com/sourcegraph/sourcegraph/lib/docgen" +) + +// rootCommand is a top-level 'src' command as shown in 'src help'. It is the +// single source for the command list in the help text and for the tests that +// keep 'src help' and the 'src doc' root index in sync. +type rootCommand struct { + name string + aliases []string + description string +} + +// rootCommands returns every visible top-level command, whether it is +// registered with the legacy commander (commands) or with urfave/cli +// (migratedCommands), sorted by name. +func rootCommands() []rootCommand { + var root []rootCommand + + for _, cmd := range commands { + if cmd.hidden { + continue + } + name := cmd.flagSet.Name() + var aliases []string + for _, alias := range cmd.aliases { + // Some legacy commands register their own name as an alias. + if alias != name { + aliases = append(aliases, alias) + } + } + root = append(root, rootCommand{ + name: name, + aliases: aliases, + description: cmd.description, + }) + } + + for _, cmd := range docgen.VisibleCommands(migratedRootCommand().Commands) { + root = append(root, rootCommand{ + name: cmd.Name, + aliases: slices.Clone(cmd.Aliases), + description: cmd.Usage, + }) + } + + slices.SortFunc(root, func(a, b rootCommand) int { + return cmp.Compare(a.name, b.name) + }) + return root +} + +// formatCommandList renders the "The commands are:" block of 'src help': +// one tab-indented line per command with the name padded to a common width, +// the description, and any aliases in parentheses. +func formatCommandList(cmds []rootCommand) string { + width := 0 + for _, cmd := range cmds { + width = max(width, len(cmd.name)) + } + + var b strings.Builder + for _, cmd := range cmds { + fmt.Fprintf(&b, "\t%-*s %s", width, cmd.name, cmd.description) + if len(cmd.aliases) > 0 { + fmt.Fprintf(&b, " (alias: %s)", strings.Join(cmd.aliases, ", ")) + } + b.WriteString("\n") + } + return b.String() +} + +// usageText renders the top-level 'src help' output. +func usageText() string { + return usageHeader + formatCommandList(rootCommands()) + usageFooter +} + +const usageHeader = `src is a tool that provides access to Sourcegraph instances. +For more information, see https://github.com/sourcegraph/src-cli + +Usage: + + src [options] command [command options] + +Environment variables + SRC_ACCESS_TOKEN Sourcegraph access token + SRC_ENDPOINT endpoint to use, if unset will default to "https://sourcegraph.com" + SRC_PROXY A proxy to use for proxying requests to the Sourcegraph endpoint. + Supports HTTP(S), SOCKS5/5h, and UNIX Domain Socket proxies. + If a UNIX Domain Socket, the path can be either an absolute path, + or can start with ~/ or %USERPROFILE%\ for a path in the user's home directory. + Examples: + - https://localhost:3080 + - https://:localhost:8080 + - socks5h://localhost:1080 + - socks5://:@localhost:1080 + - unix://~/src-proxy.sock + - unix://%USERPROFILE%\src-proxy.sock + - ~/src-proxy.sock + - %USERPROFILE%\src-proxy.sock + - C:\some\path\src-proxy.sock + +The options are: + + -v print verbose output + +The commands are: + +` + +const usageFooter = ` +Use "src [command] -h" for more information about a command. + +` diff --git a/cmd/src/help_test.go b/cmd/src/help_test.go new file mode 100644 index 0000000000..4260f381fd --- /dev/null +++ b/cmd/src/help_test.go @@ -0,0 +1,113 @@ +package main + +import ( + "sort" + "strings" + "testing" + + "github.com/google/go-cmp/cmp" +) + +// registeredRootCommandNames computes the set of visible top-level command +// names straight from the two registries, independently of rootCommands(), so +// the tests below catch a command that is registered but left out of the help +// text or the docs. +func registeredRootCommandNames() []string { + seen := map[string]bool{} + for _, cmd := range commands { + if !cmd.hidden { + seen[cmd.flagSet.Name()] = true + } + } + for _, cmd := range migratedCommands { + if !cmd.Hidden { + seen[cmd.Name] = true + } + } + names := make([]string, 0, len(seen)) + for name := range seen { + names = append(names, name) + } + sort.Strings(names) + return names +} + +// helpCommandNames parses the "The commands are:" block of the given 'src +// help' output and returns the command names (without aliases), sorted. +func helpCommandNames(t *testing.T, help string) []string { + t.Helper() + + _, block, ok := strings.Cut(help, "The commands are:\n") + if !ok { + t.Fatalf("help text has no \"The commands are:\" block:\n%s", help) + } + block, _, _ = strings.Cut(block, "\nUse \"src [command] -h\"") + + var names []string + for _, line := range strings.Split(block, "\n") { + line = strings.TrimSpace(line) + if line == "" { + continue + } + name, _, _ := strings.Cut(line, " ") + names = append(names, name) + } + sort.Strings(names) + return names +} + +func TestHelpListsAllRegisteredCommands(t *testing.T) { + got := helpCommandNames(t, usageText()) + if diff := cmp.Diff(registeredRootCommandNames(), got); diff != "" { + t.Errorf("'src help' command list does not match the registered commands (-registered +help):\n%s", diff) + } +} + +func TestHelpHidesHiddenCommands(t *testing.T) { + help := usageText() + for _, cmd := range commands { + if cmd.hidden && strings.Contains(help, "\t"+cmd.flagSet.Name()+" ") { + t.Errorf("hidden command %q is listed in 'src help'", cmd.flagSet.Name()) + } + } + if !strings.Contains(help, "\tabc ") || !strings.Contains(help, "\tbatch") { + t.Errorf("expected both a urfave/cli command (abc) and a legacy command (batch) in help:\n%s", help) + } +} + +func TestRootCommandsAreWellFormed(t *testing.T) { + names := map[string]bool{} + for _, cmd := range rootCommands() { + if cmd.description == "" { + t.Errorf("command %q has no description: set description on the legacy command or Usage on the urfave/cli command", cmd.name) + } + if names[cmd.name] { + t.Errorf("command %q is registered more than once", cmd.name) + } + names[cmd.name] = true + for _, alias := range cmd.aliases { + if alias == cmd.name { + t.Errorf("command %q lists its own name as an alias", cmd.name) + } + } + } + for _, cmd := range rootCommands() { + for _, alias := range cmd.aliases { + if names[alias] { + t.Errorf("alias %q of command %q collides with another command's name", alias, cmd.name) + } + } + } +} + +func TestFormatCommandList(t *testing.T) { + got := formatCommandList([]rootCommand{ + {name: "a", description: "first"}, + {name: "longer", aliases: []string{"l", "lg"}, description: "second"}, + }) + want := "\ta first\n" + + "\tlonger second (alias: l, lg)\n" + if diff := cmp.Diff(want, got); diff != "" { + t.Errorf("formatCommandList mismatch (-want +got):\n%s", diff) + } +} diff --git a/cmd/src/lsp.go b/cmd/src/lsp.go index e6d5608f13..64475bef9e 100644 --- a/cmd/src/lsp.go +++ b/cmd/src/lsp.go @@ -63,8 +63,9 @@ Example Neovim configuration (0.11+): } commands = append(commands, &command{ - flagSet: flagSet, - handler: handler, - usageFunc: usageFunc, + flagSet: flagSet, + description: "runs a Language Server Protocol server that proxies requests to Sourcegraph code intelligence", + handler: handler, + usageFunc: usageFunc, }) } diff --git a/cmd/src/main.go b/cmd/src/main.go index 9cc205a7ec..8635301b8a 100644 --- a/cmd/src/main.go +++ b/cmd/src/main.go @@ -21,58 +21,6 @@ import ( const SGDotComEndpoint = "https://sourcegraph.com" -const usageText = `src is a tool that provides access to Sourcegraph instances. -For more information, see https://github.com/sourcegraph/src-cli - -Usage: - - src [options] command [command options] - -Environment variables - SRC_ACCESS_TOKEN Sourcegraph access token - SRC_ENDPOINT endpoint to use, if unset will default to "https://sourcegraph.com" - SRC_PROXY A proxy to use for proxying requests to the Sourcegraph endpoint. - Supports HTTP(S), SOCKS5/5h, and UNIX Domain Socket proxies. - If a UNIX Domain Socket, the path can be either an absolute path, - or can start with ~/ or %USERPROFILE%\ for a path in the user's home directory. - Examples: - - https://localhost:3080 - - https://:localhost:8080 - - socks5h://localhost:1080 - - socks5://:@localhost:1080 - - unix://~/src-proxy.sock - - unix://%USERPROFILE%\src-proxy.sock - - ~/src-proxy.sock - - %USERPROFILE%\src-proxy.sock - - C:\some\path\src-proxy.sock - -The options are: - - -v print verbose output - -The commands are: - - abc manages agentic batch changes - auth authentication helper commands - api interacts with the Sourcegraph GraphQL API - batch manages batch changes - code-intel manages code intelligence data - config manages global, org, and user settings - extsvc manages external services - login authenticate to a Sourcegraph instance with your user credentials - orgs,org manages organizations - repos,repo manages repositories - search search for results on Sourcegraph - search-jobs manages search jobs - serve-git serves your local git repositories over HTTP for Sourcegraph to pull - users,user manages users - codeowners manages code ownership information - version display and compare the src-cli version against the recommended version for your instance - -Use "src [command] -h" for more information about a command. - -` - var ( verbose = flag.Bool("v", false, "print verbose output") @@ -102,7 +50,7 @@ func main() { } // if we didn't run a migrated command, then lets try running the legacy version - commands.run(flag.CommandLine, "src", usageText, normalizeDashHelp(os.Args[1:])) + commands.run(flag.CommandLine, "src", usageText(), normalizeDashHelp(os.Args[1:])) } // normalizeDashHelp converts --help to -help since Go's flag parser only supports single dash. diff --git a/cmd/src/repos.go b/cmd/src/repos.go index b839f6d1e8..b456457882 100644 --- a/cmd/src/repos.go +++ b/cmd/src/repos.go @@ -40,9 +40,10 @@ Use "src repos [command] -h" for more information about a command. // Register the command. commands = append(commands, &command{ - flagSet: flagSet, - aliases: []string{"repo"}, - handler: handler, + flagSet: flagSet, + description: "manages repositories", + aliases: []string{"repo"}, + handler: handler, usageFunc: func() { fmt.Println(usage) }, diff --git a/cmd/src/search.go b/cmd/src/search.go index 9cbb050a4d..6266fd6daa 100644 --- a/cmd/src/search.go +++ b/cmd/src/search.go @@ -291,8 +291,9 @@ Other tips: // Register the command. commands = append(commands, &command{ - flagSet: flagSet, - handler: handler, + flagSet: flagSet, + description: "search for results on Sourcegraph", + handler: handler, usageFunc: func() { fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src %s':\n", flagSet.Name()) flagSet.PrintDefaults() diff --git a/cmd/src/search_jobs.go b/cmd/src/search_jobs.go index 986aaf1603..4f6c15233b 100644 --- a/cmd/src/search_jobs.go +++ b/cmd/src/search_jobs.go @@ -309,9 +309,10 @@ func init() { } commands = append(commands, &command{ - flagSet: flagSet, - aliases: []string{"search-job"}, - handler: handler, + flagSet: flagSet, + description: "manages search jobs", + aliases: []string{"search-job"}, + handler: handler, usageFunc: func() { fmt.Println(usage) }, diff --git a/cmd/src/servegit.go b/cmd/src/servegit.go index 11c4c30c31..2b6a36fcef 100644 --- a/cmd/src/servegit.go +++ b/cmd/src/servegit.go @@ -88,9 +88,10 @@ Documentation at https://sourcegraph.com/docs/admin/code_hosts/src_serve_git // Register the command. commands = append(commands, &command{ - aliases: []string{"servegit"}, - flagSet: flagSet, - handler: handler, - usageFunc: usageFunc, + aliases: []string{"servegit"}, + flagSet: flagSet, + description: "serves your local git repositories over HTTP for Sourcegraph to pull", + handler: handler, + usageFunc: usageFunc, }) } diff --git a/cmd/src/snapshot.go b/cmd/src/snapshot.go index 837ed3c21a..57e3e9396e 100644 --- a/cmd/src/snapshot.go +++ b/cmd/src/snapshot.go @@ -29,7 +29,8 @@ Use "src snapshot [command] -h" for more information about a command. flagSet := flag.NewFlagSet("snapshot", flag.ExitOnError) commands = append(commands, &command{ - flagSet: flagSet, + flagSet: flagSet, + description: "manages snapshots of Sourcegraph instance databases (EXPERIMENTAL)", handler: func(args []string) error { snapshotCommands.run(flagSet, "src snapshot", usage, args) return nil diff --git a/cmd/src/version.go b/cmd/src/version.go index 646ac6b6e1..fad3a42f78 100644 --- a/cmd/src/version.go +++ b/cmd/src/version.go @@ -29,6 +29,7 @@ $ src version var versionCommand = clicompat.Wrap(&cli.Command{ Name: "version", + Usage: "display and compare the src-cli version against the recommended version for your instance", UsageText: "src version [options]", OnUsageError: clicompat.OnUsageError, Description: versionExamples, From 99c43e80c92cc75653f99eabaa588fc7c001023d Mon Sep 17 00:00:00 2001 From: Andre Eleuterio <11207474+andreeleuterio@users.noreply.github.com> Date: Wed, 21 Oct 2026 12:12:09 -0300 Subject: [PATCH 630/647] security: patch CVE-2026-111943 (#1382) * security: patch CVE-2026-111943 (eMudhra CA compromise) Bump Go to 1.26.10 and upgrade Alpine ca-certificates-bundle to 20261020-r0. * security: patch volume-workspace image, lib go.mod, changelog for CVE-2026-111943 --- CHANGELOG.md | 1 + Dockerfile | 7 ++++--- Dockerfile.release | 5 +++-- dev/vendor-lib.sh | 2 +- docker/batch-change-volume-workspace/Dockerfile | 5 +++-- go.mod | 2 +- lib/go.mod | 2 +- mise.toml | 2 +- 8 files changed, 15 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7cd8ccb416..8b1d75c623 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ All notable changes to `src-cli` are documented in this file. ### Changed +- Updated Go to 1.26.10 and the Alpine `ca-certificates-bundle` in Docker images to 20261020-r0 to stop trusting the compromised eMudhra CAs ([CVE-2026-111943](https://emudhra.we-have-a-problem.com/)). - HTTP requests now fail instead of hanging forever if the server does not start responding within 1 minute. Set the `SRC_RESPONSE_HEADER_TIMEOUT` environment variable to change this timeout, or to `0` to disable it. Responses that stream data for a long time (for example, large search job results) are not affected. - `src search-jobs logs` and `src search-jobs results` now use the standard API client, gaining proxy support, `-insecure-skip-verify`, and cross-host redirect protection, and now report an error on non-200 responses instead of writing the error page into the output. - The command list in `src help` is now generated from the registered commands instead of being maintained by hand. `src debug`, `src snapshot`, and `src lsp` now appear in it; aliases are shown after each description. diff --git a/Dockerfile b/Dockerfile index 6a1d6bf01d..6a865963eb 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,17 +4,18 @@ # # Nothing fancy here: we copy in the source code and build on the Alpine Go # image. Refer to .dockerignore to get a sense of what we're not going to copy. -FROM golang:1.26.5-alpine3.23@sha256:622e56dbc11a8cfe87cafa2331e9a201877271cbff918af53d3be315f3da88cc AS builder +FROM golang:1.26.10-alpine3.23@sha256:a07f231c19b03e6106cf442f02a5bcf262147e744d15b7b5e4b6d81d420c70a0 AS builder COPY . /src WORKDIR /src RUN go build ./cmd/src # This stage should be kept in sync with Dockerfile.release. -FROM alpine:3.22@sha256:4b7ce07002c69e8f3d704a9c5d6fd3053be500b7f1c69fc0d80990c2ad8dd412 +FROM alpine:3.22@sha256:5291449c3df73caf6ed85e649dec1b9e818b39a5d8c871e97afc13e9cd5e8fa8 # needed for `src code-intel upload` and `src actions exec` -RUN apk add --no-cache git +# ca-certificates-bundle >= 20261020-r0 drops the eMudhra roots (CVE-2026-111943). +RUN apk add --no-cache git && apk upgrade --no-cache ca-certificates-bundle COPY --from=builder /src/src /usr/bin/ ENTRYPOINT ["/usr/bin/src"] diff --git a/Dockerfile.release b/Dockerfile.release index db46c56835..baccfc98f5 100644 --- a/Dockerfile.release +++ b/Dockerfile.release @@ -2,10 +2,11 @@ # suitable for testing, since it depends on a src binary being at the project # root _and_ that src binary being runnable on Alpine. To test this, refer to # the main Dockerfile, which should have an identical second stage. -FROM alpine:3.22@sha256:4bcff63911fcb4448bd4fdacec207030997caf25e9bea4045fa6c8c44de311d1 +FROM alpine:3.22@sha256:5291449c3df73caf6ed85e649dec1b9e818b39a5d8c871e97afc13e9cd5e8fa8 # needed for `src code-intel upload` and `src actions exec` -RUN apk add --no-cache git +# ca-certificates-bundle >= 20261020-r0 drops the eMudhra roots (CVE-2026-111943). +RUN apk add --no-cache git && apk upgrade --no-cache ca-certificates-bundle COPY src /usr/bin/ ENTRYPOINT ["/usr/bin/src"] diff --git a/dev/vendor-lib.sh b/dev/vendor-lib.sh index 06db251bd9..d007d89352 100755 --- a/dev/vendor-lib.sh +++ b/dev/vendor-lib.sh @@ -136,7 +136,7 @@ echo "Creating go.mod file..." cat > "$DEST_LIB/go.mod" <= 20261020-r0 drops the eMudhra roots (CVE-2026-111943). +RUN apk add --update git unzip && apk upgrade --no-cache ca-certificates-bundle diff --git a/go.mod b/go.mod index 3a97776d6e..7e006f9e7b 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/sourcegraph/src-cli -go 1.26.5 +go 1.26.10 require ( cloud.google.com/go/storage v1.50.0 diff --git a/lib/go.mod b/lib/go.mod index a55ba1bc9f..0ebb8b20bf 100644 --- a/lib/go.mod +++ b/lib/go.mod @@ -1,6 +1,6 @@ module github.com/sourcegraph/sourcegraph/lib -go 1.26.5 +go 1.26.10 require ( github.com/Masterminds/semver v1.5.0 diff --git a/mise.toml b/mise.toml index 240c82d6fc..e8cfe85732 100644 --- a/mise.toml +++ b/mise.toml @@ -1,4 +1,4 @@ [tools] -golang = "1.26.5" +golang = "1.26.10" shfmt = "3.8.0" shellcheck = "0.10.0" From 80e63e370afad6e79e940a5ef6302b02f13b035f Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Fri, 30 Oct 2026 08:07:49 +0200 Subject: [PATCH 631/647] chore/release: guard CLI release versions (#1358) Amp-Thread-ID: https://ampcode.com/threads/T-019fb87e-0d43-7624-b5c0-7d947ce1dc16 Co-authored-by: Amp Co-authored-by: Marc <7050295+marcleblanc2@users.noreply.github.com> --- .agents/skills/release/SKILL.md | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/.agents/skills/release/SKILL.md b/.agents/skills/release/SKILL.md index de27183f0d..b4a280b191 100644 --- a/.agents/skills/release/SKILL.md +++ b/.agents/skills/release/SKILL.md @@ -38,9 +38,11 @@ For version inference: ## Hard stops -Stop and ask before continuing if: +Stop before continuing if any condition below applies. Ask for approval or remediation only when that can resolve the condition; the Sourcegraph version guard cannot be overridden. - The working tree is dirty in a way not caused by this release work. +- The target of a major or minor release has a greater major/minor version than the latest stable Sourcegraph release. Warn that this is typically an error because only patch releases should advance independently, then refuse to create or push the release tag. Do not allow confirmation to override this guard. +- The latest stable Sourcegraph release cannot be fetched or its semantic version cannot be determined. Do not infer it from memory, local src-cli tags, or previously fetched output. - A release branch or tag would be pushed without explicit approval. - A force-push or tag replacement would be needed. - Trivy or required tests fail before tagging or pushing. @@ -55,7 +57,8 @@ Before starting the release work: 1. Make sure the working tree is clean with `git status`. 2. Fetch current refs and tags with `git fetch --all --tags --prune`. -3. Run Trivy before creating final release artifacts, and earlier when the release is vulnerability-driven. +3. Before creating a major or minor release tag, run `gh release list --repo sourcegraph/sourcegraph --exclude-drafts --exclude-pre-releases --limit 1 --json tagName` to fetch the latest stable release directly from `sourcegraph/sourcegraph`. Parse the returned tag as semantic versioning and compare the `.` components. The src-cli release line must be behind or equal to the Sourcegraph release line. Ignore patch components for this check, because src-cli patch releases may advance independently. Report the Sourcegraph version and its `https://github.com/sourcegraph/sourcegraph/releases/tag/` URL in the release plan. If the command, lookup, or parsing fails, stop. If the src-cli release line is ahead, report both versions, explain that this usually indicates an erroneous release plan, and stop without creating or pushing the tag. +4. Run Trivy before creating final release artifacts, and earlier when the release is vulnerability-driven. - For this repository, use `mise x trivy -- trivy fs --exit-code 1 --severity HIGH,CRITICAL`. - Use a different documented Trivy command only if the repository adds one. - If running from a temporary worktree, `mise` may require trusting that worktree's `mise.toml`. Run `mise trust -y /mise.toml` when needed, then remove or untrust temporary state during cleanup. @@ -75,9 +78,10 @@ Use the same workflow for patch, minor, and major releases. The release type mai 5. Apply the release-type commit selection rules; use `git cherry-pick -x ` for commits ported onto an existing release branch. 6. Resolve conflicts carefully and keep the release branch limited to selected commits and release-process changes. 7. Validate every release branch after porting changes. -8. Before tagging, show the release contents summary and ask `Proceed?`. -9. Tag locally on the release branch. -10. Push the release branch and tag only when requested or required by the release process and approved by the user. +8. For a major or minor release, repeat the live `sourcegraph/sourcegraph` release lookup and compatibility check immediately before presenting the pre-tag summary so a stale earlier result cannot permit an invalid tag. Refuse to tag if the lookup fails. +9. Before tagging, show the release contents summary and ask `Proceed?`. +10. Tag locally on the release branch only if the compatibility guard passes. +11. Push the release branch and tag only when requested or required by the release process and approved by the user. Use this pre-tag summary format: From d613971fc1a16d98f7e1a10d2274c45c5fc0827c Mon Sep 17 00:00:00 2001 From: Marc <7050295+marcleblanc2@users.noreply.github.com> Date: Tue, 3 Nov 2026 16:13:50 -0600 Subject: [PATCH 632/647] chore/deps: patch Trivy and Dependabot findings preparing for release (#1383) * chore/deps: patch all open Trivy and Dependabot findings Bump golang.org/x/{crypto,net,text,mod}, github.com/klauspost/compress, github.com/go-jose/go-jose/v4, google.golang.org/grpc, and go.opentelemetry.io/otel/sdk in go.mod and lib/go.mod so that `trivy fs --severity HIGH,CRITICAL` is clean and Dependabot alerts #91-#96 close. No code changes. * chore/renovate: fix invalid JSON in renovate.json A doubled comma after the "$schema" key made renovate.json unparseable, so Renovate stopped opening PRs for this repository. Fixes #1345 * snapshot upload: use option.WithAuthCredentialsFile google.golang.org/api v0.264.0 deprecates option.WithCredentialsFile (staticcheck SA1019), which failed the go-lint job. The credentials file is a service account key, so load it as that type explicitly. Amp-Thread-ID: https://ampcode.com/threads/T-01a18b16-df86-7399-a300-979289761a30 Co-authored-by: Amp --------- Co-authored-by: Amp --- CHANGELOG.md | 1 + cmd/src/snapshot_upload.go | 5 +- go.mod | 68 ++++++++-------- go.sum | 158 +++++++++++++++++++------------------ lib/go.mod | 10 +-- lib/go.sum | 32 ++++---- renovate.json | 2 +- 7 files changed, 141 insertions(+), 135 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8b1d75c623..0835d977b8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,7 @@ All notable changes to `src-cli` are documented in this file. ### Changed - Updated Go to 1.26.10 and the Alpine `ca-certificates-bundle` in Docker images to 20261020-r0 to stop trusting the compromised eMudhra CAs ([CVE-2026-111943](https://emudhra.we-have-a-problem.com/)). +- Updated Go dependencies to patch all open Trivy and Dependabot findings: `golang.org/x/crypto`, `golang.org/x/net`, `golang.org/x/text`, `golang.org/x/mod`, `github.com/klauspost/compress`, `github.com/go-jose/go-jose/v4`, `google.golang.org/grpc`, and `go.opentelemetry.io/otel/sdk`. - HTTP requests now fail instead of hanging forever if the server does not start responding within 1 minute. Set the `SRC_RESPONSE_HEADER_TIMEOUT` environment variable to change this timeout, or to `0` to disable it. Responses that stream data for a long time (for example, large search job results) are not affected. - `src search-jobs logs` and `src search-jobs results` now use the standard API client, gaining proxy support, `-insecure-skip-verify`, and cross-host redirect protection, and now report an error on non-200 responses instead of writing the error page into the output. - The command list in `src help` is now generated from the registered commands instead of being maintained by hand. `src debug`, `src snapshot`, and `src lsp` now appear in it; aliases are shown after each description. diff --git a/cmd/src/snapshot_upload.go b/cmd/src/snapshot_upload.go index a019858ecb..3a7a88176e 100644 --- a/cmd/src/snapshot_upload.go +++ b/cmd/src/snapshot_upload.go @@ -205,7 +205,10 @@ func createGcsClient(flagSet *flag.FlagSet, credentialsPath string) (*gcsClient, out := output.NewOutput(flagSet.Output(), output.OutputOpts{Verbose: *verbose}) // https://pkg.go.dev/cloud.google.com/go/storage#section-readme - client, err := storage.NewClient(ctx, option.WithCredentialsFile(credentialsPath)) + // The credentials file Sourcegraph provides is a service account key, so + // only accept that type; option.WithCredentialsFile is deprecated because + // it loads any credential type without validation. + client, err := storage.NewClient(ctx, option.WithAuthCredentialsFile(option.ServiceAccount, credentialsPath)) if err != nil { return nil, errors.Wrap(err, "create Google Cloud Storage client") diff --git a/go.mod b/go.mod index 7e006f9e7b..87509a024d 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module github.com/sourcegraph/src-cli go 1.26.10 require ( - cloud.google.com/go/storage v1.50.0 + cloud.google.com/go/storage v1.56.0 github.com/aws/aws-sdk-go-v2/config v1.18.13 github.com/aws/aws-sdk-go-v2/service/ec2 v1.86.0 github.com/aws/aws-sdk-go-v2/service/eks v1.27.3 @@ -32,8 +32,8 @@ require ( github.com/tliron/glsp v0.2.2 github.com/urfave/cli/v3 v3.8.0 github.com/zalando/go-keyring v0.2.6 - golang.org/x/sync v0.22.0 - google.golang.org/api v0.256.0 + golang.org/x/sync v0.23.0 + google.golang.org/api v0.264.0 google.golang.org/protobuf v1.36.11 gopkg.in/yaml.v3 v3.0.1 jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7 @@ -44,13 +44,13 @@ require ( require ( al.essio.dev/pkg/shellescape v1.5.1 // indirect - cel.dev/expr v0.25.1 // indirect - cloud.google.com/go/auth v0.17.0 // indirect + cel.dev/expr v0.25.2 // indirect + cloud.google.com/go/auth v0.18.2 // indirect cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect - cloud.google.com/go/monitoring v1.24.2 // indirect - github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.32.0 // indirect - github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.50.0 // indirect - github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.50.0 // indirect + cloud.google.com/go/monitoring v1.24.3 // indirect + github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.33.0 // indirect + github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.53.0 // indirect + github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.53.0 // indirect github.com/alecthomas/chroma/v2 v2.14.0 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect @@ -65,7 +65,7 @@ require ( github.com/envoyproxy/go-control-plane/envoy v1.37.0 // indirect github.com/felixge/httpsnoop v1.0.4 // indirect github.com/fxamacker/cbor/v2 v2.7.0 // indirect - github.com/go-jose/go-jose/v4 v4.1.4 // indirect + github.com/go-jose/go-jose/v4 v4.1.6 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/godbus/dbus/v5 v5.1.0 // indirect github.com/google/gnostic-models v0.6.9 // indirect @@ -81,32 +81,32 @@ require ( github.com/segmentio/ksuid v1.0.4 // indirect github.com/sourcegraph/beaut v0.0.0-20240611013027-627e4c25335a // indirect github.com/sourcegraph/jsonrpc2 v0.2.0 // indirect - github.com/spiffe/go-spiffe/v2 v2.6.0 // indirect + github.com/spiffe/go-spiffe/v2 v2.7.0 // indirect github.com/tliron/commonlog v0.2.19 // indirect github.com/tliron/kutil v0.3.27 // indirect github.com/x448/float16 v0.8.4 // indirect github.com/xlab/treeprint v1.2.0 // indirect github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect - go.opentelemetry.io/contrib/detectors/gcp v1.43.0 // indirect + go.opentelemetry.io/contrib/detectors/gcp v1.44.0 // indirect go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0 // indirect go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0 // indirect - go.opentelemetry.io/otel v1.43.0 // indirect - go.opentelemetry.io/otel/metric v1.43.0 // indirect - go.opentelemetry.io/otel/sdk v1.43.0 // indirect - go.opentelemetry.io/otel/sdk/metric v1.43.0 // indirect - go.opentelemetry.io/otel/trace v1.43.0 // indirect - golang.org/x/net v0.57.0 // indirect - google.golang.org/genproto/googleapis/api v0.0.0-20260414002931-afd174a4e478 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20260414002931-afd174a4e478 // indirect + go.opentelemetry.io/otel v1.45.0 // indirect + go.opentelemetry.io/otel/metric v1.45.0 // indirect + go.opentelemetry.io/otel/sdk v1.45.0 // indirect + go.opentelemetry.io/otel/sdk/metric v1.45.0 // indirect + go.opentelemetry.io/otel/trace v1.45.0 // indirect + golang.org/x/net v0.60.0 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa // indirect gopkg.in/evanphx/json-patch.v4 v4.12.0 // indirect sigs.k8s.io/randfill v1.0.0 // indirect ) require ( - cloud.google.com/go v0.120.0 // indirect + cloud.google.com/go v0.121.6 // indirect cloud.google.com/go/compute/metadata v0.9.0 // indirect - cloud.google.com/go/iam v1.5.2 // indirect + cloud.google.com/go/iam v1.5.3 // indirect github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c // indirect github.com/Masterminds/semver v1.5.0 // indirect github.com/aws/aws-sdk-go-v2 v1.17.5 // indirect @@ -133,20 +133,20 @@ require ( github.com/fatih/color v1.18.0 // indirect github.com/getsentry/sentry-go v0.27.0 // indirect github.com/ghodss/yaml v1.0.0 // indirect - github.com/go-logr/logr v1.4.3 // indirect + github.com/go-logr/logr v1.4.4 // indirect github.com/go-openapi/jsonpointer v0.21.0 // indirect github.com/go-openapi/jsonreference v0.20.2 // indirect github.com/go-openapi/swag v0.23.0 // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/google/uuid v1.6.0 // indirect - github.com/googleapis/enterprise-certificate-proxy v0.3.7 // indirect - github.com/googleapis/gax-go/v2 v2.15.0 // indirect + github.com/googleapis/enterprise-certificate-proxy v0.3.11 // indirect + github.com/googleapis/gax-go/v2 v2.17.0 // indirect github.com/gorilla/css v1.0.1 // indirect github.com/hexops/gotextdiff v1.0.3 // indirect github.com/hexops/valast v1.4.4 // indirect github.com/jmespath/go-jmespath v0.4.0 // indirect github.com/josharian/intern v1.0.0 // indirect - github.com/klauspost/compress v1.18.0 // indirect + github.com/klauspost/compress v1.18.7 // indirect github.com/klauspost/pgzip v1.2.6 // indirect github.com/kr/pretty v0.3.1 // indirect github.com/kr/text v0.2.0 // indirect @@ -179,16 +179,16 @@ require ( go.uber.org/atomic v1.11.0 // indirect go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.24.0 // indirect - golang.org/x/crypto v0.54.0 // indirect - golang.org/x/mod v0.37.0 // indirect + golang.org/x/crypto v0.57.0 // indirect + golang.org/x/mod v0.41.0 // indirect golang.org/x/oauth2 v0.36.0 // indirect - golang.org/x/sys v0.47.0 // indirect - golang.org/x/term v0.45.0 // indirect - golang.org/x/text v0.40.0 // indirect + golang.org/x/sys v0.48.0 // indirect + golang.org/x/term v0.46.0 // indirect + golang.org/x/text v0.42.0 // indirect golang.org/x/time v0.14.0 // indirect - golang.org/x/tools v0.47.0 // indirect - google.golang.org/genproto v0.0.0-20250603155806-513f23925822 // indirect - google.golang.org/grpc v1.82.1 // indirect + golang.org/x/tools v0.49.0 // indirect + google.golang.org/genproto v0.0.0-20260128011058-8636f8732409 // indirect + google.golang.org/grpc v1.83.2 // indirect gopkg.in/inf.v0 v0.9.1 // indirect; direct gopkg.in/yaml.v2 v2.4.0 // indirect k8s.io/klog/v2 v2.130.1 // indirect diff --git a/go.sum b/go.sum index a3ab138c99..b104115891 100644 --- a/go.sum +++ b/go.sum @@ -1,37 +1,37 @@ al.essio.dev/pkg/shellescape v1.5.1 h1:86HrALUujYS/h+GtqoB26SBEdkWfmMI6FubjXlsXyho= al.essio.dev/pkg/shellescape v1.5.1/go.mod h1:6sIqp7X2P6mThCQ7twERpZTuigpr6KbZWtls1U8I890= -cel.dev/expr v0.25.1 h1:1KrZg61W6TWSxuNZ37Xy49ps13NUovb66QLprthtwi4= -cel.dev/expr v0.25.1/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4= -cloud.google.com/go v0.120.0 h1:wc6bgG9DHyKqF5/vQvX1CiZrtHnxJjBlKUyF9nP6meA= -cloud.google.com/go v0.120.0/go.mod h1:/beW32s8/pGRuj4IILWQNd4uuebeT4dkOhKmkfit64Q= -cloud.google.com/go/auth v0.17.0 h1:74yCm7hCj2rUyyAocqnFzsAYXgJhrG26XCFimrc/Kz4= -cloud.google.com/go/auth v0.17.0/go.mod h1:6wv/t5/6rOPAX4fJiRjKkJCvswLwdet7G8+UGXt7nCQ= +cel.dev/expr v0.25.2 h1:K6j46C81hXtZQfuX60cVWQFBJahKSE2gfRbNuvr5bFs= +cel.dev/expr v0.25.2/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4= +cloud.google.com/go v0.121.6 h1:waZiuajrI28iAf40cWgycWNgaXPO06dupuS+sgibK6c= +cloud.google.com/go v0.121.6/go.mod h1:coChdst4Ea5vUpiALcYKXEpR1S9ZgXbhEzzMcMR66vI= +cloud.google.com/go/auth v0.18.2 h1:+Nbt5Ev0xEqxlNjd6c+yYUeosQ5TtEUaNcN/3FozlaM= +cloud.google.com/go/auth v0.18.2/go.mod h1:xD+oY7gcahcu7G2SG2DsBerfFxgPAJz17zz2joOFF3M= cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIiLpZnkHRbnc= cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c= cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdBtwLoEkH9Zs= cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10= -cloud.google.com/go/iam v1.5.2 h1:qgFRAGEmd8z6dJ/qyEchAuL9jpswyODjA2lS+w234g8= -cloud.google.com/go/iam v1.5.2/go.mod h1:SE1vg0N81zQqLzQEwxL2WI6yhetBdbNQuTvIKCSkUHE= -cloud.google.com/go/logging v1.13.0 h1:7j0HgAp0B94o1YRDqiqm26w4q1rDMH7XNRU34lJXHYc= -cloud.google.com/go/logging v1.13.0/go.mod h1:36CoKh6KA/M0PbhPKMq6/qety2DCAErbhXT62TuXALA= -cloud.google.com/go/longrunning v0.6.7 h1:IGtfDWHhQCgCjwQjV9iiLnUta9LBCo8R9QmAFsS/PrE= -cloud.google.com/go/longrunning v0.6.7/go.mod h1:EAFV3IZAKmM56TyiE6VAP3VoTzhZzySwI/YI1s/nRsY= -cloud.google.com/go/monitoring v1.24.2 h1:5OTsoJ1dXYIiMiuL+sYscLc9BumrL3CarVLL7dd7lHM= -cloud.google.com/go/monitoring v1.24.2/go.mod h1:x7yzPWcgDRnPEv3sI+jJGBkwl5qINf+6qY4eq0I9B4U= -cloud.google.com/go/storage v1.50.0 h1:3TbVkzTooBvnZsk7WaAQfOsNrdoM8QHusXA1cpk6QJs= -cloud.google.com/go/storage v1.50.0/go.mod h1:l7XeiD//vx5lfqE3RavfmU9yvk5Pp0Zhcv482poyafY= -cloud.google.com/go/trace v1.11.6 h1:2O2zjPzqPYAHrn3OKl029qlqG6W8ZdYaOWRyr8NgMT4= -cloud.google.com/go/trace v1.11.6/go.mod h1:GA855OeDEBiBMzcckLPE2kDunIpC72N+Pq8WFieFjnI= +cloud.google.com/go/iam v1.5.3 h1:+vMINPiDF2ognBJ97ABAYYwRgsaqxPbQDlMnbHMjolc= +cloud.google.com/go/iam v1.5.3/go.mod h1:MR3v9oLkZCTlaqljW6Eb2d3HGDGK5/bDv93jhfISFvU= +cloud.google.com/go/logging v1.13.1 h1:O7LvmO0kGLaHY/gq8cV7T0dyp6zJhYAOtZPX4TF3QtY= +cloud.google.com/go/logging v1.13.1/go.mod h1:XAQkfkMBxQRjQek96WLPNze7vsOmay9H5PqfsNYDqvw= +cloud.google.com/go/longrunning v0.8.0 h1:LiKK77J3bx5gDLi4SMViHixjD2ohlkwBi+mKA7EhfW8= +cloud.google.com/go/longrunning v0.8.0/go.mod h1:UmErU2Onzi+fKDg2gR7dusz11Pe26aknR4kHmJJqIfk= +cloud.google.com/go/monitoring v1.24.3 h1:dde+gMNc0UhPZD1Azu6at2e79bfdztVDS5lvhOdsgaE= +cloud.google.com/go/monitoring v1.24.3/go.mod h1:nYP6W0tm3N9H/bOw8am7t62YTzZY+zUeQ+Bi6+2eonI= +cloud.google.com/go/storage v1.56.0 h1:iixmq2Fse2tqxMbWhLWC9HfBj1qdxqAmiK8/eqtsLxI= +cloud.google.com/go/storage v1.56.0/go.mod h1:Tpuj6t4NweCLzlNbw9Z9iwxEkrSem20AetIeH/shgVU= +cloud.google.com/go/trace v1.11.7 h1:kDNDX8JkaAG3R2nq1lIdkb7FCSi1rCmsEtKVsty7p+U= +cloud.google.com/go/trace v1.11.7/go.mod h1:TNn9d5V3fQVf6s4SCveVMIBS2LJUqo73GACmq/Tky0s= github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg= github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.32.0 h1:rIkQfkCOVKc1OiRCNcSDD8ml5RJlZbH/Xsq7lbpynwc= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.32.0/go.mod h1:RD2SsorTmYhF6HkTmDw7KmPYQk8OBYwTkuasChwv7R4= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.50.0 h1:5IT7xOdq17MtcdtL/vtl6mGfzhaq4m4vpollPRmlsBQ= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.50.0/go.mod h1:ZV4VOm0/eHR06JLrXWe09068dHpr3TRpY9Uo7T+anuA= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0.50.0 h1:nNMpRpnkWDAaqcpxMJvxa/Ud98gjbYwayJY4/9bdjiU= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0.50.0/go.mod h1:SZiPHWGOOk3bl8tkevxkoiwPgsIl6CwrWcbwjfHZpdM= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.50.0 h1:ig/FpDD2JofP/NExKQUbn7uOSZzJAQqogfqluZK4ed4= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.50.0/go.mod h1:otE2jQekW/PqXk1Awf5lmfokJx4uwuqcj1ab5SpGeW0= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.33.0 h1:l7+6kwRMJNwdCvYdDl7Eax+wzEYHSnNY7zrrfbhDdTA= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.33.0/go.mod h1:pJTkW8hEUIIi3Pf65lPZOnn4Y81yCllX6IWk2jNXdkM= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.53.0 h1:owcC2UnmsZycprQ5RfRgjydWhuoxg71LUfyiQdijZuM= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.53.0/go.mod h1:ZPpqegjbE99EPKsu3iUWV22A04wzGPcAY/ziSIQEEgs= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0.53.0 h1:4LP6hvB4I5ouTbGgWtixJhgED6xdf67twf9PoY96Tbg= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0.53.0/go.mod h1:jUZ5LYlw40WMd07qxcQJD5M40aUxrfwqQX1g7zxYnrQ= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.53.0 h1:Ron4zCA/yk6U7WOBXhTJcDpsUBG9npumK6xw2auFltQ= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.53.0/go.mod h1:cSgYe11MCNYunTnRXrKiR/tHc0eoKjICUuWpNZoVCOo= github.com/Masterminds/semver v1.5.0 h1:H65muMkzWKEuNDnfl9d70GUjFniHKHRbFPGBuZ3QEww= github.com/Masterminds/semver v1.5.0/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y= github.com/alecthomas/assert/v2 v2.7.0 h1:QtqSACNS3tF7oasA8CU6A6sXZSBDqnm7RfpLl9bZqbE= @@ -152,11 +152,11 @@ github.com/getsentry/sentry-go v0.27.0 h1:Pv98CIbtB3LkMWmXi4Joa5OOcwbmnX88sF5qbK github.com/getsentry/sentry-go v0.27.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA= github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og= -github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA= -github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= +github.com/go-jose/go-jose/v4 v4.1.6 h1:sNRkftxFJxwsILiQukqp5z83QBSmntVwmgRY7AqBDO4= +github.com/go-jose/go-jose/v4 v4.1.6/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= -github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8= +github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/go-openapi/jsonpointer v0.19.6/go.mod h1:osyAmYz/mB/C3I+WsTTSgw1ONzaLJoLCyoi6/zppojs= @@ -199,10 +199,10 @@ github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaU github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/googleapis/enterprise-certificate-proxy v0.3.7 h1:zrn2Ee/nWmHulBx5sAVrGgAa0f2/R35S4DJwfFaUPFQ= -github.com/googleapis/enterprise-certificate-proxy v0.3.7/go.mod h1:MkHOF77EYAE7qfSuSS9PU6g4Nt4e11cnsDUowfwewLA= -github.com/googleapis/gax-go/v2 v2.15.0 h1:SyjDc1mGgZU5LncH8gimWo9lW1DtIfPibOG81vgd/bo= -github.com/googleapis/gax-go/v2 v2.15.0/go.mod h1:zVVkkxAQHa1RQpg9z2AUCMnKhi0Qld9rcmyfL1OZhoc= +github.com/googleapis/enterprise-certificate-proxy v0.3.11 h1:vAe81Msw+8tKUxi2Dqh/NZMz7475yUvmRIkXr4oN2ao= +github.com/googleapis/enterprise-certificate-proxy v0.3.11/go.mod h1:RFV7MUdlb7AgEq2v7FmMCfeSMCllAzWxFgRdusoGks8= +github.com/googleapis/gax-go/v2 v2.17.0 h1:RksgfBpxqff0EZkDWYuz9q/uWsTVz+kf43LsZ1J6SMc= +github.com/googleapis/gax-go/v2 v2.17.0/go.mod h1:mzaqghpQp4JDh3HvADwrat+6M3MOIDp5YKHhb9PAgDY= github.com/gorilla/css v1.0.1 h1:ntNaBIghp6JmvWnxbZKANoLyuXTPZ4cAMlo6RyhlbO8= github.com/gorilla/css v1.0.1/go.mod h1:BvnYkspnSzMmwRK+b8/xgNPLiIuNZr6vbZBTPQ2A3b0= github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= @@ -246,8 +246,8 @@ github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 h1:Z9n2FFNU github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51/go.mod h1:CzGEWj7cYgsdH8dAjBGEr58BoE7ScuLd+fwFZ44+/x8= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= -github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= -github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= +github.com/klauspost/compress v1.18.7 h1:aUyZsS4kH3QTKurYhAOwAHxllVPnOthb3vPfnF1Ehjw= +github.com/klauspost/compress v1.18.7/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= github.com/klauspost/pgzip v1.2.6 h1:8RXeL5crjEUFnR2/Sn6GJNWtSQ3Dk8pq4CL3jvdDyjU= github.com/klauspost/pgzip v1.2.6/go.mod h1:Ch1tH69qFZu15pkjo5kYi6mth2Zzwzt50oCQKQE9RUs= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= @@ -347,8 +347,8 @@ github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6 github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o= github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= -github.com/spiffe/go-spiffe/v2 v2.6.0 h1:l+DolpxNWYgruGQVV0xsfeya3CsC7m8iBzDnMpsbLuo= -github.com/spiffe/go-spiffe/v2 v2.6.0/go.mod h1:gm2SeUoMZEtpnzPNs2Csc0D/gX33k1xIx7lEzqblHEs= +github.com/spiffe/go-spiffe/v2 v2.7.0 h1:uXe1MflJoHw58wAUvxVlcM7WpKtijWG7I1UidcGh6g4= +github.com/spiffe/go-spiffe/v2 v2.7.0/go.mod h1:47Q0Q9/AqGha8QLHp+kxpH4Wca7X7EnOtlIJy3mxZ3U= github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf h1:pvbZ0lM0XWPBqUKqFU8cmavspvIl9nulOYwdy6IFRRo= github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf/go.mod h1:RJID2RhlZKId02nZ62WenDCkgHFerpIOmW0iT7GKmXM= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= @@ -397,24 +397,26 @@ github.com/zalando/go-keyring v0.2.6 h1:r7Yc3+H+Ux0+M72zacZoItR3UDxeWfKTcabvkI8u github.com/zalando/go-keyring v0.2.6/go.mod h1:2TCrxYrbUNYfNS/Kgy/LSrkSQzZ5UPVH85RwfczwvcI= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= -go.opentelemetry.io/contrib/detectors/gcp v1.43.0 h1:62yY3dT7/ShwOxzA0RsKRgshBmfElKI4d/Myu2OxDFU= -go.opentelemetry.io/contrib/detectors/gcp v1.43.0/go.mod h1:RyaZMFY7yi1kAs45S6mbFGz8O8rqB0dTY14uzvG4LCs= +go.opentelemetry.io/contrib/detectors/gcp v1.44.0 h1:NmLfL734pJhM0JKaYd2Y28+nY9dPRWYAAbxhRCrKXPw= +go.opentelemetry.io/contrib/detectors/gcp v1.44.0/go.mod h1:tNAsgd8avTGke1+MndXlU5Cru4PQ9Ai/cCNWQv/ZJ/s= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0 h1:q4XOmH/0opmeuJtPsbFNivyl7bCt7yRBbeEm2sC/XtQ= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0/go.mod h1:snMWehoOh2wsEwnvvwtDyFCxVeDAODenXHtn5vzrKjo= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0 h1:RbKq8BG0FI8OiXhBfcRtqqHcZcka+gU3cskNuf05R18= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0/go.mod h1:h06DGIukJOevXaj/xrNjhi/2098RZzcLTbc0jDAUbsg= -go.opentelemetry.io/otel v1.43.0 h1:mYIM03dnh5zfN7HautFE4ieIig9amkNANT+xcVxAj9I= -go.opentelemetry.io/otel v1.43.0/go.mod h1:JuG+u74mvjvcm8vj8pI5XiHy1zDeoCS2LB1spIq7Ay0= -go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.29.0 h1:WDdP9acbMYjbKIyJUhTvtzj601sVJOqgWdUxSdR/Ysc= -go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.29.0/go.mod h1:BLbf7zbNIONBLPwvFnwNHGj4zge8uTCM/UPIVW1Mq2I= -go.opentelemetry.io/otel/metric v1.43.0 h1:d7638QeInOnuwOONPp4JAOGfbCEpYb+K6DVWvdxGzgM= -go.opentelemetry.io/otel/metric v1.43.0/go.mod h1:RDnPtIxvqlgO8GRW18W6Z/4P462ldprJtfxHxyKd2PY= -go.opentelemetry.io/otel/sdk v1.43.0 h1:pi5mE86i5rTeLXqoF/hhiBtUNcrAGHLKQdhg4h4V9Dg= -go.opentelemetry.io/otel/sdk v1.43.0/go.mod h1:P+IkVU3iWukmiit/Yf9AWvpyRDlUeBaRg6Y+C58QHzg= -go.opentelemetry.io/otel/sdk/metric v1.43.0 h1:S88dyqXjJkuBNLeMcVPRFXpRw2fuwdvfCGLEo89fDkw= -go.opentelemetry.io/otel/sdk/metric v1.43.0/go.mod h1:C/RJtwSEJ5hzTiUz5pXF1kILHStzb9zFlIEe85bhj6A= -go.opentelemetry.io/otel/trace v1.43.0 h1:BkNrHpup+4k4w+ZZ86CZoHHEkohws8AY+WTX09nk+3A= -go.opentelemetry.io/otel/trace v1.43.0/go.mod h1:/QJhyVBUUswCphDVxq+8mld+AvhXZLhe+8WVFxiFff0= +go.opentelemetry.io/otel v1.45.0 h1:pdrWmLHofpubmArBv1LgFSv1Z0Ie/ppdZzu+kUN5EeU= +go.opentelemetry.io/otel v1.45.0/go.mod h1:XZxIqPapzEYnhNSScF5DIqXhm/rYi0FzCe2XddAwZfQ= +go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.36.0 h1:rixTyDGXFxRy1xzhKrotaHy3/KXdPhlWARrCgK+eqUY= +go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.36.0/go.mod h1:dowW6UsM9MKbJq5JTz2AMVp3/5iW5I/TStsk8S+CfHw= +go.opentelemetry.io/otel/metric v1.45.0 h1:7Eg1uH7CJ5cXv9is6tnBe1FI6rj1nwUdbFypRm3br/M= +go.opentelemetry.io/otel/metric v1.45.0/go.mod h1:HAPbm1nd3p1PmFH7v2dR+6BjXxw+Lq4a2+pndMAm08s= +go.opentelemetry.io/otel/metric/x v0.67.0 h1:PcicCNZFkZ4bXfSooXdo3WN7RBOVOtjVdo1wD358Uns= +go.opentelemetry.io/otel/metric/x v0.67.0/go.mod h1:FBjCWZe6wgcqxcMtjdGiClDKXb2YxxXii0CXftE4QtI= +go.opentelemetry.io/otel/sdk v1.45.0 h1:4VVSMgQ83dUgW2aoX5f6JgLvHwIvzcuLnF9lUdCSpCw= +go.opentelemetry.io/otel/sdk v1.45.0/go.mod h1:Sr40LgXV7DsKMMJMKOhUWOgMWTfAaqvm2kF0g7ilwuA= +go.opentelemetry.io/otel/sdk/metric v1.45.0 h1:oVFszMfyj1Am6s24Vtc7wBb8BKLcwepJjNEYILuiE3o= +go.opentelemetry.io/otel/sdk/metric v1.45.0/go.mod h1:vUWUxDZvu1WVRj8JA8S0AdhsPrZoDpA2DdZauIh4mDA= +go.opentelemetry.io/otel/trace v1.45.0 h1:l/mP6Uv7oNO7/TblbhpbgMidxhq1uO/rPsikOyVhxag= +go.opentelemetry.io/otel/trace v1.45.0/go.mod h1:qoJJA2xNMnxRrdISU/kLtfUH2wNeQbiv+jhs/CxI8bc= go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= @@ -427,16 +429,16 @@ golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACk golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw= -golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk= +golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M= +golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA= golang.org/x/exp v0.0.0-20230713183714-613f0c0eb8a1 h1:MGwJjxBy0HJshjDNfLsYO8xppfqWlA5ZT9OhtUUhTNw= golang.org/x/exp v0.0.0-20230713183714-613f0c0eb8a1/go.mod h1:FXUEEKJgO7OQYeo8N01OfiKP8RXMtf6e8aTskBGqWdc= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.7.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ= -golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0= +golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c= +golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= @@ -444,8 +446,8 @@ golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwY golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.3.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE= -golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE= -golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU= +golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU= +golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs= golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -454,8 +456,8 @@ golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220819030929-7fc1605a5dde/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= -golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk= +golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -472,19 +474,19 @@ golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220829200755-d48e67d00261/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= -golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= +golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.3.0/go.mod h1:q750SLmJuPmVoN1blW3UFBPREJfb1KmY3vwxfr+nFDA= -golang.org/x/term v0.45.0 h1:NwWyBmoJCbfTHpxrWoZ9C6/VxOf7ic219I8xZZFdrf0= -golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w= +golang.org/x/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE= +golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs= -golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY= +golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= +golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E= golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI= golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -494,24 +496,24 @@ golang.org/x/tools v0.0.0-20200624163319-25775e59acb7/go.mod h1:EkVYQZoAsY45+roY golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.4.0/go.mod h1:UE5sM2OK9E/d67R0ANs2xJizIymRP5gJU295PvKXxjQ= -golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q= -golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA= +golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI= +golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= -google.golang.org/api v0.256.0 h1:u6Khm8+F9sxbCTYNoBHg6/Hwv0N/i+V94MvkOSor6oI= -google.golang.org/api v0.256.0/go.mod h1:KIgPhksXADEKJlnEoRa9qAII4rXcy40vfI8HRqcU964= -google.golang.org/genproto v0.0.0-20250603155806-513f23925822 h1:rHWScKit0gvAPuOnu87KpaYtjK5zBMLcULh7gxkCXu4= -google.golang.org/genproto v0.0.0-20250603155806-513f23925822/go.mod h1:HubltRL7rMh0LfnQPkMH4NPDFEWp0jw3vixw7jEM53s= -google.golang.org/genproto/googleapis/api v0.0.0-20260414002931-afd174a4e478 h1:yQugLulqltosq0B/f8l4w9VryjV+N/5gcW0jQ3N8Qec= -google.golang.org/genproto/googleapis/api v0.0.0-20260414002931-afd174a4e478/go.mod h1:C6ADNqOxbgdUUeRTU+LCHDPB9ttAMCTff6auwCVa4uc= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260414002931-afd174a4e478 h1:RmoJA1ujG+/lRGNfUnOMfhCy5EipVMyvUE+KNbPbTlw= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260414002931-afd174a4e478/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= -google.golang.org/grpc v1.82.1 h1:NnAxzGRA0677vCa4BUkOAnO5+FfQqVl9iUXeD0IqcGE= -google.golang.org/grpc v1.82.1/go.mod h1:yzTZ1TB1Z3SG+LIYaI+WiE8D5+PZ3ArnrSp8zF3+/ZA= +google.golang.org/api v0.264.0 h1:+Fo3DQXBK8gLdf8rFZ3uLu39JpOnhvzJrLMQSoSYZJM= +google.golang.org/api v0.264.0/go.mod h1:fAU1xtNNisHgOF5JooAs8rRaTkl2rT3uaoNGo9NS3R8= +google.golang.org/genproto v0.0.0-20260128011058-8636f8732409 h1:VQZ/yAbAtjkHgH80teYd2em3xtIkkHd7ZhqfH2N9CsM= +google.golang.org/genproto v0.0.0-20260128011058-8636f8732409/go.mod h1:rxKD3IEILWEu3P44seeNOAwZN4SaoKaQ/2eTg4mM6EM= +google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa h1:Kjn0N0tCrDgiAFW+lGO4JZ3ck44CehvJQMAwj9QF0G8= +google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:q4lMZS6kskjT5HvCPrnnypcDPVJqT/f4nfxmkE7gryY= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa h1:mZHHdPZl0dbGHCflZgAq/Q468DWVFcU2whhB2KAo8fk= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= +google.golang.org/grpc v1.83.2 h1:EManeRomTObA0BU7I8vXgg/78uE5MJ9M8B39EX2WscU= +google.golang.org/grpc v1.83.2/go.mod h1:YPI1hK3kDked6iHvgX3tR0y+nX/qpMFKhPgFsokw1S8= google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/lib/go.mod b/lib/go.mod index 0ebb8b20bf..e2c926ec8d 100644 --- a/lib/go.mod +++ b/lib/go.mod @@ -27,8 +27,8 @@ require ( github.com/xeipuuv/gojsonschema v1.2.0 github.com/xlab/treeprint v1.2.0 go.opentelemetry.io/otel v1.43.0 - golang.org/x/sys v0.47.0 - golang.org/x/term v0.45.0 + golang.org/x/sys v0.48.0 + golang.org/x/term v0.46.0 google.golang.org/protobuf v1.36.10 gopkg.in/yaml.v3 v3.0.1 ) @@ -56,7 +56,7 @@ require ( github.com/gorilla/css v1.0.1 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect - github.com/klauspost/compress v1.18.0 // indirect + github.com/klauspost/compress v1.18.7 // indirect github.com/kr/pretty v0.3.1 // indirect github.com/kr/text v0.2.0 // indirect github.com/lucasb-eyer/go-colorful v1.2.0 // indirect @@ -78,8 +78,8 @@ require ( go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.24.0 // indirect golang.org/x/exp v0.0.0-20230713183714-613f0c0eb8a1 // indirect - golang.org/x/net v0.57.0 // indirect - golang.org/x/text v0.40.0 // indirect + golang.org/x/net v0.60.0 // indirect + golang.org/x/text v0.42.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect ) diff --git a/lib/go.sum b/lib/go.sum index 39d3e6cd12..07558ed82c 100644 --- a/lib/go.sum +++ b/lib/go.sum @@ -88,8 +88,8 @@ github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= -github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= -github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= +github.com/klauspost/compress v1.18.7 h1:aUyZsS4kH3QTKurYhAOwAHxllVPnOthb3vPfnF1Ehjw= +github.com/klauspost/compress v1.18.7/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= github.com/klauspost/pgzip v1.2.6 h1:8RXeL5crjEUFnR2/Sn6GJNWtSQ3Dk8pq4CL3jvdDyjU= github.com/klauspost/pgzip v1.2.6/go.mod h1:Ch1tH69qFZu15pkjo5kYi6mth2Zzwzt50oCQKQE9RUs= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= @@ -184,38 +184,38 @@ golang.org/x/exp v0.0.0-20230713183714-613f0c0eb8a1 h1:MGwJjxBy0HJshjDNfLsYO8xpp golang.org/x/exp v0.0.0-20230713183714-613f0c0eb8a1/go.mod h1:FXUEEKJgO7OQYeo8N01OfiKP8RXMtf6e8aTskBGqWdc= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ= -golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0= +golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c= +golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE= -golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU= +golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU= +golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= -golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk= +golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= -golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= -golang.org/x/term v0.45.0 h1:NwWyBmoJCbfTHpxrWoZ9C6/VxOf7ic219I8xZZFdrf0= -golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w= +golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= +golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE= +golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs= -golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY= +golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= +golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q= -golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA= +golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI= +golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/renovate.json b/renovate.json index dd226f0096..dee4083d81 100644 --- a/renovate.json +++ b/renovate.json @@ -1,5 +1,5 @@ { - "$schema": "http://json.schemastore.org/renovate",, + "$schema": "http://json.schemastore.org/renovate", "automerge": true, "automergeType": "pr", "extends": [ From 95580696f2246c7af44b780403c88f6f71834ee0 Mon Sep 17 00:00:00 2001 From: Marc <7050295+marcleblanc2@users.noreply.github.com> Date: Tue, 3 Nov 2026 16:13:51 -0600 Subject: [PATCH 633/647] chore/deps: update Go to 1.27.3 and all dependencies to latest (#1386) * chore/deps: update Go to 1.27.3 and all dependencies to latest - Go 1.27.3 in mise.toml, go.mod, lib/go.mod, dev/vendor-lib.sh and the Docker builder images; Alpine 3.24 runtime images. - go get -u ./... and go mod tidy in both modules. Pins: - derision-test/glock v1.1.4: v1.1.5 MockTicker delivers duplicate ticks (see go.mod comment), which breaks the watchdog test. - gobwas/glob v0.2.3: v1 is a rewrite with different matching semantics, and lib/ mirrors the monorepo's pin. - k8s.io/kube-openapi at the version apimachinery v0.37.2 requires; newer pulls conflicting structured-merge-diff majors. - go fix ./... run twice in both modules (Go 1.27 modernizers), with the two leftovers lint flags cleaned up: fmt.Fprintf in curlCmd and the inlined boolPtr helper removed. - GitHub Actions: checkout v7, setup-node v7, setup-qemu v4, setup-buildx v4, Node 26.13.0 for npm publish. goreleaser-action stays on v5: v6+ installs goreleaser v2, which rejects .goreleaser-patch.yml (tap/folder removed in v2) and fails check on the v1 config. Migrating to v2 is a separate change. - golangci-lint 2.15.0, shfmt 3.14.1, shellcheck 0.11.0. Co-authored-by: Amp Amp-Thread-ID: https://ampcode.com/threads/T-01a18b16-df86-7399-a300-979289761a30 * changelog: cut the 8.1.2687 section; document patch-number ordering Per DEVELOPMENT.md step 2, move the unreleased entries under 8.1.2687 and leave an empty Unreleased section. Note that later 8.1.x patch numbers must stay above 2687 so the Build and Release action and sourcegraph.com's release cache agree on which 8.1 release is newest. Amp-Thread-ID: https://ampcode.com/threads/T-01a18b16-df86-7399-a300-979289761a30 Co-authored-by: Amp * ci: use ghcr.io/scip-code/scip-go image, which supports Go 1.27 Amp-Thread-ID: https://ampcode.com/threads/T-01a18b16-df86-7399-a300-979289761a30 Co-authored-by: Amp * ci: install scip-go with the repo's Go toolchain instead of the stale Docker image Amp-Thread-ID: https://ampcode.com/threads/T-01a18b16-df86-7399-a300-979289761a30 Co-authored-by: Amp --------- Co-authored-by: Amp --- .github/workflows/docker.yml | 6 +- .github/workflows/go-ci.yml | 2 +- .github/workflows/go-lint.yml | 2 +- .github/workflows/goreleaser-check.yml | 2 +- .github/workflows/goreleaser.yml | 16 +- .github/workflows/scip.yml | 10 +- CHANGELOG.md | 11 + DEVELOPMENT.md | 2 + Dockerfile | 4 +- Dockerfile.release | 2 +- cmd/src/code_intel_upload.go | 42 +- cmd/src/code_intel_upload_vendored.go | 1 - cmd/src/doc_test.go | 2 +- cmd/src/help_test.go | 2 +- cmd/src/snapshot_upload.go | 2 - dev/golangci-lint.sh | 2 +- dev/vendor-lib.sh | 2 +- .../batch-change-volume-workspace/Dockerfile | 2 +- go.mod | 318 +++++---- go.sum | 644 +++++++++--------- internal/api/api.go | 14 +- internal/api/proxy_test.go | 42 +- internal/api/test_unix_socket_server.go | 6 +- internal/batches/service/service.go | 6 +- internal/lsp/server_test.go | 6 +- internal/streaming/client.go | 6 +- internal/validate/kube/kube.go | 2 +- internal/validate/kube/kube_test.go | 37 +- lib/batches/batch_spec.go | 4 +- lib/batches/overridable/overridable.go | 13 +- lib/go.mod | 89 ++- lib/go.sum | 208 +++--- mise.toml | 6 +- 33 files changed, 757 insertions(+), 756 deletions(-) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index c74ad5ab64..5a4d32d6f7 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -16,16 +16,16 @@ jobs: runs-on: ubuntu-24.04 steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v7 # We need buildx to be able to build a multi-architecture image. - name: Set up Docker buildx - uses: docker/setup-buildx-action@v3 + uses: docker/setup-buildx-action@v4 # We also need QEMU, since this is running on an AMD64 host and we want to # build ARM64 images. - name: Set up QEMU - uses: docker/setup-qemu-action@v3 + uses: docker/setup-qemu-action@v4 with: platforms: arm64 diff --git a/.github/workflows/go-ci.yml b/.github/workflows/go-ci.yml index 5f7d9e63c8..bbc30740a6 100644 --- a/.github/workflows/go-ci.yml +++ b/.github/workflows/go-ci.yml @@ -11,7 +11,7 @@ jobs: runs-on: ${{ matrix.os }} steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v7 - name: Get Go version from mise id: mise run: echo "go-version=$(grep 'golang' mise.toml | cut -d'"' -f2)" >> $GITHUB_OUTPUT diff --git a/.github/workflows/go-lint.yml b/.github/workflows/go-lint.yml index 2a851b2a1b..90ba260b00 100644 --- a/.github/workflows/go-lint.yml +++ b/.github/workflows/go-lint.yml @@ -9,7 +9,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v7 - name: Get Go version from mise id: mise run: echo "go-version=$(grep 'golang' mise.toml | cut -d'"' -f2)" >> $GITHUB_OUTPUT diff --git a/.github/workflows/goreleaser-check.yml b/.github/workflows/goreleaser-check.yml index 780a6ba76b..443f131aa6 100644 --- a/.github/workflows/goreleaser-check.yml +++ b/.github/workflows/goreleaser-check.yml @@ -9,7 +9,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v7 with: fetch-depth: 0 - name: Get Go version from mise diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index 614915f0c0..35e3125826 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -47,7 +47,7 @@ jobs: second_latest_tag: ${{ env.second_latest_tag }} steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v7 with: fetch-depth: 0 - name: Set current tag, latest (highest version) tag, and second latest tag @@ -103,7 +103,7 @@ jobs: echo "latest_tag=${{ needs.release_type.outputs.latest_tag }}" >> $GITHUB_ENV echo "second_latest_tag=${{ needs.release_type.outputs.second_latest_tag }}" >> $GITHUB_ENV - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v7 with: fetch-depth: 0 - name: Set versioning variables @@ -116,7 +116,7 @@ jobs: echo "Versioned formula file: ${{ env.versioned_formula_file }}" echo "Versioned classname: ${{ env.versioned_classname }}" - name: Checkout Homebrew tap - uses: actions/checkout@v4 + uses: actions/checkout@v7 with: repository: sourcegraph/homebrew-src-cli fetch-depth: 0 @@ -171,7 +171,7 @@ jobs: run: | echo "Goreleaser config file: ${{ env.config_file }}" - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v7 with: fetch-depth: 0 - name: Get Go version from mise @@ -223,7 +223,7 @@ jobs: echo "Old symlink: ${{ env.old_symlink_name }}" echo "New symlink: ${{ env.new_symlink_name }}" - name: Checkout Homebrew tap - uses: actions/checkout@v4 + uses: actions/checkout@v7 with: repository: sourcegraph/homebrew-src-cli fetch-depth: 0 @@ -244,12 +244,12 @@ jobs: needs: goreleaser steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v7 with: fetch-depth: 0 - - uses: actions/setup-node@v6 + - uses: actions/setup-node@v7 with: - node-version: 24.16.0 + node-version: 26.13.0 registry-url: 'https://registry.npmjs.org' - run: echo "VERSION=${GITHUB_REF/refs\/tags\//}" >> $GITHUB_ENV - run: echo "Releasing version ${{ env.version }}" diff --git a/.github/workflows/scip.yml b/.github/workflows/scip.yml index 91d467626a..8117010145 100644 --- a/.github/workflows/scip.yml +++ b/.github/workflows/scip.yml @@ -5,9 +5,8 @@ on: jobs: scip-go: runs-on: ubuntu-latest - container: sourcegraph/scip-go steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v7 - name: Get Go version from mise id: mise run: echo "go-version=$(grep 'golang' mise.toml | cut -d'"' -f2)" >> $GITHUB_OUTPUT @@ -16,8 +15,11 @@ jobs: with: go-version: ${{ steps.mise.outputs.go-version }} - - name: Set directory to safe for git - run: git config --global --add safe.directory $GITHUB_WORKSPACE + # Built with the same Go toolchain as src-cli, so scip-go recognizes + # every stdlib package of that Go version. The sourcegraph/scip-go + # Docker image stopped at v0.1.26 (Go 1.26) and fails on Go 1.27. + - name: Install scip-go + run: go install github.com/scip-code/scip-go/cmd/scip-go@v0.2.9 - name: Build src-cli run: go build -o ./src-cli ./cmd/src diff --git a/CHANGELOG.md b/CHANGELOG.md index 0835d977b8..7bd9a46ff0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,8 +15,19 @@ All notable changes to `src-cli` are documented in this file. ### Changed +### Fixed + +### Removed + +## 8.1.2687 + +### Added + +### Changed + - Updated Go to 1.26.10 and the Alpine `ca-certificates-bundle` in Docker images to 20261020-r0 to stop trusting the compromised eMudhra CAs ([CVE-2026-111943](https://emudhra.we-have-a-problem.com/)). - Updated Go dependencies to patch all open Trivy and Dependabot findings: `golang.org/x/crypto`, `golang.org/x/net`, `golang.org/x/text`, `golang.org/x/mod`, `github.com/klauspost/compress`, `github.com/go-jose/go-jose/v4`, `google.golang.org/grpc`, and `go.opentelemetry.io/otel/sdk`. +- Updated Go to 1.27.3, Alpine base images to 3.24, GitHub Actions to current major versions, and all Go dependencies to their latest versions. `src snapshot upload` now loads the `-credentials-file` strictly as a service account key. - HTTP requests now fail instead of hanging forever if the server does not start responding within 1 minute. Set the `SRC_RESPONSE_HEADER_TIMEOUT` environment variable to change this timeout, or to `0` to disable it. Responses that stream data for a long time (for example, large search job results) are not affected. - `src search-jobs logs` and `src search-jobs results` now use the standard API client, gaining proxy support, `-insecure-skip-verify`, and cross-host redirect protection, and now report an error on non-200 responses instead of writing the error page into the output. - The command list in `src help` is now generated from the registered commands instead of being maintained by hand. `src debug`, `src snapshot`, and `src lsp` now appear in it; aliases are shown after each description. diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index 7b005e24de..07fc74233c 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -102,6 +102,8 @@ If a backwards-compatible change, such as a bug fix, is made _after_ a backwards A Sourcegraph instance returns the highest patch version with the same major and minor version as `MinimumVersion` as defined in the instance. Patch versions are reserved solely for non-breaking changes and minor bug fixes. This allows us to dynamically release fixes for older versions of `src-cli` without having to update the instance. +Patch numbers must only increase within a minor line. Since 8.1.2687, releases carry the Sourcegraph build number as the patch component, so a later 8.1.x must use a number above 2687 (for example the current Sourcegraph 8.1 build number). A lower number such as 8.1.1 would be treated as a patch of an older version by the Build and Release action (no `latest` tag or main Homebrew formula) while sourcegraph.com would still recommend it as the newest 8.1 release. + To release a bug fix or a new feature that is backwards compatible with one of the previous two minor version of Sourcegraph, cherry-pick the changes into a patch branch, then follow the steps above to release the patch, specifying the appropriate patch `VERSION`. The Build and Release action will automatically create the appropriate versioned release, without overwriting the latest one. ## Docker diff --git a/Dockerfile b/Dockerfile index 6a865963eb..479d894d80 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,14 +4,14 @@ # # Nothing fancy here: we copy in the source code and build on the Alpine Go # image. Refer to .dockerignore to get a sense of what we're not going to copy. -FROM golang:1.26.10-alpine3.23@sha256:a07f231c19b03e6106cf442f02a5bcf262147e744d15b7b5e4b6d81d420c70a0 AS builder +FROM golang:1.27.3-alpine3.24@sha256:d200d2dd76b03a99b52651fd1325aff7dcd35422c35c01bac56571b0507f3deb AS builder COPY . /src WORKDIR /src RUN go build ./cmd/src # This stage should be kept in sync with Dockerfile.release. -FROM alpine:3.22@sha256:5291449c3df73caf6ed85e649dec1b9e818b39a5d8c871e97afc13e9cd5e8fa8 +FROM alpine:3.24@sha256:ff7f0c727dd796aa36787bfcd9a64bf35a6ce72a73451b3359fde849b6703d63 # needed for `src code-intel upload` and `src actions exec` # ca-certificates-bundle >= 20261020-r0 drops the eMudhra roots (CVE-2026-111943). diff --git a/Dockerfile.release b/Dockerfile.release index baccfc98f5..ca867b82ac 100644 --- a/Dockerfile.release +++ b/Dockerfile.release @@ -2,7 +2,7 @@ # suitable for testing, since it depends on a src binary being at the project # root _and_ that src binary being runnable on Alpine. To test this, refer to # the main Dockerfile, which should have an identical second stage. -FROM alpine:3.22@sha256:5291449c3df73caf6ed85e649dec1b9e818b39a5d8c871e97afc13e9cd5e8fa8 +FROM alpine:3.24@sha256:ff7f0c727dd796aa36787bfcd9a64bf35a6ce72a73451b3359fde849b6703d63 # needed for `src code-intel upload` and `src actions exec` # ca-certificates-bundle >= 20261020-r0 drops the eMudhra roots (CVE-2026-111943). diff --git a/cmd/src/code_intel_upload.go b/cmd/src/code_intel_upload.go index d5e686babc..e49a43748d 100644 --- a/cmd/src/code_intel_upload.go +++ b/cmd/src/code_intel_upload.go @@ -140,30 +140,24 @@ func codeintelUploadOptions(out *output.Output) upload.UploadOptions { ) return upload.UploadOptions{ - UploadRecordOptions: upload.UploadRecordOptions{ - Repo: codeintelUploadFlags.repo, - Commit: codeintelUploadFlags.commit, - Root: codeintelUploadFlags.root, - Indexer: codeintelUploadFlags.indexer, - IndexerVersion: codeintelUploadFlags.indexerVersion, - AssociatedIndexID: associatedIndexID, - }, - SourcegraphInstanceOptions: upload.SourcegraphInstanceOptions{ - SourcegraphURL: cfg.endpointURL.String(), - AccessToken: cfg.accessToken, - AdditionalHeaders: cfg.additionalHeaders, - MaxRetries: 5, - RetryInterval: time.Second, - Path: codeintelUploadFlags.uploadRoute, - MaxPayloadSizeBytes: codeintelUploadFlags.maxPayloadSizeMb * 1000 * 1000, - MaxConcurrency: codeintelUploadFlags.maxConcurrency, - GitHubToken: codeintelUploadFlags.gitHubToken, - GitLabToken: codeintelUploadFlags.gitLabToken, - }, - OutputOptions: upload.OutputOptions{ - Output: out, - Logger: logger, - }, + Repo: codeintelUploadFlags.repo, + Commit: codeintelUploadFlags.commit, + Root: codeintelUploadFlags.root, + Indexer: codeintelUploadFlags.indexer, + IndexerVersion: codeintelUploadFlags.indexerVersion, + AssociatedIndexID: associatedIndexID, + SourcegraphURL: cfg.endpointURL.String(), + AccessToken: cfg.accessToken, + AdditionalHeaders: cfg.additionalHeaders, + MaxRetries: 5, + RetryInterval: time.Second, + Path: codeintelUploadFlags.uploadRoute, + MaxPayloadSizeBytes: codeintelUploadFlags.maxPayloadSizeMb * 1000 * 1000, + MaxConcurrency: codeintelUploadFlags.maxConcurrency, + GitHubToken: codeintelUploadFlags.gitHubToken, + GitLabToken: codeintelUploadFlags.gitLabToken, + Output: out, + Logger: logger, } } diff --git a/cmd/src/code_intel_upload_vendored.go b/cmd/src/code_intel_upload_vendored.go index a1a98fe86a..eef5b9aed8 100644 --- a/cmd/src/code_intel_upload_vendored.go +++ b/cmd/src/code_intel_upload_vendored.go @@ -176,7 +176,6 @@ func uploadMultipartIndexParts(ctx context.Context, httpClient upload.Client, op } for i, reader := range readers { - i, reader := i, reader pool.Go(func(ctx context.Context) error { // Determine size of this reader. If we're not the last reader in the slice, diff --git a/cmd/src/doc_test.go b/cmd/src/doc_test.go index 4f886405cb..75747ba874 100644 --- a/cmd/src/doc_test.go +++ b/cmd/src/doc_test.go @@ -198,7 +198,7 @@ func TestDocRootIndexMatchesHelp(t *testing.T) { } var indexed []string - for _, line := range strings.Split(string(index), "\n") { + for line := range strings.SplitSeq(string(index), "\n") { // Lines look like: * [`name`](name.md) or * [`name`](name/index.md) rest, ok := strings.CutPrefix(strings.TrimSpace(line), "* [`") if !ok { diff --git a/cmd/src/help_test.go b/cmd/src/help_test.go index 4260f381fd..fb93320a94 100644 --- a/cmd/src/help_test.go +++ b/cmd/src/help_test.go @@ -44,7 +44,7 @@ func helpCommandNames(t *testing.T, help string) []string { block, _, _ = strings.Cut(block, "\nUse \"src [command] -h\"") var names []string - for _, line := range strings.Split(block, "\n") { + for line := range strings.SplitSeq(block, "\n") { line = strings.TrimSpace(line) if line == "" { continue diff --git a/cmd/src/snapshot_upload.go b/cmd/src/snapshot_upload.go index 3a7a88176e..65d2aa34fe 100644 --- a/cmd/src/snapshot_upload.go +++ b/cmd/src/snapshot_upload.go @@ -295,8 +295,6 @@ func uploadFilesToBucket(client *gcsClient, args *uploadArgs, openedFiles []uplo // Upload each file in parallel for fileIndex, openedFile := range openedFiles { - openedFile := openedFile - uploadPool.Go(func(ctx context.Context) error { progressFn := func(bytesWritten int64) { progress.SetValue(fileIndex, float64(bytesWritten)) } diff --git a/dev/golangci-lint.sh b/dev/golangci-lint.sh index e7adad08b2..00db8cd7ce 100755 --- a/dev/golangci-lint.sh +++ b/dev/golangci-lint.sh @@ -6,7 +6,7 @@ pushd "$(dirname "${BASH_SOURCE[0]}")/.." >/dev/null mkdir -p dev/.bin -version="2.10.1" +version="2.15.0" suffix="${version}-$(go env GOOS)-$(go env GOARCH)" target="$PWD/dev/.bin/golangci-lint-${suffix}" url="https://github.com/golangci/golangci-lint/releases/download/v${version}/golangci-lint-${suffix}.tar.gz" diff --git a/dev/vendor-lib.sh b/dev/vendor-lib.sh index d007d89352..3b6ba53a2f 100755 --- a/dev/vendor-lib.sh +++ b/dev/vendor-lib.sh @@ -136,7 +136,7 @@ echo "Creating go.mod file..." cat > "$DEST_LIB/go.mod" <= 20261020-r0 drops the eMudhra roots (CVE-2026-111943). RUN apk add --update git unzip && apk upgrade --no-cache ca-certificates-bundle diff --git a/go.mod b/go.mod index 87509a024d..e90ea68b3f 100644 --- a/go.mod +++ b/go.mod @@ -1,203 +1,219 @@ module github.com/sourcegraph/src-cli -go 1.26.10 +go 1.27.3 require ( - cloud.google.com/go/storage v1.56.0 - github.com/aws/aws-sdk-go-v2/config v1.18.13 - github.com/aws/aws-sdk-go-v2/service/ec2 v1.86.0 - github.com/aws/aws-sdk-go-v2/service/eks v1.27.3 - github.com/aws/aws-sdk-go-v2/service/iam v1.19.3 - github.com/creack/goselect v0.1.2 - github.com/derision-test/glock v1.0.0 + cloud.google.com/go/storage v1.70.0 + github.com/aws/aws-sdk-go-v2/config v1.33.12 + github.com/aws/aws-sdk-go-v2/service/ec2 v1.343.0 + github.com/aws/aws-sdk-go-v2/service/eks v1.105.1 + github.com/aws/aws-sdk-go-v2/service/iam v1.64.6 + github.com/creack/goselect v0.1.3 + // Pinned: v1.1.5 regressed MockTicker, which can deliver a duplicate tick for + // a single BlockingAdvance. Its deliver() releases the lock around the channel + // send but only advances the deadline afterwards, so the process() goroutine + // can observe now >= deadline in that window and send a second tick. + github.com/derision-test/glock v1.1.4 github.com/dineshappavoo/basex v0.0.0-20170425072625-481a6f6dc663 - github.com/dustin/go-humanize v1.0.1 + github.com/dustin/go-humanize v1.1.0 github.com/gobwas/glob v0.2.3 github.com/google/go-cmp v0.7.0 github.com/grafana/regexp v0.0.0-20250905093917-f7b3be9d1853 github.com/hexops/autogold v1.3.1 - github.com/jedib0t/go-pretty/v6 v6.6.3 + github.com/jedib0t/go-pretty/v6 v6.8.3 github.com/jig/teereadcloser v0.0.0-20181016160506-953720c48e05 github.com/json-iterator/go v1.1.12 github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 - github.com/mattn/go-isatty v0.0.20 + github.com/mattn/go-isatty v0.0.24 github.com/neelance/parallel v0.0.0-20160708114440-4de9ce63d14c - github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 - github.com/scip-code/scip/bindings/go/scip v0.7.0 + github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c + github.com/scip-code/scip/bindings/go/scip v0.10.0 github.com/sourcegraph/conc v0.3.1-0.20240108182409-4afefce20f9b - github.com/sourcegraph/go-diff v0.7.0 - github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf + github.com/sourcegraph/go-diff v0.9.0 + github.com/sourcegraph/jsonx v0.0.0-20260429142705-814a2dc2d22f github.com/sourcegraph/sourcegraph/lib v0.0.0-20240709083501-1af563b61442 - github.com/stretchr/testify v1.11.1 + github.com/stretchr/testify v1.12.1 github.com/tliron/glsp v0.2.2 - github.com/urfave/cli/v3 v3.8.0 - github.com/zalando/go-keyring v0.2.6 - golang.org/x/sync v0.23.0 - google.golang.org/api v0.264.0 - google.golang.org/protobuf v1.36.11 + github.com/urfave/cli/v3 v3.14.0 + github.com/zalando/go-keyring v0.2.8 + golang.org/x/sync v0.24.0 + google.golang.org/api v0.310.0 + google.golang.org/protobuf v1.36.12 gopkg.in/yaml.v3 v3.0.1 - jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7 - k8s.io/api v0.33.2 - k8s.io/apimachinery v0.33.2 - k8s.io/client-go v0.33.2 + jaytaylor.com/html2text v0.0.0-20260303211410-1a4bdc82ecec + k8s.io/api v0.37.2 + k8s.io/apimachinery v0.37.2 + k8s.io/client-go v0.37.2 ) require ( - al.essio.dev/pkg/shellescape v1.5.1 // indirect - cel.dev/expr v0.25.2 // indirect - cloud.google.com/go/auth v0.18.2 // indirect - cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect - cloud.google.com/go/monitoring v1.24.3 // indirect - github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.33.0 // indirect - github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.53.0 // indirect - github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.53.0 // indirect - github.com/alecthomas/chroma/v2 v2.14.0 // indirect - github.com/cespare/xxhash/v2 v2.3.0 // indirect - github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect - github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834 // indirect - github.com/charmbracelet/x/ansi v0.8.0 // indirect - github.com/charmbracelet/x/cellbuf v0.0.13 // indirect - github.com/charmbracelet/x/exp/slice v0.0.0-20250327172914-2fdc97757edf // indirect - github.com/charmbracelet/x/term v0.2.1 // indirect - github.com/clipperhouse/uax29/v2 v2.2.0 // indirect - github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2 // indirect - github.com/danieljoos/wincred v1.2.2 // indirect - github.com/envoyproxy/go-control-plane/envoy v1.37.0 // indirect - github.com/felixge/httpsnoop v1.0.4 // indirect - github.com/fxamacker/cbor/v2 v2.7.0 // indirect - github.com/go-jose/go-jose/v4 v4.1.6 // indirect - github.com/go-logr/stdr v1.2.2 // indirect - github.com/godbus/dbus/v5 v5.1.0 // indirect - github.com/google/gnostic-models v0.6.9 // indirect - github.com/google/s2a-go v0.1.9 // indirect - github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 // indirect - github.com/iancoleman/strcase v0.3.0 // indirect - github.com/jackc/pgpassfile v1.0.0 // indirect - github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect - github.com/jackc/pgx/v5 v5.9.2 // indirect - github.com/petermattis/goid v0.0.0-20240813172612-4fcff4a6cae7 // indirect - github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 // indirect - github.com/sasha-s/go-deadlock v0.3.5 // indirect - github.com/segmentio/ksuid v1.0.4 // indirect - github.com/sourcegraph/beaut v0.0.0-20240611013027-627e4c25335a // indirect - github.com/sourcegraph/jsonrpc2 v0.2.0 // indirect - github.com/spiffe/go-spiffe/v2 v2.7.0 // indirect - github.com/tliron/commonlog v0.2.19 // indirect - github.com/tliron/kutil v0.3.27 // indirect - github.com/x448/float16 v0.8.4 // indirect - github.com/xlab/treeprint v1.2.0 // indirect - github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect - go.opentelemetry.io/auto/sdk v1.2.1 // indirect - go.opentelemetry.io/contrib/detectors/gcp v1.44.0 // indirect - go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0 // indirect - go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0 // indirect - go.opentelemetry.io/otel v1.45.0 // indirect - go.opentelemetry.io/otel/metric v1.45.0 // indirect - go.opentelemetry.io/otel/sdk v1.45.0 // indirect - go.opentelemetry.io/otel/sdk/metric v1.45.0 // indirect - go.opentelemetry.io/otel/trace v1.45.0 // indirect - golang.org/x/net v0.60.0 // indirect - google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa // indirect - gopkg.in/evanphx/json-patch.v4 v4.12.0 // indirect - sigs.k8s.io/randfill v1.0.0 // indirect -) - -require ( - cloud.google.com/go v0.121.6 // indirect - cloud.google.com/go/compute/metadata v0.9.0 // indirect - cloud.google.com/go/iam v1.5.3 // indirect - github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c // indirect + cel.dev/expr v0.25.3 // indirect + cloud.google.com/go v0.123.0 // indirect + cloud.google.com/go/auth v0.24.2 // indirect + cloud.google.com/go/auth/oauth2adapt v0.3.1 // indirect + cloud.google.com/go/compute/metadata v0.10.0 // indirect + cloud.google.com/go/iam v1.15.1 // indirect + cloud.google.com/go/monitoring v1.32.1 // indirect + github.com/Azure/go-ansiterm v0.0.0-20261013165250-51075c6ea6bc // indirect + github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.62.0 // indirect + github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.62.0 // indirect github.com/Masterminds/semver v1.5.0 // indirect - github.com/aws/aws-sdk-go-v2 v1.17.5 // indirect - github.com/aws/aws-sdk-go-v2/credentials v1.13.13 // indirect - github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.12.22 // indirect - github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.29 // indirect - github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.23 // indirect - github.com/aws/aws-sdk-go-v2/internal/ini v1.3.29 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.22 // indirect - github.com/aws/aws-sdk-go-v2/service/sso v1.12.2 // indirect - github.com/aws/aws-sdk-go-v2/service/ssooidc v1.14.2 // indirect - github.com/aws/aws-sdk-go-v2/service/sts v1.18.3 // indirect - github.com/aws/smithy-go v1.13.5 // indirect + github.com/alecthomas/chroma/v2 v2.27.0 // indirect + github.com/aws/aws-sdk-go-v2 v1.47.5 // indirect + github.com/aws/aws-sdk-go-v2/credentials v1.20.12 // indirect + github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.5 // indirect + github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.8 // indirect + github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.8 // indirect + github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.8 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.23 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.8 // indirect + github.com/aws/aws-sdk-go-v2/service/signin v1.12.0 // indirect + github.com/aws/aws-sdk-go-v2/service/sso v1.39.0 // indirect + github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.0 // indirect + github.com/aws/aws-sdk-go-v2/service/sts v1.51.6 // indirect + github.com/aws/smithy-go v1.28.7 // indirect github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect github.com/aymerick/douceur v0.2.0 // indirect - github.com/charmbracelet/glamour v0.10.0 // indirect - github.com/cockroachdb/errors v1.12.0 // indirect - github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect - github.com/cockroachdb/redact v1.1.6 // indirect + github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/charmbracelet/colorprofile v0.4.3 // indirect + github.com/charmbracelet/glamour v1.0.0 // indirect + github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834 // indirect + github.com/charmbracelet/x/ansi v0.11.9 // indirect + github.com/charmbracelet/x/cellbuf v0.0.15 // indirect + github.com/charmbracelet/x/exp/slice v0.1.0 // indirect + github.com/charmbracelet/x/term v0.2.2 // indirect + github.com/clipperhouse/displaywidth v0.11.0 // indirect + github.com/clipperhouse/uax29/v2 v2.7.0 // indirect + github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2 // indirect + github.com/cockroachdb/errors v1.14.0 // indirect + github.com/cockroachdb/logtags v0.0.0-20241215232642-bb51bb14a506 // indirect + github.com/cockroachdb/redact v1.1.8 // indirect + github.com/danieljoos/wincred v1.2.3 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect - github.com/dlclark/regexp2 v1.11.0 // indirect - github.com/emicklei/go-restful/v3 v3.11.0 // indirect + github.com/dlclark/regexp2/v2 v2.12.0 // indirect + github.com/emicklei/go-restful/v3 v3.13.0 // indirect + github.com/envoyproxy/go-control-plane/envoy v1.40.0 // indirect github.com/envoyproxy/protoc-gen-validate v1.3.3 // indirect - github.com/fatih/color v1.18.0 // indirect - github.com/getsentry/sentry-go v0.27.0 // indirect + github.com/fatih/color v1.19.0 // indirect + github.com/felixge/httpsnoop v1.1.0 // indirect + github.com/fxamacker/cbor/v2 v2.10.0 // indirect + github.com/getsentry/sentry-go v0.50.0 // indirect github.com/ghodss/yaml v1.0.0 // indirect + github.com/go-jose/go-jose/v4 v4.1.6 // indirect github.com/go-logr/logr v1.4.4 // indirect - github.com/go-openapi/jsonpointer v0.21.0 // indirect - github.com/go-openapi/jsonreference v0.20.2 // indirect - github.com/go-openapi/swag v0.23.0 // indirect + github.com/go-logr/stdr v1.2.2 // indirect + github.com/go-openapi/jsonpointer v1.0.2 // indirect + github.com/go-openapi/jsonreference v1.0.3 // indirect + github.com/go-openapi/swag v0.27.1 // indirect + github.com/go-openapi/swag/cmdutils v0.27.1 // indirect + github.com/go-openapi/swag/conv v0.29.2 // indirect + github.com/go-openapi/swag/fileutils v0.27.1 // indirect + github.com/go-openapi/swag/jsonutils v0.29.2 // indirect + github.com/go-openapi/swag/loading v0.27.1 // indirect + github.com/go-openapi/swag/mangling v0.27.1 // indirect + github.com/go-openapi/swag/netutils v0.27.1 // indirect + github.com/go-openapi/swag/pools v0.29.2 // indirect + github.com/go-openapi/swag/stringutils v0.27.1 // indirect + github.com/go-openapi/swag/typeutils v0.29.2 // indirect + github.com/go-openapi/swag/yamlutils v0.27.1 // indirect + github.com/goccy/go-json v0.12.0 // indirect + github.com/godbus/dbus/v5 v5.2.4 // indirect github.com/gogo/protobuf v1.3.2 // indirect + github.com/google/gnostic-models v0.7.1 // indirect + github.com/google/s2a-go v0.1.11 // indirect github.com/google/uuid v1.6.0 // indirect - github.com/googleapis/enterprise-certificate-proxy v0.3.11 // indirect - github.com/googleapis/gax-go/v2 v2.17.0 // indirect + github.com/googleapis/enterprise-certificate-proxy v0.3.24 // indirect + github.com/googleapis/gax-go/v2 v2.27.0 // indirect github.com/gorilla/css v1.0.1 // indirect + github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 // indirect github.com/hexops/gotextdiff v1.0.3 // indirect - github.com/hexops/valast v1.4.4 // indirect - github.com/jmespath/go-jmespath v0.4.0 // indirect - github.com/josharian/intern v1.0.0 // indirect - github.com/klauspost/compress v1.18.7 // indirect - github.com/klauspost/pgzip v1.2.6 // indirect + github.com/hexops/valast v1.5.0 // indirect + github.com/iancoleman/strcase v0.3.0 // indirect + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect + github.com/jackc/pgx/v5 v5.11.0 // indirect + github.com/klauspost/compress v1.20.3 // indirect + github.com/klauspost/pgzip v1.3.0 // indirect github.com/kr/pretty v0.3.1 // indirect github.com/kr/text v0.2.0 // indirect - github.com/lucasb-eyer/go-colorful v1.2.0 // indirect - github.com/mailru/easyjson v0.7.7 // indirect - github.com/mattn/go-colorable v0.1.14 // indirect - github.com/mattn/go-runewidth v0.0.19 // indirect + github.com/lucasb-eyer/go-colorful v1.4.1 // indirect + github.com/mattn/go-colorable v0.1.16 // indirect + github.com/mattn/go-runewidth v0.0.31 // indirect github.com/microcosm-cc/bluemonday v1.0.27 // indirect github.com/moby/term v0.5.2 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect - github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect github.com/muesli/reflow v0.3.0 // indirect github.com/muesli/termenv v0.16.0 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/nightlyone/lockfile v1.0.0 // indirect - github.com/olekukonko/tablewriter v0.0.5 // indirect + github.com/olekukonko/cat v0.0.0-20250911104152-50322a0618f6 // indirect + github.com/olekukonko/errors v1.3.0 // indirect + github.com/olekukonko/ll v0.1.9 // indirect + github.com/olekukonko/tablewriter v1.1.5 // indirect + github.com/petermattis/goid v0.0.0-20260918085751-abfca077860b // indirect github.com/pkg/errors v0.9.1 // indirect - github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect + github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 // indirect github.com/rivo/uniseg v0.4.7 // indirect - github.com/rogpeppe/go-internal v1.14.1 // indirect - github.com/sourcegraph/log v0.0.0-20250923023806-517b6960b55b // indirect - github.com/spf13/pflag v1.0.6 // indirect + github.com/rogpeppe/go-internal v1.16.0 // indirect + github.com/sasha-s/go-deadlock v0.3.9 // indirect + github.com/segmentio/ksuid v1.0.4 // indirect + github.com/sourcegraph/beaut v0.0.0-20240611013027-627e4c25335a // indirect + github.com/sourcegraph/jsonrpc2 v0.2.3 // indirect + github.com/sourcegraph/log v0.0.0-20260714115934-b104ff56b299 // indirect + github.com/spf13/pflag v1.0.10 // indirect + github.com/spiffe/go-spiffe/v2 v2.9.0 // indirect github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect - github.com/stretchr/objx v0.5.2 // indirect + github.com/stretchr/objx v0.8.0 // indirect + github.com/tliron/commonlog v0.2.21 // indirect + github.com/tliron/go-kutil v0.4.0 // indirect + github.com/x448/float16 v0.8.4 // indirect github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect github.com/xeipuuv/gojsonschema v1.2.0 // indirect - github.com/yuin/goldmark v1.7.17 // indirect - github.com/yuin/goldmark-emoji v1.0.5 // indirect - go.uber.org/atomic v1.11.0 // indirect + github.com/xlab/treeprint v1.2.0 // indirect + github.com/xo/terminfo v1.3.0 // indirect + github.com/yuin/goldmark v1.8.7 // indirect + github.com/yuin/goldmark-emoji v1.0.6 // indirect + go.opentelemetry.io/auto/sdk v1.2.1 // indirect + go.opentelemetry.io/contrib/detectors/gcp v1.47.0 // indirect + go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.72.0 // indirect + go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0 // indirect + go.opentelemetry.io/otel v1.47.0 // indirect + go.opentelemetry.io/otel/log v1.47.0 // indirect + go.opentelemetry.io/otel/metric v1.47.0 // indirect + go.opentelemetry.io/otel/sdk v1.47.0 // indirect + go.opentelemetry.io/otel/sdk/metric v1.47.0 // indirect + go.opentelemetry.io/otel/trace v1.47.0 // indirect + go.uber.org/atomic v1.12.0 // indirect go.uber.org/multierr v1.11.0 // indirect - go.uber.org/zap v1.24.0 // indirect - golang.org/x/crypto v0.57.0 // indirect - golang.org/x/mod v0.41.0 // indirect - golang.org/x/oauth2 v0.36.0 // indirect - golang.org/x/sys v0.48.0 // indirect - golang.org/x/term v0.46.0 // indirect - golang.org/x/text v0.42.0 // indirect - golang.org/x/time v0.14.0 // indirect - golang.org/x/tools v0.49.0 // indirect - google.golang.org/genproto v0.0.0-20260128011058-8636f8732409 // indirect - google.golang.org/grpc v1.83.2 // indirect + go.uber.org/zap v1.28.0 // indirect + go.yaml.in/yaml/v2 v2.4.4 // indirect + go.yaml.in/yaml/v3 v3.0.5 // indirect + golang.org/x/crypto v0.58.0 // indirect + golang.org/x/mod v0.42.0 // indirect + golang.org/x/net v0.62.0 // indirect + golang.org/x/oauth2 v0.37.0 // indirect + golang.org/x/sys v0.49.0 // indirect + golang.org/x/term v0.47.0 // indirect + golang.org/x/text v0.43.0 // indirect + golang.org/x/time v0.16.0 // indirect + golang.org/x/tools v0.51.0 // indirect + google.golang.org/genproto v0.0.0-20261026165753-2ffab32bce7e // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20261026165753-2ffab32bce7e // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20261026165753-2ffab32bce7e // indirect + google.golang.org/grpc v1.85.0 // indirect + gopkg.in/evanphx/json-patch.v4 v4.13.0 // indirect gopkg.in/inf.v0 v0.9.1 // indirect; direct gopkg.in/yaml.v2 v2.4.0 // indirect - k8s.io/klog/v2 v2.130.1 // indirect - k8s.io/kube-openapi v0.0.0-20250318190949-c8a335a9a2ff // indirect - k8s.io/utils v0.0.0-20241104100929-3ea5e8cea738 // indirect - mvdan.cc/gofumpt v0.5.0 // indirect - sigs.k8s.io/json v0.0.0-20241010143419-9aa6b5e7a4b3 // indirect - sigs.k8s.io/structured-merge-diff/v4 v4.6.0 // indirect - sigs.k8s.io/yaml v1.4.0 // indirect + k8s.io/klog/v2 v2.140.0 // indirect + k8s.io/kube-openapi v0.0.0-20260721132016-d427ff9ee9ad // indirect + k8s.io/utils v0.0.0-20261023123148-ca04ba58ecab // indirect + mvdan.cc/gofumpt v0.10.0 // indirect + sigs.k8s.io/json v0.0.0-20260909141634-11ed52e25bc5 // indirect + sigs.k8s.io/randfill v1.0.0 // indirect + sigs.k8s.io/structured-merge-diff/v6 v6.4.2 // indirect + sigs.k8s.io/yaml v1.6.0 // indirect ) // See: https://github.com/ghodss/yaml/pull/65 diff --git a/go.sum b/go.sum index b104115891..1a87313a69 100644 --- a/go.sum +++ b/go.sum @@ -1,155 +1,150 @@ -al.essio.dev/pkg/shellescape v1.5.1 h1:86HrALUujYS/h+GtqoB26SBEdkWfmMI6FubjXlsXyho= -al.essio.dev/pkg/shellescape v1.5.1/go.mod h1:6sIqp7X2P6mThCQ7twERpZTuigpr6KbZWtls1U8I890= -cel.dev/expr v0.25.2 h1:K6j46C81hXtZQfuX60cVWQFBJahKSE2gfRbNuvr5bFs= -cel.dev/expr v0.25.2/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4= -cloud.google.com/go v0.121.6 h1:waZiuajrI28iAf40cWgycWNgaXPO06dupuS+sgibK6c= -cloud.google.com/go v0.121.6/go.mod h1:coChdst4Ea5vUpiALcYKXEpR1S9ZgXbhEzzMcMR66vI= -cloud.google.com/go/auth v0.18.2 h1:+Nbt5Ev0xEqxlNjd6c+yYUeosQ5TtEUaNcN/3FozlaM= -cloud.google.com/go/auth v0.18.2/go.mod h1:xD+oY7gcahcu7G2SG2DsBerfFxgPAJz17zz2joOFF3M= -cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIiLpZnkHRbnc= -cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c= -cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdBtwLoEkH9Zs= -cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10= -cloud.google.com/go/iam v1.5.3 h1:+vMINPiDF2ognBJ97ABAYYwRgsaqxPbQDlMnbHMjolc= -cloud.google.com/go/iam v1.5.3/go.mod h1:MR3v9oLkZCTlaqljW6Eb2d3HGDGK5/bDv93jhfISFvU= -cloud.google.com/go/logging v1.13.1 h1:O7LvmO0kGLaHY/gq8cV7T0dyp6zJhYAOtZPX4TF3QtY= -cloud.google.com/go/logging v1.13.1/go.mod h1:XAQkfkMBxQRjQek96WLPNze7vsOmay9H5PqfsNYDqvw= -cloud.google.com/go/longrunning v0.8.0 h1:LiKK77J3bx5gDLi4SMViHixjD2ohlkwBi+mKA7EhfW8= -cloud.google.com/go/longrunning v0.8.0/go.mod h1:UmErU2Onzi+fKDg2gR7dusz11Pe26aknR4kHmJJqIfk= -cloud.google.com/go/monitoring v1.24.3 h1:dde+gMNc0UhPZD1Azu6at2e79bfdztVDS5lvhOdsgaE= -cloud.google.com/go/monitoring v1.24.3/go.mod h1:nYP6W0tm3N9H/bOw8am7t62YTzZY+zUeQ+Bi6+2eonI= -cloud.google.com/go/storage v1.56.0 h1:iixmq2Fse2tqxMbWhLWC9HfBj1qdxqAmiK8/eqtsLxI= -cloud.google.com/go/storage v1.56.0/go.mod h1:Tpuj6t4NweCLzlNbw9Z9iwxEkrSem20AetIeH/shgVU= -cloud.google.com/go/trace v1.11.7 h1:kDNDX8JkaAG3R2nq1lIdkb7FCSi1rCmsEtKVsty7p+U= -cloud.google.com/go/trace v1.11.7/go.mod h1:TNn9d5V3fQVf6s4SCveVMIBS2LJUqo73GACmq/Tky0s= -github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg= -github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.33.0 h1:l7+6kwRMJNwdCvYdDl7Eax+wzEYHSnNY7zrrfbhDdTA= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.33.0/go.mod h1:pJTkW8hEUIIi3Pf65lPZOnn4Y81yCllX6IWk2jNXdkM= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.53.0 h1:owcC2UnmsZycprQ5RfRgjydWhuoxg71LUfyiQdijZuM= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.53.0/go.mod h1:ZPpqegjbE99EPKsu3iUWV22A04wzGPcAY/ziSIQEEgs= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0.53.0 h1:4LP6hvB4I5ouTbGgWtixJhgED6xdf67twf9PoY96Tbg= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0.53.0/go.mod h1:jUZ5LYlw40WMd07qxcQJD5M40aUxrfwqQX1g7zxYnrQ= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.53.0 h1:Ron4zCA/yk6U7WOBXhTJcDpsUBG9npumK6xw2auFltQ= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.53.0/go.mod h1:cSgYe11MCNYunTnRXrKiR/tHc0eoKjICUuWpNZoVCOo= +cel.dev/expr v0.25.3 h1:A2jO8jwOugrrovveCWfj0KEZOfqiLgAcwjpHPhzIGw0= +cel.dev/expr v0.25.3/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4= +cloud.google.com/go v0.123.0 h1:2NAUJwPR47q+E35uaJeYoNhuNEM9kM8SjgRgdeOJUSE= +cloud.google.com/go v0.123.0/go.mod h1:xBoMV08QcqUGuPW65Qfm1o9Y4zKZBpGS+7bImXLTAZU= +cloud.google.com/go/auth v0.24.2 h1:B1/4OLie/oVowCTrVgFS3NpEtIrLsuudX0/BxKsEk6s= +cloud.google.com/go/auth v0.24.2/go.mod h1:p4UXqfSXnMVUDutk9xePzI8lj8yyoJ3BLsKWv0NSvQk= +cloud.google.com/go/auth/oauth2adapt v0.3.1 h1:BKLDdbWS7pafd820dsyFDF6fPEzIGqr7ny6hbTzCCgE= +cloud.google.com/go/auth/oauth2adapt v0.3.1/go.mod h1:B1nM4FJDxoDqAt3PXFG4IflUoQ5kvWAOOM3R+5wAszg= +cloud.google.com/go/compute/metadata v0.10.0 h1:pyKMUQSwchgkIBBJGdILqQbs/BNJXqwSA7Ej6LAvvtY= +cloud.google.com/go/compute/metadata v0.10.0/go.mod h1:rGFHRrIif570kSibjFTMbt6/4/tzgJWFGI/HVol4GIk= +cloud.google.com/go/iam v1.15.1 h1:i6EXLKyIi0Sh72p+5+Fz0PfnzB63bkneVpaBCGrjlWs= +cloud.google.com/go/iam v1.15.1/go.mod h1:nDJ/rfCzLKyBUY1AeiSQwOAJg/AN7zZ2QmNzRTcK2jM= +cloud.google.com/go/logging v1.21.0 h1:Grn9NZsh87BO5+CEtZFFdj5mXEAnrlPFEdHDMVo9p8Y= +cloud.google.com/go/logging v1.21.0/go.mod h1:4foM+ucR/w1KQrJOh4tDr14iHUIt0MLh2cL8094/LZs= +cloud.google.com/go/longrunning v1.4.0 h1:l53OXv/ZAQCvATPqdYIqxruIUa1+eeX3Ckg0EBMpZLM= +cloud.google.com/go/longrunning v1.4.0/go.mod h1:HAJuq0kD9eDyV6DtaN+0b6niPzFFFf9QMMHkHD7DvMc= +cloud.google.com/go/monitoring v1.32.1 h1:DzNqsbCCyMJ+Oq+McBHaR5qqqxCvdNCIgfJug/YM0Ys= +cloud.google.com/go/monitoring v1.32.1/go.mod h1:JkJhVXtTcGh6KQuvProJ9olvu2p37Ay29CinCDFKHHg= +cloud.google.com/go/storage v1.70.0 h1:LQNHn0rRF94jVFfF3e416IzdQqIufa5GfF6HilQxb80= +cloud.google.com/go/storage v1.70.0/go.mod h1:W84cNa070TZIegvTW67CBY+f5rxux8EJMb7YyiHdrls= +cloud.google.com/go/trace v1.16.0 h1:GmQovzFc5F0CNfl0VLgL64aoTtu7xsM0YajW2GlG9+E= +cloud.google.com/go/trace v1.16.0/go.mod h1:r+bdAn16dKLSV1G2D5v3e58IlQlizfxWrUfjx7kM7X0= +github.com/Azure/go-ansiterm v0.0.0-20261013165250-51075c6ea6bc h1:58s5YzGPNAP7+e1uemaL0ax/NPSeJOHdRpRIowd+JDk= +github.com/Azure/go-ansiterm v0.0.0-20261013165250-51075c6ea6bc/go.mod h1:DMNF6Kxv+EcuUvVuNkvC3f+BjEEmc/Fn9aU+qiD8zpU= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.62.0 h1:5y2LR2pripbccOte6BpZ+guv5O5W0OQIfKvUYZrGaAQ= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.62.0/go.mod h1:b3f7EifFRqkVt142USoGIP62uUeZm7ALCPrs1ZjWXYo= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0.62.0 h1:tRsXhJnn0w0TNwJpVrB94wsrimzjWKFzdQlUhRdNUzc= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0.62.0/go.mod h1:ifhe5teRNcbxg9p353DhOkOgczzL/IBLYFqT1cm1zpM= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.62.0 h1:aPMa5qZU9dp4fU34o+jQgVIPFIOi20oxYg8TLigmZLg= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.62.0/go.mod h1:sg6Wqbl0BKKZ5zKnQj2q0qic/3ziF894SCx1LpbX37Y= github.com/Masterminds/semver v1.5.0 h1:H65muMkzWKEuNDnfl9d70GUjFniHKHRbFPGBuZ3QEww= github.com/Masterminds/semver v1.5.0/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y= -github.com/alecthomas/assert/v2 v2.7.0 h1:QtqSACNS3tF7oasA8CU6A6sXZSBDqnm7RfpLl9bZqbE= -github.com/alecthomas/assert/v2 v2.7.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k= -github.com/alecthomas/chroma/v2 v2.14.0 h1:R3+wzpnUArGcQz7fCETQBzO5n9IMNi13iIs46aU4V9E= -github.com/alecthomas/chroma/v2 v2.14.0/go.mod h1:QolEbTfmUHIMVpBqxeDnNBj2uoeI4EbYP4i6n68SG4I= -github.com/alecthomas/repr v0.4.0 h1:GhI2A8MACjfegCPVq9f1FLvIBS+DrQ2KQBFZP1iFzXc= -github.com/alecthomas/repr v0.4.0/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4= -github.com/aws/aws-sdk-go-v2 v1.17.4/go.mod h1:uzbQtefpm44goOPmdKyAlXSNcwlRgF3ePWVW6EtJvvw= -github.com/aws/aws-sdk-go-v2 v1.17.5 h1:TzCUW1Nq4H8Xscph5M/skINUitxM5UBAyvm2s7XBzL4= -github.com/aws/aws-sdk-go-v2 v1.17.5/go.mod h1:uzbQtefpm44goOPmdKyAlXSNcwlRgF3ePWVW6EtJvvw= -github.com/aws/aws-sdk-go-v2/config v1.18.13 h1:v0xlYqbO6/EVlM8tUn2QEOA7btQxcgidEq2JRDBPTho= -github.com/aws/aws-sdk-go-v2/config v1.18.13/go.mod h1:r39wGSZB7wPDW1i54JyQXUpc5KsWjh5z/3S5D9eCqDg= -github.com/aws/aws-sdk-go-v2/credentials v1.13.13 h1:zw1KAc1kl00NYd3ofVmFrb09qnYlSQMeh+fmlQRAihI= -github.com/aws/aws-sdk-go-v2/credentials v1.13.13/go.mod h1:DW9nbIIF9MrIja0cBQrUpeWYQMSlNmP8fevLUyF9W38= -github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.12.22 h1:3aMfcTmoXtTZnaT86QlVaYh+BRMbvrrmZwIQ5jWqCZQ= -github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.12.22/go.mod h1:YGSIJyQ6D6FjKMQh16hVFSIUD54L4F7zTGePqYMYYJU= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.28/go.mod h1:3lwChorpIM/BhImY/hy+Z6jekmN92cXGPI1QJasVPYY= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.29 h1:9/aKwwus0TQxppPXFmf010DFrE+ssSbzroLVYINA+xE= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.29/go.mod h1:Dip3sIGv485+xerzVv24emnjX5Sg88utCL8fwGmCeWg= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.22/go.mod h1:EqK7gVrIGAHyZItrD1D8B0ilgwMD1GiWAmbU4u/JHNk= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.23 h1:b/Vn141DBuLVgXbhRWIrl9g+ww7G+ScV5SzniWR13jQ= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.23/go.mod h1:mr6c4cHC+S/MMkrjtSlG4QA36kOznDep+0fga5L/fGQ= -github.com/aws/aws-sdk-go-v2/internal/ini v1.3.29 h1:J4xhFd6zHhdF9jPP0FQJ6WknzBboGMBNjKOv4iTuw4A= -github.com/aws/aws-sdk-go-v2/internal/ini v1.3.29/go.mod h1:TwuqRBGzxjQJIwH16/fOZodwXt2Zxa9/cwJC5ke4j7s= -github.com/aws/aws-sdk-go-v2/service/ec2 v1.86.0 h1:4dt0Mg5veHbMLcA2JAR9LDxvqXjtG0ZLQdxZG/2wHy4= -github.com/aws/aws-sdk-go-v2/service/ec2 v1.86.0/go.mod h1:jK4MhMMe6HIe4qnjGaQqQQECcsxRZ0q86oCq06T8IEE= -github.com/aws/aws-sdk-go-v2/service/eks v1.27.3 h1:jlh0AJVhauqSGaiwRJx4j0LNBGEAaGn46sA1XJyTj0E= -github.com/aws/aws-sdk-go-v2/service/eks v1.27.3/go.mod h1:S30WtE6uWErcppqG9Rl03MATEFYsm0vnDyxPUKmmCqU= -github.com/aws/aws-sdk-go-v2/service/iam v1.19.3 h1:vaDXu/p/5RNK++B2pqKS3hwsWGxsVjJJqPaAMg0OkiM= -github.com/aws/aws-sdk-go-v2/service/iam v1.19.3/go.mod h1:F5Xt96+AfAiyMpRXHy9CKafE/KULVwj7MwgZ0a4row4= -github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.22 h1:LjFQf8hFuMO22HkV5VWGLBvmCLBCLPivUAmpdpnp4Vs= -github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.22/go.mod h1:xt0Au8yPIwYXf/GYPy/vl4K3CgwhfQMYbrH7DlUUIws= -github.com/aws/aws-sdk-go-v2/service/sso v1.12.2 h1:EN102fWY7hI5u/2FPheTrwwMHkSXfl49RYkeEnJsrCU= -github.com/aws/aws-sdk-go-v2/service/sso v1.12.2/go.mod h1:IgV8l3sj22nQDd5qcAGY0WenwCzCphqdbFOpfktZPrI= -github.com/aws/aws-sdk-go-v2/service/ssooidc v1.14.2 h1:f1lmlce7r13CX1BPyPqt9oh/H+uqOWc9367lDoGGwNQ= -github.com/aws/aws-sdk-go-v2/service/ssooidc v1.14.2/go.mod h1:O1YSOg3aekZibh2SngvCRRG+cRHKKlYgxf/JBF/Kr/k= -github.com/aws/aws-sdk-go-v2/service/sts v1.18.3 h1:s49mSnsBZEXjfGBkRfmK+nPqzT7Lt3+t2SmAKNyHblw= -github.com/aws/aws-sdk-go-v2/service/sts v1.18.3/go.mod h1:b+psTJn33Q4qGoDaM7ZiOVVG8uVjGI6HaZ8WBHdgDgU= -github.com/aws/smithy-go v1.13.5 h1:hgz0X/DX0dGqTYpGALqXJoRKRj5oQ7150i5FdTePzO8= -github.com/aws/smithy-go v1.13.5/go.mod h1:Tg+OJXh4MB2R/uN61Ko2f6hTZwB/ZYGOtib8J3gBHzA= +github.com/alecthomas/assert/v2 v2.11.0 h1:2Q9r3ki8+JYXvGsDyBXwH3LcJ+WK5D0gc5E8vS6K3D0= +github.com/alecthomas/assert/v2 v2.11.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k= +github.com/alecthomas/chroma/v2 v2.27.0 h1:FodwmyOBgJULFYmDqibcp9pvfDLWdtPRh9v/r5BXYZs= +github.com/alecthomas/chroma/v2 v2.27.0/go.mod h1:NjJ3ciIgrqBNeIkWZ4e46nseoLDslxU1LmfCoL+wcY8= +github.com/alecthomas/repr v0.5.2 h1:SU73FTI9D1P5UNtvseffFSGmdNci/O6RsqzeXJtP0Qs= +github.com/alecthomas/repr v0.5.2/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4= +github.com/aws/aws-sdk-go-v2 v1.47.5 h1:5yA+A+BiXbDq1ZLbYwPViwhEGDMdR0MEhL8Jh2LnLS4= +github.com/aws/aws-sdk-go-v2 v1.47.5/go.mod h1:iNIkogrRvFwm+1OQIUOP2lPBtlXZboOIUWiCa+pHEMw= +github.com/aws/aws-sdk-go-v2/config v1.33.12 h1:IV1YARaXahwCqUIyP8IlWsP85Lil+5ozTozDQXPumRk= +github.com/aws/aws-sdk-go-v2/config v1.33.12/go.mod h1:h51R06bzMVwNBRZOX5ylHhNDnkB/azZeq/LvxM6q2pQ= +github.com/aws/aws-sdk-go-v2/credentials v1.20.12 h1:6P7Q7yH/GIwHg6MLKv3ySsBqaCoE1z+C0OTzYMenhEY= +github.com/aws/aws-sdk-go-v2/credentials v1.20.12/go.mod h1:Kw/SaoW/wc7IqJErqXJIzKo8b7Aelxfbuc6XlbrRnsc= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.5 h1:iXjy2SFhGYNB1jWZBhQqq8HbhsbPF23w+/zbMvPXsTg= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.5/go.mod h1:k0RUiBnyXU0AXRJ9tJmY2jQke6XUIX2PNVnWtvgaPtc= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.8 h1:gzIWc3DTPfPbWKrQnmL6BV6WD7NPD1htxzgdk/bQ/Z4= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.8/go.mod h1:vvUA5cDAZWGo4R14FZPZfXfJCmgsafOWEq78Kg0D+ug= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.8 h1:PWv+vG8aCLS8qd+HPdYhK7Vees90aKHWFFQ1AGYD/8E= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.8/go.mod h1:xxPZEpflYHJA12366ZGyq66z9dHPCoeCIu99Jck+MPw= +github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.8 h1:WOp5De9iWdEHDPh2Kb0tBP3vGBm/dVAuRGh4a4tqduo= +github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.8/go.mod h1:z8W8YgfhbWl62XqcTtK+CxPrE+iHGRVUOtrrbIOp7ZY= +github.com/aws/aws-sdk-go-v2/service/ec2 v1.343.0 h1:pOxNUJbUOy779gx205gEpySpT5fu3B0ifPD8jBxujZI= +github.com/aws/aws-sdk-go-v2/service/ec2 v1.343.0/go.mod h1:khWfxrzSgMjGMAZIaYAHu3IobEo7KRRNwPYaHb1zpng= +github.com/aws/aws-sdk-go-v2/service/eks v1.105.1 h1:miTghTsT/Nztm4hcIlKVaEaCH1g0sWVHBVdGZ/SeaZg= +github.com/aws/aws-sdk-go-v2/service/eks v1.105.1/go.mod h1:KyMQFkvY0AL4C7ZmsggrCIBdFLaR0azUriRlMrLNarw= +github.com/aws/aws-sdk-go-v2/service/iam v1.64.6 h1:6tqE3gHbHFEvARPvlLHgRK1dXoD96ecolfPEurpYXyc= +github.com/aws/aws-sdk-go-v2/service/iam v1.64.6/go.mod h1:lV0r+RVSkXRA6WhiaxW55qn8n60ObMwQShxaqrs9UeY= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.23 h1:MCIR6iZaCKO4UE0hUvoWWLI6JVjppopV64JfAJaMjng= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.23/go.mod h1:pphWFS+z0MmIPivj8c/6bATd1Z+Av7Ust75DPdEFsPA= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.8 h1:+PMpWlJYOn2tm7sm6OZ/ZLd4jStl17T7wjNapd1Rczs= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.8/go.mod h1:cnG3xZLGQL4c/bt8pjdzlFtZsW7epBBuNS04a5xMjdo= +github.com/aws/aws-sdk-go-v2/service/signin v1.12.0 h1:3vu/eUqh0rjh7Zy4N4YKcpZX4Aud+zinB3VsLhhlQFw= +github.com/aws/aws-sdk-go-v2/service/signin v1.12.0/go.mod h1:wxAk0D2oVBSjuXEIzvcKxTZfM90zticdAbh/VD42L0Y= +github.com/aws/aws-sdk-go-v2/service/sso v1.39.0 h1:kIEpD5dUry7VET3Ybl7zj7PPHRB4lb52G9iTz+a1Tqk= +github.com/aws/aws-sdk-go-v2/service/sso v1.39.0/go.mod h1:UGsEYgWz4Gi+46vDQ5zkFLqUgJziyOE2SXjZjgmfmHc= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.0 h1:WfFev+HgTodggcNon5HieiLxxwWwb8Br8R2+nDkixvk= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.0/go.mod h1:gJSdIY6YUzDvqQLcMtPVZgBRHrFwzHryvpE8Igzbxps= +github.com/aws/aws-sdk-go-v2/service/sts v1.51.6 h1:BVjKrtRUtSYKztBCCfE1oAB+d3ViKcW2cKZfserOqMQ= +github.com/aws/aws-sdk-go-v2/service/sts v1.51.6/go.mod h1:eSukFLeLkPMm+1OxDR+F0joauZdyBkF47Ow7MqjZiJw= +github.com/aws/smithy-go v1.28.7 h1:h/n1SHrwVtaDYLz8mR1/Kq4Xh4RaFbFW7bOYckg9mfE= +github.com/aws/smithy-go v1.28.7/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc= github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k= github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8= github.com/aymanbagabas/go-udiff v0.2.0 h1:TK0fH4MteXUDspT88n8CKzvK0X9O2xu9yQjWpi6yML8= github.com/aymanbagabas/go-udiff v0.2.0/go.mod h1:RE4Ex0qsGkTAJoQdQQCA0uG+nAzJO/pI/QwceO5fgrA= github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk= github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4= -github.com/benbjohnson/clock v1.3.5 h1:VvXlSJBzZpA/zum6Sj74hxwYI2DIxRWuNIoXAzHZz5o= -github.com/benbjohnson/clock v1.3.5/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= -github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc h1:4pZI35227imm7yK2bGPcfpFEmuY1gc2YSTShr4iJBfs= -github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc/go.mod h1:X4/0JoqgTIPSFcRA/P6INZzIuyqdFY5rm8tb41s9okk= -github.com/charmbracelet/glamour v0.10.0 h1:MtZvfwsYCx8jEPFJm3rIBFIMZUfUJ765oX8V6kXldcY= -github.com/charmbracelet/glamour v0.10.0/go.mod h1:f+uf+I/ChNmqo087elLnVdCiVgjSKWuXa/l6NU2ndYk= +github.com/charmbracelet/colorprofile v0.4.3 h1:QPa1IWkYI+AOB+fE+mg/5/4HRMZcaXex9t5KX76i20Q= +github.com/charmbracelet/colorprofile v0.4.3/go.mod h1:/zT4BhpD5aGFpqQQqw7a+VtHCzu+zrQtt1zhMt9mR4Q= +github.com/charmbracelet/glamour v1.0.0 h1:AWMLOVFHTsysl4WV8T8QgkQ0s/ZNZo7CiE4WKhk8l08= +github.com/charmbracelet/glamour v1.0.0/go.mod h1:DSdohgOBkMr2ZQNhw4LZxSGpx3SvpeujNoXrQyH2hxo= github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834 h1:ZR7e0ro+SZZiIZD7msJyA+NjkCNNavuiPBLgerbOziE= github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834/go.mod h1:aKC/t2arECF6rNOnaKaVU6y4t4ZeHQzqfxedE/VkVhA= -github.com/charmbracelet/x/ansi v0.8.0 h1:9GTq3xq9caJW8ZrBTe0LIe2fvfLR/bYXKTx2llXn7xE= -github.com/charmbracelet/x/ansi v0.8.0/go.mod h1:wdYl/ONOLHLIVmQaxbIYEC/cRKOQyjTkowiI4blgS9Q= -github.com/charmbracelet/x/cellbuf v0.0.13 h1:/KBBKHuVRbq1lYx5BzEHBAFBP8VcQzJejZ/IA3iR28k= -github.com/charmbracelet/x/cellbuf v0.0.13/go.mod h1:xe0nKWGd3eJgtqZRaN9RjMtK7xUYchjzPr7q6kcvCCs= +github.com/charmbracelet/x/ansi v0.11.9 h1:kIrqLBxtTVbLyyHO2Evoi93EjQo1mylWmpNEsfPxXAM= +github.com/charmbracelet/x/ansi v0.11.9/go.mod h1:DG/hpOnaI2QJ/KMMqLL2h0KVhluuJLazf8973P+Vy5w= +github.com/charmbracelet/x/cellbuf v0.0.15 h1:ur3pZy0o6z/R7EylET877CBxaiE1Sp1GMxoFPAIztPI= +github.com/charmbracelet/x/cellbuf v0.0.15/go.mod h1:J1YVbR7MUuEGIFPCaaZ96KDl5NoS0DAWkskup+mOY+Q= github.com/charmbracelet/x/exp/golden v0.0.0-20240806155701-69247e0abc2a h1:G99klV19u0QnhiizODirwVksQB91TJKV/UaTnACcG30= github.com/charmbracelet/x/exp/golden v0.0.0-20240806155701-69247e0abc2a/go.mod h1:wDlXFlCrmJ8J+swcL/MnGUuYnqgQdW9rhSD61oNMb6U= -github.com/charmbracelet/x/exp/slice v0.0.0-20250327172914-2fdc97757edf h1:rLG0Yb6MQSDKdB52aGX55JT1oi0P0Kuaj7wi1bLUpnI= -github.com/charmbracelet/x/exp/slice v0.0.0-20250327172914-2fdc97757edf/go.mod h1:B3UgsnsBZS/eX42BlaNiJkD1pPOUa+oF1IYC6Yd2CEU= -github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ= -github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg= -github.com/clipperhouse/uax29/v2 v2.2.0 h1:ChwIKnQN3kcZteTXMgb1wztSgaU+ZemkgWdohwgs8tY= -github.com/clipperhouse/uax29/v2 v2.2.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM= +github.com/charmbracelet/x/exp/slice v0.1.0 h1:m46dwuDf3M5SFYMRhxYkLC6z9WnENGVKbcbJlp13/og= +github.com/charmbracelet/x/exp/slice v0.1.0/go.mod h1:vqEfX6xzqW1pKKZUUiFOKg0OQ7bCh54Q2vR/tserrRA= +github.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk= +github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI= +github.com/clipperhouse/displaywidth v0.11.0 h1:lBc6kY44VFw+TDx4I8opi/EtL9m20WSEFgwIwO+UVM8= +github.com/clipperhouse/displaywidth v0.11.0/go.mod h1:bkrFNkf81G8HyVqmKGxsPufD3JhNl3dSqnGhOoSD/o0= +github.com/clipperhouse/uax29/v2 v2.7.0 h1:+gs4oBZ2gPfVrKPthwbMzWZDaAFPGYK72F0NJv2v7Vk= +github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM= github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2 h1:aBangftG7EVZoUb69Os8IaYg++6uMOdKK83QtkkvJik= github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2/go.mod h1:qwXFYgsP6T7XnJtbKlf1HP8AjxZZyzxMmc+Lq5GjlU4= -github.com/cockroachdb/errors v1.12.0 h1:d7oCs6vuIMUQRVbi6jWWWEJZahLCfJpnJSVobd1/sUo= -github.com/cockroachdb/errors v1.12.0/go.mod h1:SvzfYNNBshAVbZ8wzNc/UPK3w1vf0dKDUP41ucAIf7g= -github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b h1:r6VH0faHjZeQy818SGhaone5OnYfxFR/+AzdY3sf5aE= -github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= -github.com/cockroachdb/redact v1.1.6 h1:zXJBwDZ84xJNlHl1rMyCojqyIxv+7YUpQiJLQ7n4314= -github.com/cockroachdb/redact v1.1.6/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= -github.com/creack/goselect v0.1.2 h1:2DNy14+JPjRBgPzAd1thbQp4BSIihxcBf0IXhQXDRa0= -github.com/creack/goselect v0.1.2/go.mod h1:a/NhLweNvqIYMuxcMOuWY516Cimucms3DglDzQP3hKY= +github.com/cockroachdb/errors v1.14.0 h1:EfdVEJpN3z8rPMo43Yit59LxoiIa470fSXpZXuEs+ZI= +github.com/cockroachdb/errors v1.14.0/go.mod h1:xRa70jZ9sNBQmISt5KmJmAD++E4dQHm89oCRiZGEdq0= +github.com/cockroachdb/logtags v0.0.0-20241215232642-bb51bb14a506 h1:ASDL+UJcILMqgNeV5jiqR4j+sTuvQNHdf2chuKj1M5k= +github.com/cockroachdb/logtags v0.0.0-20241215232642-bb51bb14a506/go.mod h1:Mw7HqKr2kdtu6aYGn3tPmAftiP3QPX63LdK/zcariIo= +github.com/cockroachdb/redact v1.1.8 h1:8eVLLj6juKxiKrAEw2b8cJvNqWq++U8WOfQFuL7KTaA= +github.com/cockroachdb/redact v1.1.8/go.mod h1:GceHHpJ0rMDpYARL5In88Alq/xMBUtVlz7Qxix6ZVkw= +github.com/creack/goselect v0.1.3 h1:MaGNMclRo7P2Jl21hBpR1Cn33ITSbKP6E49RtfblLKc= +github.com/creack/goselect v0.1.3/go.mod h1:a/NhLweNvqIYMuxcMOuWY516Cimucms3DglDzQP3hKY= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s= github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE= -github.com/danieljoos/wincred v1.2.2 h1:774zMFJrqaeYCK2W57BgAem/MLi6mtSE47MB6BOJ0i0= -github.com/danieljoos/wincred v1.2.2/go.mod h1:w7w4Utbrz8lqeMbDAK0lkNJUv5sAOkFi7nd/ogr0Uh8= +github.com/danieljoos/wincred v1.2.3 h1:v7dZC2x32Ut3nEfRH+vhoZGvN72+dQ/snVXo/vMFLdQ= +github.com/danieljoos/wincred v1.2.3/go.mod h1:6qqX0WNrS4RzPZ1tnroDzq9kY3fu1KwE7MRLQK4X0bs= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/derision-test/glock v1.0.0 h1:b6sViZG+Cm6QtdpqbfWEjaBVbzNPntIS4GzsxpS+CmM= -github.com/derision-test/glock v1.0.0/go.mod h1:jKtLdBMrF+XQatqvg46wiWdDfDSSDjdhO4dOM2FX9H4= +github.com/derision-test/glock v1.1.4 h1:3y1kwncYT0JRgPZ6NhMSsmJLQqjnKE3ZKj2CTtauEEg= +github.com/derision-test/glock v1.1.4/go.mod h1:b64lRouYlknys/hp3/+m9FcbNZWG3K2j7OgJawsY4VA= github.com/dineshappavoo/basex v0.0.0-20170425072625-481a6f6dc663 h1:fctNkSsavbXpt8geFWZb8n+noCqS8MrOXRJ/YfdZ2dQ= github.com/dineshappavoo/basex v0.0.0-20170425072625-481a6f6dc663/go.mod h1:Kad2hux31v/IyD4Rf4wAwIyK48995rs3qAl9IUAhc2k= -github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI= -github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= -github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= -github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= -github.com/emicklei/go-restful/v3 v3.11.0 h1:rAQeMHw1c7zTmncogyy8VvRZwtkmkZ4FxERmMY4rD+g= -github.com/emicklei/go-restful/v3 v3.11.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= +github.com/dlclark/regexp2/v2 v2.12.0 h1:GsCgDZZeHluUDHASr2yqQonZk4Tma5LFmLH9CSsFFEE= +github.com/dlclark/regexp2/v2 v2.12.0/go.mod h1:avUrQvPaLz2DrFNHJF0taWAFFX2C1GMSSoeiqFjcBmU= +github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg= +github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI= +github.com/emicklei/go-restful/v3 v3.13.0 h1:C4Bl2xDndpU6nJ4bc1jXd+uTmYPVUwkD6bFY/oTyCes= +github.com/emicklei/go-restful/v3 v3.13.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= github.com/envoyproxy/go-control-plane v0.14.0 h1:hbG2kr4RuFj222B6+7T83thSPqLjwBIfQawTkC++2HA= github.com/envoyproxy/go-control-plane v0.14.0/go.mod h1:NcS5X47pLl/hfqxU70yPwL9ZMkUlwlKxtAohpi2wBEU= -github.com/envoyproxy/go-control-plane/envoy v1.37.0 h1:u3riX6BoYRfF4Dr7dwSOroNfdSbEPe9Yyl09/B6wBrQ= -github.com/envoyproxy/go-control-plane/envoy v1.37.0/go.mod h1:DReE9MMrmecPy+YvQOAOHNYMALuowAnbjjEMkkWOi6A= +github.com/envoyproxy/go-control-plane/envoy v1.40.0 h1:G4dcl8KE/HVPnZ25BBdvGZWi8JjyeBfQSvm95U5P1Qc= +github.com/envoyproxy/go-control-plane/envoy v1.40.0/go.mod h1:UZVGjwWu2QV8PkGSlXmqWiSgqCGZe16TgIu4jDl3T5w= github.com/envoyproxy/go-control-plane/ratelimit v0.1.0 h1:/G9QYbddjL25KvtKTv3an9lx6VBE2cnb8wp1vEGNYGI= github.com/envoyproxy/go-control-plane/ratelimit v0.1.0/go.mod h1:Wk+tMFAFbCXaJPzVVHnPgRKdUdwW/KdbRt94AzgRee4= github.com/envoyproxy/protoc-gen-validate v1.3.3 h1:MVQghNeW+LZcmXe7SY1V36Z+WFMDjpqGAGacLe2T0ds= github.com/envoyproxy/protoc-gen-validate v1.3.3/go.mod h1:TsndJ/ngyIdQRhMcVVGDDHINPLWB7C82oDArY51KfB0= github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= -github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM= -github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU= -github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= -github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= +github.com/fatih/color v1.19.0 h1:Zp3PiM21/9Ld6FzSKyL5c/BULoe/ONr9KlbYVOfG8+w= +github.com/fatih/color v1.19.0/go.mod h1:zNk67I0ZUT1bEGsSGyCZYZNrHuTkJJB+r6Q9VuMi0LE= +github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc= +github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE= github.com/frankban/quicktest v1.14.3/go.mod h1:mgiwOwqx65TmIk1wJ6Q7wvnVMocbUorkibMOrVTHZps= -github.com/frankban/quicktest v1.14.4 h1:g2rn0vABPOOXmZUj+vbmUp0lPoXEMuhTpIluN0XL9UY= -github.com/frankban/quicktest v1.14.4/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= -github.com/fxamacker/cbor/v2 v2.7.0 h1:iM5WgngdRBanHcxugY4JySA0nk1wZorNOpTgCMedv5E= -github.com/fxamacker/cbor/v2 v2.7.0/go.mod h1:pxXPTn3joSm21Gbwsv0w9OSA2y1HFR9qXEeXQVeNoDQ= -github.com/getsentry/sentry-go v0.27.0 h1:Pv98CIbtB3LkMWmXi4Joa5OOcwbmnX88sF5qbK3r3Ps= -github.com/getsentry/sentry-go v0.27.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= +github.com/fxamacker/cbor/v2 v2.10.0 h1:HVF3T5vYwLqO81ebPirWEPNv2SMrUMD3HLnKgEr6uWE= +github.com/fxamacker/cbor/v2 v2.10.0/go.mod h1:uSwlToFuT9BZAKRxxVm3qQC8DR4tlWl7D6pf20iRYH4= +github.com/getsentry/sentry-go v0.50.0 h1:gkO59rn/i0RCAXUUTflC5QVbTQGPXbaFabs2olVzc9g= +github.com/getsentry/sentry-go v0.50.0/go.mod h1:+xsDuN+SoRN/xfs1hdq78wnrE3omIZf+FCuh9FOW1C8= github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA= github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og= github.com/go-jose/go-jose/v4 v4.1.6 h1:sNRkftxFJxwsILiQukqp5z83QBSmntVwmgRY7AqBDO4= @@ -159,27 +154,54 @@ github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8= github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= -github.com/go-openapi/jsonpointer v0.19.6/go.mod h1:osyAmYz/mB/C3I+WsTTSgw1ONzaLJoLCyoi6/zppojs= -github.com/go-openapi/jsonpointer v0.21.0 h1:YgdVicSA9vH5RiHs9TZW5oyafXZFc6+2Vc1rr/O9oNQ= -github.com/go-openapi/jsonpointer v0.21.0/go.mod h1:IUyH9l/+uyhIYQ/PXVA41Rexl+kOkAPDdXEYns6fzUY= -github.com/go-openapi/jsonreference v0.20.2 h1:3sVjiK66+uXK/6oQ8xgcRKcFgQ5KXa2KvnJRumpMGbE= -github.com/go-openapi/jsonreference v0.20.2/go.mod h1:Bl1zwGIM8/wsvqjsOQLJ/SH+En5Ap4rVB5KVcIDZG2k= -github.com/go-openapi/swag v0.22.3/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14= -github.com/go-openapi/swag v0.23.0 h1:vsEVJDUo2hPJ2tu0/Xc+4noaxyEffXNIs3cOULZ+GrE= -github.com/go-openapi/swag v0.23.0/go.mod h1:esZ8ITTYEsH1V2trKHjAN8Ai7xHb8RV+YSZ577vPjgQ= -github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI= -github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= +github.com/go-openapi/jsonpointer v1.0.2 h1:NbW7xT2b+l7x+JefiPGDsZWsrLk1ogrz4AHK1TTzMt8= +github.com/go-openapi/jsonpointer v1.0.2/go.mod h1:N0rI4MbNKD7xAFTiHtB+5Nhrg2j/wwYg7m7Fmb4/jk8= +github.com/go-openapi/jsonreference v1.0.3 h1:5rDbq+JsjCv6/nUDDJt83nLZoADI4w03uvHXer+4aYQ= +github.com/go-openapi/jsonreference v1.0.3/go.mod h1:OJSlMXHysgH272D9z2tiy2MGe5A9vQLHaCPb6KbYdE4= +github.com/go-openapi/swag v0.27.1 h1:VotvOLWW8q/EAxB0YdsBBGC8XYyeL1YwBj2ungAGPNg= +github.com/go-openapi/swag v0.27.1/go.mod h1:GTkJPwHfhJp6MWr4/rCh64HVI3Ofu+tcsbfjfHmTxpE= +github.com/go-openapi/swag/cmdutils v0.27.1 h1:I7sYqaWVl5mq0NEmNQkAmFDyNin9ufvMX/p2zwtQaOE= +github.com/go-openapi/swag/cmdutils v0.27.1/go.mod h1:Sm1MVFMkF6guJJ+pQqHnQA3N0j9qALV3NxzDSv6bETM= +github.com/go-openapi/swag/conv v0.29.2 h1:8c9shoB8l0QRSR6ymq1llHdBWDqpIgJfjTGHx3Vuhm0= +github.com/go-openapi/swag/conv v0.29.2/go.mod h1:AZS0YigTNf8qNtD6WqJz/N4RUNmpr76SyjFGkq4+p6Q= +github.com/go-openapi/swag/fileutils v0.27.1 h1:QQqBSoi5mW4XpU85nS0mLcA+zAE6vLzrb0QkmLKf9oM= +github.com/go-openapi/swag/fileutils v0.27.1/go.mod h1:VvJFZLTZS0AI854gEQz5tk7dBESdLjiNUMSZ/th2ry8= +github.com/go-openapi/swag/jsonutils v0.29.2 h1:uZNSD2/rJDYAfvsLYkykTzXuyxM3QpDKV9jhRHrMu6k= +github.com/go-openapi/swag/jsonutils v0.29.2/go.mod h1:ONTdNvj3Y+IXRzfa17E+Rgt2ns/qiSOYjIo2K7v2yDs= +github.com/go-openapi/swag/jsonutils/fixtures_test v0.29.2 h1:w+Fd6EBOMGlC74GYGHqCLGyb3Bpams8TtNrgM/SG4jo= +github.com/go-openapi/swag/jsonutils/fixtures_test v0.29.2/go.mod h1:HC2egPORFzbj/gf05Zrfgz8Mgplx3oW7hgGi7pjZVhM= +github.com/go-openapi/swag/loading v0.27.1 h1:/DxUgDXKbBX4bcn7r9uEXfJyzN5XpiJmZplzQTjrRCY= +github.com/go-openapi/swag/loading v0.27.1/go.mod h1:jvGh3iA2+zyUUycB5fgJWzeHnhrpvGnJJM0RVE9ZShE= +github.com/go-openapi/swag/mangling v0.27.1 h1:yC9D0HyUE8gbP+BfmGx9+AA89ikwZTMjESK3OnnoaqA= +github.com/go-openapi/swag/mangling v0.27.1/go.mod h1:jtBE2+V+3pILxOR7Vgce+Cwp6A2PgZbvVqfNntbVs0w= +github.com/go-openapi/swag/netutils v0.27.1 h1:mICMFoS82F5TZ4Zy3cqmcQk+BFeCp3Uyq3Np7GI0/qU= +github.com/go-openapi/swag/netutils v0.27.1/go.mod h1:J+WYyFMLtvtCGqa6jLv+YNUmIKI3ZRQRrvfNDMoQoEQ= +github.com/go-openapi/swag/pools v0.29.2 h1:PlGoDRF8WtSyXkedZZkpW3f9wDhFf3u8KtaBcmgmh8c= +github.com/go-openapi/swag/pools v0.29.2/go.mod h1:V3lhxVT4qDYRqc2MRSSbLsTYIYV/2HlHafhyEkmzLIc= +github.com/go-openapi/swag/stringutils v0.27.1 h1:ZXePZ0r2p1qSjo8tD3Un4vFj8+FqlCkczxDrJIhYUp8= +github.com/go-openapi/swag/stringutils v0.27.1/go.mod h1:lzRN95CxXmA03XcDWHLOb6nOMcxCqR5rGY0lOgsfRoM= +github.com/go-openapi/swag/typeutils v0.29.2 h1:O7aVvkTs3pXwikgtrPLenigEMdQFgONKRooQA9pgf2I= +github.com/go-openapi/swag/typeutils v0.29.2/go.mod h1:7+GDG+uz9Ke+eVt4rClZg7wklSDp8hT/mKNh/pC26TE= +github.com/go-openapi/swag/yamlutils v0.27.1 h1:ftxv6xvXb1E3zohUc+okZ9nSqNb9StQX/FXnKZ98sQA= +github.com/go-openapi/swag/yamlutils v0.27.1/go.mod h1:bnxFIB1qewGRiZHypXGZ3fNgf13/0HfRgnS/iZBDrOo= +github.com/go-openapi/testify/enable/yaml/v2 v2.7.0 h1:wPW6YRgx3+SID1yUy/Xwa17L8kFEaEKod2VRbJDZNUs= +github.com/go-openapi/testify/enable/yaml/v2 v2.7.0/go.mod h1:mI1M88etYbc3PhgHsWQK2kwvNwW5aGFqMPbmib+SGIs= +github.com/go-openapi/testify/v2 v2.8.0 h1:19QDx5b57p8KjO2E4sgs/woL4Akp+FGLRlVm2xn0Rho= +github.com/go-openapi/testify/v2 v2.8.0/go.mod h1:4gUN8jC+RqOE2qjW/vDmfyTvl5BCht4qL7oca0odrak= +github.com/go-quicktest/qt v1.102.0 h1:HSQxCeh5YZH3EL3W39ixjtyaEhcWSXQHtHnMBzSs474= +github.com/go-quicktest/qt v1.102.0/go.mod h1:p4lGIVX+8Wa6ZPNDvqcxq36XpUDLh42FLetFU7odllI= github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y= github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8= -github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk= -github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= +github.com/goccy/go-json v0.12.0 h1:pD+oWouAiz4yruwXIt/iT+lOMeyhr1aTtxzaMP/RgVI= +github.com/goccy/go-json v0.12.0/go.mod h1:3NdmfEkZlB7YI5UFw/qdFKq8XN1aiWR0YyRPWZNQltY= +github.com/godbus/dbus/v5 v5.2.4 h1:F2gUCy++NMIxGmo9J+z5le/+ZC8W1OgeR51P4i9ZB/U= +github.com/godbus/dbus/v5 v5.2.4/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c= github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= -github.com/google/gnostic-models v0.6.9 h1:MU/8wDLif2qCXZmzncUQ/BOfxWfthHi63KqpoNbWqVw= -github.com/google/gnostic-models v0.6.9/go.mod h1:CiWsm0s6BSQd1hRn8/QmxqB6BesYcbSZxsz9b0KuDBw= -github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/gnostic-models v0.7.1 h1:SisTfuFKJSKM5CPZkffwi6coztzzeYUhc3v4yxLWH8c= +github.com/google/gnostic-models v0.7.1/go.mod h1:whL5G0m6dmc5cPxKc5bdKdEN3UjI7OUGxBlw57miDrQ= github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE= github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= @@ -191,21 +213,17 @@ github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/martian/v3 v3.3.3 h1:DIhPTQrbPkgs2yJYdXU/eNACCG5DVQjySNRNlflZ9Fc= github.com/google/martian/v3 v3.3.3/go.mod h1:iEPrYcgCF7jA9OtScMFQyAlZZ4YXTKEtJ1E6RWzmBA0= -github.com/google/pprof v0.0.0-20241029153458-d1b30febd7db h1:097atOisP2aRj7vFgYQBbFN4U4JNXUNYpxael3UzMyo= -github.com/google/pprof v0.0.0-20241029153458-d1b30febd7db/go.mod h1:vavhavw2zAxS5dIdcRluK6cSGGPlZynqzFM8NdvU144= -github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0= -github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM= -github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaUGG7oYTSPP8MxqL4YI3kZKwcP4= -github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ= +github.com/google/s2a-go v0.1.11 h1:7v1V1TraNGP63WptsAkNqr2w8jgm4vM6A6qx6Lsw9iM= +github.com/google/s2a-go v0.1.11/go.mod h1:pz4tyvwXvJLLbyrkh6FW1eS2zPUXMaTmyNhYtyP2tNw= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/googleapis/enterprise-certificate-proxy v0.3.11 h1:vAe81Msw+8tKUxi2Dqh/NZMz7475yUvmRIkXr4oN2ao= -github.com/googleapis/enterprise-certificate-proxy v0.3.11/go.mod h1:RFV7MUdlb7AgEq2v7FmMCfeSMCllAzWxFgRdusoGks8= -github.com/googleapis/gax-go/v2 v2.17.0 h1:RksgfBpxqff0EZkDWYuz9q/uWsTVz+kf43LsZ1J6SMc= -github.com/googleapis/gax-go/v2 v2.17.0/go.mod h1:mzaqghpQp4JDh3HvADwrat+6M3MOIDp5YKHhb9PAgDY= +github.com/googleapis/enterprise-certificate-proxy v0.3.24 h1:G9iCJIY+AYVmUskKdjX8FVy7sG+nbzjOQ41cvlmhcvg= +github.com/googleapis/enterprise-certificate-proxy v0.3.24/go.mod h1:hEjCmnoakQzv5ImLUp6alkY7XgLlNoAxwTXmhHHNIsI= +github.com/googleapis/gax-go/v2 v2.27.0 h1:qe2iQOUzxb3fd6x6ewpIEixPQhJ+0Ihc/RRZhKA/2g0= +github.com/googleapis/gax-go/v2 v2.27.0/go.mod h1:RofiqDw3ehcG4L0H1zO3D2Itpwd3/uS/7wdmbNDF1DE= github.com/gorilla/css v1.0.1 h1:ntNaBIghp6JmvWnxbZKANoLyuXTPZ4cAMlo6RyhlbO8= github.com/gorilla/css v1.0.1/go.mod h1:BvnYkspnSzMmwRK+b8/xgNPLiIuNZr6vbZBTPQ2A3b0= -github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 h1:JeSE6pjso5THxAzdVpqr6/geYxZytqFMBCOtn/ujyeo= github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674/go.mod h1:r4w70xmWCQKmi1ONH4KIaBptdivuRPyosB9RmPlGEwA= github.com/grafana/regexp v0.0.0-20250905093917-f7b3be9d1853 h1:cLN4IBkmkYZNnk7EAJ0BHIethd+J6LqxFNw5mSiI2bM= @@ -213,45 +231,38 @@ github.com/grafana/regexp v0.0.0-20250905093917-f7b3be9d1853/go.mod h1:+JKpmjMGh github.com/hexops/autogold v0.8.1/go.mod h1:97HLDXyG23akzAoRYJh/2OBs3kd80eHyKPvZw0S5ZBY= github.com/hexops/autogold v1.3.1 h1:YgxF9OHWbEIUjhDbpnLhgVsjUDsiHDTyDfy2lrfdlzo= github.com/hexops/autogold v1.3.1/go.mod h1:sQO+mQUCVfxOKPht+ipDSkJ2SCJ7BNJVHZexsXqWMx4= -github.com/hexops/autogold/v2 v2.0.3 h1:zyrfTlNfyxLpX/zuk8wjTeTYP5AXaFeeRYFEZfHPwao= -github.com/hexops/autogold/v2 v2.0.3/go.mod h1:cYVc0tJn6v9Uf9xMOHvmH6scuTxsVJSxGcKR/yOVPzY= +github.com/hexops/autogold/v2 v2.3.1 h1:GcDwp9TkPkDG/wVodudePKPG8HbvEA8o8Z9hySIuAC4= +github.com/hexops/autogold/v2 v2.3.1/go.mod h1:1vQ1sj0yXQNn8VOlQeefQPXTLr9Qy9cf8pMDanZ4Gmo= github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM= github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg= github.com/hexops/valast v1.4.3/go.mod h1:Iqx2kLj3Jn47wuXpj3wX40xn6F93QNFBHuiKBerkTGA= -github.com/hexops/valast v1.4.4 h1:rETyycw+/L2ZVJHHNxEBgh8KUn+87WugH9MxcEv9PGs= -github.com/hexops/valast v1.4.4/go.mod h1:Jcy1pNH7LNraVaAZDLyv21hHg2WBv9Nf9FL6fGxU7o4= +github.com/hexops/valast v1.5.0 h1:FBTuvVi0wjTngtXJRZXMbkN/Dn6DgsUsBwch2DUJU8Y= +github.com/hexops/valast v1.5.0/go.mod h1:Jcy1pNH7LNraVaAZDLyv21hHg2WBv9Nf9FL6fGxU7o4= github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI= github.com/iancoleman/strcase v0.3.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= -github.com/jackc/pgx/v5 v5.9.2 h1:3ZhOzMWnR4yJ+RW1XImIPsD1aNSz4T4fyP7zlQb56hw= -github.com/jackc/pgx/v5 v5.9.2/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= +github.com/jackc/pgx/v5 v5.11.0 h1:IzBBtyK9AHqf98cctWFifYSci2hgQR/cd56wB4p+ogg= +github.com/jackc/pgx/v5 v5.11.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= -github.com/jedib0t/go-pretty/v6 v6.6.3 h1:nGqgS0tgIO1Hto47HSaaK4ac/I/Bu7usmdD3qvs0WvM= -github.com/jedib0t/go-pretty/v6 v6.6.3/go.mod h1:zbn98qrYlh95FIhwwsbIip0LYpwSG8SUOScs+v9/t0E= +github.com/jedib0t/go-pretty/v6 v6.8.3 h1:yVSk5aemoYHCvcrtqyXklwqcgHQIQzmy/oUzFlmffSQ= +github.com/jedib0t/go-pretty/v6 v6.8.3/go.mod h1:YwC5CE4fJ1HFUDeivSV1r//AmANFHyqczZk+U6BDALU= github.com/jig/teereadcloser v0.0.0-20181016160506-953720c48e05 h1:dSwwtWuwMyarzsbVWOq4QJ8xVy9wgcNomvWyGtrKe+E= github.com/jig/teereadcloser v0.0.0-20181016160506-953720c48e05/go.mod h1:sRUFlj+HCejvoCRpuhU0EYnNw5FG+YJpz8UFfCf0F2U= -github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg= -github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= -github.com/jmespath/go-jmespath/internal/testify v1.5.1 h1:shLQSRRSCCPj3f2gpwzGwWFoC7ycTf1rcQZHOlsJ6N8= -github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= -github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= -github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 h1:Z9n2FFNUXsshfwJMBgNA0RU6/i7WVaAegv3PtuIHPMs= github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51/go.mod h1:CzGEWj7cYgsdH8dAjBGEr58BoE7ScuLd+fwFZ44+/x8= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= -github.com/klauspost/compress v1.18.7 h1:aUyZsS4kH3QTKurYhAOwAHxllVPnOthb3vPfnF1Ehjw= -github.com/klauspost/compress v1.18.7/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= -github.com/klauspost/pgzip v1.2.6 h1:8RXeL5crjEUFnR2/Sn6GJNWtSQ3Dk8pq4CL3jvdDyjU= -github.com/klauspost/pgzip v1.2.6/go.mod h1:Ch1tH69qFZu15pkjo5kYi6mth2Zzwzt50oCQKQE9RUs= +github.com/klauspost/compress v1.20.3 h1:zWNoFqq/lSuYQRim3dUXlXeA0IqwuZGicdG5ZTfY5j4= +github.com/klauspost/compress v1.20.3/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= +github.com/klauspost/pgzip v1.3.0 h1:8t+KjjzD/0n/8vNlJGGZmTeK4njuwffOQvJm8tOSc8o= +github.com/klauspost/pgzip v1.3.0/go.mod h1:Xx7tAv5DH8ObLHUDQKXoE/nd8i/FYdNDTVMvi3SLTKI= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= -github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= @@ -259,23 +270,20 @@ github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= -github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= -github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= -github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= -github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= +github.com/lucasb-eyer/go-colorful v1.4.1 h1:1EO+WB73+EH8EVbzlrG3KLAfEypQWVHIBqlTf+2hNss= +github.com/lucasb-eyer/go-colorful v1.4.1/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= -github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE= -github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= +github.com/mattn/go-colorable v0.1.16 h1:+2YjeAe7xP1OQbZW1jERPWWCDLlNqFNCvjiqGiAt84A= +github.com/mattn/go-colorable v0.1.16/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= -github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= -github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= -github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= +github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI= +github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk= -github.com/mattn/go-runewidth v0.0.19 h1:v++JhqYnZuu5jSKrk9RbgF5v4CGUjqRfBm05byFGLdw= -github.com/mattn/go-runewidth v0.0.19/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs= +github.com/mattn/go-runewidth v0.0.31 h1:1oCV4ReTlosDBc6rYRw5cL8S/4y8iv5oRl4SJ5IBgwo= +github.com/mattn/go-runewidth v0.0.31/go.mod h1:3qAiGCV4Koz/yuveO58qUefmUTRm8r0IGEXZ9jeHp/8= github.com/microcosm-cc/bluemonday v1.0.27 h1:MpEUotklkwCSLeH+Qdx1VJgNqLlpY2KXwXFM08ygZfk= github.com/microcosm-cc/bluemonday v1.0.27/go.mod h1:jFi9vgW+H7c3V0lb6nR74Ib/DIB5OBs92Dimizgw2cA= github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ= @@ -283,8 +291,9 @@ github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFL github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8= +github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/muesli/reflow v0.3.0 h1:IFsN6K9NfGtjeggFP+68I4chLZV2yIKsXJFNZ+eWh6s= github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKtnHY/8= github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc= @@ -295,18 +304,21 @@ github.com/neelance/parallel v0.0.0-20160708114440-4de9ce63d14c h1:NZOii9TDGRAfC github.com/neelance/parallel v0.0.0-20160708114440-4de9ce63d14c/go.mod h1:eTBvSIlRgLo+CNFFQRQTwUGTZOEdvXIKeZS/xG+D2yU= github.com/nightlyone/lockfile v1.0.0 h1:RHep2cFKK4PonZJDdEl4GmkabuhbsRMgk/k3uAmxBiA= github.com/nightlyone/lockfile v1.0.0/go.mod h1:rywoIealpdNse2r832aiD9jRk8ErCatROs6LzC841CI= -github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec= -github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY= -github.com/onsi/ginkgo/v2 v2.21.0 h1:7rg/4f3rB88pb5obDgNZrNHrQ4e6WpjonchcpuBRnZM= -github.com/onsi/ginkgo/v2 v2.21.0/go.mod h1:7Du3c42kxCUegi0IImZ1wUQzMBVecgIHjR1C+NkhLQo= -github.com/onsi/gomega v1.35.1 h1:Cwbd75ZBPxFSuZ6T+rN/WCb/gOc6YgFBXLlZLhC7Ds4= -github.com/onsi/gomega v1.35.1/go.mod h1:PvZbdDc8J6XJEpDK4HCuRBm8a6Fzp9/DmhC9C7yFlog= -github.com/petermattis/goid v0.0.0-20240813172612-4fcff4a6cae7 h1:Dx7Ovyv/SFnMFw3fD4oEoeorXc6saIiQ23LrGLth0Gw= -github.com/petermattis/goid v0.0.0-20240813172612-4fcff4a6cae7/go.mod h1:pxMtw7cyUw6B2bRH0ZBANSPg+AoSud1I1iyJHI69jH4= +github.com/olekukonko/cat v0.0.0-20250911104152-50322a0618f6 h1:zrbMGy9YXpIeTnGj4EljqMiZsIcE09mmF8XsD5AYOJc= +github.com/olekukonko/cat v0.0.0-20250911104152-50322a0618f6/go.mod h1:rEKTHC9roVVicUIfZK7DYrdIoM0EOr8mK1Hj5s3JjH0= +github.com/olekukonko/errors v1.3.0 h1:teJvgLGUEqMzBUms+Dj3/3szNqCG/Jdw9iDbum8fR6U= +github.com/olekukonko/errors v1.3.0/go.mod h1:ppzxA5jBKcO1vIpCXQ9ZqgDh8iwODz6OXIGKU8r5m4Y= +github.com/olekukonko/ll v0.1.9 h1:7twe+xnE6CSlfOlvGj0Finwnvr3CgWt25W33yuWNI6k= +github.com/olekukonko/ll v0.1.9/go.mod h1:RPRC6UcscfFZgjo1nulkfMH5IM0QAYim0LfnMvUuozw= +github.com/olekukonko/tablewriter v1.1.5 h1:4LoZSfMySpMQY3PT8RWJsJeuEuMIoo9xGRgvmqjg6IQ= +github.com/olekukonko/tablewriter v1.1.5/go.mod h1:+kedxuyTtgoZLwif3P1Em4hARJs+mVnzKxmsCL/C5RY= +github.com/petermattis/goid v0.0.0-20250813065127-a731cc31b4fe/go.mod h1:pxMtw7cyUw6B2bRH0ZBANSPg+AoSud1I1iyJHI69jH4= +github.com/petermattis/goid v0.0.0-20260918085751-abfca077860b h1:OzNsuVdSWGwXvWKTtChx9ve89k4cFJ6NxYM4Aw4/f+E= +github.com/petermattis/goid v0.0.0-20260918085751-abfca077860b/go.mod h1:pxMtw7cyUw6B2bRH0ZBANSPg+AoSud1I1iyJHI69jH4= github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4= github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8= -github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 h1:KoWmjvw+nsYOo29YJK9vDA65RGE3NrOnUtO7a+RF9HU= -github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8/go.mod h1:HKlIX3XHQyzLZPlr7++PzdhaXEj94dEiJgZDTsxEqUI= +github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ= +github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU= github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= @@ -321,57 +333,49 @@ github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= -github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= -github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= -github.com/sasha-s/go-deadlock v0.3.5 h1:tNCOEEDG6tBqrNDOX35j/7hL5FcFViG6awUGROb2NsU= -github.com/sasha-s/go-deadlock v0.3.5/go.mod h1:bugP6EGbdGYObIlx7pUZtWqlvo8k9H6vCBBsiChJQ5U= -github.com/scip-code/scip/bindings/go/scip v0.7.0 h1:on80ynl7eSovvMUy3uxWkJm+kepsVjIwI2byIeMZego= -github.com/scip-code/scip/bindings/go/scip v0.7.0/go.mod h1:XC4dP3um0lKaSDRFIMwYlkBjFxKy1Rw7xFt6KDtRjAk= +github.com/rogpeppe/go-internal v1.16.0 h1:O9DK+vNMDVGLr2BeZqmpLeMjiMNkuXfcqntWbZV6S5g= +github.com/rogpeppe/go-internal v1.16.0/go.mod h1:DrUVZyrJU+txYW5/1kwtXQSMFio52ZOxX7yM1VHvnxs= +github.com/sasha-s/go-deadlock v0.3.9 h1:fiaT9rB7g5sr5ddNZvlwheclN9IP86eFW9WgqlEQV+w= +github.com/sasha-s/go-deadlock v0.3.9/go.mod h1:KuZj51ZFmx42q/mPaYbRk0P1xcwe697zsJKE03vD4/Y= +github.com/scip-code/scip/bindings/go/scip v0.10.0 h1:X7jaN76WK8WqU4/eTn1KyeaUEStvn4jdgW/NuzLzsPE= +github.com/scip-code/scip/bindings/go/scip v0.10.0/go.mod h1:4LGKCH2Vx61a1sWwq8bp5HGb7F/0qJMrAOEh0XdKKlc= github.com/segmentio/ksuid v1.0.4 h1:sBo2BdShXjmcugAMwjugoGUdUV0pcxY5mW4xKRn3v4c= github.com/segmentio/ksuid v1.0.4/go.mod h1:/XUiZBD3kVx5SmUOl55voK5yeAbBNNIed+2O73XgrPE= -github.com/shurcooL/go v0.0.0-20180423040247-9e1955d9fb6e/go.mod h1:TDJrrUr11Vxrven61rcy3hJMUqaf/CLWYhHNPmT14Lk= -github.com/shurcooL/go-goon v0.0.0-20170922171312-37c2f522c041/go.mod h1:N5mDOmsrJOB+vfqUK+7DmDyjhSLIIBnXo9lvZJj3MWQ= github.com/sourcegraph/beaut v0.0.0-20240611013027-627e4c25335a h1:j/CQ27s679M9wRGBRJYyXGrfkYuQA6VMnD7R08mHD9c= github.com/sourcegraph/beaut v0.0.0-20240611013027-627e4c25335a/go.mod h1:JG1sdvGTKWwe/oH3/3UKQ26vfcHIN//7fwEJhoqaBcM= github.com/sourcegraph/conc v0.3.1-0.20240108182409-4afefce20f9b h1:0FsjN+u9fNXTS2C1JnJ6G/gkgcUg8dscyyfu3PwHWUQ= github.com/sourcegraph/conc v0.3.1-0.20240108182409-4afefce20f9b/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0= -github.com/sourcegraph/go-diff v0.7.0 h1:9uLlrd5T46OXs5qpp8L/MTltk0zikUGi0sNNyCpA8G0= -github.com/sourcegraph/go-diff v0.7.0/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= -github.com/sourcegraph/jsonrpc2 v0.2.0 h1:KjN/dC4fP6aN9030MZCJs9WQbTOjWHhrtKVpzzSrr/U= -github.com/sourcegraph/jsonrpc2 v0.2.0/go.mod h1:ZafdZgk/axhT1cvZAPOhw+95nz2I/Ra5qMlU4gTRwIo= -github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf h1:oAdWFqhStsWiiMP/vkkHiMXqFXzl1XfUNOdxKJbd6bI= -github.com/sourcegraph/jsonx v0.0.0-20200629203448-1a936bd500cf/go.mod h1:ppFaPm6kpcHnZGqQTFhUIAQRIEhdQDWP1PCv4/ON354= -github.com/sourcegraph/log v0.0.0-20250923023806-517b6960b55b h1:2FQ72y5zECMu9e5z5jMnllb5n1jVK7qsvgjkVtdFV+g= -github.com/sourcegraph/log v0.0.0-20250923023806-517b6960b55b/go.mod h1:IDp09QkoqS8Z3CyN2RW6vXjgABkNpDbyjLIHNQwQ8P8= +github.com/sourcegraph/go-diff v0.9.0 h1:7xcVsayWHhvxZGrqt1o89vvBApCa4nyCgO7tNxDHJ+Q= +github.com/sourcegraph/go-diff v0.9.0/go.mod h1:hWlcO7Al+UZStZAP8rBumHpCK5ZHQ5BXsMls8p4+F5E= +github.com/sourcegraph/jsonrpc2 v0.2.3 h1:0VYp5WZ2irQvRK8OKKxZAbbplj6Pmda07MXm+Mdz3GQ= +github.com/sourcegraph/jsonrpc2 v0.2.3/go.mod h1:0jBvyko0tdLpe6ntNSF/mvFalb/RPRXcmogoV47cEWc= +github.com/sourcegraph/jsonx v0.0.0-20260429142705-814a2dc2d22f h1:qbr6YgS74/8iFzqDYAQGKGYhkDyFDPImJbLY+MIRA8I= +github.com/sourcegraph/jsonx v0.0.0-20260429142705-814a2dc2d22f/go.mod h1:Zux9/x595cm4kBQJ5QDYPDkQrRI6zKfPjx6S+DuKqAE= +github.com/sourcegraph/log v0.0.0-20260714115934-b104ff56b299 h1:iz6aHysi3F76ZlZsr4wCvTv9dkBqFlAmzQRlFeXCodY= +github.com/sourcegraph/log v0.0.0-20260714115934-b104ff56b299/go.mod h1:zxfuHzECDpM0+i+IAuZtWIfxySXq7qzH7hcIYe/elw0= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= -github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o= -github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= -github.com/spiffe/go-spiffe/v2 v2.7.0 h1:uXe1MflJoHw58wAUvxVlcM7WpKtijWG7I1UidcGh6g4= -github.com/spiffe/go-spiffe/v2 v2.7.0/go.mod h1:47Q0Q9/AqGha8QLHp+kxpH4Wca7X7EnOtlIJy3mxZ3U= +github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= +github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spiffe/go-spiffe/v2 v2.9.0 h1:g5qTg3qIP1HXV+GzuyEfSJFVxUCpEP5Ui1OINVJHPB4= +github.com/spiffe/go-spiffe/v2 v2.9.0/go.mod h1:w2CLWKLMTX/PPYUEUPv3ltH0RXsw5S8suwNF46w9/Aw= github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf h1:pvbZ0lM0XWPBqUKqFU8cmavspvIl9nulOYwdy6IFRRo= github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf/go.mod h1:RJID2RhlZKId02nZ62WenDCkgHFerpIOmW0iT7GKmXM= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= -github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= -github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= -github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/objx v0.8.0 h1:rm9oMkeprG/wHifkZP4EuDww9S0mvEaQ/p9cXTNT4cw= +github.com/stretchr/objx v0.8.0/go.mod h1:xSzHnPHkdEv7vtgdQej8atlCuU1mdX+ELge8bn0hCsE= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= -github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= -github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= -github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= -github.com/tliron/commonlog v0.2.19 h1:v1mOH1TyzFLqkshR03khw7ENAZPjAyZTQBQrqN+vX9c= -github.com/tliron/commonlog v0.2.19/go.mod h1:AcdhfcUqlAWukDrzTGyaPhUgYiNdZhS4dKzD/e0tjcY= +github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= +github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= +github.com/tliron/commonlog v0.2.21 h1:V1v+6opmzuOqDxxnxxM5RWtlHZmqZlDxkKeZGs6DpPg= +github.com/tliron/commonlog v0.2.21/go.mod h1:W6XVoS/zo7mHXv2Kz8HKnBq+U34dFysJ2KUh2Aboibw= github.com/tliron/glsp v0.2.2 h1:IKPfwpE8Lu8yB6Dayta+IyRMAbTVunudeauEgjXBt+c= github.com/tliron/glsp v0.2.2/go.mod h1:GMVWDNeODxHzmDPvYbYTCs7yHVaEATfYtXiYJ9w1nBg= -github.com/tliron/kutil v0.3.27 h1:Wb0V5jdbTci6Let1tiGY741J/9FIynmV/pCsPDPsjcM= -github.com/tliron/kutil v0.3.27/go.mod h1:AHeLNIFBSKBU39ELVHZdkw2f/ez2eKGAAGoxwBlhMi8= -github.com/urfave/cli/v3 v3.8.0 h1:XqKPrm0q4P0q5JpoclYoCAv0/MIvH/jZ2umzuf8pNTI= -github.com/urfave/cli/v3 v3.8.0/go.mod h1:ysVLtOEmg2tOy6PknnYVhDoouyC/6N42TMeoMzskhso= +github.com/tliron/go-kutil v0.4.0 h1:5JwcBacgnqS3XyhwCWZKvq8ftlbVttNXnt+kfCH+Y2E= +github.com/tliron/go-kutil v0.4.0/go.mod h1:hpHVq+CP1uci2M208UEjPiPwsRsz/QweGBnLB3CaQ24= +github.com/urfave/cli/v3 v3.14.0 h1:a8414NQlHJs0c/iBsulKLzlES0n/lEAskbL2LKpU4/s= +github.com/urfave/cli/v3 v3.14.0/go.mod h1:vXn6HxPNccJSzQr2QvwVncOKrgYGIHU0HY5h8B2nQj4= github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= @@ -383,62 +387,65 @@ github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17 github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y= github.com/xlab/treeprint v1.2.0 h1:HzHnuAF1plUN2zGlAFHbSQP2qJ0ZAD3XF5XD7OesXRQ= github.com/xlab/treeprint v1.2.0/go.mod h1:gj5Gd3gPdKtR1ikdDK6fnFLdmIS0X30kTTuNd/WEJu0= -github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no= -github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM= +github.com/xo/terminfo v1.3.0 h1:KstyePbNW6UaLq9y12+544VK4aTP3Eku/sym3a9+UgQ= +github.com/xo/terminfo v1.3.0/go.mod h1:lGzkSo8Fe7IRh/w+Gqz7n5mDog4FVXCj3gy/DYTBqio= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= -github.com/yuin/goldmark v1.7.1/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E= -github.com/yuin/goldmark v1.7.17 h1:p36OVWwRb246iHxA/U4p8OPEpOTESm4n+g+8t0EE5uA= -github.com/yuin/goldmark v1.7.17/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg= -github.com/yuin/goldmark-emoji v1.0.5 h1:EMVWyCGPlXJfUXBXpuMu+ii3TIaxbVBnEX9uaDC4cIk= -github.com/yuin/goldmark-emoji v1.0.5/go.mod h1:tTkZEbwu5wkPmgTcitqddVxY9osFZiavD+r4AzQrh1U= -github.com/zalando/go-keyring v0.2.6 h1:r7Yc3+H+Ux0+M72zacZoItR3UDxeWfKTcabvkI8ua9s= -github.com/zalando/go-keyring v0.2.6/go.mod h1:2TCrxYrbUNYfNS/Kgy/LSrkSQzZ5UPVH85RwfczwvcI= +github.com/yuin/goldmark v1.8.7 h1:XT/tNqCIbabh0ln675w4x3dv04kQBKi8NwYqi9IJaxI= +github.com/yuin/goldmark v1.8.7/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg= +github.com/yuin/goldmark-emoji v1.0.6 h1:QWfF2FYaXwL74tfGOW5izeiZepUDroDJfWubQI9HTHs= +github.com/yuin/goldmark-emoji v1.0.6/go.mod h1:ukxJDKFpdFb5x0a5HqbdlcKtebh086iJpI31LTKmWuA= +github.com/zalando/go-keyring v0.2.8 h1:6sD/Ucpl7jNq10rM2pgqTs0sZ9V3qMrqfIIy5YPccHs= +github.com/zalando/go-keyring v0.2.8/go.mod h1:tsMo+VpRq5NGyKfxoBVjCuMrG47yj8cmakZDO5QGii0= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= -go.opentelemetry.io/contrib/detectors/gcp v1.44.0 h1:NmLfL734pJhM0JKaYd2Y28+nY9dPRWYAAbxhRCrKXPw= -go.opentelemetry.io/contrib/detectors/gcp v1.44.0/go.mod h1:tNAsgd8avTGke1+MndXlU5Cru4PQ9Ai/cCNWQv/ZJ/s= -go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0 h1:q4XOmH/0opmeuJtPsbFNivyl7bCt7yRBbeEm2sC/XtQ= -go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0/go.mod h1:snMWehoOh2wsEwnvvwtDyFCxVeDAODenXHtn5vzrKjo= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0 h1:RbKq8BG0FI8OiXhBfcRtqqHcZcka+gU3cskNuf05R18= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0/go.mod h1:h06DGIukJOevXaj/xrNjhi/2098RZzcLTbc0jDAUbsg= -go.opentelemetry.io/otel v1.45.0 h1:pdrWmLHofpubmArBv1LgFSv1Z0Ie/ppdZzu+kUN5EeU= -go.opentelemetry.io/otel v1.45.0/go.mod h1:XZxIqPapzEYnhNSScF5DIqXhm/rYi0FzCe2XddAwZfQ= -go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.36.0 h1:rixTyDGXFxRy1xzhKrotaHy3/KXdPhlWARrCgK+eqUY= -go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.36.0/go.mod h1:dowW6UsM9MKbJq5JTz2AMVp3/5iW5I/TStsk8S+CfHw= -go.opentelemetry.io/otel/metric v1.45.0 h1:7Eg1uH7CJ5cXv9is6tnBe1FI6rj1nwUdbFypRm3br/M= -go.opentelemetry.io/otel/metric v1.45.0/go.mod h1:HAPbm1nd3p1PmFH7v2dR+6BjXxw+Lq4a2+pndMAm08s= -go.opentelemetry.io/otel/metric/x v0.67.0 h1:PcicCNZFkZ4bXfSooXdo3WN7RBOVOtjVdo1wD358Uns= -go.opentelemetry.io/otel/metric/x v0.67.0/go.mod h1:FBjCWZe6wgcqxcMtjdGiClDKXb2YxxXii0CXftE4QtI= -go.opentelemetry.io/otel/sdk v1.45.0 h1:4VVSMgQ83dUgW2aoX5f6JgLvHwIvzcuLnF9lUdCSpCw= -go.opentelemetry.io/otel/sdk v1.45.0/go.mod h1:Sr40LgXV7DsKMMJMKOhUWOgMWTfAaqvm2kF0g7ilwuA= -go.opentelemetry.io/otel/sdk/metric v1.45.0 h1:oVFszMfyj1Am6s24Vtc7wBb8BKLcwepJjNEYILuiE3o= -go.opentelemetry.io/otel/sdk/metric v1.45.0/go.mod h1:vUWUxDZvu1WVRj8JA8S0AdhsPrZoDpA2DdZauIh4mDA= -go.opentelemetry.io/otel/trace v1.45.0 h1:l/mP6Uv7oNO7/TblbhpbgMidxhq1uO/rPsikOyVhxag= -go.opentelemetry.io/otel/trace v1.45.0/go.mod h1:qoJJA2xNMnxRrdISU/kLtfUH2wNeQbiv+jhs/CxI8bc= -go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= -go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= +go.opentelemetry.io/contrib/detectors/gcp v1.47.0 h1:Ct6+aaiSO6Nk5SOb6PYcR7iWp+83YF/pL1OJcGqOmbg= +go.opentelemetry.io/contrib/detectors/gcp v1.47.0/go.mod h1:3N259ss0b1AVOs+fYw7lOO0mcUwNqSIpQ+Zitpuqx00= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.72.0 h1:Tq+E65HaNbZTeqcLw6QUhsV+/EIWdkfUH2CQzcrlE5M= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.72.0/go.mod h1:A+EVhDakAj1waJBPhmTszZaSr08ww8MRRKy1nB1rqck= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0 h1:LxwW/9ctSCv+QkE/cLR7M91ZIkXNMqJtEMi1vCw9U8s= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0/go.mod h1:tOsftB4SslBwwErVEPaenU2RpThXWPIU8DoJHEC4dyw= +go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM= +go.opentelemetry.io/otel v1.47.0/go.mod h1:8wS9O2qfXrYrzp6hIF/HOYJJf/wIhFPhR2xLuP+iXQU= +go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.45.0 h1:dm9iyzn6tioYZtwqaiBSU0TSI8Yu/8dTIbfG0+B49DY= +go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.45.0/go.mod h1:xAvxYjYK28qvt+yu4BYZ/zMmAjwMXINXD6JiMyeB8iI= +go.opentelemetry.io/otel/log v1.47.0 h1:cOTS1CcLbSQeZKanGJ+0JpF/+t4PELi3O3bbl2lqCcI= +go.opentelemetry.io/otel/log v1.47.0/go.mod h1:9byitSQ5pLC6PpqwGXjqdMKya6ZTswHRZh2vvXT33nw= +go.opentelemetry.io/otel/metric v1.47.0 h1:4PptaldXx3Eat1XjMZ68pPJEs5wrhlemctZE9a3UdWY= +go.opentelemetry.io/otel/metric v1.47.0/go.mod h1:ADGSXxRrXM6bjbvLo535EstVFlPpPYZm4LBKixjDHwU= +go.opentelemetry.io/otel/metric/x v0.69.0 h1:DjRLr15H83v+hCW7JA9NoJvOkYTtmq5YoDRbe9deYpM= +go.opentelemetry.io/otel/metric/x v0.69.0/go.mod h1:uVvsMPMFFyj/HUQfrUnH3JjnOQ1dwFDorgFLRBasM0k= +go.opentelemetry.io/otel/sdk v1.47.0 h1:zWXEr4j2lFefG87TU6Yg8a7ngfohIKFZHKp0Hf5hC6I= +go.opentelemetry.io/otel/sdk v1.47.0/go.mod h1:VUc24kiOeoGsxG8G9ULx3fWKvB7jMhnGE8Oi607lgR0= +go.opentelemetry.io/otel/sdk/metric v1.47.0 h1:lfISg2j93VT6yqdk9OfUaZmw/GfcZqCCV3jdXtsPnKw= +go.opentelemetry.io/otel/sdk/metric v1.47.0/go.mod h1:ypLp+mW1Nt2x+Szt3b5/i1syodyts49lMOwxpDI3VGw= +go.opentelemetry.io/otel/trace v1.47.0 h1:JOjX/Oci8K94QHddo+bbfya/Ai/nf6/dt9ZfrFNWSrM= +go.opentelemetry.io/otel/trace v1.47.0/go.mod h1:jNaSLa2PZEYFG6fRjJABAu+bw4FS08uDmPg28lTghu0= +go.uber.org/atomic v1.12.0 h1:BvcXdFKuviU4fTL/f+SxdQ5qJX/Jix8pAkgdUcb3XOE= +go.uber.org/atomic v1.12.0/go.mod h1:I6c4cg+6HCxRjfjSsYtApoFILnpc0CGUdGkXVqbYVNk= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= -go.uber.org/zap v1.24.0 h1:FiJd5l1UOLj0wCgbSE0rwwXHzEdAZS6hiiSnxJN/D60= -go.uber.org/zap v1.24.0/go.mod h1:2kMP+WWQ8aoFoedH3T2sq6iJ2yDWpHbP0f6MQbS9Gkg= +go.uber.org/zap v1.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo= +go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q= +go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ= +go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ= +go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= +go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M= -golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA= -golang.org/x/exp v0.0.0-20230713183714-613f0c0eb8a1 h1:MGwJjxBy0HJshjDNfLsYO8xppfqWlA5ZT9OhtUUhTNw= -golang.org/x/exp v0.0.0-20230713183714-613f0c0eb8a1/go.mod h1:FXUEEKJgO7OQYeo8N01OfiKP8RXMtf6e8aTskBGqWdc= +golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54= +golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.7.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c= -golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o= +golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg= +golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= @@ -446,18 +453,18 @@ golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwY golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.3.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE= -golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU= -golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= -golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs= -golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q= +golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= +golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= +golang.org/x/oauth2 v0.37.0 h1:JUlcxA8oAtauLfiH8FX2/FkAWHAdi0QtGCGc+hofE98= +golang.org/x/oauth2 v0.37.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220819030929-7fc1605a5dde/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk= -golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= +golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -465,98 +472,93 @@ golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210616045830-e2b7044e8c71/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220829200755-d48e67d00261/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= -golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= +golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.3.0/go.mod h1:q750SLmJuPmVoN1blW3UFBPREJfb1KmY3vwxfr+nFDA= -golang.org/x/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE= -golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc= +golang.org/x/term v0.47.0 h1:cpyOwQkr2Nzxe2p6KnrTG7Ei2wtzjsuSjhpXXepZ/BM= +golang.org/x/term v0.47.0/go.mod h1:efAfAuG6RKABvg1ArGebRkvX6LXul14SM67o2e4mUCY= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= -golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E= -golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI= -golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4= +golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc= +golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s= +golang.org/x/time v0.16.0 h1:vMb6ptszcQMkcwiRTAuNNU50gom6++Q/6gY2hDM6VDE= +golang.org/x/time v0.16.0/go.mod h1:rVKOqvZeKvrDKTQiAHJ7wmwP0RzleSphoEA9RcdLA0s= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200624163319-25775e59acb7/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.4.0/go.mod h1:UE5sM2OK9E/d67R0ANs2xJizIymRP5gJU295PvKXxjQ= -golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI= -golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo= +golang.org/x/tools v0.51.0 h1:k4Xc/1Om9jwkBJBo4NVLMSARBoWtK10mx+W5BnXCeAI= +golang.org/x/tools v0.51.0/go.mod h1:9eEncMayCV6zRMGhR5eZEC2iBx98qWcF1HZ9Z7wJOoA= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= -google.golang.org/api v0.264.0 h1:+Fo3DQXBK8gLdf8rFZ3uLu39JpOnhvzJrLMQSoSYZJM= -google.golang.org/api v0.264.0/go.mod h1:fAU1xtNNisHgOF5JooAs8rRaTkl2rT3uaoNGo9NS3R8= -google.golang.org/genproto v0.0.0-20260128011058-8636f8732409 h1:VQZ/yAbAtjkHgH80teYd2em3xtIkkHd7ZhqfH2N9CsM= -google.golang.org/genproto v0.0.0-20260128011058-8636f8732409/go.mod h1:rxKD3IEILWEu3P44seeNOAwZN4SaoKaQ/2eTg4mM6EM= -google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa h1:Kjn0N0tCrDgiAFW+lGO4JZ3ck44CehvJQMAwj9QF0G8= -google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:q4lMZS6kskjT5HvCPrnnypcDPVJqT/f4nfxmkE7gryY= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa h1:mZHHdPZl0dbGHCflZgAq/Q468DWVFcU2whhB2KAo8fk= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= -google.golang.org/grpc v1.83.2 h1:EManeRomTObA0BU7I8vXgg/78uE5MJ9M8B39EX2WscU= -google.golang.org/grpc v1.83.2/go.mod h1:YPI1hK3kDked6iHvgX3tR0y+nX/qpMFKhPgFsokw1S8= -google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= -google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +google.golang.org/api v0.310.0 h1:537ccDDmbwuwX1iof3Vtdz9vow6uJCgrSZJWedAWM0I= +google.golang.org/api v0.310.0/go.mod h1:5NUthU+LmGMKzYgRaScb+TTe1Lo7x4A+J7g+Yj8BRzA= +google.golang.org/genproto v0.0.0-20261026165753-2ffab32bce7e h1:zuDtZCGOny/OoQTOrQuC4MP9IeL/fMEfA8/6pZfW7T4= +google.golang.org/genproto v0.0.0-20261026165753-2ffab32bce7e/go.mod h1:urf0D1njFRQL4Hy45UZb7H6azkzBlHOZj9mumBat/kc= +google.golang.org/genproto/googleapis/api v0.0.0-20261026165753-2ffab32bce7e h1:e789sLZjeTdc02ZCQGTSzHOu0fR73+dwPQVKUp67Z88= +google.golang.org/genproto/googleapis/api v0.0.0-20261026165753-2ffab32bce7e/go.mod h1:vHV3wJM9WZyfV7GyB+OQGq5dWVrFwCDxapPK4WlRD88= +google.golang.org/genproto/googleapis/rpc v0.0.0-20261026165753-2ffab32bce7e h1:w3fy/G8OrJHYexn+u5y7hFyc8YRRIr7DCevtIOwAcGY= +google.golang.org/genproto/googleapis/rpc v0.0.0-20261026165753-2ffab32bce7e/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc= +google.golang.org/grpc v1.85.0 h1:BPBCfuVRQ1qvBhKDOq9uvQllMvO59rKsYhXpp7Dd8vw= +google.golang.org/grpc v1.85.0/go.mod h1:0rQrOD58yjal/0EaVbGBANindixsCZNQPDV3VKtaKuQ= +google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc= +google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= -gopkg.in/evanphx/json-patch.v4 v4.12.0 h1:n6jtcsulIzXPJaxegRbvFNNrZDjbij7ny3gmSPG+6V4= -gopkg.in/evanphx/json-patch.v4 v4.12.0/go.mod h1:p8EYWUEYMpynmqDbY58zCKCFZw8pRWMG4EsWvDvM72M= +gopkg.in/evanphx/json-patch.v4 v4.13.0 h1:czT3CmqEaQ1aanPc5SdlgQrrEIb8w/wwCvWWnfEbYzo= +gopkg.in/evanphx/json-patch.v4 v4.13.0/go.mod h1:p8EYWUEYMpynmqDbY58zCKCFZw8pRWMG4EsWvDvM72M= gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc= gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7 h1:mub0MmFLOn8XLikZOAhgLD1kXJq8jgftSrrv7m00xFo= -jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7/go.mod h1:OxvTsCwKosqQ1q7B+8FwXqg4rKZ/UG9dUW+g/VL2xH4= -k8s.io/api v0.33.2 h1:YgwIS5jKfA+BZg//OQhkJNIfie/kmRsO0BmNaVSimvY= -k8s.io/api v0.33.2/go.mod h1:fhrbphQJSM2cXzCWgqU29xLDuks4mu7ti9vveEnpSXs= -k8s.io/apimachinery v0.33.2 h1:IHFVhqg59mb8PJWTLi8m1mAoepkUNYmptHsV+Z1m5jY= -k8s.io/apimachinery v0.33.2/go.mod h1:BHW0YOu7n22fFv/JkYOEfkUYNRN0fj0BlvMFWA7b+SM= -k8s.io/client-go v0.33.2 h1:z8CIcc0P581x/J1ZYf4CNzRKxRvQAwoAolYPbtQes+E= -k8s.io/client-go v0.33.2/go.mod h1:9mCgT4wROvL948w6f6ArJNb7yQd7QsvqavDeZHvNmHo= -k8s.io/klog/v2 v2.130.1 h1:n9Xl7H1Xvksem4KFG4PYbdQCQxqc/tTUyrgXaOhHSzk= -k8s.io/klog/v2 v2.130.1/go.mod h1:3Jpz1GvMt720eyJH1ckRHK1EDfpxISzJ7I9OYgaDtPE= -k8s.io/kube-openapi v0.0.0-20250318190949-c8a335a9a2ff h1:/usPimJzUKKu+m+TE36gUyGcf03XZEP0ZIKgKj35LS4= -k8s.io/kube-openapi v0.0.0-20250318190949-c8a335a9a2ff/go.mod h1:5jIi+8yX4RIb8wk3XwBo5Pq2ccx4FP10ohkbSKCZoK8= -k8s.io/utils v0.0.0-20241104100929-3ea5e8cea738 h1:M3sRQVHv7vB20Xc2ybTt7ODCeFj6JSWYFzOFnYeS6Ro= -k8s.io/utils v0.0.0-20241104100929-3ea5e8cea738/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= +jaytaylor.com/html2text v0.0.0-20260303211410-1a4bdc82ecec h1:rWumoGZD/ScZXpzJ/ahgIQp79P5S2DJ25gjJHn+KttA= +jaytaylor.com/html2text v0.0.0-20260303211410-1a4bdc82ecec/go.mod h1:OxvTsCwKosqQ1q7B+8FwXqg4rKZ/UG9dUW+g/VL2xH4= +k8s.io/api v0.37.2 h1:PnxqnUFy93jr2GcpWDkKOm8wfy25kT9wa572MuQS8oc= +k8s.io/api v0.37.2/go.mod h1:+NVRLft99kx+Jg9v34GmHw867Dapim89TSyCsn2hK+M= +k8s.io/apimachinery v0.37.2 h1:G4t9RGoPDbQML38hz/kQQiltttgd3egg2ODCR8aIc2o= +k8s.io/apimachinery v0.37.2/go.mod h1:qaAvSNvgU2x07wRM95MSHSJTPQ/ob/LeNAGbeDgqQJg= +k8s.io/client-go v0.37.2 h1:sgFtyRZukGkOrsu+QgS7LYnbFFJ5ut3MchdBNduD//E= +k8s.io/client-go v0.37.2/go.mod h1:bo3LFC8YbCtKFPX21Yj8puMsoJLAv/+SvuOODma0s54= +k8s.io/klog/v2 v2.140.0 h1:Tf+J3AH7xnUzZyVVXhTgGhEKnFqye14aadWv7bzXdzc= +k8s.io/klog/v2 v2.140.0/go.mod h1:o+/RWfJ6PwpnFn7OyAG3QnO47BFsymfEfrz6XyYSSp0= +k8s.io/kube-openapi v0.0.0-20260721132016-d427ff9ee9ad h1:oXImqH8mQNk7PmvzKhmN3ddJoY6OnyM225MXwGHPm0A= +k8s.io/kube-openapi v0.0.0-20260721132016-d427ff9ee9ad/go.mod h1:0/mqHCVhlumdJ3BhCfnjSZQE037nAhNodh1/hK0T8/I= +k8s.io/utils v0.0.0-20261023123148-ca04ba58ecab h1:pjQrNLaF//ytZtWwCAHtW+pqwSKjtWDqzA8+TCX37RI= +k8s.io/utils v0.0.0-20261023123148-ca04ba58ecab/go.mod h1:DdQ0BJxlQtuMlKDqdg7X5IMMQCXIk2b3d1/4M9OhUYo= mvdan.cc/gofumpt v0.4.0/go.mod h1:PljLOHDeZqgS8opHRKLzp2It2VBuSdteAgqUfzMTxlQ= -mvdan.cc/gofumpt v0.5.0 h1:0EQ+Z56k8tXjj/6TQD25BFNKQXpCvT0rnansIc7Ug5E= -mvdan.cc/gofumpt v0.5.0/go.mod h1:HBeVDtMKRZpXyxFciAirzdKklDlGu8aAy1wEbH5Y9js= -pgregory.net/rapid v1.1.0 h1:CMa0sjHSru3puNx+J0MIAuiiEV4N0qj8/cMWGBBCsjw= -pgregory.net/rapid v1.1.0/go.mod h1:PY5XlDGj0+V1FCq0o192FdRhpKHGTRIWBgqjDBTrq04= -sigs.k8s.io/json v0.0.0-20241010143419-9aa6b5e7a4b3 h1:/Rv+M11QRah1itp8VhT6HoVx1Ray9eB4DBr+K+/sCJ8= -sigs.k8s.io/json v0.0.0-20241010143419-9aa6b5e7a4b3/go.mod h1:18nIHnGi6636UCz6m8i4DhaJ65T6EruyzmoQqI2BVDo= -sigs.k8s.io/randfill v0.0.0-20250304075658-069ef1bbf016/go.mod h1:XeLlZ/jmk4i1HRopwe7/aU3H5n1zNUcX6TM94b3QxOY= +mvdan.cc/gofumpt v0.10.0 h1:yGGpRS2pBN2OQIi7b21IXknJna7faPkFaVfHLrN6Euo= +mvdan.cc/gofumpt v0.10.0/go.mod h1:sU2ElXHzOEmvoPqfutYG7uunlueR4K2T1JFml40SzP4= +pgregory.net/rapid v1.3.0 h1:vBvO0VSqti75J1jjYqpgPNBLKMd1+gxa9fYo7vk/Exc= +pgregory.net/rapid v1.3.0/go.mod h1:dPlE4OBBxgXPqkP79flB6sJL1dx5azpI7HQ9MY9Z7uk= +sigs.k8s.io/json v0.0.0-20260909141634-11ed52e25bc5 h1:k9jo7ED/fsfOcz3L1P20P5tjTNtsdQNwMOG2aKzHrl8= +sigs.k8s.io/json v0.0.0-20260909141634-11ed52e25bc5/go.mod h1:mdzfpAEoE6DHQEN0uh9ZbOCuHbLK5wOm7dK4ctXE9Tg= sigs.k8s.io/randfill v1.0.0 h1:JfjMILfT8A6RbawdsK2JXGBR5AQVfd+9TbzrlneTyrU= sigs.k8s.io/randfill v1.0.0/go.mod h1:XeLlZ/jmk4i1HRopwe7/aU3H5n1zNUcX6TM94b3QxOY= -sigs.k8s.io/structured-merge-diff/v4 v4.6.0 h1:IUA9nvMmnKWcj5jl84xn+T5MnlZKThmUW1TdblaLVAc= -sigs.k8s.io/structured-merge-diff/v4 v4.6.0/go.mod h1:dDy58f92j70zLsuZVuUX5Wp9vtxXpaZnkPGWeqDfCps= -sigs.k8s.io/yaml v1.4.0 h1:Mk1wCc2gy/F0THH0TAp1QYyJNzRm2KCLy3o5ASXVI5E= -sigs.k8s.io/yaml v1.4.0/go.mod h1:Ejl7/uTz7PSA4eKMyQCUTnhZYNmLIl+5c2lQPGR2BPY= +sigs.k8s.io/structured-merge-diff/v6 v6.4.2 h1:qdOxHwrl2Kaag1aQEarlYcOA9vSyGCp3CIki3aW8c4Q= +sigs.k8s.io/structured-merge-diff/v6 v6.4.2/go.mod h1:M3W8sfWvn2HhQDIbGWj3S099YozAsymCo/wrT5ohRUE= +sigs.k8s.io/yaml v1.6.0 h1:G8fkbMSAFqgEFgh4b1wmtzDnioxFCUgTZhlbj5P9QYs= +sigs.k8s.io/yaml v1.6.0/go.mod h1:796bPqUfzR/0jLAl6XjHl3Ck7MiyVv8dbTdyT3/pMf4= diff --git a/internal/api/api.go b/internal/api/api.go index d34ccf4c93..ae0474077a 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -12,6 +12,7 @@ import ( "net/url" "os" "runtime" + "strings" "time" ioaux "github.com/jig/teereadcloser" @@ -410,18 +411,19 @@ func (r *request) curlCmd() (string, error) { return "", err } - s := "curl \\\n" + var s strings.Builder + s.WriteString("curl \\\n") if r.client.opts.AccessToken != "" { - s += fmt.Sprintf(" %s \\\n", shellquote.Join("-H", "Authorization: token "+r.client.opts.AccessToken)) + fmt.Fprintf(&s, " %s \\\n", shellquote.Join("-H", "Authorization: token "+r.client.opts.AccessToken)) } // Preserve overrides if Content-Type is set if r.client.opts.AdditionalHeaders["Content-Type"] == "" { r.client.opts.AdditionalHeaders["Content-Type"] = "application/json" } for k, v := range r.client.opts.AdditionalHeaders { - s += fmt.Sprintf(" %s \\\n", shellquote.Join("-H", k+": "+v)) + fmt.Fprintf(&s, " %s \\\n", shellquote.Join("-H", k+": "+v)) } - s += fmt.Sprintf(" %s \\\n", shellquote.Join("-d", string(data))) - s += fmt.Sprintf(" %s", shellquote.Join(r.client.opts.EndpointURL.JoinPath(".api/graphql").String())) - return s, nil + fmt.Fprintf(&s, " %s \\\n", shellquote.Join("-d", string(data))) + fmt.Fprintf(&s, " %s", shellquote.Join(r.client.opts.EndpointURL.JoinPath(".api/graphql").String())) + return s.String(), nil } diff --git a/internal/api/proxy_test.go b/internal/api/proxy_test.go index 4b2980e712..1347a824e3 100644 --- a/internal/api/proxy_test.go +++ b/internal/api/proxy_test.go @@ -266,10 +266,10 @@ func TestBuildTransport_WithProxyURL(t *testing.T) { insecure := true flags := &Flags{ insecureSkipVerify: &insecure, - dump: boolPtr(false), - getCurl: boolPtr(false), - trace: boolPtr(false), - userAgentTelemetry: boolPtr(false), + dump: new(false), + getCurl: new(false), + trace: new(false), + userAgentTelemetry: new(false), } opts := ClientOpts{ ProxyURL: proxyURL, @@ -296,10 +296,10 @@ func TestBuildTransport_WithProxyPath(t *testing.T) { insecure := true flags := &Flags{ insecureSkipVerify: &insecure, - dump: boolPtr(false), - getCurl: boolPtr(false), - trace: boolPtr(false), - userAgentTelemetry: boolPtr(false), + dump: new(false), + getCurl: new(false), + trace: new(false), + userAgentTelemetry: new(false), } opts := ClientOpts{ ProxyPath: socketPath, @@ -324,10 +324,10 @@ func TestBuildTransport_NoProxyPreservesProxyFunc(t *testing.T) { insecure := true flags := &Flags{ insecureSkipVerify: &insecure, - dump: boolPtr(false), - getCurl: boolPtr(false), - trace: boolPtr(false), - userAgentTelemetry: boolPtr(false), + dump: new(false), + getCurl: new(false), + trace: new(false), + userAgentTelemetry: new(false), } opts := ClientOpts{} // no ProxyURL or ProxyPath @@ -353,10 +353,10 @@ func TestBuildTransport_NOPROXYOverridesHTTPSPROXY(t *testing.T) { insecure := true flags := &Flags{ insecureSkipVerify: &insecure, - dump: boolPtr(false), - getCurl: boolPtr(false), - trace: boolPtr(false), - userAgentTelemetry: boolPtr(false), + dump: new(false), + getCurl: new(false), + trace: new(false), + userAgentTelemetry: new(false), } opts := ClientOpts{} // no ProxyURL or ProxyPath @@ -386,10 +386,10 @@ func TestBuildTransport_ExplicitProxyURLOverridesNOPROXY(t *testing.T) { insecure := true flags := &Flags{ insecureSkipVerify: &insecure, - dump: boolPtr(false), - getCurl: boolPtr(false), - trace: boolPtr(false), - userAgentTelemetry: boolPtr(false), + dump: new(false), + getCurl: new(false), + trace: new(false), + userAgentTelemetry: new(false), } opts := ClientOpts{ ProxyURL: proxyURL, @@ -403,5 +403,3 @@ func TestBuildTransport_ExplicitProxyURLOverridesNOPROXY(t *testing.T) { t.Fatal("explicit ProxyURL did not override NO_PROXY") } } - -func boolPtr(b bool) *bool { return &b } diff --git a/internal/api/test_unix_socket_server.go b/internal/api/test_unix_socket_server.go index c637aed0b9..a955a98251 100644 --- a/internal/api/test_unix_socket_server.go +++ b/internal/api/test_unix_socket_server.go @@ -57,9 +57,7 @@ func StartUnixSocketServer(socketPath string) (*Server, error) { StopChan: make(chan struct{}), } - server.Wg.Add(1) - go func() { - defer server.Wg.Done() + server.Wg.Go(func() { for { conn, err := server.Listener.Accept() if err != nil { @@ -96,7 +94,7 @@ func StartUnixSocketServer(socketPath string) (*Server, error) { } }(conn) } - }() + }) return server, nil } diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index dc44e31bac..09fcb4e8b4 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -337,9 +337,7 @@ func (svc *Service) EnsureDockerImages( } var wg sync.WaitGroup for i := 0; i < parallelism; i++ { - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { for { select { case <-workerCtx.Done(): @@ -363,7 +361,7 @@ func (svc *Service) EnsureDockerImages( } } } - }() + }) } go func() { diff --git a/internal/lsp/server_test.go b/internal/lsp/server_test.go index 13a57e9857..66b4ae03c1 100644 --- a/internal/lsp/server_test.go +++ b/internal/lsp/server_test.go @@ -264,10 +264,8 @@ func TestHandleTextDocumentDocumentHighlight(t *testing.T) { uri := pathToFileURI(filepath.Join(gitRoot, tt.path)) params := &protocol.DocumentHighlightParams{ - TextDocumentPositionParams: protocol.TextDocumentPositionParams{ - TextDocument: protocol.TextDocumentIdentifier{URI: uri}, - Position: protocol.Position{Line: 10, Character: 5}, - }, + TextDocument: protocol.TextDocumentIdentifier{URI: uri}, + Position: protocol.Position{Line: 10, Character: 5}, } result, err := s.handleTextDocumentDocumentHighlight(nil, params) diff --git a/internal/streaming/client.go b/internal/streaming/client.go index 79ee92efaf..e8aabc5561 100644 --- a/internal/streaming/client.go +++ b/internal/streaming/client.go @@ -137,11 +137,11 @@ func (rr Decoder) ReadAll(r io.Reader) error { } func splitColon(data []byte) ([]byte, []byte) { - i := bytes.Index(data, []byte(":")) - if i < 0 { + before, after, ok := bytes.Cut(data, []byte(":")) + if !ok { return bytes.TrimSpace(data), nil } - return bytes.TrimSpace(data[:i]), bytes.TrimSpace(data[i+1:]) + return bytes.TrimSpace(before), bytes.TrimSpace(after) } type eventMatchUnmarshaller struct { diff --git a/internal/validate/kube/kube.go b/internal/validate/kube/kube.go index ae7555b323..12be9c6ff3 100644 --- a/internal/validate/kube/kube.go +++ b/internal/validate/kube/kube.go @@ -381,7 +381,7 @@ func CurrentContextSetTo(clusterService string) error { switch clusterService { case "gke": - got := strings.Split(currentContext, "_")[0] + got, _, _ := strings.Cut(currentContext, "_") want := clusterService if got != want { return errors.New("no gke cluster configured") diff --git a/internal/validate/kube/kube_test.go b/internal/validate/kube/kube_test.go index fbc83c77ad..996a0f6e89 100644 --- a/internal/validate/kube/kube_test.go +++ b/internal/validate/kube/kube_test.go @@ -4,7 +4,6 @@ import ( "testing" corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/sourcegraph/src-cli/internal/validate" ) @@ -306,15 +305,13 @@ func TestValidatePVC(t *testing.T) { // helper test function to return a valid pod func testPod() *corev1.Pod { return &corev1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: "default", - Name: "sourcegraph-frontend-", - Labels: map[string]string{ - "deploy": "sourcegraph", - }, - Annotations: map[string]string{ - "kubectl.kubernetes.io/default-container": "frontend", - }, + Namespace: "default", + Name: "sourcegraph-frontend-", + Labels: map[string]string{ + "deploy": "sourcegraph", + }, + Annotations: map[string]string{ + "kubectl.kubernetes.io/default-container": "frontend", }, Spec: corev1.PodSpec{ Containers: []corev1.Container{ @@ -354,12 +351,10 @@ func testPod() *corev1.Pod { // helper test function to return a valid service func testService() *corev1.Service { return &corev1.Service{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: "default", - Name: "symbols", - Labels: map[string]string{ - "deploy": "sourcegraph", - }, + Namespace: "default", + Name: "symbols", + Labels: map[string]string{ + "deploy": "sourcegraph", }, Spec: corev1.ServiceSpec{ Type: corev1.ServiceTypeClusterIP, @@ -378,12 +373,10 @@ func testService() *corev1.Service { // helper test function to return a valid PVC func testPVC() *corev1.PersistentVolumeClaim { return &corev1.PersistentVolumeClaim{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: "default", - Name: "pgsql", - Labels: map[string]string{ - "deploy": "sourcegraph", - }, + Namespace: "default", + Name: "pgsql", + Labels: map[string]string{ + "deploy": "sourcegraph", }, Status: corev1.PersistentVolumeClaimStatus{ Phase: "Bound", diff --git a/lib/batches/batch_spec.go b/lib/batches/batch_spec.go index 30ef50d4a9..c1512430c4 100644 --- a/lib/batches/batch_spec.go +++ b/lib/batches/batch_spec.go @@ -45,8 +45,8 @@ type BatchSpec struct { // Hooks declares side-effect actions to run at well-defined changeset // lifecycle events. Only allowed when Version is 3. type ChangesetHooks struct { - OnCIFailure ChangesetHookAction `json:"onCIFailure,omitempty" yaml:"onCIFailure,omitempty"` - OnMergeConflict ChangesetHookAction `json:"onMergeConflict,omitempty" yaml:"onMergeConflict,omitempty"` + OnCIFailure ChangesetHookAction `json:"onCIFailure" yaml:"onCIFailure,omitempty"` + OnMergeConflict ChangesetHookAction `json:"onMergeConflict" yaml:"onMergeConflict,omitempty"` } // HookAction is a single action attached to a changeset lifecycle event. diff --git a/lib/batches/overridable/overridable.go b/lib/batches/overridable/overridable.go index 61cfaadd9b..d8d36bdf43 100644 --- a/lib/batches/overridable/overridable.go +++ b/lib/batches/overridable/overridable.go @@ -4,6 +4,7 @@ package overridable import ( "encoding/json" + "slices" "strings" "github.com/gobwas/glob" @@ -70,9 +71,9 @@ type rules []*rule // Match matches the given repository name against all rules, returning the rule value that matches at last, or nil if none match. func (r rules) Match(name string) any { // We want the last match to win, so we'll iterate in reverse order. - for i := len(r) - 1; i >= 0; i-- { - if r[i].compiled.Match(name) { - return r[i].value + for _, v := range slices.Backward(r) { + if v.compiled.Match(name) { + return v.value } } return nil @@ -83,9 +84,9 @@ func (r rules) Match(name string) any { // at last, or nil if none match. func (r rules) MatchWithSuffix(name, suffix string) any { // We want the last match to win, so we'll iterate in reverse order. - for i := len(r) - 1; i >= 0; i-- { - if r[i].compiled.Match(name) && (r[i].patternSuffix == "" || r[i].patternSuffix == suffix) { - return r[i].value + for _, v := range slices.Backward(r) { + if v.compiled.Match(name) && (v.patternSuffix == "" || v.patternSuffix == suffix) { + return v.value } } return nil diff --git a/lib/go.mod b/lib/go.mod index e2c926ec8d..4d78442098 100644 --- a/lib/go.mod +++ b/lib/go.mod @@ -1,85 +1,82 @@ module github.com/sourcegraph/sourcegraph/lib -go 1.26.10 +go 1.27.3 require ( github.com/Masterminds/semver v1.5.0 - github.com/charmbracelet/glamour v0.10.0 + github.com/charmbracelet/glamour v1.0.0 github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834 - github.com/cockroachdb/errors v1.12.0 - github.com/cockroachdb/redact v1.1.6 + github.com/cockroachdb/errors v1.14.0 + github.com/cockroachdb/redact v1.1.8 github.com/ghodss/yaml v1.0.0 github.com/gobwas/glob v0.2.3 github.com/google/go-cmp v0.7.0 github.com/grafana/regexp v0.0.0-20250905093917-f7b3be9d1853 - github.com/jackc/pgx/v5 v5.9.2 - github.com/klauspost/pgzip v1.2.6 - github.com/mattn/go-isatty v0.0.20 - github.com/mattn/go-runewidth v0.0.19 + github.com/jackc/pgx/v5 v5.11.0 + github.com/klauspost/pgzip v1.3.0 + github.com/mattn/go-isatty v0.0.24 + github.com/mattn/go-runewidth v0.0.31 github.com/moby/term v0.5.2 github.com/muesli/termenv v0.16.0 - github.com/scip-code/scip/bindings/go/scip v0.7.0 + github.com/scip-code/scip/bindings/go/scip v0.10.0 github.com/sourcegraph/conc v0.3.0 - github.com/sourcegraph/go-diff v0.7.0 - github.com/sourcegraph/log v0.0.0-20250923023806-517b6960b55b - github.com/stretchr/testify v1.11.1 - github.com/urfave/cli/v3 v3.8.0 + github.com/sourcegraph/go-diff v0.9.0 + github.com/sourcegraph/log v0.0.0-20260714115934-b104ff56b299 + github.com/stretchr/testify v1.12.1 + github.com/urfave/cli/v3 v3.14.0 github.com/xeipuuv/gojsonschema v1.2.0 github.com/xlab/treeprint v1.2.0 - go.opentelemetry.io/otel v1.43.0 - golang.org/x/sys v0.48.0 - golang.org/x/term v0.46.0 - google.golang.org/protobuf v1.36.10 + go.opentelemetry.io/otel v1.47.0 + golang.org/x/sys v0.49.0 + golang.org/x/term v0.47.0 + google.golang.org/protobuf v1.36.12 gopkg.in/yaml.v3 v3.0.1 ) require ( - github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c // indirect - github.com/alecthomas/chroma/v2 v2.14.0 // indirect + github.com/Azure/go-ansiterm v0.0.0-20261013165250-51075c6ea6bc // indirect + github.com/alecthomas/chroma/v2 v2.27.0 // indirect github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect github.com/aymerick/douceur v0.2.0 // indirect - github.com/benbjohnson/clock v1.3.5 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect - github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect - github.com/charmbracelet/x/ansi v0.8.0 // indirect - github.com/charmbracelet/x/cellbuf v0.0.13 // indirect - github.com/charmbracelet/x/exp/slice v0.0.0-20250327172914-2fdc97757edf // indirect - github.com/charmbracelet/x/term v0.2.1 // indirect - github.com/clipperhouse/uax29/v2 v2.2.0 // indirect - github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect - github.com/davecgh/go-spew v1.1.1 // indirect - github.com/dlclark/regexp2 v1.11.0 // indirect - github.com/fatih/color v1.18.0 // indirect - github.com/getsentry/sentry-go v0.27.0 // indirect + github.com/charmbracelet/colorprofile v0.4.3 // indirect + github.com/charmbracelet/x/ansi v0.11.9 // indirect + github.com/charmbracelet/x/cellbuf v0.0.15 // indirect + github.com/charmbracelet/x/exp/slice v0.1.0 // indirect + github.com/charmbracelet/x/term v0.2.2 // indirect + github.com/clipperhouse/displaywidth v0.11.0 // indirect + github.com/clipperhouse/uax29/v2 v2.7.0 // indirect + github.com/cockroachdb/logtags v0.0.0-20241215232642-bb51bb14a506 // indirect + github.com/dlclark/regexp2/v2 v2.12.0 // indirect + github.com/fatih/color v1.19.0 // indirect + github.com/getsentry/sentry-go v0.50.0 // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/google/uuid v1.6.0 // indirect github.com/gorilla/css v1.0.1 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect - github.com/klauspost/compress v1.18.7 // indirect + github.com/klauspost/compress v1.20.3 // indirect github.com/kr/pretty v0.3.1 // indirect github.com/kr/text v0.2.0 // indirect - github.com/lucasb-eyer/go-colorful v1.2.0 // indirect - github.com/mattn/go-colorable v0.1.14 // indirect + github.com/lucasb-eyer/go-colorful v1.4.1 // indirect + github.com/mattn/go-colorable v0.1.16 // indirect github.com/microcosm-cc/bluemonday v1.0.27 // indirect github.com/muesli/reflow v0.3.0 // indirect github.com/pkg/errors v0.9.1 // indirect - github.com/pmezard/go-difflib v1.0.0 // indirect github.com/rivo/uniseg v0.4.7 // indirect - github.com/rogpeppe/go-internal v1.14.1 // indirect + github.com/rogpeppe/go-internal v1.16.0 // indirect github.com/sourcegraph/beaut v0.0.0-20240611013027-627e4c25335a // indirect - github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f // indirect + github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect - github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect - github.com/yuin/goldmark v1.7.8 // indirect - github.com/yuin/goldmark-emoji v1.0.5 // indirect - go.uber.org/atomic v1.11.0 // indirect - go.uber.org/goleak v1.3.0 // indirect + github.com/xo/terminfo v1.3.0 // indirect + github.com/yuin/goldmark v1.8.7 // indirect + github.com/yuin/goldmark-emoji v1.0.6 // indirect + go.uber.org/atomic v1.12.0 // indirect go.uber.org/multierr v1.11.0 // indirect - go.uber.org/zap v1.24.0 // indirect - golang.org/x/exp v0.0.0-20230713183714-613f0c0eb8a1 // indirect - golang.org/x/net v0.60.0 // indirect - golang.org/x/text v0.42.0 // indirect + go.uber.org/zap v1.28.0 // indirect + go.yaml.in/yaml/v3 v3.0.5 // indirect + golang.org/x/net v0.62.0 // indirect + golang.org/x/text v0.43.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect ) diff --git a/lib/go.sum b/lib/go.sum index 07558ed82c..be98a3cf3a 100644 --- a/lib/go.sum +++ b/lib/go.sum @@ -1,66 +1,63 @@ -github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg= -github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= +github.com/Azure/go-ansiterm v0.0.0-20261013165250-51075c6ea6bc h1:58s5YzGPNAP7+e1uemaL0ax/NPSeJOHdRpRIowd+JDk= +github.com/Azure/go-ansiterm v0.0.0-20261013165250-51075c6ea6bc/go.mod h1:DMNF6Kxv+EcuUvVuNkvC3f+BjEEmc/Fn9aU+qiD8zpU= github.com/Masterminds/semver v1.5.0 h1:H65muMkzWKEuNDnfl9d70GUjFniHKHRbFPGBuZ3QEww= github.com/Masterminds/semver v1.5.0/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y= -github.com/alecthomas/assert/v2 v2.7.0 h1:QtqSACNS3tF7oasA8CU6A6sXZSBDqnm7RfpLl9bZqbE= -github.com/alecthomas/assert/v2 v2.7.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k= -github.com/alecthomas/chroma/v2 v2.14.0 h1:R3+wzpnUArGcQz7fCETQBzO5n9IMNi13iIs46aU4V9E= -github.com/alecthomas/chroma/v2 v2.14.0/go.mod h1:QolEbTfmUHIMVpBqxeDnNBj2uoeI4EbYP4i6n68SG4I= -github.com/alecthomas/repr v0.4.0 h1:GhI2A8MACjfegCPVq9f1FLvIBS+DrQ2KQBFZP1iFzXc= -github.com/alecthomas/repr v0.4.0/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4= +github.com/alecthomas/assert/v2 v2.11.0 h1:2Q9r3ki8+JYXvGsDyBXwH3LcJ+WK5D0gc5E8vS6K3D0= +github.com/alecthomas/assert/v2 v2.11.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k= +github.com/alecthomas/chroma/v2 v2.27.0 h1:FodwmyOBgJULFYmDqibcp9pvfDLWdtPRh9v/r5BXYZs= +github.com/alecthomas/chroma/v2 v2.27.0/go.mod h1:NjJ3ciIgrqBNeIkWZ4e46nseoLDslxU1LmfCoL+wcY8= +github.com/alecthomas/repr v0.5.2 h1:SU73FTI9D1P5UNtvseffFSGmdNci/O6RsqzeXJtP0Qs= +github.com/alecthomas/repr v0.5.2/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4= github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k= github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8= github.com/aymanbagabas/go-udiff v0.2.0 h1:TK0fH4MteXUDspT88n8CKzvK0X9O2xu9yQjWpi6yML8= github.com/aymanbagabas/go-udiff v0.2.0/go.mod h1:RE4Ex0qsGkTAJoQdQQCA0uG+nAzJO/pI/QwceO5fgrA= github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk= github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4= -github.com/benbjohnson/clock v1.3.5 h1:VvXlSJBzZpA/zum6Sj74hxwYI2DIxRWuNIoXAzHZz5o= -github.com/benbjohnson/clock v1.3.5/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= -github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc h1:4pZI35227imm7yK2bGPcfpFEmuY1gc2YSTShr4iJBfs= -github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc/go.mod h1:X4/0JoqgTIPSFcRA/P6INZzIuyqdFY5rm8tb41s9okk= -github.com/charmbracelet/glamour v0.10.0 h1:MtZvfwsYCx8jEPFJm3rIBFIMZUfUJ765oX8V6kXldcY= -github.com/charmbracelet/glamour v0.10.0/go.mod h1:f+uf+I/ChNmqo087elLnVdCiVgjSKWuXa/l6NU2ndYk= +github.com/charmbracelet/colorprofile v0.4.3 h1:QPa1IWkYI+AOB+fE+mg/5/4HRMZcaXex9t5KX76i20Q= +github.com/charmbracelet/colorprofile v0.4.3/go.mod h1:/zT4BhpD5aGFpqQQqw7a+VtHCzu+zrQtt1zhMt9mR4Q= +github.com/charmbracelet/glamour v1.0.0 h1:AWMLOVFHTsysl4WV8T8QgkQ0s/ZNZo7CiE4WKhk8l08= +github.com/charmbracelet/glamour v1.0.0/go.mod h1:DSdohgOBkMr2ZQNhw4LZxSGpx3SvpeujNoXrQyH2hxo= github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834 h1:ZR7e0ro+SZZiIZD7msJyA+NjkCNNavuiPBLgerbOziE= github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834/go.mod h1:aKC/t2arECF6rNOnaKaVU6y4t4ZeHQzqfxedE/VkVhA= -github.com/charmbracelet/x/ansi v0.8.0 h1:9GTq3xq9caJW8ZrBTe0LIe2fvfLR/bYXKTx2llXn7xE= -github.com/charmbracelet/x/ansi v0.8.0/go.mod h1:wdYl/ONOLHLIVmQaxbIYEC/cRKOQyjTkowiI4blgS9Q= -github.com/charmbracelet/x/cellbuf v0.0.13 h1:/KBBKHuVRbq1lYx5BzEHBAFBP8VcQzJejZ/IA3iR28k= -github.com/charmbracelet/x/cellbuf v0.0.13/go.mod h1:xe0nKWGd3eJgtqZRaN9RjMtK7xUYchjzPr7q6kcvCCs= +github.com/charmbracelet/x/ansi v0.11.9 h1:kIrqLBxtTVbLyyHO2Evoi93EjQo1mylWmpNEsfPxXAM= +github.com/charmbracelet/x/ansi v0.11.9/go.mod h1:DG/hpOnaI2QJ/KMMqLL2h0KVhluuJLazf8973P+Vy5w= +github.com/charmbracelet/x/cellbuf v0.0.15 h1:ur3pZy0o6z/R7EylET877CBxaiE1Sp1GMxoFPAIztPI= +github.com/charmbracelet/x/cellbuf v0.0.15/go.mod h1:J1YVbR7MUuEGIFPCaaZ96KDl5NoS0DAWkskup+mOY+Q= github.com/charmbracelet/x/exp/golden v0.0.0-20240806155701-69247e0abc2a h1:G99klV19u0QnhiizODirwVksQB91TJKV/UaTnACcG30= github.com/charmbracelet/x/exp/golden v0.0.0-20240806155701-69247e0abc2a/go.mod h1:wDlXFlCrmJ8J+swcL/MnGUuYnqgQdW9rhSD61oNMb6U= -github.com/charmbracelet/x/exp/slice v0.0.0-20250327172914-2fdc97757edf h1:rLG0Yb6MQSDKdB52aGX55JT1oi0P0Kuaj7wi1bLUpnI= -github.com/charmbracelet/x/exp/slice v0.0.0-20250327172914-2fdc97757edf/go.mod h1:B3UgsnsBZS/eX42BlaNiJkD1pPOUa+oF1IYC6Yd2CEU= -github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ= -github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg= -github.com/clipperhouse/uax29/v2 v2.2.0 h1:ChwIKnQN3kcZteTXMgb1wztSgaU+ZemkgWdohwgs8tY= -github.com/clipperhouse/uax29/v2 v2.2.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM= -github.com/cockroachdb/errors v1.12.0 h1:d7oCs6vuIMUQRVbi6jWWWEJZahLCfJpnJSVobd1/sUo= -github.com/cockroachdb/errors v1.12.0/go.mod h1:SvzfYNNBshAVbZ8wzNc/UPK3w1vf0dKDUP41ucAIf7g= -github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b h1:r6VH0faHjZeQy818SGhaone5OnYfxFR/+AzdY3sf5aE= -github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= -github.com/cockroachdb/redact v1.1.6 h1:zXJBwDZ84xJNlHl1rMyCojqyIxv+7YUpQiJLQ7n4314= -github.com/cockroachdb/redact v1.1.6/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= +github.com/charmbracelet/x/exp/slice v0.1.0 h1:m46dwuDf3M5SFYMRhxYkLC6z9WnENGVKbcbJlp13/og= +github.com/charmbracelet/x/exp/slice v0.1.0/go.mod h1:vqEfX6xzqW1pKKZUUiFOKg0OQ7bCh54Q2vR/tserrRA= +github.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk= +github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI= +github.com/clipperhouse/displaywidth v0.11.0 h1:lBc6kY44VFw+TDx4I8opi/EtL9m20WSEFgwIwO+UVM8= +github.com/clipperhouse/displaywidth v0.11.0/go.mod h1:bkrFNkf81G8HyVqmKGxsPufD3JhNl3dSqnGhOoSD/o0= +github.com/clipperhouse/uax29/v2 v2.7.0 h1:+gs4oBZ2gPfVrKPthwbMzWZDaAFPGYK72F0NJv2v7Vk= +github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM= +github.com/cockroachdb/errors v1.14.0 h1:EfdVEJpN3z8rPMo43Yit59LxoiIa470fSXpZXuEs+ZI= +github.com/cockroachdb/errors v1.14.0/go.mod h1:xRa70jZ9sNBQmISt5KmJmAD++E4dQHm89oCRiZGEdq0= +github.com/cockroachdb/logtags v0.0.0-20241215232642-bb51bb14a506 h1:ASDL+UJcILMqgNeV5jiqR4j+sTuvQNHdf2chuKj1M5k= +github.com/cockroachdb/logtags v0.0.0-20241215232642-bb51bb14a506/go.mod h1:Mw7HqKr2kdtu6aYGn3tPmAftiP3QPX63LdK/zcariIo= +github.com/cockroachdb/redact v1.1.8 h1:8eVLLj6juKxiKrAEw2b8cJvNqWq++U8WOfQFuL7KTaA= +github.com/cockroachdb/redact v1.1.8/go.mod h1:GceHHpJ0rMDpYARL5In88Alq/xMBUtVlz7Qxix6ZVkw= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/creack/pty v1.1.18 h1:n56/Zwd5o6whRC5PMGretI4IdRLlmBXYNjScPaBgsbY= github.com/creack/pty v1.1.18/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI= -github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= -github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM= -github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU= -github.com/getsentry/sentry-go v0.27.0 h1:Pv98CIbtB3LkMWmXi4Joa5OOcwbmnX88sF5qbK3r3Ps= -github.com/getsentry/sentry-go v0.27.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= +github.com/dlclark/regexp2/v2 v2.12.0 h1:GsCgDZZeHluUDHASr2yqQonZk4Tma5LFmLH9CSsFFEE= +github.com/dlclark/regexp2/v2 v2.12.0/go.mod h1:avUrQvPaLz2DrFNHJF0taWAFFX2C1GMSSoeiqFjcBmU= +github.com/fatih/color v1.19.0 h1:Zp3PiM21/9Ld6FzSKyL5c/BULoe/ONr9KlbYVOfG8+w= +github.com/fatih/color v1.19.0/go.mod h1:zNk67I0ZUT1bEGsSGyCZYZNrHuTkJJB+r6Q9VuMi0LE= +github.com/getsentry/sentry-go v0.50.0 h1:gkO59rn/i0RCAXUUTflC5QVbTQGPXbaFabs2olVzc9g= +github.com/getsentry/sentry-go v0.50.0/go.mod h1:+xsDuN+SoRN/xfs1hdq78wnrE3omIZf+FCuh9FOW1C8= github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA= github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og= github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y= github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8= github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= -github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= @@ -72,39 +69,39 @@ github.com/gorilla/css v1.0.1/go.mod h1:BvnYkspnSzMmwRK+b8/xgNPLiIuNZr6vbZBTPQ2A github.com/grafana/regexp v0.0.0-20250905093917-f7b3be9d1853 h1:cLN4IBkmkYZNnk7EAJ0BHIethd+J6LqxFNw5mSiI2bM= github.com/grafana/regexp v0.0.0-20250905093917-f7b3be9d1853/go.mod h1:+JKpmjMGhpgPL+rXZ5nsZieVzvarn86asRlBg4uNGnk= github.com/hexops/autogold v1.3.1 h1:YgxF9OHWbEIUjhDbpnLhgVsjUDsiHDTyDfy2lrfdlzo= -github.com/hexops/autogold/v2 v2.0.3 h1:zyrfTlNfyxLpX/zuk8wjTeTYP5AXaFeeRYFEZfHPwao= -github.com/hexops/autogold/v2 v2.0.3/go.mod h1:cYVc0tJn6v9Uf9xMOHvmH6scuTxsVJSxGcKR/yOVPzY= +github.com/hexops/autogold/v2 v2.3.1 h1:GcDwp9TkPkDG/wVodudePKPG8HbvEA8o8Z9hySIuAC4= +github.com/hexops/autogold/v2 v2.3.1/go.mod h1:1vQ1sj0yXQNn8VOlQeefQPXTLr9Qy9cf8pMDanZ4Gmo= github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM= github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg= -github.com/hexops/valast v1.4.3 h1:oBoGERMJh6UZdRc6cduE1CTPK+VAdXA59Y1HFgu3sm0= -github.com/hexops/valast v1.4.3/go.mod h1:Iqx2kLj3Jn47wuXpj3wX40xn6F93QNFBHuiKBerkTGA= +github.com/hexops/valast v1.5.0 h1:FBTuvVi0wjTngtXJRZXMbkN/Dn6DgsUsBwch2DUJU8Y= +github.com/hexops/valast v1.5.0/go.mod h1:Jcy1pNH7LNraVaAZDLyv21hHg2WBv9Nf9FL6fGxU7o4= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= -github.com/jackc/pgx/v5 v5.9.2 h1:3ZhOzMWnR4yJ+RW1XImIPsD1aNSz4T4fyP7zlQb56hw= -github.com/jackc/pgx/v5 v5.9.2/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= +github.com/jackc/pgx/v5 v5.11.0 h1:IzBBtyK9AHqf98cctWFifYSci2hgQR/cd56wB4p+ogg= +github.com/jackc/pgx/v5 v5.11.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= -github.com/klauspost/compress v1.18.7 h1:aUyZsS4kH3QTKurYhAOwAHxllVPnOthb3vPfnF1Ehjw= -github.com/klauspost/compress v1.18.7/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= -github.com/klauspost/pgzip v1.2.6 h1:8RXeL5crjEUFnR2/Sn6GJNWtSQ3Dk8pq4CL3jvdDyjU= -github.com/klauspost/pgzip v1.2.6/go.mod h1:Ch1tH69qFZu15pkjo5kYi6mth2Zzwzt50oCQKQE9RUs= +github.com/klauspost/compress v1.20.3 h1:zWNoFqq/lSuYQRim3dUXlXeA0IqwuZGicdG5ZTfY5j4= +github.com/klauspost/compress v1.20.3/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= +github.com/klauspost/pgzip v1.3.0 h1:8t+KjjzD/0n/8vNlJGGZmTeK4njuwffOQvJm8tOSc8o= +github.com/klauspost/pgzip v1.3.0/go.mod h1:Xx7tAv5DH8ObLHUDQKXoE/nd8i/FYdNDTVMvi3SLTKI= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= -github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= -github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= -github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE= -github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= -github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= -github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/lucasb-eyer/go-colorful v1.4.1 h1:1EO+WB73+EH8EVbzlrG3KLAfEypQWVHIBqlTf+2hNss= +github.com/lucasb-eyer/go-colorful v1.4.1/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= +github.com/mattn/go-colorable v0.1.16 h1:+2YjeAe7xP1OQbZW1jERPWWCDLlNqFNCvjiqGiAt84A= +github.com/mattn/go-colorable v0.1.16/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= +github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI= +github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk= -github.com/mattn/go-runewidth v0.0.19 h1:v++JhqYnZuu5jSKrk9RbgF5v4CGUjqRfBm05byFGLdw= -github.com/mattn/go-runewidth v0.0.19/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs= +github.com/mattn/go-runewidth v0.0.31 h1:1oCV4ReTlosDBc6rYRw5cL8S/4y8iv5oRl4SJ5IBgwo= +github.com/mattn/go-runewidth v0.0.31/go.mod h1:3qAiGCV4Koz/yuveO58qUefmUTRm8r0IGEXZ9jeHp/8= github.com/microcosm-cc/bluemonday v1.0.27 h1:MpEUotklkwCSLeH+Qdx1VJgNqLlpY2KXwXFM08ygZfk= github.com/microcosm-cc/bluemonday v1.0.27/go.mod h1:jFi9vgW+H7c3V0lb6nR74Ib/DIB5OBs92Dimizgw2cA= github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ= @@ -120,68 +117,65 @@ github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTw github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= -github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= -github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= -github.com/scip-code/scip/bindings/go/scip v0.7.0 h1:on80ynl7eSovvMUy3uxWkJm+kepsVjIwI2byIeMZego= -github.com/scip-code/scip/bindings/go/scip v0.7.0/go.mod h1:XC4dP3um0lKaSDRFIMwYlkBjFxKy1Rw7xFt6KDtRjAk= -github.com/shurcooL/go v0.0.0-20180423040247-9e1955d9fb6e/go.mod h1:TDJrrUr11Vxrven61rcy3hJMUqaf/CLWYhHNPmT14Lk= -github.com/shurcooL/go-goon v0.0.0-20170922171312-37c2f522c041/go.mod h1:N5mDOmsrJOB+vfqUK+7DmDyjhSLIIBnXo9lvZJj3MWQ= +github.com/rogpeppe/go-internal v1.16.0 h1:O9DK+vNMDVGLr2BeZqmpLeMjiMNkuXfcqntWbZV6S5g= +github.com/rogpeppe/go-internal v1.16.0/go.mod h1:DrUVZyrJU+txYW5/1kwtXQSMFio52ZOxX7yM1VHvnxs= +github.com/scip-code/scip/bindings/go/scip v0.10.0 h1:X7jaN76WK8WqU4/eTn1KyeaUEStvn4jdgW/NuzLzsPE= +github.com/scip-code/scip/bindings/go/scip v0.10.0/go.mod h1:4LGKCH2Vx61a1sWwq8bp5HGb7F/0qJMrAOEh0XdKKlc= github.com/sourcegraph/beaut v0.0.0-20240611013027-627e4c25335a h1:j/CQ27s679M9wRGBRJYyXGrfkYuQA6VMnD7R08mHD9c= github.com/sourcegraph/beaut v0.0.0-20240611013027-627e4c25335a/go.mod h1:JG1sdvGTKWwe/oH3/3UKQ26vfcHIN//7fwEJhoqaBcM= github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo= github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0= -github.com/sourcegraph/go-diff v0.7.0 h1:9uLlrd5T46OXs5qpp8L/MTltk0zikUGi0sNNyCpA8G0= -github.com/sourcegraph/go-diff v0.7.0/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= -github.com/sourcegraph/log v0.0.0-20250923023806-517b6960b55b h1:2FQ72y5zECMu9e5z5jMnllb5n1jVK7qsvgjkVtdFV+g= -github.com/sourcegraph/log v0.0.0-20250923023806-517b6960b55b/go.mod h1:IDp09QkoqS8Z3CyN2RW6vXjgABkNpDbyjLIHNQwQ8P8= +github.com/sourcegraph/go-diff v0.9.0 h1:7xcVsayWHhvxZGrqt1o89vvBApCa4nyCgO7tNxDHJ+Q= +github.com/sourcegraph/go-diff v0.9.0/go.mod h1:hWlcO7Al+UZStZAP8rBumHpCK5ZHQ5BXsMls8p4+F5E= +github.com/sourcegraph/log v0.0.0-20260714115934-b104ff56b299 h1:iz6aHysi3F76ZlZsr4wCvTv9dkBqFlAmzQRlFeXCodY= +github.com/sourcegraph/log v0.0.0-20260714115934-b104ff56b299/go.mod h1:zxfuHzECDpM0+i+IAuZtWIfxySXq7qzH7hcIYe/elw0= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152 h1:z/MpntplPaW6QW95pzcAR/72Z5TWDyDnSo0EOcyij9o= github.com/sourcegraph/yaml v1.0.1-0.20200714132230-56936252f152/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= -github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= -github.com/urfave/cli/v3 v3.8.0 h1:XqKPrm0q4P0q5JpoclYoCAv0/MIvH/jZ2umzuf8pNTI= -github.com/urfave/cli/v3 v3.8.0/go.mod h1:ysVLtOEmg2tOy6PknnYVhDoouyC/6N42TMeoMzskhso= -github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f h1:J9EGpcZtP0E/raorCMxlFGSTBrsSlaDGf3jU/qvAE2c= +github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= +github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= +github.com/urfave/cli/v3 v3.14.0 h1:a8414NQlHJs0c/iBsulKLzlES0n/lEAskbL2LKpU4/s= +github.com/urfave/cli/v3 v3.14.0/go.mod h1:vXn6HxPNccJSzQr2QvwVncOKrgYGIHU0HY5h8B2nQj4= github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= +github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb h1:zGWFAtiMcyryUHoUjUJX0/lt1H2+i2Ka2n+D3DImSNo= +github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0= github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74= github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y= github.com/xlab/treeprint v1.2.0 h1:HzHnuAF1plUN2zGlAFHbSQP2qJ0ZAD3XF5XD7OesXRQ= github.com/xlab/treeprint v1.2.0/go.mod h1:gj5Gd3gPdKtR1ikdDK6fnFLdmIS0X30kTTuNd/WEJu0= -github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no= -github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM= +github.com/xo/terminfo v1.3.0 h1:KstyePbNW6UaLq9y12+544VK4aTP3Eku/sym3a9+UgQ= +github.com/xo/terminfo v1.3.0/go.mod h1:lGzkSo8Fe7IRh/w+Gqz7n5mDog4FVXCj3gy/DYTBqio= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.7.1/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E= -github.com/yuin/goldmark v1.7.8 h1:iERMLn0/QJeHFhxSt3p6PeN9mGnvIKSpG9YYorDMnic= -github.com/yuin/goldmark v1.7.8/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E= -github.com/yuin/goldmark-emoji v1.0.5 h1:EMVWyCGPlXJfUXBXpuMu+ii3TIaxbVBnEX9uaDC4cIk= -github.com/yuin/goldmark-emoji v1.0.5/go.mod h1:tTkZEbwu5wkPmgTcitqddVxY9osFZiavD+r4AzQrh1U= -go.opentelemetry.io/otel v1.43.0 h1:mYIM03dnh5zfN7HautFE4ieIig9amkNANT+xcVxAj9I= -go.opentelemetry.io/otel v1.43.0/go.mod h1:JuG+u74mvjvcm8vj8pI5XiHy1zDeoCS2LB1spIq7Ay0= -go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= -go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= +github.com/yuin/goldmark v1.8.7 h1:XT/tNqCIbabh0ln675w4x3dv04kQBKi8NwYqi9IJaxI= +github.com/yuin/goldmark v1.8.7/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg= +github.com/yuin/goldmark-emoji v1.0.6 h1:QWfF2FYaXwL74tfGOW5izeiZepUDroDJfWubQI9HTHs= +github.com/yuin/goldmark-emoji v1.0.6/go.mod h1:ukxJDKFpdFb5x0a5HqbdlcKtebh086iJpI31LTKmWuA= +go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM= +go.opentelemetry.io/otel v1.47.0/go.mod h1:8wS9O2qfXrYrzp6hIF/HOYJJf/wIhFPhR2xLuP+iXQU= +go.uber.org/atomic v1.12.0 h1:BvcXdFKuviU4fTL/f+SxdQ5qJX/Jix8pAkgdUcb3XOE= +go.uber.org/atomic v1.12.0/go.mod h1:I6c4cg+6HCxRjfjSsYtApoFILnpc0CGUdGkXVqbYVNk= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= -go.uber.org/zap v1.24.0 h1:FiJd5l1UOLj0wCgbSE0rwwXHzEdAZS6hiiSnxJN/D60= -go.uber.org/zap v1.24.0/go.mod h1:2kMP+WWQ8aoFoedH3T2sq6iJ2yDWpHbP0f6MQbS9Gkg= +go.uber.org/zap v1.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo= +go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q= +go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= +go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/exp v0.0.0-20230713183714-613f0c0eb8a1 h1:MGwJjxBy0HJshjDNfLsYO8xppfqWlA5ZT9OhtUUhTNw= -golang.org/x/exp v0.0.0-20230713183714-613f0c0eb8a1/go.mod h1:FXUEEKJgO7OQYeo8N01OfiKP8RXMtf6e8aTskBGqWdc= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c= @@ -190,38 +184,36 @@ golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU= -golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= +golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= +golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk= -golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= +golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= -golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= -golang.org/x/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE= -golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc= +golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= +golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/term v0.47.0 h1:cpyOwQkr2Nzxe2p6KnrTG7Ei2wtzjsuSjhpXXepZ/BM= +golang.org/x/term v0.47.0/go.mod h1:efAfAuG6RKABvg1ArGebRkvX6LXul14SM67o2e4mUCY= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= -golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E= +golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc= +golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI= -golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo= +golang.org/x/tools v0.51.0 h1:k4Xc/1Om9jwkBJBo4NVLMSARBoWtK10mx+W5BnXCeAI= +golang.org/x/tools v0.51.0/go.mod h1:9eEncMayCV6zRMGhR5eZEC2iBx98qWcF1HZ9Z7wJOoA= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= -google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc= +google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= @@ -231,7 +223,7 @@ gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -mvdan.cc/gofumpt v0.4.0 h1:JVf4NN1mIpHogBj7ABpgOyZc65/UUOkKQFkoURsz4MM= -mvdan.cc/gofumpt v0.4.0/go.mod h1:PljLOHDeZqgS8opHRKLzp2It2VBuSdteAgqUfzMTxlQ= -pgregory.net/rapid v1.1.0 h1:CMa0sjHSru3puNx+J0MIAuiiEV4N0qj8/cMWGBBCsjw= -pgregory.net/rapid v1.1.0/go.mod h1:PY5XlDGj0+V1FCq0o192FdRhpKHGTRIWBgqjDBTrq04= +mvdan.cc/gofumpt v0.10.0 h1:yGGpRS2pBN2OQIi7b21IXknJna7faPkFaVfHLrN6Euo= +mvdan.cc/gofumpt v0.10.0/go.mod h1:sU2ElXHzOEmvoPqfutYG7uunlueR4K2T1JFml40SzP4= +pgregory.net/rapid v1.3.0 h1:vBvO0VSqti75J1jjYqpgPNBLKMd1+gxa9fYo7vk/Exc= +pgregory.net/rapid v1.3.0/go.mod h1:dPlE4OBBxgXPqkP79flB6sJL1dx5azpI7HQ9MY9Z7uk= diff --git a/mise.toml b/mise.toml index e8cfe85732..65c03f6d54 100644 --- a/mise.toml +++ b/mise.toml @@ -1,4 +1,4 @@ [tools] -golang = "1.26.10" -shfmt = "3.8.0" -shellcheck = "0.10.0" +golang = "1.27.3" +shfmt = "3.14.1" +shellcheck = "0.11.0" From 72b0ca2f70742c7da2bb691500c25a2a0fe785de Mon Sep 17 00:00:00 2001 From: Marc <7050295+marcleblanc2@users.noreply.github.com> Date: Tue, 3 Nov 2026 16:31:53 -0600 Subject: [PATCH 634/647] ci: fix build cache, drop duplicated test run (#1385) * ci: cache Go modules and build output per job, drop redundant test pass Every CI run compiled the whole dependency tree from scratch on all three OSes, because: - goreleaser-check ran setup-go without ever building anything, so it finished first and saved a 7 KB cache under the key that go-lint and go-test on Linux then restored ('cache hit', never re-saved). - setup-go's built-in cache has no restore-keys, so any go.sum change (every renovate PR) started cold on macOS and Windows too. - go-ci ran 'go test -race' and then 'go test' again, recompiling everything without race instrumentation to rerun the same tests. Now each job owns its cache key (job, OS, arch, Go version, go.sum hash) with a prefix fallback, goreleaser-check no longer installs Go, and the test job runs the race pass only. Amp-Thread-ID: https://ampcode.com/threads/T-01a18b5c-c5bb-7497-82f1-3e9333c8b7e1 Co-authored-by: Amp * test: run the batch spec upload tests under -race again The upload tests were tagged //go:build !race in #1082 because testify fmt-prints every recorded mock argument, and printing a bare *io.PipeReader reflects into the pipe's internals while the producer goroutine writes to it. The Windows variant never got the tag, so 'go test -race' has been failing on Windows the whole time, hidden because the step runs under pwsh, which does not fail on a non-zero exit in the middle of a multi-line script; the second non-race pass then went green. The mock client now wraps the body in a RequestBody struct, so fmt prints the pointer address instead of walking the pipe. That removes the need for the !race tag and for the second test pass. uploadFile also starts the writer goroutine only after NewHTTPRequest succeeds; before, an error there leaked a goroutine blocked forever on a pipe nobody reads. Amp-Thread-ID: https://ampcode.com/threads/T-01a18b5c-c5bb-7497-82f1-3e9333c8b7e1 Co-authored-by: Amp --------- Co-authored-by: Amp --- .github/workflows/go-ci.yml | 30 ++++++++++++++++--- .github/workflows/go-lint.yml | 19 +++++++++++- .github/workflows/goreleaser-check.yml | 11 ++----- internal/api/mock/api.go | 8 ++++- internal/batches/service/remote.go | 15 +++++----- ...e_norace_test.go => remote_upload_test.go} | 18 +++++------ .../batches/service/remote_windows_test.go | 2 +- 7 files changed, 70 insertions(+), 33 deletions(-) rename internal/batches/service/{remote_norace_test.go => remote_upload_test.go} (96%) diff --git a/.github/workflows/go-ci.yml b/.github/workflows/go-ci.yml index bbc30740a6..d11d734112 100644 --- a/.github/workflows/go-ci.yml +++ b/.github/workflows/go-ci.yml @@ -17,12 +17,34 @@ jobs: run: echo "go-version=$(grep 'golang' mise.toml | cut -d'"' -f2)" >> $GITHUB_OUTPUT shell: bash - name: Set up Go - uses: sourcegraph/actions/go-setup@main + uses: actions/setup-go@v7 with: go-version: ${{ steps.mise.outputs.go-version }} - - run: | - go test -race -v ./... - go test -v ./... + # setup-go's built-in cache keys on go.sum alone, has no fallback + # when go.sum changes, and shares one key across every job on the + # same OS, so the first job to finish (even one that compiled + # nothing) decides what everyone else restores. See the explicit + # cache step below instead. + cache: false + - name: Find Go cache directories + id: go-cache + shell: bash + run: | + echo "build=$(go env GOCACHE)" >> "$GITHUB_OUTPUT" + echo "modules=$(go env GOMODCACHE)" >> "$GITHUB_OUTPUT" + - name: Cache Go modules and build output + uses: actions/cache@v6 + with: + path: | + ${{ steps.go-cache.outputs.modules }} + ${{ steps.go-cache.outputs.build }} + key: ${{ github.job }}-${{ runner.os }}-${{ runner.arch }}-go${{ steps.mise.outputs.go-version }}-${{ hashFiles('**/go.sum') }} + restore-keys: | + ${{ github.job }}-${{ runner.os }}-${{ runner.arch }}-go${{ steps.mise.outputs.go-version }}- + # bash on every OS: the default pwsh on Windows does not fail the step + # when a command in a multi-line script exits non-zero. + - run: go test -race -v ./... + shell: bash # This job provides a stable name for branch protection rules # It will only pass if all Go CI matrix tests above pass diff --git a/.github/workflows/go-lint.yml b/.github/workflows/go-lint.yml index 90ba260b00..61a3b5ced0 100644 --- a/.github/workflows/go-lint.yml +++ b/.github/workflows/go-lint.yml @@ -14,7 +14,24 @@ jobs: id: mise run: echo "go-version=$(grep 'golang' mise.toml | cut -d'"' -f2)" >> $GITHUB_OUTPUT - name: Set up Go - uses: sourcegraph/actions/go-setup@main + uses: actions/setup-go@v7 with: go-version: ${{ steps.mise.outputs.go-version }} + # See go-ci.yml for why the built-in cache is off. + cache: false + - name: Find Go cache directories + id: go-cache + run: | + echo "build=$(go env GOCACHE)" >> "$GITHUB_OUTPUT" + echo "modules=$(go env GOMODCACHE)" >> "$GITHUB_OUTPUT" + - name: Cache Go modules, build output, and golangci-lint analysis + uses: actions/cache@v6 + with: + path: | + ${{ steps.go-cache.outputs.modules }} + ${{ steps.go-cache.outputs.build }} + ~/.cache/golangci-lint + key: ${{ github.job }}-${{ runner.os }}-${{ runner.arch }}-go${{ steps.mise.outputs.go-version }}-${{ hashFiles('**/go.sum') }} + restore-keys: | + ${{ github.job }}-${{ runner.os }}-${{ runner.arch }}-go${{ steps.mise.outputs.go-version }}- - run: ./dev/go-lint.sh diff --git a/.github/workflows/goreleaser-check.yml b/.github/workflows/goreleaser-check.yml index 443f131aa6..f13e721330 100644 --- a/.github/workflows/goreleaser-check.yml +++ b/.github/workflows/goreleaser-check.yml @@ -10,15 +10,8 @@ jobs: steps: - name: Checkout uses: actions/checkout@v7 - with: - fetch-depth: 0 - - name: Get Go version from mise - id: mise - run: echo "go-version=$(grep 'golang' mise.toml | cut -d'"' -f2)" >> $GITHUB_OUTPUT - - name: Set up Go - uses: sourcegraph/actions/go-setup@main - with: - go-version: ${{ steps.mise.outputs.go-version }} + # `goreleaser check` only parses the config; it needs neither Go nor + # git history. - name: Check GoReleaser config uses: goreleaser/goreleaser-action@v5 with: diff --git a/internal/api/mock/api.go b/internal/api/mock/api.go index 710b11aff6..f162408abc 100644 --- a/internal/api/mock/api.go +++ b/internal/api/mock/api.go @@ -34,8 +34,14 @@ func (m *Client) NewGzippedQuery(query string) api.Request { return args.Get(0).(api.Request) } +// RequestBody wraps the body handed to NewHTTPRequest. testify fmt-prints every +// recorded argument, and printing a bare *io.PipeReader reflects into the +// pipe's internals, racing with the goroutine writing to it. Behind a struct +// field, fmt prints the pointer's address instead. +type RequestBody struct{ io.Reader } + func (m *Client) NewHTTPRequest(ctx context.Context, method, path string, body io.Reader) (*http.Request, error) { - args := m.Called(ctx, method, path, body) + args := m.Called(ctx, method, path, RequestBody{body}) var obj *http.Request if args.Get(0) != nil { obj = args.Get(0).(*http.Request) diff --git a/internal/batches/service/remote.go b/internal/batches/service/remote.go index 89b3cd56c8..d8d0782ac4 100644 --- a/internal/batches/service/remote.go +++ b/internal/batches/service/remote.go @@ -175,8 +175,15 @@ func (svc *Service) uploadFile(ctx context.Context, workingDir, filePath, batchS pipeReader, pipeWriter := io.Pipe() multipartWriter := multipart.NewWriter(pipeWriter) + request, err := svc.client.NewHTTPRequest(ctx, http.MethodPost, fmt.Sprintf(".api/files/batch-changes/%s", batchSpecID), pipeReader) + if err != nil { + return err + } + request.Header.Set("Content-Type", multipartWriter.FormDataContentType()) + // Write in a separate goroutine to properly chunk the file content. Writing to the pipe lets us not have - // to put the whole file in memory. + // to put the whole file in memory. Started only once the request exists, so a NewHTTPRequest error + // doesn't leak a goroutine blocked on a pipe nobody reads. go func() { defer pipeWriter.Close() defer multipartWriter.Close() @@ -186,12 +193,6 @@ func (svc *Service) uploadFile(ctx context.Context, workingDir, filePath, batchS } }() - request, err := svc.client.NewHTTPRequest(ctx, http.MethodPost, fmt.Sprintf(".api/files/batch-changes/%s", batchSpecID), pipeReader) - if err != nil { - return err - } - request.Header.Set("Content-Type", multipartWriter.FormDataContentType()) - resp, err := svc.client.Do(request) if err != nil { // Errors passed to pipeWriter.CloseWithError come through here. diff --git a/internal/batches/service/remote_norace_test.go b/internal/batches/service/remote_upload_test.go similarity index 96% rename from internal/batches/service/remote_norace_test.go rename to internal/batches/service/remote_upload_test.go index c397175135..307f464c52 100644 --- a/internal/batches/service/remote_norace_test.go +++ b/internal/batches/service/remote_upload_test.go @@ -1,5 +1,3 @@ -//go:build !race - package service_test import ( @@ -48,7 +46,7 @@ func TestService_UploadBatchSpecWorkspaceFiles(t *testing.T) { req := httptest.NewRequest(http.MethodPost, "http://fake.com/.api/files/batch-changes/123", nil) client.On("NewHTTPRequest", mock.Anything, http.MethodPost, ".api/files/batch-changes/123", mock.Anything). Run(func(args mock.Arguments) { - req.Body = args[3].(*io.PipeReader) + req.Body = io.NopCloser(args[3].(mockclient.RequestBody)) }). Return(req, nil). Once() @@ -90,7 +88,7 @@ func TestService_UploadBatchSpecWorkspaceFiles(t *testing.T) { req := httptest.NewRequest(http.MethodPost, "http://fake.com/.api/files/batch-changes/123", nil) client.On("NewHTTPRequest", mock.Anything, http.MethodPost, ".api/files/batch-changes/123", mock.Anything). Run(func(args mock.Arguments) { - req.Body = args[3].(*io.PipeReader) + req.Body = io.NopCloser(args[3].(mockclient.RequestBody)) }). Return(req, nil). Once() @@ -132,7 +130,7 @@ func TestService_UploadBatchSpecWorkspaceFiles(t *testing.T) { req := httptest.NewRequest(http.MethodPost, "http://fake.com/.api/files/batch-changes/123", nil) client.On("NewHTTPRequest", mock.Anything, http.MethodPost, ".api/files/batch-changes/123", mock.Anything). Run(func(args mock.Arguments) { - req.Body = args[3].(*io.PipeReader) + req.Body = io.NopCloser(args[3].(mockclient.RequestBody)) }). Return(req, nil). Twice() @@ -180,7 +178,7 @@ func TestService_UploadBatchSpecWorkspaceFiles(t *testing.T) { req := httptest.NewRequest(http.MethodPost, "http://fake.com/.api/files/batch-changes/123", nil) client.On("NewHTTPRequest", mock.Anything, http.MethodPost, ".api/files/batch-changes/123", mock.Anything). Run(func(args mock.Arguments) { - req.Body = args[3].(*io.PipeReader) + req.Body = io.NopCloser(args[3].(mockclient.RequestBody)) }). Return(req, nil). Twice() @@ -229,7 +227,7 @@ func TestService_UploadBatchSpecWorkspaceFiles(t *testing.T) { req := httptest.NewRequest(http.MethodPost, "http://fake.com/.api/files/batch-changes/123", nil) client.On("NewHTTPRequest", mock.Anything, http.MethodPost, ".api/files/batch-changes/123", mock.Anything). Run(func(args mock.Arguments) { - req.Body = args[3].(*io.PipeReader) + req.Body = io.NopCloser(args[3].(mockclient.RequestBody)) }). Return(req, nil). Once() @@ -281,7 +279,7 @@ func TestService_UploadBatchSpecWorkspaceFiles(t *testing.T) { req := httptest.NewRequest(http.MethodPost, "http://fake.com/.api/files/batch-changes/123", nil) client.On("NewHTTPRequest", mock.Anything, http.MethodPost, ".api/files/batch-changes/123", mock.Anything). Run(func(args mock.Arguments) { - req.Body = args[3].(*io.PipeReader) + req.Body = io.NopCloser(args[3].(mockclient.RequestBody)) }). Return(req, nil). Times(3) @@ -362,7 +360,7 @@ func TestService_UploadBatchSpecWorkspaceFiles(t *testing.T) { req := httptest.NewRequest(http.MethodPost, "http://fake.com/.api/files/batch-changes/123", nil) client.On("NewHTTPRequest", mock.Anything, http.MethodPost, ".api/files/batch-changes/123", mock.Anything). Run(func(args mock.Arguments) { - req.Body = args[3].(*io.PipeReader) + req.Body = io.NopCloser(args[3].(mockclient.RequestBody)) }). Return(req, nil). Once() @@ -400,7 +398,7 @@ func TestService_UploadBatchSpecWorkspaceFiles(t *testing.T) { req := httptest.NewRequest(http.MethodPost, "http://fake.com/.api/files/batch-changes/123", nil) client.On("NewHTTPRequest", mock.Anything, http.MethodPost, ".api/files/batch-changes/123", mock.Anything). Run(func(args mock.Arguments) { - req.Body = args[3].(*io.PipeReader) + req.Body = io.NopCloser(args[3].(mockclient.RequestBody)) }). Return(req, nil). Once() diff --git a/internal/batches/service/remote_windows_test.go b/internal/batches/service/remote_windows_test.go index 9cbdc07182..649864f7d4 100644 --- a/internal/batches/service/remote_windows_test.go +++ b/internal/batches/service/remote_windows_test.go @@ -47,7 +47,7 @@ func TestService_UploadBatchSpecWorkspaceFiles_Windows_Path(t *testing.T) { req := httptest.NewRequest(http.MethodPost, "http://fake.com/.api/files/batch-changes/123", nil) client.On("NewHTTPRequest", mock.Anything, http.MethodPost, ".api/files/batch-changes/123", mock.Anything). Run(func(args mock.Arguments) { - req.Body = args[3].(*io.PipeReader) + req.Body = io.NopCloser(args[3].(mockclient.RequestBody)) }). Return(req, nil). Once() From 2cf148e9981264e3a13b4c8de80e26efbf3ef607 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 17:03:44 -0600 Subject: [PATCH 635/647] Update alpine:3.24 Docker digest to be26560 (#1388) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- Dockerfile | 2 +- Dockerfile.release | 2 +- docker/batch-change-volume-workspace/Dockerfile | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Dockerfile b/Dockerfile index 479d894d80..71366e2793 100644 --- a/Dockerfile +++ b/Dockerfile @@ -11,7 +11,7 @@ WORKDIR /src RUN go build ./cmd/src # This stage should be kept in sync with Dockerfile.release. -FROM alpine:3.24@sha256:ff7f0c727dd796aa36787bfcd9a64bf35a6ce72a73451b3359fde849b6703d63 +FROM alpine:3.24@sha256:be2656061b536c1883c4034790e21d0a09c5aaaf51968b89368a3c0371ea2c9a # needed for `src code-intel upload` and `src actions exec` # ca-certificates-bundle >= 20261020-r0 drops the eMudhra roots (CVE-2026-111943). diff --git a/Dockerfile.release b/Dockerfile.release index ca867b82ac..bac05ee89f 100644 --- a/Dockerfile.release +++ b/Dockerfile.release @@ -2,7 +2,7 @@ # suitable for testing, since it depends on a src binary being at the project # root _and_ that src binary being runnable on Alpine. To test this, refer to # the main Dockerfile, which should have an identical second stage. -FROM alpine:3.24@sha256:ff7f0c727dd796aa36787bfcd9a64bf35a6ce72a73451b3359fde849b6703d63 +FROM alpine:3.24@sha256:be2656061b536c1883c4034790e21d0a09c5aaaf51968b89368a3c0371ea2c9a # needed for `src code-intel upload` and `src actions exec` # ca-certificates-bundle >= 20261020-r0 drops the eMudhra roots (CVE-2026-111943). diff --git a/docker/batch-change-volume-workspace/Dockerfile b/docker/batch-change-volume-workspace/Dockerfile index 6b1a3b4d85..46cafffaa8 100644 --- a/docker/batch-change-volume-workspace/Dockerfile +++ b/docker/batch-change-volume-workspace/Dockerfile @@ -2,7 +2,7 @@ # image that we use to run curl, git, and unzip against a Docker volume when # using the volume workspace. -FROM alpine:3.24@sha256:ff7f0c727dd796aa36787bfcd9a64bf35a6ce72a73451b3359fde849b6703d63 +FROM alpine:3.24@sha256:be2656061b536c1883c4034790e21d0a09c5aaaf51968b89368a3c0371ea2c9a # ca-certificates-bundle >= 20261020-r0 drops the eMudhra roots (CVE-2026-111943). RUN apk add --update git unzip && apk upgrade --no-cache ca-certificates-bundle From c12dd33922f59c4bd8267c67a798751655d2df65 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 9 Nov 2026 17:11:13 -0600 Subject: [PATCH 636/647] Update dependency ubuntu to v26 (#1394) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .github/workflows/docker.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 5a4d32d6f7..708a28d931 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -13,7 +13,7 @@ on: jobs: publish: - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 steps: - name: Checkout uses: actions/checkout@v7 From b5802cb7f59f2c2dc29d9f89d12f490ebcb6d155 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 9 Nov 2026 23:17:22 +0000 Subject: [PATCH 637/647] Update alpine:3.24 Docker digest to 3f4d6b3 (#1401) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- Dockerfile | 2 +- Dockerfile.release | 2 +- docker/batch-change-volume-workspace/Dockerfile | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Dockerfile b/Dockerfile index 71366e2793..16dec5bc72 100644 --- a/Dockerfile +++ b/Dockerfile @@ -11,7 +11,7 @@ WORKDIR /src RUN go build ./cmd/src # This stage should be kept in sync with Dockerfile.release. -FROM alpine:3.24@sha256:be2656061b536c1883c4034790e21d0a09c5aaaf51968b89368a3c0371ea2c9a +FROM alpine:3.24@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf # needed for `src code-intel upload` and `src actions exec` # ca-certificates-bundle >= 20261020-r0 drops the eMudhra roots (CVE-2026-111943). diff --git a/Dockerfile.release b/Dockerfile.release index bac05ee89f..9cdb3a3fb0 100644 --- a/Dockerfile.release +++ b/Dockerfile.release @@ -2,7 +2,7 @@ # suitable for testing, since it depends on a src binary being at the project # root _and_ that src binary being runnable on Alpine. To test this, refer to # the main Dockerfile, which should have an identical second stage. -FROM alpine:3.24@sha256:be2656061b536c1883c4034790e21d0a09c5aaaf51968b89368a3c0371ea2c9a +FROM alpine:3.24@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf # needed for `src code-intel upload` and `src actions exec` # ca-certificates-bundle >= 20261020-r0 drops the eMudhra roots (CVE-2026-111943). diff --git a/docker/batch-change-volume-workspace/Dockerfile b/docker/batch-change-volume-workspace/Dockerfile index 46cafffaa8..1e6595fb27 100644 --- a/docker/batch-change-volume-workspace/Dockerfile +++ b/docker/batch-change-volume-workspace/Dockerfile @@ -2,7 +2,7 @@ # image that we use to run curl, git, and unzip against a Docker volume when # using the volume workspace. -FROM alpine:3.24@sha256:be2656061b536c1883c4034790e21d0a09c5aaaf51968b89368a3c0371ea2c9a +FROM alpine:3.24@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf # ca-certificates-bundle >= 20261020-r0 drops the eMudhra roots (CVE-2026-111943). RUN apk add --update git unzip && apk upgrade --no-cache ca-certificates-bundle From 02c1df81b570a2171126f9f9780f4a1704d31cdd Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 9 Nov 2026 23:22:12 +0000 Subject: [PATCH 638/647] Update golang:1.27.3-alpine3.24 Docker digest to dbaa054 (#1402) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index 16dec5bc72..c309eb1be5 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,7 +4,7 @@ # # Nothing fancy here: we copy in the source code and build on the Alpine Go # image. Refer to .dockerignore to get a sense of what we're not going to copy. -FROM golang:1.27.3-alpine3.24@sha256:d200d2dd76b03a99b52651fd1325aff7dcd35422c35c01bac56571b0507f3deb AS builder +FROM golang:1.27.3-alpine3.24@sha256:fa3d596898d9f126af7c01d14ee7597bab3f39cccf392ef36b69fe77cd681f18 AS builder COPY . /src WORKDIR /src From 61d74560d17a4763d7e7871488ee47cc5a255847 Mon Sep 17 00:00:00 2001 From: Marc <7050295+marcleblanc2@users.noreply.github.com> Date: Tue, 10 Nov 2026 04:19:34 -0600 Subject: [PATCH 639/647] feat: warn when src-cli is older than the instance's recommended version (#1403) * feat: warn when src-cli is older than the instance's recommended version Before running a command, src does a best-effort check of the running version against the version recommended by the configured instance (/.api/src-cli/version) and prints a single stderr warning when behind. Fail-open, 3s timeout, stderr only so --json is unaffected. Skips version/help/no-arg, dev builds, and SRC_SKIP_VERSION_CHECK. Compares major/minor/patch only. Adds unit tests. Closes #930. Supersedes #1339, #1343. * fix: make the outdated-version warning safe to ship - Fix a nil pointer panic on every command in release builds: the check built its API client from a zero-value api.Flags. - Run the check after flags and config are resolved, so -endpoint and -config are honored and the right instance is asked. - Ask the instance at most once every 24 hours per endpoint, caching the answer, including a failed lookup, under the user cache directory, so an instance that does not answer cannot delay every command. - Compare versions with Masterminds/semver, which is already linked into the binary, instead of a hand-written parser. - Skip 'src version' by its parsed subcommand instead of scanning every argument for the word. - Test the check end to end against a fake instance. Amp-Thread-ID: https://ampcode.com/threads/T-01a1c29c-9f51-7761-a4ba-4d4f46dcd4ef Co-authored-by: Amp * fix: run the version check with the command's own API client The check ran before the subcommand's flags were parsed, so it ignored -insecure-skip-verify and never warned on instances with an untrusted certificate. It also ran twice for nested legacy commands such as 'src repos list', which printed the warning twice. Run it once per process from config.apiClient instead, using the client the command asked for. Commands that never talk to the instance, such as 'src search -h', no longer trigger a lookup. Amp-Thread-ID: https://ampcode.com/threads/T-01a1c29c-9f51-7761-a4ba-4d4f46dcd4ef Co-authored-by: Amp * docs: document the outdated-version warning and SRC_SKIP_VERSION_CHECK * feat: make 'src version' warn too, and refresh the cached version 'src version' was the one command that never warned. It now prints the warning from the answer it just got from the instance, and caches that answer, so the commands that follow warn about the same version. It still makes a single request, and 'src version -client-only' still makes none: the check that other commands get from config.apiClient keeps skipping 'src version'. Amp-Thread-ID: https://ampcode.com/threads/T-01a1c29c-9f51-7761-a4ba-4d4f46dcd4ef Co-authored-by: Amp * docs: remove the README section on the version check The warning already names SRC_SKIP_VERSION_CHECK and links to the upgrade instructions, and CHANGELOG.md describes the feature. This reverts commit 71363c82b4753d0859101e940aa446814422821b. Amp-Thread-ID: https://ampcode.com/threads/T-01a1c29c-9f51-7761-a4ba-4d4f46dcd4ef Co-authored-by: Amp --------- Co-authored-by: Montana Co-authored-by: Amp --- CHANGELOG.md | 2 + cmd/src/main.go | 8 +- cmd/src/version.go | 18 +- cmd/src/version_check.go | 140 +++++++++++++++ cmd/src/version_check_test.go | 325 ++++++++++++++++++++++++++++++++++ go.mod | 2 +- 6 files changed, 486 insertions(+), 9 deletions(-) create mode 100644 cmd/src/version_check.go create mode 100644 cmd/src/version_check_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 7bd9a46ff0..4700ef0041 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,8 @@ All notable changes to `src-cli` are documented in this file. ### Added +- `src` now prints a warning to stderr when it is older than the version recommended by your Sourcegraph instance. The recommended version is looked up at most once every 24 hours per instance. To disable the check, set the `SRC_SKIP_VERSION_CHECK` environment variable to any non-blank string. [#930](https://github.com/sourcegraph/src-cli/issues/930) + ### Changed ### Fixed diff --git a/cmd/src/main.go b/cmd/src/main.go index 8635301b8a..cf941eeb96 100644 --- a/cmd/src/main.go +++ b/cmd/src/main.go @@ -156,7 +156,13 @@ func (c *config) apiClient(flags *api.Flags, out io.Writer) api.Client { } } - return api.NewClient(opts) + client := api.NewClient(opts) + // Checked here rather than before the command is dispatched, so that the + // lookup uses the command's own flags, such as -insecure-skip-verify. + warnOutdatedVersionOnce.Do(func() { + maybeWarnOutdatedVersion(client, c.endpointURL, flag.CommandLine.Arg(0)) + }) + return client } // readConfig reads the config file from the given path. diff --git a/cmd/src/version.go b/cmd/src/version.go index fad3a42f78..64d0659f44 100644 --- a/cmd/src/version.go +++ b/cmd/src/version.go @@ -6,6 +6,7 @@ import ( "fmt" "io" "net/http" + "net/url" "os" "github.com/sourcegraph/sourcegraph/lib/errors" @@ -42,17 +43,19 @@ var versionCommand = clicompat.Wrap(&cli.Command{ HideVersion: true, Action: func(ctx context.Context, c *cli.Command) error { args := VersionArgs{ - Client: cfg.apiClient(clicompat.APIFlagsFromCmd(c), os.Stdout), - ClientOnly: c.Bool("client-only"), + Client: cfg.apiClient(clicompat.APIFlagsFromCmd(c), os.Stdout), + EndpointURL: cfg.endpointURL, + ClientOnly: c.Bool("client-only"), } return versionHandler(args) }, }) type VersionArgs struct { - ClientOnly bool - Client api.Client - Output io.Writer + ClientOnly bool + Client api.Client + EndpointURL *url.URL + Output io.Writer } func versionHandler(args VersionArgs) error { @@ -68,9 +71,10 @@ func versionHandler(args VersionArgs) error { if recommendedVersion == "" { fmt.Println("Recommended version: ") fmt.Println("This Sourcegraph instance does not support this feature.") - return nil + } else { + fmt.Printf("Recommended version: %s or later\n", recommendedVersion) } - fmt.Printf("Recommended version: %s or later\n", recommendedVersion) + warnOutdatedVersionFromLookup(recommendedVersion, args.EndpointURL) return nil } diff --git a/cmd/src/version_check.go b/cmd/src/version_check.go new file mode 100644 index 0000000000..b3892e40ea --- /dev/null +++ b/cmd/src/version_check.go @@ -0,0 +1,140 @@ +package main + +import ( + "context" + "fmt" + "net/url" + "os" + "path/filepath" + "sync" + "time" + + "github.com/Masterminds/semver" + + "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/version" +) + +const ( + // versionCheckTimeout bounds the recommended-version lookup, which runs + // before the command the user asked for. + versionCheckTimeout = 3 * time.Second + + // versionCheckInterval is how long the result of a lookup is reused before + // the instance is asked again. + versionCheckInterval = 24 * time.Hour +) + +// warnOutdatedVersionOnce limits the check to once per run of src-cli, however +// many API clients the command creates. +var warnOutdatedVersionOnce sync.Once + +// maybeWarnOutdatedVersion prints a warning to stderr when src-cli is older +// than the version recommended by the Sourcegraph instance at endpointURL, +// which it asks using client unless a recent answer is cached. +// +// It never fails the command: an unreachable instance, an unparseable version, +// or an unwritable cache all result in no warning. +func maybeWarnOutdatedVersion(client api.Client, endpointURL *url.URL, subcommand string) { + // 'src version' asks the instance itself, and then calls + // warnOutdatedVersionFromLookup with the answer. + if subcommand == "version" || skipVersionCheck() { + return + } + cachePath, err := recommendedVersionCachePath(endpointURL) + if err != nil { + return + } + printOutdatedVersionWarning(recommendedVersion(client, cachePath), endpointURL) +} + +// warnOutdatedVersionFromLookup is the check for 'src version', which has just +// been told the recommended version by the instance at endpointURL. The answer +// is cached, so that the commands that follow warn about the same version. +func warnOutdatedVersionFromLookup(recommended string, endpointURL *url.URL) { + if skipVersionCheck() { + return + } + if cachePath, err := recommendedVersionCachePath(endpointURL); err == nil { + _ = cacheRecommendedVersion(cachePath, recommended) + } + printOutdatedVersionWarning(recommended, endpointURL) +} + +// skipVersionCheck reports whether the version check is disabled, or has no +// version to compare. +func skipVersionCheck() bool { + return os.Getenv("SRC_SKIP_VERSION_CHECK") != "" || version.BuildTag == version.DefaultBuildTag +} + +func printOutdatedVersionWarning(recommended string, endpointURL *url.URL) { + if warning := outdatedVersionWarning(recommended, endpointURL); warning != "" { + fmt.Fprintln(os.Stderr, warning) + } +} + +// outdatedVersionWarning returns the warning to print, or "" when src-cli is +// not known to be older than the recommended version. +func outdatedVersionWarning(recommendedVersion string, endpointURL *url.URL) string { + current, err := semver.NewVersion(version.BuildTag) + if err != nil { + return "" + } + recommended, err := semver.NewVersion(recommendedVersion) + if err != nil { + return "" + } + if !current.LessThan(recommended) { + return "" + } + return fmt.Sprintf("⚠️ Warning: src-cli %s is older than %s, the version recommended by %s. "+ + "To upgrade, see https://github.com/sourcegraph/src-cli#installation. "+ + "To silence this warning, set SRC_SKIP_VERSION_CHECK=1.", + current, recommended, endpointURL) +} + +// recommendedVersionCachePath returns the file that holds the version +// recommended by the instance at endpointURL. +func recommendedVersionCachePath(endpointURL *url.URL) (string, error) { + cacheDir, err := os.UserCacheDir() + if err != nil { + return "", err + } + return filepath.Join(cacheDir, "sourcegraph", "src-cli", "recommended-version-"+url.QueryEscape(endpointURL.String())), nil +} + +// cacheRecommendedVersion records recommended, and the time it was learned, in +// the file at cachePath. +func cacheRecommendedVersion(cachePath, recommended string) error { + if err := os.MkdirAll(filepath.Dir(cachePath), 0o700); err != nil { + return err + } + return os.WriteFile(cachePath, []byte(recommended), 0o600) +} + +// recommendedVersion returns the src-cli version recommended by the instance +// that client talks to, or "" when it is unknown. The answer is cached in the +// file at cachePath for versionCheckInterval, so most commands make no extra +// request. +func recommendedVersion(client api.Client, cachePath string) string { + if info, err := os.Stat(cachePath); err == nil && time.Since(info.ModTime()) < versionCheckInterval { + cached, _ := os.ReadFile(cachePath) + return string(cached) + } + + // Record the attempt before the lookup, so that an instance that does not + // answer delays one command per versionCheckInterval instead of every + // command. Without a writable cache there is no such bound, so do not look. + if cacheRecommendedVersion(cachePath, "") != nil { + return "" + } + + ctx, cancel := context.WithTimeout(context.Background(), versionCheckTimeout) + defer cancel() + recommended, err := getRecommendedVersion(ctx, client) + if err != nil { + return "" + } + _ = cacheRecommendedVersion(cachePath, recommended) + return recommended +} diff --git a/cmd/src/version_check_test.go b/cmd/src/version_check_test.go new file mode 100644 index 0000000000..e67f52e687 --- /dev/null +++ b/cmd/src/version_check_test.go @@ -0,0 +1,325 @@ +package main + +import ( + "fmt" + "io" + "log" + "net/http" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/version" +) + +// setBuildTag pretends that src-cli was built as the given release. +func setBuildTag(t *testing.T, buildTag string) { + t.Helper() + original := version.BuildTag + t.Cleanup(func() { version.BuildTag = original }) + version.BuildTag = buildTag +} + +// versionServer is a fake Sourcegraph instance that answers every request with +// the given status and recommended version, and counts the requests it gets. +func versionServer(t *testing.T, status int, recommended string) (client api.Client, endpointURL *url.URL, requests *int) { + t.Helper() + requests = new(int) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + *requests++ + if r.URL.Path != "/.api/src-cli/version" { + t.Errorf("unexpected request path %q", r.URL.Path) + } + w.WriteHeader(status) + fmt.Fprintf(w, `{"version": %q}`, recommended) + })) + t.Cleanup(server.Close) + endpointURL = mustParseURL(t, server.URL) + return api.NewClient(api.ClientOpts{EndpointURL: endpointURL, AccessToken: "token", Out: io.Discard}), endpointURL, requests +} + +// useTemporaryCacheDir points os.UserCacheDir at an empty directory. +func useTemporaryCacheDir(t *testing.T) { + t.Helper() + // Wherever os.UserCacheDir looks on this operating system. + for _, name := range []string{"HOME", "XDG_CACHE_HOME", "LocalAppData"} { + t.Setenv(name, t.TempDir()) + } +} + +// captureStderr returns what run writes to os.Stderr. +func captureStderr(t *testing.T, run func()) string { + t.Helper() + stderr := os.Stderr + defer func() { os.Stderr = stderr }() + reader, writer, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + os.Stderr = writer + run() + writer.Close() + output, err := io.ReadAll(reader) + if err != nil { + t.Fatal(err) + } + return string(output) +} + +func TestOutdatedVersionWarning(t *testing.T) { + tests := []struct { + name string + current string + status int + recommended string + wantWarning bool + }{ + {name: "older patch", current: "6.4.1", status: http.StatusOK, recommended: "6.4.2", wantWarning: true}, + {name: "older, compared as numbers not strings", current: "9.9.9", status: http.StatusOK, recommended: "10.0.0", wantWarning: true}, + {name: "newer, compared as numbers not strings", current: "10.0.0", status: http.StatusOK, recommended: "9.9.9"}, + {name: "same version", current: "6.4.2", status: http.StatusOK, recommended: "6.4.2"}, + {name: "instance does not recommend a version", current: "6.4.2", status: http.StatusNotFound}, + {name: "instance returns an error", current: "6.4.2", status: http.StatusInternalServerError, recommended: "7.0.0"}, + {name: "instance returns an unparseable version", current: "6.4.2", status: http.StatusOK, recommended: "latest"}, + {name: "running an unparseable version", current: "custom-build", status: http.StatusOK, recommended: "7.0.0"}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + setBuildTag(t, test.current) + client, endpointURL, _ := versionServer(t, test.status, test.recommended) + + warning := outdatedVersionWarning(recommendedVersion(client, filepath.Join(t.TempDir(), "recommended-version")), endpointURL) + + if !test.wantWarning { + if warning != "" { + t.Fatalf("got warning %q, want none", warning) + } + return + } + for _, want := range []string{test.current, test.recommended, endpointURL.String(), "SRC_SKIP_VERSION_CHECK"} { + if !strings.Contains(warning, want) { + t.Errorf("warning %q does not mention %q", warning, want) + } + } + }) + } +} + +func TestRecommendedVersionIsLookedUpOncePerInterval(t *testing.T) { + makeStale := func(t *testing.T, cachePath string) { + t.Helper() + stale := time.Now().Add(-versionCheckInterval - time.Minute) + if err := os.Chtimes(cachePath, stale, stale); err != nil { + t.Fatal(err) + } + } + + t.Run("answer is reused until it is stale", func(t *testing.T) { + setBuildTag(t, "6.4.1") + client, endpointURL, requests := versionServer(t, http.StatusOK, "6.4.2") + cachePath := filepath.Join(t.TempDir(), "nested", "recommended-version") + + for range 2 { + if warning := outdatedVersionWarning(recommendedVersion(client, cachePath), endpointURL); warning == "" { + t.Fatal("got no warning, want one on every command") + } + } + if *requests != 1 { + t.Fatalf("got %d requests, want 1", *requests) + } + + makeStale(t, cachePath) + outdatedVersionWarning(recommendedVersion(client, cachePath), endpointURL) + if *requests != 2 { + t.Fatalf("got %d requests after the cache went stale, want 2", *requests) + } + }) + + t.Run("upgrading silences the warning without another lookup", func(t *testing.T) { + setBuildTag(t, "6.4.1") + client, endpointURL, requests := versionServer(t, http.StatusOK, "6.4.2") + cachePath := filepath.Join(t.TempDir(), "recommended-version") + if warning := outdatedVersionWarning(recommendedVersion(client, cachePath), endpointURL); warning == "" { + t.Fatal("got no warning before upgrading, want one") + } + + setBuildTag(t, "6.4.2") + if warning := outdatedVersionWarning(recommendedVersion(client, cachePath), endpointURL); warning != "" { + t.Fatalf("got warning %q after upgrading, want none", warning) + } + if *requests != 1 { + t.Fatalf("got %d requests, want 1", *requests) + } + }) + + t.Run("failed lookup is not retried until it is stale", func(t *testing.T) { + setBuildTag(t, "6.4.1") + client, endpointURL, requests := versionServer(t, http.StatusInternalServerError, "") + cachePath := filepath.Join(t.TempDir(), "recommended-version") + + for range 2 { + if warning := outdatedVersionWarning(recommendedVersion(client, cachePath), endpointURL); warning != "" { + t.Fatalf("got warning %q, want none", warning) + } + } + if *requests != 1 { + t.Fatalf("got %d requests, want 1", *requests) + } + }) + + t.Run("no lookup without a writable cache", func(t *testing.T) { + setBuildTag(t, "6.4.1") + client, endpointURL, requests := versionServer(t, http.StatusOK, "6.4.2") + // A regular file where the cache directory should be. + blocker := filepath.Join(t.TempDir(), "blocker") + if err := os.WriteFile(blocker, nil, 0o600); err != nil { + t.Fatal(err) + } + + if warning := outdatedVersionWarning(recommendedVersion(client, filepath.Join(blocker, "recommended-version")), endpointURL); warning != "" { + t.Fatalf("got warning %q, want none", warning) + } + if *requests != 0 { + t.Fatalf("got %d requests, want 0", *requests) + } + }) +} + +func TestSkipVersionCheck(t *testing.T) { + tests := []struct { + name string + buildTag string + optOut string + want bool + }{ + {name: "release build", buildTag: "6.4.2", want: false}, + {name: "opted out", buildTag: "6.4.2", optOut: "1", want: true}, + {name: "dev build", buildTag: version.DefaultBuildTag, want: true}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + setBuildTag(t, test.buildTag) + t.Setenv("SRC_SKIP_VERSION_CHECK", test.optOut) + + if got := skipVersionCheck(); got != test.want { + t.Errorf("skipVersionCheck() = %v, want %v", got, test.want) + } + }) + } +} + +// TestVersionCommandChecksWithItsOwnLookup covers 'src version', which always +// asks the instance: it warns with that answer and caches it, instead of +// running the check that other commands get from config.apiClient. +func TestVersionCommandChecksWithItsOwnLookup(t *testing.T) { + const warning = "Warning: src-cli 6.4.1 is older than 6.4.3" + + // setup returns a fake instance that recommends 6.4.3, and the path of a + // cache that was told 6.4.2 a moment ago. + setup := func(t *testing.T) (client api.Client, endpointURL *url.URL, requests *int, cachePath string) { + t.Helper() + setBuildTag(t, "6.4.1") + t.Setenv("SRC_SKIP_VERSION_CHECK", "") + useTemporaryCacheDir(t) + client, endpointURL, requests = versionServer(t, http.StatusOK, "6.4.3") + cachePath, err := recommendedVersionCachePath(endpointURL) + if err != nil { + t.Fatal(err) + } + if err := cacheRecommendedVersion(cachePath, "6.4.2"); err != nil { + t.Fatal(err) + } + return client, endpointURL, requests, cachePath + } + + t.Run("warns with the answer it gets, and caches it for later commands", func(t *testing.T) { + client, endpointURL, requests, cachePath := setup(t) + + stderr := captureStderr(t, func() { + // The check that config.apiClient runs for every command. + maybeWarnOutdatedVersion(client, endpointURL, "version") + if err := versionHandler(VersionArgs{Client: client, EndpointURL: endpointURL}); err != nil { + t.Error(err) + } + }) + + if got := strings.Count(stderr, "Warning:"); got != 1 || !strings.Contains(stderr, warning) { + t.Errorf("got stderr %q, want only %q", stderr, warning) + } + if cached := recommendedVersion(client, cachePath); cached != "6.4.3" { + t.Errorf("got cached version %q, want 6.4.3", cached) + } + if *requests != 1 { + t.Errorf("got %d requests, want 1", *requests) + } + }) + + t.Run("-client-only does not ask the instance", func(t *testing.T) { + client, endpointURL, requests, cachePath := setup(t) + + stderr := captureStderr(t, func() { + maybeWarnOutdatedVersion(client, endpointURL, "version") + if err := versionHandler(VersionArgs{Client: client, EndpointURL: endpointURL, ClientOnly: true}); err != nil { + t.Error(err) + } + }) + + if stderr != "" { + t.Errorf("got stderr %q, want none", stderr) + } + if cached := recommendedVersion(client, cachePath); cached != "6.4.2" { + t.Errorf("got cached version %q, want 6.4.2 left alone", cached) + } + if *requests != 0 { + t.Errorf("got %d requests, want 0", *requests) + } + }) +} + +// TestAPIClientWarnsAboutOutdatedVersion covers where the check is hooked in: +// config.apiClient, which every command that talks to the instance calls with +// its own flags. +func TestAPIClientWarnsAboutOutdatedVersion(t *testing.T) { + tests := []struct { + name string + insecureSkipVerify bool + wantWarnings int + }{ + {name: "self-signed instance with -insecure-skip-verify is warned once, however many clients", insecureSkipVerify: true, wantWarnings: 1}, + {name: "self-signed instance without -insecure-skip-verify is not trusted", insecureSkipVerify: false, wantWarnings: 0}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + setBuildTag(t, "6.4.1") + t.Setenv("SRC_SKIP_VERSION_CHECK", "") + useTemporaryCacheDir(t) + warnOutdatedVersionOnce = sync.Once{} + t.Cleanup(func() { warnOutdatedVersionOnce = sync.Once{} }) + + server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fmt.Fprint(w, `{"version": "6.4.2"}`) + })) + server.Config.ErrorLog = log.New(io.Discard, "", 0) // rejected certificates + server.StartTLS() + t.Cleanup(server.Close) + cfg := &config{endpointURL: mustParseURL(t, server.URL), accessToken: "token"} + flags := api.NewFlagsFromValues(false, false, false, test.insecureSkipVerify, false) + + stderr := captureStderr(t, func() { + for range 2 { + cfg.apiClient(flags, io.Discard) + } + }) + + if got := strings.Count(stderr, "Warning: src-cli 6.4.1 is older than 6.4.2"); got != test.wantWarnings { + t.Errorf("got %d warnings, want %d; stderr: %q", got, test.wantWarnings, stderr) + } + }) + } +} diff --git a/go.mod b/go.mod index e90ea68b3f..3a1dfd626f 100644 --- a/go.mod +++ b/go.mod @@ -4,6 +4,7 @@ go 1.27.3 require ( cloud.google.com/go/storage v1.70.0 + github.com/Masterminds/semver v1.5.0 github.com/aws/aws-sdk-go-v2/config v1.33.12 github.com/aws/aws-sdk-go-v2/service/ec2 v1.343.0 github.com/aws/aws-sdk-go-v2/service/eks v1.105.1 @@ -57,7 +58,6 @@ require ( github.com/Azure/go-ansiterm v0.0.0-20261013165250-51075c6ea6bc // indirect github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.62.0 // indirect github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.62.0 // indirect - github.com/Masterminds/semver v1.5.0 // indirect github.com/alecthomas/chroma/v2 v2.27.0 // indirect github.com/aws/aws-sdk-go-v2 v1.47.5 // indirect github.com/aws/aws-sdk-go-v2/credentials v1.20.12 // indirect From 0d0128d61eeb7e7a2daaf4f62d29b03cbc46fed7 Mon Sep 17 00:00:00 2001 From: Marc <7050295+marcleblanc2@users.noreply.github.com> Date: Tue, 10 Nov 2026 11:31:11 -0600 Subject: [PATCH 640/647] docs/readme: drop the Sourcegraph 3.12 note and refresh stale content (#1396) --- .markdownlint-cli2.jsonc | 10 +++++ README.md | 79 +++++++++++++++++++++------------------- cmd/src/config.go | 2 +- 3 files changed, 52 insertions(+), 39 deletions(-) create mode 100644 .markdownlint-cli2.jsonc diff --git a/.markdownlint-cli2.jsonc b/.markdownlint-cli2.jsonc new file mode 100644 index 0000000000..95ef757ff0 --- /dev/null +++ b/.markdownlint-cli2.jsonc @@ -0,0 +1,10 @@ +{ + "config": { + // Prose in this repo is not hard-wrapped. + "MD013": false, + // "Latest version" and friends repeat under each OS heading. + "MD024": { "siblings_only": true }, + // The README floats a screenshot right and keeps an anchor that other repos link to. + "MD033": { "allowed_elements": ["img", "a"] } + } +} diff --git a/README.md b/README.md index 37100691a3..97e669a5c6 100644 --- a/README.md +++ b/README.md @@ -1,28 +1,26 @@ -# [Sourcegraph](https://sourcegraph.com) CLI [![Build Status](https://github.com/sourcegraph/src-cli/workflows/Go%20CI/badge.svg)](https://github.com/sourcegraph/src-cli/actions?query=workflow%3A%22Go+CI%22) [![Go Report Card](https://goreportcard.com/badge/sourcegraph/src-cli)](https://goreportcard.com/report/sourcegraph/src-cli) +# [Sourcegraph](https://sourcegraph.com) CLI [![Build Status](https://github.com/sourcegraph/src-cli/workflows/Go%20CI/badge.svg)](https://github.com/sourcegraph/src-cli/actions?query=workflow%3A%22Go+CI%22) - +src search results in a terminal `src` is a command line interface to Sourcegraph: - **Search & get results in your terminal** - **Search & get JSON** for programmatic consumption - Make **GraphQL API requests** with auth easily & get JSON back fast -- Execute **[batch changes](https://sourcegraph.com/docs/batch_changes)** +- Execute **[batch changes](https://sourcegraph.com/docs/batch-changes)** - **Manage & administrate** repositories, users, and more - **Easily convert src-CLI commands to equivalent curl commands**, just add --get-curl! -**Note:** Using Sourcegraph 3.12 or earlier? [See the older README](https://github.com/sourcegraph/src-cli/tree/3.11.2). - ## Installation -Binary downloads are available on the [releases tab](https://github.com/sourcegraph/src-cli/releases), and through Sourcegraph.com. _If the latest version does not work for you,_ consider using the version compatible with your Sourcegraph instance instead. +Download the latest version from the [releases page](https://github.com/sourcegraph/src-cli/releases), or from Sourcegraph.com using the commands below. If the latest version does not work with your Sourcegraph instance, download the version compatible with your Sourcegraph instance, as shown below. -### Installation: Mac OS +### Installation: macOS #### Latest version ```bash -curl -L https://sourcegraph.com/.api/src-cli/src_darwin_amd64 -o /usr/local/bin/src +curl -L https://sourcegraph.com/.api/src-cli/src_darwin_arm64 -o /usr/local/bin/src chmod +x /usr/local/bin/src ``` @@ -43,24 +41,22 @@ npm install -g @sourcegraph/src Replace `sourcegraph.example.com` with your Sourcegraph instance URL: ```bash -curl -L https://sourcegraph.example.com/.api/src-cli/src_darwin_amd64 -o /usr/local/bin/src +curl -L https://sourcegraph.example.com/.api/src-cli/src_darwin_arm64 -o /usr/local/bin/src chmod +x /usr/local/bin/src ``` -or, if you know the specific version to target, for example 3.43.2: +or, if you know the specific version to target: ```bash -brew install sourcegraph/src-cli/src-cli@3.43.2 +brew install sourcegraph/src-cli/src-cli@8.1.2687 ``` or with npm/npx: ```bash -npx @sourcegraph/src@3.43.2 version +npx @sourcegraph/src@8.1.2687 version ``` -> Note: Versioned formulas are available on Homebrew for Sourcegraph versions 3.43.2 and later. - ### Installation: Linux #### Latest version @@ -70,6 +66,8 @@ curl -L https://sourcegraph.com/.api/src-cli/src_linux_amd64 -o /usr/local/bin/s chmod +x /usr/local/bin/src ``` +On an ARM host, replace `src_linux_amd64` with `src_linux_arm64`. + or with npm: ```bash @@ -85,10 +83,10 @@ curl -L https://sourcegraph.example.com/.api/src-cli/src_linux_amd64 -o /usr/loc chmod +x /usr/local/bin/src ``` -or, with npm/npx, if you know the specific version to target, for example 3.43.2: +or, with npm/npx, if you know the specific version to target: ```bash -npx @sourcegraph/src@3.43.2 version +npx @sourcegraph/src@8.1.2687 version ``` ### Installation: Windows @@ -97,7 +95,7 @@ See [Sourcegraph CLI for Windows](WINDOWS.md). ### Installation: Docker -`sourcegraph/src-cli` is published to Docker Hub. You can use the `latest` tag or a specific version such as `3.43`. To see all versions view [sourcegraph/src-cli tags](https://hub.docker.com/r/sourcegraph/src-cli/tags). +The [`sourcegraph/src-cli`](https://hub.docker.com/r/sourcegraph/src-cli/tags) image on Docker Hub is tagged with `latest` and with each release version. ```bash docker run --rm=true sourcegraph/src-cli:latest search 'hello world' @@ -119,7 +117,7 @@ For PowerShell on Windows: $env:SRC_ENDPOINT = 'https://sourcegraph.example.com' ``` -For convenience, add this environment variable to your terminal profile or system environment variables. On Mac OS and Linux, the terminal profile is typically `~/.bash_profile` for Bash or `~/.zprofile` for Zsh. On Windows, you can add it through the *System Properties* window. See [these instructions](https://www.computerhope.com/issues/ch000549.htm) for details. +For convenience, add this environment variable to your terminal profile or system environment variables. On macOS and Linux, the terminal profile is typically `~/.zprofile` for Zsh or `~/.bash_profile` for Bash. On Windows, you can add it through the *System Properties* window. If `SRC_ENDPOINT` is not set, `src` defaults to `https://sourcegraph.com`. @@ -169,27 +167,32 @@ Is your Sourcegraph instance behind a custom auth proxy? See [auth proxy configu `src` provides different subcommands to interact with different parts of Sourcegraph: - - `src login` - authenticate to a Sourcegraph instance with your user credentials - - `src auth` - print the active authentication token or authorization header - - `src search` - perform searches and get results in your terminal or as JSON - - `src api` - run Sourcegraph GraphQL API requests - - `src batch` - execute and manage [batch changes](https://sourcegraph.com/docs/batch_changes) - - `src repos` - manage repositories - - `src users` - manage users - - `src orgs` - manages organization - - `src config` - manage global, org, and user settings - - `src extsvc` - manage external services (repository configuration) - - `src extensions` - manage extensions - - `src code-intel` - manages Code Intelligence data - - `src serve-git` - serves your local git repositories over HTTP for Sourcegraph to pull - - `src version` - check version and guaranteed-compatible version for your Sourcegraph instance +- `src abc` - manage agentic batch changes +- `src api` - run Sourcegraph GraphQL API requests +- `src auth` - print the active authentication token or authorization header +- `src batch` - execute and manage [batch changes](https://sourcegraph.com/docs/batch-changes) +- `src code-intel` - manage code intelligence data +- `src codeowners` - manage ingested code ownership data +- `src config` - manage global, org, and user settings +- `src debug` - gather and bundle debug data from a Sourcegraph deployment for troubleshooting +- `src extsvc` - manage external services (repository configuration) +- `src login` - authenticate to a Sourcegraph instance with your user credentials +- `src lsp` - run a Language Server Protocol server that proxies requests to Sourcegraph code intelligence +- `src orgs` - manage organizations +- `src repos` - manage repositories +- `src search` - perform searches and get results in your terminal or as JSON +- `src search-jobs` - manage search jobs +- `src serve-git` - serve your local git repositories over HTTP for Sourcegraph to pull +- `src snapshot` - manage snapshots of Sourcegraph instance databases (experimental) +- `src users` - manage users +- `src version` - display and compare the `src` version against the recommended version for your Sourcegraph instance Run `src -h` and `src -h` for more detailed usage information. You can also read the [usage docs for the latest version of `src-cli`](https://sourcegraph.com/docs/cli/references) online. -#### Optional: Renaming `src` +### Optional: Renaming `src` -If you have a naming conflict with the `src` command, such as a Bash alias, you can rename the static binary. For example, on Linux / Mac OS: +If you have a naming conflict with the `src` command, such as a Bash alias, you can rename the static binary. For example, on Linux / macOS: ```sh mv /usr/local/bin/src /usr/local/bin/src-cli @@ -203,13 +206,13 @@ You can then invoke it via `src-cli`. ## Telemetry -`src` includes the operating system and architecture in the `User-Agent` header sent to Sourcegraph. For example, running `src` version 3.21.10 on an x86-64 Linux host will result in this header: +`src` includes the operating system and architecture in the `User-Agent` header sent to Sourcegraph. For example, running `src` on an x86-64 Linux host will result in this header: -``` -src-cli/3.21.10 linux amd64 +```text +src-cli/8.1.2687 linux amd64 ``` -To disable this and _only_ send the version, you can set `-user-agent-telemetry=false` for a single command, or set the `SRC_DISABLE_USER_AGENT_TELEMETRY` environment variable to any non-blank string. +To disable this and *only* send the version, you can set `-user-agent-telemetry=false` for a single command, or set the `SRC_DISABLE_USER_AGENT_TELEMETRY` environment variable to any non-blank string. As with other Sourcegraph telemetry, any collected data is only sent to Sourcegraph.com in aggregate form. diff --git a/cmd/src/config.go b/cmd/src/config.go index e6e7dfc937..898e1e5d1d 100644 --- a/cmd/src/config.go +++ b/cmd/src/config.go @@ -136,7 +136,7 @@ query ViewerUserID { } if result.CurrentUser == nil || result.CurrentUser.ID == "" { - return "", errors.New("unable to determine current user ID (see https://github.com/sourcegraph/src-cli#authentication)") + return "", errors.New("unable to determine current user ID (see https://github.com/sourcegraph/src-cli#connect-to-your-sourcegraph-instance)") } return result.CurrentUser.ID, nil } From 2f3acd4aa2b67ca5a6949e34cbe2290a261f7c9f Mon Sep 17 00:00:00 2001 From: Marc <7050295+marcleblanc2@users.noreply.github.com> Date: Tue, 10 Nov 2026 11:40:56 -0600 Subject: [PATCH 641/647] ci: build Docker images and check the npm package before merge (#1398) Dockerfile, Dockerfile.release, docker/** and npm-distribution/** had no pre-merge check: goreleaser.yml and docker.yml only run on release tags, and renovate automerges on green CI. Two path-filtered workflows now build every shipped image (with the same static linux binary goreleaser feeds to Dockerfile.release) and run npm ci + npm pack on the npm package. Amp-Thread-ID: https://ampcode.com/threads/T-01a1a37e-8603-775d-bc85-c5677817f7a8 Co-authored-by: Amp --- .github/workflows/docker-check.yml | 47 ++++++++++++++++++++++++++++++ .github/workflows/npm-check.yml | 25 ++++++++++++++++ 2 files changed, 72 insertions(+) create mode 100644 .github/workflows/docker-check.yml create mode 100644 .github/workflows/npm-check.yml diff --git a/.github/workflows/docker-check.yml b/.github/workflows/docker-check.yml new file mode 100644 index 0000000000..8ba757f355 --- /dev/null +++ b/.github/workflows/docker-check.yml @@ -0,0 +1,47 @@ +# Builds every Docker image this repo ships. Nothing else tests them before a +# tag: .goreleaser.yml and docker.yml only run on release tags. +name: Docker check + +on: + workflow_dispatch: + push: + paths: + - Dockerfile + - Dockerfile.release + - .dockerignore + - docker/** + - .github/workflows/docker-check.yml + +jobs: + src-cli-image: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v7 + - name: Get Go version from mise + id: mise + run: echo "go-version=$(grep 'golang' mise.toml | cut -d'"' -f2)" >> "$GITHUB_OUTPUT" + - name: Set up Go + uses: actions/setup-go@v7 + with: + go-version: ${{ steps.mise.outputs.go-version }} + cache: false + # Dockerfile.release expects the static linux binary goreleaser builds + # into the project root. + - name: Build src like goreleaser does + run: CGO_ENABLED=0 GOOS=linux go build -o src ./cmd/src + - name: Build Dockerfile.release + run: docker build --file Dockerfile.release --tag src-cli:release . + - run: docker run --rm src-cli:release version --client-only + - name: Build Dockerfile + run: docker build --tag src-cli:dev . + - run: docker run --rm src-cli:dev version --client-only + + batch-change-volume-workspace-image: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v7 + - name: Build docker/batch-change-volume-workspace + run: docker build --tag volume-workspace docker/batch-change-volume-workspace + - run: docker run --rm volume-workspace sh -c 'git --version && unzip -v' diff --git a/.github/workflows/npm-check.yml b/.github/workflows/npm-check.yml new file mode 100644 index 0000000000..d06cc2f505 --- /dev/null +++ b/.github/workflows/npm-check.yml @@ -0,0 +1,25 @@ +# Checks the npm package that goreleaser.yml publishes on release tags. +name: npm check + +on: + workflow_dispatch: + push: + paths: + - npm-distribution/** + - .github/workflows/npm-check.yml + +jobs: + npm-check: + runs-on: ubuntu-latest + defaults: + run: + working-directory: npm-distribution + steps: + - name: Checkout + uses: actions/checkout@v7 + # The install script downloads the release binary for package.json's + # version, which does not exist until the tag is published. + - run: npm ci --ignore-scripts + - run: node -e 'require("tar")' + # Runs the prepack script and lists what would ship. + - run: npm pack --dry-run From 9b493d667e33a54d6a1c88f0cc4a3c573bcf8df7 Mon Sep 17 00:00:00 2001 From: Marc <7050295+marcleblanc2@users.noreply.github.com> Date: Tue, 10 Nov 2026 11:45:06 -0600 Subject: [PATCH 642/647] npm: drop stale overrides and the unused @types/tar devDependency (#1397) The overrides block was added in #1218 and #1219 to force patched versions of cross-spawn, glob, and brace-expansion, which tar 7.1 pulled in through rimraf. tar 7.5 (#1319, #1357) dropped rimraf, so none of those packages are in the dependency tree anymore and the overrides have no effect. Renovate still reads them as declared dependencies and keeps opening PRs to bump them (#1389, #1390, #1392, #1393). @types/tar is unused: npm-distribution has no TypeScript, and tar 7 ships its own types (#1391 would have replaced it with a deprecated stub). Amp-Thread-ID: https://ampcode.com/threads/T-01a1a37e-8603-775d-bc85-c5677817f7a8 Co-authored-by: Amp --- npm-distribution/package-lock.json | 41 ------------------------------ npm-distribution/package.json | 8 ------ 2 files changed, 49 deletions(-) diff --git a/npm-distribution/package-lock.json b/npm-distribution/package-lock.json index 8a11a72602..3d74473744 100644 --- a/npm-distribution/package-lock.json +++ b/npm-distribution/package-lock.json @@ -14,9 +14,6 @@ }, "bin": { "src": "src.js" - }, - "devDependencies": { - "@types/tar": "6.1.13" } }, "node_modules/@isaacs/fs-minipass": { @@ -40,27 +37,6 @@ "node": ">=16 || 14 >=14.17" } }, - "node_modules/@types/node": { - "version": "24.10.1", - "resolved": "https://registry.npmjs.org/@types/node/-/node-24.10.1.tgz", - "integrity": "sha512-GNWcUTRBgIRJD5zj+Tq0fKOJ5XZajIiBroOF0yvj2bSU1WvNdYS/dn9UxwsujGW4JX06dnHyjV2y9rRaybH0iQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "undici-types": "~7.16.0" - } - }, - "node_modules/@types/tar": { - "version": "6.1.13", - "resolved": "https://registry.npmjs.org/@types/tar/-/tar-6.1.13.tgz", - "integrity": "sha512-IznnlmU5f4WcGTh2ltRu/Ijpmk8wiWXfF0VA4s+HPjHZgvFggk1YaIkbo5krX/zUCzWF8N/l4+W/LNxnvAJ8nw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*", - "minipass": "^4.0.0" - } - }, "node_modules/chownr": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz", @@ -70,16 +46,6 @@ "node": ">=18" } }, - "node_modules/minipass": { - "version": "4.2.8", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-4.2.8.tgz", - "integrity": "sha512-fNzuVyifolSLFL4NzpF+wEF4qrgqaaKX0haXPQEdQ7NKAN+WecoKMHV09YcuL/DHxrUsYQOK3MiuDf7Ip2OXfQ==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=8" - } - }, "node_modules/minizlib": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.1.0.tgz", @@ -126,13 +92,6 @@ "node": ">=16 || 14 >=14.17" } }, - "node_modules/undici-types": { - "version": "7.16.0", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz", - "integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==", - "dev": true, - "license": "MIT" - }, "node_modules/yallist": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz", diff --git a/npm-distribution/package.json b/npm-distribution/package.json index c65849dac4..3521a70539 100644 --- a/npm-distribution/package.json +++ b/npm-distribution/package.json @@ -19,13 +19,5 @@ "dependencies": { "tar": "^7.5.22" }, - "overrides": { - "cross-spawn": "^7.0.5", - "glob": "^10.5.0", - "brace-expansion": "^2.0.2" - }, - "devDependencies": { - "@types/tar": "6.1.13" - }, "private": false } From bfd88518d4a75c9e0fdb242786c54251da5a94bd Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 10 Nov 2026 17:48:43 +0000 Subject: [PATCH 643/647] Update goreleaser/goreleaser-action action to v7 (#1395) * Update goreleaser/goreleaser-action action to v7 * ci: pin GoReleaser to v2.9.0 and update configs to version 2 goreleaser-action v7 resolves `version: latest` to GoReleaser v2, where v5 resolved it to v1. `goreleaser check` on v2.19.0 exits 2 because the config uses deprecated properties. - Add `version: 2` and rename `archives.format` to `formats`. - In .goreleaser-patch.yml, rename `brews.tap` to `repository` and `brews.folder` to `directory`; GoReleaser v2 removed the old names. - Pin GoReleaser to v2.9.0, the last release before `brews` was deprecated in favor of `homebrew_casks`. Moving to casks changes how the Homebrew tap is published, so it is left for a separate change. * ci: cap Renovate's GoReleaser updates below v2.10.0 Renovate updates the goreleaser-action `version` input, so it would bump the v2.9.0 pin to the latest v2 release, which fails `goreleaser check` on the deprecated `brews` section. Remove the cap after moving to `homebrew_casks`. Amp-Thread-ID: https://ampcode.com/threads/T-01a1c294-b266-7190-94ba-430f0658a726 Co-authored-by: Amp --------- Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> Co-authored-by: Marc LeBlanc <7050295+marcleblanc2@users.noreply.github.com> Co-authored-by: Amp --- .github/workflows/goreleaser-check.yml | 6 ++++-- .github/workflows/goreleaser.yml | 5 +++-- .goreleaser-patch.yml | 9 +++++---- .goreleaser.yml | 5 +++-- renovate.json | 9 +++++++++ 5 files changed, 24 insertions(+), 10 deletions(-) diff --git a/.github/workflows/goreleaser-check.yml b/.github/workflows/goreleaser-check.yml index f13e721330..7e00d61472 100644 --- a/.github/workflows/goreleaser-check.yml +++ b/.github/workflows/goreleaser-check.yml @@ -13,7 +13,9 @@ jobs: # `goreleaser check` only parses the config; it needs neither Go nor # git history. - name: Check GoReleaser config - uses: goreleaser/goreleaser-action@v5 + uses: goreleaser/goreleaser-action@v7 with: - version: latest + # Pinned: GoReleaser v2.10+ deprecates `brews`, which fails + # `goreleaser check`. Unpin after moving to `homebrew_casks`. + version: v2.9.0 args: check diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index 35e3125826..7b48f00265 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -188,9 +188,10 @@ jobs: DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }} DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }} - name: Run GoReleaser - uses: goreleaser/goreleaser-action@v5 + uses: goreleaser/goreleaser-action@v7 with: - version: latest + # Keep in sync with the version in goreleaser-check.yml. + version: v2.9.0 # We use a different goreleaser config for releasing a new latest version vs. # releasing a patch on an older version. For releasing the new latest version, # we want to update the main (unversioned) Homebrew formula. For releasing a diff --git a/.goreleaser-patch.yml b/.goreleaser-patch.yml index 5650e19d6b..d0ba187d3b 100644 --- a/.goreleaser-patch.yml +++ b/.goreleaser-patch.yml @@ -3,6 +3,7 @@ # the Homebrew tap and does not publish a "latest" image to Docker Hub. It should match # .goreleaser.yml in every way except for the brews.name template and the # dockers.image_templates list. +version: 2 dist: release env: - GO111MODULE=on @@ -27,9 +28,9 @@ builds: - arm64 archives: - id: tarball - format: tar.gz + formats: tar.gz - id: bin - format: binary + formats: binary wrap_in_directory: false name_template: "src_{{ .Os }}_{{ .Arch }}" brews: @@ -37,12 +38,12 @@ brews: name: src-cli@{{ .Major }}.{{ .Minor }}.{{ .Patch }} homepage: "https://sourcegraph.com/" description: "Sourcegraph CLI" - tap: + repository: owner: sourcegraph name: homebrew-src-cli # Folder inside the repository to put the formula. # Default is the root folder. - folder: Formula + directory: Formula # We need to set this so that goreleaser doesn't think the binary is called # `src-cli` install: | diff --git a/.goreleaser.yml b/.goreleaser.yml index e82823cf09..6bfccb6d92 100644 --- a/.goreleaser.yml +++ b/.goreleaser.yml @@ -2,6 +2,7 @@ # release. It updates the main formula in the Homebrew tap. It should match # .goreleaser-patch.yml in every way except for the brews.name template and the # dockers.image_templates list. +version: 2 dist: release env: - GO111MODULE=on @@ -26,9 +27,9 @@ builds: - arm64 archives: - id: tarball - format: tar.gz + formats: tar.gz - id: bin - format: binary + formats: binary wrap_in_directory: false name_template: "src_{{ .Os }}_{{ .Arch }}" brews: diff --git a/renovate.json b/renovate.json index dee4083d81..a3dc1d00a1 100644 --- a/renovate.json +++ b/renovate.json @@ -5,5 +5,14 @@ "extends": [ "github>sourcegraph/renovate-config" ], + "packageRules": [ + { + "description": "GoReleaser v2.10+ deprecates brews, which fails goreleaser check. Remove after moving to homebrew_casks.", + "matchPackageNames": [ + "goreleaser/goreleaser" + ], + "allowedVersions": "<2.10.0" + } + ], "semanticCommits": false } From e7263ebcddaed097e85def806f34f24ce3ddb7b7 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 10 Nov 2026 14:15:43 -0600 Subject: [PATCH 644/647] Update dependency golang to v1.27.4 (#1405) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- mise.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mise.toml b/mise.toml index 65c03f6d54..fde1ac61d1 100644 --- a/mise.toml +++ b/mise.toml @@ -1,4 +1,4 @@ [tools] -golang = "1.27.3" +golang = "1.27.4" shfmt = "3.14.1" shellcheck = "0.11.0" From 775935274ba67bbe7950980169ad2697e433e966 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 10 Nov 2026 14:24:25 -0600 Subject: [PATCH 645/647] Update golang Docker tag to v1.27.4 (#1406) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index c309eb1be5..a439a78dc5 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,7 +4,7 @@ # # Nothing fancy here: we copy in the source code and build on the Alpine Go # image. Refer to .dockerignore to get a sense of what we're not going to copy. -FROM golang:1.27.3-alpine3.24@sha256:fa3d596898d9f126af7c01d14ee7597bab3f39cccf392ef36b69fe77cd681f18 AS builder +FROM golang:1.27.4-alpine3.24@sha256:0a5f7fe796599ff487605987432e7619ae45beeb2fba4c2ce0b907879932aebf AS builder COPY . /src WORKDIR /src From 2b065fabdbe1b60422c82deb5c22b180b0f8bf95 Mon Sep 17 00:00:00 2001 From: Marc <7050295+marcleblanc2@users.noreply.github.com> Date: Tue, 10 Nov 2026 22:48:02 -0600 Subject: [PATCH 646/647] chore: Remove the `src debug server` command (#1407) It collected debug data from the single-container sourcegraph/server deployment, which was removed in Sourcegraph 7.0. Amp-Thread-ID: https://ampcode.com/threads/T-01a1c8bb-6fd3-7465-bba1-09f3d978776b Co-authored-by: Amp --- CHANGELOG.md | 2 + cmd/src/debug.go | 1 - cmd/src/debug_server.go | 179 ---------------------------------------- cmd/src/doc_test.go | 1 - 4 files changed, 2 insertions(+), 181 deletions(-) delete mode 100644 cmd/src/debug_server.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 4700ef0041..a50477cbe3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,8 @@ All notable changes to `src-cli` are documented in this file. ### Removed +- Removed the `src debug server` command. It collected debug data from the single-container `sourcegraph/server` deployment, which was removed in Sourcegraph 7.0. Use `src debug compose` or `src debug kube` instead. + ## 8.1.2687 ### Added diff --git a/cmd/src/debug.go b/cmd/src/debug.go index 4ee47d3781..8bda244b72 100644 --- a/cmd/src/debug.go +++ b/cmd/src/debug.go @@ -18,7 +18,6 @@ The commands are: kube dumps context from k8s deployments compose dumps context from docker-compose deployments - server dumps context from single-container deployments Use "src debug command -h" for more information about a subcommands. diff --git a/cmd/src/debug_server.go b/cmd/src/debug_server.go deleted file mode 100644 index d219ec7fdb..0000000000 --- a/cmd/src/debug_server.go +++ /dev/null @@ -1,179 +0,0 @@ -package main - -import ( - "archive/zip" - "context" - "flag" - "fmt" - "log" - "os" - "path/filepath" - "runtime" - - "github.com/sourcegraph/sourcegraph/lib/errors" - "golang.org/x/sync/errgroup" - "golang.org/x/sync/semaphore" -) - -func init() { - usage := ` -'src debug server' invokes docker cli diagnostic commands targeting a Sourcegraph server container, -and writes an archive file from their returns. - -Usage: - - src debug server [command options] - -Flags: - - -o Specify the name of the output zip archive. - -no-config Don't include Sourcegraph configuration json. - -Examples: - - $ src debug server -c foo -o debug.zip - - $ src -v debug server --no-configs -c ViktorVaughn -o foo.zip - -` - - flagSet := flag.NewFlagSet("server", flag.ExitOnError) - var base string - var container string - var excludeConfigs bool - flagSet.StringVar(&base, "o", "debug.zip", "The name of the output zip archive") - flagSet.StringVar(&container, "c", "", "The container to target") - flagSet.BoolVar(&excludeConfigs, "no-configs", false, "If true, exclude Sourcegraph configuration files. Defaults to false.") - - handler := func(args []string) error { - if err := flagSet.Parse(args); err != nil { - return err - } - - //process -o flag to get zipfile and base directory names, make sure container is targeted - if base == "" { - return fmt.Errorf("empty -o flag") - } - if container == "" { - return fmt.Errorf("empty -c flag, specify a container: src debug server -c foo") - } - base, baseDir := processBaseDir(base) - - // init context - ctx := context.Background() - // open pipe to output file - out, err := os.OpenFile(base, os.O_CREATE|os.O_RDWR|os.O_EXCL, 0666) - if err != nil { - return errors.Wrapf(err, "failed to open file %q", base) - } - defer out.Close() - // init zip writer - zw := zip.NewWriter(out) - defer zw.Close() - - // Safety check user knows what they are targeting with this debug command - log.Printf("This command will archive docker-cli data for container: %s\n SRC_ENDPOINT: %s\n Output filename: %s", container, cfg.endpointURL, base) - if verified, _ := verify("Do you want to start writing to an archive?"); !verified { - return nil - } - - err = archiveServ(ctx, zw, *verbose, !excludeConfigs, container, baseDir) - if err != nil { - return err - } - return nil - } - - debugCommands = append(debugCommands, &command{ - flagSet: flagSet, - handler: handler, - usageFunc: func() { - fmt.Println(usage) - }, - }) -} - -// Runs common docker cli commands on a single container -func archiveServ(ctx context.Context, zw *zip.Writer, verbose, archiveConfigs bool, container, baseDir string) error { - ctx, cancel := context.WithCancel(ctx) - defer cancel() - - // setup channel for slice of archive function outputs - ch := make(chan *archiveFile) - g, ctx := errgroup.WithContext(ctx) - semaphore := semaphore.NewWeighted(int64(runtime.GOMAXPROCS(0))) - - run := func(f func() *archiveFile) { - g.Go(func() error { - if err := semaphore.Acquire(ctx, 1); err != nil { - return err - } - defer semaphore.Release(1) - - if file := f(); file != nil { - ch <- file - } - - return nil - }) - } - - // start goroutine to run docker ps -o wide - run(func() *archiveFile { return getServLog(ctx, container, baseDir) }) - - // start goroutine to run docker ps -o wide - run(func() *archiveFile { return getServInspect(ctx, container, baseDir) }) - - // start goroutine to run docker ps -o wide - run(func() *archiveFile { return getServTop(ctx, container, baseDir) }) - - // start goroutine to get configs - if archiveConfigs { - run(func() *archiveFile { return getExternalServicesConfig(ctx, baseDir) }) - - run(func() *archiveFile { return getSiteConfig(ctx, baseDir) }) - } - - // close channel when wait group goroutines have completed - go func() { - if err := g.Wait(); err != nil { - fmt.Printf("archiveServ failed to open wait group: %s\n", err) - os.Exit(1) - } - close(ch) - }() - - // Read binaries from channel and write to archive on host machine - if err := writeChannelContentsToZip(zw, ch, verbose); err != nil { - return errors.Wrap(err, "failed to write archives from channel") - } - - return nil -} - -// runs archiveFileFromCommand with args container logs $CONTAINER -func getServLog(ctx context.Context, container, baseDir string) *archiveFile { - return archiveFileFromCommand( - ctx, - filepath.Join(baseDir, fmt.Sprintf("%s.log", container)), - "docker", "container", "logs", container, - ) -} - -// runs archiveFileFromCommand with args container inspect $CONTAINER -func getServInspect(ctx context.Context, container, baseDir string) *archiveFile { - return archiveFileFromCommand( - ctx, - filepath.Join(baseDir, fmt.Sprintf("inspect-%s.txt", container)), - "docker", "container", "inspect", container, - ) -} - -// runs archiveFileFromCommand with args top $CONTAINER -func getServTop(ctx context.Context, container, baseDir string) *archiveFile { - return archiveFileFromCommand( - ctx, - filepath.Join(baseDir, fmt.Sprintf("top-%s.txt", container)), - "docker", "top", container, - ) -} diff --git a/cmd/src/doc_test.go b/cmd/src/doc_test.go index 75747ba874..cb24b5454e 100644 --- a/cmd/src/doc_test.go +++ b/cmd/src/doc_test.go @@ -51,7 +51,6 @@ var expectedDocFiles = []string{ "debug/compose.md", "debug/index.md", "debug/kube.md", - "debug/server.md", "extsvc/create.md", "extsvc/edit.md", "extsvc/index.md", From f2901d14d2db58c4f25d0f73736805e01b14f502 Mon Sep 17 00:00:00 2001 From: Nacho Rodriguez Paez Date: Thu, 12 Nov 2026 09:27:33 +0000 Subject: [PATCH 647/647] Pin GitHub Actions to commit SHAs (#1408) Sourcegraph-Batch-Change: https://sourcegraph.sourcegraph.com/batch-change-agents/1257 --- .github/workflows/diff-tour.yml | 2 +- .github/workflows/docker-check.yml | 6 +++--- .github/workflows/docker.yml | 6 +++--- .github/workflows/go-ci.yml | 6 +++--- .github/workflows/go-lint.yml | 6 +++--- .github/workflows/goreleaser-check.yml | 4 ++-- .github/workflows/goreleaser.yml | 18 +++++++++--------- .github/workflows/npm-check.yml | 2 +- .github/workflows/scip.yml | 4 ++-- 9 files changed, 27 insertions(+), 27 deletions(-) diff --git a/.github/workflows/diff-tour.yml b/.github/workflows/diff-tour.yml index 78abbc7c51..b4d0564a53 100644 --- a/.github/workflows/diff-tour.yml +++ b/.github/workflows/diff-tour.yml @@ -24,4 +24,4 @@ jobs: # Diff Tour resolves branch names against the base repo, so skip fork PRs if: github.event.pull_request.head.repo.full_name == github.repository steps: - - uses: sourcegraph/actions/diff-tour@main + - uses: sourcegraph/actions/diff-tour@4430dc1e4dde002387a4b655b41f6431ca75b1c1 # main diff --git a/.github/workflows/docker-check.yml b/.github/workflows/docker-check.yml index 8ba757f355..4b7297a6a3 100644 --- a/.github/workflows/docker-check.yml +++ b/.github/workflows/docker-check.yml @@ -17,12 +17,12 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Get Go version from mise id: mise run: echo "go-version=$(grep 'golang' mise.toml | cut -d'"' -f2)" >> "$GITHUB_OUTPUT" - name: Set up Go - uses: actions/setup-go@v7 + uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: go-version: ${{ steps.mise.outputs.go-version }} cache: false @@ -41,7 +41,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Build docker/batch-change-volume-workspace run: docker build --tag volume-workspace docker/batch-change-volume-workspace - run: docker run --rm volume-workspace sh -c 'git --version && unzip -v' diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 708a28d931..4c8b06a691 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -16,16 +16,16 @@ jobs: runs-on: ubuntu-26.04 steps: - name: Checkout - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 # We need buildx to be able to build a multi-architecture image. - name: Set up Docker buildx - uses: docker/setup-buildx-action@v4 + uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 # We also need QEMU, since this is running on an AMD64 host and we want to # build ARM64 images. - name: Set up QEMU - uses: docker/setup-qemu-action@v4 + uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4.4.0 with: platforms: arm64 diff --git a/.github/workflows/go-ci.yml b/.github/workflows/go-ci.yml index d11d734112..b06be6bc98 100644 --- a/.github/workflows/go-ci.yml +++ b/.github/workflows/go-ci.yml @@ -11,13 +11,13 @@ jobs: runs-on: ${{ matrix.os }} steps: - name: Checkout - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Get Go version from mise id: mise run: echo "go-version=$(grep 'golang' mise.toml | cut -d'"' -f2)" >> $GITHUB_OUTPUT shell: bash - name: Set up Go - uses: actions/setup-go@v7 + uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: go-version: ${{ steps.mise.outputs.go-version }} # setup-go's built-in cache keys on go.sum alone, has no fallback @@ -33,7 +33,7 @@ jobs: echo "build=$(go env GOCACHE)" >> "$GITHUB_OUTPUT" echo "modules=$(go env GOMODCACHE)" >> "$GITHUB_OUTPUT" - name: Cache Go modules and build output - uses: actions/cache@v6 + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: | ${{ steps.go-cache.outputs.modules }} diff --git a/.github/workflows/go-lint.yml b/.github/workflows/go-lint.yml index 61a3b5ced0..bc1e94ae85 100644 --- a/.github/workflows/go-lint.yml +++ b/.github/workflows/go-lint.yml @@ -9,12 +9,12 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Get Go version from mise id: mise run: echo "go-version=$(grep 'golang' mise.toml | cut -d'"' -f2)" >> $GITHUB_OUTPUT - name: Set up Go - uses: actions/setup-go@v7 + uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: go-version: ${{ steps.mise.outputs.go-version }} # See go-ci.yml for why the built-in cache is off. @@ -25,7 +25,7 @@ jobs: echo "build=$(go env GOCACHE)" >> "$GITHUB_OUTPUT" echo "modules=$(go env GOMODCACHE)" >> "$GITHUB_OUTPUT" - name: Cache Go modules, build output, and golangci-lint analysis - uses: actions/cache@v6 + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: | ${{ steps.go-cache.outputs.modules }} diff --git a/.github/workflows/goreleaser-check.yml b/.github/workflows/goreleaser-check.yml index 7e00d61472..229bcafe7b 100644 --- a/.github/workflows/goreleaser-check.yml +++ b/.github/workflows/goreleaser-check.yml @@ -9,11 +9,11 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 # `goreleaser check` only parses the config; it needs neither Go nor # git history. - name: Check GoReleaser config - uses: goreleaser/goreleaser-action@v7 + uses: goreleaser/goreleaser-action@a4f02ab5355a589de60d917a659ce617ed19b3de # v7.3.0 with: # Pinned: GoReleaser v2.10+ deprecates `brews`, which fails # `goreleaser check`. Unpin after moving to `homebrew_casks`. diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index 7b48f00265..33b7758a74 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -47,7 +47,7 @@ jobs: second_latest_tag: ${{ env.second_latest_tag }} steps: - name: Checkout - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 - name: Set current tag, latest (highest version) tag, and second latest tag @@ -103,7 +103,7 @@ jobs: echo "latest_tag=${{ needs.release_type.outputs.latest_tag }}" >> $GITHUB_ENV echo "second_latest_tag=${{ needs.release_type.outputs.second_latest_tag }}" >> $GITHUB_ENV - name: Checkout - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 - name: Set versioning variables @@ -116,7 +116,7 @@ jobs: echo "Versioned formula file: ${{ env.versioned_formula_file }}" echo "Versioned classname: ${{ env.versioned_classname }}" - name: Checkout Homebrew tap - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: repository: sourcegraph/homebrew-src-cli fetch-depth: 0 @@ -171,14 +171,14 @@ jobs: run: | echo "Goreleaser config file: ${{ env.config_file }}" - name: Checkout - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 - name: Get Go version from mise id: mise run: echo "go-version=$(grep 'golang' mise.toml | cut -d'"' -f2)" >> $GITHUB_OUTPUT - name: Set up Go - uses: sourcegraph/actions/go-setup@main + uses: sourcegraph/actions/go-setup@4430dc1e4dde002387a4b655b41f6431ca75b1c1 # main with: go-version: ${{ steps.mise.outputs.go-version }} - run: go test ./... @@ -188,7 +188,7 @@ jobs: DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }} DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }} - name: Run GoReleaser - uses: goreleaser/goreleaser-action@v7 + uses: goreleaser/goreleaser-action@a4f02ab5355a589de60d917a659ce617ed19b3de # v7.3.0 with: # Keep in sync with the version in goreleaser-check.yml. version: v2.9.0 @@ -224,7 +224,7 @@ jobs: echo "Old symlink: ${{ env.old_symlink_name }}" echo "New symlink: ${{ env.new_symlink_name }}" - name: Checkout Homebrew tap - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: repository: sourcegraph/homebrew-src-cli fetch-depth: 0 @@ -245,10 +245,10 @@ jobs: needs: goreleaser steps: - name: Checkout - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 - - uses: actions/setup-node@v7 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: 26.13.0 registry-url: 'https://registry.npmjs.org' diff --git a/.github/workflows/npm-check.yml b/.github/workflows/npm-check.yml index d06cc2f505..92291a5eb6 100644 --- a/.github/workflows/npm-check.yml +++ b/.github/workflows/npm-check.yml @@ -16,7 +16,7 @@ jobs: working-directory: npm-distribution steps: - name: Checkout - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 # The install script downloads the release binary for package.json's # version, which does not exist until the tag is published. - run: npm ci --ignore-scripts diff --git a/.github/workflows/scip.yml b/.github/workflows/scip.yml index 8117010145..06b83af9e6 100644 --- a/.github/workflows/scip.yml +++ b/.github/workflows/scip.yml @@ -6,12 +6,12 @@ jobs: scip-go: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Get Go version from mise id: mise run: echo "go-version=$(grep 'golang' mise.toml | cut -d'"' -f2)" >> $GITHUB_OUTPUT - name: Set up Go - uses: sourcegraph/actions/go-setup@main + uses: sourcegraph/actions/go-setup@4430dc1e4dde002387a4b655b41f6431ca75b1c1 # main with: go-version: ${{ steps.mise.outputs.go-version }}