diff options
author | Jacob Vosmaer <jacob@gitlab.com> | 2019-10-16 17:54:40 +0300 |
---|---|---|
committer | Jacob Vosmaer <jacob@gitlab.com> | 2019-10-16 17:54:40 +0300 |
commit | 78de944558414c1ae8f97ed900ce303725fdea90 (patch) | |
tree | 2a6e178b468fb68b7dac279f1aec6859fbd80d9f | |
parent | 427e0f5aa924bc310173a19cdda5b52b94b38283 (diff) | |
parent | 31c6e181db1bb1d6d50124dcb8abfae6fb7a8d6e (diff) |
Merge branch 'jv-bracefmt' into 'master'
Add go brace whitespace formatter
See merge request gitlab-org/gitaly!1537
68 files changed, 332 insertions, 73 deletions
diff --git a/_support/Makefile.template b/_support/Makefile.template index 592c1e7f9..e2982a8f6 100644 --- a/_support/Makefile.template +++ b/_support/Makefile.template @@ -159,17 +159,25 @@ lint: {{ .GoLint }} go get golang.org/x/lint/golint@959b441ac422379a43da2230f62be024250818b0 .PHONY: check-formatting -check-formatting: {{ .GoImports }} +check-formatting: {{ .GoImports }} {{ .BraceFmt }} # goimports - @cd {{ .SourceDir }} && goimports -e -l {{ join .GoFiles " " }} | awk '{ print } END { if(NR>0) { print "Formatting error, run make format"; exit(1) } }' + @cd {{ .SourceDir }} && goimports -e -l {{ join .GoFiles " " }} | {{ .MakeFormatCheck }} + # bracefmt + @cd {{ .SourceDir }} && {{ .BraceFmt }} {{ join .GoFiles " " }} | {{ .MakeFormatCheck }} {{ .GoImports }}: go get golang.org/x/tools/cmd/goimports@2538eef75904eff384a2551359968e40c207d9d2 +{{ .BraceFmt }}: + @cd {{ .SourceDir }} && go build -o $@ ./internal/cmd/bracefmt + .PHONY: format -format: {{ .GoImports }} - # In addition to fixing imports, goimports also formats your code in the same style as gofmt - # so it can be used as a replacement. +format: {{ .GoImports }} {{ .BraceFmt }} + # goimports pass 1 + @cd {{ .SourceDir }} && goimports -w -l {{ join .GoFiles " " }} + # bracefmt + @cd {{ .SourceDir }} && {{ .BraceFmt }} -w {{ join .GoFiles " " }} + # goimports pass 2 @cd {{ .SourceDir }} && goimports -w -l {{ join .GoFiles " " }} .PHONY: staticcheck diff --git a/_support/makegen.go b/_support/makegen.go index 3a076317a..6849464f4 100644 --- a/_support/makegen.go +++ b/_support/makegen.go @@ -72,6 +72,7 @@ func (gm *gitalyMake) BuildDir() string { func (gm *gitalyMake) Pkg() string { return "gitlab.com/gitlab-org/gitaly" } func (gm *gitalyMake) GoImports() string { return "bin/goimports" } +func (gm *gitalyMake) BraceFmt() string { return filepath.Join(gm.BuildDir(), "bin/bracefmt") } func (gm *gitalyMake) GoCovMerge() string { return "bin/gocovmerge" } func (gm *gitalyMake) GoLint() string { return "bin/golint" } func (gm *gitalyMake) GoVendor() string { return "bin/govendor" } @@ -249,7 +250,7 @@ func (gm *gitalyMake) GoFiles() []string { } } - if !info.IsDir() && strings.HasSuffix(path, ".go") { + if !info.IsDir() && strings.HasSuffix(path, ".go") && !strings.HasSuffix(path, ".pb.go") { rel, err := filepath.Rel(root, path) if err != nil { return err @@ -309,6 +310,10 @@ func (gm *gitalyMake) ProtoCSHA256() string { return protoCDownload[runtime.GOOS+"/"+runtime.GOARCH].sha256 } +func (gm *gitalyMake) MakeFormatCheck() string { + return `awk '{ print } END { if(NR>0) { print "Formatting error, run make format"; exit(1) } }'` +} + var templateText = func() string { contents, err := ioutil.ReadFile("../_support/Makefile.template") if err != nil { diff --git a/auth/extract_test.go b/auth/extract_test.go index db742ddec..4274785c4 100644 --- a/auth/extract_test.go +++ b/auth/extract_test.go @@ -50,7 +50,6 @@ func TestCheckTokenV1(t *testing.T) { require.Equal(t, tc.code, status.Code(err), "expected grpc code in error %v", err) }) } - } func TestCheckTokenV2(t *testing.T) { diff --git a/client/dial.go b/client/dial.go index 13518882e..81dea7d5b 100644 --- a/client/dial.go +++ b/client/dial.go @@ -76,7 +76,6 @@ func Dial(rawAddress string, connOpts []grpc.DialOption) (*grpc.ClientConn, erro PermitWithoutStream: true, }), ) - } conn, err := grpc.Dial(canonicalAddress, connOpts...) diff --git a/cmd/gitaly-remote/add_test.go b/cmd/gitaly-remote/add_test.go index 1faf45721..ca0eb8317 100644 --- a/cmd/gitaly-remote/add_test.go +++ b/cmd/gitaly-remote/add_test.go @@ -54,5 +54,4 @@ func TestAddRemote(t *testing.T) { require.Equal(t, tc.url, strings.TrimSpace(string(out))) }) } - } diff --git a/cmd/gitaly-remote/main.go b/cmd/gitaly-remote/main.go index af55e2c29..92ef802e6 100644 --- a/cmd/gitaly-remote/main.go +++ b/cmd/gitaly-remote/main.go @@ -27,7 +27,6 @@ func main() { if err != nil { log.Fatalf("error while setting remote: %v", err) } - } //addOrUpdate adds, or updates if exits, the remote to repository diff --git a/cmd/gitaly-wrapper/main.go b/cmd/gitaly-wrapper/main.go index 79f100f6d..e1c1e367f 100644 --- a/cmd/gitaly-wrapper/main.go +++ b/cmd/gitaly-wrapper/main.go @@ -116,7 +116,6 @@ func forwardSignals(gitaly *os.Process, log *logrus.Entry) { if err := gitaly.Signal(sig); err != nil { log.WithField("signal", sig).WithError(err).Error("can't forward the signal") } - } }() diff --git a/cmd/praefect/main.go b/cmd/praefect/main.go index 6e83b214d..6ffee7756 100644 --- a/cmd/praefect/main.go +++ b/cmd/praefect/main.go @@ -92,7 +92,6 @@ func configure() (config.Config, error) { } func run(listeners []net.Listener, conf config.Config) error { - clientConnections := conn.NewClientConnections() for _, node := range conf.Nodes { diff --git a/internal/cmd/bracefmt/brace.go b/internal/cmd/bracefmt/brace.go new file mode 100644 index 000000000..e6f55d1d4 --- /dev/null +++ b/internal/cmd/bracefmt/brace.go @@ -0,0 +1,105 @@ +package main + +import ( + "bytes" + "go/scanner" + "go/token" +) + +type editCommand int + +const ( + keepLine editCommand = iota + addLineBefore + removeLine +) + +type edit struct { + line int + cmd editCommand +} + +func braceFmt(src []byte) []byte { + var s scanner.Scanner + fset := token.NewFileSet() + file := fset.AddFile("", fset.Base(), len(src)) + s.Init(file, src, nil, scanner.ScanComments) + + var ( + edits []edit + lastNonEmptyLine, lastLBraceLine int + lastOuterRBraceLine = -1 + ) + + for { + pos, tok, _ := s.Scan() + if tok == token.EOF { + break + } + + position := fset.Position(pos) + currentLine := position.Line + var nextEdit edit + + switch tok { + case token.RBRACE: + if currentLine-lastNonEmptyLine > 1 { + // ......foo + // + // ...} + nextEdit = edit{line: currentLine - 1, cmd: removeLine} + } + + if position.Column == 1 { + lastOuterRBraceLine = currentLine + } + + if lastLBraceLine == currentLine { + lastLBraceLine = 0 + } + case token.LBRACE: + lastLBraceLine = currentLine + + if lastOuterRBraceLine == currentLine { + lastOuterRBraceLine = -1 + } + default: + if currentLine-lastOuterRBraceLine == 1 { + // } + // func bar() { + nextEdit = edit{line: currentLine, cmd: addLineBefore} + } else if currentLine-lastLBraceLine > 1 && lastNonEmptyLine == lastLBraceLine { + // ...foo() { + // + // ......bar + nextEdit = edit{line: currentLine - 1, cmd: removeLine} + } + } + + if nextEdit.cmd != keepLine { + if len(edits) == 0 || edits[0] != nextEdit { + // Store edits in reverse line order: that way line numbers in edits + // won't become invalid when edits get applied. + edits = append([]edit{nextEdit}, edits...) + } + } + + lastNonEmptyLine = currentLine + } + + srcLines := bytes.Split(src, []byte("\n")) + for _, e := range edits { + i := e.line - 1 // scanner uses 1 based indexing; convert to 0 based + + switch e.cmd { + case addLineBefore: + srcLines = append(srcLines[:i], append([][]byte{nil}, srcLines[i:]...)...) + case removeLine: + if len(srcLines[i]) == 0 { + srcLines = append(srcLines[:i], srcLines[i+1:]...) + } + } + } + + return bytes.Join(srcLines, []byte("\n")) +} diff --git a/internal/cmd/bracefmt/brace_test.go b/internal/cmd/bracefmt/brace_test.go new file mode 100644 index 000000000..b3de996dd --- /dev/null +++ b/internal/cmd/bracefmt/brace_test.go @@ -0,0 +1,130 @@ +package main + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestBraceFmt(t *testing.T) { + testCases := []struct { + desc string + in string + out string + unchanged bool + }{ + { + desc: "empty lines inside braces", + in: `package main + +import "log" + +func main() { + + log.Print("hello") + +} +`, + out: `package main + +import "log" + +func main() { + log.Print("hello") +} +`, + }, + { + desc: "missing empty line after top-level closing brace", + in: `package main + +import "log" + +func main() { + log.Print("hello") +} +func foo() { log.Print("foobar") } +`, + out: `package main + +import "log" + +func main() { + log.Print("hello") +} + +func foo() { log.Print("foobar") } +`, + }, + { + desc: "allow skipping empty line when not at top level", + in: `package main + +import "log" + +func main() { + if true { + log.Print("hello") + } + if false { + log.Print("world") + } +} +`, + unchanged: true, + }, + { + desc: "allow skipping empty line between one-line functions", + in: `package main + +import "log" + +func foo() { log.Print("world") } +func bar() { log.Print("hello") } + +func main() { + foo() + bar() +} +`, + unchanged: true, + }, + { + desc: "allow }{ at start of line", + in: `package main + +var anonymousStruct = struct { + foo string +}{ + foo: "bar", +} +`, + unchanged: true, + }, + { + desc: "allow trailing */ before closing brace", + in: `package main + +func foo() { + return + + /* trailing comment + */ +} +`, + unchanged: true, + }, + } + + for _, tc := range testCases { + t.Run(tc.desc, func(t *testing.T) { + out := braceFmt([]byte(tc.in)) + + if tc.unchanged { + require.Equal(t, tc.in, string(out)) + } else { + require.Equal(t, tc.out, string(out)) + } + }) + } +} diff --git a/internal/cmd/bracefmt/main.go b/internal/cmd/bracefmt/main.go new file mode 100644 index 000000000..ffa4b05d9 --- /dev/null +++ b/internal/cmd/bracefmt/main.go @@ -0,0 +1,62 @@ +package main + +import ( + "bytes" + "flag" + "fmt" + "io/ioutil" + "os" +) + +const ( + progName = "bracefmt" +) + +var ( + writeFiles = flag.Bool("w", false, "write changes to inspected files") +) + +func main() { + flag.Parse() + + if len(flag.Args()) == 0 { + fmt.Fprintf(os.Stderr, "usage: %s file.go [file.go...]\n", progName) + os.Exit(1) + } + + if err := _main(flag.Args()); err != nil { + fmt.Fprintf(os.Stderr, "%s: fatal: %v", progName, err) + os.Exit(1) + } +} + +func _main(args []string) error { + for _, f := range args { + fi, err := os.Stat(f) + if err != nil { + return err + } + + src, err := ioutil.ReadFile(f) + if err != nil { + return err + } + + dst := braceFmt(src) + if bytes.Equal(src, dst) { + continue + } + + fmt.Println(f) + + if !*writeFiles { + continue + } + + if err := ioutil.WriteFile(f, dst, fi.Mode()); err != nil { + return err + } + } + + return nil +} diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 338b27ef2..7785dbcde 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -401,7 +401,6 @@ func TestValidateShellPath(t *testing.T) { } else { assert.NoError(t, err) } - } } diff --git a/internal/git/catfile/batch_cache.go b/internal/git/catfile/batch_cache.go index 7d08cc598..153f20f66 100644 --- a/internal/git/catfile/batch_cache.go +++ b/internal/git/catfile/batch_cache.go @@ -176,7 +176,6 @@ func (bc *batchCache) lookup(k key) (int, bool) { if ent.key == k { return i, true } - } return -1, false diff --git a/internal/git/catfile/batch_cache_test.go b/internal/git/catfile/batch_cache_test.go index 510b91a7a..519c6ef28 100644 --- a/internal/git/catfile/batch_cache_test.go +++ b/internal/git/catfile/batch_cache_test.go @@ -162,7 +162,6 @@ func requireCacheValid(t *testing.T, bc *batchCache) { defer bc.Unlock() for _, ent := range bc.entries { - v := ent.value require.False(t, v.isClosed(), "values in cache should not be closed: %v %v", ent, v) } diff --git a/internal/git/catfile/catfile_test.go b/internal/git/catfile/catfile_test.go index 8825afbd1..0321c9c9e 100644 --- a/internal/git/catfile/catfile_test.go +++ b/internal/git/catfile/catfile_test.go @@ -119,7 +119,6 @@ func TestCommit(t *testing.T) { require.Equal(t, tc.output, string(contents)) }) } - } func TestTag(t *testing.T) { @@ -190,7 +189,6 @@ func TestTree(t *testing.T) { require.Equal(t, tc.output, string(contents)) }) } - } func TestRepeatedCalls(t *testing.T) { diff --git a/internal/git/hooks/hooks_test.go b/internal/git/hooks/hooks_test.go index 6c2657461..e58139953 100644 --- a/internal/git/hooks/hooks_test.go +++ b/internal/git/hooks/hooks_test.go @@ -33,5 +33,4 @@ func TestPath(t *testing.T) { require.Equal(t, "/var/empty", Path()) }) - } diff --git a/internal/git/log/commit_test.go b/internal/git/log/commit_test.go index fe0ea3afa..a70efdb36 100644 --- a/internal/git/log/commit_test.go +++ b/internal/git/log/commit_test.go @@ -97,7 +97,6 @@ func TestParseRawCommit(t *testing.T) { out, err := parseRawCommit(bytes.NewBuffer(tc.in), info) require.NoError(t, err, "parse error") require.Equal(t, tc.out, out) - }) } } diff --git a/internal/git/objectpool/fetch_test.go b/internal/git/objectpool/fetch_test.go index 674f09375..a7ff6ba32 100644 --- a/internal/git/objectpool/fetch_test.go +++ b/internal/git/objectpool/fetch_test.go @@ -185,7 +185,6 @@ func TestFetchFromOriginRefUpdates(t *testing.T) { looseRefs := testhelper.MustRunCommand(t, nil, "find", filepath.Join(poolPath, "refs"), "-type", "f") require.Equal(t, "", string(looseRefs), "there should be no loose refs after the fetch") - } func resolveRef(t *testing.T, repo string, ref string) string { diff --git a/internal/git/pktline/pkt_line_test.go b/internal/git/pktline/pkt_line_test.go index 3024a31d1..8cbbeed07 100644 --- a/internal/git/pktline/pkt_line_test.go +++ b/internal/git/pktline/pkt_line_test.go @@ -60,7 +60,6 @@ func TestScanner(t *testing.T) { if tc.fail { require.Error(t, scanner.Err()) - } else { require.NoError(t, scanner.Err()) } diff --git a/internal/git/proto.go b/internal/git/proto.go index 17323c600..dce5408f8 100644 --- a/internal/git/proto.go +++ b/internal/git/proto.go @@ -100,7 +100,6 @@ func VersionLessThan(v1Str, v2Str string) (bool, error) { func versionLessThan(v1, v2 version) bool { switch { - case v1.major < v2.major: return true case v1.major > v2.major: @@ -119,7 +118,6 @@ func versionLessThan(v1, v2 version) bool { default: // this should only be reachable when versions are equal return false - } } diff --git a/internal/git/rawdiff/rawdiff_test.go b/internal/git/rawdiff/rawdiff_test.go index 21eb009b9..5877c0e18 100644 --- a/internal/git/rawdiff/rawdiff_test.go +++ b/internal/git/rawdiff/rawdiff_test.go @@ -9,7 +9,6 @@ import ( ) func TestParser(t *testing.T) { - testCases := []struct { desc string in string diff --git a/internal/git/remote/remote_test.go b/internal/git/remote/remote_test.go index ec4809d5e..af4c56a9e 100644 --- a/internal/git/remote/remote_test.go +++ b/internal/git/remote/remote_test.go @@ -48,7 +48,6 @@ func TestRemoveRemoteDontRemoveLocalBranches(t *testing.T) { out = testhelper.MustRunCommand(t, nil, "git", "-C", repoPath, "show-ref", "refs/heads/master") require.Equal(t, masterBeforeRemove, out) - } func TestRemoteExists(t *testing.T) { diff --git a/internal/helper/storage.go b/internal/helper/storage.go index 4a8559c06..f74a3302f 100644 --- a/internal/helper/storage.go +++ b/internal/helper/storage.go @@ -46,7 +46,6 @@ func IncomingToOutgoing(ctx context.Context) context.Context { // InjectGitalyServers injects gitaly-servers metadata into an outgoing context func InjectGitalyServers(ctx context.Context, name, address, token string) (context.Context, error) { - gitalyServers := storage.GitalyServers{ name: { "address": address, diff --git a/internal/praefect/conn/client_connections.go b/internal/praefect/conn/client_connections.go index c3734937a..d2e36f352 100644 --- a/internal/praefect/conn/client_connections.go +++ b/internal/praefect/conn/client_connections.go @@ -66,5 +66,4 @@ func (c *ClientConnections) GetConnection(storageName string) (*grpc.ClientConn, } return cc, nil - } diff --git a/internal/praefect/datastore.go b/internal/praefect/datastore.go index b336bff0c..4d97abc55 100644 --- a/internal/praefect/datastore.go +++ b/internal/praefect/datastore.go @@ -174,7 +174,6 @@ func (md *MemoryDatastore) PickAPrimary() (*models.Node, error) { } return nil, errors.New("no default primaries found") - } // GetReplicas gets the secondaries for a repository based on the relative path @@ -233,7 +232,6 @@ func (md *MemoryDatastore) GetPrimary(relativePath string) (*models.Node, error) return nil, errors.New("node storage not found") } return &storageNode, nil - } // SetPrimary sets the primary storagee node for a repository of a repository relative path diff --git a/internal/praefect/grpc-proxy/proxy/codec.go b/internal/praefect/grpc-proxy/proxy/codec.go index 24d5f5cea..a6aa3dc1d 100644 --- a/internal/praefect/grpc-proxy/proxy/codec.go +++ b/internal/praefect/grpc-proxy/proxy/codec.go @@ -42,7 +42,6 @@ func (c *rawCodec) Marshal(v interface{}) ([]byte, error) { return c.parentCodec.Marshal(v) } return out.payload, nil - } func (c *rawCodec) Unmarshal(data []byte, v interface{}) error { diff --git a/internal/praefect/grpc-proxy/proxy/codec_test.go b/internal/praefect/grpc-proxy/proxy/codec_test.go index dd3893c16..99569ac0d 100644 --- a/internal/praefect/grpc-proxy/proxy/codec_test.go +++ b/internal/praefect/grpc-proxy/proxy/codec_test.go @@ -20,5 +20,4 @@ func TestCodec_ReadYourWrites(t *testing.T) { out, err = codec.Marshal(framePtr) require.NoError(t, err, "no marshal error") require.Equal(t, []byte{0x55}, out, "output and data must be the same") - } diff --git a/internal/praefect/grpc-proxy/proxy/helper_test.go b/internal/praefect/grpc-proxy/proxy/helper_test.go index 615d5a3fd..7502fc271 100644 --- a/internal/praefect/grpc-proxy/proxy/helper_test.go +++ b/internal/praefect/grpc-proxy/proxy/helper_test.go @@ -103,12 +103,15 @@ func (ip *interceptPinger) PingStream(stream testservice.TestService_PingStreamS func (ip *interceptPinger) PingEmpty(ctx context.Context, req *testservice.Empty) (*testservice.PingResponse, error) { return ip.pingEmpty(ctx, req) } + func (ip *interceptPinger) Ping(ctx context.Context, req *testservice.PingRequest) (*testservice.PingResponse, error) { return ip.ping(ctx, req) } + func (ip *interceptPinger) PingError(ctx context.Context, req *testservice.PingRequest) (*testservice.Empty, error) { return ip.pingError(ctx, req) } + func (ip *interceptPinger) PingList(req *testservice.PingRequest, stream testservice.TestService_PingListServer) error { return ip.pingList(req, stream) } diff --git a/internal/praefect/replicator.go b/internal/praefect/replicator.go index b4c18083f..63511ae4c 100644 --- a/internal/praefect/replicator.go +++ b/internal/praefect/replicator.go @@ -125,7 +125,6 @@ func getChecksumFunc(ctx context.Context, client gitalypb.RepositoryServiceClien } func (dr defaultReplicator) confirmChecksums(ctx context.Context, primaryClient, replicaClient gitalypb.RepositoryServiceClient, primary, replica *gitalypb.Repository) (bool, error) { - g, gCtx := errgroup.WithContext(ctx) var primaryChecksum, replicaChecksum string @@ -307,5 +306,4 @@ func (r ReplMgr) processReplJob(ctx context.Context, job ReplJob) error { return err } return nil - } diff --git a/internal/praefect/replicator_test.go b/internal/praefect/replicator_test.go index a46b2140c..ac57a1fe7 100644 --- a/internal/praefect/replicator_test.go +++ b/internal/praefect/replicator_test.go @@ -152,7 +152,6 @@ func TestConfirmReplication(t *testing.T) { equal, err = replicator.confirmChecksums(ctx, gitalypb.NewRepositoryServiceClient(conn), gitalypb.NewRepositoryServiceClient(conn), testRepoA, testRepoB) require.NoError(t, err) require.False(t, equal) - } func runFullGitalyServer(t *testing.T) (*grpc.Server, string) { diff --git a/internal/praefect/service/server/info.go b/internal/praefect/service/server/info.go index 9647af4db..76c2fd67b 100644 --- a/internal/praefect/service/server/info.go +++ b/internal/praefect/service/server/info.go @@ -13,7 +13,6 @@ import ( // ServerInfo sends ServerInfoRequest to all of a praefect server's internal gitaly nodes and aggregates the results into // a response func (s *Server) ServerInfo(ctx context.Context, in *gitalypb.ServerInfoRequest) (*gitalypb.ServerInfoResponse, error) { - storageStatuses := make([][]*gitalypb.ServerInfoResponse_StorageStatus, len(s.conf.Nodes)) var gitVersion, serverVersion string diff --git a/internal/service/blob/get_blobs.go b/internal/service/blob/get_blobs.go index ec588e273..f2f645316 100644 --- a/internal/service/blob/get_blobs.go +++ b/internal/service/blob/get_blobs.go @@ -89,7 +89,6 @@ func sendGetBlobsResponse(req *gitalypb.GetBlobsRequest, stream gitalypb.BlobSer } func sendBlobTreeEntry(response *gitalypb.GetBlobsResponse, stream gitalypb.BlobService_GetBlobsServer, c *catfile.Batch, limit int64) error { - var readLimit int64 if limit < 0 || limit > response.Size { readLimit = response.Size diff --git a/internal/service/blob/lfs_pointers.go b/internal/service/blob/lfs_pointers.go index d43b82a00..e904a5139 100644 --- a/internal/service/blob/lfs_pointers.go +++ b/internal/service/blob/lfs_pointers.go @@ -191,6 +191,7 @@ func (s *allLFSPointersSender) Reset() { s.lfsPointers = nil } func (s *allLFSPointersSender) Append(it chunk.Item) { s.lfsPointers = append(s.lfsPointers, it.(*gitalypb.LFSPointer)) } + func (s *allLFSPointersSender) Send() error { return s.stream.Send(&gitalypb.GetAllLFSPointersResponse{LfsPointers: s.lfsPointers}) } diff --git a/internal/service/commit/between.go b/internal/service/commit/between.go index 2f6d666eb..9eee9f522 100644 --- a/internal/service/commit/between.go +++ b/internal/service/commit/between.go @@ -18,6 +18,7 @@ func (sender *commitsBetweenSender) Reset() { sender.commits = nil } func (sender *commitsBetweenSender) Append(it chunk.Item) { sender.commits = append(sender.commits, it.(*gitalypb.GitCommit)) } + func (sender *commitsBetweenSender) Send() error { return sender.stream.Send(&gitalypb.CommitsBetweenResponse{Commits: sender.commits}) } diff --git a/internal/service/commit/commits_by_message.go b/internal/service/commit/commits_by_message.go index 877cabca0..2f95a06ef 100644 --- a/internal/service/commit/commits_by_message.go +++ b/internal/service/commit/commits_by_message.go @@ -18,6 +18,7 @@ func (sender *commitsByMessageSender) Reset() { sender.commits = nil } func (sender *commitsByMessageSender) Append(it chunk.Item) { sender.commits = append(sender.commits, it.(*gitalypb.GitCommit)) } + func (sender *commitsByMessageSender) Send() error { return sender.stream.Send(&gitalypb.CommitsByMessageResponse{Commits: sender.commits}) } diff --git a/internal/service/commit/commits_by_message_test.go b/internal/service/commit/commits_by_message_test.go index 0a5986101..40fb232d6 100644 --- a/internal/service/commit/commits_by_message_test.go +++ b/internal/service/commit/commits_by_message_test.go @@ -120,7 +120,6 @@ func TestSuccessfulCommitsByMessageRequest(t *testing.T) { for _, testCase := range testCases { t.Run(testCase.desc, func(t *testing.T) { - request := testCase.request request.Repository = testRepo @@ -193,7 +192,6 @@ func TestFailedCommitsByMessageRequest(t *testing.T) { for _, testCase := range testCases { t.Run(testCase.desc, func(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) defer cancel() c, err := client.CommitsByMessage(ctx, testCase.request) diff --git a/internal/service/commit/count_commits_test.go b/internal/service/commit/count_commits_test.go index a4b07611e..b609366fb 100644 --- a/internal/service/commit/count_commits_test.go +++ b/internal/service/commit/count_commits_test.go @@ -118,7 +118,6 @@ func TestSuccessfulCountCommitsRequest(t *testing.T) { for _, testCase := range testCases { t.Run(testCase.desc, func(t *testing.T) { - request := &gitalypb.CountCommitsRequest{Repository: testCase.repo} if testCase.all { @@ -184,7 +183,6 @@ func TestFailedCountCommitsRequestDueToValidationError(t *testing.T) { for _, rpcRequest := range rpcRequests { t.Run(fmt.Sprintf("%v", rpcRequest), func(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) defer cancel() _, err := client.CountCommits(ctx, &rpcRequest) diff --git a/internal/service/commit/count_diverging_commits.go b/internal/service/commit/count_diverging_commits.go index 102ef2b68..9ec4aed8d 100644 --- a/internal/service/commit/count_diverging_commits.go +++ b/internal/service/commit/count_diverging_commits.go @@ -29,7 +29,6 @@ func (s *server) CountDivergingCommits(ctx context.Context, req *gitalypb.CountD } return &gitalypb.CountDivergingCommitsResponse{LeftCount: left, RightCount: right}, nil - } func validateCountDivergingCommitsRequest(req *gitalypb.CountDivergingCommitsRequest) error { diff --git a/internal/service/commit/find_all_commits.go b/internal/service/commit/find_all_commits.go index 0ce2a20b8..09bc7d9b6 100644 --- a/internal/service/commit/find_all_commits.go +++ b/internal/service/commit/find_all_commits.go @@ -22,6 +22,7 @@ func (sender *findAllCommitsSender) Reset() { sender.commits = nil } func (sender *findAllCommitsSender) Append(it chunk.Item) { sender.commits = append(sender.commits, it.(*gitalypb.GitCommit)) } + func (sender *findAllCommitsSender) Send() error { return sender.stream.Send(&gitalypb.FindAllCommitsResponse{Commits: sender.commits}) } diff --git a/internal/service/commit/find_all_commits_test.go b/internal/service/commit/find_all_commits_test.go index 43dd6fae7..629207133 100644 --- a/internal/service/commit/find_all_commits_test.go +++ b/internal/service/commit/find_all_commits_test.go @@ -261,7 +261,6 @@ func TestSuccessfulFindAllCommitsRequest(t *testing.T) { for _, testCase := range testCases { t.Run(testCase.desc, func(t *testing.T) { - request := testCase.request request.Repository = testRepo @@ -322,7 +321,6 @@ func TestFailedFindAllCommitsRequest(t *testing.T) { for _, testCase := range testCases { t.Run(testCase.desc, func(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) defer cancel() c, err := client.FindAllCommits(ctx, testCase.request) diff --git a/internal/service/commit/find_commit_test.go b/internal/service/commit/find_commit_test.go index e13c149b9..08cc730c8 100644 --- a/internal/service/commit/find_commit_test.go +++ b/internal/service/commit/find_commit_test.go @@ -294,6 +294,7 @@ func TestFailedFindCommitRequest(t *testing.T) { func BenchmarkFindCommitNoCache(b *testing.B) { benchmarkFindCommit(false, b) } + func BenchmarkFindCommitWithCache(b *testing.B) { benchmarkFindCommit(true, b) } diff --git a/internal/service/commit/find_commits.go b/internal/service/commit/find_commits.go index cad71f4c3..c7f5bd092 100644 --- a/internal/service/commit/find_commits.go +++ b/internal/service/commit/find_commits.go @@ -49,7 +49,6 @@ func (s *server) FindCommits(req *gitalypb.FindCommitsRequest, stream gitalypb.C } func findCommits(ctx context.Context, req *gitalypb.FindCommitsRequest, stream gitalypb.CommitService_FindCommitsServer) error { - args := getLogCommandFlags(req) logCmd, err := git.Command(ctx, req.GetRepository(), args...) if err != nil { @@ -130,6 +129,7 @@ func (s *findCommitsSender) Reset() { s.commits = nil } func (s *findCommitsSender) Append(it chunk.Item) { s.commits = append(s.commits, it.(*gitalypb.GitCommit)) } + func (s *findCommitsSender) Send() error { return s.stream.Send(&gitalypb.FindCommitsResponse{Commits: s.commits}) } diff --git a/internal/service/commit/last_commit_for_path_test.go b/internal/service/commit/last_commit_for_path_test.go index f9c58757c..ccf581672 100644 --- a/internal/service/commit/last_commit_for_path_test.go +++ b/internal/service/commit/last_commit_for_path_test.go @@ -132,7 +132,6 @@ func TestFailedLastCommitForPathRequest(t *testing.T) { for _, testCase := range testCases { t.Run(testCase.desc, func(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) defer cancel() _, err := client.LastCommitForPath(ctx, testCase.request) diff --git a/internal/service/commit/list_files_test.go b/internal/service/commit/list_files_test.go index 8c80a4896..1efcf4428 100644 --- a/internal/service/commit/list_files_test.go +++ b/internal/service/commit/list_files_test.go @@ -157,7 +157,6 @@ func TestListFilesFailure(t *testing.T) { for _, test := range tests { t.Run(test.desc, func(t *testing.T) { - rpcRequest := gitalypb.ListFilesRequest{ Repository: test.repo, Revision: []byte("master"), } diff --git a/internal/service/commit/raw_blame_test.go b/internal/service/commit/raw_blame_test.go index cde759ff2..034b9f1ce 100644 --- a/internal/service/commit/raw_blame_test.go +++ b/internal/service/commit/raw_blame_test.go @@ -45,7 +45,6 @@ func TestSuccessfulRawBlameRequest(t *testing.T) { for _, testCase := range testCases { t.Run(fmt.Sprintf("test case: revision=%q path=%q", testCase.revision, testCase.path), func(t *testing.T) { - request := &gitalypb.RawBlameRequest{ Repository: testRepo, Revision: testCase.revision, @@ -124,7 +123,6 @@ func TestFailedRawBlameRequest(t *testing.T) { for _, testCase := range testCases { t.Run(testCase.description, func(t *testing.T) { - request := gitalypb.RawBlameRequest{ Repository: testCase.repo, Revision: testCase.revision, diff --git a/internal/service/commit/tree_entry_test.go b/internal/service/commit/tree_entry_test.go index 5460cb336..32a68a970 100644 --- a/internal/service/commit/tree_entry_test.go +++ b/internal/service/commit/tree_entry_test.go @@ -140,7 +140,6 @@ func TestSuccessfulTreeEntry(t *testing.T) { for _, testCase := range testCases { t.Run(fmt.Sprintf("test case: revision=%q path=%q", testCase.revision, testCase.path), func(t *testing.T) { - request := &gitalypb.TreeEntryRequest{ Repository: testRepo, Revision: testCase.revision, @@ -183,7 +182,6 @@ func TestFailedTreeEntryRequestDueToValidationError(t *testing.T) { for _, rpcRequest := range rpcRequests { t.Run(fmt.Sprintf("%+v", rpcRequest), func(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) defer cancel() c, err := client.TreeEntry(ctx, &rpcRequest) diff --git a/internal/service/conflicts/list_conflict_files_test.go b/internal/service/conflicts/list_conflict_files_test.go index e05c4e7d2..9119c55ca 100644 --- a/internal/service/conflicts/list_conflict_files_test.go +++ b/internal/service/conflicts/list_conflict_files_test.go @@ -143,7 +143,6 @@ func TestListConflictFilesFailedPrecondition(t *testing.T) { for _, tc := range testCases { t.Run(tc.desc, func(t *testing.T) { - request := &gitalypb.ListConflictFilesRequest{ Repository: testRepo, OurCommitOid: tc.ourCommitOid, diff --git a/internal/service/diff/commit_test.go b/internal/service/diff/commit_test.go index b24c7122a..89610cc1a 100644 --- a/internal/service/diff/commit_test.go +++ b/internal/service/diff/commit_test.go @@ -612,7 +612,6 @@ func TestSuccessfulCommitDiffRequestWithLimits(t *testing.T) { for _, requestAndResult := range requestsAndResults { t.Run(requestAndResult.desc, func(t *testing.T) { - request := requestAndResult.request request.Repository = testRepo request.LeftCommitId = leftCommit @@ -666,7 +665,6 @@ func TestFailedCommitDiffRequestDueToValidationError(t *testing.T) { for _, rpcRequest := range rpcRequests { t.Run(fmt.Sprintf("%v", rpcRequest), func(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) defer cancel() c, err := client.CommitDiff(ctx, &rpcRequest) @@ -919,7 +917,6 @@ func TestFailedCommitDeltaRequestDueToValidationError(t *testing.T) { for _, rpcRequest := range rpcRequests { t.Run(fmt.Sprintf("%v", rpcRequest), func(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) defer cancel() c, err := client.CommitDelta(ctx, &rpcRequest) diff --git a/internal/service/operations/apply_patch_test.go b/internal/service/operations/apply_patch_test.go index d80b7a419..fefb2217e 100644 --- a/internal/service/operations/apply_patch_test.go +++ b/internal/service/operations/apply_patch_test.go @@ -134,7 +134,6 @@ func TestSuccessfulUserApplyPatch(t *testing.T) { require.Equal(t, string(commit.Author.Email), "patchuser@gitlab.org") require.Equal(t, string(commit.Committer.Email), string(user.Email)) } - }) } } diff --git a/internal/service/operations/merge_test.go b/internal/service/operations/merge_test.go index 7cf2ded2f..e2dd5d473 100644 --- a/internal/service/operations/merge_test.go +++ b/internal/service/operations/merge_test.go @@ -276,7 +276,6 @@ func TestFailedMergeDueToHooks(t *testing.T) { require.Equal(t, mergeBranchHeadBefore, text.ChompBytes(currentBranchHead), "branch head updated") }) } - } func TestSuccessfulUserFFBranchRequest(t *testing.T) { diff --git a/internal/service/ref/branches_test.go b/internal/service/ref/branches_test.go index 27faf09d5..7d633137a 100644 --- a/internal/service/ref/branches_test.go +++ b/internal/service/ref/branches_test.go @@ -312,7 +312,6 @@ func TestFailedFindBranchRequest(t *testing.T) { for _, testCase := range testCases { t.Run(testCase.desc, func(t *testing.T) { - request := &gitalypb.FindBranchRequest{ Repository: testRepo, Name: []byte(testCase.branchName), diff --git a/internal/service/ref/refnames.go b/internal/service/ref/refnames.go index 848b92d95..54e9a9c39 100644 --- a/internal/service/ref/refnames.go +++ b/internal/service/ref/refnames.go @@ -25,6 +25,7 @@ func (ts *findAllBranchNamesSender) Reset() { ts.branchNames = nil } func (ts *findAllBranchNamesSender) Append(it chunk.Item) { ts.branchNames = append(ts.branchNames, []byte(it.(string))) } + func (ts *findAllBranchNamesSender) Send() error { return ts.stream.Send(&gitalypb.FindAllBranchNamesResponse{Names: ts.branchNames}) } @@ -45,6 +46,7 @@ func (ts *findAllTagNamesSender) Reset() { ts.tagNames = nil } func (ts *findAllTagNamesSender) Append(it chunk.Item) { ts.tagNames = append(ts.tagNames, []byte(it.(string))) } + func (ts *findAllTagNamesSender) Send() error { return ts.stream.Send(&gitalypb.FindAllTagNamesResponse{Names: ts.tagNames}) } diff --git a/internal/service/ref/refnames_containing.go b/internal/service/ref/refnames_containing.go index 13d412dc6..39a21997a 100644 --- a/internal/service/ref/refnames_containing.go +++ b/internal/service/ref/refnames_containing.go @@ -48,6 +48,7 @@ func (bs *branchNamesContainingCommitSender) Reset() { bs.branchNames = nil } func (bs *branchNamesContainingCommitSender) Append(it chunk.Item) { bs.branchNames = append(bs.branchNames, stripPrefix(it, "refs/heads/")) } + func (bs *branchNamesContainingCommitSender) Send() error { return bs.stream.Send(&gitalypb.ListBranchNamesContainingCommitResponse{BranchNames: bs.branchNames}) } @@ -77,6 +78,7 @@ func (ts *tagNamesContainingCommitSender) Reset() { ts.tagNames = nil } func (ts *tagNamesContainingCommitSender) Append(it chunk.Item) { ts.tagNames = append(ts.tagNames, stripPrefix(it, "refs/tags/")) } + func (ts *tagNamesContainingCommitSender) Send() error { return ts.stream.Send(&gitalypb.ListTagNamesContainingCommitResponse{TagNames: ts.tagNames}) } diff --git a/internal/service/ref/refs_test.go b/internal/service/ref/refs_test.go index f882f4d4c..c50631825 100644 --- a/internal/service/ref/refs_test.go +++ b/internal/service/ref/refs_test.go @@ -1076,7 +1076,6 @@ func TestInvalidFindAllBranchesRequest(t *testing.T) { for _, tc := range testCases { t.Run(tc.description, func(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) defer cancel() c, err := client.FindAllBranches(ctx, &tc.request) @@ -1421,7 +1420,6 @@ func TestSuccessfulFindTagRequest(t *testing.T) { } for _, expectedTag := range expectedTags { - rpcRequest := &gitalypb.FindTagRequest{Repository: testRepoCopy, TagName: expectedTag.Name} resp, err := client.FindTag(ctx, rpcRequest) diff --git a/internal/service/remote/remotes_test.go b/internal/service/remote/remotes_test.go index 3a657cf90..763be1211 100644 --- a/internal/service/remote/remotes_test.go +++ b/internal/service/remote/remotes_test.go @@ -316,7 +316,6 @@ func TestListDifferentPushUrlRemote(t *testing.T) { require.Len(t, receivedRemotes, len(testCases)) require.ElementsMatch(t, testCases, receivedRemotes) - } func TestListRemotes(t *testing.T) { @@ -401,7 +400,6 @@ func TestListRemotes(t *testing.T) { require.ElementsMatch(t, tc.remotes, receivedRemotes) }) } - } func consumeListRemotesResponse(t *testing.T, l gitalypb.RemoteService_ListRemotesClient) []*gitalypb.ListRemotesResponse_Remote { diff --git a/internal/service/repository/clone_from_pool_internal.go b/internal/service/repository/clone_from_pool_internal.go index e91794c64..ed661088b 100644 --- a/internal/service/repository/clone_from_pool_internal.go +++ b/internal/service/repository/clone_from_pool_internal.go @@ -110,7 +110,6 @@ func validateCloneFromPoolInternalRequestArgs(req *gitalypb.CloneFromPoolInterna } func cloneFromPool(ctx context.Context, objectPoolRepo *gitalypb.ObjectPool, repo repository.GitRepo) error { - objectPoolPath, err := helper.GetPath(objectPoolRepo.GetRepository()) if err != nil { return fmt.Errorf("could not get object pool path: %v", err) diff --git a/internal/service/repository/clone_from_pool_test.go b/internal/service/repository/clone_from_pool_test.go index 558e23f03..759a5a437 100644 --- a/internal/service/repository/clone_from_pool_test.go +++ b/internal/service/repository/clone_from_pool_test.go @@ -72,5 +72,4 @@ func TestCloneFromPoolHTTP(t *testing.T) { // we establish that the target has branches, even though (as we saw above) it has no objects. testhelper.MustRunCommand(t, nil, "git", "-C", forkRepoPath, "show-ref", "--verify", "refs/heads/feature") testhelper.MustRunCommand(t, nil, "git", "-C", forkRepoPath, "show-ref", "--verify", fmt.Sprintf("refs/heads/%s", newBranch)) - } diff --git a/internal/service/repository/create_test.go b/internal/service/repository/create_test.go index b125153f1..dcfc09de2 100644 --- a/internal/service/repository/create_test.go +++ b/internal/service/repository/create_test.go @@ -101,6 +101,7 @@ func TestCreateRepositoryFailureInvalidArgs(t *testing.T) { }) } } + func TestCreateRepositoryIdempotent(t *testing.T) { server, serverSocketPath := runRepoServer(t) defer server.Stop() @@ -123,5 +124,4 @@ func TestCreateRepositoryIdempotent(t *testing.T) { refsAfter := strings.Split(string(testhelper.MustRunCommand(t, nil, "git", "-C", testRepoPath, "for-each-ref")), "\n") assert.Equal(t, refsBefore, refsAfter) - } diff --git a/internal/service/repository/fetch_remote_test.go b/internal/service/repository/fetch_remote_test.go index ecdb066a8..be309b7c7 100644 --- a/internal/service/repository/fetch_remote_test.go +++ b/internal/service/repository/fetch_remote_test.go @@ -183,7 +183,6 @@ func TestFetchRemoteOverHTTP(t *testing.T) { require.Len(t, refs, 1) assert.Equal(t, "master", refs[0]) - }) } } diff --git a/internal/service/repository/gc_test.go b/internal/service/repository/gc_test.go index f90a1122e..b5bdb0c6f 100644 --- a/internal/service/repository/gc_test.go +++ b/internal/service/repository/gc_test.go @@ -195,7 +195,6 @@ func TestGarbageCollectFailure(t *testing.T) { testhelper.RequireGrpcError(t, err, test.code) }) } - } func TestCleanupInvalidKeepAroundRefs(t *testing.T) { diff --git a/internal/service/repository/raw_changes.go b/internal/service/repository/raw_changes.go index 254c28b97..3c179b90e 100644 --- a/internal/service/repository/raw_changes.go +++ b/internal/service/repository/raw_changes.go @@ -107,6 +107,7 @@ func (s *rawChangesSender) Reset() { s.changes = nil } func (s *rawChangesSender) Append(it chunk.Item) { s.changes = append(s.changes, it.(*gitalypb.GetRawChangesResponse_RawChange)) } + func (s *rawChangesSender) Send() error { response := &gitalypb.GetRawChangesResponse{RawChanges: s.changes} return s.stream.Send(response) diff --git a/internal/service/repository/search_files_test.go b/internal/service/repository/search_files_test.go index bb2620c13..2b320aced 100644 --- a/internal/service/repository/search_files_test.go +++ b/internal/service/repository/search_files_test.go @@ -258,7 +258,6 @@ func TestSearchFilesByContentFailure(t *testing.T) { for _, tc := range testCases { t.Run(tc.desc, func(t *testing.T) { - stream, err := client.SearchFilesByContent(ctx, &gitalypb.SearchFilesByContentRequest{ Repository: tc.repo, Query: tc.query, @@ -363,7 +362,6 @@ func TestSearchFilesByNameFailure(t *testing.T) { for _, tc := range testCases { t.Run(tc.desc, func(t *testing.T) { - stream, err := client.SearchFilesByName(ctx, &gitalypb.SearchFilesByNameRequest{ Repository: tc.repo, Query: tc.query, diff --git a/internal/service/repository/size_test.go b/internal/service/repository/size_test.go index 959ab63db..9643a43c8 100644 --- a/internal/service/repository/size_test.go +++ b/internal/service/repository/size_test.go @@ -54,7 +54,6 @@ func TestFailedRepositorySizeRequest(t *testing.T) { for _, testCase := range testCases { t.Run(testCase.description, func(t *testing.T) { - request := &gitalypb.RepositorySizeRequest{ Repository: testCase.repo, } diff --git a/internal/service/repository/snapshot.go b/internal/service/repository/snapshot.go index 55575651f..d013a1fac 100644 --- a/internal/service/repository/snapshot.go +++ b/internal/service/repository/snapshot.go @@ -118,7 +118,6 @@ func addAlternateFiles(ctx context.Context, repository *gitalypb.Repository, bui } func walkAndAddToBuilder(alternateObjDir string, builder *archive.TarBuilder) error { - matchWalker := archive.NewMatchWalker(objectFiles, func(path string, info os.FileInfo, err error) error { fmt.Printf("walking down %v\n", path) if err != nil { diff --git a/internal/service/repository/write_ref.go b/internal/service/repository/write_ref.go index 1a874bcac..bbaf239cb 100644 --- a/internal/service/repository/write_ref.go +++ b/internal/service/repository/write_ref.go @@ -52,7 +52,6 @@ func updateRef(ctx context.Context, req *gitalypb.WriteRefRequest) error { return fmt.Errorf("error when running update-ref command: %v", err) } return nil - } func validateWriteRefRequest(req *gitalypb.WriteRefRequest) error { diff --git a/internal/service/server/info_test.go b/internal/service/server/info_test.go index d708c8a03..106c9f8fa 100644 --- a/internal/service/server/info_test.go +++ b/internal/service/server/info_test.go @@ -88,6 +88,7 @@ func runServer(t *testing.T) (*grpc.Server, string) { return server, "unix://" + serverSocketPath } + func TestServerNoAuth(t *testing.T) { srv, path := runServer(t) defer srv.Stop() diff --git a/internal/service/smarthttp/cache.go b/internal/service/smarthttp/cache.go index 8cb864bdd..89714edb7 100644 --- a/internal/service/smarthttp/cache.go +++ b/internal/service/smarthttp/cache.go @@ -61,7 +61,6 @@ func tryCache(ctx context.Context, in *gitalypb.InfoRefsRequest, w io.Writer, mi stream, err := infoRefCache.GetStream(ctx, in.GetRepository(), in) switch err { - case nil: countHit() logger.Info("cache hit for UploadPack response") diff --git a/internal/testhelper/commit.go b/internal/testhelper/commit.go index 4408f6fcb..4c4a567ba 100644 --- a/internal/testhelper/commit.go +++ b/internal/testhelper/commit.go @@ -102,7 +102,6 @@ func CommitBlobWithName(t *testing.T, testRepoPath, blobID, fileName, commitMess "-c", fmt.Sprintf("user.email=%s", committerEmail), "-C", testRepoPath, "commit-tree", treeID, "-m", commitMessage), ) - } // CreateCommitOnNewBranch creates a branch and a commit, returning the commit sha and the branch name respectivelyi |