diff --git a/cli/meta/env/__main__.py b/cli/meta/env/__main__.py index d4f7e3764f..d1abfe9c6f 100644 --- a/cli/meta/env/__main__.py +++ b/cli/meta/env/__main__.py @@ -2,8 +2,10 @@ from __future__ import annotations +import argparse import os import sys +from pathlib import Path from utils.env.builder import build_env from utils.env.parser import parse_static_env_with_comments @@ -14,18 +16,34 @@ from . import PROJECT_ROOT as REPO_ROOT HOST_OWNED_KEY = "INFINITO_DOTENV_HOST_OWNED" # nocheck: dotenv-host-owned-marker Reason: set only by compose.yml inside the runner container; not a configuration key, a .env entry could freeze the host .env -def main() -> int: +def main(argv: list[str] | None = None) -> int: + """Generate the env set from default.env and the runtime context. + + Args: + argv: command-line arguments; ``--output PATH`` writes the set to PATH + instead of the repository's ``.env``, which then stays untouched. + + Returns: + 0 on success, 2 when default.env is missing. + """ + parser = argparse.ArgumentParser(prog="python -m cli.meta.env") + parser.add_argument("--output", type=Path) + args = parser.parse_args([] if argv is None else argv) static_path = REPO_ROOT / "default.env" - out_path = REPO_ROOT / ".env" + out_path = args.output or REPO_ROOT / ".env" + out_name = args.output or ".env" if not static_path.is_file(): print(f"ERROR: missing {static_path}", file=sys.stderr) return 2 - if out_path.is_file() and os.environ.get(HOST_OWNED_KEY) == "true": + if ( + args.output is None + and out_path.is_file() + and os.environ.get(HOST_OWNED_KEY) == "true" + ): print( - f"Kept {out_path.relative_to(REPO_ROOT)}: the host checkout owns it " - f"({HOST_OWNED_KEY})", + f"Kept {out_name}: the host checkout owns it ({HOST_OWNED_KEY})", file=sys.stderr, ) return 0 @@ -33,12 +51,9 @@ def main() -> int: static, static_comments = parse_static_env_with_comments(static_path) eb = build_env(static, repo_root=REPO_ROOT, comments=static_comments) write_dotenv(eb, out_path) - print( - f"Wrote {out_path.relative_to(REPO_ROOT)} ({len(eb.values)} variables)", - file=sys.stderr, - ) + print(f"Wrote {out_name} ({len(eb.values)} variables)", file=sys.stderr) return 0 if __name__ == "__main__": - sys.exit(main()) + sys.exit(main(sys.argv[1:])) diff --git a/docs/contributing/environment/variables.md b/docs/contributing/environment/variables.md index a14e12cd88..6b47e34511 100644 --- a/docs/contributing/environment/variables.md +++ b/docs/contributing/environment/variables.md @@ -27,6 +27,7 @@ Already-set env vars take precedence over `default.env` defaults. - [`env/`](../../../utils/env/) (under `utils/`) holds the parser, runtime helpers, writer, and one handler module per dynamically-computed variable under [`handlers/`](../../../utils/env/handlers/). - [`env/`](../../../cli/meta/env/) (under `cli/meta/`) provides the CLI entry point invoked as `python -m cli.meta.env`. - [`load.sh`](../../../scripts/meta/env/load.sh) is the shell loader; it sources `.env` and auto-generates it on a cold clone. + When the exported `INFINITO_DISTRO` differs from the one `.env` was generated for, it loads a set generated for that distro through `python -m cli.meta.env --output ` and leaves `.env` as it is. ## Variables NOT in `default.env` diff --git a/roles/web-app-bridgy-fed/meta/services.yml b/roles/web-app-bridgy-fed/meta/services.yml index fd40548d63..c47b937e41 100644 --- a/roles/web-app-bridgy-fed/meta/services.yml +++ b/roles/web-app-bridgy-fed/meta/services.yml @@ -48,7 +48,8 @@ bridgy-fed: swarm: enabled: true image: python - version: 3.15-slim + # nocheck: docker-version upstream's requirements.pinned.txt pins cbor2 6.1.4, which ships wheels up to cp314 and needs Rust >= 1.88 to build from source. TODO: return to 3.15-slim once the pinned upstream ref carries cbor2 >= 6.1.5 (cp315 wheels) + version: 3.14-slim name: web-app-bridgy-fed repository: https://github.com/snarfed/bridgy-fed.git # nocheck: repository-version -- upstream publishes no tags, so the pin is a commit diff --git a/roles/web-app-n8n/meta/services.yml b/roles/web-app-n8n/meta/services.yml index 46bb83d1b1..e1899e35c4 100644 --- a/roles/web-app-n8n/meta/services.yml +++ b/roles/web-app-n8n/meta/services.yml @@ -67,7 +67,7 @@ n8n: backup: no_stop_required: false image: docker.n8n.io/n8nio/n8n - version: "2.44.1" + version: "2.44.2" update: type: registry_tags image: docker.n8n.io/n8nio/n8n diff --git a/scripts/meta/env/load.sh b/scripts/meta/env/load.sh index b1dff51f4c..dfb67daf3a 100755 --- a/scripts/meta/env/load.sh +++ b/scripts/meta/env/load.sh @@ -7,6 +7,9 @@ # re-entry from generator subshells (BASH_ENV would otherwise recurse). # PYTHON/PATH are re-resolved on every source so a venv created mid-chain wins; # caller-set values are snapshotted and restored after the bulk .env source. +# INFINITO_CONTAINER, INFINITO_PARENT_IMAGE and INFINITO_IMAGE derive from the +# distro: a caller INFINITO_DISTRO other than the one `.env` was generated for +# loads a set generated for that distro instead, and `.env` stays untouched. # zsh cannot run this loader's bash-isms (BASH_SOURCE, ${!indirect}, assoc-array # key expansion). When sourced from zsh, delegate to bash and import the @@ -44,7 +47,7 @@ if [[ -n "${VENV:-}" && -d "${VENV%/}/bin" ]]; then fi _infinito_env_mtime="$(stat -c %Y "${_infinito_env_dotenv}" 2>/dev/null || echo 0)" -if [[ "${INFINITO_ENV_LOADED:-}" == "1" && "${INFINITO_ENV_LOADED_MTIME:-}" == "${_infinito_env_mtime}" ]]; then # nocheck: env-loader-internal-guard +if [[ "${INFINITO_ENV_LOADED:-}" == "1" && "${INFINITO_ENV_LOADED_MTIME:-}" == "${_infinito_env_mtime}" && "${INFINITO_ENV_LOADED_DISTRO:-}" == "${INFINITO_DISTRO:-}" ]]; then # nocheck: env-loader-internal-guard unset _infinito_env_repo_root _infinito_env_dotenv _infinito_env_mtime return 0 fi @@ -53,11 +56,23 @@ if [[ "${INFINITO_ENV_GENERATING:-}" == "1" ]]; then # nocheck: env-loader-inter return 0 fi -if [[ ! -f "${_infinito_env_dotenv}" ]]; then +if [[ -n "${INFINITO_ENV_LOADED_DISTRO:-}" && "${INFINITO_ENV_LOADED_DISTRO}" != "${INFINITO_DISTRO:-}" ]]; then # nocheck: env-loader-internal-guard + unset INFINITO_CONTAINER INFINITO_PARENT_IMAGE INFINITO_IMAGE +fi + +_infinito_env_source="${_infinito_env_dotenv}" +_infinito_env_scratch="" +_infinito_env_distro="${INFINITO_DISTRO:-}" +if [[ -f "${_infinito_env_dotenv}" && -n "${_infinito_env_distro}" && "${_infinito_env_distro}" != "$(sed -n 's/^INFINITO_DISTRO=//p' "${_infinito_env_dotenv}")" ]]; then + _infinito_env_scratch="$(mktemp -d)" + _infinito_env_source="${_infinito_env_scratch}/env" +fi + +if [[ ! -f "${_infinito_env_source}" ]]; then ( cd "${_infinito_env_repo_root}" || exit 1 export INFINITO_ENV_GENERATING=1 - "${PYTHON}" -m cli.meta.env + "${PYTHON}" -m cli.meta.env --output "${_infinito_env_source}" ) >&2 fi @@ -73,14 +88,19 @@ while IFS= read -r _infinito_env_line; do if [[ -n "${!_infinito_env_key:-}" ]]; then _infinito_env_preserved["${_infinito_env_key}"]="${!_infinito_env_key}" fi -done <"${_infinito_env_dotenv}" +done <"${_infinito_env_source}" unset _infinito_env_line _infinito_env_key set -a # shellcheck disable=SC1090 -source "${_infinito_env_dotenv}" +source "${_infinito_env_source}" set +a +if [[ -n "${_infinito_env_scratch}" ]]; then + rm -rf "${_infinito_env_scratch}" +fi +unset _infinito_env_source _infinito_env_scratch _infinito_env_distro + for _infinito_env_key in "${!_infinito_env_preserved[@]}"; do declare -gx "${_infinito_env_key}=${_infinito_env_preserved[${_infinito_env_key}]}" done @@ -100,4 +120,5 @@ fi export INFINITO_ENV_LOADED="1" _infinito_env_mtime="$(stat -c %Y "${_infinito_env_dotenv}" 2>/dev/null || echo 0)" export INFINITO_ENV_LOADED_MTIME="${_infinito_env_mtime}" +export INFINITO_ENV_LOADED_DISTRO="${INFINITO_DISTRO:-}" unset _infinito_env_repo_root _infinito_env_dotenv _infinito_env_mtime diff --git a/scripts/tests/deploy/act/down_act_outer.sh b/scripts/tests/deploy/act/down_act_outer.sh index af792d57f2..f8d0340ae2 100755 --- a/scripts/tests/deploy/act/down_act_outer.sh +++ b/scripts/tests/deploy/act/down_act_outer.sh @@ -1,10 +1,11 @@ #!/usr/bin/env bash set +e -# Match act's outer-runner name prefix, not the image: ACT_PLATFORM_IMAGE varies the ancestor. -ids="$(docker ps -aq --filter "name=^act-")" +: "${INFINITO_CONTAINER:?INFINITO_CONTAINER is not set; source scripts/meta/env/load.sh or invoke via make}" + +ids="$(docker ps -aq --filter "name=^act-" --filter "label=infinito.worktree=${INFINITO_CONTAINER}")" if [ -n "${ids}" ]; then - echo "→ removing act outer container(s): ${ids}" + echo "→ removing act outer container(s) of ${INFINITO_CONTAINER}: ${ids}" # shellcheck disable=SC2086 docker rm -f ${ids} >/dev/null 2>&1 else diff --git a/scripts/tests/deploy/act/workflow.sh b/scripts/tests/deploy/act/workflow.sh index 2d5e126a9a..7be72c21a6 100755 --- a/scripts/tests/deploy/act/workflow.sh +++ b/scripts/tests/deploy/act/workflow.sh @@ -5,7 +5,8 @@ set -euo pipefail : "${ACT_EVENT:=workflow_dispatch}" : "${ACT_JOB:=}" : "${ACT_MATRIX:=}" -: "${ACT_CONTAINER_OPTIONS:=--privileged}" +: "${INFINITO_CONTAINER:?INFINITO_CONTAINER is not set; source scripts/meta/env/load.sh or invoke via make}" +: "${ACT_CONTAINER_OPTIONS:=--privileged --label infinito.worktree=${INFINITO_CONTAINER}}" : "${ACT_NETWORK:=host}" : "${ACT_PULL:=false}" : "${ACT_RM:=true}" diff --git a/tests/unit/python/cli/meta/env/test_main.py b/tests/unit/python/cli/meta/env/test_main.py index d2cc44c42f..261857a54e 100644 --- a/tests/unit/python/cli/meta/env/test_main.py +++ b/tests/unit/python/cli/meta/env/test_main.py @@ -9,7 +9,13 @@ import cli.meta.env.__main__ as env_main class TestDotenvHostOwned(unittest.TestCase): - def _run(self, *, dotenv_exists: bool, host_owned: str | None) -> tuple[int, bool]: + def _run( + self, + *, + dotenv_exists: bool, + host_owned: str | None, + argv: list[str] | None = None, + ) -> tuple[int, bool]: with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) (root / "default.env").write_text("INFINITO_DISTRO=debian\n") @@ -28,7 +34,7 @@ class TestDotenvHostOwned(unittest.TestCase): patch.object(env_main, "write_dotenv") as write_dotenv, ): build_env.return_value.values = {} - rc = env_main.main() + rc = env_main.main(argv) return rc, write_dotenv.called def test_a_host_owned_dotenv_is_kept(self) -> None: @@ -40,6 +46,16 @@ class TestDotenvHostOwned(unittest.TestCase): def test_without_the_marker_the_dotenv_is_regenerated(self) -> None: self.assertEqual(self._run(dotenv_exists=True, host_owned=None), (0, True)) + def test_an_explicit_output_is_written_even_when_host_owned(self) -> None: + self.assertEqual( + self._run( + dotenv_exists=True, + host_owned="true", + argv=["--output", "/nonexistent/distro.env"], + ), + (0, True), + ) + if __name__ == "__main__": # pragma: no cover unittest.main() diff --git a/tests/unit/python/scripts/meta/env/__init__.py b/tests/unit/python/scripts/meta/env/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/scripts/meta/env/test_load.py b/tests/unit/python/scripts/meta/env/test_load.py new file mode 100644 index 0000000000..1fa719719d --- /dev/null +++ b/tests/unit/python/scripts/meta/env/test_load.py @@ -0,0 +1,136 @@ +"""The distro-derived keys follow the distro the caller asks for. + +``scripts/tests/deploy/distros.sh`` exports ``INFINITO_DISTRO`` per iteration +and sources the loader again. The keys composed from the distro must then name +that distro, not the one ``.env`` was generated for, and ``.env`` itself must +stay as it was. +""" + +from __future__ import annotations + +import filecmp +import os +import shutil +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path +from typing import ClassVar + +from utils.cache.files import PROJECT_ROOT + +LOADER_DIR = Path(PROJECT_ROOT) / "scripts" / "meta" / "env" +SHOWN = ( + "INFINITO_DISTRO", + "INFINITO_CONTAINER", + "INFINITO_PARENT_IMAGE", + "INFINITO_IMAGE", +) +SHOW = "printf '%s\\n' " + " ".join(f'"{key}=${{{key}:-}}"' for key in SHOWN) + + +def clean_env(**overrides: str) -> dict[str, str]: + env = { + k: v + for k, v in os.environ.items() + if not k.startswith("INFINITO_") + and k not in ("BASH_ENV", "PYTHONPATH", "VENV", "PYTHON", "VIRTUAL_ENV") + } + env["PYTHONPATH"] = str(PROJECT_ROOT) + env.update(overrides) + return env + + +def bash(script: str, cwd: Path) -> dict[str, str]: + proc = subprocess.run( + ["bash", "-c", f"{script}\n{SHOW}"], + env=clean_env(), + cwd=cwd, + capture_output=True, + text=True, + check=True, + ) + return dict(line.split("=", 1) for line in proc.stdout.splitlines()) + + +class TestDistroDerivedKeys(unittest.TestCase): + scratch: ClassVar[Path] + expected: ClassVar[dict[str, dict[str, str]]] + + @classmethod + def setUpClass(cls) -> None: + cls.scratch = Path(tempfile.mkdtemp()) + cls.expected = {} + for distro in ("debian", "centos"): + path = cls.scratch / f"{distro}.env" + subprocess.run( + [sys.executable, "-m", "cli.meta.env", "--output", str(path)], + env=clean_env(INFINITO_DISTRO=distro), + cwd=PROJECT_ROOT, + capture_output=True, + check=True, + ) + cls.expected[distro] = bash(f'set -a; source "{path}"', cls.scratch) + + @classmethod + def tearDownClass(cls) -> None: + shutil.rmtree(cls.scratch) + + def run_loader(self, steps: str) -> dict[str, str]: + """Source a copy of the loader in a checkout whose ``.env`` is debian's. + + Args: + steps: bash run before the keys are shown; ``load`` sources the + loader. + + Returns: + The keys as the steps leave them. + """ + checkout = Path(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, checkout) + (checkout / "scripts" / "meta" / "env").mkdir(parents=True) + for name in ("load.sh", "python.sh"): + shutil.copy(LOADER_DIR / name, checkout / "scripts" / "meta" / "env") + dotenv = checkout / ".env" + shutil.copy(self.scratch / "debian.env", dotenv) + shown = bash( + f"load() {{ source scripts/meta/env/load.sh; }}\n{steps}", checkout + ) + self.assertTrue( + filecmp.cmp(dotenv, self.scratch / "debian.env", shallow=False), + ".env was rewritten", + ) + return shown + + def test_the_two_distros_derive_different_keys(self): + self.assertNotEqual( + self.expected["debian"]["INFINITO_PARENT_IMAGE"], + self.expected["centos"]["INFINITO_PARENT_IMAGE"], + ) + + def test_a_distro_exported_after_the_first_load_gets_its_own_keys(self): + shown = self.run_loader("load\nexport INFINITO_DISTRO=centos\nload") + self.assertEqual(shown, self.expected["centos"]) + + def test_a_distro_exported_before_the_first_load_gets_its_own_keys(self): + shown = self.run_loader("export INFINITO_DISTRO=centos\nload") + self.assertEqual(shown, self.expected["centos"]) + + def test_switching_back_restores_the_keys_of_the_dotenv(self): + shown = self.run_loader( + "load\nexport INFINITO_DISTRO=centos\nload\n" + "export INFINITO_DISTRO=debian\nload" + ) + self.assertEqual(shown, self.expected["debian"]) + + def test_a_caller_value_for_the_loaded_distro_still_wins(self): + shown = self.run_loader( + "load\nexport INFINITO_PARENT_IMAGE=caller/image:pinned\n" + "touch -d '+1 minute' .env\nload" + ) + self.assertEqual(shown["INFINITO_PARENT_IMAGE"], "caller/image:pinned") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/scripts/tests/deploy/act/__init__.py b/tests/unit/python/scripts/tests/deploy/act/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/scripts/tests/deploy/act/test_down_act_outer.py b/tests/unit/python/scripts/tests/deploy/act/test_down_act_outer.py new file mode 100644 index 0000000000..8082bf8f20 --- /dev/null +++ b/tests/unit/python/scripts/tests/deploy/act/test_down_act_outer.py @@ -0,0 +1,74 @@ +from __future__ import annotations + +import os +import subprocess +import tempfile +import unittest +from pathlib import Path + +from utils.cache.files import PROJECT_ROOT + +SCRIPT = PROJECT_ROOT / "scripts" / "tests" / "deploy" / "act" / "down_act_outer.sh" +DOCKER_STUB = ( + "#!/usr/bin/env bash\n" + 'printf "%s\\n" "$*" >>"${STUB_LOG}"\n' + 'if [ "$1" = ps ]; then\n' + ' case "$*" in *"label=infinito.worktree=own"*) echo own-id ;; esac\n' + "fi\n" +) + + +def teardown(container: str | None) -> tuple[subprocess.CompletedProcess, list[str]]: + """Run the teardown against a ``docker`` stub that only knows ``own-id``. + + Args: + container: value of ``INFINITO_CONTAINER``, or None to leave it unset. + + Returns: + The finished process and the docker invocations it made. + """ + with tempfile.TemporaryDirectory() as tmp: + stub = Path(tmp) / "docker" + stub.write_text(DOCKER_STUB) + stub.chmod(0o755) + log = Path(tmp) / "docker.log" + log.touch() + env = { + k: v + for k, v in os.environ.items() + if k not in ("BASH_ENV", "INFINITO_CONTAINER") + } + env.update(PATH=f"{tmp}{os.pathsep}{os.environ['PATH']}", STUB_LOG=str(log)) + if container is not None: + env["INFINITO_CONTAINER"] = container + done = subprocess.run( + ["bash", str(SCRIPT)], + env=env, + capture_output=True, + text=True, + check=False, + ) + return done, log.read_text().splitlines() # nocheck: cache-read stub call log + + +class TestDownActOuter(unittest.TestCase): + def test_only_the_own_worktrees_act_containers_are_listed(self) -> None: + _, calls = teardown("own") + self.assertIn("label=infinito.worktree=own", calls[0]) + + def test_the_own_act_container_is_removed(self) -> None: + _, calls = teardown("own") + self.assertEqual(calls[1], "rm -f own-id") + + def test_a_foreign_worktrees_act_container_is_left_alone(self) -> None: + _, calls = teardown("foreign") + self.assertEqual(len(calls), 1) + + def test_an_unset_container_name_removes_nothing(self) -> None: + done, calls = teardown(None) + self.assertNotEqual(done.returncode, 0) + self.assertEqual(calls, []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/scripts/tests/deploy/test_distros.py b/tests/unit/python/scripts/tests/deploy/test_distros.py index 4b6cb76aee..80c4d7903f 100644 --- a/tests/unit/python/scripts/tests/deploy/test_distros.py +++ b/tests/unit/python/scripts/tests/deploy/test_distros.py @@ -20,6 +20,7 @@ import unittest from pathlib import Path from utils.cache.files import PROJECT_ROOT, read_text +from utils.distros import pkgmgr_image from utils.env.parser import parse_static_env LOOP = PROJECT_ROOT / "scripts" / "tests" / "deploy" / "distros.sh" @@ -76,6 +77,19 @@ class TestDistrosLoop(unittest.TestCase): self.assertEqual(proc.returncode, 0, proc.stderr) self.assertEqual(sorted(record.split()), sorted(DISTROS.split())) + def test_every_distro_runs_with_a_parent_image_of_its_own(self) -> None: + proc, record = self._run( + DISTROS, + 'echo "${INFINITO_DISTRO} ${INFINITO_PARENT_IMAGE}' + ' ${INFINITO_PARENT_IMAGE_OWNER} ${INFINITO_PARENT_IMAGE_TAG}" >> "${RECORD}"', + INFINITO_CI_DISTRO_BUDGET_SECONDS="600", + ) + self.assertEqual(proc.returncode, 0, proc.stderr) + rows = [line.split() for line in record.splitlines()] + self.assertEqual(sorted(row[0] for row in rows), sorted(DISTROS.split())) + for distro, image, owner, tag in rows: + self.assertEqual(image, pkgmgr_image(distro, owner=owner, tag=tag)) + def test_the_command_inherits_the_env_layer(self) -> None: proc, record = self._run( "debian",