Add a bump bot that opens update pull requests for recipes (#30)

A daily workflow compares each recipe with its upstream's newest stable
release and opens one pull request when the image for it is published:
version, image tag and multi-arch digest only. bump/track.yml holds where
each project releases and how its image tag follows the version; it lives
outside cottage.yml because Hearth reads that file strictly. Patch and
minor releases wait 3 days, majors 14. A guard check fails a bump branch
that changes anything else, and 'scripts/bump.py audit' shows how far
behind each recipe is.
This commit is contained in:
michael authored and GitHub committed 2026-11-23 04:33:21 -05:00
1 parent ad8148af74
commit 5796d0eebb
5 files changed
+770

No files matched your search

+324
View File
@@ -0,0 +1,324 @@
#!/usr/bin/env python3
"""Keeps recipes on the newest upstream release.
scripts/bump.py infer write bump/track.yml from the recipes (run once, then review)
scripts/bump.py audit print how far each recipe is behind upstream
scripts/bump.py run [slug...] open one pull request per recipe that has a newer release
DRY=1 scripts/bump.py run show what run would do, changing nothing on GitHub
scripts/bump.py guard BASE check that a bump branch only changes versions, tags and digests
Tracking data lives in bump/track.yml, not in cottage.yml: Hearth reads cottage.yml strictly, so
an extra key there would stop the catalog sync. Needs PyYAML, the gh CLI (logged in) and docker.
"""
import glob
import json
import os
import re
import subprocess
import sys
import urllib.request
from datetime import datetime, timezone
import yaml
TRACK = "bump/track.yml"
COOLDOWN_DAYS = {"patch": 3, "minor": 3, "major": 14} # how old a release must be before we bump
PRERELEASE = re.compile(r"(alpha|beta|rc|preview|nightly|dev|snapshot|canary|pre)", re.I)
# ---- recipes ---------------------------------------------------------------------------------
def recipes():
for p in sorted(glob.glob("apps/*/template.yml")):
slug = p.split("/")[1]
t = yaml.safe_load(open(p))
c = yaml.safe_load(open(f"apps/{slug}/cottage.yml"))
yield slug, str(t["x-harbor"]["version"]), c.get("upstream", ""), [i["ref"] for i in c.get("images", [])]
def split_version(v):
up, _, rev = v.rpartition("-c")
return up, int(rev)
def nums(s):
return tuple(int(x) for x in s.split("."))
def kind(cur, new):
a, b = nums(cur), nums(new)
if b <= a:
return "current" if b == a else "ahead"
if a[0] != b[0]:
return "major"
if (a[1:2] or (0,)) != (b[1:2] or (0,)):
return "minor"
return "patch"
def normalize(tag):
"""A release tag as dotted numbers, or None when it isn't a plain release."""
t = re.sub(r"^[^0-9]*", "", tag)
if PRERELEASE.search(tag):
return None
m = re.fullmatch(r"(\d{4})-(\d{2})-(\d{2})", t)
if m:
return ".".join(str(int(x)) for x in m.groups())
return t if re.fullmatch(r"[0-9]+(\.[0-9]+)*", t) else None
# ---- upstream releases -----------------------------------------------------------------------
def get_json(url, headers=None):
req = urllib.request.Request(url, headers={"User-Agent": "cottage-catalog-bump", **(headers or {})})
with urllib.request.urlopen(req, timeout=30) as r:
return json.load(r)
def gh_json(path):
out = subprocess.run(["gh", "api", path], capture_output=True, text=True)
return json.loads(out.stdout) if out.returncode == 0 else None
def latest_release(source, repo):
"""(tag, published datetime) of the newest stable release, or None."""
items = []
try:
if source == "github":
rel = gh_json(f"repos/{repo}/releases?per_page=30") or []
items = [(r["tag_name"], r["published_at"]) for r in rel if not r["prerelease"] and not r["draft"]]
if not items: # projects that only push tags
tags = gh_json(f"repos/{repo}/tags?per_page=30") or []
items = [(t["name"], None) for t in tags]
elif source == "codeberg":
rel = get_json(f"https://codeberg.org/api/v1/repos/{repo}/releases?limit=30")
items = [(r["tag_name"], r["published_at"]) for r in rel if not r["prerelease"] and not r["draft"]]
elif source == "gitlab":
rel = get_json(f"https://gitlab.com/api/v4/projects/{repo.replace('/', '%2F')}/releases")
items = [(r["tag_name"], r["released_at"]) for r in rel]
except Exception as e:
print(f" {repo}: {e}", file=sys.stderr)
return None
best = None
for tag, when in items:
n = normalize(tag)
if n and (best is None or nums(n) > nums(best[0])):
best = (n, tag, when)
return best
# ---- images ----------------------------------------------------------------------------------
def image_digest(ref):
"""The multi-arch (index) digest of an image, or None when the tag isn't published."""
out = subprocess.run(["docker", "buildx", "imagetools", "inspect", ref], capture_output=True, text=True)
m = re.search(r"^Digest:\s+(sha256:[0-9a-f]{64})", out.stdout, re.M)
return m.group(1) if m else None
# ---- infer -----------------------------------------------------------------------------------
def infer():
tracks = {}
for slug, version, upstream, images in recipes():
m = re.match(r"https://(github\.com|codeberg\.org|gitlab\.com)/([^/]+/[^/#?]+)", upstream)
entry = {}
if not m:
tracks[slug] = {"skip": "no upstream repository to follow"}
continue
entry["source"] = {"github.com": "github", "codeberg.org": "codeberg", "gitlab.com": "gitlab"}[m.group(1)]
entry["repo"] = re.sub(r"\.git$", "", m.group(2))
repo, _, tag = images[0].rpartition(":")
up, _ = split_version(version)
if tag == up:
fmt = "{version}"
elif tag == "v" + up:
fmt = "v{version}"
elif tag.startswith(up) and re.fullmatch(r"[-.\w]*", tag[len(up):]):
fmt = "{version}" + tag[len(up):]
else:
fmt = None
if fmt is None:
entry["manual"] = f"image tag {tag!r} doesn't follow version {up!r}; the bot will not touch it"
else:
entry["image_tag"] = fmt
tracks[slug] = entry
os.makedirs("bump", exist_ok=True)
with open(TRACK, "w") as f:
f.write("# What the bump bot follows for each recipe (scripts/bump.py).\n"
"# source/repo where upstream publishes releases\n"
"# image_tag how the first image's tag is built from the release; {version} is the\n"
"# dotted version. Companion images (databases, caches) are never bumped.\n"
"# manual the bot reports this recipe but never changes it\n"
"# skip not followed at all\n")
yaml.safe_dump(tracks, f, sort_keys=True, width=140)
print(f"wrote {TRACK}: {len(tracks)} recipes, {sum('manual' in v for v in tracks.values())} manual, "
f"{sum('skip' in v for v in tracks.values())} skipped")
# ---- audit -----------------------------------------------------------------------------------
def load_track():
return yaml.safe_load(open(TRACK))
def candidates(only=()):
track = load_track()
for slug, version, _, images in recipes():
if only and slug not in only:
continue
t = track.get(slug, {})
cur, _ = split_version(version)
if "skip" in t or "repo" not in t:
yield slug, cur, None, "skip", t, images, version
continue
rel = latest_release(t["source"], t["repo"])
if rel is None:
yield slug, cur, None, "no-release", t, images, version
continue
yield slug, cur, rel, kind(cur, rel[0]), t, images, version
def audit(only=()):
rows = []
for slug, cur, rel, k, t, _, _ in candidates(only):
new = rel[0] if rel else "-"
flag = "manual" if "manual" in t else ""
rows.append((slug, cur, new, k, flag))
order = {"major": 0, "minor": 1, "patch": 2}
rows.sort(key=lambda r: (order.get(r[3], 9), r[0]))
print(f"{'recipe':22} {'recipe is on':16} {'upstream':16} {'behind by':10} note")
for r in rows:
print(f"{r[0]:22} {r[1]:16} {r[2]:16} {r[3]:10} {r[4]}")
behind = [r for r in rows if r[3] in order]
print(f"\n{len(behind)} of {len(rows)} recipes are behind "
f"({sum(r[3] == 'major' for r in rows)} major, {sum(r[3] == 'minor' for r in rows)} minor, "
f"{sum(r[3] == 'patch' for r in rows)} patch)")
# ---- run -------------------------------------------------------------------------------------
def sh(*a, check=True):
return subprocess.run(a, capture_output=True, text=True, check=check)
def apply_bump(slug, cur, new, t, images, version):
"""Edits the recipe's files in place; returns (old_ref, new_ref, digest) or a reason string."""
old_ref = images[0]
repo = old_ref.rpartition(":")[0]
new_ref = f"{repo}:{t['image_tag'].format(version=new)}"
digest = image_digest(new_ref)
if digest is None:
return f"{new_ref} isn't published yet"
tp, cp = f"apps/{slug}/template.yml", f"apps/{slug}/cottage.yml"
tpl, cot = open(tp).read(), open(cp).read()
if tpl.count(old_ref) < 1:
return f"{old_ref} not found in template.yml"
old_tag = old_ref.rpartition(":")[2]
rest = tpl.replace(old_ref, "").replace(version, "")
if cur in rest or old_tag in rest:
return "the old version is used elsewhere in template.yml"
tpl = tpl.replace(old_ref, new_ref).replace(f'version: "{version}"', f'version: "{new}-c1"')
pat = re.compile(r"(- ref: " + re.escape(old_ref) + r"\n\s+digest: )sha256:[0-9a-f]{64}")
if not pat.search(cot):
return "digest line not found in cottage.yml"
cot = pat.sub(lambda m: m.group(1) + digest, cot)
open(tp, "w").write(tpl)
open(cp, "w").write(cot)
return old_ref, new_ref, digest
def run(only=()):
now = datetime.now(timezone.utc)
sh("git", "fetch", "-q", "origin")
if not os.environ.get("DRY"):
for k in COOLDOWN_DAYS:
sh("gh", "label", "create", f"bump-{k}", "--color", "0e8a16", "--description", f"Automatic {k} update", check=False)
opened = 0
start = sh("git", "branch", "--show-current").stdout.strip()
for slug, cur, rel, k, t, images, version in candidates(only):
if k not in COOLDOWN_DAYS or "manual" in t:
if k in COOLDOWN_DAYS:
print(f"{slug}: {cur} -> {rel[0]} needs a person ({t['manual']})")
continue
new, tag, when = rel
if when:
age = (now - datetime.fromisoformat(when.replace("Z", "+00:00"))).days
if age < COOLDOWN_DAYS[k] and not os.environ.get("NO_COOLDOWN"):
print(f"{slug}: {new} is {age} days old, waiting for {COOLDOWN_DAYS[k]}")
continue
branch = f"bump/{slug}-{new}"
if not os.environ.get("DRY") and sh("gh", "pr", "list", "--state", "open", "--search", f"head:bump/{slug}-", "--json", "number").stdout.strip() != "[]":
print(f"{slug}: a bump pull request is already open")
continue
if not os.environ.get("DRY"):
sh("git", "switch", "-q", "-C", branch, "origin/main")
res = apply_bump(slug, cur, new, t, images, version)
if isinstance(res, str):
print(f"{slug}: {cur} -> {new} skipped, {res}")
sh("git", "checkout", "-q", "--", ".")
continue
old_ref, new_ref, digest = res
if os.environ.get("DRY"):
print(f"{slug}: would open an update to {new} ({old_ref} -> {new_ref})")
print(sh("git", "diff", "--stat").stdout)
sh("git", "checkout", "-q", "--", ".")
continue
sh("git", "add", f"apps/{slug}/template.yml", f"apps/{slug}/cottage.yml")
title = f"Update {slug} to {new}"
body = (f"Automatic {k} update from the bump bot.\n\n- {old_ref} -> {new_ref}\n- digest `{digest}`\n"
f"- release: https://github.com/{t['repo']}/releases/tag/{tag}" if t["source"] == "github" else
f"Automatic {k} update from the bump bot.\n\n- {old_ref} -> {new_ref}\n- digest `{digest}`")
sh("git", "commit", "-q", "-m", f"{title}\n\n{body}")
sh("git", "push", "-q", "-f", "origin", branch)
sh("gh", "pr", "create", "--base", "main", "--head", branch, "--title", title, "--body", body,
"--label", f"bump-{k}", check=False)
opened += 1
print(f"{slug}: opened {title}")
if start and not os.environ.get("DRY"):
sh("git", "switch", "-q", start, check=False)
print(f"{opened} pull requests opened")
# ---- guard -----------------------------------------------------------------------------------
def guard(base):
"""A bump branch may only change version lines, image tags and digests."""
files = sh("git", "diff", "--name-only", f"{base}...HEAD").stdout.split()
bad = [f for f in files if not re.fullmatch(r"apps/[^/]+/(template|cottage)\.yml", f)]
problems = [f"{f}: bump pull requests may only change template.yml and cottage.yml" for f in bad]
for f in files:
if f in bad:
continue
diff = sh("git", "diff", "-U0", f"{base}...HEAD", "--", f).stdout.splitlines()
minus = [l[1:] for l in diff if l.startswith("-") and not l.startswith("---")]
plus = [l[1:] for l in diff if l.startswith("+") and not l.startswith("+++")]
for a, b in zip(minus, plus):
if re.match(r'\s*version: "', a) and re.match(r'\s*version: "', b):
continue
if re.match(r"\s*digest: sha256:", a) and re.match(r"\s*digest: sha256:[0-9a-f]{64}$", b):
continue
ma = re.match(r"(\s*(?:- ref|image): )(\S+?):(\S+)$", a)
mb = re.match(r"(\s*(?:- ref|image): )(\S+?):(\S+)$", b)
if ma and mb and ma.group(2) == mb.group(2):
continue # same image repository, new tag
problems.append(f"{f}: unexpected change\n - {a.strip()}\n + {b.strip()}")
if len(minus) != len(plus):
problems.append(f"{f}: the change adds or removes lines")
print("\n".join(problems) or "bump only changes versions, tags and digests")
sys.exit(1 if problems else 0)
if __name__ == "__main__":
cmd, args = (sys.argv[1] if len(sys.argv) > 1 else ""), sys.argv[2:]
if cmd == "infer":
infer()
elif cmd == "audit":
audit(args)
elif cmd == "run":
run(args)
elif cmd == "guard" and args:
guard(args[0])
else:
sys.exit(__doc__)