Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 35 additions & 31 deletions gitindex/index.go
Original file line number Diff line number Diff line change
Expand Up @@ -1432,59 +1432,63 @@ func diffTreesGoGit(from, to *object.Tree) ([]fileChange, error) {
// lsTreeFiles returns the IDs of the files at paths in commit, using git
// ls-tree. Paths with no file in commit are missing from the result.
func lsTreeFiles(gitDir string, commit plumbing.Hash, paths map[string]struct{}) (map[string]plumbing.Hash, error) {
cmd := gitCommand(gitDir, "ls-tree", "-r", "-z", "--full-tree", commit.String())
files := map[string]plumbing.Hash{}
err := lsTree(gitDir, commit, func(p string, e object.TreeEntry) {
if _, ok := paths[p]; ok && e.Mode.IsFile() {
files[p] = e.Hash
}
})
return files, err
}

// lsTree calls fn with the path and entry of every non-tree entry below
// treeish, such as files and submodules, using git ls-tree -r. It fails if a
// tree is missing.
func lsTree(gitDir string, treeish plumbing.Hash, fn func(path string, e object.TreeEntry)) error {
cmd := gitCommand(gitDir, "ls-tree", "-r", "-z", "--full-tree", treeish.String())
var stderr bytes.Buffer
cmd.Stderr = &stderr
out, err := cmd.StdoutPipe()
if err != nil {
return nil, err
return err
}
if err := cmd.Start(); err != nil {
return nil, fmt.Errorf("start git ls-tree: %w", err)
return fmt.Errorf("start git ls-tree: %w", err)
}

files := map[string]plumbing.Hash{}
// Each entry is "<mode> <type> <ID>\t<path>\0".
var parseErr error
r := bufio.NewReaderSize(out, 64*1024)
for {
mode, _, id, p, err := readLsTreeEntry(r)
line, err := r.ReadString(0)
if err == io.EOF && line == "" {
break
}
if err != nil {
if err != io.EOF {
parseErr = err
}
parseErr = err
break
}
if _, ok := paths[p]; ok && isFileMode(mode) {
files[p] = plumbing.NewHash(id)
meta, p, ok := strings.Cut(line[:len(line)-1], "\t")
fields := strings.Fields(meta)
var mode filemode.FileMode
if ok && len(fields) == 3 {
mode, err = filemode.New(fields[0])
}
if !ok || len(fields) != 3 || err != nil || !plumbing.IsHash(fields[2]) {
parseErr = fmt.Errorf("unexpected entry %q", line)
break
}
fn(p, object.TreeEntry{Name: path.Base(p), Mode: mode, Hash: plumbing.NewHash(fields[2])})
}
// Drain stdout so git can exit before we wait for it.
_, _ = io.Copy(io.Discard, r)
if err := cmd.Wait(); err != nil {
return nil, fmt.Errorf("git ls-tree %s: %w: %s", commit, err, bytes.TrimSpace(stderr.Bytes()))
return fmt.Errorf("git ls-tree %s: %w: %s", treeish, err, bytes.TrimSpace(stderr.Bytes()))
}
if parseErr != nil {
return nil, fmt.Errorf("git ls-tree %s: %w", commit, parseErr)
}
return files, nil
}

// readLsTreeEntry reads one "<mode> <type> <ID>\t<path>\0" entry of git
// ls-tree -z output.
func readLsTreeEntry(r *bufio.Reader) (mode, typ, id, path string, err error) {
line, err := r.ReadString(0)
if err != nil {
if err == io.EOF && line != "" {
err = io.ErrUnexpectedEOF
}
return "", "", "", "", err
return fmt.Errorf("git ls-tree %s: %w", treeish, parseErr)
}
meta, path, ok := strings.Cut(line[:len(line)-1], "\t")
fields := strings.Fields(meta)
if !ok || len(fields) != 3 {
return "", "", "", "", fmt.Errorf("unexpected ls-tree entry %q", line)
}
return fields[0], fields[1], fields[2], path, nil
return nil
}

// isFileMode reports whether a git tree entry mode, in octal, is a file:
Expand Down
29 changes: 27 additions & 2 deletions gitindex/tree.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,11 +112,36 @@ func (rw *RepoWalker) CollectFiles(t *object.Tree, branch string) (map[string]pl
return nil, fmt.Errorf("newIgnoreMatcher: %w", err)
}

// Path => commit SHA1
subRepoVersions := make(map[string]plumbing.Hash)

// The git binary lists the tree unless ZOEKT_DISABLE_CATFILE_BATCH=true
// selects the go-git fallback.
if gitDir, ok := repoGitDir(rw.repo); ok && !gitBinaryDisabled() {
type entry struct {
path string
e object.TreeEntry
}
// Collect all entries first, so a failed listing changes nothing.
var entries []entry
err := lsTree(gitDir, t.Hash, func(p string, e object.TreeEntry) {
entries = append(entries, entry{p, e})
})
if err == nil {
for _, e := range entries {
if err := rw.handleEntry(e.path, &e.e, branch, subRepoVersions, ig); err != nil {
return nil, fmt.Errorf("handleEntry: %w", err)
}
}
return subRepoVersions, nil
}
// ls-tree fails on a missing tree, which the go-git walk skips.
slog.Info("git ls-tree failed, walking the tree with go-git", "branch", branch, "error", err)
}

tw := object.NewTreeWalker(t, true, make(map[plumbing.Hash]bool))
defer tw.Close()

// Path => commit SHA1
subRepoVersions := make(map[string]plumbing.Hash)
skippedTrees := 0
for {
name, entry, err := tw.Next()
Expand Down
60 changes: 60 additions & 0 deletions gitindex/tree_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (
"path/filepath"
"reflect"
"sort"
"strings"
"testing"
"time"

Expand Down Expand Up @@ -705,3 +706,62 @@ func TestLatestCommit(t *testing.T) {
t.Fatalf("want %s, got %s", want, rlist.Repos[0].Repository.LatestCommitDate)
}
}

// A tree whose object is missing is skipped and the rest is indexed, whether
// git ls-tree or the go-git walk lists the files.
func TestIndexGitRepo_MissingTree(t *testing.T) {
for _, disableGitBinary := range []string{"false", "true"} {
t.Run("ZOEKT_DISABLE_CATFILE_BATCH="+disableGitBinary, func(t *testing.T) {
t.Setenv("ZOEKT_DISABLE_CATFILE_BATCH", disableGitBinary)

dir := t.TempDir()
testutil.RunGit(t, dir, "init", "-b", "main")
for _, name := range []string{"a.txt", "lost/b.txt", "kept/c.txt"} {
if err := os.MkdirAll(filepath.Dir(filepath.Join(dir, name)), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, name), []byte(name), 0o644); err != nil {
t.Fatal(err)
}
}
testutil.RunGit(t, dir, "add", "-A")
testutil.RunGit(t, dir, "commit", "-m", "files")
lost := strings.TrimSpace(testutil.RunGit(t, dir, "rev-parse", "HEAD:lost"))
if err := os.Remove(filepath.Join(dir, ".git", "objects", lost[:2], lost[2:])); err != nil {
t.Fatal(err)
}

indexDir := t.TempDir()
opts := Options{
RepoDir: filepath.Join(dir, ".git"),
Branches: []string{"main"},
BuildOptions: index.Options{
IndexDir: indexDir,
RepositoryDescription: zoekt.Repository{Name: "repo"},
DisableCTags: true,
},
}
if _, err := IndexGitRepo(opts); err != nil {
t.Fatal(err)
}

ss, err := search.NewDirectorySearcher(indexDir)
if err != nil {
t.Fatal(err)
}
defer ss.Close()
res, err := ss.Search(context.Background(), &query.Const{Value: true}, &zoekt.SearchOptions{})
if err != nil {
t.Fatal(err)
}
var got []string
for _, f := range res.Files {
got = append(got, f.FileName)
}
sort.Strings(got)
if want := []string{"a.txt", "kept/c.txt"}; !cmp.Equal(got, want) {
t.Errorf("indexed files %v, want %v", got, want)
}
})
}
}