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/manifest.py
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
"""Asset manifest parser and validator adhering to docs/ASSET_MANIFEST.md §2-§3."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from pathlib import Path, PurePosixPath, PureWindowsPath
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
import yaml
|
|
10
|
+
from yaml.composer import Composer
|
|
11
|
+
from yaml.constructor import SafeConstructor
|
|
12
|
+
from yaml.parser import Parser
|
|
13
|
+
from yaml.reader import Reader
|
|
14
|
+
from yaml.resolver import Resolver
|
|
15
|
+
from yaml.scanner import Scanner
|
|
16
|
+
|
|
17
|
+
from itqan_cli.exceptions import (
|
|
18
|
+
DuplicateAssetEntryError,
|
|
19
|
+
InvalidConstraintSyntaxError,
|
|
20
|
+
MissingRequiredFieldError,
|
|
21
|
+
NonStringAssetKeyError,
|
|
22
|
+
ScalarShorthandEntryError,
|
|
23
|
+
UnknownFieldError,
|
|
24
|
+
UnsupportedSchemaVersionError,
|
|
25
|
+
YamlProfileViolationError,
|
|
26
|
+
)
|
|
27
|
+
from itqan_cli.semver import parse_constraint
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True, slots=True)
|
|
31
|
+
class AssetManifestEntry:
|
|
32
|
+
"""One manifest entry. ``slug`` is the entry's key (its name); ``asset`` is
|
|
33
|
+
the CMS slug it installs, which defaults to the key. ``language`` picks the
|
|
34
|
+
language rendition; None means the asset's source language."""
|
|
35
|
+
|
|
36
|
+
slug: str
|
|
37
|
+
version: str
|
|
38
|
+
package: str | None = None
|
|
39
|
+
asset: str = ""
|
|
40
|
+
language: str | None = None
|
|
41
|
+
|
|
42
|
+
def to_request(self, version: str | None = None) -> dict[str, str]:
|
|
43
|
+
"""Registry request for this entry, optionally pinned to ``version``."""
|
|
44
|
+
request = {"version": version or self.version}
|
|
45
|
+
if self.asset != self.slug:
|
|
46
|
+
request["asset"] = self.asset
|
|
47
|
+
if self.language is not None:
|
|
48
|
+
request["language"] = self.language
|
|
49
|
+
return request
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass(frozen=True, slots=True)
|
|
53
|
+
class AssetManifest:
|
|
54
|
+
schema_version: int
|
|
55
|
+
assets: dict[str, AssetManifestEntry]
|
|
56
|
+
assets_dir: str | None = None
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def raw_constraints(self) -> dict[str, str]:
|
|
60
|
+
"""Mapping of entry name -> version constraint string as declared in manifest."""
|
|
61
|
+
return {slug: entry.version for slug, entry in self.assets.items()}
|
|
62
|
+
|
|
63
|
+
@property
|
|
64
|
+
def registry_requests(self) -> dict[str, dict[str, str]]:
|
|
65
|
+
"""Mapping of entry name -> registry request object."""
|
|
66
|
+
return {slug: entry.to_request() for slug, entry in self.assets.items()}
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class _StrictYamlLoader(Reader, Scanner, Parser, Composer, SafeConstructor, Resolver):
|
|
70
|
+
"""A strictly conforming YAML loader implementing §2 constraints.
|
|
71
|
+
|
|
72
|
+
Rejects:
|
|
73
|
+
- Anchors and aliases
|
|
74
|
+
- Duplicate keys
|
|
75
|
+
"""
|
|
76
|
+
|
|
77
|
+
def __init__(self, stream: Any) -> None:
|
|
78
|
+
Reader.__init__(self, stream)
|
|
79
|
+
Scanner.__init__(self)
|
|
80
|
+
Parser.__init__(self)
|
|
81
|
+
Composer.__init__(self)
|
|
82
|
+
SafeConstructor.__init__(self)
|
|
83
|
+
Resolver.__init__(self)
|
|
84
|
+
|
|
85
|
+
def compose_node(self, parent: Any, index: Any) -> Any:
|
|
86
|
+
if self.check_event(yaml.events.AliasEvent):
|
|
87
|
+
event = self.get_event()
|
|
88
|
+
raise YamlProfileViolationError(f"YAML aliases/anchors are rejected: *{event.anchor}")
|
|
89
|
+
return super().compose_node(parent, index)
|
|
90
|
+
|
|
91
|
+
def construct_mapping(self, node: yaml.MappingNode, deep: bool = False) -> dict[Any, Any]:
|
|
92
|
+
if not isinstance(node, yaml.MappingNode):
|
|
93
|
+
raise YamlProfileViolationError(f"Expected mapping, got {node.id}")
|
|
94
|
+
|
|
95
|
+
mapping: dict[Any, Any] = {}
|
|
96
|
+
seen_keys: set[Any] = set()
|
|
97
|
+
|
|
98
|
+
for key_node, value_node in node.value:
|
|
99
|
+
key = self.construct_object(key_node, deep=deep)
|
|
100
|
+
|
|
101
|
+
if key in seen_keys:
|
|
102
|
+
raise YamlProfileViolationError(f"Duplicate mapping key: {key}")
|
|
103
|
+
seen_keys.add(key)
|
|
104
|
+
|
|
105
|
+
# Check if an asset key or top-level key was coerced from boolean or int
|
|
106
|
+
# In YAML 1.1 unquoted 'on', 'no', 'true', 123 become bool/int
|
|
107
|
+
if not isinstance(key, str):
|
|
108
|
+
raise NonStringAssetKeyError(f"Mapping key '{key}' must be a string, got {type(key).__name__}.")
|
|
109
|
+
|
|
110
|
+
val = self.construct_object(value_node, deep=deep)
|
|
111
|
+
mapping[key] = val
|
|
112
|
+
|
|
113
|
+
return mapping
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _validate_manifest_dict(data: dict[str, Any]) -> AssetManifest:
|
|
117
|
+
"""Validate parsed manifest mapping against the V1 specification."""
|
|
118
|
+
allowed_top_keys = {"schema_version", "assets", "assets_dir"}
|
|
119
|
+
for key in data.keys():
|
|
120
|
+
if key not in allowed_top_keys:
|
|
121
|
+
raise UnknownFieldError(f"Unknown top-level field: '{key}'. Allowed: {allowed_top_keys}")
|
|
122
|
+
|
|
123
|
+
if "schema_version" not in data:
|
|
124
|
+
raise UnsupportedSchemaVersionError("Missing required 'schema_version' field.")
|
|
125
|
+
|
|
126
|
+
schema_version_val = data["schema_version"]
|
|
127
|
+
if not isinstance(schema_version_val, int) or isinstance(schema_version_val, bool):
|
|
128
|
+
raise UnsupportedSchemaVersionError(
|
|
129
|
+
f"'schema_version' must be an integer, got {type(schema_version_val).__name__}."
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
if schema_version_val != 1:
|
|
133
|
+
raise UnsupportedSchemaVersionError(f"Unsupported schema_version {schema_version_val}. Expected 1.")
|
|
134
|
+
|
|
135
|
+
if "assets" not in data:
|
|
136
|
+
raise MissingRequiredFieldError("Missing required top-level 'assets' field.")
|
|
137
|
+
|
|
138
|
+
assets_raw = data["assets"]
|
|
139
|
+
if assets_raw is None:
|
|
140
|
+
# `assets:` with only comments under it (e.g. a fresh `itqan init` file)
|
|
141
|
+
assets_raw = {}
|
|
142
|
+
if not isinstance(assets_raw, dict):
|
|
143
|
+
raise YamlProfileViolationError(f"'assets' must be a mapping, got {type(assets_raw).__name__}.")
|
|
144
|
+
|
|
145
|
+
parsed_assets: dict[str, AssetManifestEntry] = {}
|
|
146
|
+
seen_targets: dict[tuple[str, str | None], str] = {}
|
|
147
|
+
|
|
148
|
+
for slug, entry_raw in assets_raw.items():
|
|
149
|
+
if not isinstance(slug, str):
|
|
150
|
+
raise NonStringAssetKeyError(f"Asset slug key '{slug}' must be a string.")
|
|
151
|
+
|
|
152
|
+
if not slug.strip():
|
|
153
|
+
raise NonStringAssetKeyError("Asset slug key cannot be empty.")
|
|
154
|
+
|
|
155
|
+
if not isinstance(entry_raw, dict):
|
|
156
|
+
raise ScalarShorthandEntryError(
|
|
157
|
+
f"Asset '{slug}' entry must be a mapping with a 'version' key, not a scalar."
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
allowed_entry_keys = {"version", "package", "asset", "language"}
|
|
161
|
+
for entry_k in entry_raw.keys():
|
|
162
|
+
if entry_k not in allowed_entry_keys:
|
|
163
|
+
raise UnknownFieldError(f"Unknown field '{entry_k}' in entry for asset '{slug}'.")
|
|
164
|
+
|
|
165
|
+
if "version" not in entry_raw:
|
|
166
|
+
raise MissingRequiredFieldError(f"Asset '{slug}' is missing required 'version' field.")
|
|
167
|
+
|
|
168
|
+
version_val = entry_raw["version"]
|
|
169
|
+
if not isinstance(version_val, str) or isinstance(version_val, bool):
|
|
170
|
+
raise InvalidConstraintSyntaxError(f"Version for asset '{slug}' must be a string.")
|
|
171
|
+
|
|
172
|
+
try:
|
|
173
|
+
parse_constraint(version_val)
|
|
174
|
+
except ValueError as exc:
|
|
175
|
+
raise InvalidConstraintSyntaxError(
|
|
176
|
+
f"Invalid version constraint '{version_val}' for asset '{slug}': {exc}"
|
|
177
|
+
) from exc
|
|
178
|
+
|
|
179
|
+
package_val: str | None = None
|
|
180
|
+
if "package" in entry_raw:
|
|
181
|
+
package_raw = entry_raw["package"]
|
|
182
|
+
if not isinstance(package_raw, str) or not package_raw.strip():
|
|
183
|
+
raise UnknownFieldError(f"Reserved field 'package' for asset '{slug}' must be a non-empty string.")
|
|
184
|
+
package_val = package_raw
|
|
185
|
+
|
|
186
|
+
asset_val = _optional_string_field(entry_raw, "asset", slug) or slug
|
|
187
|
+
language_val = _optional_string_field(entry_raw, "language", slug)
|
|
188
|
+
|
|
189
|
+
target = (asset_val, language_val)
|
|
190
|
+
if target in seen_targets:
|
|
191
|
+
raise DuplicateAssetEntryError(
|
|
192
|
+
f"Entries '{seen_targets[target]}' and '{slug}' both name asset '{asset_val}'"
|
|
193
|
+
f" in {f'language {language_val!r}' if language_val else 'its source language'}."
|
|
194
|
+
)
|
|
195
|
+
seen_targets[target] = slug
|
|
196
|
+
|
|
197
|
+
parsed_assets[slug] = AssetManifestEntry(
|
|
198
|
+
slug=slug,
|
|
199
|
+
version=version_val,
|
|
200
|
+
package=package_val,
|
|
201
|
+
asset=asset_val,
|
|
202
|
+
language=language_val,
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
return AssetManifest(
|
|
206
|
+
schema_version=schema_version_val,
|
|
207
|
+
assets=parsed_assets,
|
|
208
|
+
assets_dir=validate_assets_dir(data["assets_dir"]) if "assets_dir" in data else None,
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def validate_assets_dir(value: Any) -> str:
|
|
213
|
+
"""``assets_dir`` must be a relative path that stays inside the project."""
|
|
214
|
+
if not isinstance(value, str) or not value.strip():
|
|
215
|
+
raise UnknownFieldError("'assets_dir' must be a non-empty string.")
|
|
216
|
+
posix, windows = PurePosixPath(value), PureWindowsPath(value)
|
|
217
|
+
if posix.is_absolute() or windows.is_absolute() or windows.drive:
|
|
218
|
+
raise UnknownFieldError(f"'assets_dir' must be relative to the manifest, got '{value}'.")
|
|
219
|
+
if ".." in posix.parts or ".." in windows.parts:
|
|
220
|
+
raise UnknownFieldError(f"'assets_dir' must stay inside the project, got '{value}'.")
|
|
221
|
+
return value
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _optional_string_field(entry_raw: dict[str, Any], field: str, slug: str) -> str | None:
|
|
225
|
+
if field not in entry_raw:
|
|
226
|
+
return None
|
|
227
|
+
value = entry_raw[field]
|
|
228
|
+
if not isinstance(value, str) or not value.strip():
|
|
229
|
+
raise UnknownFieldError(f"Field '{field}' for asset '{slug}' must be a non-empty string.")
|
|
230
|
+
return value
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def parse_manifest_content(content_bytes: bytes) -> AssetManifest:
|
|
234
|
+
"""Parse raw bytes of a manifest file strictly according to §2."""
|
|
235
|
+
if not content_bytes or not content_bytes.strip():
|
|
236
|
+
raise YamlProfileViolationError("Manifest file is empty or contains only whitespace.")
|
|
237
|
+
|
|
238
|
+
# Check for UTF-8 BOM
|
|
239
|
+
if content_bytes.startswith(b"\xef\xbb\xbf"):
|
|
240
|
+
raise YamlProfileViolationError("UTF-8 BOM is rejected.")
|
|
241
|
+
|
|
242
|
+
try:
|
|
243
|
+
content_str = content_bytes.decode("utf-8")
|
|
244
|
+
except UnicodeDecodeError as exc:
|
|
245
|
+
raise YamlProfileViolationError(f"Manifest must be valid UTF-8: {exc}") from exc
|
|
246
|
+
|
|
247
|
+
loader = _StrictYamlLoader(content_str)
|
|
248
|
+
try:
|
|
249
|
+
node = loader.get_single_node()
|
|
250
|
+
except Exception as exc:
|
|
251
|
+
raise YamlProfileViolationError(f"Invalid YAML syntax: {exc}") from exc
|
|
252
|
+
|
|
253
|
+
if node is None:
|
|
254
|
+
raise YamlProfileViolationError("Manifest contains no YAML document.")
|
|
255
|
+
|
|
256
|
+
try:
|
|
257
|
+
data = loader.construct_object(node, deep=True)
|
|
258
|
+
except (YamlProfileViolationError, NonStringAssetKeyError):
|
|
259
|
+
raise
|
|
260
|
+
except Exception as exc:
|
|
261
|
+
raise YamlProfileViolationError(f"Failed to parse YAML structure: {exc}") from exc
|
|
262
|
+
|
|
263
|
+
if not isinstance(data, dict):
|
|
264
|
+
raise YamlProfileViolationError(f"Manifest root must be a YAML mapping, got {type(data).__name__}.")
|
|
265
|
+
|
|
266
|
+
return _validate_manifest_dict(data)
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def load_manifest(path: Path | str) -> AssetManifest:
|
|
270
|
+
"""Load and parse manifest from a file path."""
|
|
271
|
+
p = Path(path)
|
|
272
|
+
if not p.is_file():
|
|
273
|
+
raise FileNotFoundError(f"Manifest file not found: {p}")
|
|
274
|
+
return parse_manifest_content(p.read_bytes())
|
itqan_cli/semver.py
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
"""Pure Python SemVer 2.0.0 primitives adhering to docs/ASSET_MANIFEST.md §3.
|
|
2
|
+
|
|
3
|
+
Zero Django / ORM dependencies so it can run headlessly in any environment.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
import re
|
|
10
|
+
|
|
11
|
+
_SEMVER_RE = re.compile(
|
|
12
|
+
r"^(?P<major>0|[1-9]\d*)"
|
|
13
|
+
r"\.(?P<minor>0|[1-9]\d*)"
|
|
14
|
+
r"\.(?P<patch>0|[1-9]\d*)"
|
|
15
|
+
r"(?:-(?P<prerelease>[0-9A-Za-z\-]+(?:\.[0-9A-Za-z\-]+)*))?"
|
|
16
|
+
r"(?:\+(?P<build>[0-9A-Za-z\-]+(?:\.[0-9A-Za-z\-]+)*))?$"
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
_CARET_RE = re.compile(r"^(\^)(?P<version>.+)$")
|
|
20
|
+
_TILDE_RE = re.compile(r"^(~)(?P<version>.+)$")
|
|
21
|
+
_TWO_COMPONENT_RE = re.compile(r"^(?P<major>0|[1-9]\d*)\.(?P<minor>0|[1-9]\d*)$")
|
|
22
|
+
_PRERELEASE_RE = re.compile(
|
|
23
|
+
r"^(?P<major>0|[1-9]\d*)\.(?P<minor>0|[1-9]\d*)\.(?P<patch>0|[1-9]\d*)"
|
|
24
|
+
r"-(?P<prerelease>[0-9A-Za-z\-]+(?:\.[0-9A-Za-z\-]+)*)$"
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True, slots=True)
|
|
29
|
+
class SemVer:
|
|
30
|
+
"""Immutable SemVer 2.0.0 representation."""
|
|
31
|
+
|
|
32
|
+
major: int
|
|
33
|
+
minor: int
|
|
34
|
+
patch: int
|
|
35
|
+
prerelease: str | None = None
|
|
36
|
+
|
|
37
|
+
@property
|
|
38
|
+
def is_prerelease(self) -> bool:
|
|
39
|
+
return self.prerelease is not None
|
|
40
|
+
|
|
41
|
+
def to_canonical_string(self) -> str:
|
|
42
|
+
base = f"{self.major}.{self.minor}.{self.patch}"
|
|
43
|
+
if self.prerelease is not None:
|
|
44
|
+
base += f"-{self.prerelease}"
|
|
45
|
+
return base
|
|
46
|
+
|
|
47
|
+
def _precedence_key(self) -> tuple:
|
|
48
|
+
if self.prerelease is None:
|
|
49
|
+
return (self.major, self.minor, self.patch, 1, "")
|
|
50
|
+
identifiers = self.prerelease.split(".")
|
|
51
|
+
id_keys = []
|
|
52
|
+
for ident in identifiers:
|
|
53
|
+
if ident.isdigit():
|
|
54
|
+
id_keys.append((0, int(ident), ""))
|
|
55
|
+
else:
|
|
56
|
+
id_keys.append((1, 0, ident))
|
|
57
|
+
return (self.major, self.minor, self.patch, 0, tuple(id_keys))
|
|
58
|
+
|
|
59
|
+
def __lt__(self, other: SemVer) -> bool:
|
|
60
|
+
return self._precedence_key() < other._precedence_key()
|
|
61
|
+
|
|
62
|
+
def __le__(self, other: SemVer) -> bool:
|
|
63
|
+
return self._precedence_key() <= other._precedence_key()
|
|
64
|
+
|
|
65
|
+
def __gt__(self, other: SemVer) -> bool:
|
|
66
|
+
return self._precedence_key() > other._precedence_key()
|
|
67
|
+
|
|
68
|
+
def __ge__(self, other: SemVer) -> bool:
|
|
69
|
+
return self._precedence_key() >= other._precedence_key()
|
|
70
|
+
|
|
71
|
+
def __eq__(self, other: object) -> bool:
|
|
72
|
+
if not isinstance(other, SemVer):
|
|
73
|
+
return NotImplemented
|
|
74
|
+
return self._precedence_key() == other._precedence_key()
|
|
75
|
+
|
|
76
|
+
def __hash__(self) -> int:
|
|
77
|
+
return hash(self._precedence_key())
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def parse_semver(version_str: str) -> SemVer | None:
|
|
81
|
+
"""Parse a canonical SemVer string. Returns None if invalid."""
|
|
82
|
+
m = _SEMVER_RE.match(version_str)
|
|
83
|
+
if m is None:
|
|
84
|
+
return None
|
|
85
|
+
|
|
86
|
+
prerelease_raw = m.group("prerelease")
|
|
87
|
+
if prerelease_raw is not None:
|
|
88
|
+
for ident in prerelease_raw.split("."):
|
|
89
|
+
if ident.isdigit() and len(ident) > 1 and ident.startswith("0"):
|
|
90
|
+
return None
|
|
91
|
+
|
|
92
|
+
return SemVer(
|
|
93
|
+
major=int(m.group("major")),
|
|
94
|
+
minor=int(m.group("minor")),
|
|
95
|
+
patch=int(m.group("patch")),
|
|
96
|
+
prerelease=prerelease_raw,
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def canonicalize_version(version_str: str) -> str:
|
|
101
|
+
"""Expand two-component version to three components.
|
|
102
|
+
|
|
103
|
+
`1.2` -> `1.2.0`, `1.2.3` -> `1.2.3`.
|
|
104
|
+
"""
|
|
105
|
+
if "+" in version_str:
|
|
106
|
+
raise ValueError(f"Build metadata not allowed in version: {version_str}")
|
|
107
|
+
|
|
108
|
+
if version_str.startswith("v") or version_str.startswith("V"):
|
|
109
|
+
raise ValueError(f"v prefix not allowed in version: {version_str}")
|
|
110
|
+
|
|
111
|
+
m = _TWO_COMPONENT_RE.match(version_str)
|
|
112
|
+
if m is not None:
|
|
113
|
+
return f"{m.group('major')}.{m.group('minor')}.0"
|
|
114
|
+
|
|
115
|
+
m = _PRERELEASE_RE.match(version_str)
|
|
116
|
+
if m is not None:
|
|
117
|
+
return version_str
|
|
118
|
+
|
|
119
|
+
m = _SEMVER_RE.match(version_str)
|
|
120
|
+
if m is not None:
|
|
121
|
+
if m.group("build"):
|
|
122
|
+
raise ValueError(f"Build metadata not allowed in version: {version_str}")
|
|
123
|
+
return version_str
|
|
124
|
+
|
|
125
|
+
raise ValueError(f"Invalid version: {version_str}")
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
@dataclass(frozen=True)
|
|
129
|
+
class VersionConstraint:
|
|
130
|
+
kind: str # "exact", "caret", "tilde"
|
|
131
|
+
base: SemVer
|
|
132
|
+
upper_exclusive: SemVer | None = None
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def parse_constraint(constraint_str: str) -> VersionConstraint:
|
|
136
|
+
"""Parse a constraint string into a VersionConstraint.
|
|
137
|
+
|
|
138
|
+
Raises ValueError on invalid syntax.
|
|
139
|
+
"""
|
|
140
|
+
s = constraint_str.strip()
|
|
141
|
+
if not s:
|
|
142
|
+
raise ValueError("Empty constraint")
|
|
143
|
+
|
|
144
|
+
caret_m = _CARET_RE.match(s)
|
|
145
|
+
tilde_m = _TILDE_RE.match(s)
|
|
146
|
+
|
|
147
|
+
if caret_m:
|
|
148
|
+
kind = "caret"
|
|
149
|
+
raw_version = caret_m.group("version")
|
|
150
|
+
elif tilde_m:
|
|
151
|
+
kind = "tilde"
|
|
152
|
+
raw_version = tilde_m.group("version")
|
|
153
|
+
else:
|
|
154
|
+
kind = "exact"
|
|
155
|
+
raw_version = s
|
|
156
|
+
|
|
157
|
+
if kind != "exact" and "-" in raw_version:
|
|
158
|
+
raise ValueError(f"Ranged prerelease constraints are not allowed: {constraint_str}")
|
|
159
|
+
|
|
160
|
+
if "+" in raw_version:
|
|
161
|
+
raise ValueError(f"Build metadata not allowed in constraint: {constraint_str}")
|
|
162
|
+
|
|
163
|
+
canonical = canonicalize_version(raw_version)
|
|
164
|
+
semver = parse_semver(canonical)
|
|
165
|
+
if semver is None:
|
|
166
|
+
raise ValueError(f"Invalid version in constraint: {constraint_str}")
|
|
167
|
+
|
|
168
|
+
if kind == "exact":
|
|
169
|
+
if "-" in raw_version:
|
|
170
|
+
prerelease_part = raw_version.split("-", 1)[1]
|
|
171
|
+
for ident in prerelease_part.split("."):
|
|
172
|
+
if ident.isdigit() and len(ident) > 1 and ident.startswith("0"):
|
|
173
|
+
raise ValueError(f"Leading zeros not allowed in prerelease identifier: {ident}")
|
|
174
|
+
return VersionConstraint(kind="exact", base=semver)
|
|
175
|
+
|
|
176
|
+
if kind == "caret":
|
|
177
|
+
if semver.major == 0:
|
|
178
|
+
if semver.minor == 0:
|
|
179
|
+
upper = SemVer(0, 0, semver.patch + 1)
|
|
180
|
+
else:
|
|
181
|
+
upper = SemVer(0, semver.minor + 1, 0)
|
|
182
|
+
else:
|
|
183
|
+
upper = SemVer(semver.major + 1, 0, 0)
|
|
184
|
+
return VersionConstraint(kind="caret", base=semver, upper_exclusive=upper)
|
|
185
|
+
|
|
186
|
+
if kind == "tilde":
|
|
187
|
+
upper = SemVer(semver.major, semver.minor + 1, 0)
|
|
188
|
+
return VersionConstraint(kind="tilde", base=semver, upper_exclusive=upper)
|
|
189
|
+
|
|
190
|
+
raise ValueError(f"Unknown constraint kind: {constraint_str}")
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def matches_constraint(version: SemVer, constraint: VersionConstraint) -> bool:
|
|
194
|
+
"""Check if a canonical SemVer matches a parsed constraint."""
|
|
195
|
+
if constraint.kind == "exact":
|
|
196
|
+
return version == constraint.base
|
|
197
|
+
|
|
198
|
+
if version.is_prerelease:
|
|
199
|
+
return False
|
|
200
|
+
|
|
201
|
+
if version < constraint.base:
|
|
202
|
+
return False
|
|
203
|
+
if constraint.upper_exclusive is not None and version >= constraint.upper_exclusive:
|
|
204
|
+
return False
|
|
205
|
+
return True
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: itqan-cli
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Itqan Quranic Asset Manager: install and pin Itqan Quranic assets in your project.
|
|
5
|
+
Project-URL: Homepage, https://github.com/Itqan-community/itqan-cli
|
|
6
|
+
Project-URL: Repository, https://github.com/Itqan-community/itqan-cli
|
|
7
|
+
Project-URL: Issues, https://github.com/Itqan-community/itqan-cli/issues
|
|
8
|
+
Project-URL: Manifest format, https://github.com/Itqan-community/cms-backend/blob/main/docs/ASSET_MANIFEST.md
|
|
9
|
+
Author: Itqan
|
|
10
|
+
Author-email: Hassaan Alansary <hassaanalansary@yahoo.com>
|
|
11
|
+
License-Expression: MIT
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Keywords: assets,cli,itqan,mushaf,package-manager,quran,quranic,tafsir
|
|
14
|
+
Classifier: Development Status :: 3 - Alpha
|
|
15
|
+
Classifier: Environment :: Console
|
|
16
|
+
Classifier: Intended Audience :: Developers
|
|
17
|
+
Classifier: Operating System :: OS Independent
|
|
18
|
+
Classifier: Programming Language :: Python :: 3
|
|
19
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
23
|
+
Classifier: Topic :: Religion
|
|
24
|
+
Classifier: Topic :: Software Development :: Build Tools
|
|
25
|
+
Requires-Python: >=3.11
|
|
26
|
+
Requires-Dist: click>=8.1
|
|
27
|
+
Requires-Dist: pyyaml>=6.0
|
|
28
|
+
Requires-Dist: questionary>=2.1
|
|
29
|
+
Requires-Dist: requests>=2.31
|
|
30
|
+
Description-Content-Type: text/markdown
|
|
31
|
+
|
|
32
|
+
# itqan-cli
|
|
33
|
+
|
|
34
|
+
**Itqan Quranic Asset Manager**
|
|
35
|
+
|
|
36
|
+
Install and pin [Itqan](https://cms.itqan.dev) Quranic assets (mushafs, tafsirs, translations,
|
|
37
|
+
fonts) in your project, the way a package manager does for code.
|
|
38
|
+
|
|
39
|
+
You declare the assets you use and the versions you accept in `itqan-assets.yaml`. The CLI
|
|
40
|
+
resolves them against the Itqan registry, downloads them, and records the exact versions in
|
|
41
|
+
`itqan-assets.lock`, so teammates and CI get the same files.
|
|
42
|
+
|
|
43
|
+
## Install
|
|
44
|
+
|
|
45
|
+
Requires Python 3.11+.
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
pipx install itqan-cli # or: uv tool install itqan-cli
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
This installs the `itqan` command; `itqan-cli` is the same command under the package's name.
|
|
52
|
+
|
|
53
|
+
### Without Python
|
|
54
|
+
|
|
55
|
+
Each [GitHub Release](https://github.com/Itqan-community/itqan-cli/releases) has a standalone
|
|
56
|
+
`itqan` executable for macOS (arm64, x86_64), Linux (x86_64, arm64) and Windows (x86_64), named
|
|
57
|
+
`itqan-<version>-<os>-<arch>` (`.exe` on Windows). Download yours, check it against
|
|
58
|
+
`SHA256SUMS` and put it on your `PATH` as `itqan`. For example, on an Apple Silicon Mac:
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
v=0.2.0 # the release you want
|
|
62
|
+
curl -fLO "https://github.com/Itqan-community/itqan-cli/releases/download/v$v/itqan-$v-macos-arm64"
|
|
63
|
+
curl -fLO "https://github.com/Itqan-community/itqan-cli/releases/download/v$v/SHA256SUMS"
|
|
64
|
+
shasum -a 256 --check --ignore-missing SHA256SUMS
|
|
65
|
+
chmod +x "itqan-$v-macos-arm64"
|
|
66
|
+
sudo mv "itqan-$v-macos-arm64" /usr/local/bin/itqan
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
The binaries aren't notarized by Apple, so macOS blocks one downloaded with a browser. Clear the
|
|
70
|
+
quarantine flag to allow it: `xattr -d com.apple.quarantine /usr/local/bin/itqan`. (`curl`
|
|
71
|
+
doesn't set the flag.) On Linux, use `sha256sum --check --ignore-missing SHA256SUMS`.
|
|
72
|
+
|
|
73
|
+
## Quick start
|
|
74
|
+
|
|
75
|
+
```bash
|
|
76
|
+
itqan init # writes itqan-assets.yaml with a few real assets as examples
|
|
77
|
+
itqan browse # search the catalog and add more assets to it
|
|
78
|
+
itqan install # downloads them and writes itqan-assets.lock
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
Commit both `itqan-assets.yaml` and `itqan-assets.lock`. The downloaded files are reproducible
|
|
82
|
+
from the lockfile, so add the assets folder to `.gitignore` if you like.
|
|
83
|
+
|
|
84
|
+
## The manifest
|
|
85
|
+
|
|
86
|
+
```yaml
|
|
87
|
+
schema_version: 1
|
|
88
|
+
|
|
89
|
+
# Folder the assets are downloaded into, relative to this file (default: assets).
|
|
90
|
+
assets_dir: "public/quran"
|
|
91
|
+
|
|
92
|
+
assets:
|
|
93
|
+
# Source language of the asset.
|
|
94
|
+
tafsir-jalalayn:
|
|
95
|
+
version: "^2.0.0" # any 2.x from 2.0.0 on
|
|
96
|
+
|
|
97
|
+
# The same asset in English: its own entry, pointing at the asset.
|
|
98
|
+
tafsir-jalalayn-en:
|
|
99
|
+
asset: tafsir-jalalayn
|
|
100
|
+
language: en
|
|
101
|
+
version: "~1.3" # any 1.3.x
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
Each language of an asset has its own version history, so each gets its own entry, constraint,
|
|
105
|
+
lock entry and folder (`public/quran/tafsir-jalalayn-en/`). The full format is specified in
|
|
106
|
+
[ASSET_MANIFEST.md](https://github.com/Itqan-community/cms-backend/blob/main/docs/ASSET_MANIFEST.md).
|
|
107
|
+
|
|
108
|
+
## Commands
|
|
109
|
+
|
|
110
|
+
| Command | What it does |
|
|
111
|
+
|---|---|
|
|
112
|
+
| `itqan init` | Create `itqan-assets.yaml` from the registry's catalog (commented examples when offline). `--assets-dir`, `--force`. |
|
|
113
|
+
| `itqan browse [QUERY]` | Search the registry's catalog and pick assets to add to `itqan-assets.yaml` (created if missing), then optionally install them. Type in the picker to filter further. `--category`, `--no-interactive` (print a table; the default outside a terminal), `--json`. |
|
|
114
|
+
| `itqan login` | Save your API key (create one at [cms.itqan.dev/account/api-keys](https://cms.itqan.dev/account/api-keys)). The key is checked first, then saved for that registry, readable only by you. `--api-key` to pass it without the prompt. |
|
|
115
|
+
| `itqan logout` | Remove the saved key. |
|
|
116
|
+
| `itqan install` | Resolve, download and lock. Uses the lockfile's exact versions when it is up to date; `--force` re-resolves. |
|
|
117
|
+
| `itqan sync` | Same as `install`. |
|
|
118
|
+
| `itqan --version` | Print the CLI version. |
|
|
119
|
+
|
|
120
|
+
## Configuration
|
|
121
|
+
|
|
122
|
+
| Option | Environment variable | Default |
|
|
123
|
+
|---|---|---|
|
|
124
|
+
| `--registry-url` | `ITQAN_REGISTRY_URL` | `https://api.cms.itqan.dev` |
|
|
125
|
+
| `--api-key` | `ITQAN_API_KEY` | the key saved by `itqan login` for the registry, if any |
|
|
126
|
+
|
|
127
|
+
`itqan login` saves keys in `~/.config/itqan/credentials` (`%APPDATA%\itqan` on Windows; set
|
|
128
|
+
`ITQAN_CONFIG_DIR` to move it). `--api-key` and `ITQAN_API_KEY`, for CI, take precedence over it.
|
|
129
|
+
|
|
130
|
+
## Assets that need access approval
|
|
131
|
+
|
|
132
|
+
Some publishers approve each developer before their assets can be downloaded. `itqan browse`
|
|
133
|
+
lists these too, marked `request access`, `access pending` or `access rejected`, with a link to
|
|
134
|
+
the asset's page on cms.itqan.dev where you request access. They can't be added until your
|
|
135
|
+
request is approved; then run `itqan login` with your API key and they show as `granted`.
|
|
136
|
+
`itqan install` says which assets in your manifest still need access, and where to ask.
|
|
137
|
+
|
|
138
|
+
## Development
|
|
139
|
+
|
|
140
|
+
```bash
|
|
141
|
+
uv sync
|
|
142
|
+
uv run pytest
|
|
143
|
+
uv build
|
|
144
|
+
uv run --group binary pyinstaller --onefile --name itqan --copy-metadata itqan-cli --specpath build src/itqan_cli/__main__.py # dist/itqan
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
Releases are published from version tags; see [RELEASING.md](RELEASING.md).
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
itqan_cli/__init__.py,sha256=2aXF5qBe7xpVVy2CHAMDrDuVZri47A_dVV3RcC8R0Tk,36
|
|
2
|
+
itqan_cli/__main__.py,sha256=1odaSDmH7sYrQN-Esl7OoPH6wM7MOwaMod9mt-ivsFY,74
|
|
3
|
+
itqan_cli/browse.py,sha256=nnqiBSB1TT6H0Gub8Ln03HSZwpf9wNGdGVvJCABtiE0,14030
|
|
4
|
+
itqan_cli/client.py,sha256=F-vhy0pozHB95b5aMpOQwiraCmaV5A2hiSusvVUyjTQ,12883
|
|
5
|
+
itqan_cli/credentials.py,sha256=x_uDY_ElxgMfl2deFLLilQzYjL7IOPRh9gdHbMgG7so,3083
|
|
6
|
+
itqan_cli/downloader.py,sha256=Vm0LFW1WiEmtgDZp_IlS6RqFT4sJ0ykeBVHOkuck4Gw,9045
|
|
7
|
+
itqan_cli/exceptions.py,sha256=0gLzPdUTQlULsbeZ1yW9izFA3XUTwzgPk9TY94hajm8,1960
|
|
8
|
+
itqan_cli/init_template.py,sha256=CsQrEqDC9CXJM5ZN0zR2fYnBiV-vrlwi8Oh0dBRWBX4,4844
|
|
9
|
+
itqan_cli/lockfile.py,sha256=HtzDMtWvJgbZeU60w0ajtBHlJxXPDQRqybMrwGHHU_U,10697
|
|
10
|
+
itqan_cli/main.py,sha256=DnhjyuWYXHJrX-5Z8LNtAbHquBSVLZJPQ3r0WIXGE-I,19438
|
|
11
|
+
itqan_cli/manifest.py,sha256=xcMb0rhJf_vS3u7G8hR0URpB1_DMZA-__zqibK7_Mgk,10719
|
|
12
|
+
itqan_cli/semver.py,sha256=LcsuqbuHOVXVIAwIO9ATG38S-ckrFttGVTKSnmVqwKA,6608
|
|
13
|
+
itqan_cli-0.1.0.dist-info/METADATA,sha256=pRpjwZlP-SRUdbsdvy9lFNbveQKscinfamB7nV3i2UM,6366
|
|
14
|
+
itqan_cli-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
15
|
+
itqan_cli-0.1.0.dist-info/entry_points.txt,sha256=q9uVS5X2wSU1w4AeqnraJTOpdVmx5zxssRBEL3TMl-8,76
|
|
16
|
+
itqan_cli-0.1.0.dist-info/licenses/LICENSE,sha256=nZiSfqFbxg8aVaXy7BAIYu02w60VbZrozdXFAsGT6rI,1072
|
|
17
|
+
itqan_cli-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Itqan Community
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|