qmdc-model 0.3.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.
qmdc_model/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """qmdc-model — metamodel operator and linter for QMD workspaces."""
2
+
3
+ from importlib.metadata import version
4
+
5
+ # Single source of truth is pyproject.toml; scripts/bump_version.py changes it.
6
+ __version__ = version("qmdc-model")
qmdc_model/cli.py ADDED
@@ -0,0 +1,396 @@
1
+ """qmdc-model command-line interface: init, upgrade, lint, sop."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import hashlib
7
+ import os
8
+ import re
9
+ import stat
10
+ import sys
11
+ import tempfile
12
+ import unicodedata
13
+ from importlib import resources
14
+ from pathlib import Path
15
+ from string import Template
16
+
17
+ from . import __version__
18
+ from .linter import lint_workspace, issues_to_json
19
+
20
+
21
+ def _asset(*parts: str) -> str:
22
+ return resources.files("qmdc_model").joinpath(*parts).read_text(encoding="utf-8")
23
+
24
+
25
+ def _asset_path(*parts: str) -> Path:
26
+ """Filesystem path of a packaged asset (wheels install unzipped, so this is real)."""
27
+ return Path(str(resources.files("qmdc_model").joinpath(*parts)))
28
+
29
+
30
+ def _workspace_id(name: str) -> str:
31
+ """Derive a valid, stable QMD id from a directory name, preserving Unicode letters."""
32
+ normalized = unicodedata.normalize("NFKC", name).casefold()
33
+ slug = re.sub(r"_+", "_", "".join(ch if ch.isalnum() else "_" for ch in normalized)).strip("_")
34
+ if not slug:
35
+ digest = hashlib.sha256(name.encode("utf-8")).hexdigest()[:8]
36
+ return f"ws_{digest}"
37
+ if slug[0].isdigit():
38
+ return f"ws_{slug}"
39
+ return slug
40
+
41
+
42
+ def _workspace_label(name: str) -> str:
43
+ """A one-line human label that cannot inject another QMD object declaration."""
44
+ label = re.sub(r"\s+", " ", name).strip() or "Workspace"
45
+ return label.replace("[", "[").replace("]", "]")
46
+
47
+
48
+ # `*.vendor.qmd.md` files are OWNED by this tool: `upgrade` creates, overwrites and
49
+ # deletes them to match the installed version, so hand edits are always lost. Everything
50
+ # else init writes is a seed the author then owns.
51
+ VENDOR_SUFFIX = ".vendor.qmd.md"
52
+ MARKER_OPEN = "<!-- qmdc-model "
53
+
54
+
55
+ def _vendor_marker() -> str:
56
+ return (f"{MARKER_OPEN}{__version__} — generated file owned by the tool: "
57
+ f"`qmdc-model upgrade` rewrites or deletes it. Do not edit by hand. -->\n\n")
58
+
59
+
60
+ def _strip_marker(text: str) -> str:
61
+ """Drop the generated-file marker so two vendored copies compare by body alone."""
62
+ if text.startswith(MARKER_OPEN):
63
+ return text.partition("-->")[2].lstrip("\n")
64
+ return text
65
+
66
+
67
+ def _shipped_vendor() -> dict[str, str]:
68
+ """Vendored files this version ships: file name -> body (without the marker)."""
69
+ vendor_dir = _asset_path("vendor")
70
+ return {p.name: p.read_text(encoding="utf-8")
71
+ for p in sorted(vendor_dir.glob("*" + VENDOR_SUFFIX))}
72
+
73
+
74
+ class UpgradePathError(ValueError):
75
+ pass
76
+
77
+
78
+ def _assert_no_symlink(ws: Path, path: Path) -> None:
79
+ """Every component below ws must be a real path, never a redirect elsewhere."""
80
+ try:
81
+ rel = path.relative_to(ws)
82
+ except ValueError as e:
83
+ raise UpgradePathError(f"path is outside workspace: {path}") from e
84
+ cursor = ws
85
+ for part in rel.parts:
86
+ cursor = cursor / part
87
+ if cursor.is_symlink():
88
+ target = cursor.resolve(strict=False)
89
+ raise UpgradePathError(f"refusing symlink inside workspace: {cursor} -> {target}")
90
+ resolved_parent = path.parent.resolve(strict=False)
91
+ if not resolved_parent.is_relative_to(ws):
92
+ raise UpgradePathError(f"path resolves outside workspace: {path} -> {resolved_parent}")
93
+
94
+
95
+ def _metamodel_dirs(ws: Path) -> list[Path]:
96
+ """Every real `_metamodel` namespace contained in the workspace."""
97
+ found = []
98
+ for path in sorted(ws.rglob("_metamodel")):
99
+ _assert_no_symlink(ws, path)
100
+ if path.is_dir():
101
+ found.append(path)
102
+ elif path.exists():
103
+ raise UpgradePathError(f"_metamodel path is not a directory: {path}")
104
+ return found
105
+
106
+
107
+ def _validate_vendor_path(ws: Path, path: Path) -> None:
108
+ _assert_no_symlink(ws, path)
109
+ if path.exists() and not path.is_file():
110
+ raise UpgradePathError(f"vendor path is not a regular file: {path}")
111
+
112
+
113
+ def _preflight_plan(ws: Path, plan, *, require_writable: bool) -> None:
114
+ """Refuse unsafe paths always; check mutability before a real apply."""
115
+ for verb, path, _body, _why in plan:
116
+ _validate_vendor_path(ws, path)
117
+ if not require_writable:
118
+ continue
119
+ if path.exists():
120
+ immutable = getattr(stat, "UF_IMMUTABLE", 0) | getattr(stat, "SF_IMMUTABLE", 0)
121
+ if getattr(path.stat(), "st_flags", 0) & immutable:
122
+ raise UpgradePathError(f"vendor path is immutable: {path}")
123
+ if verb == "update" and not os.access(path, os.W_OK):
124
+ raise UpgradePathError(f"vendor file is not writable: {path}")
125
+ if verb in {"create", "delete"} and not os.access(path.parent, os.W_OK):
126
+ raise UpgradePathError(f"vendor directory is not writable: {path.parent}")
127
+
128
+
129
+ def _write_owned_file(path: Path, content: str) -> None:
130
+ """Atomically replace one tool-owned file without following/altering a hard link."""
131
+ temp_name = None
132
+ mode = stat.S_IMODE(path.stat().st_mode) if path.exists() else 0o644
133
+ try:
134
+ with tempfile.NamedTemporaryFile("w", encoding="utf-8", dir=path.parent,
135
+ prefix=".qmdc-model-", suffix=".tmp",
136
+ delete=False) as temp:
137
+ temp.write(content)
138
+ temp.flush()
139
+ os.fsync(temp.fileno())
140
+ temp_name = Path(temp.name)
141
+ os.chmod(temp_name, mode)
142
+ os.replace(temp_name, path)
143
+ temp_name = None
144
+ finally:
145
+ if temp_name is not None:
146
+ temp_name.unlink(missing_ok=True)
147
+
148
+
149
+ def _build_upgrade_plan(ws: Path, shipped: dict[str, str], *, require_writable: bool):
150
+ mm_dirs = _metamodel_dirs(ws)
151
+ if not mm_dirs:
152
+ return [], []
153
+ primary = ws / "_metamodel"
154
+ if primary not in mm_dirs:
155
+ primary = mm_dirs[0]
156
+
157
+ found: dict[str, list[Path]] = {}
158
+ for mm in mm_dirs:
159
+ for path in sorted(mm.glob("*" + VENDOR_SUFFIX)):
160
+ _validate_vendor_path(ws, path)
161
+ found.setdefault(path.name, []).append(path)
162
+
163
+ plan: list[tuple[str, Path, str | None, str]] = []
164
+ for name, body in shipped.items():
165
+ copies = sorted(found.get(name, []), key=lambda p: (p.parent != primary, len(p.parts)))
166
+ if not copies:
167
+ plan.append(("create", primary / name, body, ""))
168
+ continue
169
+ keep, extra = copies[0], copies[1:]
170
+ if keep.read_text(encoding="utf-8") != _vendor_marker() + body:
171
+ plan.append(("update", keep, body, ""))
172
+ for duplicate in extra:
173
+ plan.append(("delete", duplicate, None,
174
+ "duplicate copy — vendored once per workspace"))
175
+ for name, copies in found.items():
176
+ if name not in shipped:
177
+ plan.extend(("delete", p, None, "not shipped by this version") for p in copies)
178
+
179
+ _preflight_plan(ws, plan, require_writable=require_writable)
180
+ return mm_dirs, plan
181
+
182
+
183
+ def cmd_init(args) -> int:
184
+ if args.workspace == "":
185
+ print("error: workspace path must not be empty")
186
+ return 2
187
+ ws = Path(args.workspace).resolve()
188
+ if ws.exists() and not ws.is_dir():
189
+ print(f"error: workspace path '{ws}' exists and is not a directory")
190
+ return 2
191
+ created_dir = not ws.exists()
192
+ try:
193
+ ws.mkdir(parents=True, exist_ok=True)
194
+ mm = ws / "_metamodel"
195
+ _assert_no_symlink(ws, mm)
196
+ if mm.exists() and not mm.is_dir():
197
+ print(f"error: _metamodel path exists and is not a directory: {mm}")
198
+ return 2
199
+ mm.mkdir(exist_ok=True)
200
+ except (OSError, UpgradePathError) as e:
201
+ print(f"error: cannot initialize workspace: {e}")
202
+ return 2
203
+
204
+ root_readme = Template(_asset("templates", "workspace-readme.qmd.md")).substitute(
205
+ label=_workspace_label(ws.name), id=_workspace_id(ws.name)
206
+ )
207
+ targets = {
208
+ "readme.qmd.md": root_readme,
209
+ "_metamodel/readme.qmd.md": _asset("templates", "metamodel-readme.qmd.md"),
210
+ }
211
+ for name, body in _shipped_vendor().items():
212
+ targets[f"_metamodel/{name}"] = _vendor_marker() + body
213
+
214
+ created, skipped = [], []
215
+ try:
216
+ for rel, content in targets.items():
217
+ dest = ws / rel
218
+ if rel.endswith(VENDOR_SUFFIX):
219
+ _validate_vendor_path(ws, dest)
220
+ if dest.exists() or dest.is_symlink():
221
+ skipped.append(rel)
222
+ else:
223
+ dest.write_text(content, encoding="utf-8")
224
+ created.append(rel)
225
+ except (OSError, UpgradePathError) as e:
226
+ print(f"error: cannot initialize workspace: {e}")
227
+ return 2
228
+
229
+ if created_dir:
230
+ print(f" created {ws}/")
231
+ for rel in created:
232
+ print(f" created {rel}")
233
+ for rel in skipped:
234
+ print(f" skipped {rel} (exists)")
235
+ print(f"Initialized workspace {ws}")
236
+ return 0
237
+
238
+
239
+ def cmd_upgrade(args) -> int:
240
+ """Re-vendor the workspace so its vendored files match this version of the tool.
241
+
242
+ The tool owns `*.vendor.qmd.md` outright: a missing one is created, a stale one is
243
+ rewritten, and one this version no longer ships is deleted. Nothing else is touched —
244
+ the workspace's own readmes, KindSchemas and LintRules are the author's.
245
+
246
+ A vendored file is kept as ONE copy per workspace even though `_metamodel` namespaces
247
+ are many: the base meta-kinds carry fixed object ids, so a second copy makes every
248
+ reference inside them ambiguous. Extra copies are therefore removed, and the linter
249
+ finds the surviving one by `__kind` from anywhere in the workspace.
250
+ """
251
+ if args.workspace == "":
252
+ print("error: workspace path must not be empty")
253
+ return 2
254
+ ws = Path(args.workspace).resolve()
255
+ if not ws.is_dir():
256
+ print(f"error: workspace '{ws}' is not a directory")
257
+ return 2
258
+
259
+ try:
260
+ shipped = _shipped_vendor()
261
+ mm_dirs, plan = _build_upgrade_plan(ws, shipped,
262
+ require_writable=not args.dry_run)
263
+ except (OSError, UpgradePathError) as e:
264
+ print(f"error: cannot plan upgrade: {e}")
265
+ return 2
266
+ if not mm_dirs:
267
+ print(f"no _metamodel namespace under {ws} — run 'qmdc-model init' first")
268
+ return 0
269
+
270
+ if not plan:
271
+ print(f"vendored metaschema already at {__version__}: one workspace copy across "
272
+ f"{len(mm_dirs)} _metamodel namespace(s) — nothing to do")
273
+ return 0
274
+
275
+ done = {"create": "created", "update": "updated", "delete": "deleted"}
276
+ try:
277
+ for verb, path, body, why in plan:
278
+ rel = path.relative_to(ws)
279
+ note = f" ({why})" if why else ""
280
+ if args.dry_run:
281
+ print(f" would {verb} {rel}{note}")
282
+ continue
283
+ if verb == "delete":
284
+ path.unlink()
285
+ else:
286
+ _write_owned_file(path, _vendor_marker() + body)
287
+ print(f" {done[verb]} {rel}{note}")
288
+ except OSError as e:
289
+ print(f"error: upgrade failed while applying {path}: {e}")
290
+ return 2
291
+
292
+ if args.dry_run:
293
+ print(f"dry run: {len(plan)} change(s) pending, nothing written")
294
+ else:
295
+ print(f"Upgraded vendored metaschema to {__version__} in {ws}")
296
+ return 0
297
+
298
+
299
+ SOP_ASSET = ("sop", "sop-metamodel-creation.md")
300
+
301
+ def cmd_sop(args) -> int:
302
+ """Emit the metamodel-creation SOP shipped with — and version-locked to — this tool."""
303
+ if args.path:
304
+ p = _asset_path(*SOP_ASSET)
305
+ if not p.is_file():
306
+ print("error: the SOP ships inside the package but is not a file on disk")
307
+ return 2
308
+ print(p)
309
+ return 0
310
+ print(_asset(*SOP_ASSET), end="")
311
+ return 0
312
+
313
+
314
+ def cmd_lint(args) -> int:
315
+ if args.workspace == "":
316
+ print("error: workspace path must not be empty")
317
+ return 2
318
+ ws = Path(args.workspace)
319
+ issues = lint_workspace(ws)
320
+
321
+ if args.json:
322
+ print(issues_to_json(issues))
323
+ else:
324
+ errors = [i for i in issues if i.severity == "error"]
325
+ warnings = [i for i in issues if i.severity == "warning"]
326
+ infos = [i for i in issues if i.severity == "info"]
327
+ print(f"METAMODEL LINT ({ws})")
328
+ if not issues:
329
+ print(" ✅ ok")
330
+ icons = {"error": "❌", "warning": "⚠️", "info": "ℹ️"}
331
+ for i in issues:
332
+ icon = icons.get(i.severity, "❓")
333
+ location = f" {i.file}:{i.line}" if i.file else ""
334
+ print(f" {icon} [{i.code}]{location} {i.message or i.object}")
335
+ print(f"RESULT: {len(errors)} errors, {len(warnings)} warnings, {len(infos)} infos")
336
+ print("🎉 Lint PASSED" if not errors else "⛔ Lint FAILED")
337
+
338
+ return 1 if any(i.severity == "error" for i in issues) else 0
339
+
340
+
341
+ def _tolerate_narrow_console() -> None:
342
+ """Never crash on output: a cp1252 stdout (Windows pipes) cannot encode ✅/🎉.
343
+
344
+ Such streams keep their encoding but replace what they cannot show with '?'.
345
+ """
346
+ for stream in (sys.stdout, sys.stderr):
347
+ enc = (getattr(stream, "encoding", None) or "").lower().replace("-", "")
348
+ if enc != "utf8" and hasattr(stream, "reconfigure"):
349
+ stream.reconfigure(errors="replace")
350
+
351
+
352
+ def main(argv=None) -> int:
353
+ _tolerate_narrow_console()
354
+ p = argparse.ArgumentParser(prog="qmdc-model", description="Metamodel operator and linter for QMD workspaces")
355
+ p.add_argument("--version", action="version", version=f"qmdc-model {__version__}")
356
+ sub = p.add_subparsers(dest="command", required=True)
357
+
358
+ pi = sub.add_parser(
359
+ "init",
360
+ help="Create the workspace directory if missing, scaffold its root readme and the "
361
+ "_metamodel namespace, and vendor the base meta-kinds",
362
+ )
363
+ pi.add_argument("workspace", nargs="?", default=".")
364
+ pi.set_defaults(func=cmd_init)
365
+
366
+ pu = sub.add_parser(
367
+ "upgrade",
368
+ help="Re-vendor the workspace to this version: the tool owns *.vendor.qmd.md and "
369
+ "creates, rewrites or deletes them (one copy per workspace); nothing else is "
370
+ "touched",
371
+ )
372
+ pu.add_argument("workspace", nargs="?", default=".")
373
+ pu.add_argument("--dry-run", action="store_true",
374
+ help="Print the changes without writing or deleting anything")
375
+ pu.set_defaults(func=cmd_upgrade)
376
+
377
+ pl = sub.add_parser("lint", help="Lint a workspace against its metaschema and KindSchemas (two-phase)")
378
+ pl.add_argument("workspace", nargs="?", default=".")
379
+ pl.add_argument("--json", action="store_true", help="Emit structured issues as JSON")
380
+ pl.set_defaults(func=cmd_lint)
381
+
382
+ ps = sub.add_parser(
383
+ "sop",
384
+ help="Print the metamodel-creation SOP shipped with this version (the procedure "
385
+ "is version-locked to the checks the linter enforces)",
386
+ )
387
+ ps.add_argument("--path", action="store_true",
388
+ help="Print the SOP's path on disk instead of its text")
389
+ ps.set_defaults(func=cmd_sop)
390
+
391
+ args = p.parse_args(argv)
392
+ return args.func(args)
393
+
394
+
395
+ if __name__ == "__main__":
396
+ sys.exit(main())