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 <ewencuthiell@gmail.com>

* 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 <noreply@anthropic.com>

* 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 <ewencuthiell@gmail.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
ecuthiell 2026-09-30 02:46:12 -06:00 • committed by GitHub
commit e766da5ed0
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 120 additions and 9 deletions

View file

@ -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",

View file

@ -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
}

View file

@ -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)
}
})
}

View file

@ -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)
}
}

View file

@ -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"},