#!/usr/bin/env python3 """Build the browser catalogue from curated EU records and GitHub metadata. GitHub is used for facts it can support: licence metadata, stars, forks, update timestamps, releases, and community-health files. EU stewardship and company adoption remain curated claims with explicit evidence URLs. """ from __future__ import annotations import argparse import hashlib import json import math import os import sys from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path from typing import Any from urllib.error import HTTPError, URLError from urllib.parse import quote from urllib.request import Request, urlopen GITHUB_API = "https://api.github.com" API_VERSION = "2022-11-28" EU_EEA_CODES = { "AT", "BE", "BG", "HR", "CY", "CZ", "DE", "DK", "EE", "EL", "ES", "FI", "FR", "GR", "HU", "IE", "IS", "IT", "LI", "LT", "LU", "LV", "MT", "NL", "NO", "PL", "PT", "RO", "SE", "SI", "SK", } OSI_LICENCES = { "0BSD", "AGPL-3.0", "Apache-2.0", "BSD-2-Clause", "BSD-3-Clause", "EPL-2.0", "EUPL-1.1", "EUPL-1.2", "GPL-2.0", "GPL-3.0", "ISC", "LGPL-2.1", "LGPL-3.0", "MIT", "MPL-2.0", } class CatalogueError(RuntimeError): pass def utc_now() -> datetime: return datetime.now(timezone.utc) def parse_github_time(value: str | None) -> datetime | None: if not value: return None return datetime.fromisoformat(value.replace("Z", "+00:00")) def load_json(path: Path) -> Any: try: return json.loads(path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError) as exc: raise CatalogueError(f"Cannot load {path}: {exc}") from exc def require_https(value: str, label: str) -> None: if not isinstance(value, str) or not value.startswith("https://"): raise CatalogueError(f"{label} must be an https URL") def validate_projects(projects: list[dict[str, Any]]) -> None: ids: set[str] = set() repos: set[str] = set() for index, project in enumerate(projects): label = f"projects[{index}]" for field in ("id", "name", "github", "description", "steward"): if not project.get(field): raise CatalogueError(f"{label}.{field} is required") if project["id"] in ids: raise CatalogueError(f"Duplicate project id: {project['id']}") if project["github"] in repos: raise CatalogueError(f"Duplicate GitHub repository: {project['github']}") if project["github"].count("/") != 1: raise CatalogueError(f"{label}.github must use owner/repository form") ids.add(project["id"]) repos.add(project["github"]) steward = project["steward"] if steward.get("country_code") not in EU_EEA_CODES: raise CatalogueError(f"{label} has no supported EU/EEA steward country") require_https(steward.get("evidence_url", ""), f"{label}.steward.evidence_url") for field in ("tasks", "deployment", "languages", "assurance"): if not isinstance(project.get(field), list) or not project[field]: raise CatalogueError(f"{label}.{field} must be a non-empty list") def validate_champions(champions: list[dict[str, Any]], project_ids: set[str]) -> None: ids: set[str] = set() for index, champion in enumerate(champions): label = f"champions[{index}]" for field in ("id", "company", "country", "sectors", "tasks", "tools", "implementation", "evidence"): if not champion.get(field): raise CatalogueError(f"{label}.{field} is required") if champion["id"] in ids: raise CatalogueError(f"Duplicate champion id: {champion['id']}") ids.add(champion["id"]) unknown = set(champion["tools"]) - project_ids if unknown: raise CatalogueError(f"{label} references unknown tools: {', '.join(sorted(unknown))}") evidence = champion["evidence"] require_https(evidence.get("url", ""), f"{label}.evidence.url") if evidence.get("level") not in {"case_study", "public_reference"}: raise CatalogueError(f"{label}.evidence.level is not supported") @dataclass class ApiResult: data: dict[str, Any] | list[Any] | None stale: bool = False class GitHubClient: def __init__(self, cache_dir: Path, token: str | None = None, offline: bool = False): self.cache_dir = cache_dir self.token = token self.offline = offline self.cache_dir.mkdir(parents=True, exist_ok=True) def _cache_path(self, endpoint: str) -> Path: digest = hashlib.sha256(endpoint.encode("utf-8")).hexdigest() return self.cache_dir / f"{digest}.json" def _cached(self, path: Path) -> dict[str, Any] | None: if not path.exists(): return None cached = load_json(path) return cached if isinstance(cached, dict) else None def get(self, endpoint: str, optional: bool = False) -> ApiResult: cache_path = self._cache_path(endpoint) cached = self._cached(cache_path) if self.offline: if cached is not None: return ApiResult(cached.get("data"), stale=True) if optional: return ApiResult(None, stale=True) raise CatalogueError(f"No cached GitHub response for {endpoint}") headers = { "Accept": "application/vnd.github+json", "User-Agent": "open-eu-commons-catalogue-builder/1.0", "X-GitHub-Api-Version": API_VERSION, } if self.token: headers["Authorization"] = f"Bearer {self.token}" if cached and cached.get("etag"): headers["If-None-Match"] = cached["etag"] request = Request(f"{GITHUB_API}{endpoint}", headers=headers) try: with urlopen(request, timeout=20) as response: data = json.loads(response.read().decode("utf-8")) payload = { "endpoint": endpoint, "etag": response.headers.get("ETag"), "fetched_at": utc_now().isoformat(), "data": data, } cache_path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8") return ApiResult(data) except HTTPError as exc: if exc.code == 304 and cached is not None: return ApiResult(cached.get("data")) if optional and exc.code == 404: cache_path.write_text(json.dumps({ "endpoint": endpoint, "etag": None, "fetched_at": utc_now().isoformat(), "data": None, "not_found": True, }, indent=2) + "\n", encoding="utf-8") return ApiResult(None) if cached is not None: return ApiResult(cached.get("data"), stale=True) raise CatalogueError(f"GitHub returned HTTP {exc.code} for {endpoint}") from exc except (URLError, TimeoutError, json.JSONDecodeError) as exc: if cached is not None: return ApiResult(cached.get("data"), stale=True) raise CatalogueError(f"GitHub request failed for {endpoint}: {exc}") from exc def popularity_score(stars: int) -> int: if stars <= 0: return 0 return min(30, round(6 * math.log10(stars + 1))) def activity_score(pushed_at: str | None, now: datetime) -> tuple[int, int | None]: pushed = parse_github_time(pushed_at) if pushed is None: return 0, None age = max(0, (now - pushed).days) if age <= 30: return 25, age if age <= 90: return 20, age if age <= 180: return 15, age if age <= 365: return 8, age return 0, age def normalize_spdx(value: str | None) -> str | None: if not value or value == "NOASSERTION": return None return value.replace("-only", "").replace("-or-later", "") def score_project( repo: dict[str, Any], community: dict[str, Any] | None, release: dict[str, Any] | None, security_policy: dict[str, Any] | None, now: datetime ) -> tuple[int, str, dict[str, int | None]]: stars = int(repo.get("stargazers_count") or 0) popularity = popularity_score(stars) activity, age_days = activity_score(repo.get("pushed_at"), now) spdx = normalize_spdx((repo.get("license") or {}).get("spdx_id")) licence = 15 if spdx in OSI_LICENCES else 0 security = 10 if security_policy else 0 releases = 10 if release else 0 health = int((community or {}).get("health_percentage") or 0) community_points = min(10, round(health / 10)) score = popularity + activity + licence + security + releases + community_points if repo.get("archived"): status = "archived" score = min(score, 20) elif not licence: status = "licence-review" elif age_days is None or age_days > 365: status = "maintenance-review" elif not security: status = "assurance-review" else: status = "verified" breakdown: dict[str, int | None] = { "popularity": popularity, "activity": activity, "licence": licence, "security": security, "release": releases, "community": community_points, "last_push_age_days": age_days, } return score, status, breakdown def find_security_policy(client: GitHubClient, repository: str) -> tuple[dict[str, Any] | None, bool]: """Find a repository-level policy without treating generic security docs as one.""" stale = False for path in ("SECURITY.md", ".github/SECURITY.md", "docs/SECURITY.md"): result = client.get(f"/repos/{repository}/contents/{path}", optional=True) stale = stale or result.stale if isinstance(result.data, dict): return result.data, stale return None, stale def enrich_project(project: dict[str, Any], client: GitHubClient, now: datetime) -> dict[str, Any]: repository = project["github"] repo_result = client.get(f"/repos/{repository}") community_result = client.get(f"/repos/{repository}/community/profile", optional=True) release_result = client.get(f"/repos/{repository}/releases/latest", optional=True) security_policy, security_stale = find_security_policy(client, repository) repo = repo_result.data if not isinstance(repo, dict): raise CatalogueError(f"Unexpected repository response for {repository}") community = community_result.data if isinstance(community_result.data, dict) else None release = release_result.data if isinstance(release_result.data, dict) else None score, status, breakdown = score_project(repo, community, release, security_policy, now) spdx = normalize_spdx((repo.get("license") or {}).get("spdx_id")) return { **project, "task": project["tasks"][0], "licence": spdx or "Review required", "maturity": { "verified": "Verified active project", "assurance-review": "Security evidence review", "maintenance-review": "Maintenance review", "licence-review": "Licence review", "archived": "Archived project", }[status], "verification": { "status": status, "score": score, "breakdown": breakdown, "reviewed_at": now.date().isoformat(), }, "github_metrics": { "repository": repository, "url": repo.get("html_url"), "stars": int(repo.get("stargazers_count") or 0), "forks": int(repo.get("forks_count") or 0), "open_issues": int(repo.get("open_issues_count") or 0), "last_push": repo.get("pushed_at"), "latest_release": (release or {}).get("tag_name"), "latest_release_at": (release or {}).get("published_at"), "community_health": int((community or {}).get("health_percentage") or 0), "has_security_policy": bool(security_policy), "security_policy_url": (security_policy or {}).get("html_url"), "archived": bool(repo.get("archived")), "metadata_stale": repo_result.stale or community_result.stale or release_result.stale or security_stale, }, "sources": [ {"claim": "repository metadata", "url": repo.get("html_url")}, {"claim": "EU/EEA stewardship", "url": project["steward"]["evidence_url"]}, ] + ([{"claim": "security policy", "url": security_policy.get("html_url")}] if security_policy else []), } def discover_candidates( projects: list[dict[str, Any]], client: GitHubClient, per_organization: int = 5 ) -> tuple[list[dict[str, Any]], list[dict[str, str]]]: """Find popular repositories from already verified European steward organizations. Results form an editorial queue only. They are never promoted to the public catalogue without task/deployment classification and legal-steward review. """ existing = {project["github"].lower() for project in projects} organizations: dict[str, dict[str, Any]] = {} for project in projects: owner = project["github"].split("/", 1)[0] organizations.setdefault(owner, project["steward"]) candidates: list[dict[str, Any]] = [] errors: list[dict[str, str]] = [] for owner, steward in organizations.items(): query = quote(f"org:{owner} archived:false fork:false") endpoint = f"/search/repositories?q={query}&sort=stars&order=desc&per_page={per_organization}" try: result = client.get(endpoint) payload = result.data if not isinstance(payload, dict) or not isinstance(payload.get("items"), list): raise CatalogueError(f"Unexpected repository search response for {owner}") for repo in payload["items"]: full_name = repo.get("full_name") if not full_name or full_name.lower() in existing: continue candidates.append({ "github": full_name, "name": repo.get("name"), "description": repo.get("description"), "url": repo.get("html_url"), "stars": int(repo.get("stargazers_count") or 0), "licence": normalize_spdx((repo.get("license") or {}).get("spdx_id")), "last_push": repo.get("pushed_at"), "steward": steward, "metadata_stale": result.stale, "status": "editorial-review", "reason": "Popular repository under a reviewed European steward organization", }) except CatalogueError as exc: errors.append({"organization": owner, "error": str(exc)}) candidates.sort(key=lambda item: (-item["stars"], item["github"].lower())) return candidates, errors def build_catalogue( projects: list[dict[str, Any]], champions: list[dict[str, Any]], client: GitHubClient, now: datetime ) -> dict[str, Any]: validate_projects(projects) project_ids = {project["id"] for project in projects} validate_champions(champions, project_ids) enriched: list[dict[str, Any]] = [] errors: list[dict[str, str]] = [] for project in projects: try: enriched.append(enrich_project(project, client, now)) except CatalogueError as exc: errors.append({"project": project["id"], "error": str(exc)}) enriched.sort(key=lambda item: (-item["verification"]["score"], item["name"].lower())) reviewed_at = now.date().isoformat() sourced_champions = [ {**champion, "verification": {"status": "source-backed", "reviewed_at": reviewed_at}} for champion in champions ] verified_count = sum(item["verification"]["status"] == "verified" for item in enriched) return { "schema_version": 1, "generated_at": now.isoformat(), "methodology": { "repository_signals": "GitHub REST API metadata, releases, licence, and community profile", "eu_eligibility": "Curated EU/EEA steward legal-entity evidence", "champions": "Named public case study or implementation reference; vendor claims are labelled by evidence level", "warning": "Stars indicate reach, not fitness, security, or procurement readiness.", }, "summary": { "projects": len(enriched), "verified_projects": verified_count, "champions": len(sourced_champions), "failed_projects": len(errors), }, "projects": enriched, "champions": sourced_champions, "errors": errors, } def parse_args(argv: list[str] | None = None) -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--projects", type=Path, default=Path("config/projects.json")) parser.add_argument("--champions", type=Path, default=Path("config/champions.json")) parser.add_argument("--output", type=Path, default=Path("public/data/catalogue.json")) parser.add_argument("--cache", type=Path, default=Path(".cache/github")) parser.add_argument("--offline", action="store_true", help="Use cached GitHub responses only") parser.add_argument("--skip-discovery", action="store_true", help="Do not refresh the editorial candidate queue") parser.add_argument("--strict", action="store_true", help="Fail if any project could not be enriched") return parser.parse_args(argv) def main(argv: list[str] | None = None) -> int: args = parse_args(argv) try: projects = load_json(args.projects) champions = load_json(args.champions) if not isinstance(projects, list) or not isinstance(champions, list): raise CatalogueError("Project and champion configuration must be JSON arrays") client = GitHubClient(args.cache, token=os.environ.get("GITHUB_TOKEN"), offline=args.offline) catalogue = build_catalogue(projects, champions, client, utc_now()) if args.skip_discovery: candidates, discovery_errors = [], [] else: candidates, discovery_errors = discover_candidates(projects, client) catalogue["candidates"] = candidates catalogue["discovery_errors"] = discovery_errors catalogue["summary"]["discovery_candidates"] = len(candidates) args.output.parent.mkdir(parents=True, exist_ok=True) args.output.write_text(json.dumps(catalogue, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") print( f"Wrote {len(catalogue['projects'])} projects and " f"{len(catalogue['champions'])} champions to {args.output}" ) if args.strict and (catalogue["errors"] or discovery_errors): for error in catalogue["errors"]: print(f"ERROR {error['project']}: {error['error']}", file=sys.stderr) for error in discovery_errors: print(f"ERROR {error['organization']}: {error['error']}", file=sys.stderr) return 1 return 0 except CatalogueError as exc: print(f"ERROR: {exc}", file=sys.stderr) return 2 if __name__ == "__main__": raise SystemExit(main())