diff --git a/scripts/check-layout.py b/scripts/check-layout.py index 0a10ff0..5c55dc8 100644 --- a/scripts/check-layout.py +++ b/scripts/check-layout.py @@ -1,10 +1,31 @@ #!/usr/bin/env python3 +"""Validate a Marqdo ecosystem Git tree. + +The checker follows the hierarchical governance rules of the Marqdo ecosystem +specification (sections 2-4, 13): + +* the root catalog describes direct components and domain aggregates; +* an active ``kind = "domain"`` gitlink is only expanded when ``--checkouts`` + is requested, at its exact pinned commit; +* each aggregate layer has its own ``components.toml`` / ``.gitmodules`` and + registers only its direct children; +* governance depth is limited to two gitlink levels (root -> domain -> leaf); +* global ids and remotes are unique, dependency edges resolve globally and + ``requires`` stays acyclic while ``checks_with`` may contain cycles. + +Commit identity comes from the Git tree (gitlinks), the authority for remotes +is ``.gitmodules`` and the catalog never repeats SHAs. The checker never +fetches from a network remote, never runs ``git submodule update`` and only +reads objects already present in the local repositories. +""" + import argparse import graphlib import re import subprocess import sys import tomllib +import unicodedata from pathlib import Path ROOT = Path(__file__).resolve().parents[1] @@ -14,10 +35,16 @@ ROOT_FILES = {".gitattributes", ".gitignore", ".gitmodules", "AGENTS.md", "LICEN ROOT_DIRS = {".gitea", ".woodpecker", "docs", "examples", "scripts"} CATEGORY_READMES = {"stdlib/README.md", "extensions/README.md"} RELEASE_ROLES = {"core": "base", "stdlib": "base", "extension": "optional", "tool": "optional", "test": "none"} +DOMAIN_RELEASE = {"none", "base"} +DOMAIN_FILES = {".gitattributes", ".gitignore", ".gitmodules", "AGENTS.md", "LICENSE", "README.md", "components.toml"} +DOMAIN_DIRS = {".gitea", ".woodpecker", "docs", "examples", "scripts", "tests"} +DOMAIN_CHILD_KINDS = {"stdlib", "extension", "tool"} +AUTHORITY = "https://git.cflmy.cn/cflmy" +ENTRY = r"(?:[a-zA-Z0-9_-]+/)*[a-zA-Z0-9_-][a-zA-Z0-9_.-]*" def git(*args, cwd=ROOT): - return subprocess.check_output(["git", "-C", cwd, *args]).decode() + return subprocess.check_output(["git", "-C", str(cwd), *args]).decode() def require(condition, message): @@ -25,55 +52,156 @@ def require(condition, message): raise ValueError(message) -def catalog(revision): - components = tomllib.loads(git("show", f"{revision}:components.toml")) - require(set(components) == {"component"} and isinstance(components["component"], list), "invalid catalog") - by_id = {} - paths = set() - for component in components["component"]: - state = component.get("state") - fields = FIELDS | ({"entry"} if state == "active" else set()) - require(set(component) == fields and state in {"active", "planned"}, f"invalid fields: {component}") - id = component["id"] - kind = component["kind"] - require(isinstance(id, str) and re.fullmatch(NAME, id) and id not in by_id, f"invalid or duplicate id: {id}") - require(kind in RELEASE_ROLES and component["release"] == RELEASE_ROLES[kind], f"invalid release role: {id}") - path = component["path"] - expected = { - "core": "cli" if id == "cli" else None, - "test": "tests/conformance" if id == "conformance" else None, - "stdlib": f"stdlib/{id.removeprefix('std-')}" if id.startswith("std-") else None, - "extension": f"extensions/{id}", - "tool": f"tools/{id}", - }[kind] - require(path == expected and path not in paths, f"invalid or duplicate path: {path}") - for key in ("owner", "scope"): - require(isinstance(component[key], str) and component[key].strip(), f"missing {key}: {id}") - for key in ("requires", "checks_with"): - items = component[key] - require(isinstance(items, list) and all(isinstance(item, str) for item in items), f"invalid {key}: {id}") - require(id not in items and len(set(items)) == len(items), f"invalid {key}: {id}") - if state == "active": - require(re.fullmatch(r"(?:[a-zA-Z0-9_-]+/)*[a-zA-Z0-9_-][a-zA-Z0-9_.-]*", component["entry"]), f"unsafe entry: {id}") - paths.add(path) - by_id[id] = component - - for id, component in by_id.items(): - for field in ("requires", "checks_with"): - for dependency in component[field]: - require(dependency in by_id, f"unknown dependency: {id} -> {dependency}") - target = by_id[dependency] - require(component["state"] != "active" or target["state"] == "active", f"active depends on planned: {id} -> {dependency}") - if field == "requires": - require(component["kind"] != "stdlib" or target["kind"] in {"core", "stdlib"}, f"stdlib dependency violation: {id} -> {dependency}") - require(component["kind"] != "tool" or target["kind"] == "core", f"tool dependency violation: {id} -> {dependency}") - tuple(graphlib.TopologicalSorter({id: item["requires"] for id, item in by_id.items()}).static_order()) - return by_id +def nfc(value): + return unicodedata.normalize("NFC", value) -def tree(revision): +class Layer: + """One governance level: the root tree or one expanded domain aggregate.""" + + def __init__(self, repo, revision, label, depth, order, components, gitlinks, active, planned, urls): + self.repo = Path(repo) + self.revision = revision + self.label = label + self.depth = depth + self.order = order + self.components = components + self.gitlinks = gitlinks + self.active = active + self.planned = planned + self.urls = urls + + +def read_blob(repo, revision, path, label): + try: + return git("show", f"{revision}:{path}", cwd=repo) + except subprocess.CalledProcessError: + return None + + +def check_relative_path(path, id, label): + require(isinstance(path, str) and path, f"{label}: invalid path for {id}: {path!r}") + require("\\" not in path and not path.startswith("/") and not path.endswith("/"), + f"{label}: invalid path for {id}: {path!r}") + segments = path.split("/") + require(all(segment and segment not in {".", ".."} for segment in segments), + f"{label}: invalid path for {id}: {path!r}") + require(all(re.fullmatch(NAME, segment) for segment in segments), + f"{label}: invalid path for {id}: {path!r}") + require(nfc(path) == path, f"{label}: non-NFC path for {id}: {path!r}") + return path + + +def expected_root_path(component): + kind = component["kind"] + id = component["id"] + if kind == "core": + return "cli" if id == "cli" else None + if kind == "test": + return "tests/conformance" if id == "conformance" else None + if kind == "stdlib": + return f"stdlib/{id.removeprefix('std-')}" if id.startswith("std-") else None + if kind == "extension": + return f"extensions/{id}" + if kind == "tool": + return f"tools/{id}" + if kind == "domain": + return "stdlib" if id == "stdlib" else f"extensions/{id}" + return None + + +def expected_remote(component, depth): + """Derive the single approved self-hosted HTTPS remote for a component. + + Root direct components keep their historical ``marqdo-`` / + ``marqdo-ext-`` / ``marqdo-extension-conformance`` repository names. + Components registered by a domain aggregate are independently named + ``marqdo-`` (for example ``marqdo-web-design``). + """ + id = component["id"] + kind = component["kind"] + if depth == 0: + if kind == "test": + name = "extension-conformance" + elif kind == "extension": + name = f"ext-{id}" + elif kind == "domain": + name = "stdlib" if id == "stdlib" else f"ext-{id}" + else: + name = id + else: + name = id + return f"{AUTHORITY}/marqdo-{name}.git" + + +def check_component(raw, depth, label, by_id, paths, path_keys): + require(isinstance(raw, dict), f"{label}: invalid component entry: {raw!r}") + id = raw.get("id") + state = raw.get("state") + require(state in {"active", "planned"}, f"{label}: invalid state: {id!r}") + fields = FIELDS | ({"entry"} if state == "active" else set()) + require(set(raw) == fields, f"{label}: invalid fields for {id!r}: {sorted(set(raw) ^ fields)}") + require(isinstance(id, str) and re.fullmatch(NAME, id), f"{label}: invalid id: {id!r}") + + for key in ("requires", "checks_with"): + items = raw[key] + require(isinstance(items, list) and all(isinstance(item, str) for item in items), + f"{label}: invalid {key}: {id}") + require(id not in items and len(set(items)) == len(items), f"{label}: invalid {key}: {id}") + + kind = raw["kind"] + require(kind in RELEASE_ROLES or kind == "domain", f"{label}: unknown kind: {id}: {kind!r}") + if kind == "domain": + require(depth == 0, f"{label}: domain kind is only allowed at the root layer: {id}") + require(raw["release"] in DOMAIN_RELEASE, f"{label}: invalid release role: {id}") + require(raw["requires"] == [], f"{label}: domain requires must be empty: {id}") + else: + require(depth == 0 or kind in DOMAIN_CHILD_KINDS, + f"{label}: component kind is not allowed inside a domain: {id} ({kind})") + require(raw["release"] == RELEASE_ROLES[kind], f"{label}: invalid release role: {id}") + + path = check_relative_path(raw["path"], id, label) + if depth == 0: + expected = expected_root_path(raw) + require(expected is not None and path == expected, + f"{label}: invalid path: {id}: {path} (expected {expected})") + require(path not in paths, f"{label}: invalid or duplicate path: {path}") + key = nfc(path).casefold() + require(key not in path_keys, f"{label}: path case/NFC conflict: {id}: {path}") + for other in paths: + require(not path.startswith(other + "/") and not other.startswith(path + "/"), + f"{label}: overlapping component path: {path} / {other}") + + for key in ("owner", "scope"): + require(isinstance(raw[key], str) and raw[key].strip(), f"{label}: missing {key}: {id}") + if state == "active": + require(isinstance(raw["entry"], str) and re.fullmatch(ENTRY, raw["entry"]), + f"{label}: unsafe entry: {id}") + + paths.add(path) + path_keys.add(key) + by_id[id] = raw + return raw + + +def parse_catalog(repo, revision, label): + text = read_blob(repo, revision, "components.toml", label) + require(text is not None, f"{label}: missing components.toml at {revision}") + try: + data = tomllib.loads(text) + except tomllib.TOMLDecodeError as error: + raise ValueError(f"{label}: invalid components.toml: {error}") from None + require(set(data) == {"component"} and isinstance(data["component"], list), f"{label}: invalid catalog") + return data["component"] + + +def tree_entries(repo, revision, label): + try: + output = git("ls-tree", "-rz", "--full-tree", revision, cwd=repo) + except subprocess.CalledProcessError: + raise ValueError(f"{label}: missing Git tree at {revision}") from None entries = {} - for record in git("ls-tree", "-rz", "--full-tree", revision).split("\0"): + for record in output.split("\0"): if record: metadata, path = record.split("\t", 1) mode, _, sha = metadata.split() @@ -81,17 +209,12 @@ def tree(revision): return entries -def validate(revision, checkouts): - components = catalog(revision) - active = {item["path"]: item for item in components.values() if item["state"] == "active"} +def check_root_tree(entries, active, planned, label): allowed_readmes = CATEGORY_READMES | { f'{item["path"]}/README.md' - for item in components.values() - if item["state"] == "planned" and item["kind"] in {"stdlib", "extension"} + for item in planned + if item["kind"] in {"stdlib", "extension", "domain"} } - entries = tree(revision) - gitlinks = {path: sha for path, (mode, sha) in entries.items() if mode == "160000"} - require(gitlinks.keys() == active.keys(), f"gitlink/catalog mismatch: {sorted(gitlinks.keys() ^ active.keys())}") for path, (mode, _) in entries.items(): root = path.split("/", 1)[0] require( @@ -99,35 +222,206 @@ def validate(revision, checkouts): or (mode in {"100644", "100755"} and ( path in ROOT_FILES or root in ROOT_DIRS and "/" in path or path.startswith("tests/integration/") )), - f"unexpected tracked path or mode: {path} ({mode})", + f"{label}: unexpected tracked path or mode: {path} ({mode})", ) + +def check_domain_tree(entries, active, planned, label): + """Aggregate layers only carry governance, docs, examples and tests. + + Production implementations stay in the child repositories: an aggregate + may not add a renderer, parser or driver under its own tree. + """ + allowed_readmes = {f'{item["path"]}/README.md' for item in planned} + for path, (mode, _) in entries.items(): + if path in active: + continue + if mode == "100644" and path in allowed_readmes: + continue + top = path.split("/", 1)[0] + top_level_doc = mode == "100644" and "/" not in path and path.endswith(".md") + require( + mode in {"100644", "100755"} and ( + path in DOMAIN_FILES or top_level_doc or (top in DOMAIN_DIRS and "/" in path) + ), + f"{label}: unexpected aggregate tracked path or mode: {path} ({mode})", + ) + + +def read_submodules(repo, revision, label): + if read_blob(repo, revision, ".gitmodules", label) is None: + return {} + try: + output = git("config", "--null", "--blob", f"{revision}:.gitmodules", "--list", cwd=repo) + except subprocess.CalledProcessError: + raise ValueError(f"{label}: invalid .gitmodules") from None config = {} - for record in git("config", "--null", "--blob", f"{revision}:.gitmodules", "--list").split("\0"): + for record in output.split("\0"): if record: key, value = record.split("\n", 1) - require(key not in config, f"duplicate submodule setting: {key}") + require(key not in config, f"{label}: duplicate submodule setting: {key}") config[key] = value - for path, item in active.items(): - prefix = f"submodule.{path}." - require(config.pop(prefix + "path", None) == path, f"missing or invalid submodule path: {path}") - name = item["id"] - if item["kind"] == "extension": - name = f"ext-{name}" - elif item["kind"] == "test": - name = "extension-conformance" - url = config.pop(prefix + "url", "") - require(url == f"https://git.cflmy.cn/cflmy/marqdo-{name}.git", f"invalid submodule URL: {path}") - if checkouts: - checkout = ROOT / path - sha = gitlinks[path] - require(checkout.resolve() == checkout and (checkout / ".git").exists(), f"missing submodule checkout: {path}") - require(git("rev-parse", "HEAD", cwd=checkout).strip() == sha, f"wrong checked-out commit: {path}") - require(not git("status", "--porcelain", cwd=checkout), f"dirty submodule: {path}") - entry = checkout / item["entry"] - require(entry.is_file() and entry.resolve() == entry, f"missing or symbolic entry: {path}/{item['entry']}") - print(f"{item['id']} {path} {gitlinks[path]}") - require(not config, f"unexpected submodule settings: {sorted(config)}") + return config + + +def check_submodules(config, active, depth, label, urls): + """Match ``.gitmodules`` sections by ``path``, not by section name. + + Git configuration keys are keyed by the submodule section name, which is + not required to equal the checked-out path. Path and URL remain the + authority for identity; any other setting (for example an ``update`` + command or a relative override) is rejected as unexpected. + """ + sections = {} + extras = [] + for key, value in config.items(): + match = re.fullmatch(r"submodule\.(.+)\.(path|url)", key) + if not match: + extras.append(key) + continue + name, field = match.groups() + sections.setdefault(name, {})[field] = value + by_path = {} + for name, fields in sections.items(): + require(set(fields) == {"path", "url"}, + f"{label}: unexpected submodule settings: " + f"{sorted(f'submodule.{name}.{field}' for field in fields ^ {'path', 'url'})}") + path = fields["path"] + require(path not in by_path, f"{label}: duplicate submodule path: {path}") + by_path[path] = fields["url"] + require(not extras, f"{label}: unexpected submodule settings: {sorted(extras)}") + for path, component in active.items(): + require(path in by_path, f"{label}: missing or invalid submodule path: {path}") + url = by_path.pop(path) + expected = expected_remote(component, depth) + require(url == expected, f"{label}: invalid submodule URL: {path}: {url!r}") + require(url not in urls, f"{label}: duplicate submodule remote: {path}: {url}") + urls[url] = path + require(not by_path, f"{label}: unexpected submodule settings: {sorted(by_path)}") + + +def read_layer(repo, revision, label, depth): + repo = Path(repo) + order = [] + components = {} + paths = set() + path_keys = set() + for raw in parse_catalog(repo, revision, label): + order.append(check_component(raw, depth, label, components, paths, path_keys)) + entries = tree_entries(repo, revision, label) + gitlinks = {path: sha for path, (mode, sha) in entries.items() if mode == "160000"} + active = {item["path"]: item for item in order if item["state"] == "active"} + planned = [item for item in order if item["state"] == "planned"] + require(gitlinks.keys() == active.keys(), + f"{label}: gitlink/catalog mismatch: {sorted(gitlinks.keys() ^ active.keys())}") + if depth == 0: + check_root_tree(entries, active, planned, label) + else: + check_domain_tree(entries, active, planned, label) + urls = {} + check_submodules(read_submodules(repo, revision, label), active, depth, label, urls) + return Layer(repo, revision, label, depth, order, components, gitlinks, active, planned, urls) + + +def verify_checkout(layer, component): + path = component["path"] + checkout = layer.repo / path + sha = layer.gitlinks[path] + require(checkout.resolve() == checkout and (checkout / ".git").exists(), + f"{layer.label}: missing submodule checkout: {path}") + try: + git("cat-file", "-e", f"{sha}^{{commit}}", cwd=checkout) + except subprocess.CalledProcessError: + raise ValueError(f"{layer.label}: missing committed object: {path}@{sha}") from None + require(git("rev-parse", "HEAD", cwd=checkout).strip() == sha, + f"{layer.label}: wrong checked-out commit: {path}") + status = ["status", "--porcelain"] + if component["kind"] == "domain": + # Child dirt is the responsibility of the child checkout and is + # reported by its own leaf check, not by the aggregate repository. + status.append("--ignore-submodules=all") + require(not git(*status, cwd=checkout), + f"{layer.label}: dirty submodule: {path}") + entry = checkout / component["entry"] + require(entry.is_file() and entry.resolve() == entry, + f"{layer.label}: missing or symbolic entry: {path}/{component['entry']}") + return checkout + + +def verify_leaf(layer, component): + checkout = verify_checkout(layer, component) + sha = layer.gitlinks[component["path"]] + label = f'{layer.label} leaf {component["id"]} ({component["path"]})' + nested = tree_entries(checkout, sha, label) + gitlinks = sorted(path for path, (mode, _) in nested.items() if mode == "160000") + require(not gitlinks, f"{label}: leaf must not register gitlinks: {gitlinks}") + + +def validate_graph(layers): + components = {} + for layer in layers: + for component in layer.order: + id = component["id"] + require(id not in components, f"{layer.label}: duplicate global id: {id}") + components[id] = (component, layer) + remotes = {} + for layer in layers: + for url, path in layer.urls.items(): + require(url not in remotes, f"{layer.label}: duplicate global remote: {path}: {url}") + remotes[url] = path + for layer in layers: + for component in layer.order: + id = component["id"] + for field in ("requires", "checks_with"): + for dependency in component[field]: + require(dependency in components, f"{layer.label}: unknown dependency: {id} -> {dependency}") + target, _ = components[dependency] + require(component["state"] != "active" or target["state"] == "active", + f"{layer.label}: active depends on planned: {id} -> {dependency}") + if field != "requires": + continue + target_kind = target["kind"] + source_kind = component["kind"] + require(target_kind != "domain", + f"{layer.label}: requires must not target a domain: {id} -> {dependency}") + if source_kind in {"core", "domain"}: + require(False, f"{layer.label}: dependency violation: {id} must not require {dependency}") + if source_kind == "stdlib": + require(target_kind in {"core", "stdlib"}, + f"{layer.label}: stdlib dependency violation: {id} -> {dependency}") + elif source_kind == "tool": + require(target_kind in {"core", "extension"}, + f"{layer.label}: tool dependency violation: {id} -> {dependency}") + elif source_kind == "extension": + require(target_kind in {"core", "stdlib", "extension"}, + f"{layer.label}: extension dependency violation: {id} -> {dependency}") + try: + graph = {id: list(item["requires"]) for id, (item, _) in components.items()} + tuple(graphlib.TopologicalSorter(graph).static_order()) + except graphlib.CycleError as error: + raise ValueError(f"root: requires DAG cycle: {error}") from None + + +def validate(revision, checkouts): + layers = [read_layer(ROOT, revision, "root", 0)] + if checkouts: + root = layers[0] + for component in root.active.values(): + verify_checkout(root, component) + for path, component in root.active.items(): + if component["kind"] != "domain": + continue + domain_repo = ROOT / path + domain = read_layer(domain_repo, root.gitlinks[path], + f"domain {component['id']} ({path})", 1) + layers.append(domain) + for child in domain.active.values(): + verify_leaf(domain, child) + validate_graph(layers) + for layer in layers: + for component in layer.order: + if component["state"] == "active": + print(f'{component["id"]} {component["path"]} {layer.gitlinks[component["path"]]}') def main(): diff --git a/tests/integration/test_layout.py b/tests/integration/test_layout.py index d3c9365..c794f5d 100644 --- a/tests/integration/test_layout.py +++ b/tests/integration/test_layout.py @@ -1,4 +1,5 @@ import importlib.util +import shutil import subprocess import tempfile import unittest @@ -37,6 +38,77 @@ checks_with = [] release = "base" ''' +CORE_URL = "https://git.cflmy.cn/cflmy/marqdo-cli.git" + +WEB_DOMAIN = ''' +[[component]] +id = "web" +path = "extensions/web" +kind = "domain" +state = "active" +owner = "maintainer" +scope = "web prototype domain governance" +requires = [] +checks_with = [] +release = "none" +entry = "scripts/integration.sh" +''' + +STDLIB_DOMAIN = ''' +[[component]] +id = "stdlib" +path = "stdlib" +kind = "domain" +state = "active" +owner = "maintainer" +scope = "standard library bundle assembly" +requires = [] +checks_with = [] +release = "base" +entry = "scripts/integration.sh" +''' + +DOMAIN = ''' +[[component]] +id = "web-design" +path = "design" +kind = "extension" +state = "active" +owner = "maintainer" +scope = "design document interpretation" +requires = ["cli"] +checks_with = [] +release = "optional" +entry = "scripts/ci.sh" + +[[component]] +id = "web-preview" +path = "preview" +kind = "tool" +state = "active" +owner = "maintainer" +scope = "prototype rendering" +requires = ["cli", "web-design"] +checks_with = [] +release = "optional" +entry = "scripts/ci.sh" + +[[component]] +id = "web-components" +path = "components" +kind = "extension" +state = "planned" +owner = "maintainer" +scope = "design templates" +requires = ["web-design"] +checks_with = ["web-preview"] +release = "optional" +''' + + +def catalog(*blocks): + return "".join(blocks) + class LayoutTests(unittest.TestCase): def setUp(self): @@ -52,7 +124,7 @@ class LayoutTests(unittest.TestCase): def git(self, *args, cwd=None): return subprocess.check_output(["git", "-C", cwd or self.root, *args]).decode() - def candidate(self, metadata=CLI, url="https://git.cflmy.cn/cflmy/marqdo-cli.git", extra=None, file=None): + def candidate(self, metadata=CLI, url=CORE_URL, extra=None, file=None): (self.root / "components.toml").write_text(metadata) (self.root / ".gitmodules").write_text(f'[submodule "cli"]\npath = cli\nurl = {url}\n') self.git("add", ".gitmodules", "components.toml") @@ -110,5 +182,510 @@ class LayoutTests(unittest.TestCase): layout.validate("HEAD", True) +class HierarchicalLayoutTests(unittest.TestCase): + """End-to-end fixtures with real local Git repositories. + + The fixture builds root -> domain -> two leaves using only local clones: + no network remote is contacted, no ``git submodule update`` is executed. + """ + + def setUp(self): + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.root = Path(temporary.name) + sources = tempfile.TemporaryDirectory() + self.addCleanup(sources.cleanup) + self.sources = Path(sources.name) + self.enterContext(patch.object(layout, "ROOT", self.root)) + self.enterContext(patch.object(layout, "git", side_effect=self.git)) + self.git("init", "-q", "-b", "main") + self.git("commit", "--allow-empty", "-qm", "fixture") + + def git(self, *args, cwd=None): + return subprocess.check_output([ + "git", + "-c", "user.name=Test", + "-c", "user.email=test@example.invalid", + "-C", str(cwd or self.root), + *args, + ], stderr=subprocess.DEVNULL).decode() + + # -- fixture primitives ------------------------------------------------- + + def repo(self, name): + path = self.sources / name + path.mkdir(parents=True) + self.git("init", "-q", "-b", "main", cwd=path) + return path + + def write(self, repo, relative, content): + path = Path(repo) / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content) + + def stage(self, repo): + self.git("add", "-A", cwd=repo) + + def commit(self, repo, message): + self.git("commit", "-qm", message, cwd=repo) + return self.git("rev-parse", "HEAD", cwd=repo).strip() + + def gitlink(self, repo, path, sha): + self.git("update-index", "--add", "--cacheinfo", f"160000,{sha},{path}", cwd=repo) + + def modules(self, repo, entries): + self.write(repo, ".gitmodules", "".join( + f'[submodule "{path}"]\n\tpath = {path}\n\turl = {url}\n' for path, url in entries.items())) + + def leaf(self, name, entry="scripts/ci.sh", symlink_entry=False): + repo = self.repo(name) + if symlink_entry: + self.write(repo, "scripts/real.sh", "#!/bin/sh\nexit 0\n") + link = repo / entry + link.parent.mkdir(parents=True, exist_ok=True) + link.symlink_to("real.sh") + else: + self.write(repo, entry, "#!/bin/sh\nexit 0\n") + self.stage(repo) + return repo, self.commit(repo, f"leaf {name}") + + def leaf_with_gitlink(self, name): + inner = self.repo(f"{name}-inner") + self.write(inner, "scripts/ci.sh", "#!/bin/sh\nexit 0\n") + self.stage(inner) + inner_sha = self.commit(inner, "inner") + repo = self.repo(name) + self.write(repo, "scripts/ci.sh", "#!/bin/sh\nexit 0\n") + self.stage(repo) + self.gitlink(repo, "nested/inner", inner_sha) + return repo, self.commit(repo, f"leaf {name}") + + def domain(self, catalog_text, links, files=None, modules=None): + repo = self.repo("domain-source") + if catalog_text is not None: + self.write(repo, "components.toml", catalog_text) + self.write(repo, "scripts/integration.sh", "#!/bin/sh\nexit 0\n") + for relative, content in (files or {}).items(): + self.write(repo, relative, content) + entries = { + "design": "https://git.cflmy.cn/cflmy/marqdo-web-design.git", + "preview": "https://git.cflmy.cn/cflmy/marqdo-web-preview.git", + } + if modules is not None: + entries = modules + self.modules(repo, entries) + self.stage(repo) + for path, sha in links.items(): + self.gitlink(repo, path, sha) + return repo, self.commit(repo, "domain") + + def root_repo(self, catalog_text, links, modules): + self.write(self.root, "components.toml", catalog_text) + self.modules(self.root, modules) + self.stage(self.root) + for path, sha in links.items(): + self.gitlink(self.root, path, sha) + return self.commit(self.root, "root") + + def clone(self, source, target, sha): + target.parent.mkdir(parents=True, exist_ok=True) + self.git("clone", "-q", str(source), str(target), cwd=self.sources) + self.git("checkout", "-q", sha, cwd=target) + + def assemble(self, domain_catalog=DOMAIN, domain_files=None, domain_modules=None, + omit_domain_link=None, extra_domain_link=None, root_catalog=None, + root_modules=None, checkout=True, core=None, design=None, preview=None): + core = core or self.leaf("core", entry="scripts/test.sh") + design = design or self.leaf("design") + preview = preview or self.leaf("preview") + links = {"design": design[1], "preview": preview[1]} + if omit_domain_link: + links.pop(omit_domain_link) + if extra_domain_link: + links[extra_domain_link[0]] = extra_domain_link[1] + domain_repo, domain_sha = self.domain(domain_catalog, links, domain_files, domain_modules) + modules = root_modules if root_modules is not None else { + "cli": CORE_URL, + "extensions/web": "https://git.cflmy.cn/cflmy/marqdo-ext-web.git", + } + self.root_repo(root_catalog if root_catalog is not None else catalog(CLI, WEB_DOMAIN), + {"cli": core[1], "extensions/web": domain_sha}, modules) + if checkout: + self.clone(core[0], self.root / "cli", core[1]) + self.clone(domain_repo, self.root / "extensions/web", domain_sha) + sources = {"design": design, "preview": preview} + for path, sha in links.items(): + self.clone(sources.get(path, design)[0], self.root / "extensions/web" / path, sha) + return {"core": core, "design": design, "preview": preview, "domain": (domain_repo, domain_sha)} + + # -- positive cases ----------------------------------------------------- + + def test_accepts_a_two_level_domain_tree_with_checkouts(self): + self.assemble(domain_files={"docs/WEB-DESIGN.md": "# contract\n", "examples/research/README.md": "example\n"}) + layout.validate("HEAD", True) + layout.validate("HEAD", False) + + def test_non_checkout_mode_only_validates_the_root_layer(self): + self.assemble() + shutil.rmtree(self.root / "extensions" / "web") + layout.validate("HEAD", False) + with self.assertRaisesRegex(ValueError, "missing submodule checkout: extensions/web"): + layout.validate("HEAD", True) + + def test_accepts_a_stdlib_domain_with_base_release(self): + self.root_repo(catalog(CLI, STDLIB_DOMAIN), + {"cli": self.leaf("core", entry="scripts/test.sh")[1], "stdlib": "a" * 40}, + {"cli": CORE_URL, "stdlib": "https://git.cflmy.cn/cflmy/marqdo-stdlib.git"}) + layout.validate("HEAD", False) + + def test_allows_checks_with_cycles(self): + cycle = CLI.replace('checks_with = []', 'checks_with = ["view"]') + ''' +[[component]] +id = "view" +path = "tools/view" +kind = "tool" +state = "active" +owner = "maintainer" +scope = "read and observe" +requires = ["cli"] +checks_with = ["cli"] +release = "optional" +entry = "scripts/acceptance.sh" +''' + sha = self.leaf("core", entry="scripts/test.sh")[1] + self.root_repo(cycle, {"cli": sha, "tools/view": sha}, + {"cli": CORE_URL, "tools/view": "https://git.cflmy.cn/cflmy/marqdo-view.git"}) + layout.validate("HEAD", False) + + # -- checkout failures -------------------------------------------------- + + def test_rejects_a_dirty_domain_child(self): + self.assemble() + (self.root / "extensions/web/design/scratch.txt").write_text("dirty") + with self.assertRaisesRegex(ValueError, r"domain web \(extensions/web\): dirty submodule: design"): + layout.validate("HEAD", True) + + def test_rejects_a_wrong_checked_out_commit(self): + self.assemble() + self.git("commit", "--allow-empty", "-qm", "drift", cwd=self.root / "extensions/web/design") + with self.assertRaisesRegex(ValueError, r"domain web \(extensions/web\): wrong checked-out commit: design"): + layout.validate("HEAD", True) + + def test_rejects_a_missing_domain_child_checkout(self): + self.assemble() + shutil.rmtree(self.root / "extensions/web/preview") + with self.assertRaisesRegex(ValueError, r"domain web \(extensions/web\): missing submodule checkout: preview"): + layout.validate("HEAD", True) + + def test_rejects_a_missing_committed_object(self): + self.assemble() + self.git("update-index", "--add", "--cacheinfo", f"160000,{'f' * 40},extensions/web", cwd=self.root) + self.git("commit", "-qm", "bad gitlink") + with self.assertRaisesRegex(ValueError, "missing committed object: extensions/web"): + layout.validate("HEAD", True) + + def test_rejects_a_symbolic_entry(self): + design = self.leaf("design", symlink_entry=True) + self.assemble(design=design) + with self.assertRaisesRegex(ValueError, "missing or symbolic entry: design/scripts/ci.sh"): + layout.validate("HEAD", True) + + def test_rejects_a_third_level_gitlink(self): + design = self.leaf_with_gitlink("design") + self.assemble(design=design) + with self.assertRaisesRegex(ValueError, r"domain web \(extensions/web\) leaf web-design \(design\): leaf must not register gitlinks"): + layout.validate("HEAD", True) + + # -- catalog and layer failures ---------------------------------------- + + def test_rejects_a_missing_domain_catalog(self): + self.assemble(domain_catalog=None) + layout.validate("HEAD", False) + with self.assertRaisesRegex(ValueError, "missing components.toml at"): + layout.validate("HEAD", True) + + def test_rejects_a_domain_catalog_missing_a_gitlink(self): + extra = DOMAIN + ''' +[[component]] +id = "web-extra" +path = "extra" +kind = "extension" +state = "active" +owner = "maintainer" +scope = "extra component" +requires = ["cli"] +checks_with = [] +release = "optional" +entry = "scripts/ci.sh" +''' + self.assemble(domain_catalog=extra) + with self.assertRaisesRegex(ValueError, r"domain web \(extensions/web\): gitlink/catalog mismatch"): + layout.validate("HEAD", True) + + def test_rejects_an_unregistered_domain_gitlink(self): + info = self.assemble() + extra = self.leaf("extra") + domain_repo = self.sources / "domain-source" + self.git("update-index", "--add", "--cacheinfo", f"160000,{extra[1]},extra", cwd=domain_repo) + new_domain_sha = self.commit(domain_repo, "extra gitlink") + self.git("update-index", "--add", "--cacheinfo", f"160000,{new_domain_sha},extensions/web", cwd=self.root) + self.git("commit", "-qm", "advance domain") + shutil.rmtree(self.root / "extensions/web") + self.clone(domain_repo, self.root / "extensions/web", new_domain_sha) + for name in ("design", "preview"): + self.clone(info[name][0], self.root / "extensions/web" / name, info[name][1]) + self.clone(extra[0], self.root / "extensions/web" / "extra", extra[1]) + with self.assertRaisesRegex(ValueError, r"domain web \(extensions/web\): gitlink/catalog mismatch"): + layout.validate("HEAD", True) + + def test_rejects_a_nested_domain(self): + nested = ''' +[[component]] +id = "web-inner" +path = "inner" +kind = "domain" +state = "planned" +owner = "maintainer" +scope = "nested aggregate" +requires = [] +checks_with = [] +release = "none" +''' + self.assemble(domain_catalog=nested) + with self.assertRaisesRegex(ValueError, "domain kind is only allowed at the root layer: web-inner"): + layout.validate("HEAD", True) + + def test_rejects_a_core_component_inside_a_domain(self): + nested = ''' +[[component]] +id = "web-core" +path = "core" +kind = "core" +state = "planned" +owner = "maintainer" +scope = "not allowed here" +requires = [] +checks_with = [] +release = "base" +''' + self.assemble(domain_catalog=nested) + with self.assertRaisesRegex(ValueError, "component kind is not allowed inside a domain: web-core"): + layout.validate("HEAD", True) + + def test_rejects_a_production_file_in_the_domain_tree(self): + self.assemble(domain_files={"Cargo.toml": '[package]\nname = "web-domain"\n'}) + with self.assertRaisesRegex(ValueError, "unexpected aggregate tracked path or mode: Cargo.toml"): + layout.validate("HEAD", True) + + def test_rejects_a_planned_child_implementation_file(self): + self.assemble(domain_files={"components/renderer.py": "print('not allowed')\n"}) + with self.assertRaisesRegex(ValueError, "unexpected aggregate tracked path or mode: components/renderer.py"): + layout.validate("HEAD", True) + + def test_rejects_a_wrong_domain_child_url(self): + self.assemble(domain_modules={ + "design": "https://git.cflmy.cn/cflmy/marqdo-ext-design.git", + "preview": "https://git.cflmy.cn/cflmy/marqdo-web-preview.git", + }) + with self.assertRaisesRegex(ValueError, "invalid submodule URL: design"): + layout.validate("HEAD", True) + + # -- global graph failures --------------------------------------------- + + def test_rejects_a_duplicate_global_id(self): + self.assemble(domain_catalog=DOMAIN.replace('id = "web-components"', 'id = "cli"')) + with self.assertRaisesRegex(ValueError, "duplicate global id: cli"): + layout.validate("HEAD", True) + + def test_rejects_an_unknown_domain_dependency(self): + self.assemble(domain_catalog=DOMAIN.replace('requires = ["cli"]', 'requires = ["cli", "missing"]', 1)) + with self.assertRaisesRegex(ValueError, "unknown dependency: web-design -> missing"): + layout.validate("HEAD", True) + + def test_rejects_an_active_domain_child_dependency_on_planned(self): + self.assemble(domain_catalog=DOMAIN.replace( + 'requires = ["cli", "web-design"]', 'requires = ["cli", "web-design", "web-components"]', 1)) + with self.assertRaisesRegex(ValueError, "active depends on planned: web-preview -> web-components"): + layout.validate("HEAD", True) + + # -- root catalog rules ------------------------------------------------- + + def test_rejects_domain_requires(self): + self.root_repo(CLI + WEB_DOMAIN.replace("requires = []", 'requires = ["cli"]'), + {"cli": "a" * 40, "extensions/web": "b" * 40}, + {"cli": CORE_URL, "extensions/web": "https://git.cflmy.cn/cflmy/marqdo-ext-web.git"}) + with self.assertRaisesRegex(ValueError, "domain requires must be empty: web"): + layout.validate("HEAD", False) + + def test_rejects_an_invalid_domain_release_role(self): + self.root_repo(CLI + WEB_DOMAIN.replace('release = "none"', 'release = "optional"'), + {"cli": "a" * 40, "extensions/web": "b" * 40}, + {"cli": CORE_URL, "extensions/web": "https://git.cflmy.cn/cflmy/marqdo-ext-web.git"}) + with self.assertRaisesRegex(ValueError, "invalid release role: web"): + layout.validate("HEAD", False) + + def test_rejects_an_invalid_domain_path(self): + self.root_repo(CLI + WEB_DOMAIN.replace('path = "extensions/web"', 'path = "extensions/other"'), + {"cli": "a" * 40, "extensions/other": "b" * 40}, + {"cli": CORE_URL, "extensions/other": "https://git.cflmy.cn/cflmy/marqdo-ext-web.git"}) + with self.assertRaisesRegex(ValueError, "invalid path: web: extensions/other"): + layout.validate("HEAD", False) + + def test_rejects_a_requires_edge_to_a_domain(self): + view = ''' +[[component]] +id = "view" +path = "tools/view" +kind = "tool" +state = "active" +owner = "maintainer" +scope = "read and observe" +requires = ["web"] +checks_with = [] +release = "optional" +entry = "scripts/acceptance.sh" +''' + self.root_repo(CLI + WEB_DOMAIN + view, + {"cli": "a" * 40, "extensions/web": "b" * 40, "tools/view": "a" * 40}, + {"cli": CORE_URL, + "extensions/web": "https://git.cflmy.cn/cflmy/marqdo-ext-web.git", + "tools/view": "https://git.cflmy.cn/cflmy/marqdo-view.git"}) + with self.assertRaisesRegex(ValueError, "requires must not target a domain: view -> web"): + layout.validate("HEAD", False) + + def test_rejects_stdlib_dependency_on_extension(self): + stdlib_extra = ''' +[[component]] +id = "std-extra" +path = "stdlib/extra" +kind = "stdlib" +state = "planned" +owner = "maintainer" +scope = "not allowed to depend on extensions" +requires = ["math"] +checks_with = [] +release = "base" +''' + math = ''' +[[component]] +id = "math" +path = "extensions/math" +kind = "extension" +state = "planned" +owner = "maintainer" +scope = "numeric algorithms" +requires = ["cli"] +checks_with = [] +release = "optional" +''' + self.root_repo(CLI + stdlib_extra + math, {"cli": "a" * 40}, {"cli": CORE_URL}) + with self.assertRaisesRegex(ValueError, "stdlib dependency violation: std-extra -> math"): + layout.validate("HEAD", False) + + def test_rejects_core_build_dependency_on_other_component(self): + conformance = ''' +[[component]] +id = "conformance" +path = "tests/conformance" +kind = "test" +state = "active" +owner = "maintainer" +scope = "independent protocol tests" +requires = [] +checks_with = [] +release = "none" +entry = "scripts/build_all.sh" +''' + cli = CLI.replace("requires = []", 'requires = ["conformance"]') + self.root_repo(cli + conformance, + {"cli": "a" * 40, "tests/conformance": "a" * 40}, + {"cli": CORE_URL, + "tests/conformance": "https://git.cflmy.cn/cflmy/marqdo-extension-conformance.git"}) + with self.assertRaisesRegex(ValueError, "dependency violation: cli must not require conformance"): + layout.validate("HEAD", False) + + def test_rejects_a_requires_cycle(self): + math = ''' +[[component]] +id = "math" +path = "extensions/math" +kind = "extension" +state = "planned" +owner = "maintainer" +scope = "numeric algorithms" +requires = ["linalg"] +checks_with = [] +release = "optional" +''' + linalg = ''' +[[component]] +id = "linalg" +path = "extensions/linalg" +kind = "extension" +state = "planned" +owner = "maintainer" +scope = "linear algebra" +requires = ["math"] +checks_with = [] +release = "optional" +''' + self.root_repo(CLI + math + linalg, {"cli": "a" * 40}, {"cli": CORE_URL}) + with self.assertRaisesRegex(ValueError, "requires DAG cycle"): + layout.validate("HEAD", False) + + def test_rejects_overlapping_component_paths(self): + stdlib_domain = STDLIB_DOMAIN.replace("state = \"active\"", "state = \"planned\"").replace( + 'entry = "scripts/integration.sh"\n', "") + planned = PLANNED + self.root_repo(CLI + stdlib_domain + planned, {"cli": "a" * 40}, {"cli": CORE_URL}) + with self.assertRaisesRegex(ValueError, "overlapping component path: stdlib/core / stdlib"): + layout.validate("HEAD", False) + + def test_rejects_a_submodule_update_command(self): + self.root_repo(CLI, {"cli": "a" * 40}, {"cli": CORE_URL}) + self.write(self.root, ".gitmodules", + f'[submodule "cli"]\n\tpath = cli\n\turl = {CORE_URL}\n\tupdate = !false\n') + self.stage(self.root) + self.gitlink(self.root, "cli", "a" * 40) + self.git("commit", "-qm", "update command") + with self.assertRaisesRegex(ValueError, "unexpected submodule settings"): + layout.validate("HEAD", False) + + def test_rejects_forbidden_submodule_urls(self): + for url in ("file:///tmp/marqdo-cli.git", "../marqdo-cli.git", "git@git.cflmy.cn:cflmy/marqdo-cli.git"): + with self.subTest(url=url): + self.root_repo(CLI, {"cli": "a" * 40}, {"cli": url}) + with self.assertRaisesRegex(ValueError, "invalid submodule URL: cli"): + layout.validate("HEAD", False) + + def test_rejects_a_wrong_domain_root_url(self): + self.root_repo(CLI + WEB_DOMAIN, + {"cli": "a" * 40, "extensions/web": "b" * 40}, + {"cli": CORE_URL, + "extensions/web": "https://git.cflmy.cn/cflmy/ext-web.git"}) + with self.assertRaisesRegex(ValueError, "invalid submodule URL: extensions/web"): + layout.validate("HEAD", False) + + def test_rejects_a_domain_without_submodule_gitmodules(self): + self.assemble(domain_modules={}) + with self.assertRaisesRegex(ValueError, "missing or invalid submodule path: design"): + layout.validate("HEAD", True) + + def test_rejects_an_unknown_root_dependency(self): + self.root_repo(CLI.replace('requires = []', 'requires = ["missing"]'), {"cli": "a" * 40}, {"cli": CORE_URL}) + with self.assertRaisesRegex(ValueError, "unknown dependency: cli -> missing"): + layout.validate("HEAD", False) + + def test_rejects_an_absolute_or_parent_path(self): + for path in ("/extensions/web", "extensions/../web", "extensions//web"): + with self.subTest(path=path): + self.root_repo( + CLI + WEB_DOMAIN.replace('path = "extensions/web"', f'path = "{path}"'), + {"cli": "a" * 40}, + {"cli": CORE_URL}) + with self.assertRaisesRegex(ValueError, "invalid path for web"): + layout.validate("HEAD", False) + + if __name__ == "__main__": unittest.main()