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 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 desc.TenantID, _ = strconv.Atoi(sec.Options.Get("tenantID"))
252
253 if desc.RawConfig == nil {
254 desc.RawConfig = map[string]string{}
255 }
256 for _, o := range sec.Options {
257 desc.RawConfig[o.Key] = o.Value
258 }
259
260 // Ranking info.
261
262 // Github:
263 traction := 0
264 for _, s := range []string{"github-stars", "github-forks", "github-watchers", "github-subscribers"} {
265 f, err := strconv.Atoi(sec.Options.Get(s))
266 if err == nil {
267 traction += f
268 }
269 }
270
271 if strings.Contains(desc.Name, "googlesource.com/") && traction == 0 {
272 // Pretend everything on googlesource.com has 1000
273 // github stars.
274 traction = 1000
275 }
276
277 if traction > 0 {
278 l := math.Log(float64(traction))
279 desc.Rank = uint16((1.0 - 1.0/math.Pow(1+l, 0.6)) * 10000)
280 }
281
282 return nil
283}
284
285// SetTemplatesFromOrigin fills in templates based on the origin URL.
286func SetTemplatesFromOrigin(desc *zoekt.Repository, u *url.URL) error {
287 desc.Name = filepath.Join(u.Host, strings.TrimSuffix(u.Path, ".git"))
288
289 if strings.HasSuffix(u.Host, ".googlesource.com") {
290 return setTemplates(desc, u, "gitiles")
291 } else if u.Host == "github.com" {
292 u.Path = strings.TrimSuffix(u.Path, ".git")
293 return setTemplates(desc, u, "github")
294 } else {
295 return fmt.Errorf("unknown git hosting site %q", u)
296 }
297}
298
299// The Options structs controls details of the indexing process.
300type Options struct {
301 // The repository to be indexed.
302 RepoDir string
303
304 // If set, follow submodule links. This requires RepoCacheDir to be set.
305 Submodules bool
306
307 // If set, skip indexing if the existing index shard is newer
308 // than the refs in the repository.
309 Incremental bool
310
311 // Don't error out if some branch is missing
312 AllowMissingBranch bool
313
314 // Specifies the root of a Repository cache. Needed for submodule indexing.
315 RepoCacheDir string
316
317 // Indexing options.
318 BuildOptions index.Options
319
320 // Prefix of the branch to index, e.g. `remotes/origin`.
321 BranchPrefix string
322
323 // List of branch names to index, e.g. []string{"HEAD", "stable"}
324 Branches []string
325
326 // DeltaShardNumberFallbackThreshold defines an upper limit (inclusive) on the number of preexisting shards
327 // that can exist before attempting another delta build. If the number of preexisting shards exceeds this threshold,
328 // then a normal build will be performed instead.
329 //
330 // If DeltaShardNumberFallbackThreshold is 0, then this fallback behavior is disabled:
331 // a delta build will always be performed regardless of the number of preexisting shards.
332 DeltaShardNumberFallbackThreshold uint64
333}
334
335func expandBranches(repo *git.Repository, bs []string, prefix string) ([]string, error) {
336 var result []string
337 for _, b := range bs {
338 // Sourcegraph: We disable resolving refs. We want to return the exact ref
339 // requested so we can match it up.
340 if b == "HEAD" && false {
341 ref, err := repo.Head()
342 if err != nil {
343 return nil, err
344 }
345
346 result = append(result, strings.TrimPrefix(ref.Name().String(), prefix))
347 continue
348 }
349
350 if strings.Contains(b, "*") {
351 iter, err := repo.Branches()
352 if err != nil {
353 return nil, err
354 }
355
356 defer iter.Close()
357 for {
358 ref, err := iter.Next()
359 if err == io.EOF {
360 break
361 }
362 if err != nil {
363 return nil, err
364 }
365
366 name := ref.Name().Short()
367 if matched, err := filepath.Match(b, name); err != nil {
368 return nil, err
369 } else if !matched {
370 continue
371 }
372
373 result = append(result, strings.TrimPrefix(name, prefix))
374 }
375 continue
376 }
377
378 result = append(result, b)
379 }
380
381 return result, nil
382}
383
384// IndexGitRepo indexes the git repository as specified by the options.
385// The returned bool indicates whether the index was updated as a result. This
386// can be informative if doing incremental indexing.
387func IndexGitRepo(opts Options) (bool, error) {
388 return indexGitRepo(opts, gitIndexConfig{})
389}
390
391// indexGitRepo indexes the git repository as specified by the options and the provided gitIndexConfig.
392// The returned bool indicates whether the index was updated as a result. This
393// can be informative if doing incremental indexing.
394func indexGitRepo(opts Options, config gitIndexConfig) (bool, error) {
395 prepareDeltaBuild := prepareDeltaBuild
396 if config.prepareDeltaBuild != nil {
397 prepareDeltaBuild = config.prepareDeltaBuild
398 }
399
400 prepareNormalBuild := prepareNormalBuild
401 if config.prepareNormalBuild != nil {
402 prepareNormalBuild = config.prepareNormalBuild
403 }
404
405 // Set max thresholds, since we use them in this function.
406 opts.BuildOptions.SetDefaults()
407 if opts.RepoDir == "" {
408 return false, fmt.Errorf("gitindex: must set RepoDir")
409 }
410
411 opts.BuildOptions.RepositoryDescription.Source = opts.RepoDir
412
413 var repo *git.Repository
414 legacyRepoOpen := cmp.Or(os.Getenv("ZOEKT_DISABLE_GOGIT_OPTIMIZATION"), "false")
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 := index.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 })
592
593 // Because we're keeping descriptors open, we need to close the storage object when we're done.
594 repo, err := git.Open(s, fs)
595 return repo, s, err
596}
597
598func newIgnoreMatcher(tree *object.Tree) (*ignore.Matcher, error) {
599 ignoreFile, err := tree.File(ignore.IgnoreFile)
600 if err == object.ErrFileNotFound {
601 return &ignore.Matcher{}, nil
602 }
603 if err != nil {
604 return nil, err
605 }
606 content, err := ignoreFile.Contents()
607 if err != nil {
608 return nil, err
609 }
610 return ignore.ParseIgnoreFile(strings.NewReader(content))
611}
612
613// prepareDeltaBuildFunc is a function that calculates the necessary metadata for preparing
614// a build.Builder instance for generating a delta build.
615type prepareDeltaBuildFunc func(options Options, repository *git.Repository) (repos map[fileKey]BlobLocation, branchVersions map[string]map[string]plumbing.Hash, changedOrDeletedPaths []string, err error)
616
617// prepareNormalBuildFunc is a function that calculates the necessary metadata for preparing
618// a build.Builder instance for generating a normal build.
619type prepareNormalBuildFunc func(options Options, repository *git.Repository) (repos map[fileKey]BlobLocation, branchVersions map[string]map[string]plumbing.Hash, err error)
620
621type gitIndexConfig struct {
622 // prepareDeltaBuild, if not nil, is the function that is used to calculate the metadata that will be used to
623 // prepare the build.Builder instance for generating a delta build.
624 //
625 // If prepareDeltaBuild is nil, gitindex.prepareDeltaBuild will be used instead.
626 prepareDeltaBuild prepareDeltaBuildFunc
627
628 // prepareNormalBuild, if not nil, is the function that is used to calculate the metadata that will be used to
629 // prepare the build.Builder instance for generating a normal build.
630 //
631 // If prepareNormalBuild is nil, gitindex.prepareNormalBuild will be used instead.
632 prepareNormalBuild prepareNormalBuildFunc
633}
634
635func prepareDeltaBuild(options Options, repository *git.Repository) (repos map[fileKey]BlobLocation, branchVersions map[string]map[string]plumbing.Hash, changedOrDeletedPaths []string, err error) {
636 if options.Submodules {
637 return nil, nil, nil, fmt.Errorf("delta builds currently don't support submodule indexing")
638 }
639
640 // discover what commits we indexed during our last build
641 existingRepository, _, ok, err := options.BuildOptions.FindRepositoryMetadata()
642 if err != nil {
643 return nil, nil, nil, fmt.Errorf("failed to get repository metadata: %w", err)
644 }
645
646 if !ok {
647 return nil, nil, nil, fmt.Errorf("no existing shards found for repository")
648 }
649
650 if options.DeltaShardNumberFallbackThreshold > 0 {
651 // HACK: For our interim compaction strategy, we force a full normal index once
652 // the number of shards on disk for this repository exceeds the provided threshold.
653 //
654 // This strategy obviously isn't optimal (as an example: we currently can't differentiate
655 // between "normal" and "delta" shards, so repositories like the gigarepo that generate a large number of shards per
656 // build would be disproportionately affected by this), but it'll allow us to continue experimenting on real workloads
657 // while we create a better compaction strategy).
658
659 oldShards := options.BuildOptions.FindAllShards()
660 if uint64(len(oldShards)) > options.DeltaShardNumberFallbackThreshold {
661 return nil, nil, nil, fmt.Errorf("number of existing shards (%d) > requested shard threshold (%d)", len(oldShards), options.DeltaShardNumberFallbackThreshold)
662 }
663 }
664
665 // Check to see if the set of branch names is consistent with what we last indexed.
666 // If it isn't consistent, that we can't proceed with a delta build (and the caller should fall back to a
667 // normal one).
668
669 if !index.BranchNamesEqual(existingRepository.Branches, options.BuildOptions.RepositoryDescription.Branches) {
670 var existingBranchNames []string
671 for _, b := range existingRepository.Branches {
672 existingBranchNames = append(existingBranchNames, b.Name)
673 }
674
675 var optionsBranchNames []string
676 for _, b := range options.BuildOptions.RepositoryDescription.Branches {
677 optionsBranchNames = append(optionsBranchNames, b.Name)
678 }
679
680 existingBranchList := strings.Join(existingBranchNames, ", ")
681 optionsBranchList := strings.Join(optionsBranchNames, ", ")
682
683 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)
684 }
685
686 // Check if the build options hash does not match the repository metadata's hash
687 // If it does not index then one or more index options has changed and will require a normal build instead of a delta build
688 if options.BuildOptions.GetHash() != existingRepository.IndexOptions {
689 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())
690 }
691
692 // branch => (path, sha1) => repo.
693 repos = map[fileKey]BlobLocation{}
694
695 branches, err := expandBranches(repository, options.Branches, options.BranchPrefix)
696 if err != nil {
697 return nil, nil, nil, fmt.Errorf("expandBranches: %w", err)
698 }
699
700 // branch name -> git worktree at most current commit
701 branchToCurrentTree := make(map[string]*object.Tree, len(branches))
702
703 for _, b := range branches {
704 commit, err := getCommit(repository, options.BranchPrefix, b)
705 if err != nil {
706 return nil, nil, nil, fmt.Errorf("getting last current commit for branch %q: %w", b, err)
707 }
708
709 tree, err := commit.Tree()
710 if err != nil {
711 return nil, nil, nil, fmt.Errorf("getting current git tree for branch %q: %w", b, err)
712 }
713
714 branchToCurrentTree[b] = tree
715 }
716
717 rawURL := options.BuildOptions.RepositoryDescription.URL
718 u, err := url.Parse(rawURL)
719 if err != nil {
720 return nil, nil, nil, fmt.Errorf("parsing repository URL %q: %w", rawURL, err)
721 }
722
723 // TODO: Support repository submodules for delta builds
724
725 // loop over all branches, calculate the diff between our
726 // last indexed commit and the current commit, and add files mentioned in the diff
727 for _, branch := range existingRepository.Branches {
728 lastIndexedCommit, err := getCommit(repository, "", branch.Version)
729 if err != nil {
730 return nil, nil, nil, fmt.Errorf("getting last indexed commit for branch %q: %w", branch.Name, err)
731 }
732
733 lastIndexedTree, err := lastIndexedCommit.Tree()
734 if err != nil {
735 return nil, nil, nil, fmt.Errorf("getting lasted indexed git tree for branch %q: %w", branch.Name, err)
736 }
737
738 changes, err := object.DiffTreeWithOptions(context.Background(), lastIndexedTree, branchToCurrentTree[branch.Name], &object.DiffTreeOptions{DetectRenames: false})
739 if err != nil {
740 return nil, nil, nil, fmt.Errorf("generating changeset for branch %q: %w", branch.Name, err)
741 }
742
743 for i, c := range changes {
744 oldFile, newFile, err := c.Files()
745 if err != nil {
746 return nil, nil, nil, fmt.Errorf("change #%d: getting files before and after change: %w", i, err)
747 }
748
749 if newFile != nil {
750 // note: newFile.Name could be a path that isn't relative to the repository root - using the
751 // change's Name field is the only way that @ggilmore saw to get the full path relative to the root
752 newFileRelativeRootPath := c.To.Name
753
754 // TODO@ggilmore: HACK - remove once ignore files are supported in delta builds
755 if newFileRelativeRootPath == ignore.IgnoreFile {
756 return nil, nil, nil, fmt.Errorf("%q file is not yet supported in delta builds", ignore.IgnoreFile)
757 }
758
759 // either file is added or renamed, so we need to add the new version to the build
760 file := fileKey{Path: newFileRelativeRootPath, ID: newFile.Hash}
761 if existing, ok := repos[file]; ok {
762 existing.Branches = append(existing.Branches, branch.Name)
763 repos[file] = existing
764 } else {
765 repos[file] = BlobLocation{
766 GitRepo: repository,
767 URL: u,
768 Branches: []string{branch.Name},
769 }
770 }
771 }
772
773 if oldFile == nil {
774 // file added - nothing more to do
775 continue
776 }
777
778 // Note: oldFile.Name could be a path that isn't relative to the repository root - using the
779 // change's "Name" field is the only way that ggilmore saw to get the full path relative to the root
780 oldFileRelativeRootPath := c.From.Name
781
782 if oldFileRelativeRootPath == ignore.IgnoreFile {
783 return nil, nil, nil, fmt.Errorf("%q file is not yet supported in delta builds", ignore.IgnoreFile)
784 }
785
786 // The file is either modified or deleted. So, we need to add ALL versions
787 // of the old file (across all branches) to the build.
788 for b, currentTree := range branchToCurrentTree {
789 f, err := currentTree.File(oldFileRelativeRootPath)
790 if err != nil {
791 // the file doesn't exist in this branch
792 if errors.Is(err, object.ErrFileNotFound) {
793 continue
794 }
795
796 return nil, nil, nil, fmt.Errorf("getting hash for file %q in branch %q: %w", oldFile.Name, b, err)
797 }
798
799 file := fileKey{Path: oldFileRelativeRootPath, ID: f.ID()}
800 if existing, ok := repos[file]; ok {
801 existing.Branches = append(existing.Branches, b)
802 repos[file] = existing
803 } else {
804 repos[file] = BlobLocation{
805 GitRepo: repository,
806 URL: u,
807 Branches: []string{b},
808 }
809 }
810 }
811
812 changedOrDeletedPaths = append(changedOrDeletedPaths, oldFileRelativeRootPath)
813 }
814 }
815
816 // we need to de-duplicate the branch map before returning it - it's possible for the same
817 // branch to have been added multiple times if a file has been modified across multiple commits
818 for _, info := range repos {
819 sort.Strings(info.Branches)
820 info.Branches = uniq(info.Branches)
821 }
822
823 // we also need to de-duplicate the list of changed or deleted file paths, it's also possible to have duplicates
824 // for the same reasoning as above
825 sort.Strings(changedOrDeletedPaths)
826 changedOrDeletedPaths = uniq(changedOrDeletedPaths)
827
828 return repos, nil, changedOrDeletedPaths, nil
829}
830
831func prepareNormalBuild(options Options, repository *git.Repository) (repos map[fileKey]BlobLocation, branchVersions map[string]map[string]plumbing.Hash, err error) {
832 var repoCache *RepoCache
833 if options.Submodules {
834 repoCache = NewRepoCache(options.RepoCacheDir)
835 }
836
837 // Branch => Repo => SHA1
838 branchVersions = map[string]map[string]plumbing.Hash{}
839
840 branches, err := expandBranches(repository, options.Branches, options.BranchPrefix)
841 if err != nil {
842 return nil, nil, fmt.Errorf("expandBranches: %w", err)
843 }
844
845 rw := NewRepoWalker(repository, options.BuildOptions.RepositoryDescription.URL, repoCache)
846 for _, b := range branches {
847 commit, err := getCommit(repository, options.BranchPrefix, b)
848 if err != nil {
849 if options.AllowMissingBranch && err.Error() == "reference not found" {
850 continue
851 }
852
853 return nil, nil, fmt.Errorf("getCommit: %w", err)
854 }
855
856 tree, err := commit.Tree()
857 if err != nil {
858 return nil, nil, fmt.Errorf("commit.Tree: %w", err)
859 }
860
861 ig, err := newIgnoreMatcher(tree)
862 if err != nil {
863 return nil, nil, fmt.Errorf("newIgnoreMatcher: %w", err)
864 }
865
866 subVersions, err := rw.CollectFiles(tree, b, ig)
867 if err != nil {
868 return nil, nil, fmt.Errorf("CollectFiles: %w", err)
869 }
870
871 branchVersions[b] = subVersions
872 }
873
874 return rw.Files, branchVersions, nil
875}
876
877func createDocument(key fileKey,
878 repos map[fileKey]BlobLocation,
879 opts index.Options,
880) (index.Document, error) {
881 repo := repos[key]
882 blob, err := repo.GitRepo.BlobObject(key.ID)
883 branches := repos[key].Branches
884
885 // We filter out large documents when fetching the repo. So if an object is too large, it will not be found.
886 if errors.Is(err, plumbing.ErrObjectNotFound) {
887 return skippedLargeDoc(key, branches), nil
888 }
889
890 if err != nil {
891 return index.Document{}, err
892 }
893
894 keyFullPath := key.FullPath()
895 if blob.Size > int64(opts.SizeMax) && !opts.IgnoreSizeMax(keyFullPath) {
896 return skippedLargeDoc(key, branches), nil
897 }
898
899 contents, err := blobContents(blob)
900 if err != nil {
901 return index.Document{}, err
902 }
903
904 return index.Document{
905 SubRepositoryPath: key.SubRepoPath,
906 Name: keyFullPath,
907 Content: contents,
908 Branches: branches,
909 }, nil
910}
911
912func skippedLargeDoc(key fileKey, branches []string) index.Document {
913 return index.Document{
914 SkipReason: index.SkipReasonTooLarge,
915 Name: key.FullPath(),
916 Branches: branches,
917 SubRepositoryPath: key.SubRepoPath,
918 }
919}
920
921func blobContents(blob *object.Blob) ([]byte, error) {
922 r, err := blob.Reader()
923 if err != nil {
924 return nil, err
925 }
926 defer r.Close()
927
928 var buf bytes.Buffer
929 buf.Grow(int(blob.Size))
930 _, err = buf.ReadFrom(r)
931 if err != nil {
932 return nil, err
933 }
934 return buf.Bytes(), nil
935}
936
937func uniq(ss []string) []string {
938 result := ss[:0]
939 var last string
940 for i, s := range ss {
941 if i == 0 || s != last {
942 result = append(result, s)
943 }
944 last = s
945 }
946 return result
947}