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
53 changes: 46 additions & 7 deletions scripts/local_review.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@
"""

import argparse
import errno
import hashlib
import json
import os
Expand Down Expand Up @@ -165,6 +166,18 @@ def silence(stream: object) -> None:
pass


def closed_reader(e: BaseException) -> bool:
"""Whether a write failed because the reader at the other end of a pipe went away.

POSIX reports that as EPIPE, which Python raises as BrokenPipeError. Windows reports the same
event as EINVAL on the write, a plain OSError, so testing for the subclass alone misses it
there and the interpreter's own shutdown flush then exits 120.
"""
if isinstance(e, BrokenPipeError):
return True
return os.name == "nt" and isinstance(e, OSError) and e.errno == errno.EINVAL


def emit(text: str, stream: object = None) -> None:
"""Write a line, tolerating a reader that closed the pipe before it arrived.

Expand All @@ -183,9 +196,10 @@ def emit(text: str, stream: object = None) -> None:
# The guards below are what cover a stand-in that is not writable.
print(text, file=target) # type: ignore[arg-type]
target.flush() # type: ignore[union-attr]
except BrokenPipeError:
silence(target)
except (OSError, ValueError):
except OSError as e:
if closed_reader(e):
silence(target)
except ValueError:
pass


Expand Down Expand Up @@ -507,7 +521,25 @@ def worktree_states(root: Path) -> dict[str, set[str]]:
finally:
Path(staging).unlink(missing_ok=True)
Path(staging + ".lock").unlink(missing_ok=True)
shutil.rmtree(objects, ignore_errors=True)
shutil.rmtree(objects, onexc=unlink_read_only)


def unlink_read_only(func: object, path: str, exc: BaseException) -> None:
"""An rmtree error handler that removes a read-only file, and swallows anything else.

git writes every loose object read-only. POSIX unlinks such a file anyway, since that needs
write access to the directory rather than to the file, but Windows refuses it. The throwaway
object directory then outlived the read, holding the staged content of every untracked file.
Any other failure is still swallowed, since this runs in a finally block that must not
replace the read's own result.
"""
if func is not os.unlink or not isinstance(exc, PermissionError):
return
try:
os.chmod(path, stat.S_IWRITE)
os.unlink(path)
except OSError:
pass


def state_mark(index: set[str], work: set[str]) -> str:
Expand Down Expand Up @@ -1143,7 +1175,9 @@ def main(argv: list[str] | None = None) -> int:
return EXIT_CANNOT_RUN
# A reader that closes early, `| head -1` being the ordinary case, otherwise raises here.
# It then raises again during the interpreter's own shutdown flush, which exits 120, outside the contract.
except BrokenPipeError:
except OSError as e:
if not closed_reader(e):
return crashed(e)
# A backstop only, since `emit` absorbs a closed reader at the point of writing.
# Reaching here means the failure came from somewhere that does not report through it.
# Whatever verdict was reached is still the honest answer.
Expand All @@ -1154,8 +1188,13 @@ def main(argv: list[str] | None = None) -> int:
# A crash is the check not having run, so it reports the boundary code.
# Falling through to the interpreter's own exit 1 would read as the not-covered verdict.
except Exception as e: # noqa: BLE001
emit(f"local_review: unexpected failure ({type(e).__name__}: {e})", sys.stderr)
return EXIT_CANNOT_RUN
return crashed(e)


def crashed(e: Exception) -> int:
"""Report an unexpected failure and return the boundary code, since the check did not run."""
emit(f"local_review: unexpected failure ({type(e).__name__}: {e})", sys.stderr)
return EXIT_CANNOT_RUN


if __name__ == "__main__":
Expand Down
13 changes: 11 additions & 2 deletions tests/test_local_review.py
Original file line number Diff line number Diff line change
Expand Up @@ -608,6 +608,7 @@ def test_a_ref_naming_an_absent_object_refuses(self) -> None:
blob = run(self.tmp, "hash-object", "-w", str(content)).strip()
run(self.tmp, "update-ref", "refs/remotes/upstream/main", blob)
loose = local_review.objects_dir(self.tmp) / blob[:2] / blob[2:]
loose.chmod(0o644)
loose.unlink()
self.shadow_with_a_local_branch()
with self.assertRaisesRegex(local_review.CannotRun, "exists but does not resolve"):
Expand Down Expand Up @@ -987,8 +988,11 @@ def run_piped(self, args: list[str], shell: str) -> int:
Driven through a shell rather than in process, because the failure being tested is a
genuine EPIPE on a descriptor, and the exit code being tested includes the one the
interpreter produces during its own shutdown flush, which no in-process case can reach.
The suite's own interpreter is named rather than a bare `python3`, which the shell could
resolve to a different one.
"""
script = f"python3 {shlex.quote(SCRIPT.as_posix())} {' '.join(args)} {shell}"
python = shlex.quote(Path(sys.executable).as_posix())
script = f"{python} {shlex.quote(SCRIPT.as_posix())} {' '.join(args)} {shell}"
proc = subprocess.run(
[bash_or_skip(), "-c", f"{script}; exit ${{PIPESTATUS[0]}}"],
cwd=str(self.tmp),
Expand Down Expand Up @@ -1231,13 +1235,18 @@ def fake_cli(
) -> None:
bin_dir = self.outside / "fakebin"
bin_dir.mkdir(exist_ok=True)
script = bin_dir / "coderabbit"
body = "#!/usr/bin/env python3\nimport sys\n"
if argv_log is not None:
body += f"open({str(argv_log)!r}, 'w').write(chr(10).join(sys.argv[1:]))\n"
if also:
body += also + "\n"
body += f"sys.stdout.write({stdout!r})\nsys.exit({code})\n"
if os.name == "nt":
script = bin_dir / "coderabbit.py"
wrapper = f'@"{sys.executable}" "{script}" %*\r\n@exit /b %ERRORLEVEL%\r\n'
(bin_dir / "coderabbit.cmd").write_text(wrapper, encoding="utf-8", newline="")
else:
script = bin_dir / "coderabbit"
script.write_text(body, encoding="utf-8")
script.chmod(0o755)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
prev = os.environ.get("PATH", "")
Expand Down
Loading