This commit is contained in:
Mateusz Gruszczyński committed 2026-11-28 17:36:53 +01:00
1 parent 5b6d4a7903
commit 4d1087e357
160 files changed
+2407 -1933

No files matched your search

+3 -20
View File
@@ -37,11 +37,9 @@ HELP = ("Install Python 3.10+ and allow HTTPS access to github.com/codeload.gith
"or set SWAGGER_UI_DOWNLOAD_URL=file:///absolute/path/swagger-ui-5.33.1.zip "
"to a reviewed copy of the same tag archive. See docs/INSTALL.md.")
class AssetError(ValueError):
"""A controlled, actionable source/archive error (never an implicit fallback)."""
def source_value(value: str | None) -> str | Path:
"""Unset/empty means the pin, never the adapter's historical default."""
if value is None or not value.strip():
@@ -56,7 +54,6 @@ def source_value(value: str | None) -> str | Path:
if (parts.scheme != "file" or parts.netloc not in ("", "localhost")
or parts.query or parts.fragment):
raise ValueError()
# url2pathname decodes percent escapes (including spaces) on this platform.
path = Path(url2pathname(parts.path))
if not path.is_absolute() or any(c in str(path) for c in "\r\n\0"):
raise ValueError()
@@ -64,7 +61,6 @@ def source_value(value: str | None) -> str | Path:
except (ValueError, OSError):
raise AssetError("Swagger source must be the pinned HTTPS URL or an absolute file:// URL.") from None
def expected_digest(value: str | None) -> str | None:
if value is None or not value.strip():
return None
@@ -73,7 +69,6 @@ def expected_digest(value: str | None) -> str | None:
raise AssetError("SWAGGER_UI_ARCHIVE_SHA256 must contain exactly 64 hexadecimal digits.")
return value
class HttpsRedirects(HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
target = urlsplit(newurl)
@@ -82,7 +77,6 @@ class HttpsRedirects(HTTPRedirectHandler):
raise AssetError("Swagger download refused an unexpected redirect.")
return super().redirect_request(req, fp, code, msg, headers, newurl)
def download(destination: Path) -> None:
"""Download with a few retries; github.com occasionally times out or returns a gateway error."""
last: Exception | None = None
@@ -92,7 +86,7 @@ def download(destination: Path) -> None:
return
except AssetError:
raise
except (OSError, ValueError) as error: # URLError/HTTPError/timeouts are OSError subclasses
except (OSError, ValueError) as error:
last = error
if attempt < 3:
delay = (3, 6, 12)[attempt]
@@ -100,7 +94,6 @@ def download(destination: Path) -> None:
time.sleep(delay)
raise AssetError(f"Swagger download failed after 4 attempts: {last}")
def _download_once(destination: Path) -> None:
"""TLS verification uses Python's default trust store; never executes a shell."""
started = time.monotonic()
@@ -120,7 +113,6 @@ def _download_once(destination: Path) -> None:
raise AssetError("Swagger download exceeded the size or time limit.")
output.write(block)
def read_assets(path: Path, checksum: str | None) -> tuple[dict[str, bytes], str]:
if not path.is_file() or not 0 < path.stat().st_size <= MAX_ARCHIVE:
raise AssetError("Swagger archive must be a nonempty regular file of at most 64 MiB.")
@@ -148,7 +140,6 @@ def read_assets(path: Path, checksum: str | None) -> tuple[dict[str, bytes], str
mode = (info.external_attr >> 16) & 0o170000
if info.is_dir() or mode not in (0, 0o100000) or not 0 < info.file_size <= limit:
raise AssetError(f"Swagger archive member is not a bounded regular file: {name}.")
# Bounded read as well as metadata validation; CRC checked by ZipFile.
with archive.open(info) as stream:
data = stream.read(limit + 1)
if not 0 < len(data) <= limit or len(data) != info.file_size:
@@ -168,10 +159,9 @@ def read_assets(path: Path, checksum: str | None) -> tuple[dict[str, bytes], str
assets["licenses.txt"] = b"Swagger UI " + VERSION.encode() + b"\n\n" + b"\n\n".join(licenses)
return assets, digest
def atomic_write(path: Path, data: bytes) -> None:
if path.is_file() and path.read_bytes() == data:
return # Preserve mtime for Cargo's rerun-if-changed tracking.
return
fd, name = tempfile.mkstemp(prefix=".swagger-", dir=path.parent)
temporary = Path(name)
try:
@@ -181,7 +171,6 @@ def atomic_write(path: Path, data: bytes) -> None:
finally:
temporary.unlink(missing_ok=True)
def cached_archives(out_dir: Path, cache: Path) -> list[Path]:
"""Previously downloaded copies of the pinned archive.
@@ -203,7 +192,6 @@ def cached_archives(out_dir: Path, cache: Path) -> list[Path]:
candidates.extend(siblings)
return [item for item in dict.fromkeys(candidates) if item != cache and item.is_file()]
def remember_archive(out_dir: Path, cache: Path) -> None:
"""Best-effort copy of a validated archive into the shared cache directory."""
parents = out_dir.parents
@@ -216,7 +204,6 @@ def remember_archive(out_dir: Path, cache: Path) -> None:
except OSError:
pass
def read_vendored() -> tuple[dict[str, bytes], str, Path] | None:
"""Assets vendored in third_party/ (official swagger-ui-dist files); verified against SHA256SUMS.
@@ -250,7 +237,6 @@ def read_vendored() -> tuple[dict[str, bytes], str, Path] | None:
"licenses.txt": b"Swagger UI " + VERSION.encode() + b"\n\n" + b"\n\n".join(licenses)}
return assets, hashlib.sha256(manifest.read_bytes()).hexdigest(), manifest
def prepare(out_dir: Path, source: str | Path, checksum: str | None = None,
*, offline: bool = False) -> list[Path]:
out_dir.mkdir(parents=True, exist_ok=True)
@@ -288,7 +274,7 @@ def prepare(out_dir: Path, source: str | Path, checksum: str | None = None,
try:
download(temporary)
assets, digest = read_assets(temporary, checksum)
os.replace(temporary, cache) # Cache only an already-validated archive.
os.replace(temporary, cache)
finally:
temporary.unlink(missing_ok=True)
remember_archive(out_dir, cache)
@@ -307,11 +293,9 @@ def prepare(out_dir: Path, source: str | Path, checksum: str | None = None,
}
receipt_path = destination / "source.json"
atomic_write(receipt_path, (json.dumps(receipt, indent=2, sort_keys=True) + "\n").encode())
# Watch both a supplied symlink and its resolved target, plus cached/generated files.
inputs = [archive.absolute(), archive.resolve(), *outputs, receipt_path]
return list(dict.fromkeys(inputs))
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--out-dir", required=True, type=Path)
@@ -335,6 +319,5 @@ def main() -> int:
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())