From 233ecd5c448d7792ef95a283dcd1cb3f9f9e2167 Mon Sep 17 00:00:00 2001 From: Michael Johnson Date: Sun, 15 Nov 2026 07:08:00 -0500 Subject: [PATCH] feat(docs): canonical categories and fjord-first docs Adopt the 10 canonical categories plus Base with part_of and tags metadata, validate category and label parity in lint, fix braced volume colon splitting and external repo_dir enrichment, sample pure toggle suites in O(N), and reorder README and site templates with fjord first and static defaults in place of placeholder tokens. --- dbuild/config.py | 37 ++++-- dbuild/docs.py | 120 +++++++++++++------ dbuild/init.py | 53 +++++---- dbuild/lint.py | 86 +++++++++++++- dbuild/templates/README.j2 | 134 +++++++++++----------- dbuild/templates/README.mkdocs.j2 | 71 ++++++------ dbuild/templates/appjail-director.yml.j2 | 6 +- dbuild/templates/appjail.env.j2 | 2 +- tests/test_docs.py | 140 ++++++++++++++++++++--- tests/test_lint.py | 62 +++++++++- 10 files changed, 509 insertions(+), 202 deletions(-) diff --git a/dbuild/config.py b/dbuild/config.py index 02950bf..677c746 100644 --- a/dbuild/config.py +++ b/dbuild/config.py @@ -115,19 +115,17 @@ def _prefix_from_executable() -> Path | None: VALID_TYPES: list[str] = ["app", "base", "stack", "appliance"] VALID_CATEGORIES: list[str] = [ + "Automation & Comms", "Base", "Databases", - "Development", - "Downloaders", - "Infrastructure", - "Media Management", - "Media Servers", + "DevOps", + "Media & Photos", + "Media Automation", "Monitoring", - "Network", - "Photos & Media", - "Productivity", + "Networking", + "Productivity & Docs", "Security", - "Utilities", + "Storage & Backup", ] @@ -358,12 +356,19 @@ class Metadata: description: str = field(default="", metadata={ "desc": "Short description of the application", }) - category: str = field(default="Apps", metadata={ + category: str = field(default="", metadata={ "desc": ( "Application category. Valid values: " + ", ".join(VALID_CATEGORIES) ), }) + part_of: str = field(default="", metadata={ + "desc": "Parent stack or suite repository ID (e.g. `immich`, `crafting-apps`) for catalog folding.", + }) + tags: list[str] = field(default_factory=list, metadata={ + "desc": "Lowercase discovery tags (e.g. `[dns, adblock, doh]`).", + "display_default": "[]", + }) upstream_url: str = field(default="", metadata={ "desc": "URL to the upstream source repository", }) @@ -471,6 +476,7 @@ class Config: compose_text: str = "" example_env: str = "" compose_data: dict[str, Any] = field(default_factory=dict) + fjord_exclude: bool = False @property def full_image(self) -> str: @@ -804,10 +810,15 @@ def _parse_metadata(data: dict[str, Any], app_name: str, base: Path | None = Non logo_dark = f"{app_name}-dark{ext}" break + raw_tags = meta.get("tags") + tags = [str(t).strip() for t in raw_tags if str(t).strip()] if isinstance(raw_tags, list) else [] + return Metadata( title=meta.get("title", app_name.title()), description=meta.get("description", ""), - category=meta.get("category", "Apps"), + category=meta.get("category", ""), + part_of=str(meta.get("part_of", "") or ""), + tags=tags, upstream_url=meta.get("upstream_url", ""), web_url=meta.get("web_url", ""), freshports_url=meta.get("freshports_url", ""), @@ -1042,6 +1053,9 @@ def load(base: Path | None = None) -> Config: if example_env_path.is_file(): example_env = example_env_path.read_text() + fjord_cfg = local_data.get("fjord") + fjord_exclude = bool(fjord_cfg.get("exclude")) if isinstance(fjord_cfg, dict) else False + return Config( image=image_name, registry=registry, @@ -1056,6 +1070,7 @@ def load(base: Path | None = None) -> Config: compose_text=compose_text, example_env=example_env, compose_data=compose_data if isinstance(compose_data, dict) else {}, + fjord_exclude=fjord_exclude, ) diff --git a/dbuild/docs.py b/dbuild/docs.py index 6a10cfb..6f9dc70 100644 --- a/dbuild/docs.py +++ b/dbuild/docs.py @@ -10,7 +10,7 @@ from pathlib import Path from typing import Any -from .config import _confident_prefix +from .config import _confident_prefix, _split_compose try: import jinja2 @@ -302,34 +302,27 @@ def _normalize_base_version(raw: str, default: str = "15.1") -> str: def _site_placeholders(text: str, env_file: bool = False) -> str: - """Put the docs site's placeholders into a repo's own compose or .env. + """Normalize sample config roots (/path/to/containers -> /containers) for site snippets. - /containers -> @CONTAINER_CONFIG_ROOT@, PUID/PGID=1000 -> @PUID@/@PGID@, - and in a .env the TZ line -> TZ=@TZ@, so the settings panel fills them - in as it does on a one-service page. + Site snippets render clean static defaults (/containers, PUID=1000, TZ=UTC) + so pages work natively with Zensical instant navigation without post-build + @PLACEHOLDER@ HTML mutation; the client-side customizer rewrites them live. """ + _ = env_file if not text: return "" - text = re.sub(CONFIG_ROOT_RE, CONFIG_ROOT_VAR, text) - text = re.sub(r"(?m)(\bPUID=)1000\b", r"\g<1>@PUID@", text) - text = re.sub(r"(?m)(\bPGID=)1000\b", r"\g<1>@PGID@", text) - if env_file: - text = re.sub(r"(?m)^#?\s*TZ=\S*$", "TZ=@TZ@", text) - else: - # A YAML value can't start with @: the highlighter splits it, and the - # site's settings panel never finds the placeholder. Quoted, it's one - # string (the README template quotes its volume lines for this). - text = re.sub(r"""(?m)^(\s*(?:-\s+|[\w.-]+:\s+))(@[A-Z_]+@[^\s#"']*)(?=[ \t]*(?:#.*)?$)""", r'\1"\2"', text) - return text + return re.sub(CONFIG_ROOT_RE, "/containers", text) # Each combination listed is a full set of files on the page, so they -# multiply: crafting-apps' ten on/off choices made 2048, a 42 MB page that -# crashed browsers. Up to MAX_COMBOS they are listed; past it the site merges -# them into one block (choice_merge) and the GitHub README shows the defaults. -# Past MAX_MERGED even the merge's proof is too much work: defaults only. +# multiply: crafting-apps' sixteen on/off choices make 65536. Up to MAX_COMBOS +# they are listed; past it the site merges them into one block (choice_merge) +# and the GitHub README shows the defaults. Pure on/off toggle suites sample +# O(N) combinations (default, single-off, adjacent-pair-off, all-off) so even +# large suites merge in milliseconds; general choice matrices cap past MAX_MERGED. MAX_COMBOS = 16 MAX_MERGED = 4096 +MAX_TOGGLE_SUITE = 64 # GitHub's alert blockquote (> [!WARNING]) -> the site's admonition. The site @@ -359,18 +352,28 @@ def _combination_count(cfg: Config, runtime: str = "") -> int: return math.prod(len(c.options) for c in cs) if cs else 0 +def _is_pure_toggle_suite(cs: list[Any]) -> bool: + """Every choice is an independent on/off service toggle (e.g. crafting-apps).""" + return bool(cs) and len(cs) <= MAX_TOGGLE_SUITE and all(_toggle(c) is not None for c in cs) + + def _choices_mode(cfg: Config) -> str: """"list" every combination, "merged" one block on the site, "capped" the defaults only. "" without choices.""" count = _combination_count(cfg) if not count: return "" - return "list" if count <= MAX_COMBOS else "merged" if count <= MAX_MERGED else "capped" + if count <= MAX_COMBOS: + return "list" + if count <= MAX_MERGED or _is_pure_toggle_suite(cfg.metadata.choices): + return "merged" + return "capped" def _combinations(cfg: Config) -> list[list[tuple[Any, Any]]]: """Every way of answering the choices: one option per choice, every - combination, the all-default one first. Only the default past MAX_MERGED.""" + combination, the all-default one first. Past MAX_MERGED, pure toggle suites + sample O(N) combinations; general matrices return only the default.""" import itertools cs = cfg.metadata.choices @@ -378,6 +381,30 @@ def _combinations(cfg: Config) -> list[list[tuple[Any, Any]]]: return [] ordered = [sorted(c.options, key=lambda o: o.id != c.default) for c in cs] if _combination_count(cfg) > MAX_MERGED: + if _is_pure_toggle_suite(cs): + n = len(cs) + seen_keys: set[tuple[str, ...]] = set() + sample: list[list[tuple[Any, Any]]] = [] + + def _add(picks: list[tuple[Any, Any]]) -> None: + key = tuple(o.id for _, o in picks) + if key not in seen_keys: + seen_keys.add(key) + sample.append(picks) + + # 1. All-default (all services enabled) + _add([(c, ordered[i][0]) for i, c in enumerate(cs)]) + # 2. Each single toggle off (tags every service's lines) + for k in range(n): + _add([(c, ordered[i][1 if i == k else 0]) for i, c in enumerate(cs)]) + # 3. Adjacent pairs off (proves blank-line separators between neighbors) + for k in range(n - 1): + _add([(c, ordered[i][1 if i in (k, k + 1) else 0]) for i, c in enumerate(cs)]) + # 4. All-off (and per-runtime all-off when toggles restrict runtimes) + _add([(c, ordered[i][1]) for i, c in enumerate(cs)]) + for rt in choices_mod.RUNTIMES: + _add([(c, ordered[i][1 if c.applies(rt) else 0]) for i, c in enumerate(cs)]) + return sample return [[(c, o[0]) for c, o in zip(cs, ordered, strict=True)]] return [list(zip(cs, picks, strict=True)) for picks in itertools.product(*ordered)] @@ -448,22 +475,23 @@ def _director_for_option(director: dict, cfg: Config, option) -> dict: if isinstance(v, dict): used.update(v.keys()) elif isinstance(v, str): - used.add(v.split(":")[0].strip()) + used.add(_split_compose(v)[0].strip()) if isinstance(director.get("volumes"), dict): out["volumes"] = {k: v for k, v in director["volumes"].items() if k in used} return out -def _sidecar_templates(cfg: Config) -> list[dict[str, str]]: +def _sidecar_templates(cfg: Config, repo_dir: Path | None = None) -> list[dict[str, str]]: """Jail templates the authored bundle ships beside director.yml (appjail.depends_on[].template), with their text, for the README.""" + base_dir = repo_dir if repo_dir is not None else Path.cwd() aj = cfg.metadata.appjail if isinstance(cfg.metadata.appjail, dict) else {} out = [] for dep in (aj or {}).get("depends_on") or []: tpl = dep.get("template") if isinstance(dep, dict) else None if not tpl: continue - path = Path.cwd() / tpl + path = base_dir / tpl if path.is_file(): out.append({"file": tpl, "text": path.read_text().rstrip("\n")}) return out @@ -579,7 +607,7 @@ def build(pair_list: list) -> list[dict]: for svc in parsed.values(): for v in (svc or {}).get("volumes") or []: if isinstance(v, str): - bits = v.split(":") + bits = _split_compose(v) src, ro = resolve(bits[0]), len(bits) > 2 and "ro" in bits[2].split(",") else: src, ro = resolve(str((v or {}).get("source", ""))), bool((v or {}).get("read_only")) @@ -592,7 +620,7 @@ def build(pair_list: list) -> list[dict]: k, _, v = ln.partition("=") if k.endswith("_LOCATION") and v and v not in folders: folders.append(v) - folders = [_re.sub(CONFIG_ROOT_RE, CONFIG_ROOT_VAR, f) for f in folders] + folders = [_re.sub(CONFIG_ROOT_RE, "/containers", f) for f in folders] director_text = director_env_text = "" if authored is not None: sliced = _director_for_option(authored, cfg, None if is_default else opts) @@ -675,12 +703,17 @@ def merge(rendered: list[str], runtime: str = "podman") -> dict | None: "exceptions": [{"key": ";".join(f"{c}={o}" for c, o in zip(choice_ids, k, strict=True)), "text": rendered[keys.index(k)]} for k in exceptions]} - return {"choices": declared, "combos": combos, "all_combos": all_combos, "tree": tree(0, ()), "mode": mode, "merge": merge, + return {"choices": declared, "combos": combos, "all_combos": all_combos, "tree": tree(0, ()) if mode == "list" else None, "mode": mode, "merge": merge, "capped": {r: _capped_note(cfg, r) for r in ("podman", "appjail")}} -def _enrich_metadata(cfg: Config, community_override: str | None = None) -> dict[str, Any]: +def _enrich_metadata( + cfg: Config, + community_override: str | None = None, + repo_dir: Path | None = None, +) -> dict[str, Any]: """Build a context dict for templates with enriched env/vol/port data from Config.""" + base_dir = Path(repo_dir) if repo_dir is not None else Path.cwd() meta = cfg.metadata docs = meta.docs if isinstance(meta.docs, dict) else {} @@ -717,7 +750,7 @@ def _enrich_metadata(cfg: Config, community_override: str | None = None) -> dict # Extract base version from Containerfile.j2 if present base_version = "15.1" # fallback default - cf_path = Path.cwd() / "Containerfile.j2" + cf_path = base_dir / "Containerfile.j2" if cf_path.exists(): match = re.search(r"ARG BASE_VERSION=(.*)", cf_path.read_text()) if match: @@ -727,16 +760,30 @@ def _enrich_metadata(cfg: Config, community_override: str | None = None) -> dict # fjord matches the two, and refused opencloud-radicale (service # "radicale") with "this stack has no service named radicale". app_service = cfg.image - compose_path = Path.cwd() / "compose.yaml" + compose_services: dict[str, Any] = {} + compose_path = base_dir / "compose.yaml" if compose_path.exists(): import yaml # lazy, as everywhere in this module try: - svcs = list(((yaml.safe_load(compose_path.read_text()) or {}).get("services") or {}).keys()) + compose_services = ((yaml.safe_load(compose_path.read_text()) or {}).get("services") or {}) + svcs = list(compose_services.keys()) except yaml.YAMLError: svcs = [] if len(svcs) == 1: app_service = str(svcs[0]) + has_services = bool(compose_services or (cfg.compose_data or {}).get("services") or cfg.compose_text) + fjord_supported = bool( + not cfg.fjord_exclude + and meta.deprecated is None + and meta.title + and has_services + and ( + cfg.type == "stack" + or (meta.image_class == "service" and (len(compose_services) <= 1 or bool(cfg.example_env))) + ) + ) + context = { "name": cfg.image, "app_service": app_service, @@ -744,6 +791,9 @@ def _enrich_metadata(cfg: Config, community_override: str | None = None) -> dict "title": meta.title, "description": meta.description, "category": meta.category, + "part_of": meta.part_of, + "image_tags": meta.tags, + "fjord_supported": fjord_supported, "upstream_url": meta.upstream_url, "web_url": meta.web_url, "freshports_url": meta.freshports_url, @@ -794,7 +844,7 @@ def _enrich_metadata(cfg: Config, community_override: str | None = None) -> dict "bastille_enabled": bastille_enabled, "docs": meta.docs, "deprecated": meta.deprecated, - "screenshots": _collect_screenshots(Path.cwd()), + "screenshots": _collect_screenshots(base_dir), "cit_mode": cfg.test.mode if cfg.test else "none", "image_class": meta.image_class, "compose_text": cfg.compose_text, @@ -950,7 +1000,7 @@ def _enrich_metadata(cfg: Config, community_override: str | None = None) -> dict authored = _authored_director(cfg) context["director_override_text"] = _render_director_override(authored) if authored else "" context["director_override_env"] = _render_override_env(authored, context) if authored else "" - context["sidecar_templates"] = _sidecar_templates(cfg) + context["sidecar_templates"] = _sidecar_templates(cfg, base_dir) context["stack_parts"] = _stack_parts(cfg) context["is_stack"] = cfg.type == "stack" return context @@ -1187,7 +1237,7 @@ def render_generated( return outputs, ["jinja2 is not installed"] community_override = getattr(args, "community", None) - context = _enrich_metadata(cfg, community_override) + context = _enrich_metadata(cfg, community_override, repo_dir=base) env = _get_jinja_env(base) if env is None: diff --git a/dbuild/init.py b/dbuild/init.py index bfa9976..5a737be 100644 --- a/dbuild/init.py +++ b/dbuild/init.py @@ -44,28 +44,26 @@ # best-effort. Unmapped categories fall back to None (triggers a warning). _CATEGORY_MAP: dict[str, str] = { "databases": "Databases", - "devel": "Development", - "lang": "Development", - "editors": "Development", - "dns": "Network", - "ftp": "Downloaders", - "net": "Network", - "net-im": "Network", + "devel": "DevOps", + "lang": "DevOps", + "editors": "DevOps", + "dns": "Networking", + "ftp": "Storage & Backup", + "net": "Networking", + "net-im": "Automation & Comms", "net-mgmt": "Monitoring", - "net-p2p": "Downloaders", - "net-vpn": "Network", + "net-p2p": "Media Automation", + "net-vpn": "Networking", "security": "Security", - "sysutils": "Utilities", - "multimedia": "Media Servers", - "graphics": "Photos & Media", - "audio": "Media Servers", - "www": "Network", - "finance": "Productivity", - "misc": "Utilities", - "ports-mgmt": "Utilities", - "shells": "Utilities", - "textproc": "Utilities", - "archivers": "Utilities", + "sysutils": "DevOps", + "multimedia": "Media & Photos", + "graphics": "Media & Photos", + "audio": "Media & Photos", + "www": "Networking", + "finance": "Productivity & Docs", + "deskutils": "Productivity & Docs", + "mail": "Automation & Comms", + "archivers": "Storage & Backup", } @@ -826,13 +824,14 @@ def _port_summary(meta: dict[str, object], title: str, port: int, port_from_arg: if meta["category"]: log.success(f"category: {meta['category']} (port: {meta['category_raw']})") - if meta["category_raw"] == "www" and not category_from_arg: + if meta["category_raw"] in ("www", "sysutils") and not category_from_arg: review.append( - "category: www/ ports land in Network; a git forge is Infrastructure, " - "a wiki or notes app Productivity (compose.yaml, or --category)" + f"category: {meta['category_raw']}/ ports land in {meta['category']}; " + "a git forge is DevOps, a wiki or notes app Productivity & Docs " + "(compose.yaml, or --category)" ) else: - log.warn(f"category: Utilities (no mapping for '{meta['category_raw']}')") + log.warn(f"category: DevOps (no mapping for '{meta['category_raw']}')") review.append("category in compose.yaml (--category next time)") if meta["binary"]: @@ -925,10 +924,10 @@ def run(args: argparse.Namespace) -> int: app_name = args.name or port_meta.get("name") or Path.cwd().name # node_exporter -> Node Exporter; a brand's own casing is a --title job title = args.title or " ".join(w.capitalize() for w in app_name.split("_")) - category_from_arg = args.category != "Apps" + category_from_arg = bool(args.category and args.category != "Apps") category = ( args.category if category_from_arg - else (port_meta.get("category") or "Utilities") + else (port_meta.get("category") or "DevOps") ) port_arg = getattr(args, "port", None) port = int(port_arg) if port_arg else (int(port_meta.get("port") or 0) or _DEFAULT_PORT) @@ -964,7 +963,7 @@ def run(args: argparse.Namespace) -> int: "port": port, "mlock": mlock, "mlock_bool": mlock, - "description": port_meta.get("description") or f"{title} on FreeBSD.", + "description": port_meta.get("description") or f"{title} container image.", "web_url": port_meta.get("web_url") or f"https://{app_name}.org/", "upstream_url": port_meta.get("upstream_url") or port_meta.get("web_url") or f"https://github.com/daemonless/{app_name}", "repo_url": f"https://github.com/daemonless/{app_name}", diff --git a/dbuild/lint.py b/dbuild/lint.py index db90e98..d8156b7 100644 --- a/dbuild/lint.py +++ b/dbuild/lint.py @@ -11,7 +11,11 @@ from typing import Any from dbuild import choices as choices_mod -from dbuild.config import VALID_CATEGORIES, VALID_TYPES, is_cli_name +from dbuild.config import VALID_CATEGORIES, VALID_IMAGE_CLASSES, VALID_TYPES, is_cli_name + +_SLUG_RE = re.compile(r"^[a-z0-9][a-z0-9-]*$") +_CF_CATEGORY_LABEL_RE = re.compile(r'io\.daemonless\.category="([^"{}$]+)"') +_SCREENSHOT_MAX_BYTES = int(1.5 * 1024 * 1024) try: import yaml @@ -177,13 +181,43 @@ def lint_repo(repo_path: Path, verbose: bool = False) -> tuple[list[str], list[s ) if verbose: - print(" checking category") + print(" checking category & class") category = meta.get("category", "") + image_class = meta.get("class", "") + if image_class and image_class not in VALID_IMAGE_CLASSES: + errors.append( + f"Invalid class '{image_class}'." + f" Valid: {', '.join(VALID_IMAGE_CLASSES)}" + ) if category and category not in VALID_CATEGORIES: errors.append( f"Invalid category '{category}'." f" Valid: {', '.join(VALID_CATEGORIES)}" ) + elif category == "Base" and image_class != "base": + errors.append( + "Category 'Base' is reserved for x-daemonless.class: base images" + ) + elif image_class == "base" and category and category != "Base": + errors.append( + f"x-daemonless.class: base must use category 'Base' (got '{category}')" + ) + + if "part_of" in meta: + part_of = meta.get("part_of") + if not isinstance(part_of, str) or not _SLUG_RE.match(part_of): + errors.append( + f"x-daemonless.part_of must be a lowercase repo slug (got {part_of!r})" + ) + + if "tags" in meta: + tags = meta.get("tags") + if not isinstance(tags, list) or not all( + isinstance(t, str) and _SLUG_RE.match(t) for t in tags + ): + errors.append( + "x-daemonless.tags must be a list of lowercase slug strings (e.g. [dns, adblock])" + ) if verbose: print(" checking choices") @@ -232,6 +266,13 @@ def lint_repo(repo_path: Path, verbose: bool = False) -> tuple[list[str], list[s if screenshots_dir.is_dir(): for screenshot_file in sorted(screenshots_dir.iterdir()): if screenshot_file.is_file(): + size_bytes = screenshot_file.stat().st_size + if size_bytes > _SCREENSHOT_MAX_BYTES: + size_mb = size_bytes / (1024 * 1024) + warnings.append( + f".daemonless/screenshots/{screenshot_file.name}: " + f"{size_mb:.1f} MB exceeds 1.5 MB — convert to WebP or compress" + ) for msg in upstream_assets.screenshot_warnings( str(screenshot_file), screenshot_file.suffix ): @@ -285,6 +326,28 @@ def lint_repo(repo_path: Path, verbose: bool = False) -> tuple[list[str], list[s errors.append("Empty .daemonless/config.yaml") return errors, warnings + if not compose_path.exists(): + cfg_meta = config.get("x-daemonless") + if isinstance(cfg_meta, dict): + cfg_cat = cfg_meta.get("category", "") + if not cfg_cat: + errors.append("Missing required field: x-daemonless.category") + elif cfg_cat not in VALID_CATEGORIES: + errors.append( + f"Invalid category '{cfg_cat}'." + f" Valid: {', '.join(VALID_CATEGORIES)}" + ) + else: + warnings.append( + "Missing compose.yaml (add compose.yaml with x-daemonless metadata)" + ) + + effective_type = config.get("type") or meta.get("type", "") + if meta.get("class") == "base" and effective_type != "base": + errors.append( + "x-daemonless.class: base requires type: base (in compose.yaml or .daemonless/config.yaml)" + ) + archs = config.get("build", {}).get("architectures", []) if archs and not isinstance(archs, list): errors.append("build.architectures should be a list") @@ -438,8 +501,19 @@ def lint_repo(repo_path: Path, verbose: bool = False) -> tuple[list[str], list[s if not has_containerfile and not is_stack_repo: errors.append("Missing Containerfile") + if ( + compose_path.exists() + and not config_path.exists() + and meta.get("class") == "base" + and meta.get("type") != "base" + ): + errors.append( + "x-daemonless.class: base requires type: base (in compose.yaml or .daemonless/config.yaml)" + ) + if verbose: print(" checking for stale base images") + expected_category = meta.get("category", "") for cf_path in sorted(repo_path.glob("Containerfile*")): try: cf_text = cf_path.read_text() @@ -447,6 +521,14 @@ def lint_repo(repo_path: Path, verbose: bool = False) -> tuple[list[str], list[s continue if "BASE_VERSION=15.0" in cf_text or "base:15.0" in cf_text: warnings.append(f"{cf_path.name} uses stale FreeBSD 15.0 baseline — update to 15.1") + if expected_category: + for m in _CF_CATEGORY_LABEL_RE.finditer(cf_text): + cf_cat = m.group(1).strip() + if cf_cat != expected_category: + errors.append( + f"{cf_path.name}: io.daemonless.category={cf_cat!r} does not match" + f" x-daemonless.category={expected_category!r}" + ) warnings.extend(_lint_containerfile_bloat(cf_path, cf_text.splitlines())) if verbose: diff --git a/dbuild/templates/README.j2 b/dbuild/templates/README.j2 index 51b28ab..2f19b28 100644 --- a/dbuild/templates/README.j2 +++ b/dbuild/templates/README.j2 @@ -1,15 +1,9 @@ {#- ================================================================== - Logic — Resolve values based on render_mode (MkDocs vs GitHub) + Logic — Resolve default values ================================================================== #} -{%- if render_mode == "mkdocs" %} - {%- set reg_var = "@REGISTRY@" %} - {%- set cfg_root = "@CONTAINER_CONFIG_ROOT@" %} - {%- set port_var = "@" ~ name.upper().replace("-", "_") ~ "_PORT@" %} -{%- else %} - {%- set reg_var = registry %} - {%- set cfg_root = "/containers" %} - {%- set port_var = ports[0].port if ports else "" %} -{%- endif -%} +{%- set reg_var = registry -%} +{%- set cfg_root = "/containers" -%} +{%- set port_var = ports[0].port if ports else "" -%} {#- ================================================================== Macros — deployment snippets @@ -17,9 +11,7 @@ {%- macro vol_src(v) -%} {%- if v.root_var -%} -{{ cfg_root }}/{{ v.placeholder if (render_mode == "mkdocs" and v.placeholder) else v.source }} -{%- elif render_mode == "mkdocs" and v.placeholder -%} -{{ v.placeholder }} +{{ cfg_root }}/{{ v.source }} {%- elif v.source.startswith('/') -%} {{ v.source }} {%- else -%} @@ -67,7 +59,7 @@ services: {%- if e.unset %} # - {{ e.name }}={{ " # " ~ e.desc if e.desc else "" }} {%- else %} - - {{ e.name }}={{ e.placeholder if (render_mode == "mkdocs" and e.placeholder) else e.default }}{{ " # " ~ e.desc if e.desc else "" }} + - {{ e.name }}={{ e.default }}{{ " # " ~ e.desc if e.desc else "" }} {%- endif %} {%- endfor %} {%- endif %} @@ -239,7 +231,7 @@ podman run -d --name {{ name }} \ --health-cmd {{ healthcheck }} \ {%- endif %} {%- for e in env if not e.unset %} - -e {{ e.name }}={{ e.placeholder if (render_mode == "mkdocs" and e.placeholder) else e.default }} \ + -e {{ e.name }}={{ e.default }} \ {%- endfor %} {%- for v in volumes %} -v {{ vol_src(v) }}:{{ vol_tgt(v) }}{{ " # optional" if v.optional else "" }} \ @@ -259,7 +251,7 @@ services: {%- if env %} environment: {%- for e in env if not e.unset %} - - {{ e.name }}={{ e.placeholder if (render_mode == "mkdocs" and e.placeholder) else e.default }} + - {{ e.name }}={{ e.default }} {%- endfor %} {%- endif %} {%- if volumes %} @@ -385,65 +377,45 @@ Source: dbuild templates | **Website** | [{{ web_url }}]({{ web_url }}) | {%- endif %} {%- endblock %} - -{%- if variants or (readme and readme.version_tags) %} - -## Version Tags -{%- endif %} - -{%- if readme and readme.version_tags %} -{{ readme.version_tags }} -{%- elif not variants %} -{%- elif render_mode == "mkdocs" and 'aarch64' in (architectures | default(['amd64'])) %} - -=== "Shared (recommended)" - - Multi-arch manifests — resolve automatically to the right image for your platform. - - {{ version_tags_table() | indent(4) }} - -=== "amd64" - - {{ version_tags_table('-amd64') | indent(4) }} - -=== "aarch64" - - {{ version_tags_table('-aarch64') | indent(4) }} -{%- else %} -{{ version_tags_table() }} -{%- endif %} {%- endblock %} -{%- if stack_parts | length > 1 %} - -## Parts +{%- block notes %} +{%- if notes %} -| Service | Image | Role | | -|---|---|---|---| -{%- for p in stack_parts %} -| **{{ p.name }}** | `{{ p.image }}` | {{ p.desc }}{% if p.when %} ({{ p.when }}){% endif %} | {% if p.page %}[docs]({% if render_mode == "mkdocs" %}{{ p.page }}.md{% else %}https://github.com/daemonless/{{ p.page }}{% endif %}){% endif %} | -{%- endfor %} +{{ notes | trim }} {%- endif %} +{%- endblock %} {%- block prerequisites -%} -{%- if image_class == "service" %} +{%- if is_stack or image_class == "service" %} ## Prerequisites {%- if readme and readme.prerequisites %} -{{ readme.prerequisites }} +{{ readme.prerequisites | trim }} {%- endif %} + Before deploying, ensure your host environment is ready. See the [Quick Start Guide](https://daemonless.io/guides/quick-start) for host setup instructions. {%- endif %} {%- endblock %} {%- block deployment -%} -{%- if image_class in ["service", "cli", "stack"] %} - -## Deployment +{%- if is_stack or image_class in ["service", "cli"] %} +{% block deployment_heading %}## Deployment{% endblock %} +{%- block deployment_customizer %}{% endblock %} {%- block deployment_tabs -%} -{%- if image_class in ["service", "stack"] %} +{%- if fjord_supported %} + +### Fjord + +Install and manage **{{ title }}** on FreeBSD with [fjord](https://fjord.daemonless.io): + +```bash +fjord install {{ name }} +``` +{%- endif %} +{%- if is_stack or image_class == "service" %} ### Podman Compose @@ -506,7 +478,7 @@ Then run `podman-compose up -d`. Then run `podman-compose up -d`. {%- else %} -{%- if env and image_class == "stack" %} +{%- if env and is_stack %} **1.** Save as `.env`: ```env { data-zip-bundle="{{ name }}-podman" data-zip-filename=".env" } @@ -518,10 +490,10 @@ Then run `podman-compose up -d`. **2.** Save as `compose.yaml`: {%- endif %} -```yaml{% if env and image_class == "stack" %} { data-zip-bundle="{{ name }}-podman" data-zip-filename="compose.yaml" }{% endif %} +```yaml{% if env and is_stack %} { data-zip-bundle="{{ name }}-podman" data-zip-filename="compose.yaml" }{% endif %} {{ compose_snippet() }} ``` -{%- if image_class == "stack" %} +{%- if is_stack %} Then run `podman-compose up -d`. {%- else %} @@ -603,11 +575,22 @@ Save as `bastille-compose.yml`, then run `bastille up`. {#- Not localhost: a published port is a pf rdr, and pf never redirects the host's own connections to it. #} -Open `http://:{{ ports[0].port if render_mode != "mkdocs" else port_var }}` from another machine (the server's own browser can't use a published port). +Open `http://:{{ port_var }}` from another machine (the server's own browser can't use a published port). {%- endif %} {%- endif %} {%- endblock %} +{%- if stack_parts | length > 1 %} + +## Parts + +| Service | Image | Role | | +|---|---|---|---| +{%- for p in stack_parts %} +| **{{ p.name }}** | `{{ p.image }}` | {{ p.desc }}{% if p.when %} ({{ p.when }}){% endif %} | {% if p.page %}[docs]({% if render_mode == "mkdocs" %}{{ p.page }}.md{% else %}https://github.com/daemonless/{{ p.page }}{% endif %}){% endif %} | +{%- endfor %} +{%- endif %} + {%- if readme and readme.setup %} ## Setup Instructions @@ -622,8 +605,6 @@ Open `http://:{{ ports[0].port if render_mode != "mkdocs" else port_var {{ readme.troubleshooting }} {%- endif %} -{%- block interactive_config %}{%- endblock %} - {%- block parameters -%} {%- if env or volumes or ports %} @@ -664,11 +645,32 @@ Open `http://:{{ ports[0].port if render_mode != "mkdocs" else port_var {%- endif %} {%- endblock %} -{%- block notes %} -{%- if notes %} +{%- block version_tags -%} +{%- if variants or (readme and readme.version_tags) %} -{{ notes }} +{% block version_tags_heading %}## Version Tags{% endblock %} +{%- if readme and readme.version_tags %} +{{ readme.version_tags }} +{%- elif not variants %} +{%- elif render_mode == "mkdocs" and 'aarch64' in (architectures | default(['amd64'])) %} + +=== "Shared (recommended)" + + Multi-arch manifests — resolve automatically to the right image for your platform. + + {{ version_tags_table() | indent(4) }} + +=== "amd64" + + {{ version_tags_table('-amd64') | indent(4) }} + +=== "aarch64" + + {{ version_tags_table('-aarch64') | indent(4) }} +{%- else %} +{{ version_tags_table() }} +{%- endif %} {%- endif %} {%- endblock %} diff --git a/dbuild/templates/README.mkdocs.j2 b/dbuild/templates/README.mkdocs.j2 index 46b06fa..ede2b6d 100644 --- a/dbuild/templates/README.mkdocs.j2 +++ b/dbuild/templates/README.mkdocs.j2 @@ -181,19 +181,13 @@ description: "{{ description }} Built natively for FreeBSD with PUID/PGID suppor {% block screenshots %} {% if screenshots %} - + {% endif %} {% endblock %} @@ -213,19 +207,46 @@ description: "{{ description }} Built natively for FreeBSD with PUID/PGID suppor {%- endif %} {% endblock %} -{% block prerequisites %} -{%- if readme and readme.prerequisites %} +{% block prerequisites -%} +{%- if is_stack or image_class == "service" %} -{{ readme.prerequisites }} +## Prerequisites +{%- if readme and readme.prerequisites %} + +{{ readme.prerequisites | trim }} {%- endif %} Before deploying, ensure your host environment is ready. See the [Quick Start Guide](../guides/quick-start.md) for host setup instructions, including the security model for host vs. container privileges. +{%- endif -%} +{% endblock %} + +{% block deployment_heading %}## Deployment { #deployment data-search-exclude }{% endblock %} + +{% block deployment_customizer -%} +{%- if is_stack or image_class in ["service", "cli"] %} + +
+ Customize Paths, UID & Ports +
+
+{%- endif -%} {% endblock %} {% block deployment_tabs %} -{%- set port_var = "@" ~ name.upper().replace("-", "_") ~ "_PORT@" %} +{%- set port_var = ports[0].port if ports else "" %} {%- set bastille_tab = bastille_enabled and image_class == "service" %} +{%- if fjord_supported %} +=== ":fjord-fjord: fjord" + + Install and manage **{{ title }}** on FreeBSD with [fjord](https://fjord.daemonless.io): + + ```bash + fjord install {{ name }} + ``` + + Or open the **App Store** in the fjord web UI and install **{{ title }}** from the wizard. New to fjord? See the [Install Guide](https://fjord.daemonless.io/install/). +{% endif -%} {%- if compose_text %} {#- An app shipped with its database: the real compose and the .env it reads. The one-service snippet dropped the database; the one-container recipes @@ -261,7 +282,7 @@ Before deploying, ensure your host environment is ready. See the [Quick Start Gu Save the files above, then run `appjail-director up`. {% endif %} -{%- elif appjail_enabled or bastille_tab %} +{%- elif fjord_supported or appjail_enabled or bastille_tab %} {#- One tab per runtime, one way each. #} === ":podman-podman: Podman" {% if image_class == "service" %} @@ -323,16 +344,7 @@ Save as `run.sh`, then run `sh run.sh`. {%- endif %} {% endblock %} -{% block interactive_config %} -{#- The settings table lands under this heading (ux-settings-v2.js moves it - here); without the heading it stays wherever the plugin drops it. Every - page has at least the registry placeholder, a base image included, so - every page gets the heading; an empty table hides itself. #} - -### Interactive Configuration - -
-{% endblock %} +{% block version_tags_heading %}## Version Tags { #version-tags data-search-exclude }{% endblock %} {% block implementation_details %} !!! info "Implementation Details" @@ -346,7 +358,7 @@ Save as `run.sh`, then run `sh run.sh`. {%- else %} - **User:** `{{ user }}` (UID/GID set via [PUID/PGID](../guides/permissions.md)). Defaults to `1000:1000`. {%- endif %} - - **Base:** Built on `@REGISTRY@/base` (FreeBSD {{ base_version }}). + - **Base:** Built on `{{ registry }}/base` (FreeBSD {{ base_version }}). {%- if mlock %} - **mlock:** Requires `--annotation 'org.freebsd.jail.allow.mlock=true'` ([ocijail 0.5.0+](/guides/ocijail-patch/)) {%- endif %} @@ -354,8 +366,3 @@ Save as `run.sh`, then run `sh run.sh`. - **sysvipc:** Requires `--annotation 'org.freebsd.jail.allow.sysvipc=true'` ([ocijail 0.5.0+](/guides/ocijail-patch/)) {%- endif %} {% endblock %} - -{% block links %} -[Website]({{ web_url }}){ .md-button .md-button--primary } -[Source Code]({{ upstream_url }}){ .md-button } -{% endblock %} diff --git a/dbuild/templates/appjail-director.yml.j2 b/dbuild/templates/appjail-director.yml.j2 index 71c01fc..3ab3a53 100644 --- a/dbuild/templates/appjail-director.yml.j2 +++ b/dbuild/templates/appjail-director.yml.j2 @@ -71,7 +71,7 @@ services: {%- if volumes %} volumes: {%- for v in volumes %} - - {{ v.placeholder.replace("@", "") if (render_mode is defined and render_mode in ("mkdocs", "deploy") and v.placeholder) else v.source.replace("/", "_").replace(".", "_").strip("_") }}: {{ v.path }} + - {{ v.placeholder.replace("@", "") if (render_mode is defined and render_mode == "deploy" and v.placeholder) else v.source.replace("/", "_").replace(".", "_").strip("_") }}: {{ v.path }} {%- endfor %} {%- endif %} @@ -111,11 +111,11 @@ services: volumes: {%- if volumes %} {%- for v in volumes %} - {{ v.placeholder.replace("@", "") if (render_mode is defined and render_mode in ("mkdocs", "deploy") and v.placeholder) else v.source.replace("/", "_").replace(".", "_").strip("_") }}: + {{ v.placeholder.replace("@", "") if (render_mode is defined and render_mode == "deploy" and v.placeholder) else v.source.replace("/", "_").replace(".", "_").strip("_") }}: {%- if render_mode is defined and render_mode == "deploy" %} device: !ENV '${{ '{' }}{{ v.placeholder.replace("@", "") }}{{ '}' }}' {%- else %} - device: '{% if v.root_var %}{{ cfg_root }}/{% endif %}{{ v.placeholder if (render_mode is defined and render_mode == "mkdocs" and v.placeholder) else v.source }}' + device: '{% if v.root_var %}{{ cfg_root }}/{% endif %}{{ v.source }}' {%- endif %} {%- endfor %} {%- endif %} diff --git a/dbuild/templates/appjail.env.j2 b/dbuild/templates/appjail.env.j2 index a8c2fc4..2882a74 100644 --- a/dbuild/templates/appjail.env.j2 +++ b/dbuild/templates/appjail.env.j2 @@ -2,7 +2,7 @@ DIRECTOR_PROJECT={{ name }} {%- for e in env if not e.unset %} -{{ e.name }}={{ e.placeholder if (render_mode is defined and render_mode == "mkdocs" and e.placeholder) else (e.env_ref or e.default) }} +{{ e.name }}={{ e.env_ref or e.default }} {%- endfor %} {%- if render_mode is defined and render_mode == "deploy" %} {%- for p in ports %} diff --git a/tests/test_docs.py b/tests/test_docs.py index 8561eef..2087040 100644 --- a/tests/test_docs.py +++ b/tests/test_docs.py @@ -30,7 +30,7 @@ x-daemonless: title: "TestApp" description: "A test app." - category: "Utilities" + category: "Productivity & Docs" icon: ":test:" upstream_url: "https://example.com" user: "bsd" @@ -508,30 +508,25 @@ def test_bare_latest_and_empty_fall_back(self): class TestSitePlaceholders: - def test_repo_compose_and_env_get_site_placeholders(self): + def test_repo_compose_and_env_keep_clean_static_defaults(self): from dbuild.docs import _site_placeholders compose = " - PUID=1000\n - PGID=1000\n volumes:\n - /containers/app/config:/config\n" - assert _site_placeholders(compose) == ( - " - PUID=@PUID@\n - PGID=@PGID@\n volumes:\n" - ' - "@CONTAINER_CONFIG_ROOT@/app/config:/config"\n') + assert _site_placeholders(compose) == compose env = "CONFIG_LOCATION=/containers/app\n# TZ=UTC\n" - assert _site_placeholders(env, env_file=True) == ( - "CONFIG_LOCATION=@CONTAINER_CONFIG_ROOT@/app\nTZ=@TZ@\n") + assert _site_placeholders(env, env_file=True) == env assert _site_placeholders("") == "" - def test_the_whole_fleet_root_becomes_the_placeholder(self): - # 122 composes write /path/to/containers/: only /containers was - # swapped, so the page showed /path/to@CONTAINER_CONFIG_ROOT@/. + def test_the_whole_fleet_root_normalizes_to_containers(self): + # 122 composes write /path/to/containers/: normalize cleanly to /containers/. from dbuild.docs import _site_placeholders compose = " - /path/to/containers/uptime-kuma:/config\n" - # quoted: a YAML value starting with @ is split by the highlighter - assert _site_placeholders(compose) == ' - "@CONTAINER_CONFIG_ROOT@/uptime-kuma:/config"\n' + assert _site_placeholders(compose) == " - /containers/uptime-kuma:/config\n" long_form = " source: /path/to/containers/app/db\n" - assert _site_placeholders(long_form) == ' source: "@CONTAINER_CONFIG_ROOT@/app/db"\n' + assert _site_placeholders(long_form) == " source: /containers/app/db\n" commented = " - /path/to/containers/x:/data # required\n" - assert _site_placeholders(commented) == ' - "@CONTAINER_CONFIG_ROOT@/x:/data" # required\n' + assert _site_placeholders(commented) == " - /containers/x:/data # required\n" env = "DB_LOCATION=/path/to/containers/app/db\n" - assert _site_placeholders(env, env_file=True) == "DB_LOCATION=@CONTAINER_CONFIG_ROOT@/app/db\n" + assert _site_placeholders(env, env_file=True) == "DB_LOCATION=/containers/app/db\n" assert _site_placeholders(" - /srv/containers/x:/x\n") == " - /srv/containers/x:/x\n", "only at a path's start" @@ -542,7 +537,7 @@ def test_the_whole_fleet_root_becomes_the_placeholder(self): x-daemonless: title: "Todo" description: "A to-do app." - category: "Utilities" + category: "Productivity & Docs" icon: ":test:" upstream_url: "https://example.com" user: "bsd" @@ -655,7 +650,7 @@ def test_you_get_names_what_runs_and_where_data_lands(self): self.assertEqual([(p["name"], p["kind"]) for p in pg["parts"]], [("todo", "app"), ("postgres", "db")]) self.assertEqual(pg["parts"][1]["image"], "postgres:17") self.assertTrue(pg["jails"][1]["name"].endswith("_postgres"), pg["jails"]) # _postgres - self.assertIn("@CONTAINER_CONFIG_ROOT@/todo/postgres", pg["folders"]) + self.assertIn("/containers/todo/postgres", pg["folders"]) ext = _combo(ctx, database="external") self.assertEqual(ext["parts"][-1]["kind"], "none") both = _combo(ctx, database="postgres", search="on") @@ -909,7 +904,7 @@ def test_the_line_resolves_tags_and_skips_the_clock_mount(self): on = ctx["combos"][0] self.assertTrue(on["default"]) self.assertEqual(on["parts"][0]["image"], "photos-server:latest", "the compose fallback resolves") - self.assertEqual(on["folders"], ["@CONTAINER_CONFIG_ROOT@/photos/library", "@CONTAINER_CONFIG_ROOT@/photos/cache"]) + self.assertEqual(on["folders"], ["/containers/photos/library", "/containers/photos/cache"]) def test_bundle_on_disk_is_the_default_answer(self): with tempfile.TemporaryDirectory() as d: @@ -1138,8 +1133,20 @@ def test_the_site_merges_them_into_one_block(self): self.assertEqual(page.count('class="toggle"'), 20, "ten switches per runtime") self.assertLess(len(page), 120_000) + def test_sixteen_toggle_suite_merges_in_linear_samples(self): + import jinja2 + + ctx, _, errors = self._ctx(16) + self.assertEqual(errors, []) + self.assertEqual(ctx["choices_mode"], "merged") + self.assertLess(len(ctx["all_combos"]()), 40, "O(N) sample instead of 2^16 = 65536") + env = jinja2.Environment(loader=jinja2.FileSystemLoader(str(Path(docs.__file__).parent / "templates"))) + page = env.get_template("README.mkdocs.j2").render(dict(ctx, render_mode="mkdocs")) + self.assertEqual(page.count('class="deploy-merged"'), 2, "one per runtime") + self.assertEqual(page.count('class="toggle"'), 32, "sixteen switches per runtime") + def test_past_the_merge_limit_defaults_only(self): - ctx, _, errors = self._ctx(13) + ctx, _, errors = self._ctx(65) self.assertEqual(errors, []) self.assertEqual(ctx["choices_mode"], "capped") self.assertEqual(len(ctx["combos"]), 1) @@ -1349,3 +1356,98 @@ def test_the_merged_form_leaves_out_the_hidden_choice(self): "the merge's conditions name only the form's own choices") for key in (m.split('"')[0] for m in appjail.split('data-key="')[1:]): self.assertNotIn("app0=", key) + + +class TestOperatorFirstAndFjordTab(unittest.TestCase): + """Operator-First layout, fjord default tab, repo_dir isolation, and zero @PLACEHOLDER@ tokens.""" + + def test_operator_first_order_and_fjord_default_tab(self): + import re as _re + + with tempfile.TemporaryDirectory() as d: + repo = Path(d) / "radarr" + (repo / ".daemonless" / "screenshots").mkdir(parents=True) + (repo / ".daemonless" / "screenshots" / "ui.png").write_bytes(b"png") + (repo / "Containerfile.j2").write_text("ARG BASE_VERSION=15.1-latest\n" + CONTAINERFILE_J2) + (repo / ".daemonless" / "config.yaml").write_text( + "build:\n variants:\n - tag: latest\n default: true\n" + ) + (repo / "compose.yaml").write_text( + "name: radarr\n" + "x-daemonless:\n" + ' title: "Radarr"\n' + ' description: "Movie manager."\n' + ' category: "Media Automation"\n' + ' icon: ":material-movie:"\n' + ' upstream_url: "https://github.com/Radarr/Radarr"\n' + ' user: "bsd"\n' + " appjail: {}\n" + "services:\n" + " radarr:\n" + " image: ghcr.io/daemonless/radarr:latest\n" + " environment:\n" + " - PUID=1000\n" + " - TZ=UTC\n" + " volumes:\n" + " - /path/to/containers/radarr:/config\n" + " ports:\n" + ' - "7878:7878"\n' + ) + # Call _enrich_metadata from a DIFFERENT working directory via repo_dir! + with tempfile.TemporaryDirectory() as outside, _chdir(Path(outside)): + cfg = dbuild_config.load(repo) + ctx = docs._enrich_metadata(cfg, repo_dir=repo) + site = docs._get_jinja_env(repo).get_template("README.mkdocs.j2").render( + dict(ctx, render_mode="mkdocs") + ) + with _chdir(repo): + outputs, errors = docs.render_generated(cfg, argparse.Namespace(community=None), repo) + + self.assertEqual(errors, []) + self.assertTrue(ctx["fjord_supported"]) + self.assertEqual(ctx["base_version"], "15.1") + self.assertEqual(ctx["screenshots"], [".daemonless/screenshots/ui.png"]) + + # Zero @PLACEHOLDER@ tokens on site output + self.assertEqual(_re.findall(r"@[A-Z][A-Z0-9_]+@", site), []) + self.assertIn('class="screenshot-strip"', site) + self.assertIn('class="deploy-customizer"', site) + self.assertIn("## Deployment { #deployment data-search-exclude }", site) + self.assertIn("## Version Tags { #version-tags data-search-exclude }", site) + + # fjord tab is first tab before Podman + self.assertLess(site.index('=== ":fjord-fjord: fjord"'), site.index('=== ":podman-podman: Podman"')) + self.assertIn("fjord install radarr", site) + + # Operator-First section order on both site and GitHub README + self.assertLess(site.index("## Deployment"), site.index("## Parameters")) + self.assertLess(site.index("## Parameters"), site.index("## Version Tags")) + readme = outputs["README.md"] + self.assertLess(readme.index("## Deployment"), readme.index("## Parameters")) + self.assertLess(readme.index("## Parameters"), readme.index("## Version Tags")) + self.assertLess(readme.index("### Fjord"), readme.index("### Podman Compose")) + + def test_fjord_exclude_suppresses_fjord_tab(self): + with tempfile.TemporaryDirectory() as d: + repo = Path(d) / "sylve" + (repo / ".daemonless").mkdir(parents=True) + (repo / ".daemonless" / "config.yaml").write_text("fjord:\n exclude: true\n") + (repo / "compose.yaml").write_text( + "name: sylve\n" + "x-daemonless:\n" + ' title: "Sylve"\n' + ' description: "Hypervisor."\n' + ' category: "Productivity & Docs"\n' + ' upstream_url: "https://example.com"\n' + ' user: "root"\n' + "services:\n" + " sylve:\n" + " image: ghcr.io/daemonless/sylve:latest\n" + ) + cfg = dbuild_config.load(repo) + ctx = docs._enrich_metadata(cfg, repo_dir=repo) + site = docs._get_jinja_env(repo).get_template("README.mkdocs.j2").render( + dict(ctx, render_mode="mkdocs") + ) + self.assertFalse(ctx["fjord_supported"]) + self.assertNotIn(":fjord-fjord:", site) diff --git a/tests/test_lint.py b/tests/test_lint.py index fbb522e..5fa40f2 100644 --- a/tests/test_lint.py +++ b/tests/test_lint.py @@ -312,7 +312,7 @@ def test_stack_needs_no_containerfile_or_user(self): with tempfile.TemporaryDirectory() as d: p = Path(d) (p / "compose.yaml").write_text( - "name: photos\nx-daemonless:\n title: Photos\n icon: ':x:'\n category: Photos & Media\n" + "name: photos\nx-daemonless:\n title: Photos\n icon: ':x:'\n category: Media & Photos\n" " description: d\n upstream_url: https://example.com\n type: stack\n" "services:\n app:\n image: ghcr.io/daemonless/app:latest\n") errors, _ = lint_repo(p) @@ -332,7 +332,7 @@ def test_uncleaned_pkg_install_warns(self): with tempfile.TemporaryDirectory() as d: p = Path(d) (p / "compose.yaml").write_text( - "name: app\nx-daemonless:\n title: App\n icon: ':x:'\n category: Utilities\n" + "name: app\nx-daemonless:\n title: App\n icon: ':x:'\n category: Productivity & Docs\n" " description: d\n upstream_url: https://example.com\n user: bsd\n" "services:\n app:\n image: ghcr.io/daemonless/app:latest\n" ) @@ -356,7 +356,7 @@ def test_cleaned_pkg_install_no_warn(self): with tempfile.TemporaryDirectory() as d: p = Path(d) (p / "compose.yaml").write_text( - "name: app\nx-daemonless:\n title: App\n icon: ':x:'\n category: Utilities\n" + "name: app\nx-daemonless:\n title: App\n icon: ':x:'\n category: Productivity & Docs\n" " description: d\n upstream_url: https://example.com\n user: bsd\n" "services:\n app:\n image: ghcr.io/daemonless/app:latest\n" ) @@ -382,7 +382,7 @@ def test_standalone_cleanup_run_warns(self): with tempfile.TemporaryDirectory() as d: p = Path(d) (p / "compose.yaml").write_text( - "name: app\nx-daemonless:\n title: App\n icon: ':x:'\n category: Utilities\n" + "name: app\nx-daemonless:\n title: App\n icon: ':x:'\n category: Productivity & Docs\n" " description: d\n upstream_url: https://example.com\n user: bsd\n" "services:\n app:\n image: ghcr.io/daemonless/app:latest\n" ) @@ -406,7 +406,7 @@ def _errors(self, cli_yaml: str) -> list[str]: p = Path(d) (p / "Containerfile").write_text("FROM scratch\n") (p / "compose.yaml").write_text( - "name: chat\nx-daemonless:\n title: Chat\n icon: ':x:'\n category: Utilities\n" + "name: chat\nx-daemonless:\n title: Chat\n icon: ':x:'\n category: Productivity & Docs\n" " description: d\n upstream_url: https://example.com\n user: bsd\n" + cli_yaml + "services:\n chat:\n image: ghcr.io/daemonless/chat:latest\n") errors, _ = lint_repo(p) @@ -429,7 +429,7 @@ def test_own_path_must_keep_the_wrappers_first(self): p = Path(d) (p / "Containerfile.j2").write_text(cf) (p / "compose.yaml").write_text( - "name: chat\nx-daemonless:\n title: Chat\n icon: ':x:'\n category: Utilities\n" + "name: chat\nx-daemonless:\n title: Chat\n icon: ':x:'\n category: Productivity & Docs\n" " description: d\n upstream_url: https://example.com\n user: bsd\n cli: [chat]\n" "services:\n chat:\n image: ghcr.io/daemonless/chat:latest\n") errors, _ = lint_repo(p) @@ -437,3 +437,53 @@ def test_own_path_must_keep_the_wrappers_first(self): (p / "Containerfile.j2").write_text(cf.replace("/opt/venv/bin:", "/usr/local/daemonless/bin:/opt/venv/bin:")) errors, _ = lint_repo(p) self.assertFalse([e for e in errors if "sets PATH" in e], errors) + + +class TestTaxonomyAndMetadataLint(unittest.TestCase): + """Tests for canonical 10-category taxonomy, Base/class parity, Containerfile label parity, and screenshot bloat.""" + + def test_utilities_category_is_rejected(self): + import tempfile + with tempfile.TemporaryDirectory() as d: + p = Path(d) + (p / "Containerfile").write_text("FROM scratch\n") + (p / "compose.yaml").write_text( + "name: app\nx-daemonless:\n title: App\n icon: ':x:'\n category: Utilities\n" + " description: d\n upstream_url: https://example.com\n user: bsd\n" + "services:\n app:\n image: ghcr.io/daemonless/app:latest\n" + ) + errors, _ = lint_repo(p) + self.assertTrue(any("Invalid category 'Utilities'" in e for e in errors), errors) + + def test_base_category_and_class_parity(self): + import tempfile + with tempfile.TemporaryDirectory() as d: + p = Path(d) + (p / "Containerfile").write_text("FROM scratch\n") + (p / "compose.yaml").write_text( + "name: app\nx-daemonless:\n title: App\n icon: ':x:'\n category: Base\n" + " description: d\n upstream_url: https://example.com\n user: bsd\n" + "services:\n app:\n image: ghcr.io/daemonless/app:latest\n" + ) + errors, _ = lint_repo(p) + self.assertTrue(any("Category 'Base' is reserved" in e for e in errors), errors) + + def test_containerfile_category_mismatch_and_oversized_screenshot(self): + import tempfile + with tempfile.TemporaryDirectory() as d: + p = Path(d) + (p / "Containerfile").write_text( + 'FROM scratch\nLABEL io.daemonless.category="Utilities"\n' + ) + (p / ".daemonless" / "screenshots").mkdir(parents=True) + (p / ".daemonless" / "screenshots" / "huge.png").write_bytes(b"0" * (1600 * 1024)) + (p / "compose.yaml").write_text( + "name: app\nx-daemonless:\n title: App\n icon: ':x:'\n category: Networking\n" + " description: d\n upstream_url: https://example.com\n user: bsd\n" + " part_of: Bad_Slug\n" + "services:\n app:\n image: ghcr.io/daemonless/app:latest\n" + ) + errors, warnings = lint_repo(p) + self.assertTrue(any("io.daemonless.category" in e for e in errors), errors) + self.assertTrue(any("part_of" in e for e in errors), errors) + self.assertTrue(any("huge.png" in w for w in warnings), warnings)