-
Notifications
You must be signed in to change notification settings - Fork 1
301 lines (256 loc) · 11 KB
/
ci-cd.yml
File metadata and controls
301 lines (256 loc) · 11 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
name: Regenerate NEAR RPC Client (auto PR, merge & release)
on:
workflow_dispatch:
schedule:
- cron: "0 0 * * *" # daily at midnight
permissions:
contents: write
pull-requests: write
jobs:
regenerate-merge-release:
runs-on: ubuntu-latest
steps:
- name: Exit if triggered by GitHub Actions bot
if: github.actor == 'github-actions[bot]'
run: |
echo "Triggered by GitHub Actions bot; exiting to avoid loop."
exit 0
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0
persist-credentials: true
- name: Set up JDK 21
uses: actions/setup-java@v3
with:
distribution: temurin
java-version: 21
- name: Grant execute permission for Gradlew
run: chmod +x ./gradlew
- name: Run Generator (safe mode)
id: generator
run: |
set +e
./gradlew :generator:run --args="--openapi-url https://raw.githubusercontent.com/near/nearcore/master/chain/jsonrpc/openapi/openapi.json" --no-daemon
EXIT_CODE=$?
set -e
if [ $EXIT_CODE -ne 0 ]; then
echo "⚠️ OpenAPI generation failed. Skipping regeneration."
echo "pr_required=false" >> "$GITHUB_OUTPUT"
exit 0
fi
echo "Generator completed successfully."
echo "pr_required=true" >> "$GITHUB_OUTPUT"
- name: Build project (without tests)
run: ./gradlew build -x test --stacktrace --no-daemon
- name: Prepare branch, commit regenerated sources
id: commit
env:
PAT_TOKEN: ${{ secrets.PAT_TOKEN }}
run: |
set -euo pipefail
git config --local user.email "automation@github.com"
git config --local user.name "GitHub Actions Bot"
SHORT_SHA=${GITHUB_SHA:0:8}
BRANCH="regenerate-openapi-${GITHUB_RUN_NUMBER}-${SHORT_SHA}"
git checkout -b "$BRANCH"
git add -A
echo "=== GIT STATUS ==="
git status
echo "=== GIT DIFF SUMMARY ==="
git diff --cached --stat || true
echo "=== GIT DIFF FULL (trimmed to 100 lines) ==="
git diff --cached | head -n 100 || true
if git diff --cached --name-status | grep -q '^[AM]'; then
echo "Changes detected, creating PR."
echo "pr_required=true" >> "$GITHUB_OUTPUT"
else
echo "No meaningful changes detected — skipping regeneration."
echo "pr_required=false" >> "$GITHUB_OUTPUT"
exit 0
fi
git commit -m "chore: regenerate client from OpenAPI"
git push https://x-access-token:${PAT_TOKEN}@github.com/${GITHUB_REPOSITORY}.git "$BRANCH"
echo "pr_required=true" >> "$GITHUB_OUTPUT"
echo "branch=$BRANCH" >> "$GITHUB_OUTPUT"
- name: Auto-create and merge PR (capture merge SHA)
if: steps.commit.outputs.pr_required == 'true'
id: auto_merge
uses: actions/github-script@v6
with:
github-token: ${{ secrets.PAT_TOKEN }}
script: |
const fs = require('fs');
const branch = '${{ steps.commit.outputs.branch }}';
const title = `chore: regenerate client from OpenAPI (${branch})`;
const body = `This PR regenerates the NEAR RPC client and models from the latest OpenAPI spec.\n\nAutomatically merged after generation.`;
// Create PR
const pr = await github.rest.pulls.create({
owner: context.repo.owner,
repo: context.repo.repo,
title,
head: branch,
base: "main",
body
});
// Merge PR (squash)
const mergeRes = await github.rest.pulls.merge({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: pr.data.number,
merge_method: "squash"
});
let merge_sha = mergeRes.data && mergeRes.data.sha ? mergeRes.data.sha : '';
if (!merge_sha) {
// fallback: read PR info to get merge_commit_sha (or head.sha)
const prInfo = await github.rest.pulls.get({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: pr.data.number
});
merge_sha = prInfo.data.merge_commit_sha || prInfo.data.head.sha || '';
}
if (!merge_sha) {
throw new Error('Could not determine merge commit SHA after merging PR.');
}
fs.appendFileSync(process.env.GITHUB_OUTPUT, `merge_sha=${merge_sha}\n`);
console.log(`Merged PR #${pr.data.number} -> ${merge_sha}`);
- name: Output when no changes
if: steps.commit.outputs.pr_required != 'true'
run: echo "No regenerated changes — nothing to create a PR for."
- name: Sync main after merge (wait for origin/main to point to merge SHA)
if: steps.commit.outputs.pr_required == 'true'
env:
MERGE_SHA: ${{ steps.auto_merge.outputs.merge_sha }}
run: |
set -euo pipefail
echo "Waiting for GitHub to update merge state..."
if [ -z "${MERGE_SHA:-}" ]; then
echo "ERROR: merge SHA not found. Aborting to avoid tagging wrong commit."
exit 1
fi
ATTEMPTS=30
SLEEP_SECONDS=2
i=0
while [ $i -lt $ATTEMPTS ]; do
git fetch origin main --force
REMOTE_MAIN_SHA=$(git ls-remote origin refs/heads/main | awk '{print $1}')
echo "remote main sha: ${REMOTE_MAIN_SHA}, expected: ${MERGE_SHA}"
if [ "${REMOTE_MAIN_SHA}" = "${MERGE_SHA}" ]; then
echo "origin/main is synced to merge SHA."
break
fi
i=$((i+1))
echo "origin/main not synced yet. retry ${i}/${ATTEMPTS}"
sleep $SLEEP_SECONDS
done
if [ "${REMOTE_MAIN_SHA}" != "${MERGE_SHA}" ]; then
echo "::error::origin/main did not update to merge SHA within timeout. Aborting to avoid tagging incorrect commit."
exit 1
fi
git fetch origin --tags --force
git checkout main
git reset --hard origin/main
echo "Main branch and tags synced successfully."
- name: Determine new tag version (initial suggestion)
if: steps.commit.outputs.pr_required == 'true'
id: tag
run: |
set -euo pipefail
git fetch origin --tags --force
TAGS=$(git ls-remote --tags origin | awk '{print $2}' | sed 's|refs/tags/||' | sed 's/\^{}//g' | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' || true)
if [ -z "${TAGS:-}" ]; then
LAST_TAG="v1.0.0"
else
LAST_TAG=$(echo "$TAGS" | sort -V | tail -n1)
fi
echo "Last tag detected: ${LAST_TAG}"
IFS='.' read -r MAJOR MINOR PATCH <<<"${LAST_TAG#v}"
MAJOR=${MAJOR:-1}
MINOR=${MINOR:-1}
PATCH=${PATCH:-0}
PATCH=$((PATCH+1))
NEW_TAG="v${MAJOR}.${MINOR}.${PATCH}"
echo "Determined candidate tag: ${NEW_TAG}"
echo "new_tag=${NEW_TAG}" >> $GITHUB_OUTPUT
- name: Create tag via GitHub API (robust, retries and bump on conflict)
id: create_tag_api
if: steps.commit.outputs.pr_required == 'true'
uses: actions/github-script@v6
with:
github-token: ${{ secrets.PAT_TOKEN }}
script: |
const fs = require('fs');
let candidateTag = '${{ steps.tag.outputs.new_tag }}';
const MERGE_SHA = '${{ steps.auto_merge.outputs.merge_sha }}';
if (!candidateTag) throw new Error('No candidate tag supplied.');
if (!MERGE_SHA) throw new Error('MERGE_SHA missing.');
// helper to bump patch: vA.B.C -> vA.B.(C+1)
function bumpPatch(tag) {
const m = tag.match(/^v(\d+)\.(\d+)\.(\d+)$/);
if (!m) throw new Error('Invalid semver tag: ' + tag);
const major = parseInt(m[1], 10);
const minor = parseInt(m[2], 10);
const patch = parseInt(m[3], 10) + 1;
return `v${major}.${minor}.${patch}`;
}
const MAX_ATTEMPTS = 8;
let created = false;
let finalTag = candidateTag;
for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
try {
// Check if tag exists
try {
await github.rest.git.getRef({
owner: context.repo.owner,
repo: context.repo.repo,
ref: `tags/${finalTag}`
});
// exists => bump and retry
console.log(`Tag ${finalTag} already exists. Bumping...`);
finalTag = bumpPatch(finalTag);
continue;
} catch (err) {
if (err.status !== 404) throw err;
// 404 means not found => proceed to create
}
// create the ref pointing to MERGE_SHA
await github.rest.git.createRef({
owner: context.repo.owner,
repo: context.repo.repo,
ref: `refs/tags/${finalTag}`,
sha: MERGE_SHA
});
console.log(`Created tag ${finalTag} -> ${MERGE_SHA}`);
created = true;
break;
} catch (err) {
// If conflict (already created by parallel run) -> bump and retry
if (err.status === 422 || err.status === 409) {
console.log(`CreateRef conflict on ${finalTag} (attempt ${attempt}). Bumping and retrying...`);
finalTag = bumpPatch(finalTag);
continue;
}
// other errors -> rethrow
throw err;
}
}
if (!created) {
console.log('Failed to create tag after retries. Tagging skipped.');
fs.appendFileSync(process.env.GITHUB_OUTPUT, `tag_created=false\n`);
fs.appendFileSync(process.env.GITHUB_OUTPUT, `created_tag=\n`);
} else {
fs.appendFileSync(process.env.GITHUB_OUTPUT, `tag_created=true\n`);
fs.appendFileSync(process.env.GITHUB_OUTPUT, `created_tag=${finalTag}\n`);
}
- name: Create GitHub Release
if: steps.create_tag_api.outputs.tag_created == 'true'
uses: softprops/action-gh-release@v1
with:
tag_name: ${{ steps.create_tag_api.outputs.created_tag }}
name: "Release ${{ steps.create_tag_api.outputs.created_tag }}"
body: |
🚀 Automated release generated by workflow.
This release was created automatically after merging the regenerated client into main.
env:
GITHUB_TOKEN: ${{ secrets.PAT_TOKEN }}