Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5e230201e6 | ||
|
|
114a21fc0f | ||
|
|
c33da78633 | ||
|
|
7dbf9a1bd0 | ||
|
|
6c031acc26 | ||
|
|
16b1aa4136 | ||
|
|
e4eb3bc656 | ||
|
|
15c3731e7f | ||
|
|
04259751ad | ||
|
|
699179674f | ||
|
|
bf604a1af2 | ||
|
|
3d2fab5388 | ||
|
|
042051b3e5 |
No files matched your search
@@ -80,10 +80,7 @@ issue.
|
||||
- **What a pull request runs is chosen by `scripts/select_molecule_scenarios.py`:** the scenarios
|
||||
of the roles it changes and of the roles that use them (any file naming
|
||||
`mortis.kamino.<role>`, transitively), none for a diff of only IGNORED paths, a failure for a
|
||||
changed role with no scenario, for a `.gitea/workflows/molecule.yml` diff of only comments
|
||||
(outside `run:` scripts) or image pins the scenarios that name a changed `MOLECULE_IMAGE*` pin
|
||||
(every scenario for `CI_IMAGE`, or when a shared molecule file names the pin), and every
|
||||
scenario for any other file. *Why:* a full run takes
|
||||
changed role with no scenario, and every scenario for any other file. *Why:* a full run takes
|
||||
the single runner slot for a long time. *Held:* control: the selector and its tests.
|
||||
- **A role named in an include, import, play `roles:` entry or meta dependency is written out in
|
||||
full**, never bare or templated. *Why:* the selector finds dependent roles by their FQCN.
|
||||
|
||||
@@ -28,7 +28,7 @@ jobs:
|
||||
timeout-minutes: 30
|
||||
# The ci image (images/ci, built by image.yml): tag for the release, digest enforced.
|
||||
container:
|
||||
image: git.rkdr.net/mortis/ci:0.2.46@sha256:a03015cc2177bdd6ef7f348f245a89f361893c7c64edc1264d9f9c1387d9defc
|
||||
image: git.rkdr.net/mortis/ci:0.2.48@sha256:d1c6653255abf366462c0265d9372626d5b59095084fe74ae95b9ebe7414007d
|
||||
env:
|
||||
PIP_DISABLE_PIP_VERSION_CHECK: "1"
|
||||
steps:
|
||||
|
||||
@@ -44,7 +44,7 @@ jobs:
|
||||
# The ci image (images/ci, built by image.yml), at the pin of lint.yml: tag for the
|
||||
# release, digest enforced. Only its /opt/venv Python (with PyYAML) is used here.
|
||||
container:
|
||||
image: git.rkdr.net/mortis/ci:0.2.46@sha256:a03015cc2177bdd6ef7f348f245a89f361893c7c64edc1264d9f9c1387d9defc
|
||||
image: git.rkdr.net/mortis/ci:0.2.48@sha256:d1c6653255abf366462c0265d9372626d5b59095084fe74ae95b9ebe7414007d
|
||||
steps:
|
||||
# The container has no Node, so JavaScript actions such as actions/checkout
|
||||
# cannot run; clone with git and the job token.
|
||||
|
||||
@@ -31,7 +31,7 @@ jobs:
|
||||
# The tag says which release, the digest is what is enforced (bump both together
|
||||
# when image.yml publishes a new version).
|
||||
container:
|
||||
image: git.rkdr.net/mortis/ci:0.2.46@sha256:a03015cc2177bdd6ef7f348f245a89f361893c7c64edc1264d9f9c1387d9defc
|
||||
image: git.rkdr.net/mortis/ci:0.2.48@sha256:d1c6653255abf366462c0265d9372626d5b59095084fe74ae95b9ebe7414007d
|
||||
env:
|
||||
PIP_DISABLE_PIP_VERSION_CHECK: "1"
|
||||
PRE_COMMIT_HOME: /opt/pre-commit
|
||||
|
||||
@@ -53,7 +53,7 @@ jobs:
|
||||
env:
|
||||
# The tools and collections molecule runs with: the image Lint and Build use.
|
||||
CI_IMAGE: >-
|
||||
git.rkdr.net/mortis/ci:0.2.46@sha256:a03015cc2177bdd6ef7f348f245a89f361893c7c64edc1264d9f9c1387d9defc
|
||||
git.rkdr.net/mortis/ci:0.2.48@sha256:d1c6653255abf366462c0265d9372626d5b59095084fe74ae95b9ebe7414007d
|
||||
# Used by the scenarios as `image: ${MOLECULE_IMAGE}`; set it the same way to run
|
||||
# one locally.
|
||||
MOLECULE_IMAGE: >-
|
||||
|
||||
@@ -12,6 +12,7 @@ and pin updates. The choice is hard to undo once every workflow pins an image.
|
||||
|
||||
- **We build our own images:** a `ci` image, and one Dockerfile per molecule image (one per Ubuntu
|
||||
release, and later the Debian 13 one).
|
||||
Molecule's controller image is added by [ADR 0003](0003-molecule-controller-image.md).
|
||||
- **The molecule images bake in everything except what a role installs itself.** The test
|
||||
fixtures a scenario's `prepare.yml` needs are baked in. Packages a role installs are still
|
||||
downloaded, because that install path is what the test exercises. A converge is not kept off
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
# 0003. Molecule runs in its own controller image, not the `ci` image
|
||||
|
||||
Status: accepted
|
||||
|
||||
## Context
|
||||
|
||||
[ADR 0002](0002-self-built-ci-and-molecule-images.md) built one `ci` image that bakes every CI
|
||||
tool, and Lint, Build and Molecule all pin it. A change to a tool only Lint uses (apm-cli,
|
||||
antsibull-changelog, a pre-commit hook environment) publishes a new `ci` version, and its pin
|
||||
pull request moves `CI_IMAGE` in `molecule.yml`. The scenario selector cannot tell what changed
|
||||
inside an image, so it runs every scenario. 9 of 18 `ci` pin pull requests over two weeks
|
||||
were Lint-only. Images are built only on push to `main`, so a bump and its pin never share a pull
|
||||
request.
|
||||
|
||||
## Decision
|
||||
|
||||
- **Molecule runs in a `molecule-controller` image**, separate from `ci`. It bakes only what
|
||||
Molecule needs: ansible-core, molecule, molecule-plugins, the Python packages of the Docker
|
||||
connection, and the collections of `requirements.yml` and
|
||||
`extensions/molecule/requirements.yml`.
|
||||
- **Its Python packages come from a requirements file and hash-pinned lock of its own.**
|
||||
- **`molecule.yml` pins it instead of `ci`**; Lint and Build keep `ci`.
|
||||
- **It follows ADR 0002 otherwise:** built by `image.yml`, versioned by CI, pinned by
|
||||
`<version>@sha256:<digest>`, moved by Renovate. This adds to ADR 0002's set of images; the
|
||||
rest of ADR 0002 stands.
|
||||
|
||||
## Reason
|
||||
|
||||
A `ci` pin pull request then touches only paths the selector ignores and runs no scenario. A
|
||||
`molecule-controller` pin pull request still runs every scenario, which is right: it changes
|
||||
Molecule's tools.
|
||||
|
||||
The cost: one more image and lock to maintain, its layers to estimate against the 100 MB limit,
|
||||
a hand-made first pin, and ansible-core pinned in two locks that must stay equal. A collection
|
||||
bump is an input of both images, so it publishes two versions and two pin pull requests.
|
||||
|
||||
The controller's requirements file and lock must not be on the selector's IGNORED list, so a
|
||||
bump of ansible-core or molecule there runs every scenario before it merges. Today
|
||||
`requirements-dev.txt` and `requirements-dev.lock` are on IGNORED, so such a bump selects no
|
||||
scenario unless it edits `meta/runtime.yml`; this decision does not change that list.
|
||||
|
||||
The implementation updates: `image.yml` (matrix, and its push `paths` unless the new files live
|
||||
under `images/`), `molecule.yml`,
|
||||
`scripts/run_molecule_in_ci_image.sh` (its pin comparison reads the `ci` image's checksums),
|
||||
`scripts/check_image_versions.py`, `scripts/check_bot_pr_diff.py` and
|
||||
`scripts/lock-requirements.sh` (they know only `requirements-dev.lock`), their tests, the
|
||||
`pip-compile` patterns in `renovate.json`, `images/AGENTS.md` (the consumer list, and "each
|
||||
molecule image is one Ubuntu release"), the Molecule rules in `.gitea/workflows/AGENTS.md`,
|
||||
`docs/images/` (a new page, and `ci.md`, which names Molecule as a consumer), the `ci`
|
||||
Dockerfile's description label, `docs/contributing/setup.md` if the clone's tools change, and the
|
||||
[Accepted risks](../../SECURITY.md#accepted-risks) entry "Pin bumps first behaviour-tested after
|
||||
they merge", which counts on the `ci` pin pull request running every scenario.
|
||||
|
||||
## Not done
|
||||
|
||||
- **The selector classifies the packages a lock change moves, to decide whether a `CI_IMAGE`
|
||||
bump matters:** a heuristic package list inside a script that judges pull requests.
|
||||
- **Status quo:** every Lint-only tool change keeps costing a full Molecule run.
|
||||
- **Grouping pin pull requests only:** adopted separately; it lowers the number of full runs
|
||||
but not the cause.
|
||||
@@ -15,10 +15,23 @@ trailers, are in [ai-assistance.md](ai-assistance.md).
|
||||
*Reason:* every change reaches `main` through the Lint and Build checks and a reviewer.
|
||||
*Held by:* control: branch protection on `main`.
|
||||
- **Do not push to someone else's branch or to a bot's branch; put your change in a pull request of
|
||||
your own.** Updating a branch from `main` with Gitea's update button is allowed.
|
||||
your own.** Updating a branch from `main` with Gitea's update button is allowed under the next
|
||||
two rules.
|
||||
*Reason:* a push changes a head its author already reviewed or scheduled to merge, and a hand-made
|
||||
commit on a `renovate/` branch makes Renovate stop rebasing it.
|
||||
*Held by:* aspirational.
|
||||
- **Update a pull request's branch from `main` only when it is next to merge: reviewed, green on its
|
||||
previous head, and the only branch being updated. After updating your own pull request, give it a
|
||||
scheduled merge; merge anyone else's as [reviewing.md](reviewing.md) says.**
|
||||
*Reason:* `main` blocks an outdated branch, so every update re-runs Lint, Build and Molecule, and
|
||||
a new head cancels the run in progress; an update made while another pull request merges first is
|
||||
wasted.
|
||||
*Held by:* aspirational.
|
||||
- **Never press the update button on a `renovate/` branch. When a Renovate pull request is next to
|
||||
merge and behind `main`, tick the rebase/retry checkbox in its description; Renovate rebases it at
|
||||
its next run.**
|
||||
*Reason:* the update button adds a hand-made commit, and Renovate stops rebasing that branch.
|
||||
*Held by:* aspirational.
|
||||
- **File an issue or open a pull request with the headings of the matching template in `.gitea/`,
|
||||
also when you file through the API, `tea` or an MCP server.**
|
||||
*Reason:* those routes skip the templates, and an agent's built-in body leaves out what review needs.
|
||||
|
||||
+48
-9
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
|
||||
"description": "Run by .gitea/workflows/renovate.yml on this repository's own runner. Policy: automerge minor and patch, majors by hand. Every bot pull request must pass scripts/check_bot_pr_diff.py (lint workflow), which allows only version, tag, digest and pin lines. Image versions are assigned by the Images workflow when an image's inputs change, so a bot pull request needs no version edit.",
|
||||
"description": "Run by .gitea/workflows/renovate.yml on this repository's own runner. Policy: automerge minor and patch, majors by hand. Every bot pull request must pass scripts/check_bot_pr_diff.py (lint workflow), which allows only version, tag, digest and pin lines. Image versions are assigned by the Images workflow when an image's inputs change, so a bot pull request needs no version edit. Updates open on Mondays (UTC), so any Monday run can act; the own image pins and vulnerability fixes found on osv.dev open at any time. The weekly window and the groups bound the volume, so there is no hourly pull request limit. Vulnerability fixes skip the release-age wait, so they are never automerged: a person checks a fix that had no time to be pulled as a compromised release. Base-image bumps are manual: every Dockerfile is FROM ubuntu, grouped with the job containers.",
|
||||
"extends": [
|
||||
"config:recommended",
|
||||
":enablePreCommit"
|
||||
@@ -19,7 +19,7 @@
|
||||
],
|
||||
"automerge": true,
|
||||
"automergeType": "pr",
|
||||
"prHourlyLimit": 5,
|
||||
"prHourlyLimit": 0,
|
||||
"minimumReleaseAge": "3 days",
|
||||
"minimumReleaseAgeBehaviour": "timestamp-optional",
|
||||
"timezone": "UTC",
|
||||
@@ -90,7 +90,7 @@
|
||||
],
|
||||
"packageRules": [
|
||||
{
|
||||
"description": "Dockerfile base-image tag and digest bumps (images/*/Dockerfile) MAY automerge. Kamino is the untrusted side and the bump pull request's own CI exercises the new image before the merge. Placed first so the major-version rule below still turns automerge off. The merge publishes a new image version.",
|
||||
"description": "Dockerfile base-image tag and digest bumps (images/*/Dockerfile) MAY automerge. Kamino is the untrusted side and the bump pull request's own CI exercises the new image before the merge. Placed first so the major-version rule below still turns automerge off. The merge publishes a new image version. Today every Dockerfile is FROM ubuntu, whose bumps join the manual ubuntu base images group below; this rule is the safety net for a future base image of another kind.",
|
||||
"matchManagers": [
|
||||
"dockerfile"
|
||||
],
|
||||
@@ -145,12 +145,18 @@
|
||||
"allowedVersions": "<=26.10.1"
|
||||
},
|
||||
{
|
||||
"description": "The job containers of image.yml (matrix job_image, ubuntu by digest) hold the org registry push credential while the image job runs: never automerged, and kept in their own branch so the Dockerfile base-image bumps are not held back with them.",
|
||||
"description": "The job containers of image.yml (matrix job_image, ubuntu by digest) hold the org registry push credential while the image job runs: never automerged. Their ubuntu bumps share one branch with the Dockerfile FROM bumps (ubuntu base images rule below), so that pull request is manual too: a group automerges only if every update in it does.",
|
||||
"matchFileNames": [
|
||||
".gitea/workflows/image.yml"
|
||||
],
|
||||
"automerge": false,
|
||||
"additionalBranchPrefix": "job-container-"
|
||||
"automerge": false
|
||||
},
|
||||
{
|
||||
"description": "The Dockerfile FROM digests and the image.yml job_image digests of one Ubuntu update move in one pull request, so the release pair stays in step and one Images run covers both.",
|
||||
"matchPackageNames": [
|
||||
"ubuntu"
|
||||
],
|
||||
"groupName": "ubuntu base images"
|
||||
},
|
||||
{
|
||||
"description": "Safety net only: kaniko is pinned by layer digests in image.yml and no Renovate manager reads them, so it is updated by hand. If a manager ever starts to read it, its bumps are not automerged.",
|
||||
@@ -160,11 +166,15 @@
|
||||
"automerge": false
|
||||
},
|
||||
{
|
||||
"description": "Pin follow-up for our own images (git.rkdr.net/mortis/*): moves the image:<version>@sha256:<digest> pins of lint.yml, build.yml, molecule.yml and gitea-release-key.yml to the newest published version and its digest, and automerges. The Images workflow's completion starts a Renovate run, so this pull request opens minutes after a new version is pushed. The pull request's own Lint and Build run in the new image before the merge, and scripts/check_bot_pr_diff.py allows only these pin lines. The registry lists tags and digests anonymously, so no hostRules are needed. A major version stays manual (rule above).",
|
||||
"description": "Pin follow-up for our own images (git.rkdr.net/mortis/*): moves the image:<version>@sha256:<digest> pins of lint.yml, build.yml, molecule.yml and gitea-release-key.yml to the newest published version and its digest, and automerges. The Images workflow's completion starts a Renovate run, so this pull request opens minutes after a new version is pushed. The pull request's own Lint and Build run in the new image before the merge, and scripts/check_bot_pr_diff.py allows only these pin lines. The registry lists tags and digests anonymously, so no hostRules are needed. A major version stays manual (rule above). One pull request moves every image an Images run published (ci and both molecule images), so one Molecule run tests them together. Exempt from the weekly schedule, so the pins on main catch up with a new image within minutes.",
|
||||
"matchPackageNames": [
|
||||
"git.rkdr.net/mortis/**"
|
||||
],
|
||||
"automerge": true
|
||||
"automerge": true,
|
||||
"groupName": "own CI images",
|
||||
"schedule": [
|
||||
"at any time"
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "Look the pre-commit hook repositories up with git ls-remote (git-tags) instead of the GitHub API. This run has no GitHub token, and the github-tags datasource then either skips every hook (skipReason github-token-required, dry run 3880) or is refused at once with 403 rate limit (githubTokenWarn off, local run). git-tags needs no API and no credential, and it uses the dereferenced hash of an annotated tag, so the new rev is the commit, as pre-commit needs. The `# frozen:` form is kept by the manager's own replace template. It works only together with RENOVATE_GITHUB_TOKEN_WARN=false in renovate.yml: the token check runs after extraction and skips every github-tags dependency before a package rule can change its datasource (local run, Renovate 44.161.0). git-tags has no release timestamps, so minimumReleaseAge cannot delay a hook bump: hook bumps are never automerged, a person reviews each one.",
|
||||
@@ -177,16 +187,45 @@
|
||||
"overrideDatasource": "git-tags",
|
||||
"overridePackageName": "https://github.com/{{{depName}}}",
|
||||
"automerge": false
|
||||
},
|
||||
{
|
||||
"description": "Lint and build tooling in one weekly pull request across requirements-dev.lock and the ci image's uv pin, so one ci image build instead of one per tool.",
|
||||
"matchDatasources": [
|
||||
"pypi"
|
||||
],
|
||||
"matchPackageNames": [
|
||||
"apm-cli",
|
||||
"antsibull-changelog",
|
||||
"galaxy-importer",
|
||||
"reuse",
|
||||
"pre-commit",
|
||||
"uv"
|
||||
],
|
||||
"groupName": "lint tooling"
|
||||
},
|
||||
{
|
||||
"description": "The pre-commit hooks in one weekly pull request; never automerged (rule above).",
|
||||
"matchManagers": [
|
||||
"pre-commit"
|
||||
],
|
||||
"groupName": "pre-commit hooks"
|
||||
}
|
||||
],
|
||||
"lockFileMaintenance": {
|
||||
"enabled": true,
|
||||
"schedule": [
|
||||
"before 6am on monday"
|
||||
"on monday"
|
||||
],
|
||||
"automerge": false,
|
||||
"labels": [
|
||||
"lock-file-maintenance"
|
||||
]
|
||||
},
|
||||
"schedule": [
|
||||
"on monday"
|
||||
],
|
||||
"osvVulnerabilityAlerts": true,
|
||||
"vulnerabilityAlerts": {
|
||||
"automerge": false
|
||||
}
|
||||
}
|
||||
@@ -18,11 +18,6 @@ Only a pull request is narrowed, and only when <base-ref> is given and EVENT_NAM
|
||||
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.<other>`
|
||||
@@ -55,7 +50,6 @@ control characters in paths escaped so a crafted file name cannot inject a log c
|
||||
"""
|
||||
|
||||
import fnmatch
|
||||
import glob
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
@@ -117,21 +111,6 @@ IGNORED = (
|
||||
)
|
||||
|
||||
|
||||
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(
|
||||
@@ -208,134 +187,20 @@ def with_users(roles, used_by):
|
||||
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("<pin>")
|
||||
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):
|
||||
def select(all_scenarios, changed, root="."):
|
||||
"""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])
|
||||
@@ -354,9 +219,7 @@ def select(all_scenarios, changed, root=".", pins=None):
|
||||
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)
|
||||
if s in extensions or (s.startswith("roles/") and s.split("/")[1] in roles)
|
||||
]
|
||||
covered = {s.split("/")[1] for s in chosen if s.startswith("roles/")}
|
||||
bare = sorted(
|
||||
@@ -367,7 +230,23 @@ def select(all_scenarios, changed, root=".", pins=None):
|
||||
"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)
|
||||
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))
|
||||
)
|
||||
reason = "; ".join(notes) or "no change that a scenario reads"
|
||||
return chosen, reason
|
||||
|
||||
|
||||
def changed_paths(base_ref):
|
||||
@@ -388,23 +267,6 @@ def changed_paths(base_ref):
|
||||
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:
|
||||
@@ -432,8 +294,7 @@ def main(argv, environ=None):
|
||||
chosen = scenarios
|
||||
else:
|
||||
try:
|
||||
pins = workflow_pins(base_ref, changed)
|
||||
chosen, reason = select(scenarios, changed, pins=pins)
|
||||
chosen, reason = select(scenarios, changed)
|
||||
except ValueError as exc:
|
||||
print(f"::error::{exc}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
@@ -452,41 +452,6 @@ class MainTest(unittest.TestCase):
|
||||
finally:
|
||||
os.chdir(cwd)
|
||||
|
||||
IMG = "git.rkdr.net/mortis/molecule-ubuntu2604:0.1.1@sha256:" + "a" * 64
|
||||
WORKFLOW_BASE = (
|
||||
f"env:\n # a comment\n MOLECULE_IMAGE_2604: >-\n {IMG}\nrun: x\n"
|
||||
)
|
||||
|
||||
def run_workflow_topic(self, text):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
pathlib.Path(root, ".gitea/workflows").mkdir(parents=True)
|
||||
pathlib.Path(root, sel.WORKFLOW).write_text(self.WORKFLOW_BASE)
|
||||
self.topic_repo(root, {sel.WORKFLOW: text})
|
||||
cwd = os.getcwd()
|
||||
os.chdir(root)
|
||||
try:
|
||||
return self.run_main(["main"], {"EVENT_NAME": "pull_request"})
|
||||
finally:
|
||||
os.chdir(cwd)
|
||||
|
||||
def test_a_comment_only_change_selects_nothing(self):
|
||||
code, out, _err = self.run_workflow_topic(
|
||||
self.WORKFLOW_BASE.replace("a comment", "other")
|
||||
)
|
||||
self.assertEqual((code, out), (0, []))
|
||||
|
||||
def test_a_pin_change_selects_by_image_and_another_change_everything(self):
|
||||
code, out, err = self.run_workflow_topic(
|
||||
self.WORKFLOW_BASE.replace(self.IMG, self.IMG.replace("0.1.1", "0.1.2"))
|
||||
)
|
||||
# make_repo's scenarios name no image, so the 2604 pin reaches none of them
|
||||
self.assertEqual((code, out), (0, []))
|
||||
self.assertIn("image pins changed: MOLECULE_IMAGE_2604", err)
|
||||
code, out, _err = self.run_workflow_topic(
|
||||
self.WORKFLOW_BASE.replace("run: x", "run: y")
|
||||
)
|
||||
self.assertEqual((code, len(out)), (0, 3))
|
||||
|
||||
def test_empty_base_ref_argument_runs_all(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
self.make_repo(root)
|
||||
@@ -644,202 +609,5 @@ class MainTest(unittest.TestCase):
|
||||
self.assertTrue(all((REPO / d / "molecule.yml").is_file() for d in found))
|
||||
|
||||
|
||||
class WorkflowPinsTest(unittest.TestCase):
|
||||
WORKFLOW = (REPO / sel.WORKFLOW).read_text()
|
||||
|
||||
def edited(self, old, new):
|
||||
self.assertIn(old, self.WORKFLOW)
|
||||
return sel.pin_changes(self.WORKFLOW, self.WORKFLOW.replace(old, new, 1))
|
||||
|
||||
def pin(self, key):
|
||||
lines = self.WORKFLOW.splitlines()
|
||||
return lines[lines.index(f" {key}: >-") + 1].strip()
|
||||
|
||||
def bumped(self, key):
|
||||
"""The pin of `key` at another digest, as Renovate would write it."""
|
||||
return self.pin(key).split("@sha256:")[0] + "@sha256:" + "0" * 64
|
||||
|
||||
def test_the_workflow_has_each_pin_where_the_selector_looks(self):
|
||||
for key in ("CI_IMAGE", "MOLECULE_IMAGE", "MOLECULE_IMAGE_2604"):
|
||||
self.assertEqual(self.edited(self.pin(key), self.bumped(key)), {key}, key)
|
||||
|
||||
def test_comments_and_blank_lines_change_nothing(self):
|
||||
self.assertEqual(self.edited("# Behavioural tests", "# Other words"), set())
|
||||
self.assertEqual(self.edited("\njobs:\n", "\n\n\njobs:\n"), set())
|
||||
self.assertEqual(
|
||||
self.edited(
|
||||
" # Used by the scenarios", " # Read by the scenarios"
|
||||
),
|
||||
set(),
|
||||
)
|
||||
|
||||
def test_a_hash_line_inside_a_block_scalar_is_content(self):
|
||||
# In a `run: |` script a `#` line may be heredoc content, not a comment.
|
||||
self.assertIsNone(
|
||||
self.edited(" # Assigned first", " # Set first")
|
||||
)
|
||||
|
||||
def test_two_pins(self):
|
||||
changed = sel.pin_changes(
|
||||
self.WORKFLOW,
|
||||
self.WORKFLOW.replace(
|
||||
self.pin("MOLECULE_IMAGE"), self.bumped("MOLECULE_IMAGE")
|
||||
).replace(
|
||||
self.pin("MOLECULE_IMAGE_2604"), self.bumped("MOLECULE_IMAGE_2604")
|
||||
),
|
||||
)
|
||||
self.assertEqual(changed, {"MOLECULE_IMAGE", "MOLECULE_IMAGE_2604"})
|
||||
|
||||
def test_a_pin_value_is_the_next_line_in_renovates_shape(self):
|
||||
value = self.pin("MOLECULE_IMAGE")
|
||||
indent = " " * 8
|
||||
for new in (
|
||||
# YAML folds the comment into the value: '# x git.rkdr.net/...'
|
||||
f"{indent}# x\n{indent}{value}",
|
||||
f"\n{indent}{value}",
|
||||
f"{indent}{value}\n{indent}more",
|
||||
f"{indent}other:1",
|
||||
value,
|
||||
):
|
||||
self.assertIsNone(self.edited(f"{indent}{value}", new), new)
|
||||
|
||||
def test_a_value_line_replaced_by_an_env_key_is_not_narrowed(self):
|
||||
self.assertIsNone(
|
||||
self.edited(
|
||||
" " + self.pin("MOLECULE_IMAGE_2604"),
|
||||
" MOLECULE_IMAGE: other:1",
|
||||
)
|
||||
)
|
||||
|
||||
def test_any_other_change_is_not_narrowed(self):
|
||||
for old, new in (
|
||||
("timeout-minutes: 90", "timeout-minutes: 60"),
|
||||
(" MOLECULE_IMAGE_2604: >-", " MOLECULE_IMAGE_2605: >-"),
|
||||
(" MOLECULE_IMAGE: >-", " MOLECULE_IMAGE: >"),
|
||||
("-e MOLECULE_IMAGE -e", "-e"),
|
||||
(
|
||||
" # Every scenario, nightly",
|
||||
" schedule: []\n # Every scenario, nightly",
|
||||
),
|
||||
("--init", "--init # not a comment line"),
|
||||
):
|
||||
self.assertIsNone(self.edited(old, new), old)
|
||||
|
||||
def test_a_pin_and_another_change_is_not_narrowed(self):
|
||||
text = self.WORKFLOW.replace(
|
||||
self.pin("MOLECULE_IMAGE_2604"), self.bumped("MOLECULE_IMAGE_2604")
|
||||
).replace("timeout-minutes: 90", "timeout-minutes: 60")
|
||||
self.assertIsNone(sel.pin_changes(self.WORKFLOW, text))
|
||||
|
||||
|
||||
SCENARIO_IMAGES = {
|
||||
"extensions/molecule/image-smoke": "image: ${MOLECULE_IMAGE}",
|
||||
"extensions/molecule/image-smoke-2604": "image: ${MOLECULE_IMAGE_2604}",
|
||||
"roles/docker/molecule/default": "${MOLECULE_IMAGE} ${MOLECULE_IMAGE_2604}",
|
||||
"roles/fail2ban/molecule/default": "image: ${MOLECULE_IMAGE}",
|
||||
"roles/system_baseline/molecule/default": "image: ubuntu:24.04",
|
||||
}
|
||||
|
||||
|
||||
class SelectByPinTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(tmp.cleanup)
|
||||
self.root = tmp.name
|
||||
for scenario, text in SCENARIO_IMAGES.items():
|
||||
pathlib.Path(self.root, scenario).mkdir(parents=True)
|
||||
pathlib.Path(self.root, scenario, "molecule.yml").write_text(text)
|
||||
|
||||
def select(self, pins, changed=(sel.WORKFLOW,)):
|
||||
return sel.select(ALL, list(changed), self.root, pins)[0]
|
||||
|
||||
def test_a_2604_pin_selects_the_scenarios_naming_it(self):
|
||||
self.assertEqual(
|
||||
self.select({"MOLECULE_IMAGE_2604"}),
|
||||
["extensions/molecule/image-smoke-2604", "roles/docker/molecule/default"],
|
||||
)
|
||||
|
||||
def test_a_2404_pin_does_not_match_the_2604_name(self):
|
||||
self.assertEqual(
|
||||
self.select({"MOLECULE_IMAGE"}),
|
||||
[
|
||||
"extensions/molecule/image-smoke",
|
||||
"roles/docker/molecule/default",
|
||||
"roles/fail2ban/molecule/default",
|
||||
],
|
||||
)
|
||||
|
||||
def test_comments_only_select_nothing(self):
|
||||
self.assertEqual(self.select(set()), [])
|
||||
|
||||
def test_the_ci_image_or_no_analysis_selects_everything(self):
|
||||
self.assertEqual(self.select({"CI_IMAGE", "MOLECULE_IMAGE"}), ALL)
|
||||
self.assertEqual(self.select(None), ALL)
|
||||
|
||||
def test_pins_do_not_narrow_another_file(self):
|
||||
self.assertEqual(self.select(set(), [sel.WORKFLOW, "meta/runtime.yml"]), ALL)
|
||||
self.assertEqual(self.select(set(), ["meta/runtime.yml"]), ALL)
|
||||
|
||||
def test_a_shared_file_naming_the_pin_selects_everything(self):
|
||||
for shared in (
|
||||
".config/molecule/config.yml",
|
||||
"extensions/molecule/shared/vars.yml",
|
||||
"roles/docker/molecule/resources/prepare.yml",
|
||||
):
|
||||
path = pathlib.Path(self.root, shared)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text("image: ${MOLECULE_IMAGE_2604}")
|
||||
try:
|
||||
self.assertEqual(self.select({"MOLECULE_IMAGE_2604"}), ALL, shared)
|
||||
finally:
|
||||
path.unlink()
|
||||
|
||||
def test_a_shared_file_not_naming_the_pin_narrows(self):
|
||||
path = pathlib.Path(self.root, ".config/molecule/config.yml")
|
||||
path.parent.mkdir(parents=True)
|
||||
path.write_text("image: ${MOLECULE_IMAGE}")
|
||||
self.assertEqual(
|
||||
self.select({"MOLECULE_IMAGE_2604"}),
|
||||
["extensions/molecule/image-smoke-2604", "roles/docker/molecule/default"],
|
||||
)
|
||||
|
||||
def test_an_unreadable_scenario_selects_everything(self):
|
||||
shutil.rmtree(pathlib.Path(self.root, "roles/fail2ban/molecule/default"))
|
||||
self.assertEqual(self.select({"MOLECULE_IMAGE_2604"}), ALL)
|
||||
|
||||
def test_a_symlink_selects_everything(self):
|
||||
# os.walk does not follow a directory symlink, so its target would go unread.
|
||||
target = pathlib.Path(self.root, "elsewhere")
|
||||
target.mkdir()
|
||||
(target / "vars.yml").write_text("image: ${MOLECULE_IMAGE_2604}")
|
||||
for link in (
|
||||
"roles/fail2ban/molecule/default/shared",
|
||||
"extensions/molecule/shared",
|
||||
):
|
||||
path = pathlib.Path(self.root, link)
|
||||
path.symlink_to(target, target_is_directory=True)
|
||||
try:
|
||||
self.assertEqual(self.select({"MOLECULE_IMAGE_2604"}), ALL, link)
|
||||
finally:
|
||||
path.unlink()
|
||||
self.assertEqual(
|
||||
self.select({"MOLECULE_IMAGE_2604"}),
|
||||
["extensions/molecule/image-smoke-2604", "roles/docker/molecule/default"],
|
||||
)
|
||||
|
||||
def test_pins_combine_with_a_role(self):
|
||||
self.assertEqual(
|
||||
self.select(
|
||||
{"MOLECULE_IMAGE_2604"},
|
||||
[sel.WORKFLOW, "roles/system_baseline/tasks/main.yml"],
|
||||
),
|
||||
[
|
||||
"extensions/molecule/image-smoke-2604",
|
||||
"roles/docker/molecule/default",
|
||||
"roles/system_baseline/molecule/default",
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user