test: replace worktree removal process matrix (bd-kuqlg.2) (#5280)

This commit is contained in:
Julian Knutsen 2026-08-02 09:34:29 -07:00 • committed by GitHub
commit bf87097a79
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 901 additions and 1552 deletions

View file

@ -3,10 +3,7 @@ package main
import (
"context"
"errors"
"os"
"path/filepath"
"reflect"
"runtime"
"strings"
"testing"
@ -149,28 +146,6 @@ func TestWorktreeRemovalOrchestrationPresentsPartialRemoveFailure(t *testing.T)
}
}
func TestWorktreeRemovalCommandUsesPolicyPinnedMutation(t *testing.T) {
observer := &recordingWorktreeRemovalObserver{
prepare: worktreeRemovalFacts(worktreeremove.IgnoreAbsent),
revalidation: []worktreeremove.RevalidationFacts{worktreeRemovalRevalidationFacts(worktreeremove.Normal)},
}
mutator := &recordingWorktreeRemovalMutator{}
err := runWorktreeRemovalOrchestration(
context.Background(),
worktreeRemovalRequest{mode: worktreeremove.Normal},
observer,
mutator,
&recordingWorktreeRemovalPresenter{},
)
if err != nil {
t.Fatalf("runWorktreeRemovalOrchestration() error = %v", err)
}
if want := []worktreeremove.Mutation{{TargetPath: "/exact/registry/path", Force: false}}; !reflect.DeepEqual(mutator.removals, want) {
t.Fatalf("removals = %#v, want %#v", mutator.removals, want)
}
}
func TestWorktreeRemovalCommandRefusesStaleApprovalAndPrepareDiagnostic(t *testing.T) {
for _, tt := range []struct {
name string
@ -218,43 +193,6 @@ func TestWorktreeRemovalCommandRefusesStaleApprovalAndPrepareDiagnostic(t *testi
}
}
func TestWorktreeRemovalGitAdapterUsesExactApprovedArgs(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("the recording git executable is a POSIX shell script")
}
dir := t.TempDir()
argsPath := filepath.Join(dir, "args")
gitPath := filepath.Join(dir, "git")
if err := os.WriteFile(gitPath, []byte("#!/bin/sh\nprintf '%s\\n' \"$@\" > \"$WORKTREE_REMOVE_ARGS_FILE\"\n"), 0755); err != nil {
t.Fatalf("write recording git: %v", err)
}
adapter := &gitWorktreeRemovalAdapter{plan: &worktreeRemovalPlan{
git: &worktreeRemovalGit{executable: gitPath, env: []string{"WORKTREE_REMOVE_ARGS_FILE=" + argsPath}},
executionRoot: dir,
target: pinnedWorktreeTarget{path: "/exact/registered path"},
force: true,
}}
mutation := worktreeremove.Mutation{TargetPath: "/exact/registered path", Force: true}
if err := adapter.Remove(context.Background(), mutation); err != nil {
t.Fatalf("Remove() error = %v", err)
}
got, err := os.ReadFile(argsPath)
if err != nil {
t.Fatalf("read recorded git arguments: %v", err)
}
if want := "-c\ncore.hooksPath=\n-c\ncore.fsmonitor=false\n-c\ncore.ignorecase=false\nworktree\nremove\n--force\n--\n/exact/registered path\n"; string(got) != want {
t.Fatalf("git arguments = %q, want %q", got, want)
}
if err := adapter.Remove(context.Background(), worktreeremove.Mutation{TargetPath: "/forged/path", Force: true}); err == nil {
t.Fatal("Remove() accepted a forged target path")
}
adapter.plan.gitignoreCleanup = &gitignoreCleanupPlan{entry: "nested/lane"}
if err := adapter.Cleanup(context.Background(), worktreeremove.Cleanup{Entry: "other/lane"}); err == nil {
t.Fatal("Cleanup() accepted a forged managed-ignore entry")
}
}
type recordingWorktreeRemovalObserver struct {
prepare worktreeremove.PrepareFacts
prepareErr error

View file

@ -0,0 +1,538 @@
package main
import (
"bytes"
"context"
"os"
"path/filepath"
"strings"
"testing"
"github.com/steveyegge/beads/internal/worktreeremove"
)
// runWorktreeRemoveGitAdapter exercises the real Git and filesystem adapter
// without the child-process Cobra harness. Command grammar has its own unit
// coverage; these contracts own the adapter's observations and mutations.
func runWorktreeRemoveGitAdapter(
t *testing.T,
dir, name string,
force bool,
mergedInto string,
hooks worktreeRemoveHooks,
) error {
t.Helper()
if force && mergedInto != "" {
t.Fatalf("force adapter test requested unreachable comparator state %q", mergedInto)
}
t.Chdir(dir)
options := &worktreeRemoveOptions{
force: singleWorktreeBoolFlag{name: "force", value: force, set: force},
}
if mergedInto != "" {
options.mergedInto = singleWorktreeStringFlag{name: "merged-into", value: mergedInto, set: true}
}
mode := worktreeremove.Normal
if force {
mode = worktreeremove.Force
}
adapter := &gitWorktreeRemovalAdapter{name: name, options: options, hooks: hooks}
return runWorktreeRemovalOrchestration(
context.Background(),
worktreeRemovalRequest{mode: mode},
adapter,
adapter,
cliWorktreeRemovalPresenter{},
)
}
func requireWorktreeRemoveGitAdapterFailure(t *testing.T, err error, want string) {
t.Helper()
if err == nil || !strings.Contains(err.Error(), want) {
t.Fatalf("adapter removal error = %v, want substring %q", err, want)
}
}
func TestWorktreeRemoveGitAdapterSafetyRefusals(t *testing.T) {
tests := []struct {
name string
setup func(*testing.T, *worktreeRemovalFixture)
force bool
compare func(*worktreeRemovalFixture) string
wantErr string
}{
{"ignored status", func(t *testing.T, f *worktreeRemovalFixture) {
f.writeLaneFile(t, filepath.Join("ignored", "cache.bin"), "ignored\n")
}, false, func(f *worktreeRemovalFixture) string { return "main" }, "modified, untracked, or ignored files"},
{"missing upstream", nil, false, nil, "no single resolvable upstream"},
{"configured upstream tag collision", func(t *testing.T, f *worktreeRemovalFixture) {
f.setUpstream(t)
f.commitLane(t, "ahead of upstream")
f.git(t, f.repo, "tag", "heads/main", "lane")
}, false, nil, "commits not contained in its configured upstream"},
{"not contained", func(t *testing.T, f *worktreeRemovalFixture) { f.commitLane(t, "uncontained") }, false, func(f *worktreeRemovalFixture) string { return "main" }, "is not contained"},
{"HEAD pseudoref", nil, false, func(f *worktreeRemovalFixture) string { return "HEAD" }, "worktree-local pseudoref"},
{"ORIG_HEAD pseudoref", func(t *testing.T, f *worktreeRemovalFixture) { f.writeTargetPseudoref(t, "ORIG_HEAD") }, false, func(f *worktreeRemovalFixture) string { return "ORIG_HEAD" }, "worktree-local pseudoref"},
{"future pseudoref", func(t *testing.T, f *worktreeRemovalFixture) {
f.writeTargetPseudoref(t, "FUTURE_HEAD")
f.git(t, f.repo, "branch", "FUTURE_HEAD")
}, false, func(f *worktreeRemovalFixture) string { return "FUTURE_HEAD" }, "worktree-local pseudoref"},
{"irregular pseudoref", func(t *testing.T, f *worktreeRemovalFixture) {
f.writeTargetPseudoref(t, "BISECT_EXPECTED_REV")
f.git(t, f.repo, "branch", "BISECT_EXPECTED_REV")
}, false, func(f *worktreeRemovalFixture) string { return "BISECT_EXPECTED_REV" }, "worktree-local pseudoref"},
{"refs worktree", func(t *testing.T, f *worktreeRemovalFixture) {
f.git(t, f.repo, "update-ref", "refs/worktree/proof", f.baseOID)
}, false, func(f *worktreeRemovalFixture) string { return "refs/worktree/proof" }, "worktree-local ref namespace"},
{"refs bisect", func(t *testing.T, f *worktreeRemovalFixture) {
f.git(t, f.repo, "update-ref", "refs/bisect/proof", f.baseOID)
}, false, func(f *worktreeRemovalFixture) string { return "refs/bisect/proof" }, "worktree-local ref namespace"},
{"refs rewritten", func(t *testing.T, f *worktreeRemovalFixture) {
f.git(t, f.repo, "update-ref", "refs/rewritten/proof", f.baseOID)
}, false, func(f *worktreeRemovalFixture) string { return "refs/rewritten/proof" }, "worktree-local ref namespace"},
{"revision expression", nil, false, func(f *worktreeRemovalFixture) string { return "HEAD~1" }, "not an accepted ref name or full commit object ID"},
{"missing full ref", nil, false, func(f *worktreeRemovalFixture) string { return "refs/heads/missing" }, "does not resolve to a commit"},
{"target branch", nil, false, func(f *worktreeRemovalFixture) string { return "refs/heads/lane" }, "cannot independently prove containment"},
{"target HEAD OID", nil, false, func(f *worktreeRemovalFixture) string { return f.baseOID }, "target HEAD itself"},
{"ambiguous short ref", func(t *testing.T, f *worktreeRemovalFixture) {
f.git(t, f.repo, "branch", "comparison")
f.git(t, f.repo, "tag", "comparison")
}, false, func(f *worktreeRemovalFixture) string { return "comparison" }, "is ambiguous"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
fixture := newWorktreeRemovalFixture(t)
if test.setup != nil {
test.setup(t, fixture)
}
before := fixture.snapshot(t)
compare := ""
if test.compare != nil {
compare = test.compare(fixture)
}
err := runWorktreeRemoveGitAdapter(t, fixture.repo, fixture.lane, test.force, compare, worktreeRemoveHooks{})
requireWorktreeRemoveGitAdapterFailure(t, err, test.wantErr)
fixture.assertSnapshot(t, before)
})
}
}
func TestWorktreeRemoveGitAdapterComparatorAndCleanupContracts(t *testing.T) {
t.Run("configured upstream success", func(t *testing.T) {
fixture := newWorktreeRemovalFixture(t)
fixture.commitLane(t, "contained upstream")
fixture.mergeLaneIntoMain(t)
fixture.setUpstream(t)
if err := runWorktreeRemoveGitAdapter(t, fixture.repo, fixture.lane, false, "", worktreeRemoveHooks{}); err != nil {
t.Fatal(err)
}
fixture.assertRemovedAndCleaned(t)
})
for _, comparator := range []struct{ name, value string }{{"short ref", "main"}, {"full ref", "refs/heads/main"}} {
t.Run(comparator.name, func(t *testing.T) {
fixture := newWorktreeRemovalFixture(t)
fixture.commitLane(t, "contained")
fixture.mergeLaneIntoMain(t)
if err := runWorktreeRemoveGitAdapter(t, fixture.repo, fixture.lane, false, comparator.value, worktreeRemoveHooks{}); err != nil {
t.Fatal(err)
}
fixture.assertRemovedAndCleaned(t)
})
}
t.Run("full descendant object ID", func(t *testing.T) {
fixture := newWorktreeRemovalFixture(t)
fixture.commitLane(t, "contained by object")
fixture.mergeLaneIntoMain(t)
fixture.git(t, fixture.repo, "commit", "--allow-empty", "-m", "descendant")
comparator := fixture.git(t, fixture.repo, "rev-parse", "main")
if err := runWorktreeRemoveGitAdapter(t, fixture.repo, fixture.lane, false, comparator, worktreeRemoveHooks{}); err != nil {
t.Fatal(err)
}
fixture.assertRemovedAndCleaned(t)
})
for _, test := range []struct {
name, path string
body func(*testing.T, *worktreeRemovalFixture)
}{
{"force ignored removal", "lane", func(t *testing.T, f *worktreeRemovalFixture) {
f.writeLaneFile(t, filepath.Join("ignored", "cache.bin"), "ignored\n")
}},
{"nested cleanup", "nested/lane", func(t *testing.T, f *worktreeRemovalFixture) {
f.commitLane(t, "contained nested")
f.mergeLaneIntoMain(t)
}},
{"CRLF cleanup", "lane", func(t *testing.T, f *worktreeRemovalFixture) {
f.commitLane(t, "contained")
f.mergeLaneIntoMain(t)
before := "# bd worktree\r\nlane/\r\n# bd worktree\r\nother/\r\n# unrelated\r\nignored/\r\n"
if err := os.WriteFile(filepath.Join(f.repo, ".gitignore"), []byte(before), 0644); err != nil {
t.Fatal(err)
}
}},
{"leading space cleanup", " lane", func(t *testing.T, f *worktreeRemovalFixture) {
if err := os.WriteFile(filepath.Join(f.repo, ".gitignore"), []byte("# bd worktree\n lane/\n# bd worktree\nlane/\nignored/\n"), 0644); err != nil {
t.Fatal(err)
}
}},
} {
t.Run(test.name, func(t *testing.T) {
fixture := newWorktreeRemovalFixtureAt(t, test.path)
test.body(t, fixture)
force := test.name == "force ignored removal"
comparator := "main"
if force {
comparator = ""
}
if err := runWorktreeRemoveGitAdapter(t, fixture.repo, fixture.lane, force, comparator, worktreeRemoveHooks{}); err != nil {
t.Fatal(err)
}
fixture.assertRemovedAndCleaned(t)
if test.name == "CRLF cleanup" && fixture.readGitignore(t) != "# bd worktree\r\nother/\r\n# unrelated\r\nignored/\r\n" {
t.Fatal("CRLF cleanup changed unrelated bytes")
}
if test.name == "leading space cleanup" && fixture.readGitignore(t) != "# bd worktree\nlane/\nignored/\n" {
t.Fatal("leading-space cleanup conflated entries")
}
})
}
}
func TestWorktreeRemoveGitAdapterScrubsEveryPoisonedEnvironmentKey(t *testing.T) {
fixture := newWorktreeRemovalFixture(t)
fixture.commitLane(t, "contained")
fixture.mergeLaneIntoMain(t)
decoy := filepath.Join(t.TempDir(), "decoy")
if err := os.MkdirAll(decoy, 0755); err != nil {
t.Fatal(err)
}
fixture.git(t, decoy, "init")
shallow := filepath.Join(t.TempDir(), "shallow")
if err := os.WriteFile(shallow, nil, 0600); err != nil {
t.Fatal(err)
}
for key, value := range map[string]string{
"GIT_DIR": filepath.Join(decoy, ".git"), "GIT_WORK_TREE": decoy, "GIT_COMMON_DIR": filepath.Join(decoy, ".git"), "GIT_INDEX_FILE": filepath.Join(decoy, ".git", "index"), "GIT_OBJECT_DIRECTORY": filepath.Join(decoy, ".git", "objects"), "GIT_ALTERNATE_OBJECT_DIRECTORIES": filepath.Join(decoy, ".git", "objects"), "GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": "core.worktree", "GIT_CONFIG_VALUE_0": decoy, "GIT_EXEC_PATH": t.TempDir(), "GIT_SHALLOW_FILE": shallow, "GIT_REPLACE_REF_BASE": "refs/heads", "GIT_NO_REPLACE_OBJECTS": "0",
} {
t.Setenv(key, value)
}
if err := runWorktreeRemoveGitAdapter(t, fixture.repo, fixture.lane, false, "main", worktreeRemoveHooks{}); err != nil {
t.Fatal(err)
}
fixture.assertRemovedAndCleaned(t)
if _, err := os.Stat(filepath.Join(decoy, ".git")); err != nil {
t.Fatalf("poisoned environment damaged decoy: %v", err)
}
}
func TestWorktreeRemoveGitAdapterRejectsForgedMutationIdentities(t *testing.T) {
fixture := newWorktreeRemovalFixture(t)
t.Chdir(fixture.repo)
options := &worktreeRemoveOptions{
force: singleWorktreeBoolFlag{name: "force"},
mergedInto: singleWorktreeStringFlag{
name: "merged-into",
value: "main",
set: true,
},
}
adapter := &gitWorktreeRemovalAdapter{
name: fixture.lane,
options: options,
}
if _, err := adapter.Prepare(context.Background(), worktreeRemovalRequest{mode: worktreeremove.Normal}); err != nil {
t.Fatalf("prepare real adapter: %v", err)
}
if adapter.plan == nil || adapter.plan.gitignoreCleanup == nil {
t.Fatal("real adapter did not prepare target and managed-ignore identities")
}
before := fixture.snapshot(t)
for _, mutation := range []worktreeremove.Mutation{
{TargetPath: fixture.lane + "-forged", Force: false},
{TargetPath: fixture.lane, Force: true},
} {
err := adapter.Remove(context.Background(), mutation)
requireWorktreeRemoveGitAdapterFailure(t, err, "unapproved mutation")
fixture.assertSnapshot(t, before)
}
err := adapter.Cleanup(
context.Background(),
worktreeremove.Cleanup{Entry: adapter.plan.gitignoreCleanup.entry + "-forged"},
)
requireWorktreeRemoveGitAdapterFailure(t, err, "approved identity")
fixture.assertSnapshot(t, before)
}
func TestWorktreeRemoveGitAdapterClassifiesRealRemovalFailures(t *testing.T) {
t.Run("stable locked target is unchanged", func(t *testing.T) {
fixture := newWorktreeRemovalFixture(t)
fixture.commitLane(t, "contained locked worktree")
fixture.mergeLaneIntoMain(t)
fixture.git(t, fixture.repo, "worktree", "lock", "--reason", "test lock", fixture.lane)
before := fixture.snapshot(t)
err := runWorktreeRemoveGitAdapter(
t,
fixture.repo,
fixture.lane,
false,
"main",
worktreeRemoveHooks{},
)
requireWorktreeRemoveGitAdapterFailure(t, err, "target was revalidated unchanged")
if strings.Contains(err.Error(), "partial or indeterminate") {
t.Fatalf("stable failure was classified as indeterminate: %v", err)
}
fixture.assertSnapshot(t, before)
})
t.Run("moved target is partial or indeterminate", func(t *testing.T) {
fixture := newWorktreeRemovalFixture(t)
fixture.commitLane(t, "contained moving worktree")
fixture.mergeLaneIntoMain(t)
branchOID := fixture.git(t, fixture.repo, "rev-parse", "refs/heads/lane")
moved := fixture.lane + "-moved"
hooks := worktreeRemoveHooks{beforeRemove: func() error {
return runWorktreeRemoveHookGit(
fixture.repo,
"worktree",
"move",
"--",
fixture.lane,
moved,
)
}}
err := runWorktreeRemoveGitAdapter(
t,
fixture.repo,
fixture.lane,
false,
"main",
hooks,
)
requireWorktreeRemoveGitAdapterFailure(t, err, "partial or indeterminate")
if !strings.Contains(err.Error(), "registered=false, path_exists=false") {
t.Fatalf("partial failure omitted observed state: %v", err)
}
if !fixture.registered(t, moved) {
t.Fatal("moved worktree is no longer registered")
}
if _, statErr := os.Stat(moved); statErr != nil {
t.Fatalf("moved worktree did not survive: %v", statErr)
}
if _, statErr := os.Stat(fixture.lane); !os.IsNotExist(statErr) {
t.Fatalf("old worktree path still exists: %v", statErr)
}
if got := fixture.git(t, fixture.repo, "rev-parse", "refs/heads/lane"); got != branchOID {
t.Fatalf("target branch changed: got %s, want %s", got, branchOID)
}
if got := fixture.readGitignore(t); !strings.Contains(got, "lane/") {
t.Fatalf("failed removal cleaned managed ignore entry: %q", got)
}
})
}
func TestWorktreeRemoveGitAdapterRevalidatesFilesystemAndGitState(t *testing.T) {
tests := []struct {
name, want string
setup func(*testing.T, *worktreeRemovalFixture) worktreeRemoveHooks
}{
{"symlink replacement", "target path is not a real directory", func(t *testing.T, f *worktreeRemovalFixture) worktreeRemoveHooks {
return worktreeRemoveHooks{beforeFinalCheck: func() error {
if err := os.Rename(f.lane, f.lane+"-original"); err != nil {
return err
}
return os.Symlink(f.lane+"-original", f.lane)
}}
}},
{"HEAD", "target HEAD changed", func(t *testing.T, f *worktreeRemovalFixture) worktreeRemoveHooks {
return worktreeRemoveHooks{beforeFinalCheck: func() error { return runWorktreeRemoveHookGit(f.lane, "commit", "--allow-empty", "-m", "interleaved") }}
}},
{"cleanliness", "target cleanliness changed", func(t *testing.T, f *worktreeRemovalFixture) worktreeRemoveHooks {
return worktreeRemoveHooks{beforeFinalCheck: func() error {
return os.WriteFile(filepath.Join(f.lane, "interleaved.txt"), []byte("changed\n"), 0644)
}}
}},
{"dirty content", "target changed files changed", func(t *testing.T, f *worktreeRemovalFixture) worktreeRemoveHooks {
f.writeLaneFile(t, "dirty.txt", "alpha\n")
return worktreeRemoveHooks{beforeFinalCheck: func() error { return os.WriteFile(filepath.Join(f.lane, "dirty.txt"), []byte("bravo\n"), 0644) }}
}},
{"comparator", "comparison target changed", func(t *testing.T, f *worktreeRemovalFixture) worktreeRemoveHooks {
return worktreeRemoveHooks{beforeFinalCheck: func() error { return runWorktreeRemoveHookGit(f.repo, "reset", "--hard", f.baseOID) }}
}},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
fixture := newWorktreeRemovalFixture(t)
if test.name != "dirty content" {
fixture.commitLane(t, "contained")
fixture.mergeLaneIntoMain(t)
}
hooks := test.setup(t, fixture)
force := test.name == "dirty content"
comparator := "main"
if force {
comparator = ""
}
err := runWorktreeRemoveGitAdapter(t, fixture.repo, fixture.lane, force, comparator, hooks)
requireWorktreeRemoveGitAdapterFailure(t, err, test.want)
if !fixture.registered(t, fixture.lane) {
t.Fatal("target was removed after revalidation failure")
}
if test.name == "dirty content" {
contents, readErr := os.ReadFile(filepath.Join(fixture.lane, "dirty.txt"))
if readErr != nil {
t.Fatalf("read interleaved dirty file after refusal: %v", readErr)
}
if got, want := string(contents), "bravo\n"; got != want {
t.Fatalf("interleaved dirty file after refusal = %q, want %q", got, want)
}
}
if test.name == "symlink replacement" {
replacement, statErr := os.Lstat(fixture.lane)
if statErr != nil {
t.Fatalf("inspect replacement path: %v", statErr)
}
if replacement.Mode()&os.ModeSymlink == 0 {
t.Fatalf("replacement path mode = %s, want symlink", replacement.Mode())
}
original, statErr := os.Stat(fixture.lane + "-original")
if statErr != nil {
t.Fatalf("inspect original target directory: %v", statErr)
}
if !original.IsDir() {
t.Fatalf("original target mode = %s, want directory", original.Mode())
}
}
})
}
}
func TestWorktreeRemoveGitAdapterRevalidatesLockStateInBothDirections(t *testing.T) {
for _, test := range []struct {
name string
before func(*testing.T, *worktreeRemovalFixture) worktreeRemovalSnapshot
hook func(*worktreeRemovalFixture) worktreeRemoveHooks
}{
{
name: "locked to unlocked",
before: func(t *testing.T, fixture *worktreeRemovalFixture) worktreeRemovalSnapshot {
want := fixture.snapshot(t)
fixture.git(t, fixture.repo, "worktree", "lock", fixture.lane)
return want
},
hook: func(fixture *worktreeRemovalFixture) worktreeRemoveHooks {
return worktreeRemoveHooks{beforeFinalCheck: func() error {
return runWorktreeRemoveHookGit(fixture.repo, "worktree", "unlock", "--", fixture.lane)
}}
},
},
{
name: "unlocked to locked",
before: func(t *testing.T, fixture *worktreeRemovalFixture) worktreeRemovalSnapshot {
fixture.git(t, fixture.repo, "worktree", "lock", fixture.lane)
want := fixture.snapshot(t)
fixture.git(t, fixture.repo, "worktree", "unlock", fixture.lane)
return want
},
hook: func(fixture *worktreeRemovalFixture) worktreeRemoveHooks {
return worktreeRemoveHooks{beforeFinalCheck: func() error {
return runWorktreeRemoveHookGit(fixture.repo, "worktree", "lock", "--", fixture.lane)
}}
},
},
} {
t.Run(test.name, func(t *testing.T) {
fixture := newWorktreeRemovalFixture(t)
want := test.before(t, fixture)
err := runWorktreeRemoveGitAdapter(t, fixture.repo, fixture.lane, false, "main", test.hook(fixture))
requireWorktreeRemoveGitAdapterFailure(t, err, "registered target identity changed")
fixture.assertSnapshot(t, want)
})
}
}
func TestWorktreeRemoveGitAdapterRejectsUnsafeGitignore(t *testing.T) {
for _, test := range []struct {
name string
makeUnsafe func(*testing.T, string) func()
}{
{"directory", func(t *testing.T, path string) func() {
if err := os.Remove(path); err != nil {
t.Fatal(err)
}
if err := os.Mkdir(path, 0755); err != nil {
t.Fatal(err)
}
return func() {
info, err := os.Lstat(path)
if err != nil {
t.Fatalf("inspect unsafe .gitignore directory: %v", err)
}
if !info.IsDir() {
t.Fatalf("unsafe .gitignore mode = %s, want directory", info.Mode())
}
}
}},
{"symlink", func(t *testing.T, path string) func() {
external := filepath.Join(t.TempDir(), "external")
externalContent := []byte("external sentinel\n")
if err := os.WriteFile(external, externalContent, 0644); err != nil {
t.Fatal(err)
}
if err := os.Remove(path); err != nil {
t.Fatal(err)
}
if err := os.Symlink(external, path); err != nil {
t.Fatal(err)
}
return func() {
info, err := os.Lstat(path)
if err != nil {
t.Fatalf("inspect unsafe .gitignore symlink: %v", err)
}
if info.Mode()&os.ModeSymlink == 0 {
t.Fatalf("unsafe .gitignore mode = %s, want symlink", info.Mode())
}
content, err := os.ReadFile(external)
if err != nil {
t.Fatalf("read external sentinel: %v", err)
}
if !bytes.Equal(content, externalContent) {
t.Fatalf("external symlink target changed: %q", content)
}
}
}},
} {
t.Run(test.name, func(t *testing.T) {
fixture := newWorktreeRemovalFixture(t)
fixture.commitLane(t, "contained")
fixture.mergeLaneIntoMain(t)
beforeRegistry := fixture.git(t, fixture.repo, "worktree", "list", "--porcelain", "-z")
beforeHead := fixture.git(t, fixture.lane, "rev-parse", "HEAD")
beforeBranch := fixture.git(t, fixture.repo, "rev-parse", "refs/heads/lane")
beforeStatus := fixture.git(t, fixture.lane, "status", "--porcelain=v1", "-z", "--untracked-files=all", "--ignored=matching")
verifyUnsafe := test.makeUnsafe(t, filepath.Join(fixture.repo, ".gitignore"))
err := runWorktreeRemoveGitAdapter(t, fixture.repo, fixture.lane, false, "main", worktreeRemoveHooks{})
requireWorktreeRemoveGitAdapterFailure(t, err, "is not a regular file")
if !fixture.registered(t, fixture.lane) {
t.Fatal("unsafe .gitignore removed target")
}
if got := fixture.git(t, fixture.repo, "worktree", "list", "--porcelain", "-z"); got != beforeRegistry {
t.Fatalf("unsafe .gitignore refusal changed registry\ngot: %q\nwant: %q", got, beforeRegistry)
}
if got := fixture.git(t, fixture.lane, "rev-parse", "HEAD"); got != beforeHead {
t.Fatalf("unsafe .gitignore refusal changed HEAD: got %s, want %s", got, beforeHead)
}
if got := fixture.git(t, fixture.repo, "rev-parse", "refs/heads/lane"); got != beforeBranch {
t.Fatalf("unsafe .gitignore refusal changed branch: got %s, want %s", got, beforeBranch)
}
if got := fixture.git(t, fixture.lane, "status", "--porcelain=v1", "-z", "--untracked-files=all", "--ignored=matching"); got != beforeStatus {
t.Fatalf("unsafe .gitignore refusal changed target status: got %q, want %q", got, beforeStatus)
}
verifyUnsafe()
})
}
}

View file

@ -0,0 +1,237 @@
package main
import (
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
func TestWorktreeRemoveGitAdapterWindowsOrdinaryIgnoreCaseRemoval(t *testing.T) {
fixture := newWorktreeRemovalFixture(t)
fixture.git(t, fixture.repo, "config", "core.ignorecase", "true")
if err := runWorktreeRemoveGitAdapter(t, fixture.repo, fixture.lane, false, "main", worktreeRemoveHooks{}); err != nil {
t.Fatal(err)
}
fixture.assertRemovedAndCleaned(t)
}
func TestWorktreeRemoveGitAdapterWindowsMissingCaseVariantRefuses(t *testing.T) {
fixture, upperLane, gitignore := newWindowsCaseSensitiveRemovalFixture(t, false)
if _, err := os.Stat(fixture.lane); !os.IsNotExist(err) {
t.Fatalf("lowercase target unexpectedly exists: %v", err)
}
if sameWorktreePath(upperLane, fixture.lane) {
t.Fatal("existing and missing case variants aliased")
}
beforeRegistry := fixture.git(t, fixture.repo, "worktree", "list", "--porcelain", "-z")
beforeHead := fixture.git(t, upperLane, "rev-parse", "HEAD")
beforeBranch := fixture.git(t, fixture.repo, "rev-parse", "refs/heads/upper-lane")
beforeFingerprint, err := fingerprintWorktreeFilesystem(upperLane)
if err != nil {
t.Fatal(err)
}
err = runWorktreeRemoveGitAdapter(t, fixture.repo, fixture.lane, false, "main", worktreeRemoveHooks{})
requireWorktreeRemoveGitAdapterFailure(t, err, "registered worktree not found")
if got := fixture.git(t, fixture.repo, "worktree", "list", "--porcelain", "-z"); got != beforeRegistry {
t.Fatal("registry changed")
}
if !windowsRegisteredWorktreePathExact(t, fixture, upperLane) {
t.Fatal("uppercase worktree was removed")
}
if got := fixture.git(t, upperLane, "rev-parse", "HEAD"); got != beforeHead {
t.Fatal("uppercase HEAD changed")
}
if got := fixture.git(t, fixture.repo, "rev-parse", "refs/heads/upper-lane"); got != beforeBranch {
t.Fatal("uppercase branch changed")
}
if got, err := fingerprintWorktreeFilesystem(upperLane); err != nil || got != beforeFingerprint {
t.Fatalf("uppercase worktree changed: %v", err)
}
if got := fixture.readGitignore(t); got != gitignore {
t.Fatal(".gitignore changed")
}
if _, statErr := os.Stat(fixture.lane); !os.IsNotExist(statErr) {
t.Fatalf("lowercase target exists after refusal: %v", statErr)
}
}
func TestWorktreeRemoveGitAdapterWindowsPrunableCaseVariants(t *testing.T) {
for _, test := range []struct {
name string
includeLower bool
want string
}{
{"single variant", false, "registered worktree not found"},
{"two variants", true, "failed to resolve target git directory"},
} {
t.Run(test.name, func(t *testing.T) {
fixture, upperLane, upperStage, lowerStage, _ := newWindowsPrunableCaseVariantFixture(t, test.includeLower)
if sameWorktreePath(upperLane, fixture.lane) {
t.Fatal("case variants aliased")
}
before := captureWindowsPrunableState(t, fixture, upperStage, lowerStage)
err := runWorktreeRemoveGitAdapter(t, fixture.repo, fixture.lane, true, "", worktreeRemoveHooks{})
requireWorktreeRemoveGitAdapterFailure(t, err, test.want)
assertWindowsPrunableState(t, fixture, upperLane, upperStage, lowerStage, before)
})
}
}
func TestWorktreeRemoveGitAdapterWindowsPrunableWrongCaseRestorationRefuses(t *testing.T) {
fixture, upperLane, upperStage, lowerStage, _ := newWindowsPrunableCaseVariantFixture(t, true)
before := captureWindowsPrunableState(t, fixture, upperStage, lowerStage)
adminFingerprint, err := fingerprintWorktreeFilesystem(filepath.Join(fixture.repo, ".git", "worktrees"))
if err != nil {
t.Fatal(err)
}
hooks := worktreeRemoveHooks{afterTargetResolution: func() error { return os.Rename(upperStage, upperLane) }}
err = runWorktreeRemoveGitAdapter(t, fixture.repo, fixture.lane, true, "", hooks)
requireWorktreeRemoveGitAdapterFailure(t, err, "failed to resolve target git directory")
if !windowsRegisteredWorktreePathExact(t, fixture, upperLane) || !windowsRegisteredWorktreePathExact(t, fixture, fixture.lane) {
t.Fatal("registered case variant was removed")
}
if got, err := fingerprintWorktreeFilesystem(filepath.Join(fixture.repo, ".git", "worktrees")); err != nil || got != adminFingerprint {
t.Fatalf("registry changed: %v", err)
}
if _, err := os.Stat(upperStage); !os.IsNotExist(err) {
t.Fatalf("staging path remains: %v", err)
}
if got, err := fingerprintWorktreeFilesystem(upperLane); err != nil || got != before.upperFingerprint {
t.Fatalf("uppercase worktree changed: %v", err)
}
if got, err := fingerprintWorktreeFilesystem(lowerStage); err != nil || got != before.lowerFingerprint {
t.Fatalf("lowercase worktree changed: %v", err)
}
if got := fixture.git(t, fixture.repo, "rev-parse", "refs/heads/upper-lane"); got != before.upperBranchOID {
t.Fatal("uppercase branch changed")
}
if got := fixture.git(t, fixture.repo, "rev-parse", "refs/heads/lane"); got != before.lowerBranchOID {
t.Fatal("lowercase branch changed")
}
if got := fixture.readGitignore(t); got != before.gitignore {
t.Fatal(".gitignore changed")
}
}
type windowsPrunableState struct{ registry, upperBranchOID, lowerBranchOID, gitignore, upperFingerprint, lowerFingerprint string }
func captureWindowsPrunableState(t *testing.T, fixture *worktreeRemovalFixture, upperStage, lowerStage string) windowsPrunableState {
t.Helper()
state := windowsPrunableState{registry: fixture.git(t, fixture.repo, "worktree", "list", "--porcelain", "-z"), upperBranchOID: fixture.git(t, fixture.repo, "rev-parse", "refs/heads/upper-lane"), gitignore: fixture.readGitignore(t)}
var err error
state.upperFingerprint, err = fingerprintWorktreeFilesystem(upperStage)
if err != nil {
t.Fatal(err)
}
if lowerStage != "" {
state.lowerBranchOID = fixture.git(t, fixture.repo, "rev-parse", "refs/heads/lane")
state.lowerFingerprint, err = fingerprintWorktreeFilesystem(lowerStage)
if err != nil {
t.Fatal(err)
}
}
return state
}
func assertWindowsPrunableState(t *testing.T, fixture *worktreeRemovalFixture, upperLane, upperStage, lowerStage string, want windowsPrunableState) {
t.Helper()
if got := captureWindowsPrunableState(t, fixture, upperStage, lowerStage); got != want {
t.Fatalf("prunable state mutated\ngot: %#v\nwant: %#v", got, want)
}
if !windowsRegisteredWorktreePathExact(t, fixture, upperLane) {
t.Fatal("uppercase registration removed")
}
if _, err := os.Stat(upperLane); !os.IsNotExist(err) {
t.Fatal("uppercase registry path exists")
}
if _, err := os.Stat(fixture.lane); !os.IsNotExist(err) {
t.Fatal("lowercase registry path exists")
}
if lowerStage != "" && !windowsRegisteredWorktreePathExact(t, fixture, fixture.lane) {
t.Fatal("lowercase registration removed")
}
}
func newWindowsPrunableCaseVariantFixture(t *testing.T, includeLower bool) (*worktreeRemovalFixture, string, string, string, string) {
t.Helper()
fixture, upperLane, gitignore := newWindowsCaseSensitiveRemovalFixture(t, includeLower)
stageRoot := filepath.Join(filepath.Dir(fixture.repo), "staged")
if err := os.Mkdir(stageRoot, 0755); err != nil {
t.Fatal(err)
}
upperStage := filepath.Join(stageRoot, "upper")
if err := os.Rename(upperLane, upperStage); err != nil {
t.Fatal(err)
}
lowerStage := ""
if includeLower {
lowerStage = filepath.Join(stageRoot, "lower")
if err := os.Rename(fixture.lane, lowerStage); err != nil {
t.Fatal(err)
}
}
return fixture, upperLane, upperStage, lowerStage, gitignore
}
func newWindowsCaseSensitiveRemovalFixture(t *testing.T, includeLower bool) (*worktreeRemovalFixture, string, string) {
t.Helper()
root := t.TempDir()
requireWindowsCaseSensitiveDirectory(t, root)
fixture := &worktreeRemovalFixture{repo: filepath.Join(root, "repo"), gitignoreEntry: "lane"}
fixture.lane = filepath.Join(fixture.repo, fixture.gitignoreEntry)
upperLane := filepath.Join(fixture.repo, "Lane")
if err := os.Mkdir(fixture.repo, 0755); err != nil {
t.Fatal(err)
}
fixture.git(t, fixture.repo, "init")
fixture.git(t, fixture.repo, "config", "user.name", worktreeRemoveTestActorName)
fixture.git(t, fixture.repo, "config", "user.email", worktreeRemoveTestActorEmail)
fixture.git(t, fixture.repo, "config", "commit.gpgsign", "false")
fixture.git(t, fixture.repo, "config", "core.ignorecase", "false")
fixture.git(t, fixture.repo, "config", "core.hooksPath", ".git/hooks")
fixture.git(t, fixture.repo, "symbolic-ref", "HEAD", "refs/heads/main")
gitignore := "# bd worktree\nLane/\nignored/\n"
if includeLower {
gitignore = "# bd worktree\nLane/\n# bd worktree\nlane/\nignored/\n"
}
if err := os.WriteFile(filepath.Join(fixture.repo, ".gitignore"), []byte(gitignore), 0644); err != nil {
t.Fatal(err)
}
fixture.git(t, fixture.repo, "add", ".gitignore")
fixture.git(t, fixture.repo, "commit", "-m", "base")
fixture.baseOID = fixture.git(t, fixture.repo, "rev-parse", "HEAD")
fixture.git(t, fixture.repo, "worktree", "add", "-b", "upper-lane", upperLane)
if includeLower {
fixture.git(t, fixture.repo, "worktree", "add", "-b", "lane", fixture.lane)
}
return fixture, upperLane, gitignore
}
func windowsRegisteredWorktreePathExact(t *testing.T, fixture *worktreeRemovalFixture, want string) bool {
t.Helper()
want = filepath.Clean(want)
wantParent, err := os.Stat(filepath.Dir(want))
if err != nil {
t.Fatal(err)
}
output := fixture.git(t, fixture.repo, "worktree", "list", "--porcelain", "-z")
for _, field := range strings.Split(output, "\x00") {
if !strings.HasPrefix(field, "worktree ") {
continue
}
registered := filepath.Clean(strings.TrimPrefix(field, "worktree "))
if filepath.Base(registered) != filepath.Base(want) {
continue
}
registeredParent, err := os.Stat(filepath.Dir(registered))
if err == nil && os.SameFile(registeredParent, wantParent) {
return true
}
}
return false
}
func requireWindowsCaseSensitiveDirectory(t *testing.T, path string) {
t.Helper()
set := exec.Command("fsutil.exe", "file", "SetCaseSensitiveInfo", path, "enable")
if output, err := set.CombinedOutput(); err != nil {
t.Fatalf("native Windows worktree boundary requires per-directory case sensitivity: %v\n%s", err, strings.TrimSpace(string(output)))
}
}

File diff suppressed because it is too large Load diff

View file

@ -2,480 +2,86 @@ package main
import (
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
func TestWorktreeRemoveWindowsOrdinalGitSelectorRemovesOrdinaryWorktree(t *testing.T) {
fixture := newWorktreeRemovalFixture(t)
fixture.git(t, fixture.repo, "config", "core.ignorecase", "true")
result := runWorktreeRemoveProcess(
t,
fixture.repo,
nil,
fixture.lane,
"--merged-into",
"main",
)
result.requireSuccess(t)
fixture.assertRemovedAndCleaned(t)
}
func TestWorktreeRemoveWindowsOrdinalGitSelectorProtectsCaseSiblingAfterTargetDisappears(
t *testing.T,
) {
func TestWorktreeRemoveWindowsE2ELaneAndLaneSiblingIdentity(t *testing.T) {
fixture, upperLane, _ := newWindowsCaseSensitiveRemovalFixture(t, true)
upperFingerprint, err := fingerprintWorktreeFilesystem(upperLane)
if err != nil {
t.Fatalf("fingerprint uppercase sibling: %v", err)
}
lowerFingerprint, err := fingerprintWorktreeFilesystem(fixture.lane)
if err != nil {
t.Fatalf("fingerprint lowercase target: %v", err)
}
upperBranch := fixture.git(t, fixture.repo, "rev-parse", "refs/heads/upper-lane")
lowerBranch := fixture.git(t, fixture.repo, "rev-parse", "refs/heads/lane")
result := runWorktreeRemoveProcess(
t,
fixture.repo,
[]string{
worktreeRemoveHelperHookEnv + "=" + worktreeRemoveHookCaseRace,
worktreeRemoveHelperMain + "=" + fixture.repo,
worktreeRemoveHelperTarget + "=" + fixture.lane,
},
fixture.lane,
"--merged-into",
"main",
)
result.requireSuccess(t)
movedLower := fixture.lane + "-moved"
if !windowsRegisteredWorktreePathExact(t, fixture, upperLane) {
t.Fatal("uppercase sibling registration was removed after lowercase target disappeared")
}
if windowsRegisteredWorktreePathExact(t, fixture, fixture.lane) {
t.Fatal("disappeared lowercase target remains registered")
}
if _, err := os.Stat(upperLane); err != nil {
t.Fatalf("uppercase sibling path was not preserved: %v", err)
}
if _, err := os.Stat(fixture.lane); !os.IsNotExist(err) {
t.Fatalf("lowercase target path unexpectedly exists: %v", err)
}
if _, err := os.Stat(movedLower); err != nil {
t.Fatalf("interleaved moved target was not preserved: %v", err)
}
gotUpperFingerprint, err := fingerprintWorktreeFilesystem(upperLane)
if err != nil {
t.Fatalf("fingerprint preserved uppercase sibling: %v", err)
}
if gotUpperFingerprint != upperFingerprint {
t.Fatal("uppercase sibling changed after lowercase target disappeared")
}
gotLowerFingerprint, err := fingerprintWorktreeFilesystem(movedLower)
if err != nil {
t.Fatalf("fingerprint interleaved moved target: %v", err)
}
if gotLowerFingerprint != lowerFingerprint {
t.Fatal("interleaved moved target changed during exact-registration removal")
}
if got := fixture.git(t, fixture.repo, "rev-parse", "refs/heads/upper-lane"); got != upperBranch {
t.Fatalf("uppercase branch changed: got %s, want %s", got, upperBranch)
}
if got := fixture.git(t, fixture.repo, "rev-parse", "refs/heads/lane"); got != lowerBranch {
t.Fatalf("lowercase branch changed: got %s, want %s", got, lowerBranch)
}
if got := fixture.git(t, fixture.repo, "config", "--get", "core.ignorecase"); got != "true" {
t.Fatalf("race hook did not change core.ignorecase: got %q", got)
}
wantGitignore := "# bd worktree\nLane/\nignored/\n"
if got := fixture.readGitignore(t); got != wantGitignore {
t.Fatalf(".gitignore cleanup targeted the wrong case sibling\ngot: %q\nwant: %q", got, wantGitignore)
}
}
func TestWorktreeRemoveWindowsCaseSensitiveSiblingPaths(t *testing.T) {
fixture, upperLane, _ := newWindowsCaseSensitiveRemovalFixture(t, true)
upperInfo, err := os.Stat(upperLane)
if err != nil {
t.Fatalf("stat uppercase sibling: %v", err)
t.Fatal(err)
}
lowerInfo, err := os.Stat(fixture.lane)
if err != nil {
t.Fatalf("stat lowercase target: %v", err)
t.Fatal(err)
}
if os.SameFile(upperInfo, lowerInfo) {
t.Fatal("case-sensitive siblings unexpectedly identify the same directory")
if os.SameFile(upperInfo, lowerInfo) || sameWorktreePath(upperLane, fixture.lane) {
t.Fatal("case-sensitive siblings were conflated")
}
if sameWorktreePath(upperLane, fixture.lane) {
t.Fatal("sameWorktreePath conflated stat-proven case-sensitive siblings")
}
result := runWorktreeRemoveProcess(
t,
fixture.repo,
nil,
fixture.lane,
"--merged-into",
"main",
)
result := runWorktreeRemoveProcess(t, fixture.repo, nil, fixture.lane, "--merged-into", "main")
result.requireSuccess(t)
if windowsRegisteredWorktreePathExact(t, fixture, fixture.lane) {
t.Fatal("lowercase target remains registered")
}
if _, err := os.Stat(fixture.lane); !os.IsNotExist(err) {
t.Fatalf("lowercase target path still exists: %v", err)
t.Fatalf("lowercase target still exists: %v", err)
}
if !windowsRegisteredWorktreePathExact(t, fixture, upperLane) {
t.Fatal("uppercase sibling was removed instead of the exact lowercase target")
t.Fatal("uppercase sibling was removed")
}
if _, err := os.Stat(upperLane); err != nil {
t.Fatalf("uppercase sibling path was not preserved: %v", err)
t.Fatalf("uppercase sibling was not preserved: %v", err)
}
fixture.git(t, fixture.repo, "rev-parse", "--verify", "refs/heads/lane")
fixture.git(t, fixture.repo, "rev-parse", "--verify", "refs/heads/upper-lane")
wantGitignore := "# bd worktree\nLane/\nignored/\n"
if got := fixture.readGitignore(t); got != wantGitignore {
t.Fatalf(".gitignore cleanup targeted the wrong sibling\ngot: %q\nwant: %q", got, wantGitignore)
if got := fixture.readGitignore(t); got != "# bd worktree\nLane/\nignored/\n" {
t.Fatalf("cleanup targeted wrong sibling: %q", got)
}
}
func TestWorktreeRemoveWindowsMissingCaseVariantRefuses(t *testing.T) {
fixture, upperLane, gitignore := newWindowsCaseSensitiveRemovalFixture(t, false)
func TestWorktreeRemoveWindowsE2EFinalBoundaryDisappearanceAndIgnoreCaseFlip(t *testing.T) {
fixture, upperLane, _ := newWindowsCaseSensitiveRemovalFixture(t, true)
upperFingerprint, err := fingerprintWorktreeFilesystem(upperLane)
if err != nil {
t.Fatal(err)
}
lowerFingerprint, err := fingerprintWorktreeFilesystem(fixture.lane)
if err != nil {
t.Fatal(err)
}
upperBranch := fixture.git(t, fixture.repo, "rev-parse", "refs/heads/upper-lane")
lowerBranch := fixture.git(t, fixture.repo, "rev-parse", "refs/heads/lane")
result := runWorktreeRemoveProcess(t, fixture.repo, []string{worktreeRemoveHelperHookEnv + "=" + worktreeRemoveHookCaseRace, worktreeRemoveHelperMain + "=" + fixture.repo, worktreeRemoveHelperTarget + "=" + fixture.lane}, fixture.lane, "--merged-into", "main")
result.requireSuccess(t)
movedLower := fixture.lane + "-moved"
if !windowsRegisteredWorktreePathExact(t, fixture, upperLane) || windowsRegisteredWorktreePathExact(t, fixture, fixture.lane) {
t.Fatal("registered case siblings changed")
}
if _, err := os.Stat(upperLane); err != nil {
t.Fatalf("uppercase sibling missing: %v", err)
}
if _, err := os.Stat(fixture.lane); !os.IsNotExist(err) {
t.Fatalf("lowercase target unexpectedly exists: %v", err)
}
if sameWorktreePath(upperLane, fixture.lane) {
t.Fatal("sameWorktreePath aliased an existing path to a missing case variant")
if _, err := os.Stat(movedLower); err != nil {
t.Fatalf("moved target missing: %v", err)
}
beforeRegistry := fixture.git(t, fixture.repo, "worktree", "list", "--porcelain", "-z")
beforeHead := fixture.git(t, upperLane, "rev-parse", "HEAD")
beforeBranch := fixture.git(t, fixture.repo, "rev-parse", "refs/heads/upper-lane")
beforeFingerprint, err := fingerprintWorktreeFilesystem(upperLane)
if err != nil {
t.Fatalf("fingerprint uppercase worktree: %v", err)
if got, err := fingerprintWorktreeFilesystem(upperLane); err != nil || got != upperFingerprint {
t.Fatalf("uppercase sibling changed: %v", err)
}
result := runWorktreeRemoveProcess(
t,
fixture.repo,
nil,
fixture.lane,
"--merged-into",
"main",
)
result.requireFailure(t, "registered worktree not found")
if got := fixture.git(t, fixture.repo, "worktree", "list", "--porcelain", "-z"); got != beforeRegistry {
t.Fatalf("worktree registry changed on missing-case refusal\ngot: %q\nwant: %q", got, beforeRegistry)
if got, err := fingerprintWorktreeFilesystem(movedLower); err != nil || got != lowerFingerprint {
t.Fatalf("moved target changed: %v", err)
}
if !windowsRegisteredWorktreePathExact(t, fixture, upperLane) {
t.Fatal("uppercase worktree was removed for a missing lowercase request")
if got := fixture.git(t, fixture.repo, "rev-parse", "refs/heads/upper-lane"); got != upperBranch {
t.Fatalf("uppercase branch changed: %s", got)
}
if got := fixture.git(t, upperLane, "rev-parse", "HEAD"); got != beforeHead {
t.Fatalf("uppercase worktree HEAD changed: got %s, want %s", got, beforeHead)
if got := fixture.git(t, fixture.repo, "rev-parse", "refs/heads/lane"); got != lowerBranch {
t.Fatalf("lowercase branch changed: %s", got)
}
if got := fixture.git(t, fixture.repo, "rev-parse", "refs/heads/upper-lane"); got != beforeBranch {
t.Fatalf("uppercase branch changed: got %s, want %s", got, beforeBranch)
if got := fixture.git(t, fixture.repo, "config", "--get", "core.ignorecase"); got != "true" {
t.Fatalf("core.ignorecase = %q", got)
}
afterFingerprint, err := fingerprintWorktreeFilesystem(upperLane)
if err != nil {
t.Fatalf("fingerprint preserved uppercase worktree: %v", err)
}
if afterFingerprint != beforeFingerprint {
t.Fatal("uppercase worktree bytes or metadata changed on missing-case refusal")
}
if got := fixture.readGitignore(t); got != gitignore {
t.Fatalf(".gitignore changed on missing-case refusal\ngot: %q\nwant: %q", got, gitignore)
}
if _, err := os.Stat(fixture.lane); !os.IsNotExist(err) {
t.Fatalf("missing lowercase path was created: %v", err)
}
}
func TestWorktreeRemoveWindowsSinglePrunableCaseVariantRefuses(t *testing.T) {
fixture, upperLane, upperStage, lowerStage, _ :=
newWindowsPrunableCaseVariantFixture(t, false)
if sameWorktreePath(upperLane, fixture.lane) {
t.Fatal("sameWorktreePath aliased two absent case-variant paths")
}
before := captureWindowsPrunableState(t, fixture, upperStage, lowerStage)
result := runWorktreeRemoveProcess(
t,
fixture.repo,
nil,
fixture.lane,
"--force",
)
result.requireFailure(t, "registered worktree not found")
assertWindowsPrunableState(t, fixture, upperLane, upperStage, lowerStage, before)
}
func TestWorktreeRemoveWindowsTwoPrunableCaseVariantsStayDistinct(t *testing.T) {
fixture, upperLane, upperStage, lowerStage, _ :=
newWindowsPrunableCaseVariantFixture(t, true)
if sameWorktreePath(upperLane, fixture.lane) {
t.Fatal("sameWorktreePath collapsed two registered absent case variants")
}
before := captureWindowsPrunableState(t, fixture, upperStage, lowerStage)
result := runWorktreeRemoveProcess(
t,
fixture.repo,
nil,
fixture.lane,
"--force",
)
result.requireFailure(t, "failed to resolve target git directory")
assertWindowsPrunableState(t, fixture, upperLane, upperStage, lowerStage, before)
}
func TestWorktreeRemoveWindowsPrunableWrongCaseRestorationRefuses(t *testing.T) {
fixture, upperLane, upperStage, lowerStage, _ :=
newWindowsPrunableCaseVariantFixture(t, true)
before := captureWindowsPrunableState(t, fixture, upperStage, lowerStage)
adminFingerprint, err := fingerprintWorktreeFilesystem(
filepath.Join(fixture.repo, ".git", "worktrees"),
)
if err != nil {
t.Fatalf("fingerprint worktree registry: %v", err)
}
sentinel := filepath.Join(t.TempDir(), "restore-hook-reached")
result := runWorktreeRemoveProcess(
t,
fixture.repo,
[]string{
worktreeRemoveHelperHookEnv + "=" + worktreeRemoveHookRestore,
worktreeRemoveHelperTarget + "=" + upperLane,
worktreeRemoveHelperRestore + "=" + upperStage,
worktreeRemoveHelperSentinel + "=" + sentinel,
},
fixture.lane,
"--force",
)
result.requireFailure(t, "failed to resolve target git directory")
if content, err := os.ReadFile(sentinel); err != nil {
t.Fatalf("restore hook did not publish its sentinel: %v", err)
} else if string(content) != "reached\n" {
t.Fatalf("restore hook sentinel = %q, want %q", content, "reached\n")
}
if !windowsRegisteredWorktreePathExact(t, fixture, upperLane) ||
!windowsRegisteredWorktreePathExact(t, fixture, fixture.lane) {
t.Fatal("wrong-case restoration removed a registered case variant")
}
gotAdminFingerprint, err := fingerprintWorktreeFilesystem(
filepath.Join(fixture.repo, ".git", "worktrees"),
)
if err != nil {
t.Fatalf("fingerprint preserved worktree registry: %v", err)
}
if gotAdminFingerprint != adminFingerprint {
t.Fatal("worktree administrative registry changed after wrong-case restoration")
}
if _, err := os.Stat(upperStage); !os.IsNotExist(err) {
t.Fatalf("uppercase staging path still exists after restoration: %v", err)
}
upperFingerprint, err := fingerprintWorktreeFilesystem(upperLane)
if err != nil {
t.Fatalf("fingerprint restored uppercase worktree: %v", err)
}
if upperFingerprint != before.upperFingerprint {
t.Fatal("restored uppercase worktree changed during lowercase refusal")
}
lowerFingerprint, err := fingerprintWorktreeFilesystem(lowerStage)
if err != nil {
t.Fatalf("fingerprint staged lowercase worktree: %v", err)
}
if lowerFingerprint != before.lowerFingerprint {
t.Fatal("staged lowercase worktree changed during wrong-case restoration")
}
if got := fixture.git(t, fixture.repo, "rev-parse", "refs/heads/upper-lane"); got != before.upperBranchOID {
t.Fatalf("uppercase branch changed: got %s, want %s", got, before.upperBranchOID)
}
if got := fixture.git(t, fixture.repo, "rev-parse", "refs/heads/lane"); got != before.lowerBranchOID {
t.Fatalf("lowercase branch changed: got %s, want %s", got, before.lowerBranchOID)
}
if got := fixture.readGitignore(t); got != before.gitignore {
t.Fatalf(".gitignore changed after wrong-case restoration\ngot: %q\nwant: %q", got, before.gitignore)
}
}
type windowsPrunableState struct {
registry string
upperBranchOID string
lowerBranchOID string
gitignore string
upperFingerprint string
lowerFingerprint string
}
func captureWindowsPrunableState(
t *testing.T,
fixture *worktreeRemovalFixture,
upperStage string,
lowerStage string,
) windowsPrunableState {
t.Helper()
state := windowsPrunableState{
registry: fixture.git(t, fixture.repo, "worktree", "list", "--porcelain", "-z"),
upperBranchOID: fixture.git(t, fixture.repo, "rev-parse", "refs/heads/upper-lane"),
gitignore: fixture.readGitignore(t),
}
var err error
state.upperFingerprint, err = fingerprintWorktreeFilesystem(upperStage)
if err != nil {
t.Fatalf("fingerprint staged uppercase worktree: %v", err)
}
if lowerStage != "" {
state.lowerBranchOID = fixture.git(t, fixture.repo, "rev-parse", "refs/heads/lane")
state.lowerFingerprint, err = fingerprintWorktreeFilesystem(lowerStage)
if err != nil {
t.Fatalf("fingerprint staged lowercase worktree: %v", err)
}
}
return state
}
func assertWindowsPrunableState(
t *testing.T,
fixture *worktreeRemovalFixture,
upperLane string,
upperStage string,
lowerStage string,
want windowsPrunableState,
) {
t.Helper()
got := captureWindowsPrunableState(t, fixture, upperStage, lowerStage)
if got != want {
t.Fatalf("prunable worktree state mutated on refusal\ngot: %#v\nwant: %#v", got, want)
}
if !windowsRegisteredWorktreePathExact(t, fixture, upperLane) {
t.Fatal("uppercase prunable registration was removed")
}
if _, err := os.Stat(upperLane); !os.IsNotExist(err) {
t.Fatalf("uppercase registry path unexpectedly exists: %v", err)
}
if _, err := os.Stat(fixture.lane); !os.IsNotExist(err) {
t.Fatalf("lowercase registry path unexpectedly exists: %v", err)
}
if lowerStage != "" && !windowsRegisteredWorktreePathExact(t, fixture, fixture.lane) {
t.Fatal("lowercase prunable registration was removed")
}
}
func newWindowsPrunableCaseVariantFixture(
t *testing.T,
includeLower bool,
) (*worktreeRemovalFixture, string, string, string, string) {
t.Helper()
fixture, upperLane, gitignore := newWindowsCaseSensitiveRemovalFixture(t, includeLower)
stageRoot := filepath.Join(filepath.Dir(fixture.repo), "staged")
if err := os.Mkdir(stageRoot, 0755); err != nil {
t.Fatalf("create staging directory: %v", err)
}
upperStage := filepath.Join(stageRoot, "upper")
if err := os.Rename(upperLane, upperStage); err != nil {
t.Fatalf("stage uppercase worktree: %v", err)
}
lowerStage := ""
if includeLower {
lowerStage = filepath.Join(stageRoot, "lower")
if err := os.Rename(fixture.lane, lowerStage); err != nil {
t.Fatalf("stage lowercase worktree: %v", err)
}
}
return fixture, upperLane, upperStage, lowerStage, gitignore
}
func newWindowsCaseSensitiveRemovalFixture(
t *testing.T,
includeLower bool,
) (*worktreeRemovalFixture, string, string) {
t.Helper()
root := t.TempDir()
requireWindowsCaseSensitiveDirectory(t, root)
fixture := &worktreeRemovalFixture{
repo: filepath.Join(root, "repo"),
gitignoreEntry: "lane",
}
fixture.lane = filepath.Join(fixture.repo, fixture.gitignoreEntry)
upperLane := filepath.Join(fixture.repo, "Lane")
if err := os.Mkdir(fixture.repo, 0755); err != nil {
t.Fatalf("create repository: %v", err)
}
fixture.git(t, fixture.repo, "init")
fixture.git(t, fixture.repo, "config", "user.name", worktreeRemoveTestActorName)
fixture.git(t, fixture.repo, "config", "user.email", worktreeRemoveTestActorEmail)
fixture.git(t, fixture.repo, "config", "commit.gpgsign", "false")
fixture.git(t, fixture.repo, "config", "core.ignorecase", "false")
fixture.git(t, fixture.repo, "config", "core.hooksPath", ".git/hooks")
fixture.git(t, fixture.repo, "symbolic-ref", "HEAD", "refs/heads/main")
gitignore := "# bd worktree\nLane/\nignored/\n"
if includeLower {
gitignore = "# bd worktree\nLane/\n# bd worktree\nlane/\nignored/\n"
}
if err := os.WriteFile(
filepath.Join(fixture.repo, ".gitignore"),
[]byte(gitignore),
0644,
); err != nil {
t.Fatalf("write .gitignore: %v", err)
}
fixture.git(t, fixture.repo, "add", ".gitignore")
fixture.git(t, fixture.repo, "commit", "-m", "base")
fixture.baseOID = fixture.git(t, fixture.repo, "rev-parse", "HEAD")
fixture.git(t, fixture.repo, "worktree", "add", "-b", "upper-lane", upperLane)
if includeLower {
fixture.git(t, fixture.repo, "worktree", "add", "-b", "lane", fixture.lane)
}
return fixture, upperLane, gitignore
}
func windowsRegisteredWorktreePathExact(
t *testing.T,
fixture *worktreeRemovalFixture,
want string,
) bool {
t.Helper()
want = filepath.Clean(want)
wantParent, err := os.Stat(filepath.Dir(want))
if err != nil {
t.Fatalf("stat expected registry parent: %v", err)
}
output := fixture.git(t, fixture.repo, "worktree", "list", "--porcelain", "-z")
for _, field := range strings.Split(output, "\x00") {
if !strings.HasPrefix(field, "worktree ") {
continue
}
registered := filepath.Clean(strings.TrimPrefix(field, "worktree "))
if filepath.Base(registered) != filepath.Base(want) {
continue
}
registeredParent, err := os.Stat(filepath.Dir(registered))
if err == nil && os.SameFile(registeredParent, wantParent) {
return true
}
}
return false
}
func requireWindowsCaseSensitiveDirectory(t *testing.T, path string) {
t.Helper()
set := exec.Command("fsutil.exe", "file", "SetCaseSensitiveInfo", path, "enable")
if output, err := set.CombinedOutput(); err != nil {
t.Fatalf(
"native Windows worktree boundary requires per-directory case sensitivity: %v\n%s",
err,
strings.TrimSpace(string(output)),
)
if got := fixture.readGitignore(t); got != "# bd worktree\nLane/\nignored/\n" {
t.Fatalf("cleanup targeted wrong sibling: %q", got)
}
}

View file

@ -29,15 +29,15 @@ func TestPrepareRefusesUnsafeTargetsInExistingOrder(t *testing.T) {
}
}
func TestPrepareCleanlinessAndContainmentRespectForce(t *testing.T) {
func TestPreparePolicyCleanlinessAndContainment(t *testing.T) {
for _, tt := range []struct {
name string
req Request
set func(*PrepareFacts)
want string
}{
{"dirty refused", Request{Mode: Normal}, func(f *PrepareFacts) { f.Status = Dirty }, "modified, untracked, or ignored"},
{"dirty forced", Request{Mode: Force}, func(f *PrepareFacts) {
{"dirty target refusal", Request{Mode: Normal}, func(f *PrepareFacts) { f.Status = Dirty }, "modified, untracked, or ignored"},
{"force stable dirty success", Request{Mode: Force}, func(f *PrepareFacts) {
f.Status, f.Comparator, f.Containment = Dirty, ComparatorNotRequired, ContainmentNotRequired
}, ""},
{"comparator required", Request{Mode: Normal}, func(f *PrepareFacts) { f.Comparator = ComparatorMissing }, "cannot verify unpushed commits"},
@ -136,25 +136,30 @@ func TestRevalidateRefusesZeroUnknownAndChangedInvariant(t *testing.T) {
}
}
func TestClassifyFailureUsesRawPostFailureEvidence(t *testing.T) {
func TestClassifyFailurePolicyUsesRawPostFailureEvidence(t *testing.T) {
plan, err := Prepare(Request{Mode: Normal}, prepareFacts())
if err != nil {
t.Fatal(err)
}
removeErr := assertErr{}
stable := FailureFacts{Revalidation: revalidationFacts(Normal), RevalidationResult: RevalidationPassed, Registration: Present, TargetPath: Present}
if got, err := ClassifyFailure(plan, stable, removeErr); err != nil || got.Kind != UnchangedFailure {
t.Fatalf("stable failure = (%#v, %v), want unchanged", got, err)
}
for _, facts := range []FailureFacts{
{Revalidation: revalidationFacts(Normal), Registration: Missing, TargetPath: Present},
{Revalidation: revalidationFacts(Normal), Registration: Present, TargetPath: Missing},
{Revalidation: revalidationFacts(Normal), RevalidationResult: RevalidationFailed, Registration: Present, TargetPath: Present},
func() FailureFacts { f := stable; f.Revalidation.Head = InvariantUnknown; return f }(),
for _, tt := range []struct {
name string
facts FailureFacts
want FailureKind
}{
{"unchanged primary failure", stable, UnchangedFailure},
{"indeterminate primary failure: missing registration", FailureFacts{Revalidation: revalidationFacts(Normal), Registration: Missing, TargetPath: Present}, PartialFailure},
{"indeterminate primary failure: missing path", FailureFacts{Revalidation: revalidationFacts(Normal), Registration: Present, TargetPath: Missing}, PartialFailure},
{"indeterminate primary failure: failed reinspection", FailureFacts{Revalidation: revalidationFacts(Normal), RevalidationResult: RevalidationFailed, Registration: Present, TargetPath: Present}, PartialFailure},
{"indeterminate primary failure: unknown invariant", func() FailureFacts { f := stable; f.Revalidation.Head = InvariantUnknown; return f }(), PartialFailure},
} {
if got, err := ClassifyFailure(plan, facts, removeErr); err != nil || got.Kind != PartialFailure {
t.Fatalf("indeterminate failure = (%#v, %v), want partial", got, err)
}
t.Run(tt.name, func(t *testing.T) {
got, err := ClassifyFailure(plan, tt.facts, removeErr)
if err != nil || got.Kind != tt.want {
t.Fatalf("ClassifyFailure() = (%#v, %v), want %v", got, err, tt.want)
}
})
}
if _, err := ClassifyFailure(Plan{}, stable, removeErr); err == nil {
t.Fatal("ClassifyFailure() accepted zero plan")