diff options
author | Sami Hiltunen <shiltunen@gitlab.com> | 2022-07-08 17:31:52 +0300 |
---|---|---|
committer | Sami Hiltunen <shiltunen@gitlab.com> | 2022-07-08 17:31:52 +0300 |
commit | 823c15369c005fc51a4598cf98adc60d49d30dcd (patch) | |
tree | 376ba940e30360f601aece8a374620bd26475189 | |
parent | 43cb85d43809733551d9ad682987d89a2f4afb36 (diff) | |
parent | 39e80f85a7314483652eadd15f76d89f2a027f9f (diff) |
Merge branch 'toon-linguist-be-gone' into 'master'
linguist: Implement Stats in pure Go
See merge request gitlab-org/gitaly!4580
-rw-r--r-- | NOTICE | 204 | ||||
-rw-r--r-- | go.mod | 2 | ||||
-rw-r--r-- | go.sum | 4 | ||||
-rw-r--r-- | internal/git/gitpipe/diff_tree.go | 147 | ||||
-rw-r--r-- | internal/git/gitpipe/diff_tree_test.go | 140 | ||||
-rw-r--r-- | internal/git/gitpipe/ls_tree.go | 126 | ||||
-rw-r--r-- | internal/git/gitpipe/ls_tree_test.go | 151 | ||||
-rw-r--r-- | internal/git/localrepo/repo.go | 15 | ||||
-rw-r--r-- | internal/git/localrepo/repo_test.go | 20 | ||||
-rw-r--r-- | internal/gitaly/linguist/language_stats.go | 157 | ||||
-rw-r--r-- | internal/gitaly/linguist/language_stats_test.go | 195 | ||||
-rw-r--r-- | internal/gitaly/linguist/linguist.go | 112 | ||||
-rw-r--r-- | internal/gitaly/linguist/linguist_test.go | 251 | ||||
-rw-r--r-- | internal/gitaly/service/commit/languages.go | 6 | ||||
-rw-r--r-- | internal/gitaly/service/commit/languages_test.go | 60 | ||||
-rw-r--r-- | internal/metadata/featureflag/ff_go_language_stats.go | 10 | ||||
-rw-r--r-- | proto/commit.proto | 29 | ||||
-rw-r--r-- | proto/go/gitalypb/commit.pb.go | 26 | ||||
-rw-r--r-- | proto/go/gitalypb/commit_grpc.pb.go | 6 | ||||
-rw-r--r-- | ruby/Gemfile | 2 | ||||
-rw-r--r-- | ruby/Gemfile.lock | 10 | ||||
-rw-r--r-- | ruby/proto/gitaly/commit_services_pb.rb | 3 |
22 files changed, 1576 insertions, 100 deletions
@@ -7670,6 +7670,210 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +LICENSE - github.com/go-enry/go-enry/v2 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ LICENSE.md - github.com/go-enry/go-license-detector/v4/licensedb Apache License ============== @@ -8,6 +8,7 @@ require ( github.com/containerd/cgroups v0.0.0-20201118023556-2819c83ced99 github.com/getsentry/sentry-go v0.13.0 github.com/git-lfs/git-lfs/v3 v3.2.0 + github.com/go-enry/go-enry/v2 v2.8.2 github.com/go-enry/go-license-detector/v4 v4.3.0 github.com/google/go-cmp v0.5.8 github.com/google/uuid v1.3.0 @@ -97,6 +98,7 @@ require ( github.com/git-lfs/go-netrc v0.0.0-20210914205454-f0c862dd687a // indirect github.com/git-lfs/pktline v0.0.0-20210330133718-06e9096e2825 // indirect github.com/git-lfs/wildmatch/v2 v2.0.1 // indirect + github.com/go-enry/go-oniguruma v1.2.1 // indirect github.com/go-git/gcfg v1.5.0 // indirect github.com/go-git/go-billy/v5 v5.1.0 // indirect github.com/go-git/go-git/v5 v5.3.0 // indirect @@ -386,8 +386,12 @@ github.com/git-lfs/wildmatch/v2 v2.0.1/go.mod h1:EVqonpk9mXbREP3N8UkwoWdrF249uHp github.com/gliderlabs/ssh v0.2.2 h1:6zsha5zo/TWhRhwqCD3+EarCAgZ2yN28ipRnGPnwkI0= github.com/gliderlabs/ssh v0.2.2/go.mod h1:U7qILu1NlMHj9FlMhZLlkCdDnU1DBEAqr0aevW3Awn0= github.com/go-check/check v0.0.0-20180628173108-788fd7840127/go.mod h1:9ES+weclKsC9YodN5RgxqK/VD9HM9JsCSh7rNhMZE98= +github.com/go-enry/go-enry/v2 v2.8.2 h1:uiGmC+3K8sVd/6DOe2AOJEOihJdqda83nPyJNtMR8RI= +github.com/go-enry/go-enry/v2 v2.8.2/go.mod h1:GVzIiAytiS5uT/QiuakK7TF1u4xDab87Y8V5EJRpsIQ= github.com/go-enry/go-license-detector/v4 v4.3.0 h1:OFlQAVNw5FlKUjX4OuW8JOabu8MQHjTKDb9pdeNYMUw= github.com/go-enry/go-license-detector/v4 v4.3.0/go.mod h1:HaM4wdNxSlz/9Gw0uVOKSQS5JVFqf2Pk8xUPEn6bldI= +github.com/go-enry/go-oniguruma v1.2.1 h1:k8aAMuJfMrqm/56SG2lV9Cfti6tC4x8673aHCcBk+eo= +github.com/go-enry/go-oniguruma v1.2.1/go.mod h1:bWDhYP+S6xZQgiRL7wlTScFYBe023B6ilRZbCAD5Hf4= 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-git/gcfg v1.5.0 h1:Q5ViNfGF8zFgyJWPqYwA7qGFoMTEiBmdlkcfRmpIMa4= diff --git a/internal/git/gitpipe/diff_tree.go b/internal/git/gitpipe/diff_tree.go new file mode 100644 index 000000000..c41e77a6a --- /dev/null +++ b/internal/git/gitpipe/diff_tree.go @@ -0,0 +1,147 @@ +package gitpipe + +import ( + "bufio" + "bytes" + "context" + "fmt" + "strings" + + "gitlab.com/gitlab-org/gitaly/v15/internal/git" + "gitlab.com/gitlab-org/gitaly/v15/internal/git/localrepo" +) + +// diffTreeConfig is configuration for the DiffTree pipeline step. +type diffTreeConfig struct { + recursive bool + ignoreSubmodules bool + skipResult func(*RevisionResult) bool +} + +// DiffTreeOption is an option for the DiffTree pipeline step. +type DiffTreeOption func(cfg *diffTreeConfig) + +// DiffTreeWithRecursive will make DiffTree recurse into subtrees. +func DiffTreeWithRecursive() DiffTreeOption { + return func(cfg *diffTreeConfig) { + cfg.recursive = true + } +} + +// DiffTreeWithIgnoreSubmodules causes git-diff-tree(1) to exclude submodule changes. +func DiffTreeWithIgnoreSubmodules() DiffTreeOption { + return func(cfg *diffTreeConfig) { + cfg.ignoreSubmodules = true + } +} + +// DiffTreeWithSkip will execute the given function for each RevisionResult processed by the +// pipeline. If the callback returns `true`, then the object will be skipped and not passed down +// the pipeline. +func DiffTreeWithSkip(skipResult func(*RevisionResult) bool) DiffTreeOption { + return func(cfg *diffTreeConfig) { + cfg.skipResult = skipResult + } +} + +// DiffTree runs git-diff-tree(1) between the two given revisions. The returned +// channel will contain the new object IDs listed by this command. For deleted +// files this would be git.ZeroOID. Cancelling the context will cause the +// pipeline to be cancelled, too. By default, it will not recurse into subtrees. +func DiffTree( + ctx context.Context, + repo *localrepo.Repo, + leftRevision, rightRevision string, + options ...DiffTreeOption, +) RevisionIterator { + var cfg diffTreeConfig + for _, option := range options { + option(&cfg) + } + + resultChan := make(chan RevisionResult) + go func() { + defer close(resultChan) + + flags := []git.Option{} + + if cfg.recursive { + flags = append(flags, git.Flag{Name: "-r"}) + } + if cfg.ignoreSubmodules { + flags = append(flags, git.Flag{Name: "--ignore-submodules"}) + } + + var stderr strings.Builder + cmd, err := repo.Exec(ctx, + git.SubCmd{ + Name: "diff-tree", + Flags: flags, + Args: []string{leftRevision, rightRevision}, + }, + git.WithStderr(&stderr), + ) + if err != nil { + sendRevisionResult(ctx, resultChan, RevisionResult{ + err: fmt.Errorf("executing diff-tree: %w", err), + }) + return + } + + scanner := bufio.NewScanner(cmd) + for scanner.Scan() { + // We need to copy the line here because we'll hand it over to the caller + // asynchronously, and the next call to `Scan()` will overwrite the buffer. + line := make([]byte, len(scanner.Bytes())) + copy(line, scanner.Bytes()) + + attrsAndFile := bytes.SplitN(line, []byte{'\t'}, 2) + if len(attrsAndFile) != 2 { + sendRevisionResult(ctx, resultChan, RevisionResult{ + err: fmt.Errorf("splitting diff-tree attributes and file"), + }) + return + } + + attrs := bytes.SplitN(attrsAndFile[0], []byte{' '}, 5) + if len(attrs) != 5 { + sendRevisionResult(ctx, resultChan, RevisionResult{ + err: fmt.Errorf("splitting diff-tree attributes"), + }) + return + } + + result := RevisionResult{ + OID: git.ObjectID(attrs[3]), + ObjectName: attrsAndFile[1], + } + + if cfg.skipResult != nil && cfg.skipResult(&result) { + continue + } + + if isDone := sendRevisionResult(ctx, resultChan, result); isDone { + return + } + } + + if err := scanner.Err(); err != nil { + sendRevisionResult(ctx, resultChan, RevisionResult{ + err: fmt.Errorf("scanning diff-tree output: %w", err), + }) + return + } + + if err := cmd.Wait(); err != nil { + sendRevisionResult(ctx, resultChan, RevisionResult{ + err: fmt.Errorf("diff-tree pipeline command: %w, stderr: %q", err, stderr.String()), + }) + return + } + }() + + return &revisionIterator{ + ctx: ctx, + ch: resultChan, + } +} diff --git a/internal/git/gitpipe/diff_tree_test.go b/internal/git/gitpipe/diff_tree_test.go new file mode 100644 index 000000000..700772244 --- /dev/null +++ b/internal/git/gitpipe/diff_tree_test.go @@ -0,0 +1,140 @@ +package gitpipe + +import ( + "errors" + "testing" + + "github.com/stretchr/testify/require" + "gitlab.com/gitlab-org/gitaly/v15/internal/git/gittest" + "gitlab.com/gitlab-org/gitaly/v15/internal/git/localrepo" + "gitlab.com/gitlab-org/gitaly/v15/internal/testhelper" + "gitlab.com/gitlab-org/gitaly/v15/internal/testhelper/testcfg" +) + +func TestDiffTree(t *testing.T) { + cfg := testcfg.Build(t) + + repoProto, _ := gittest.CloneRepo(t, cfg, cfg.Storages[0]) + repo := localrepo.NewTestRepo(t, cfg, repoProto) + + for _, tc := range []struct { + desc string + leftRevision string + rightRevision string + options []DiffTreeOption + expectedResults []RevisionResult + expectedErr error + }{ + { + desc: "single file", + leftRevision: "b83d6e391c22777fca1ed3012fce84f633d7fed0", + rightRevision: "4a24d82dbca5c11c61556f3b35ca472b7463187e", + expectedResults: []RevisionResult{ + { + OID: "c60514b6d3d6bf4bec1030f70026e34dfbd69ad5", + ObjectName: []byte("README.md"), + }, + }, + }, + { + desc: "single file in subtree without recursive", + leftRevision: "7975be0116940bf2ad4321f79d02a55c5f7779aa", + rightRevision: "1e292f8fedd741b75372e19097c76d327140c312", + expectedResults: []RevisionResult{ + { + OID: "ceb102b8d3f9a95c2eb979213e49f7cc1b23d56e", + ObjectName: []byte("files"), + }, + }, + }, + { + desc: "single file in subtree with recursive", + leftRevision: "7975be0116940bf2ad4321f79d02a55c5f7779aa", + rightRevision: "1e292f8fedd741b75372e19097c76d327140c312", + options: []DiffTreeOption{ + DiffTreeWithRecursive(), + }, + expectedResults: []RevisionResult{ + { + OID: "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391", + ObjectName: []byte("files/flat/path/correct/content.txt"), + }, + }, + }, + { + desc: "with submodules", + leftRevision: "570e7b2abdd848b95f2f578043fc23bd6f6fd24d", + rightRevision: "5937ac0a7beb003549fc5fd26fc247adbce4a52e", + expectedResults: []RevisionResult{ + { + OID: "efd587ccb47caf5f31fc954edb21f0a713d9ecc3", + ObjectName: []byte(".gitmodules"), + }, + { + OID: "645f6c4c82fd3f5e06f67134450a570b795e55a6", + ObjectName: []byte("gitlab-grack"), + }, + }, + }, + { + desc: "without submodules", + leftRevision: "570e7b2abdd848b95f2f578043fc23bd6f6fd24d", + rightRevision: "5937ac0a7beb003549fc5fd26fc247adbce4a52e", + options: []DiffTreeOption{ + DiffTreeWithIgnoreSubmodules(), + }, + expectedResults: []RevisionResult{ + { + OID: "efd587ccb47caf5f31fc954edb21f0a713d9ecc3", + ObjectName: []byte(".gitmodules"), + }, + }, + }, + { + desc: "with skip function", + leftRevision: "570e7b2abdd848b95f2f578043fc23bd6f6fd24d", + rightRevision: "5937ac0a7beb003549fc5fd26fc247adbce4a52e", + options: []DiffTreeOption{ + DiffTreeWithSkip(func(r *RevisionResult) bool { + return r.OID == "efd587ccb47caf5f31fc954edb21f0a713d9ecc3" + }), + }, + expectedResults: []RevisionResult{ + { + OID: "645f6c4c82fd3f5e06f67134450a570b795e55a6", + ObjectName: []byte("gitlab-grack"), + }, + }, + }, + { + desc: "invalid revision", + leftRevision: "refs/heads/master", + rightRevision: "refs/heads/does-not-exist", + expectedErr: errors.New("diff-tree pipeline command: exit status 128, stderr: " + + "\"fatal: ambiguous argument 'refs/heads/does-not-exist': unknown revision or path not in the working tree.\\n" + + "Use '--' to separate paths from revisions, like this:\\n" + + "'git <command> [<revision>...] -- [<file>...]'\\n\""), + }, + } { + t.Run(tc.desc, func(t *testing.T) { + ctx := testhelper.Context(t) + + it := DiffTree(ctx, repo, tc.leftRevision, tc.rightRevision, tc.options...) + + var results []RevisionResult + for it.Next() { + results = append(results, it.Result()) + } + + // We're converting the error here to a plain un-nested error such that we + // don't have to replicate the complete error's structure. + err := it.Err() + if err != nil { + err = errors.New(err.Error()) + } + + require.Equal(t, tc.expectedErr, err) + require.Equal(t, tc.expectedResults, results) + }) + } +} diff --git a/internal/git/gitpipe/ls_tree.go b/internal/git/gitpipe/ls_tree.go new file mode 100644 index 000000000..10c6237c1 --- /dev/null +++ b/internal/git/gitpipe/ls_tree.go @@ -0,0 +1,126 @@ +package gitpipe + +import ( + "context" + "errors" + "fmt" + "io" + "strings" + + "gitlab.com/gitlab-org/gitaly/v15/internal/git" + "gitlab.com/gitlab-org/gitaly/v15/internal/git/localrepo" + "gitlab.com/gitlab-org/gitaly/v15/internal/git/lstree" +) + +// lsTreeConfig is configuration for the LsTree pipeline step. +type lsTreeConfig struct { + recursive bool + typeFilter func(*lstree.Entry) bool + skipResult func(*RevisionResult) bool +} + +// LsTreeOption is an option for the LsTree pipeline step. +type LsTreeOption func(cfg *lsTreeConfig) + +// LsTreeWithRecursive will make LsTree recursive into subtrees. +func LsTreeWithRecursive() LsTreeOption { + return func(cfg *lsTreeConfig) { + cfg.recursive = true + } +} + +// LsTreeWithBlobFilter configures LsTree to only pass through blob objects. +func LsTreeWithBlobFilter() LsTreeOption { + return func(cfg *lsTreeConfig) { + cfg.typeFilter = func(e *lstree.Entry) bool { return e.Type == lstree.Blob } + } +} + +// LsTree runs git-ls-tree(1) for the given revisions. The returned channel will +// contain all object IDs listed by this command. This might include: +// - Blobs +// - Trees, unless you're calling it with LsTreeWithRecursive() +// - Submodules, referring to the commit of the submodule +func LsTree( + ctx context.Context, + repo *localrepo.Repo, + revision string, + options ...LsTreeOption, +) RevisionIterator { + var cfg lsTreeConfig + for _, option := range options { + option(&cfg) + } + + resultChan := make(chan RevisionResult) + go func() { + defer close(resultChan) + + flags := []git.Option{ + git.Flag{Name: "-z"}, + } + + if cfg.recursive { + flags = append(flags, git.Flag{Name: "-r"}) + } + + var stderr strings.Builder + cmd, err := repo.Exec(ctx, + git.SubCmd{ + Name: "ls-tree", + Flags: flags, + Args: []string{revision}, + }, + git.WithStderr(&stderr), + ) + if err != nil { + sendRevisionResult(ctx, resultChan, RevisionResult{ + err: fmt.Errorf("spawning ls-tree: %w", err), + }) + return + } + + parser := lstree.NewParser(cmd) + for { + entry, err := parser.NextEntry() + if err != nil { + if errors.Is(err, io.EOF) { + break + } + sendRevisionResult(ctx, resultChan, RevisionResult{ + err: fmt.Errorf("scanning ls-tree output: %w", err), + }) + return + } + + if cfg.typeFilter != nil && !cfg.typeFilter(entry) { + continue + } + + result := RevisionResult{ + OID: entry.ObjectID, + ObjectName: []byte(entry.Path), + } + + if cfg.skipResult != nil && cfg.skipResult(&result) { + continue + } + + if isDone := sendRevisionResult(ctx, resultChan, result); isDone { + return + } + } + + if err := cmd.Wait(); err != nil { + sendRevisionResult(ctx, resultChan, RevisionResult{ + err: fmt.Errorf("ls-tree pipeline command: %w, stderr: %q", err, stderr.String()), + }) + return + } + }() + + return &revisionIterator{ + ctx: ctx, + ch: resultChan, + } +} diff --git a/internal/git/gitpipe/ls_tree_test.go b/internal/git/gitpipe/ls_tree_test.go new file mode 100644 index 000000000..7d1133055 --- /dev/null +++ b/internal/git/gitpipe/ls_tree_test.go @@ -0,0 +1,151 @@ +package gitpipe + +import ( + "errors" + "testing" + + "github.com/stretchr/testify/require" + "gitlab.com/gitlab-org/gitaly/v15/internal/git/gittest" + "gitlab.com/gitlab-org/gitaly/v15/internal/git/localrepo" + "gitlab.com/gitlab-org/gitaly/v15/internal/testhelper" + "gitlab.com/gitlab-org/gitaly/v15/internal/testhelper/testcfg" +) + +func TestLsTree(t *testing.T) { + cfg := testcfg.Build(t) + + repoProto, _ := gittest.CloneRepo(t, cfg, cfg.Storages[0]) + repo := localrepo.NewTestRepo(t, cfg, repoProto) + + for _, tc := range []struct { + desc string + revision string + options []LsTreeOption + expectedResults []RevisionResult + expectedErr error + }{ + { + desc: "initial commit", + revision: "1a0b36b3cdad1d2ee32457c102a8c0b7056fa863", + expectedResults: []RevisionResult{ + {OID: "470ad2fcf1e33798f1afc5781d08e60c40f51e7a", ObjectName: []byte(".gitignore")}, + {OID: "50b27c6518be44c42c4d87966ae2481ce895624c", ObjectName: []byte("LICENSE")}, + {OID: "faaf198af3a36dbf41961466703cc1d47c61d051", ObjectName: []byte("README.md")}, + }, + }, + { + desc: "includes submodule", + revision: "cfe32cf61b73a0d5e9f13e774abde7ff789b1660", + expectedResults: []RevisionResult{ + {OID: "470ad2fcf1e33798f1afc5781d08e60c40f51e7a", ObjectName: []byte(".gitignore")}, + {OID: "fdaada1754989978413d618ee1fb1c0469d6a664", ObjectName: []byte(".gitmodules")}, + {OID: "c1788657b95998a2f177a4f86d68a60f2a80117f", ObjectName: []byte("CONTRIBUTING.md")}, + {OID: "50b27c6518be44c42c4d87966ae2481ce895624c", ObjectName: []byte("LICENSE")}, + {OID: "faaf198af3a36dbf41961466703cc1d47c61d051", ObjectName: []byte("README.md")}, + {OID: "409f37c4f05865e4fb208c771485f211a22c4c2d", ObjectName: []byte("six")}, + }, + }, + { + desc: "filter blobs only", + revision: "cfe32cf61b73a0d5e9f13e774abde7ff789b1660", + options: []LsTreeOption{ + LsTreeWithBlobFilter(), + }, + expectedResults: []RevisionResult{ + {OID: "470ad2fcf1e33798f1afc5781d08e60c40f51e7a", ObjectName: []byte(".gitignore")}, + {OID: "fdaada1754989978413d618ee1fb1c0469d6a664", ObjectName: []byte(".gitmodules")}, + {OID: "c1788657b95998a2f177a4f86d68a60f2a80117f", ObjectName: []byte("CONTRIBUTING.md")}, + {OID: "50b27c6518be44c42c4d87966ae2481ce895624c", ObjectName: []byte("LICENSE")}, + {OID: "faaf198af3a36dbf41961466703cc1d47c61d051", ObjectName: []byte("README.md")}, + }, + }, + { + desc: "empty tree", + revision: "7efb185dd22fd5c51ef044795d62b7847900c341", + }, + { + desc: "non-recursive", + revision: "913c66a37b4a45b9769037c55c2d238bd0942d2e", + expectedResults: []RevisionResult{ + {OID: "fd90a3d2d21d6b4f9bec2c33fb7f49780c55f0d2", ObjectName: []byte(".DS_Store")}, + {OID: "470ad2fcf1e33798f1afc5781d08e60c40f51e7a", ObjectName: []byte(".gitignore")}, + {OID: "fdaada1754989978413d618ee1fb1c0469d6a664", ObjectName: []byte(".gitmodules")}, + {OID: "c74175afd117781cbc983664339a0f599b5bb34e", ObjectName: []byte("CHANGELOG")}, + {OID: "c1788657b95998a2f177a4f86d68a60f2a80117f", ObjectName: []byte("CONTRIBUTING.md")}, + {OID: "50b27c6518be44c42c4d87966ae2481ce895624c", ObjectName: []byte("LICENSE")}, + {OID: "95d9f0a5e7bb054e9dd3975589b8dfc689e20e88", ObjectName: []byte("MAINTENANCE.md")}, + {OID: "bf757025c40c62e6ffa6f11d3819c769a76dbe09", ObjectName: []byte("PROCESS.md")}, + {OID: "faaf198af3a36dbf41961466703cc1d47c61d051", ObjectName: []byte("README.md")}, + {OID: "998707b421c89bd9a3063333f9f728ef3e43d101", ObjectName: []byte("VERSION")}, + {OID: "3c122d2b7830eca25235131070602575cf8b41a1", ObjectName: []byte("encoding")}, + {OID: "ab746f8ad0b84b147290041dc13cc9c7adc52930", ObjectName: []byte("files")}, + {OID: "409f37c4f05865e4fb208c771485f211a22c4c2d", ObjectName: []byte("six")}, + }, + }, + { + desc: "recursive", + revision: "913c66a37b4a45b9769037c55c2d238bd0942d2e", + options: []LsTreeOption{ + LsTreeWithRecursive(), + }, + expectedResults: []RevisionResult{ + {OID: "fd90a3d2d21d6b4f9bec2c33fb7f49780c55f0d2", ObjectName: []byte(".DS_Store")}, + {OID: "470ad2fcf1e33798f1afc5781d08e60c40f51e7a", ObjectName: []byte(".gitignore")}, + {OID: "fdaada1754989978413d618ee1fb1c0469d6a664", ObjectName: []byte(".gitmodules")}, + {OID: "c74175afd117781cbc983664339a0f599b5bb34e", ObjectName: []byte("CHANGELOG")}, + {OID: "c1788657b95998a2f177a4f86d68a60f2a80117f", ObjectName: []byte("CONTRIBUTING.md")}, + {OID: "50b27c6518be44c42c4d87966ae2481ce895624c", ObjectName: []byte("LICENSE")}, + {OID: "95d9f0a5e7bb054e9dd3975589b8dfc689e20e88", ObjectName: []byte("MAINTENANCE.md")}, + {OID: "bf757025c40c62e6ffa6f11d3819c769a76dbe09", ObjectName: []byte("PROCESS.md")}, + {OID: "faaf198af3a36dbf41961466703cc1d47c61d051", ObjectName: []byte("README.md")}, + {OID: "998707b421c89bd9a3063333f9f728ef3e43d101", ObjectName: []byte("VERSION")}, + {OID: "8af7f880ce38649fc49f66e3f38857bfbec3f0b7", ObjectName: []byte("encoding/feature-1.txt")}, + {OID: "16ca0b267f82cd2f5ca1157dd162dae98745eab8", ObjectName: []byte("encoding/feature-2.txt")}, + {OID: "0fb47f093f769008049a0b0976ac3fa6d6125033", ObjectName: []byte("encoding/hotfix-1.txt")}, + {OID: "4ae6c5e14452a35d04156277ae63e8356eb17cae", ObjectName: []byte("encoding/hotfix-2.txt")}, + {OID: "570f8e1dfe8149c1d17002712310d43dfeb43159", ObjectName: []byte("encoding/russian.rb")}, + {OID: "7a17968582c21c9153ec24c6a9d5f33592ad9103", ObjectName: []byte("encoding/test.txt")}, + {OID: "f3064a3aa9c14277483f690250072e987e2c8356", ObjectName: []byte("encoding/\343\203\206\343\202\271\343\203\210.txt")}, + {OID: "3a26c18b02e843b459732e7ade7ab9a154a1002b", ObjectName: []byte("encoding/\343\203\206\343\202\271\343\203\210.xls")}, + {OID: "60d7a906c2fd9e4509aeb1187b98d0ea7ce827c9", ObjectName: []byte("files/.DS_Store")}, + {OID: "c84b9e90e4bee2666f5cb3688690d9824d88f3ee", ObjectName: []byte("files/html/500.html")}, + {OID: "4a96572d570108366da2cf5aa8213f69b591a2a3", ObjectName: []byte("files/images/logo-black.png")}, + {OID: "bc2ef601a538d69ef99d5bdafa605e63f902e8e4", ObjectName: []byte("files/images/logo-white.png")}, + {OID: "4a393dbfe81113d35d9aedeb5c76f763190c1b2f", ObjectName: []byte("files/js/application.js")}, + {OID: "5f53439ca4b009096571d3c8bc3d09d30e7431b3", ObjectName: []byte("files/js/commit.js.coffee")}, + {OID: "3da5c4ddbaf17d37aea52c485d8bb85b07d77816", ObjectName: []byte("files/markdown/ruby-style-guide.md")}, + {OID: "e2fbafb389911ef68e4da2da7da917f6acb9e86a", ObjectName: []byte("files/ruby/popen.rb")}, + {OID: "d18fc8bf2cecbe21bbbd5da692eaf83e32c48638", ObjectName: []byte("files/ruby/regex.rb")}, + {OID: "6ee41e85cc9bf33c10b690df09ca735b22f3790f", ObjectName: []byte("files/ruby/version_info.rb")}, + {OID: "409f37c4f05865e4fb208c771485f211a22c4c2d", ObjectName: []byte("six")}, + }, + }, + { + desc: "invalid revision", + revision: "refs/heads/does-not-exist", + expectedErr: errors.New("ls-tree pipeline command: exit status 128, stderr: " + + "\"fatal: Not a valid object name refs/heads/does-not-exist\\n\""), + }, + } { + t.Run(tc.desc, func(t *testing.T) { + ctx := testhelper.Context(t) + + it := LsTree(ctx, repo, tc.revision, tc.options...) + + var results []RevisionResult + for it.Next() { + results = append(results, it.Result()) + } + + // We're converting the error here to a plain un-nested error such that we + // don't have to replicate the complete error's structure. + err := it.Err() + if err != nil { + err = errors.New(err.Error()) + } + + require.Equal(t, tc.expectedErr, err) + require.Equal(t, tc.expectedResults, results) + }) + } +} diff --git a/internal/git/localrepo/repo.go b/internal/git/localrepo/repo.go index 6d6ac6da3..730176543 100644 --- a/internal/git/localrepo/repo.go +++ b/internal/git/localrepo/repo.go @@ -205,3 +205,18 @@ func (repo *Repo) Size(ctx context.Context, opts ...RepoSizeOption) (int64, erro return size, nil } + +// StorageTempDir returns the temporary dir for the storage where the repo is on. +// When this directory does not exist yet, it's being created. +func (repo *Repo) StorageTempDir() (string, error) { + tempPath, err := repo.locator.TempDir(repo.GetStorageName()) + if err != nil { + return "", err + } + + if err := os.MkdirAll(tempPath, 0o755); err != nil { + return "", err + } + + return tempPath, nil +} diff --git a/internal/git/localrepo/repo_test.go b/internal/git/localrepo/repo_test.go index bc986eddf..f90e5377e 100644 --- a/internal/git/localrepo/repo_test.go +++ b/internal/git/localrepo/repo_test.go @@ -342,3 +342,23 @@ func TestSize(t *testing.T) { }) } } + +func TestRepo_StorageTempDir(t *testing.T) { + cfg := testcfg.Build(t) + gitCmdFactory := gittest.NewCommandFactory(t, cfg) + catfileCache := catfile.NewCache(cfg) + t.Cleanup(catfileCache.Stop) + locator := config.NewLocator(cfg) + + pbRepo, _ := gittest.CloneRepo(t, cfg, cfg.Storages[0]) + repo := New(locator, gitCmdFactory, catfileCache, pbRepo) + + expected, err := locator.TempDir(cfg.Storages[0].Name) + require.NoError(t, err) + require.NoDirExists(t, expected) + + tempPath, err := repo.StorageTempDir() + require.NoError(t, err) + require.DirExists(t, expected) + require.Equal(t, expected, tempPath) +} diff --git a/internal/gitaly/linguist/language_stats.go b/internal/gitaly/linguist/language_stats.go new file mode 100644 index 000000000..9dad17c11 --- /dev/null +++ b/internal/gitaly/linguist/language_stats.go @@ -0,0 +1,157 @@ +package linguist + +import ( + "compress/zlib" + "encoding/json" + "fmt" + "os" + "path/filepath" + "sync" + + "gitlab.com/gitlab-org/gitaly/v15/internal/git/localrepo" +) + +const ( + // languageStatsFilename is the name of the file in the repo that stores + // a cached version of the language statistics. The name is + // intentionally different from what the linguist gem uses. + languageStatsFilename = "gitaly-language.stats" + languageStatsVersion = "v1:gitaly" +) + +// languageStats takes care of accumulating and caching language statistics for +// a repository. +type languageStats struct { + // Version holds the file format version + Version string `json:"version"` + // CommitID holds the commit ID for the cached Totals + CommitID string `json:"commit_id"` + + // m will protect concurrent writes to Totals & ByFile maps + m sync.Mutex + + // Totals contains the total statistics for the CommitID + Totals ByteCountPerLanguage `json:"totals"` + // ByFile contains the statistics for a single file, where the filename + // is it's key. + ByFile map[string]ByteCountPerLanguage `json:"by_file"` +} + +// newLanguageStats creates a languageStats object and tries to load the +// optionally available stats from file. +func newLanguageStats(repo *localrepo.Repo) (*languageStats, error) { + stats := languageStats{ + Totals: ByteCountPerLanguage{}, + ByFile: make(map[string]ByteCountPerLanguage), + } + + objPath, err := repo.Path() + if err != nil { + return &stats, fmt.Errorf("new language stats get repo path: %w", err) + } + + file, err := os.Open(filepath.Join(objPath, languageStatsFilename)) + if err != nil { + if os.IsNotExist(err) { + return &stats, nil + } + return &stats, fmt.Errorf("new language stats open: %w", err) + } + defer file.Close() + + r, err := zlib.NewReader(file) + if err != nil { + return &stats, fmt.Errorf("new language stats zlib reader: %w", err) + } + + var loaded languageStats + if err = json.NewDecoder(r).Decode(&loaded); err != nil { + return &stats, fmt.Errorf("new language stats json decode: %w", err) + } + + if loaded.Version != languageStatsVersion { + return &stats, fmt.Errorf("new language stats version mismatch %s vs %s", languageStatsVersion, loaded.Version) + } + + return &loaded, nil +} + +// add the statistics for the given filename +func (c *languageStats) add(filename, language string, size uint64) { + c.m.Lock() + defer c.m.Unlock() + + for k, v := range c.ByFile[filename] { + c.Totals[k] -= v + if c.Totals[k] <= 0 { + delete(c.Totals, k) + } + } + + c.ByFile[filename] = ByteCountPerLanguage{language: size} + c.Totals[language] += size +} + +// drop statistics for the given files +func (c *languageStats) drop(filenames ...string) { + c.m.Lock() + defer c.m.Unlock() + + for _, f := range filenames { + for k, v := range c.ByFile[f] { + c.Totals[k] -= v + if c.Totals[k] <= 0 { + delete(c.Totals, k) + } + } + delete(c.ByFile, f) + } +} + +// save the language stats to file in the repository +func (c *languageStats) save(repo *localrepo.Repo, commitID string) error { + c.CommitID = commitID + c.Version = languageStatsVersion + + repoPath, err := repo.Path() + if err != nil { + return fmt.Errorf("languageStats save get repo path: %w", err) + } + + tempPath, err := repo.StorageTempDir() + if err != nil { + return fmt.Errorf("languageStats locate temp dir: %w", err) + } + + file, err := os.CreateTemp(tempPath, languageStatsFilename) + if err != nil { + return fmt.Errorf("languageStats create temp file: %w", err) + } + defer func() { + file.Close() + _ = os.Remove(file.Name()) + }() + + w := zlib.NewWriter(file) + defer w.Close() + + if err = json.NewEncoder(w).Encode(c); err != nil { + return fmt.Errorf("languageStats encode json: %w", err) + } + + if err = w.Close(); err != nil { + return fmt.Errorf("languageStats zlib write: %w", err) + } + if err = file.Sync(); err != nil { + return fmt.Errorf("languageStats flush: %w", err) + } + if err = file.Close(); err != nil { + return fmt.Errorf("languageStats close: %w", err) + } + + if err = os.Rename(file.Name(), filepath.Join(repoPath, languageStatsFilename)); err != nil { + return fmt.Errorf("languageStats rename: %w", err) + } + + return nil +} diff --git a/internal/gitaly/linguist/language_stats_test.go b/internal/gitaly/linguist/language_stats_test.go new file mode 100644 index 000000000..56f03bce7 --- /dev/null +++ b/internal/gitaly/linguist/language_stats_test.go @@ -0,0 +1,195 @@ +package linguist + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/require" + "gitlab.com/gitlab-org/gitaly/v15/internal/git/gittest" + "gitlab.com/gitlab-org/gitaly/v15/internal/git/localrepo" + "gitlab.com/gitlab-org/gitaly/v15/internal/testhelper/testcfg" +) + +func TestNewLanguageStats(t *testing.T) { + t.Parallel() + + cfg := testcfg.Build(t) + repoProto, repoPath := gittest.CloneRepo(t, cfg, cfg.Storages[0]) + repo := localrepo.NewTestRepo(t, cfg, repoProto) + + t.Run("non-existing cache", func(t *testing.T) { + s, err := newLanguageStats(repo) + require.NoError(t, err) + require.Empty(t, s.Totals) + require.Empty(t, s.ByFile) + }) + + t.Run("pre-existing cache", func(t *testing.T) { + s, err := newLanguageStats(repo) + require.NoError(t, err) + + s.Totals["C"] = 555 + require.NoError(t, s.save(repo, "badcafe")) + + require.Equal(t, ByteCountPerLanguage{"C": 555}, s.Totals) + }) + + t.Run("corrupt cache", func(t *testing.T) { + require.NoError(t, os.WriteFile(filepath.Join(repoPath, languageStatsFilename), []byte("garbage"), 0o644)) + + s, err := newLanguageStats(repo) + require.Errorf(t, err, "new language stats zlib reader: invalid header") + require.Empty(t, s.Totals) + require.Empty(t, s.ByFile) + }) +} + +func TestLanguageStats_add(t *testing.T) { + t.Parallel() + + cfg := testcfg.Build(t) + repoProto, _ := gittest.CloneRepo(t, cfg, cfg.Storages[0]) + repo := localrepo.NewTestRepo(t, cfg, repoProto) + + for _, tc := range []struct { + desc string + run func(*testing.T, *languageStats) + }{ + { + desc: "adds to the total", + run: func(t *testing.T, s *languageStats) { + s.add("main.go", "Go", 100) + + require.Equal(t, uint64(100), s.Totals["Go"]) + require.Len(t, s.ByFile, 1) + require.Equal(t, ByteCountPerLanguage{"Go": 100}, s.ByFile["main.go"]) + }, + }, + { + desc: "accumulates", + run: func(t *testing.T, s *languageStats) { + s.add("main.go", "Go", 100) + s.add("main_test.go", "Go", 80) + + require.Equal(t, uint64(180), s.Totals["Go"]) + require.Len(t, s.ByFile, 2) + require.Equal(t, ByteCountPerLanguage{"Go": 100}, s.ByFile["main.go"]) + require.Equal(t, ByteCountPerLanguage{"Go": 80}, s.ByFile["main_test.go"]) + }, + }, + { + desc: "languages don't interfere", + run: func(t *testing.T, s *languageStats) { + s.add("main.go", "Go", 60) + s.add("Makefile", "Make", 30) + + require.Equal(t, uint64(60), s.Totals["Go"]) + require.Equal(t, uint64(30), s.Totals["Make"]) + require.Len(t, s.ByFile, 2) + require.Equal(t, ByteCountPerLanguage{"Go": 60}, s.ByFile["main.go"]) + require.Equal(t, ByteCountPerLanguage{"Make": 30}, s.ByFile["Makefile"]) + }, + }, + { + desc: "updates the stat for a file", + run: func(t *testing.T, s *languageStats) { + s.add("main.go", "Go", 60) + s.add("main.go", "Go", 30) + + require.Equal(t, uint64(30), s.Totals["Go"]) + require.Len(t, s.ByFile, 1) + require.Equal(t, ByteCountPerLanguage{"Go": 30}, s.ByFile["main.go"]) + }, + }, + } { + t.Run(tc.desc, func(t *testing.T) { + s, err := newLanguageStats(repo) + require.NoError(t, err) + + tc.run(t, s) + }) + } +} + +func TestLanguageStats_drop(t *testing.T) { + t.Parallel() + + cfg := testcfg.Build(t) + repoProto, _ := gittest.CloneRepo(t, cfg, cfg.Storages[0]) + repo := localrepo.NewTestRepo(t, cfg, repoProto) + + for _, tc := range []struct { + desc string + run func(*testing.T, *languageStats) + }{ + { + desc: "existing file", + run: func(t *testing.T, s *languageStats) { + s.drop("main.go") + + require.Equal(t, uint64(20), s.Totals["Go"]) + require.Len(t, s.ByFile, 1) + require.Equal(t, ByteCountPerLanguage{"Go": 20}, s.ByFile["main_test.go"]) + }, + }, + { + desc: "non-existing file", + run: func(t *testing.T, s *languageStats) { + s.drop("foo.go") + + require.Equal(t, uint64(100), s.Totals["Go"]) + require.Len(t, s.ByFile, 2) + require.Equal(t, ByteCountPerLanguage{"Go": 80}, s.ByFile["main.go"]) + require.Equal(t, ByteCountPerLanguage{"Go": 20}, s.ByFile["main_test.go"]) + }, + }, + { + desc: "all files", + run: func(t *testing.T, s *languageStats) { + s.drop("main.go", "main_test.go") + + require.Empty(t, s.Totals) + require.Empty(t, s.ByFile) + }, + }, + } { + t.Run(tc.desc, func(t *testing.T) { + s, err := newLanguageStats(repo) + require.NoError(t, err) + + s.Totals["Go"] = 100 + s.ByFile["main.go"] = ByteCountPerLanguage{"Go": 80} + s.ByFile["main_test.go"] = ByteCountPerLanguage{"Go": 20} + + tc.run(t, s) + }) + } +} + +func TestLanguageStats_save(t *testing.T) { + t.Parallel() + + cfg := testcfg.Build(t) + repoProto, repoPath := gittest.CloneRepo(t, cfg, cfg.Storages[0]) + repo := localrepo.NewTestRepo(t, cfg, repoProto) + + s, err := newLanguageStats(repo) + require.NoError(t, err) + + s.Totals["Go"] = 100 + s.ByFile["main.go"] = ByteCountPerLanguage{"Go": 80} + s.ByFile["main_test.go"] = ByteCountPerLanguage{"Go": 20} + + err = s.save(repo, "buzz") + require.NoError(t, err) + require.FileExists(t, filepath.Join(repoPath, languageStatsFilename)) + + loaded, err := newLanguageStats(repo) + require.NoError(t, err) + + require.Equal(t, "buzz", loaded.CommitID) + require.Equal(t, languageStatsVersion, loaded.Version) + require.Equal(t, s.Totals, loaded.Totals) + require.Equal(t, s.ByFile, loaded.ByFile) +} diff --git a/internal/gitaly/linguist/linguist.go b/internal/gitaly/linguist/linguist.go index da085b58a..2a1a92c60 100644 --- a/internal/gitaly/linguist/linguist.go +++ b/internal/gitaly/linguist/linguist.go @@ -10,10 +10,16 @@ import ( "os/exec" "path/filepath" + "github.com/go-enry/go-enry/v2" + "github.com/grpc-ecosystem/go-grpc-middleware/logging/logrus/ctxlogrus" "gitlab.com/gitlab-org/gitaly/v15/internal/command" "gitlab.com/gitlab-org/gitaly/v15/internal/git" + "gitlab.com/gitlab-org/gitaly/v15/internal/git/catfile" + "gitlab.com/gitlab-org/gitaly/v15/internal/git/gitpipe" + "gitlab.com/gitlab-org/gitaly/v15/internal/git/localrepo" "gitlab.com/gitlab-org/gitaly/v15/internal/gitaly/config" "gitlab.com/gitlab-org/gitaly/v15/internal/helper/env" + "gitlab.com/gitlab-org/gitaly/v15/internal/metadata/featureflag" ) // Language is used to parse Linguist's language.json file. @@ -53,7 +59,16 @@ func New(cfg config.Cfg, gitCmdFactory git.CommandFactory) (*Instance, error) { } // Stats returns the repository's language stats as reported by 'git-linguist'. -func (inst *Instance) Stats(ctx context.Context, repoPath string, commitID string) (ByteCountPerLanguage, error) { +func (inst *Instance) Stats(ctx context.Context, repo *localrepo.Repo, commitID string, catfileCache catfile.Cache) (ByteCountPerLanguage, error) { + if featureflag.GoLanguageStats.IsEnabled(ctx) { + return inst.enryStats(ctx, repo, commitID, catfileCache) + } + + repoPath, err := repo.Path() + if err != nil { + return nil, fmt.Errorf("get repo path: %w", err) + } + cmd, err := inst.startGitLinguist(ctx, repoPath, commitID) if err != nil { return nil, fmt.Errorf("starting linguist: %w", err) @@ -145,3 +160,98 @@ func openLanguagesJSON(cfg config.Cfg) (io.ReadCloser, error) { return os.Open(filepath.Join(linguistPathSymlink.Name(), "lib", "linguist", "languages.json")) } + +func (inst *Instance) enryStats(ctx context.Context, repo *localrepo.Repo, commitID string, catfileCache catfile.Cache) (ByteCountPerLanguage, error) { + stats, err := newLanguageStats(repo) + if err != nil { + ctxlogrus.Extract(ctx).WithError(err).Info("linguist load from cache") + } + if stats.CommitID == commitID { + return stats.Totals, nil + } + + objectReader, cancel, err := catfileCache.ObjectReader(ctx, repo) + if err != nil { + return nil, fmt.Errorf("create object reader: %w", err) + } + defer cancel() + + var revlistIt gitpipe.RevisionIterator + + if stats.CommitID == "" { + // No existing stats cached, so get all the files for the commit + // using git-ls-tree(1). + revlistIt = gitpipe.LsTree(ctx, repo, + commitID, + gitpipe.LsTreeWithRecursive(), + gitpipe.LsTreeWithBlobFilter(), + ) + } else { + // Stats are cached for one commit, so get the git-diff-tree(1) + // between that commit and the one we're calculating stats for. + + skipDeleted := func(result *gitpipe.RevisionResult) bool { + // Skip files that are deleted. + if result.OID.IsZeroOID() { + // It's a little bit of a hack to use this skip + // function, but for every file that's deleted, + // remove the stats. + stats.drop(string(result.ObjectName)) + return true + } + return false + } + + revlistIt = gitpipe.DiffTree(ctx, repo, + stats.CommitID, commitID, + gitpipe.DiffTreeWithRecursive(), + gitpipe.DiffTreeWithIgnoreSubmodules(), + gitpipe.DiffTreeWithSkip(skipDeleted), + ) + } + + objectIt, err := gitpipe.CatfileObject(ctx, objectReader, revlistIt) + if err != nil { + return nil, fmt.Errorf("linguist gitpipe: %w", err) + } + + for objectIt.Next() { + object := objectIt.Result() + filename := string(object.ObjectName) + + // Read arbitrary number of bytes considered enough to determine language + content, err := io.ReadAll(io.LimitReader(object, 2048)) + if err != nil { + return nil, fmt.Errorf("linguist read blob: %w", err) + } + + if _, err := io.Copy(io.Discard, object); err != nil { + return nil, fmt.Errorf("linguist discard excess blob: %w", err) + } + + lang := enry.GetLanguage(filename, content) + + // Ignore anything that's neither markup nor a programming language, + // similar to what the linguist gem does: + // https://github.com/github/linguist/blob/v7.20.0/lib/linguist/blob_helper.rb#L378-L387 + if enry.GetLanguageType(lang) != enry.Programming && + enry.GetLanguageType(lang) != enry.Markup { + // The file might have been included in the stats before + stats.drop(filename) + + continue + } + + stats.add(filename, lang, uint64(object.Object.ObjectSize())) + } + + if err := objectIt.Err(); err != nil { + return nil, fmt.Errorf("linguist object iterator: %w", err) + } + + if err := stats.save(repo, commitID); err != nil { + return nil, fmt.Errorf("linguist language stats save: %w", err) + } + + return stats.Totals, nil +} diff --git a/internal/gitaly/linguist/linguist_test.go b/internal/gitaly/linguist/linguist_test.go index 24cacf81e..b42168b41 100644 --- a/internal/gitaly/linguist/linguist_test.go +++ b/internal/gitaly/linguist/linguist_test.go @@ -1,43 +1,113 @@ package linguist import ( + "context" "encoding/json" "os" "path/filepath" "testing" + "github.com/go-enry/go-enry/v2" + enrydata "github.com/go-enry/go-enry/v2/data" + "github.com/sirupsen/logrus" + "github.com/sirupsen/logrus/hooks/test" "github.com/stretchr/testify/require" "gitlab.com/gitlab-org/gitaly/v15/internal/git" + "gitlab.com/gitlab-org/gitaly/v15/internal/git/catfile" "gitlab.com/gitlab-org/gitaly/v15/internal/git/gittest" + "gitlab.com/gitlab-org/gitaly/v15/internal/git/localrepo" "gitlab.com/gitlab-org/gitaly/v15/internal/gitaly/config" + "gitlab.com/gitlab-org/gitaly/v15/internal/metadata/featureflag" "gitlab.com/gitlab-org/gitaly/v15/internal/testhelper" "gitlab.com/gitlab-org/gitaly/v15/internal/testhelper/testcfg" + "gitlab.com/gitlab-org/gitaly/v15/proto/go/gitalypb" ) func TestMain(m *testing.M) { testhelper.Run(m) } +// TestNew_knownLanguages tests the compatibility between the Ruby and the Go +// implementation. This test will be removed together with the Ruby implementation. +func TestNew_knownLanguages(t *testing.T) { + t.Parallel() + + cfg := testcfg.Build(t, testcfg.WithRealLinguist()) + gitCmdFactory := gittest.NewCommandFactory(t, cfg) + + linguist, err := New(cfg, gitCmdFactory) + require.NoError(t, err) + + t.Run("by name", func(t *testing.T) { + linguistLanguages := make([]string, 0, len(linguist.colorMap)) + for language := range linguist.colorMap { + linguistLanguages = append(linguistLanguages, language) + } + + enryLanguages := make([]string, 0, len(enrydata.IDByLanguage)) + for language := range enrydata.IDByLanguage { + enryLanguages = append(enryLanguages, language) + } + + require.ElementsMatch(t, linguistLanguages, enryLanguages) + }) + + t.Run("with their color", func(t *testing.T) { + exclude := map[string]struct{}{} + + linguistLanguages := make(map[string]string, len(linguist.colorMap)) + for language, color := range linguist.colorMap { + if color.Color == "" { + exclude[language] = struct{}{} + continue + } + linguistLanguages[language] = color.Color + } + + enryLanguages := make(map[string]string, len(enrydata.IDByLanguage)) + for language := range enrydata.IDByLanguage { + if _, excluded := exclude[language]; excluded { + continue + } + + color := enry.GetColor(language) + enryLanguages[language] = color + } + + require.Equal(t, linguistLanguages, enryLanguages) + }) +} + func TestInstance_Stats(t *testing.T) { - ctx := testhelper.Context(t) + testhelper.NewFeatureSets(featureflag.GoLanguageStats). + Run(t, testInstanceStats) +} + +func testInstanceStats(t *testing.T, ctx context.Context) { cfg := testcfg.Build(t) + gitCmdFactory := gittest.NewCommandFactory(t, cfg) - linguist, err := New(cfg, gittest.NewCommandFactory(t, cfg)) + linguist, err := New(cfg, gitCmdFactory) require.NoError(t, err) + catfileCache := catfile.NewCache(cfg) + t.Cleanup(catfileCache.Stop) + commitID := git.ObjectID("1e292f8fedd741b75372e19097c76d327140c312") + languageStatsFilename := filenameForCache(ctx) + for _, tc := range []struct { desc string - setup func(t *testing.T) (string, git.ObjectID) + setup func(t *testing.T) (*gitalypb.Repository, string, git.ObjectID) expectedStats ByteCountPerLanguage expectedErr string }{ { desc: "successful", - setup: func(t *testing.T) (string, git.ObjectID) { - _, repoPath := gittest.CloneRepo(t, cfg, cfg.Storages[0]) - return repoPath, commitID + setup: func(t *testing.T) (*gitalypb.Repository, string, git.ObjectID) { + repoProto, repoPath := gittest.CloneRepo(t, cfg, cfg.Storages[0]) + return repoProto, repoPath, commitID }, expectedStats: map[string]uint64{ "CoffeeScript": 107, @@ -48,16 +118,20 @@ func TestInstance_Stats(t *testing.T) { }, { desc: "preexisting cache", - setup: func(t *testing.T) (string, git.ObjectID) { - _, repoPath := gittest.CloneRepo(t, cfg, cfg.Storages[0]) + setup: func(t *testing.T) (*gitalypb.Repository, string, git.ObjectID) { + repoProto, repoPath := gittest.CloneRepo(t, cfg, cfg.Storages[0]) + repo := localrepo.NewTestRepo(t, cfg, repoProto) // We simply run the linguist once before so that it can already // write the cache. - _, err := linguist.Stats(ctx, repoPath, commitID.String()) + _, err := linguist.Stats(ctx, repo, commitID.String(), catfileCache) require.NoError(t, err) - require.FileExists(t, filepath.Join(repoPath, "language-stats.cache")) + require.FileExists(t, filepath.Join(repoPath, languageStatsFilename)) + + // Make sure it isn't able to generate stats from scratch + require.NoError(t, os.RemoveAll(filepath.Join(repoPath, "objects", "pack"))) - return repoPath, commitID + return repoProto, repoPath, commitID }, expectedStats: map[string]uint64{ "CoffeeScript": 107, @@ -68,12 +142,12 @@ func TestInstance_Stats(t *testing.T) { }, { desc: "corrupted cache", - setup: func(t *testing.T) (string, git.ObjectID) { - _, repoPath := gittest.CloneRepo(t, cfg, cfg.Storages[0]) + setup: func(t *testing.T) (*gitalypb.Repository, string, git.ObjectID) { + repoProto, repoPath := gittest.CloneRepo(t, cfg, cfg.Storages[0]) - require.NoError(t, os.WriteFile(filepath.Join(repoPath, "language-stats.cache"), []byte("garbage"), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(repoPath, languageStatsFilename), []byte("garbage"), 0o644)) - return repoPath, commitID + return repoProto, repoPath, commitID }, expectedStats: map[string]uint64{ "CoffeeScript": 107, @@ -84,8 +158,9 @@ func TestInstance_Stats(t *testing.T) { }, { desc: "old cache", - setup: func(t *testing.T) (string, git.ObjectID) { - _, repoPath := gittest.InitRepo(t, cfg, cfg.Storages[0]) + setup: func(t *testing.T) (*gitalypb.Repository, string, git.ObjectID) { + repoProto, repoPath := gittest.InitRepo(t, cfg, cfg.Storages[0]) + repo := localrepo.NewTestRepo(t, cfg, repoProto) oldCommitID := gittest.WriteCommit(t, cfg, repoPath, gittest.WithParents(), gittest.WithTreeEntries( gittest.TreeEntry{Path: "main.rb", Content: "require 'fileutils'", Mode: "100644"}, @@ -96,14 +171,14 @@ func TestInstance_Stats(t *testing.T) { // Precreate the cache with the old commit. This ensures that // linguist knows to update the cache. - stats, err := linguist.Stats(ctx, repoPath, oldCommitID.String()) + stats, err := linguist.Stats(ctx, repo, oldCommitID.String(), catfileCache) require.NoError(t, err) - require.FileExists(t, filepath.Join(repoPath, "language-stats.cache")) + require.FileExists(t, filepath.Join(repoPath, languageStatsFilename)) require.Equal(t, ByteCountPerLanguage{ "Ruby": 19, }, stats) - return repoPath, newCommitID + return repoProto, repoPath, newCommitID }, expectedStats: map[string]uint64{ "Go": 12, @@ -111,30 +186,34 @@ func TestInstance_Stats(t *testing.T) { }, { desc: "missing repository", - setup: func(t *testing.T) (string, git.ObjectID) { - return filepath.Join(testhelper.TempDir(t), "nonexistent"), commitID + setup: func(t *testing.T) (*gitalypb.Repository, string, git.ObjectID) { + repoPath := filepath.Join(testhelper.TempDir(t), "nonexistent") + repoProto := &gitalypb.Repository{StorageName: cfg.Storages[0].Name, RelativePath: "nonexistent"} + + return repoProto, repoPath, commitID }, - expectedErr: "waiting for linguist: exit status 1", + expectedErr: "GetRepoPath: not a git repository", }, { desc: "missing commit", - setup: func(t *testing.T) (string, git.ObjectID) { - _, repoPath := gittest.InitRepo(t, cfg, cfg.Storages[0]) - return repoPath, commitID + setup: func(t *testing.T) (*gitalypb.Repository, string, git.ObjectID) { + repoProto, repoPath := gittest.InitRepo(t, cfg, cfg.Storages[0]) + return repoProto, repoPath, commitID }, - expectedErr: "waiting for linguist: exit status 1", + expectedErr: "linguist", }, } { t.Run(tc.desc, func(t *testing.T) { - repoPath, objectID := tc.setup(t) + repoProto, repoPath, objectID := tc.setup(t) + repo := localrepo.NewTestRepo(t, cfg, repoProto) - stats, err := linguist.Stats(ctx, repoPath, objectID.String()) + stats, err := linguist.Stats(ctx, repo, objectID.String(), catfileCache) if tc.expectedErr == "" { require.NoError(t, err) require.Equal(t, tc.expectedStats, stats) - require.FileExists(t, filepath.Join(repoPath, "language-stats.cache")) + require.FileExists(t, filepath.Join(repoPath, languageStatsFilename)) } else { - require.EqualError(t, err, tc.expectedErr) + require.Contains(t, err.Error(), tc.expectedErr) } }) } @@ -142,20 +221,64 @@ func TestInstance_Stats(t *testing.T) { func TestInstance_Stats_unmarshalJSONError(t *testing.T) { cfg := testcfg.Build(t) - ctx := testhelper.Context(t) + ctx := featureflag.ContextWithFeatureFlag(testhelper.Context(t), featureflag.GoLanguageStats, false) + gitCmdFactory := gittest.NewCommandFactory(t, cfg) + invalidRepo := &gitalypb.Repository{StorageName: "fake", RelativePath: "path"} - ling, err := New(cfg, gittest.NewCommandFactory(t, cfg)) + catfileCache := catfile.NewCache(cfg) + t.Cleanup(catfileCache.Stop) + + repo := localrepo.New(config.NewLocator(cfg), gitCmdFactory, catfileCache, invalidRepo) + + ling, err := New(cfg, gitCmdFactory) require.NoError(t, err) // When an error occurs, this used to trigger JSON marshelling of a plain string // the new behaviour shouldn't do that, and return an command error - _, err = ling.Stats(ctx, "/var/empty", "deadbeef") + _, err = ling.Stats(ctx, repo, "deadbeef", catfileCache) require.Error(t, err) _, ok := err.(*json.SyntaxError) require.False(t, ok, "expected the error not be a json Syntax Error") } +func TestInstance_Stats_incremental(t *testing.T) { + t.Parallel() + + cfg := testcfg.Build(t) + logger, hook := test.NewNullLogger() + ctx := testhelper.Context(t, testhelper.ContextWithLogger(logrus.NewEntry(logger))) + ctx = featureflag.ContextWithFeatureFlag(ctx, featureflag.GoLanguageStats, true) + + gitCmdFactory := gittest.NewCommandFactory(t, cfg) + + linguist, err := New(cfg, gitCmdFactory) + require.NoError(t, err) + + catfileCache := catfile.NewCache(cfg) + t.Cleanup(catfileCache.Stop) + + repoProto, repoPath := gittest.CloneRepo(t, cfg, cfg.Storages[0]) + repo := localrepo.NewTestRepo(t, cfg, repoProto) + + cleanStats, err := linguist.Stats(ctx, repo, "1e292f8fedd741b75372e19097c76d327140c312", catfileCache) + require.NoError(t, err) + require.Len(t, hook.AllEntries(), 0) + require.NoError(t, os.Remove(filepath.Join(repoPath, languageStatsFilename))) + + _, err = linguist.Stats(ctx, repo, "cfe32cf61b73a0d5e9f13e774abde7ff789b1660", catfileCache) + require.NoError(t, err) + require.Len(t, hook.AllEntries(), 0) + require.FileExists(t, filepath.Join(repoPath, languageStatsFilename)) + + incStats, err := linguist.Stats(ctx, repo, "1e292f8fedd741b75372e19097c76d327140c312", catfileCache) + require.NoError(t, err) + require.Len(t, hook.AllEntries(), 0) + require.FileExists(t, filepath.Join(repoPath, languageStatsFilename)) + + require.Equal(t, cleanStats, incStats) +} + func TestNew(t *testing.T) { cfg := testcfg.Build(t, testcfg.WithRealLinguist()) @@ -176,3 +299,63 @@ func TestNew_loadLanguagesCustomPath(t *testing.T) { require.Equal(t, "foo color", ling.Color("FooBar")) } + +// filenameForCache returns the filename where the cache is stored, depending on +// the feature flag. +func filenameForCache(ctx context.Context) string { + if featureflag.GoLanguageStats.IsDisabled(ctx) { + return "language-stats.cache" + } + return languageStatsFilename +} + +func BenchmarkInstance_Stats(b *testing.B) { + testhelper.NewFeatureSets(featureflag.GoLanguageStats). + Bench(b, benchmarkInstanceStats) +} + +func benchmarkInstanceStats(b *testing.B, ctx context.Context) { + cfg := testcfg.Build(b) + gitCmdFactory := gittest.NewCommandFactory(b, cfg) + languageStatsFilename := filenameForCache(ctx) + + linguist, err := New(cfg, gitCmdFactory) + require.NoError(b, err) + + catfileCache := catfile.NewCache(cfg) + b.Cleanup(catfileCache.Stop) + + repoProto, repoPath := gittest.CloneRepo(b, cfg, cfg.Storages[0], gittest.CloneRepoOpts{ + SourceRepo: "benchmark.git", + }) + repo := localrepo.NewTestRepo(b, cfg, repoProto) + + var scratchStat ByteCountPerLanguage + var incStats ByteCountPerLanguage + + b.Run("from scratch", func(b *testing.B) { + for i := 0; i < b.N; i++ { + b.StopTimer() + require.NoError(b, os.RemoveAll(filepath.Join(repoPath, languageStatsFilename))) + b.StartTimer() + + scratchStat, err = linguist.Stats(ctx, repo, "f5dfdd0057cd6bffc6259a5c8533dde5bf6a9d37", catfileCache) + require.NoError(b, err) + } + }) + + b.Run("incremental", func(b *testing.B) { + for i := 0; i < b.N; i++ { + b.StopTimer() + require.NoError(b, os.RemoveAll(filepath.Join(repoPath, languageStatsFilename))) + // a commit about 3 months older than the next + _, err = linguist.Stats(ctx, repo, "3c813b292d25a9b2ffda70e7f609f623bfc0cb37", catfileCache) + b.StartTimer() + + incStats, err = linguist.Stats(ctx, repo, "f5dfdd0057cd6bffc6259a5c8533dde5bf6a9d37", catfileCache) + require.NoError(b, err) + } + }) + + require.Equal(b, scratchStat, incStats) +} diff --git a/internal/gitaly/service/commit/languages.go b/internal/gitaly/service/commit/languages.go index 9577d4864..4363011c0 100644 --- a/internal/gitaly/service/commit/languages.go +++ b/internal/gitaly/service/commit/languages.go @@ -38,11 +38,7 @@ func (s *server) CommitLanguages(ctx context.Context, req *gitalypb.CommitLangua return nil, helper.ErrInternalf("looking up revision: %w", err) } - repoPath, err := repo.Path() - if err != nil { - return nil, helper.ErrInternalf("repository path: %w", err) - } - stats, err := s.linguist.Stats(ctx, repoPath, commitID) + stats, err := s.linguist.Stats(ctx, repo, commitID, s.catfileCache) if err != nil { return nil, helper.ErrInternalf("language stats: %w", err) } diff --git a/internal/gitaly/service/commit/languages_test.go b/internal/gitaly/service/commit/languages_test.go index 8f4790c89..731f950cd 100644 --- a/internal/gitaly/service/commit/languages_test.go +++ b/internal/gitaly/service/commit/languages_test.go @@ -1,10 +1,12 @@ package commit import ( + "context" "testing" "github.com/stretchr/testify/require" "gitlab.com/gitlab-org/gitaly/v15/internal/git/gittest" + "gitlab.com/gitlab-org/gitaly/v15/internal/metadata/featureflag" "gitlab.com/gitlab-org/gitaly/v15/internal/testhelper" "gitlab.com/gitlab-org/gitaly/v15/internal/testhelper/testcfg" "gitlab.com/gitlab-org/gitaly/v15/proto/go/gitalypb" @@ -12,12 +14,16 @@ import ( ) func TestLanguages(t *testing.T) { + testhelper.NewFeatureSets(featureflag.GoLanguageStats). + Run(t, testLanguagesFeatured) +} + +func testLanguagesFeatured(t *testing.T, ctx context.Context) { t.Parallel() cfg := testcfg.Build(t, testcfg.WithRealLinguist()) cfg.SocketPath = startTestServices(t, cfg) - ctx := testhelper.Context(t) repo, _ := gittest.CreateRepository(ctx, t, cfg, gittest.CreateRepositoryConfig{ Seed: gittest.SeedGitLabTest, }) @@ -32,30 +38,25 @@ func TestLanguages(t *testing.T) { resp, err := client.CommitLanguages(ctx, request) require.NoError(t, err) - require.NotZero(t, len(resp.Languages), "number of languages in response") - expectedLanguages := []*gitalypb.CommitLanguagesResponse_Language{ - {Name: "Ruby", Share: 66, Color: "#701516", FileCount: 4, Bytes: 2943}, - {Name: "JavaScript", Share: 22, Color: "#f1e05a", FileCount: 1, Bytes: 1014}, - {Name: "HTML", Share: 7, Color: "#e34c26", FileCount: 1, Bytes: 349}, - {Name: "CoffeeScript", Share: 2, Color: "#244776", FileCount: 1, Bytes: 107}, - // Modula-2 is a special case because Linguist has no color for it. This - // test case asserts that we invent a color for it (SHA256 of the name). - {Name: "Modula-2", Share: 2, Color: "#3fd5e0", FileCount: 1, Bytes: 95}, + {Name: "Ruby", Share: 65.28394, Color: "#701516", Bytes: 2943}, + {Name: "JavaScript", Share: 22.493345, Color: "#f1e05a", Bytes: 1014}, + {Name: "HTML", Share: 7.741792, Color: "#e34c26", Bytes: 349}, + {Name: "CoffeeScript", Share: 2.373558, Color: "#244776", Bytes: 107}, + {Name: "Modula-2", Share: 2.1073646, Color: "#10253f", Bytes: 95}, } - require.Equal(t, len(expectedLanguages), len(resp.Languages)) - - for i, el := range expectedLanguages { - actualLanguage := resp.Languages[i] - requireLanguageEqual(t, el, actualLanguage) - } + testhelper.ProtoEqual(t, expectedLanguages, resp.Languages) } func TestFileCountIsZeroWhenFeatureIsDisabled(t *testing.T) { + testhelper.NewFeatureSets(featureflag.GoLanguageStats). + Run(t, testFileCountIsZeroWhenFeatureIsDisabled) +} + +func testFileCountIsZeroWhenFeatureIsDisabled(t *testing.T, ctx context.Context) { t.Parallel() - ctx := testhelper.Context(t) _, repo, _, client := setupCommitServiceWithRepo(ctx, t) request := &gitalypb.CommitLanguagesRequest{ @@ -74,19 +75,14 @@ func TestFileCountIsZeroWhenFeatureIsDisabled(t *testing.T) { } } -func requireLanguageEqual(t *testing.T, expected, actual *gitalypb.CommitLanguagesResponse_Language) { - t.Helper() - - require.Equal(t, expected.Name, actual.Name) - require.Equal(t, expected.Color, actual.Color) - require.False(t, (expected.Share-actual.Share)*(expected.Share-actual.Share) >= 1.0, "shares do not match") - require.Equal(t, expected.Bytes, actual.Bytes) +func TestLanguagesEmptyRevision(t *testing.T) { + testhelper.NewFeatureSets(featureflag.GoLanguageStats). + Run(t, testLanguagesEmptyRevisionFeatured) } -func TestLanguagesEmptyRevision(t *testing.T) { +func testLanguagesEmptyRevisionFeatured(t *testing.T, ctx context.Context) { t.Parallel() - ctx := testhelper.Context(t) _, repo, _, client := setupCommitServiceWithRepo(ctx, t) request := &gitalypb.CommitLanguagesRequest{ @@ -107,9 +103,13 @@ func TestLanguagesEmptyRevision(t *testing.T) { } func TestInvalidCommitLanguagesRequestRevision(t *testing.T) { + testhelper.NewFeatureSets(featureflag.GoLanguageStats). + Run(t, testInvalidCommitLanguagesRequestRevisionFeatured) +} + +func testInvalidCommitLanguagesRequestRevisionFeatured(t *testing.T, ctx context.Context) { t.Parallel() - ctx := testhelper.Context(t) _, repo, _, client := setupCommitServiceWithRepo(ctx, t) _, err := client.CommitLanguages(ctx, &gitalypb.CommitLanguagesRequest{ @@ -120,9 +120,13 @@ func TestInvalidCommitLanguagesRequestRevision(t *testing.T) { } func TestAmbiguousRefCommitLanguagesRequestRevision(t *testing.T) { + testhelper.NewFeatureSets(featureflag.GoLanguageStats). + Run(t, testAmbiguousRefCommitLanguagesRequestRevisionFeatured) +} + +func testAmbiguousRefCommitLanguagesRequestRevisionFeatured(t *testing.T, ctx context.Context) { t.Parallel() - ctx := testhelper.Context(t) _, repo, _, client := setupCommitServiceWithRepo(ctx, t) // gitlab-test repo has both a branch and a tag named 'v1.1.0' diff --git a/internal/metadata/featureflag/ff_go_language_stats.go b/internal/metadata/featureflag/ff_go_language_stats.go new file mode 100644 index 000000000..cf4626a06 --- /dev/null +++ b/internal/metadata/featureflag/ff_go_language_stats.go @@ -0,0 +1,10 @@ +package featureflag + +// GoLanguageStats flag enables getting CommitLanguages statistics written in +// Go. +var GoLanguageStats = NewFeatureFlag( + "go_language_stats", + "v15.2.0", + "https://gitlab.com/gitlab-org/gitaly/-/issues/4254", + false, +) diff --git a/proto/commit.proto b/proto/commit.proto index 121daaa56..36143dd28 100644 --- a/proto/commit.proto +++ b/proto/commit.proto @@ -99,7 +99,8 @@ service CommitService { }; } - // This comment is left unintentionally blank. + // CommitLanguages detects the source code languages of the whole tree for a + // given commit. Returns an error in case no languages could be detected. rpc CommitLanguages(CommitLanguagesRequest) returns (CommitLanguagesResponse) { option (op_type) = { op: ACCESSOR @@ -611,31 +612,35 @@ message FindCommitsResponse { repeated GitCommit commits = 1; } -// This comment is left unintentionally blank. +// CommitLanguagesRequest requests to detect the source code languages. message CommitLanguagesRequest { - // This comment is left unintentionally blank. + // Repository is the repository where to detect the languages in. Repository repository = 1 [(target_repository)=true]; - // This comment is left unintentionally blank. + // Revision tells for which commit the languages should be detected. If it's + // omitted, the HEAD commit of the default branch is used. bytes revision = 2; } -// This comment is left unintentionally blank. +// CommitLanguagesResponse returns the language statistics. message CommitLanguagesResponse { - // This comment is left unintentionally blank. + // Language specifies the statistics for one language. message Language { - // This comment is left unintentionally blank. + // Name is the name of the detected language, for example: Ruby, Go, HTML + // A full list of language names can be found at: + // https://github.com/github/linguist/blob/master/lib/linguist/languages.yml string name = 1; - // This comment is left unintentionally blank. + // Share is the percentual share (value between 0 and 100) of this language + // in relation to other languages that exist in the given revision. float share = 2; - // This comment is left unintentionally blank. + // Color specifies the associated color for this language, for example #3fd5e0. string color = 3; - // This comment is left unintentionally blank. + // FileCount tells how many files with this language are found. uint32 file_count = 4; - // This comment is left unintentionally blank. + // Bytes is the total amount of bytes written in this language uint64 bytes = 5; } - // This comment is left unintentionally blank. + // Languages is a set of all the detected languages and their statistics. repeated Language languages = 1; } diff --git a/proto/go/gitalypb/commit.pb.go b/proto/go/gitalypb/commit.pb.go index 0062cae67..349e7e0c0 100644 --- a/proto/go/gitalypb/commit.pb.go +++ b/proto/go/gitalypb/commit.pb.go @@ -2453,15 +2453,16 @@ func (x *FindCommitsResponse) GetCommits() []*GitCommit { return nil } -// This comment is left unintentionally blank. +// CommitLanguagesRequest requests to detect the source code languages. type CommitLanguagesRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields - // This comment is left unintentionally blank. + // Repository is the repository where to detect the languages in. Repository *Repository `protobuf:"bytes,1,opt,name=repository,proto3" json:"repository,omitempty"` - // This comment is left unintentionally blank. + // Revision tells for which commit the languages should be detected. If it's + // omitted, the HEAD commit of the default branch is used. Revision []byte `protobuf:"bytes,2,opt,name=revision,proto3" json:"revision,omitempty"` } @@ -2511,13 +2512,13 @@ func (x *CommitLanguagesRequest) GetRevision() []byte { return nil } -// This comment is left unintentionally blank. +// CommitLanguagesResponse returns the language statistics. type CommitLanguagesResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields - // This comment is left unintentionally blank. + // Languages is a set of all the detected languages and their statistics. Languages []*CommitLanguagesResponse_Language `protobuf:"bytes,1,rep,name=languages,proto3" json:"languages,omitempty"` } @@ -3763,21 +3764,24 @@ func (x *ListCommitsByRefNameResponse_CommitForRef) GetRefName() []byte { return nil } -// This comment is left unintentionally blank. +// Language specifies the statistics for one language. type CommitLanguagesResponse_Language struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields - // This comment is left unintentionally blank. + // Name is the name of the detected language, for example: Ruby, Go, HTML + // A full list of language names can be found at: + // https://github.com/github/linguist/blob/master/lib/linguist/languages.yml Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - // This comment is left unintentionally blank. + // Share is the percentual share (value between 0 and 100) of this language + // in relation to other languages that exist in the given revision. Share float32 `protobuf:"fixed32,2,opt,name=share,proto3" json:"share,omitempty"` - // This comment is left unintentionally blank. + // Color specifies the associated color for this language, for example #3fd5e0. Color string `protobuf:"bytes,3,opt,name=color,proto3" json:"color,omitempty"` - // This comment is left unintentionally blank. + // FileCount tells how many files with this language are found. FileCount uint32 `protobuf:"varint,4,opt,name=file_count,json=fileCount,proto3" json:"file_count,omitempty"` - // This comment is left unintentionally blank. + // Bytes is the total amount of bytes written in this language Bytes uint64 `protobuf:"varint,5,opt,name=bytes,proto3" json:"bytes,omitempty"` } diff --git a/proto/go/gitalypb/commit_grpc.pb.go b/proto/go/gitalypb/commit_grpc.pb.go index 4a32b22c5..4fb2773d2 100644 --- a/proto/go/gitalypb/commit_grpc.pb.go +++ b/proto/go/gitalypb/commit_grpc.pb.go @@ -49,7 +49,8 @@ type CommitServiceClient interface { FindAllCommits(ctx context.Context, in *FindAllCommitsRequest, opts ...grpc.CallOption) (CommitService_FindAllCommitsClient, error) // This comment is left unintentionally blank. FindCommits(ctx context.Context, in *FindCommitsRequest, opts ...grpc.CallOption) (CommitService_FindCommitsClient, error) - // This comment is left unintentionally blank. + // CommitLanguages detects the source code languages of the whole tree for a + // given commit. Returns an error in case no languages could be detected. CommitLanguages(ctx context.Context, in *CommitLanguagesRequest, opts ...grpc.CallOption) (*CommitLanguagesResponse, error) // This comment is left unintentionally blank. RawBlame(ctx context.Context, in *RawBlameRequest, opts ...grpc.CallOption) (CommitService_RawBlameClient, error) @@ -688,7 +689,8 @@ type CommitServiceServer interface { FindAllCommits(*FindAllCommitsRequest, CommitService_FindAllCommitsServer) error // This comment is left unintentionally blank. FindCommits(*FindCommitsRequest, CommitService_FindCommitsServer) error - // This comment is left unintentionally blank. + // CommitLanguages detects the source code languages of the whole tree for a + // given commit. Returns an error in case no languages could be detected. CommitLanguages(context.Context, *CommitLanguagesRequest) (*CommitLanguagesResponse, error) // This comment is left unintentionally blank. RawBlame(*RawBlameRequest, CommitService_RawBlameServer) error diff --git a/ruby/Gemfile b/ruby/Gemfile index 7037e215f..cbb9321fd 100644 --- a/ruby/Gemfile +++ b/ruby/Gemfile @@ -1,7 +1,7 @@ source 'https://rubygems.org' gem 'rugged', '~> 1.2' -gem 'github-linguist', '~> 7.12', require: 'linguist' +gem 'github-linguist', '~> 7.20.0', require: 'linguist' gem 'gitlab-markup', '~> 1.7.1' gem 'activesupport', '~> 6.1.4.7' gem 'rdoc', '~> 6.0' diff --git a/ruby/Gemfile.lock b/ruby/Gemfile.lock index f8688dbb5..65faf2b72 100644 --- a/ruby/Gemfile.lock +++ b/ruby/Gemfile.lock @@ -40,7 +40,7 @@ GEM dotenv (2.7.6) equalizer (0.0.11) erubi (1.10.0) - escape_utils (1.2.1) + escape_utils (1.2.2) factory_bot (5.0.2) activesupport (>= 4.2.0) faraday (1.0.1) @@ -48,11 +48,11 @@ GEM ffi (1.15.3) gemojione (3.3.0) json - github-linguist (7.12.1) + github-linguist (7.20.0) charlock_holmes (~> 0.7.7) escape_utils (~> 1.2.0) mini_mime (~> 1.0) - rugged (>= 0.25.1) + rugged (~> 1.0) github-markup (1.7.0) gitlab-gollum-lib (4.2.7.10.gitlab.2) gemojione (~> 3.2) @@ -110,7 +110,7 @@ GEM mime-types (3.3.1) mime-types-data (~> 3.2015) mime-types-data (3.2020.1104) - mini_mime (1.0.2) + mini_mime (1.1.2) mini_portile2 (2.8.0) minitest (5.15.0) msgpack (1.3.3) @@ -228,7 +228,7 @@ DEPENDENCIES activesupport (~> 6.1.4.7) factory_bot faraday (~> 1.0) - github-linguist (~> 7.12) + github-linguist (~> 7.20.0) gitlab-gollum-lib (~> 4.2.7.10.gitlab.2) gitlab-gollum-rugged_adapter (~> 0.4.4.4.gitlab.1) gitlab-labkit (~> 0.23) diff --git a/ruby/proto/gitaly/commit_services_pb.rb b/ruby/proto/gitaly/commit_services_pb.rb index 17df1b4b8..c99e663fb 100644 --- a/ruby/proto/gitaly/commit_services_pb.rb +++ b/ruby/proto/gitaly/commit_services_pb.rb @@ -43,7 +43,8 @@ module Gitaly rpc :FindAllCommits, ::Gitaly::FindAllCommitsRequest, stream(::Gitaly::FindAllCommitsResponse) # This comment is left unintentionally blank. rpc :FindCommits, ::Gitaly::FindCommitsRequest, stream(::Gitaly::FindCommitsResponse) - # This comment is left unintentionally blank. + # CommitLanguages detects the source code languages of the whole tree for a + # given commit. Returns an error in case no languages could be detected. rpc :CommitLanguages, ::Gitaly::CommitLanguagesRequest, ::Gitaly::CommitLanguagesResponse # This comment is left unintentionally blank. rpc :RawBlame, ::Gitaly::RawBlameRequest, stream(::Gitaly::RawBlameResponse) |