diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index cb219532..6594cc47 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -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")) push = ["push", "-u", "origin"] if pr is not None: known = config_mod.run_git(wt, "cat-file", "-e", f"{pr.head_sha}^{{commit}}") @@ -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: @@ -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) @@ -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) @@ -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 @@ -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: diff --git a/src/loopzero/github.py b/src/loopzero/github.py index 80d1b365..503565b6 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -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 @@ -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")) 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}") diff --git a/src/loopzero/worktree.py b/src/loopzero/worktree.py index 3164a27a..f71e1ded 100644 --- a/src/loopzero/worktree.py +++ b/src/loopzero/worktree.py @@ -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) @@ -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 @@ -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: @@ -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") @@ -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}") diff --git a/tests/test_cli.py b/tests/test_cli.py index f2654626..e27e7b48 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -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) @@ -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",)) +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: diff --git a/tests/test_github.py b/tests/test_github.py index 13690a02..79a5044a 100644 --- a/tests/test_github.py +++ b/tests/test_github.py @@ -4,6 +4,7 @@ import hashlib import json +import subprocess import sys from dataclasses import replace from pathlib import Path @@ -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}") @@ -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()