Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 95 additions & 0 deletions .github/workflows/catalog-update.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
# Opens a catalogue pull request for each entry whose repo has a newer final release
# (tools/catalog.py updates): the entry written again from that release's zip, as add
# does. A bump of one entry is merged by the Catalogue auto-merge once the Catalogue
# check passes; anything else (a changed name, a new repo for the key) waits for a
# maintainer. Head units read the catalogue from main, so a merged bump reaches owners
# on their next catalogue check: no HMG-API release is needed.
#
# Hourly, from main. One branch per version (catalog-update/<id>-<version>): a version
# whose branch exists, open or closed by a maintainer, isn't opened again; a newer
# version closes the older one's pull request. The pull request is the Open-HMG
# catalogue app's (vars.CATALOG_APP_CLIENT_ID, secrets.CATALOG_APP_PRIVATE_KEY), so the
# Catalogue check runs on it: one opened with GITHUB_TOKEN starts no workflows.
name: Catalogue updates

on:
schedule:
- cron: "17 * * * *"
workflow_dispatch:

permissions: {}

concurrency:
group: catalog-update
cancel-in-progress: false

jobs:
update:
if: github.repository == 'Open-HMG/HMG-API'
runs-on: ubuntu-24.04
permissions:
contents: read
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: main
fetch-depth: 0
persist-credentials: false

- uses: actions/setup-java@77dd5b2ce225ea11469928ac317850245a74ae78 # v6.2.0
with:
distribution: temurin
java-version: "17"

- name: Newer releases
id: updates
env:
GH_TOKEN: ${{ github.token }}
run: |
python3 tools/catalog.py updates > "$RUNNER_TEMP/updates.txt"
cat "$RUNNER_TEMP/updates.txt"
{ echo '```'; cat "$RUNNER_TEMP/updates.txt"; echo '```'; } >> "$GITHUB_STEP_SUMMARY"
if [ -s "$RUNNER_TEMP/updates.txt" ]; then echo "any=1" >> "$GITHUB_OUTPUT"; fi

- uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0
id: app
if: steps.updates.outputs.any
with:
client-id: ${{ vars.CATALOG_APP_CLIENT_ID }}
private-key: ${{ secrets.CATALOG_APP_PRIVATE_KEY }}
permission-contents: write
permission-pull-requests: write

- name: A pull request for each
if: steps.app.outputs.token
env:
GH_TOKEN: ${{ github.token }}
APP_TOKEN: ${{ steps.app.outputs.token }}
run: |
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
while read -r id old new url <&3; do # fd 3: nothing in the loop can eat the list
case "$id $old $new" in *[!a-z0-9.\ -]*) echo "odd line: $id $old $new"; continue ;; esac
git checkout -q -f origin/main && git clean -fdq catalog maps # nothing left over from the mod before
branch="catalog-update/$id-$new"
if git ls-remote --exit-code --heads origin "$branch" > /dev/null; then echo "$id $new: $branch is there already"; continue; fi
git checkout -q -B "$branch" origin/main
if ! python3 tools/catalog.py updates --apply "$id"; then echo "$id $new: not written"; continue; fi
git add -A catalog maps
git commit -qm "Catalogue: $id $new" -m "From $url (tools/catalog.py updates)."
git push -q "https://x-access-token:${APP_TOKEN}@github.com/${GITHUB_REPOSITORY}.git" "HEAD:refs/heads/$branch"
# this mod's older version PRs: catalog-update/<this id>-<x.y.z> exactly (not <id>-2's)
GH_TOKEN=$APP_TOKEN gh pr list --repo "$GITHUB_REPOSITORY" --state open --base main --json number,headRefName \
--jq '.[] | "\(.number) \(.headRefName)"' | while read -r n ref; do
[ "$ref" != "$branch" ] || continue
v=${ref#catalog-update/$id-}
[ "$v" != "$ref" ] || continue
case "$v" in *[!0-9.]*|.*|*.|*..*) continue ;; *.*.*) ;; *) continue ;; esac
GH_TOKEN=$APP_TOKEN gh pr close "$n" --repo "$GITHUB_REPOSITORY" --delete-branch --comment "Replaced by $id $new."
done
printf '%s\n' "$id $old to $new, from its own repo's release: $url" "" \
"Opened by the Catalogue updates workflow (\`tools/catalog.py updates\`). If it only bumps the version, the Catalogue auto-merge merges it once the Catalogue check passes; otherwise it waits for a maintainer." \
> "$RUNNER_TEMP/body.md"
GH_TOKEN=$APP_TOKEN gh pr create --repo "$GITHUB_REPOSITORY" --base main --head "$branch" \
--title "Catalogue: $id $new" --body-file "$RUNNER_TEMP/body.md"
done 3< "$RUNNER_TEMP/updates.txt"
4 changes: 3 additions & 1 deletion docs/mod-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -558,7 +558,9 @@ that is newer than what's installed, in the Updates tab, saying where it came fr
- Only your key updates your mod: a release signed with another key, a zip whose
`mod.json` isn't the tag's id and version, or one over 64 MB is never taken.

For a listed mod the catalogue stays the source; the owner can choose its releases
For a listed mod the catalogue stays the source. It follows your releases by itself:
HMG-API's Catalogue updates workflow opens the version bump for each new final release
within the hour, and it merges itself once CI passes. The owner can choose its releases
instead (a test build from a fork), or turn updates off, on the mod's page
(`hmgapid engine update-source <id> catalogue | releases | off | default`).
HMG-API's maintainers can stop a version for both sources in `catalog/withdrawn.json`.
Expand Down
2 changes: 1 addition & 1 deletion docs/releasing.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ alongside core 1.1.0-rc.1).
|---|---|---|---|
| core final | published, **Latest** (unless it's a hotfix to an older line) | — | — |
| core alpha, beta, rc | published as a **pre-release**, never Latest | — | — |
| mod final | published in the mod's repo | **yes**: the catalogue PR (`tools/catalog.py add`, printed by the release run) | by the next core release, through its catalogue entry |
| mod final | published in the mod's repo | **yes**: the first listing is a catalogue PR (`tools/catalog.py add`, printed by the release run); each later final is opened within the hour by the Catalogue updates workflow (`tools/catalog.py updates`) and auto-merged as a bump | by the next core release, through its catalogue entry |
| mod alpha, beta, rc | published as a pre-release in the mod's repo | **no**: `catalog.py` refuses pre-releases | only by a core pre-release, pinned in `tools/release-mods.txt` |
| core test build | published as a **pre-release** `test-<name>`, never Latest (below) | — | — |

Expand Down
51 changes: 51 additions & 0 deletions tools/catalog-test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -237,4 +237,55 @@ has "... an id" 'entry 2 has no mod "id"' "$out"
has "... a readable range" 'x: "versions"' "$out"
rm $R/catalog/withdrawn.json

# updates (the Catalogue updates workflow): GitHub's releases API from $T/api, downloads from $T/dl
G checkout -q -- .
U() { set +e; out=$(python3 - "$T" $R/tools/catalog.py "$@" 2>&1 <<'P'
import os, runpy, sys, urllib.request
t = sys.argv[1]
def get(req, timeout=None):
u = req.full_url
if u.startswith('https://api.github.com/repos/'):
p = u.split('?')[0].split('/')
return open(os.path.join(t, 'api', p[4] + '_' + p[5] + '.json'), 'rb')
return open(os.path.join(t, 'dl', u.rsplit('/', 1)[1]), 'rb')
urllib.request.urlopen = get
sys.argv = sys.argv[2:]
runpy.run_path(sys.argv[0], run_name='__main__')
P
); rc=$?; set -e; }
UD=https://github.com/example/hello/releases/download/v1.1.0/hello-1.1.0.zip
rels() { # <asset name for v1.1.0>: the repo's releases, newest first (a pre-release, 1.1.0, 1.0.0)
mkdir -p $T/api; cat > $T/api/example_hello.json <<J
[{"tag_name": "v1.2.0-rc.1", "prerelease": true, "assets": [{"name": "hello-1.2.0-rc.1.zip", "browser_download_url": "https://github.com/example/hello/releases/download/v1.2.0-rc.1/hello-1.2.0-rc.1.zip"}]},
{"tag_name": "v1.1.0", "prerelease": false, "assets": [{"name": "$1", "browser_download_url": "https://github.com/example/hello/releases/download/v1.1.0/$1"}]},
{"tag_name": "v1.0.0", "prerelease": false, "assets": []}]
J
}
rels hello-1.1.0.zip
U updates; check "updates" 0 $rc; check "... the newer final release, not the pre-release" "hello 1.0.0 1.1.0 $UD" "$out"
echo '{"withdrawn": [{"id": "hello", "versions": ">=1.1.0 <1.2.0", "why": "breaks things"}]}' > $R/catalog/withdrawn.json
U updates; check "updates: a withdrawn version skipped" "" "$out"
rm $R/catalog/withdrawn.json
rels other.zip
U updates; check "updates: no zip of the mod in the release" 0 $rc; has "... says so" "hello 1.1.0: the release has no zip named hello-1.1.0.zip or hello-v1.1.0.zip" "$out"
rels hello-1.1.0.zip
G checkout -qb up1; cp $T/h2.zip $T/dl/hello-1.1.0.zip
U updates --apply hello; check "updates --apply" 0 $rc
check "... the entry is the release" "1.1.0 $UD $(sha256sum $T/h2.zip | cut -d' ' -f1)" "$(python3 -c 'import json,sys; e=json.load(open(sys.argv[1])); print(e["version"], e["download"], e["sha256"])' $R/catalog/hello.json)"
B update; check "... and is a version bump (the auto-merge takes it)" 0 $rc
G checkout -q main; cp $T/hb2.zip $T/dl/hello-1.1.0.zip
U updates --apply hello; check "updates --apply: a zip by another key refused" 1 $rc; has "... says why" "signed with $UB" "$out"
G checkout -q -- .
echo '[{"tag_name": "v1.0.0", "assets": []}]' > $T/api/example_hello.json
U updates --apply hello; check "updates --apply: nothing newer" 1 $rc; has "... says so" "hello: no newer release to write" "$out"
python3 - $R/tools/catalog.py <<'P' && echo "ok updates: version ranges as the engine reads them" || { echo "FAIL updates: version ranges"; fail=1; }
import runpy, sys
s = runpy.run_path(sys.argv[1])['satisfies']
for v, r, want in [('1.1.0', '^1.0.0', True), ('2.0.0', '^1.0.0', False), ('0.3.1', '^0.3', True), ('0.4.0', '^0.3', False),
('1.2.5', '~1.2.0', True), ('1.3.0', '~1.2.0', False), ('1.1.0', '>=1.0.0 <1.1.0', False),
('1.0.5', '>=1.0.0 <1.1.0', True), ('1.1.0', '1.1.0', True), ('1.1.1', '=1.1.0', False), ('1.1.0', '*', True),
('1.1.0', 'v1.1', True), ('1.0.9', '>1.0', True), ('1.0.0', '<=1', True)]:
assert s(v, r) == want, (v, r, want)
P

[ $fail = 0 ] && echo "catalog: all ok" || { echo "catalog: FAILED"; exit 1; }
110 changes: 109 additions & 1 deletion tools/catalog.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@
A list line "<id> <version> <url> <sha256>" pins a pre-release of a catalogue
mod instead, for a HMG-API pre-release only: from the entry's repo's releases,
newer than the entry, signed with the entry's author key
tools/catalog.py updates [--apply <id>]
each entry whose repo has a newer final release: "<id> <old> <new> <download>"
lines (the zip named as the entry's download, or <id>-<version>.zip /
<id>-v<version>.zip; withdrawn versions skipped). --apply writes that entry from
the release's zip, as add does: the Catalogue updates workflow opens it as a bump
tools/catalog.py wiki <out.md>
the Community mods page
tools/catalog.py index [<out>]
Expand Down Expand Up @@ -630,6 +635,107 @@ def cmd_wiki(a):
print(f'{a.out}: {len(es)} mods')


# ---- updates (the Catalogue updates workflow: a version bump pull request for each newer release)


def satisfies(v, r):
"""version v is in range r, as hmgapi.engine.Version.satisfies reads it"""
def full(x):
x = x[1:] if x[:1] == 'v' else x
m = re.match(r'^(\d+)(?:\.(\d+))?(?:\.(\d+))?(.*)$', x)
return f'{m[1]}.{m[2] or 0}.{m[3] or 0}{m[4]}' if m else x
r = (r or '').strip()
if r in ('', '*'):
return True
v = full(v)
have = vkey(v)
for c in r.split():
op = c[:2] if c[:2] in ('>=', '<=') else c[:1] if c[:1] in ('<', '>', '=', '^', '~') else ''
w = full(c[len(op):])
want = vkey(w)
cmp = (have > want) - (have < want)
hn, wn = [int(x) for x in v.split('.')[:2]], [int(re.match(r'\d+', x)[0]) for x in w.split('.')[:2]]
ok = {'>=': cmp >= 0, '<=': cmp <= 0, '>': cmp > 0, '<': cmp < 0, '=': cmp == 0, '': cmp == 0}.get(op)
if ok is None: # ^ and ~: at least want, and the same major (^; minor too under 1.0) or major.minor (~)
same = (hn[0] == 0 and hn[1] == wn[1]) if op == '^' and wn[0] == 0 else hn[0] == wn[0]
ok = cmp >= 0 and same and (op == '^' or hn[1] == wn[1])
if not ok:
return False
return True


def github_json(url):
h = {'User-Agent': 'HMG-API catalog updates', 'Accept': 'application/vnd.github+json'}
token = os.environ.get('GH_TOKEN') or os.environ.get('GITHUB_TOKEN')
if token:
h['Authorization'] = 'Bearer ' + token
with urllib.request.urlopen(urllib.request.Request(url, headers=h), timeout=60) as r:
return json.load(r)


def newer_release(n, e, withdrawn):
"""the newest final release of entry e's repo that is newer than e and not withdrawn:
((version, zip url), None), (None, None) when there is none, or (None, why)"""
m = re.match(r'^https://github\.com/([A-Za-z0-9._-]+)/([A-Za-z0-9._-]+?)(?:\.git)?/?$', str(e.get('repo', '')))
if not m:
return None, f'{n}: its repo {e.get("repo")} isn\'t a GitHub repository'
try:
rels = github_json(f'https://api.github.com/repos/{m[1]}/{m[2]}/releases?per_page=20')
except Exception as x:
return None, f'{n}: {m[1]}/{m[2]}\'s releases: {x}'
best = None
for rel in rels if isinstance(rels, list) else []:
if not isinstance(rel, dict) or rel.get('draft') or rel.get('prerelease'):
continue
v = str(rel.get('tag_name', ''))
v = v[1:] if v[:1] == 'v' else v
if not FINAL.match(v) or vkey(v) <= vkey(e['version']):
continue
if any(isinstance(w, dict) and w.get('id') == n and satisfies(v, str(w.get('versions', ''))) for w in withdrawn):
continue
if best is None or vkey(v) > vkey(best[0]):
best = (v, rel)
if best is None:
return None, None
v, rel = best
assets = {str(x.get('name')): x.get('browser_download_url') for x in rel.get('assets') or [] if isinstance(x, dict)}
old = str(e.get('download', '')).rsplit('/', 1)[-1]
names = list(dict.fromkeys(([old.replace(e['version'], v)] if e['version'] in old else []) + [f'{n}-{v}.zip', f'{n}-v{v}.zip']))
for x in names:
if assets.get(x):
return (v, assets[x]), None
return None, f'{n} {v}: the release has no zip named {" or ".join(names)}'


def cmd_updates(a):
w = load(WITHDRAWN) if os.path.exists(WITHDRAWN) else {}
w = (w.get('withdrawn') if isinstance(w, dict) else w) or []
es = entries()
if a.apply and a.apply not in es:
die(f'{a.apply}: not in the catalogue')
for n in [a.apply] if a.apply else sorted(es):
got, why = newer_release(n, es[n], w)
if why:
print('skip ' + why, file=sys.stderr)
if not got:
if a.apply:
die(f'{n}: no newer release to write')
continue
v, url = got
if not a.apply:
print(f'{n} {es[n]["version"]} {v} {url}')
continue
if not HTTPS.match(url) or host(url) not in GITHUB:
die(f'{n} {v}: {url} isn\'t a GitHub download')
work = tempfile.mkdtemp(prefix='catalog-update-')
try:
z = os.path.join(work, f'{n}-{v}.zip')
fetch(url, z)
cmd_add(argparse.Namespace(zip=z, download=url, repo=es[n]['repo']))
finally:
shutil.rmtree(work, ignore_errors=True)


def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
sub = ap.add_subparsers(dest='cmd', required=True)
Expand All @@ -647,6 +753,8 @@ def main():
s.add_argument('dir')
s.add_argument('ids', nargs='*')
s.add_argument('--list', help='the ids (and pre-release pins) from this file, e.g. tools/release-mods.txt')
s = sub.add_parser('updates')
s.add_argument('--apply', metavar='ID', help='write this entry from its newer release (as add does)')
s = sub.add_parser('wiki')
s.add_argument('out')
s = sub.add_parser('index')
Expand All @@ -658,7 +766,7 @@ def main():
die(f'--download is on {host(a.download)}: the head unit only downloads from GitHub ({", ".join(sorted(GITHUB))})')
if a.cmd == 'add' and a.repo and not HTTPS.match(a.repo):
die('--repo is an https:// link')
{'add': cmd_add, 'check': cmd_check, 'bump': cmd_bump, 'fetch': cmd_fetch, 'wiki': cmd_wiki, 'index': cmd_index}[a.cmd](a)
{'add': cmd_add, 'check': cmd_check, 'bump': cmd_bump, 'fetch': cmd_fetch, 'wiki': cmd_wiki, 'index': cmd_index, 'updates': cmd_updates}[a.cmd](a)
if _engine and _engine != os.environ.get('HMGAPI_ENGINE_CLASSES'): # ours, not the caller's
shutil.rmtree(_engine, ignore_errors=True)

Expand Down
7 changes: 6 additions & 1 deletion wiki/Making-mods.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,12 @@ a HMG-API release carries the list).
3. Open the pull request with both files. CI downloads the zip and checks that its
SHA-256, signature, id and version match the entry.

A new version is the same steps with the new zip: the entry's author key can't
A new version needs no pull request from you. Tag it `vX.Y.Z` in your repo and attach
the zip named as the listed one (or `my-mod-X.Y.Z.zip`): within the hour HMG-API's
Catalogue updates workflow opens the bump, and it merges itself once CI passes if only
the version changed. Head units read the catalogue as it is on HMG-API's main, so
owners see it on their next catalogue check, without a HMG-API release. You can still
open the bump yourself (the same steps with the new zip). The entry's author key can't
change (only your key updates your mod), and its version can't go back. A pull
request changes only its own author's entry in the trusted list. Listing means the
package is whole and signed by you; the maintainer reviews each new author before
Expand Down
Loading