Skip to content

armgit / herdr

Public Imported from GitHub
0

the runtime your coding agents live on

fix: bundle pinned ConPTY in local Windows builds (#4760)

JJ Liebig7479f8e126da
diff --git a/justfile b/justfile
index af867d6f3..d651a34b4 100644
--- a/justfile
+++ b/justfile
@@ -80,9 +80,14 @@ install-hooks:
@echo "installed git hooks from .githooks"
# Build release binary
+[unix]
build:
cargo build --release --locked
+[windows]
+build:
+ python scripts/package_windows_conpty.py build-local
+
# Non-gating full-render scaling profile for background workspaces and active panes
bench-render-scale:
cargo test --release --locked --bin herdr render_scale_profile -- --ignored --nocapture --test-threads=1
diff --git a/scripts/package_windows_conpty.py b/scripts/package_windows_conpty.py
index 1877d6b05..42daae3fd 100644
--- a/scripts/package_windows_conpty.py
+++ b/scripts/package_windows_conpty.py
@@ -4,8 +4,11 @@ from __future__ import annotations
import argparse
import hashlib
import json
+import os
import shutil
import struct
+import subprocess
+import sys
import tempfile
import time
import urllib.error
@@ -313,6 +316,94 @@ def stage_bundle(
staging.rename(output_dir)
+def install_local_bundle(
+ metadata_path: Path, architecture: str, package_path: Path, herdr_exe: Path
+) -> None:
+ release_dir = herdr_exe.resolve().parent
+ destination = release_dir / "conpty"
+ with tempfile.TemporaryDirectory(prefix="herdr-conpty-install-", dir=release_dir) as temporary:
+ stage = Path(temporary) / "stage"
+ stage_bundle(metadata_path, architecture, package_path, herdr_exe, stage)
+ staged_bundle = stage / "conpty"
+ if destination.exists() or destination.is_symlink():
+ staged_files = {
+ path.relative_to(staged_bundle)
+ for path in staged_bundle.rglob("*")
+ if path.is_file()
+ }
+ installed_files = {
+ path.relative_to(destination)
+ for path in destination.rglob("*")
+ if path.is_file()
+ }
+ matches = (
+ destination.is_dir()
+ and not destination.is_symlink()
+ and not any(path.is_symlink() for path in destination.rglob("*"))
+ and installed_files == staged_files
+ and all(
+ not (destination / relative).is_symlink()
+ and sha256_file(destination / relative) == sha256_file(staged_bundle / relative)
+ for relative in staged_files
+ )
+ )
+ # ponytail: pin upgrades require stopping Herdr and removing the old local bundle.
+ if not matches:
+ raise ValueError(
+ f"local ConPTY bundle at {destination} differs from the pinned version; "
+ "stop Herdr, remove that directory, then run just build again"
+ )
+
+ for notice in load_metadata(metadata_path)["notices"]:
+ relative = PurePosixPath(notice["destination"])
+ target = release_dir / relative
+ target.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(stage / relative, target)
+ if not destination.exists():
+ staged_bundle.rename(destination)
+
+
+def build_local_bundle(metadata_path: Path) -> None:
+ executable = None
+ with subprocess.Popen(
+ ["cargo", "build", "--release", "--locked", "--message-format=json"],
+ cwd=PROJECT_ROOT,
+ stdout=subprocess.PIPE,
+ text=True,
+ encoding="utf-8",
+ ) as cargo:
+ assert cargo.stdout is not None
+ for line in cargo.stdout:
+ if not line.startswith("{"):
+ print(line, end="")
+ continue
+ message = json.loads(line)
+ if message.get("reason") == "compiler-message":
+ print(message["message"]["rendered"], end="", file=sys.stderr)
+ elif (
+ message.get("reason") == "compiler-artifact"
+ and message["manifest_path"] == str(PROJECT_ROOT / "Cargo.toml")
+ and message["target"]["name"] == "herdr"
+ and "bin" in message["target"]["kind"]
+ ):
+ executable = Path(message["executable"])
+ status = cargo.wait()
+ if status:
+ raise SystemExit(status)
+ if executable is None:
+ raise ValueError("cargo did not report the Herdr executable")
+
+ target = Path(os.environ.get("CARGO_TARGET_DIR", "target"))
+ if not target.is_absolute():
+ target = PROJECT_ROOT / target
+ install_local_bundle(
+ metadata_path,
+ "x86_64",
+ target / "conpty" / "Microsoft.Windows.Console.ConPTY.nupkg",
+ executable,
+ )
+
+
def expected_stage_files(metadata: dict[str, Any], architecture: str) -> set[str]:
files = {"herdr.exe", MARKER_PATH.as_posix()}
files.update(item["destination"] for item in metadata["bundles"][architecture]["files"])
@@ -376,6 +467,7 @@ def parse_args() -> argparse.Namespace:
archive.add_argument("--architecture", choices=("x86_64",), default="x86_64")
archive.add_argument("--stage-dir", type=Path, required=True)
archive.add_argument("--output", type=Path, required=True)
+ subparsers.add_parser("build-local")
return parser.parse_args()
@@ -389,8 +481,10 @@ def main() -> None:
args.herdr_exe,
args.output_dir,
)
- else:
+ elif args.command == "archive":
archive_bundle(args.metadata, args.architecture, args.stage_dir, args.output)
+ else:
+ build_local_bundle(args.metadata)
if __name__ == "__main__":
diff --git a/scripts/test_package_windows_conpty.py b/scripts/test_package_windows_conpty.py
index 61aec9d0d..a8c006cc1 100644
--- a/scripts/test_package_windows_conpty.py
+++ b/scripts/test_package_windows_conpty.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import hashlib
import io
import json
+import os
import struct
import tempfile
import unittest
@@ -15,6 +16,29 @@ from scripts import package_windows_conpty as package
class WindowsConptyPackageTests(unittest.TestCase):
+ def test_local_build_installs_beside_cargos_reported_executable(self) -> None:
+ executable = Path("other-target/x86_64-pc-windows-msvc/release/herdr.exe")
+ cargo = mock.MagicMock()
+ cargo.__enter__.return_value = cargo
+ cargo.stdout = io.StringIO(
+ json.dumps(
+ {
+ "reason": "compiler-artifact",
+ "manifest_path": str(package.PROJECT_ROOT / "Cargo.toml"),
+ "target": {"name": "herdr", "kind": ["bin"]},
+ "executable": str(executable),
+ }
+ )
+ + "\n"
+ )
+ cargo.wait.return_value = 0
+ with (
+ mock.patch.object(package.subprocess, "Popen", return_value=cargo),
+ mock.patch.object(package, "install_local_bundle") as install,
+ ):
+ package.build_local_bundle(package.DEFAULT_METADATA)
+ self.assertEqual(install.call_args.args[-1], executable)
+
def test_pinned_metadata_and_notices_are_consistent(self) -> None:
metadata = package.load_metadata(package.DEFAULT_METADATA)
self.assertEqual(metadata["package"]["id"], "Microsoft.Windows.Console.ConPTY")
@@ -110,7 +134,11 @@ class WindowsConptyPackageTests(unittest.TestCase):
]
nupkg = root / "conpty.nupkg"
self._write_package(nupkg, files, {item["source"]: data for item, data in zip(files, (dll, x64_host, arm64_host))})
- metadata_path = root / "conpty.json"
+ notice_paths = [root / "NOTICE-a.txt", root / "NOTICE-b.txt"]
+ for index, notice in enumerate(notice_paths):
+ notice.write_text(f"notice {index}", encoding="utf-8")
+ metadata_path = root / "packaging" / "windows" / "conpty.json"
+ metadata_path.parent.mkdir(parents=True)
metadata_path.write_text(
json.dumps(
{
@@ -123,7 +151,14 @@ class WindowsConptyPackageTests(unittest.TestCase):
"license": "MIT",
},
"bundles": {"x86_64": {"files": files}},
- "notices": [],
+ "notices": [
+ {
+ "source": notice.name,
+ "destination": f"THIRD-PARTY-NOTICES/{notice.name}",
+ "sha256": package.sha256_file(notice),
+ }
+ for notice in notice_paths
+ ],
}
),
encoding="utf-8",
@@ -153,6 +188,55 @@ class WindowsConptyPackageTests(unittest.TestCase):
),
)
+ local = root / "local" / "release"
+ local.mkdir(parents=True)
+ local_exe = local / "herdr.exe"
+ local_exe.write_bytes(herdr.read_bytes())
+ package.install_local_bundle(metadata_path, "x86_64", nupkg, local_exe)
+ self.assertEqual((local / "conpty" / "conpty.dll").read_bytes(), dll)
+ self.assertEqual(
+ (local / "conpty" / "herdr-conpty.json").read_bytes(),
+ package.marker_data(package.load_metadata(metadata_path), "x86_64"),
+ )
+ for notice in notice_paths:
+ self.assertEqual(
+ (local / "THIRD-PARTY-NOTICES" / notice.name).read_bytes(),
+ notice.read_bytes(),
+ )
+
+ package.install_local_bundle(metadata_path, "x86_64", nupkg, local_exe)
+ (local / "conpty" / "stale-file").write_bytes(b"stale")
+ with self.assertRaisesRegex(ValueError, "differs from the pinned version"):
+ package.install_local_bundle(metadata_path, "x86_64", nupkg, local_exe)
+ self.assertTrue((local / "conpty" / "stale-file").exists())
+ (local / "conpty" / "stale-file").unlink()
+ package.install_local_bundle(metadata_path, "x86_64", nupkg, local_exe)
+
+ dangling = local / "conpty" / "dangling"
+ try:
+ dangling.symlink_to("missing")
+ except OSError:
+ if os.name != "nt":
+ raise
+ else:
+ with self.assertRaisesRegex(ValueError, "differs from the pinned version"):
+ package.install_local_bundle(metadata_path, "x86_64", nupkg, local_exe)
+ dangling.unlink()
+
+ dangling_root = root / "dangling-root"
+ dangling_root.mkdir()
+ dangling_exe = dangling_root / "herdr.exe"
+ dangling_exe.write_bytes(herdr.read_bytes())
+ try:
+ (dangling_root / "conpty").symlink_to("missing", target_is_directory=True)
+ except OSError:
+ if os.name != "nt":
+ raise
+ else:
+ with self.assertRaisesRegex(ValueError, "differs from the pinned version"):
+ package.install_local_bundle(metadata_path, "x86_64", nupkg, dangling_exe)
+ self.assertFalse((dangling_root / "THIRD-PARTY-NOTICES").exists())
+
(stage / "conpty" / "conpty.dll").write_bytes(b"tampered")
with self.assertRaisesRegex(ValueError, "staged file hash mismatch"):
package.validate_stage(metadata_path, "x86_64", stage)