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
44 changes: 23 additions & 21 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -707,6 +707,7 @@ def cmd_pr(args: argparse.Namespace) -> int:
existing = _sync_task_narrative(wt, pr.body or "") if pr is not None else None
body = _pr_body(wt, head, config, existing)
force_lease = False
git_branch = os.fsdecode(branch.encode("utf-8", "surrogateescape"))

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: Unicode↔Git-native name conversion is repeated by hand in five places

The same idiom is written out at five sites:

  • os.fsdecode(x.encode("utf-8", "surrogateescape")) at cli.py:712, cli.py:1853 and github.py:1479.
  • The reverse, os.fsencode(x).decode("utf-8", "surrogateescape"), at worktree.py:308 and worktree.py:355.

branch() now returns either form depending on the native flag, so every new Git call that takes a task-branch name must remember to convert it. If one forgets, it crashes with UnicodeEncodeError under a legacy locale.

The same gap already exists for the configured base branch. The TOML-sourced base_branch reaches Git argv unconverted at config.py:75, 106 and 109, worktree.py:231 and cli.py:1277. These are outside this task's acceptance, but they belong to the same class.

Suggested fix: add a pair of helpers in worktree, for example git_name(unicode) -> native and unicode_name(native) -> unicode, and use them at all of these sites. That keeps the conversion in one place.

push = ["push", "-u", "origin"]
if pr is not None:
known = config_mod.run_git(wt, "cat-file", "-e", f"{pr.head_sha}^{{commit}}")
Expand All @@ -716,13 +717,13 @@ def cmd_pr(args: argparse.Namespace) -> int:
)
force_lease = pr.head_sha != head and not _is_ancestor(wt, pr.head_sha, head)
if force_lease:
previous_heads = _git(wt, "reflog", "show", "--format=%H", f"refs/heads/{branch}").splitlines()
previous_heads = _git(wt, "reflog", "show", "--format=%H", f"refs/heads/{git_branch}").splitlines()
if not any(_is_ancestor(wt, pr.head_sha, previous) for previous in previous_heads):
raise CliError(
f"PR head {pr.head_sha[:12]} is absent from this task branch's history; integrate it first"
)
push.extend(("--porcelain", f"--force-with-lease={branch}:{pr.head_sha}"))
push.append(branch)
push.extend(("--porcelain", f"--force-with-lease={git_branch}:{pr.head_sha}"))
push.append(git_branch)
_require_push_target(wt, config.repo)
_git_push(wt, push, force_lease=force_lease)
if pr is not None:
Expand Down Expand Up @@ -1847,18 +1848,22 @@ 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:
print(f"warning: merged but tracking ref cleanup failed for {ref}: {exc}", file=sys.stderr)


def cmd_resolve(args: argparse.Namespace) -> int:
def _print_display(text: str) -> None:
encoding = getattr(sys.stdout, "encoding", None) or "utf-8"
print(text.encode(encoding, "backslashreplace").decode(encoding))


def cmd_resolve(args: argparse.Namespace) -> int:
wt, config = _context(args, pin_checks=True) # publishers come from the base, not the PR
branch = worktree.branch(wt)
pr = _require_pr(config, branch)
Expand All @@ -1867,10 +1872,10 @@ def cmd_resolve(args: argparse.Namespace) -> int:
publishers = config.review_publishers or (github.login(),)
if not args.finding:
for marker_id, _thread, f in github.open_findings(config.repo, pr.number, publishers):
print(f"{marker_id} {f.severity} {f.path or '-'}:{f.line or '-'} {f.title}".encode(encoding, "backslashreplace").decode(encoding))
_print_display(f"{marker_id} {f.severity} {f.path or '-'}:{f.line or '-'} {f.title}")
return 0
finding = github.resolve_finding(config.repo, pr.number, args.finding, args.reply, publishers)
print(f"resolved {args.finding}: {finding.title}".encode(encoding, "backslashreplace").decode(encoding))
_print_display(f"resolved {args.finding}: {finding.title}")
try:
with github.api_error_diagnostics():
remaining = github.open_blocking_findings(config.repo, pr.number, None, publishers)
Expand All @@ -1894,27 +1899,24 @@ 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}")
print(f"dirty: {'yes' if worktree.is_dirty(wt) else 'no'}")
_print_display(f"worktree: {wt}\nbranch: {branch}\nhead: {head}\nbase: {config.base_branch}")
_print_display(f"dirty: {'yes' if worktree.is_dirty(wt) else 'no'}")
pr = github.pr_for_branch(config.repo, branch)
if pr is None:
print("pr: none (commit changes and pass `loopzero check` before `loopzero pr`)")
_print_display("pr: none (commit changes and pass `loopzero check` before `loopzero pr`)")
return 0
print(f"pr: #{pr.number} {pr.url} ({'draft' if pr.is_draft else 'ready'}, {pr.state})")
_print_display(f"pr: #{pr.number} {pr.url} ({'draft' if pr.is_draft else 'ready'}, {pr.state})")
reviews = _pr_reviews(config.repo, pr.number)
markers = _pr_markers(reviews, head, config.review_publishers, repo=config.repo, number=pr.number)
if markers:
latest = markers[-1]
print(f"review: {latest.kind} on {latest.head[:12]} ({latest.state.lower() or 'posted'})")
_print_display(f"review: {latest.kind} on {latest.head[:12]} ({latest.state.lower() or 'posted'})")
else:
print("review: none on this PR")
_print_display("review: none on this PR")
readiness = _readiness(wt, config, pr, head, reviews, diagnostics=True)
print(f"ready: {'yes' if readiness.ready else 'no'}")
_print_display(f"ready: {'yes' if readiness.ready else 'no'}")
for reason in readiness.reasons:
print(f" - {reason}")
_print_display(f" - {reason}")
if config.merge_strategy == "mergify" and pr.state == "OPEN" and pr.head_sha == head:
_print_mergify_status(config, pr, readiness)
return 0
Expand All @@ -1932,9 +1934,9 @@ def _print_mergify_status(config: Config, pr: github.PR, readiness: github.Readi
label = "ejected"
elif requested or (readiness.ready and report):
label = "waiting for admission"
print(f"mergify: {label} ({queue})")
_print_display(f"mergify: {label} ({queue})")
if label == "waiting for admission" and report:
print(f" Mergify report: {report}")
_print_display(f" Mergify report: {report}")


def main(argv: list[str] | None = None) -> int:
Expand Down
4 changes: 2 additions & 2 deletions src/loopzero/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -390,7 +390,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 @@ -1516,7 +1516,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"))

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: No test runs delete_remote_branch under a legacy locale

The legacy-locale test calls cli._delete_tracking_ref and worktree.cleanup directly. It never goes through cmd_merge → _cleanup_remote_refs → github.delete_remote_branch, so the native-ref change at github.py:1479 has no test. If that conversion regresses, git push :refs/heads/lz/Łódź fails with UnicodeEncodeError at argv encoding. _cleanup_remote_refs only catches GhError and ProcTimeout, so the error escapes and aborts merge after the PR has already merged.

Add a narrow check for this path. One option: monkeypatch github._remote_branch_head and assert the argv bytes inside the legacy-locale subprocess.

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 @@ -59,10 +59,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 @@ -273,7 +271,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 @@ -303,11 +301,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 @@ -354,7 +352,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 @@ -390,11 +389,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
45 changes: 43 additions & 2 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,8 +189,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 @@ -1353,6 +1353,47 @@ def test_pr_uses_lease_for_rewritten_open_pr(wt, repo, gh, fake_tool, tmp_path,
assert git(origin, "rev-parse", "refs/heads/lz/t1").strip() == (old if case == "hook-fails" else head)


@pytest.mark.parametrize("wt", ["Łódź"], indirect=True)
def test_legacy_locale_status_reflog_push_and_cleanup(wt, repo, gh, monkeypatch, rewritten_branch):
branch, head = "lz/Łódź", head_of(wt)
ref, origin = f"refs/heads/{branch}", repo.parent / "origin.git"
git(wt, "branch", "-m", branch)
git(origin, "update-ref", ref, rewritten_branch)
assert git(wt, "remote", "get-url", "origin").strip() == str(origin)
monkeypatch.chdir(repo)

gh.respond(branch_history_key(branch=branch), [])
gh.respond_pr_list([pr_json(headRefOid=rewritten_branch)], branch=branch)
gh.respond(reviews_key(), [])
gh.respond(f"api repos/{REPO}/pulls/7 --method PATCH", {})
program = """
from pathlib import Path
from loopzero import cli, worktree

cli._readiness = lambda *_, **__: cli.github.Readiness(False, ("check \\u0141 is pending",))

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: Legacy-locale test stubs out _readiness, so the real readiness path never runs with a Unicode branch

The subprocess replaces cli._readiness with a lambda that returns a fixed reason. That proves _print_display escapes the reason text. It does not check that the real readiness evaluation (check runs, review markers and branch-history lookups for lz/Łódź) works under LC_ALL=C. If that evaluation decoded or encoded the branch wrongly, this test would still pass. A smaller fix: keep the real _readiness and add fake GitHub responses so it returns a pending or blocking reason that includes the Unicode branch or a finding title. If that costs too much fixture setup, add a comment saying the stub only covers display escaping.

assert cli.main(["status"]) == 0
# The fixture verifies and uses a local bare remote.
cli._require_push_target = lambda *_: None
assert cli.main(["pr"]) == 0
wt = Path.cwd()
head = worktree.head(wt)
cli._delete_tracking_ref(wt, worktree.branch(wt), head)
worktree.cleanup(wt, head)
"""
result = subprocess.run(
[sys.executable, "-X", "utf8=0", "-c", program], cwd=wt,
env={**os.environ, "LC_ALL": "C", "PYTHONCOERCECLOCALE": "0", "PYTHONIOENCODING": "ascii:strict"},
capture_output=True, encoding="ascii",
)
assert result.returncode == 0, result.stderr
escaped = branch.encode("ascii", "backslashreplace").decode("ascii")
assert f"branch: {escaped}" in result.stdout
assert r"check \u0141 is pending" in result.stdout
assert any(pr_list_key(branch).removeprefix("api ") in call["argv"] for call in gh.calls)
assert git(origin, "rev-parse", ref).strip() == head
assert not wt.exists() and not git(repo, "branch", "-a", "--list", f"*{branch}")


def test_pr_refuses_to_overwrite_a_pr_head_it_has_never_seen(
wt: Path, repo: Path, gh: FakeGh, capsys
) -> None:
Expand Down
18 changes: 9 additions & 9 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 All @@ -28,8 +29,8 @@ def pr_list_key(branch: str = "lz/t1", state: str = "open") -> str:
return (f"api repos/{REPO}/pulls?state={state}&head={head}"
"&sort=created&direction=desc&per_page=1")

def branch_history_key(page: int = 1) -> str:
head = quote(f"{REPO.split('/')[0]}:lz/t1", safe="")
def branch_history_key(page: int = 1, *, branch: str = "lz/t1") -> str:
head = quote(f"{REPO.split('/')[0]}:{branch}", safe="")
return (f"api repos/{REPO}/pulls?state=closed&head={head}"
f"&sort=created&direction=desc&per_page=100&page={page}")

Expand Down Expand Up @@ -692,13 +693,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
Loading