|
1 | | -"""Template catalog listing (stub URL / fixtures).""" |
| 1 | +"""Template catalog fetch and listing.""" |
2 | 2 |
|
3 | 3 | from __future__ import annotations |
4 | 4 |
|
5 | 5 | import json |
| 6 | +import os |
| 7 | +import time |
| 8 | +import urllib.error |
| 9 | +import urllib.request |
6 | 10 | from pathlib import Path |
| 11 | +from typing import Any |
7 | 12 |
|
| 13 | +from create_python_app_core.paths import default_cache_dir, resolve_source |
8 | 14 | from rich.console import Console |
9 | 15 | from rich.table import Table |
10 | 16 |
|
11 | | -console = Console() |
| 17 | +from create_awesome_python_app import __version__ |
| 18 | + |
| 19 | +console = Console(stderr=True) |
| 20 | + |
| 21 | +DEFAULT_CATALOG_URL = ( |
| 22 | + "https://raw.githubusercontent.com/Create-Python-App/cpa-templates/main/templates.json" |
| 23 | +) |
| 24 | +CACHE_TTL_SECONDS = 3600 |
| 25 | +FETCH_TIMEOUT_SECONDS = 10 |
| 26 | +USER_AGENT = f"create-awesome-python-app/{__version__} (https://github.com/Create-Python-App/create-python-app)" |
12 | 27 |
|
13 | 28 | _FIXTURE = ( |
14 | 29 | Path(__file__).resolve().parents[4] / "fixtures" / "catalog" / "templates.json" |
15 | 30 | ) |
16 | 31 |
|
| 32 | +_memory_cache: dict[str, Any] | None = None |
| 33 | +_memory_ts: float = 0.0 |
| 34 | + |
| 35 | + |
| 36 | +def catalog_url() -> str: |
| 37 | + return os.environ.get("CPA_CATALOG_URL", DEFAULT_CATALOG_URL) |
| 38 | + |
| 39 | + |
| 40 | +def catalog_cache_path() -> Path: |
| 41 | + return default_cache_dir() / "catalog" / "templates.json" |
17 | 42 |
|
18 | | -def _load() -> dict: |
| 43 | + |
| 44 | +def _read_json_file(path: Path) -> dict[str, Any]: |
| 45 | + return json.loads(path.read_text(encoding="utf-8")) |
| 46 | + |
| 47 | + |
| 48 | +def _read_fixture() -> dict[str, Any]: |
19 | 49 | if _FIXTURE.is_file(): |
20 | | - return json.loads(_FIXTURE.read_text(encoding="utf-8")) |
21 | | - return { |
22 | | - "templates": [{"slug": "example-cli", "category": "cli", "url": "file://."}], |
23 | | - "addons": [{"slug": "ruff-setup", "category": "tooling"}], |
24 | | - } |
| 50 | + return _read_json_file(_FIXTURE) |
| 51 | + return {"templates": [], "extensions": [], "categories": []} |
| 52 | + |
| 53 | + |
| 54 | +def _read_disk_cache() -> dict[str, Any] | None: |
| 55 | + path = catalog_cache_path() |
| 56 | + if not path.is_file(): |
| 57 | + return None |
| 58 | + try: |
| 59 | + return _read_json_file(path) |
| 60 | + except json.JSONDecodeError: |
| 61 | + return None |
| 62 | + |
| 63 | + |
| 64 | +def _write_disk_cache(data: dict[str, Any]) -> None: |
| 65 | + path = catalog_cache_path() |
| 66 | + path.parent.mkdir(parents=True, exist_ok=True) |
| 67 | + path.write_text(json.dumps(data), encoding="utf-8") |
| 68 | + |
| 69 | + |
| 70 | +def _fetch_file_url(url: str) -> dict[str, Any]: |
| 71 | + source = resolve_source(url) |
| 72 | + if source.local_path is None: |
| 73 | + raise OSError(f"Invalid file catalog URL: {url}") |
| 74 | + base = source.local_path |
| 75 | + if source.subdir: |
| 76 | + base = base / source.subdir |
| 77 | + catalog_file = base / "templates.json" |
| 78 | + if not catalog_file.is_file(): |
| 79 | + raise FileNotFoundError(f"Catalog not found: {catalog_file}") |
| 80 | + return _read_json_file(catalog_file) |
| 81 | + |
| 82 | + |
| 83 | +def _fetch_remote(url: str) -> dict[str, Any]: |
| 84 | + if url.startswith("file://"): |
| 85 | + return _fetch_file_url(url) |
| 86 | + req = urllib.request.Request( |
| 87 | + url, |
| 88 | + headers={"Accept": "application/json", "User-Agent": USER_AGENT}, |
| 89 | + ) |
| 90 | + with urllib.request.urlopen(req, timeout=FETCH_TIMEOUT_SECONDS) as resp: |
| 91 | + payload = resp.read().decode("utf-8") |
| 92 | + return json.loads(payload) |
| 93 | + |
| 94 | + |
| 95 | +def get_catalog_data(*, force_refresh: bool = False) -> dict[str, Any]: |
| 96 | + """Load templates.json from remote URL, disk cache, or local fixture.""" |
| 97 | + global _memory_cache, _memory_ts |
| 98 | + |
| 99 | + if ( |
| 100 | + not force_refresh |
| 101 | + and _memory_cache is not None |
| 102 | + and os.environ.get("CPA_NO_CATALOG_CACHE") != "1" |
| 103 | + and time.time() - _memory_ts <= CACHE_TTL_SECONDS |
| 104 | + ): |
| 105 | + return _memory_cache |
| 106 | + |
| 107 | + if os.environ.get("CPA_CATALOG_FIXTURE") == "1": |
| 108 | + data = _read_fixture() |
| 109 | + else: |
| 110 | + url = catalog_url() |
| 111 | + try: |
| 112 | + data = _fetch_remote(url) |
| 113 | + _write_disk_cache(data) |
| 114 | + except (urllib.error.URLError, TimeoutError, OSError, json.JSONDecodeError) as err: |
| 115 | + disk = _read_disk_cache() |
| 116 | + if disk is not None: |
| 117 | + console.print( |
| 118 | + f"[yellow][cpa] Could not refresh catalog ({err}); using disk cache.[/yellow]" |
| 119 | + ) |
| 120 | + data = disk |
| 121 | + else: |
| 122 | + fixture = _read_fixture() |
| 123 | + if fixture.get("templates"): |
| 124 | + console.print( |
| 125 | + f"[yellow][cpa] Could not refresh catalog ({err}); using fixture.[/yellow]" |
| 126 | + ) |
| 127 | + data = fixture |
| 128 | + else: |
| 129 | + raise RuntimeError(f"Failed to load template catalog: {err}") from err |
| 130 | + |
| 131 | + _memory_cache = data |
| 132 | + _memory_ts = time.time() |
| 133 | + return data |
| 134 | + |
| 135 | + |
| 136 | +def reset_catalog_cache_for_tests() -> None: |
| 137 | + global _memory_cache, _memory_ts |
| 138 | + _memory_cache = None |
| 139 | + _memory_ts = 0.0 |
25 | 140 |
|
26 | 141 |
|
27 | 142 | def list_templates() -> None: |
28 | | - data = _load() |
| 143 | + data = get_catalog_data() |
29 | 144 | table = Table(title="Templates") |
30 | 145 | table.add_column("slug") |
31 | 146 | table.add_column("category") |
| 147 | + table.add_column("type") |
32 | 148 | for t in data.get("templates", []): |
33 | | - table.add_row(t.get("slug", ""), t.get("category", "")) |
| 149 | + table.add_row( |
| 150 | + str(t.get("slug", "")), |
| 151 | + str(t.get("category", "")), |
| 152 | + str(t.get("type", "")), |
| 153 | + ) |
34 | 154 | console.print(table) |
35 | 155 |
|
36 | 156 |
|
37 | 157 | def list_addons(template_slug: str | None = None) -> None: |
38 | | - _ = template_slug |
39 | | - data = _load() |
40 | | - table = Table(title="Addons") |
| 158 | + data = get_catalog_data() |
| 159 | + template_type: str | None = None |
| 160 | + if template_slug: |
| 161 | + for t in data.get("templates", []): |
| 162 | + if t.get("slug") == template_slug: |
| 163 | + template_type = str(t.get("type", "")) |
| 164 | + break |
| 165 | + |
| 166 | + table = Table(title="Extensions") |
41 | 167 | table.add_column("slug") |
42 | 168 | table.add_column("category") |
43 | | - for t in data.get("addons", []): |
44 | | - table.add_row(t.get("slug", ""), t.get("category", "")) |
| 169 | + table.add_column("type") |
| 170 | + for ext in data.get("extensions", data.get("addons", [])): |
| 171 | + ext_types = ext.get("type", []) |
| 172 | + if isinstance(ext_types, str): |
| 173 | + ext_types = [ext_types] |
| 174 | + if template_type and template_type not in ext_types: |
| 175 | + continue |
| 176 | + type_label = ", ".join(ext_types) if isinstance(ext_types, list) else str(ext_types) |
| 177 | + table.add_row( |
| 178 | + str(ext.get("slug", "")), |
| 179 | + str(ext.get("category", "")), |
| 180 | + type_label, |
| 181 | + ) |
45 | 182 | console.print(table) |
0 commit comments