diff --git a/.gitea/PULL_REQUEST_TEMPLATE.md b/.gitea/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..ac51ad1 --- /dev/null +++ b/.gitea/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,26 @@ +## Vraag + + +## Wat is er gedaan + +- + +## Zo test je het + +- [ ] + +## Zelf getest + +- + +## Tijd en tokens + + +## Onderhoud + + +## Met de hand te doen + + +## Vervolgstappen + diff --git a/.gitea/scripts/auto_merge.py b/.gitea/scripts/auto_merge.py new file mode 100755 index 0000000..0c31961 --- /dev/null +++ b/.gitea/scripts/auto_merge.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 +"""Turns on auto-merge for a pull request to a release branch (`release/vX.Y.Z`). + +Run by the `release-automerge` job whenever such a pull request is opened or updated. Gitea then +merges it by itself once the required check is green, so features flow into the release branch +without anyone pressing the button. A pull request to anything else is left alone: `production` +is merged by hand. + +Environment: GT_URL, GT_OWNER, GT_REPO, GT_TOKEN (a token that may edit pull requests), +PULL_REQUEST_NUMBER. Optional: AUTO_MERGE_PREFIX (default "release/"), MERGE_STYLE (default "merge"). +Standard library only. +""" + +import json +import os +import sys +import urllib.error +import urllib.request + +URL = os.environ.get("GT_URL", "").rstrip("/") +OWNER = os.environ.get("GT_OWNER", "") +REPO = os.environ.get("GT_REPO", "") +TOKEN = os.environ.get("GT_TOKEN", "") +NUMBER = os.environ.get("PULL_REQUEST_NUMBER", "").lstrip("#") +PREFIX = os.environ.get("AUTO_MERGE_PREFIX") or "release/" +MERGE_STYLE = os.environ.get("MERGE_STYLE") or "merge" + +ALREADY_ON = object() + + +def api(method, path, body=None): + request = urllib.request.Request( + f"{URL}/api/v1/repos/{OWNER}/{REPO}/{path}", + data=json.dumps(body).encode() if body is not None else None, + method=method, + headers={"Authorization": f"token {TOKEN}", "Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=30) as response: + text = response.read().decode() + except urllib.error.HTTPError as e: + detail = e.read().decode() + # A second push runs this job again while auto-merge is still on: that is what was wanted. + if e.code == 409 and "already scheduled to auto merge" in detail: + return ALREADY_ON + sys.exit(f"Gitea API {method} {path} failed: {e.code} {detail}") + return json.loads(text) if text else None + + +def main(): + if not (URL and OWNER and REPO and TOKEN and NUMBER.isdigit()): + sys.exit("GT_URL, GT_OWNER, GT_REPO, GT_TOKEN and PULL_REQUEST_NUMBER are required.") + + pull = api("GET", f"pulls/{NUMBER}") or {} + base_ref = (pull.get("base") or {}).get("ref", "") + + if not base_ref.startswith(PREFIX): + print(f"Pull request #{NUMBER} targets {base_ref}, not {PREFIX}*: left alone.") + return + if pull.get("state") != "open" or pull.get("merged"): + print(f"Pull request #{NUMBER} is not open: nothing to do.") + return + + answer = api("POST", f"pulls/{NUMBER}/merge", { + "do": MERGE_STYLE, + "merge_when_checks_succeed": True, + "delete_branch_after_merge": False, + }) + if answer is ALREADY_ON: + print(f"Auto-merge was already on for pull request #{NUMBER}.") + return + print(f"Auto-merge is on for pull request #{NUMBER}: it merges once the required check is green.") + + +if __name__ == "__main__": + main() diff --git a/.gitea/scripts/check_flow.py b/.gitea/scripts/check_flow.py new file mode 100755 index 0000000..cb424bd --- /dev/null +++ b/.gitea/scripts/check_flow.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python3 +"""PR CI: does this pull request follow the development cycle? + + develop -> feature/*, fix/*, ... -> release/vX.Y.Z -> production + (collects features) (release: tag + Packagist) + production -> develop (the sync after a release, by the pipeline) + +Pull requests go to a release branch or to production, never to develop. + - to `release/vX.Y.Z`: the release must not be out yet (its version is above the latest tag), + and the pull request does not come from production, develop or another release branch. + - to `production`: only from `release/vX.Y.Z`, with a version above the latest tag, a section + for it in CHANGELOG.md, and no "version" in composer.json (Packagist reads the tag). + +Environment: BASE_REF, HEAD_REF. Run in a checkout with the tags (fetch-depth 0). +Standard library + git only. +""" + +import json +import os +import subprocess +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import semver # noqa: E402 + + +def tags(): + result = subprocess.run(["git", "tag", "--list", "v*"], capture_output=True, text=True) + return result.stdout.split() + + +def problems(base, head, existing_tags, changelog, composer): + found = [] + newest = semver.latest(existing_tags) + + if base == "production": + version = semver.release_version(head) + if version is None: + return [f"A pull request to production comes from a branch named release/vX.Y.Z, not from {head or '?'}."] + found += above_latest(version, newest) + if changelog is None or semver.changelog_section(changelog, version) is None: + found.append(f"CHANGELOG.md has no section '## v{semver.text(version)}' for this release.") + if isinstance(composer, dict) and "version" in composer: + found.append("composer.json must not have a \"version\": Packagist takes the version from the tag.") + return found + + if base.startswith("release/"): + version = semver.release_version(base) + if version is None: + return [f"{base} is not a release branch name: use release/vX.Y.Z."] + found += above_latest(version, newest, "That release is already out: start the next one.") + if head in ("production", "develop") or head.startswith("release/"): + found.append(f"A release branch takes features (feature/*, fix/*), not {head}.") + return found + + return [f"Pull requests go to release/vX.Y.Z or to production, not to {base or '?'}: develop only takes the sync after a release."] + + +def above_latest(version, newest, hint="The version of a release must be above the latest tag."): + if newest is not None and version <= newest: + return [f"v{semver.text(version)} is not above the latest tag v{semver.text(newest)}. {hint}"] + return [] + + +def main(): + base = os.environ.get("BASE_REF", "").strip() + head = os.environ.get("HEAD_REF", "").strip() + + changelog = open("CHANGELOG.md", encoding="utf-8").read() if os.path.exists("CHANGELOG.md") else None + try: + composer = json.load(open("composer.json", encoding="utf-8")) + except (OSError, ValueError): + composer = None + + found = problems(base, head, tags(), changelog, composer) + for line in found: + print(f"::error::{line}") + if found: + return 1 + print(f"{head} -> {base}: follows the development cycle.") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.gitea/scripts/check_tokens.py b/.gitea/scripts/check_tokens.py new file mode 100755 index 0000000..ebea658 --- /dev/null +++ b/.gitea/scripts/check_tokens.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python3 +"""PR CI: a pull request must add its row to TOKENS.md. + +TOKENS.md holds one row per piece of work: the tokens of the AI model that +went into it and the hours that were worked on it. This check compares the +rows of the pull request with the rows on the branch it goes to, and fails +when the pull request brings no new row. The new rows are printed, so every +pull request shows in its log what it cost. + +Exempt, because nobody worked on them: the release pull request of the +pipeline (release/*), the dependency updates (renovate/*), and a pull +request that only carries one long-lived branch into another (production +into staging, staging into production, develop). + +Environment (set by the workflow): + BASE_REF the branch the pull request goes to + HEAD_REF the branch the pull request comes from + PR_AUTHOR who opened it + +Standard library only. +""" + +import os +import subprocess +import sys + +LEDGER = "TOKENS.md" +EXEMPT_PREFIXES = ("release/", "renovate/") +EXEMPT_BRANCHES = ("production", "staging", "develop") +EXEMPT_AUTHORS = ("deploy-bot", "renovate-bot") + + +def rows(text): + """The rows of the table: the lines that start with a date.""" + return [line.strip() for line in text.splitlines() if line.startswith("| 20")] + + +def git(*args): + return subprocess.run(["git", *args], capture_output=True, text=True) + + +def main(): + base = os.environ.get("BASE_REF", "").strip() + head = os.environ.get("HEAD_REF", "").strip() + author = os.environ.get("PR_AUTHOR", "").strip() + + if head.startswith(EXEMPT_PREFIXES) or head in EXEMPT_BRANCHES or author in EXEMPT_AUTHORS: + print(f"No row needed: {head or 'this pull request'} by {author or 'unknown'} is not a piece of work.") + return 0 + + if not base: + print("BASE_REF is not set: cannot tell which branch this pull request goes to.") + return 1 + + if not os.path.exists(LEDGER): + print(f"{LEDGER} is missing. See AGENTS.md, 'Token usage and hours'.") + return 1 + + fetch = git("fetch", "--quiet", "--no-tags", "--depth=1", "origin", base) + if fetch.returncode != 0: + print(f"Could not fetch {base}: {fetch.stderr.strip()}") + return 1 + + shown = git("show", f"FETCH_HEAD:{LEDGER}") + before = set(rows(shown.stdout)) if shown.returncode == 0 else set() + with open(LEDGER, encoding="utf-8") as handle: + new = [row for row in rows(handle.read()) if row not in before] + + if not new: + print(f"This pull request adds no row to {LEDGER}.") + print("Every pull request records what went into it: the tokens of the AI model and the hours.") + print("Add the row with dev/token-usage.py (see AGENTS.md, 'Token usage and hours') and push again.") + return 1 + + print(f"{len(new)} new row(s) in {LEDGER}:") + for row in new: + print(" " + row) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.gitea/scripts/install-trivy.sh b/.gitea/scripts/install-trivy.sh new file mode 100755 index 0000000..4823ab1 --- /dev/null +++ b/.gitea/scripts/install-trivy.sh @@ -0,0 +1,13 @@ +#!/bin/sh +# Installs Trivy at a fixed version, checked against a fixed checksum, so a changed download fails the +# job instead of running. To update: take the version and the checksum of the Linux-64bit tarball from +# https://github.com/aquasecurity/trivy/releases (the checksums file of that release). +set -eu + +VERSION=0.77.0 +SHA256=c9504e6ff8184b91e8e7266c84ad8538f76347f1e5488e07cb083855883cd9a6 + +curl -fsSL -o /tmp/trivy.tar.gz "https://github.com/aquasecurity/trivy/releases/download/v${VERSION}/trivy_${VERSION}_Linux-64bit.tar.gz" +echo "${SHA256} /tmp/trivy.tar.gz" | sha256sum -c - +tar -xzf /tmp/trivy.tar.gz -C /usr/local/bin trivy +trivy --version diff --git a/.gitea/scripts/packagist.py b/.gitea/scripts/packagist.py new file mode 100755 index 0000000..8c43c75 --- /dev/null +++ b/.gitea/scripts/packagist.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python3 +"""Tells Packagist that the package has a new version. + +Packagist reads the tags of the repository; this asks it to do that now, instead of waiting for its +own poll. The package must have been submitted on packagist.org once (by hand); until then, and +while PACKAGIST_USERNAME and PACKAGIST_TOKEN are not set, this only says so and succeeds. + +Environment: PACKAGIST_USERNAME, PACKAGIST_TOKEN (the API token of the Packagist account, a secret +of the repository), PACKAGE_URL (the public address of the repository). +The token goes in the request and never in the log. Standard library only. +""" + +import json +import os +import sys +import urllib.error +import urllib.parse +import urllib.request + +USER = os.environ.get("PACKAGIST_USERNAME", "").strip() +TOKEN = os.environ.get("PACKAGIST_TOKEN", "").strip() +PACKAGE_URL = os.environ.get("PACKAGE_URL", "").strip() + + +def main(): + if not (USER and TOKEN): + print("PACKAGIST_USERNAME / PACKAGIST_TOKEN are not set: Packagist was not told. " + "Set both as secrets of the repository once the package is submitted on packagist.org.") + return + if not PACKAGE_URL.startswith("https://"): + sys.exit("PACKAGE_URL must be the public https address of the repository.") + + query = urllib.parse.urlencode({"username": USER, "apiToken": TOKEN}) + request = urllib.request.Request( + f"https://packagist.org/api/update-package?{query}", + data=json.dumps({"repository": {"url": PACKAGE_URL}}).encode(), + method="POST", + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=30) as response: + print(f"Packagist answered {response.status}: it will read the new tag.") + except urllib.error.HTTPError as e: + # Never echo the request (it holds the token); the answer of Packagist says enough. + sys.exit(f"Packagist refused: {e.code} {e.read().decode()[:300]}") + + +if __name__ == "__main__": + main() diff --git a/.gitea/scripts/release.py b/.gitea/scripts/release.py new file mode 100755 index 0000000..3b05fcf --- /dev/null +++ b/.gitea/scripts/release.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python3 +"""Release step of the `Release` workflow: tag what was just merged into production. + +A push to production is a release when it is the merge of a `release/vX.Y.Z` pull request. This +finds that version (from the pull request Gitea knows for the commit, or from the merge message), +and makes the release `vX.Y.Z` on that commit, with the changelog section as its text. Gitea +makes the tag; Packagist picks the tag up in the next step. + +Runs again on the same commit without harm: a tag that is already there on that commit is fine. +A push that is not a release merge (a hotfix pushed by an admin, say) makes no release and says so. + +Environment: GT_URL, GT_OWNER, GT_REPO, GT_TOKEN (may create releases), COMMIT_HASH. +Standard library + git only. +""" + +import json +import os +import re +import subprocess +import sys +import urllib.error +import urllib.request + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import semver # noqa: E402 + +URL = os.environ.get("GT_URL", "").rstrip("/") +OWNER = os.environ.get("GT_OWNER", "") +REPO = os.environ.get("GT_REPO", "") +TOKEN = os.environ.get("GT_TOKEN", "") +COMMIT = os.environ.get("COMMIT_HASH", "").strip() + + +def api(method, path, body=None, allow=()): + request = urllib.request.Request( + f"{URL}/api/v1/repos/{OWNER}/{REPO}/{path}", + data=json.dumps(body).encode() if body is not None else None, + method=method, + headers={"Authorization": f"token {TOKEN}", "Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=30) as response: + text = response.read().decode() + except urllib.error.HTTPError as e: + if e.code in allow: + return None + sys.exit(f"Gitea API {method} {path} failed: {e.code} {e.read().decode()}") + return json.loads(text) if text else None + + +def release_branch_of(commit): + """The release branch whose pull request made this commit, or None.""" + pull = api("GET", f"commits/{commit}/pull", allow=(404,)) + head = ((pull or {}).get("head") or {}).get("ref", "") + if semver.release_version(head): + return head + + # Gitea's own merge message: "Merge pull request 'title' (#7) from release/v1.2.0 into production". + message = subprocess.run(["git", "log", "-1", "--pretty=%s", commit], capture_output=True, text=True).stdout + found = re.search(r"from (release/v\d+\.\d+\.\d+) into production", message) + return found.group(1) if found else None + + +def main(): + if not (URL and OWNER and REPO and TOKEN): + sys.exit("GT_URL, GT_OWNER, GT_REPO and GT_TOKEN are required.") + if not re.fullmatch(r"[0-9a-f]{40}", COMMIT): + sys.exit("COMMIT_HASH must be the full commit hash.") + + branch = release_branch_of(COMMIT) + if branch is None: + print(f"{COMMIT[:8]} is not the merge of a release/vX.Y.Z pull request: no release made.") + return + + version = semver.release_version(branch) + tag = f"v{semver.text(version)}" + + existing = api("GET", f"releases/tags/{tag}", allow=(404,)) + if existing: + print(f"{tag} already exists: nothing to do.") + return + + changelog = open("CHANGELOG.md", encoding="utf-8").read() if os.path.exists("CHANGELOG.md") else "" + notes = semver.changelog_section(changelog, version) + if notes is None: + sys.exit(f"CHANGELOG.md has no section for {tag}: the release pull request should have been stopped by PR CI.") + + api("POST", "releases", { + "tag_name": tag, + "target_commitish": COMMIT, + "name": tag, + "body": notes, + "draft": False, + "prerelease": False, + }) + print(f"Released {tag} on {COMMIT[:8]}.") + + +if __name__ == "__main__": + main() diff --git a/.gitea/scripts/semver.py b/.gitea/scripts/semver.py new file mode 100755 index 0000000..5224295 --- /dev/null +++ b/.gitea/scripts/semver.py @@ -0,0 +1,44 @@ +"""Version helpers shared by the release scripts. Standard library only.""" + +import re + +# A version is always three numbers: 1.4.0. The tag has a v in front (v1.4.0), the branch is release/v1.4.0. +VERSION = re.compile(r"(\d+)\.(\d+)\.(\d+)") +RELEASE_BRANCH = re.compile(r"release/v(\d+)\.(\d+)\.(\d+)") +TAG = re.compile(r"v(\d+)\.(\d+)\.(\d+)") + + +def release_version(branch): + """The version of a `release/vX.Y.Z` branch as a tuple, or None when it is not one.""" + match = RELEASE_BRANCH.fullmatch(branch or "") + return tuple(int(part) for part in match.groups()) if match else None + + +def tag_version(tag): + match = TAG.fullmatch(tag or "") + return tuple(int(part) for part in match.groups()) if match else None + + +def latest(tags): + """The highest version among the tags that are versions, or None.""" + versions = [version for version in (tag_version(tag) for tag in tags) if version] + return max(versions) if versions else None + + +def text(version): + return ".".join(str(part) for part in version) + + +def changelog_section(changelog, version): + """The body under `## vX.Y.Z` of the changelog, up to the next `## `; None when there is no such heading.""" + heading = re.compile(rf"^##\s+v?{re.escape(text(version))}(\s|$)") + lines = changelog.splitlines() + for index, line in enumerate(lines): + if heading.match(line): + body = [] + for following in lines[index + 1:]: + if following.startswith("## "): + break + body.append(following) + return "\n".join(body).strip() + return None diff --git a/.gitea/scripts/start_release.py b/.gitea/scripts/start_release.py new file mode 100755 index 0000000..ed91403 --- /dev/null +++ b/.gitea/scripts/start_release.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python3 +"""Starts a release: makes the branch release/vX.Y.Z from develop. + +Features are pull requests to that branch (they merge by themselves when CI is green). When the release +is ready, a pull request from it to production makes the release. + +Environment: GT_URL, GT_OWNER, GT_REPO, GT_TOKEN (may create branches), VERSION (1.4.0, or v1.4.0). +Standard library only. +""" + +import json +import os +import re +import sys +import urllib.error +import urllib.request + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import semver # noqa: E402 + +URL = os.environ.get("GT_URL", "").rstrip("/") +OWNER = os.environ.get("GT_OWNER", "") +REPO = os.environ.get("GT_REPO", "") +TOKEN = os.environ.get("GT_TOKEN", "") + + +def api(method, path, body=None, allow=()): + request = urllib.request.Request( + f"{URL}/api/v1/repos/{OWNER}/{REPO}/{path}", + data=json.dumps(body).encode() if body is not None else None, + method=method, + headers={"Authorization": f"token {TOKEN}", "Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=30) as response: + text = response.read().decode() + except urllib.error.HTTPError as e: + if e.code in allow: + return None + sys.exit(f"Gitea API {method} {path} failed: {e.code} {e.read().decode()}") + return json.loads(text) if text else None + + +def main(): + if not (URL and OWNER and REPO and TOKEN): + sys.exit("GT_URL, GT_OWNER, GT_REPO and GT_TOKEN are required.") + + given = os.environ.get("VERSION", "").strip().lstrip("v") + if not semver.VERSION.fullmatch(given): + sys.exit(f"'{given}' is not a version: use three numbers, like 1.4.0.") + version = tuple(int(part) for part in given.split(".")) + + tags = [tag["name"] for tag in api("GET", "tags?limit=50") or []] + newest = semver.latest(tags) + if newest is not None and version <= newest: + sys.exit(f"v{given} is not above the latest tag v{semver.text(newest)}.") + + name = f"release/v{given}" + if api("GET", f"branches/{name}", allow=(404,)): + sys.exit(f"{name} already exists.") + + api("POST", "branches", {"new_branch_name": name, "old_branch_name": "develop"}) + print(f"{name} made from develop. Make features as pull requests to it; when it is ready, open one to production.") + + +if __name__ == "__main__": + main() diff --git a/.gitea/scripts/sync_develop.py b/.gitea/scripts/sync_develop.py new file mode 100755 index 0000000..2fb72c8 --- /dev/null +++ b/.gitea/scripts/sync_develop.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python3 +"""Sync step of the `Release` workflow: merge production into develop. + +Runs after a release, so `develop` always contains what is live. Features are made from develop, so +it must be on the latest production before the next release is started. +`develop` takes direct pushes (only `production` and the release branches are protected), +so this is a plain merge and push: fast-forward when possible, otherwise a +merge commit `chore: sync production into develop`. + +A conflict fails the step on purpose. The release itself is done by then; the +red build is the signal that `develop` holds something production does not +and needs a merge by hand. + +Environment: GT_URL, GT_OWNER, GT_REPO, GT_TOKEN (an access token +that may push to develop), COMMIT_HASH (the commit this job released; defaults +to the tip of production). SYNC_REMOTE overrides the clone URL (local testing). + +Standard library + git only. +""" + +import json +import os +import re +import subprocess +import tempfile +import urllib.request + +URL = os.environ.get("GT_URL", "").rstrip("/") +OWNER = os.environ.get("GT_OWNER", "") +REPO = os.environ.get("GT_REPO", "") +TOKEN = os.environ.get("GT_TOKEN", "") +REMOTE = os.environ.get("SYNC_REMOTE", "") +MESSAGE = "chore: sync production into develop" + + +def git(repo, *args, check=True): + result = subprocess.run(["git", "-C", repo, *args], capture_output=True, text=True) + if check and result.returncode != 0: + raise SystemExit(f"git {' '.join(args[:2])} failed: {result.stderr.strip()}") + return result + + +def main(): + user = os.environ.get("GT_BOT_USER") or "sync" + remote = REMOTE + if not remote: + if not (URL and OWNER and REPO and TOKEN): + raise SystemExit("GT_URL, GT_OWNER, GT_REPO and GT_TOKEN are required") + remote = f"https://{user}:{TOKEN}@{URL.split('://', 1)[1]}/{OWNER}/{REPO}.git" + + repo = os.path.join(tempfile.mkdtemp(), "repo") + result = subprocess.run(["git", "clone", "--quiet", "--branch", "develop", remote, repo], + capture_output=True, text=True) + if result.returncode != 0: + raise SystemExit(f"Could not clone develop: {result.stderr.strip()}") + git(repo, "config", "user.name", user) + git(repo, "config", "user.email", f"{user}@iriks-it.nl") + + commit = os.environ.get("COMMIT_HASH", "").strip() + source = commit if re.fullmatch(r"[0-9a-f]{40}", commit) else "origin/production" + short = git(repo, "rev-parse", "--short", source).stdout.strip() + + if git(repo, "merge-base", "--is-ancestor", source, "HEAD", check=False).returncode == 0: + print(f"develop already contains production ({short}) — nothing to do.") + return + + merge = git(repo, "merge", "--no-edit", "-m", MESSAGE, source, check=False) + if merge.returncode != 0: + conflicts = git(repo, "diff", "--name-only", "--diff-filter=U", check=False).stdout.strip() + raise SystemExit( + f"production ({short}) does not merge cleanly into develop — merge it by hand.\n" + f"Conflicting files:\n{conflicts or merge.stdout.strip() or merge.stderr.strip()}" + ) + + push = git(repo, "push", "--quiet", "origin", "HEAD:refs/heads/develop", check=False) + if push.returncode != 0: + raise SystemExit(f"Could not push develop: {push.stderr.strip()}") + print(f"develop now contains production ({short}).") + + +if __name__ == "__main__": + main() diff --git a/.gitea/scripts/test_scripts.py b/.gitea/scripts/test_scripts.py new file mode 100644 index 0000000..94b3c86 --- /dev/null +++ b/.gitea/scripts/test_scripts.py @@ -0,0 +1,74 @@ +"""Tests of the release scripts: `python3 -m unittest discover -s .gitea/scripts` (run by the `flow` job).""" + +import os +import sys +import unittest + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import check_flow # noqa: E402 +import semver # noqa: E402 + +TAGS = ["v0.1.0", "v0.2.0", "v0.10.0", "not-a-version"] +CHANGELOG = "# Changelog\n\n## v0.11.0 - 2026-12-10\n\n- A feature\n- Another\n\n## v0.10.0 - 2026-12-01\n\n- Older\n" + + +class Versions(unittest.TestCase): + def test_release_branch(self): + self.assertEqual(semver.release_version("release/v1.2.3"), (1, 2, 3)) + for wrong in ("release/1.2.3", "release/v1.2", "feature/x", "release/v1.2.3-rc1", "", None): + self.assertIsNone(semver.release_version(wrong)) + + def test_latest_is_numeric_not_alphabetical(self): + self.assertEqual(semver.latest(TAGS), (0, 10, 0)) + self.assertIsNone(semver.latest(["x"])) + + def test_changelog_section(self): + self.assertEqual(semver.changelog_section(CHANGELOG, (0, 11, 0)), "- A feature\n- Another") + self.assertEqual(semver.changelog_section(CHANGELOG, (0, 10, 0)), "- Older") + self.assertIsNone(semver.changelog_section(CHANGELOG, (0, 1, 0))) + self.assertIsNone(semver.changelog_section(CHANGELOG, (0, 1, 1))) + + +class Flow(unittest.TestCase): + def check(self, base, head, tags=TAGS, changelog=CHANGELOG, composer=None): + return check_flow.problems(base, head, tags, changelog, composer or {"name": "x/y"}) + + def test_release_to_production(self): + self.assertEqual(self.check("production", "release/v0.11.0"), []) + + def test_production_only_from_a_release_branch(self): + self.assertTrue(self.check("production", "feature/x")) + self.assertTrue(self.check("production", "develop")) + + def test_release_must_be_above_the_latest_tag(self): + self.assertTrue(self.check("production", "release/v0.10.0")) + self.assertTrue(self.check("production", "release/v0.9.0")) + + def test_release_needs_its_changelog_section(self): + self.assertTrue(self.check("production", "release/v0.12.0")) + self.assertTrue(self.check("production", "release/v0.11.0", changelog=None)) + + def test_composer_json_has_no_version(self): + self.assertTrue(self.check("production", "release/v0.11.0", composer={"version": "0.11.0"})) + + def test_features_into_an_open_release_branch(self): + self.assertEqual(self.check("release/v0.11.0", "feature/x"), []) + self.assertEqual(self.check("release/v0.11.0", "fix/y"), []) + + def test_nothing_into_a_release_that_is_out(self): + self.assertTrue(self.check("release/v0.10.0", "feature/x")) + + def test_a_release_branch_takes_no_long_lived_branch(self): + for head in ("production", "develop", "release/v0.12.0"): + self.assertTrue(self.check("release/v0.11.0", head)) + + def test_nothing_goes_to_develop_or_anything_else(self): + self.assertTrue(self.check("develop", "feature/x")) + self.assertTrue(self.check("main", "feature/x")) + + def test_first_release_without_tags(self): + self.assertEqual(self.check("production", "release/v0.1.0", tags=[], changelog="## v0.1.0 - x\n\n- a\n"), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/.gitea/workflows/pr-ci.yml b/.gitea/workflows/pr-ci.yml index d6730fc..709eddc 100644 --- a/.gitea/workflows/pr-ci.yml +++ b/.gitea/workflows/pr-ci.yml @@ -1,18 +1,150 @@ name: PR CI +# Pull requests go to a release branch (features) or to production (the release). develop only takes +# the sync after a release. See README.md, "Development cycle". on: pull_request: - branches: [production, staging] + branches: ['release/**', production] + +env: + COMPOSER_NO_INTERACTION: '1' jobs: - pr-ci: + # Does the pull request follow the cycle: right branches, a version above the latest tag, a changelog + # section for a release. + flow: runs-on: docker container: image: webdevops/php:8.4 steps: - - uses: actions/checkout@v4 - - run: composer validate - - run: composer install --no-interaction --prefer-dist - - run: vendor/bin/pint --test - - run: vendor/bin/pest - - run: composer audit + - name: checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: tests of the release scripts + run: python3 -m unittest discover -s .gitea/scripts + + - name: development cycle + run: | + git config --global --add safe.directory "$(pwd)" + python3 .gitea/scripts/check_flow.py + env: + BASE_REF: ${{ github.base_ref }} + HEAD_REF: ${{ github.head_ref }} + + # Every piece of work records its tokens and hours (TOKENS.md). Exempt: release/*, renovate/*, bots. + ledger: + runs-on: docker + container: + image: webdevops/php:8.4 + steps: + - name: checkout + uses: actions/checkout@v4 + + - name: token ledger updated + run: | + git config --global --add safe.directory "$(pwd)" + python3 .gitea/scripts/check_tokens.py + env: + BASE_REF: ${{ github.base_ref }} + HEAD_REF: ${{ github.head_ref }} + PR_AUTHOR: ${{ github.event.pull_request.user.login }} + + # Style and tests, with the newest dependencies the constraints allow and with the oldest: a package + # has to work for everyone in between. + test: + runs-on: docker + container: + image: webdevops/php:8.4 + strategy: + fail-fast: false + matrix: + dependencies: [stable, lowest] + steps: + - name: checkout + uses: actions/checkout@v4 + + - name: cache composer downloads + uses: actions/cache@v4 + with: + path: ~/.composer/cache + key: composer-${{ matrix.dependencies }}-${{ hashFiles('composer.json') }} + restore-keys: | + composer-${{ matrix.dependencies }}- + + - name: composer validate + run: composer validate --strict --no-check-lock + + - name: install dependencies (${{ matrix.dependencies }}) + run: | + if [ "${{ matrix.dependencies }}" = "lowest" ]; then + composer update --prefer-lowest --prefer-stable --prefer-dist + else + composer update --prefer-stable --prefer-dist + fi + + - name: lint (pint) + if: matrix.dependencies == 'stable' + run: vendor/bin/pint --test + + - name: pest tests + run: vendor/bin/pest + + # Known vulnerabilities in the dependencies, and secrets or bad settings in the repository. + security: + runs-on: docker + container: + image: webdevops/php:8.4 + steps: + - name: checkout + uses: actions/checkout@v4 + + - name: install dependencies + run: composer update --prefer-stable --prefer-dist --no-scripts + + - name: composer audit + run: composer audit + + - name: install trivy + run: .gitea/scripts/install-trivy.sh + + # Fails on HIGH and CRITICAL. vendor/ is left out of the secret and settings scan (it is other + # people's code); the lock file made above is what the vulnerability scan reads. + - name: trivy + run: | + trivy fs --no-progress --scanners vuln,secret,misconfig --severity HIGH,CRITICAL --exit-code 1 --skip-dirs vendor . + + # Pull requests to a release branch merge by themselves when the check below is green. + release-automerge: + runs-on: docker + needs: pr-ci + if: startsWith(github.base_ref, 'release/') && needs.pr-ci.result == 'success' + container: + image: python:3.12-alpine + steps: + - name: checkout + uses: actions/checkout@v4 + + - name: enable auto-merge + run: python3 .gitea/scripts/auto_merge.py + env: + GT_URL: https://git.iriks.casa + GT_OWNER: iriks-it + GT_REPO: laravel-manager + GT_TOKEN: ${{ secrets.DEPLOY_TOKEN }} + PULL_REQUEST_NUMBER: ${{ github.event.pull_request.number }} + + # The one check the branch protection asks for (`PR CI / pr-ci (pull_request)`): green only when + # every job above is. Do not rename it without changing the protection rule. + pr-ci: + runs-on: docker + needs: [flow, ledger, test, security] + if: always() + container: + image: alpine:3.20 + steps: + - name: all checks green + run: | + echo "flow=${{ needs.flow.result }} ledger=${{ needs.ledger.result }} test=${{ needs.test.result }} security=${{ needs.security.result }}" + [ "${{ needs.flow.result }}" = "success" ] && [ "${{ needs.ledger.result }}" = "success" ] && [ "${{ needs.test.result }}" = "success" ] && [ "${{ needs.security.result }}" = "success" ] diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml new file mode 100644 index 0000000..1394ca0 --- /dev/null +++ b/.gitea/workflows/release.yml @@ -0,0 +1,90 @@ +name: Release + +# A push to production is the merge of a release pull request. Check it once more, tag it, tell +# Packagist, and bring develop up to date, so the next features start from what was released. +on: + push: + branches: [production] + +concurrency: + group: release + cancel-in-progress: false + +jobs: + verify: + runs-on: docker + container: + image: webdevops/php:8.4 + steps: + - name: checkout + uses: actions/checkout@v4 + + - name: install dependencies + run: composer update --prefer-stable --prefer-dist + + - name: pest tests + run: vendor/bin/pest + + - name: composer audit + run: composer audit + + tag: + runs-on: docker + needs: verify + container: + image: webdevops/php:8.4 + steps: + - name: checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: release + run: | + git config --global --add safe.directory "$(pwd)" + python3 .gitea/scripts/release.py + env: + GT_URL: https://git.iriks.casa + GT_OWNER: iriks-it + GT_REPO: laravel-manager + GT_TOKEN: ${{ secrets.DEPLOY_TOKEN }} + COMMIT_HASH: ${{ github.sha }} + + # Needs the secrets PACKAGIST_USERNAME and PACKAGIST_TOKEN on the repository, and the package + # submitted on packagist.org once. Without them this step only says so. + packagist: + runs-on: docker + needs: tag + container: + image: python:3.12-alpine + steps: + - name: checkout + uses: actions/checkout@v4 + + - name: tell Packagist + run: python3 .gitea/scripts/packagist.py + env: + PACKAGIST_USERNAME: ${{ secrets.PACKAGIST_USERNAME }} + PACKAGIST_TOKEN: ${{ secrets.PACKAGIST_TOKEN }} + PACKAGE_URL: https://git.iriks.casa/iriks-it/laravel-manager + + # Last: merge what was released into develop. Runs even when Packagist could not be told. + sync-develop: + runs-on: docker + needs: [tag, packagist] + if: always() && needs.tag.result == 'success' + container: + image: webdevops/php:8.4 + steps: + - name: checkout + uses: actions/checkout@v4 + + - name: sync develop + run: python3 .gitea/scripts/sync_develop.py + env: + GT_URL: https://git.iriks.casa + GT_OWNER: iriks-it + GT_REPO: laravel-manager + GT_TOKEN: ${{ secrets.DEPLOY_TOKEN }} + GT_BOT_USER: deploy-bot + COMMIT_HASH: ${{ github.sha }} diff --git a/.gitea/workflows/scheduled.yml b/.gitea/workflows/scheduled.yml new file mode 100644 index 0000000..6858c86 --- /dev/null +++ b/.gitea/workflows/scheduled.yml @@ -0,0 +1,32 @@ +name: Scheduled checks + +# What was released does not stay safe: new vulnerabilities are found in old dependencies. Every +# Monday the released code is checked again; a red run is the signal. +on: + schedule: + - cron: '30 5 * * 1' + workflow_dispatch: + +jobs: + audit: + runs-on: docker + container: + image: webdevops/php:8.4 + steps: + - name: checkout production + uses: actions/checkout@v4 + with: + ref: production + + - name: install dependencies + run: composer update --prefer-stable --prefer-dist --no-scripts + + - name: composer audit + run: composer audit + + - name: install trivy + run: .gitea/scripts/install-trivy.sh + + - name: trivy + run: | + trivy fs --no-progress --scanners vuln,secret,misconfig --severity HIGH,CRITICAL --exit-code 1 --skip-dirs vendor . diff --git a/.gitea/workflows/start-release.yml b/.gitea/workflows/start-release.yml new file mode 100644 index 0000000..73204bf --- /dev/null +++ b/.gitea/workflows/start-release.yml @@ -0,0 +1,27 @@ +name: Start release + +# By hand (Actions → Start release → Run workflow): makes release/vX.Y.Z from develop. +on: + workflow_dispatch: + inputs: + version: + description: 'Version of the release, like 0.2.0' + required: true + +jobs: + start: + runs-on: docker + container: + image: python:3.12-alpine + steps: + - name: checkout + uses: actions/checkout@v4 + + - name: make the release branch + run: python3 .gitea/scripts/start_release.py + env: + GT_URL: https://git.iriks.casa + GT_OWNER: iriks-it + GT_REPO: laravel-manager + GT_TOKEN: ${{ secrets.DEPLOY_TOKEN }} + VERSION: ${{ inputs.version }} diff --git a/.gitignore b/.gitignore index c7b2db9..241a9ba 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ vendor/ composer.lock .phpunit.result.cache .env +__pycache__/ diff --git a/AGENTS.md b/AGENTS.md index 3a27849..b73d420 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -9,7 +9,7 @@ between lil-koneko.com, CarsHub, iriks-it.nl and bouwbedrijf.iriks-it.nl, as one - Core modules (users, media) are on by default; the rest is off or on per `config/manager.php`. - Nothing site-specific in the package. A site's own part is its own module class. - Tests: `composer test` (Pest + Testbench); style: `composer lint` (Pint). -- Branches: `production` is main, work on `feature/…` from `develop`; I never merge to `production`. +- Branches: `production` is what is released, `develop` is production plus nothing (the sync), `release/vX.Y.Z` collects the features of a release. Work on `feature/…` or `fix/…` from `develop` and open the pull request to the **release branch**; never to `develop` or `production`. A release is a pull request from the release branch to `production`, merged by hand: never by me. See the README, "Development cycle". - No mention of an AI in commits or PRs. Keep a row per piece of work in `TOKENS.md` (`dev/token-usage.py`; helper agents are counted in the row, one row per model). ## Open decisions diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..39f8986 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,11 @@ +# Changelog + +Every release has a section here, named after its version (`## v0.1.0 - 2026-12-04`). The release pull request +to `production` is stopped by PR CI when its section is missing, and the text of the section is the text of the +release in Gitea. + +## v0.1.0 - unreleased + +- First version: the module registry with switches per part of the manager; the users module (accounts, + groups, permissions, `manager:create-user`); the media module (library, public file route); posts with + categories and tags. diff --git a/README.md b/README.md index d366627..0d731f2 100644 --- a/README.md +++ b/README.md @@ -72,3 +72,31 @@ The answers of every action are JSON, in the shape the screens of bouwbedrijf.ir Inertia props. The screens themselves are not in the package yet: the frontend is an open decision (`AGENTS.md`). Posts, pages and reviews are still skeletons (a list), and so are login, profile, the audit log and revisions: they are not part of users and media. + +## Development cycle + +``` +develop ── feature/*, fix/* ──► release/vX.Y.Z ──► production ──► tag vX.Y.Z ──► Packagist + ▲ (pull request, (collects the (pull request, │ + │ merges by itself) features) merged by hand) │ + └──────────────────────── sync: production into develop ◄─────────────────────────┘ +``` + +1. **Start a release:** Actions → *Start release* → version (`0.2.0`). That makes `release/v0.2.0` from `develop`. +2. **Features:** branch `feature/…` or `fix/…` from `develop`, open a pull request to the release branch. It + merges by itself when *PR CI* is green. Every pull request adds its row to `TOKENS.md`. +3. **Ready:** add a section `## v0.2.0 - date` to `CHANGELOG.md` and open a pull request from the release branch + to `production`. A person merges it. +4. **Release (automatic, on the merge):** tests and audit once more, the tag `v0.2.0` and a Gitea release with the + changelog text, Packagist is told, and `production` is merged into `develop`. + +Nobody opens a pull request to `develop`, and `production` and the release branches take no direct pushes. + +| When | What runs | +|---|---| +| Pull request to a release branch or to production | *flow* (right branches, version above the latest tag, changelog section, tests of these scripts), *ledger* (`TOKENS.md`), *test* (Pint, Pest with the newest and the oldest dependencies, `composer validate`), *security* (`composer audit`, Trivy on the dependencies, secrets and settings). The check `PR CI / pr-ci` is green when all are. | +| Push to production | verify (Pest, audit), tag and release, Packagist, sync develop | +| Every Monday | `composer audit` and Trivy on production | + +Secrets of the repository for this: `DEPLOY_TOKEN` (the organisation has it), and `PACKAGIST_USERNAME` and +`PACKAGIST_TOKEN` once the package is submitted on packagist.org (until then that step only says so). diff --git a/TOKENS.md b/TOKENS.md index 98dc1d9..19109a5 100644 --- a/TOKENS.md +++ b/TOKENS.md @@ -6,3 +6,4 @@ Per stuk werk een rij; zie `dev/token-usage.py`. |---|---|---|---|---:|---:|---:|---:|---:|---:| | 2026-12-04 | Eerste opzet van het pakket: modules, schakelaars, rechten. Gebruikers en media uit bouwbedrijf overgezet | - | claude-sonnet-5-5 | 34 | 57.433 | 76 | 131.194 | 3.225.205 | 0,18 | | 2026-12-04 | Token-script telt de tokens van helper-agents mee in de rij, per model | - | claude-sonnet-5-5 | 16 | 27.013 | 36 | 45.155 | 2.982.056 | 0,06 | +| 2026-12-04 | CI en releaseproces opgezet: releasebranch, tag, Packagist, sync naar develop, tests, audit en Trivy | - | claude-sonnet-5-5 | 14 | 31.242 | 30 | 48.735 | 3.520.606 | 0,09 |