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/plumbing/cache"
37 "github.com/go-git/go-git/v5/storage/filesystem"
38 "github.com/sourcegraph/zoekt"
39 "github.com/sourcegraph/zoekt/build"
40 "github.com/sourcegraph/zoekt/ignore"
41
42 "github.com/go-git/go-git/v5/config"
43 "github.com/go-git/go-git/v5/plumbing"
44 "github.com/go-git/go-git/v5/plumbing/object"
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 configLookupRemoteURL(cfg *config.Config, key string) string {
186 rc := cfg.Remotes[key]
187 if rc == nil || len(rc.URLs) == 0 {
188 return ""
189 }
190 return rc.URLs[0]
191}
192
193var sshRelativeURLRegexp = regexp.MustCompile(`^([^@]+)@([^:]+):(.*)$`)
194
195func setTemplatesFromConfig(desc *zoekt.Repository, repoDir string) error {
196 repo, err := git.PlainOpen(repoDir)
197 if err != nil {
198 return err
199 }
200
201 cfg, err := repo.Config()
202 if err != nil {
203 return err
204 }
205
206 sec := cfg.Raw.Section("zoekt")
207
208 webURLStr := sec.Options.Get("web-url")
209 webURLType := sec.Options.Get("web-url-type")
210
211 if webURLType != "" && webURLStr != "" {
212 webURL, err := url.Parse(webURLStr)
213 if err != nil {
214 return err
215 }
216 if err := setTemplates(desc, webURL, webURLType); err != nil {
217 return err
218 }
219 } else if webURLStr != "" {
220 desc.URL = webURLStr
221 }
222
223 name := sec.Options.Get("name")
224 if name != "" {
225 desc.Name = name
226 } else {
227 remoteURL := configLookupRemoteURL(cfg, "origin")
228 if remoteURL == "" {
229 return nil
230 }
231 if sm := sshRelativeURLRegexp.FindStringSubmatch(remoteURL); sm != nil {
232 user := sm[1]
233 host := sm[2]
234 path := sm[3]
235
236 remoteURL = fmt.Sprintf("ssh+git://%s@%s/%s", user, host, path)
237 }
238
239 u, err := url.Parse(remoteURL)
240 if err != nil {
241 return err
242 }
243 if err := SetTemplatesFromOrigin(desc, u); err != nil {
244 return err
245 }
246 }
247
248 id, _ := strconv.ParseUint(sec.Options.Get("repoid"), 10, 32)
249 desc.ID = uint32(id)
250
251 if desc.RawConfig == nil {
252 desc.RawConfig = map[string]string{}
253 }
254 for _, o := range sec.Options {
255 desc.RawConfig[o.Key] = o.Value
256 }
257
258 // Ranking info.
259
260 // Github:
261 traction := 0
262 for _, s := range []string{"github-stars", "github-forks", "github-watchers", "github-subscribers"} {
263 f, err := strconv.Atoi(sec.Options.Get(s))
264 if err == nil {
265 traction += f
266 }
267 }
268
269 if strings.Contains(desc.Name, "googlesource.com/") && traction == 0 {
270 // Pretend everything on googlesource.com has 1000
271 // github stars.
272 traction = 1000
273 }
274
275 if traction > 0 {
276 l := math.Log(float64(traction))
277 desc.Rank = uint16((1.0 - 1.0/math.Pow(1+l, 0.6)) * 10000)
278 }
279
280 return nil
281}
282
283// SetTemplatesFromOrigin fills in templates based on the origin URL.
284func SetTemplatesFromOrigin(desc *zoekt.Repository, u *url.URL) error {
285 desc.Name = filepath.Join(u.Host, strings.TrimSuffix(u.Path, ".git"))
286
287 if strings.HasSuffix(u.Host, ".googlesource.com") {
288 return setTemplates(desc, u, "gitiles")
289 } else if u.Host == "github.com" {
290 u.Path = strings.TrimSuffix(u.Path, ".git")
291 return setTemplates(desc, u, "github")
292 } else {
293 return fmt.Errorf("unknown git hosting site %q", u)
294 }
295}
296
297// The Options structs controls details of the indexing process.
298type Options struct {
299 // The repository to be indexed.
300 RepoDir string
301
302 // If set, follow submodule links. This requires RepoCacheDir to be set.
303 Submodules bool
304
305 // If set, skip indexing if the existing index shard is newer
306 // than the refs in the repository.
307 Incremental bool
308
309 // Don't error out if some branch is missing
310 AllowMissingBranch bool
311
312 // Specifies the root of a Repository cache. Needed for submodule indexing.
313 RepoCacheDir string
314
315 // Indexing options.
316 BuildOptions build.Options
317
318 // Prefix of the branch to index, e.g. `remotes/origin`.
319 BranchPrefix string
320
321 // List of branch names to index, e.g. []string{"HEAD", "stable"}
322 Branches []string
323
324 // DeltaShardNumberFallbackThreshold defines an upper limit (inclusive) on the number of preexisting shards
325 // that can exist before attempting another delta build. If the number of preexisting shards exceeds this threshold,
326 // then a normal build will be performed instead.
327 //
328 // If DeltaShardNumberFallbackThreshold is 0, then this fallback behavior is disabled:
329 // a delta build will always be performed regardless of the number of preexisting shards.
330 DeltaShardNumberFallbackThreshold uint64
331}
332
333func expandBranches(repo *git.Repository, bs []string, prefix string) ([]string, error) {
334 var result []string
335 for _, b := range bs {
336 // Sourcegraph: We disable resolving refs. We want to return the exact ref
337 // requested so we can match it up.
338 if b == "HEAD" && false {
339 ref, err := repo.Head()
340 if err != nil {
341 return nil, err
342 }
343
344 result = append(result, strings.TrimPrefix(ref.Name().String(), prefix))
345 continue
346 }
347
348 if strings.Contains(b, "*") {
349 iter, err := repo.Branches()
350 if err != nil {
351 return nil, err
352 }
353
354 defer iter.Close()
355 for {
356 ref, err := iter.Next()
357 if err == io.EOF {
358 break
359 }
360 if err != nil {
361 return nil, err
362 }
363
364 name := ref.Name().Short()
365 if matched, err := filepath.Match(b, name); err != nil {
366 return nil, err
367 } else if !matched {
368 continue
369 }
370
371 result = append(result, strings.TrimPrefix(name, prefix))
372 }
373 continue
374 }
375
376 result = append(result, b)
377 }
378
379 return result, nil
380}
381
382// IndexGitRepo indexes the git repository as specified by the options.
383// The returned bool indicates whether the index was updated as a result. This
384// can be informative if doing incremental indexing.
385func IndexGitRepo(opts Options) (bool, error) {
386 return indexGitRepo(opts, gitIndexConfig{})
387}
388
389// indexGitRepo indexes the git repository as specified by the options and the provided gitIndexConfig.
390// The returned bool indicates whether the index was updated as a result. This
391// can be informative if doing incremental indexing.
392func indexGitRepo(opts Options, config gitIndexConfig) (bool, error) {
393 prepareDeltaBuild := prepareDeltaBuild
394 if config.prepareDeltaBuild != nil {
395 prepareDeltaBuild = config.prepareDeltaBuild
396 }
397
398 prepareNormalBuild := prepareNormalBuild
399 if config.prepareNormalBuild != nil {
400 prepareNormalBuild = config.prepareNormalBuild
401 }
402
403 // Set max thresholds, since we use them in this function.
404 opts.BuildOptions.SetDefaults()
405 if opts.RepoDir == "" {
406 return false, fmt.Errorf("gitindex: must set RepoDir")
407 }
408
409 opts.BuildOptions.RepositoryDescription.Source = opts.RepoDir
410
411 var repo *git.Repository
412 // TODO: this now defaults to on since we found a bug in it. Once we have
413 // fixed openRepo default to false.
414 legacyRepoOpen := cmp.Or(os.Getenv("ZOEKT_DISABLE_GOGIT_OPTIMIZATION"), "true")
415 if b, err := strconv.ParseBool(legacyRepoOpen); b || err != nil {
416 repo, err = git.PlainOpen(opts.RepoDir)
417 if err != nil {
418 return false, fmt.Errorf("git.PlainOpen: %w", err)
419 }
420 } else {
421 var repoCloser io.Closer
422 repo, repoCloser, err = openRepo(opts.RepoDir)
423 if err != nil {
424 return false, fmt.Errorf("openRepo: %w", err)
425 }
426 defer repoCloser.Close()
427 }
428
429 if err := setTemplatesFromConfig(&opts.BuildOptions.RepositoryDescription, opts.RepoDir); err != nil {
430 log.Printf("setTemplatesFromConfig(%s): %s", opts.RepoDir, err)
431 }
432
433 branches, err := expandBranches(repo, opts.Branches, opts.BranchPrefix)
434 if err != nil {
435 return false, fmt.Errorf("expandBranches: %w", err)
436 }
437 for _, b := range branches {
438 commit, err := getCommit(repo, opts.BranchPrefix, b)
439 if err != nil {
440 if opts.AllowMissingBranch && err.Error() == "reference not found" {
441 continue
442 }
443
444 return false, fmt.Errorf("getCommit(%q, %q): %w", opts.BranchPrefix, b, err)
445 }
446
447 opts.BuildOptions.RepositoryDescription.Branches = append(opts.BuildOptions.RepositoryDescription.Branches, zoekt.RepositoryBranch{
448 Name: b,
449 Version: commit.Hash.String(),
450 })
451
452 if when := commit.Committer.When; when.After(opts.BuildOptions.RepositoryDescription.LatestCommitDate) {
453 opts.BuildOptions.RepositoryDescription.LatestCommitDate = when
454 }
455 }
456
457 if opts.Incremental && opts.BuildOptions.IncrementalSkipIndexing() {
458 return false, nil
459 }
460
461 // branch => (path, sha1) => repo.
462 var repos map[fileKey]BlobLocation
463
464 // Branch => Repo => SHA1
465 var branchVersions map[string]map[string]plumbing.Hash
466
467 // set of file paths that have been changed or deleted since
468 // the last indexed commit
469 //
470 // These only have an effect on delta builds
471 var changedOrRemovedFiles []string
472
473 if opts.BuildOptions.IsDelta {
474 repos, branchVersions, changedOrRemovedFiles, err = prepareDeltaBuild(opts, repo)
475 if err != nil {
476 log.Printf("delta build: falling back to normal build since delta build failed, repository=%q, err=%s", opts.BuildOptions.RepositoryDescription.Name, err)
477 opts.BuildOptions.IsDelta = false
478 }
479 }
480
481 if !opts.BuildOptions.IsDelta {
482 repos, branchVersions, err = prepareNormalBuild(opts, repo)
483 if err != nil {
484 return false, fmt.Errorf("preparing normal build: %w", err)
485 }
486 }
487
488 reposByPath := map[string]BlobLocation{}
489 for key, info := range repos {
490 reposByPath[key.SubRepoPath] = info
491 }
492
493 opts.BuildOptions.SubRepositories = map[string]*zoekt.Repository{}
494 for path, info := range reposByPath {
495 tpl := opts.BuildOptions.RepositoryDescription
496 if path != "" {
497 tpl = zoekt.Repository{URL: info.URL.String()}
498 if err := SetTemplatesFromOrigin(&tpl, info.URL); err != nil {
499 log.Printf("setTemplatesFromOrigin(%s, %s): %s", path, info.URL, err)
500 }
501 }
502 opts.BuildOptions.SubRepositories[path] = &tpl
503 }
504
505 for _, br := range opts.BuildOptions.RepositoryDescription.Branches {
506 for path, repo := range opts.BuildOptions.SubRepositories {
507 id := branchVersions[br.Name][path]
508 repo.Branches = append(repo.Branches, zoekt.RepositoryBranch{
509 Name: br.Name,
510 Version: id.String(),
511 })
512 }
513 }
514
515 builder, err := build.NewBuilder(opts.BuildOptions)
516 if err != nil {
517 return false, fmt.Errorf("build.NewBuilder: %w", err)
518 }
519
520 // Preparing the build can consume substantial memory, so check usage before starting to index.
521 builder.CheckMemoryUsage()
522
523 // we don't need to check error, since we either already have an error, or
524 // we returning the first call to builder.Finish.
525 defer builder.Finish() // nolint:errcheck
526
527 for _, f := range changedOrRemovedFiles {
528 builder.MarkFileAsChangedOrRemoved(f)
529 }
530
531 var names []string
532 fileKeys := map[string][]fileKey{}
533 totalFiles := 0
534
535 for key := range repos {
536 n := key.FullPath()
537 fileKeys[n] = append(fileKeys[n], key)
538 names = append(names, n)
539 totalFiles++
540 }
541
542 sort.Strings(names)
543 names = uniq(names)
544
545 log.Printf("attempting to index %d total files", totalFiles)
546 for idx, name := range names {
547 keys := fileKeys[name]
548
549 for _, key := range keys {
550 doc, err := createDocument(key, repos, opts.BuildOptions)
551 if err != nil {
552 return false, err
553 }
554
555 if err := builder.Add(doc); err != nil {
556 return false, fmt.Errorf("error adding document with name %s: %w", key.FullPath(), err)
557 }
558
559 if idx%10_000 == 0 {
560 builder.CheckMemoryUsage()
561 }
562 }
563 }
564 return true, builder.Finish()
565}
566
567// openRepo opens a git repository in a way that's optimized for indexing.
568//
569// It copies the relevant logic from git.PlainOpen, and tweaks certain filesystem options.
570func openRepo(repoDir string) (*git.Repository, io.Closer, error) {
571 fs := osfs.New(repoDir)
572
573 // Check if the root directory exists.
574 if _, err := fs.Stat(""); err != nil {
575 if os.IsNotExist(err) {
576 return nil, nil, git.ErrRepositoryNotExists
577 }
578 return nil, nil, err
579 }
580
581 // If there's a .git directory, use that as the new root.
582 if fi, err := fs.Stat(git.GitDirName); err == nil && fi.IsDir() {
583 if fs, err = fs.Chroot(git.GitDirName); err != nil {
584 return nil, nil, fmt.Errorf("fs.Chroot: %w", err)
585 }
586 }
587
588 s := filesystem.NewStorageWithOptions(fs, cache.NewObjectLRUDefault(), filesystem.Options{
589 // Cache the packfile handles, preventing the packfile from being opened then closed on every object access
590 KeepDescriptors: true,
591 // Disable caching for most objects, by setting the threshold to 1 byte. This avoids allocating a bunch of
592 // in-memory objects that are unlikely to be reused, since we only read each file once. Note: go-git still
593 // proactively caches objects under 16KB (see smallObjectThreshold in packfile logic).
594 LargeObjectThreshold: 1,
595 })
596
597 // Because we're keeping descriptors open, we need to close the storage object when we're done.
598 repo, err := git.Open(s, fs)
599 return repo, s, err
600}
601
602type repoPathRanks struct {
603 MeanRank float64 `json:"mean_reference_count"`
604 Paths map[string]float64 `json:"paths"`
605}
606
607// rank returns the rank for a given path. It uses these rules:
608// - If we have a concrete rank for this file, always use it
609// - If there's no rank, and it's a low priority file like a test, then use rank 0
610// - Otherwise use the mean rank of this repository, to avoid giving it a big disadvantage
611func (r repoPathRanks) rank(path string, content []byte) float64 {
612 if rank, ok := r.Paths[path]; ok {
613 return rank
614 } else if build.IsLowPriority(path, content) {
615 return 0.0
616 } else {
617 return r.MeanRank
618 }
619}
620
621func newIgnoreMatcher(tree *object.Tree) (*ignore.Matcher, error) {
622 ignoreFile, err := tree.File(ignore.IgnoreFile)
623 if err == object.ErrFileNotFound {
624 return &ignore.Matcher{}, nil
625 }
626 if err != nil {
627 return nil, err
628 }
629 content, err := ignoreFile.Contents()
630 if err != nil {
631 return nil, err
632 }
633 return ignore.ParseIgnoreFile(strings.NewReader(content))
634}
635
636// prepareDeltaBuildFunc is a function that calculates the necessary metadata for preparing
637// a build.Builder instance for generating a delta build.
638type prepareDeltaBuildFunc func(options Options, repository *git.Repository) (repos map[fileKey]BlobLocation, branchVersions map[string]map[string]plumbing.Hash, changedOrDeletedPaths []string, err error)
639
640// prepareNormalBuildFunc is a function that calculates the necessary metadata for preparing
641// a build.Builder instance for generating a normal build.
642type prepareNormalBuildFunc func(options Options, repository *git.Repository) (repos map[fileKey]BlobLocation, branchVersions map[string]map[string]plumbing.Hash, err error)
643
644type gitIndexConfig struct {
645 // prepareDeltaBuild, if not nil, is the function that is used to calculate the metadata that will be used to
646 // prepare the build.Builder instance for generating a delta build.
647 //
648 // If prepareDeltaBuild is nil, gitindex.prepareDeltaBuild will be used instead.
649 prepareDeltaBuild prepareDeltaBuildFunc
650
651 // prepareNormalBuild, if not nil, is the function that is used to calculate the metadata that will be used to
652 // prepare the build.Builder instance for generating a normal build.
653 //
654 // If prepareNormalBuild is nil, gitindex.prepareNormalBuild will be used instead.
655 prepareNormalBuild prepareNormalBuildFunc
656}
657
658func prepareDeltaBuild(options Options, repository *git.Repository) (repos map[fileKey]BlobLocation, branchVersions map[string]map[string]plumbing.Hash, changedOrDeletedPaths []string, err error) {
659 if options.Submodules {
660 return nil, nil, nil, fmt.Errorf("delta builds currently don't support submodule indexing")
661 }
662
663 // discover what commits we indexed during our last build
664 existingRepository, _, ok, err := options.BuildOptions.FindRepositoryMetadata()
665 if err != nil {
666 return nil, nil, nil, fmt.Errorf("failed to get repository metadata: %w", err)
667 }
668
669 if !ok {
670 return nil, nil, nil, fmt.Errorf("no existing shards found for repository")
671 }
672
673 if options.DeltaShardNumberFallbackThreshold > 0 {
674 // HACK: For our interim compaction strategy, we force a full normal index once
675 // the number of shards on disk for this repository exceeds the provided threshold.
676 //
677 // This strategy obviously isn't optimal (as an example: we currently can't differentiate
678 // between "normal" and "delta" shards, so repositories like the gigarepo that generate a large number of shards per
679 // build would be disproportionately affected by this), but it'll allow us to continue experimenting on real workloads
680 // while we create a better compaction strategy).
681
682 oldShards := options.BuildOptions.FindAllShards()
683 if uint64(len(oldShards)) > options.DeltaShardNumberFallbackThreshold {
684 return nil, nil, nil, fmt.Errorf("number of existing shards (%d) > requested shard threshold (%d)", len(oldShards), options.DeltaShardNumberFallbackThreshold)
685 }
686 }
687
688 // Check to see if the set of branch names is consistent with what we last indexed.
689 // If it isn't consistent, that we can't proceed with a delta build (and the caller should fall back to a
690 // normal one).
691
692 if !build.BranchNamesEqual(existingRepository.Branches, options.BuildOptions.RepositoryDescription.Branches) {
693 var existingBranchNames []string
694 for _, b := range existingRepository.Branches {
695 existingBranchNames = append(existingBranchNames, b.Name)
696 }
697
698 var optionsBranchNames []string
699 for _, b := range options.BuildOptions.RepositoryDescription.Branches {
700 optionsBranchNames = append(optionsBranchNames, b.Name)
701 }
702
703 existingBranchList := strings.Join(existingBranchNames, ", ")
704 optionsBranchList := strings.Join(optionsBranchNames, ", ")
705
706 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)
707 }
708
709 // Check if the build options hash does not match the repository metadata's hash
710 // If it does not match then one or more index options has changed and will require a normal build instead of a delta build
711 if options.BuildOptions.GetHash() != existingRepository.IndexOptions {
712 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())
713 }
714
715 // branch => (path, sha1) => repo.
716 repos = map[fileKey]BlobLocation{}
717
718 // branch name -> git worktree at most current commit
719 branchToCurrentTree := make(map[string]*object.Tree, len(options.Branches))
720
721 for _, b := range options.Branches {
722 commit, err := getCommit(repository, options.BranchPrefix, b)
723 if err != nil {
724 return nil, nil, nil, fmt.Errorf("getting last current commit for branch %q: %w", b, err)
725 }
726
727 tree, err := commit.Tree()
728 if err != nil {
729 return nil, nil, nil, fmt.Errorf("getting current git tree for branch %q: %w", b, err)
730 }
731
732 branchToCurrentTree[b] = tree
733 }
734
735 rawURL := options.BuildOptions.RepositoryDescription.URL
736 u, err := url.Parse(rawURL)
737 if err != nil {
738 return nil, nil, nil, fmt.Errorf("parsing repository URL %q: %w", rawURL, err)
739 }
740
741 // TODO: Support repository submodules for delta builds
742
743 // loop over all branches, calculate the diff between our
744 // last indexed commit and the current commit, and add files mentioned in the diff
745 for _, branch := range existingRepository.Branches {
746 lastIndexedCommit, err := getCommit(repository, "", branch.Version)
747 if err != nil {
748 return nil, nil, nil, fmt.Errorf("getting last indexed commit for branch %q: %w", branch.Name, err)
749 }
750
751 lastIndexedTree, err := lastIndexedCommit.Tree()
752 if err != nil {
753 return nil, nil, nil, fmt.Errorf("getting lasted indexed git tree for branch %q: %w", branch.Name, err)
754 }
755
756 changes, err := object.DiffTreeWithOptions(context.Background(), lastIndexedTree, branchToCurrentTree[branch.Name], &object.DiffTreeOptions{DetectRenames: false})
757 if err != nil {
758 return nil, nil, nil, fmt.Errorf("generating changeset for branch %q: %w", branch.Name, err)
759 }
760
761 for i, c := range changes {
762 oldFile, newFile, err := c.Files()
763 if err != nil {
764 return nil, nil, nil, fmt.Errorf("change #%d: getting files before and after change: %w", i, err)
765 }
766
767 if newFile != nil {
768 // note: newFile.Name could be a path that isn't relative to the repository root - using the
769 // change's Name field is the only way that @ggilmore saw to get the full path relative to the root
770 newFileRelativeRootPath := c.To.Name
771
772 // TODO@ggilmore: HACK - remove once ignore files are supported in delta builds
773 if newFileRelativeRootPath == ignore.IgnoreFile {
774 return nil, nil, nil, fmt.Errorf("%q file is not yet supported in delta builds", ignore.IgnoreFile)
775 }
776
777 // either file is added or renamed, so we need to add the new version to the build
778 file := fileKey{Path: newFileRelativeRootPath, ID: newFile.Hash}
779 if existing, ok := repos[file]; ok {
780 existing.Branches = append(existing.Branches, branch.Name)
781 repos[file] = existing
782 } else {
783 repos[file] = BlobLocation{
784 GitRepo: repository,
785 URL: u,
786 Branches: []string{branch.Name},
787 }
788 }
789 }
790
791 if oldFile == nil {
792 // file added - nothing more to do
793 continue
794 }
795
796 // Note: oldFile.Name could be a path that isn't relative to the repository root - using the
797 // change's "Name" field is the only way that ggilmore saw to get the full path relative to the root
798 oldFileRelativeRootPath := c.From.Name
799
800 if oldFileRelativeRootPath == ignore.IgnoreFile {
801 return nil, nil, nil, fmt.Errorf("%q file is not yet supported in delta builds", ignore.IgnoreFile)
802 }
803
804 // The file is either modified or deleted. So, we need to add ALL versions
805 // of the old file (across all branches) to the build.
806 for b, currentTree := range branchToCurrentTree {
807 f, err := currentTree.File(oldFileRelativeRootPath)
808 if err != nil {
809 // the file doesn't exist in this branch
810 if errors.Is(err, object.ErrFileNotFound) {
811 continue
812 }
813
814 return nil, nil, nil, fmt.Errorf("getting hash for file %q in branch %q: %w", oldFile.Name, b, err)
815 }
816
817 file := fileKey{Path: oldFileRelativeRootPath, ID: f.ID()}
818 if existing, ok := repos[file]; ok {
819 existing.Branches = append(existing.Branches, b)
820 repos[file] = existing
821 } else {
822 repos[file] = BlobLocation{
823 GitRepo: repository,
824 URL: u,
825 Branches: []string{b},
826 }
827 }
828 }
829
830 changedOrDeletedPaths = append(changedOrDeletedPaths, oldFileRelativeRootPath)
831 }
832 }
833
834 // we need to de-duplicate the branch map before returning it - it's possible for the same
835 // branch to have been added multiple times if a file has been modified across multiple commits
836 for _, info := range repos {
837 sort.Strings(info.Branches)
838 info.Branches = uniq(info.Branches)
839 }
840
841 // we also need to de-duplicate the list of changed or deleted file paths, it's also possible to have duplicates
842 // for the same reasoning as above
843 sort.Strings(changedOrDeletedPaths)
844 changedOrDeletedPaths = uniq(changedOrDeletedPaths)
845
846 return repos, nil, changedOrDeletedPaths, nil
847}
848
849func prepareNormalBuild(options Options, repository *git.Repository) (repos map[fileKey]BlobLocation, branchVersions map[string]map[string]plumbing.Hash, err error) {
850 var repoCache *RepoCache
851 if options.Submodules {
852 repoCache = NewRepoCache(options.RepoCacheDir)
853 }
854
855 // Branch => Repo => SHA1
856 branchVersions = map[string]map[string]plumbing.Hash{}
857
858 branches, err := expandBranches(repository, options.Branches, options.BranchPrefix)
859 if err != nil {
860 return nil, nil, fmt.Errorf("expandBranches: %w", err)
861 }
862
863 rw := NewRepoWalker(repository, options.BuildOptions.RepositoryDescription.URL, repoCache)
864 for _, b := range branches {
865 commit, err := getCommit(repository, options.BranchPrefix, b)
866 if err != nil {
867 if options.AllowMissingBranch && err.Error() == "reference not found" {
868 continue
869 }
870
871 return nil, nil, fmt.Errorf("getCommit: %w", err)
872 }
873
874 tree, err := commit.Tree()
875 if err != nil {
876 return nil, nil, fmt.Errorf("commit.Tree: %w", err)
877 }
878
879 ig, err := newIgnoreMatcher(tree)
880 if err != nil {
881 return nil, nil, fmt.Errorf("newIgnoreMatcher: %w", err)
882 }
883
884 subVersions, err := rw.CollectFiles(tree, b, ig)
885 if err != nil {
886 return nil, nil, fmt.Errorf("CollectFiles: %w", err)
887 }
888
889 branchVersions[b] = subVersions
890 }
891
892 return rw.Files, branchVersions, nil
893}
894
895func createDocument(key fileKey,
896 repos map[fileKey]BlobLocation,
897 opts build.Options,
898) (zoekt.Document, error) {
899 repo := repos[key]
900 blob, err := repo.GitRepo.BlobObject(key.ID)
901 branches := repos[key].Branches
902
903 // We filter out large documents when fetching the repo. So if an object is too large, it will not be found.
904 if errors.Is(err, plumbing.ErrObjectNotFound) {
905 return skippedLargeDoc(key, branches, opts), nil
906 }
907
908 if err != nil {
909 return zoekt.Document{}, err
910 }
911
912 keyFullPath := key.FullPath()
913 if blob.Size > int64(opts.SizeMax) && !opts.IgnoreSizeMax(keyFullPath) {
914 return skippedLargeDoc(key, branches, opts), nil
915 }
916
917 contents, err := blobContents(blob)
918 if err != nil {
919 return zoekt.Document{}, err
920 }
921
922 return zoekt.Document{
923 SubRepositoryPath: key.SubRepoPath,
924 Name: keyFullPath,
925 Content: contents,
926 Branches: branches,
927 }, nil
928}
929
930func skippedLargeDoc(key fileKey, branches []string, opts build.Options) zoekt.Document {
931 return zoekt.Document{
932 SkipReason: fmt.Sprintf("file size exceeds maximum size %d", opts.SizeMax),
933 Name: key.FullPath(),
934 Branches: branches,
935 SubRepositoryPath: key.SubRepoPath,
936 }
937}
938
939func blobContents(blob *object.Blob) ([]byte, error) {
940 r, err := blob.Reader()
941 if err != nil {
942 return nil, err
943 }
944 defer r.Close()
945
946 var buf bytes.Buffer
947 buf.Grow(int(blob.Size))
948 _, err = buf.ReadFrom(r)
949 if err != nil {
950 return nil, err
951 }
952 return buf.Bytes(), nil
953}
954
955func uniq(ss []string) []string {
956 result := ss[:0]
957 var last string
958 for i, s := range ss {
959 if i == 0 || s != last {
960 result = append(result, s)
961 }
962 last = s
963 }
964 return result
965}