detached 2593286

#1 feat(release): mirror ermite releases to GitHub as link-only releases

state
merged · 2593286 · fast-forward
branch
feat/ermite-release-mirror → main
opened
bnema ·
updated

Reusable ermite-release-mirror.yml: link-only GitHub releases built from the ermite release (notes + Downloads table). Uses only the job's GITHUB_TOKEN.

CommitSubjectAuthorDateSignatureStatus
2593286feat(release): mirror ermite releases to GitHub as link-only releasesbrice GPG Verified

Checks 0

no checks

1 file · +162 -0
no checks
A .github/workflows/ermite-release-mirror.yml +162 -0
@@ -0,0 +1,162 @@
1+# Publishes a link-only GitHub release for a release hosted on ermite.
2+#
3+# The caller runs on the GitHub mirror when a tag arrives. This workflow reads
4+# the ermite release through its public GitHub-compatible API, copies its
5+# notes, and appends a Downloads table that links to the ermite assets. No file
6+# is uploaded to GitHub and no token other than the job's GITHUB_TOKEN is used.
7+#
8+# Caller (.github/workflows/github-release.yml):
9+#
10+# on:
11+# push:
12+# tags: ['v*']
13+# workflow_dispatch:
14+# inputs:
15+# tag: {description: 'Tag to mirror', required: true, type: string}
16+# permissions:
17+# contents: write
18+# jobs:
19+# release:
20+# if: github.server_url == 'https://github.com'
21+# uses: bnema/gh-actions/.github/workflows/ermite-release-mirror.yml@main
22+# with:
23+# tag: ${{ inputs.tag }}
24+name: Ermite Release Mirror
25+
26+on:
27+ workflow_call:
28+ inputs:
29+ tag:
30+ description: 'Tag to mirror (default: the pushed tag)'
31+ type: string
32+ default: ''
33+ repository:
34+ description: 'Repository name on ermite (default: the GitHub repository name)'
35+ type: string
36+ default: ''
37+ forge:
38+ description: 'ermite base URL'
39+ type: string
40+ default: 'https://git.bnema.dev'
41+ owner:
42+ description: 'Owner segment of the ermite GitHub-compatible API'
43+ type: string
44+ default: 'bnema'
45+ wait-minutes:
46+ description: 'How long to wait for the ermite release to be published'
47+ type: number
48+ default: 30
49+
50+permissions:
51+ contents: write
52+
53+jobs:
54+ mirror:
55+ name: Mirror release
56+ runs-on: ubuntu-latest
57+ permissions:
58+ contents: write
59+ timeout-minutes: 45
60+ steps:
61+ - name: Build the release notes from ermite
62+ id: notes
63+ env:
64+ INPUT_TAG: ${{ inputs.tag }}
65+ INPUT_REPOSITORY: ${{ inputs.repository }}
66+ FORGE: ${{ inputs.forge }}
67+ OWNER: ${{ inputs.owner }}
68+ WAIT_MINUTES: ${{ inputs.wait-minutes }}
69+ shell: python
70+ run: |
71+ import json, os, re, sys, time, urllib.error, urllib.request
72+
73+ tag = os.environ["INPUT_TAG"] or os.environ["GITHUB_REF_NAME"]
74+ repo = os.environ["INPUT_REPOSITORY"] or os.environ["GITHUB_REPOSITORY"].split("/", 1)[1]
75+ forge = os.environ["FORGE"].rstrip("/")
76+ owner = os.environ["OWNER"]
77+ for name, value in (("tag", tag), ("repository", repo), ("owner", owner)):
78+ if not re.fullmatch(r"[A-Za-z0-9._+-]+", value):
79+ sys.exit(f"invalid {name}: {value!r}")
80+ if not re.fullmatch(r"https://[A-Za-z0-9.-]+(:[0-9]+)?", forge):
81+ sys.exit(f"forge must be an https origin, got {forge!r}")
82+
83+ url = f"{forge}/-/github/api/repos/{owner}/{repo}/releases/tags/{tag}"
84+ deadline = time.monotonic() + float(os.environ["WAIT_MINUTES"]) * 60
85+ while True:
86+ try:
87+ req = urllib.request.Request(url, headers={"Accept": "application/vnd.github+json"})
88+ with urllib.request.urlopen(req, timeout=30) as resp:
89+ release = json.load(resp)
90+ if not release.get("draft"):
91+ break
92+ reason = "still a draft"
93+ except urllib.error.HTTPError as err:
94+ if err.code != 404:
95+ raise
96+ reason = "not published yet"
97+ if time.monotonic() > deadline:
98+ sys.exit(f"ermite release {repo} {tag} {reason} after waiting; re-run this job once it is published")
99+ print(f"ermite release {tag} {reason}, retrying in 30s", flush=True)
100+ time.sleep(30)
101+
102+ def size(n):
103+ for unit in ("B", "KB", "MB", "GB"):
104+ if n < 1024 or unit == "GB":
105+ return f"{n:.0f} {unit}" if unit == "B" else f"{n:.1f} {unit}"
106+ n /= 1024
107+
108+ # GitHub marks as latest only the release ermite marks as latest.
109+ latest = False
110+ try:
111+ req = urllib.request.Request(f"{forge}/-/github/api/repos/{owner}/{repo}/releases/latest",
112+ headers={"Accept": "application/vnd.github+json"})
113+ with urllib.request.urlopen(req, timeout=30) as resp:
114+ latest = json.load(resp).get("tag_name") == tag
115+ except urllib.error.HTTPError as err:
116+ if err.code != 404:
117+ raise
118+
119+ page = release.get("html_url") or f"{forge}/{repo}/releases/tag/{tag}"
120+ lines = [(release.get("body") or "").rstrip(), "", "## Downloads", ""]
121+ lines.append(f"This project is developed on [ermite]({forge}/{repo}). "
122+ f"Release files are hosted there: {page}")
123+ assets = sorted(release.get("assets") or [], key=lambda a: a["name"])
124+ if assets:
125+ lines += ["", "| File | Size |", "|---|---|"]
126+ for a in assets:
127+ link = a["browser_download_url"]
128+ if not link.startswith(forge + "/"):
129+ sys.exit(f"asset URL outside {forge}: {link}")
130+ name = a["name"].replace("|", "\\|")
131+ lines.append(f"| [{name}]({link}) | {size(a.get('size') or 0)} |")
132+ notes = "\n".join(lines).lstrip() + "\n"
133+
134+ runner_temp = os.environ["RUNNER_TEMP"]
135+ with open(os.path.join(runner_temp, "notes.md"), "w") as f:
136+ f.write(notes)
137+ with open(os.environ["GITHUB_OUTPUT"], "a") as f:
138+ f.write(f"tag={tag}\n")
139+ f.write(f"title={release.get('name') or tag}\n")
140+ f.write(f"prerelease={'true' if release.get('prerelease') else 'false'}\n")
141+ f.write(f"latest={'true' if latest else 'false'}\n")
142+ print(notes)
143+
144+ - name: Create or update the GitHub release
145+ env:
146+ GH_TOKEN: ${{ github.token }}
147+ GH_REPO: ${{ github.repository }}
148+ TAG: ${{ steps.notes.outputs.tag }}
149+ TITLE: ${{ steps.notes.outputs.title }}
150+ PRERELEASE: ${{ steps.notes.outputs.prerelease }}
151+ LATEST: ${{ steps.notes.outputs.latest }}
152+ run: |
153+ set -euo pipefail
154+ notes="$RUNNER_TEMP/notes.md"
155+ flags=(--title "$TITLE" --notes-file "$notes" "--prerelease=$PRERELEASE" "--latest=$LATEST")
156+ if gh release view "$TAG" >/dev/null 2>&1; then
157+ gh release edit "$TAG" "${flags[@]}" --draft=false
158+ else
159+ gh release create "$TAG" "${flags[@]}" --verify-tag
160+ fi
161+ gh release view "$TAG" --json url,isPrerelease,assets \
162+ --jq '{url, isPrerelease, assets: (.assets | length)}'
@@ -0,0 +1,162 @@
1+# Publishes a link-only GitHub release for a release hosted on ermite.
2+#
3+# The caller runs on the GitHub mirror when a tag arrives. This workflow reads
4+# the ermite release through its public GitHub-compatible API, copies its
5+# notes, and appends a Downloads table that links to the ermite assets. No file
6+# is uploaded to GitHub and no token other than the job's GITHUB_TOKEN is used.
7+#
8+# Caller (.github/workflows/github-release.yml):
9+#
10+# on:
11+# push:
12+# tags: ['v*']
13+# workflow_dispatch:
14+# inputs:
15+# tag: {description: 'Tag to mirror', required: true, type: string}
16+# permissions:
17+# contents: write
18+# jobs:
19+# release:
20+# if: github.server_url == 'https://github.com'
21+# uses: bnema/gh-actions/.github/workflows/ermite-release-mirror.yml@main
22+# with:
23+# tag: ${{ inputs.tag }}
24+name: Ermite Release Mirror
25+
26+on:
27+ workflow_call:
28+ inputs:
29+ tag:
30+ description: 'Tag to mirror (default: the pushed tag)'
31+ type: string
32+ default: ''
33+ repository:
34+ description: 'Repository name on ermite (default: the GitHub repository name)'
35+ type: string
36+ default: ''
37+ forge:
38+ description: 'ermite base URL'
39+ type: string
40+ default: 'https://git.bnema.dev'
41+ owner:
42+ description: 'Owner segment of the ermite GitHub-compatible API'
43+ type: string
44+ default: 'bnema'
45+ wait-minutes:
46+ description: 'How long to wait for the ermite release to be published'
47+ type: number
48+ default: 30
49+
50+permissions:
51+ contents: write
52+
53+jobs:
54+ mirror:
55+ name: Mirror release
56+ runs-on: ubuntu-latest
57+ permissions:
58+ contents: write
59+ timeout-minutes: 45
60+ steps:
61+ - name: Build the release notes from ermite
62+ id: notes
63+ env:
64+ INPUT_TAG: ${{ inputs.tag }}
65+ INPUT_REPOSITORY: ${{ inputs.repository }}
66+ FORGE: ${{ inputs.forge }}
67+ OWNER: ${{ inputs.owner }}
68+ WAIT_MINUTES: ${{ inputs.wait-minutes }}
69+ shell: python
70+ run: |
71+ import json, os, re, sys, time, urllib.error, urllib.request
72+
73+ tag = os.environ["INPUT_TAG"] or os.environ["GITHUB_REF_NAME"]
74+ repo = os.environ["INPUT_REPOSITORY"] or os.environ["GITHUB_REPOSITORY"].split("/", 1)[1]
75+ forge = os.environ["FORGE"].rstrip("/")
76+ owner = os.environ["OWNER"]
77+ for name, value in (("tag", tag), ("repository", repo), ("owner", owner)):
78+ if not re.fullmatch(r"[A-Za-z0-9._+-]+", value):
79+ sys.exit(f"invalid {name}: {value!r}")
80+ if not re.fullmatch(r"https://[A-Za-z0-9.-]+(:[0-9]+)?", forge):
81+ sys.exit(f"forge must be an https origin, got {forge!r}")
82+
83+ url = f"{forge}/-/github/api/repos/{owner}/{repo}/releases/tags/{tag}"
84+ deadline = time.monotonic() + float(os.environ["WAIT_MINUTES"]) * 60
85+ while True:
86+ try:
87+ req = urllib.request.Request(url, headers={"Accept": "application/vnd.github+json"})
88+ with urllib.request.urlopen(req, timeout=30) as resp:
89+ release = json.load(resp)
90+ if not release.get("draft"):
91+ break
92+ reason = "still a draft"
93+ except urllib.error.HTTPError as err:
94+ if err.code != 404:
95+ raise
96+ reason = "not published yet"
97+ if time.monotonic() > deadline:
98+ sys.exit(f"ermite release {repo} {tag} {reason} after waiting; re-run this job once it is published")
99+ print(f"ermite release {tag} {reason}, retrying in 30s", flush=True)
100+ time.sleep(30)
101+
102+ def size(n):
103+ for unit in ("B", "KB", "MB", "GB"):
104+ if n < 1024 or unit == "GB":
105+ return f"{n:.0f} {unit}" if unit == "B" else f"{n:.1f} {unit}"
106+ n /= 1024
107+
108+ # GitHub marks as latest only the release ermite marks as latest.
109+ latest = False
110+ try:
111+ req = urllib.request.Request(f"{forge}/-/github/api/repos/{owner}/{repo}/releases/latest",
112+ headers={"Accept": "application/vnd.github+json"})
113+ with urllib.request.urlopen(req, timeout=30) as resp:
114+ latest = json.load(resp).get("tag_name") == tag
115+ except urllib.error.HTTPError as err:
116+ if err.code != 404:
117+ raise
118+
119+ page = release.get("html_url") or f"{forge}/{repo}/releases/tag/{tag}"
120+ lines = [(release.get("body") or "").rstrip(), "", "## Downloads", ""]
121+ lines.append(f"This project is developed on [ermite]({forge}/{repo}). "
122+ f"Release files are hosted there: {page}")
123+ assets = sorted(release.get("assets") or [], key=lambda a: a["name"])
124+ if assets:
125+ lines += ["", "| File | Size |", "|---|---|"]
126+ for a in assets:
127+ link = a["browser_download_url"]
128+ if not link.startswith(forge + "/"):
129+ sys.exit(f"asset URL outside {forge}: {link}")
130+ name = a["name"].replace("|", "\\|")
131+ lines.append(f"| [{name}]({link}) | {size(a.get('size') or 0)} |")
132+ notes = "\n".join(lines).lstrip() + "\n"
133+
134+ runner_temp = os.environ["RUNNER_TEMP"]
135+ with open(os.path.join(runner_temp, "notes.md"), "w") as f:
136+ f.write(notes)
137+ with open(os.environ["GITHUB_OUTPUT"], "a") as f:
138+ f.write(f"tag={tag}\n")
139+ f.write(f"title={release.get('name') or tag}\n")
140+ f.write(f"prerelease={'true' if release.get('prerelease') else 'false'}\n")
141+ f.write(f"latest={'true' if latest else 'false'}\n")
142+ print(notes)
143+
144+ - name: Create or update the GitHub release
145+ env:
146+ GH_TOKEN: ${{ github.token }}
147+ GH_REPO: ${{ github.repository }}
148+ TAG: ${{ steps.notes.outputs.tag }}
149+ TITLE: ${{ steps.notes.outputs.title }}
150+ PRERELEASE: ${{ steps.notes.outputs.prerelease }}
151+ LATEST: ${{ steps.notes.outputs.latest }}
152+ run: |
153+ set -euo pipefail
154+ notes="$RUNNER_TEMP/notes.md"
155+ flags=(--title "$TITLE" --notes-file "$notes" "--prerelease=$PRERELEASE" "--latest=$LATEST")
156+ if gh release view "$TAG" >/dev/null 2>&1; then
157+ gh release edit "$TAG" "${flags[@]}" --draft=false
158+ else
159+ gh release create "$TAG" "${flags[@]}" --verify-tag
160+ fi
161+ gh release view "$TAG" --json url,isPrerelease,assets \
162+ --jq '{url, isPrerelease, assets: (.assets | length)}'

Comments00 unresolved

    no comments yet.

    Keyboard shortcuts

    Single-key shortcuts are on. ctrl k and esc work whatever this says.

    ctrl k :
    go to a section, branch, tag, file or repository
    ?
    this list
    j k
    move the row cursor down / up
    enter
    open the row under the cursor; on Files, a directory opens or closes in place
    ↑ ↓ ← → home end
    in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
    l h
    on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. On pages with a side panel: into the panel (on a merge request, its files) / back to the content; there j k move between its controls
    g g G
    first / last row
    /
    filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
    b
    switch branch or tag
    g s g f g c g b g m g i g r g a
    tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
    g h
    home
    w
    wide mode: use the whole width of the screen, or not (remembered)
    y
    copy a permalink pinned to the commit; in a file, click a line number to select it, shift-click for a range
    d u x
    diff: split / unified / collapse or expand all
    e E
    diff: the whole file in view / every file, with the lines the hunks hide
    n
    merge request: next note in the diff
    l
    merge request: the list of files (j k move, enter opens, esc back)
    M
    merge request: the merge menu; there 1–3 pick the mode, D deletes the branch, enter merges
    R
    merge request: mark the head read
    esc
    close a dialog, leave a field

    Branches 1

    Tags 0

      ↑↓ moveenter openesc close