itqan-cli 0.1.0__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 +1 -0
- itqan_cli/__main__.py +5 -0
- itqan_cli/browse.py +344 -0
- itqan_cli/client.py +334 -0
- itqan_cli/credentials.py +91 -0
- itqan_cli/downloader.py +220 -0
- itqan_cli/exceptions.py +69 -0
- itqan_cli/init_template.py +118 -0
- itqan_cli/lockfile.py +285 -0
- itqan_cli/main.py +535 -0
- itqan_cli/manifest.py +274 -0
- itqan_cli/semver.py +205 -0
- itqan_cli-0.1.0.dist-info/METADATA +147 -0
- itqan_cli-0.1.0.dist-info/RECORD +17 -0
- itqan_cli-0.1.0.dist-info/WHEEL +4 -0
- itqan_cli-0.1.0.dist-info/entry_points.txt +3 -0
- itqan_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
itqan_cli/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Itqan Package Manager CLI."""
|
itqan_cli/__main__.py
ADDED
itqan_cli/browse.py
ADDED
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
"""`itqan browse`: list the registry's catalog and add picked assets to the manifest.
|
|
2
|
+
|
|
3
|
+
The pieces that decide what to show and what to write are plain functions;
|
|
4
|
+
only `pick_packages` and `pick_languages` talk to the terminal.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
import re
|
|
11
|
+
import shutil
|
|
12
|
+
from typing import TYPE_CHECKING, Any
|
|
13
|
+
|
|
14
|
+
from itqan_cli.client import CatalogLanguage, CatalogPackage
|
|
15
|
+
from itqan_cli.exceptions import ManifestError
|
|
16
|
+
from itqan_cli.init_template import entry_lines
|
|
17
|
+
from itqan_cli.manifest import AssetManifest, parse_manifest_content
|
|
18
|
+
|
|
19
|
+
if TYPE_CHECKING:
|
|
20
|
+
from questionary import Question
|
|
21
|
+
|
|
22
|
+
# (asset slug, language code); None stands for the asset's source language.
|
|
23
|
+
Target = tuple[str, str | None]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True, slots=True)
|
|
27
|
+
class NewEntry:
|
|
28
|
+
"""A manifest entry `browse` is about to add."""
|
|
29
|
+
|
|
30
|
+
name: str
|
|
31
|
+
package: CatalogPackage
|
|
32
|
+
language: CatalogLanguage
|
|
33
|
+
|
|
34
|
+
def lines(self, indent: str) -> list[str]:
|
|
35
|
+
if self.language.is_source:
|
|
36
|
+
return entry_lines(self.name, self.language.latest_version, indent=indent)
|
|
37
|
+
return entry_lines(
|
|
38
|
+
self.name,
|
|
39
|
+
self.language.latest_version,
|
|
40
|
+
asset=self.package.slug,
|
|
41
|
+
language=self.language.language,
|
|
42
|
+
indent=indent,
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def manifest_targets(manifest: AssetManifest | None) -> set[Target]:
|
|
47
|
+
if manifest is None:
|
|
48
|
+
return set()
|
|
49
|
+
return {(entry.asset or entry.slug, entry.language) for entry in manifest.assets.values()}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def is_declared(targets: set[Target], package: CatalogPackage, language: CatalogLanguage) -> bool:
|
|
53
|
+
"""Whether the manifest already installs this language of the package."""
|
|
54
|
+
if (package.slug, language.language) in targets:
|
|
55
|
+
return True
|
|
56
|
+
return language.is_source and (package.slug, None) in targets
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def missing_languages(targets: set[Target], package: CatalogPackage) -> list[CatalogLanguage]:
|
|
60
|
+
return [lang for lang in package.languages if not is_declared(targets, package, lang)]
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def plan_entries(
|
|
64
|
+
picks: list[tuple[CatalogPackage, CatalogLanguage]], manifest: AssetManifest | None
|
|
65
|
+
) -> tuple[list[NewEntry], list[str]]:
|
|
66
|
+
"""Entries to add for the picked (package, language) pairs, and a warning
|
|
67
|
+
for each pick that is skipped. The source language is named after the slug,
|
|
68
|
+
another language `<slug>-<language>`, the same names `itqan init` uses."""
|
|
69
|
+
targets = manifest_targets(manifest)
|
|
70
|
+
taken = set(manifest.assets) if manifest is not None else set()
|
|
71
|
+
entries: list[NewEntry] = []
|
|
72
|
+
warnings: list[str] = []
|
|
73
|
+
for package, language in picks:
|
|
74
|
+
if is_declared(targets, package, language):
|
|
75
|
+
warnings.append(f"{package.slug} ({language.language or 'source'}) is already in the manifest; skipped.")
|
|
76
|
+
continue
|
|
77
|
+
name = package.slug if language.is_source else f"{package.slug}-{language.language}"
|
|
78
|
+
if name in taken:
|
|
79
|
+
warnings.append(f"An entry named {name!r} already exists for another asset; skipped {package.slug}.")
|
|
80
|
+
continue
|
|
81
|
+
taken.add(name)
|
|
82
|
+
targets.add((package.slug, None if language.is_source else language.language))
|
|
83
|
+
entries.append(NewEntry(name=name, package=package, language=language))
|
|
84
|
+
return entries, warnings
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
_ASSETS_KEY = re.compile(r"^assets[ \t]*:[ \t]*(#.*)?$")
|
|
88
|
+
_ENTRY_INDENT = re.compile(r"^([ \t]+)[^ \t#]")
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def add_entries(content: str, entries: list[NewEntry]) -> str:
|
|
92
|
+
"""``content`` with ``entries`` appended to the end of its `assets:` block.
|
|
93
|
+
|
|
94
|
+
Edits the text rather than re-dumping the YAML, so the file's comments and
|
|
95
|
+
layout survive. New entries take the indentation of the existing ones.
|
|
96
|
+
|
|
97
|
+
Raises:
|
|
98
|
+
ManifestError when the file has no block-style `assets:` key or the
|
|
99
|
+
result would not be a valid manifest.
|
|
100
|
+
"""
|
|
101
|
+
lines = content.splitlines()
|
|
102
|
+
start = next((i for i, line in enumerate(lines) if _ASSETS_KEY.match(line)), None)
|
|
103
|
+
if start is None:
|
|
104
|
+
raise ManifestError("Could not find a block-style `assets:` key to add entries under.")
|
|
105
|
+
|
|
106
|
+
end = start # last indented line of the block (entries or comments under it)
|
|
107
|
+
indent: str | None = None
|
|
108
|
+
for i in range(start + 1, len(lines)):
|
|
109
|
+
line = lines[i]
|
|
110
|
+
if not line.strip():
|
|
111
|
+
continue
|
|
112
|
+
if line[0] in " \t":
|
|
113
|
+
end = i
|
|
114
|
+
match = _ENTRY_INDENT.match(line)
|
|
115
|
+
if indent is None and match:
|
|
116
|
+
indent = match.group(1)
|
|
117
|
+
elif not line.startswith("#"):
|
|
118
|
+
break # the next top-level key
|
|
119
|
+
|
|
120
|
+
block: list[str] = []
|
|
121
|
+
for entry in entries:
|
|
122
|
+
name = " ".join(entry.package.name.split())
|
|
123
|
+
block += ["", f"{indent or ' '}# {name} ({entry.language.language or 'source'})"]
|
|
124
|
+
block += entry.lines(indent or " ")
|
|
125
|
+
if end == start:
|
|
126
|
+
block = block[1:] # first entry: no blank line right under `assets:`
|
|
127
|
+
|
|
128
|
+
updated = "\n".join(lines[: end + 1] + block + lines[end + 1 :]) + "\n"
|
|
129
|
+
manifest = parse_manifest_content(updated.encode("utf-8"))
|
|
130
|
+
missing = [entry.name for entry in entries if entry.name not in manifest.assets]
|
|
131
|
+
if missing:
|
|
132
|
+
raise ManifestError(f"Could not add {', '.join(missing)} to the manifest's assets.")
|
|
133
|
+
return updated
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _languages_text(package: CatalogPackage) -> str:
|
|
137
|
+
return ",".join(lang.language or "source" for lang in package.languages)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _latest_text(package: CatalogPackage) -> str:
|
|
141
|
+
source = next((lang for lang in package.languages if lang.is_source), None)
|
|
142
|
+
first = source or (package.languages[0] if package.languages else None)
|
|
143
|
+
return first.latest_version if first else "-"
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
# What each catalog `access` value means for the user.
|
|
147
|
+
_ACCESS_LABELS = {
|
|
148
|
+
"open": "open access",
|
|
149
|
+
"granted": "access granted",
|
|
150
|
+
"pending": "access pending",
|
|
151
|
+
"rejected": "access rejected",
|
|
152
|
+
"none": "request access",
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def can_install(package: CatalogPackage, has_api_key: bool) -> bool:
|
|
157
|
+
"""Whether the registry will serve this package to the caller."""
|
|
158
|
+
if package.access is None: # a registry that only reports open / gated
|
|
159
|
+
return package.is_open_access or has_api_key
|
|
160
|
+
return package.access in ("open", "granted")
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def access_label(package: CatalogPackage) -> str:
|
|
164
|
+
if package.access is None:
|
|
165
|
+
return "open access" if package.is_open_access else "needs an API key"
|
|
166
|
+
return _ACCESS_LABELS.get(package.access, package.access)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _access_column(package: CatalogPackage) -> str:
|
|
170
|
+
if package.access is None:
|
|
171
|
+
return "open" if package.is_open_access else "api-key"
|
|
172
|
+
return "request" if package.access == "none" else package.access
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def access_footer(packages: list[CatalogPackage], has_api_key: bool) -> list[str]:
|
|
176
|
+
"""Where to request access to the listed assets the caller can't install,
|
|
177
|
+
and, without a key, how to use one."""
|
|
178
|
+
blocked = [p for p in packages if not can_install(p, has_api_key)]
|
|
179
|
+
if not blocked:
|
|
180
|
+
return []
|
|
181
|
+
width = max(len(p.slug) for p in blocked)
|
|
182
|
+
lines = ["", "Request access on each asset's page:"]
|
|
183
|
+
lines += [f" {p.slug.ljust(width)} {p.access_request_url or '-'} ({access_label(p)})" for p in blocked]
|
|
184
|
+
if not has_api_key:
|
|
185
|
+
lines.append("Already approved? Run `itqan login` to use your API key.")
|
|
186
|
+
return lines
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def render_table(packages: list[CatalogPackage], targets: set[Target]) -> str:
|
|
190
|
+
"""Plain-text listing for pipes, CI and `--no-interactive`."""
|
|
191
|
+
header = ("SLUG", "CATEGORY", "LANGUAGES", "LATEST", "ACCESS", "NAME")
|
|
192
|
+
rows = [header] + [
|
|
193
|
+
(
|
|
194
|
+
("* " if not missing_languages(targets, package) else "") + package.slug,
|
|
195
|
+
package.category,
|
|
196
|
+
_languages_text(package),
|
|
197
|
+
_latest_text(package),
|
|
198
|
+
_access_column(package),
|
|
199
|
+
" ".join(package.name.split()),
|
|
200
|
+
)
|
|
201
|
+
for package in packages
|
|
202
|
+
]
|
|
203
|
+
widths = [max(len(row[col]) for row in rows) for col in range(len(header) - 1)]
|
|
204
|
+
return "\n".join(" ".join([cell.ljust(width) for cell, width in zip(row, widths)] + [row[-1]]) for row in rows)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def to_json(packages: list[CatalogPackage], targets: set[Target]) -> list[dict]:
|
|
208
|
+
return [
|
|
209
|
+
{
|
|
210
|
+
"slug": package.slug,
|
|
211
|
+
"name": package.name,
|
|
212
|
+
"category": package.category,
|
|
213
|
+
"is_open_access": package.is_open_access,
|
|
214
|
+
"access": package.access,
|
|
215
|
+
"access_request_url": package.access_request_url,
|
|
216
|
+
"publisher_name": package.publisher_name,
|
|
217
|
+
"languages": [
|
|
218
|
+
{
|
|
219
|
+
"language": lang.language,
|
|
220
|
+
"is_source": lang.is_source,
|
|
221
|
+
"latest_version": lang.latest_version,
|
|
222
|
+
"in_manifest": is_declared(targets, package, lang),
|
|
223
|
+
}
|
|
224
|
+
for lang in package.languages
|
|
225
|
+
],
|
|
226
|
+
}
|
|
227
|
+
for package in packages
|
|
228
|
+
]
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
# Room the picker takes before a row's title: pointer, checkbox and spaces.
|
|
232
|
+
_ROW_PREFIX = 5
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _truncate(text: str, width: int) -> str:
|
|
236
|
+
return text if len(text) <= width else text[: max(width - 1, 0)] + "…"
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def choice_titles(packages: list[CatalogPackage], reasons: list[str | None], max_width: int) -> list[str]:
|
|
240
|
+
"""One aligned row per package that fits in ``max_width`` columns, leaving
|
|
241
|
+
room for the picker's ` (<reason>)` note on rows that can't be picked."""
|
|
242
|
+
columns = [
|
|
243
|
+
(package.slug, package.category, _languages_text(package), _latest_text(package)) for package in packages
|
|
244
|
+
]
|
|
245
|
+
widths = [max(len(row[col]) for row in columns) for col in range(4)]
|
|
246
|
+
titles = []
|
|
247
|
+
for package, row, reason in zip(packages, columns, reasons):
|
|
248
|
+
prefix = " ".join(cell.ljust(width) for cell, width in zip(row, widths)) + " "
|
|
249
|
+
room = max_width - _ROW_PREFIX - len(prefix) - (len(reason) + 3 if reason else 0)
|
|
250
|
+
titles.append(prefix + _truncate(" ".join(package.name.split()), room))
|
|
251
|
+
return titles
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def choice_description(package: CatalogPackage, has_api_key: bool) -> str:
|
|
255
|
+
"""Shown under the list for the highlighted row."""
|
|
256
|
+
parts = [" ".join(package.name.split())]
|
|
257
|
+
if package.publisher_name:
|
|
258
|
+
parts.append(package.publisher_name)
|
|
259
|
+
parts.append(access_label(package))
|
|
260
|
+
if not can_install(package, has_api_key) and package.access_request_url:
|
|
261
|
+
parts.append(f"request at {package.access_request_url}")
|
|
262
|
+
if not has_api_key:
|
|
263
|
+
parts.append("approved? run `itqan login`")
|
|
264
|
+
return " · ".join(parts)
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def unavailable_reason(package: CatalogPackage, targets: set[Target], has_api_key: bool) -> str | None:
|
|
268
|
+
"""Why a package can't be picked, or None when it can."""
|
|
269
|
+
if not missing_languages(targets, package):
|
|
270
|
+
return "in manifest"
|
|
271
|
+
if not can_install(package, has_api_key):
|
|
272
|
+
return access_label(package)
|
|
273
|
+
return None
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def pick_packages(
|
|
277
|
+
packages: list[CatalogPackage], targets: set[Target], has_api_key: bool, **prompt_kwargs: Any
|
|
278
|
+
) -> list[CatalogPackage] | None:
|
|
279
|
+
"""Fuzzy multi-select over the catalog; None when the user cancels.
|
|
280
|
+
``prompt_kwargs`` go to the prompt_toolkit Application (tests pass input/output)."""
|
|
281
|
+
import questionary
|
|
282
|
+
|
|
283
|
+
reasons = [unavailable_reason(package, targets, has_api_key) for package in packages]
|
|
284
|
+
titles = choice_titles(packages, reasons, shutil.get_terminal_size().columns)
|
|
285
|
+
choices = [
|
|
286
|
+
questionary.Choice(
|
|
287
|
+
title=title, value=package, disabled=reason, description=choice_description(package, has_api_key)
|
|
288
|
+
)
|
|
289
|
+
for package, title, reason in zip(packages, titles, reasons)
|
|
290
|
+
]
|
|
291
|
+
question = questionary.checkbox(
|
|
292
|
+
"Pick assets (type to search, enter to add, space to select several):",
|
|
293
|
+
choices=choices,
|
|
294
|
+
use_search_filter=True,
|
|
295
|
+
use_jk_keys=False,
|
|
296
|
+
instruction="",
|
|
297
|
+
erase_when_done=True, # the caller prints a one-line summary instead of the picked rows
|
|
298
|
+
**prompt_kwargs,
|
|
299
|
+
)
|
|
300
|
+
_enter_picks_highlighted(question)
|
|
301
|
+
return question.ask()
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def _enter_picks_highlighted(question: Question) -> None:
|
|
305
|
+
"""Make Enter with nothing selected pick the highlighted row, instead of
|
|
306
|
+
confirming an empty selection. prompt_toolkit runs the last binding added
|
|
307
|
+
for a key, so this one replaces the checkbox's own Enter handler."""
|
|
308
|
+
from prompt_toolkit.key_binding import KeyBindings
|
|
309
|
+
from prompt_toolkit.keys import Keys
|
|
310
|
+
from questionary.prompts.common import InquirerControl
|
|
311
|
+
|
|
312
|
+
control = next(c for c in question.application.layout.find_all_controls() if isinstance(c, InquirerControl))
|
|
313
|
+
bindings = question.application.key_bindings
|
|
314
|
+
assert isinstance(bindings, KeyBindings)
|
|
315
|
+
|
|
316
|
+
@bindings.add(Keys.ControlM, eager=True)
|
|
317
|
+
def _(event: Any) -> None:
|
|
318
|
+
pointed = control.get_pointed_at()
|
|
319
|
+
# A search that matches nothing shows the whole list again; don't pick from it.
|
|
320
|
+
no_match = control.search_filter and not control.found_in_search
|
|
321
|
+
if not control.selected_options and not no_match and not pointed.disabled:
|
|
322
|
+
control.selected_options.append(pointed.value)
|
|
323
|
+
control.submission_attempted = True
|
|
324
|
+
control.is_answered = True
|
|
325
|
+
event.app.exit(result=[choice.value for choice in control.get_selected_values()])
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def pick_languages(package: CatalogPackage, targets: set[Target]) -> list[CatalogLanguage] | None:
|
|
329
|
+
"""The languages to add for ``package``: asks only when there is a choice."""
|
|
330
|
+
available = missing_languages(targets, package)
|
|
331
|
+
if len(available) <= 1:
|
|
332
|
+
return available
|
|
333
|
+
import questionary
|
|
334
|
+
|
|
335
|
+
preferred = next((lang for lang in available if lang.is_source), available[0])
|
|
336
|
+
choices = [
|
|
337
|
+
questionary.Choice(
|
|
338
|
+
title=f"{lang.language or 'source'}{' (source)' if lang.is_source else ''} {lang.latest_version}",
|
|
339
|
+
value=lang,
|
|
340
|
+
checked=lang is preferred,
|
|
341
|
+
)
|
|
342
|
+
for lang in available
|
|
343
|
+
]
|
|
344
|
+
return questionary.checkbox(f"{package.slug}: which languages?", choices=choices, erase_when_done=True).ask()
|
itqan_cli/client.py
ADDED
|
@@ -0,0 +1,334 @@
|
|
|
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
|
+
# The caller's access (open | granted | pending | rejected | none); None from
|
|
49
|
+
# a registry that predates it, which only says whether the asset is open.
|
|
50
|
+
access: str | None = None
|
|
51
|
+
access_request_url: str | None = None
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass(frozen=True, slots=True)
|
|
55
|
+
class Account:
|
|
56
|
+
"""The owner of an API key, from GET /packages/me/."""
|
|
57
|
+
|
|
58
|
+
name: str
|
|
59
|
+
email: str
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
# The public API (not the cms.itqan.dev website, which serves the web app).
|
|
63
|
+
DEFAULT_REGISTRY_URL = "https://api.cms.itqan.dev"
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _cli_version() -> str:
|
|
67
|
+
try:
|
|
68
|
+
return version("itqan-cli")
|
|
69
|
+
except PackageNotFoundError: # running from a source checkout that isn't installed
|
|
70
|
+
return "unknown"
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _error_detail(response: requests.Response) -> str:
|
|
74
|
+
"""`: <reason>` from an error body like a 400 validation error, or ""."""
|
|
75
|
+
try:
|
|
76
|
+
body = response.json()
|
|
77
|
+
extra = body.get("extra") or []
|
|
78
|
+
reason = extra[0]["msg"] if extra and isinstance(extra[0], dict) else body.get("message")
|
|
79
|
+
except (ValueError, AttributeError, KeyError, TypeError):
|
|
80
|
+
return ""
|
|
81
|
+
return f": {reason}" if reason else ""
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class RegistryClient:
|
|
85
|
+
"""HTTP Client for Itqan Package Registry API."""
|
|
86
|
+
|
|
87
|
+
def __init__(
|
|
88
|
+
self,
|
|
89
|
+
base_url: str = DEFAULT_REGISTRY_URL,
|
|
90
|
+
api_key: str | None = None,
|
|
91
|
+
timeout: float = 30.0,
|
|
92
|
+
session: requests.Session | None = None,
|
|
93
|
+
) -> None:
|
|
94
|
+
self.base_url = base_url.rstrip("/")
|
|
95
|
+
self.api_key = api_key
|
|
96
|
+
self.timeout = timeout
|
|
97
|
+
self.session = session or requests.Session()
|
|
98
|
+
|
|
99
|
+
# Security: reject HTTP for non-loopback URLs when an API key is provided.
|
|
100
|
+
# Sending an API key over plain HTTP exposes it to network eavesdroppers.
|
|
101
|
+
if api_key:
|
|
102
|
+
parsed = __import__("urllib.parse", fromlist=["urlparse"]).urlparse(self.base_url)
|
|
103
|
+
is_loopback = parsed.hostname in ("localhost", "127.0.0.1", "::1")
|
|
104
|
+
if parsed.scheme == "http" and not is_loopback:
|
|
105
|
+
raise RegistryApiError(
|
|
106
|
+
"Refusing to send API key over an insecure HTTP connection. "
|
|
107
|
+
"Use HTTPS or a loopback address for development."
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
def _headers(self) -> dict[str, str]:
|
|
111
|
+
headers = {
|
|
112
|
+
"Accept": "application/json",
|
|
113
|
+
"Content-Type": "application/json",
|
|
114
|
+
"User-Agent": f"itqan-cli/{_cli_version()}",
|
|
115
|
+
}
|
|
116
|
+
if self.api_key:
|
|
117
|
+
headers["X-API-Key"] = self.api_key
|
|
118
|
+
return headers
|
|
119
|
+
|
|
120
|
+
def list_packages(
|
|
121
|
+
self,
|
|
122
|
+
*,
|
|
123
|
+
open_access: bool | None = None,
|
|
124
|
+
search: str | None = None,
|
|
125
|
+
category: str | None = None,
|
|
126
|
+
page_size: int = 50,
|
|
127
|
+
) -> list[CatalogPackage]:
|
|
128
|
+
"""Call GET /packages/ for the first page of installable assets.
|
|
129
|
+
|
|
130
|
+
Raises:
|
|
131
|
+
RegistryApiError when the registry can't be reached or answers badly.
|
|
132
|
+
"""
|
|
133
|
+
packages, _ = self._catalog_page(
|
|
134
|
+
open_access=open_access, search=search, category=category, page=1, page_size=page_size
|
|
135
|
+
)
|
|
136
|
+
return packages
|
|
137
|
+
|
|
138
|
+
def list_all_packages(
|
|
139
|
+
self,
|
|
140
|
+
*,
|
|
141
|
+
open_access: bool | None = None,
|
|
142
|
+
search: str | None = None,
|
|
143
|
+
category: str | None = None,
|
|
144
|
+
page_size: int = 50,
|
|
145
|
+
) -> list[CatalogPackage]:
|
|
146
|
+
"""Every installable asset matching the filters, following GET /packages/ pagination.
|
|
147
|
+
|
|
148
|
+
Raises:
|
|
149
|
+
RegistryApiError when the registry can't be reached or answers badly.
|
|
150
|
+
"""
|
|
151
|
+
packages: list[CatalogPackage] = []
|
|
152
|
+
page = 1
|
|
153
|
+
while True:
|
|
154
|
+
batch, count = self._catalog_page(
|
|
155
|
+
open_access=open_access, search=search, category=category, page=page, page_size=page_size
|
|
156
|
+
)
|
|
157
|
+
packages.extend(batch)
|
|
158
|
+
if not batch or len(packages) >= count:
|
|
159
|
+
return packages
|
|
160
|
+
page += 1
|
|
161
|
+
|
|
162
|
+
def _catalog_page(
|
|
163
|
+
self,
|
|
164
|
+
*,
|
|
165
|
+
open_access: bool | None,
|
|
166
|
+
search: str | None,
|
|
167
|
+
category: str | None,
|
|
168
|
+
page: int,
|
|
169
|
+
page_size: int,
|
|
170
|
+
) -> tuple[list[CatalogPackage], int]:
|
|
171
|
+
"""One page of GET /packages/ and the total number of matching assets."""
|
|
172
|
+
params: dict[str, str] = {"page_size": str(page_size)}
|
|
173
|
+
if page > 1:
|
|
174
|
+
params["page"] = str(page)
|
|
175
|
+
if open_access is not None:
|
|
176
|
+
params["open_access"] = "true" if open_access else "false"
|
|
177
|
+
if search:
|
|
178
|
+
params["search"] = search
|
|
179
|
+
if category:
|
|
180
|
+
params["category"] = category
|
|
181
|
+
try:
|
|
182
|
+
response = self.session.get(
|
|
183
|
+
f"{self.base_url}/packages/", params=params, headers=self._headers(), timeout=self.timeout
|
|
184
|
+
)
|
|
185
|
+
except requests.RequestException as exc:
|
|
186
|
+
raise RegistryApiError(f"Failed to connect to package registry at {self.base_url}: {exc}") from exc
|
|
187
|
+
if response.status_code != 200:
|
|
188
|
+
raise RegistryApiError(
|
|
189
|
+
f"Registry catalog request failed with status {response.status_code}{_error_detail(response)}",
|
|
190
|
+
status_code=response.status_code,
|
|
191
|
+
)
|
|
192
|
+
try:
|
|
193
|
+
body = response.json()
|
|
194
|
+
packages = [
|
|
195
|
+
CatalogPackage(
|
|
196
|
+
slug=item["slug"],
|
|
197
|
+
name=item["name"],
|
|
198
|
+
category=item["category"],
|
|
199
|
+
is_open_access=item["is_open_access"],
|
|
200
|
+
publisher_name=item.get("publisher_name"),
|
|
201
|
+
access=item.get("access"),
|
|
202
|
+
access_request_url=item.get("access_request_url"),
|
|
203
|
+
languages=tuple(
|
|
204
|
+
CatalogLanguage(
|
|
205
|
+
language=lang["language"],
|
|
206
|
+
is_source=lang["is_source"],
|
|
207
|
+
latest_version=lang["latest_version"],
|
|
208
|
+
)
|
|
209
|
+
for lang in item["languages"]
|
|
210
|
+
),
|
|
211
|
+
)
|
|
212
|
+
for item in body["results"]
|
|
213
|
+
]
|
|
214
|
+
return packages, int(body.get("count", len(packages)))
|
|
215
|
+
except (ValueError, KeyError, TypeError) as exc:
|
|
216
|
+
raise RegistryApiError(f"Failed to parse registry catalog response: {exc}") from exc
|
|
217
|
+
|
|
218
|
+
def whoami(self) -> Account:
|
|
219
|
+
"""Call GET /packages/me/ to check the API key.
|
|
220
|
+
|
|
221
|
+
Raises:
|
|
222
|
+
RegistryApiError with status_code 401 when the key is missing or
|
|
223
|
+
invalid, 404 when the registry has no such endpoint.
|
|
224
|
+
"""
|
|
225
|
+
try:
|
|
226
|
+
response = self.session.get(f"{self.base_url}/packages/me/", headers=self._headers(), timeout=self.timeout)
|
|
227
|
+
except requests.RequestException as exc:
|
|
228
|
+
raise RegistryApiError(f"Failed to connect to package registry at {self.base_url}: {exc}") from exc
|
|
229
|
+
if response.status_code != 200:
|
|
230
|
+
raise RegistryApiError(
|
|
231
|
+
f"API key check failed with status {response.status_code}{_error_detail(response)}",
|
|
232
|
+
status_code=response.status_code,
|
|
233
|
+
)
|
|
234
|
+
try:
|
|
235
|
+
body = response.json()
|
|
236
|
+
return Account(name=body["name"], email=body["email"])
|
|
237
|
+
except (ValueError, KeyError, TypeError) as exc:
|
|
238
|
+
raise RegistryApiError(f"Failed to parse API key check response: {exc}") from exc
|
|
239
|
+
|
|
240
|
+
def resolve_manifest(self, assets: dict[str, str | dict[str, str]]) -> list[ResolvedAssetPayload]:
|
|
241
|
+
"""Call POST /packages/resolve/manifest/ to resolve manifest constraints.
|
|
242
|
+
|
|
243
|
+
Args:
|
|
244
|
+
assets: dict of entry name -> constraint string (e.g. {"quran": "^2.1.0"}),
|
|
245
|
+
or -> request object ({"version": ..., "asset": ..., "language": ...})
|
|
246
|
+
|
|
247
|
+
Returns:
|
|
248
|
+
list of ResolvedAssetPayload
|
|
249
|
+
|
|
250
|
+
Raises:
|
|
251
|
+
RegistryApiError on any failure.
|
|
252
|
+
"""
|
|
253
|
+
url = f"{self.base_url}/packages/resolve/manifest/"
|
|
254
|
+
payload = {"assets": assets}
|
|
255
|
+
|
|
256
|
+
try:
|
|
257
|
+
response = self.session.post(
|
|
258
|
+
url,
|
|
259
|
+
json=payload,
|
|
260
|
+
headers=self._headers(),
|
|
261
|
+
timeout=self.timeout,
|
|
262
|
+
)
|
|
263
|
+
except requests.RequestException as exc:
|
|
264
|
+
raise RegistryApiError(f"Failed to connect to package registry at {self.base_url}: {exc}") from exc
|
|
265
|
+
|
|
266
|
+
if response.status_code == 200:
|
|
267
|
+
try:
|
|
268
|
+
data = response.json()
|
|
269
|
+
# Require "results" to be explicitly present as a list.
|
|
270
|
+
# A missing key means the response is malformed — do not silently
|
|
271
|
+
# continue with zero assets, as that would allow _run_install to
|
|
272
|
+
# report success while writing an empty lockfile.
|
|
273
|
+
if "results" not in data or not isinstance(data["results"], list):
|
|
274
|
+
raise RegistryApiError(
|
|
275
|
+
"Registry returned a 200 response but 'results' field is missing or not a list. "
|
|
276
|
+
"Cannot proceed with installation."
|
|
277
|
+
)
|
|
278
|
+
results_raw = data["results"]
|
|
279
|
+
requested_slugs = set(assets.keys())
|
|
280
|
+
returned_slugs = {item.get("name") or item["slug"] for item in results_raw if isinstance(item, dict)}
|
|
281
|
+
missing = requested_slugs - returned_slugs
|
|
282
|
+
if missing:
|
|
283
|
+
raise RegistryApiError(
|
|
284
|
+
f"Registry resolved {len(returned_slugs)} of {len(requested_slugs)} requested assets. "
|
|
285
|
+
f"Missing: {', '.join(sorted(missing))}"
|
|
286
|
+
)
|
|
287
|
+
return [
|
|
288
|
+
ResolvedAssetPayload(
|
|
289
|
+
slug=item["slug"],
|
|
290
|
+
asset_version_id=item["asset_version_id"],
|
|
291
|
+
resolved_version=item["resolved_version"],
|
|
292
|
+
asset_name=item["asset_name"],
|
|
293
|
+
download_url=item.get("download_url"),
|
|
294
|
+
publisher_id=item.get("publisher_id"),
|
|
295
|
+
publisher_name=item.get("publisher_name"),
|
|
296
|
+
name=item.get("name") or item["slug"],
|
|
297
|
+
language=item.get("language"),
|
|
298
|
+
)
|
|
299
|
+
for item in results_raw
|
|
300
|
+
]
|
|
301
|
+
except RegistryApiError:
|
|
302
|
+
raise
|
|
303
|
+
except Exception as exc:
|
|
304
|
+
raise RegistryApiError(f"Failed to parse registry API response: {exc}") from exc
|
|
305
|
+
|
|
306
|
+
# Handle API Error responses
|
|
307
|
+
status_code = response.status_code
|
|
308
|
+
error_name: str | None = None
|
|
309
|
+
message = f"Registry request failed with status {status_code}"
|
|
310
|
+
|
|
311
|
+
try:
|
|
312
|
+
err_data = response.json()
|
|
313
|
+
if isinstance(err_data, dict):
|
|
314
|
+
error_name = err_data.get("error_name") or err_data.get("error")
|
|
315
|
+
message = err_data.get("message") or err_data.get("detail") or message
|
|
316
|
+
except Exception:
|
|
317
|
+
message = response.text or message
|
|
318
|
+
|
|
319
|
+
if status_code == 401:
|
|
320
|
+
friendly_msg = f"Authentication required (API key missing or invalid): {message}"
|
|
321
|
+
elif status_code == 403:
|
|
322
|
+
friendly_msg = f"Access denied for requested assets (approved access required): {message}"
|
|
323
|
+
elif status_code == 404:
|
|
324
|
+
friendly_msg = f"Asset or version not found in registry: {message}"
|
|
325
|
+
elif status_code == 422:
|
|
326
|
+
friendly_msg = f"Cannot satisfy version constraints: {message}"
|
|
327
|
+
else:
|
|
328
|
+
friendly_msg = f"Registry API error [{status_code}]: {message}"
|
|
329
|
+
|
|
330
|
+
raise RegistryApiError(
|
|
331
|
+
friendly_msg,
|
|
332
|
+
status_code=status_code,
|
|
333
|
+
error_name=error_name,
|
|
334
|
+
)
|