diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 96cb5ca..4645f17 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -86,7 +86,7 @@ repos: - id: ansible-lint name: ansible-lint description: ansible-lint production profile, offline - entry: ansible-lint --offline --nocolor + entry: scripts/ansible-lint.sh language: system files: ^(roles/|plugins/|meta/|galaxy\.yml$|requirements\.yml$|\.ansible-lint$|\.yamllint$) stages: ['pre-commit'] diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index be545f6..370d9fd 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -17,7 +17,8 @@ - Set up the tooling once per clone with `scripts/dev-setup.sh`: it creates a virtualenv with the pinned tools (`requirements-dev.txt`), installs the pinned collections the roles call (`requirements.yml`, into `.ansible/collections`, so local lint resolves the versions CI does) - and installs git hooks that find both. Then + and installs git hooks that find the tools (the `ansible-lint` hook, `scripts/ansible-lint.sh`, uses those + collections, also from a bare `pre-commit run`). Then `pre-commit run --all-files` before pushing. - Never commit credentials, tokens or key material. - Releases are cut by the maintainer: bump `version` in `galaxy.yml`, add a diff --git a/scripts/ansible-lint.sh b/scripts/ansible-lint.sh new file mode 100755 index 0000000..ebdf8e9 --- /dev/null +++ b/scripts/ansible-lint.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +# The ansible-lint pre-commit hook: ansible-lint --offline against the pinned collections. +# +# CI sets ANSIBLE_COLLECTIONS_PATH (the ci image bakes requirements.yml into /opt/collections) and +# this script then leaves the environment alone. A local run does not set it, and ansible-lint would +# resolve modules from the control host's ~/.ansible, whose collection versions need not be the +# ones CI tests against (#118, #80). So when the variable is unset, this script uses the collections +# scripts/dev-setup.sh installed into .ansible/collections of this clone, and fails with the fix +# when they are missing. That covers `git commit` and a bare `pre-commit run` alike. +set -euo pipefail + +root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$root" + +if [ -z "${ANSIBLE_COLLECTIONS_PATH:-}" ]; then + if [ ! -d "$root/.ansible/collections/ansible_collections" ]; then + echo "error: the pinned collections are not installed in $root/.ansible/collections; run scripts/dev-setup.sh" >&2 + exit 1 + fi + export ANSIBLE_HOME="$root/.ansible" + export ANSIBLE_COLLECTIONS_PATH="$root/.ansible/collections" +fi + +exec ansible-lint --offline --nocolor diff --git a/scripts/dev-setup.sh b/scripts/dev-setup.sh index 0b12e12..e06a2f2 100755 --- a/scripts/dev-setup.sh +++ b/scripts/dev-setup.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash # Sets up a local checkout for development: a virtualenv with the pinned tools # (requirements-dev.txt, the versions CI runs), the pinned collections the roles call -# (requirements.yml) and git hooks that find both. +# (requirements.yml) and git hooks that find the tools. # # scripts/dev-setup.sh # KAMINO_PYTHON=python3.13 scripts/dev-setup.sh to pick one # @@ -17,11 +17,11 @@ # Some hooks of .pre-commit-config.yaml are `language: system` (REUSE, changelog lint, # ansible-lint): they run their tools by name, so the tools must be on PATH when git # runs the hook. `pre-commit install` does not arrange that, so this script puts the -# virtualenv first on PATH inside the installed hook scripts. It also points ANSIBLE_HOME -# at .ansible/ of this clone and ANSIBLE_COLLECTIONS_PATH at the collections installed into -# it, so ansible-lint resolves the same collection versions as CI (the ci image bakes -# requirements.yml) and never the ones in the control host's ~/.ansible. It is idempotent; -# run it again after changing requirements-dev.txt, requirements.yml or the hook types. +# virtualenv first on PATH inside the installed hook scripts. It also installs the collections +# of requirements.yml into .ansible/collections of this clone: scripts/ansible-lint.sh (the +# ansible-lint hook) resolves modules from there, so local lint sees the collection versions CI +# does (the ci image bakes requirements.yml) and not the control host's ~/.ansible. It is +# idempotent; run it again after changing requirements-dev.txt, requirements.yml or the hook types. set -euo pipefail # ansible-core 2.22 (requirements-dev.txt) needs Python 3.13+. Renovate raises that pin, so @@ -132,7 +132,6 @@ ANSIBLE_COLLECTIONS_PATH="$collections" .venv/bin/ansible-galaxy collection inst -r requirements.yml -p "$collections" marker="# kamino-dev-setup: virtualenv first on PATH" -collections_marker="# kamino-dev-setup: collections from this clone" # default_install_hook_types in .pre-commit-config.yaml names these; keep in step. for hook in pre-commit commit-msg; do file="$(git -C "$root" rev-parse --path-format=absolute --git-path "hooks/$hook")" @@ -140,22 +139,12 @@ for hook in pre-commit commit-msg; do echo "error: $file was not installed by 'pre-commit install'; check default_install_hook_types in .pre-commit-config.yaml." >&2 exit 1 fi - # Each block is added on its own, so a hook installed by an older version of this script - # (PATH only) gains the collections path without a second PATH line. - add=() if ! grep -qxF "$marker" "$file"; then - # %q shell-quotes the path: a repository path with spaces, quotes or $(...) is data. - add+=("$marker" "export PATH=$(printf '%q' "$root/.venv/bin"):\"\$PATH\"") - fi - if ! grep -qxF "$collections_marker" "$file"; then - add+=("$collections_marker" "export ANSIBLE_HOME=$(printf '%q' "$root/.ansible")") - add+=("export ANSIBLE_COLLECTIONS_PATH=$(printf '%q' "$collections")") - fi - if [ "${#add[@]}" -gt 0 ]; then tmp="$(mktemp)" { head -n 1 "$file" - printf '%s\n' "${add[@]}" + # %q shell-quotes the path: a repository path with spaces, quotes or $(...) is data. + printf '%s\n' "$marker" "export PATH=$(printf '%q' "$root/.venv/bin"):\"\$PATH\"" tail -n +2 "$file" } > "$tmp" cat "$tmp" > "$file" # keeps the file mode of the hook diff --git a/scripts/select_molecule_scenarios.py b/scripts/select_molecule_scenarios.py index 5965e2b..770f621 100644 --- a/scripts/select_molecule_scenarios.py +++ b/scripts/select_molecule_scenarios.py @@ -81,6 +81,7 @@ IGNORED = ( "scripts/check_bot_pr_diff.py", "scripts/check_image_versions.py", "scripts/check_tarball.py", + "scripts/ansible-lint.sh", "scripts/dev-setup.sh", "scripts/reuse_lint.py", ) diff --git a/tests/scripts/test_ansible_lint_wrapper.py b/tests/scripts/test_ansible_lint_wrapper.py new file mode 100644 index 0000000..b8300bb --- /dev/null +++ b/tests/scripts/test_ansible_lint_wrapper.py @@ -0,0 +1,87 @@ +# SPDX-FileCopyrightText: Defame1297 and contributors +# SPDX-License-Identifier: GPL-3.0-or-later +"""Tests for scripts/ansible-lint.sh against a throwaway copy of the script and a stub ansible-lint. + +Run with: python3 -m unittest discover -s tests/scripts +""" + +import os +import pathlib +import shutil +import subprocess +import tempfile +import unittest + +SCRIPT = pathlib.Path(__file__).resolve().parents[2] / "scripts" / "ansible-lint.sh" + +# Prints what the wrapper hands to ansible-lint: its arguments, directory and the two variables. +STUB = """#!/bin/sh +echo "args=$*" +echo "cwd=$(pwd -P)" +echo "home=${ANSIBLE_HOME-unset}" +echo "path=${ANSIBLE_COLLECTIONS_PATH-unset}" +""" + + +@unittest.skipUnless(shutil.which("bash"), "bash is required") +class AnsibleLintWrapperTest(unittest.TestCase): + def setUp(self): + self.tmp = pathlib.Path(tempfile.mkdtemp(prefix="kamino-lintwrap-")).resolve() + self.addCleanup(shutil.rmtree, self.tmp, True) + self.repo = self.tmp / "repo" + (self.repo / "scripts").mkdir(parents=True) + shutil.copy(SCRIPT, self.repo / "scripts" / "ansible-lint.sh") + self.bin = self.tmp / "bin" + self.bin.mkdir() + stub = self.bin / "ansible-lint" + stub.write_text(STUB) + stub.chmod(0o755) + + def run_wrapper(self, cwd=None, **env): + base = {"PATH": f"{self.bin}:{os.environ['PATH']}", "HOME": str(self.tmp)} + return subprocess.run( + ["bash", str(self.repo / "scripts" / "ansible-lint.sh")], + env={**base, **env}, + cwd=str(cwd or self.repo), + capture_output=True, + text=True, + check=False, + ) + + def install_collections(self): + (self.repo / ".ansible" / "collections" / "ansible_collections").mkdir( + parents=True + ) + + def test_uses_the_clone_collections_when_the_variable_is_unset(self): + self.install_collections() + result = self.run_wrapper() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("args=--offline --nocolor", result.stdout) + self.assertIn(f"home={self.repo / '.ansible'}", result.stdout) + self.assertIn(f"path={self.repo / '.ansible' / 'collections'}", result.stdout) + + def test_leaves_a_preset_collections_path_alone(self): + # CI sets it (the ci image bakes the collections into /opt/collections), even with none in the clone. + result = self.run_wrapper(ANSIBLE_COLLECTIONS_PATH="/opt/collections") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("path=/opt/collections", result.stdout) + self.assertIn("home=unset", result.stdout) + + def test_fails_with_the_fix_when_the_collections_are_not_installed(self): + result = self.run_wrapper() + self.assertNotEqual(result.returncode, 0) + self.assertIn("scripts/dev-setup.sh", result.stderr) + self.assertNotIn("args=", result.stdout) + + def test_runs_from_the_repository_root_whatever_the_caller_directory(self): + self.install_collections() + elsewhere = self.tmp / "elsewhere" + elsewhere.mkdir() + result = self.run_wrapper(cwd=elsewhere) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn(f"cwd={self.repo}", result.stdout) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/scripts/test_dev_setup.py b/tests/scripts/test_dev_setup.py index 97146e3..17f40d5 100644 --- a/tests/scripts/test_dev_setup.py +++ b/tests/scripts/test_dev_setup.py @@ -146,12 +146,6 @@ class DevSetupTest(unittest.TestCase): for name in ("pre-commit", "commit-msg"): text = self.hook(repo, name).read_text() self.assertIn("# kamino-dev-setup: virtualenv first on PATH", text) - self.assertIn("# kamino-dev-setup: collections from this clone", text) - self.assertIn(f"export ANSIBLE_HOME={repo / '.ansible'}", text) - self.assertIn( - f"export ANSIBLE_COLLECTIONS_PATH={repo / '.ansible' / 'collections'}", - text, - ) self.assertEqual(self.hooks_z(repo), b"") def galaxy_calls(self) -> list[str]: @@ -174,29 +168,6 @@ class DevSetupTest(unittest.TestCase): self.assertIn("stub galaxy failure", result.stderr) self.assertNotIn("kamino-dev-setup", self.hook(repo).read_text()) - def test_hook_of_the_previous_version_gains_only_the_collections_path( - self, - ) -> None: - repo = self.make_repo() - self.assertEqual(self.run_setup(repo).returncode, 0) - hook = self.hook(repo) - # What the previous version of the script wrote: the PATH block, no collections block. - lines = hook.read_text().splitlines() - old = [ - line - for line in lines - if "collections from this clone" not in line - and "ANSIBLE_COLLECTIONS_PATH" not in line - and "ANSIBLE_HOME" not in line - ] - hook.write_text("\n".join(old) + "\n") - self.assertEqual(self.run_setup(repo).returncode, 0) - text = hook.read_text() - self.assertEqual(text.count("kamino-dev-setup: virtualenv first"), 1) - self.assertEqual(text.count("kamino-dev-setup: collections from this clone"), 1) - self.assertEqual(text.count("export ANSIBLE_COLLECTIONS_PATH="), 1) - self.assertEqual(text.count("export ANSIBLE_HOME="), 1) - def test_rerun_is_idempotent(self) -> None: repo = self.make_repo() self.assertEqual(self.run_setup(repo).returncode, 0) @@ -205,9 +176,6 @@ class DevSetupTest(unittest.TestCase): self.assertEqual(second_run.returncode, 0, second_run.stderr) self.assertEqual(self.hook(repo).read_text(), first) self.assertEqual(first.count("kamino-dev-setup: virtualenv first"), 1) - self.assertEqual( - first.count("kamino-dev-setup: collections from this clone"), 1 - ) def test_own_absolute_hooks_path_is_lifted_and_restored(self) -> None: repo = self.make_repo()