From 72a1fccfd5086a7c42bca629f4cc4f61276dd41f Mon Sep 17 00:00:00 2001 From: Michael Johnson Date: Sat, 14 Nov 2026 18:09:31 -0500 Subject: [PATCH] feat(choices): limit a choice to some runtimes A choice can say which runtimes it is for with `runtimes: [podman]` (or `[appjail]`); without the key it is offered everywhere, as before. On a runtime that does not offer it, the choice gets no row on the site, only its default combination is listed, and block keys and the merge leave it out; the README sections follow the same rule. AppJail option forms skip it, lint rejects unknown runtime names, and fjord's catalog carries the list when set. reverse-proxy's container-label choice reads podman's socket, so on AppJail it did nothing, but the AppJail tab offered it. --- dbuild/appjail_choices.py | 2 + dbuild/choices.py | 20 ++++- dbuild/docs.py | 35 ++++++--- dbuild/templates/README.j2 | 22 +++--- dbuild/templates/README.mkdocs.j2 | 36 +++++---- tests/test_docs.py | 124 ++++++++++++++++++++++++++++++ 6 files changed, 202 insertions(+), 37 deletions(-) diff --git a/dbuild/appjail_choices.py b/dbuild/appjail_choices.py index e28d65f..8cf86c1 100644 --- a/dbuild/appjail_choices.py +++ b/dbuild/appjail_choices.py @@ -74,6 +74,8 @@ def option_forms(cfg: Any) -> dict[str, dict[str, dict[str, Any]]]: base = _director_dict(base_text) for c in cfg.metadata.choices: + if not c.applies("appjail"): + continue for o in c.options: files: dict[str, str] = {} hostnames: dict[str, str] = {} diff --git a/dbuild/choices.py b/dbuild/choices.py index 344f1f5..88de002 100644 --- a/dbuild/choices.py +++ b/dbuild/choices.py @@ -61,6 +61,8 @@ # The database engines dbuild knows how to run. One place: an app that # offers postgres gets this service, and a fix here fixes every app. +RUNTIMES = ("podman", "appjail") + ENGINES: dict[str, dict[str, Any]] = { "sqlite": {"label": "SQLite", "type": "sqlite", "doc": "A file in the app's config folder. Right for one person, nothing extra to run."}, @@ -142,11 +144,17 @@ class Choice: service: str = "" # the app service the choice wires (database); "" = first env_map: dict[str, str] = field(default_factory=dict) # database: role -> the app's variable options: list[Option] = field(default_factory=list) + # The runtimes the choice means something on; empty = every one. A choice + # about podman's socket has nothing to offer an AppJail install. + runtimes: list[str] = field(default_factory=list) @property def default_option(self) -> Option | None: return next((o for o in self.options if o.id == self.default), None) + def applies(self, runtime: str) -> bool: + return not self.runtimes or runtime in self.runtimes + def _database_options(cid: str, c: dict[str, Any], services: dict[str, Any]) -> tuple[list[Option], dict[str, str]]: env_map = {str(k): str(v) for k, v in (c.get("env") or {}).items()} @@ -257,8 +265,10 @@ def parse(meta: dict[str, Any], compose_data: dict[str, Any] | None = None) -> l drop=[str(x) for x in (o.get("drop") or [])], )) default = str(c.get("default", "")) or (opts[0].id if opts else "") + runtimes = c.get("runtimes") or [] out.append(Choice(id=str(cid), label=label, kind=kind, doc=doc, default=default, - service=str(c.get("service", "")), env_map=env_map, options=opts)) + service=str(c.get("service", "")), env_map=env_map, options=opts, + runtimes=[str(r) for r in runtimes] if isinstance(runtimes, list) else [str(runtimes)])) return out @@ -276,6 +286,9 @@ def validate(choices: list[Choice], compose_data: dict[str, Any]) -> list[str]: if not c.options: errors.append(f"{where}: no options") continue + for r in c.runtimes: + if r not in RUNTIMES: + errors.append(f"{where}.runtimes: '{r}' is not a runtime (one of {', '.join(RUNTIMES)})") if c.default_option is None: errors.append(f"{where}: default '{c.default}' is not one of its options") elif c.default_option.profile or c.default_option.service_yaml: @@ -565,5 +578,8 @@ def to_fjord(choices: list[Choice], compose_text: str, compose_data: dict[str, A "hostnames": dict(o.hostnames), "ask": [{"name": a.name, "label": a.label, "default": a.default, "type": a.type, "values": dict(a.values)} for a in o.ask], }) - out.append({"id": c.id, "kind": c.kind, "label": c.label, "doc": c.doc, "default": c.default, "options": opts}) + entry = {"id": c.id, "kind": c.kind, "label": c.label, "doc": c.doc, "default": c.default, "options": opts} + if c.runtimes: + entry["runtimes"] = list(c.runtimes) + out.append(entry) return {"choices": out} diff --git a/dbuild/docs.py b/dbuild/docs.py index 4c2a841..6a10cfb 100644 --- a/dbuild/docs.py +++ b/dbuild/docs.py @@ -350,10 +350,13 @@ def admonition(m: re.Match) -> str: return _GITHUB_ALERT_RE.sub(admonition, text) -def _combination_count(cfg: Config) -> int: +def _combination_count(cfg: Config, runtime: str = "") -> int: + """How many ways the choices can be answered; on one runtime, counting + only the choices it shows.""" import math - return math.prod(len(c.options) for c in cfg.metadata.choices) if cfg.metadata.choices else 0 + cs = [c for c in cfg.metadata.choices if not runtime or c.applies(runtime)] + return math.prod(len(c.options) for c in cs) if cs else 0 def _choices_mode(cfg: Config) -> str: @@ -383,10 +386,10 @@ def _capped_note(cfg: Config, runtime: str) -> str: """What the docs say in place of the choices once they are past MAX_COMBOS (the README; the site when the merge fails), or "" when every combination is listed.""" - count = _combination_count(cfg) + count = _combination_count(cfg, runtime) if count <= MAX_COMBOS: return "" - cs = cfg.metadata.choices + cs = [c for c in cfg.metadata.choices if c.applies(runtime)] where = "its jail from `appjail-director.yml`" if runtime == "appjail" else "its service from `compose.yaml`" # Every option only keeps or drops services (the default drops none). if all(_pure(o) for c in cs for o in c.options): @@ -600,10 +603,16 @@ def build(pair_list: list) -> list[dict]: tpl = next((o for o in opts if o.jail_template_file), None) combos.append({ "id": suffix or "default", "default": is_default, - "selections": [{"choice": c.id, "choice_label": c.label, "option": o.id, "label": o.label, "default": o.id == c.default} for c, o in pairs], + "selections": [{"choice": c.id, "choice_label": c.label, "option": o.id, "label": o.label, "default": o.id == c.default, + "runtimes": [r for r in choices_mod.RUNTIMES if c.applies(r)]} for c, o in pairs], + # A runtime lists a combination only when every choice it does + # not show is at its default (AppJail never sees podman's socket). + "runtimes": [r for r in choices_mod.RUNTIMES if all(c.applies(r) or o.id == c.default for c, o in pairs)], + "labels": {r: ", ".join(o.label for c, o in pairs if c.applies(r)) for r in choices_mod.RUNTIMES}, "label": ", ".join(o.label for _, o in pairs), "doc": " ".join(o.doc for _, o in pairs if o.doc), "docs": [o.doc for _, o in pairs if o.doc], + "docs_for": {r: [o.doc for c, o in pairs if o.doc and c.applies(r)] for r in choices_mod.RUNTIMES}, "parts": parts, "jails": jails, "folders": folders, "appjail": aj, "appjail_env": aj_env, "director_text": director_text, "director_env_text": director_env_text, @@ -645,14 +654,18 @@ def tree(level: int, picked: tuple) -> dict | None: return {"id": c.id, "label": c.label, "doc": c.doc, "options": nodes} declared = [{"id": c.id, "label": c.label, "doc": c.doc, "default": c.default, "toggle": _toggle(c), + "runtimes": [r for r in choices_mod.RUNTIMES if c.applies(r)], "options": [{"id": o.id, "label": o.label, "doc": o.doc, "default": o.id == c.default} for o in c.options]} for c in cfg.metadata.choices] - choice_ids = [c.id for c in cfg.metadata.choices] - options = [[o.id for o in sorted(c.options, key=lambda o: o.id != c.default)] for c in cfg.metadata.choices] - def merge(rendered: list[str]) -> dict | None: - """The site's one block for the combinations' renders (in - all_combos' order), or None when they do not merge.""" - keys = [tuple(sel["option"] for sel in cb["selections"]) for cb in all_combos()] + def merge(rendered: list[str], runtime: str = "podman") -> dict | None: + """The site's one block for the combinations' renders (all_combos' + order, the runtime's combinations only), or None when they do not + merge.""" + shown = [c for c in cfg.metadata.choices if c.applies(runtime)] + choice_ids = [c.id for c in shown] + options = [[o.id for o in sorted(c.options, key=lambda o: o.id != c.default)] for c in shown] + keys = [tuple(sel["option"] for sel in cb["selections"] if runtime in sel["runtimes"]) + for cb in all_combos() if runtime in cb["runtimes"]] got = choice_merge.merge(dict(zip(keys, (r.split("\n") for r in rendered), strict=True)), keys[0], options) if got is None: return None diff --git a/dbuild/templates/README.j2 b/dbuild/templates/README.j2 index 1769254..51b28ab 100644 --- a/dbuild/templates/README.j2 +++ b/dbuild/templates/README.j2 @@ -448,7 +448,7 @@ Before deploying, ensure your host environment is ready. See the [Quick Start Gu ### Podman Compose {%- if compose_text and choices %} -{%- for c in choices %} +{%- for c in choices if "podman" in c.runtimes %} **{{ c.label }}.** {{ c.doc }} {%- endfor %} @@ -456,14 +456,16 @@ Before deploying, ensure your host environment is ready. See the [Quick Start Gu {{ choices_capped.podman }} {%- endif %} -{%- for cb in (combos[:1] if choices_capped.podman else combos) %} -{%- if not choices_capped.podman %} +{#- Only the combinations Podman can reach: an AppJail-only choice at its default. #} +{%- set pm_combos = [] %}{% for cb in combos if "podman" in cb.runtimes %}{% set _ = pm_combos.append(cb) %}{% endfor %} +{%- for cb in (pm_combos[:1] if choices_capped.podman or pm_combos | length == 1 else pm_combos) %} +{%- if not choices_capped.podman and pm_combos | length > 1 %} -#### {{ cb.label }}{% if cb.default %} (default){% endif %} +#### {{ cb.labels.podman }}{% if cb.default %} (default){% endif %} {%- endif %} -{%- if cb.doc %} +{%- if cb.docs_for.podman %} -{{ cb.doc }} +{{ cb.docs_for.podman | join(" ") }} {%- endif %} {%- if cb.example_env | trim %} @@ -535,10 +537,12 @@ Save as `compose.yaml`, then run `podman-compose up -d`. {{ choices_capped.appjail }} {%- endif %} -{%- for cb in (combos[:1] if choices_capped.appjail else combos) %} -{%- if not choices_capped.appjail %} +{#- Only the combinations AppJail can reach: a podman-only choice at its default. #} +{%- set aj_combos = [] %}{% for cb in combos if "appjail" in cb.runtimes %}{% set _ = aj_combos.append(cb) %}{% endfor %} +{%- for cb in (aj_combos[:1] if choices_capped.appjail or aj_combos | length == 1 else aj_combos) %} +{%- if not choices_capped.appjail and aj_combos | length > 1 %} -#### {{ cb.label }}{% if cb.default %} (default){% endif %} +#### {{ cb.labels.appjail }}{% if cb.default %} (default){% endif %} {%- endif %} {{ appjail_director_snippet(option=cb) }} diff --git a/dbuild/templates/README.mkdocs.j2 b/dbuild/templates/README.mkdocs.j2 index 08c1a9c..46b06fa 100644 --- a/dbuild/templates/README.mkdocs.j2 +++ b/dbuild/templates/README.mkdocs.j2 @@ -15,27 +15,33 @@ choice_merge folds them into one block whose varying lines carry the picks that keep them; the script shows those. Combinations the merge cannot express follow it whole. #} +{#- A choice that is not for this runtime (runtimes: [podman]) gets no row + here, and only the combinations with it at its default are listed, keyed + without it: the script builds a form's key from its own rows. #} {%- macro choice_form(runtime) -%} +{%- set shown = [] %}{% for c in choices if runtime in c.runtimes %}{% set _ = shown.append(c) %}{% endfor %} {%- set merged = none %} -{%- if choices_mode == "merged" %} +{%- if shown and choices_mode == "merged" %} {%- set rendered = [] %} -{%- for cb in all_combos() %}{% set _ = rendered.append(combo_files(cb, runtime, true)) %}{% endfor %} -{%- set merged = choice_merge(rendered) %} +{%- for cb in all_combos() if runtime in cb.runtimes %}{% set _ = rendered.append(combo_files(cb, runtime, true)) %}{% endfor %} +{%- set merged = choice_merge(rendered, runtime) %} {%- endif %} -{%- if choices_capped[runtime] and not merged %} +{%- if not shown %} +{{ combo_files(combos[0], runtime) }} +{% elif choices_capped[runtime] and not merged %} {{ choices_capped[runtime] }} {{ combo_files(combos[0], runtime) }} {% else -%} -
-{% for c in choices if not c.toggle %} +
+{% for c in shown if not c.toggle %} **{{ c.label }}** {{ c.doc }} {: .choice data-choice="{{ c.id }}" }
{% for o in c.options %}{% endfor %}
{% endfor %} -{%- set toggles = choices | selectattr("toggle") | list %} +{%- set toggles = shown | selectattr("toggle") | list %} {%- if toggles %}
{% for c in toggles %}{% endfor %}
@@ -61,9 +67,9 @@
{% endfor %} {%- else %} -{% for cb in combos %} +{% for cb in combos if runtime in cb.runtimes %} -
+
{{ combo_files(cb, runtime) }} @@ -79,11 +85,11 @@ {% if runtime == "podman" %} {{ you_get(cb, cb.parts, "container", merged) }} {% if merged %} -{% for d in cb.docs %} +{% for d in cb.docs_for.podman %} {{ d }} {% endfor %} -{% elif cb.doc %} -{{ cb.doc }} +{% elif cb.docs_for.podman %} +{{ cb.docs_for.podman | join(" ") }} {% endif %} {#- No .env at all (SQLite: nothing to set): no step asking to fill one in. #} {% if cb.example_env_site | trim -%} @@ -106,11 +112,11 @@ Then run `podman-compose up -d`. {% else %} {{ you_get(cb, cb.jails, "jail", merged) }} {% if merged %} -{% for d in cb.docs %} +{% for d in cb.docs_for.appjail %} {{ d }} {% endfor %} -{% elif cb.doc %} -{{ cb.doc }} +{% elif cb.docs_for.appjail %} +{{ cb.docs_for.appjail | join(" ") }} {% endif %} {{ appjail_director_snippet(port_var, cb, merged) }} diff --git a/tests/test_docs.py b/tests/test_docs.py index d3773f9..8561eef 100644 --- a/tests/test_docs.py +++ b/tests/test_docs.py @@ -1225,3 +1225,127 @@ def test_deploy_bundle_env_and_mkdocs_zip_filename(self): self.assertNotIn("RADARR_CONFIG_PATH=/radarr", env_text) self.assertIn('data-zip-filename="appjail-director.yml"', mkdocs) self.assertNotIn('data-zip-filename="appjail-director.yaml"', mkdocs) + + +# ── Choices limited to a runtime ─────────────────────────────────────── + +# search only on podman: AppJail shows the database row alone. +RUNTIME_COMPOSE = CHOICES_COMPOSE.replace( + " search:\n label: Search\n", + " search:\n label: Search\n runtimes: [podman]\n", 1) + + +class TestChoiceRuntimes(unittest.TestCase): + def _load(self, t: Path): + (t / "compose.yaml").write_text(RUNTIME_COMPOSE) + (t / "example.env").write_text(CHOICES_ENV) + (t / "Containerfile.j2").write_text(CONTAINERFILE_J2) + return dbuild_config.load(t) + + def test_parsed_and_linted(self): + import yaml as _yaml + + from dbuild import choices as choices_mod + data = _yaml.safe_load(RUNTIME_COMPOSE) + cs = {c.id: c for c in choices_mod.parse(data["x-daemonless"], data)} + self.assertTrue(cs["search"].applies("podman")) + self.assertFalse(cs["search"].applies("appjail")) + self.assertTrue(cs["database"].applies("appjail"), "no runtimes: every runtime") + self.assertEqual(choices_mod.validate(list(cs.values()), data), []) + data["x-daemonless"]["choices"]["search"]["runtimes"] = ["docker"] + errs = choices_mod.validate(choices_mod.parse(data["x-daemonless"], data), data) + self.assertTrue(any("runtimes: 'docker' is not a runtime" in e for e in errs), errs) + + def test_catalog_carries_runtimes_only_when_set(self): + from dbuild import choices as choices_mod + with tempfile.TemporaryDirectory() as d: + t = Path(d) + with _chdir(t): + cfg = self._load(t) + out = {c["id"]: c for c in choices_mod.to_fjord(cfg.metadata.choices, cfg.compose_text, cfg.compose_data)["choices"]} + self.assertEqual(out["search"]["runtimes"], ["podman"]) + self.assertNotIn("runtimes", out["database"]) + + def test_appjail_lists_only_combinations_at_the_hidden_default(self): + with tempfile.TemporaryDirectory() as d: + t = Path(d) + with _chdir(t): + cfg = self._load(t) + ctx = docs._enrich_metadata(cfg, None) + site = docs._get_jinja_env(t).get_template("README.mkdocs.j2").render(dict(ctx, render_mode="mkdocs")) + outputs, errors = docs.render_generated(cfg, argparse.Namespace(community=None), t) + self.assertEqual(errors, []) + on = _combo(ctx, search="on") + self.assertEqual(on["runtimes"], ["podman"]) + self.assertEqual(_combo(ctx, database="postgres")["runtimes"], ["podman", "appjail"]) + self.assertEqual(_combo(ctx, database="postgres")["labels"]["appjail"], "PostgreSQL") + podman, appjail = site.split(':appjail-appjail: AppJail', 1) + self.assertIn('data-choice="search"', podman) + self.assertIn('data-key="database=sqlite;search=on"', podman) + self.assertNotIn('data-choice="search"', appjail, "no row for a podman-only choice") + self.assertNotIn("search=", appjail, "keys built from the form's own rows") + self.assertIn('data-key="database=postgres"', appjail) + readme_aj = outputs["README.md"].split("### AppJail Director", 1)[1] + self.assertIn("#### PostgreSQL\n", readme_aj) + self.assertNotIn(", On", readme_aj) + self.assertNotIn(", Off", readme_aj) + self.assertIn("#### SQLite, On\n", outputs["README.md"].split("### AppJail Director", 1)[0]) + + def test_a_form_with_no_choices_for_the_runtime_is_just_the_files(self): + compose = RUNTIME_COMPOSE.replace(" kind: database\n", " kind: database\n runtimes: [podman]\n", 1) + with tempfile.TemporaryDirectory() as d: + t = Path(d) + (t / "compose.yaml").write_text(compose) + (t / "example.env").write_text(CHOICES_ENV) + (t / "Containerfile.j2").write_text(CONTAINERFILE_J2) + with _chdir(t): + cfg = dbuild_config.load(t) + site = docs._get_jinja_env(t).get_template("README.mkdocs.j2").render(dict(docs._enrich_metadata(cfg), render_mode="mkdocs")) + appjail = site.split(':appjail-appjail: AppJail', 1)[1] + self.assertNotIn('class="deploy-choices"', appjail) + self.assertNotIn("deploy-combo", appjail) + self.assertIn("appjail-director.yml", appjail) + + + def test_an_appjail_only_choice_leaves_podman_alone(self): + compose = CHOICES_COMPOSE.replace(" search:\n label: Search\n", + " search:\n label: Search\n runtimes: [appjail]\n", 1) + with tempfile.TemporaryDirectory() as d: + t = Path(d) + (t / "compose.yaml").write_text(compose) + (t / "example.env").write_text(CHOICES_ENV) + (t / "Containerfile.j2").write_text(CONTAINERFILE_J2) + with _chdir(t): + cfg = dbuild_config.load(t) + site = docs._get_jinja_env(t).get_template("README.mkdocs.j2").render(dict(docs._enrich_metadata(cfg), render_mode="mkdocs")) + outputs, _ = docs.render_generated(cfg, argparse.Namespace(community=None), t) + podman, appjail = site.split(':appjail-appjail: AppJail', 1) + self.assertNotIn('data-choice="search"', podman) + self.assertNotIn("search=", podman) + self.assertIn('data-choice="search"', appjail) + readme_pm = outputs["README.md"].split("### Podman Compose", 1)[1].split("### AppJail Director", 1)[0] + self.assertNotIn("**Search.**", readme_pm) + self.assertIn("#### PostgreSQL\n", readme_pm) + self.assertNotIn("compose.database-sqlite.search-on.yaml", site) + + def test_the_merged_form_leaves_out_the_hidden_choice(self): + compose = _toggles_compose(6).replace(" label: App0\n", " label: App0\n runtimes: [podman]\n", 1) + with tempfile.TemporaryDirectory() as d: + t = Path(d) + (t / "compose.yaml").write_text(compose) + (t / "example.env").write_text("TZ=UTC\n") + (t / "Containerfile.j2").write_text(CONTAINERFILE_J2) + with _chdir(t): + cfg = dbuild_config.load(t) + ctx = docs._enrich_metadata(cfg, None) + site = docs._get_jinja_env(t).get_template("README.mkdocs.j2").render(dict(ctx, render_mode="mkdocs")) + self.assertEqual(ctx["choices_mode"], "merged") + podman, appjail = site.split(':appjail-appjail: AppJail', 1) + self.assertEqual(podman.count('class="deploy-merged"'), 1) + self.assertEqual(appjail.count('class="deploy-merged"'), 1) + self.assertIn('data-choice="app0"', podman) + self.assertNotIn('data-choice="app0"', appjail) + self.assertNotIn('app0', appjail.split('class="deploy-merged"', 1)[1].split("data-when=", 1)[1].split('"', 2)[1], + "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)