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/lockfile.py ADDED
@@ -0,0 +1,285 @@
1
+ """Lockfile parser, serializer, and state evaluator adhering to docs/ASSET_MANIFEST.md §5."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from enum import StrEnum
7
+ from pathlib import Path
8
+
9
+ from itqan_cli.exceptions import (
10
+ LockfileError,
11
+ YamlProfileViolationError,
12
+ )
13
+ from itqan_cli.manifest import (
14
+ AssetManifest,
15
+ _StrictYamlLoader,
16
+ load_manifest,
17
+ )
18
+ from itqan_cli.semver import (
19
+ matches_constraint,
20
+ parse_constraint,
21
+ parse_semver,
22
+ )
23
+
24
+
25
+ class LockfileState(StrEnum):
26
+ ABSENT = "ABSENT"
27
+ INVALID = "INVALID"
28
+ ORPHAN = "ORPHAN"
29
+ MISSING = "MISSING"
30
+ STALE = "STALE"
31
+ FRESH = "FRESH"
32
+
33
+
34
+ @dataclass(frozen=True, slots=True)
35
+ class LockfileEntry:
36
+ """``slug`` is the manifest entry name. ``asset`` is recorded only when the
37
+ entry installs a different slug; ``language`` only when the entry declares one."""
38
+
39
+ slug: str
40
+ constraint: str
41
+ version: str
42
+ asset: str | None = None
43
+ language: str | None = None
44
+
45
+
46
+ @dataclass(frozen=True, slots=True)
47
+ class AssetLockfile:
48
+ lockfile_version: int
49
+ manifest_schema_version: int
50
+ assets: dict[str, LockfileEntry]
51
+
52
+
53
+ def parse_lockfile_content(content_bytes: bytes) -> AssetLockfile:
54
+ """Parse raw bytes of a lockfile strictly according to §5."""
55
+ if not content_bytes or not content_bytes.strip():
56
+ raise YamlProfileViolationError("Lockfile is empty or contains only whitespace.")
57
+
58
+ if content_bytes.startswith(b"\xef\xbb\xbf"):
59
+ raise YamlProfileViolationError("UTF-8 BOM is rejected in lockfile.")
60
+
61
+ try:
62
+ content_str = content_bytes.decode("utf-8")
63
+ except UnicodeDecodeError as exc:
64
+ raise YamlProfileViolationError(f"Lockfile must be valid UTF-8: {exc}") from exc
65
+
66
+ loader = _StrictYamlLoader(content_str)
67
+ try:
68
+ node = loader.get_single_node()
69
+ except Exception as exc:
70
+ raise YamlProfileViolationError(f"Invalid YAML syntax in lockfile: {exc}") from exc
71
+
72
+ if node is None:
73
+ raise YamlProfileViolationError("Lockfile contains no YAML document.")
74
+
75
+ try:
76
+ data = loader.construct_object(node, deep=True)
77
+ except Exception as exc:
78
+ raise YamlProfileViolationError(f"Failed to parse lockfile YAML: {exc}") from exc
79
+
80
+ if not isinstance(data, dict):
81
+ raise YamlProfileViolationError("Lockfile root must be a mapping.")
82
+
83
+ # Strict schema checking
84
+ allowed_top_keys = {"lockfile_version", "manifest_schema_version", "assets"}
85
+ for k in data.keys():
86
+ if k not in allowed_top_keys:
87
+ raise LockfileError(f"Unknown top-level key in lockfile: '{k}'")
88
+
89
+ lockfile_version = data.get("lockfile_version")
90
+ if lockfile_version != 1 or isinstance(lockfile_version, bool):
91
+ raise LockfileError(f"Unsupported lockfile_version {lockfile_version}. Expected 1.")
92
+
93
+ manifest_schema_version = data.get("manifest_schema_version")
94
+ if manifest_schema_version != 1 or isinstance(manifest_schema_version, bool):
95
+ raise LockfileError(f"Unsupported manifest_schema_version {manifest_schema_version}. Expected 1.")
96
+
97
+ assets_raw = data.get("assets")
98
+ if not isinstance(assets_raw, dict):
99
+ raise LockfileError("'assets' in lockfile must be a mapping.")
100
+
101
+ entries: dict[str, LockfileEntry] = {}
102
+ for slug, entry_data in assets_raw.items():
103
+ if not isinstance(slug, str):
104
+ raise LockfileError(f"Lockfile asset slug must be a string, got {type(slug).__name__}.")
105
+
106
+ if not isinstance(entry_data, dict):
107
+ raise LockfileError(f"Entry for asset '{slug}' must be a mapping.")
108
+
109
+ allowed_entry_keys = {"constraint", "version", "asset", "language"}
110
+ for ek in entry_data.keys():
111
+ if ek not in allowed_entry_keys:
112
+ raise LockfileError(f"Unknown key '{ek}' in lockfile entry for '{slug}'.")
113
+
114
+ if "constraint" not in entry_data:
115
+ raise LockfileError(f"Missing 'constraint' in lockfile entry for '{slug}'.")
116
+ if "version" not in entry_data:
117
+ raise LockfileError(f"Missing 'version' in lockfile entry for '{slug}'.")
118
+
119
+ constraint_val = entry_data["constraint"]
120
+ version_val = entry_data["version"]
121
+
122
+ if not isinstance(constraint_val, str):
123
+ raise LockfileError(f"'constraint' for '{slug}' must be a string.")
124
+ if not isinstance(version_val, str):
125
+ raise LockfileError(f"'version' for '{slug}' must be a string.")
126
+
127
+ # Canonical SemVer checking without build metadata
128
+ if "+" in version_val:
129
+ raise LockfileError(f"Build metadata not allowed in lockfile version: '{version_val}'")
130
+
131
+ semver = parse_semver(version_val)
132
+ if semver is None or version_val != semver.to_canonical_string():
133
+ raise LockfileError(
134
+ f"Version '{version_val}' for '{slug}' is not in canonical three-component SemVer form."
135
+ )
136
+
137
+ optional: dict[str, str | None] = {}
138
+ for field in ("asset", "language"):
139
+ value = entry_data.get(field)
140
+ if value is not None and (not isinstance(value, str) or not value):
141
+ raise LockfileError(f"'{field}' for '{slug}' must be a non-empty string.")
142
+ optional[field] = value
143
+
144
+ entries[slug] = LockfileEntry(
145
+ slug=slug,
146
+ constraint=constraint_val,
147
+ version=version_val,
148
+ asset=optional["asset"],
149
+ language=optional["language"],
150
+ )
151
+
152
+ return AssetLockfile(
153
+ lockfile_version=lockfile_version,
154
+ manifest_schema_version=manifest_schema_version,
155
+ assets=entries,
156
+ )
157
+
158
+
159
+ def serialize_lockfile(lockfile: AssetLockfile) -> bytes:
160
+ """Serialize lockfile to byte-exact deterministic UTF-8 bytes adhering to §5.
161
+
162
+ - UTF-8 without BOM
163
+ - LF line endings with exactly one newline at EOF
164
+ - 2 spaces indentation
165
+ - Keys double-quoted with standard escaping
166
+ - Sorted ascending by slug's UTF-8 byte sequence
167
+ """
168
+ lines: list[str] = [
169
+ f"lockfile_version: {lockfile.lockfile_version}",
170
+ f"manifest_schema_version: {lockfile.manifest_schema_version}",
171
+ "",
172
+ ]
173
+
174
+ if not lockfile.assets:
175
+ lines.append("assets: {}")
176
+ else:
177
+ lines.append("assets:")
178
+ # Sort by slug UTF-8 byte sequence
179
+ sorted_slugs = sorted(lockfile.assets.keys(), key=lambda s: s.encode("utf-8"))
180
+ for slug in sorted_slugs:
181
+ entry = lockfile.assets[slug]
182
+ # Escape quotes
183
+ escaped_slug = slug.replace("\\", "\\\\").replace('"', '\\"')
184
+ escaped_constraint = entry.constraint.replace("\\", "\\\\").replace('"', '\\"')
185
+ escaped_version = entry.version.replace("\\", "\\\\").replace('"', '\\"')
186
+
187
+ lines.append(f' "{escaped_slug}":')
188
+ for field in ("asset", "language"):
189
+ value = getattr(entry, field)
190
+ if value is not None:
191
+ escaped_value = value.replace("\\", "\\\\").replace('"', '\\"')
192
+ lines.append(f' {field}: "{escaped_value}"')
193
+ lines.append(f' constraint: "{escaped_constraint}"')
194
+ lines.append(f' version: "{escaped_version}"')
195
+
196
+ lines.append("") # Ensures single trailing newline
197
+ return "\n".join(lines).encode("utf-8")
198
+
199
+
200
+ def evaluate_lockfile_state(
201
+ manifest_path: Path | str,
202
+ lockfile_path: Path | str,
203
+ ) -> tuple[LockfileState, AssetManifest | None, AssetLockfile | None]:
204
+ """Evaluate repository state into one of the 6 canonical states per §5.
205
+
206
+ Evaluation order:
207
+ 1. ABSENT (neither file present)
208
+ 2. INVALID (manifest or lockfile invalid)
209
+ 3. ORPHAN (valid lockfile present, manifest absent)
210
+ 4. MISSING (valid manifest present, lockfile absent)
211
+ 5. STALE (manifest and lockfile valid, but mismatched)
212
+ 6. FRESH (manifest and lockfile valid and fully matching)
213
+ """
214
+ m_path = Path(manifest_path)
215
+ l_path = Path(lockfile_path)
216
+
217
+ m_exists = m_path.is_file()
218
+ l_exists = l_path.is_file()
219
+
220
+ # 1. ABSENT
221
+ if not m_exists and not l_exists:
222
+ return LockfileState.ABSENT, None, None
223
+
224
+ # Parse and validate lockfile if present (lockfile validation precedes ORPHAN)
225
+ parsed_lockfile: AssetLockfile | None = None
226
+ if l_exists:
227
+ try:
228
+ parsed_lockfile = parse_lockfile_content(l_path.read_bytes())
229
+ except Exception:
230
+ return LockfileState.INVALID, None, None
231
+
232
+ # 3. ORPHAN (lockfile valid, manifest absent)
233
+ if not m_exists and l_exists:
234
+ return LockfileState.ORPHAN, None, parsed_lockfile
235
+
236
+ # Parse and validate manifest
237
+ parsed_manifest: AssetManifest | None = None
238
+ try:
239
+ parsed_manifest = load_manifest(m_path)
240
+ except Exception:
241
+ # 2. INVALID precedes MISSING
242
+ return LockfileState.INVALID, None, parsed_lockfile
243
+
244
+ # 4. MISSING (manifest valid, lockfile absent)
245
+ if m_exists and not l_exists:
246
+ return LockfileState.MISSING, parsed_manifest, None
247
+
248
+ assert parsed_lockfile is not None
249
+ assert parsed_manifest is not None
250
+
251
+ # Check STALE vs FRESH
252
+ # A. Schema version mismatch
253
+ if parsed_lockfile.manifest_schema_version != parsed_manifest.schema_version:
254
+ return LockfileState.STALE, parsed_manifest, parsed_lockfile
255
+
256
+ # B. Asset Key-Set mismatch
257
+ manifest_slugs = set(parsed_manifest.assets.keys())
258
+ lockfile_slugs = set(parsed_lockfile.assets.keys())
259
+ if manifest_slugs != lockfile_slugs:
260
+ return LockfileState.STALE, parsed_manifest, parsed_lockfile
261
+
262
+ # C. Constraint text mismatch & satisfaction
263
+ for slug in manifest_slugs:
264
+ m_entry = parsed_manifest.assets[slug]
265
+ l_entry = parsed_lockfile.assets[slug]
266
+
267
+ # Literal constraint text must match verbatim
268
+ if m_entry.version != l_entry.constraint:
269
+ return LockfileState.STALE, parsed_manifest, parsed_lockfile
270
+
271
+ # The entry must still name the same asset and language rendition
272
+ if (l_entry.asset or slug) != m_entry.asset or l_entry.language != m_entry.language:
273
+ return LockfileState.STALE, parsed_manifest, parsed_lockfile
274
+
275
+ # Locked version must satisfy the constraint
276
+ try:
277
+ parsed_constraint = parse_constraint(m_entry.version)
278
+ locked_semver = parse_semver(l_entry.version)
279
+ if locked_semver is None or not matches_constraint(locked_semver, parsed_constraint):
280
+ return LockfileState.STALE, parsed_manifest, parsed_lockfile
281
+ except Exception:
282
+ return LockfileState.STALE, parsed_manifest, parsed_lockfile
283
+
284
+ # 6. FRESH
285
+ return LockfileState.FRESH, parsed_manifest, parsed_lockfile