-
Notifications
You must be signed in to change notification settings - Fork 149
302 lines (268 loc) · 12.3 KB
/
Copy pathauto-merge.yml
File metadata and controls
302 lines (268 loc) · 12.3 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
name: Auto-Merge PRs
<<<<<<< HEAD
# Fires when a PR is opened/updated (to enable native auto-merge) and when a
# check suite completes (to directly merge if every check went green and the
# branch has no conflicts).
on:
pull_request:
types: [opened, synchronize, reopened, ready_for_review]
branches: [main]
check_suite:
types: [completed]
permissions:
contents: write # needed to merge
pull-requests: write # needed to update PR auto-merge flag
jobs:
# ── 1. Enable GitHub's built-in auto-merge the moment a PR is opened / updated
enable-auto-merge:
name: Enable auto-merge on PR
if: |
github.event_name == 'pull_request' &&
github.event.pull_request.draft == false
runs-on: ubuntu-latest
steps:
- name: Enable squash auto-merge
# continue-on-error so a repo without branch-protection rules doesn't
# block the workflow; the merge-when-green job is the primary mechanism.
continue-on-error: true
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
gh pr merge --auto --squash \
--repo "${{ github.repository }}" \
"${{ github.event.pull_request.number }}"
# ── 2. Directly merge when ALL check runs on the suite pass ──────────────
merge-when-green:
name: Merge PR when all checks pass
if: |
github.event_name == 'check_suite' &&
github.event.check_suite.conclusion == 'success'
runs-on: ubuntu-latest
steps:
- name: Merge passing, conflict-free PRs
uses: actions/github-script@v7
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const headSha = context.payload.check_suite.head_sha;
const prs = context.payload.check_suite.pull_requests ?? [];
if (prs.length === 0) {
core.info('No open PRs linked to this check suite — nothing to do.');
return;
}
for (const pr of prs) {
// Fetch the full PR object (includes mergeable + draft fields)
const { data: pull } = await github.rest.pulls.get({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: pr.number,
});
if (pull.draft) {
core.info(`PR #${pr.number} is a draft — skipping.`);
continue;
}
if (pull.state !== 'open') {
core.info(`PR #${pr.number} is already closed — skipping.`);
continue;
}
// GitHub computes mergeability asynchronously; poll once if null.
let mergeable = pull.mergeable;
if (mergeable === null) {
core.info(`PR #${pr.number}: mergeability not yet computed, waiting 6 s…`);
await new Promise(r => setTimeout(r, 6000));
const { data: refreshed } = await github.rest.pulls.get({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: pr.number,
});
mergeable = refreshed.mergeable;
}
if (mergeable === false) {
core.info(`PR #${pr.number} has merge conflicts — skipping.`);
continue;
}
// Confirm every completed check run passed (or was neutral/skipped).
const { data: { check_runs } } = await github.rest.checks.listForRef({
owner: context.repo.owner,
repo: context.repo.repo,
ref: headSha,
per_page: 100,
});
const failing = check_runs.filter(r =>
r.status === 'completed' &&
!['success', 'skipped', 'neutral'].includes(r.conclusion)
);
if (failing.length > 0) {
core.info(
`PR #${pr.number} has failing checks ` +
`(${failing.map(r => r.name).join(', ')}) — skipping.`
);
continue;
}
// Everything is green and conflict-free — merge!
try {
await github.rest.pulls.merge({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: pr.number,
merge_method: 'squash',
commit_title: `${pull.title} (#${pr.number})`,
commit_message: pull.body ?? '',
});
core.info(`✅ Auto-merged PR #${pr.number}: ${pull.title}`);
} catch (err) {
core.error(`Failed to merge PR #${pr.number}: ${err.message}`);
=======
# Merges open PRs once every check that ran for their head commit has gone green.
#
# Why `workflow_run` and not `check_suite`:
# GitHub does not start a new workflow run from events generated by the
# built-in GITHUB_TOKEN, so the `check_suite: completed` suites produced by
# Actions never triggered this workflow (0 runs in ~40 attempts). `workflow_run`
# is the supported way to react to another workflow finishing.
#
# Why not GitHub's native auto-merge (`gh pr merge --auto`):
# `main` has no branch protection and therefore no *required* status checks.
# Native auto-merge only waits for required checks, so with none configured it
# merges as soon as the PR is mergeable — i.e. before CI has finished. This
# workflow evaluates the checks itself instead.
#
# Security: jobs here run in the base-repo context with a writable token and
# deliberately never check out or execute PR-authored code — they only call the
# REST API.
on:
workflow_run:
workflows:
- "Frontend CI"
- "Frontend Build Check"
- "Smart Contract CI"
- "Contract Tests"
types: [completed]
# Safety net: re-sweep periodically so a PR whose triggering event was missed
# (or that went green while another PR was merging) still lands.
schedule:
- cron: "*/30 * * * *"
workflow_dispatch:
permissions:
contents: write # needed to merge
pull-requests: write # needed to comment / update PRs
checks: read
statuses: read
concurrency:
group: auto-merge
cancel-in-progress: false
jobs:
merge-green-prs:
name: Merge PRs with all checks passing
runs-on: ubuntu-latest
steps:
- name: Evaluate and merge
uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const { owner, repo } = context.repo;
const TERMINAL_OK = ['success', 'skipped', 'neutral'];
// ── Work out which PRs to consider ────────────────────────────
// `workflow_run.pull_requests` is always empty for PRs from forks,
// so resolve candidates by matching head SHA against open PRs.
const openPrs = await github.paginate(github.rest.pulls.list, {
owner, repo, state: 'open', per_page: 100,
});
let candidates = openPrs;
if (context.eventName === 'workflow_run') {
const run = context.payload.workflow_run;
if (run.conclusion !== 'success') {
core.info(`Upstream run "${run.name}" concluded "${run.conclusion}" — nothing to do.`);
return;
}
candidates = openPrs.filter(pr => pr.head.sha === run.head_sha);
if (candidates.length === 0) {
core.info(`No open PR matches head SHA ${run.head_sha}.`);
return;
}
}
core.info(`Evaluating ${candidates.length} PR(s).`);
for (const summary of candidates) {
const number = summary.number;
// Re-fetch: the list payload omits `mergeable`/`mergeable_state`.
let { data: pr } = await github.rest.pulls.get({
owner, repo, pull_number: number,
});
if (pr.draft) { core.info(`#${number}: draft — skipping.`); continue; }
if (pr.state !== 'open') { core.info(`#${number}: not open — skipping.`); continue; }
// ── Checks must all be finished and green ───────────────────
const sha = pr.head.sha;
const { data: { check_runs } } = await github.rest.checks.listForRef({
owner, repo, ref: sha, per_page: 100,
});
// Ignore this workflow's own check so it never waits on itself.
const relevant = check_runs.filter(r => r.name !== 'Merge PRs with all checks passing');
if (relevant.length === 0) {
core.info(`#${number}: no checks reported for ${sha} — refusing to merge unchecked.`);
continue;
}
const pending = relevant.filter(r => r.status !== 'completed');
if (pending.length > 0) {
core.info(`#${number}: still running (${pending.map(r => r.name).join(', ')}) — waiting.`);
continue;
}
const failing = relevant.filter(r => !TERMINAL_OK.includes(r.conclusion));
if (failing.length > 0) {
core.info(`#${number}: failing checks (${failing.map(r => r.name).join(', ')}) — skipping.`);
continue;
}
// Legacy commit statuses (non-Actions integrations) count too.
const { data: combined } = await github.rest.repos.getCombinedStatusForRef({
owner, repo, ref: sha,
});
if (combined.total_count > 0 && combined.state !== 'success') {
core.info(`#${number}: commit status is "${combined.state}" — skipping.`);
continue;
}
// ── Mergeability (computed asynchronously by GitHub) ────────
for (let attempt = 0; pr.mergeable === null && attempt < 3; attempt++) {
core.info(`#${number}: mergeability not computed yet, retrying in 5s…`);
await new Promise(r => setTimeout(r, 5000));
({ data: pr } = await github.rest.pulls.get({
owner, repo, pull_number: number,
}));
}
if (pr.mergeable === false) {
core.info(`#${number}: merge conflicts (${pr.mergeable_state}) — skipping.`);
continue;
}
if (pr.mergeable === null) {
core.info(`#${number}: mergeability still unknown — will retry next sweep.`);
continue;
}
if (['blocked', 'behind', 'draft'].includes(pr.mergeable_state)) {
core.info(`#${number}: mergeable_state="${pr.mergeable_state}" — skipping.`);
continue;
}
// ── Merge ──────────────────────────────────────────────────
// Drop AI-assistant co-author trailers from the squash message.
// Human co-authors are deliberately left intact — stripping those
// would erase real contributor attribution.
const body = (pr.body ?? '')
.split('\n')
.filter(line => !/^\s*co-authored-by:.*(claude|anthropic\.com)/i.test(line))
.join('\n')
.trim();
try {
await github.rest.pulls.merge({
owner, repo,
pull_number: number,
merge_method: 'squash',
commit_title: `${pr.title} (#${number})`,
commit_message: body,
sha,
});
core.notice(`Auto-merged #${number}: ${pr.title}`);
} catch (err) {
// 405 = not mergeable right now, 409 = head moved. Both are
// transient; the next sweep retries.
core.warning(`#${number}: merge failed (${err.status}): ${err.message}`);
>>>>>>> emwulrd/main
}
}