# SPDX-FileCopyrightText: Defame1297 and contributors # SPDX-License-Identifier: GPL-3.0-or-later """Choose the molecule scenarios a run needs. python3 -I scripts/select_molecule_scenarios.py [] Prints one scenario directory per line (`extensions/molecule/` or `roles//molecule/`), extensions first, then roles, each sorted. The molecule workflow runs `molecule test` in each. Only a pull request is narrowed, and only when is given and EVENT_NAME is `pull_request`. Then the diff of ...HEAD decides: * a file under roles// selects that role's scenarios, and those of every role that uses it (below); * a file under extensions/molecule//, when that is a scenario, selects that scenario only (the image-smoke scenarios test the images, not the roles); a shared file such as extensions/molecule/requirements.yml is "any other file"; * a file on the IGNORED list (documentation, changelog, repository tooling that no scenario reads; galaxy.yml by a rule in .gitea/workflows/AGENTS.md) selects nothing; * .gitea/workflows/molecule.yml, when only comments, blank lines (both outside a block scalar such as `run: |`) or the image pins changed: nothing for comments; for MOLECULE_IMAGE or MOLECULE_IMAGE_2604, every scenario whose directory names that variable, or every scenario when a shared molecule file names it; for CI_IMAGE (the tools molecule runs with), every scenario. Any other change to it is "any other file"; * any other file selects every scenario. A role uses another when any file under its directory names it as `mortis.kamino.` (an include_role, a scenario's prepare play, a comment). The relation is transitive: when `a` names `b` and `b` names `c`, a change to `c` selects all three. The roles call each other by that full name only (a test checks includes, imports, play `roles:` entries and meta dependencies for a bare or templated role name), so the text search finds every use. It reads the tree under test, not the base: a pull request that drops a use also changes the using role, which then selects itself, and a role the pull request deletes or renames still counts as used by the roles that name it. A shared file outside roles// (a plugin) already selects everything. Every other case runs everything: a push, a manual dispatch, a scheduled run, no , a git failure. Narrowing is an optimisation, so any doubt resolves to the full set. The scenarios the selection skips still run on `main`: the nightly run and a manual dispatch run them all. A changed role that exists but has no scenario is an error, not an empty selection: a new role without a molecule scenario, or a deleted or renamed scenario, must not pass Molecule with nothing tested. A role whose directory is gone (the role was deleted) selects nothing. The workflow runs this script from the base branch's copy, not the pull request's, so a pull request cannot edit the rules it is judged by (the same reason lint.yml runs check_bot_pr_diff.py from origin/main). No scenario runs the pull request's copy, so this file is on the IGNORED list: its unit tests test it, and the nightly run and a manual dispatch run it. Exit codes: 0 ok (an empty selection from an all-ignored diff is ok), 1 no scenario exists at all, or a changed role has none, 2 bad usage. Notices go to stderr as `::notice::` lines, with control characters in paths escaped so a crafted file name cannot inject a log command. """ import fnmatch import glob import os import re import subprocess import sys # Paths no scenario reads. A match is by fnmatch on the repository-relative path, where `*` # also crosses `/`. Keep this list short and literal: anything not listed runs everything. IGNORED = ( "docs/*", "changelogs/*", "LICENSES/*", "README.md", "galaxy.yml", "CONTRIBUTING.md", "SECURITY.md", "GLOSSARY.md", "AGENTS.md", "*/AGENTS.md", "roles/*/README.md", "CODEOWNERS", "CHANGELOG.rst", "COPYING", "NOTICE", "REUSE.toml", "renovate.json", ".gitignore", ".yamllint", ".ansible-lint", ".ansible-lint-ignore", ".pre-commit-config.yaml", ".python-version", "requirements-dev.txt", "requirements-dev.lock", "ruff.toml", "apm.yml", "apm.lock.yaml", ".claude/*", "tests/sanity/*", "tests/scripts/*", "images/*", ".gitea/actionlint.yaml", ".gitea/ISSUE_TEMPLATE/*", ".gitea/PULL_REQUEST_TEMPLATE.md", ".gitea/workflows/lint.yml", ".gitea/workflows/build.yml", ".gitea/workflows/image.yml", ".gitea/workflows/renovate.yml", ".gitea/workflows/gitea-release-key.yml", "scripts/check_bot_pr_diff.py", "scripts/check_image_versions.py", "scripts/next_image_version.py", "scripts/check_tarball.py", "scripts/check_gitea_release_key.py", "scripts/ansible-lint.sh", "scripts/ansible-test-sanity.sh", "scripts/dev-setup.sh", "scripts/lock-requirements.sh", "scripts/select_molecule_scenarios.py", ) WORKFLOW = ".gitea/workflows/molecule.yml" # The image pins of WORKFLOW, each a `KEY: >-` line followed by its value line, in the shape # Renovate writes. PIN_KEY = re.compile(r"(\s+)(CI_IMAGE|MOLECULE_IMAGE|MOLECULE_IMAGE_2604): >-") PIN_VALUE = re.compile( r"(\s+)git\.rkdr\.net/mortis/[a-z0-9._-]+:[^@\s]+@sha256:[0-9a-f]{64}" ) # A line that opens a block scalar (`run: |`, `if: >-`, `- |`): its `#` lines are content. # A tagged or anchored opener (`!!str |`, `&a |`) or a bare `|` line is not recognised; adding # one changes a significant line, so it fails closed. BLOCK_OPENER = re.compile(r"(\s*).*[:-][ \t]+[|>][-+0-9]*([ \t]+#.*)?") # Where molecule reads files shared by scenarios; a scenario directory below them is not shared. SHARED = (".config/molecule", "extensions/molecule", "roles/*/molecule") def printable(text): """`text` with control characters (a newline in a file name) escaped, for a log line.""" return "".join( c if c.isprintable() else c.encode("unicode_escape").decode("ascii") for c in text ) def discover(root="."): """Every scenario directory, extensions first, each group sorted.""" found = [] ext = os.path.join(root, "extensions", "molecule") if os.path.isdir(ext): for name in sorted(os.listdir(ext)): if name.isprintable() and os.path.isfile( os.path.join(ext, name, "molecule.yml") ): found.append(f"extensions/molecule/{name}") roles = os.path.join(root, "roles") if os.path.isdir(roles): for role in sorted(os.listdir(roles)): mol = os.path.join(roles, role, "molecule") if not os.path.isdir(mol): continue for name in sorted(os.listdir(mol)): if ( role.isprintable() and name.isprintable() and os.path.isfile(os.path.join(mol, name, "molecule.yml")) ): found.append(f"roles/{role}/molecule/{name}") return found ROLE_REFERENCE = re.compile(r"mortis\.kamino\.([A-Za-z0-9_]+)") def users(root=".", gone=()): """Map each role to the roles whose files name it as mortis.kamino.. Self-references (a scenario converging its own role) are left out, and so are names that are neither a role directory nor in `gone`: the changed roles, so that a role deleted or renamed by the pull request still selects the roles that call it. """ base = os.path.join(root, "roles") if not os.path.isdir(base): return {} roles = {r for r in os.listdir(base) if os.path.isdir(os.path.join(base, r))} known = roles | set(gone) used_by = {} for role in roles: for dirpath, _dirs, files in os.walk(os.path.join(base, role)): for name in files: try: with open(os.path.join(dirpath, name), "rb") as f: text = f.read().decode("utf-8", "ignore") except OSError: continue for other in ROLE_REFERENCE.findall(text): if other != role and other in known: used_by.setdefault(other, set()).add(role) return used_by def with_users(roles, used_by): """`roles` plus every role that uses one of them, directly or through another.""" found = set(roles) todo = list(roles) while todo: for user in used_by.get(todo.pop(), ()): if user not in found: found.add(user) todo.append(user) return found def _significant(text): """WORKFLOW's lines without comments and blank lines, and its pins; None when unsure. Only lines outside a block scalar are dropped: inside one (a `run: |` script) a `#` line is content. A pin's value must be the very next line, deeper than its key, in PIN_VALUE's shape. """ lines, pins, key, block = [], [], None, None for line in text.splitlines(): indent = len(line) - len(line.lstrip()) if key: if not PIN_VALUE.fullmatch(line) or indent <= key[1]: return None pins.append((key[0], line.strip())) lines.append("") key = None continue if block is not None and (not line.strip() or indent > block): lines.append(line) continue block = None if not line.strip() or line.lstrip().startswith("#"): continue match = PIN_KEY.fullmatch(line) if match: key = (match[2], len(match[1])) if BLOCK_OPENER.fullmatch(line): block = indent lines.append(line) return None if key else (lines, pins) def pin_changes(old, new): """The pins that differ between two texts of WORKFLOW, or None when anything else does. An empty set means only comments or blank lines outside block scalars changed. """ old_split, new_split = _significant(old), _significant(new) if old_split is None or new_split is None or old_split[0] != new_split[0]: return None return {k for (k, a), (_k, b) in zip(old_split[1], new_split[1]) if a != b} def _raise(error): raise error def _names(path, word, skip=()): """Whether a file under `path`, outside the directories in `skip`, matches `word`. Raises OSError when a directory or file cannot be read, or is a symlink (os.walk does not follow one, so what it points to would go unread). """ if os.path.islink(path): raise OSError(f"symlink: {path}") for dirpath, dirs, files in os.walk(path, onerror=_raise): for name in dirs + files: if os.path.islink(os.path.join(dirpath, name)): raise OSError(f"symlink: {os.path.join(dirpath, name)}") dirs[:] = [d for d in dirs if os.path.join(dirpath, d) not in skip] for name in files: with open(os.path.join(dirpath, name), "rb") as f: if word.search(f.read().decode("utf-8", "ignore")): return True return False def naming(all_scenarios, variable, root="."): """The scenarios a change to the image pin `variable` reaches. Those with a file naming it; every scenario when a shared file names it or a file cannot be read. """ word = re.compile(r"\b" + re.escape(variable) + r"\b") scenarios = {os.path.join(root, s) for s in all_scenarios} shared = [d for g in SHARED for d in glob.glob(os.path.join(root, g))] try: if any(_names(d, word, scenarios) for d in shared if os.path.isdir(d)): return list(all_scenarios) return [s for s in all_scenarios if _names(os.path.join(root, s), word)] except OSError: return list(all_scenarios) def is_ignored(path): return any(fnmatch.fnmatchcase(path, pattern) for pattern in IGNORED) def reason_for(changed_roles, roles, extensions, image_pins): """The one-line reason select() gives for its choice.""" notes = [] if roles: notes.append( "roles changed: " + ", ".join(printable(r) for r in sorted(changed_roles)) ) if roles - changed_roles: notes.append( "their users: " + ", ".join(printable(r) for r in sorted(roles - changed_roles)) ) if extensions: notes.append( "image-smoke scenarios changed: " + ", ".join(printable(e.split("/")[2]) for e in sorted(extensions)) ) if image_pins: notes.append("image pins changed: " + ", ".join(sorted(image_pins))) return "; ".join(notes) or "no change that a scenario reads" def select(all_scenarios, changed, root=".", pins=None): """The scenarios `changed` (repository-relative paths) needs, and a one-line reason. `pins` is pin_changes() of WORKFLOW; None when it is not narrowed. Raises ValueError when a changed role still exists but has no scenario. """ roles = set() extensions = set() by_image = set() image_pins = set() for path in changed: if is_ignored(path): continue if path == WORKFLOW and pins is not None and "CI_IMAGE" not in pins: image_pins = pins for pin in pins: by_image.update(naming(all_scenarios, pin, root)) continue parts = path.split("/") if len(parts) > 2 and parts[0] == "roles": roles.add(parts[1]) continue scenario = "/".join(parts[:3]) if ( len(parts) > 3 and parts[:2] == ["extensions", "molecule"] and scenario in all_scenarios ): extensions.add(scenario) continue return list(all_scenarios), f"{printable(path)} can affect every scenario" changed_roles = roles roles = with_users(changed_roles, users(root, changed_roles)) chosen = [ s for s in all_scenarios if s in extensions or s in by_image or (s.startswith("roles/") and s.split("/")[1] in roles) ] covered = {s.split("/")[1] for s in chosen if s.startswith("roles/")} bare = sorted( r for r in roles - covered if os.path.isdir(os.path.join(root, "roles", r)) ) if bare: raise ValueError( "role without a molecule scenario (changed, or a user of a changed role): " + ", ".join(printable(r) for r in bare) ) return chosen, reason_for(changed_roles, roles, extensions, image_pins) def changed_paths(base_ref): """Paths changed in base_ref...HEAD; a rename counts as a delete plus an add.""" out = subprocess.run( [ "git", "diff", "--name-only", "--no-renames", "-z", f"{base_ref}...HEAD", "--", ], check=True, capture_output=True, ).stdout return [os.fsdecode(p) for p in out.split(b"\0") if p] def workflow_pins(base_ref, changed): """pin_changes() of WORKFLOW from the merge base to HEAD; None on any doubt.""" if WORKFLOW not in changed: return None def git(*args): return subprocess.run(["git", *args], check=True, capture_output=True).stdout try: base = git("merge-base", base_ref, "HEAD").decode("ascii").strip() old = git("show", f"{base}:{WORKFLOW}").decode("utf-8") new = git("show", f"HEAD:{WORKFLOW}").decode("utf-8") except (subprocess.CalledProcessError, OSError, UnicodeError): return None return pin_changes(old, new) def main(argv, environ=None): environ = os.environ if environ is None else environ if len(argv) > 2: print("usage: select_molecule_scenarios.py []", file=sys.stderr) return 2 base_ref = argv[1] if len(argv) == 2 else "" scenarios = discover() if not scenarios: print("::error::no molecule scenario found", file=sys.stderr) return 1 if environ.get("EVENT_NAME") != "pull_request" or not base_ref: print( f"::notice::Running all {len(scenarios)} scenarios (not a pull request)", file=sys.stderr, ) chosen = scenarios else: try: changed = changed_paths(base_ref) except (subprocess.CalledProcessError, OSError, UnicodeError) as exc: print( f"::warning::cannot diff against {printable(base_ref)} ({printable(str(exc))}); running all scenarios", file=sys.stderr, ) chosen = scenarios else: try: pins = workflow_pins(base_ref, changed) chosen, reason = select(scenarios, changed, pins=pins) except ValueError as exc: print(f"::error::{exc}", file=sys.stderr) return 1 print( f"::notice::Running {len(chosen)} of {len(scenarios)} scenarios: {reason}", file=sys.stderr, ) for scenario in chosen: print(scenario) return 0 if __name__ == "__main__": sys.exit(main(sys.argv))