-
Notifications
You must be signed in to change notification settings - Fork 0
327 lines (295 loc) · 11.7 KB
/
Copy pathrelease.yml
File metadata and controls
327 lines (295 loc) · 11.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
name: Release
on:
workflow_dispatch:
inputs:
bump:
description: "Which part of the semver to bump"
required: true
type: choice
options:
- patch
- minor
- major
default: patch
permissions:
contents: write
packages: write
concurrency:
group: release
cancel-in-progress: false
jobs:
prepare:
name: Prepare release
runs-on: ubuntu-latest
outputs:
version: ${{ steps.version.outputs.version }}
current: ${{ steps.version.outputs.current }}
last_tag: ${{ steps.commits.outputs.last_tag }}
steps:
- name: Generate rheo-app token
id: app-token
uses: actions/create-github-app-token@v1
with:
app-id: ${{ secrets.RHEO_APP_ID }}
private-key: ${{ secrets.RHEO_APP_PRIVATE_KEY }}
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
fetch-tags: true
token: ${{ steps.app-token.outputs.token }}
- name: Set up Java
uses: actions/setup-java@v4
with:
java-version: '21'
distribution: 'temurin'
cache: 'maven'
- name: Compute next version
id: version
env:
BUMP: ${{ inputs.bump }}
run: |
set -euo pipefail
CURRENT=$(mvn -B -q -DforceStdout help:evaluate -Dexpression=project.version)
if [ -z "$CURRENT" ]; then
echo "::error::Failed to read current version from pom.xml"
exit 1
fi
VERSION=$(npx --yes --package=semver -- semver -i "$BUMP" "$CURRENT")
if [ -z "$VERSION" ]; then
echo "::error::Failed to bump '$CURRENT' with '$BUMP' (not a valid semver?)"
exit 1
fi
if git rev-parse "v${VERSION}" >/dev/null 2>&1; then
echo "::error::Tag v${VERSION} already exists"
exit 1
fi
echo "version=${VERSION}" >> "$GITHUB_OUTPUT"
echo "current=${CURRENT}" >> "$GITHUB_OUTPUT"
- name: Collect commits since last tag
id: commits
run: |
set -euo pipefail
LAST_TAG=$(git describe --tags --abbrev=0 2>/dev/null || echo "")
if [ -z "$LAST_TAG" ]; then
echo "No previous tag found; using full history."
COMMITS=$(git log --pretty=format:"- %s (%h)")
else
echo "Collecting commits in ${LAST_TAG}..HEAD"
COMMITS=$(git log "${LAST_TAG}..HEAD" --pretty=format:"- %s (%h)")
fi
echo "last_tag=${LAST_TAG}" >> "$GITHUB_OUTPUT"
# Store multi-line value in GITHUB_ENV for the next step
{
echo 'GIT_COMMITS<<GIT_COMMITS_EOF'
echo "$COMMITS"
echo 'GIT_COMMITS_EOF'
} >> "$GITHUB_ENV"
- name: Generate changelog entry with Gemini
env:
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
GEMINI_MODEL: ${{ vars.GEMINI_MODEL }}
VERSION: ${{ steps.version.outputs.version }}
run: |
python3 - <<'PY'
import json, os, re, sys, time, urllib.error, urllib.request
from datetime import date
from pathlib import Path
version = os.environ["VERSION"]
api_key = os.environ["GEMINI_API_KEY"]
model = os.environ.get("GEMINI_MODEL") or "gemini-2.5-flash"
commits = os.environ.get("GIT_COMMITS", "").strip()
today = date.today().strftime("%Y-%m-%d")
# Extract [Unreleased] section directly from CHANGELOG — no temp file
changelog = Path("CHANGELOG.md").read_text()
m = re.search(r"## \[Unreleased\][^\n]*\n(.*?)(?=\n## \[|\Z)", changelog, re.DOTALL)
unreleased = m.group(1).strip() if m else ""
unreleased_section = (
f"Curated [Unreleased] notes (incorporate these — do not duplicate):\n{unreleased}\n\n"
if unreleased else ""
)
prompt = (
f"You are generating a release changelog entry for the Rhesis Java SDK, "
f"following the Keep a Changelog format (https://keepachangelog.com/en/1.0.0/).\n\n"
f"Version: {version}\nDate: {today}\n\n"
f"{unreleased_section}"
f"Commits since last release:\n{commits}\n\n"
f"Requirements:\n"
f'- Start the entry with the exact header "## [{version}] - {today}".\n'
f"- Group bullets under \"### Added\", \"### Changed\", \"### Fixed\", "
f"\"### Removed\", \"### Deprecated\", \"### Security\" as appropriate. "
f"Omit any empty section.\n"
f"- Write concise, user-facing bullets. Collapse related commits and any "
f"curated [Unreleased] notes into a single unified entry. Drop purely internal "
f"noise (formatting, CI tweaks, version bumps) unless significant.\n"
f"- Use backticks around code identifiers (classes, methods, files).\n"
f"- Output ONLY the markdown for the new entry. No preamble, no trailing "
f"commentary, no code fences."
)
payload = json.dumps({"contents": [{"parts": [{"text": prompt}]}]}).encode()
url = (
f"https://generativelanguage.googleapis.com/v1beta/models/"
f"{model}:generateContent?key={api_key}"
)
entry = ""
for attempt in range(1, 5):
try:
req = urllib.request.Request(
url, data=payload, headers={"Content-Type": "application/json"}
)
with urllib.request.urlopen(req, timeout=60) as resp:
data = json.load(resp)
entry = data["candidates"][0]["content"]["parts"][0]["text"].strip()
break
except urllib.error.HTTPError as exc:
if exc.code not in (429, 500, 502, 503, 504) or attempt == 4:
body = exc.read().decode(errors="replace")
print(f"::error::Gemini HTTP {exc.code}:\n{body}", file=sys.stderr)
sys.exit(1)
sleep = 2 ** attempt
print(f"Gemini returned HTTP {exc.code} on attempt {attempt}, retrying in {sleep}s...")
time.sleep(sleep)
if not entry:
print("::error::Gemini returned an empty changelog entry", file=sys.stderr)
sys.exit(1)
# Strip accidental code fences
m = re.match(r"^```(?:markdown)?\s*\n(.*?)\n```$", entry, re.DOTALL)
if m:
entry = m.group(1).strip()
if not re.search(rf"^## \[{re.escape(version)}\]", entry, re.MULTILINE):
print(
f"::error::Generated entry does not start with '## [{version}]':\n{entry}",
file=sys.stderr,
)
sys.exit(1)
# Only file written — required for the cross-job artifact
Path("/tmp/entry.md").write_text(entry)
print(f"Changelog entry written ({len(entry)} chars).")
PY
- name: Upload changelog entry
uses: actions/upload-artifact@v4
with:
name: release-entry
path: /tmp/entry.md
retention-days: 7
- name: Write approval summary
env:
CURRENT: ${{ steps.version.outputs.current }}
VERSION: ${{ steps.version.outputs.version }}
BUMP: ${{ inputs.bump }}
LAST_TAG: ${{ steps.commits.outputs.last_tag }}
run: |
{
echo "# Release candidate ready for approval"
echo ""
echo "| | |"
echo "| --- | --- |"
echo "| Current version | \`${CURRENT}\` |"
echo "| Bump | \`${BUMP}\` |"
echo "| **New version** | **\`${VERSION}\`** |"
echo "| Git tag to create | \`v${VERSION}\` |"
echo "| Previous tag | \`${LAST_TAG:-<none>}\` |"
echo ""
echo "## Proposed CHANGELOG entry"
echo ""
cat /tmp/entry.md
echo ""
echo "---"
echo ""
echo "**Approve the \`release\` job to:**"
echo "1. Prepend this entry to \`CHANGELOG.md\`"
echo "2. Bump \`pom.xml\` to \`${VERSION}\`"
echo "3. Commit, tag \`v${VERSION}\`, and push to \`${GITHUB_REF_NAME}\`"
echo "4. Build and publish to GitHub Packages"
echo "5. Create the GitHub Release"
echo ""
echo "Reject the deployment to abort the release."
} >> "$GITHUB_STEP_SUMMARY"
release:
name: Publish release
needs: prepare
runs-on: ubuntu-latest
environment: release
env:
VERSION: ${{ needs.prepare.outputs.version }}
steps:
- name: Generate rheo-app token
id: app-token
uses: actions/create-github-app-token@v1
with:
app-id: ${{ secrets.RHEO_APP_ID }}
private-key: ${{ secrets.RHEO_APP_PRIVATE_KEY }}
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
fetch-tags: true
token: ${{ steps.app-token.outputs.token }}
- name: Set up Java
uses: actions/setup-java@v4
with:
java-version: '21'
distribution: 'temurin'
cache: 'maven'
server-id: github
server-username: MAVEN_USERNAME
server-password: MAVEN_PASSWORD
- name: Configure git
run: |
git config user.name "rheo-app[bot]"
git config user.email "237771051+rheo-app[bot]@users.noreply.github.com"
- name: Re-check tag is still available
run: |
if git rev-parse "v${VERSION}" >/dev/null 2>&1; then
echo "::error::Tag v${VERSION} was created between prepare and approval"
exit 1
fi
- name: Download changelog entry
uses: actions/download-artifact@v4
with:
name: release-entry
path: /tmp/
- name: Prepend entry to CHANGELOG.md
run: |
set -euo pipefail
python3 - <<'PY'
import re
from pathlib import Path
entry = Path('/tmp/entry.md').read_text().strip() + "\n"
path = Path('CHANGELOG.md')
content = path.read_text()
# Strip the [Unreleased] section if present so it isn't left dangling.
content = re.sub(r'\n## \[Unreleased\][^\n]*\n.*?(?=\n## \[|\Z)', '', content, flags=re.DOTALL)
marker = "\n## ["
idx = content.find(marker)
if idx == -1:
new = content.rstrip() + "\n\n" + entry
else:
new = content[:idx + 1] + entry + "\n" + content[idx + 1:]
path.write_text(new)
PY
- name: Bump pom.xml version
run: mvn -B -q versions:set -DnewVersion=${VERSION} -DgenerateBackupPoms=false
- name: Commit, tag and push
run: |
set -euo pipefail
git add pom.xml CHANGELOG.md
git commit -m "chore(release): bump version to ${VERSION} and update CHANGELOG"
git tag -a "v${VERSION}" -m "Release v${VERSION}"
git push origin "HEAD:${GITHUB_REF_NAME}"
git push origin "v${VERSION}"
- name: Build
run: mvn -B -DskipTests package --file pom.xml
- name: Publish to GitHub Packages
env:
MAVEN_USERNAME: ${{ github.actor }}
MAVEN_PASSWORD: ${{ secrets.GITHUB_TOKEN }}
run: mvn -B -DskipTests deploy --file pom.xml
- name: Create GitHub Release
env:
GH_TOKEN: ${{ steps.app-token.outputs.token }}
run: |
gh release create "v${VERSION}" \
--title "v${VERSION}" \
--notes-file /tmp/entry.md \
--verify-tag