itqan-cli 0.1.0rc1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
itqan_cli/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """Itqan Package Manager CLI."""
itqan_cli/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Allow `python -m itqan_cli`."""
2
+
3
+ from itqan_cli.main import cli
4
+
5
+ cli()
itqan_cli/client.py ADDED
@@ -0,0 +1,233 @@
1
+ """Package Registry HTTP client for resolving manifests and obtaining download URLs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from importlib.metadata import PackageNotFoundError, version
7
+
8
+ import requests
9
+
10
+ from itqan_cli.exceptions import RegistryApiError
11
+
12
+
13
+ @dataclass(frozen=True, slots=True)
14
+ class ResolvedAssetPayload:
15
+ slug: str
16
+ asset_version_id: int
17
+ resolved_version: str
18
+ asset_name: str
19
+ download_url: str | None
20
+ publisher_id: int | None = None
21
+ publisher_name: str | None = None
22
+ name: str = ""
23
+ language: str | None = None
24
+
25
+ @property
26
+ def entry_name(self) -> str:
27
+ """The manifest entry this result answers (the slug unless the entry set `asset`)."""
28
+ return self.name or self.slug
29
+
30
+
31
+ @dataclass(frozen=True, slots=True)
32
+ class CatalogLanguage:
33
+ language: str
34
+ is_source: bool
35
+ latest_version: str
36
+
37
+
38
+ @dataclass(frozen=True, slots=True)
39
+ class CatalogPackage:
40
+ """One installable asset from GET /packages/."""
41
+
42
+ slug: str
43
+ name: str
44
+ category: str
45
+ is_open_access: bool
46
+ languages: tuple[CatalogLanguage, ...]
47
+ publisher_name: str | None = None
48
+
49
+
50
+ # The public API (not the cms.itqan.dev website, which serves the web app).
51
+ DEFAULT_REGISTRY_URL = "https://api.cms.itqan.dev"
52
+
53
+
54
+ def _cli_version() -> str:
55
+ try:
56
+ return version("itqan-cli")
57
+ except PackageNotFoundError: # running from a source checkout that isn't installed
58
+ return "unknown"
59
+
60
+
61
+ class RegistryClient:
62
+ """HTTP Client for Itqan Package Registry API."""
63
+
64
+ def __init__(
65
+ self,
66
+ base_url: str = DEFAULT_REGISTRY_URL,
67
+ api_key: str | None = None,
68
+ timeout: float = 30.0,
69
+ session: requests.Session | None = None,
70
+ ) -> None:
71
+ self.base_url = base_url.rstrip("/")
72
+ self.api_key = api_key
73
+ self.timeout = timeout
74
+ self.session = session or requests.Session()
75
+
76
+ # Security: reject HTTP for non-loopback URLs when an API key is provided.
77
+ # Sending an API key over plain HTTP exposes it to network eavesdroppers.
78
+ if api_key:
79
+ parsed = __import__("urllib.parse", fromlist=["urlparse"]).urlparse(self.base_url)
80
+ is_loopback = parsed.hostname in ("localhost", "127.0.0.1", "::1")
81
+ if parsed.scheme == "http" and not is_loopback:
82
+ raise RegistryApiError(
83
+ "Refusing to send API key over an insecure HTTP connection. "
84
+ "Use HTTPS or a loopback address for development."
85
+ )
86
+
87
+ def _headers(self) -> dict[str, str]:
88
+ headers = {
89
+ "Accept": "application/json",
90
+ "Content-Type": "application/json",
91
+ "User-Agent": f"itqan-cli/{_cli_version()}",
92
+ }
93
+ if self.api_key:
94
+ headers["X-API-Key"] = self.api_key
95
+ return headers
96
+
97
+ def list_packages(self, *, open_access: bool | None = None, page_size: int = 50) -> list[CatalogPackage]:
98
+ """Call GET /packages/ for the first page of installable assets.
99
+
100
+ Raises:
101
+ RegistryApiError when the registry can't be reached or answers badly.
102
+ """
103
+ params: dict[str, str] = {"page_size": str(page_size)}
104
+ if open_access is not None:
105
+ params["open_access"] = "true" if open_access else "false"
106
+ try:
107
+ response = self.session.get(
108
+ f"{self.base_url}/packages/", params=params, headers=self._headers(), timeout=self.timeout
109
+ )
110
+ except requests.RequestException as exc:
111
+ raise RegistryApiError(f"Failed to connect to package registry at {self.base_url}: {exc}") from exc
112
+ if response.status_code != 200:
113
+ raise RegistryApiError(
114
+ f"Registry catalog request failed with status {response.status_code}",
115
+ status_code=response.status_code,
116
+ )
117
+ try:
118
+ return [
119
+ CatalogPackage(
120
+ slug=item["slug"],
121
+ name=item["name"],
122
+ category=item["category"],
123
+ is_open_access=item["is_open_access"],
124
+ publisher_name=item.get("publisher_name"),
125
+ languages=tuple(
126
+ CatalogLanguage(
127
+ language=lang["language"],
128
+ is_source=lang["is_source"],
129
+ latest_version=lang["latest_version"],
130
+ )
131
+ for lang in item["languages"]
132
+ ),
133
+ )
134
+ for item in response.json()["results"]
135
+ ]
136
+ except (ValueError, KeyError, TypeError) as exc:
137
+ raise RegistryApiError(f"Failed to parse registry catalog response: {exc}") from exc
138
+
139
+ def resolve_manifest(self, assets: dict[str, str | dict[str, str]]) -> list[ResolvedAssetPayload]:
140
+ """Call POST /packages/resolve/manifest/ to resolve manifest constraints.
141
+
142
+ Args:
143
+ assets: dict of entry name -> constraint string (e.g. {"quran": "^2.1.0"}),
144
+ or -> request object ({"version": ..., "asset": ..., "language": ...})
145
+
146
+ Returns:
147
+ list of ResolvedAssetPayload
148
+
149
+ Raises:
150
+ RegistryApiError on any failure.
151
+ """
152
+ url = f"{self.base_url}/packages/resolve/manifest/"
153
+ payload = {"assets": assets}
154
+
155
+ try:
156
+ response = self.session.post(
157
+ url,
158
+ json=payload,
159
+ headers=self._headers(),
160
+ timeout=self.timeout,
161
+ )
162
+ except requests.RequestException as exc:
163
+ raise RegistryApiError(f"Failed to connect to package registry at {self.base_url}: {exc}") from exc
164
+
165
+ if response.status_code == 200:
166
+ try:
167
+ data = response.json()
168
+ # Require "results" to be explicitly present as a list.
169
+ # A missing key means the response is malformed — do not silently
170
+ # continue with zero assets, as that would allow _run_install to
171
+ # report success while writing an empty lockfile.
172
+ if "results" not in data or not isinstance(data["results"], list):
173
+ raise RegistryApiError(
174
+ "Registry returned a 200 response but 'results' field is missing or not a list. "
175
+ "Cannot proceed with installation."
176
+ )
177
+ results_raw = data["results"]
178
+ requested_slugs = set(assets.keys())
179
+ returned_slugs = {item.get("name") or item["slug"] for item in results_raw if isinstance(item, dict)}
180
+ missing = requested_slugs - returned_slugs
181
+ if missing:
182
+ raise RegistryApiError(
183
+ f"Registry resolved {len(returned_slugs)} of {len(requested_slugs)} requested assets. "
184
+ f"Missing: {', '.join(sorted(missing))}"
185
+ )
186
+ return [
187
+ ResolvedAssetPayload(
188
+ slug=item["slug"],
189
+ asset_version_id=item["asset_version_id"],
190
+ resolved_version=item["resolved_version"],
191
+ asset_name=item["asset_name"],
192
+ download_url=item.get("download_url"),
193
+ publisher_id=item.get("publisher_id"),
194
+ publisher_name=item.get("publisher_name"),
195
+ name=item.get("name") or item["slug"],
196
+ language=item.get("language"),
197
+ )
198
+ for item in results_raw
199
+ ]
200
+ except RegistryApiError:
201
+ raise
202
+ except Exception as exc:
203
+ raise RegistryApiError(f"Failed to parse registry API response: {exc}") from exc
204
+
205
+ # Handle API Error responses
206
+ status_code = response.status_code
207
+ error_name: str | None = None
208
+ message = f"Registry request failed with status {status_code}"
209
+
210
+ try:
211
+ err_data = response.json()
212
+ if isinstance(err_data, dict):
213
+ error_name = err_data.get("error_name") or err_data.get("error")
214
+ message = err_data.get("message") or err_data.get("detail") or message
215
+ except Exception:
216
+ message = response.text or message
217
+
218
+ if status_code == 401:
219
+ friendly_msg = f"Authentication required (API key missing or invalid): {message}"
220
+ elif status_code == 403:
221
+ friendly_msg = f"Access denied for requested assets (license required): {message}"
222
+ elif status_code == 404:
223
+ friendly_msg = f"Asset or version not found in registry: {message}"
224
+ elif status_code == 422:
225
+ friendly_msg = f"Cannot satisfy version constraints: {message}"
226
+ else:
227
+ friendly_msg = f"Registry API error [{status_code}]: {message}"
228
+
229
+ raise RegistryApiError(
230
+ friendly_msg,
231
+ status_code=status_code,
232
+ error_name=error_name,
233
+ )
@@ -0,0 +1,220 @@
1
+ """Downloader and artifact materializer ensuring idempotency and atomic writes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ import os
7
+ from pathlib import Path
8
+ import tempfile
9
+ import urllib.parse
10
+
11
+ import requests
12
+
13
+ from itqan_cli.client import ResolvedAssetPayload
14
+ from itqan_cli.exceptions import DownloadError
15
+
16
+ # The version marker filename is reserved — a download URL must never produce
17
+ # a basename matching this name, or it would silently overwrite version metadata.
18
+ _RESERVED_FILENAME = ".itqan_version"
19
+
20
+
21
+ def _validate_slug(slug: str) -> None:
22
+ """Reject slugs that could escape the assets directory via path traversal.
23
+
24
+ A valid slug is a single path component with no separators or traversal
25
+ sequences. Examples that are rejected: '../etc', 'foo/bar', 'a\\b'.
26
+
27
+ Why this matters: if asset.slug came from an untrusted source and contained
28
+ '../../../etc/passwd', the path join `assets_dir / slug` would resolve
29
+ outside the assets directory, allowing arbitrary file writes on the system.
30
+ """
31
+ if not slug or not slug.strip():
32
+ raise DownloadError("Asset slug cannot be empty.")
33
+ # Reject any separator or traversal component
34
+ forbidden = {"/", "\\", ".."}
35
+ for part in forbidden:
36
+ if part in slug:
37
+ raise DownloadError(
38
+ f"Asset slug '{slug}' contains forbidden path component '{part}'. "
39
+ "Slugs must be single safe path components."
40
+ )
41
+ # Path(slug).name must equal slug — catches edge cases like 'a/b' on Windows
42
+ if Path(slug).name != slug:
43
+ raise DownloadError(f"Asset slug '{slug}' is not a safe single path component.")
44
+
45
+
46
+ def _validate_download_url(url: str, slug: str) -> None:
47
+ """Reject non-HTTPS download URLs for non-loopback hosts.
48
+
49
+ Why this matters: downloading over HTTP exposes the artifact to
50
+ man-in-the-middle attacks — an attacker on the network could replace
51
+ the downloaded file with malicious content before it reaches the disk.
52
+ Loopback addresses (localhost, 127.x.x.x) are allowed for development.
53
+ """
54
+ parsed = urllib.parse.urlparse(url)
55
+ is_loopback = parsed.hostname in ("localhost", "127.0.0.1", "::1") or (
56
+ parsed.hostname is not None and parsed.hostname.startswith("127.")
57
+ )
58
+ if parsed.scheme == "http" and not is_loopback:
59
+ raise DownloadError(
60
+ f"Refusing to download asset '{slug}' over insecure HTTP from {url}. "
61
+ "Use HTTPS or a loopback address for development."
62
+ )
63
+
64
+
65
+ @dataclass(frozen=True, slots=True)
66
+ class DownloadResult:
67
+ slug: str
68
+ version: str
69
+ target_path: Path
70
+ downloaded: bool
71
+ size_bytes: int
72
+
73
+
74
+ class AssetDownloader:
75
+ """Handles streaming download and atomic materialization of asset packages."""
76
+
77
+ def __init__(
78
+ self,
79
+ assets_dir: Path | str = "assets",
80
+ session: requests.Session | None = None,
81
+ timeout: float = 60.0,
82
+ ) -> None:
83
+ self.assets_dir = Path(assets_dir)
84
+ self.session = session or requests.Session()
85
+ self.timeout = timeout
86
+
87
+ def _determine_target_file(self, asset: ResolvedAssetPayload, target_dir: Path) -> Path:
88
+ """Derive filename from download_url or fall back to slug.pkg.
89
+
90
+ The reserved filename '.itqan_version' is rejected — if a URL's basename
91
+ collides with the version marker we use internally, it would silently
92
+ overwrite version metadata and break idempotency checks.
93
+ """
94
+ if asset.download_url:
95
+ parsed = urllib.parse.urlparse(asset.download_url)
96
+ filename = Path(parsed.path).name
97
+ if filename:
98
+ if filename == _RESERVED_FILENAME:
99
+ raise DownloadError(
100
+ f"Download URL for asset '{asset.slug}' has a reserved filename "
101
+ f"'{_RESERVED_FILENAME}'. This name is used internally by the CLI."
102
+ )
103
+ return target_dir / filename
104
+ return target_dir / f"{asset.slug}.pkg"
105
+
106
+ def materialize_asset(
107
+ self,
108
+ asset: ResolvedAssetPayload,
109
+ *,
110
+ force: bool = False,
111
+ ) -> DownloadResult:
112
+ """Materialize a single resolved asset into the assets/<entry name>/ folder.
113
+
114
+ The folder is named after the manifest entry, so two languages of one
115
+ asset (two entries) install side by side.
116
+
117
+ Ensures:
118
+ - Safety: slug is validated against path traversal before any I/O.
119
+ - Idempotency: skip if already present and non-empty.
120
+ - Atomicity: stream to temp file and rename upon success.
121
+ - Marker atomicity: version marker is staged as a temp file then
122
+ renamed — both the artifact and its marker are committed together
123
+ so a power loss between the two writes cannot leave a stale marker.
124
+ """
125
+ # --- Safety: validate slug before any path join ---
126
+ _validate_slug(asset.entry_name)
127
+
128
+ slug_dir = self.assets_dir / asset.entry_name
129
+ slug_dir.mkdir(parents=True, exist_ok=True)
130
+
131
+ target_file = self._determine_target_file(asset, slug_dir)
132
+
133
+ # Version marker file to ensure version integrity
134
+ version_marker = slug_dir / _RESERVED_FILENAME
135
+
136
+ # Idempotency check: if target file and matching version marker exist
137
+ if not force and target_file.is_file() and target_file.stat().st_size > 0:
138
+ if (
139
+ version_marker.is_file()
140
+ and version_marker.read_text(encoding="utf-8").strip() == asset.resolved_version
141
+ ):
142
+ return DownloadResult(
143
+ slug=asset.entry_name,
144
+ version=asset.resolved_version,
145
+ target_path=target_file,
146
+ downloaded=False,
147
+ size_bytes=target_file.stat().st_size,
148
+ )
149
+
150
+ if not asset.download_url:
151
+ raise DownloadError(
152
+ f"Asset '{asset.slug}' (version {asset.resolved_version}) has no download URL in the catalog."
153
+ )
154
+
155
+ # --- Security: validate download URL before connecting ---
156
+ _validate_download_url(asset.download_url, asset.slug)
157
+
158
+ # Download atomically to a temporary file in the same filesystem
159
+ temp_fd, temp_path_str = tempfile.mkstemp(
160
+ prefix=f"{asset.slug}_",
161
+ suffix=".tmp",
162
+ dir=slug_dir,
163
+ )
164
+ temp_file = Path(temp_path_str)
165
+
166
+ # Also stage the version marker as a temp file so both are committed
167
+ # in a single rename sequence — prevents a torn state if the process
168
+ # dies between writing the artifact and writing the marker.
169
+ marker_fd, marker_tmp_str = tempfile.mkstemp(
170
+ prefix=".itqan_version_",
171
+ suffix=".tmp",
172
+ dir=slug_dir,
173
+ )
174
+ # Close the marker fd immediately — we will re-open it for writing
175
+ # inside the try block. Keeping it open here would prevent deletion
176
+ # on Windows if an exception occurs before we reach the cleanup block.
177
+ os.close(marker_fd)
178
+ marker_tmp = Path(marker_tmp_str)
179
+
180
+ try:
181
+ with open(temp_fd, "wb") as f_out:
182
+ with self.session.get(asset.download_url, stream=True, timeout=self.timeout) as resp:
183
+ if resp.status_code != 200:
184
+ raise DownloadError(
185
+ f"Failed to download '{asset.slug}' from {asset.download_url}: HTTP {resp.status_code}"
186
+ )
187
+ for chunk in resp.iter_content(chunk_size=65536):
188
+ if chunk:
189
+ f_out.write(chunk)
190
+
191
+ # Write version string to the staged marker tmp file
192
+ marker_tmp.write_text(asset.resolved_version, encoding="utf-8")
193
+
194
+ # Atomically promote both: marker first, then artifact.
195
+ # os.replace() is atomic on POSIX and best-effort on Windows.
196
+ # If the artifact rename fails the marker is already in place, but
197
+ # the idempotency check requires BOTH to exist and match, so the
198
+ # next run will re-download correctly.
199
+ os.replace(marker_tmp, version_marker)
200
+ os.replace(temp_file, target_file)
201
+
202
+ return DownloadResult(
203
+ slug=asset.entry_name,
204
+ version=asset.resolved_version,
205
+ target_path=target_file,
206
+ downloaded=True,
207
+ size_bytes=target_file.stat().st_size,
208
+ )
209
+
210
+ except Exception as exc:
211
+ # Clean up temp files on failure — never leave partial artifacts
212
+ for tmp in (temp_file, marker_tmp):
213
+ try:
214
+ if tmp.exists():
215
+ tmp.unlink()
216
+ except OSError:
217
+ pass
218
+ if isinstance(exc, DownloadError):
219
+ raise
220
+ raise DownloadError(f"Error downloading asset '{asset.slug}': {exc}") from exc
@@ -0,0 +1,69 @@
1
+ """CLI exceptions adhering to docs/ASSET_MANIFEST.md error taxonomy."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class ItqanCliError(Exception):
7
+ """Base exception for all Itqan CLI errors."""
8
+
9
+ def __init__(self, message: str, *, exit_code: int = 1) -> None:
10
+ super().__init__(message)
11
+ self.message = message
12
+ self.exit_code = exit_code
13
+
14
+
15
+ class ManifestError(ItqanCliError):
16
+ """Base exception for manifest parsing/validation failures."""
17
+
18
+
19
+ class UnsupportedSchemaVersionError(ManifestError):
20
+ """schema_version is missing or not 1."""
21
+
22
+
23
+ class YamlProfileViolationError(ManifestError):
24
+ """YAML violates the strict profile (BOM, duplicate keys, multiple docs, etc.)."""
25
+
26
+
27
+ class ScalarShorthandEntryError(ManifestError):
28
+ """An entry under assets is a scalar instead of a mapping."""
29
+
30
+
31
+ class NonStringAssetKeyError(ManifestError):
32
+ """An asset key resolves to a non-string scalar (bool, int, float)."""
33
+
34
+
35
+ class UnknownFieldError(ManifestError):
36
+ """Any key outside the accepted schema."""
37
+
38
+
39
+ class MissingRequiredFieldError(ManifestError):
40
+ """An entry has no required 'version' field."""
41
+
42
+
43
+ class InvalidConstraintSyntaxError(ManifestError):
44
+ """Constraint string violates the SemVer grammar."""
45
+
46
+
47
+ class DuplicateAssetEntryError(ManifestError):
48
+ """Two entries name the same asset and language."""
49
+
50
+
51
+ class LockfileError(ItqanCliError):
52
+ """Base exception for lockfile operations."""
53
+
54
+
55
+ class LockfileStateError(LockfileError):
56
+ """Lockfile is in an unexpected or invalid state."""
57
+
58
+
59
+ class RegistryApiError(ItqanCliError):
60
+ """Error communicating with the Package Registry API."""
61
+
62
+ def __init__(self, message: str, *, status_code: int | None = None, error_name: str | None = None) -> None:
63
+ super().__init__(message)
64
+ self.status_code = status_code
65
+ self.error_name = error_name
66
+
67
+
68
+ class DownloadError(ItqanCliError):
69
+ """Error downloading or verifying an asset artifact."""
@@ -0,0 +1,109 @@
1
+ """Text of the starter itqan-assets.yaml written by `itqan init`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+
7
+ from itqan_cli.client import CatalogLanguage, CatalogPackage
8
+ from itqan_cli.semver import parse_semver
9
+
10
+ SAMPLE_COUNT = 3
11
+
12
+ _HEADER = """\
13
+ # Itqan assets manifest: the Quranic data this project uses.
14
+ # Spec: https://github.com/Itqan-community/cms-backend/blob/main/docs/ASSET_MANIFEST.md
15
+ #
16
+ # After editing, run `itqan install` to download the assets and write
17
+ # itqan-assets.lock. Commit both files.
18
+
19
+ schema_version: 1
20
+
21
+ # Folder the assets are downloaded into, relative to this file.
22
+ assets_dir: {assets_dir}
23
+
24
+ # Each entry is a name (the asset's slug, unless the entry sets `asset`) and a
25
+ # version range:
26
+ # "^1.2.0" any 1.x from 1.2.0 on "~1.2" any 1.2.x "1.2.0" exactly 1.2.0
27
+ #
28
+ # Languages: an entry installs the asset's source language. Add
29
+ # `language: <code>` to install another one. To install several languages of
30
+ # the same asset, give each its own entry and point it at the asset with
31
+ # `asset: <slug>`. Each language has its own version history.
32
+ assets:
33
+ """
34
+
35
+ _FALLBACK_ENTRIES = """\
36
+ # {reason} so these are examples: replace the slugs with real ones
37
+ # from the asset library at https://cms.itqan.dev, then uncomment.
38
+ #
39
+ # "tafsir-example":
40
+ # version: "^1.0.0"
41
+ #
42
+ # The same asset in English:
43
+ # "tafsir-example-en":
44
+ # asset: "tafsir-example"
45
+ # language: "en"
46
+ # version: "^1.0.0"
47
+ """
48
+
49
+
50
+ def _quote(value: str) -> str:
51
+ """YAML double-quoted scalar; slugs like `true` or `123` must stay strings."""
52
+ return json.dumps(value, ensure_ascii=False)
53
+
54
+
55
+ def _constraint(version: str) -> str:
56
+ """`^latest`, except a prerelease, which only an exact pin can select."""
57
+ semver = parse_semver(version)
58
+ return version if semver is not None and semver.prerelease is not None else f"^{version}"
59
+
60
+
61
+ def _describe(language: CatalogLanguage) -> str:
62
+ if not language.language: # an asset whose source language code was never set
63
+ return f"source ({language.latest_version})"
64
+ source = "source, " if language.is_source else ""
65
+ return f"{language.language} ({source}{language.latest_version})"
66
+
67
+
68
+ def _entry(name: str, version: str, *, asset: str | None = None, language: str | None = None) -> list[str]:
69
+ lines = [f" {_quote(name)}:"]
70
+ if asset is not None:
71
+ lines.append(f" asset: {_quote(asset)}")
72
+ if language is not None:
73
+ lines.append(f" language: {_quote(language)}")
74
+ lines.append(f" version: {_quote(_constraint(version))}")
75
+ return lines
76
+
77
+
78
+ def pick_samples(packages: list[CatalogPackage], count: int = SAMPLE_COUNT) -> list[CatalogPackage]:
79
+ """Up to ``count`` packages, leading with one that has several languages so
80
+ the starter file shows a second-language entry."""
81
+ usable = [package for package in packages if package.languages]
82
+ multilingual = next((package for package in usable if len(package.languages) > 1), None)
83
+ ordered = ([multilingual] if multilingual else []) + [package for package in usable if package is not multilingual]
84
+ return ordered[:count]
85
+
86
+
87
+ def render_from_catalog(samples: list[CatalogPackage], assets_dir: str) -> str:
88
+ lines: list[str] = []
89
+ names: set[str] = set()
90
+ for package in samples:
91
+ if lines:
92
+ lines.append("")
93
+ name = " ".join(package.name.split()) # one line, even if the name has newlines
94
+ lines.append(f" # {name} — languages: {', '.join(_describe(lang) for lang in package.languages)}")
95
+ source = next((lang for lang in package.languages if lang.is_source), None)
96
+ first = source or package.languages[0]
97
+ lines += _entry(package.slug, first.latest_version, language=None if source else first.language)
98
+ names.add(package.slug)
99
+ other = next((lang for lang in package.languages if lang is not first), None)
100
+ entry_name = f"{package.slug}-{other.language}" if other else None
101
+ if other is not None and entry_name not in names:
102
+ lines.append(f" # The same asset in another language ({other.language}):")
103
+ lines += _entry(entry_name, other.latest_version, asset=package.slug, language=other.language)
104
+ names.add(entry_name)
105
+ return _HEADER.format(assets_dir=_quote(assets_dir)) + "\n".join(lines) + "\n"
106
+
107
+
108
+ def render_fallback(assets_dir: str, reason: str) -> str:
109
+ return _HEADER.format(assets_dir=_quote(assets_dir)) + _FALLBACK_ENTRIES.format(reason=reason)