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

-18
View File
@@ -20,7 +20,6 @@ WHITESPACE = " \t\n\r\f"
HEX = "0123456789abcdefABCDEF"
DELIMITERS = frozenset("{};")
def _escape_end(text: str, start: int) -> int:
end = start + 1
if end == len(text):
@@ -36,7 +35,6 @@ def _escape_end(text: str, start: int) -> int:
return end
return end + (2 if text[end:end + 2] == "\r\n" else 1)
def _string_end(text: str, start: int) -> int:
end = start + 1
while end < len(text):
@@ -50,17 +48,13 @@ def _string_end(text: str, start: int) -> int:
end += 1
raise ValueError("Unterminated CSS string")
def _comment_end(text: str, start: int) -> int:
end = text.find("*/", start + 2)
if end < 0:
raise ValueError("Unterminated CSS comment")
return end + 2
def _group_end(text: str, start: int) -> int:
# Do not rewrite anything in functions or attribute selectors. This also
# protects unquoted data URLs and whitespace required by calc()/CSS escapes.
closing = ")" if text[start] == "(" else "]"
is_url = (text[start] == "(" and text[max(0, start - 3):start].lower() == "url"
and (start < 4 or not (text[start - 4].isalnum() or text[start - 4] in "_-")))
@@ -79,11 +73,9 @@ def _group_end(text: str, start: int) -> int:
elif text[end] in ")]" and not is_url:
raise ValueError("Mismatched CSS delimiter")
else:
# In an unquoted url(), /* and square brackets are literal data.
end += 1
raise ValueError(f"Unterminated CSS {text[start]} group")
def minify(text: str) -> str:
"""Conservatively compact a stylesheet without reordering its CSS tokens."""
tokens: list[tuple[str, str]] = []
@@ -119,8 +111,6 @@ def minify(text: str) -> str:
if depth:
raise ValueError("Unterminated CSS rule")
# Source modules must stay independent of runtime imports and encoding
# declarations; all are UTF-8 and are delivered as one embedded response.
for index, token in enumerate(tokens):
if token != ("plain", "@"):
continue
@@ -152,8 +142,6 @@ def minify(text: str) -> str:
if (before and after and before[0] != "space" and after[0] != "space"
and not (before[0] == "plain" and before[1] in DELIMITERS)
and not (after[0] == "plain" and after[1] in DELIMITERS)):
# Retain a token boundary: e.g. --value:foo/**/bar must never
# become the single identifier foobar. No guessed whitespace.
compact.append(("protected", "/**/"))
continue
if kind == "space" and compact and compact[-1][0] == "space":
@@ -173,7 +161,6 @@ def minify(text: str) -> str:
output.append(value)
return "".join(output)
def source_files(root: Path = ROOT) -> list[Path]:
directory = root / CSS_DIRECTORY
manifest = directory / "manifest.json"
@@ -199,7 +186,6 @@ def source_files(root: Path = ROOT) -> list[Path]:
raise ValueError(f"CSS source must be a regular, non-symlink file: {path.name}")
return paths
def bundle(root: Path = ROOT) -> tuple[str, list[Path], int]:
paths = source_files(root)
parts: list[str] = []
@@ -213,7 +199,6 @@ def bundle(root: Path = ROOT) -> tuple[str, list[Path], int]:
raise ValueError(f"{path.name}: {error}") from error
return "\n".join(parts) + "\n", paths, source_bytes
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--root", type=Path, default=ROOT)
@@ -234,8 +219,6 @@ def main() -> int:
if args.cargo:
watched = [root / CSS_DIRECTORY, root / CSS_DIRECTORY / "manifest.json", *paths]
if args.out_dir is not None:
# Cargo must rerun the generator when its cached output is
# removed even if every source module is unchanged.
watched.append(args.out_dir.resolve() / "panel-style.css")
for path in watched:
if any(char in str(path) for char in "\r\n\0"):
@@ -249,6 +232,5 @@ def main() -> int:
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())
+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())