fork of https://github.com/sourcegraph/zoekt
1// Copyright 2016 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15// Package gitindex provides functions for indexing Git repositories.
16package gitindex
17
18import (
19 "bytes"
20 "cmp"
21 "context"
22 "errors"
23 "fmt"
24 "io"
25 "log"
26 "math"
27 "net/url"
28 "os"
29 "path/filepath"
30 "regexp"
31 "sort"
32 "strconv"
33 "strings"
34
35 "github.com/go-git/go-billy/v5/osfs"
36 "github.com/go-git/go-git/v5/config"
37 "github.com/go-git/go-git/v5/plumbing"
38 "github.com/go-git/go-git/v5/plumbing/cache"
39 "github.com/go-git/go-git/v5/plumbing/object"
40 "github.com/go-git/go-git/v5/storage/filesystem"
41
42 "github.com/sourcegraph/zoekt"
43 "github.com/sourcegraph/zoekt/ignore"
44 "github.com/sourcegraph/zoekt/index"
45
46 git "github.com/go-git/go-git/v5"
47)
48
49// FindGitRepos finds directories holding git repositories below the
50// given directory. It will find both bare and the ".git" dirs in
51// non-bare repositories. It returns the full path including the dir
52// passed in.
53func FindGitRepos(dir string) ([]string, error) {
54 arg, err := filepath.Abs(dir)
55 if err != nil {
56 return nil, err
57 }
58 var dirs []string
59 if err := filepath.Walk(arg, func(name string, fi os.FileInfo, err error) error {
60 // Best-effort, ignore filepath.Walk failing
61 if err != nil {
62 return nil
63 }
64
65 if fi, err := os.Lstat(filepath.Join(name, ".git")); err == nil && fi.IsDir() {
66 dirs = append(dirs, filepath.Join(name, ".git"))
67 return filepath.SkipDir
68 }
69
70 if !strings.HasSuffix(name, ".git") || !fi.IsDir() {
71 return nil
72 }
73
74 fi, err = os.Lstat(filepath.Join(name, "objects"))
75 if err != nil || !fi.IsDir() {
76 return nil
77 }
78
79 dirs = append(dirs, name)
80 return filepath.SkipDir
81 }); err != nil {
82 return nil, err
83 }
84
85 return dirs, nil
86}
87
88// setTemplates fills in URL templates for known git hosting
89// sites.
90func setTemplates(repo *zoekt.Repository, u *url.URL, typ string) error {
91 if u.Scheme == "ssh+git" {
92 u.Scheme = "https"
93 u.User = nil
94 }
95
96 // helper to generate u.JoinPath as a template
97 varVersion := ".Version"
98 varPath := ".Path"
99 urlJoinPath := func(elem ...string) string {
100 elem = append([]string{u.String()}, elem...)
101 var parts []string
102 for _, e := range elem {
103 if e == varVersion || e == varPath {
104 parts = append(parts, e)
105 } else {
106 parts = append(parts, strconv.Quote(e))
107 }
108 }
109 return fmt.Sprintf("{{URLJoinPath %s}}", strings.Join(parts, " "))
110 }
111
112 repo.URL = u.String()
113 switch typ {
114 case "gitiles":
115 // eg. https://gerrit.googlesource.com/gitiles/+/master/tools/run_dev.sh#20
116 repo.CommitURLTemplate = urlJoinPath("+", varVersion)
117 repo.FileURLTemplate = urlJoinPath("+", varVersion, varPath)
118 repo.LineFragmentTemplate = "#{{.LineNumber}}"
119 case "github":
120 // eg. https://github.com/hanwen/go-fuse/blob/notify/genversion.sh#L10
121 repo.CommitURLTemplate = urlJoinPath("commit", varVersion)
122 repo.FileURLTemplate = urlJoinPath("blob", varVersion, varPath)
123 repo.LineFragmentTemplate = "#L{{.LineNumber}}"
124 case "cgit":
125 // http://git.savannah.gnu.org/cgit/lilypond.git/tree/elisp/lilypond-mode.el?h=dev/philh&id=b2ca0fefe3018477aaca23b6f672c7199ba5238e#n100
126 repo.CommitURLTemplate = urlJoinPath("commit") + "/?id={{.Version}}"
127 repo.FileURLTemplate = urlJoinPath("tree", varPath) + "/?id={{.Version}}"
128 repo.LineFragmentTemplate = "#n{{.LineNumber}}"
129 case "gitweb":
130 // https://gerrit.libreoffice.org/gitweb?p=online.git;a=blob;f=Makefile.am;h=cfcfd7c36fbae10e269653dc57a9b68c92d4c10b;hb=848145503bf7b98ce4a4aa0a858a0d71dd0dbb26#l10
131 repo.FileURLTemplate = u.String() + ";a=blob;f={{.Path}};hb={{.Version}}"
132 repo.CommitURLTemplate = u.String() + ";a=commit;h={{.Version}}"
133 repo.LineFragmentTemplate = "#l{{.LineNumber}}"
134 case "source.bazel.build":
135 // https://source.bazel.build/bazel/+/57bc201346e61c62a921c1cbf32ad24f185c10c9
136 // https://source.bazel.build/bazel/+/57bc201346e61c62a921c1cbf32ad24f185c10c9:tools/cpp/BUILD.empty;l=10
137 repo.CommitURLTemplate = u.String() + "/%2B/{{.Version}}"
138 repo.FileURLTemplate = u.String() + "/%2B/{{.Version}}:{{.Path}}"
139 repo.LineFragmentTemplate = ";l={{.LineNumber}}"
140 case "bitbucket-server":
141 // https://<bitbucketserver-host>/projects/<project>/repos/<repo>/commits/5be7ca73b898bf17a08e607918accfdeafe1e0bc
142 // https://<bitbucketserver-host>/projects/<project>/repos/<repo>/browse/<file>?at=5be7ca73b898bf17a08e607918accfdeafe1e0bc
143 repo.CommitURLTemplate = urlJoinPath("commits", varVersion)
144 repo.FileURLTemplate = urlJoinPath(varPath) + "?at={{.Version}}"
145 repo.LineFragmentTemplate = "#{{.LineNumber}}"
146 case "gitlab":
147 // https://gitlab.com/gitlab-org/omnibus-gitlab/-/commit/b152c864303dae0e55377a1e2c53c9592380ffed
148 // https://gitlab.com/gitlab-org/omnibus-gitlab/-/blob/aad04155b3f6fc50ede88aedaee7fc624d481149/files/gitlab-config-template/gitlab.rb.template
149 repo.CommitURLTemplate = urlJoinPath("-/commit", varVersion)
150 repo.FileURLTemplate = urlJoinPath("-/blob", varVersion, varPath)
151 repo.LineFragmentTemplate = "#L{{.LineNumber}}"
152 case "gitea":
153 repo.CommitURLTemplate = urlJoinPath("commit", varVersion)
154 // NOTE The `display=source` query parameter is required to disable file rendering.
155 // Since line numbers are disabled in rendered files, you wouldn't be able to jump to
156 // a line without `display=source`. This is supported since gitea 1.17.0.
157 // When /src/{{.Version}} is used it will redirect to /src/commit/{{.Version}},
158 // but the query parameters are obmitted.
159 repo.FileURLTemplate = urlJoinPath("src/commit", varVersion, varPath) + "?display=source"
160 repo.LineFragmentTemplate = "#L{{.LineNumber}}"
161 default:
162 return fmt.Errorf("URL scheme type %q unknown", typ)
163 }
164 return nil
165}
166
167// getCommit returns a tree object for the given reference.
168func getCommit(repo *git.Repository, prefix, ref string) (*object.Commit, error) {
169 sha1, err := repo.ResolveRevision(plumbing.Revision(ref))
170 // ref might be a branch name (e.g. "master") add branch prefix and try again.
171 if err != nil {
172 sha1, err = repo.ResolveRevision(plumbing.Revision(filepath.Join(prefix, ref)))
173 }
174 if err != nil {
175 return nil, err
176 }
177
178 commitObj, err := repo.CommitObject(*sha1)
179 if err != nil {
180 return nil, err
181 }
182 return commitObj, nil
183}
184
185func plainOpenRepo(repoDir string) (*git.Repository, error) {
186 // Try repoDir as the repository root first so bare repositories open
187 // correctly. If repoDir itself is not a repository, fall back to searching
188 // for a .git entry to preserve compatibility with worktree paths.
189 repo, err := git.PlainOpenWithOptions(repoDir, &git.PlainOpenOptions{
190 EnableDotGitCommonDir: true,
191 })
192 if err == nil || !errors.Is(err, git.ErrRepositoryNotExists) {
193 return repo, err
194 }
195
196 return git.PlainOpenWithOptions(repoDir, &git.PlainOpenOptions{
197 DetectDotGit: true,
198 EnableDotGitCommonDir: true,
199 })
200}
201
202func configLookupRemoteURL(cfg *config.Config, key string) string {
203 rc := cfg.Remotes[key]
204 if rc == nil || len(rc.URLs) == 0 {
205 return ""
206 }
207 return rc.URLs[0]
208}
209
210var sshRelativeURLRegexp = regexp.MustCompile(`^([^@]+)@([^:]+):(.*)$`)
211
212func setTemplatesFromConfig(desc *zoekt.Repository, repoDir string) error {
213 repo, err := plainOpenRepo(repoDir)
214 if err != nil {
215 return err
216 }
217
218 cfg, err := repo.Config()
219 if err != nil {
220 return err
221 }
222
223 return setTemplatesFromRepoConfig(desc, cfg)
224}
225
226func setTemplatesFromRepo(desc *zoekt.Repository, repo *git.Repository, repoDir string) error {
227 cfg, err := repo.Config()
228 if err == nil {
229 return setTemplatesFromRepoConfig(desc, cfg)
230 }
231
232 return setTemplatesFromConfig(desc, repoDir)
233}
234
235func setTemplatesFromRepoConfig(desc *zoekt.Repository, cfg *config.Config) error {
236 sec := cfg.Raw.Section("zoekt")
237
238 webURLStr := sec.Options.Get("web-url")
239 webURLType := sec.Options.Get("web-url-type")
240
241 if webURLType != "" && webURLStr != "" {
242 webURL, err := url.Parse(webURLStr)
243 if err != nil {
244 return err
245 }
246 if err := setTemplates(desc, webURL, webURLType); err != nil {
247 return err
248 }
249 } else if webURLStr != "" {
250 desc.URL = webURLStr
251 }
252
253 name := sec.Options.Get("name")
254 if name != "" {
255 desc.Name = name
256 } else {
257 remoteURL := configLookupRemoteURL(cfg, "origin")
258 if remoteURL == "" {
259 return nil
260 }
261 if sm := sshRelativeURLRegexp.FindStringSubmatch(remoteURL); sm != nil {
262 user := sm[1]
263 host := sm[2]
264 path := sm[3]
265
266 remoteURL = fmt.Sprintf("ssh+git://%s@%s/%s", user, host, path)
267 }
268
269 u, err := url.Parse(remoteURL)
270 if err != nil {
271 return err
272 }
273 if err := SetTemplatesFromOrigin(desc, u); err != nil {
274 return err
275 }
276 }
277
278 id, _ := strconv.ParseUint(sec.Options.Get("repoid"), 10, 32)
279 desc.ID = uint32(id)
280
281 desc.TenantID, _ = strconv.Atoi(sec.Options.Get("tenantID"))
282
283 if desc.RawConfig == nil {
284 desc.RawConfig = map[string]string{}
285 }
286 for _, o := range sec.Options {
287 desc.RawConfig[o.Key] = o.Value
288 }
289
290 // Ranking info.
291
292 // Github:
293 traction := 0
294 for _, s := range []string{"github-stars", "github-forks", "github-watchers", "github-subscribers"} {
295 f, err := strconv.Atoi(sec.Options.Get(s))
296 if err == nil {
297 traction += f
298 }
299 }
300
301 if strings.Contains(desc.Name, "googlesource.com/") && traction == 0 {
302 // Pretend everything on googlesource.com has 1000
303 // github stars.
304 traction = 1000
305 }
306
307 if traction > 0 {
308 l := math.Log(float64(traction))
309 desc.Rank = uint16((1.0 - 1.0/math.Pow(1+l, 0.6)) * 10000)
310 }
311
312 return nil
313}
314
315// This attempts to get a repo URL similar to the main repository template processing as in setTemplatesFromConfig()
316func normalizeSubmoduleRemoteURL(cfg *config.Config) (string, error) {
317 sec := cfg.Raw.Section("zoekt")
318 remoteURL := sec.Options.Get("web-url")
319 if remoteURL == "" {
320 // fall back to "origin" remote
321 remoteURL = configLookupRemoteURL(cfg, "origin")
322 if remoteURL == "" {
323 return "", nil
324 }
325 }
326
327 if sm := sshRelativeURLRegexp.FindStringSubmatch(remoteURL); sm != nil {
328 user := sm[1]
329 host := sm[2]
330 path := sm[3]
331
332 remoteURL = fmt.Sprintf("ssh+git://%s@%s/%s", user, host, path)
333 }
334
335 u, err := url.Parse(remoteURL)
336 if err != nil {
337 return "", fmt.Errorf("unable to parse remote URL %q: %w", remoteURL, err)
338 }
339
340 if u.Scheme == "ssh+git" {
341 u.Scheme = "https"
342 u.User = nil
343 }
344
345 // Assume we cannot build templates for this URL, leave it empty
346 if u.Scheme == "" {
347 return "", nil
348 }
349
350 return u.String(), nil
351}
352
353// SetTemplatesFromOrigin fills in templates based on the origin URL.
354func SetTemplatesFromOrigin(desc *zoekt.Repository, u *url.URL) error {
355 desc.Name = filepath.Join(u.Host, strings.TrimSuffix(u.Path, ".git"))
356
357 if strings.HasSuffix(u.Host, ".googlesource.com") {
358 return setTemplates(desc, u, "gitiles")
359 } else if u.Host == "github.com" {
360 u.Path = strings.TrimSuffix(u.Path, ".git")
361 return setTemplates(desc, u, "github")
362 } else {
363 return fmt.Errorf("unknown git hosting site %q", u)
364 }
365}
366
367// The Options structs controls details of the indexing process.
368type Options struct {
369 // The repository to be indexed.
370 RepoDir string
371
372 // If set, follow submodule links. This requires RepoCacheDir to be set.
373 Submodules bool
374
375 // If set, skip indexing if the existing index shard is newer
376 // than the refs in the repository.
377 Incremental bool
378
379 // Don't error out if some branch is missing
380 AllowMissingBranch bool
381
382 // Specifies the root of a Repository cache. Needed for submodule indexing.
383 RepoCacheDir string
384
385 // Indexing options.
386 BuildOptions index.Options
387
388 // Prefix of the branch to index, e.g. `remotes/origin`.
389 BranchPrefix string
390
391 // List of branch names to index, e.g. []string{"HEAD", "stable"}
392 Branches []string
393
394 // DeltaShardNumberFallbackThreshold defines an upper limit (inclusive) on the number of preexisting shards
395 // that can exist before attempting another delta build. If the number of preexisting shards exceeds this threshold,
396 // then a normal build will be performed instead.
397 //
398 // If DeltaShardNumberFallbackThreshold is 0, then this fallback behavior is disabled:
399 // a delta build will always be performed regardless of the number of preexisting shards.
400 DeltaShardNumberFallbackThreshold uint64
401}
402
403func expandBranches(repo *git.Repository, bs []string, prefix string) ([]string, error) {
404 var result []string
405 for _, b := range bs {
406 // Sourcegraph: We disable resolving refs. We want to return the exact ref
407 // requested so we can match it up.
408 if b == "HEAD" && false {
409 ref, err := repo.Head()
410 if err != nil {
411 return nil, err
412 }
413
414 result = append(result, strings.TrimPrefix(ref.Name().String(), prefix))
415 continue
416 }
417
418 if strings.Contains(b, "*") {
419 iter, err := repo.Branches()
420 if err != nil {
421 return nil, err
422 }
423
424 defer iter.Close()
425 for {
426 ref, err := iter.Next()
427 if err == io.EOF {
428 break
429 }
430 if err != nil {
431 return nil, err
432 }
433
434 name := ref.Name().Short()
435 if matched, err := filepath.Match(b, name); err != nil {
436 return nil, err
437 } else if !matched {
438 continue
439 }
440
441 result = append(result, strings.TrimPrefix(name, prefix))
442 }
443 continue
444 }
445
446 result = append(result, b)
447 }
448
449 return result, nil
450}
451
452// IndexGitRepo indexes the git repository as specified by the options.
453// The returned bool indicates whether the index was updated as a result. This
454// can be informative if doing incremental indexing.
455func IndexGitRepo(opts Options) (bool, error) {
456 return indexGitRepo(opts, gitIndexConfig{})
457}
458
459// indexGitRepo indexes the git repository as specified by the options and the provided gitIndexConfig.
460// The returned bool indicates whether the index was updated as a result. This
461// can be informative if doing incremental indexing.
462func indexGitRepo(opts Options, config gitIndexConfig) (bool, error) {
463 prepareDeltaBuild := prepareDeltaBuild
464 if config.prepareDeltaBuild != nil {
465 prepareDeltaBuild = config.prepareDeltaBuild
466 }
467
468 prepareNormalBuild := prepareNormalBuild
469 if config.prepareNormalBuild != nil {
470 prepareNormalBuild = config.prepareNormalBuild
471 }
472
473 // Set max thresholds, since we use them in this function.
474 opts.BuildOptions.SetDefaults()
475 if opts.RepoDir == "" {
476 return false, fmt.Errorf("gitindex: must set RepoDir")
477 }
478
479 opts.BuildOptions.RepositoryDescription.Source = opts.RepoDir
480
481 var repo *git.Repository
482 legacyRepoOpen := cmp.Or(os.Getenv("ZOEKT_DISABLE_GOGIT_OPTIMIZATION"), "false")
483 if b, err := strconv.ParseBool(legacyRepoOpen); b || err != nil {
484 repo, err = plainOpenRepo(opts.RepoDir)
485 if err != nil {
486 return false, fmt.Errorf("plainOpenRepo: %w", err)
487 }
488 } else {
489 var repoCloser io.Closer
490 repo, repoCloser, err = openRepo(opts.RepoDir)
491 if err != nil {
492 return false, fmt.Errorf("openRepo: %w", err)
493 }
494 defer repoCloser.Close()
495 }
496
497 if err := setTemplatesFromRepo(&opts.BuildOptions.RepositoryDescription, repo, opts.RepoDir); err != nil {
498 log.Printf("setTemplatesFromRepo(%s): %s", opts.RepoDir, err)
499 }
500
501 branches, err := expandBranches(repo, opts.Branches, opts.BranchPrefix)
502 if err != nil {
503 return false, fmt.Errorf("expandBranches: %w", err)
504 }
505 for _, b := range branches {
506 commit, err := getCommit(repo, opts.BranchPrefix, b)
507 if err != nil {
508 if opts.AllowMissingBranch && err.Error() == "reference not found" {
509 continue
510 }
511
512 return false, fmt.Errorf("getCommit(%q, %q): %w", opts.BranchPrefix, b, err)
513 }
514
515 opts.BuildOptions.RepositoryDescription.Branches = append(opts.BuildOptions.RepositoryDescription.Branches, zoekt.RepositoryBranch{
516 Name: b,
517 Version: commit.Hash.String(),
518 })
519
520 if when := commit.Committer.When; when.After(opts.BuildOptions.RepositoryDescription.LatestCommitDate) {
521 opts.BuildOptions.RepositoryDescription.LatestCommitDate = when
522 }
523 }
524
525 if opts.Incremental && opts.BuildOptions.IncrementalSkipIndexing() {
526 return false, nil
527 }
528
529 // branch => (path, sha1) => repo.
530 var repos map[fileKey]BlobLocation
531
532 // Branch => Repo => SHA1
533 var branchVersions map[string]map[string]plumbing.Hash
534
535 // set of file paths that have been changed or deleted since
536 // the last indexed commit
537 //
538 // These only have an effect on delta builds
539 var changedOrRemovedFiles []string
540
541 if opts.BuildOptions.IsDelta {
542 repos, branchVersions, changedOrRemovedFiles, err = prepareDeltaBuild(opts, repo)
543 if err != nil {
544 log.Printf("delta build: falling back to normal build since delta build failed, repository=%q, err=%s", opts.BuildOptions.RepositoryDescription.Name, err)
545 opts.BuildOptions.IsDelta = false
546 }
547 }
548
549 if !opts.BuildOptions.IsDelta {
550 repos, branchVersions, err = prepareNormalBuild(opts, repo)
551 if err != nil {
552 return false, fmt.Errorf("preparing normal build: %w", err)
553 }
554 }
555
556 reposByPath := map[string]BlobLocation{}
557 for key, info := range repos {
558 reposByPath[key.SubRepoPath] = info
559 }
560
561 opts.BuildOptions.SubRepositories = map[string]*zoekt.Repository{}
562 for path, info := range reposByPath {
563 tpl := opts.BuildOptions.RepositoryDescription
564 if path != "" {
565 tpl = zoekt.Repository{URL: info.URL.String()}
566 if info.URL.String() != "" {
567 if err := SetTemplatesFromOrigin(&tpl, info.URL); err != nil {
568 log.Printf("setTemplatesFromOrigin(%s, %s): %s", path, info.URL, err)
569 }
570 }
571 if tpl.Name == "" {
572 tpl.Name = path
573 }
574 }
575 opts.BuildOptions.SubRepositories[path] = &tpl
576 }
577
578 for _, br := range opts.BuildOptions.RepositoryDescription.Branches {
579 for path, repo := range opts.BuildOptions.SubRepositories {
580 id := branchVersions[br.Name][path]
581 repo.Branches = append(repo.Branches, zoekt.RepositoryBranch{
582 Name: br.Name,
583 Version: id.String(),
584 })
585 }
586 }
587
588 builder, err := index.NewBuilder(opts.BuildOptions)
589 if err != nil {
590 return false, fmt.Errorf("build.NewBuilder: %w", err)
591 }
592
593 // Preparing the build can consume substantial memory, so check usage before starting to index.
594 builder.CheckMemoryUsage()
595
596 // we don't need to check error, since we either already have an error, or
597 // we returning the first call to builder.Finish.
598 defer builder.Finish() // nolint:errcheck
599
600 for _, f := range changedOrRemovedFiles {
601 builder.MarkFileAsChangedOrRemoved(f)
602 }
603
604 var names []string
605 fileKeys := map[string][]fileKey{}
606 totalFiles := 0
607
608 for key := range repos {
609 n := key.FullPath()
610 fileKeys[n] = append(fileKeys[n], key)
611 names = append(names, n)
612 totalFiles++
613 }
614
615 sort.Strings(names)
616 names = uniq(names)
617
618 // Separate main-repo keys from submodule keys, collecting blob SHAs
619 // for the main repo so we can stream them via git cat-file --batch.
620 // ZOEKT_DISABLE_CATFILE_BATCH=true falls back to the go-git path for
621 // all files, useful as a kill switch if the cat-file path causes issues.
622 catfileBatchDisabled := cmp.Or(os.Getenv("ZOEKT_DISABLE_CATFILE_BATCH"), "false")
623 useCatfileBatch := true
624 if disabled, _ := strconv.ParseBool(catfileBatchDisabled); disabled {
625 useCatfileBatch = false
626 log.Printf("cat-file batch disabled via ZOEKT_DISABLE_CATFILE_BATCH, using go-git")
627 }
628
629 mainRepoKeys := make([]fileKey, 0, totalFiles)
630 mainRepoIDs := make([]plumbing.Hash, 0, totalFiles)
631 var submoduleKeys []fileKey
632
633 for _, name := range names {
634 for _, key := range fileKeys[name] {
635 if useCatfileBatch && key.SubRepoPath == "" {
636 mainRepoKeys = append(mainRepoKeys, key)
637 mainRepoIDs = append(mainRepoIDs, key.ID)
638 } else {
639 submoduleKeys = append(submoduleKeys, key)
640 }
641 }
642 }
643
644 log.Printf("attempting to index %d total files (%d via cat-file, %d via go-git)", totalFiles, len(mainRepoIDs), len(submoduleKeys))
645
646 // Stream main-repo blobs via pipelined cat-file --batch --buffer.
647 // Large blobs are skipped without reading content into memory.
648 if len(mainRepoIDs) > 0 {
649 crOpts := catfileReaderOptions{
650 filterSpec: catfileFilterSpec(opts),
651 }
652 cr, err := newCatfileReader(opts.RepoDir, mainRepoIDs, crOpts)
653 if err != nil {
654 return false, fmt.Errorf("newCatfileReader: %w", err)
655 }
656
657 if err := indexCatfileBlobs(cr, mainRepoKeys, repos, opts, builder); err != nil {
658 return false, err
659 }
660 }
661
662 // Index submodule blobs via go-git.
663 for idx, key := range submoduleKeys {
664 doc, err := createDocument(key, repos, opts.BuildOptions)
665 if err != nil {
666 return false, err
667 }
668
669 if err := builder.Add(doc); err != nil {
670 return false, fmt.Errorf("error adding document with name %s: %w", key.FullPath(), err)
671 }
672
673 if idx%10_000 == 0 {
674 builder.CheckMemoryUsage()
675 }
676 }
677
678 return true, builder.Finish()
679}
680
681// indexCatfileBlobs streams main-repo blobs from the catfileReader into the
682// builder. Large blobs are skipped without reading content into memory.
683// keys must correspond 1:1 (in order) with the ids passed to newCatfileReader.
684// The reader is always closed when this function returns.
685func indexCatfileBlobs(cr *catfileReader, keys []fileKey, repos map[fileKey]BlobLocation, opts Options, builder *index.Builder) error {
686 defer cr.Close()
687
688 for idx, key := range keys {
689 size, missing, excluded, err := cr.Next()
690 if err != nil {
691 return fmt.Errorf("cat-file next for %s: %w", key.FullPath(), err)
692 }
693
694 branches := repos[key].Branches
695 var doc index.Document
696
697 if missing {
698 // Unexpected for local repos — may indicate corruption, shallow
699 // clone, or a race with git gc. Log a warning and skip.
700 log.Printf("warning: blob %s missing for %s", key.ID, key.FullPath())
701 doc = skippedDoc(key, branches, index.SkipReasonMissing)
702 } else if excluded {
703 doc = skippedDoc(key, branches, index.SkipReasonTooLarge)
704 } else {
705 keyFullPath := key.FullPath()
706 if size > opts.BuildOptions.SizeMax && !opts.BuildOptions.IgnoreSizeMax(keyFullPath) {
707 // Skip without reading content into memory.
708 doc = skippedDoc(key, branches, index.SkipReasonTooLarge)
709 } else {
710 // Pre-allocate and read the full blob content in one call.
711 // io.ReadFull is preferred over io.LimitedReader here as it
712 // avoids the intermediate allocation and the size is known.
713 content := make([]byte, size)
714 if _, err := io.ReadFull(cr, content); err != nil {
715 return fmt.Errorf("read blob %s: %w", keyFullPath, err)
716 }
717 doc = index.Document{
718 SubRepositoryPath: key.SubRepoPath,
719 Name: keyFullPath,
720 Content: content,
721 Branches: branches,
722 }
723 }
724 }
725
726 if err := builder.Add(doc); err != nil {
727 return fmt.Errorf("error adding document with name %s: %w", key.FullPath(), err)
728 }
729
730 if idx%10_000 == 0 {
731 builder.CheckMemoryUsage()
732 }
733 }
734
735 return nil
736}
737
738// openRepo opens a git repository in a way that's optimized for indexing.
739//
740// It copies the relevant logic from git.PlainOpen, and tweaks certain filesystem options.
741func openRepo(repoDir string) (*git.Repository, io.Closer, error) {
742 fs := osfs.New(repoDir)
743
744 // Check if the root directory exists.
745 if _, err := fs.Stat(""); err != nil {
746 if os.IsNotExist(err) {
747 return nil, nil, git.ErrRepositoryNotExists
748 }
749 return nil, nil, err
750 }
751
752 fi, err := fs.Stat(git.GitDirName)
753 if err == nil && !fi.IsDir() {
754 return openCompatibleRepo(repoDir)
755 }
756
757 return openOptimizedRepo(repoDir)
758}
759
760func openCompatibleRepo(repoDir string) (*git.Repository, io.Closer, error) {
761 repo, err := plainOpenRepo(repoDir)
762 if err != nil {
763 return nil, nil, err
764 }
765
766 return repo, noopCloser{}, nil
767}
768
769func openOptimizedRepo(repoDir string) (*git.Repository, io.Closer, error) {
770 fs := osfs.New(repoDir)
771 wt := fs
772
773 // If there's a .git directory, use that as the new root.
774 if fi, err := fs.Stat(git.GitDirName); err == nil && fi.IsDir() {
775 if fs, err = fs.Chroot(git.GitDirName); err != nil {
776 return nil, nil, fmt.Errorf("fs.Chroot: %w", err)
777 }
778 }
779
780 s := filesystem.NewStorageWithOptions(fs, cache.NewObjectLRUDefault(), filesystem.Options{
781 // Cache the packfile handles, preventing the packfile from being opened then closed on every object access
782 KeepDescriptors: true,
783 })
784
785 // Because we're keeping descriptors open, we need to close the storage object when we're done.
786 repo, err := git.Open(s, wt)
787 return repo, s, err
788}
789
790type noopCloser struct{}
791
792func (noopCloser) Close() error { return nil }
793
794func catfileFilterSpec(opts Options) string {
795 // Can't filter by size if we have large file exceptions
796 if len(opts.BuildOptions.LargeFiles) > 0 {
797 return ""
798 }
799
800 if opts.BuildOptions.SizeMax <= 0 {
801 return ""
802 }
803
804 // Git's blob:limit filter excludes blobs whose size is >= the given limit,
805 // while zoekt indexes files up to and including SizeMax bytes.
806 return fmt.Sprintf("blob:limit=%d", int64(opts.BuildOptions.SizeMax)+1)
807}
808
809func newIgnoreMatcher(tree *object.Tree) (*ignore.Matcher, error) {
810 ignoreFile, err := tree.File(ignore.IgnoreFile)
811 if err == object.ErrFileNotFound {
812 return &ignore.Matcher{}, nil
813 }
814 if err != nil {
815 return nil, err
816 }
817 content, err := ignoreFile.Contents()
818 if err != nil {
819 return nil, err
820 }
821 return ignore.ParseIgnoreFile(strings.NewReader(content))
822}
823
824// prepareDeltaBuildFunc is a function that calculates the necessary metadata for preparing
825// a build.Builder instance for generating a delta build.
826type prepareDeltaBuildFunc func(options Options, repository *git.Repository) (repos map[fileKey]BlobLocation, branchVersions map[string]map[string]plumbing.Hash, changedOrDeletedPaths []string, err error)
827
828// prepareNormalBuildFunc is a function that calculates the necessary metadata for preparing
829// a build.Builder instance for generating a normal build.
830type prepareNormalBuildFunc func(options Options, repository *git.Repository) (repos map[fileKey]BlobLocation, branchVersions map[string]map[string]plumbing.Hash, err error)
831
832type gitIndexConfig struct {
833 // prepareDeltaBuild, if not nil, is the function that is used to calculate the metadata that will be used to
834 // prepare the build.Builder instance for generating a delta build.
835 //
836 // If prepareDeltaBuild is nil, gitindex.prepareDeltaBuild will be used instead.
837 prepareDeltaBuild prepareDeltaBuildFunc
838
839 // prepareNormalBuild, if not nil, is the function that is used to calculate the metadata that will be used to
840 // prepare the build.Builder instance for generating a normal build.
841 //
842 // If prepareNormalBuild is nil, gitindex.prepareNormalBuild will be used instead.
843 prepareNormalBuild prepareNormalBuildFunc
844}
845
846func prepareDeltaBuild(options Options, repository *git.Repository) (repos map[fileKey]BlobLocation, branchVersions map[string]map[string]plumbing.Hash, changedOrDeletedPaths []string, err error) {
847 if options.Submodules {
848 return nil, nil, nil, fmt.Errorf("delta builds currently don't support submodule indexing")
849 }
850
851 // discover what commits we indexed during our last build
852 existingRepository, _, ok, err := options.BuildOptions.FindRepositoryMetadata()
853 if err != nil {
854 return nil, nil, nil, fmt.Errorf("failed to get repository metadata: %w", err)
855 }
856
857 if !ok {
858 return nil, nil, nil, fmt.Errorf("no existing shards found for repository")
859 }
860
861 if options.DeltaShardNumberFallbackThreshold > 0 {
862 // HACK: For our interim compaction strategy, we force a full normal index once
863 // the number of shards on disk for this repository exceeds the provided threshold.
864 //
865 // This strategy obviously isn't optimal (as an example: we currently can't differentiate
866 // between "normal" and "delta" shards, so repositories like the gigarepo that generate a large number of shards per
867 // build would be disproportionately affected by this), but it'll allow us to continue experimenting on real workloads
868 // while we create a better compaction strategy).
869
870 oldShards := options.BuildOptions.FindAllShards()
871 if uint64(len(oldShards)) > options.DeltaShardNumberFallbackThreshold {
872 return nil, nil, nil, fmt.Errorf("number of existing shards (%d) > requested shard threshold (%d)", len(oldShards), options.DeltaShardNumberFallbackThreshold)
873 }
874 }
875
876 // Check to see if the set of branch names is consistent with what we last indexed.
877 // If it isn't consistent, that we can't proceed with a delta build (and the caller should fall back to a
878 // normal one).
879
880 if !index.BranchNamesEqual(existingRepository.Branches, options.BuildOptions.RepositoryDescription.Branches) {
881 var existingBranchNames []string
882 for _, b := range existingRepository.Branches {
883 existingBranchNames = append(existingBranchNames, b.Name)
884 }
885
886 var optionsBranchNames []string
887 for _, b := range options.BuildOptions.RepositoryDescription.Branches {
888 optionsBranchNames = append(optionsBranchNames, b.Name)
889 }
890
891 existingBranchList := strings.Join(existingBranchNames, ", ")
892 optionsBranchList := strings.Join(optionsBranchNames, ", ")
893
894 return nil, nil, nil, fmt.Errorf("requested branch set in build options (%q) != branch set found on disk (%q) - branch set must be the same for delta shards", optionsBranchList, existingBranchList)
895 }
896
897 // Check if the build options hash does not match the repository metadata's hash
898 // If it does not index then one or more index options has changed and will require a normal build instead of a delta build
899 if options.BuildOptions.GetHash() != existingRepository.IndexOptions {
900 return nil, nil, nil, fmt.Errorf("one or more index options previously stored for repository %s (ID: %d) does not match the index options for this requested build; These index option updates are incompatible with delta build. new index options: %+v", existingRepository.Name, existingRepository.ID, options.BuildOptions.HashOptions())
901 }
902
903 // branch => (path, sha1) => repo.
904 repos = map[fileKey]BlobLocation{}
905
906 branches, err := expandBranches(repository, options.Branches, options.BranchPrefix)
907 if err != nil {
908 return nil, nil, nil, fmt.Errorf("expandBranches: %w", err)
909 }
910
911 // branch name -> git worktree at most current commit
912 branchToCurrentTree := make(map[string]*object.Tree, len(branches))
913
914 for _, b := range branches {
915 commit, err := getCommit(repository, options.BranchPrefix, b)
916 if err != nil {
917 return nil, nil, nil, fmt.Errorf("getting last current commit for branch %q: %w", b, err)
918 }
919
920 tree, err := commit.Tree()
921 if err != nil {
922 return nil, nil, nil, fmt.Errorf("getting current git tree for branch %q: %w", b, err)
923 }
924
925 branchToCurrentTree[b] = tree
926 }
927
928 rawURL := options.BuildOptions.RepositoryDescription.URL
929 u, err := url.Parse(rawURL)
930 if err != nil {
931 return nil, nil, nil, fmt.Errorf("parsing repository URL %q: %w", rawURL, err)
932 }
933
934 // TODO: Support repository submodules for delta builds
935
936 // loop over all branches, calculate the diff between our
937 // last indexed commit and the current commit, and add files mentioned in the diff
938 for _, branch := range existingRepository.Branches {
939 lastIndexedCommit, err := getCommit(repository, "", branch.Version)
940 if err != nil {
941 return nil, nil, nil, fmt.Errorf("getting last indexed commit for branch %q: %w", branch.Name, err)
942 }
943
944 lastIndexedTree, err := lastIndexedCommit.Tree()
945 if err != nil {
946 return nil, nil, nil, fmt.Errorf("getting lasted indexed git tree for branch %q: %w", branch.Name, err)
947 }
948
949 changes, err := object.DiffTreeWithOptions(context.Background(), lastIndexedTree, branchToCurrentTree[branch.Name], &object.DiffTreeOptions{DetectRenames: false})
950 if err != nil {
951 return nil, nil, nil, fmt.Errorf("generating changeset for branch %q: %w", branch.Name, err)
952 }
953
954 for i, c := range changes {
955 oldFile, newFile, err := c.Files()
956 if err != nil {
957 return nil, nil, nil, fmt.Errorf("change #%d: getting files before and after change: %w", i, err)
958 }
959
960 if newFile != nil {
961 // note: newFile.Name could be a path that isn't relative to the repository root - using the
962 // change's Name field is the only way that @ggilmore saw to get the full path relative to the root
963 newFileRelativeRootPath := c.To.Name
964
965 // TODO@ggilmore: HACK - remove once ignore files are supported in delta builds
966 if newFileRelativeRootPath == ignore.IgnoreFile {
967 return nil, nil, nil, fmt.Errorf("%q file is not yet supported in delta builds", ignore.IgnoreFile)
968 }
969
970 // either file is added or renamed, so we need to add the new version to the build
971 file := fileKey{Path: newFileRelativeRootPath, ID: newFile.Hash}
972 if existing, ok := repos[file]; ok {
973 existing.Branches = append(existing.Branches, branch.Name)
974 repos[file] = existing
975 } else {
976 repos[file] = BlobLocation{
977 GitRepo: repository,
978 URL: u,
979 Branches: []string{branch.Name},
980 }
981 }
982 }
983
984 if oldFile == nil {
985 // file added - nothing more to do
986 continue
987 }
988
989 // Note: oldFile.Name could be a path that isn't relative to the repository root - using the
990 // change's "Name" field is the only way that ggilmore saw to get the full path relative to the root
991 oldFileRelativeRootPath := c.From.Name
992
993 if oldFileRelativeRootPath == ignore.IgnoreFile {
994 return nil, nil, nil, fmt.Errorf("%q file is not yet supported in delta builds", ignore.IgnoreFile)
995 }
996
997 // The file is either modified or deleted. So, we need to add ALL versions
998 // of the old file (across all branches) to the build.
999 for b, currentTree := range branchToCurrentTree {
1000 f, err := currentTree.File(oldFileRelativeRootPath)
1001 if err != nil {
1002 // the file doesn't exist in this branch
1003 if errors.Is(err, object.ErrFileNotFound) {
1004 continue
1005 }
1006
1007 return nil, nil, nil, fmt.Errorf("getting hash for file %q in branch %q: %w", oldFile.Name, b, err)
1008 }
1009
1010 file := fileKey{Path: oldFileRelativeRootPath, ID: f.ID()}
1011 if existing, ok := repos[file]; ok {
1012 existing.Branches = append(existing.Branches, b)
1013 repos[file] = existing
1014 } else {
1015 repos[file] = BlobLocation{
1016 GitRepo: repository,
1017 URL: u,
1018 Branches: []string{b},
1019 }
1020 }
1021 }
1022
1023 changedOrDeletedPaths = append(changedOrDeletedPaths, oldFileRelativeRootPath)
1024 }
1025 }
1026
1027 // we need to de-duplicate the branch map before returning it - it's possible for the same
1028 // branch to have been added multiple times if a file has been modified across multiple commits
1029 for _, info := range repos {
1030 sort.Strings(info.Branches)
1031 info.Branches = uniq(info.Branches)
1032 }
1033
1034 // we also need to de-duplicate the list of changed or deleted file paths, it's also possible to have duplicates
1035 // for the same reasoning as above
1036 sort.Strings(changedOrDeletedPaths)
1037 changedOrDeletedPaths = uniq(changedOrDeletedPaths)
1038
1039 return repos, nil, changedOrDeletedPaths, nil
1040}
1041
1042func prepareNormalBuild(options Options, repository *git.Repository) (repos map[fileKey]BlobLocation, branchVersions map[string]map[string]plumbing.Hash, err error) {
1043 var repoCache *RepoCache
1044 if options.Submodules && options.RepoCacheDir != "" {
1045 repoCache = NewRepoCache(options.RepoCacheDir)
1046 }
1047 return prepareNormalBuildRecurse(options, repository, repoCache, false)
1048}
1049
1050func prepareNormalBuildRecurse(options Options, repository *git.Repository, repoCache *RepoCache, isSubrepo bool) (repos map[fileKey]BlobLocation, branchVersions map[string]map[string]plumbing.Hash, err error) {
1051 // Branch => Repo => SHA1
1052 branchVersions = map[string]map[string]plumbing.Hash{}
1053
1054 branches, err := expandBranches(repository, options.Branches, options.BranchPrefix)
1055 if err != nil {
1056 return nil, nil, fmt.Errorf("expandBranches: %w", err)
1057 }
1058
1059 repoURL := options.BuildOptions.RepositoryDescription.URL
1060
1061 if isSubrepo {
1062 cfg, err := repository.Config()
1063 if err != nil {
1064 return nil, nil, fmt.Errorf("unable to get repository config: %w", err)
1065 }
1066
1067 u, err := normalizeSubmoduleRemoteURL(cfg)
1068 if err != nil {
1069 return nil, nil, fmt.Errorf("failed to identify subrepository URL: %w", err)
1070 }
1071 repoURL = u
1072 }
1073
1074 rw := NewRepoWalker(repository, repoURL, repoCache)
1075 for _, b := range branches {
1076 commit, err := getCommit(repository, options.BranchPrefix, b)
1077 if err != nil {
1078 if options.AllowMissingBranch && err.Error() == "reference not found" {
1079 continue
1080 }
1081
1082 return nil, nil, fmt.Errorf("getCommit: %w", err)
1083 }
1084
1085 tree, err := commit.Tree()
1086 if err != nil {
1087 return nil, nil, fmt.Errorf("commit.Tree: %w", err)
1088 }
1089
1090 ig, err := newIgnoreMatcher(tree)
1091 if err != nil {
1092 return nil, nil, fmt.Errorf("newIgnoreMatcher: %w", err)
1093 }
1094
1095 subVersions, err := rw.CollectFiles(tree, b, ig)
1096 if err != nil {
1097 return nil, nil, fmt.Errorf("CollectFiles: %w", err)
1098 }
1099
1100 branchVersions[b] = subVersions
1101 }
1102
1103 // Index submodules using go-git if we didn't do so using the repo cache
1104 if options.Submodules && options.RepoCacheDir == "" {
1105 worktree, err := repository.Worktree()
1106 if err != nil {
1107 return nil, nil, fmt.Errorf("failed to get repository worktree: %w", err)
1108 }
1109
1110 submodules, err := worktree.Submodules()
1111 if err != nil {
1112 return nil, nil, fmt.Errorf("failed to get submodules: %w", err)
1113 }
1114
1115 for _, submodule := range submodules {
1116 subRepository, err := submodule.Repository()
1117 if err != nil {
1118 log.Printf("failed to open submodule repository: %s, %s", submodule.Config().Name, err)
1119 continue
1120 }
1121
1122 sw, subVersions, err := prepareNormalBuildRecurse(options, subRepository, repoCache, true)
1123 if err != nil {
1124 log.Printf("failed to index submodule repository: %s, %s", submodule.Config().Name, err)
1125 continue
1126 }
1127
1128 log.Printf("adding subrepository files from: %s", submodule.Config().Name)
1129
1130 for k, repo := range sw {
1131 rw.Files[fileKey{
1132 SubRepoPath: filepath.Join(submodule.Config().Path, k.SubRepoPath),
1133 Path: k.Path,
1134 ID: k.ID,
1135 }] = repo
1136 }
1137
1138 for k, v := range subVersions {
1139 branchVersions[filepath.Join(submodule.Config().Path, k)] = v
1140 }
1141 }
1142 }
1143
1144 return rw.Files, branchVersions, nil
1145}
1146
1147func createDocument(key fileKey,
1148 repos map[fileKey]BlobLocation,
1149 opts index.Options,
1150) (index.Document, error) {
1151 repo := repos[key]
1152 blob, err := repo.GitRepo.BlobObject(key.ID)
1153 branches := repos[key].Branches
1154
1155 // We filter out large documents when fetching the repo. So if an object is too large, it will not be found.
1156 if errors.Is(err, plumbing.ErrObjectNotFound) {
1157 return skippedDoc(key, branches, index.SkipReasonTooLarge), nil
1158 }
1159
1160 if err != nil {
1161 return index.Document{}, err
1162 }
1163
1164 keyFullPath := key.FullPath()
1165 if blob.Size > int64(opts.SizeMax) && !opts.IgnoreSizeMax(keyFullPath) {
1166 return skippedDoc(key, branches, index.SkipReasonTooLarge), nil
1167 }
1168
1169 contents, err := blobContents(blob)
1170 if err != nil {
1171 return index.Document{}, err
1172 }
1173
1174 return index.Document{
1175 SubRepositoryPath: key.SubRepoPath,
1176 Name: keyFullPath,
1177 Content: contents,
1178 Branches: branches,
1179 }, nil
1180}
1181
1182// skippedDoc creates a Document placeholder for a blob that was not indexed.
1183func skippedDoc(key fileKey, branches []string, reason index.SkipReason) index.Document {
1184 return index.Document{
1185 SkipReason: reason,
1186 Name: key.FullPath(),
1187 Branches: branches,
1188 SubRepositoryPath: key.SubRepoPath,
1189 }
1190}
1191
1192func blobContents(blob *object.Blob) ([]byte, error) {
1193 r, err := blob.Reader()
1194 if err != nil {
1195 return nil, err
1196 }
1197 defer r.Close()
1198
1199 var buf bytes.Buffer
1200 buf.Grow(int(blob.Size))
1201 _, err = buf.ReadFrom(r)
1202 if err != nil {
1203 return nil, err
1204 }
1205 return buf.Bytes(), nil
1206}
1207
1208func uniq(ss []string) []string {
1209 result := ss[:0]
1210 var last string
1211 for i, s := range ss {
1212 if i == 0 || s != last {
1213 result = append(result, s)
1214 }
1215 last = s
1216 }
1217 return result
1218}