diff --git a/api.go b/api.go index 79e9efe2e..02153a8d0 100644 --- a/api.go +++ b/api.go @@ -27,11 +27,13 @@ import ( "github.com/sourcegraph/zoekt/query" ) -const mapHeaderBytes uint64 = 48 -const sliceHeaderBytes uint64 = 24 -const stringHeaderBytes uint64 = 16 -const pointerSize uint64 = 8 -const interfaceBytes uint64 = 16 +const ( + mapHeaderBytes uint64 = 48 + sliceHeaderBytes uint64 = 24 + stringHeaderBytes uint64 = 16 + pointerSize uint64 = 8 + interfaceBytes uint64 = 16 +) // FileMatch contains all the matches within a file. type FileMatch struct { diff --git a/api_proto.go b/api_proto.go index 32dde3864..7e17b8ca0 100644 --- a/api_proto.go +++ b/api_proto.go @@ -405,7 +405,6 @@ func RepositoryBranchFromProto(p *proto.RepositoryBranch) RepositoryBranch { Name: p.GetName(), Version: p.GetVersion(), } - } func (r *RepositoryBranch) ToProto() *proto.RepositoryBranch { diff --git a/api_test.go b/api_test.go index ca6b47d56..c7492730d 100644 --- a/api_test.go +++ b/api_test.go @@ -85,7 +85,7 @@ func benchmarkEncoding(data interface{}) func(*testing.B) { } func TestSizeBytesSearchResult(t *testing.T) { - var sr = SearchResult{ + sr := SearchResult{ Stats: Stats{}, // 129 bytes Progress: Progress{}, // 16 bytes Files: []FileMatch{{ // 24 bytes + 460 bytes diff --git a/btree.go b/btree.go index 04b525dca..f70d0a638 100644 --- a/btree.go +++ b/btree.go @@ -237,10 +237,12 @@ func (n *innerNode) maybeSplit(opts btreeOpts) (left node, right node, newKey ng } return &innerNode{ keys: append(make([]ngram, 0, opts.v-1), n.keys[0:opts.v-1]...), - children: append(make([]node, 0, opts.v), n.children[:opts.v]...)}, + children: append(make([]node, 0, opts.v), n.children[:opts.v]...), + }, &innerNode{ keys: append(make([]ngram, 0, (2*opts.v)-1), n.keys[opts.v:]...), - children: append(make([]node, 0, 2*opts.v), n.children[opts.v:]...)}, + children: append(make([]node, 0, 2*opts.v), n.children[opts.v:]...), + }, n.keys[opts.v-1], true } diff --git a/build/builder_test.go b/build/builder_test.go index fa0575855..e5f4742df 100644 --- a/build/builder_test.go +++ b/build/builder_test.go @@ -71,7 +71,7 @@ func TestBuildv16(t *testing.T) { if err != nil { t.Fatal(err) } - err = os.WriteFile(wantP, data, 0644) + err = os.WriteFile(wantP, data, 0o644) if err != nil { t.Fatal(err) } @@ -798,7 +798,7 @@ func TestIsLowPriority(t *testing.T) { func createTestShard(t *testing.T, indexDir string, r zoekt.Repository, numShards int, optFns ...func(options *Options)) []string { t.Helper() - if err := os.MkdirAll(filepath.Dir(indexDir), 0700); err != nil { + if err := os.MkdirAll(filepath.Dir(indexDir), 0o700); err != nil { t.Fatal(err) } @@ -897,7 +897,6 @@ func createTestCompoundShard(t *testing.T, indexDir string, repositories []zoekt } func TestIgnoreSizeMax(t *testing.T) { - for _, test := range []struct { name string largeFiles []string diff --git a/build/e2e_test.go b/build/e2e_test.go index 838057e0b..f66b64b9e 100644 --- a/build/e2e_test.go +++ b/build/e2e_test.go @@ -132,7 +132,7 @@ func TestBasic(t *testing.T) { t.Fatal(err) } - if err := os.WriteFile(p+".meta", b, 0600); err != nil { + if err := os.WriteFile(p+".meta", b, 0o600); err != nil { t.Fatal(err) } } @@ -682,7 +682,6 @@ func TestDeltaShards(t *testing.T) { expectedDocuments: []zoekt.Document{barAtMain, fooAtMainAndRelease}, }, { - name: "tombstone foo", documents: nil, optFn: func(t *testing.T, o *Options) { diff --git a/build/scoring_test.go b/build/scoring_test.go index 4254d60b1..e5378fe88 100644 --- a/build/scoring_test.go +++ b/build/scoring_test.go @@ -467,7 +467,8 @@ func Get() { `), query: &query.And{Children: []query.Q{ &query.Symbol{Expr: &query.Substring{Pattern: "http", Content: true}}, - &query.Symbol{Expr: &query.Substring{Pattern: "Get", Content: true}}}}, + &query.Symbol{Expr: &query.Substring{Pattern: "Get", Content: true}}, + }}, language: "Go", // 7000 (full base match) + 800 (Go func) + 50 (Exported Go) + 500 (word) + 200 (atom) + 10 (file order) wantScore: 8560, @@ -516,7 +517,8 @@ func checkScoring(t *testing.T, c scoreCase, parserType ctags.CTagsParserType) { Name: "repo", }, LanguageMap: ctags.LanguageMap{ - normalizeLanguage(c.language): parserType}, + normalizeLanguage(c.language): parserType, + }, } epsilon := 0.01 @@ -628,7 +630,6 @@ func TestDocumentRanks(t *testing.T) { DocumentRanksWeight: c.documentRanksWeight, DebugScore: true, }) - if err != nil { t.Fatal(err) } @@ -717,7 +718,6 @@ func TestRepoRanks(t *testing.T) { UseDocumentRanks: true, DebugScore: true, }) - if err != nil { t.Fatal(err) } diff --git a/cmd/zoekt-dynamic-indexserver/main.go b/cmd/zoekt-dynamic-indexserver/main.go index 229de7ed4..fd9244528 100644 --- a/cmd/zoekt-dynamic-indexserver/main.go +++ b/cmd/zoekt-dynamic-indexserver/main.go @@ -148,7 +148,6 @@ func (s *indexServer) serveIndex(w http.ResponseWriter, r *http.Request) { dec.DisallowUnknownFields() var req indexRequest err := dec.Decode(&req) - if err != nil { log.Printf("Error decoding index request: %v", err) http.Error(w, "JSON parser error", http.StatusBadRequest) @@ -170,7 +169,6 @@ func (s *indexServer) serveIndex(w http.ResponseWriter, r *http.Request) { func (s *indexServer) serveTruncate(w http.ResponseWriter, r *http.Request) { route := "truncate" err := emptyDirectory(s.opts.repoDir) - if err != nil { err = fmt.Errorf("Failed to empty repoDir repoDir: %v with error: %v", s.opts.repoDir, err) @@ -179,7 +177,6 @@ func (s *indexServer) serveTruncate(w http.ResponseWriter, r *http.Request) { } err = emptyDirectory(s.opts.indexDir) - if err != nil { err = fmt.Errorf("Failed to empty repoDir indexDir: %v with error: %v", s.opts.repoDir, err) @@ -247,7 +244,6 @@ func (s *indexServer) startIndexingApi() { func emptyDirectory(dir string) error { files, err := os.ReadDir(dir) - if err != nil { return err } diff --git a/cmd/zoekt-dynamic-indexserver/main_test.go b/cmd/zoekt-dynamic-indexserver/main_test.go index cd3245979..c1302ad28 100644 --- a/cmd/zoekt-dynamic-indexserver/main_test.go +++ b/cmd/zoekt-dynamic-indexserver/main_test.go @@ -13,9 +13,7 @@ import ( "time" ) -var ( - cmdTimeout = 100 * time.Millisecond -) +var cmdTimeout = 100 * time.Millisecond func captureOutput(f func()) string { var buf bytes.Buffer @@ -91,7 +89,6 @@ func TestIndexRepository(t *testing.T) { } _, err := indexRepository(opts, req) - if err != nil { t.Fatal(err) } diff --git a/cmd/zoekt-repo-index/main.go b/cmd/zoekt-repo-index/main.go index 5e7517f20..d5b04d5e4 100644 --- a/cmd/zoekt-repo-index/main.go +++ b/cmd/zoekt-repo-index/main.go @@ -324,7 +324,8 @@ func getManifest(repo *git.Repository, branch, path string) (*manifest.Manifest, // iterateManifest constructs a complete tree from the given Manifest. func iterateManifest(mf *manifest.Manifest, baseURL url.URL, revPrefix string, - cache *gitindex.RepoCache) (map[fileKey]gitindex.BlobLocation, map[string]plumbing.Hash, error) { + cache *gitindex.RepoCache, +) (map[fileKey]gitindex.BlobLocation, map[string]plumbing.Hash, error) { allFiles := map[fileKey]gitindex.BlobLocation{} allVersions := map[string]plumbing.Hash{} for _, p := range mf.Project { diff --git a/cmd/zoekt-sourcegraph-indexserver/backoff.go b/cmd/zoekt-sourcegraph-indexserver/backoff.go index e8e2cb2d1..6e628c9a2 100644 --- a/cmd/zoekt-sourcegraph-indexserver/backoff.go +++ b/cmd/zoekt-sourcegraph-indexserver/backoff.go @@ -1,8 +1,9 @@ package main import ( - "github.com/sourcegraph/log" "time" + + "github.com/sourcegraph/log" ) type backoff struct { diff --git a/cmd/zoekt-sourcegraph-indexserver/backoff_test.go b/cmd/zoekt-sourcegraph-indexserver/backoff_test.go index 0480f246f..67268a368 100644 --- a/cmd/zoekt-sourcegraph-indexserver/backoff_test.go +++ b/cmd/zoekt-sourcegraph-indexserver/backoff_test.go @@ -1,9 +1,10 @@ package main import ( - "github.com/sourcegraph/log/logtest" "testing" "time" + + "github.com/sourcegraph/log/logtest" ) func TestQueue_BackoffOnFail(t *testing.T) { diff --git a/cmd/zoekt-sourcegraph-indexserver/cleanup.go b/cmd/zoekt-sourcegraph-indexserver/cleanup.go index 3a8a05407..0d87d676e 100644 --- a/cmd/zoekt-sourcegraph-indexserver/cleanup.go +++ b/cmd/zoekt-sourcegraph-indexserver/cleanup.go @@ -30,7 +30,7 @@ var metricCleanupDuration = promauto.NewHistogram(prometheus.HistogramOpts{ func cleanup(indexDir string, repos []uint32, now time.Time, shardMerging bool) { start := time.Now() trashDir := filepath.Join(indexDir, ".trash") - if err := os.MkdirAll(trashDir, 0755); err != nil { + if err := os.MkdirAll(trashDir, 0o755); err != nil { log.Printf("failed to create trash dir: %v", err) } diff --git a/cmd/zoekt-sourcegraph-indexserver/cleanup_test.go b/cmd/zoekt-sourcegraph-indexserver/cleanup_test.go index f6e532804..6514b8ffd 100644 --- a/cmd/zoekt-sourcegraph-indexserver/cleanup_test.go +++ b/cmd/zoekt-sourcegraph-indexserver/cleanup_test.go @@ -164,7 +164,7 @@ func TestCleanup(t *testing.T) { func createTestShard(t *testing.T, repo string, id uint32, path string, optFns ...func(in *zoekt.Repository)) { t.Helper() - if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil { + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { t.Fatal(err) } r := &zoekt.Repository{ @@ -178,7 +178,7 @@ func createTestShard(t *testing.T, repo string, id uint32, path string, optFns . if err != nil { t.Fatal(err) } - f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0600) + f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0o600) if err != nil { t.Fatal(err) } diff --git a/cmd/zoekt-sourcegraph-indexserver/index.go b/cmd/zoekt-sourcegraph-indexserver/index.go index 83c3acef0..39453987d 100644 --- a/cmd/zoekt-sourcegraph-indexserver/index.go +++ b/cmd/zoekt-sourcegraph-indexserver/index.go @@ -221,7 +221,7 @@ func gitIndex(c gitIndexConfig, o *indexArgs, sourcegraph Sourcegraph, l sglog.L metricFetchDuration.WithLabelValues(success, name).Observe(fetchDuration.Seconds()) }() - var runFetch = func(branches []zoekt.RepositoryBranch) error { + runFetch := func(branches []zoekt.RepositoryBranch) error { // We shallow fetch each commit specified in zoekt.Branches. This requires // the server to have configured both uploadpack.allowAnySHA1InWant and // uploadpack.allowFilter. (See gitservice.go in the Sourcegraph repository) @@ -229,7 +229,8 @@ func gitIndex(c gitIndexConfig, o *indexArgs, sourcegraph Sourcegraph, l sglog.L "-C", gitDir, "-c", "protocol.version=2", "-c", "http.extraHeader=X-Sourcegraph-Actor-UID: internal", - "fetch", "--depth=1", o.CloneURL} + "fetch", "--depth=1", o.CloneURL, + } var commits []string for _, b := range branches { @@ -359,7 +360,7 @@ func gitIndex(c gitIndexConfig, o *indexArgs, sourcegraph Sourcegraph, l sglog.L return err } - if err := os.WriteFile(documentsRankFile, b, 0600); err != nil { + if err := os.WriteFile(documentsRankFile, b, 0o600); err != nil { return fmt.Errorf("failed to write %s to disk: %w", documentsRankFile, err) } diff --git a/cmd/zoekt-sourcegraph-indexserver/index_test.go b/cmd/zoekt-sourcegraph-indexserver/index_test.go index f50f6f1b4..58bf0e774 100644 --- a/cmd/zoekt-sourcegraph-indexserver/index_test.go +++ b/cmd/zoekt-sourcegraph-indexserver/index_test.go @@ -157,7 +157,6 @@ func TestIterateIndexOptions_Fingerprint(t *testing.T) { } }) } - }) t.Run("REST", func(t *testing.T) { @@ -321,13 +320,11 @@ func TestIterateIndexOptions_Fingerprint(t *testing.T) { } }) } - }) } func TestGetIndexOptions(t *testing.T) { t.Run("gRPC", func(t *testing.T) { - type testCase struct { name string response *proto.SearchConfigurationResponse @@ -465,7 +462,6 @@ func TestGetIndexOptions(t *testing.T) { // Mimic our fingerprint API, which doesn't return anything if the // repo hasn't changed. t.Run("unchanged", func(t *testing.T) { - called := false mockClient := &mockGRPCClient{ mockSearchConfiguration: func(_ context.Context, _ *proto.SearchConfigurationRequest, _ ...grpc.CallOption) (*proto.SearchConfigurationResponse, error) { @@ -506,7 +502,6 @@ func TestGetIndexOptions(t *testing.T) { t.Fatalf("expected no options, got %v", gotAtLeastOneOption) } }) - }) t.Run("REST", func(t *testing.T) { var response []byte @@ -834,7 +829,6 @@ func TestIndex(t *testing.T) { for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - var got []string runCmd := func(c *exec.Cmd) error { cmd := strings.Join(c.Args, " ") diff --git a/cmd/zoekt-sourcegraph-indexserver/main.go b/cmd/zoekt-sourcegraph-indexserver/main.go index 694ee4075..44ee746d0 100644 --- a/cmd/zoekt-sourcegraph-indexserver/main.go +++ b/cmd/zoekt-sourcegraph-indexserver/main.go @@ -902,7 +902,6 @@ func (s *Server) handleDebugList(w http.ResponseWriter, r *http.Request) { // trigger an initial merge run. In the steady-state, merges happen rarely, even // on busy instances, and users can rely on automatic merging instead. func (s *Server) handleDebugMerge(w http.ResponseWriter, _ *http.Request) { - // A merge operation can take very long, depending on the number merges and the // target size of the compound shards. We run the merge in the background and // return immediately to the user. @@ -1027,7 +1026,7 @@ func setupTmpDir(logger sglog.Logger, main bool, index string) error { } } - if err := os.MkdirAll(tmpRoot, 0755); err != nil { + if err := os.MkdirAll(tmpRoot, 0o755); err != nil { return err } @@ -1275,7 +1274,6 @@ func startServer(conf rootConfig) error { go func() { debug.Printf("serving HTTP on %s", conf.listen) log.Fatal(http.ListenAndServe(conf.listen, mux)) - }() // Serve mux on a unix domain socket on a best-effort-basis so that @@ -1303,7 +1301,7 @@ func startServer(conf rootConfig) error { // it. // // See https://github.com/golang/go/issues/11822 for more context. - if err := os.Chmod(socket, 0777); err != nil { + if err := os.Chmod(socket, 0o777); err != nil { return fmt.Errorf("failed to change permission of socket %s: %w", socket, err) } debug.Printf("serving HTTP on %s", socket) @@ -1362,7 +1360,7 @@ func newServer(conf rootConfig) (*Server, error) { } if _, err := os.Stat(conf.index); err != nil { - if err := os.MkdirAll(conf.index, 0755); err != nil { + if err := os.MkdirAll(conf.index, 0o755); err != nil { return nil, fmt.Errorf("MkdirAll %s: %v", conf.index, err) } } diff --git a/cmd/zoekt-sourcegraph-indexserver/main_test.go b/cmd/zoekt-sourcegraph-indexserver/main_test.go index de0de51bc..9a7d80815 100644 --- a/cmd/zoekt-sourcegraph-indexserver/main_test.go +++ b/cmd/zoekt-sourcegraph-indexserver/main_test.go @@ -134,7 +134,6 @@ func TestServer_parallelism(t *testing.T) { func TestListRepoIDs(t *testing.T) { t.Run("gRPC", func(t *testing.T) { - grpcClient := &mockGRPCClient{} clientOptions := []SourcegraphClientOption{ @@ -247,7 +246,6 @@ func TestListRepoIDs_Error_REST(t *testing.T) { msg := "deadbeaf deadbeaf" ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - // This is how Sourcegraph returns error messages to the caller. http.Error(w, msg, http.StatusInternalServerError) })) diff --git a/cmd/zoekt-sourcegraph-indexserver/merge.go b/cmd/zoekt-sourcegraph-indexserver/merge.go index 67a005c80..7c3ff0fba 100644 --- a/cmd/zoekt-sourcegraph-indexserver/merge.go +++ b/cmd/zoekt-sourcegraph-indexserver/merge.go @@ -57,7 +57,6 @@ func (s *Server) doMerge() { // same as doMerge but with a configurable merge command. func (s *Server) merge(mergeCmd func(args ...string) *exec.Cmd) { - // Guard against the user triggering competing merge jobs with the debug // command. if !mergeRunning.CompareAndSwap(false, true) { diff --git a/cmd/zoekt-sourcegraph-indexserver/merge_test.go b/cmd/zoekt-sourcegraph-indexserver/merge_test.go index 690f83546..a7491d96b 100644 --- a/cmd/zoekt-sourcegraph-indexserver/merge_test.go +++ b/cmd/zoekt-sourcegraph-indexserver/merge_test.go @@ -118,7 +118,6 @@ func TestCallMerge(t *testing.T) { } func TestMerge(t *testing.T) { - // A fixed set of shards gives us reliable shard sizes which makes it easy to // define a cutoff with targetSizeBytes. m := []string{ @@ -197,7 +196,6 @@ func TestMerge(t *testing.T) { checkCount(dir, "*_v16.00000.zoekt", tc.wantSimple) }) } - } func copyTestShards(dstDir string, srcShards []string) ([]string, error) { diff --git a/cmd/zoekt-sourcegraph-indexserver/owner.go b/cmd/zoekt-sourcegraph-indexserver/owner.go index a1c5c32cb..572ac8a7c 100644 --- a/cmd/zoekt-sourcegraph-indexserver/owner.go +++ b/cmd/zoekt-sourcegraph-indexserver/owner.go @@ -67,7 +67,7 @@ hostname=%s `, o.Hostname)) // Always write out since we may update the comment - if err := os.WriteFile(o.Path, content, 0600); err != nil { + if err := os.WriteFile(o.Path, content, 0o600); err != nil { return fmt.Errorf("failed to write owner file %s: %w", o.Path, err) } diff --git a/cmd/zoekt-sourcegraph-indexserver/owner_test.go b/cmd/zoekt-sourcegraph-indexserver/owner_test.go index b1245403b..5eaef0a95 100644 --- a/cmd/zoekt-sourcegraph-indexserver/owner_test.go +++ b/cmd/zoekt-sourcegraph-indexserver/owner_test.go @@ -38,7 +38,7 @@ func TestOwner(t *testing.T) { assertSuccess(bob.Check()) // bob is still the owner // Test what happens if someone corrupts the file - if err := os.WriteFile(path, []byte("!corrupt"), 0600); err != nil { + if err := os.WriteFile(path, []byte("!corrupt"), 0o600); err != nil { t.Fatal(err) } assertFailed(alice.Check()) // corrupt so fail diff --git a/cmd/zoekt-sourcegraph-indexserver/queue_test.go b/cmd/zoekt-sourcegraph-indexserver/queue_test.go index 63d1f9f81..e10937d87 100644 --- a/cmd/zoekt-sourcegraph-indexserver/queue_test.go +++ b/cmd/zoekt-sourcegraph-indexserver/queue_test.go @@ -129,7 +129,6 @@ func TestQueue_Bump(t *testing.T) { } func TestQueue_Integration_DebugQueue(t *testing.T) { - // helper function to normalize the queue's debug output - this makes the test less brittle // + makes it much less annoying to make edits to the expected output in a way that doesn't // materially affect the caller diff --git a/cmd/zoekt-sourcegraph-indexserver/sg.go b/cmd/zoekt-sourcegraph-indexserver/sg.go index d28954cd5..061a454cf 100644 --- a/cmd/zoekt-sourcegraph-indexserver/sg.go +++ b/cmd/zoekt-sourcegraph-indexserver/sg.go @@ -141,7 +141,6 @@ func newSourcegraphClient(rootURL *url.URL, hostname string, opts ...Sourcegraph } return client - } // sourcegraphClient contains methods which interact with the sourcegraph API. @@ -763,7 +762,6 @@ func (s *sourcegraphClient) UpdateIndexStatus(repositories []indexStatus) error func (s *sourcegraphClient) updateIndexStatusGRPC(r updateIndexStatusRequest) error { request := r.ToProto() _, err := s.grpcClient.UpdateIndexStatus(context.Background(), request) - if err != nil { return fmt.Errorf("failed to update index status: %w", err) } @@ -924,7 +922,6 @@ func (sf sourcegraphFake) GetIndexOptions(repos ...uint32) ([]indexOptionsItem, items[idx] = indexOptionsItem{IndexOptions: opts} } }) - if err != nil { return nil, err } diff --git a/cmd/zoekt-test/main.go b/cmd/zoekt-test/main.go index d2d87dd01..6dee60297 100644 --- a/cmd/zoekt-test/main.go +++ b/cmd/zoekt-test/main.go @@ -169,8 +169,10 @@ func compare(dir, patfile string, caseSensitive bool) error { return nil } -var memprofile = flag.String("memprofile", "", "write memory profile to `file`") -var cpuprofile = flag.String("cpuprofile", "", "write memory profile to `file`") +var ( + memprofile = flag.String("memprofile", "", "write memory profile to `file`") + cpuprofile = flag.String("cpuprofile", "", "write memory profile to `file`") +) func testLoadIndexDir(indexDir string) { var a, b runtime.MemStats diff --git a/cmd/zoekt-webserver/grpc/server/server_test.go b/cmd/zoekt-webserver/grpc/server/server_test.go index acce877b9..eae99d60d 100644 --- a/cmd/zoekt-webserver/grpc/server/server_test.go +++ b/cmd/zoekt-webserver/grpc/server/server_test.go @@ -129,7 +129,6 @@ func TestFuzzGRPCChunkSender(t *testing.T) { if diff := cmp.Diff(expectedResult.GetProgress(), receivedResponse.GetProgress(), protocmp.Transform()); diff != "" { return fmt.Errorf("unexpected difference in progress (-want +got):\n%s", diff) } - } else { // All other responses should ensure that the progress' priority is less than the max-pending priority, to // ensure that the client consumes the entire set of chunks @@ -140,7 +139,6 @@ func TestFuzzGRPCChunkSender(t *testing.T) { i, receivedResponse, receivedResponse.GetProgress().GetPriority(), receivedResponse.GetProgress().GetMaxPendingPriority(), ) - } } diff --git a/cmd/zoekt-webserver/main.go b/cmd/zoekt-webserver/main.go index 2befd9982..c54afdb42 100644 --- a/cmd/zoekt-webserver/main.go +++ b/cmd/zoekt-webserver/main.go @@ -551,9 +551,7 @@ func (s *loggedSearcher) StreamSearch( opts *zoekt.SearchOptions, sender zoekt.Sender, ) error { - var ( - stats zoekt.Stats - ) + var stats zoekt.Stats metricSearchRequestsTotal.Inc() err := s.Streamer.StreamSearch(ctx, q, opts, stream.SenderFunc(func(event *zoekt.SearchResult) { diff --git a/cmd/zoekt-webserver/main_linux.go b/cmd/zoekt-webserver/main_linux.go index dbb198e54..160d5ddf9 100644 --- a/cmd/zoekt-webserver/main_linux.go +++ b/cmd/zoekt-webserver/main_linux.go @@ -1,10 +1,11 @@ package main import ( + "path" + "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/procfs" sglog "github.com/sourcegraph/log" - "path" ) func mustRegisterMemoryMapMetrics(logger sglog.Logger) { diff --git a/eval_test.go b/eval_test.go index 7b02ba18c..aeff6c27e 100644 --- a/eval_test.go +++ b/eval_test.go @@ -351,7 +351,8 @@ func TestGatherBranches(t *testing.T) { {"main", "v1"}, {"bar", "v1"}, {"quz", "v1"}, - }}, + }, + }, Document{Name: "f1", Content: content, Branches: []string{"foo", "bar", "quz"}}, Document{Name: "f2", Content: content, Branches: []string{"foo", "foo-2"}}, Document{Name: "f3", Content: content, Branches: []string{"main"}}) diff --git a/gitindex/filter.go b/gitindex/filter.go index 2ff52605a..3d0fb85c9 100644 --- a/gitindex/filter.go +++ b/gitindex/filter.go @@ -42,7 +42,6 @@ func NewFilter(includeRegex, excludeRegex string) (*Filter, error) { var err error if includeRegex != "" { f.inc, err = regexp.Compile(includeRegex) - if err != nil { return nil, err } diff --git a/gitindex/ignore_test.go b/gitindex/ignore_test.go index fa8981c86..ca19613d9 100644 --- a/gitindex/ignore_test.go +++ b/gitindex/ignore_test.go @@ -17,7 +17,7 @@ import ( ) func createSourcegraphignoreRepo(dir string) error { - if err := os.MkdirAll(dir, 0755); err != nil { + if err := os.MkdirAll(dir, 0o755); err != nil { return err } script := `mkdir repo diff --git a/gitindex/index_test.go b/gitindex/index_test.go index a1932d55e..1b1886120 100644 --- a/gitindex/index_test.go +++ b/gitindex/index_test.go @@ -562,12 +562,12 @@ func TestIndexDeltaBasic(t *testing.T) { file := filepath.Join(repositoryDir, d.Name) - err := os.MkdirAll(filepath.Dir(file), 0755) + err := os.MkdirAll(filepath.Dir(file), 0o755) if err != nil { t.Fatalf("ensuring that folders exist for file %q: %s", file, err) } - err = os.WriteFile(file, d.Content, 0644) + err = os.WriteFile(file, d.Content, 0o644) if err != nil { t.Fatalf("writing file %q: %s", d.Name, err) } @@ -753,7 +753,7 @@ func TestRepoPathRanks(t *testing.T) { } func runScript(t *testing.T, cwd string, script string) { - err := os.MkdirAll(cwd, 0755) + err := os.MkdirAll(cwd, 0o755) if err != nil { t.Fatalf("ensuring path %q exists: %s", cwd, err) } diff --git a/gitindex/submodule_test.go b/gitindex/submodule_test.go index 51163e007..ae630831e 100644 --- a/gitindex/submodule_test.go +++ b/gitindex/submodule_test.go @@ -23,18 +23,20 @@ func TestParseGitModules(t *testing.T) { cases := []struct { data string want map[string]*SubmoduleEntry - }{{ - `[submodule "plugins/abc"] + }{ + { + `[submodule "plugins/abc"] path = plugins/abc url = ../plugins/abc branch = .`, - map[string]*SubmoduleEntry{ - "plugins/abc": { - Path: "plugins/abc", - URL: "../plugins/abc", - Branch: ".", + map[string]*SubmoduleEntry{ + "plugins/abc": { + Path: "plugins/abc", + URL: "../plugins/abc", + Branch: ".", + }, }, - }}, + }, { "\uFEFF" + `[submodule "plugins/abc"] path = plugins/abc @@ -46,7 +48,8 @@ func TestParseGitModules(t *testing.T) { URL: "../plugins/abc", Branch: ".", }, - }}, + }, + }, {"", map[string]*SubmoduleEntry{}}, } diff --git a/gitindex/tree.go b/gitindex/tree.go index c7d441beb..98f9d2092 100644 --- a/gitindex/tree.go +++ b/gitindex/tree.go @@ -98,7 +98,8 @@ func (rw *repoWalker) parseModuleMap(t *object.Tree) error { // non-nil, recurse into submodules. In addition, it returns a mapping // that indicates in which repo each SHA1 can be found. func TreeToFiles(r *git.Repository, t *object.Tree, - repoURL string, repoCache *RepoCache) (map[fileKey]BlobLocation, map[string]plumbing.Hash, error) { + repoURL string, repoCache *RepoCache, +) (map[fileKey]BlobLocation, map[string]plumbing.Hash, error) { rw := newRepoWalker(r, repoURL, repoCache) if err := rw.parseModuleMap(t); err != nil { diff --git a/grpc/chunk/chunker_test.go b/grpc/chunk/chunker_test.go index d7c87532c..b17799d2b 100644 --- a/grpc/chunk/chunker_test.go +++ b/grpc/chunk/chunker_test.go @@ -201,7 +201,6 @@ func TestChunkerE2E(t *testing.T) { receivedPayloadSizeBytes, humanize.Bytes(uint64(receivedPayloadSizeBytes)), ) } - }) } } diff --git a/grpc/internalerrs/common.go b/grpc/internalerrs/common.go index e14c733a7..35bad4e0b 100644 --- a/grpc/internalerrs/common.go +++ b/grpc/internalerrs/common.go @@ -208,7 +208,6 @@ func findNonUTF8StringFields(m proto.Message) ([]string, error) { return nil }) - if err != nil { return nil, fmt.Errorf("iterating over proto message: %w", err) } @@ -228,7 +227,6 @@ func massageIntoStatusErr(err error) (s *status.Status, ok bool) { if errors.Is(err, context.Canceled) { return status.New(codes.Canceled, context.Canceled.Error()), true - } if errors.Is(err, context.DeadlineExceeded) { diff --git a/grpc/internalerrs/prometheus.go b/grpc/internalerrs/prometheus.go index fb69a99c0..5c9fb9551 100644 --- a/grpc/internalerrs/prometheus.go +++ b/grpc/internalerrs/prometheus.go @@ -87,7 +87,6 @@ func newPrometheusServerStream(s grpc.ClientStream, serviceName, methodName stri } }, } - } func doObservation(serviceName, methodName string, rpcErr error) { diff --git a/grpc/messagesize/messagesize_test.go b/grpc/messagesize/messagesize_test.go index 2bc064298..d49ecc140 100644 --- a/grpc/messagesize/messagesize_test.go +++ b/grpc/messagesize/messagesize_test.go @@ -9,12 +9,10 @@ import ( ) func TestGetMessageSizeBytesFromString(t *testing.T) { - t.Run("8 MB", func(t *testing.T) { sizeString := "8MB" size, err := getMessageSizeBytesFromString(sizeString, 0, math.MaxInt) - if err != nil { t.Fatalf("unexpected error: %s", err) } diff --git a/grpc/messagesize/prometheus_test.go b/grpc/messagesize/prometheus_test.go index 739dda598..193d607cb 100644 --- a/grpc/messagesize/prometheus_test.go +++ b/grpc/messagesize/prometheus_test.go @@ -161,7 +161,6 @@ func TestUnaryServerInterceptor(t *testing.T) { } func TestStreamServerInterceptor(t *testing.T) { - response1 := &newspb.BinaryAttachment{ Name: "", Data: []byte("response"), @@ -666,7 +665,8 @@ func TestObserver(t *testing.T) { "key2": "value2", }, }, - }}, + }, + }, } for _, tc := range testCases { @@ -754,5 +754,7 @@ func (s *mockClientStream) CloseSend() error { return errors.New("close send not implemented") } -var _ grpc.ServerStream = &mockServerStream{} -var _ grpc.ClientStream = &mockClientStream{} +var ( + _ grpc.ServerStream = &mockServerStream{} + _ grpc.ClientStream = &mockClientStream{} +) diff --git a/ignore/ignore_test.go b/ignore/ignore_test.go index d03d484ac..54ff3317a 100644 --- a/ignore/ignore_test.go +++ b/ignore/ignore_test.go @@ -18,7 +18,8 @@ func TestParseIgnoreFile(t *testing.T) { ignoreFile: []byte("# ignore this \n \n foo\n bar/"), wantIgnoreList: []glob.Glob{ glob.MustCompile("foo**", '/'), - glob.MustCompile("bar/**", '/')}, + glob.MustCompile("bar/**", '/'), + }, }, { ignoreFile: []byte("/foo/bar \n /qux \n *.go\nfoo.go"), @@ -26,7 +27,8 @@ func TestParseIgnoreFile(t *testing.T) { glob.MustCompile("foo/bar**", '/'), glob.MustCompile("qux**", '/'), glob.MustCompile("*.go", '/'), - glob.MustCompile("foo.go", '/')}, + glob.MustCompile("foo.go", '/'), + }, }, } diff --git a/index_test.go b/index_test.go index 13adcf7d7..9836032e6 100644 --- a/index_test.go +++ b/index_test.go @@ -595,7 +595,6 @@ func TestSearchStats(t *testing.T) { } }) } - }) } @@ -977,7 +976,6 @@ func TestSearchMatchAllRegexp(t *testing.T) { if len(matches[0].LineMatches[0].Line) != 4 || len(matches[1].LineMatches[0].Line) != 4 { t.Fatalf("want 4 chars in every file, got %#v", matches) } - }) t.Run("ChunkMatches", func(t *testing.T) { @@ -990,7 +988,6 @@ func TestSearchMatchAllRegexp(t *testing.T) { if len(matches[0].ChunkMatches[0].Content) != 4 || len(matches[1].ChunkMatches[0].Content) != 4 { t.Fatalf("want 4 chars in every file, got %#v", matches) } - }) } @@ -1228,7 +1225,6 @@ func TestBranchReport(t *testing.T) { t.Fatalf("got branches %q, want %q", f.Branches, branches) } }) - } func TestBranchVersions(t *testing.T) { @@ -3582,7 +3578,6 @@ func TestStats(t *testing.T) { if diff := cmp.Diff(want, got, ignored...); diff != "" { t.Fatalf("mismatch (-want +got):\n%s", diff) } - }) t.Run("one simple shard", func(t *testing.T) { @@ -3609,7 +3604,6 @@ func TestStats(t *testing.T) { if diff := cmp.Diff(want, got, ignored...); diff != "" { t.Fatalf("mismatch (-want +got):\n%s", diff) } - }) t.Run("one compound shard", func(t *testing.T) { @@ -3703,7 +3697,6 @@ func TestStats(t *testing.T) { if diff := cmp.Diff(want, got, ignored...); diff != "" { t.Fatalf("mismatch (-want +got):\n%s", diff) } - }) } diff --git a/internal/e2e/e2e_rank_test.go b/internal/e2e/e2e_rank_test.go index 47e6666d7..77e37e44e 100644 --- a/internal/e2e/e2e_rank_test.go +++ b/internal/e2e/e2e_rank_test.go @@ -187,7 +187,7 @@ func assertGolden(t *testing.T, name string, got []byte) { wantPath := filepath.Join("testdata", name+".txt") if *update { - if err := os.WriteFile(wantPath, got, 0600); err != nil { + if err := os.WriteFile(wantPath, got, 0o600); err != nil { t.Fatal(err) } } @@ -206,11 +206,13 @@ type rankingQuery struct { Target string } -var tarballCache = "/tmp/zoekt-test-ranking-tarballs-" + os.Getenv("USER") -var shardCache = "/tmp/zoekt-test-ranking-shards-" + os.Getenv("USER") +var ( + tarballCache = "/tmp/zoekt-test-ranking-tarballs-" + os.Getenv("USER") + shardCache = "/tmp/zoekt-test-ranking-shards-" + os.Getenv("USER") +) func indexURL(indexDir, u string) error { - if err := os.MkdirAll(tarballCache, 0700); err != nil { + if err := os.MkdirAll(tarballCache, 0o700); err != nil { return err } @@ -264,7 +266,7 @@ func download(url, dst string) error { } defer rc.Close() - f, err := os.OpenFile(tmpPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) + f, err := os.OpenFile(tmpPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600) if err != nil { return err } diff --git a/json/json.go b/json/json.go index 79b2edd6e..80b47348d 100644 --- a/json/json.go +++ b/json/json.go @@ -115,7 +115,8 @@ func jsonError(w http.ResponseWriter, statusCode int, err string) { func CalculateDefaultSearchLimits(ctx context.Context, q query.Q, searcher zoekt.Searcher, - opts *zoekt.SearchOptions) error { + opts *zoekt.SearchOptions, +) error { if opts.MaxDocDisplayCount == 0 || opts.ShardMaxMatchCount != 0 { return nil } @@ -134,7 +135,6 @@ func CalculateDefaultSearchLimits(ctx context.Context, // 10k docs, 50 maxResultDocs -> max match = (250 + 250 / 10) opts.ShardMaxMatchCount = maxResultDocs*5 + (5*maxResultDocs)/(numdocs/1000) - } else { // Virtually no limits for a small corpus. n := numdocs + maxResultDocs*100 diff --git a/matchtree.go b/matchtree.go index a653c841e..61d7c84d2 100644 --- a/matchtree.go +++ b/matchtree.go @@ -1058,7 +1058,6 @@ func (d *indexData) newMatchTree(q query.Q, opt matchTreeOpt) (matchTree, error) } masks = append(masks, mask) } - } return &branchQueryMatchTree{ masks: masks, diff --git a/merge_test.go b/merge_test.go index a5a59ebbc..07abf1ca6 100644 --- a/merge_test.go +++ b/merge_test.go @@ -115,7 +115,7 @@ func checkSameShards(t *testing.T, shard1, shard2 string) { if *update { t.Logf("updating %s", shard1) - err := os.WriteFile(shard1, b2, 0600) + err := os.WriteFile(shard1, b2, 0o600) if err != nil { t.Fatal(err) } diff --git a/query/parse.go b/query/parse.go index 8602d7574..028017692 100644 --- a/query/parse.go +++ b/query/parse.go @@ -119,7 +119,6 @@ func parseExpr(in []byte) (Q, int, error) { expr = &caseQ{text} case tokRepo: r, err := regexp.Compile(text) - if err != nil { return nil, 0, err } diff --git a/query/query_proto_test.go b/query/query_proto_test.go index e1e8b8582..a1d6aaaa4 100644 --- a/query/query_proto_test.go +++ b/query/query_proto_test.go @@ -101,7 +101,6 @@ func TestQueryRoundtrip(t *testing.T) { } }) } - } func regexpMustParse(s string) *syntax.Regexp { diff --git a/read_test.go b/read_test.go index dad0578c9..1e5668d8a 100644 --- a/read_test.go +++ b/read_test.go @@ -58,7 +58,6 @@ func TestReadWrite(t *testing.T) { var toc indexTOC err = r.readTOC(&toc) - if err != nil { t.Errorf("got read error %v", err) } @@ -272,7 +271,7 @@ func TestReadSearch(t *testing.T) { if raw, err := json.MarshalIndent(got, "", " "); err != nil { t.Errorf("failed marshalling search results for %s during updating: %v", name, err) continue - } else if err := os.WriteFile(golden, raw, 0644); err != nil { + } else if err := os.WriteFile(golden, raw, 0o644); err != nil { t.Errorf("failed writing search results for %s during updating: %v", name, err) continue } @@ -376,7 +375,7 @@ func TestBackwardsCompat(t *testing.T) { outname := fmt.Sprintf("testdata/backcompat/new_v%d.%05d.zoekt", IndexFormatVersion, 0) t.Log("writing new file", outname) - err = os.WriteFile(outname, buf.Bytes(), 0644) + err = os.WriteFile(outname, buf.Bytes(), 0o644) if err != nil { t.Fatalf("Creating output file: %v", err) } @@ -402,7 +401,6 @@ func TestBackwardsCompat(t *testing.T) { var toc indexTOC err = r.readTOC(&toc) - if err != nil { t.Errorf("got read error %v", err) } diff --git a/shards/aggregate.go b/shards/aggregate.go index 0491b0be5..e6faf5de1 100644 --- a/shards/aggregate.go +++ b/shards/aggregate.go @@ -12,13 +12,11 @@ import ( "github.com/sourcegraph/zoekt/stream" ) -var ( - metricFinalAggregateSize = promauto.NewHistogramVec(prometheus.HistogramOpts{ - Name: "zoekt_final_aggregate_size", - Help: "The number of file matches we aggregated before flushing", - Buckets: prometheus.ExponentialBuckets(1, 2, 20), - }, []string{"reason"}) -) +var metricFinalAggregateSize = promauto.NewHistogramVec(prometheus.HistogramOpts{ + Name: "zoekt_final_aggregate_size", + Help: "The number of file matches we aggregated before flushing", + Buckets: prometheus.ExponentialBuckets(1, 2, 20), +}, []string{"reason"}) // collectSender is a sender that will aggregate results. Once sending is // done, you call Done to return the aggregated result which are ranked. diff --git a/shards/shards.go b/shards/shards.go index a3317605f..0e3672745 100644 --- a/shards/shards.go +++ b/shards/shards.go @@ -770,7 +770,6 @@ search: // We split by repository instead of by priority because it is easier to set // RepoURLs and LineFragments in zoekt.SearchResult. func sendByRepository(result *zoekt.SearchResult, opts *zoekt.SearchOptions, sender zoekt.Sender) { - if len(result.RepoURLs) <= 1 || len(result.Files) == 0 { zoekt.SortFiles(result.Files) sender.Send(result) diff --git a/shards/shards_test.go b/shards/shards_test.go index 3132c2920..1a2a99313 100644 --- a/shards/shards_test.go +++ b/shards/shards_test.go @@ -261,7 +261,6 @@ func TestShardedSearcher_DocumentRanking(t *testing.T) { stream.SenderFunc(func(event *zoekt.SearchResult) { results = append(results, event) })) - if err != nil { t.Fatal(err) } @@ -863,7 +862,6 @@ func TestSendByRepository(t *testing.T) { // n1, n2, n3 are the number of file matches for each of the 3 repositories in this // test. f := func(n1, n2, n3 uint8) bool { - sr := createMockSearchResult(n1, n2, n3, wantStats) mock := &mockSender{} diff --git a/shards/watcher_test.go b/shards/watcher_test.go index afd54b0a7..be91fb4ba 100644 --- a/shards/watcher_test.go +++ b/shards/watcher_test.go @@ -188,7 +188,7 @@ func TestDirWatcherLoadLatest(t *testing.T) { for delta := -1; delta <= 1; delta++ { repo := fmt.Sprintf("foo_v%d.00000.zoekt", want+delta) shard := filepath.Join(dir, repo) - if err := os.WriteFile(shard, []byte("hello"), 0644); err != nil { + if err := os.WriteFile(shard, []byte("hello"), 0o644); err != nil { t.Fatalf("WriteFile: %v", err) } } diff --git a/trace/trace.go b/trace/trace.go index d8a3eae04..b98955640 100644 --- a/trace/trace.go +++ b/trace/trace.go @@ -163,21 +163,27 @@ func (e *encoder) EmitInt(key string, value int) { func (e *encoder) EmitInt32(key string, value int32) { e.EmitString(key, strconv.FormatInt(int64(value), 10)) } + func (e *encoder) EmitInt64(key string, value int64) { e.EmitString(key, strconv.FormatInt(value, 10)) } + func (e *encoder) EmitUint32(key string, value uint32) { e.EmitString(key, strconv.FormatUint(uint64(value), 10)) } + func (e *encoder) EmitUint64(key string, value uint64) { e.EmitString(key, strconv.FormatUint(value, 10)) } + func (e *encoder) EmitFloat32(key string, value float32) { e.EmitString(key, strconv.FormatFloat(float64(value), 'E', -1, 64)) } + func (e *encoder) EmitFloat64(key string, value float64) { e.EmitString(key, strconv.FormatFloat(value, 'E', -1, 64)) } + func (e *encoder) EmitObject(key string, value interface{}) { e.EmitString(key, fmt.Sprintf("%+v", value)) } diff --git a/web/server.go b/web/server.go index 7096e5679..a8b237215 100644 --- a/web/server.go +++ b/web/server.go @@ -563,7 +563,6 @@ func (s *Server) servePrintErr(w http.ResponseWriter, r *http.Request) error { } repoRe, err := regexp.Compile("^" + regexp.QuoteMeta(repoStr) + "$") - if err != nil { return err } diff --git a/write.go b/write.go index 00fcb6027..80e1b7512 100644 --- a/write.go +++ b/write.go @@ -67,7 +67,8 @@ func (s *compoundSection) writeMap(w *writer, m map[string]uint32) { } func writePostings(w *writer, s *postingsBuilder, ngramText *simpleSection, - charOffsets *simpleSection, postings *compoundSection, endRunes *simpleSection) { + charOffsets *simpleSection, postings *compoundSection, endRunes *simpleSection, +) { keys := make(ngramSlice, 0, len(s.postings)) for k := range s.postings { keys = append(keys, k)