diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..76c17dcc --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +# Check out text files with LF on every OS, so the gate's byte comparisons +# and formatters see the same files as CI. +* text=auto eol=lf diff --git a/scripts/_uv.py b/scripts/_uv.py index 1eb82687..37e954f3 100644 --- a/scripts/_uv.py +++ b/scripts/_uv.py @@ -8,6 +8,7 @@ import shutil import subprocess import tarfile +import zipfile from pathlib import Path from urllib.request import urlopen @@ -18,6 +19,8 @@ "x86_64-apple-darwin": "20c47e4c1f630b8abaff8c291fa9b9aa300fef92c4fbff95adf198b55287cda7", "aarch64-unknown-linux-gnu": "71279f8d3c67241e807b9d8db872d1bf541579fb9f08b7d1eb1682196d1e57dc", "x86_64-unknown-linux-gnu": "c5221ff41b7892bfc223543883600125f6a47fe845093e0f5bdff4f359196d83", + "aarch64-pc-windows-msvc": "505d9e65e7692bac3ddf98c66754aa26c5050c409c184af30a881a0a72cc85e3", + "x86_64-pc-windows-msvc": "0cdc5b38fe5a8168ed6a25814f5ba43c21d313dd3187314fccb37b7cec46e021", } @@ -31,21 +34,43 @@ def matching(executable: Path) -> bool: return False +def release_target(system: str, machine: str) -> str: + # Windows reports AMD64 or ARM64; macOS reports arm64. + architecture = {"arm64": "aarch64", "aarch64": "aarch64", "x86_64": "x86_64", "amd64": "x86_64"} + systems = {"Darwin": "apple-darwin", "Linux": "unknown-linux-gnu", "Windows": "pc-windows-msvc"} + return f"{architecture.get(machine.lower())}-{systems.get(system)}" + + +def unpack(content: bytes, target: str) -> bytes: + """Return the uv executable from a verified release archive.""" + if target.endswith("-windows-msvc"): + # The Windows release is a zip with uv.exe at its root. + with zipfile.ZipFile(io.BytesIO(content)) as package: + return package.read("uv.exe") + with tarfile.open(fileobj=io.BytesIO(content), mode="r:gz") as package: + member = package.getmember(f"uv-{target}/uv") + if not member.isfile(): + raise SystemExit("The verified uv archive has no regular uv executable.") + source = package.extractfile(member) + if source is None: + raise SystemExit("The verified uv archive has no uv executable.") + with source: + return source.read() + + def executable(tools: Path) -> Path: installed = shutil.which("uv") if installed is not None and matching(Path(installed)): return Path(installed) - architecture = {"arm64": "aarch64", "aarch64": "aarch64", "x86_64": "x86_64"}.get( - platform.machine() - ) - system = {"Darwin": "apple-darwin", "Linux": "unknown-linux-gnu"}.get(platform.system()) - target = f"{architecture}-{system}" + target = release_target(platform.system(), platform.machine()) if target not in CHECKSUMS: raise SystemExit("Install uv 0.13.7 to run the gate on this bootstrap platform.") + windows = target.endswith("-windows-msvc") tools.mkdir(parents=True, exist_ok=True) - archive = tools / f"uv-{VERSION}-{target}.tar.gz" + suffix = ".zip" if windows else ".tar.gz" + archive = tools / f"uv-{VERSION}-{target}{suffix}" if not archive.exists(): - url = f"https://github.com/astral-sh/uv/releases/download/{VERSION}/uv-{target}.tar.gz" + url = f"https://github.com/astral-sh/uv/releases/download/{VERSION}/uv-{target}{suffix}" with urlopen(url, timeout=30) as response: content = response.read(64 * 1024 * 1024) if hashlib.sha256(content).hexdigest() != CHECKSUMS[target]: @@ -54,16 +79,8 @@ def executable(tools: Path) -> Path: content = archive.read_bytes() if hashlib.sha256(content).hexdigest() != CHECKSUMS[target]: raise SystemExit("The cached uv archive does not match the pinned official checksum.") - binary = tools / f"uv-{VERSION}-{target}" - with tarfile.open(fileobj=io.BytesIO(content), mode="r:gz") as package: - member = package.getmember(f"uv-{target}/uv") - if not member.isfile(): - raise SystemExit("The verified uv archive has no regular uv executable.") - source = package.extractfile(member) - if source is None: - raise SystemExit("The verified uv archive has no uv executable.") - with source: - binary.write_bytes(source.read()) + binary = tools / f"uv-{VERSION}-{target}{'.exe' if windows else ''}" + binary.write_bytes(unpack(content, target)) binary.chmod(0o755) if not matching(binary): raise SystemExit("The verified uv executable has an unexpected version.") diff --git a/scripts/contracts.py b/scripts/contracts.py index 6e6255a2..e7bd5925 100644 --- a/scripts/contracts.py +++ b/scripts/contracts.py @@ -13,7 +13,7 @@ def main() -> None: - document = json.loads((ROOT / "openapi.public.json").read_text()) + document = json.loads((ROOT / "openapi.public.json").read_text(encoding="utf-8")) declared = { operation["operationId"] for item in json_operations(document)["paths"].values() @@ -52,7 +52,7 @@ def main() -> None: raise SystemExit(f"{client.__name__} operations differ from the public contract.") prohibited = {"safe", "passed", "clean"} for path in (ROOT / "proofline").rglob("*.py"): - for node in ast.walk(ast.parse(path.read_text())): + for node in ast.walk(ast.parse(path.read_text(encoding="utf-8"))): identifier = None if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): identifier = node.name diff --git a/scripts/generate.py b/scripts/generate.py index a35a26b6..ac0ac605 100644 --- a/scripts/generate.py +++ b/scripts/generate.py @@ -85,7 +85,7 @@ def generate(destination: Path) -> None: raise SystemExit(f"Generation requires openapi-python-client=={VERSION}.") if importlib.metadata.version("ruff") != RUFF_VERSION: raise SystemExit(f"Generation requires ruff=={RUFF_VERSION}.") - document = json.loads(DOCUMENT.read_text()) + document = json.loads(DOCUMENT.read_text(encoding="utf-8")) # The 7.2 SDK accepts (checkpoint, due_at, result) positionally. The # generator emits optional constructor arguments in schema property order. checkpoint = document["components"]["schemas"]["DeployCoverageCheckpoint"] @@ -107,13 +107,14 @@ def generate(destination: Path) -> None: } with tempfile.TemporaryDirectory(prefix="proofline-json-contract-") as temporary: json_document = Path(temporary) / "openapi.json" - json_document.write_text(json.dumps(json_operations(document))) + json_document.write_text(json.dumps(json_operations(document)), encoding="utf-8") generate_json(destination, json_document) def check_version() -> None: - document = json.loads(DOCUMENT.read_text()) - version = tomllib.loads((ROOT / "pyproject.toml").read_text())["project"]["version"] + document = json.loads(DOCUMENT.read_text(encoding="utf-8")) + pyproject = (ROOT / "pyproject.toml").read_text(encoding="utf-8") + version = tomllib.loads(pyproject)["project"]["version"] package_version = tuple(map(int, version.split("."))) api_version = tuple(map(int, document["info"]["version"].split("."))) if package_version[:2] != api_version[:2] or package_version[2] < api_version[2]: @@ -162,8 +163,8 @@ def generate_json(destination: Path, document: Path) -> None: sync=custom["ProoflineClient"], asynchronous=custom["AsyncProoflineClient"], ) - (destination / "api/operations.py").write_text(facade) - body = json.loads(document.read_text())["paths"][ + (destination / "api/operations.py").write_text(facade, encoding="utf-8") + body = json.loads(document.read_text(encoding="utf-8"))["paths"][ "/api/v1/organizations/{org_id}/repositories/{repo_id}/pull-requests/{number}/review" ]["post"].get("requestBody") if body is not None: @@ -175,7 +176,7 @@ def generate_json(destination: Path, document: Path) -> None: ): raise SystemExit("request_review requires its optional named RunNowRequest JSON body.") endpoint = destination / "api" / "default" / "request_review.py" - source = endpoint.read_text() + source = endpoint.read_text(encoding="utf-8") header = ' headers["Content-Type"] = "application/json"\n' json_body = ( ' if not isinstance(body, Unset):\n _kwargs["json"] = body.to_dict()\n' @@ -188,7 +189,8 @@ def generate_json(destination: Path, document: Path) -> None: raise SystemExit("The pinned optional request_review body template has changed.") # The pinned generator sets this header even when its optional body is UNSET. endpoint.write_text( - source.replace(header, " if not isinstance(body, Unset):\n " + header) + source.replace(header, " if not isinstance(body, Unset):\n " + header), + encoding="utf-8", ) shutil.copyfile(ROOT / "templates" / "LICENSE.openapi-python-client", destination / "LICENSE") subprocess.run( @@ -207,12 +209,34 @@ def generate_json(destination: Path, document: Path) -> None: check=True, cwd=ROOT, ) - subprocess.run([sys.executable, "-m", "ruff", "format", str(destination)], check=True, cwd=ROOT) + format_python(destination) + + +def format_python(destination: Path) -> None: + # The generator writes CRLF on Windows; the committed files are LF on every OS. + subprocess.run( + [ + sys.executable, + "-m", + "ruff", + "format", + "--config", + "format.line-ending = 'lf'", + str(destination), + ], + check=True, + cwd=ROOT, + ) + + +def text(content: bytes) -> bytes: + # .gitattributes stores text with LF, so a CRLF working copy is the same file. + return content if b"\0" in content else content.replace(b"\r\n", b"\n") def files(directory: Path) -> dict[Path, bytes]: return { - path.relative_to(directory): path.read_bytes() + path.relative_to(directory): text(path.read_bytes()) for path in directory.rglob("*") if path.is_file() and "__pycache__" not in path.parts } diff --git a/tests/test_generate.py b/tests/test_generate.py new file mode 100644 index 00000000..801c4bfd --- /dev/null +++ b/tests/test_generate.py @@ -0,0 +1,54 @@ +"""The committed generated API is reproducible whatever the machine's text encoding.""" + +import importlib.util +import os +import subprocess +import sys +from pathlib import Path +from types import ModuleType + +ROOT = Path(__file__).resolve().parents[1] + + +def test_generation_does_not_depend_on_the_locale_encoding() -> None: + # Windows defaults to a legacy code page such as cp1252, and a C locale to ASCII. + # -X utf8=0 keeps Python from switching to UTF-8 on its own. + env = {name: value for name, value in os.environ.items() if name != "PYTHONUTF8"} + env.update({"LC_ALL": "C", "LANG": "C", "PYTHONCOERCECLOCALE": "0"}) + result = subprocess.run( + [sys.executable, "-X", "utf8=0", "scripts/generate.py", "--check"], + cwd=ROOT, + env=env, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + ) + assert result.returncode == 0, result.stderr + + +def load_generate() -> ModuleType: + spec = importlib.util.spec_from_file_location("generate", ROOT / "scripts/generate.py") + assert spec is not None and spec.loader is not None + generate = importlib.util.module_from_spec(spec) + spec.loader.exec_module(generate) + return generate + + +def test_check_treats_a_crlf_working_copy_as_unchanged(tmp_path: Path) -> None: + generate = load_generate() + for name, newline in (("lf", b"\n"), ("crlf", b"\r\n")): + (tmp_path / name / "models").mkdir(parents=True) + (tmp_path / name / "models" / "a.py").write_bytes(b"a = 1" + newline + b"b = 2" + newline) + assert generate.files(tmp_path / "lf") == generate.files(tmp_path / "crlf") + # A file with a NUL byte is binary and still compared byte for byte. + (tmp_path / "lf" / "data.bin").write_bytes(b"\0\n") + (tmp_path / "crlf" / "data.bin").write_bytes(b"\0\r\n") + assert generate.files(tmp_path / "lf") != generate.files(tmp_path / "crlf") + + +def test_generated_python_is_formatted_with_lf_line_endings(tmp_path: Path) -> None: + # Windows text writes produce CRLF; the formatting step must turn them into LF. + (tmp_path / "model.py").write_bytes(b"a = 1\r\nb = 2\r\n") + load_generate().format_python(tmp_path) + assert (tmp_path / "model.py").read_bytes() == b"a = 1\nb = 2\n" diff --git a/tests/test_uv.py b/tests/test_uv.py new file mode 100644 index 00000000..2588b456 --- /dev/null +++ b/tests/test_uv.py @@ -0,0 +1,137 @@ +"""The gate can bootstrap its pinned uv on Windows as well as macOS and Linux.""" + +import hashlib +import importlib.util +import io +import tarfile +import zipfile +from pathlib import Path + +import pytest + +SCRIPT = Path(__file__).resolve().parents[1] / "scripts/_uv.py" +spec = importlib.util.spec_from_file_location("_uv", SCRIPT) +assert spec is not None and spec.loader is not None +uv = importlib.util.module_from_spec(spec) +spec.loader.exec_module(uv) + + +@pytest.mark.parametrize( + ("system", "machine", "target"), + [ + ("Windows", "AMD64", "x86_64-pc-windows-msvc"), + ("Windows", "ARM64", "aarch64-pc-windows-msvc"), + ("Linux", "x86_64", "x86_64-unknown-linux-gnu"), + ("Darwin", "arm64", "aarch64-apple-darwin"), + ], +) +def test_supported_platforms_have_a_pinned_archive(system: str, machine: str, target: str) -> None: + assert uv.release_target(system, machine) == target + assert target in uv.CHECKSUMS + + +def test_windows_archive_yields_its_uv_executable() -> None: + archive = io.BytesIO() + with zipfile.ZipFile(archive, "w") as package: + package.writestr("uv.exe", b"uv") + package.writestr("uvx.exe", b"uvx") + assert uv.unpack(archive.getvalue(), "x86_64-pc-windows-msvc") == b"uv" + + +def windows_zip() -> bytes: + archive = io.BytesIO() + with zipfile.ZipFile(archive, "w") as package: + package.writestr("uv.exe", b"uv") + return archive.getvalue() + + +def fake_windows( + monkeypatch: pytest.MonkeyPatch, machine: str, content: bytes +) -> tuple[list[str], list[Path]]: + """Pretend to be Windows with no matching uv installed; serve `content` as the release. + + Returns the requested URLs and the executables whose version was checked. + """ + requested: list[str] = [] + checked: list[Path] = [] + + def download(url: str, timeout: int) -> io.BytesIO: + requested.append(url) + return io.BytesIO(content) + + monkeypatch.setattr(uv.shutil, "which", lambda name: None) + monkeypatch.setattr(uv.platform, "system", lambda: "Windows") + monkeypatch.setattr(uv.platform, "machine", lambda: machine) + monkeypatch.setattr(uv, "urlopen", download) + + def matching(executable: Path) -> bool: + checked.append(executable) + return True + + monkeypatch.setattr(uv, "matching", matching) + return requested, checked + + +@pytest.mark.parametrize( + ("machine", "target"), + [("AMD64", "x86_64-pc-windows-msvc"), ("ARM64", "aarch64-pc-windows-msvc")], +) +def test_windows_bootstrap_downloads_the_zip_and_saves_an_exe( + machine: str, target: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + content = windows_zip() + requested, checked = fake_windows(monkeypatch, machine, content) + monkeypatch.setitem(uv.CHECKSUMS, target, hashlib.sha256(content).hexdigest()) + binary = uv.executable(tmp_path) + assert requested == [ + f"https://github.com/astral-sh/uv/releases/download/{uv.VERSION}/uv-{target}.zip" + ] + assert binary == tmp_path / f"uv-{uv.VERSION}-{target}.exe" + assert binary.read_bytes() == b"uv" + assert checked == [binary] + + +def test_windows_bootstrap_refuses_an_unexpected_uv_version( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + content = windows_zip() + fake_windows(monkeypatch, "AMD64", content) + monkeypatch.setitem(uv.CHECKSUMS, "x86_64-pc-windows-msvc", hashlib.sha256(content).hexdigest()) + monkeypatch.setattr(uv, "matching", lambda executable: False) + with pytest.raises(SystemExit, match="unexpected version"): + uv.executable(tmp_path) + + +@pytest.mark.parametrize( + ("cached", "message"), + [(False, "release archive does not match"), (True, "cached uv archive does not match")], +) +def test_windows_zip_with_a_wrong_checksum_is_refused( + cached: bool, message: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + content = windows_zip() + fake_windows(monkeypatch, "AMD64", content) + target = "x86_64-pc-windows-msvc" + monkeypatch.setitem(uv.CHECKSUMS, target, "0" * 64) + + def unpack(content: bytes, target: str) -> bytes: + raise AssertionError("an unverified archive was unpacked") + + monkeypatch.setattr(uv, "unpack", unpack) + archive = tmp_path / f"uv-{uv.VERSION}-{target}.zip" + if cached: + archive.write_bytes(content) + with pytest.raises(SystemExit, match=message): + uv.executable(tmp_path) + # A rejected download is never saved, and a rejected archive is never extracted. + assert archive.exists() == cached + assert not (tmp_path / f"uv-{uv.VERSION}-{target}.exe").exists() + + +def test_unix_archive_still_yields_its_uv_executable() -> None: + archive = io.BytesIO() + with tarfile.open(fileobj=archive, mode="w:gz") as package: + member = tarfile.TarInfo("uv-x86_64-unknown-linux-gnu/uv") + member.size = 2 + package.addfile(member, io.BytesIO(b"uv")) + assert uv.unpack(archive.getvalue(), "x86_64-unknown-linux-gnu") == b"uv"