* fix(exec): match Windows environment key identity (#5618) Centralize os/exec-compatible environment-key comparison and use it for credential, metrics, Git-hook, trace, and repro subprocess filters. Preserve exact Unix semantics and Unicode near-collisions. Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell Signed-off-by: Ewen Cuthiell <ewencuthiell@gmail.com> * fix(worktree): scrub inherited Git routing state Establish CWD as the worktree repository boundary before discovery can consume inherited Git routing. Fence the startup config probe, clear routing in-process before root pre-run discovery, and retain command-owned subprocess scrubbing as defense in depth without changing PID or signal semantics. Fixes #5531 Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell * refactor(worktree): explain owned filtering and remove an unused shim Document why filtering the fresh routing slice in place is safe and call the shared routing-key classifier directly from tests. Retain the two forwarders used by production worktree subprocess/removal paths. Review: https://github.com/gastownhall/beads/pull/5623#pullrequestreview-5098421671 Bead: saa-cgh.23 Agent-Signature: unknown-model/unknown-reasoning * fix(config): isolate identity and tracked-file Git probes from routing Reuse the worktree routing owner for GetIdentity and isGitTracked so explicit cwd/path selection is not displaced by inherited repository, index or injected config state. Preserve identity precedence and the tracked-secret refusal contract, with real target/decoy regressions. Follow-up: https://github.com/gastownhall/beads/issues/6222 Dependency: https://github.com/gastownhall/beads/pull/5623 Reported-by: bee-ghosttrack Bead: saa-cgh.93 Agent-Signature: unknown-model/unknown-reasoning * test(execenv): exercise every environment operation under both host rules Thread the host choice through narrow private helpers behind the existing exported functions. Keep one normalization owner and retain native wrapper tests; the additional table covers both host branches for equality, prefix matching, last-wins lookup, filtering and input preservation. Review: https://github.com/gastownhall/beads/pull/5672#pullrequestreview-5096948965 Bead: saa-cgh.78 Agent-Signature: unknown-model/unknown-reasoning * docs(worktree): explain startup Git environment scope (saa-cgh.23) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * test(execenv): exercise exported host policy wiring (saa-cgh.78) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(config): share subprocess key identity for Git routing (saa-cgh.93) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(hooks): isolate tracked-file guard from Git routing (saa-cgh.98) Follow-up to bee-ghosttrack's review of gastownhall/beads#6322; refs #6356. Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(config): isolate role commands from Git routing (saa-cgh.99) Follow-up to bee-ghosttrack's review of gastownhall/beads#6322; refs #6357. Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * test(env): exercise shared key helpers on native Windows (saa-cgh.78) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * refactor(gitenv): share key parsing and normalize routing membership once (saa-cgh.93) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * docs(config): explain role command routing policy (saa-cgh.99) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(hooks): retain legitimate inherited tracking context (saa-cgh.98) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * test(hooks): isolate trusted global configuration fixture (saa-cgh.98) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(hooks): isolate role cleanup in the selected repository (saa-cgh.109.4) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(hooks): reset only common local role configuration (saa-cgh.109.10) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(hooks): scope hooks-path cleanup to selected common config (saa-cgh.109.11) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * test(hooks): make worktree role preservation independent (saa-cgh.120) Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell * Report selected config read failures during hook reset (saa-cgh.120) Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell * fix(hooks): keep successful config stdout separate from diagnostics (saa-cgh.120) Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell * fix(config): pin role writes to fresh common context (GH#6384) (saa-cgh.120.3) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(config): retain Git diagnostics from role writes (saa-cgh.120.3) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * test(config): assert the actual Git lock diagnostic (saa-cgh.120.3) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(config,hooks): restore the inherited-tracking fallback in the secret guard Maintainer review fixes for PR #6454 (adopt-pr iteration 1). The scorecard approved at 913/1000 with no blocker or major surviving synthesis; these are the non-gating findings that were cheap to close while the fixup was open. Finding 1 (minor, security) is the only in-range regression in the report. The range switched internal/config.isGitTracked from the inherited environment to gitenv.ScrubRouting only, so a config.yaml tracked solely through legitimate routing -- a bare repository whose work tree is named by GIT_DIR/GIT_WORK_TREE -- reported untracked, and a secret-key write that upstream-base refused was silently allowed. Restores the scrubbed-then-inherited union the same stack already gave cmd/bd.isGitTrackedFile. Finding 4 (nit) composes with it rather than conflicting, so both land as one change: the inherited probe now runs only when the scrubbed probe failed for a configuration reason. git's exit codes discriminate exactly -- 0 tracked, 1 repository reached but path untracked (final), 128 no reachable repository -- so the ordinary untracked-hook miss no longer spawns a second `git ls-files` while the bare-work-tree fallback is preserved. Finding 2 (minor). scrubWorktreeRemovalGitEnvForOS keyed its stricter no-optional-locks policy on strings.ToUpper while the rest of the PR uses execenv key identity. The two disagree in both directions on Windows: GIT_OPTIONAL_LOCKS with a dotted capital I (U+0130) survived the scrub although Git honors it, and GIT_OPTIONAL_LOCK with a long s (U+017F) was dropped although os/exec keeps it distinct. normalizeWorktreeGitEnvKey is deleted in favour of execenv.KeyEqualForOS. Base applied ToUpper on all platforms, so this is a consistency fix in newly rewritten code, not a regression. Finding 5 (nit). The comment above resetHooksPathIfBeadsManaged's probe asserted that repoRoot and commonDir share the cached Git context. Probed false: with cwd A and GIT_DIR=B/.git, `git rev-parse --git-common-dir --show-toplevel` prints B/.git and A. Restated as intent. Finding 3 (scrubGitHookEnv is a fifth, strictly weaker routing scrubber) is deliberately not taken here: cmd/bd/export_auto.go is untouched by this range, so the hazard is byte-identical at base, and the synthesis scoped it to a follow-up bead rather than growing this stack. Each fix is mutation-proved. Reverting isGitTracked reds only the new TestSecretGitTrackingHonorsInheritedBareWorkTree -- including "refusal = <nil>", the actual security consequence -- while the incumbent decoy test stays green, so the pin adds coverage rather than duplicating it. Restoring ToUpper reds only the new Windows row, showing both directions at once. TestGuardHookWritePathHonorsInheritedRepository gains a fixture guard asserting its scrubbed probe fails for a configuration reason rather than exit 1, so a future fixture change cannot silently make the fallback unreachable. scrubWorktreeRemovalGitEnvForOS had no test at all before this. Green locally: ./internal/config, ./internal/execenv, ./internal/gitenv, ./internal/githooksenv, ./internal/gittraceenv, ./internal/metrics, ./scripts, ./internal/beads (the GIT_CONFIG_GLOBAL blast radius neither reviewer ran), and a blast-radius cmd/bd run over the hooks, worktree, role and uninstall suites. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --------- Signed-off-by: Ewen Cuthiell <ewencuthiell@gmail.com> Co-authored-by: Bee <bee@ghosttrack.com> Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local> Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com> Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
453 lines
17 KiB
Go
453 lines
17 KiB
Go
package main
|
||
|
||
import (
|
||
"bytes"
|
||
"encoding/json"
|
||
"errors"
|
||
"fmt"
|
||
"os"
|
||
"os/exec"
|
||
"path/filepath"
|
||
"reflect"
|
||
"strings"
|
||
"testing"
|
||
)
|
||
|
||
const (
|
||
worktreeRemoveHelperEnv = "BD_WORKTREE_REMOVE_PROCESS_HELPER"
|
||
worktreeRemoveHelperArgsEnv = "BD_WORKTREE_REMOVE_PROCESS_ARGS"
|
||
worktreeRemoveHelperHookEnv = "BD_WORKTREE_REMOVE_PROCESS_HOOK"
|
||
worktreeRemoveHelperTarget = "BD_WORKTREE_REMOVE_PROCESS_TARGET"
|
||
worktreeRemoveHelperMain = "BD_WORKTREE_REMOVE_PROCESS_MAIN"
|
||
worktreeRemoveHookReplace = "replace-target"
|
||
worktreeRemoveHookCaseRace = "case-race-before-remove"
|
||
worktreeRemoveHookGitignore = "change-gitignore-after-remove"
|
||
worktreeRemoveTestActorName = "Worktree Removal Test"
|
||
worktreeRemoveTestActorEmail = "worktree-removal@example.invalid"
|
||
)
|
||
|
||
// TestWorktreeRemoveProcessHelper runs the command only for the small E2E
|
||
// lane. Adapter contracts execute in-process in worktree_remove_git_test.go.
|
||
func TestWorktreeRemoveProcessHelper(t *testing.T) {
|
||
if os.Getenv(worktreeRemoveHelperEnv) != "1" {
|
||
return
|
||
}
|
||
var args []string
|
||
if err := json.Unmarshal([]byte(os.Getenv(worktreeRemoveHelperArgsEnv)), &args); err != nil {
|
||
t.Fatalf("decode helper arguments: %v", err)
|
||
}
|
||
hooks := worktreeRemoveHooks{}
|
||
switch os.Getenv(worktreeRemoveHelperHookEnv) {
|
||
case "":
|
||
case worktreeRemoveHookReplace:
|
||
hooks.beforeFinalCheck = func() error {
|
||
mainWorktree, target := os.Getenv(worktreeRemoveHelperMain), os.Getenv(worktreeRemoveHelperTarget)
|
||
if err := runWorktreeRemoveHookGit(mainWorktree, "worktree", "remove", "--", target); err != nil {
|
||
return err
|
||
}
|
||
if err := runWorktreeRemoveHookGit(mainWorktree, "worktree", "add", "--", target, "lane"); err != nil {
|
||
return err
|
||
}
|
||
return runWorktreeRemoveHookGit(target, "reset", "--hard", "HEAD")
|
||
}
|
||
case worktreeRemoveHookGitignore:
|
||
hooks.afterRemoval = func() error {
|
||
path := filepath.Join(os.Getenv(worktreeRemoveHelperMain), ".gitignore")
|
||
file, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
if _, err := file.WriteString("# concurrent change\n"); err != nil {
|
||
_ = file.Close()
|
||
return err
|
||
}
|
||
return file.Close()
|
||
}
|
||
case worktreeRemoveHookCaseRace:
|
||
hooks.beforeRemove = func() error {
|
||
target := os.Getenv(worktreeRemoveHelperTarget)
|
||
if err := os.Rename(target, target+"-moved"); err != nil {
|
||
return err
|
||
}
|
||
return runWorktreeRemoveHookGit(os.Getenv(worktreeRemoveHelperMain), "config", "core.ignorecase", "true")
|
||
}
|
||
default:
|
||
t.Fatalf("unknown helper hook %q", os.Getenv(worktreeRemoveHelperHookEnv))
|
||
}
|
||
command := newWorktreeRemoveCommandWithHooks(hooks)
|
||
command.SetArgs(args)
|
||
if err := command.Execute(); err != nil {
|
||
fmt.Fprintln(os.Stderr, err)
|
||
t.FailNow()
|
||
}
|
||
}
|
||
|
||
func runWorktreeRemoveHookGit(dir string, args ...string) error {
|
||
command := exec.Command("git", args...)
|
||
command.Dir = dir
|
||
command.Env = append(scrubWorktreeGitRoutingEnv(os.Environ()), "GIT_CONFIG_GLOBAL="+os.DevNull, "GIT_CONFIG_SYSTEM="+os.DevNull, "GIT_CONFIG_NOSYSTEM=1", "GIT_NO_REPLACE_OBJECTS=1")
|
||
output, err := command.CombinedOutput()
|
||
if err != nil {
|
||
return fmt.Errorf("git %s failed: %w\n%s", strings.Join(args, " "), err, output)
|
||
}
|
||
return nil
|
||
}
|
||
|
||
func TestWorktreeRemoveCobraGrammar(t *testing.T) {
|
||
tests := []struct {
|
||
name string
|
||
args []string
|
||
wantErr string
|
||
}{
|
||
{"explicit empty comparator", []string{"lane", "--merged-into="}, "--merged-into requires a non-empty value"},
|
||
{"repeated comparator", []string{"lane", "--merged-into", "main", "--merged-into", "refs/heads/main"}, "--merged-into may be specified only once"},
|
||
{"repeated force", []string{"lane", "--force", "--force"}, "--force may be specified only once"},
|
||
{"force conflicts with comparator", []string{"lane", "--force", "--merged-into", "main"}, "--force and --merged-into cannot be used together"},
|
||
{"explicit false force still conflicts with comparator", []string{"lane", "--force=false", "--merged-into", "main"}, "--force and --merged-into cannot be used together"},
|
||
}
|
||
for _, test := range tests {
|
||
t.Run(test.name, func(t *testing.T) {
|
||
command := newWorktreeRemoveCommand()
|
||
command.SetArgs(test.args)
|
||
if err := command.Execute(); err == nil || !strings.Contains(err.Error(), test.wantErr) {
|
||
t.Fatalf("command error = %v, want %q", err, test.wantErr)
|
||
}
|
||
})
|
||
}
|
||
}
|
||
|
||
func TestWorktreeRemoveE2ECleanExplicitComparatorSuccess(t *testing.T) {
|
||
fixture := newWorktreeRemovalFixture(t)
|
||
fixture.commitLane(t, "contained")
|
||
fixture.mergeLaneIntoMain(t)
|
||
result := runWorktreeRemoveProcess(t, fixture.repo, nil, fixture.lane, "--merged-into", "main")
|
||
result.requireSuccess(t)
|
||
fixture.assertRemovedAndCleaned(t)
|
||
}
|
||
|
||
func TestWorktreeRemoveE2ERefusesBetweenObservationIdentityMutation(t *testing.T) {
|
||
fixture := newWorktreeRemovalFixture(t)
|
||
fixture.commitLane(t, "contained")
|
||
fixture.mergeLaneIntoMain(t)
|
||
before := fixture.snapshot(t)
|
||
result := runWorktreeRemoveProcess(t, fixture.repo, []string{worktreeRemoveHelperHookEnv + "=" + worktreeRemoveHookReplace, worktreeRemoveHelperTarget + "=" + fixture.lane, worktreeRemoveHelperMain + "=" + fixture.repo}, fixture.lane, "--merged-into", "main")
|
||
result.requireFailure(t, "identity changed")
|
||
fixture.assertSnapshot(t, before)
|
||
}
|
||
|
||
func TestWorktreeRemoveE2EReportsRemovalSuccessCleanupFailure(t *testing.T) {
|
||
fixture := newWorktreeRemovalFixture(t)
|
||
fixture.commitLane(t, "contained")
|
||
fixture.mergeLaneIntoMain(t)
|
||
result := runWorktreeRemoveProcess(t, fixture.repo, []string{worktreeRemoveHelperHookEnv + "=" + worktreeRemoveHookGitignore, worktreeRemoveHelperMain + "=" + fixture.repo}, fixture.lane, "--merged-into", "main")
|
||
result.requireFailure(t, "worktree was removed")
|
||
if !strings.Contains(result.combined(), ".gitignore cleanup failed") {
|
||
t.Fatalf("partial error did not name cleanup failure:\n%s", result.combined())
|
||
}
|
||
if fixture.registered(t, fixture.lane) {
|
||
t.Fatal("partial outcome did not remove target")
|
||
}
|
||
if _, err := os.Stat(fixture.lane); !os.IsNotExist(err) {
|
||
t.Fatalf("target still exists: %v", err)
|
||
}
|
||
gitignore := fixture.readGitignore(t)
|
||
if !strings.Contains(gitignore, "lane/") || !strings.Contains(gitignore, "# concurrent change") {
|
||
t.Fatalf("failed cleanup overwrote concurrent .gitignore content:\n%s", gitignore)
|
||
}
|
||
fixture.git(t, fixture.repo, "rev-parse", "--verify", "refs/heads/lane")
|
||
}
|
||
|
||
func TestScrubWorktreeGitEnvUsesHostKeySemantics(t *testing.T) {
|
||
input := []string{
|
||
"PATH=/trusted/bin",
|
||
"HOME=/home/test",
|
||
"GIT_AUTHOR_NAME=Test User",
|
||
"GIT_DIR=/wrong",
|
||
"git_work_tree=/wrong-case",
|
||
"GIT_CONFIG_COUNT=1",
|
||
"GIT_CONFIG_KEY_0=core.worktree",
|
||
"git_config_value_0=/wrong-case",
|
||
"GIT_OBJECT_DIRECTORY=/wrong-objects",
|
||
"GIT_EXEC_PATH=/wrong-exec",
|
||
"GIT_NO_REPLACE_OBJECTS=1",
|
||
"GIT_OPTIONAL_LOCKS=1",
|
||
}
|
||
for _, test := range []struct {
|
||
name, goos string
|
||
want []string
|
||
}{
|
||
{
|
||
name: "POSIX names are case-sensitive",
|
||
goos: "linux",
|
||
want: []string{"PATH=/trusted/bin", "HOME=/home/test", "GIT_AUTHOR_NAME=Test User", "git_work_tree=/wrong-case", "git_config_value_0=/wrong-case", "GIT_NO_REPLACE_OBJECTS=1", "GIT_OPTIONAL_LOCKS=1"},
|
||
},
|
||
{
|
||
name: "Windows names are case-insensitive",
|
||
goos: "windows",
|
||
want: []string{"PATH=/trusted/bin", "HOME=/home/test", "GIT_AUTHOR_NAME=Test User", "GIT_NO_REPLACE_OBJECTS=1", "GIT_OPTIONAL_LOCKS=1"},
|
||
},
|
||
} {
|
||
t.Run(test.name, func(t *testing.T) {
|
||
if got := scrubWorktreeGitRoutingEnvForOS(input, test.goos); !reflect.DeepEqual(got, test.want) {
|
||
t.Fatalf("scrubWorktreeGitRoutingEnvForOS() = %#v, want %#v", got, test.want)
|
||
}
|
||
})
|
||
}
|
||
}
|
||
|
||
// The removal scrub's stricter no-optional-locks policy must key off the same
|
||
// identity rule the subprocess uses (execenv), not strings.ToUpper: on Windows
|
||
// the two disagree in both directions for non-ASCII keys, so ToUpper both lets
|
||
// a honored key survive and drops one os/exec keeps distinct.
|
||
func TestScrubWorktreeRemovalGitEnvUsesSubprocessKeyIdentity(t *testing.T) {
|
||
input := []string{
|
||
"PATH=/trusted/bin",
|
||
"GIT_NO_REPLACE_OBJECTS=1",
|
||
"GIT_OPTIONAL_LOCKS=1",
|
||
// U+0130: ToUpper leaves it unmatched, Win32 folds it to git_optional_locks.
|
||
"GİT_OPTIONAL_LOCKS=1",
|
||
// U+017F: ToUpper folds it onto the literal, Win32 keeps it distinct.
|
||
"GIT_OPTIONAL_LOCKſ=1",
|
||
}
|
||
for _, test := range []struct {
|
||
name, goos string
|
||
want []string
|
||
}{
|
||
{
|
||
name: "POSIX keys are byte-exact",
|
||
goos: "linux",
|
||
want: []string{"PATH=/trusted/bin", "GİT_OPTIONAL_LOCKS=1", "GIT_OPTIONAL_LOCKſ=1"},
|
||
},
|
||
{
|
||
name: "Windows keys follow subprocess identity",
|
||
goos: "windows",
|
||
want: []string{"PATH=/trusted/bin", "GIT_OPTIONAL_LOCKſ=1"},
|
||
},
|
||
} {
|
||
t.Run(test.name, func(t *testing.T) {
|
||
if got := scrubWorktreeRemovalGitEnvForOS(input, test.goos); !reflect.DeepEqual(got, test.want) {
|
||
t.Fatalf("scrubWorktreeRemovalGitEnvForOS() = %#v, want %#v", got, test.want)
|
||
}
|
||
})
|
||
}
|
||
}
|
||
|
||
func TestNewWorktreeRemovalGitPinsExecutable(t *testing.T) {
|
||
t.Setenv("GIT_NO_REPLACE_OBJECTS", "0")
|
||
t.Setenv("GIT_OPTIONAL_LOCKS", "1")
|
||
runner, err := newWorktreeRemovalGit()
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if !filepath.IsAbs(runner.executable) {
|
||
t.Fatalf("git executable is not absolute: %q", runner.executable)
|
||
}
|
||
for key, want := range map[string]string{
|
||
"GIT_NO_REPLACE_OBJECTS": "1",
|
||
"GIT_OPTIONAL_LOCKS": "0",
|
||
} {
|
||
matches := 0
|
||
for _, entry := range runner.env {
|
||
if strings.HasPrefix(entry, key+"=") {
|
||
matches++
|
||
if entry != key+"="+want {
|
||
t.Fatalf("%s = %q, want %q", key, entry, key+"="+want)
|
||
}
|
||
}
|
||
}
|
||
if matches != 1 {
|
||
t.Fatalf("%s occurs %d times in removal environment, want once", key, matches)
|
||
}
|
||
}
|
||
}
|
||
|
||
type worktreeRemoveProcessResult struct {
|
||
stdout, stderr string
|
||
exitCode int
|
||
}
|
||
|
||
func (result worktreeRemoveProcessResult) combined() string { return result.stdout + result.stderr }
|
||
func (result worktreeRemoveProcessResult) requireSuccess(t *testing.T) {
|
||
t.Helper()
|
||
if result.exitCode != 0 {
|
||
t.Fatalf("worktree command failed with exit code %d\nstdout:\n%s\nstderr:\n%s", result.exitCode, result.stdout, result.stderr)
|
||
}
|
||
}
|
||
func (result worktreeRemoveProcessResult) requireFailure(t *testing.T, substring string) {
|
||
t.Helper()
|
||
if result.exitCode == 0 {
|
||
t.Fatalf("worktree remove succeeded; want failure containing %q", substring)
|
||
}
|
||
if !strings.Contains(result.combined(), substring) {
|
||
t.Fatalf("failure output did not contain %q\nstdout:\n%s\nstderr:\n%s", substring, result.stdout, result.stderr)
|
||
}
|
||
}
|
||
|
||
func runWorktreeRemoveProcess(t *testing.T, dir string, extraEnv []string, args ...string) worktreeRemoveProcessResult {
|
||
t.Helper()
|
||
executable, err := os.Executable()
|
||
if err != nil {
|
||
t.Fatalf("resolve test executable: %v", err)
|
||
}
|
||
encodedArgs, err := json.Marshal(args)
|
||
if err != nil {
|
||
t.Fatalf("encode helper arguments: %v", err)
|
||
}
|
||
command := exec.Command(executable, "-test.run=^TestWorktreeRemoveProcessHelper$")
|
||
command.Dir = dir
|
||
command.Env = overrideWorktreeRemoveEnv(os.Environ(), append([]string{worktreeRemoveHelperEnv + "=1", worktreeRemoveHelperArgsEnv + "=" + string(encodedArgs), "BD_DISABLE_METRICS=1"}, extraEnv...))
|
||
var stdout, stderr bytes.Buffer
|
||
command.Stdout, command.Stderr = &stdout, &stderr
|
||
err = command.Run()
|
||
exitCode := 0
|
||
if err != nil {
|
||
var exitError *exec.ExitError
|
||
if !errors.As(err, &exitError) {
|
||
t.Fatalf("launch worktree remove helper: %v", err)
|
||
}
|
||
exitCode = exitError.ExitCode()
|
||
}
|
||
return worktreeRemoveProcessResult{stdout: stdout.String(), stderr: stderr.String(), exitCode: exitCode}
|
||
}
|
||
|
||
func overrideWorktreeRemoveEnv(base, overrides []string) []string {
|
||
result := append([]string(nil), base...)
|
||
for _, override := range overrides {
|
||
key := override
|
||
if separator := strings.IndexByte(override, '='); separator >= 0 {
|
||
key = override[:separator]
|
||
}
|
||
filtered := result[:0]
|
||
for _, entry := range result {
|
||
entryKey := entry
|
||
if separator := strings.IndexByte(entry, '='); separator >= 0 {
|
||
entryKey = entry[:separator]
|
||
}
|
||
if !strings.EqualFold(entryKey, key) {
|
||
filtered = append(filtered, entry)
|
||
}
|
||
}
|
||
result = append(filtered, override)
|
||
}
|
||
return result
|
||
}
|
||
|
||
type worktreeRemovalFixture struct{ repo, lane, baseOID, gitignoreEntry string }
|
||
|
||
func newWorktreeRemovalFixture(t *testing.T) *worktreeRemovalFixture {
|
||
return newWorktreeRemovalFixtureAt(t, "lane")
|
||
}
|
||
func newWorktreeRemovalFixtureAt(t *testing.T, gitignoreEntry string) *worktreeRemovalFixture {
|
||
t.Helper()
|
||
root := t.TempDir()
|
||
fixture := &worktreeRemovalFixture{repo: filepath.Join(root, "repo"), gitignoreEntry: gitignoreEntry}
|
||
fixture.lane = filepath.Join(fixture.repo, filepath.FromSlash(gitignoreEntry))
|
||
if err := os.MkdirAll(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.hooksPath", ".git/hooks")
|
||
fixture.git(t, fixture.repo, "symbolic-ref", "HEAD", "refs/heads/main")
|
||
if err := os.WriteFile(filepath.Join(fixture.repo, ".gitignore"), []byte(fmt.Sprintf("# bd worktree\n%s/\nignored/\n", fixture.gitignoreEntry)), 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", "lane", fixture.lane)
|
||
return fixture
|
||
}
|
||
func (fixture *worktreeRemovalFixture) setUpstream(t *testing.T) {
|
||
t.Helper()
|
||
fixture.git(t, fixture.lane, "branch", "--set-upstream-to=main", "lane")
|
||
}
|
||
func (fixture *worktreeRemovalFixture) commitLane(t *testing.T, message string) {
|
||
t.Helper()
|
||
fixture.git(t, fixture.lane, "commit", "--allow-empty", "-m", message)
|
||
}
|
||
func (fixture *worktreeRemovalFixture) mergeLaneIntoMain(t *testing.T) {
|
||
t.Helper()
|
||
fixture.git(t, fixture.repo, "merge", "--ff-only", "lane")
|
||
}
|
||
func (fixture *worktreeRemovalFixture) writeLaneFile(t *testing.T, name, content string) {
|
||
t.Helper()
|
||
path := filepath.Join(fixture.lane, name)
|
||
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if err := os.WriteFile(path, []byte(content), 0644); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
}
|
||
func (fixture *worktreeRemovalFixture) writeTargetPseudoref(t *testing.T, name string) {
|
||
t.Helper()
|
||
gitPath := fixture.git(t, fixture.lane, "rev-parse", "--git-path", name)
|
||
if !filepath.IsAbs(gitPath) {
|
||
gitPath = filepath.Join(fixture.lane, gitPath)
|
||
}
|
||
head := fixture.git(t, fixture.lane, "rev-parse", "HEAD")
|
||
if err := os.WriteFile(gitPath, []byte(head+"\n"), 0644); err != nil {
|
||
t.Fatalf("write target pseudoref %s: %v", name, err)
|
||
}
|
||
}
|
||
func (fixture *worktreeRemovalFixture) registered(t *testing.T, path string) bool {
|
||
t.Helper()
|
||
output := fixture.git(t, fixture.repo, "worktree", "list", "--porcelain", "-z")
|
||
for _, field := range strings.Split(output, "\x00") {
|
||
if strings.HasPrefix(field, "worktree ") && sameWorktreePath(strings.TrimPrefix(field, "worktree "), path) {
|
||
return true
|
||
}
|
||
}
|
||
return false
|
||
}
|
||
|
||
type worktreeRemovalSnapshot struct{ registry, head, status, branchOID, gitignore string }
|
||
|
||
func (fixture *worktreeRemovalFixture) snapshot(t *testing.T) worktreeRemovalSnapshot {
|
||
t.Helper()
|
||
return worktreeRemovalSnapshot{registry: fixture.git(t, fixture.repo, "worktree", "list", "--porcelain", "-z"), head: fixture.git(t, fixture.lane, "rev-parse", "HEAD"), status: fixture.git(t, fixture.lane, "status", "--porcelain=v1", "-z", "--untracked-files=all", "--ignored=matching"), branchOID: fixture.git(t, fixture.repo, "rev-parse", "refs/heads/lane"), gitignore: fixture.readGitignore(t)}
|
||
}
|
||
func (fixture *worktreeRemovalFixture) assertSnapshot(t *testing.T, want worktreeRemovalSnapshot) {
|
||
t.Helper()
|
||
if got := fixture.snapshot(t); !reflect.DeepEqual(got, want) {
|
||
t.Fatalf("worktree state mutated on refusal\ngot: %#v\nwant: %#v", got, want)
|
||
}
|
||
if !fixture.registered(t, fixture.lane) {
|
||
t.Fatal("target is no longer registered after refusal")
|
||
}
|
||
}
|
||
func (fixture *worktreeRemovalFixture) readGitignore(t *testing.T) string {
|
||
t.Helper()
|
||
content, err := os.ReadFile(filepath.Join(fixture.repo, ".gitignore"))
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
return string(content)
|
||
}
|
||
func (fixture *worktreeRemovalFixture) assertRemovedAndCleaned(t *testing.T) {
|
||
t.Helper()
|
||
if fixture.registered(t, fixture.lane) {
|
||
t.Fatal("target remains registered")
|
||
}
|
||
if _, err := os.Stat(fixture.lane); !os.IsNotExist(err) {
|
||
t.Fatalf("target path still exists: %v", err)
|
||
}
|
||
fixture.git(t, fixture.repo, "rev-parse", "--verify", "refs/heads/lane")
|
||
if strings.Contains(fixture.readGitignore(t), fixture.gitignoreEntry+"/") {
|
||
t.Fatalf(".gitignore still contains entry")
|
||
}
|
||
}
|
||
func (fixture *worktreeRemovalFixture) git(t *testing.T, directory string, args ...string) string {
|
||
t.Helper()
|
||
command := exec.Command("git", args...)
|
||
command.Dir = directory
|
||
command.Env = append(scrubWorktreeGitRoutingEnv(os.Environ()), "GIT_CONFIG_GLOBAL="+os.DevNull, "GIT_CONFIG_SYSTEM="+os.DevNull, "GIT_CONFIG_NOSYSTEM=1", "GIT_NO_REPLACE_OBJECTS=1")
|
||
output, err := command.CombinedOutput()
|
||
if err != nil {
|
||
t.Fatalf("git %s failed: %v\n%s", strings.Join(args, " "), err, output)
|
||
}
|
||
return strings.TrimSpace(string(output))
|
||
}
|