Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 18 additions & 19 deletions src/loopzero/worktree.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,21 @@
from __future__ import annotations

import errno
import fcntl
import os
import re
import stat
import subprocess
import tempfile
from collections.abc import Iterator
from contextlib import contextmanager
from contextlib import contextmanager, suppress
from pathlib import Path
from select import select
from uuid import uuid4

from loopzero._proc import build_env, run

GIT_ENV = ("PATH", "HOME", "LANG", "LC_ALL", "TERM", "GIT_SSH_COMMAND", "SSH_AUTH_SOCK")
_ABSOLUTE_COMMON_DIR = ("rev-parse", "--path-format=absolute", "--git-common-dir")
EXCLUDES = (".worktrees/", ".loopzero/")
EXCLUDES = (b".worktrees/", b".loopzero/")
_BASE_LINE = re.compile(r"^Base:\s*([0-9a-fA-F]{7,40})\s*$", re.MULTILINE)
_TASK_TEMPLATE = """# {title}

Expand Down Expand Up @@ -111,21 +111,20 @@ def _ensure_excludes(repo_root: Path) -> None:
if not info.is_relative_to(common) or not exclude.is_relative_to(common):
raise WorktreeError(f"Git exclude is outside its Git directory: {exclude}")
exclude.parent.mkdir(parents=True, exist_ok=True)
existing = exclude.read_text() if exclude.exists() else ""
missing = [entry for entry in EXCLUDES if entry not in existing.splitlines()]
if missing:
sep = "" if not existing or existing.endswith("\n") else "\n"
mode = stat.S_IMODE(exclude.stat().st_mode) if exclude.exists() else None
temp = exclude.with_name(f".exclude-{uuid4().hex}")
stream = temp.open("x")
try:
with stream:
stream.write(existing + sep + "\n".join(missing) + "\n")
if mode is not None:
temp.chmod(mode)
temp.replace(exclude)
finally:
temp.unlink(missing_ok=True)
while True:
fd = os.open(exclude, os.O_RDWR | os.O_CREAT | os.O_APPEND | os.O_NOFOLLOW, 0o666)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Replacing the exclude path with a symlink or directory during the loop raises a raw OSError

exclude is resolved and checked once, before the loop. If the path becomes a symlink before os.open runs, O_NOFOLLOW raises OSError(ELOOP); if it becomes a directory, os.open raises IsADirectoryError. Either way the caller gets a raw OSError instead of the WorktreeError the start command reports cleanly. Both are unlikely during a write, but wrapping os.open to turn ELOOP/EISDIR into WorktreeError("Git exclude is outside its Git directory") would keep error handling consistent with the containment check just above.

with os.fdopen(fd, "rb") as stream:
fcntl.flock(fd, fcntl.LOCK_EX)
lines = set(stream.read().splitlines())
missing = [entry for entry in EXCLUDES if entry not in lines]
if missing:
# An editor can append an unterminated line before this write.
rules = b"\n" + b"\n".join(missing) + b"\n"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Separator newline is added even when the file already ends with one

rules always starts with b"\n". Most exclude files end with a newline, including Git's default template, so start inserts an empty line before the generated rules, and does it again on every replace-retry pass. Git ignores blank lines in exclude files, so nothing breaks, but the file gets messier each time. The safe gap is narrow: an editor can only append between stream.read() and os.write, and that window is also why the prefix is unconditional. Smallest fix: keep the bytes from stream.read() as data and add the leading newline only when data is non-empty and does not end with b"\n". This leaves a small chance of a joined line if an unterminated append lands in that window. Or keep the current behaviour and say in the comment that the blank line is intentional.

if os.write(fd, rules) != len(rules):
raise WorktreeError(f"incomplete write to Git exclude: {exclude}")
with suppress(FileNotFoundError):
if os.path.samestat(os.fstat(fd), exclude.lstat()):
return


def start(repo_root: Path, slug: str, base_branch: str) -> Path:
Expand Down
27 changes: 21 additions & 6 deletions tests/test_worktree.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,21 +141,36 @@ def interrupt_after_add(cwd, *args, **kwargs):
assert task.read_text().endswith("(filled by `loopzero review`)\n")


@pytest.mark.parametrize("redirect", [None, "file", "directory"])
def test_start_excludes_worktrees_and_task_dir(repo: Path, redirect: str | None) -> None:
@pytest.mark.parametrize("case", ["regular", "file", "directory", "append", "replace"])
def test_start_excludes_worktrees_and_task_dir(repo: Path, monkeypatch, case: str) -> None:
exclude = repo / ".git" / "info" / "exclude"
exclude.write_text("*.log") # no trailing newline on purpose
if redirect:
link = exclude if redirect == "file" else exclude.parent
if case in ("file", "directory"):
link = exclude if case == "file" else exclude.parent
link.symlink_to(link.rename(repo.parent / "outside"))
with pytest.raises(worktree.WorktreeError, match="outside its Git directory"):
worktree.start(repo, "t1", "main")
assert exclude.read_text() == "*.log" and not (repo / ".worktrees").exists()
return
old_inode = exclude.stat().st_ino
write = worktree.os.write
replacement, concurrent = case == "replace", case in ("append", "replace")

def interleave(fd, rules):
if concurrent and rules.endswith(b".loopzero/\n"):
edit = exclude.with_suffix(".edited") if replacement else exclude
with edit.open("w" if replacement else "a") as stream:
stream.write("*.log\nlocal.env" if replacement else "\nlocal.env")
if replacement:
edit.replace(exclude)
monkeypatch.setattr(worktree.os, "write", write)
return write(fd, rules)

monkeypatch.setattr(worktree.os, "write", interleave)
wt = worktree.start(repo, "t1", "main")
assert exclude.stat().st_ino != old_inode
assert exclude.read_text().splitlines() == ["*.log", ".worktrees/", ".loopzero/"]
assert (exclude.stat().st_ino != old_inode) == replacement
expected = ["*.log", "local.env"] if concurrent else ["*.log"]
assert exclude.read_text().splitlines() == [*expected, ".worktrees/", ".loopzero/"]
assert not worktree.is_dirty(wt), "fresh worktree with task.md is clean"
assert git(repo, "status", "--porcelain") == ""
installed = exclude.stat()
Expand Down
Loading