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 //
623 // 2026-04-02(keegan) we are regularly seeing git growing to over 9GB in
624 // memory usage in our production cluster. Disabling by default until the
625 // issue is resolved.
626 catfileBatchDisabled := cmp.Or(os.Getenv("ZOEKT_DISABLE_CATFILE_BATCH"), "true")
627 useCatfileBatch := true
628 if disabled, _ := strconv.ParseBool(catfileBatchDisabled); disabled {
629 useCatfileBatch = false
630 log.Printf("cat-file batch disabled via ZOEKT_DISABLE_CATFILE_BATCH, using go-git")
631 }
632
633 mainRepoKeys := make([]fileKey, 0, totalFiles)
634 mainRepoIDs := make([]plumbing.Hash, 0, totalFiles)
635 var submoduleKeys []fileKey
636
637 for _, name := range names {
638 for _, key := range fileKeys[name] {
639 if useCatfileBatch && key.SubRepoPath == "" {
640 mainRepoKeys = append(mainRepoKeys, key)
641 mainRepoIDs = append(mainRepoIDs, key.ID)
642 } else {
643 submoduleKeys = append(submoduleKeys, key)
644 }
645 }
646 }
647
648 log.Printf("attempting to index %d total files (%d via cat-file, %d via go-git)", totalFiles, len(mainRepoIDs), len(submoduleKeys))
649
650 // Stream main-repo blobs via pipelined cat-file --batch --buffer.
651 // Large blobs are skipped without reading content into memory.
652 if len(mainRepoIDs) > 0 {
653 crOpts := catfileReaderOptions{
654 filterSpec: catfileFilterSpec(opts),
655 }
656 cr, err := newCatfileReader(opts.RepoDir, mainRepoIDs, crOpts)
657 if err != nil {
658 return false, fmt.Errorf("newCatfileReader: %w", err)
659 }
660
661 if err := indexCatfileBlobs(cr, mainRepoKeys, repos, opts, builder); err != nil {
662 return false, err
663 }
664 }
665
666 // Index submodule blobs via go-git.
667 for idx, key := range submoduleKeys {
668 doc, err := createDocument(key, repos, opts.BuildOptions)
669 if err != nil {
670 return false, err
671 }
672
673 if err := builder.Add(doc); err != nil {
674 return false, fmt.Errorf("error adding document with name %s: %w", key.FullPath(), err)
675 }
676
677 if idx%10_000 == 0 {
678 builder.CheckMemoryUsage()
679 }
680 }
681
682 return true, builder.Finish()
683}
684
685// indexCatfileBlobs streams main-repo blobs from the catfileReader into the
686// builder. Large blobs are skipped without reading content into memory.
687// keys must correspond 1:1 (in order) with the ids passed to newCatfileReader.
688// The reader is always closed when this function returns.
689func indexCatfileBlobs(cr *catfileReader, keys []fileKey, repos map[fileKey]BlobLocation, opts Options, builder *index.Builder) error {
690 defer cr.Close()
691
692 for idx, key := range keys {
693 size, missing, excluded, err := cr.Next()
694 if err != nil {
695 return fmt.Errorf("cat-file next for %s: %w", key.FullPath(), err)
696 }
697
698 branches := repos[key].Branches
699 var doc index.Document
700
701 if missing {
702 // Unexpected for local repos — may indicate corruption, shallow
703 // clone, or a race with git gc. Log a warning and skip.
704 log.Printf("warning: blob %s missing for %s", key.ID, key.FullPath())
705 doc = skippedDoc(key, branches, index.SkipReasonMissing)
706 } else if excluded {
707 doc = skippedDoc(key, branches, index.SkipReasonTooLarge)
708 } else {
709 keyFullPath := key.FullPath()
710 if size > opts.BuildOptions.SizeMax && !opts.BuildOptions.IgnoreSizeMax(keyFullPath) {
711 // Skip without reading content into memory.
712 doc = skippedDoc(key, branches, index.SkipReasonTooLarge)
713 } else {
714 // Pre-allocate and read the full blob content in one call.
715 // io.ReadFull is preferred over io.LimitedReader here as it
716 // avoids the intermediate allocation and the size is known.
717 content := make([]byte, size)
718 if _, err := io.ReadFull(cr, content); err != nil {
719 return fmt.Errorf("read blob %s: %w", keyFullPath, err)
720 }
721 doc = index.Document{
722 SubRepositoryPath: key.SubRepoPath,
723 Name: keyFullPath,
724 Content: content,
725 Branches: branches,
726 }
727 }
728 }
729
730 if err := builder.Add(doc); err != nil {
731 return fmt.Errorf("error adding document with name %s: %w", key.FullPath(), err)
732 }
733
734 if idx%10_000 == 0 {
735 builder.CheckMemoryUsage()
736 }
737 }
738
739 return nil
740}
741
742// openRepo opens a git repository in a way that's optimized for indexing.
743//
744// It copies the relevant logic from git.PlainOpen, and tweaks certain filesystem options.
745func openRepo(repoDir string) (*git.Repository, io.Closer, error) {
746 fs := osfs.New(repoDir)
747
748 // Check if the root directory exists.
749 if _, err := fs.Stat(""); err != nil {
750 if os.IsNotExist(err) {
751 return nil, nil, git.ErrRepositoryNotExists
752 }
753 return nil, nil, err
754 }
755
756 fi, err := fs.Stat(git.GitDirName)
757 if err == nil && !fi.IsDir() {
758 return openCompatibleRepo(repoDir)
759 }
760
761 return openOptimizedRepo(repoDir)
762}
763
764func openCompatibleRepo(repoDir string) (*git.Repository, io.Closer, error) {
765 repo, err := plainOpenRepo(repoDir)
766 if err != nil {
767 return nil, nil, err
768 }
769
770 return repo, noopCloser{}, nil
771}
772
773func openOptimizedRepo(repoDir string) (*git.Repository, io.Closer, error) {
774 fs := osfs.New(repoDir)
775 wt := fs
776
777 // If there's a .git directory, use that as the new root.
778 if fi, err := fs.Stat(git.GitDirName); err == nil && fi.IsDir() {
779 if fs, err = fs.Chroot(git.GitDirName); err != nil {
780 return nil, nil, fmt.Errorf("fs.Chroot: %w", err)
781 }
782 }
783
784 s := filesystem.NewStorageWithOptions(fs, cache.NewObjectLRUDefault(), filesystem.Options{
785 // Cache the packfile handles, preventing the packfile from being opened then closed on every object access
786 KeepDescriptors: true,
787 })
788
789 // Because we're keeping descriptors open, we need to close the storage object when we're done.
790 repo, err := git.Open(s, wt)
791 return repo, s, err
792}
793
794type noopCloser struct{}
795
796func (noopCloser) Close() error { return nil }
797
798func catfileFilterSpec(opts Options) string {
799 // Can't filter by size if we have large file exceptions
800 if len(opts.BuildOptions.LargeFiles) > 0 {
801 return ""
802 }
803
804 if opts.BuildOptions.SizeMax <= 0 {
805 return ""
806 }
807
808 // Git's blob:limit filter excludes blobs whose size is >= the given limit,
809 // while zoekt indexes files up to and including SizeMax bytes.
810 return fmt.Sprintf("blob:limit=%d", int64(opts.BuildOptions.SizeMax)+1)
811}
812
813func newIgnoreMatcher(tree *object.Tree) (*ignore.Matcher, error) {
814 ignoreFile, err := tree.File(ignore.IgnoreFile)
815 if err == object.ErrFileNotFound {
816 return &ignore.Matcher{}, nil
817 }
818 if err != nil {
819 return nil, err
820 }
821 content, err := ignoreFile.Contents()
822 if err != nil {
823 return nil, err
824 }
825 return ignore.ParseIgnoreFile(strings.NewReader(content))
826}
827
828// prepareDeltaBuildFunc is a function that calculates the necessary metadata for preparing
829// a build.Builder instance for generating a delta build.
830type prepareDeltaBuildFunc func(options Options, repository *git.Repository) (repos map[fileKey]BlobLocation, branchVersions map[string]map[string]plumbing.Hash, changedOrDeletedPaths []string, err error)
831
832// prepareNormalBuildFunc is a function that calculates the necessary metadata for preparing
833// a build.Builder instance for generating a normal build.
834type prepareNormalBuildFunc func(options Options, repository *git.Repository) (repos map[fileKey]BlobLocation, branchVersions map[string]map[string]plumbing.Hash, err error)
835
836type gitIndexConfig struct {
837 // prepareDeltaBuild, if not nil, is the function that is used to calculate the metadata that will be used to
838 // prepare the build.Builder instance for generating a delta build.
839 //
840 // If prepareDeltaBuild is nil, gitindex.prepareDeltaBuild will be used instead.
841 prepareDeltaBuild prepareDeltaBuildFunc
842
843 // prepareNormalBuild, if not nil, is the function that is used to calculate the metadata that will be used to
844 // prepare the build.Builder instance for generating a normal build.
845 //
846 // If prepareNormalBuild is nil, gitindex.prepareNormalBuild will be used instead.
847 prepareNormalBuild prepareNormalBuildFunc
848}
849
850func prepareDeltaBuild(options Options, repository *git.Repository) (repos map[fileKey]BlobLocation, branchVersions map[string]map[string]plumbing.Hash, changedOrDeletedPaths []string, err error) {
851 if options.Submodules {
852 return nil, nil, nil, fmt.Errorf("delta builds currently don't support submodule indexing")
853 }
854
855 // discover what commits we indexed during our last build
856 existingRepository, _, ok, err := options.BuildOptions.FindRepositoryMetadata()
857 if err != nil {
858 return nil, nil, nil, fmt.Errorf("failed to get repository metadata: %w", err)
859 }
860
861 if !ok {
862 return nil, nil, nil, fmt.Errorf("no existing shards found for repository")
863 }
864
865 if options.DeltaShardNumberFallbackThreshold > 0 {
866 // HACK: For our interim compaction strategy, we force a full normal index once
867 // the number of shards on disk for this repository exceeds the provided threshold.
868 //
869 // This strategy obviously isn't optimal (as an example: we currently can't differentiate
870 // between "normal" and "delta" shards, so repositories like the gigarepo that generate a large number of shards per
871 // build would be disproportionately affected by this), but it'll allow us to continue experimenting on real workloads
872 // while we create a better compaction strategy).
873
874 oldShards := options.BuildOptions.FindAllShards()
875 if uint64(len(oldShards)) > options.DeltaShardNumberFallbackThreshold {
876 return nil, nil, nil, fmt.Errorf("number of existing shards (%d) > requested shard threshold (%d)", len(oldShards), options.DeltaShardNumberFallbackThreshold)
877 }
878 }
879
880 // Check to see if the set of branch names is consistent with what we last indexed.
881 // If it isn't consistent, that we can't proceed with a delta build (and the caller should fall back to a
882 // normal one).
883
884 if !index.BranchNamesEqual(existingRepository.Branches, options.BuildOptions.RepositoryDescription.Branches) {
885 var existingBranchNames []string
886 for _, b := range existingRepository.Branches {
887 existingBranchNames = append(existingBranchNames, b.Name)
888 }
889
890 var optionsBranchNames []string
891 for _, b := range options.BuildOptions.RepositoryDescription.Branches {
892 optionsBranchNames = append(optionsBranchNames, b.Name)
893 }
894
895 existingBranchList := strings.Join(existingBranchNames, ", ")
896 optionsBranchList := strings.Join(optionsBranchNames, ", ")
897
898 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)
899 }
900
901 // Check if the build options hash does not match the repository metadata's hash
902 // If it does not index then one or more index options has changed and will require a normal build instead of a delta build
903 if options.BuildOptions.GetHash() != existingRepository.IndexOptions {
904 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())
905 }
906
907 // branch => (path, sha1) => repo.
908 repos = map[fileKey]BlobLocation{}
909
910 branches, err := expandBranches(repository, options.Branches, options.BranchPrefix)
911 if err != nil {
912 return nil, nil, nil, fmt.Errorf("expandBranches: %w", err)
913 }
914
915 // branch name -> git worktree at most current commit
916 branchToCurrentTree := make(map[string]*object.Tree, len(branches))
917
918 for _, b := range branches {
919 commit, err := getCommit(repository, options.BranchPrefix, b)
920 if err != nil {
921 return nil, nil, nil, fmt.Errorf("getting last current commit for branch %q: %w", b, err)
922 }
923
924 tree, err := commit.Tree()
925 if err != nil {
926 return nil, nil, nil, fmt.Errorf("getting current git tree for branch %q: %w", b, err)
927 }
928
929 branchToCurrentTree[b] = tree
930 }
931
932 rawURL := options.BuildOptions.RepositoryDescription.URL
933 u, err := url.Parse(rawURL)
934 if err != nil {
935 return nil, nil, nil, fmt.Errorf("parsing repository URL %q: %w", rawURL, err)
936 }
937
938 // TODO: Support repository submodules for delta builds
939
940 // loop over all branches, calculate the diff between our
941 // last indexed commit and the current commit, and add files mentioned in the diff
942 for _, branch := range existingRepository.Branches {
943 lastIndexedCommit, err := getCommit(repository, "", branch.Version)
944 if err != nil {
945 return nil, nil, nil, fmt.Errorf("getting last indexed commit for branch %q: %w", branch.Name, err)
946 }
947
948 lastIndexedTree, err := lastIndexedCommit.Tree()
949 if err != nil {
950 return nil, nil, nil, fmt.Errorf("getting lasted indexed git tree for branch %q: %w", branch.Name, err)
951 }
952
953 changes, err := object.DiffTreeWithOptions(context.Background(), lastIndexedTree, branchToCurrentTree[branch.Name], &object.DiffTreeOptions{DetectRenames: false})
954 if err != nil {
955 return nil, nil, nil, fmt.Errorf("generating changeset for branch %q: %w", branch.Name, err)
956 }
957
958 for i, c := range changes {
959 oldFile, newFile, err := c.Files()
960 if err != nil {
961 return nil, nil, nil, fmt.Errorf("change #%d: getting files before and after change: %w", i, err)
962 }
963
964 if newFile != nil {
965 // note: newFile.Name could be a path that isn't relative to the repository root - using the
966 // change's Name field is the only way that @ggilmore saw to get the full path relative to the root
967 newFileRelativeRootPath := c.To.Name
968
969 // TODO@ggilmore: HACK - remove once ignore files are supported in delta builds
970 if newFileRelativeRootPath == ignore.IgnoreFile {
971 return nil, nil, nil, fmt.Errorf("%q file is not yet supported in delta builds", ignore.IgnoreFile)
972 }
973
974 // either file is added or renamed, so we need to add the new version to the build
975 file := fileKey{Path: newFileRelativeRootPath, ID: newFile.Hash}
976 if existing, ok := repos[file]; ok {
977 existing.Branches = append(existing.Branches, branch.Name)
978 repos[file] = existing
979 } else {
980 repos[file] = BlobLocation{
981 GitRepo: repository,
982 URL: u,
983 Branches: []string{branch.Name},
984 }
985 }
986 }
987
988 if oldFile == nil {
989 // file added - nothing more to do
990 continue
991 }
992
993 // Note: oldFile.Name could be a path that isn't relative to the repository root - using the
994 // change's "Name" field is the only way that ggilmore saw to get the full path relative to the root
995 oldFileRelativeRootPath := c.From.Name
996
997 if oldFileRelativeRootPath == ignore.IgnoreFile {
998 return nil, nil, nil, fmt.Errorf("%q file is not yet supported in delta builds", ignore.IgnoreFile)
999 }
1000
1001 // The file is either modified or deleted. So, we need to add ALL versions
1002 // of the old file (across all branches) to the build.
1003 for b, currentTree := range branchToCurrentTree {
1004 f, err := currentTree.File(oldFileRelativeRootPath)
1005 if err != nil {
1006 // the file doesn't exist in this branch
1007 if errors.Is(err, object.ErrFileNotFound) {
1008 continue
1009 }
1010
1011 return nil, nil, nil, fmt.Errorf("getting hash for file %q in branch %q: %w", oldFile.Name, b, err)
1012 }
1013
1014 file := fileKey{Path: oldFileRelativeRootPath, ID: f.ID()}
1015 if existing, ok := repos[file]; ok {
1016 existing.Branches = append(existing.Branches, b)
1017 repos[file] = existing
1018 } else {
1019 repos[file] = BlobLocation{
1020 GitRepo: repository,
1021 URL: u,
1022 Branches: []string{b},
1023 }
1024 }
1025 }
1026
1027 changedOrDeletedPaths = append(changedOrDeletedPaths, oldFileRelativeRootPath)
1028 }
1029 }
1030
1031 // we need to de-duplicate the branch map before returning it - it's possible for the same
1032 // branch to have been added multiple times if a file has been modified across multiple commits
1033 for _, info := range repos {
1034 sort.Strings(info.Branches)
1035 info.Branches = uniq(info.Branches)
1036 }
1037
1038 // we also need to de-duplicate the list of changed or deleted file paths, it's also possible to have duplicates
1039 // for the same reasoning as above
1040 sort.Strings(changedOrDeletedPaths)
1041 changedOrDeletedPaths = uniq(changedOrDeletedPaths)
1042
1043 return repos, nil, changedOrDeletedPaths, nil
1044}
1045
1046func prepareNormalBuild(options Options, repository *git.Repository) (repos map[fileKey]BlobLocation, branchVersions map[string]map[string]plumbing.Hash, err error) {
1047 var repoCache *RepoCache
1048 if options.Submodules && options.RepoCacheDir != "" {
1049 repoCache = NewRepoCache(options.RepoCacheDir)
1050 }
1051 return prepareNormalBuildRecurse(options, repository, repoCache, false)
1052}
1053
1054func prepareNormalBuildRecurse(options Options, repository *git.Repository, repoCache *RepoCache, isSubrepo bool) (repos map[fileKey]BlobLocation, branchVersions map[string]map[string]plumbing.Hash, err error) {
1055 // Branch => Repo => SHA1
1056 branchVersions = map[string]map[string]plumbing.Hash{}
1057
1058 branches, err := expandBranches(repository, options.Branches, options.BranchPrefix)
1059 if err != nil {
1060 return nil, nil, fmt.Errorf("expandBranches: %w", err)
1061 }
1062
1063 repoURL := options.BuildOptions.RepositoryDescription.URL
1064
1065 if isSubrepo {
1066 cfg, err := repository.Config()
1067 if err != nil {
1068 return nil, nil, fmt.Errorf("unable to get repository config: %w", err)
1069 }
1070
1071 u, err := normalizeSubmoduleRemoteURL(cfg)
1072 if err != nil {
1073 return nil, nil, fmt.Errorf("failed to identify subrepository URL: %w", err)
1074 }
1075 repoURL = u
1076 }
1077
1078 rw := NewRepoWalker(repository, repoURL, repoCache)
1079 for _, b := range branches {
1080 commit, err := getCommit(repository, options.BranchPrefix, b)
1081 if err != nil {
1082 if options.AllowMissingBranch && err.Error() == "reference not found" {
1083 continue
1084 }
1085
1086 return nil, nil, fmt.Errorf("getCommit: %w", err)
1087 }
1088
1089 tree, err := commit.Tree()
1090 if err != nil {
1091 return nil, nil, fmt.Errorf("commit.Tree: %w", err)
1092 }
1093
1094 ig, err := newIgnoreMatcher(tree)
1095 if err != nil {
1096 return nil, nil, fmt.Errorf("newIgnoreMatcher: %w", err)
1097 }
1098
1099 subVersions, err := rw.CollectFiles(tree, b, ig)
1100 if err != nil {
1101 return nil, nil, fmt.Errorf("CollectFiles: %w", err)
1102 }
1103
1104 branchVersions[b] = subVersions
1105 }
1106
1107 // Index submodules using go-git if we didn't do so using the repo cache
1108 if options.Submodules && options.RepoCacheDir == "" {
1109 worktree, err := repository.Worktree()
1110 if err != nil {
1111 return nil, nil, fmt.Errorf("failed to get repository worktree: %w", err)
1112 }
1113
1114 submodules, err := worktree.Submodules()
1115 if err != nil {
1116 return nil, nil, fmt.Errorf("failed to get submodules: %w", err)
1117 }
1118
1119 for _, submodule := range submodules {
1120 subRepository, err := submodule.Repository()
1121 if err != nil {
1122 log.Printf("failed to open submodule repository: %s, %s", submodule.Config().Name, err)
1123 continue
1124 }
1125
1126 sw, subVersions, err := prepareNormalBuildRecurse(options, subRepository, repoCache, true)
1127 if err != nil {
1128 log.Printf("failed to index submodule repository: %s, %s", submodule.Config().Name, err)
1129 continue
1130 }
1131
1132 log.Printf("adding subrepository files from: %s", submodule.Config().Name)
1133
1134 for k, repo := range sw {
1135 rw.Files[fileKey{
1136 SubRepoPath: filepath.Join(submodule.Config().Path, k.SubRepoPath),
1137 Path: k.Path,
1138 ID: k.ID,
1139 }] = repo
1140 }
1141
1142 for k, v := range subVersions {
1143 branchVersions[filepath.Join(submodule.Config().Path, k)] = v
1144 }
1145 }
1146 }
1147
1148 return rw.Files, branchVersions, nil
1149}
1150
1151func createDocument(key fileKey,
1152 repos map[fileKey]BlobLocation,
1153 opts index.Options,
1154) (index.Document, error) {
1155 repo := repos[key]
1156 blob, err := repo.GitRepo.BlobObject(key.ID)
1157 branches := repos[key].Branches
1158
1159 // We filter out large documents when fetching the repo. So if an object is too large, it will not be found.
1160 if errors.Is(err, plumbing.ErrObjectNotFound) {
1161 return skippedDoc(key, branches, index.SkipReasonTooLarge), nil
1162 }
1163
1164 if err != nil {
1165 return index.Document{}, err
1166 }
1167
1168 keyFullPath := key.FullPath()
1169 if blob.Size > int64(opts.SizeMax) && !opts.IgnoreSizeMax(keyFullPath) {
1170 return skippedDoc(key, branches, index.SkipReasonTooLarge), nil
1171 }
1172
1173 contents, err := blobContents(blob)
1174 if err != nil {
1175 return index.Document{}, err
1176 }
1177
1178 return index.Document{
1179 SubRepositoryPath: key.SubRepoPath,
1180 Name: keyFullPath,
1181 Content: contents,
1182 Branches: branches,
1183 }, nil
1184}
1185
1186// skippedDoc creates a Document placeholder for a blob that was not indexed.
1187func skippedDoc(key fileKey, branches []string, reason index.SkipReason) index.Document {
1188 return index.Document{
1189 SkipReason: reason,
1190 Name: key.FullPath(),
1191 Branches: branches,
1192 SubRepositoryPath: key.SubRepoPath,
1193 }
1194}
1195
1196func blobContents(blob *object.Blob) ([]byte, error) {
1197 r, err := blob.Reader()
1198 if err != nil {
1199 return nil, err
1200 }
1201 defer r.Close()
1202
1203 var buf bytes.Buffer
1204 buf.Grow(int(blob.Size))
1205 _, err = buf.ReadFrom(r)
1206 if err != nil {
1207 return nil, err
1208 }
1209 return buf.Bytes(), nil
1210}
1211
1212func uniq(ss []string) []string {
1213 result := ss[:0]
1214 var last string
1215 for i, s := range ss {
1216 if i == 0 || s != last {
1217 result = append(result, s)
1218 }
1219 last = s
1220 }
1221 return result
1222}