Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
45f4ed2660 | ||
|
|
fc51dd5bdb | ||
|
|
a5e640b31b | ||
|
|
3e8a73d3da | ||
|
|
bb1f4e1292 | ||
|
|
41d82a969a | ||
|
|
541d1ee690 | ||
|
|
a921f14d85 |
No files matched your search
@@ -10,6 +10,8 @@ Pull requests go to a release branch or to production, never to develop.
|
||||
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).
|
||||
The one other way in is `renovate/*`: the nightly dependency update of the homelab (release.py makes a
|
||||
patch release of it, unless a release branch is open).
|
||||
|
||||
Environment: BASE_REF, HEAD_REF. Run in a checkout with the tags (fetch-depth 0).
|
||||
Standard library + git only.
|
||||
@@ -34,6 +36,8 @@ def problems(base, head, existing_tags, changelog, composer):
|
||||
newest = semver.latest(existing_tags)
|
||||
|
||||
if base == "production":
|
||||
if head.startswith("renovate/"):
|
||||
return []
|
||||
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 '?'}."]
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
#!/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
|
||||
+68
-14
@@ -6,8 +6,14 @@ finds that version (from the pull request Gitea knows for the commit, or from th
|
||||
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.
|
||||
|
||||
The other way into production is the nightly dependency update of the homelab, a pull request from
|
||||
`renovate/*`. That makes a patch release too: the version above the latest tag with the patch raised by
|
||||
one (v0.5.0 -> v0.5.1), its text the title and description of the pull request. Renovate makes one pull
|
||||
request per night, so that is at most one patch release a night. When a release branch is open (a version
|
||||
above the latest tag) it makes none: the update goes out with that release.
|
||||
|
||||
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.
|
||||
A push that is neither (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.
|
||||
@@ -48,9 +54,13 @@ def api(method, path, body=None, allow=()):
|
||||
return json.loads(text) if text else None
|
||||
|
||||
|
||||
def release_branch_of(commit):
|
||||
def pull_of(commit):
|
||||
"""The pull request that made this commit, or None."""
|
||||
return api("GET", f"commits/{commit}/pull", allow=(404,))
|
||||
|
||||
|
||||
def release_branch_of(commit, pull=None):
|
||||
"""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
|
||||
@@ -61,15 +71,67 @@ def release_branch_of(commit):
|
||||
return found.group(1) if found else None
|
||||
|
||||
|
||||
def next_patch(newest):
|
||||
"""v0.5.0 -> (0, 5, 1); None without a tag to count from."""
|
||||
return None if newest is None else (newest[0], newest[1], newest[2] + 1)
|
||||
|
||||
|
||||
def release_is_open(branches, newest):
|
||||
"""True when one of the branches is a release/vX.Y.Z above the latest tag."""
|
||||
return any((v := semver.release_version(b)) and (newest is None or v > newest) for b in branches)
|
||||
|
||||
|
||||
def dependency_release(commit, pull):
|
||||
"""Makes the patch release for a merged renovate/* pull request; says why when it makes none."""
|
||||
tags = subprocess.run(["git", "tag", "--list", "v*"], capture_output=True, text=True).stdout.split()
|
||||
already = subprocess.run(["git", "tag", "--points-at", commit], capture_output=True, text=True).stdout.split()
|
||||
if any(semver.tag_version(tag) for tag in already):
|
||||
print(f"{commit[:8]} is already tagged ({' '.join(already)}): nothing to do.")
|
||||
return
|
||||
|
||||
newest = semver.latest(tags)
|
||||
version = next_patch(newest)
|
||||
if version is None:
|
||||
print("No tag to count from: no release made.")
|
||||
return
|
||||
|
||||
branches = [b["name"] for b in api("GET", "branches?limit=100") or []]
|
||||
if release_is_open(branches, newest):
|
||||
print("A release branch is open: this update goes out with it, no patch release made.")
|
||||
return
|
||||
|
||||
tag = f"v{semver.text(version)}"
|
||||
title = (pull.get("title") or "Dependency update").strip()
|
||||
body = (pull.get("body") or "").strip()
|
||||
notes = f"- {title}" + (f"\n\n{body}" if body else "")
|
||||
publish(tag, commit, notes)
|
||||
|
||||
|
||||
def publish(tag, commit, notes):
|
||||
api("POST", "releases", {
|
||||
"tag_name": tag,
|
||||
"target_commitish": commit,
|
||||
"name": tag,
|
||||
"body": notes,
|
||||
"draft": False,
|
||||
"prerelease": False,
|
||||
})
|
||||
print(f"Released {tag} on {commit[:8]}.")
|
||||
|
||||
|
||||
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)
|
||||
pull = pull_of(COMMIT)
|
||||
branch = release_branch_of(COMMIT, pull)
|
||||
if branch is None:
|
||||
print(f"{COMMIT[:8]} is not the merge of a release/vX.Y.Z pull request: no release made.")
|
||||
if ((pull or {}).get("head") or {}).get("ref", "").startswith("renovate/"):
|
||||
dependency_release(COMMIT, pull)
|
||||
else:
|
||||
print(f"{COMMIT[:8]} is not the merge of a release/vX.Y.Z or renovate/* pull request: no release made.")
|
||||
return
|
||||
|
||||
version = semver.release_version(branch)
|
||||
@@ -85,15 +147,7 @@ def main():
|
||||
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]}.")
|
||||
publish(tag, COMMIT, notes)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -11,7 +11,7 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
import check_flow # noqa: E402
|
||||
import packagist # noqa: E402
|
||||
import prune_branches # noqa: E402
|
||||
import update_dependencies # noqa: E402
|
||||
import release # noqa: E402
|
||||
import semver # noqa: E402
|
||||
|
||||
TAGS = ["v0.1.0", "v0.2.0", "v0.10.0", "not-a-version"]
|
||||
@@ -42,6 +42,10 @@ class Flow(unittest.TestCase):
|
||||
def test_release_to_production(self):
|
||||
self.assertEqual(self.check("production", "release/v0.11.0"), [])
|
||||
|
||||
def test_production_also_takes_the_nightly_renovate_branch(self):
|
||||
self.assertEqual(self.check("production", "renovate/deps-20261205"), [])
|
||||
self.assertTrue(self.check("production", "renovate"))
|
||||
|
||||
def test_production_only_from_a_release_branch(self):
|
||||
self.assertTrue(self.check("production", "feature/x"))
|
||||
self.assertTrue(self.check("production", "develop"))
|
||||
@@ -136,73 +140,17 @@ class HermesTokens(unittest.TestCase):
|
||||
self.assertTrue(self.hermes.lines(per_model, "Work", "2026-12-04", "", None)[0].endswith("| 4.000 | |"))
|
||||
|
||||
|
||||
class DependencyUpdates(unittest.TestCase):
|
||||
def test_only_a_release_above_the_latest_tag_is_open(self):
|
||||
branches = ["develop", "production", "release/v0.1.0", "release/v0.2.0", "release/v0.3.0", "feature/x"]
|
||||
self.assertEqual(update_dependencies.open_release(branches, ["v0.1.0", "v0.2.0"]), "release/v0.3.0")
|
||||
self.assertIsNone(update_dependencies.open_release(branches, ["v0.3.0"]))
|
||||
self.assertEqual(update_dependencies.open_release(["release/v0.1.0"], []), "release/v0.1.0")
|
||||
class DependencyRelease(unittest.TestCase):
|
||||
def test_the_next_patch(self):
|
||||
self.assertEqual(release.next_patch((0, 5, 0)), (0, 5, 1))
|
||||
self.assertEqual(release.next_patch((1, 2, 9)), (1, 2, 10))
|
||||
self.assertIsNone(release.next_patch(None))
|
||||
|
||||
def test_widening_adds_the_new_major_once(self):
|
||||
self.assertEqual(update_dependencies.widen("^13.0", "14.2.1"), "^13.0||^14.0")
|
||||
self.assertEqual(update_dependencies.widen("^12.0 || ^13.0", "14.0.0"), "^12.0 || ^13.0||^14.0")
|
||||
self.assertIsNone(update_dependencies.widen("^13.0||^14.0", "14.2.1"))
|
||||
self.assertEqual(update_dependencies.widen("^0.5", "0.6.3"), "^0.5||^0.6")
|
||||
|
||||
def test_odd_constraints_are_left_to_a_person(self):
|
||||
for odd in (">=1.0", "dev-main", "*", "1.2.*"):
|
||||
self.assertIsNone(update_dependencies.widen(odd, "9.0.0"))
|
||||
|
||||
def test_only_what_is_outside_the_constraint_changes(self):
|
||||
composer = {"require": {"a/a": "^1.0", "b/b": "^2.0"}, "require-dev": {"c/c": "^3.0"}}
|
||||
outdated = [
|
||||
{"name": "a/a", "latest": "2.0.0", "latest-status": "update-possible"},
|
||||
{"name": "b/b", "latest": "2.4.0", "latest-status": "semver-safe-update"},
|
||||
{"name": "c/c", "latest": "4.1.0", "latest-status": "update-possible"},
|
||||
]
|
||||
changes = update_dependencies.widened(composer, outdated)
|
||||
self.assertEqual(sorted(changes), ["a/a", "c/c"])
|
||||
self.assertEqual(composer["require"]["a/a"], "^1.0||^2.0")
|
||||
self.assertEqual(composer["require"]["b/b"], "^2.0")
|
||||
self.assertEqual(composer["require-dev"]["c/c"], "^3.0||^4.0")
|
||||
|
||||
|
||||
class NpmUpdates(unittest.TestCase):
|
||||
NOW = __import__("datetime").datetime(2026, 12, 8, 12, 0, tzinfo=__import__("datetime").timezone.utc)
|
||||
|
||||
def published(self, ages):
|
||||
import datetime
|
||||
|
||||
return lambda name, version: None if (name, version) not in ages else self.NOW - datetime.timedelta(hours=ages[(name, version)])
|
||||
|
||||
def test_a_release_must_be_public_for_two_days(self):
|
||||
outdated = {"vue": {"current": "3.5.0", "wanted": "3.5.9", "latest": "4.0.0"}}
|
||||
# The newest is a day old: the newest one inside the range is taken instead.
|
||||
targets = update_dependencies.npm_targets(outdated, self.published({("vue", "4.0.0"): 24, ("vue", "3.5.9"): 200}), self.NOW)
|
||||
self.assertEqual(targets, {"vue": ("3.5.0", "3.5.9")})
|
||||
# Both too new: nothing this week.
|
||||
self.assertEqual(update_dependencies.npm_targets(outdated, self.published({("vue", "4.0.0"): 24, ("vue", "3.5.9"): 47}), self.NOW), {})
|
||||
|
||||
def test_the_newest_is_taken_when_it_is_old_enough(self):
|
||||
outdated = {"vite": {"current": "7.0.0", "wanted": "7.1.0", "latest": "8.0.0"}}
|
||||
targets = update_dependencies.npm_targets(outdated, self.published({("vite", "8.0.0"): 49}), self.NOW)
|
||||
self.assertEqual(targets["vite"], ("7.0.0", "8.0.0"))
|
||||
|
||||
def test_a_held_back_package_stays_on_its_major(self):
|
||||
outdated = {"typescript": {"current": "5.9.3", "wanted": "5.9.3", "latest": "7.0.2"}}
|
||||
self.assertEqual(update_dependencies.npm_targets(outdated, self.published({("typescript", "7.0.2"): 999}), self.NOW), {})
|
||||
outdated["typescript"]["wanted"] = "5.9.9"
|
||||
targets = update_dependencies.npm_targets(outdated, self.published({("typescript", "7.0.2"): 999, ("typescript", "5.9.9"): 999}), self.NOW)
|
||||
self.assertEqual(targets, {"typescript": ("5.9.3", "5.9.9")})
|
||||
|
||||
def test_unknown_dates_prereleases_and_missing_installs_are_left_alone(self):
|
||||
outdated = {
|
||||
"a": {"current": "1.0.0", "wanted": "1.0.0", "latest": "2.0.0"},
|
||||
"b": {"current": "1.0.0", "wanted": "1.0.0", "latest": "2.0.0-beta.1"},
|
||||
"c": {"wanted": "1.0.0", "latest": "2.0.0"},
|
||||
}
|
||||
ages = {("b", "2.0.0-beta.1"): 999, ("c", "2.0.0"): 999}
|
||||
self.assertEqual(update_dependencies.npm_targets(outdated, self.published(ages), self.NOW), {})
|
||||
def test_an_open_release_takes_the_update_with_it(self):
|
||||
branches = ["production", "develop", "release/v0.4.0", "release/v0.5.0", "renovate/deps-1"]
|
||||
self.assertFalse(release.release_is_open(branches, (0, 5, 0)))
|
||||
self.assertTrue(release.release_is_open(branches, (0, 4, 0)))
|
||||
self.assertTrue(release.release_is_open(branches + ["release/v0.5.1"], (0, 5, 0)))
|
||||
|
||||
|
||||
class PackagistNotice(unittest.TestCase):
|
||||
|
||||
@@ -1,294 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Weekly dependency update for a library: widens the version constraints of composer.json.
|
||||
|
||||
A package has no composer.lock, so there is nothing to bump: what can go stale is the range of
|
||||
versions it accepts. When a direct dependency has a release outside its constraint (a new major,
|
||||
say Laravel 14), the constraint is widened to accept it as well (`^13.0||^14.0`) and a pull request
|
||||
is opened to the open release branch (`release/vX.Y.Z` above the latest tag). PR CI then tests the
|
||||
new version; the pull request merges by itself when everything is green, and stays open when
|
||||
it is not, so a red pull request is the signal that the package does not work with it yet.
|
||||
|
||||
Nothing happens when no release is open (start one first), when a pull request of this script is
|
||||
still open, or when nothing is outside its constraint.
|
||||
|
||||
The screens have their own dependencies (`ui/package.json`, with a lock file). `update_dependencies.py ui` moves
|
||||
every npm package that has a newer release (a new major too) to it, but only to a release that has been public for
|
||||
48 hours (a supply-chain guard: a hijacked release is usually pulled within days), rebuilds `resources/dist`, and opens
|
||||
a pull request the same way. PR CI type-checks and builds it, so a red pull request is the signal.
|
||||
|
||||
Environment: GT_URL, GT_OWNER, GT_REPO, GT_TOKEN (the deploy bot: pushes a branch, opens a pull
|
||||
request). Needs git and composer (npm and node for `ui`). Standard library only.
|
||||
"""
|
||||
|
||||
import datetime
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
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", "")
|
||||
USER = "deploy-bot"
|
||||
BRANCH_PREFIX = "renovate/deps-"
|
||||
UI_BRANCH_PREFIX = "renovate/ui-deps-"
|
||||
MIN_AGE = datetime.timedelta(hours=48)
|
||||
# npm packages held at a major until what depends on them works with the next one (remove the line then).
|
||||
HELD = {"typescript": 5} # vue-tsc (the type check of the screens) does not run on TypeScript 7 yet
|
||||
SECTIONS = ("require", "require-dev")
|
||||
|
||||
|
||||
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:
|
||||
sys.exit(f"Gitea API {method} {path} failed: {e.code} {e.read().decode()}")
|
||||
return json.loads(text) if text else None
|
||||
|
||||
|
||||
def open_release(branches, tags):
|
||||
"""The release branch that is not released yet (its version is above the latest tag); the highest one."""
|
||||
newest = semver.latest(tags)
|
||||
open_ones = [(semver.release_version(name), name) for name in branches]
|
||||
open_ones = [(version, name) for version, name in open_ones if version and (newest is None or version > newest)]
|
||||
return max(open_ones)[1] if open_ones else None
|
||||
|
||||
|
||||
def caret(version):
|
||||
"""`^14.0` for 14.2.1; `^0.6` for 0.6.3 (a caret on a 0.x version only allows the minor)."""
|
||||
parts = version.lstrip("v").split(".")
|
||||
return f"^{parts[0]}.{parts[1] if parts[0] == '0' else '0'}"
|
||||
|
||||
|
||||
def widen(constraint, latest):
|
||||
"""The constraint with the version of `latest` added, or None when it is (already) accepted or not a plain range."""
|
||||
# Only the plain forms: a caret, a tilde or a list of those. Anything else is left to a person.
|
||||
if not re.fullmatch(r"[\^~][\w.\-]+(\s*\|\|?\s*[\^~][\w.\-]+)*", constraint.strip()):
|
||||
return None
|
||||
|
||||
added = caret(latest)
|
||||
|
||||
if added in constraint.replace(" ", "").split("||"):
|
||||
return None
|
||||
|
||||
return f"{constraint.strip()}||{added}"
|
||||
|
||||
|
||||
def widened(composer, outdated):
|
||||
"""Applies the packages that `composer outdated` says have a release outside their constraint; returns what changed."""
|
||||
changes = {}
|
||||
|
||||
for package in outdated:
|
||||
name, latest = package.get("name"), package.get("latest")
|
||||
|
||||
if package.get("latest-status") != "update-possible" or not latest:
|
||||
continue
|
||||
|
||||
for section in SECTIONS:
|
||||
current = composer.get(section, {}).get(name)
|
||||
new = widen(current, latest) if current else None
|
||||
|
||||
if new:
|
||||
composer[section][name] = new
|
||||
changes[name] = (current, new)
|
||||
|
||||
return changes
|
||||
|
||||
|
||||
def npm_targets(outdated, published, now):
|
||||
"""What each outdated npm package moves to: its newest release (or the newest inside its range) that is old enough.
|
||||
|
||||
`outdated` is `npm outdated --json` (name -> current, wanted, latest); `published(name, version)` is the time that
|
||||
release came out (a datetime, or None when unknown, which counts as too new).
|
||||
"""
|
||||
targets = {}
|
||||
|
||||
for name, info in sorted(outdated.items()):
|
||||
if not isinstance(info, dict) or not info.get("current"):
|
||||
continue
|
||||
|
||||
for candidate in (info.get("latest"), info.get("wanted")):
|
||||
if not candidate or candidate == info["current"] or "-" in candidate:
|
||||
continue
|
||||
|
||||
if name in HELD and int(candidate.split(".")[0]) > HELD[name]:
|
||||
continue
|
||||
|
||||
when = published(name, candidate)
|
||||
|
||||
if when is not None and now - when >= MIN_AGE:
|
||||
targets[name] = (info["current"], candidate)
|
||||
break
|
||||
|
||||
return targets
|
||||
|
||||
|
||||
def main_ui():
|
||||
"""The same cycle for ui/: bump what is outdated and old enough, rebuild the bundle, open a pull request."""
|
||||
work, release, remote = prepare(UI_BRANCH_PREFIX)
|
||||
ui = os.path.join(work, "ui")
|
||||
|
||||
install = run(["npm", "ci", "--no-audit", "--no-fund", "--ignore-scripts"], ui, retries=3)
|
||||
|
||||
if install.returncode != 0:
|
||||
sys.exit(f"npm ci failed:\n{install.stderr[-2000:]}")
|
||||
|
||||
listed = run(["npm", "outdated", "--json"], ui) # exit code 1 means "something is outdated"
|
||||
outdated = json.loads(listed.stdout or "{}")
|
||||
times = {}
|
||||
|
||||
def published(name, version):
|
||||
if name not in times:
|
||||
view = run(["npm", "view", name, "time", "--json"], ui, retries=2)
|
||||
try:
|
||||
times[name] = json.loads(view.stdout or "{}")
|
||||
except ValueError:
|
||||
times[name] = {}
|
||||
|
||||
stamp = times[name].get(version) if isinstance(times[name], dict) else None
|
||||
|
||||
try:
|
||||
return datetime.datetime.fromisoformat(stamp.replace("Z", "+00:00")) if stamp else None
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
targets = npm_targets(outdated, published, datetime.datetime.now(datetime.timezone.utc))
|
||||
|
||||
if not targets:
|
||||
print("Every npm package is up to date, or too new to adopt yet: nothing to do.")
|
||||
return
|
||||
|
||||
applied = {}
|
||||
|
||||
for name, (old, new) in targets.items():
|
||||
result = run(["npm", "install", f"{name}@{new}", "--save-prefix=^", "--no-audit", "--no-fund", "--ignore-scripts"], ui)
|
||||
|
||||
if result.returncode == 0:
|
||||
applied[name] = (old, new)
|
||||
else:
|
||||
run(["git", "checkout", "--", "ui/package.json", "ui/package-lock.json"], work)
|
||||
print(f"{name} {new} does not install: left as it was.")
|
||||
|
||||
if not applied:
|
||||
print("Nothing could be installed.")
|
||||
return
|
||||
|
||||
# A new bundle with the new dependencies; when it does not build the pull request still opens, red, with the old bundle.
|
||||
if run(["npm", "run", "build"], ui).returncode != 0:
|
||||
print("The build failed with the new packages: the pull request will be red.")
|
||||
|
||||
publish(work, release, remote, UI_BRANCH_PREFIX, applied, "Update the dependencies of the screens", ["ui/package.json", "ui/package-lock.json", "resources/dist"])
|
||||
|
||||
|
||||
def prepare(prefix):
|
||||
"""Finds the open release, makes sure no pull request of this kind is open, and clones the release branch."""
|
||||
if not (URL and OWNER and REPO and TOKEN):
|
||||
sys.exit("GT_URL, GT_OWNER, GT_REPO and GT_TOKEN are required.")
|
||||
|
||||
branches = [item["name"] for item in api("GET", "branches?limit=50") or []]
|
||||
tags = [item["name"] for item in api("GET", "tags?limit=50") or []]
|
||||
release = open_release(branches, tags)
|
||||
|
||||
if release is None:
|
||||
print("No release is open: nothing to update. Start a release first.")
|
||||
sys.exit(0)
|
||||
|
||||
for pull in api("GET", "pulls?state=open&limit=50") or []:
|
||||
if pull["head"]["ref"].startswith(prefix):
|
||||
print(f"Pull request #{pull['number']} of this workflow is still open: not making another.")
|
||||
sys.exit(0)
|
||||
|
||||
remote = f"https://{USER}:{TOKEN}@{URL.split('://', 1)[1]}/{OWNER}/{REPO}.git"
|
||||
work = os.path.join(tempfile.mkdtemp(), "repo")
|
||||
clone = subprocess.run(["git", "clone", "--quiet", "--branch", release, remote, work], capture_output=True, text=True)
|
||||
|
||||
if clone.returncode != 0:
|
||||
sys.exit("git clone failed.")
|
||||
|
||||
return work, release, remote
|
||||
|
||||
|
||||
def publish(work, release, remote, prefix, changes, title, paths):
|
||||
"""Commits `paths`, pushes a branch and opens the pull request to the release."""
|
||||
branch = prefix + datetime.date.today().strftime("%Y%m%d")
|
||||
|
||||
for command in (
|
||||
["git", "config", "user.name", USER],
|
||||
["git", "config", "user.email", f"{USER}@iriks-it.nl"],
|
||||
["git", "checkout", "-b", branch],
|
||||
["git", "add", "--", *paths],
|
||||
["git", "commit", "-m", f"{title}: " + ", ".join(sorted(changes))],
|
||||
["git", "push", "--quiet", "origin", branch],
|
||||
):
|
||||
result = subprocess.run(command, cwd=work, capture_output=True, text=True)
|
||||
|
||||
if result.returncode != 0:
|
||||
sys.exit(f"{' '.join(command[:2])} failed: {result.stderr.strip()}")
|
||||
|
||||
pull = api("POST", "pulls", {"title": f"{title}: " + ", ".join(sorted(changes)), "head": branch, "base": release, "body": body(changes, release)})
|
||||
print(f"Pull request #{pull['number']} to {release}: {', '.join(sorted(changes))}.")
|
||||
|
||||
|
||||
def run(command, cwd, retries=1):
|
||||
for attempt in range(1, retries + 1):
|
||||
result = subprocess.run(command, cwd=cwd, capture_output=True, text=True)
|
||||
|
||||
if result.returncode == 0 or attempt == retries:
|
||||
return result
|
||||
|
||||
time.sleep(attempt * 10)
|
||||
|
||||
|
||||
def body(changes, release):
|
||||
lines = "\n".join(f"- `{name}`: `{old}` → `{new}`" for name, (old, new) in sorted(changes.items()))
|
||||
return f"""Automatic update of the dependencies, by the weekly workflow `Dependency updates`.
|
||||
|
||||
{lines}
|
||||
|
||||
PR CI tests the package with the newer versions (and rebuilds the screens when it is about npm). It merges into `{release}` by itself when everything is green; when it is red, the package does not work with them yet."""
|
||||
|
||||
|
||||
def main():
|
||||
work, release, remote = prepare(BRANCH_PREFIX)
|
||||
|
||||
update = run(["composer", "update", "--prefer-stable", "--prefer-dist", "--no-scripts", "--no-interaction"], work, retries=3)
|
||||
|
||||
if update.returncode != 0:
|
||||
sys.exit(f"composer update failed:\n{update.stderr[-2000:]}")
|
||||
|
||||
listed = run(["composer", "outdated", "--direct", "--format=json", "--no-interaction"], work)
|
||||
outdated = json.loads(listed.stdout or "{}").get("installed", [])
|
||||
|
||||
path = os.path.join(work, "composer.json")
|
||||
composer = json.load(open(path))
|
||||
changes = widened(composer, outdated)
|
||||
|
||||
if not changes:
|
||||
print("Every direct dependency is inside its constraint: nothing to do.")
|
||||
return
|
||||
|
||||
with open(path, "w") as file:
|
||||
json.dump(composer, file, indent=4, ensure_ascii=False)
|
||||
file.write("\n")
|
||||
|
||||
publish(work, release, remote, BRANCH_PREFIX, changes, "Dependency updates", ["composer.json"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main_ui() if sys.argv[1:] == ["ui"] else main()
|
||||
@@ -1,56 +0,0 @@
|
||||
name: Dependency updates
|
||||
|
||||
# A package has no composer.lock, so what goes stale is the range of versions it accepts. Every
|
||||
# Monday this looks for a direct dependency with a release outside its constraint (a new major) and
|
||||
# opens a pull request to the open release branch that accepts it as well; PR CI then tests it and the
|
||||
# pull request merges by itself when it is green. The second job does the same for the npm packages of the
|
||||
# screens (ui/), to a release that has been public for 48 hours, and rebuilds resources/dist. Nothing happens
|
||||
# while no release is open.
|
||||
on:
|
||||
schedule:
|
||||
- cron: '0 5 * * 1'
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
update:
|
||||
runs-on: docker
|
||||
container:
|
||||
image: webdevops/php:8.4
|
||||
steps:
|
||||
- name: checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: cache composer downloads
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.composer/cache
|
||||
key: composer-dependencies-${{ hashFiles('composer.json') }}
|
||||
restore-keys: |
|
||||
composer-dependencies-
|
||||
|
||||
- name: widen the constraints
|
||||
run: python3 .gitea/scripts/update_dependencies.py
|
||||
env:
|
||||
COMPOSER_MAX_PARALLEL_HTTP: '4'
|
||||
GT_URL: https://git.iriks.casa
|
||||
GT_OWNER: iriks-it
|
||||
GT_REPO: laravel-manager
|
||||
GT_TOKEN: ${{ secrets.DEPLOY_TOKEN }}
|
||||
|
||||
# The screens: npm packages that have a newer release (a new major too), once it has been public for 48 hours.
|
||||
# The node image has git and python3; PR CI type-checks and builds the result.
|
||||
ui:
|
||||
runs-on: docker
|
||||
container:
|
||||
image: node:22-bookworm
|
||||
steps:
|
||||
- name: checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: update the packages of the screens
|
||||
run: python3 .gitea/scripts/update_dependencies.py ui
|
||||
env:
|
||||
GT_URL: https://git.iriks.casa
|
||||
GT_OWNER: iriks-it
|
||||
GT_REPO: laravel-manager
|
||||
GT_TOKEN: ${{ secrets.DEPLOY_TOKEN }}
|
||||
@@ -151,15 +151,6 @@ jobs:
|
||||
- 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.
|
||||
# Every job that checks out runs in an image with git: without git the checkout is the archive of the
|
||||
# repository, which leaves out what .gitattributes export-ignores (.gitea/ with these scripts).
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
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: cache composer downloads
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.composer/cache
|
||||
key: composer-scheduled-${{ hashFiles('composer.json') }}
|
||||
restore-keys: |
|
||||
composer-scheduled-
|
||||
|
||||
- name: install dependencies
|
||||
env:
|
||||
COMPOSER_MAX_PARALLEL_HTTP: '4'
|
||||
run: |
|
||||
for attempt in 1 2 3; do
|
||||
composer update --prefer-stable --prefer-dist --no-scripts && exit 0
|
||||
echo "composer failed (attempt $attempt of 3), trying again" >&2
|
||||
sleep $((attempt * 10))
|
||||
done
|
||||
exit 1
|
||||
|
||||
- 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 .
|
||||
@@ -15,10 +15,11 @@ between lil-koneko.com, CarsHub, iriks-it.nl and bouwbedrijf.iriks-it.nl, as one
|
||||
- **Pull request description.** Every pull request has the eight headings of `.gitea/PULL_REQUEST_TEMPLATE.md`, in that order (`## Vraag`, `## Wat is er gedaan`, `## Zo test je het`, `## Zelf getest`, `## Tijd en tokens`, `## Onderhoud`, `## Met de hand te doen`, `## Vervolgstappen`); a section with nothing to say gets `Niets.` or `Geen.`. Open it from a branch in Gitea or through the API, never with push options (`refs/for/…`): such a pull request gets no secrets in its jobs and its auto-merge fails.
|
||||
- **Every pull request adds its row to `TOKENS.md`** (PR CI fails without one; exempt: `release/*`, `renovate/*`, syncs). Measure it with `dev/token-usage.py LOG --since <when it began> --row "<what was made>"` (for work done by a Hermes agent: `dev/token-usage-hermes.py SESSION_ID… --include-children --hours <h> --row "…"`, from `~/.hermes/state.db`; its hours are a human figure, never invented), starting after the end of the previous row so rows do not overlap; the last cell is the hours. Never make up a row or hours, and keep no totals in the file.
|
||||
- **The two bot accounts.** `deploy-bot` is for the pipeline (`DEPLOY_TOKEN`: auto-merge, tag, release, sync). `renovate-bot` is only for Renovate: no workflow or script here uses its token, and never add a secret for it.
|
||||
- **Nothing runs weekly in a repository.** Security and updates are the homelab's: Trivy every night (03:00) and after every release, the dependency round every night (04:00, branches `renovate/*`). A repository's own pipeline does `composer audit` (or the equivalent) on every pull request and on every release, and nothing on a schedule. Do not add a `schedule:` trigger; the nightly branch pruning is the one exception.
|
||||
- **Security first.** Validate at system boundaries, never trust raw request data, and never introduce the OWASP top-10 (injection, XSS, …). This package is public: no real addresses, names, tokens or client details in code, tests, docs or defaults. In a migration a moment that may not be null is `dateTime`, never `timestamp` (the MySQL of the servers gives such a `timestamp` a default by itself and refuses a second one in a table).
|
||||
|
||||
## Open decisions
|
||||
|
||||
1. Frontend: decided and built: the screens are in the package (`ui/`, built into `resources/dist`, committed; PR CI checks it is up to date). Still open: a theme editor in the manager, and a `host` mode that publishes the sources for a site to build itself.
|
||||
2. Moving the rest from bouwbedrijf.iriks-it.nl: real pages and reviews (now skeletons) and revisions. Users, media, posts, audit log and statistics are done, with their screens. Leave out what is site-specific (the IriksIT API disk, the owner's simple screens, client names): this repo is public.
|
||||
2. Moving the rest from bouwbedrijf.iriks-it.nl: reviews (still a read-only list). Users, media, posts, pages with fields, resources, revisions, audit log and statistics are done, with their screens. Leave out what is site-specific (the IriksIT API disk, client names): this repo is public. Still open: two-factor login, cropping pictures, automated tests of the screens in CI.
|
||||
3. Decided in 0.5.0: groups stay the default and the host's roles are added next to them (`manager.permissions`: `mode` groups, host or merge; `roles` or a `PermissionResolver`). A host that wants to replace the groups screens entirely is not planned.
|
||||
@@ -35,6 +35,11 @@ the section is the text of the release in Gitea.
|
||||
Cloudflare Turnstile is built in (two env keys). No two-factor login in the package itself.
|
||||
- Roles of the host: `manager.permissions` (`mode` groups/host/merge, `roles` map or a `resolver` implementing `PermissionResolver`) lets a site
|
||||
with its own roles say what an account may do; groups stay the default.
|
||||
- CI: nothing runs weekly any more, and Trivy no longer runs in the jobs (the runner disk filled up with its database). `composer audit` stays in every
|
||||
pull request and every release; Trivy scans production from the homelab, every night and after every release. The nightly dependency round of the
|
||||
homelab replaces the weekly *Dependency updates* workflow (and `update_dependencies.py`); its `renovate/*` pull requests may go to `production` and
|
||||
become a patch release of their own (one a night at most, none while a release branch is open).
|
||||
- `manager:doctor` has a `names` check: it warns when the site uses a route name or an address of the manager and says to set `route_name` or `path`.
|
||||
|
||||
## v0.4.0 - 2026-12-04
|
||||
|
||||
|
||||
@@ -47,9 +47,11 @@ on the JSON routes. A browser that opens a manager address gets the page; anythi
|
||||
| `reviews` | Reviews | off |
|
||||
| `audit` | Audit log and address bans | off |
|
||||
| `statistics` | Visitor statistics | off |
|
||||
| `resources` | Lists defined in config (`manager.resources`) | on (nothing without definitions) |
|
||||
| `revisions` | History of posts and pages, with restore | on |
|
||||
|
||||
Switch a part in `config/manager.php` (`modules`) or with `MANAGER_PAGES`, `MANAGER_POSTS`,
|
||||
`MANAGER_REVIEWS`, `MANAGER_AUDIT`, `MANAGER_STATISTICS`. A module that is off has **no routes, no tables, no menu item and no permissions**:
|
||||
`MANAGER_REVIEWS`, `MANAGER_AUDIT`, `MANAGER_STATISTICS`, `MANAGER_REVISIONS`. A module that is off has **no routes, no tables, no menu item and no permissions**:
|
||||
its migrations are not loaded at all. A module that needs another one (`requires()`) fails at boot when
|
||||
that one is off.
|
||||
|
||||
@@ -228,12 +230,14 @@ scheduled daily), so a code cannot be traced back afterwards. A browser that sen
|
||||
|
||||
## State of this version
|
||||
|
||||
Done: module registry and switches, permissions per module, users (accounts, groups, command), media (library and public file
|
||||
route), posts (with categories and tags), the audit log with bans, the statistics, the built-in screens for all of these (with a
|
||||
login and profile), themes, and the install and doctor commands for AI agents. `composer test` runs the tests.
|
||||
Done: module registry and switches, permissions per module, users (accounts, groups, command, roles of the host), media (library and
|
||||
public file route, focus point), posts (with categories and tags), pages with fields, lists defined in config, the history with restore,
|
||||
the audit log with bans, the statistics (with the counting script), the built-in screens for all of these (with a login, checks on the
|
||||
login, a profile and the simple view), an editor, themes, translations, a site's own bundle of screens, the import of existing data, and
|
||||
the install and doctor commands for AI agents. `composer test` runs the tests.
|
||||
|
||||
Pages and reviews are still skeletons (a read-only list), and revisions are not ported yet. The answers of every action are JSON
|
||||
in the shape the screens use, so an app can build its own screens with `MANAGER_UI=none`.
|
||||
Reviews are still a read-only list. The answers of every action are JSON in the shape the screens use, so an app can build its own screens
|
||||
with `MANAGER_UI=none`. Not in the package: two-factor login (the login checks are the place for it), cropping or rotating pictures, a theme editor.
|
||||
|
||||
## Development cycle
|
||||
|
||||
@@ -256,12 +260,23 @@ Nobody opens a pull request to `develop`, and `production` and the release branc
|
||||
|
||||
| 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 |
|
||||
| Every Monday | *Dependency updates*: a direct dependency with a release outside its constraint (a new major) gets its constraint widened in a pull request `renovate/deps-DATE` to the open release branch; the npm packages of the screens (`ui/`) move to their newest release that has been public for 48 hours, with a rebuilt `resources/dist`, in `renovate/ui-deps-DATE`. PR CI tests them and they merge when green. Nothing happens while no release is open. The central Trivy (every night 03:00 UTC) and Renovate (04:00 UTC) of the homelab also pass over this repo, but read a `composer.lock` and a package has none, so they find little here. |
|
||||
| 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`: the job fails on any advisory). The check `PR CI / pr-ci` is green when all are. |
|
||||
| Push to production | verify (Pest, `composer audit`), tag and release, Packagist, sync develop; then the homelab scans production with Trivy |
|
||||
| Every night | the homelab scans every repository with Trivy (03:00) and updates its dependencies (04:00): nothing runs weekly in this repository |
|
||||
| Every night | *Prune branches*: removes `feature/*` and `fix/*` branches whose last commit is over 30 days old and that have no open pull request (a branch of a pull request can be restored from it in Gitea) |
|
||||
|
||||
### Security and updates
|
||||
|
||||
Nothing here runs on a weekly schedule; the checks hang on the moments that matter, and the homelab does the rest every night.
|
||||
|
||||
- **Every pull request:** `composer audit` (it fails on any advisory).
|
||||
- **Every release:** `composer audit` again on the merge to `production`.
|
||||
- **After every release to production:** Trivy scans `production` from the homelab (LXC 120, no database to download in a job).
|
||||
- **Every night:** Trivy scans every repository of the organisation (03:00), and the dependency round (04:00) opens a pull request
|
||||
`renovate/deps-DATE` straight to `production` for updates that have been public for 48 hours. PR CI tests it, and when it is
|
||||
merged the Release workflow makes a patch release of it (v0.5.0 → v0.5.1, text from the pull request), tells Packagist and syncs `develop`:
|
||||
one a night at most. While a release branch is open there is no patch release; the update goes out with that release. A critical advisory on the installed version skips the 48 hours.
|
||||
|
||||
Secrets of the repository for this: `DEPLOY_TOKEN` (the organisation has it), and `PACKAGIST_USERNAME` and
|
||||
`PACKAGIST_TOKEN` (until they are set that step only says so). When Packagist does not know the package yet, that step
|
||||
submits it through the create-package API; after that it only tells Packagist about each new tag.
|
||||
|
||||
@@ -43,3 +43,7 @@ Per stuk werk een rij; zie `dev/token-usage.py`.
|
||||
| 2026-12-04 | Het telscript en de Blade-component voor de publieke pagina's van de statistieken | - | claude-sonnet-5-5 | 8 | 9.037 | 16 | 15.948 | 2.254.948 | 0,04 |
|
||||
| 2026-12-04 | Loginhaken: eigen velden en controles, en Turnstile | - | claude-sonnet-5-5 | 4 | 9.009 | 8 | 9.515 | 1.178.544 | 0,02 |
|
||||
| 2026-12-04 | Rollen van de site naast de groepen van het pakket | - | claude-sonnet-5-5 | 3 | 5.308 | 6 | 8.235 | 921.246 | 0,01 |
|
||||
| 2026-12-04 | Controle op namen die de site al gebruikt, en de documenten van 0.5.0 rechtgezet | - | claude-sonnet-5-5 | 9 | 7.281 | 18 | 12.115 | 2.881.457 | 0,03 |
|
||||
| 2026-12-04 | Trivy uit de PR-jobs (schijf van de runners vol), opruimen en wekelijkse prune | - | claude-sonnet-5-5 | 20 | 9.723 | 44 | 94.863 | 1.460.150 | 0,15 |
|
||||
| 2026-12-04 | Niets meer wekelijks: nachtelijke scan en updates, Trivy na een release, docs | - | claude-sonnet-5-5 | 27 | 19.377 | 58 | 41.226 | 2.879.048 | 0,63 |
|
||||
| 2026-12-04 | Patch-release voor de nachtelijke renovate-update | - | claude-sonnet-5-5 | 24 | 17.609 | 54 | 35.165 | 3.038.359 | 0,16 |
|
||||
@@ -17,6 +17,14 @@ order and never edit files inside `vendor/`.
|
||||
Repeat until `"ok": true`.
|
||||
|
||||
Facts that matter:
|
||||
- A site that already has `manager.*` route names, `manager_*` tables or its own posts and pages: `manager:doctor` has a `names` check that says
|
||||
so. Set `route_name`, `table_prefix` or `tables` in `config/manager.php` before the first `migrate`, then copy what exists with
|
||||
`php artisan manager:import posts|pages|reviews --table=<table> --map=<package_column>=<column> --dry-run` (the source is only read).
|
||||
- What the site's own content looks like is configuration, not code: `manager.pages.definitions` (texts with keys, read with `Page::contentFor('slug')`),
|
||||
`manager.resources` (lists such as services or testimonials, in a model of the site or the package's table) and `manager.menu` (order, sections,
|
||||
icons, own links). A screen that needs code is a JavaScript module in `manager.extensions`; it registers with `IriksManager.register`.
|
||||
- Who may do what: the groups of the package, or the roles of the site (`manager.permissions`); more on the login: `manager.login.checks`, Turnstile
|
||||
with two env keys. The public pages count visits with `<x-manager::pulse />` when `statistics` is on.
|
||||
- The screens are part of the package (`MANAGER_UI=package`, the default): open `/manager` in a browser. The app does not need a
|
||||
login of its own: when it has no route named `login`, the manager's own login at `/manager/login` is used. With
|
||||
`MANAGER_UI=none` there are only the JSON routes.
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
## iriks-it/laravel-manager
|
||||
|
||||
A modular backend (users, media, pages, posts, reviews, audit, statistics) installed as a package.
|
||||
A modular backend (users, media, pages, posts, reviews, audit, statistics, resources, revisions) installed as a package.
|
||||
|
||||
- To integrate it, follow `vendor/iriks-it/laravel-manager/resources/ai/INTEGRATION.md` step by step.
|
||||
- Set it up with `php artisan manager:install --modules=... --user-model=...`, then `config:clear`, `migrate`, `storage:link`; verify in a new process with `php artisan manager:doctor --json` (non-zero exit on failure, every problem has a `fix`).
|
||||
- The screens come with the package (`MANAGER_UI`), including a login when the app has none; themes: `php artisan manager:make-theme`, `MANAGER_THEME`.
|
||||
- The user model needs the `HasManagerAccess` trait; `is_super_admin` is never mass assignable. The first super admin comes from `php artisan manager:create-user`.
|
||||
- The site's content is configuration: `manager.pages.definitions`, `manager.resources`, `manager.menu`, `manager.permissions`, `manager.login.checks`; code only as a JavaScript module in `manager.extensions`. Existing data comes in with `php artisan manager:import`.
|
||||
- Switch parts with `MANAGER_<MODULE>=true|false`; never edit `vendor/`. Site-specific parts are your own `Module` class.
|
||||
@@ -31,6 +31,7 @@ class DoctorCommand extends Command
|
||||
$this->checkUserModel($modules);
|
||||
$this->checkTables($modules);
|
||||
$this->checkRoutes();
|
||||
$this->checkNames();
|
||||
$this->checkModules($modules);
|
||||
|
||||
$failed = collect($this->checks)->contains('status', 'fail');
|
||||
@@ -127,6 +128,38 @@ class DoctorCommand extends Command
|
||||
}
|
||||
}
|
||||
|
||||
/** Route names or addresses of the site that the package would share with its own. */
|
||||
private function checkNames(): void
|
||||
{
|
||||
$prefix = Names::routePrefix();
|
||||
$path = trim((string) config('manager.path'), '/');
|
||||
$names = [];
|
||||
$foreign = [];
|
||||
|
||||
foreach (Route::getRoutes()->getRoutes() as $route) {
|
||||
$name = (string) $route->getName();
|
||||
$mine = $route->isFallback || ($route->getActionName() === 'Closure' && str_starts_with($name, $prefix)) || str_starts_with(ltrim($route->getActionName(), '\\'), 'IriksIT\\Manager\\');
|
||||
|
||||
if ($prefix !== '' && str_starts_with($name, $prefix) && $name !== $prefix) {
|
||||
$names[$name] = ($names[$name] ?? 0) + 1;
|
||||
}
|
||||
|
||||
if (! $mine && ($route->uri() === $path || str_starts_with($route->uri(), $path.'/'))) {
|
||||
$foreign[] = $route->uri();
|
||||
}
|
||||
}
|
||||
|
||||
$twice = array_keys(array_filter($names, fn (int $count) => $count > 1));
|
||||
|
||||
if ($twice !== []) {
|
||||
$this->add('names', 'warn', 'Route names used twice: '.implode(', ', array_slice($twice, 0, 5)).'. The site and the manager share them, and one of the two stops working.', "Set 'route_name' in config/manager.php to something the site does not use, for example 'cms'.");
|
||||
} elseif ($foreign !== []) {
|
||||
$this->add('names', 'warn', 'The site has routes under the address of the manager: '.implode(', ', array_slice($foreign, 0, 5)).'.', "Move them, or set 'path' in config/manager.php (MANAGER_PATH) to another address.");
|
||||
} else {
|
||||
$this->add('names', 'ok', 'No route name or address is shared with the site.');
|
||||
}
|
||||
}
|
||||
|
||||
private function checkModules(ModuleRegistry $modules): void
|
||||
{
|
||||
$active = array_keys($modules->active());
|
||||
|
||||
@@ -73,3 +73,24 @@ it('leaves the check to a new process after it changed the switches', function (
|
||||
|
||||
expect(Artisan::output())->toContain('manager:doctor')->not->toContain('[OK]');
|
||||
});
|
||||
|
||||
it('finds no shared names in a clean setup', function () {
|
||||
$check = collect(doctorReport()['checks'])->firstWhere('check', 'names');
|
||||
expect($check['message'])->toBe('No route name or address is shared with the site.');
|
||||
});
|
||||
|
||||
it('warns when the site uses a route name of the manager, and says what to set', function () {
|
||||
Route::get('/home', fn () => 'x')->name('manager.dashboard');
|
||||
|
||||
$check = collect(doctorReport()['checks'])->firstWhere('check', 'names');
|
||||
|
||||
expect($check['status'])->toBe('warn')->and($check['message'])->toContain('manager.dashboard')->and($check['fix'])->toContain('route_name');
|
||||
});
|
||||
|
||||
it('warns when the site has routes under the address of the manager', function () {
|
||||
Route::get('/manager/reports', fn () => 'x');
|
||||
|
||||
$check = collect(doctorReport()['checks'])->firstWhere('check', 'names');
|
||||
|
||||
expect($check['status'])->toBe('warn')->and($check['message'])->toContain('manager/reports');
|
||||
});
|
||||
Reference in new issue
Block a user