From 0109088d77ed2c4c822c72c9646f295c31afbadc Mon Sep 17 00:00:00 2001 From: Jack Minnetian <270441393+BlueBottleLatte@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:00:41 -0500 Subject: [PATCH 1/3] fix(gitindex): keep one document per file when a delta build adds it to another branch A document carries every branch that has its blob at its path. When a delta build saw a file added on a branch, it indexed a new document for that branch alone and left the older shards untouched. If another branch already had the same file, the index ended up with two documents for it, each on a subset of the branches. A search that required both branches missed the file, and a search that excluded one of them still found it. A delta build now handles an added file the way it handles a modified or deleted one: it indexes the file's current version from every branch and tombstones the path in the older shards. It skips the tombstone when the file is new to its branch and no other branch has it, since no older shard has that path. The delta tests now compare each delta build with a clean normal build of the same commits, including the branches of every document. Co-Authored-By: Claude Fable 5.2 --- gitindex/index.go | 64 +++++++++---------- gitindex/index_test.go | 135 +++++++++++++++++++++++++++++------------ 2 files changed, 123 insertions(+), 76 deletions(-) diff --git a/gitindex/index.go b/gitindex/index.go index 5cdd24641..c89c352a1 100644 --- a/gitindex/index.go +++ b/gitindex/index.go @@ -980,57 +980,45 @@ func prepareDeltaBuild(options Options, repository *git.Repository) (repos map[f return nil, nil, nil, fmt.Errorf("change #%d: getting files before and after change: %w", i, err) } - if newFile != nil { - // note: newFile.Name could be a path that isn't relative to the repository root - using the - // change's Name field is the only way that @ggilmore saw to get the full path relative to the root - newFileRelativeRootPath := c.To.Name - - // TODO@ggilmore: HACK - remove once ignore files are supported in delta builds - if newFileRelativeRootPath == ignore.IgnoreFile { - return nil, nil, nil, fmt.Errorf("%q file is not yet supported in delta builds", ignore.IgnoreFile) - } - - // either file is added or renamed, so we need to add the new version to the build - file := fileKey{Path: newFileRelativeRootPath, ID: newFile.Hash} - if existing, ok := repos[file]; ok { - existing.Branches = append(existing.Branches, branch.Name) - repos[file] = existing - } else { - repos[file] = BlobLocation{ - GitRepo: repository, - URL: u, - Branches: []string{branch.Name}, - } - } - } - - if oldFile == nil { - // file added - nothing more to do + if oldFile == nil && newFile == nil { + // not a file (e.g. a submodule) - nothing to index continue } - // Note: oldFile.Name could be a path that isn't relative to the repository root - using the - // change's "Name" field is the only way that ggilmore saw to get the full path relative to the root - oldFileRelativeRootPath := c.From.Name + // Renames aren't detected, so a change is about a single path. + // + // note: a file's Name could be a path that isn't relative to the repository root - using the + // change's Name field is the only way that @ggilmore saw to get the full path relative to the root + path := c.To.Name + if newFile == nil { + path = c.From.Name + } - if oldFileRelativeRootPath == ignore.IgnoreFile { + // TODO@ggilmore: HACK - remove once ignore files are supported in delta builds + if path == ignore.IgnoreFile { return nil, nil, nil, fmt.Errorf("%q file is not yet supported in delta builds", ignore.IgnoreFile) } - // The file is either modified or deleted. So, we need to add ALL versions - // of the old file (across all branches) to the build. + // A document carries every branch that has its blob at its path, so adding, modifying or + // deleting the file on one branch can change a document that other branches share. + // So, we need to add ALL current versions of the file (across all branches) to the build. + onOtherBranch := false for b, currentTree := range branchToCurrentTree { - f, err := currentTree.File(oldFileRelativeRootPath) + f, err := currentTree.File(path) if err != nil { // the file doesn't exist in this branch if errors.Is(err, object.ErrFileNotFound) { continue } - return nil, nil, nil, fmt.Errorf("getting hash for file %q in branch %q: %w", oldFile.Name, b, err) + return nil, nil, nil, fmt.Errorf("getting hash for file %q in branch %q: %w", path, b, err) + } + + if b != branch.Name { + onOtherBranch = true } - file := fileKey{Path: oldFileRelativeRootPath, ID: f.ID()} + file := fileKey{Path: path, ID: f.ID()} if existing, ok := repos[file]; ok { existing.Branches = append(existing.Branches, b) repos[file] = existing @@ -1043,7 +1031,11 @@ func prepareDeltaBuild(options Options, repository *git.Repository) (repos map[f } } - changedOrDeletedPaths = append(changedOrDeletedPaths, oldFileRelativeRootPath) + // Tombstone the path so that the versions added above replace the ones in the older shards. + // A file that is new to this branch and on no other branch isn't in those shards. + if oldFile != nil || onOtherBranch { + changedOrDeletedPaths = append(changedOrDeletedPaths, path) + } } } diff --git a/gitindex/index_test.go b/gitindex/index_test.go index d8d303751..af7de4cac 100644 --- a/gitindex/index_test.go +++ b/gitindex/index_test.go @@ -454,6 +454,31 @@ func TestIndexDeltaBasic(t *testing.T) { }, }, }, + { + name: "addition: file reaches a second branch", + branches: []string{"main", "release"}, + steps: []step{ + { + name: "setup", + addedDocuments: branchToDocumentMap{ + "main": []index.Document{fruitV1}, + }, + + expectedDocuments: []index.Document{fruitV1}, + }, + { + name: "add main's version of fruits to 'release'", + addedDocuments: branchToDocumentMap{ + "release": []index.Document{fruitV1}, + }, + optFn: func(t *testing.T, o *Options) { + o.BuildOptions.IsDelta = true + }, + + expectedDocuments: []index.Document{fruitV1}, + }, + }, + }, { name: "deletion", branches: []string{"main"}, @@ -941,56 +966,38 @@ func TestIndexDeltaBasic(t *testing.T) { t.Fatalf("expected normalBuildCalled to be %t, got %t", step.expectedFallbackToNormalBuild, normalBuildCalled) } - // examine outcome: load shards into a searcher instance and run a dummy search query - // that returns every document contained in the shards - // - // then, compare returned set of documents with the expected set for the step and see if they agree + // examine outcome: compare the set of documents in the shards with the expected set + // for the step and see if they agree - ss, err := search.NewDirectorySearcher(indexDir) - if err != nil { - t.Fatalf("NewDirectorySearcher(%s): %s", indexDir, err) - } - defer ss.Close() + receivedDocuments := indexedDocuments(t, indexDir) + sortDocuments(step.expectedDocuments) - searchOpts := &zoekt.SearchOptions{Whole: true} - result, err := ss.Search(context.Background(), &query.Const{Value: true}, searchOpts) - if err != nil { - t.Fatalf("Search: %s", err) + compareOptions := []cmp.Option{ + cmpopts.IgnoreFields(index.Document{}, "Branches"), + cmpopts.EquateEmpty(), } - var receivedDocuments []index.Document - for _, f := range result.Files { - receivedDocuments = append(receivedDocuments, index.Document{ - Name: f.FileName, - Content: f.Content, - }) + if diff := cmp.Diff(step.expectedDocuments, receivedDocuments, compareOptions...); diff != "" { + t.Errorf("diff in received documents (-want +got):%s\n:", diff) } - for _, docs := range [][]index.Document{step.expectedDocuments, receivedDocuments} { - sort.Slice(docs, func(i, j int) bool { - a, b := docs[i], docs[j] - - // first compare names, then fallback to contents if the names are equal - - if a.Name < b.Name { - return true - } - - if a.Name > b.Name { - return false - } - - return bytes.Compare(a.Content, b.Content) < 0 - }) + if !options.BuildOptions.IsDelta { + return } - compareOptions := []cmp.Option{ - cmpopts.IgnoreFields(index.Document{}, "Branches"), - cmpopts.EquateEmpty(), + // A delta build must leave the index with the same documents, on the same branches, + // as a clean normal build of the same commits. + fullOptions := options + fullOptions.BuildOptions.IndexDir = t.TempDir() + fullOptions.BuildOptions.IsDelta = false + + if _, err := IndexGitRepo(fullOptions); err != nil { + t.Fatalf("IndexGitRepo (clean normal build): %s", err) } - if diff := cmp.Diff(step.expectedDocuments, receivedDocuments, compareOptions...); diff != "" { - t.Errorf("diff in received documents (-want +got):%s\n:", diff) + fullDocuments := indexedDocuments(t, fullOptions.BuildOptions.IndexDir) + if diff := cmp.Diff(fullDocuments, receivedDocuments, cmpopts.EquateEmpty()); diff != "" { + t.Errorf("delta build differs from a clean normal build (-normal +delta):%s\n:", diff) } }) } @@ -998,6 +1005,54 @@ func TestIndexDeltaBasic(t *testing.T) { } } +// indexedDocuments returns every document in the shards of indexDir, with the branches it is on. +func indexedDocuments(t *testing.T, indexDir string) []index.Document { + t.Helper() + + ss, err := search.NewDirectorySearcher(indexDir) + if err != nil { + t.Fatalf("NewDirectorySearcher(%s): %s", indexDir, err) + } + defer ss.Close() + + // a dummy search query that returns every document contained in the shards + searchOpts := &zoekt.SearchOptions{Whole: true} + result, err := ss.Search(context.Background(), &query.Const{Value: true}, searchOpts) + if err != nil { + t.Fatalf("Search: %s", err) + } + + var docs []index.Document + for _, f := range result.Files { + docs = append(docs, index.Document{ + Name: f.FileName, + Content: f.Content, + Branches: f.Branches, + }) + } + + sortDocuments(docs) + return docs +} + +func sortDocuments(docs []index.Document) { + sort.Slice(docs, func(i, j int) bool { + a, b := docs[i], docs[j] + + // first compare names, then fallback to contents if the names are equal + + if a.Name < b.Name { + return true + } + + if a.Name > b.Name { + return false + } + + return bytes.Compare(a.Content, b.Content) < 0 + }) +} + func runGit(t *testing.T, cwd string, args ...string) { t.Helper() From 5634b7ffb27e198aec75721ab1c0b85651bf64b1 Mon Sep 17 00:00:00 2001 From: Jack Minnetian <270441393+BlueBottleLatte@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:01:34 -0500 Subject: [PATCH 2/3] fix(gitindex): apply each branch's ignore file to the files a delta build indexes A normal build leaves out the files that a branch's .sourcegraph/ignore matches. A delta build never read the ignore file. It only fell back to a normal build when the ignore file itself changed. So when a tracked file under an ignored path was added or modified, the delta build indexed it and its contents became searchable. A delta build now reads the ignore file at each branch's current commit. It skips a change to a path that the changed branch ignores, and it leaves a branch off a document when that branch ignores the path. A change to the ignore file still falls back to a normal build, because it can add or remove files that the diff doesn't mention. Co-Authored-By: Claude Fable 5.2 --- gitindex/index.go | 23 ++++++++++++++++++++++- gitindex/index_test.go | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 1 deletion(-) diff --git a/gitindex/index.go b/gitindex/index.go index c89c352a1..6814d7924 100644 --- a/gitindex/index.go +++ b/gitindex/index.go @@ -934,6 +934,9 @@ func prepareDeltaBuild(options Options, repository *git.Repository) (repos map[f // branch name -> git worktree at most current commit branchToCurrentTree := make(map[string]*object.Tree, len(branches)) + // branch name -> ignore rules at most current commit + branchToIgnoreMatcher := make(map[string]*ignore.Matcher, len(branches)) + for _, b := range branches { commit, err := getCommit(repository, options.BranchPrefix, b) if err != nil { @@ -946,6 +949,13 @@ func prepareDeltaBuild(options Options, repository *git.Repository) (repos map[f } branchToCurrentTree[b] = tree + + ig, err := newIgnoreMatcher(tree) + if err != nil { + return nil, nil, nil, fmt.Errorf("getting ignore rules for branch %q: %w", b, err) + } + + branchToIgnoreMatcher[b] = ig } rawURL := options.BuildOptions.RepositoryDescription.URL @@ -994,16 +1004,27 @@ func prepareDeltaBuild(options Options, repository *git.Repository) (repos map[f path = c.From.Name } - // TODO@ggilmore: HACK - remove once ignore files are supported in delta builds + // A change to the ignore file can add or remove files that this diff doesn't mention, so it + // needs a normal build. if path == ignore.IgnoreFile { return nil, nil, nil, fmt.Errorf("%q file is not yet supported in delta builds", ignore.IgnoreFile) } + // The ignore file is the same as in the last build, so a path that it matches wasn't + // indexed for this branch then and isn't now. + if branchToIgnoreMatcher[branch.Name].Match(path) { + continue + } + // A document carries every branch that has its blob at its path, so adding, modifying or // deleting the file on one branch can change a document that other branches share. // So, we need to add ALL current versions of the file (across all branches) to the build. onOtherBranch := false for b, currentTree := range branchToCurrentTree { + if branchToIgnoreMatcher[b].Match(path) { + continue + } + f, err := currentTree.File(path) if err != nil { // the file doesn't exist in this branch diff --git a/gitindex/index_test.go b/gitindex/index_test.go index af7de4cac..f5a8c1491 100644 --- a/gitindex/index_test.go +++ b/gitindex/index_test.go @@ -374,6 +374,11 @@ func TestIndexDeltaBasic(t *testing.T) { emptySourcegraphIgnore := index.Document{Name: ignore.IgnoreFile} sourcegraphIgnoreWithContent := index.Document{Name: ignore.IgnoreFile, Content: []byte("good_content.txt")} + sourcegraphIgnoreGenerated := index.Document{Name: ignore.IgnoreFile, Content: []byte("generated/")} + reportV1 := index.Document{Name: "generated/report.txt", Content: []byte("draft")} + reportV2 := index.Document{Name: "generated/report.txt", Content: []byte("final")} + summary := index.Document{Name: "generated/summary.txt", Content: []byte("summary")} + for _, test := range []struct { name string branches []string @@ -800,6 +805,33 @@ func TestIndexDeltaBasic(t *testing.T) { }, }, }, + { + name: "should apply each branch's Sourcegraph ignore file to added and modified files", + branches: []string{"main", "release"}, + steps: []step{ + { + name: "setup: only 'main' ignores the generated folder", + addedDocuments: branchToDocumentMap{ + "main": []index.Document{sourcegraphIgnoreGenerated, reportV1}, + "release": []index.Document{reportV1}, + }, + + expectedDocuments: []index.Document{sourcegraphIgnoreGenerated, reportV1}, + }, + { + name: "modify the report on both branches + add a summary on 'main'", + addedDocuments: branchToDocumentMap{ + "main": []index.Document{reportV2, summary}, + "release": []index.Document{reportV2}, + }, + optFn: func(t *testing.T, o *Options) { + o.BuildOptions.IsDelta = true + }, + + expectedDocuments: []index.Document{sourcegraphIgnoreGenerated, reportV2}, + }, + }, + }, { name: "should fallback to a full, normal build if the repository has more than the specified threshold of shards", branches: []string{"main"}, From 36e5276e035c48f0cdaa07bb754897406c0b9161 Mon Sep 17 00:00:00 2001 From: Jack Minnetian <270441393+BlueBottleLatte@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:48:24 -0500 Subject: [PATCH 3/3] fix(gitindex): handle each changed path once in a delta build A delta build diffs every branch against its last indexed commit. When several branches picked up the same commit, each branch's diff reported the same paths. For each report, the build looked the path up on every branch and added those branches to the document again. So the work grew with the square of the number of branches, and a document listed the same branch many times. Modified and deleted files already behaved this way. The two previous commits made added files do it too. The step that removed the repeated branches never took effect, because it wrote to a copy of the document. Documents are ranked by how many branches they list, so a file on two branches could rank above an otherwise identical file on three. A delta build now collects the changed paths from all the diffs first. It takes a branch's version of a path from that branch's diff, and looks the path up only on the branches that didn't change it. Those lookups read each directory once and share it between branches. A branch is added to a document once. A path is tombstoned if any branch had the file at its last indexed commit, whichever branch comes first. A file that is new to every branch that has it gets no tombstone. The build reads file modes from the diff instead of loading both versions of each file. Two things follow. A file that a submodule replaces, or the reverse, is now handled. Before, the change was skipped. And a change to a file whose content the clone doesn't have (a clone with a blob size filter) no longer makes the delta build fall back to a normal build. 64 branches fast-forwarding to a commit with 1,000 new files took 62s and 307 MiB before this commit. It now takes 0.46s and 110 MiB. The same with 1,000 modified files went from 67s to 0.40s. Co-Authored-By: Claude Fable 5.2 --- gitindex/index.go | 192 ++++++++++++++++++++++++++++------------- gitindex/index_test.go | 46 +++++++++- 2 files changed, 177 insertions(+), 61 deletions(-) diff --git a/gitindex/index.go b/gitindex/index.go index 6814d7924..e9af2bde4 100644 --- a/gitindex/index.go +++ b/gitindex/index.go @@ -36,7 +36,9 @@ import ( "github.com/go-git/go-git/v5/config" "github.com/go-git/go-git/v5/plumbing" "github.com/go-git/go-git/v5/plumbing/cache" + "github.com/go-git/go-git/v5/plumbing/filemode" "github.com/go-git/go-git/v5/plumbing/object" + "github.com/go-git/go-git/v5/plumbing/storer" "github.com/go-git/go-git/v5/storage/filesystem" "github.com/sourcegraph/zoekt" @@ -966,9 +968,30 @@ func prepareDeltaBuild(options Options, repository *git.Repository) (repos map[f // TODO: Support repository submodules for delta builds + // changedPath is a path that changed on at least one branch since the last build. + type changedPath struct { + // branches holds the indexes (in existingRepository.Branches) of the branches that changed + // the path, in ascending order. + branches []int + + // inOlderShards is true if a branch had the file at its last indexed commit. + inOlderShards bool + } + changedPaths := map[string]*changedPath{} + + addBranch := func(path string, id plumbing.Hash, branch string) { + file := fileKey{Path: path, ID: id} + location, ok := repos[file] + if !ok { + location = BlobLocation{GitRepo: repository, URL: u} + } + location.Branches = append(location.Branches, branch) + repos[file] = location + } + // loop over all branches, calculate the diff between our // last indexed commit and the current commit, and add files mentioned in the diff - for _, branch := range existingRepository.Branches { + for i, branch := range existingRepository.Branches { lastIndexedCommit, err := getCommit(repository, "", branch.Version) if err != nil { return nil, nil, nil, fmt.Errorf("getting last indexed commit for branch %q: %w", branch.Name, err) @@ -984,23 +1007,11 @@ func prepareDeltaBuild(options Options, repository *git.Repository) (repos map[f return nil, nil, nil, fmt.Errorf("generating changeset for branch %q: %w", branch.Name, err) } - for i, c := range changes { - oldFile, newFile, err := c.Files() - if err != nil { - return nil, nil, nil, fmt.Errorf("change #%d: getting files before and after change: %w", i, err) - } - - if oldFile == nil && newFile == nil { - // not a file (e.g. a submodule) - nothing to index - continue - } - - // Renames aren't detected, so a change is about a single path. - // - // note: a file's Name could be a path that isn't relative to the repository root - using the - // change's Name field is the only way that @ggilmore saw to get the full path relative to the root + for _, c := range changes { + // Renames aren't detected, so a change is about a single path. The side that doesn't + // have the path is empty. path := c.To.Name - if newFile == nil { + if path == "" { path = c.From.Name } @@ -1010,71 +1021,132 @@ func prepareDeltaBuild(options Options, repository *git.Repository) (repos map[f return nil, nil, nil, fmt.Errorf("%q file is not yet supported in delta builds", ignore.IgnoreFile) } + wasFile, isFile := isIndexedFile(c.From.TreeEntry.Mode), isIndexedFile(c.To.TreeEntry.Mode) + if !wasFile && !isFile { + // not a file (e.g. a submodule) - nothing to index + continue + } + // The ignore file is the same as in the last build, so a path that it matches wasn't // indexed for this branch then and isn't now. if branchToIgnoreMatcher[branch.Name].Match(path) { continue } - // A document carries every branch that has its blob at its path, so adding, modifying or - // deleting the file on one branch can change a document that other branches share. - // So, we need to add ALL current versions of the file (across all branches) to the build. - onOtherBranch := false - for b, currentTree := range branchToCurrentTree { - if branchToIgnoreMatcher[b].Match(path) { - continue - } + change := changedPaths[path] + if change == nil { + change = &changedPath{} + changedPaths[path] = change + } - f, err := currentTree.File(path) - if err != nil { - // the file doesn't exist in this branch - if errors.Is(err, object.ErrFileNotFound) { - continue - } + change.branches = append(change.branches, i) + if wasFile { + change.inOlderShards = true + } + if isFile { + addBranch(path, c.To.TreeEntry.Hash, branch.Name) + } + } + } - return nil, nil, nil, fmt.Errorf("getting hash for file %q in branch %q: %w", path, b, err) - } + // A document carries every branch that has its blob at its path, so a change on one branch can + // change a document that other branches share. So, the build needs the current version of each + // changed path from the branches that didn't change it too. + files := treeFiles{storer: repository.Storer, dirs: map[plumbing.Hash]*object.Tree{}} + for path, change := range changedPaths { + changedOn := change.branches + for i, branch := range existingRepository.Branches { + if len(changedOn) > 0 && changedOn[0] == i { + // the branch's diff already gave its version + changedOn = changedOn[1:] + continue + } - if b != branch.Name { - onOtherBranch = true - } + if branchToIgnoreMatcher[branch.Name].Match(path) { + continue + } - file := fileKey{Path: path, ID: f.ID()} - if existing, ok := repos[file]; ok { - existing.Branches = append(existing.Branches, b) - repos[file] = existing - } else { - repos[file] = BlobLocation{ - GitRepo: repository, - URL: u, - Branches: []string{b}, - } - } + entry, err := files.entry(branchToCurrentTree[branch.Name], path) + if err != nil { + return nil, nil, nil, fmt.Errorf("getting file %q in branch %q: %w", path, branch.Name, err) } - // Tombstone the path so that the versions added above replace the ones in the older shards. - // A file that is new to this branch and on no other branch isn't in those shards. - if oldFile != nil || onOtherBranch { - changedOrDeletedPaths = append(changedOrDeletedPaths, path) + if entry == nil { + continue } + + // the branch didn't change the file, so it had it at its last indexed commit + change.inOlderShards = true + addBranch(path, entry.Hash, branch.Name) } - } - // we need to de-duplicate the branch map before returning it - it's possible for the same - // branch to have been added multiple times if a file has been modified across multiple commits - for _, info := range repos { - sort.Strings(info.Branches) - info.Branches = uniq(info.Branches) + // Tombstone the path so that the versions added above replace the ones in the older shards. + // A file that is new to every branch that has it isn't in those shards. + if change.inOlderShards { + changedOrDeletedPaths = append(changedOrDeletedPaths, path) + } } - // we also need to de-duplicate the list of changed or deleted file paths, it's also possible to have duplicates - // for the same reasoning as above sort.Strings(changedOrDeletedPaths) - changedOrDeletedPaths = uniq(changedOrDeletedPaths) return repos, nil, changedOrDeletedPaths, nil } +// isIndexedFile reports whether a tree entry with the given mode is a file that gets a document. +// It has to agree with RepoWalker.handleEntry, which decides this for normal builds. +func isIndexedFile(mode filemode.FileMode) bool { + switch mode { + case filemode.Regular, filemode.Executable, filemode.Symlink: + return true + default: + return false + } +} + +// treeFiles finds files in git trees. It keeps the directories it reads, so that branches share +// the ones they have in common. +type treeFiles struct { + storer storer.EncodedObjectStorer + dirs map[plumbing.Hash]*object.Tree +} + +// entry returns the tree's entry for the file at path, or nil if the tree has no file there. +func (f *treeFiles) entry(tree *object.Tree, path string) (*object.TreeEntry, error) { + for { + name, rest, inDir := strings.Cut(path, "/") + + entry, err := tree.FindEntry(name) + if errors.Is(err, object.ErrEntryNotFound) { + return nil, nil + } + if err != nil { + return nil, err + } + + if !inDir { + if !isIndexedFile(entry.Mode) { + return nil, nil + } + return entry, nil + } + + if entry.Mode != filemode.Dir { + return nil, nil + } + + dir, ok := f.dirs[entry.Hash] + if !ok { + dir, err = object.GetTree(f.storer, entry.Hash) + if err != nil { + return nil, err + } + f.dirs[entry.Hash] = dir + } + + tree, path = dir, rest + } +} + func prepareNormalBuild(options Options, repository *git.Repository) (repos map[fileKey]BlobLocation, branchVersions map[string]map[string]plumbing.Hash, err error) { var repoCache *RepoCache if options.Submodules && options.RepoCacheDir != "" { diff --git a/gitindex/index_test.go b/gitindex/index_test.go index f5a8c1491..e945c0292 100644 --- a/gitindex/index_test.go +++ b/gitindex/index_test.go @@ -23,6 +23,7 @@ import ( "os/exec" "path/filepath" "runtime" + "slices" "sort" "strings" "testing" @@ -484,6 +485,37 @@ func TestIndexDeltaBasic(t *testing.T) { }, }, }, + { + name: "addition and deletion of the same file on different branches", + branches: []string{"main", "release"}, + steps: []step{ + { + name: "setup", + addedDocuments: branchToDocumentMap{ + "main": []index.Document{fruitV1}, + "release": []index.Document{foo}, + }, + + expectedDocuments: []index.Document{fruitV1, foo}, + }, + { + name: "move fruits from 'main' to 'release' + move foo from 'release' to 'main'", + addedDocuments: branchToDocumentMap{ + "main": []index.Document{foo}, + "release": []index.Document{fruitV1}, + }, + deletedDocuments: branchToDocumentMap{ + "main": []index.Document{fruitV1}, + "release": []index.Document{foo}, + }, + optFn: func(t *testing.T, o *Options) { + o.BuildOptions.IsDelta = true + }, + + expectedDocuments: []index.Document{fruitV1, foo}, + }, + }, + }, { name: "deletion", branches: []string{"main"}, @@ -969,7 +1001,19 @@ func TestIndexDeltaBasic(t *testing.T) { deltaBuildCalled := false prepareDeltaSpy := func(options Options, repository *git.Repository) (repos map[fileKey]BlobLocation, branchVersions map[string]map[string]plumbing.Hash, changedOrDeletedPaths []string, err error) { deltaBuildCalled = true - return prepareDeltaBuild(options, repository) + repos, branchVersions, changedOrDeletedPaths, err = prepareDeltaBuild(options, repository) + + // Documents are ranked by how many branches they list, so a branch that is + // listed twice ranks its document too high. + for file, location := range repos { + branches := slices.Clone(location.Branches) + slices.Sort(branches) + if len(slices.Compact(branches)) != len(location.Branches) { + t.Errorf("%q lists a branch more than once: %v", file.Path, location.Branches) + } + } + + return repos, branchVersions, changedOrDeletedPaths, err } normalBuildCalled := false