fork of https://github.com/sourcegraph/zoekt
0

Configure Feed

Select the types of activity you want to include in your feed.

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