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