diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 3ac7a1c5..f5ddbbf9 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -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)] + 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)") @@ -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: @@ -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: diff --git a/src/loopzero/github.py b/src/loopzero/github.py index 7a4d8a85..fb224ef0 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -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 @@ -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}") diff --git a/src/loopzero/worktree.py b/src/loopzero/worktree.py index 8916bc2a..4b95e243 100644 --- a/src/loopzero/worktree.py +++ b/src/loopzero/worktree.py @@ -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) @@ -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 @@ -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: @@ -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") @@ -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}") diff --git a/tests/test_cli.py b/tests/test_cli.py index e790e384..eb1ee3dd 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -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) @@ -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") diff --git a/tests/test_github.py b/tests/test_github.py index d92af20d..7fc96a74 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 @@ -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() diff --git a/tests/test_worktree.py b/tests/test_worktree.py index 13db9bb1..0313aa4d 100644 --- a/tests/test_worktree.py +++ b/tests/test_worktree.py @@ -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"])