From e766da5ed07c59e3cf23c756c5bb9cf82e5a5fe7 Mon Sep 17 00:00:00 2001 From: ecuthiell Date: Wed, 30 Sep 2026 02:46:12 -0600 Subject: [PATCH] fix(worktree): preserve CRLF gitignore appends (#5677) * fix(worktree): preserve CRLF gitignore appends (#5670) Choose CRLF only when the user repository's existing .gitignore delimiters are consistently CRLF. Preserve existing bytes and retain LF as the default for every other convention. Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell Signed-off-by: Ewen Cuthiell * fix(worktree): complete trailing CR before a CRLF gitignore append Append only LF when the last existing byte already supplies the CR in the file's unambiguous CRLF convention. Preserve all existing bytes and cover the exact output and repeated-add behavior. Refs gastownhall/beads#5677 Agent: unknown-model/unknown-reasoning * docs(worktree): clarify LF trailing CR completion (saa-cgh.83) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * refactor(worktree): reuse the shared gitignore line-ending detector (saa-cgh.83) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * test(gitignore): keep line ending coverage with its shared owner (saa-cgh.83) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * build(bazel): enumerate worktree_gitignore_eol_test.go in cmd/bd go_test srcs cmd/bd/BUILD.bazel lists go_test srcs explicitly (647 entries), so the new untagged test file added by this PR is not compiled into //cmd/bd:bd_test. `make bazel-sync-check` cannot see this: it only runs tools/bazel/go_srcs.py, which manages the go_srcs filegroup glob, not the go_library/go_test srcs lists. The bazel.yml "BUILD files in sync" step runs `make bazel-sync` and fails on any resulting porcelain drift, so gazelle adding this entry would red that job; the lane is armed for this fork PR via `github.event.pull_request.head.repo.fork == true`. This line is gazelle's own output: re-running `make bazel-sync` after it leaves the file unchanged. With it, both of the PR's new tests execute under bazel (TestAddToGitignoreCompletesTrailingCR PASS in shard 3/16, TestAddToGitignorePreservesCRLFWhenAppending PASS in shard 4/16; //cmd/bd:bd_test 8 PASS / 0 FAIL / 0 SKIP) instead of being silently excluded from every bazel target. Co-Authored-By: Claude Opus 5 * test(worktree): cover the CRLF append arm that uses the detected line ending Maintainer review fix for PR #5677, adoption iteration 1. The synthesis is `approve` with no required changes; the one actionable finding is a minor, and it is taken because the PR already owes a push (the rebase needed a repair and a maintainer bazel commit is already on the branch). addToGitignore's `separator := lineEnding` is guarded twice: the block is only entered when the file does not end in "\n", and inside it a trailing "\r" is completed with a bare "\n" instead. So the detected "\r\n" is used for exactly one shape -- a CRLF file whose final byte is neither, i.e. an unterminated final line. Neither existing fixture reaches it: "a/\r\nb/\r" ends in CR and takes the completion branch, and "node_modules/\r\n" ends in LF so the block is never entered. internal/gitignore's own table already covers this input for the detector; the call site that consumes it did not. The new case asserts the exact bytes for initial "node_modules/\r\nbuild/", and appends twice so idempotence is covered as well as CRLF correctness. Mutation-proved: replacing `separator := lineEnding` with a hardcoded "\n" -- which would write the mixed-terminator .gitignore this PR exists to prevent -- reds ONLY this new test; all three pre-existing tests stay green. That is the surviving mutant the review reported, and it is now dead. The remaining nit asked for no change ("None required": the inline duplication of the append policy is byte-for-byte nil today, deliberate because the O_APPEND stream cannot take a whole-buffer API, and locked by exact-byte tests), so none was made. Not included: `make bazel-sync` also wants an `upgrade_smoke_loop_test.go` row in scripts/BUILD.bazel. That is base drift, not PR content -- the row is absent at this branch's rebase base (147047e153) but origin/main already carries it, 33 commits ahead -- so it heals on the next base refresh, and adding it here would duplicate main's own fix on a file this PR does not touch. --------- Signed-off-by: Ewen Cuthiell Co-authored-by: Gas City Adopt-PR Co-authored-by: Claude Opus 5 --- cmd/bd/BUILD.bazel | 1 + cmd/bd/worktree_cmd.go | 12 ++- cmd/bd/worktree_cmd_test.go | 11 +-- cmd/bd/worktree_gitignore_eol_test.go | 104 ++++++++++++++++++++++++++ internal/gitignore/append_test.go | 1 + 5 files changed, 120 insertions(+), 9 deletions(-) create mode 100644 cmd/bd/worktree_gitignore_eol_test.go diff --git a/cmd/bd/BUILD.bazel b/cmd/bd/BUILD.bazel index f3a7837e7..c47697a15 100644 --- a/cmd/bd/BUILD.bazel +++ b/cmd/bd/BUILD.bazel @@ -1164,6 +1164,7 @@ go_test( "workspace_gate_test.go", "workspace_identity_test.go", "worktree_cmd_test.go", + "worktree_gitignore_eol_test.go", "worktree_permissions_test.go", "worktree_remove_cmd_test.go", "worktree_remove_git_test.go", diff --git a/cmd/bd/worktree_cmd.go b/cmd/bd/worktree_cmd.go index 37a3b6b12..51b6ad5aa 100644 --- a/cmd/bd/worktree_cmd.go +++ b/cmd/bd/worktree_cmd.go @@ -23,6 +23,7 @@ import ( "github.com/steveyegge/beads/internal/execenv" "github.com/steveyegge/beads/internal/git" "github.com/steveyegge/beads/internal/gitenv" + "github.com/steveyegge/beads/internal/gitignore" "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/ui" "github.com/steveyegge/beads/internal/worktreeremove" @@ -2140,15 +2141,22 @@ func addToGitignore(ctx context.Context, repoRoot, entry string) error { } defer f.Close() + lineEnding := gitignore.AppendLineEnding(content) + // Add newline if file doesn't end with one if len(content) > 0 && content[len(content)-1] != '\n' { - if _, err := f.WriteString("\n"); err != nil { + separator := lineEnding + // Only CRLF needs this guard: the LF separator already completes a trailing CR. + if lineEnding == "\r\n" && content[len(content)-1] == '\r' { + separator = "\n" // Complete the existing CR without rewriting it. + } + if _, err := f.WriteString(separator); err != nil { return err } } // Add comment and entry - if _, err := f.WriteString(fmt.Sprintf("# bd worktree\n%s/\n", entry)); err != nil { + if _, err := fmt.Fprintf(f, "# bd worktree%s%s/%s", lineEnding, entry, lineEnding); err != nil { return err } diff --git a/cmd/bd/worktree_cmd_test.go b/cmd/bd/worktree_cmd_test.go index 91ec16bf1..ae2e6d4e1 100644 --- a/cmd/bd/worktree_cmd_test.go +++ b/cmd/bd/worktree_cmd_test.go @@ -1,6 +1,7 @@ package main import ( + "bytes" "context" "fmt" "os" @@ -271,13 +272,9 @@ func TestAddToGitignore(t *testing.T) { if err != nil { t.Fatalf("failed to read .gitignore: %v", err) } - content := string(updated) - - if count := strings.Count(content, "# bd worktree"); count != 1 { - t.Fatalf("expected one worktree marker, got %d:\n%s", count, content) - } - if count := strings.Count(content, entry+"/"); count != 1 { - t.Fatalf("expected one worktree entry, got %d:\n%s", count, content) + want := []byte("node_modules/\n# bd worktree\nworktree-feature/\n") + if !bytes.Equal(updated, want) { + t.Fatalf(".gitignore bytes after two appends:\nwant: %q\ngot: %q", want, updated) } }) } diff --git a/cmd/bd/worktree_gitignore_eol_test.go b/cmd/bd/worktree_gitignore_eol_test.go new file mode 100644 index 000000000..f330f8965 --- /dev/null +++ b/cmd/bd/worktree_gitignore_eol_test.go @@ -0,0 +1,104 @@ +package main + +import ( + "bytes" + "context" + "os" + "path/filepath" + "testing" +) + +func TestAddToGitignoreCompletesTrailingCR(t *testing.T) { + repoRoot := initGitRepoForGitignoreTest(t) + path := filepath.Join(repoRoot, ".gitignore") + initial := []byte("a/\r\nb/\r") + if err := os.WriteFile(path, initial, 0644); err != nil { + t.Fatal(err) + } + want := []byte("a/\r\nb/\r\n# bd worktree\r\nworktree-feature/\r\n") + for i := 0; i < 2; i++ { + if err := addToGitignore(context.Background(), repoRoot, "worktree-feature"); err != nil { + t.Fatal(err) + } + got, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, want) { + t.Fatalf("append %d bytes = %q, want %q", i+1, got, want) + } + } +} + +// TestAddToGitignoreCompletesUnterminatedCRLFLine covers the one arm where +// addToGitignore actually uses the detected line ending as its separator. +// +// The separator assignment is guarded twice over: the block is only entered when +// the file does not end in "\n", and inside it a trailing "\r" is completed with +// a bare "\n" instead. So the detected "\r\n" is used only for a CRLF file whose +// final byte is neither — an unterminated final line like "build/". The sibling +// fixtures in this file cannot reach it: "a/\r\nb/\r" ends in CR and takes the +// completion branch, and "node_modules/\r\n" ends in LF and never enters the +// block at all. Without this case, reverting the separator to a hardcoded "\n" +// still passes every test here while writing exactly the mixed-terminator +// .gitignore this change exists to prevent. +// +// internal/gitignore's own table already covers this input for the detector +// (append_test.go, "CRLF with unterminated final line"); this is the call site +// that consumes it. +func TestAddToGitignoreCompletesUnterminatedCRLFLine(t *testing.T) { + repoRoot := initGitRepoForGitignoreTest(t) + path := filepath.Join(repoRoot, ".gitignore") + initial := []byte("node_modules/\r\nbuild/") + if err := os.WriteFile(path, initial, 0644); err != nil { + t.Fatal(err) + } + want := []byte("node_modules/\r\nbuild/\r\n# bd worktree\r\nworktree-feature/\r\n") + // Twice: the append must be idempotent as well as CRLF-correct. + for i := 0; i < 2; i++ { + if err := addToGitignore(context.Background(), repoRoot, "worktree-feature"); err != nil { + t.Fatal(err) + } + got, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, want) { + t.Fatalf("append %d bytes = %q, want %q", i+1, got, want) + } + } +} + +func TestAddToGitignorePreservesCRLFWhenAppending(t *testing.T) { + repoRoot := initGitRepoForGitignoreTest(t) + gitignorePath := filepath.Join(repoRoot, ".gitignore") + initial := []byte("node_modules/\r\n") + if err := os.WriteFile(gitignorePath, initial, 0644); err != nil { + t.Fatalf("failed to write .gitignore: %v", err) + } + + entry := "worktree-feature" + if err := addToGitignore(context.Background(), repoRoot, entry); err != nil { + t.Fatalf("first addToGitignore failed: %v", err) + } + + want := []byte("node_modules/\r\n# bd worktree\r\nworktree-feature/\r\n") + updated, err := os.ReadFile(gitignorePath) + if err != nil { + t.Fatalf("failed to read .gitignore: %v", err) + } + if !bytes.Equal(updated, want) { + t.Fatalf(".gitignore bytes after append:\nwant: %q\ngot: %q", want, updated) + } + + if err := addToGitignore(context.Background(), repoRoot, entry); err != nil { + t.Fatalf("second addToGitignore failed: %v", err) + } + unchanged, err := os.ReadFile(gitignorePath) + if err != nil { + t.Fatalf("failed to reread .gitignore: %v", err) + } + if !bytes.Equal(unchanged, want) { + t.Fatalf("second append changed .gitignore:\nwant: %q\ngot: %q", want, unchanged) + } +} diff --git a/internal/gitignore/append_test.go b/internal/gitignore/append_test.go index 5c51fc85b..250c39ee7 100644 --- a/internal/gitignore/append_test.go +++ b/internal/gitignore/append_test.go @@ -8,6 +8,7 @@ func TestAppendLineEnding(t *testing.T) { {"delimiter-free", "local", "\n"}, {"LF", "a\n", "\n"}, {"CRLF", "a\r\n", "\r\n"}, + {"CRLF with unterminated final line", "node_modules/\r\nbuild/", "\r\n"}, {"mixed", "a\r\nb\r\nc\n", "\n"}, {"BOM LF", "\xef\xbb\xbfa\n", "\n"}, {"BOM CRLF", "\xef\xbb\xbfa\r\n", "\r\n"},