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