diff --git a/gitindex/index.go b/gitindex/index.go index 5cdd24641..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" @@ -934,6 +936,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 +951,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 @@ -956,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) @@ -974,94 +1007,146 @@ 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) + 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 path == "" { + path = c.From.Name } - 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) - } + // 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) + } - // 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}, - } - } + 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 } - if oldFile == nil { - // file added - nothing more to do + // 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 } - // 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 + change := changedPaths[path] + if change == nil { + change = &changedPath{} + changedPaths[path] = change + } - if oldFileRelativeRootPath == ignore.IgnoreFile { - return nil, nil, nil, fmt.Errorf("%q file is not yet supported in delta builds", ignore.IgnoreFile) + change.branches = append(change.branches, i) + if wasFile { + change.inOlderShards = true + } + if isFile { + addBranch(path, c.To.TreeEntry.Hash, branch.Name) } + } + } - // The file is either modified or deleted. So, we need to add ALL versions - // of the old file (across all branches) to the build. - for b, currentTree := range branchToCurrentTree { - f, err := currentTree.File(oldFileRelativeRootPath) - if err != nil { - // the file doesn't exist in this branch - if errors.Is(err, object.ErrFileNotFound) { - continue - } + // 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 + } - return nil, nil, nil, fmt.Errorf("getting hash for file %q in branch %q: %w", oldFile.Name, b, err) - } + if branchToIgnoreMatcher[branch.Name].Match(path) { + continue + } - file := fileKey{Path: oldFileRelativeRootPath, 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) + } + + if entry == nil { + continue } - changedOrDeletedPaths = append(changedOrDeletedPaths, oldFileRelativeRootPath) + // 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 d8d303751..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" @@ -374,6 +375,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 @@ -454,6 +460,62 @@ 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: "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"}, @@ -775,6 +837,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"}, @@ -912,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 @@ -941,56 +1042,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 +1081,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()