Skip to content
Merged
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
53 changes: 53 additions & 0 deletions internal/timber/list_collection.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package timber

import "sync"

const listRepositoryConcurrency = 8

func collectListedWorktrees(runtime Runtime, repos []registeredRepo, enrich worktreeEnricher) ([]managedWorktree, error) {
type result struct {
worktrees []managedWorktree
err error
}
results := make([]result, len(repos))
jobs := make(chan int)
var workers sync.WaitGroup
for range min(listRepositoryConcurrency, len(repos)) {
workers.Go(func() {
for index := range jobs {
results[index].worktrees, results[index].err = listRepositoryWorktrees(runtime, repos[index], enrich)
}
})
}
for index := range repos {
jobs <- index
}
close(jobs)
workers.Wait()

// Preserve serial ordering, including which error is reported first.
worktrees := make([]managedWorktree, 0)
for _, result := range results {
if result.err != nil {
return nil, result.err
}
worktrees = append(worktrees, result.worktrees...)
}
return worktrees, nil
}

func listRepositoryWorktrees(runtime Runtime, repo registeredRepo, enrich worktreeEnricher) ([]managedWorktree, error) {
repository := new(Repository{GitDir: repo.GitDir, Runtime: runtime})
worktrees, err := runtime.managedWorktreesFromRepository(repository, repo.Name)
if err != nil {
return nil, err
}
for i, worktree := range worktrees {
enriched, err := enrich(repository, worktree)
if err != nil {
return nil, err
}
worktrees[i] = enriched
}
return worktrees, nil
}
20 changes: 19 additions & 1 deletion internal/timber/registry.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
package timber

import (
"fmt"
"strings"
)

type registeredRepo struct {
Name string
BarePath string
GitDir string // Git's absolute directory, resolved during registration discovery.
}

func (x registeredRepo) alias(runtime Runtime, origin string) string {
Expand All @@ -22,5 +28,17 @@ func (x registeredRepo) originURL(runtime Runtime) string {
}

func (x registeredRepo) ref() RepoRef {
return RepoRef(x)
return RepoRef{Name: x.Name, BarePath: x.BarePath}
}

func registeredBareGitDir(runtime Runtime, path string) (string, error) {
result, err := gitOutput(runtime, path, "rev-parse", "--absolute-git-dir", "--is-bare-repository")
if err != nil {
return "", err
}
dir, bare, _ := strings.CutLast(result.stdout, "\n")
if bare != "true" {
return "", fmt.Errorf("repository at %q is not bare", path)
}
return strings.TrimSpace(dir), nil
}
76 changes: 76 additions & 0 deletions internal/timber/review/patch_attributes.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package review

import (
"context"
"fmt"
"maps"
"slices"
"strings"
)

// Ask Git to resolve attributes once, but key each stack with only the
// attributes of its own changed paths.
func stackPatchAttributes(ctx context.Context, r Repository, stacks []Stack) (map[string]string, error) {
pathsByTip, err := snapshotPatchPaths(ctx, r, stacks)
if err != nil {
return nil, err
}
attributesByPath, err := resolvePatchAttributes(ctx, r, pathsByTip)
if err != nil {
return nil, err
}
attributesByTip := make(map[string]string, len(stacks))
for tip, paths := range pathsByTip {
slices.Sort(paths)
var attributes strings.Builder
for _, path := range slices.Compact(paths) {
attributes.WriteString(attributesByPath[path])
}
attributesByTip[tip] = attributes.String()
}
return attributesByTip, nil
}

func resolvePatchAttributes(ctx context.Context, r Repository, pathsByTip map[string][]string) (map[string]string, error) {
uniquePaths := make(map[string]struct{})
for paths := range maps.Values(pathsByTip) {
for _, path := range paths {
uniquePaths[path] = struct{}{}
}
}
if len(uniquePaths) == 0 {
return nil, nil
}
paths := slices.Sorted(maps.Keys(uniquePaths))
out, err := r.gitInput(ctx, strings.Join(paths, "\x00")+"\x00", "check-attr", "--all", "--stdin", "-z")
if err != nil {
return nil, err
}
return parsePatchAttributes(out)
}

func parsePatchAttributes(out string) (map[string]string, error) {
if out == "" {
return nil, nil
}
records := strings.Split(out, "\x00")
if !validAttributeRecords(records) {
return nil, fmt.Errorf("invalid Git check-attr records")
}
byPath := make(map[string][]string)
for i := 0; i < len(records)-1; i += 3 {
path, name, value := records[i], records[i+1], records[i+2]
byPath[path] = append(byPath[path], path+"\x00"+name+"\x00"+value+"\x00")
}
attributes := make(map[string]string, len(byPath))
for path, entries := range byPath {
// Git's attribute output order can depend on the other paths queried.
slices.Sort(entries)
attributes[path] = strings.Join(entries, "")
}
return attributes, nil
}

func validAttributeRecords(records []string) bool {
return isSame(len(records)%3, 1) && isSame(records[len(records)-1], "")
}
44 changes: 14 additions & 30 deletions internal/timber/review/patch_cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,30 +7,22 @@ import (
"io"
"os"
"path/filepath"
"slices"
"strings"
)

// The cache is disposable and independent of review state. Each entry includes
// the fingerprint version, immutable endpoints, and Git's effective diff inputs.
type patchCache struct {
dir, context string
repo string
writable bool
dir, context string
attributesByTip map[string]string
writable bool
}

func (c *patchCache) hash(ctx context.Context, r Repository, base, tip string) (string, error) {
if c == nil {
return r.patchHash(ctx, base, tip)
}
root := r
root.Dir = c.repo
attributes, err := patchAttributes(ctx, root, base, tip)
if err != nil {
r.logger().Debug("Patch cache unavailable", "error", err)
return r.patchHash(ctx, base, tip)
}
key := fmt.Sprintf("%x.patch", sha256.Sum256([]byte(c.context+"\x00"+attributes+"\x00"+base+"\x00"+tip)))
key := fmt.Sprintf("%x.patch", sha256.Sum256([]byte(c.context+"\x00"+c.attributesByTip[tip]+"\x00"+base+"\x00"+tip)))
path := filepath.Join(c.dir, key)
if hash, ok := readPatchCache(path); ok {
r.logger().Debug("Patch cache hit", "tip", tip)
Expand Down Expand Up @@ -72,7 +64,16 @@ func newPatchCache(ctx context.Context, r Repository, view Snapshot, repo string
return nil
}
inputs := []string{"patch-context-v3", version, config, environmentValue(r.Environment, "GIT_DIFF_OPTS"), environmentValue(r.Environment, "GIT_ATTR_SOURCE")}
cache := &patchCache{dir: patchCachePath(view), repo: repo, context: fmt.Sprintf("%x", sha256.Sum256([]byte(strings.Join(inputs, "\x00"))))}
attributes, err := stackPatchAttributes(ctx, root, view.Stacks)
if err != nil {
r.logger().Debug("Patch cache unavailable", "error", err)
return nil
}
cache := new(patchCache{
dir: patchCachePath(view),
context: fmt.Sprintf("%x", sha256.Sum256([]byte(strings.Join(inputs, "\x00")))),
attributesByTip: attributes,
})
if err := os.MkdirAll(cache.dir, 0o700); err != nil {
r.logger().Debug("Patch cache is read-only", "error", err)
} else {
Expand All @@ -81,23 +82,6 @@ func newPatchCache(ctx context.Context, r Repository, view Snapshot, repo string
return cache
}

// Attribute inputs belong to one stack, not the snapshot that selected it.
// Git resolves worktree, index, info, and global/system attribute sources.
func patchAttributes(ctx context.Context, r Repository, base, tip string) (string, error) {
paths, err := r.gitOutput(ctx, "diff-tree", "--no-commit-id", "--name-only", "--no-renames", "-r", "-z", base, tip)
if err != nil {
return "", err
}
names := strings.Split(strings.TrimSuffix(paths, "\x00"), "\x00")
slices.Sort(names)
names = slices.Compact(names)
input := ""
if paths != "" {
input = strings.Join(names, "\x00") + "\x00"
}
return r.gitInput(ctx, input, "check-attr", "--all", "--stdin", "-z")
}

func readPatchCache(path string) (string, bool) {
file, err := os.Open(path)
if err != nil {
Expand Down
22 changes: 22 additions & 0 deletions internal/timber/review/patch_cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"testing"

"charm.land/log/v2"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

Expand Down Expand Up @@ -80,6 +81,27 @@ func TestSnapshotPatchCacheTracksDiffInputs(t *testing.T) {
}
}

func TestSnapshotRefreshesPatchForAttributesOnOneOfSeveralStacks(t *testing.T) {
r := testRepo(t)
for _, path := range []string{"first file", "second"} {
require.NoError(t, os.WriteFile(filepath.Join(r.Dir, path), []byte("text\n"), 0o600))
gitTest(t, r.Dir, "add", "--", path)
gitTest(t, r.Dir, "commit", "-m", "Add "+path)
}
before, err := r.Snapshot(t.Context())
require.NoError(t, err)
require.Len(t, before.Stacks, 2)

attributes := filepath.Join(r.Dir, ".git", "info", "attributes")
require.NoError(t, os.WriteFile(attributes, []byte("\"first file\" -diff\n"), 0o600))
after, err := r.Snapshot(t.Context())
require.NoError(t, err)
require.Len(t, after.Stacks, 2)
assert.Equal(t, before.Head, after.Head)
assert.NotEqual(t, before.Stacks[0].PatchHash, after.Stacks[0].PatchHash)
assert.Equal(t, before.Stacks[1].PatchHash, after.Stacks[1].PatchHash)
}

func TestSnapshotPatchCacheFailureIsDisposable(t *testing.T) {
for _, failure := range []string{"corrupt", "unavailable"} {
t.Run(failure, func(t *testing.T) {
Expand Down
89 changes: 89 additions & 0 deletions internal/timber/review/patch_paths.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
package review

import (
"context"
"fmt"
"strings"
)

func snapshotPatchPaths(ctx context.Context, r Repository, stacks []Stack) (map[string][]string, error) {
if len(stacks) > 1 {
paths, err := batchPatchPaths(ctx, r, stacks)
if err == nil {
return paths, nil
}
r.logger().Debug("Batched patch paths unavailable", "error", err)
}
pathsByTip := make(map[string][]string, len(stacks))
for _, stack := range stacks {
paths, err := patchPaths(ctx, r, stack.Base, stack.Tip)
if err != nil {
return nil, err
}
pathsByTip[stack.Tip] = paths
}
return pathsByTip, nil
}

func patchPaths(ctx context.Context, r Repository, base, tip string) ([]string, error) {
out, err := r.gitOutput(ctx, "diff-tree", "--no-commit-id", "--name-only", "--no-renames", "-r", "-z", base, tip)
if err != nil {
return nil, err
}
if out == "" {
return nil, nil
}
return strings.Split(strings.TrimSuffix(out, "\x00"), "\x00"), nil
}

func batchPatchPaths(ctx context.Context, r Repository, stacks []Stack) (map[string][]string, error) {
var input strings.Builder
for _, stack := range stacks {
input.WriteString(stack.Tip)
input.WriteByte(' ')
input.WriteString(stack.Base)
input.WriteByte('\n')
}
// On stdin, the second commit supplies the parent for the first.
// Raw records separate paths from commit headers, even when a path
// looks like a commit ID. --always includes headers for empty diffs.
out, err := r.gitInput(ctx, input.String(), "diff-tree", "--stdin", "--raw", "--no-renames", "-r", "-z", "--always")
if err != nil {
return nil, err
}
return parseBatchPatchPaths(out, stacks)
}

func parseBatchPatchPaths(out string, stacks []Stack) (map[string][]string, error) {
pathsByTip := make(map[string][]string, len(stacks))
for _, stack := range stacks {
tip, records, ok := strings.Cut(out, "\x00")
if !ok || !isSame(tip, stack.Tip) {
return nil, fmt.Errorf("missing Git diff-tree header for %s", stack.Tip)
}
paths, rest, err := takeBatchPatchPaths(records)
if err != nil {
return nil, err
}
pathsByTip[tip] = paths
out = rest
}
if out != "" {
return nil, fmt.Errorf("unexpected trailing Git diff-tree records")
}
return pathsByTip, nil
}

func takeBatchPatchPaths(out string) ([]string, string, error) {
var paths []string
for strings.HasPrefix(out, ":") {
_, afterHeader, _ := strings.Cut(out, "\x00")
path, rest, ok := strings.Cut(afterHeader, "\x00")
if !ok || isEmpty(path) {
return nil, "", fmt.Errorf("invalid Git diff-tree path record")
}
paths = append(paths, path)
out = rest
}
return paths, out, nil
}
Loading
Loading