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 plainOpenRepo(repoDir string) (*git.Repository, error) { 186 // Try repoDir as the repository root first so bare repositories open 187 // correctly. If repoDir itself is not a repository, fall back to searching 188 // for a .git entry to preserve compatibility with worktree paths. 189 repo, err := git.PlainOpenWithOptions(repoDir, &git.PlainOpenOptions{ 190 EnableDotGitCommonDir: true, 191 }) 192 if err == nil || !errors.Is(err, git.ErrRepositoryNotExists) { 193 return repo, err 194 } 195 196 return git.PlainOpenWithOptions(repoDir, &git.PlainOpenOptions{ 197 DetectDotGit: true, 198 EnableDotGitCommonDir: true, 199 }) 200} 201 202func configLookupRemoteURL(cfg *config.Config, key string) string { 203 rc := cfg.Remotes[key] 204 if rc == nil || len(rc.URLs) == 0 { 205 return "" 206 } 207 return rc.URLs[0] 208} 209 210var sshRelativeURLRegexp = regexp.MustCompile(`^([^@]+)@([^:]+):(.*)$`) 211 212func setTemplatesFromConfig(desc *zoekt.Repository, repoDir string) error { 213 repo, err := plainOpenRepo(repoDir) 214 if err != nil { 215 return err 216 } 217 218 cfg, err := repo.Config() 219 if err != nil { 220 return err 221 } 222 223 return setTemplatesFromRepoConfig(desc, cfg) 224} 225 226func setTemplatesFromRepo(desc *zoekt.Repository, repo *git.Repository, repoDir string) error { 227 cfg, err := repo.Config() 228 if err == nil { 229 return setTemplatesFromRepoConfig(desc, cfg) 230 } 231 232 return setTemplatesFromConfig(desc, repoDir) 233} 234 235func setTemplatesFromRepoConfig(desc *zoekt.Repository, cfg *config.Config) error { 236 sec := cfg.Raw.Section("zoekt") 237 238 webURLStr := sec.Options.Get("web-url") 239 webURLType := sec.Options.Get("web-url-type") 240 241 if webURLType != "" && webURLStr != "" { 242 webURL, err := url.Parse(webURLStr) 243 if err != nil { 244 return err 245 } 246 if err := setTemplates(desc, webURL, webURLType); err != nil { 247 return err 248 } 249 } else if webURLStr != "" { 250 desc.URL = webURLStr 251 } 252 253 name := sec.Options.Get("name") 254 if name != "" { 255 desc.Name = name 256 } else { 257 remoteURL := configLookupRemoteURL(cfg, "origin") 258 if remoteURL == "" { 259 return nil 260 } 261 if sm := sshRelativeURLRegexp.FindStringSubmatch(remoteURL); sm != nil { 262 user := sm[1] 263 host := sm[2] 264 path := sm[3] 265 266 remoteURL = fmt.Sprintf("ssh+git://%s@%s/%s", user, host, path) 267 } 268 269 u, err := url.Parse(remoteURL) 270 if err != nil { 271 return err 272 } 273 if err := SetTemplatesFromOrigin(desc, u); err != nil { 274 return err 275 } 276 } 277 278 id, _ := strconv.ParseUint(sec.Options.Get("repoid"), 10, 32) 279 desc.ID = uint32(id) 280 281 desc.TenantID, _ = strconv.Atoi(sec.Options.Get("tenantID")) 282 283 if desc.RawConfig == nil { 284 desc.RawConfig = map[string]string{} 285 } 286 for _, o := range sec.Options { 287 desc.RawConfig[o.Key] = o.Value 288 } 289 290 // Ranking info. 291 292 // Github: 293 traction := 0 294 for _, s := range []string{"github-stars", "github-forks", "github-watchers", "github-subscribers"} { 295 f, err := strconv.Atoi(sec.Options.Get(s)) 296 if err == nil { 297 traction += f 298 } 299 } 300 301 if strings.Contains(desc.Name, "googlesource.com/") && traction == 0 { 302 // Pretend everything on googlesource.com has 1000 303 // github stars. 304 traction = 1000 305 } 306 307 if traction > 0 { 308 l := math.Log(float64(traction)) 309 desc.Rank = uint16((1.0 - 1.0/math.Pow(1+l, 0.6)) * 10000) 310 } 311 312 return nil 313} 314 315// This attempts to get a repo URL similar to the main repository template processing as in setTemplatesFromConfig() 316func normalizeSubmoduleRemoteURL(cfg *config.Config) (string, error) { 317 sec := cfg.Raw.Section("zoekt") 318 remoteURL := sec.Options.Get("web-url") 319 if remoteURL == "" { 320 // fall back to "origin" remote 321 remoteURL = configLookupRemoteURL(cfg, "origin") 322 if remoteURL == "" { 323 return "", nil 324 } 325 } 326 327 if sm := sshRelativeURLRegexp.FindStringSubmatch(remoteURL); sm != nil { 328 user := sm[1] 329 host := sm[2] 330 path := sm[3] 331 332 remoteURL = fmt.Sprintf("ssh+git://%s@%s/%s", user, host, path) 333 } 334 335 u, err := url.Parse(remoteURL) 336 if err != nil { 337 return "", fmt.Errorf("unable to parse remote URL %q: %w", remoteURL, err) 338 } 339 340 if u.Scheme == "ssh+git" { 341 u.Scheme = "https" 342 u.User = nil 343 } 344 345 // Assume we cannot build templates for this URL, leave it empty 346 if u.Scheme == "" { 347 return "", nil 348 } 349 350 return u.String(), nil 351} 352 353// SetTemplatesFromOrigin fills in templates based on the origin URL. 354func SetTemplatesFromOrigin(desc *zoekt.Repository, u *url.URL) error { 355 desc.Name = filepath.Join(u.Host, strings.TrimSuffix(u.Path, ".git")) 356 357 if strings.HasSuffix(u.Host, ".googlesource.com") { 358 return setTemplates(desc, u, "gitiles") 359 } else if u.Host == "github.com" { 360 u.Path = strings.TrimSuffix(u.Path, ".git") 361 return setTemplates(desc, u, "github") 362 } else { 363 return fmt.Errorf("unknown git hosting site %q", u) 364 } 365} 366 367// The Options structs controls details of the indexing process. 368type Options struct { 369 // The repository to be indexed. 370 RepoDir string 371 372 // If set, follow submodule links. This requires RepoCacheDir to be set. 373 Submodules bool 374 375 // If set, skip indexing if the existing index shard is newer 376 // than the refs in the repository. 377 Incremental bool 378 379 // Don't error out if some branch is missing 380 AllowMissingBranch bool 381 382 // Specifies the root of a Repository cache. Needed for submodule indexing. 383 RepoCacheDir string 384 385 // Indexing options. 386 BuildOptions index.Options 387 388 // Prefix of the branch to index, e.g. `remotes/origin`. 389 BranchPrefix string 390 391 // List of branch names to index, e.g. []string{"HEAD", "stable"} 392 Branches []string 393 394 // DeltaShardNumberFallbackThreshold defines an upper limit (inclusive) on the number of preexisting shards 395 // that can exist before attempting another delta build. If the number of preexisting shards exceeds this threshold, 396 // then a normal build will be performed instead. 397 // 398 // If DeltaShardNumberFallbackThreshold is 0, then this fallback behavior is disabled: 399 // a delta build will always be performed regardless of the number of preexisting shards. 400 DeltaShardNumberFallbackThreshold uint64 401} 402 403func expandBranches(repo *git.Repository, bs []string, prefix string) ([]string, error) { 404 var result []string 405 for _, b := range bs { 406 // Sourcegraph: We disable resolving refs. We want to return the exact ref 407 // requested so we can match it up. 408 if b == "HEAD" && false { 409 ref, err := repo.Head() 410 if err != nil { 411 return nil, err 412 } 413 414 result = append(result, strings.TrimPrefix(ref.Name().String(), prefix)) 415 continue 416 } 417 418 if strings.Contains(b, "*") { 419 iter, err := repo.Branches() 420 if err != nil { 421 return nil, err 422 } 423 424 defer iter.Close() 425 for { 426 ref, err := iter.Next() 427 if err == io.EOF { 428 break 429 } 430 if err != nil { 431 return nil, err 432 } 433 434 name := ref.Name().Short() 435 if matched, err := filepath.Match(b, name); err != nil { 436 return nil, err 437 } else if !matched { 438 continue 439 } 440 441 result = append(result, strings.TrimPrefix(name, prefix)) 442 } 443 continue 444 } 445 446 result = append(result, b) 447 } 448 449 return result, nil 450} 451 452// IndexGitRepo indexes the git repository as specified by the options. 453// The returned bool indicates whether the index was updated as a result. This 454// can be informative if doing incremental indexing. 455func IndexGitRepo(opts Options) (bool, error) { 456 return indexGitRepo(opts, gitIndexConfig{}) 457} 458 459// indexGitRepo indexes the git repository as specified by the options and the provided gitIndexConfig. 460// The returned bool indicates whether the index was updated as a result. This 461// can be informative if doing incremental indexing. 462func indexGitRepo(opts Options, config gitIndexConfig) (bool, error) { 463 prepareDeltaBuild := prepareDeltaBuild 464 if config.prepareDeltaBuild != nil { 465 prepareDeltaBuild = config.prepareDeltaBuild 466 } 467 468 prepareNormalBuild := prepareNormalBuild 469 if config.prepareNormalBuild != nil { 470 prepareNormalBuild = config.prepareNormalBuild 471 } 472 473 // Set max thresholds, since we use them in this function. 474 opts.BuildOptions.SetDefaults() 475 if opts.RepoDir == "" { 476 return false, fmt.Errorf("gitindex: must set RepoDir") 477 } 478 479 opts.BuildOptions.RepositoryDescription.Source = opts.RepoDir 480 481 var repo *git.Repository 482 legacyRepoOpen := cmp.Or(os.Getenv("ZOEKT_DISABLE_GOGIT_OPTIMIZATION"), "false") 483 if b, err := strconv.ParseBool(legacyRepoOpen); b || err != nil { 484 repo, err = plainOpenRepo(opts.RepoDir) 485 if err != nil { 486 return false, fmt.Errorf("plainOpenRepo: %w", err) 487 } 488 } else { 489 var repoCloser io.Closer 490 repo, repoCloser, err = openRepo(opts.RepoDir) 491 if err != nil { 492 return false, fmt.Errorf("openRepo: %w", err) 493 } 494 defer repoCloser.Close() 495 } 496 497 if err := setTemplatesFromRepo(&opts.BuildOptions.RepositoryDescription, repo, opts.RepoDir); err != nil { 498 log.Printf("setTemplatesFromRepo(%s): %s", opts.RepoDir, err) 499 } 500 501 branches, err := expandBranches(repo, opts.Branches, opts.BranchPrefix) 502 if err != nil { 503 return false, fmt.Errorf("expandBranches: %w", err) 504 } 505 for _, b := range branches { 506 commit, err := getCommit(repo, opts.BranchPrefix, b) 507 if err != nil { 508 if opts.AllowMissingBranch && err.Error() == "reference not found" { 509 continue 510 } 511 512 return false, fmt.Errorf("getCommit(%q, %q): %w", opts.BranchPrefix, b, err) 513 } 514 515 opts.BuildOptions.RepositoryDescription.Branches = append(opts.BuildOptions.RepositoryDescription.Branches, zoekt.RepositoryBranch{ 516 Name: b, 517 Version: commit.Hash.String(), 518 }) 519 520 if when := commit.Committer.When; when.After(opts.BuildOptions.RepositoryDescription.LatestCommitDate) { 521 opts.BuildOptions.RepositoryDescription.LatestCommitDate = when 522 } 523 } 524 525 if opts.Incremental && opts.BuildOptions.IncrementalSkipIndexing() { 526 return false, nil 527 } 528 529 // branch => (path, sha1) => repo. 530 var repos map[fileKey]BlobLocation 531 532 // Branch => Repo => SHA1 533 var branchVersions map[string]map[string]plumbing.Hash 534 535 // set of file paths that have been changed or deleted since 536 // the last indexed commit 537 // 538 // These only have an effect on delta builds 539 var changedOrRemovedFiles []string 540 541 if opts.BuildOptions.IsDelta { 542 repos, branchVersions, changedOrRemovedFiles, err = prepareDeltaBuild(opts, repo) 543 if err != nil { 544 log.Printf("delta build: falling back to normal build since delta build failed, repository=%q, err=%s", opts.BuildOptions.RepositoryDescription.Name, err) 545 opts.BuildOptions.IsDelta = false 546 } 547 } 548 549 if !opts.BuildOptions.IsDelta { 550 repos, branchVersions, err = prepareNormalBuild(opts, repo) 551 if err != nil { 552 return false, fmt.Errorf("preparing normal build: %w", err) 553 } 554 } 555 556 reposByPath := map[string]BlobLocation{} 557 for key, info := range repos { 558 reposByPath[key.SubRepoPath] = info 559 } 560 561 opts.BuildOptions.SubRepositories = map[string]*zoekt.Repository{} 562 for path, info := range reposByPath { 563 tpl := opts.BuildOptions.RepositoryDescription 564 if path != "" { 565 tpl = zoekt.Repository{URL: info.URL.String()} 566 if info.URL.String() != "" { 567 if err := SetTemplatesFromOrigin(&tpl, info.URL); err != nil { 568 log.Printf("setTemplatesFromOrigin(%s, %s): %s", path, info.URL, err) 569 } 570 } 571 if tpl.Name == "" { 572 tpl.Name = path 573 } 574 } 575 opts.BuildOptions.SubRepositories[path] = &tpl 576 } 577 578 for _, br := range opts.BuildOptions.RepositoryDescription.Branches { 579 for path, repo := range opts.BuildOptions.SubRepositories { 580 id := branchVersions[br.Name][path] 581 repo.Branches = append(repo.Branches, zoekt.RepositoryBranch{ 582 Name: br.Name, 583 Version: id.String(), 584 }) 585 } 586 } 587 588 builder, err := index.NewBuilder(opts.BuildOptions) 589 if err != nil { 590 return false, fmt.Errorf("build.NewBuilder: %w", err) 591 } 592 593 // Preparing the build can consume substantial memory, so check usage before starting to index. 594 builder.CheckMemoryUsage() 595 596 // we don't need to check error, since we either already have an error, or 597 // we returning the first call to builder.Finish. 598 defer builder.Finish() // nolint:errcheck 599 600 for _, f := range changedOrRemovedFiles { 601 builder.MarkFileAsChangedOrRemoved(f) 602 } 603 604 var names []string 605 fileKeys := map[string][]fileKey{} 606 totalFiles := 0 607 608 for key := range repos { 609 n := key.FullPath() 610 fileKeys[n] = append(fileKeys[n], key) 611 names = append(names, n) 612 totalFiles++ 613 } 614 615 sort.Strings(names) 616 names = uniq(names) 617 618 // Separate main-repo keys from submodule keys, collecting blob SHAs 619 // for the main repo so we can stream them via git cat-file --batch. 620 // ZOEKT_DISABLE_CATFILE_BATCH=true falls back to the go-git path for 621 // all files, useful as a kill switch if the cat-file path causes issues. 622 // 623 // 2026-04-02(keegan) we are regularly seeing git growing to over 9GB in 624 // memory usage in our production cluster. Disabling by default until the 625 // issue is resolved. 626 catfileBatchDisabled := cmp.Or(os.Getenv("ZOEKT_DISABLE_CATFILE_BATCH"), "true") 627 useCatfileBatch := true 628 if disabled, _ := strconv.ParseBool(catfileBatchDisabled); disabled { 629 useCatfileBatch = false 630 log.Printf("cat-file batch disabled via ZOEKT_DISABLE_CATFILE_BATCH, using go-git") 631 } 632 633 mainRepoKeys := make([]fileKey, 0, totalFiles) 634 mainRepoIDs := make([]plumbing.Hash, 0, totalFiles) 635 var submoduleKeys []fileKey 636 637 for _, name := range names { 638 for _, key := range fileKeys[name] { 639 if useCatfileBatch && key.SubRepoPath == "" { 640 mainRepoKeys = append(mainRepoKeys, key) 641 mainRepoIDs = append(mainRepoIDs, key.ID) 642 } else { 643 submoduleKeys = append(submoduleKeys, key) 644 } 645 } 646 } 647 648 log.Printf("attempting to index %d total files (%d via cat-file, %d via go-git)", totalFiles, len(mainRepoIDs), len(submoduleKeys)) 649 650 // Stream main-repo blobs via pipelined cat-file --batch --buffer. 651 // Large blobs are skipped without reading content into memory. 652 if len(mainRepoIDs) > 0 { 653 crOpts := catfileReaderOptions{ 654 filterSpec: catfileFilterSpec(opts), 655 } 656 cr, err := newCatfileReader(opts.RepoDir, mainRepoIDs, crOpts) 657 if err != nil { 658 return false, fmt.Errorf("newCatfileReader: %w", err) 659 } 660 661 if err := indexCatfileBlobs(cr, mainRepoKeys, repos, opts, builder); err != nil { 662 return false, err 663 } 664 } 665 666 // Index submodule blobs via go-git. 667 for idx, key := range submoduleKeys { 668 doc, err := createDocument(key, repos, opts.BuildOptions) 669 if err != nil { 670 return false, err 671 } 672 673 if err := builder.Add(doc); err != nil { 674 return false, fmt.Errorf("error adding document with name %s: %w", key.FullPath(), err) 675 } 676 677 if idx%10_000 == 0 { 678 builder.CheckMemoryUsage() 679 } 680 } 681 682 return true, builder.Finish() 683} 684 685// indexCatfileBlobs streams main-repo blobs from the catfileReader into the 686// builder. Large blobs are skipped without reading content into memory. 687// keys must correspond 1:1 (in order) with the ids passed to newCatfileReader. 688// The reader is always closed when this function returns. 689func indexCatfileBlobs(cr *catfileReader, keys []fileKey, repos map[fileKey]BlobLocation, opts Options, builder *index.Builder) error { 690 defer cr.Close() 691 692 slab := newContentSlab(16 << 20) // 16 MB per slab 693 694 for idx, key := range keys { 695 size, missing, excluded, err := cr.Next() 696 if err != nil { 697 return fmt.Errorf("cat-file next for %s: %w", key.FullPath(), err) 698 } 699 700 branches := repos[key].Branches 701 var doc index.Document 702 703 if missing { 704 // Unexpected for local repos — may indicate corruption, shallow 705 // clone, or a race with git gc. Log a warning and skip. 706 log.Printf("warning: blob %s missing for %s", key.ID, key.FullPath()) 707 doc = skippedDoc(key, branches, index.SkipReasonMissing) 708 } else if excluded { 709 doc = skippedDoc(key, branches, index.SkipReasonTooLarge) 710 } else { 711 keyFullPath := key.FullPath() 712 if size > opts.BuildOptions.SizeMax && !opts.BuildOptions.IgnoreSizeMax(keyFullPath) { 713 // Skip without reading content into memory. 714 doc = skippedDoc(key, branches, index.SkipReasonTooLarge) 715 } else { 716 content := slab.alloc(size) 717 if _, err := io.ReadFull(cr, content); err != nil { 718 return fmt.Errorf("read blob %s: %w", keyFullPath, err) 719 } 720 doc = index.Document{ 721 SubRepositoryPath: key.SubRepoPath, 722 Name: keyFullPath, 723 Content: content, 724 Branches: branches, 725 } 726 } 727 } 728 729 if err := builder.Add(doc); err != nil { 730 return fmt.Errorf("error adding document with name %s: %w", key.FullPath(), err) 731 } 732 733 if idx%10_000 == 0 { 734 builder.CheckMemoryUsage() 735 } 736 } 737 738 return nil 739} 740 741// openRepo opens a git repository in a way that's optimized for indexing. 742// 743// It copies the relevant logic from git.PlainOpen, and tweaks certain filesystem options. 744func openRepo(repoDir string) (*git.Repository, io.Closer, error) { 745 fs := osfs.New(repoDir) 746 747 // Check if the root directory exists. 748 if _, err := fs.Stat(""); err != nil { 749 if os.IsNotExist(err) { 750 return nil, nil, git.ErrRepositoryNotExists 751 } 752 return nil, nil, err 753 } 754 755 fi, err := fs.Stat(git.GitDirName) 756 if err == nil && !fi.IsDir() { 757 return openCompatibleRepo(repoDir) 758 } 759 760 return openOptimizedRepo(repoDir) 761} 762 763func openCompatibleRepo(repoDir string) (*git.Repository, io.Closer, error) { 764 repo, err := plainOpenRepo(repoDir) 765 if err != nil { 766 return nil, nil, err 767 } 768 769 return repo, noopCloser{}, nil 770} 771 772func openOptimizedRepo(repoDir string) (*git.Repository, io.Closer, error) { 773 fs := osfs.New(repoDir) 774 wt := fs 775 776 // If there's a .git directory, use that as the new root. 777 if fi, err := fs.Stat(git.GitDirName); err == nil && fi.IsDir() { 778 if fs, err = fs.Chroot(git.GitDirName); err != nil { 779 return nil, nil, fmt.Errorf("fs.Chroot: %w", err) 780 } 781 } 782 783 s := filesystem.NewStorageWithOptions(fs, cache.NewObjectLRUDefault(), filesystem.Options{ 784 // Cache the packfile handles, preventing the packfile from being opened then closed on every object access 785 KeepDescriptors: true, 786 }) 787 788 // Because we're keeping descriptors open, we need to close the storage object when we're done. 789 repo, err := git.Open(s, wt) 790 return repo, s, err 791} 792 793type noopCloser struct{} 794 795func (noopCloser) Close() error { return nil } 796 797func catfileFilterSpec(opts Options) string { 798 // Can't filter by size if we have large file exceptions 799 if len(opts.BuildOptions.LargeFiles) > 0 { 800 return "" 801 } 802 803 if opts.BuildOptions.SizeMax <= 0 { 804 return "" 805 } 806 807 // Git's blob:limit filter excludes blobs whose size is >= the given limit, 808 // while zoekt indexes files up to and including SizeMax bytes. 809 return fmt.Sprintf("blob:limit=%d", int64(opts.BuildOptions.SizeMax)+1) 810} 811 812func newIgnoreMatcher(tree *object.Tree) (*ignore.Matcher, error) { 813 ignoreFile, err := tree.File(ignore.IgnoreFile) 814 if err == object.ErrFileNotFound { 815 return &ignore.Matcher{}, nil 816 } 817 if err != nil { 818 return nil, err 819 } 820 content, err := ignoreFile.Contents() 821 if err != nil { 822 return nil, err 823 } 824 return ignore.ParseIgnoreFile(strings.NewReader(content)) 825} 826 827// prepareDeltaBuildFunc is a function that calculates the necessary metadata for preparing 828// a build.Builder instance for generating a delta build. 829type prepareDeltaBuildFunc func(options Options, repository *git.Repository) (repos map[fileKey]BlobLocation, branchVersions map[string]map[string]plumbing.Hash, changedOrDeletedPaths []string, err error) 830 831// prepareNormalBuildFunc is a function that calculates the necessary metadata for preparing 832// a build.Builder instance for generating a normal build. 833type prepareNormalBuildFunc func(options Options, repository *git.Repository) (repos map[fileKey]BlobLocation, branchVersions map[string]map[string]plumbing.Hash, err error) 834 835type gitIndexConfig struct { 836 // prepareDeltaBuild, if not nil, is the function that is used to calculate the metadata that will be used to 837 // prepare the build.Builder instance for generating a delta build. 838 // 839 // If prepareDeltaBuild is nil, gitindex.prepareDeltaBuild will be used instead. 840 prepareDeltaBuild prepareDeltaBuildFunc 841 842 // prepareNormalBuild, if not nil, is the function that is used to calculate the metadata that will be used to 843 // prepare the build.Builder instance for generating a normal build. 844 // 845 // If prepareNormalBuild is nil, gitindex.prepareNormalBuild will be used instead. 846 prepareNormalBuild prepareNormalBuildFunc 847} 848 849func prepareDeltaBuild(options Options, repository *git.Repository) (repos map[fileKey]BlobLocation, branchVersions map[string]map[string]plumbing.Hash, changedOrDeletedPaths []string, err error) { 850 if options.Submodules { 851 return nil, nil, nil, fmt.Errorf("delta builds currently don't support submodule indexing") 852 } 853 854 // discover what commits we indexed during our last build 855 existingRepository, _, ok, err := options.BuildOptions.FindRepositoryMetadata() 856 if err != nil { 857 return nil, nil, nil, fmt.Errorf("failed to get repository metadata: %w", err) 858 } 859 860 if !ok { 861 return nil, nil, nil, fmt.Errorf("no existing shards found for repository") 862 } 863 864 if options.DeltaShardNumberFallbackThreshold > 0 { 865 // HACK: For our interim compaction strategy, we force a full normal index once 866 // the number of shards on disk for this repository exceeds the provided threshold. 867 // 868 // This strategy obviously isn't optimal (as an example: we currently can't differentiate 869 // between "normal" and "delta" shards, so repositories like the gigarepo that generate a large number of shards per 870 // build would be disproportionately affected by this), but it'll allow us to continue experimenting on real workloads 871 // while we create a better compaction strategy). 872 873 oldShards := options.BuildOptions.FindAllShards() 874 if uint64(len(oldShards)) > options.DeltaShardNumberFallbackThreshold { 875 return nil, nil, nil, fmt.Errorf("number of existing shards (%d) > requested shard threshold (%d)", len(oldShards), options.DeltaShardNumberFallbackThreshold) 876 } 877 } 878 879 // Check to see if the set of branch names is consistent with what we last indexed. 880 // If it isn't consistent, that we can't proceed with a delta build (and the caller should fall back to a 881 // normal one). 882 883 if !index.BranchNamesEqual(existingRepository.Branches, options.BuildOptions.RepositoryDescription.Branches) { 884 var existingBranchNames []string 885 for _, b := range existingRepository.Branches { 886 existingBranchNames = append(existingBranchNames, b.Name) 887 } 888 889 var optionsBranchNames []string 890 for _, b := range options.BuildOptions.RepositoryDescription.Branches { 891 optionsBranchNames = append(optionsBranchNames, b.Name) 892 } 893 894 existingBranchList := strings.Join(existingBranchNames, ", ") 895 optionsBranchList := strings.Join(optionsBranchNames, ", ") 896 897 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) 898 } 899 900 // Check if the build options hash does not match the repository metadata's hash 901 // If it does not index then one or more index options has changed and will require a normal build instead of a delta build 902 if options.BuildOptions.GetHash() != existingRepository.IndexOptions { 903 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()) 904 } 905 906 // branch => (path, sha1) => repo. 907 repos = map[fileKey]BlobLocation{} 908 909 branches, err := expandBranches(repository, options.Branches, options.BranchPrefix) 910 if err != nil { 911 return nil, nil, nil, fmt.Errorf("expandBranches: %w", err) 912 } 913 914 // branch name -> git worktree at most current commit 915 branchToCurrentTree := make(map[string]*object.Tree, len(branches)) 916 917 for _, b := range branches { 918 commit, err := getCommit(repository, options.BranchPrefix, b) 919 if err != nil { 920 return nil, nil, nil, fmt.Errorf("getting last current commit for branch %q: %w", b, err) 921 } 922 923 tree, err := commit.Tree() 924 if err != nil { 925 return nil, nil, nil, fmt.Errorf("getting current git tree for branch %q: %w", b, err) 926 } 927 928 branchToCurrentTree[b] = tree 929 } 930 931 rawURL := options.BuildOptions.RepositoryDescription.URL 932 u, err := url.Parse(rawURL) 933 if err != nil { 934 return nil, nil, nil, fmt.Errorf("parsing repository URL %q: %w", rawURL, err) 935 } 936 937 // TODO: Support repository submodules for delta builds 938 939 // loop over all branches, calculate the diff between our 940 // last indexed commit and the current commit, and add files mentioned in the diff 941 for _, branch := range existingRepository.Branches { 942 lastIndexedCommit, err := getCommit(repository, "", branch.Version) 943 if err != nil { 944 return nil, nil, nil, fmt.Errorf("getting last indexed commit for branch %q: %w", branch.Name, err) 945 } 946 947 lastIndexedTree, err := lastIndexedCommit.Tree() 948 if err != nil { 949 return nil, nil, nil, fmt.Errorf("getting lasted indexed git tree for branch %q: %w", branch.Name, err) 950 } 951 952 changes, err := object.DiffTreeWithOptions(context.Background(), lastIndexedTree, branchToCurrentTree[branch.Name], &object.DiffTreeOptions{DetectRenames: false}) 953 if err != nil { 954 return nil, nil, nil, fmt.Errorf("generating changeset for branch %q: %w", branch.Name, err) 955 } 956 957 for i, c := range changes { 958 oldFile, newFile, err := c.Files() 959 if err != nil { 960 return nil, nil, nil, fmt.Errorf("change #%d: getting files before and after change: %w", i, err) 961 } 962 963 if newFile != nil { 964 // note: newFile.Name could be a path that isn't relative to the repository root - using the 965 // change's Name field is the only way that @ggilmore saw to get the full path relative to the root 966 newFileRelativeRootPath := c.To.Name 967 968 // TODO@ggilmore: HACK - remove once ignore files are supported in delta builds 969 if newFileRelativeRootPath == ignore.IgnoreFile { 970 return nil, nil, nil, fmt.Errorf("%q file is not yet supported in delta builds", ignore.IgnoreFile) 971 } 972 973 // either file is added or renamed, so we need to add the new version to the build 974 file := fileKey{Path: newFileRelativeRootPath, ID: newFile.Hash} 975 if existing, ok := repos[file]; ok { 976 existing.Branches = append(existing.Branches, branch.Name) 977 repos[file] = existing 978 } else { 979 repos[file] = BlobLocation{ 980 GitRepo: repository, 981 URL: u, 982 Branches: []string{branch.Name}, 983 } 984 } 985 } 986 987 if oldFile == nil { 988 // file added - nothing more to do 989 continue 990 } 991 992 // Note: oldFile.Name could be a path that isn't relative to the repository root - using the 993 // change's "Name" field is the only way that ggilmore saw to get the full path relative to the root 994 oldFileRelativeRootPath := c.From.Name 995 996 if oldFileRelativeRootPath == ignore.IgnoreFile { 997 return nil, nil, nil, fmt.Errorf("%q file is not yet supported in delta builds", ignore.IgnoreFile) 998 } 999 1000 // The file is either modified or deleted. So, we need to add ALL versions 1001 // of the old file (across all branches) to the build. 1002 for b, currentTree := range branchToCurrentTree { 1003 f, err := currentTree.File(oldFileRelativeRootPath) 1004 if err != nil { 1005 // the file doesn't exist in this branch 1006 if errors.Is(err, object.ErrFileNotFound) { 1007 continue 1008 } 1009 1010 return nil, nil, nil, fmt.Errorf("getting hash for file %q in branch %q: %w", oldFile.Name, b, err) 1011 } 1012 1013 file := fileKey{Path: oldFileRelativeRootPath, ID: f.ID()} 1014 if existing, ok := repos[file]; ok { 1015 existing.Branches = append(existing.Branches, b) 1016 repos[file] = existing 1017 } else { 1018 repos[file] = BlobLocation{ 1019 GitRepo: repository, 1020 URL: u, 1021 Branches: []string{b}, 1022 } 1023 } 1024 } 1025 1026 changedOrDeletedPaths = append(changedOrDeletedPaths, oldFileRelativeRootPath) 1027 } 1028 } 1029 1030 // we need to de-duplicate the branch map before returning it - it's possible for the same 1031 // branch to have been added multiple times if a file has been modified across multiple commits 1032 for _, info := range repos { 1033 sort.Strings(info.Branches) 1034 info.Branches = uniq(info.Branches) 1035 } 1036 1037 // we also need to de-duplicate the list of changed or deleted file paths, it's also possible to have duplicates 1038 // for the same reasoning as above 1039 sort.Strings(changedOrDeletedPaths) 1040 changedOrDeletedPaths = uniq(changedOrDeletedPaths) 1041 1042 return repos, nil, changedOrDeletedPaths, nil 1043} 1044 1045func prepareNormalBuild(options Options, repository *git.Repository) (repos map[fileKey]BlobLocation, branchVersions map[string]map[string]plumbing.Hash, err error) { 1046 var repoCache *RepoCache 1047 if options.Submodules && options.RepoCacheDir != "" { 1048 repoCache = NewRepoCache(options.RepoCacheDir) 1049 } 1050 return prepareNormalBuildRecurse(options, repository, repoCache, false) 1051} 1052 1053func prepareNormalBuildRecurse(options Options, repository *git.Repository, repoCache *RepoCache, isSubrepo bool) (repos map[fileKey]BlobLocation, branchVersions map[string]map[string]plumbing.Hash, err error) { 1054 // Branch => Repo => SHA1 1055 branchVersions = map[string]map[string]plumbing.Hash{} 1056 1057 branches, err := expandBranches(repository, options.Branches, options.BranchPrefix) 1058 if err != nil { 1059 return nil, nil, fmt.Errorf("expandBranches: %w", err) 1060 } 1061 1062 repoURL := options.BuildOptions.RepositoryDescription.URL 1063 1064 if isSubrepo { 1065 cfg, err := repository.Config() 1066 if err != nil { 1067 return nil, nil, fmt.Errorf("unable to get repository config: %w", err) 1068 } 1069 1070 u, err := normalizeSubmoduleRemoteURL(cfg) 1071 if err != nil { 1072 return nil, nil, fmt.Errorf("failed to identify subrepository URL: %w", err) 1073 } 1074 repoURL = u 1075 } 1076 1077 rw := NewRepoWalker(repository, repoURL, repoCache) 1078 for _, b := range branches { 1079 commit, err := getCommit(repository, options.BranchPrefix, b) 1080 if err != nil { 1081 if options.AllowMissingBranch && err.Error() == "reference not found" { 1082 continue 1083 } 1084 1085 return nil, nil, fmt.Errorf("getCommit: %w", err) 1086 } 1087 1088 tree, err := commit.Tree() 1089 if err != nil { 1090 return nil, nil, fmt.Errorf("commit.Tree: %w", err) 1091 } 1092 1093 ig, err := newIgnoreMatcher(tree) 1094 if err != nil { 1095 return nil, nil, fmt.Errorf("newIgnoreMatcher: %w", err) 1096 } 1097 1098 subVersions, err := rw.CollectFiles(tree, b, ig) 1099 if err != nil { 1100 return nil, nil, fmt.Errorf("CollectFiles: %w", err) 1101 } 1102 1103 branchVersions[b] = subVersions 1104 } 1105 1106 // Index submodules using go-git if we didn't do so using the repo cache 1107 if options.Submodules && options.RepoCacheDir == "" { 1108 worktree, err := repository.Worktree() 1109 if err != nil { 1110 return nil, nil, fmt.Errorf("failed to get repository worktree: %w", err) 1111 } 1112 1113 submodules, err := worktree.Submodules() 1114 if err != nil { 1115 return nil, nil, fmt.Errorf("failed to get submodules: %w", err) 1116 } 1117 1118 for _, submodule := range submodules { 1119 subRepository, err := submodule.Repository() 1120 if err != nil { 1121 log.Printf("failed to open submodule repository: %s, %s", submodule.Config().Name, err) 1122 continue 1123 } 1124 1125 sw, subVersions, err := prepareNormalBuildRecurse(options, subRepository, repoCache, true) 1126 if err != nil { 1127 log.Printf("failed to index submodule repository: %s, %s", submodule.Config().Name, err) 1128 continue 1129 } 1130 1131 log.Printf("adding subrepository files from: %s", submodule.Config().Name) 1132 1133 for k, repo := range sw { 1134 rw.Files[fileKey{ 1135 SubRepoPath: filepath.Join(submodule.Config().Path, k.SubRepoPath), 1136 Path: k.Path, 1137 ID: k.ID, 1138 }] = repo 1139 } 1140 1141 for k, v := range subVersions { 1142 branchVersions[filepath.Join(submodule.Config().Path, k)] = v 1143 } 1144 } 1145 } 1146 1147 return rw.Files, branchVersions, nil 1148} 1149 1150func createDocument(key fileKey, 1151 repos map[fileKey]BlobLocation, 1152 opts index.Options, 1153) (index.Document, error) { 1154 repo := repos[key] 1155 blob, err := repo.GitRepo.BlobObject(key.ID) 1156 branches := repos[key].Branches 1157 1158 // We filter out large documents when fetching the repo. So if an object is too large, it will not be found. 1159 if errors.Is(err, plumbing.ErrObjectNotFound) { 1160 return skippedDoc(key, branches, index.SkipReasonTooLarge), nil 1161 } 1162 1163 if err != nil { 1164 return index.Document{}, err 1165 } 1166 1167 keyFullPath := key.FullPath() 1168 if blob.Size > int64(opts.SizeMax) && !opts.IgnoreSizeMax(keyFullPath) { 1169 return skippedDoc(key, branches, index.SkipReasonTooLarge), nil 1170 } 1171 1172 contents, err := blobContents(blob) 1173 if err != nil { 1174 return index.Document{}, err 1175 } 1176 1177 return index.Document{ 1178 SubRepositoryPath: key.SubRepoPath, 1179 Name: keyFullPath, 1180 Content: contents, 1181 Branches: branches, 1182 }, nil 1183} 1184 1185// skippedDoc creates a Document placeholder for a blob that was not indexed. 1186func skippedDoc(key fileKey, branches []string, reason index.SkipReason) index.Document { 1187 return index.Document{ 1188 SkipReason: reason, 1189 Name: key.FullPath(), 1190 Branches: branches, 1191 SubRepositoryPath: key.SubRepoPath, 1192 } 1193} 1194 1195func blobContents(blob *object.Blob) ([]byte, error) { 1196 r, err := blob.Reader() 1197 if err != nil { 1198 return nil, err 1199 } 1200 defer r.Close() 1201 1202 var buf bytes.Buffer 1203 buf.Grow(int(blob.Size)) 1204 _, err = buf.ReadFrom(r) 1205 if err != nil { 1206 return nil, err 1207 } 1208 return buf.Bytes(), nil 1209} 1210 1211func uniq(ss []string) []string { 1212 result := ss[:0] 1213 var last string 1214 for i, s := range ss { 1215 if i == 0 || s != last { 1216 result = append(result, s) 1217 } 1218 last = s 1219 } 1220 return result 1221}