Repository navigation
661 lines (623 loc) · 24.8 KB
/
Copy pathcla.yml
File metadata and controls
661 lines (623 loc) · 24.8 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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
name: ✍️ CLA
on:
workflow_call:
# pull_request_target (never pull_request): fork PRs get a read-only GITHUB_TOKEN
# on pull_request, which cannot post signing instructions. These jobs never check
# out or execute PR head code.
pull_request_target:
types:
- opened
- reopened
- synchronize
- closed
issue_comment:
types:
- created
- edited
- deleted
workflow_dispatch:
permissions:
contents: read
jobs:
cla:
if: >-
github.event_name == 'pull_request_target' &&
github.event.action != 'closed'
runs-on: ubuntu-latest
name: ✍️ CLA
timeout-minutes: 5
permissions:
contents: read
pull-requests: write
steps:
- name: 📦 Checkout CLA hub
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
repository: NativeScript/.github
ref: master
path: cla-hub
persist-credentials: false
- name: 📜 Checkout org CLA signatures
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
repository: NativeScript/.github
ref: cla-signatures
path: org-cla-signatures
persist-credentials: false
- name: 🟢 Setup Node
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
with:
node-version: '24'
- name: 🧾 Collect identities and comments
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
env:
PR_NUMBER: ${{ github.event.pull_request.number }}
with:
script: |
const fs = require('node:fs/promises');
const pullNumber = Number(process.env.PR_NUMBER);
const owner = context.repo.owner;
const repo = context.repo.repo;
// Load repo-local cla-signatures if this repository has recorded signers not yet swept org-wide
if (`${owner}/${repo}`.toLowerCase() !== 'nativescript/.github') {
try {
const localRes = await github.rest.repos.getContent({
owner,
repo,
path: 'cla-signers.json',
ref: 'cla-signatures',
});
if (localRes.data && 'content' in localRes.data && localRes.data.content) {
const decoded = Buffer.from(localRes.data.content, 'base64').toString('utf8');
await fs.writeFile('local-cla-signers.json', decoded, 'utf8');
}
} catch (err) {
if (err.status !== 404) {
core.info(`No repo-local cla-signatures loaded (${err.status ?? err.message}).`);
}
}
}
const identities = [
{
githubLogin: context.payload.pull_request.user.login,
name: context.payload.pull_request.user.login,
email: null,
},
];
const commits = await github.paginate(
github.rest.pulls.listCommits,
{
owner,
repo,
pull_number: pullNumber,
per_page: 100,
},
);
for (const commit of commits) {
identities.push({
githubLogin: commit.author?.login ?? null,
name: commit.commit.author?.name ?? null,
email: commit.commit.author?.email ?? null,
});
}
const comments = await github.paginate(
github.rest.issues.listComments,
{
owner,
repo,
issue_number: pullNumber,
per_page: 100,
},
);
const signingComments = comments
.filter((comment) => comment.user?.type === 'User')
.map((comment) => ({
login: comment.user.login,
createdAt: comment.created_at,
body: comment.body ?? '',
}));
// Cross-repo instant fallback: if an identity is not yet in org-cla-signatures
// and has not commented on this PR, check if they already signed on a merged PR
// anywhere in org:NativeScript before the hourly org sync runs.
const orgRaw = JSON.parse(await fs.readFile('org-cla-signatures/cla-signers.json', 'utf8'));
const knownSet = new Set([
...orgRaw.allowlist.github.map((s) => s.trim().toLowerCase()),
...orgRaw.signers.map((s) => s.github.trim().toLowerCase()),
]);
const phrase = 'I have read the CLA and I hereby sign the CLA';
for (const sc of signingComments) {
if (sc.body.trim() === phrase) {
knownSet.add(sc.login.trim().toLowerCase());
}
}
const candidateLogins = new Set();
for (const id of identities) {
if (!id.githubLogin) continue;
const low = id.githubLogin.trim().toLowerCase();
if (low.endsWith('[bot]') || low.startsWith('app/') || knownSet.has(low)) continue;
candidateLogins.add(id.githubLogin.trim());
}
for (const login of candidateLogins) {
try {
const searchRes = await github.rest.search.issuesAndPullRequests({
q: `org:${owner} is:pr is:merged commenter:${login} "${phrase}"`,
per_page: 5,
});
for (const item of searchRes.data.items) {
const repoParts = item.repository_url.split('/');
const itemRepo = repoParts.at(-1);
const itemOwner = repoParts.at(-2);
const prComments = await github.paginate(
github.rest.issues.listComments,
{
owner: itemOwner,
repo: itemRepo,
issue_number: item.number,
per_page: 100,
},
);
const match = prComments.find(
(c) =>
c.user?.type === 'User' &&
c.user?.login?.toLowerCase() === login.toLowerCase() &&
(c.body ?? '').trim() === phrase,
);
if (match) {
signingComments.push({
login: match.user.login,
createdAt: match.created_at,
body: match.body ?? '',
});
break;
}
}
} catch (err) {
core.info(`Cross-repo signing search skipped for @${login}: ${err.message}`);
}
}
await fs.writeFile(
'cla-identities.json',
`${JSON.stringify(identities, null, '\t')}\n`,
);
await fs.writeFile(
'cla-signing-comments.json',
`${JSON.stringify(signingComments, null, '\t')}\n`,
);
- name: ✍️ Check CLA
id: check
run: |
check_args=(
--signers org-cla-signatures/cla-signers.json
--identities-json cla-identities.json
--signing-comments-json cla-signing-comments.json
--missing-json cla-missing.json
)
if [ -f local-cla-signers.json ]; then
check_args+=(--extra-signers local-cla-signers.json)
fi
set +e
node cla-hub/scripts/check-cla.mjs "${check_args[@]}"
code=$?
echo "exit_code=$code" >> "$GITHUB_OUTPUT"
if [ "$code" -ne 0 ] && [ "$code" -ne 1 ]; then
exit "$code"
fi
- name: 💬 Comment when unsigned
if: steps.check.outputs.exit_code == '1'
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
with:
script: |
const fs = require('node:fs/promises');
const missing = JSON.parse(await fs.readFile('cla-missing.json', 'utf8'));
const marker = '<!-- nativescript-cla-check -->';
const missingLines = missing.map((entry) => `- ${entry.reason}`);
const body = [
marker,
'Unsigned contributions cannot merge.',
'',
'1. Read the [Individual CLA](https://github.com/NativeScript/.github/blob/master/docs/legal/individual-cla.md) (or the [Corporate CLA](https://github.com/NativeScript/.github/blob/master/docs/legal/corporate-cla.md) if an organization owns the work).',
'2. Comment exactly: `I have read the CLA and I hereby sign the CLA`',
'3. That signing comment satisfies this check across all `NativeScript` repositories. The signer is recorded on the [`cla-signatures`](https://github.com/NativeScript/.github/blob/cla-signatures/cla-signers.json) branch after this pull request merges. See the [CLA guide](https://github.com/NativeScript/.github/blob/master/CLA.md).',
...(missingLines.length > 0 ? ['', '**Missing CLA status:**', ...missingLines] : []),
'',
'Adding your own username on this branch does not pass the check.',
].join('\n');
const comments = await github.paginate(
github.rest.issues.listComments,
{
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.payload.pull_request.number,
per_page: 100,
},
);
const existing = comments.find((comment) =>
comment.body?.includes(marker),
);
if (existing) {
await github.rest.issues.updateComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: existing.id,
body,
});
} else {
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.payload.pull_request.number,
body,
});
}
- name: ✅ Update prior unsigned comment when now signed
if: steps.check.outputs.exit_code == '0'
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
with:
script: |
const marker = '<!-- nativescript-cla-check -->';
const comments = await github.paginate(
github.rest.issues.listComments,
{
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.payload.pull_request.number,
per_page: 100,
},
);
const existing = comments.find((comment) =>
comment.body?.includes(marker),
);
if (existing && !existing.body.includes('✅ All contributors')) {
const body = [
marker,
'✅ All contributors on this pull request have satisfied the [NativeScript CLA](https://github.com/NativeScript/.github/blob/master/CLA.md).',
].join('\n');
await github.rest.issues.updateComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: existing.id,
body,
});
}
- name: ❌ Fail when unsigned
if: steps.check.outputs.exit_code == '1'
run: exit 1
record:
if: >-
github.event_name == 'issue_comment' &&
github.event.issue.pull_request != null &&
github.event.comment.user.type == 'User' &&
(
contains(github.event.comment.body, 'I hereby sign the CLA') ||
(
github.event.action == 'edited' &&
contains(github.event.changes.body.from, 'I hereby sign the CLA')
)
)
runs-on: ubuntu-latest
name: 📝 Record CLA
timeout-minutes: 5
permissions:
pull-requests: write
actions: write
steps:
- name: 💬 Acknowledge signature and re-run CLA
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
env:
PR_NUMBER: ${{ github.event.issue.number }}
CLA_LOGIN: ${{ github.event.comment.user.login }}
COMMENT_ACTION: ${{ github.event.action }}
with:
script: |
const login = process.env.CLA_LOGIN;
const action = process.env.COMMENT_ACTION;
const commentBody = context.payload.comment.body ?? '';
const isSigning =
action !== 'deleted' &&
commentBody.trim() === 'I have read the CLA and I hereby sign the CLA';
const pullNumber = Number(process.env.PR_NUMBER);
const owner = context.repo.owner;
const repo = context.repo.repo;
const pull = await github.rest.pulls.get({
owner,
repo,
pull_number: pullNumber,
});
const headSha = pull.data.head.sha;
async function latestClaRun() {
const runs = await github.rest.actions.listWorkflowRuns({
owner,
repo,
workflow_id: 'cla.yml',
event: 'pull_request_target',
head_sha: headSha,
per_page: 5,
});
return (
runs.data.workflow_runs.find(
(run) =>
run.status !== 'completed' || run.conclusion !== 'skipped',
) ?? null
);
}
const deadline = Date.now() + 180_000;
let latest = await latestClaRun();
while (latest && latest.status !== 'completed' && Date.now() < deadline) {
await new Promise((resolve) => setTimeout(resolve, 10_000));
latest = await latestClaRun();
}
let reran = false;
if (latest?.status === 'completed') {
try {
await github.rest.actions.reRunWorkflow({
owner,
repo,
run_id: latest.id,
});
reran = true;
} catch (error) {
core.warning(
`Could not re-run CLA: ${error instanceof Error ? error.message : String(error)}`,
);
}
}
if (isSigning) {
const marker = `<!-- nativescript-cla-recorded:${login.toLowerCase()} -->`;
const followUp = reran
? 'The CLA check will re-run.'
: 'The CLA check will include this signing comment on its next run.';
const body = [
marker,
`Thanks @${login} — your signature on this PR satisfies the CLA check, and you'll be recorded on the \`cla-signatures\` branch after this PR merges. ${followUp}`,
].join('\n');
const comments = await github.paginate(
github.rest.issues.listComments,
{
owner,
repo,
issue_number: pullNumber,
per_page: 100,
},
);
const existing = comments.find((comment) =>
comment.body?.includes(marker),
);
if (existing) {
await github.rest.issues.updateComment({
owner,
repo,
comment_id: existing.id,
body,
});
} else {
await github.rest.issues.createComment({
owner,
repo,
issue_number: pullNumber,
body,
});
}
}
record-on-merge:
if: >-
(
github.event_name == 'pull_request_target' &&
github.event.pull_request.merged == true
) ||
github.event_name == 'workflow_dispatch'
runs-on: ubuntu-latest
name: 📝 Record CLA after merge
timeout-minutes: 15
concurrency:
group: cla-signatures-${{ github.repository }}
cancel-in-progress: false
permissions:
contents: write
steps:
- name: 📦 Checkout CLA hub
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
repository: NativeScript/.github
ref: master
path: cla-hub
persist-credentials: false
- name: 📜 Checkout org CLA signatures
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
repository: NativeScript/.github
ref: cla-signatures
path: org-cla-signatures
persist-credentials: false
- name: 🟢 Setup Node
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
with:
node-version: '24'
- name: 🧾 Collect signing comments from recent merged PRs
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
with:
script: |
const path = require('node:path');
const fs = require('node:fs/promises');
const {
githubApiErrorStatus,
isRetryableGithubApiError,
withGithubApiRetry,
} = require(
path.join(
process.env.GITHUB_WORKSPACE,
'cla-hub/scripts/github-api-retry.cjs',
),
);
const owner = context.repo.owner;
const repo = context.repo.repo;
async function collectSigningComments() {
const byMergedDesc = (left, right) =>
Date.parse(right.merged_at) - Date.parse(left.merged_at);
const mergedByNumber = new Map();
for (let page = 1; page <= 50; page += 1) {
const response = await github.rest.pulls.list({
owner,
repo,
state: 'closed',
sort: 'updated',
direction: 'desc',
per_page: 100,
page,
});
if (response.data.length === 0) break;
for (const pull of response.data) {
if (pull.merged_at) mergedByNumber.set(pull.number, pull);
}
if (response.data.length < 100) break;
if (mergedByNumber.size >= 50) {
const cutoff = Date.parse(
[...mergedByNumber.values()].sort(byMergedDesc)[49]
.merged_at,
);
const oldestUpdated = Date.parse(
response.data.at(-1).updated_at,
);
if (oldestUpdated < cutoff) break;
}
}
const mergedPulls = [...mergedByNumber.values()]
.sort(byMergedDesc)
.slice(0, 50);
const candidates = new Map(
mergedPulls.map((pull) => [pull.number, pull]),
);
const eventPull = context.payload.pull_request;
if (eventPull) candidates.set(eventPull.number, eventPull);
const signingComments = [];
for (const pull of candidates.values()) {
const eligibleLogins = new Set();
const authorLogin = pull.user?.login;
if (authorLogin) eligibleLogins.add(authorLogin.toLowerCase());
const commits = await github.paginate(
github.rest.pulls.listCommits,
{
owner,
repo,
pull_number: pull.number,
per_page: 100,
},
);
for (const commit of commits) {
const login = commit.author?.login;
if (login) eligibleLogins.add(login.toLowerCase());
}
const comments = await github.paginate(
github.rest.issues.listComments,
{
owner,
repo,
issue_number: pull.number,
per_page: 100,
},
);
for (const comment of comments) {
const login = comment.user?.login;
if (
comment.user?.type !== 'User' ||
!login ||
!eligibleLogins.has(login.toLowerCase())
) {
continue;
}
signingComments.push({
login,
createdAt: comment.created_at,
body: comment.body ?? '',
});
}
}
signingComments.sort((left, right) =>
left.createdAt.localeCompare(right.createdAt),
);
return signingComments;
}
try {
const signingComments = await withGithubApiRetry(
collectSigningComments,
{
maxAttempts: 5,
baseDelayMs: 8_000,
onRetry: ({ attempt, maxAttempts, delayMs, error }) => {
const status = githubApiErrorStatus(error) ?? 'network';
const detail =
error instanceof Error ? error.message : String(error);
core.info(
`Transient GitHub error (${status}) on CLA collect attempt ${attempt}/${maxAttempts}: ${detail}. Retrying in ${delayMs}ms.`,
);
},
},
);
await fs.writeFile(
'cla-signing-comments.json',
`${JSON.stringify(signingComments, null, '\t')}\n`,
);
} catch (error) {
if (isRetryableGithubApiError(error)) {
const status = githubApiErrorStatus(error) ?? 'network';
const detail =
error instanceof Error ? error.message : String(error);
core.warning(
`CLA collect failed after retries due to transient GitHub error (${status}): ${detail}. Skipping this run; the next merge rescans the last 50 merges.`,
);
await fs.writeFile('cla-signing-comments.json', '[]\n');
return;
}
throw error;
}
- name: 📝 Prepare target cla-signatures branch and record new signers
id: record
env:
GH_TOKEN: ${{ github.token }}
TARGET_REPO: ${{ github.repository }}
run: |
set -euo pipefail
repo_url="https://x-access-token:${GH_TOKEN}@github.com/${TARGET_REPO}.git"
mkdir -p target-cla-signatures
if git ls-remote --exit-code --heads "$repo_url" cla-signatures >/dev/null 2>&1; then
git clone --depth 1 --branch cla-signatures "$repo_url" target-cla-signatures
else
git -C target-cla-signatures init
git -C target-cla-signatures checkout --orphan cla-signatures
git -C target-cla-signatures remote add origin "$repo_url"
cat > target-cla-signatures/cla-signers.json <<'JSON'
{
"version": 1,
"document": "docs/legal/individual-cla.md",
"allowlist": {
"github": [],
"email": []
},
"signers": []
}
JSON
fi
record_args=(
--signers target-cla-signatures/cla-signers.json
--record-comments-json cla-signing-comments.json
)
if [ "${TARGET_REPO}" != "NativeScript/.github" ]; then
record_args+=(--known-signers org-cla-signatures/cla-signers.json)
fi
node cla-hub/scripts/check-cla.mjs "${record_args[@]}" > cla-record-output.txt
cat cla-record-output.txt
grep -E '^(added|github)=' cla-record-output.txt >> "$GITHUB_OUTPUT"
- name: 🌱 Commit and push signers
if: steps.record.outputs.added == 'true'
working-directory: target-cla-signatures
env:
CLA_LOGINS: ${{ steps.record.outputs.github }}
run: |
set -euo pipefail
git add cla-signers.json
if git diff --cached --quiet; then
exit 0
fi
git config user.name 'github-actions[bot]'
git config user.email '41898282+github-actions[bot]@users.noreply.github.com'
git commit -m "Record CLA signers: @${CLA_LOGINS//,/, @}"
git push origin HEAD:refs/heads/cla-signatures