Skip to content

The agent that grows with you

fix(build): decode release and Termux inputs consistently

ethernet176d1c771e35
diff --git a/scripts/bundles/release_artifacts.py b/scripts/bundles/release_artifacts.py
index 7dc580d63d7..9d9689cad41 100644
--- a/scripts/bundles/release_artifacts.py
+++ b/scripts/bundles/release_artifacts.py
@@ -74,7 +74,7 @@ def record(platform: str, arch: str, root: Path, tag: str, commit: str, out: Pat
with tempfile.TemporaryDirectory() as temp:
subprocess.run(["dpkg-deb", "--extract", str(package), temp], check=True)
stamps = list(Path(temp).rglob("install-stamp.json"))
- if not any((data := json.loads(p.read_text(encoding="utf-8"))).get("commit") == commit and data.get("tag") == tag for p in stamps):
+ if not any((data := json.loads(p.read_text(encoding="utf-8-sig"))).get("commit") == commit and data.get("tag") == tag for p in stamps):
raise ValueError("Termux package has no matching provenance")
else:
raise ValueError("Unknown platform")
@@ -93,7 +93,7 @@ def assemble(root: Path, tag: str, commit: str, public_base: str, out: Path) ->
file = root / receipt_name(name)
if not file.is_file():
raise ValueError(f"Missing candidate handoff: {name}")
- receipt = json.loads(file.read_text(encoding="utf-8"))
+ receipt = json.loads(file.read_text(encoding="utf-8-sig"))
for row in validate_receipt(receipt, tag, commit, name):
prior = by_name.get(row["path"])
if prior is not None and prior != row:
@@ -106,7 +106,7 @@ def assemble(root: Path, tag: str, commit: str, public_base: str, out: Path) ->
if not file.is_file() or sha256_file(file) != receipt["sha256"]:
raise ValueError(f"Candidate local digest mismatch: {name}")
if name.startswith("metadata-"):
- rows.append(json.loads(file.read_text(encoding="utf-8")))
+ rows.append(json.loads(file.read_text(encoding="utf-8-sig")))
universal_name = single(name for name in by_name if name.endswith(".msixbundle") and not name.startswith("Store-"))
single(name for name in by_name if name.endswith(".msixbundle") and name.startswith("Store-"))
windows = [r for r in rows if r["platform"] == "windows"]
diff --git a/scripts/ci/archive_inputs.py b/scripts/ci/archive_inputs.py
index ac4cf1c68b1..c07a6b680b8 100644
--- a/scripts/ci/archive_inputs.py
+++ b/scripts/ci/archive_inputs.py
@@ -86,7 +86,7 @@ def pinned_inputs(repo: Path, *, target: str | None = None, packages: set[str] |
continue # OCI digests belong to the container registry, not HTTP archives.
pins.append(_pin(label, row, "tool"))
if packages is None and target in (None, TERMUX_TARGET):
- table = json.loads((repo / "scripts/termux/runtime_libs.json").read_text(encoding="utf-8"))
+ table = json.loads((repo / "scripts/termux/runtime_libs.json").read_text(encoding="utf-8-sig"))
pins.extend(_pin(name, row, "library") for name, row in table["libs"].items())
if table.get("licenses") is not None:
pins.append(_pin("termux-licenses", table["licenses"], "license"))
diff --git a/scripts/generate_icons.py b/scripts/generate_icons.py
index b53eaa819c0..3c972af578c 100644
--- a/scripts/generate_icons.py
+++ b/scripts/generate_icons.py
@@ -215,7 +215,7 @@ def girl_path(art: IconArt, girl: str) -> str:
"""The girl `<path>` element with editor metadata stripped (resvg rejects
undeclared inkscape/sodipodi prefixes)."""
if girl not in art.paths:
- src = art.girls[girl].read_text(encoding="utf-8")
+ src = art.girls[girl].read_text(encoding="utf-8-sig")
m = re.search(r"<path\b.*?/>", src, re.S)
assert m, f"no <path> found in {art.girls[girl].name}"
path = re.sub(r'\s+(inkscape|sodipodi):[a-zA-Z-]+="[^"]*"', "", m.group(0))
@@ -249,7 +249,7 @@ def girl_layer(art: IconArt, girl: str, box: tuple[float, float, float, float])
def background_inner(art: IconArt, name: str) -> tuple[str, int, int]:
"""Inner content + (width, height) of a background SVG asset."""
- text = (art.backgrounds / name).read_text(encoding="utf-8")
+ text = (art.backgrounds / name).read_text(encoding="utf-8-sig")
if art.colors:
text = text.replace('fill="#ffffff"', f'fill="{art.colors[0]}"')
text = text.replace(f'fill="{DARK_HEX}"', f'fill="{art.colors[1]}"')
diff --git a/scripts/release.py b/scripts/release.py
index a3bd3a1007f..493382f7b01 100755
--- a/scripts/release.py
+++ b/scripts/release.py
@@ -2414,7 +2414,7 @@ def update_version_files(semver: str, calver_date: str) -> list[str]:
# package.json + tauri.conf.json; a hardcoded 0.0.1 ships in the DMG.
installer_pkg = REPO_ROOT / "apps" / "bootstrap-installer" / "package.json"
if installer_pkg.exists():
- pkg_text = installer_pkg.read_text(encoding="utf-8")
+ pkg_text = installer_pkg.read_text(encoding="utf-8-sig")
pkg_text = re.sub(
r'("version"\s*:\s*)"[^"]+"',
rf'\g<1>"{semver}"',
@@ -2428,7 +2428,7 @@ def update_version_files(semver: str, calver_date: str) -> list[str]:
REPO_ROOT / "apps" / "bootstrap-installer" / "src-tauri" / "tauri.conf.json"
)
if installer_tauri.exists():
- pkg_text = installer_tauri.read_text(encoding="utf-8")
+ pkg_text = installer_tauri.read_text(encoding="utf-8-sig")
pkg_text = re.sub(
r'("version"\s*:\s*)"[^"]+"',
rf'\g<1>"{semver}"',
@@ -2442,7 +2442,7 @@ def update_version_files(semver: str, calver_date: str) -> list[str]:
REPO_ROOT / "apps" / "bootstrap-installer" / "src-tauri" / "Cargo.toml"
)
if installer_cargo.exists():
- cargo_text = installer_cargo.read_text(encoding="utf-8")
+ cargo_text = installer_cargo.read_text(encoding="utf-8-sig")
cargo_text = re.sub(
r'^version\s*=\s*"[^"]+"',
f'version = "{semver}"',
diff --git a/scripts/releases/commit_build.py b/scripts/releases/commit_build.py
index bab52f5885d..279c5c5355c 100644
--- a/scripts/releases/commit_build.py
+++ b/scripts/releases/commit_build.py
@@ -116,7 +116,7 @@ def cmd_build_commit(args) -> None:
print("Dry run. Add --publish to dispatch.")
return
print("Starting workflow!")
- result = subprocess.run(command, cwd=release.REPO_ROOT, capture_output=True, text=True,
+ result = subprocess.run(command, cwd=release.REPO_ROOT, capture_output=True, text=True, # windows-footgun: ok — encoding and replacement policy are on the next line.
encoding="utf-8", errors="replace", check=True, timeout=60)
print((result.stdout or "").strip() or f"Dispatched commit build {commit}. No release was created.")
except (OSError, ValueError, subprocess.SubprocessError) as exc:
diff --git a/scripts/releases/darwin.py b/scripts/releases/darwin.py
index 8507a1b2169..89fdbf6cf31 100644
--- a/scripts/releases/darwin.py
+++ b/scripts/releases/darwin.py
@@ -16,7 +16,7 @@ _TAG_PATTERN = re.compile(r"^v\d+\.\d+\.\d+(?:-canary\.\d{14})?$")
def _darwin_feed(channel: str, light: bool = False) -> dict[str, Any]:
"""Read the same feed facts as the desktop runtime."""
- with (Path(__file__).resolve().parents[2] / "apps/desktop/update-feed.json").open(encoding="utf-8") as file:
+ with (Path(__file__).resolve().parents[2] / "apps/desktop/update-feed.json").open(encoding="utf-8-sig") as file:
feeds = json.load(file)
if channel not in feeds:
raise TypeError(f"Unknown update channel: {channel}")
@@ -169,7 +169,7 @@ def finalize(tag: str, dir: str, variant: str | None = None) -> None:
import os
legs = {
- name: open(os.path.join(dir, name), encoding="utf-8").read()
+ name: open(os.path.join(dir, name), encoding="utf-8-sig").read()
for name in sorted(os.listdir(dir))
if name.endswith("-mac.yml")
}
diff --git a/scripts/termux/build_environment.py b/scripts/termux/build_environment.py
index 61ff4452339..dd27c278651 100644
--- a/scripts/termux/build_environment.py
+++ b/scripts/termux/build_environment.py
@@ -28,7 +28,7 @@ def application(root: Path, requirements: Path, python: Path) -> None:
from pm import build_requirements_environment
build_requirements_environment(
- requirements.read_text(encoding="utf-8").splitlines(), out=root / "venv",
+ requirements.read_text(encoding="utf-8-sig").splitlines(), out=root / "venv",
python=python, wheelhouse=root / "wheelhouse", offline=True, sealed=True, explicit=True,
)
diff --git a/scripts/termux/build_wheels.py b/scripts/termux/build_wheels.py
index b19dbc08fbd..b6feff92eac 100644
--- a/scripts/termux/build_wheels.py
+++ b/scripts/termux/build_wheels.py
@@ -44,9 +44,9 @@ def normalize_reqs(export: Path, lock: Path, resolved: Path) -> None:
from packaging.requirements import Requirement
from packaging.utils import canonicalize_name
- packages = tomllib.loads(lock.read_text(encoding="utf-8"))["package"]
+ packages = tomllib.loads(lock.read_text(encoding="utf-8-sig"))["package"]
rows = []
- for line in export.read_text(encoding="utf-8").splitlines():
+ for line in export.read_text(encoding="utf-8-sig").splitlines():
if not line.strip() or line.lstrip().startswith("#"):
continue
req = Requirement(line)
@@ -171,13 +171,13 @@ def build_wheels(build_set: list[str], specs: dict[str, str], wheelhouse: Path,
# also (re)writes ./configure WITHOUT the exec bit
# (setup.py then 127s) -- chmod after bootstrap.
proc = subprocess.run(["bash", "autogen.sh"], cwd=libuv,
- check=False, capture_output=True, text=True)
+ check=False, capture_output=True, text=True, encoding="utf-8")
if proc.returncode == 0 and (libuv / "configure").is_file():
# Run configure under the container's own sh
# (its #!/bin/sh shebang can't exec here).
cfg_proc = subprocess.run(
[os.environ["PREFIX"] + "/bin/sh", "./configure"],
- cwd=libuv, check=False, capture_output=True, text=True,
+ cwd=libuv, check=False, capture_output=True, text=True, encoding="utf-8",
)
if cfg_proc.returncode != 0:
print(f"FIXUP FAILED (libuv configure) for {name}")
@@ -188,7 +188,7 @@ def build_wheels(build_set: list[str], specs: dict[str, str], wheelhouse: Path,
# autogen needs autoreconf when configure is
# stale; fall back to explicit bootstrap
proc2 = subprocess.run(["autoreconf", "-i"], cwd=libuv,
- check=False, capture_output=True, text=True)
+ check=False, capture_output=True, text=True, encoding="utf-8")
if proc2.returncode != 0:
print(f"FIXUP FAILED (libuv bootstrap) for {name}")
print("autogen stdout:", proc.stdout[-1200:])
@@ -198,7 +198,7 @@ def build_wheels(build_set: list[str], specs: dict[str, str], wheelhouse: Path,
proc = subprocess.run(
[python, "-m", "pip", "wheel", "--no-deps", "--no-build-isolation",
"-w", str(wheelhouse), str(src)],
- check=False, cwd=tmp, capture_output=True, text=True,
+ check=False, cwd=tmp, capture_output=True, text=True, encoding="utf-8",
)
if proc.returncode != 0:
print(f"BUILD FAILED: {name}")
@@ -215,7 +215,7 @@ def build_wheels(build_set: list[str], specs: dict[str, str], wheelhouse: Path,
proc = subprocess.run(
[python, "-m", "pip", "wheel", "--no-deps",
"--no-binary", ":all:", "-w", str(wheelhouse), req],
- check=False, capture_output=True, text=True,
+ check=False, capture_output=True, text=True, encoding="utf-8",
)
if proc.returncode != 0:
print(f"BUILD FAILED: {name}")
@@ -255,7 +255,7 @@ def _marker_admits(marker: str) -> bool:
def _parse_full(resolved: Path) -> list[tuple[str, str, str, str]]:
"""Name, wheel version, marker and optional build source for each entry."""
out: list[tuple[str, str, str, str]] = []
- for line in resolved.read_text(encoding="utf-8").splitlines():
+ for line in resolved.read_text(encoding="utf-8-sig").splitlines():
if not line.strip():
continue
parts = line.split("\t")
@@ -295,7 +295,7 @@ def fetch_pure_wheels(build_set: list[str], specs: dict[str, str], wheelhouse: P
proc = subprocess.run(
[sys.executable, "-m", "pip", "download", "--no-deps",
"--only-binary", ":all:", "-d", str(wheelhouse), *reqs],
- check=False, capture_output=True, text=True,
+ check=False, capture_output=True, text=True, encoding="utf-8",
)
if proc.returncode != 0:
print("PURE-WHEEL FETCH FAILED")
@@ -360,7 +360,7 @@ def wheelhouse_gates(resolved: Path, wheelhouse: Path, build_set: list[str]) ->
reqs = tmp / "reqs.txt"
write_reqs_file(resolved, reqs)
vp = build_requirements_environment(
- reqs.read_text(encoding="utf-8").splitlines(), out=tmp / "venv",
+ reqs.read_text(encoding="utf-8-sig").splitlines(), out=tmp / "venv",
python=Path(sys.executable), wheelhouse=wheelhouse, offline=True, explicit=True,
)
print(" completeness gate: offline install of the marker-admitted graph OK")
@@ -381,7 +381,7 @@ def main() -> int:
return 0
args = parse_args()
resolved = Path(args.resolved)
- build_set = [l.strip() for l in Path(args.build_set).read_text(encoding="utf-8").splitlines() if l.strip()]
+ build_set = [l.strip() for l in Path(args.build_set).read_text(encoding="utf-8-sig").splitlines() if l.strip()]
wheelhouse = Path(args.wheelhouse)
wheelhouse.mkdir(parents=True, exist_ok=True)
specs = load_entries(resolved)
diff --git a/scripts/termux/payload_facts.py b/scripts/termux/payload_facts.py
index 5f419335ef5..b7d02a45e7e 100644
--- a/scripts/termux/payload_facts.py
+++ b/scripts/termux/payload_facts.py
@@ -19,7 +19,7 @@ def write_facts(payload: Path, lock_path: Path, build_set: Path, tui: Path) -> N
payload = payload.resolve()
target = "linux-arm64-bionic"
record_tools(payload, lock_path, target, {name: name for name in ("python", "node", "uv", "npm", "ffmpeg", "ripgrep")})
- natives = [line.strip() for line in build_set.read_text(encoding="utf-8").splitlines() if line.strip()]
+ natives = [line.strip() for line in build_set.read_text(encoding="utf-8-sig").splitlines() if line.strip()]
(payload / "native-wheels.json").write_text(json.dumps(natives) + "\n", encoding="utf-8")
# This is the target pin, never the host's sys.version_info or sysconfig.
version = Lockfile(lock_path).version("python")
diff --git a/scripts/termux/stage_apt_repo.py b/scripts/termux/stage_apt_repo.py
index bebbb8390ae..71774e41caf 100644
--- a/scripts/termux/stage_apt_repo.py
+++ b/scripts/termux/stage_apt_repo.py
@@ -113,7 +113,7 @@ def deb_control_fields_and_bytes(deb_path: Path) -> tuple[dict, bytes]:
f = tf.extractfile(member)
if f is None:
continue
- fields = _parse_debian_control(f.read().decode("utf-8", "replace"))
+ fields = _parse_debian_control(f.read().decode("utf-8-sig", "replace"))
break
for req in REQUIRED_CONTROL_FIELDS:
if req not in fields:
@@ -202,7 +202,7 @@ def existing_published(out_dir: Path, suite: str) -> set:
packages_file = out_dir / "dists" / suite / COMPONENT / f"binary-{ARCH}" / "Packages"
published = set()
if packages_file.exists():
- text = packages_file.read_text(encoding="utf-8")
+ text = packages_file.read_text(encoding="utf-8-sig")
# deb822 records are separated by blank lines; never rely on field
# order inside a record.
for stanza in text.split("\n\n"):
diff --git a/scripts/termux/stage_runtime_libs.py b/scripts/termux/stage_runtime_libs.py
index 542bc94aa1a..10de9b51d57 100644
--- a/scripts/termux/stage_runtime_libs.py
+++ b/scripts/termux/stage_runtime_libs.py
@@ -85,7 +85,7 @@ def _cache_valid(out: Path, manifest_path: Path, table: dict) -> bool:
if not out.is_dir() or not manifest_path.is_file():
return False
try:
- manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
+ manifest = json.loads(manifest_path.read_text(encoding="utf-8-sig"))
files = manifest["files"]
except (ValueError, KeyError, OSError):
return False
@@ -218,7 +218,7 @@ def main() -> int:
print("usage: stage_runtime_libs.py <payload-dir>", file=sys.stderr)
return 2
payload = Path(sys.argv[1]).resolve()
- table = json.loads((HERE / "runtime_libs.json").read_text(encoding="utf-8"))
+ table = json.loads((HERE / "runtime_libs.json").read_text(encoding="utf-8-sig"))
try:
stage(payload, table["libs"], table.get("licenses"))
except Exception as exc: # noqa: BLE001 -- CLI boundary reports and exits
diff --git a/scripts/termux/validate_installed.py b/scripts/termux/validate_installed.py
index d145d782967..eaea44a7725 100644
--- a/scripts/termux/validate_installed.py
+++ b/scripts/termux/validate_installed.py
@@ -16,7 +16,7 @@ import time
def run(argv: list[str], env: dict[str, str], cwd: Path) -> subprocess.CompletedProcess:
- result = subprocess.run(argv, env=env, cwd=cwd, capture_output=True, text=True, timeout=90)
+ result = subprocess.run(argv, env=env, cwd=cwd, capture_output=True, text=True, encoding="utf-8", timeout=90)
print("+", " ".join(argv), flush=True)
print(result.stdout, result.stderr, flush=True)
result.check_returncode()
@@ -120,7 +120,7 @@ def main() -> None:
"assert detect_install_method() == 'apt'; "
"print('CLI_AND_STDLIB_IMPORTS_OK')",
], env, home)
- natives = json.loads((root / "native-wheels.json").read_text(encoding="utf-8"))
+ natives = json.loads((root / "native-wheels.json").read_text(encoding="utf-8-sig"))
run([
str(python), str(root / "app/scripts/termux/build_wheels.py"),
"--import-modules", *natives,
@@ -141,7 +141,7 @@ def main() -> None:
"import pm; issues = pm.check(); "
"assert not issues, issues; print('PM_RUNTIME_TOOLS_OK')",
], env, home)
- result = subprocess.run([str(launcher), "update"], env=env, cwd=home, capture_output=True, text=True, timeout=60)
+ result = subprocess.run([str(launcher), "update"], env=env, cwd=home, capture_output=True, text=True, encoding="utf-8", timeout=60)
validate_update_refusal(root / "app", result)
tui_smoke(launcher, env, home)
print("INSTALLED_BUNDLE_VALIDATION_OK", flush=True)
diff --git a/scripts/termux/wheelhouse_cache.py b/scripts/termux/wheelhouse_cache.py
index 2818673ee43..952b3ff7f6e 100644
--- a/scripts/termux/wheelhouse_cache.py
+++ b/scripts/termux/wheelhouse_cache.py
@@ -53,7 +53,7 @@ def write_manifest(payload: Path, identity: dict[str, str], **metadata: str) ->
def is_usable(payload: Path, identity: dict[str, str]) -> bool:
try:
- index = json.loads((payload / "index.json").read_text(encoding="utf-8"))
+ index = json.loads((payload / "index.json").read_text(encoding="utf-8-sig"))
if index["schemaVersion"] != 2 or index["inputs"] != identity:
return False
if index["resolvedSha256"] != _sha256(payload / ".work/resolved.txt"):
diff --git a/scripts/validate_plugin_catalog.py b/scripts/validate_plugin_catalog.py
index d7fda110aa4..ed55644fbd3 100644
--- a/scripts/validate_plugin_catalog.py
+++ b/scripts/validate_plugin_catalog.py
@@ -192,7 +192,7 @@ def validate_file(path: Path) -> tuple[list[str], list[str]]:
try:
reader = YAML(typ="safe")
reader.version = (1, 1)
- with open(path, encoding="utf-8") as fh:
+ with open(path, encoding="utf-8-sig") as fh:
data = reader.load(fh)
except OSError as exc:
return [f"cannot read file: {exc}"], []
diff --git a/tests/ci/test_termux_input_archive.py b/tests/ci/test_termux_input_archive.py
index d2a6fc62554..fa47414a8a3 100644
--- a/tests/ci/test_termux_input_archive.py
+++ b/tests/ci/test_termux_input_archive.py
@@ -1,6 +1,9 @@
"""CI runs archival before the exact tool and payload consumers."""
+import json
from pathlib import Path
+import pytest
+
from ruamel.yaml import YAML
ROOT = Path(__file__).resolve().parents[2]
@@ -11,6 +14,25 @@ def load(name):
return YAML(typ="base").load((ROOT / ".github/workflows" / name).read_text(encoding="utf-8"))
+def test_archive_reader_accepts_bom_without_changing_pin_authority(tmp_path):
+ from scripts.ci.archive_inputs import pinned_inputs
+
+ (tmp_path / "pm").mkdir()
+ (tmp_path / "pm/lock.json").write_bytes(b'\xef\xbb\xbf{"schema":1,"packages":{}}')
+ table = tmp_path / "scripts/termux/runtime_libs.json"
+ table.parent.mkdir(parents=True)
+ row = {"url": "https://example.invalid/café.deb", "sha256": "a" * 64}
+ table.write_bytes(b"\xef\xbb\xbf" + json.dumps({"libs": {"lib": row}}, ensure_ascii=False).encode("utf-8"))
+ before = table.read_bytes()
+ (pin,) = pinned_inputs(tmp_path, target="linux-arm64-bionic")
+ assert (pin.name, pin.url, pin.sha256) == ("lib", row["url"], row["sha256"])
+ assert table.read_bytes() == before
+ row["sha256"] = " " + row["sha256"]
+ table.write_bytes(b"\xef\xbb\xbf" + json.dumps({"libs": {"lib": row}}).encode("utf-8"))
+ with pytest.raises(ValueError):
+ pinned_inputs(tmp_path, target="linux-arm64-bionic")
+
+
def test_archive_gate_uses_bootstrap_python_and_trusted_exact_revision():
workflow = load("archive-inputs.yml")
assert not {"pull_request", "pull_request_target"} & workflow["on"].keys()
diff --git a/tests/scripts/test_icon_generation_exit.py b/tests/scripts/test_icon_generation_exit.py
index 2f63b0b425e..3888e0bb89a 100644
--- a/tests/scripts/test_icon_generation_exit.py
+++ b/tests/scripts/test_icon_generation_exit.py
@@ -3,12 +3,36 @@ import importlib.util
import io
import sys
from pathlib import Path
-from types import ModuleType
+from types import ModuleType, SimpleNamespace
import pytest
from PIL import Image
[email protected]("bom", [b"", b"\xef\xbb\xbf"])
+def test_svg_readers_accept_bom_without_rewriting_assets(tmp_path, monkeypatch, bom):
+ monkeypatch.setitem(sys.modules, "resvg_py", ModuleType("resvg_py"))
+ script = Path(__file__).resolve().parents[2] / "scripts/generate_icons.py"
+ spec = importlib.util.spec_from_file_location("icon_readers_under_test", script)
+ assert spec is not None and spec.loader is not None
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ path = tmp_path / "art.svg"
+ element = '<path d="M0 0 L1 1" aria-label="café 東京"/>'
+ raw = bom + f'<svg viewBox="0 0 20 30">{element}</svg>'.encode("utf-8")
+ path.write_bytes(raw)
+ art = SimpleNamespace(girls={"black": path}, paths={}, backgrounds=tmp_path, colors=None)
+ assert module.girl_path(art, "black") == element
+ assert module.background_inner(art, path.name) == (element, 20, 30)
+ assert path.read_bytes() == raw
+ path.write_bytes(bom + b"<svg/>")
+ art.paths.clear()
+ with pytest.raises(AssertionError, match="no <path>"):
+ module.girl_path(art, "black")
+ with pytest.raises(AssertionError, match="viewBox"):
+ module.background_inner(art, path.name)
+
+
@pytest.mark.parametrize("failure", [None, "render", "directory", "verify"])
def test_write_status_includes_every_target(tmp_path, monkeypatch, capsys, failure):
# The renderer is build-only. This test injects failures at its byte boundary.
diff --git a/tests/scripts/test_pm_build_consumers.py b/tests/scripts/test_pm_build_consumers.py
index 15b69820c02..6e6995cf5e2 100644
--- a/tests/scripts/test_pm_build_consumers.py
+++ b/tests/scripts/test_pm_build_consumers.py
@@ -109,6 +109,7 @@ def test_termux_gate_checks_real_offline_wheels_and_application_uses_same_graph(
build_wheels.wheelhouse_gates(resolved, wheels, ["native-probe"])
requirements = tmp_path / "requirements.txt"
build_wheels.write_reqs_file(resolved, requirements)
+ requirements.write_bytes(b"\xef\xbb\xbf" + requirements.read_bytes())
build_environment.application(tmp_path, requirements, Path(sys.executable))
python = tmp_path / "venv" / ("Scripts/python.exe" if os.name == "nt" else "bin/python")
subprocess.run([str(python), "-I", "-c", "import native_probe"], check=True)
diff --git a/tests/scripts/test_release_bootstrap_installer_version.py b/tests/scripts/test_release_bootstrap_installer_version.py
index 5cfa3e09bfe..af675c76102 100644
--- a/tests/scripts/test_release_bootstrap_installer_version.py
+++ b/tests/scripts/test_release_bootstrap_installer_version.py
@@ -13,6 +13,8 @@ import importlib.util
import json
from pathlib import Path
+import pytest
+
SCRIPT = Path(__file__).resolve().parents[2] / "scripts" / "release.py"
@@ -85,8 +87,12 @@ def _patch_repo(tmp_path, monkeypatch, *, with_installer: bool = True):
}
-def test_update_version_files_stamps_bootstrap_installer(tmp_path, monkeypatch):
[email protected]("bom", [b"", b"\xef\xbb\xbf"])
+def test_update_version_files_stamps_bootstrap_installer(tmp_path, monkeypatch, bom):
paths = _patch_repo(tmp_path, monkeypatch)
+ for key in ("installer_pkg", "tauri_conf", "cargo_toml"):
+ path = paths[key]
+ path.write_bytes(bom + path.read_bytes())
staged = release.update_version_files("0.21.1", "2026.9.10")
assert all(str(paths[key]) in staged for key in (
@@ -95,6 +101,8 @@ def test_update_version_files_stamps_bootstrap_installer(tmp_path, monkeypatch):
assert _json_version(paths["installer_pkg"]) == "0.21.1"
assert _json_version(paths["tauri_conf"]) == "0.21.1"
assert 'version = "0.21.1"' in paths["cargo_toml"].read_text(encoding="utf-8")
+ assert all(not paths[key].read_bytes().startswith(b"\xef\xbb\xbf")
+ for key in ("installer_pkg", "tauri_conf", "cargo_toml"))
# CONTROL: existing desktop / Python stamps still happen.
assert _json_version(paths["desktop_pkg"]) == "0.21.1"
diff --git a/tests/scripts/test_termux_agent_assembly.py b/tests/scripts/test_termux_agent_assembly.py
index cf60829f826..b2b12c9fbd6 100644
--- a/tests/scripts/test_termux_agent_assembly.py
+++ b/tests/scripts/test_termux_agent_assembly.py
@@ -38,7 +38,7 @@ def test_bionic_facts_and_agent_keep_fixed_prefix_and_tui_only(tmp_path):
(tui / "dist/entry.js").write_text("built", encoding="utf-8")
(tui / "package.json").write_text('{"type":"module"}', encoding="utf-8")
build_set = tmp_path / "build-set.txt"
- build_set.write_text("native-fixture\n", encoding="utf-8")
+ build_set.write_bytes(b"\xef\xbb\xbfnative-fixture\n")
write_facts(payload, lock, build_set, tui)
manifest = json.loads((payload / "manifest.json").read_text())
assert manifest["runtime"]["commands"] == {"probe": "bin/probe"}
diff --git a/tests/scripts/test_termux_update_refusal.py b/tests/scripts/test_termux_update_refusal.py
index ad9eacaa386..77a5e9ac1bb 100644
--- a/tests/scripts/test_termux_update_refusal.py
+++ b/tests/scripts/test_termux_update_refusal.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import json
import subprocess
+import sys
from pathlib import Path
from types import SimpleNamespace
@@ -11,6 +12,23 @@ import pytest
from hermes_cli.update_contract import COMMIT_BUILD_UPDATE_MESSAGE
+def test_validator_child_decodes_utf8_and_preserves_strict_errors(tmp_path, monkeypatch):
+ import os
+ from scripts.termux.validate_installed import run
+
+ # Force a non-UTF-8 locale fallback without pretending to be a different OS.
+ monkeypatch.setattr(subprocess, "_text_encoding", lambda: "ascii")
+ message = "café 東京\n"
+ command = [sys.executable, "-c", f"import os; os.write(1, {message.encode('utf-8')!r})"]
+ assert run(command, dict(os.environ), tmp_path).stdout == message
+ with pytest.raises(subprocess.CalledProcessError) as failed:
+ run([*command[:-1], command[-1] + "; raise SystemExit(7)"], dict(os.environ), tmp_path)
+ assert failed.value.returncode == 7 and failed.value.stdout == message
+ with pytest.raises(UnicodeDecodeError):
+ run([*command[:-1], "import os; os.write(1, bytes([255]))"], dict(os.environ), tmp_path)
+
+
@pytest.fixture(params=["bundle", "commit-build"])
def artifact(tmp_path, request):
root = tmp_path / "app"
diff --git a/tests/scripts/test_validate_plugin_catalog.py b/tests/scripts/test_validate_plugin_catalog.py
index 3305f5d59a9..1c87aef7926 100644
--- a/tests/scripts/test_validate_plugin_catalog.py
+++ b/tests/scripts/test_validate_plugin_catalog.py
@@ -12,6 +12,7 @@ import sys
from pathlib import Path
import hermes_yaml as yaml
+import pytest
REPO_ROOT = Path(__file__).resolve().parents[2]
SCRIPT = REPO_ROOT / "scripts" / "validate_plugin_catalog.py"
@@ -54,8 +55,10 @@ def run_validator(*args: str) -> subprocess.CompletedProcess:
# ── valid input ────────────────────────────────────────────────────────
-def test_valid_entry_passes(tmp_path):
- path = write_entry(tmp_path, VALID_ENTRY)
[email protected]("bom", [b"", b"\xef\xbb\xbf"])
+def test_valid_entry_passes(tmp_path, bom):
+ path = write_entry(tmp_path, {**VALID_ENTRY, "description": "café 東京"})
+ path.write_bytes(bom + path.read_bytes())
result = run_validator(str(path))
assert result.returncode == 0, result.stdout + result.stderr
diff --git a/tests/test_termux_build_wheels.py b/tests/test_termux_build_wheels.py
index b9636e43d3d..1fa5f39c81b 100644
--- a/tests/test_termux_build_wheels.py
+++ b/tests/test_termux_build_wheels.py
@@ -12,6 +12,23 @@ import pytest
from scripts.termux import build_wheels as builder
[email protected]("bom", [b"", b"\xef\xbb\xbf"])
+def test_requirement_readers_preserve_pins_and_reject_malformed_rows(tmp_path, bom):
+ lock, export, resolved, reqs = (tmp_path / name for name in
+ ("uv.lock", "export.txt", "resolved.txt", "reqs.txt"))
+ lock.write_bytes(bom + 'package = []\n# café\n'.encode("utf-8"))
+ export.write_bytes(bom + 'example==1.0\n# café\n'.encode("utf-8"))
+ builder.normalize_reqs(export, lock, resolved)
+ assert resolved.read_bytes() == b"example\t==1.0\t\t\n"
+ resolved.write_bytes(bom + resolved.read_bytes())
+ assert builder.load_entries(resolved) == {"example": "==1.0"}
+ builder.write_reqs_file(resolved, reqs)
+ assert reqs.read_bytes() == b"example==1.0\n"
+ resolved.write_bytes(bom + b"example\t==1.0\n")
+ with pytest.raises(ValueError, match="fields"):
+ builder.load_entries(resolved)
+
+
def test_source_pin_survives_resolution_build_and_offline_install(tmp_path):
repo = tmp_path / "source"
repo.mkdir()
diff --git a/tests/test_termux_deb_version.py b/tests/test_termux_deb_version.py
index e550b508827..6a602946fa1 100644
--- a/tests/test_termux_deb_version.py
+++ b/tests/test_termux_deb_version.py
@@ -10,6 +10,25 @@ from scripts.termux.deb_version import channel_for_tag, deb_version_for_tag
SCRIPT = Path(__file__).resolve().parents[1] / "scripts/termux/deb_version.py"
[email protected]("bom", ["", "\ufeff"])
+def test_apt_readers_accept_bom_and_keep_archive_bytes(tmp_path, bom):
+ from scripts.termux import stage_apt_repo as apt
+ from tests.termux_fixtures import build_deb
+
+ control = {bom + "Package": "example", "Version": "1.2.3-1", "Architecture": "aarch64",
+ "Description": "café 東京"}
+ package = tmp_path / "example.deb"
+ build_deb(package, control)
+ original = package.read_bytes()
+ fields, raw = apt.deb_control_fields_and_bytes(package)
+ assert fields == {key.removeprefix("\ufeff"): value for key, value in control.items()}
+ assert raw == original == package.read_bytes()
+ index = tmp_path / "dists/stable" / apt.COMPONENT / f"binary-{apt.ARCH}" / "Packages"
+ index.parent.mkdir(parents=True)
+ index.write_text(bom + "Package: example\nVersion: 1.2.3-1\n\nPackage: incomplete\n", encoding="utf-8")
+ assert apt.existing_published(tmp_path, "stable") == {("example", "1.2.3-1")}
+
+
@pytest.mark.parametrize("tag,version,channel", [
("v1.2.3", "1.2.3-1", "stable"),
("v26.8.31", "26.8.31-1", "stable"),
diff --git a/tests/test_termux_runtime_libs.py b/tests/test_termux_runtime_libs.py
index bb3e969fa37..f0297b6cc18 100644
--- a/tests/test_termux_runtime_libs.py
+++ b/tests/test_termux_runtime_libs.py
@@ -119,7 +119,9 @@ def test_stage_cache_correctness(tmp_path, lib_source, corruption):
out = _stage(tmp_path, table)
names = {"liba.so", "libb.so"}
assert {p.name for p in out.glob("*.so*")} == names
- manifest = json.loads(out.parent.joinpath("manifest.json").read_text())
+ manifest_path = out.parent / "manifest.json"
+ manifest = json.loads(manifest_path.read_text())
+ manifest_path.write_bytes(b"\xef\xbb\xbf" + manifest_path.read_bytes())
# Same URL/table throughout: corruption must invalidate output evidence,
# not accidentally trigger the independent table-identity check.
diff --git a/tests/test_termux_wheelhouse_cache.py b/tests/test_termux_wheelhouse_cache.py
index 8a5d174b972..91c2307e621 100644
--- a/tests/test_termux_wheelhouse_cache.py
+++ b/tests/test_termux_wheelhouse_cache.py
@@ -24,9 +24,12 @@ def cache_tree(tmp_path: Path) -> tuple[Path, dict[str, str]]:
return payload, identity
-def test_cache_rejects_changed_inputs_and_modified_outputs(tmp_path):
[email protected]("bom", [b"", b"\xef\xbb\xbf"])
+def test_cache_rejects_changed_inputs_and_modified_outputs(tmp_path, bom):
payload, identity = cache_tree(tmp_path)
wheelhouse_cache.write_manifest(payload, identity)
+ index = payload / "index.json"
+ index.write_bytes(bom + index.read_bytes())
assert wheelhouse_cache.is_usable(payload, identity)
for key in identity:
assert not wheelhouse_cache.is_usable(payload, {**identity, key: "changed"})