Source code for s365b.core.third_party

"""The open-source Python packages this server runs with, read where it runs.

Walks the installed ``mailsafehouse`` distribution's runtime requirements
(extras included) through ``importlib.metadata``, so the About page shows
the versions actually in the image, not those of a developer's machine.
Each package's own licence file is installed with it.
"""

from __future__ import annotations

import functools
import re
from importlib import metadata
from typing import Any

from packaging.requirements import Requirement

[docs] DISTRIBUTION = "mailsafehouse"
# Trove classifier names as SPDX identifiers, for one style throughout.
[docs] SPDX = { "MIT License": "MIT", "Apache Software License": "Apache-2.0", "BSD License": "BSD", "ISC License (ISCL)": "ISC", "Mozilla Public License 2.0 (MPL 2.0)": "MPL-2.0", "Python Software Foundation License": "PSF-2.0", }
def _norm(name: str) -> str: return re.sub(r"[-_.]+", "-", name).lower() def _license(md: Any) -> str: if expr := md.get("License-Expression"): return str(expr) classifiers = [ c.split(" :: ")[-1] for c in md.get_all("Classifier") or [] if c.startswith("License :: OSI Approved ::") ] if classifiers: return " OR ".join(SPDX.get(c, c) for c in classifiers) text = str(md.get("License") or "").strip() return SPDX.get(text, text.splitlines()[0][:60]) if text else "see package" def _url(md: Any, name: str) -> str: for entry in md.get_all("Project-URL") or []: label, _, url = entry.partition(",") if label.strip().lower() in ("homepage", "home", "source", "repository", "source code"): return str(url).strip() return str(md.get("Home-page") or f"https://pypi.org/project/{name}/") @functools.cache
[docs] def server_packages() -> list[dict[str, str]]: """Every Python package the server needs to run, with its licence. Returns: Entries with ``name``, ``version``, ``license``, ``url`` and ``part`` (``"server"``), sorted by name; empty if the server is not installed as a package (e.g. run from a source tree). """ out: dict[str, dict[str, str]] = {} todo: list[tuple[str, frozenset[str]]] = [(DISTRIBUTION, frozenset())] done: set[tuple[str, frozenset[str]]] = set() while todo: name, extras = todo.pop() if (_norm(name), extras) in done: continue done.add((_norm(name), extras)) try: dist = metadata.distribution(name) except metadata.PackageNotFoundError: continue # only for another platform md = dist.metadata if _norm(name) != DISTRIBUTION: out[_norm(name)] = { "name": str(md["Name"]), "version": dist.version, "license": _license(md), "url": _url(md, str(md["Name"])), "part": "server", } for raw in dist.requires or []: req = Requirement(raw) envs = [{"extra": e} for e in extras] or [{"extra": ""}] if req.marker is None or any(req.marker.evaluate(env) for env in envs): todo.append((req.name, frozenset(req.extras))) return sorted(out.values(), key=lambda p: p["name"].lower())