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 "context"
21 "encoding/json"
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 "time"
35
36 "github.com/sourcegraph/zoekt"
37 "github.com/sourcegraph/zoekt/build"
38 "github.com/sourcegraph/zoekt/ignore"
39
40 "github.com/go-git/go-git/v5/config"
41 "github.com/go-git/go-git/v5/plumbing"
42 "github.com/go-git/go-git/v5/plumbing/object"
43
44 git "github.com/go-git/go-git/v5"
45)
46
47// RepoModTime returns the time of last fetch of a git repository.
48func RepoModTime(dir string) (time.Time, error) {
49 var last time.Time
50 refDir := filepath.Join(dir, "refs")
51 if _, err := os.Lstat(refDir); err == nil {
52 if err := filepath.Walk(refDir,
53 func(_ string, fi os.FileInfo, _ error) error {
54 if !fi.IsDir() && last.Before(fi.ModTime()) {
55 last = fi.ModTime()
56 }
57 return nil
58 }); err != nil {
59 return last, err
60 }
61 }
62
63 // git gc compresses refs into the following file:
64 for _, fn := range []string{"info/refs", "packed-refs"} {
65 if fi, err := os.Lstat(filepath.Join(dir, fn)); err == nil && !fi.IsDir() && last.Before(fi.ModTime()) {
66 last = fi.ModTime()
67 }
68 }
69
70 return last, nil
71}
72
73// FindGitRepos finds directories holding git repositories below the
74// given directory. It will find both bare and the ".git" dirs in
75// non-bare repositories. It returns the full path including the dir
76// passed in.
77func FindGitRepos(dir string) ([]string, error) {
78 arg, err := filepath.Abs(dir)
79 if err != nil {
80 return nil, err
81 }
82 var dirs []string
83 if err := filepath.Walk(arg, func(name string, fi os.FileInfo, err error) error {
84 // Best-effort, ignore filepath.Walk failing
85 if err != nil {
86 return nil
87 }
88
89 if fi, err := os.Lstat(filepath.Join(name, ".git")); err == nil && fi.IsDir() {
90 dirs = append(dirs, filepath.Join(name, ".git"))
91 return filepath.SkipDir
92 }
93
94 if !strings.HasSuffix(name, ".git") || !fi.IsDir() {
95 return nil
96 }
97
98 fi, err = os.Lstat(filepath.Join(name, "objects"))
99 if err != nil || !fi.IsDir() {
100 return nil
101 }
102
103 dirs = append(dirs, name)
104 return filepath.SkipDir
105 }); err != nil {
106 return nil, err
107 }
108
109 return dirs, nil
110}
111
112// setTemplates fills in URL templates for known git hosting
113// sites.
114func setTemplates(repo *zoekt.Repository, u *url.URL, typ string) error {
115 if u.Scheme == "ssh+git" {
116 u.Scheme = "https"
117 u.User = nil
118 }
119
120 repo.URL = u.String()
121 switch typ {
122 case "gitiles":
123 // eg. https://gerrit.googlesource.com/gitiles/+/master/tools/run_dev.sh#20
124 repo.CommitURLTemplate = u.String() + "/+/{{.Version}}"
125 repo.FileURLTemplate = u.String() + "/+/{{.Version}}/{{.Path}}"
126 repo.LineFragmentTemplate = "#{{.LineNumber}}"
127 case "github":
128 // eg. https://github.com/hanwen/go-fuse/blob/notify/genversion.sh#L10
129 repo.CommitURLTemplate = u.String() + "/commit/{{.Version}}"
130 repo.FileURLTemplate = u.String() + "/blob/{{.Version}}/{{.Path}}"
131 repo.LineFragmentTemplate = "#L{{.LineNumber}}"
132 case "cgit":
133 // http://git.savannah.gnu.org/cgit/lilypond.git/tree/elisp/lilypond-mode.el?h=dev/philh&id=b2ca0fefe3018477aaca23b6f672c7199ba5238e#n100
134 repo.CommitURLTemplate = u.String() + "/commit/?id={{.Version}}"
135 repo.FileURLTemplate = u.String() + "/tree/{{.Path}}/?id={{.Version}}"
136 repo.LineFragmentTemplate = "#n{{.LineNumber}}"
137 case "gitweb":
138 // https://gerrit.libreoffice.org/gitweb?p=online.git;a=blob;f=Makefile.am;h=cfcfd7c36fbae10e269653dc57a9b68c92d4c10b;hb=848145503bf7b98ce4a4aa0a858a0d71dd0dbb26#l10
139 repo.FileURLTemplate = u.String() + ";a=blob;f={{.Path}};hb={{.Version}}"
140 repo.CommitURLTemplate = u.String() + ";a=commit;h={{.Version}}"
141 repo.LineFragmentTemplate = "#l{{.LineNumber}}"
142 case "source.bazel.build":
143 // https://source.bazel.build/bazel/+/57bc201346e61c62a921c1cbf32ad24f185c10c9
144 // https://source.bazel.build/bazel/+/57bc201346e61c62a921c1cbf32ad24f185c10c9:tools/cpp/BUILD.empty;l=10
145 repo.CommitURLTemplate = u.String() + "/+/{{.Version}}"
146 repo.FileURLTemplate = u.String() + "/+/{{.Version}}:{{.Path}}"
147 repo.LineFragmentTemplate = ";l={{.LineNumber}}"
148 case "bitbucket-server":
149 // https://<bitbucketserver-host>/projects/<project>/repos/<repo>/commits/5be7ca73b898bf17a08e607918accfdeafe1e0bc
150 // https://<bitbucketserver-host>/projects/<project>/repos/<repo>/browse/<file>?at=5be7ca73b898bf17a08e607918accfdeafe1e0bc
151 repo.CommitURLTemplate = u.String() + "/commits/{{.Version}}"
152 repo.FileURLTemplate = u.String() + "/{{.Path}}?at={{.Version}}"
153 repo.LineFragmentTemplate = "#{{.LineNumber}}"
154 case "gitlab":
155 // https://gitlab.com/gitlab-org/omnibus-gitlab/-/commit/b152c864303dae0e55377a1e2c53c9592380ffed
156 // https://gitlab.com/gitlab-org/omnibus-gitlab/-/blob/aad04155b3f6fc50ede88aedaee7fc624d481149/files/gitlab-config-template/gitlab.rb.template
157 repo.CommitURLTemplate = u.String() + "/-/commit/{{.Version}}"
158 repo.FileURLTemplate = u.String() + "/-/blob/{{.Version}}/{{.Path}}"
159 repo.LineFragmentTemplate = "#L{{.LineNumber}}"
160 case "gitea":
161 repo.CommitURLTemplate = u.String() + "/commit/{{.Version}}"
162 // NOTE The `display=source` query parameter is required to disable file rendering.
163 // Since line numbers are disabled in rendered files, you wouldn't be able to jump to
164 // a line without `display=source`. This is supported since gitea 1.17.0.
165 // When /src/{{.Version}} is used it will redirect to /src/commit/{{.Version}},
166 // but the query parameters are obmitted.
167 repo.FileURLTemplate = u.String() + "/src/commit/{{.Version}}/{{.Path}}?display=source"
168 repo.LineFragmentTemplate = "#L{{.LineNumber}}"
169 default:
170 return fmt.Errorf("URL scheme type %q unknown", typ)
171 }
172 return nil
173}
174
175// getCommit returns a tree object for the given reference.
176func getCommit(repo *git.Repository, prefix, ref string) (*object.Commit, error) {
177 sha1, err := repo.ResolveRevision(plumbing.Revision(ref))
178 // ref might be a branch name (e.g. "master") add branch prefix and try again.
179 if err != nil {
180 sha1, err = repo.ResolveRevision(plumbing.Revision(filepath.Join(prefix, ref)))
181 }
182 if err != nil {
183 return nil, err
184 }
185
186 commitObj, err := repo.CommitObject(*sha1)
187 if err != nil {
188 return nil, err
189 }
190 return commitObj, nil
191}
192
193func configLookupRemoteURL(cfg *config.Config, key string) string {
194 rc := cfg.Remotes[key]
195 if rc == nil || len(rc.URLs) == 0 {
196 return ""
197 }
198 return rc.URLs[0]
199}
200
201var sshRelativeURLRegexp = regexp.MustCompile(`^([^@]+)@([^:]+):(.*)$`)
202
203func setTemplatesFromConfig(desc *zoekt.Repository, repoDir string) error {
204 repo, err := git.PlainOpen(repoDir)
205 if err != nil {
206 return err
207 }
208
209 cfg, err := repo.Config()
210 if err != nil {
211 return err
212 }
213
214 sec := cfg.Raw.Section("zoekt")
215
216 webURLStr := sec.Options.Get("web-url")
217 webURLType := sec.Options.Get("web-url-type")
218
219 if webURLType != "" && webURLStr != "" {
220 webURL, err := url.Parse(webURLStr)
221 if err != nil {
222 return err
223 }
224 if err := setTemplates(desc, webURL, webURLType); err != nil {
225 return err
226 }
227 } else if webURLStr != "" {
228 desc.URL = webURLStr
229 }
230
231 name := sec.Options.Get("name")
232 if name != "" {
233 desc.Name = name
234 } else {
235 remoteURL := configLookupRemoteURL(cfg, "origin")
236 if remoteURL == "" {
237 return nil
238 }
239 if sm := sshRelativeURLRegexp.FindStringSubmatch(remoteURL); sm != nil {
240 user := sm[1]
241 host := sm[2]
242 path := sm[3]
243
244 remoteURL = fmt.Sprintf("ssh+git://%s@%s/%s", user, host, path)
245 }
246
247 u, err := url.Parse(remoteURL)
248 if err != nil {
249 return err
250 }
251 if err := SetTemplatesFromOrigin(desc, u); err != nil {
252 return err
253 }
254 }
255
256 id, _ := strconv.ParseUint(sec.Options.Get("repoid"), 10, 32)
257 desc.ID = uint32(id)
258
259 if desc.RawConfig == nil {
260 desc.RawConfig = map[string]string{}
261 }
262 for _, o := range sec.Options {
263 desc.RawConfig[o.Key] = o.Value
264 }
265
266 // Ranking info.
267
268 // Github:
269 traction := 0
270 for _, s := range []string{"github-stars", "github-forks", "github-watchers", "github-subscribers"} {
271 f, err := strconv.Atoi(sec.Options.Get(s))
272 if err == nil {
273 traction += f
274 }
275 }
276
277 if strings.Contains(desc.Name, "googlesource.com/") && traction == 0 {
278 // Pretend everything on googlesource.com has 1000
279 // github stars.
280 traction = 1000
281 }
282
283 if traction > 0 {
284 l := math.Log(float64(traction))
285 desc.Rank = uint16((1.0 - 1.0/math.Pow(1+l, 0.6)) * 10000)
286 }
287
288 return nil
289}
290
291// SetTemplatesFromOrigin fills in templates based on the origin URL.
292func SetTemplatesFromOrigin(desc *zoekt.Repository, u *url.URL) error {
293 desc.Name = filepath.Join(u.Host, strings.TrimSuffix(u.Path, ".git"))
294
295 if strings.HasSuffix(u.Host, ".googlesource.com") {
296 return setTemplates(desc, u, "gitiles")
297 } else if u.Host == "github.com" {
298 u.Path = strings.TrimSuffix(u.Path, ".git")
299 return setTemplates(desc, u, "github")
300 } else {
301 return fmt.Errorf("unknown git hosting site %q", u)
302 }
303}
304
305// The Options structs controls details of the indexing process.
306type Options struct {
307 // The repository to be indexed.
308 RepoDir string
309
310 // If set, follow submodule links. This requires RepoCacheDir to be set.
311 Submodules bool
312
313 // If set, skip indexing if the existing index shard is newer
314 // than the refs in the repository.
315 Incremental bool
316
317 // Don't error out if some branch is missing
318 AllowMissingBranch bool
319
320 // Specifies the root of a Repository cache. Needed for submodule indexing.
321 RepoCacheDir string
322
323 // Indexing options.
324 BuildOptions build.Options
325
326 // Prefix of the branch to index, e.g. `remotes/origin`.
327 BranchPrefix string
328
329 // List of branch names to index, e.g. []string{"HEAD", "stable"}
330 Branches []string
331
332 // DeltaShardNumberFallbackThreshold defines an upper limit (inclusive) on the number of preexisting shards
333 // that can exist before attempting another delta build. If the number of preexisting shards exceeds this threshold,
334 // then a normal build will be performed instead.
335 //
336 // If DeltaShardNumberFallbackThreshold is 0, then this fallback behavior is disabled:
337 // a delta build will always be performed regardless of the number of preexisting shards.
338 DeltaShardNumberFallbackThreshold uint64
339}
340
341func expandBranches(repo *git.Repository, bs []string, prefix string) ([]string, error) {
342 var result []string
343 for _, b := range bs {
344 // Sourcegraph: We disable resolving refs. We want to return the exact ref
345 // requested so we can match it up.
346 if b == "HEAD" && false {
347 ref, err := repo.Head()
348 if err != nil {
349 return nil, err
350 }
351
352 result = append(result, strings.TrimPrefix(ref.Name().String(), prefix))
353 continue
354 }
355
356 if strings.Contains(b, "*") {
357 iter, err := repo.Branches()
358 if err != nil {
359 return nil, err
360 }
361
362 defer iter.Close()
363 for {
364 ref, err := iter.Next()
365 if err == io.EOF {
366 break
367 }
368 if err != nil {
369 return nil, err
370 }
371
372 name := ref.Name().Short()
373 if matched, err := filepath.Match(b, name); err != nil {
374 return nil, err
375 } else if !matched {
376 continue
377 }
378
379 result = append(result, strings.TrimPrefix(name, prefix))
380 }
381 continue
382 }
383
384 result = append(result, b)
385 }
386
387 return result, nil
388}
389
390// IndexGitRepo indexes the git repository as specified by the options.
391func IndexGitRepo(opts Options) error {
392 return indexGitRepo(opts, gitIndexConfig{})
393}
394
395// indexGitRepo indexes the git repository as specified by the options and the provided gitIndexConfig.
396func indexGitRepo(opts Options, config gitIndexConfig) error {
397 prepareDeltaBuild := prepareDeltaBuild
398 if config.prepareDeltaBuild != nil {
399 prepareDeltaBuild = config.prepareDeltaBuild
400 }
401
402 prepareNormalBuild := prepareNormalBuild
403 if config.prepareNormalBuild != nil {
404 prepareNormalBuild = config.prepareNormalBuild
405 }
406
407 // Set max thresholds, since we use them in this function.
408 opts.BuildOptions.SetDefaults()
409 if opts.RepoDir == "" {
410 return fmt.Errorf("gitindex: must set RepoDir")
411 }
412
413 opts.BuildOptions.RepositoryDescription.Source = opts.RepoDir
414 repo, err := git.PlainOpen(opts.RepoDir)
415 if err != nil {
416 return fmt.Errorf("git.PlainOpen: %w", err)
417 }
418
419 if err := setTemplatesFromConfig(&opts.BuildOptions.RepositoryDescription, opts.RepoDir); err != nil {
420 log.Printf("setTemplatesFromConfig(%s): %s", opts.RepoDir, err)
421 }
422
423 branches, err := expandBranches(repo, opts.Branches, opts.BranchPrefix)
424 if err != nil {
425 return fmt.Errorf("expandBranches: %w", err)
426 }
427 for _, b := range branches {
428 commit, err := getCommit(repo, opts.BranchPrefix, b)
429 if err != nil {
430 if opts.AllowMissingBranch && err.Error() == "reference not found" {
431 continue
432 }
433
434 return fmt.Errorf("getCommit(%q, %q): %w", opts.BranchPrefix, b, err)
435 }
436
437 opts.BuildOptions.RepositoryDescription.Branches = append(opts.BuildOptions.RepositoryDescription.Branches, zoekt.RepositoryBranch{
438 Name: b,
439 Version: commit.Hash.String(),
440 })
441
442 if when := commit.Committer.When; when.After(opts.BuildOptions.RepositoryDescription.LatestCommitDate) {
443 opts.BuildOptions.RepositoryDescription.LatestCommitDate = when
444 }
445 }
446
447 if opts.Incremental && opts.BuildOptions.IncrementalSkipIndexing() {
448 return nil
449 }
450
451 // branch => (path, sha1) => repo.
452 var repos map[fileKey]BlobLocation
453
454 // fileKey => branches
455 var branchMap map[fileKey][]string
456
457 // Branch => Repo => SHA1
458 var branchVersions map[string]map[string]plumbing.Hash
459
460 // set of file paths that have been changed or deleted since
461 // the last indexed commit
462 //
463 // These only have an effect on delta builds
464 var changedOrRemovedFiles []string
465
466 if opts.BuildOptions.IsDelta {
467 repos, branchMap, branchVersions, changedOrRemovedFiles, err = prepareDeltaBuild(opts, repo)
468 if err != nil {
469 log.Printf("delta build: falling back to normal build since delta build failed, repository=%q, err=%s", opts.BuildOptions.RepositoryDescription.Name, err)
470 opts.BuildOptions.IsDelta = false
471 }
472 }
473
474 if !opts.BuildOptions.IsDelta {
475 repos, branchMap, branchVersions, err = prepareNormalBuild(opts, repo)
476 if err != nil {
477 return fmt.Errorf("preparing normal build: %w", err)
478 }
479 }
480
481 reposByPath := map[string]BlobLocation{}
482 for key, location := range repos {
483 reposByPath[key.SubRepoPath] = location
484 }
485
486 opts.BuildOptions.SubRepositories = map[string]*zoekt.Repository{}
487 for path, location := range reposByPath {
488 tpl := opts.BuildOptions.RepositoryDescription
489 if path != "" {
490 tpl = zoekt.Repository{URL: location.URL.String()}
491 if err := SetTemplatesFromOrigin(&tpl, location.URL); err != nil {
492 log.Printf("setTemplatesFromOrigin(%s, %s): %s", path, location.URL, err)
493 }
494 }
495 opts.BuildOptions.SubRepositories[path] = &tpl
496 }
497
498 for _, br := range opts.BuildOptions.RepositoryDescription.Branches {
499 for path, repo := range opts.BuildOptions.SubRepositories {
500 id := branchVersions[br.Name][path]
501 repo.Branches = append(repo.Branches, zoekt.RepositoryBranch{
502 Name: br.Name,
503 Version: id.String(),
504 })
505 }
506 }
507
508 builder, err := build.NewBuilder(opts.BuildOptions)
509 if err != nil {
510 return fmt.Errorf("build.NewBuilder: %w", err)
511 }
512
513 var ranks repoPathRanks
514 var meanRank float64
515 if opts.BuildOptions.DocumentRanksPath != "" {
516 data, err := os.ReadFile(opts.BuildOptions.DocumentRanksPath)
517 if err != nil {
518 return err
519 }
520
521 err = json.Unmarshal(data, &ranks)
522 if err != nil {
523 return err
524 }
525
526 // Compute the mean rank for this repository. Note: we overwrite the rank
527 // mean that's stored in the document ranks file, since that currently
528 // represents a global mean rank across repos, which is not what we want.
529 numRanks := len(ranks.Paths)
530 if numRanks > 0 {
531 for _, rank := range ranks.Paths {
532 meanRank += rank
533 }
534 ranks.MeanRank = meanRank / float64(numRanks)
535 }
536 }
537
538 // we don't need to check error, since we either already have an error, or
539 // we returning the first call to builder.Finish.
540 defer builder.Finish() // nolint:errcheck
541
542 for _, f := range changedOrRemovedFiles {
543 builder.MarkFileAsChangedOrRemoved(f)
544 }
545
546 var names []string
547 fileKeys := map[string][]fileKey{}
548 totalFiles := 0
549
550 for key := range repos {
551 n := key.FullPath()
552 fileKeys[n] = append(fileKeys[n], key)
553 names = append(names, n)
554 totalFiles++
555 }
556
557 sort.Strings(names)
558 names = uniq(names)
559
560 log.Printf("attempting to index %d total files", totalFiles)
561 for _, name := range names {
562 keys := fileKeys[name]
563
564 for _, key := range keys {
565 doc, err := createDocument(key, repos, branchMap, ranks, opts.BuildOptions)
566 if err != nil {
567 return err
568 }
569
570 if err := builder.Add(doc); err != nil {
571 return fmt.Errorf("error adding document with name %s: %w", key.FullPath(), err)
572 }
573 }
574 }
575
576 return builder.Finish()
577}
578
579type repoPathRanks struct {
580 MeanRank float64 `json:"mean_reference_count"`
581 Paths map[string]float64 `json:"paths"`
582}
583
584// rank returns the rank for a given path. It uses these rules:
585// - If we have a concrete rank for this file, always use it
586// - If there's no rank, and it's a low priority file like a test, then use rank 0
587// - Otherwise use the mean rank of this repository, to avoid giving it a big disadvantage
588func (r repoPathRanks) rank(path string) float64 {
589 if rank, ok := r.Paths[path]; ok {
590 return rank
591 } else if build.IsLowPriority(path) {
592 return 0.0
593 } else {
594 return r.MeanRank
595 }
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, branchMap map[fileKey][]string, 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, branchMap map[fileKey][]string, 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, branchMap map[fileKey][]string, branchVersions map[string]map[string]plumbing.Hash, changedOrDeletedPaths []string, err error) {
636 if options.Submodules {
637 return nil, 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, nil, fmt.Errorf("failed to get repository metadata: %w", err)
644 }
645
646 if !ok {
647 return nil, 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, 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 !build.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, 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 match 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, 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 // fileKey => branches
696 branchMap = map[fileKey][]string{}
697
698 // branch name -> git worktree at most current commit
699 branchToCurrentTree := make(map[string]*object.Tree, len(options.Branches))
700
701 for _, b := range options.Branches {
702 commit, err := getCommit(repository, options.BranchPrefix, b)
703 if err != nil {
704 return nil, nil, nil, nil, fmt.Errorf("getting last current commit for branch %q: %w", b, err)
705 }
706
707 tree, err := commit.Tree()
708 if err != nil {
709 return nil, nil, nil, nil, fmt.Errorf("getting current git tree for branch %q: %w", b, err)
710 }
711
712 branchToCurrentTree[b] = tree
713 }
714
715 rawURL := options.BuildOptions.RepositoryDescription.URL
716 u, err := url.Parse(rawURL)
717 if err != nil {
718 return nil, nil, nil, nil, fmt.Errorf("parsing repository URL %q: %w", rawURL, err)
719 }
720
721 // TODO: Support repository submodules for delta builds
722 // For this prototype, we are ignoring repository submodules, which means that we can use the same
723 // blob location for all files
724 hackSharedBlobLocation := BlobLocation{
725 Repo: repository,
726 URL: u,
727 }
728
729 // loop over all branches, calculate the diff between our
730 // last indexed commit and the current commit, and add files mentioned in the diff
731 for _, branch := range existingRepository.Branches {
732 lastIndexedCommit, err := getCommit(repository, "", branch.Version)
733 if err != nil {
734 return nil, nil, nil, nil, fmt.Errorf("getting last indexed commit for branch %q: %w", branch.Name, err)
735 }
736
737 lastIndexedTree, err := lastIndexedCommit.Tree()
738 if err != nil {
739 return nil, nil, nil, nil, fmt.Errorf("getting lasted indexed git tree for branch %q: %w", branch.Name, err)
740 }
741
742 changes, err := object.DiffTreeWithOptions(context.Background(), lastIndexedTree, branchToCurrentTree[branch.Name], &object.DiffTreeOptions{DetectRenames: false})
743 if err != nil {
744 return nil, nil, nil, nil, fmt.Errorf("generating changeset for branch %q: %w", branch.Name, err)
745 }
746
747 for i, c := range changes {
748 oldFile, newFile, err := c.Files()
749 if err != nil {
750 return nil, nil, nil, nil, fmt.Errorf("change #%d: getting files before and after change: %w", i, err)
751 }
752
753 if newFile != nil {
754 // note: newFile.Name could be a path that isn't relative to the repository root - using the
755 // change's Name field is the only way that @ggilmore saw to get the full path relative to the root
756 newFileRelativeRootPath := c.To.Name
757
758 // TODO@ggilmore: HACK - remove once ignore files are supported in delta builds
759 if newFileRelativeRootPath == ignore.IgnoreFile {
760 return nil, nil, nil, nil, fmt.Errorf("%q file is not yet supported in delta builds", ignore.IgnoreFile)
761 }
762
763 // either file is added or renamed, so we need to add the new version to the build
764 file := fileKey{Path: newFileRelativeRootPath, ID: newFile.Hash}
765 repos[file] = hackSharedBlobLocation
766 branchMap[file] = append(branchMap[file], branch.Name)
767 }
768
769 if oldFile == nil {
770 // file added - nothing more to do
771 continue
772 }
773
774 // Note: oldFile.Name could be a path that isn't relative to the repository root - using the
775 // change's "Name" field is the only way that ggilmore saw to get the full path relative to the root
776 oldFileRelativeRootPath := c.From.Name
777
778 if oldFileRelativeRootPath == ignore.IgnoreFile {
779 return nil, nil, nil, nil, fmt.Errorf("%q file is not yet supported in delta builds", ignore.IgnoreFile)
780 }
781
782 // The file is either modified or deleted. So, we need to add ALL versions
783 // of the old file (across all branches) to the build.
784 for b, currentTree := range branchToCurrentTree {
785 f, err := currentTree.File(oldFileRelativeRootPath)
786 if err != nil {
787 // the file doesn't exist in this branch
788 if errors.Is(err, object.ErrFileNotFound) {
789 continue
790 }
791
792 return nil, nil, nil, nil, fmt.Errorf("getting hash for file %q in branch %q: %w", oldFile.Name, b, err)
793 }
794
795 file := fileKey{Path: oldFileRelativeRootPath, ID: f.ID()}
796 repos[file] = hackSharedBlobLocation
797 branchMap[file] = append(branchMap[file], b)
798 }
799
800 changedOrDeletedPaths = append(changedOrDeletedPaths, oldFileRelativeRootPath)
801 }
802 }
803
804 // we need to de-duplicate the branch map before returning it - it's possible for the same
805 // branch to have been added multiple times if a file has been modified across multiple commits
806
807 for file, branches := range branchMap {
808 sort.Strings(branches)
809 branchMap[file] = uniq(branches)
810 }
811
812 // we also need to de-duplicate the list of changed or deleted file paths, it's also possible to have duplicates
813 // for the same reasoning as above
814
815 sort.Strings(changedOrDeletedPaths)
816 changedOrDeletedPaths = uniq(changedOrDeletedPaths)
817
818 return repos, branchMap, nil, changedOrDeletedPaths, nil
819}
820
821func prepareNormalBuild(options Options, repository *git.Repository) (repos map[fileKey]BlobLocation, branchMap map[fileKey][]string, branchVersions map[string]map[string]plumbing.Hash, err error) {
822 var repoCache *RepoCache
823 if options.Submodules {
824 repoCache = NewRepoCache(options.RepoCacheDir)
825 }
826
827 // branch => (path, sha1) => repo.
828 repos = map[fileKey]BlobLocation{}
829
830 // fileKey => branches
831 branchMap = map[fileKey][]string{}
832
833 // Branch => Repo => SHA1
834 branchVersions = map[string]map[string]plumbing.Hash{}
835
836 branches, err := expandBranches(repository, options.Branches, options.BranchPrefix)
837 if err != nil {
838 return nil, nil, nil, fmt.Errorf("expandBranches: %w", err)
839 }
840
841 for _, b := range branches {
842 commit, err := getCommit(repository, options.BranchPrefix, b)
843 if err != nil {
844 if options.AllowMissingBranch && err.Error() == "reference not found" {
845 continue
846 }
847
848 return nil, nil, nil, fmt.Errorf("getCommit: %w", err)
849 }
850
851 tree, err := commit.Tree()
852 if err != nil {
853 return nil, nil, nil, fmt.Errorf("commit.Tree: %w", err)
854 }
855
856 ig, err := newIgnoreMatcher(tree)
857 if err != nil {
858 return nil, nil, nil, fmt.Errorf("newIgnoreMatcher: %w", err)
859 }
860
861 files, subVersions, err := TreeToFiles(repository, tree, options.BuildOptions.RepositoryDescription.URL, repoCache)
862 if err != nil {
863 return nil, nil, nil, fmt.Errorf("TreeToFiles: %w", err)
864 }
865 for k, v := range files {
866 if ig.Match(k.Path) {
867 continue
868 }
869 repos[k] = v
870 branchMap[k] = append(branchMap[k], b)
871 }
872
873 branchVersions[b] = subVersions
874 }
875
876 return repos, branchMap, branchVersions, nil
877}
878
879func createDocument(key fileKey,
880 repos map[fileKey]BlobLocation,
881 branchMap map[fileKey][]string,
882 ranks repoPathRanks,
883 opts build.Options,
884) (zoekt.Document, error) {
885 blob, err := repos[key].Repo.BlobObject(key.ID)
886 if err != nil {
887 return zoekt.Document{}, err
888 }
889
890 keyFullPath := key.FullPath()
891 if blob.Size > int64(opts.SizeMax) && !opts.IgnoreSizeMax(keyFullPath) {
892 return zoekt.Document{
893 SkipReason: fmt.Sprintf("file size %d exceeds maximum size %d", blob.Size, opts.SizeMax),
894 Name: key.FullPath(),
895 Branches: branchMap[key],
896 SubRepositoryPath: key.SubRepoPath,
897 }, nil
898 }
899
900 contents, err := blobContents(blob)
901 if err != nil {
902 return zoekt.Document{}, err
903 }
904
905 var pathRanks []float64
906 if len(ranks.Paths) > 0 {
907 // If the repository has ranking data, then store the file's rank.
908 pathRank := ranks.rank(keyFullPath)
909 pathRanks = []float64{pathRank}
910 }
911
912 return zoekt.Document{
913 SubRepositoryPath: key.SubRepoPath,
914 Name: keyFullPath,
915 Content: contents,
916 Branches: branchMap[key],
917 Ranks: pathRanks,
918 }, nil
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}