Skip to content
Closed
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
15 changes: 7 additions & 8 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,8 @@ def _require_push_target(wt: Path, repo: str) -> None:


def _git_push(wt: Path, args: list[str], *, force_lease: bool) -> None:
done = _proc.run(["git", *args], cwd=wt, env_allowlist=worktree.GIT_ENV,
extra_env={"LC_ALL": "C"}, timeout=PUSH_TIMEOUT)
argv = ["git", *(os.fsdecode(arg.encode("utf-8", "surrogateescape")) for arg in args)]

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Reviewer location src/loopzero/cli.py:699 is not in the diff; anchored here.

important: Force-lease reflog lookup still passes the UTF-8 branch view to git without converting it to native form

worktree.branch(wt) now returns the UTF-8 view of the branch name (os.fsencode(name).decode("utf-8", "surrogateescape")). This delta converts that view back to the filesystem form in _git_push, _delete_tracking_ref and github.delete_remote_branch. It does not convert _git(wt, "reflog", "show", "--format=%H", f"refs/heads/{branch}") on the force-lease path of cmd_pr, so the plain str goes straight to Popen, which encodes it with the filesystem encoding.

What goes wrong:

  • Under ASCII, a branch such as lz/Łódź raises UnicodeEncodeError.
  • Under ISO-8859-2, Ł is encoded as 0xA3 instead of UTF-8 C5 81. Git reads a different ref, the reflog lookup fails or comes back empty, and loopzero pr refuses a legitimate force-with-lease update with an error saying the PR head is absent from the branch history.

The acceptance criterion says Unicode branches must survive legacy locales, and this path breaks it.

Smallest fix: build the ref with the same conversion used elsewhere. Better, add one helper (for example worktree.native_ref(text)) and use it at every call site: here, in _git_push, _delete_tracking_ref, delete_remote_branch, and for the inverse in branch() / _lock_verified_ref. The four copies of the conversion in this diff are what let this call be missed.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Reviewer location tests/test_worktree.py:45 is not in the diff; anchored here.

important: The merge resolution removed every legacy-locale test, so the new conversions are never exercised

Resolving the merge with origin/main dropped these tests:

  • test_branch_preserves_unicode_whitespace (it forced an ASCII _text_encoding)
  • the subprocess._text_encoding ASCII monkeypatch in test_status_full
  • the subprocess-based test_pr_title_prefers_human_heading, which ran with LC_ALL=C and -X utf8=0

The tests that remain (test_branch_reads_valid_names..., test_cleanup_removes_worktree_and_branch with zażółć, test_pr_pushes_and_creates_draft with lz/zażółć , and test_status_full with Łódź) all run with a UTF-8 filesystem encoding. Under that encoding, os.fsencode(x).decode("utf-8", "surrogateescape") and os.fsdecode(x.encode("utf-8", "surrogateescape")) return their input unchanged, so branch(native=...), _git_push, _delete_tracking_ref, delete_remote_branch, _lock_verified_ref and the status backslashreplace path could all be wrong and every test would still pass.

The retained test_pr_title_prefers_human_heading monkeypatches Path.read_text, but task_text now reads through read_local_state/os.fdopen, so that test also checks nothing about the locale.

The acceptance criteria call for status and branch lookup to work under ASCII and ISO-8859-2, so they are no longer verified.

Smallest fix: restore at least one subprocess-based test that runs status (or branch and the push/cleanup ref construction) with LC_ALL=C or an ISO-8859-2 locale, PYTHONCOERCECLOCALE=0 and -X utf8=0, extending an existing test so the net line change stays at zero. The removed _pr_title subprocess form is a good template.

done = _proc.run(argv, cwd=wt, env_allowlist=worktree.GIT_ENV, extra_env={"LC_ALL": "C"}, timeout=PUSH_TIMEOUT)
if done.exit_code != 0:
detail = _proc.tail(done.stderr)[-2000:]
if force_lease and any(line.startswith("!\t") and line.endswith("\t[rejected] (stale info)")
Expand Down Expand Up @@ -1816,10 +1816,10 @@ def _cleanup_remote_refs(wt: Path, config: Config, branch: str, expected_head: s
def _delete_tracking_ref(wt: Path, branch: str, expected_head: str) -> None:
if not branch.startswith("lz/") or branch.count("/") != 1:
return
ref = f"refs/remotes/origin/{branch}"
ref = os.fsdecode(f"refs/remotes/origin/{branch}".encode("utf-8", "surrogateescape"))
try:
_repo_root(wt)
current = _git(wt, "for-each-ref", "--format=%(objectname) %(refname) %(symref)", ref)
current = _git(wt, "for-each-ref", "--format=%(objectname) %(refname) %(symref)", ref, paths=True).rstrip(" ")
if current == f"{expected_head} {ref}":
_git(wt, "update-ref", "--no-deref", "-d", ref, expected_head)
except (CliError, OSError, _proc.ProcTimeout) as exc:
Expand Down Expand Up @@ -1862,10 +1862,9 @@ def cmd_status(args: argparse.Namespace) -> int:
wt = _toplevel()
config = _load_config(args, wt, pin_checks=True)
branch, head = worktree.branch(wt), worktree.head(wt)
print(f"worktree: {wt}")
print(f"branch: {branch}")
print(f"head: {head}")
print(f"base: {config.base_branch}")
encoding = getattr(sys.stdout, "encoding", None) or "utf-8"
identity = f"worktree: {wt}\nbranch: {branch}\nhead: {head}\nbase: {config.base_branch}"
print(identity.encode(encoding, "backslashreplace").decode(encoding))
print(f"dirty: {'yes' if worktree.is_dirty(wt) else 'no'}")
pr = github.pr_for_branch(config.repo, branch)
if pr is None:
Expand Down
4 changes: 2 additions & 2 deletions src/loopzero/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -371,7 +371,7 @@ def _gh(*args: str, cwd: Path | None = None, timeout: float = 120,
try:
done = run(list(argv), cwd=cwd, env_allowlist=GH_ENV,
extra_env={"GH_TOKEN": selected} if selected else None,
timeout=_read_timeout(timeout, scoped=read_only))
timeout=_read_timeout(timeout, scoped=read_only), encoding="utf-8")
except ToolMissing as exc:
raise GhMissing(argv, str(exc), token=selected,
guidance=f"\nInstall GitHub CLI, then {GH_AUTH_REMEDY}") from exc
Expand Down Expand Up @@ -1450,7 +1450,7 @@ def delete_remote_branch(repo: str, branch: str, expected_head: str) -> bool:
current = _remote_branch_head(endpoint)
if current != expected_head:
return current is None
ref = f"refs/heads/{branch}"
ref = os.fsdecode(f"refs/heads/{branch}".encode("utf-8", "surrogateescape"))
argv = ("git", "-c", "credential.helper=!gh auth git-credential",
"push", f"--force-with-lease={ref}:{expected_head}",
f"https://github.com/{repo}.git", f":{ref}")
Expand Down
19 changes: 9 additions & 10 deletions src/loopzero/worktree.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,8 @@ def __init__(self, command: tuple[str, ...], tail: str) -> None:
super().__init__(f"{' '.join(command)} failed: {tail.strip()[-400:]}")


def _git(
cwd: Path, *args: str, timeout: float = 120,
preserve_whitespace: bool = False, preserve_newlines: bool = False,
) -> str:
def _git(cwd: Path, *args: str, timeout: float = 120,
preserve_whitespace: bool = False, preserve_newlines: bool = False) -> str:
argv = ("git", *args)
if preserve_whitespace:
done = run_git_paths(argv, cwd=cwd, env_allowlist=GIT_ENV, timeout=timeout)
Expand Down Expand Up @@ -258,7 +256,7 @@ def _resumable_head(repo_root: Path, wt: Path, expected_branch: str) -> str | No
or not (wt / ".git").is_file()):
return None
common = _git(repo_root, *_ABSOLUTE_COMMON_DIR, preserve_whitespace=True)
if _git(wt, *_ABSOLUTE_COMMON_DIR, preserve_whitespace=True) != common or branch(wt) != expected_branch:
if _git(wt, *_ABSOLUTE_COMMON_DIR, preserve_whitespace=True) != common or branch(wt, native=True) != expected_branch:
return None
current_head = head(wt)
return current_head if fields[1] == f"HEAD {current_head}" and not is_dirty(wt) else None
Expand Down Expand Up @@ -288,11 +286,11 @@ def is_linked_checkout(wt: Path) -> bool:
return git_dir != common_dir


def branch(wt: Path) -> str:
def branch(wt: Path, *, native: bool = False) -> str:
name = _git(Path(wt), "branch", "--show-current", preserve_whitespace=True)
if not name:
raise WorktreeError("HEAD is detached. Switch to a branch and retry.")
return name
return name if native else os.fsencode(name).decode("utf-8", "surrogateescape")


def task_text(wt: Path) -> str:
Expand Down Expand Up @@ -339,7 +337,8 @@ def _lock_verified_ref(wt: Path, ref: str, expected_head: str) -> Iterator[None]
) as transaction:
assert transaction.stdin is not None and transaction.stdout is not None
try:
transaction.stdin.write(f"option no-deref\nverify {ref} {expected_head}\nprepare\n")
wire_ref = os.fsencode(ref).decode("utf-8", "surrogateescape")
transaction.stdin.write(f"option no-deref\nverify {wire_ref} {expected_head}\nprepare\n")
transaction.stdin.flush()
if not select([transaction.stdout], [], [], 30)[0]:
raise GitError(argv, "timed out verifying the merged branch")
Expand Down Expand Up @@ -375,11 +374,11 @@ def cleanup(wt: Path, expected_head: str) -> None:
raise WorktreeError(f"no such worktree: {wt}")
if head(wt) != expected_head:
raise WorktreeError("local HEAD differs from merged PR head")
name = branch(wt)
name = branch(wt, native=True)
gd = Path(_git(wt, *_ABSOLUTE_COMMON_DIR, preserve_whitespace=True))
ref = f"refs/heads/{name}"
with _lock_verified_ref(wt, ref, expected_head):
if branch(wt) != name:
if branch(wt, native=True) != name:
raise WorktreeError("local branch changed during merge cleanup")
if is_dirty(wt):
raise WorktreeError(f"worktree is dirty, refusing to remove: {wt}")
Expand Down
10 changes: 5 additions & 5 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,8 +186,8 @@ def run(argv, *, cwd, env_allowlist, extra_env=None, **kwargs):


@pytest.fixture
def wt(repo: Path, git_seed: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
path = cli.worktree.worktree_dir(repo, "t1")
def wt(repo: Path, git_seed: Path, monkeypatch: pytest.MonkeyPatch, request) -> Path:
path = cli.worktree.worktree_dir(repo, getattr(request, "param", "t1"))
git(repo, "worktree", "add", "-q", str(path), "lz/t1")
shutil.copytree(git_seed / ".loopzero", cli.worktree.task_file(path).parent)
monkeypatch.chdir(path)
Expand Down Expand Up @@ -3705,11 +3705,11 @@ def test_status_explains_detached_head(wt: Path, capsys) -> None:
assert err == "loopzero status: HEAD is detached. Switch to a branch and retry.\n"


def test_status_full(wt: Path, gh: FakeGh, capsys, git_calls) -> None:
head = head_of(wt)
@pytest.mark.parametrize("wt", ["Łódź"], indirect=True)
def test_status_full(wt: Path, gh: FakeGh, capsys, git_calls, head) -> None:
gh.respond_pr_list([])
out, _ = expect_cli(capsys, 0, "status")
assert "branch: lz/t1" in out and f"head: {head}" in out and "dirty: no" in out
assert f"worktree: {wt}" in out and "branch: lz/t1" in out and f"head: {head}" in out and "dirty: no" in out
assert "pr: none (commit changes and pass `loopzero check` before `loopzero pr`)" in out
arm_approved_pr_with_check_result(gh, head, wt, "pending")
(wt / "scratch").write_text("x")
Expand Down
14 changes: 7 additions & 7 deletions tests/test_github.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import hashlib
import json
import subprocess
import sys
from dataclasses import replace
from pathlib import Path
Expand Down Expand Up @@ -716,13 +717,12 @@ def test_pr_for_branch_missing_key_is_gh_error(gh: FakeGh) -> None:
github.pr_for_branch(REPO, "lz/x")


def test_api_get_and_login_helpers(gh: FakeGh) -> None:
gh.respond("api graphql viewer", {"data": {"viewer": {"login": "bot-user"}}})
gh.respond("api repos/acme/widgets", {"default_branch": "main"})
assert github.api_get("repos/acme/widgets") == {"default_branch": "main"}
assert gh.argv(0) == ["api", "repos/acme/widgets", "--include"]
assert github.login() == "bot-user"
gh.respond("api graphql viewer", {"data": {"viewer": {}}})
def test_api_get_and_login_helpers(gh: FakeGh, monkeypatch) -> None:
monkeypatch.setattr(subprocess, "_text_encoding", lambda: "ascii")
gh.respond("api graphql viewer", '{"data":{"viewer":{"login":"Łódź"}}}', {"data": {"viewer": {}}})
gh.respond("api repos/acme/widgets", '{"default_branch":"Łódź"}')
assert (github.api_get("repos/acme/widgets"), gh.argv(0)) == ({"default_branch": "Łódź"}, ["api", "repos/acme/widgets", "--include"])
assert github.login() == "Łódź"
with pytest.raises(github.GhError, match="no login"):
github.login()

Expand Down
4 changes: 2 additions & 2 deletions tests/test_worktree.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,12 +248,12 @@ def test_task_helpers_errors(repo: Path) -> None:


def test_cleanup_removes_worktree_and_branch(repo: Path, monkeypatch) -> None:
wt, calls, real = worktree.start(repo, "done", "main"), [], worktree._git
wt, calls, real = worktree.start(repo, "zażółć", "main"), [], worktree._git
monkeypatch.setattr(worktree, "_git", lambda d, *a, **k: calls.append((d, a)) or real(d, *a, **k))
(wt / f".loopzero/reviewer-output-{worktree.head(wt)[:12]}-primary.json").write_text("{}")
worktree.cleanup(wt, worktree.head(wt)) # #439: no cleanup git runs in (or -C) the primary checkout
assert calls and all(Path(d).resolve() != repo.resolve() and "-C" not in a for d, a in calls)
assert not wt.exists() and not git(repo, "branch", "--list", "lz/done") and "done" not in git(repo, "worktree", "list")
assert not wt.exists() and not git(repo, "branch", "--list", "lz/zażółć") and "zażółć" not in git(repo, "worktree", "list")


@pytest.mark.parametrize("file", ["scratch.txt", "local.env", ".loopzero/user-notes.md"])
Expand Down
Loading