forked from MetOffice/growss
-
Notifications
You must be signed in to change notification settings - Fork 0
289 lines (250 loc) · 13 KB
/
Copy pathcla-check.yaml
File metadata and controls
289 lines (250 loc) · 13 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
# ------------------------------------------------------------------------------
# (c) Crown copyright Met Office. All rights reserved.
# The file LICENCE, distributed with this code, contains details of the terms
# under which the code may be used.
# ------------------------------------------------------------------------------
name: CLA Checker
on:
workflow_call:
inputs:
runner:
description: 'The runner to use for the job'
required: false
type: string
default: 'ubuntu-24.04'
permissions:
contents: read
pull-requests: write # Required to add labels and comments
jobs:
check-cla:
runs-on: ${{ inputs.runner }}
steps:
- name: Checkout Base Branch
uses: actions/checkout@v6
with:
token: ${{ secrets.GITHUB_TOKEN }}
ref: ${{ github.ref }}
path: base_branch
- name: Determine if contributor exists in base
id: check_contributor_base
working-directory: ./base_branch
run: |
AUTHOR="${{ github.event.pull_request.user.login }}"
if [ -f "CONTRIBUTORS.md" ]; then
if grep -qE "\|\s*$AUTHOR\s*\|" CONTRIBUTORS.md; then
echo "on_base=true" >> $GITHUB_OUTPUT
echo "🎉 $AUTHOR has already signed the CLA on base branch."
else
echo "on_base=false" >> $GITHUB_OUTPUT
echo "⚠️ $AUTHOR not on base. Proceeding to check PR branch."
fi
else
# If CONTRIBUTORS.md file doesn't exist, we must check PR branch
echo "on_base=undefined" >> $GITHUB_OUTPUT
echo "🔴 CONTRIBUTORS.md file does not exist on base. Proceeding to check PR branch."
fi
- name: Checkout PR Branch
uses: actions/checkout@v6
with:
token: ${{ secrets.GITHUB_TOKEN }}
ref: ${{ github.event.pull_request.head.sha }}
path: pr_branch
- name: Determine if contributor exists in PR branch
id: check_contributor_pr
working-directory: pr_branch
run: |
AUTHOR="${{ github.event.pull_request.user.login }}"
if [ -f "CONTRIBUTORS.md" ]; then
if grep -qE "\|\s*$AUTHOR\s*\|" CONTRIBUTORS.md; then
echo "on_pr=true" >> $GITHUB_OUTPUT
echo "✅ $AUTHOR is in the CONTRIBUTORS.md file on PR branch."
else
echo "on_pr=false" >> $GITHUB_OUTPUT
echo "⚠️ $AUTHOR is not in the CONTRIBUTORS.md file on PR branch."
fi
else
echo "on_pr=undefined" >> $GITHUB_OUTPUT
echo "🔴 CONTRIBUTORS.md file does not exist on PR branch."
fi
- name: Check Merge Ref Exists
id: check_merge_ref
working-directory: ./base_branch
shell: bash
run: |
ref="refs/pull/${{ github.event.number }}/merge"
hash=$(git ls-remote origin $ref)
if [[ -z $hash ]]; then
echo "merge_ref_defined=false" >> $GITHUB_ENV
else
echo "merge_ref_defined=true" >> $GITHUB_ENV
fi
- name: Checkout Merge Branch
if: env.merge_ref_defined == 'true'
id: checkout_merge
uses: actions/checkout@v6
continue-on-error: true
with:
token: ${{ secrets.GITHUB_TOKEN }}
ref: "refs/pull/${{ github.event.number }}/merge"
path: merge_branch
# -- Check if CONTRIBUTORS.md was modified in this PR
- name: Check if CONTRIBUTORS.md was modified in PR
id: check_contributors_modified
run: |
if [[ "$merge_ref_defined" == "false" ]]; then
echo "::warning::Merge conflicts mean the check for modification of a signed CONTRIBUTORS.md file was not completed. Allowing this to pass while conflict exists."
echo "modified=false" >> $GITHUB_OUTPUT
else
cd merge_branch
git fetch origin ${{ github.event.pull_request.base.ref }}
CHANGED_FILES=$(git diff --name-only $GITHUB_BASE_REF)
if echo "$CHANGED_FILES" | grep -q "^CONTRIBUTORS.md$"; then
echo "modified=true" >> $GITHUB_OUTPUT
echo "📝 CONTRIBUTORS.md file was modified in this PR."
else
echo "modified=false" >> $GITHUB_OUTPUT
echo "ℹ️ CONTRIBUTORS.md file was NOT modified in this PR."
fi
fi
# -- Step 3: Manage PR Labels, Comments, and Final Status (Consolidated)
- name: Manage CLA Status, Labels, and Comments
uses: actions/github-script@v8
# Using 'always()' here so this step runs regardless of previous
# success/failure to manage labels correctly
if: always()
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const signedOnBase = '${{ steps.check_contributor_base.outputs.on_base }}' === 'true';
const signedOnPr = '${{ steps.check_contributor_pr.outputs.on_pr }}' === 'true';
const contributorsModified = '${{ steps.check_contributors_modified.outputs.modified }}' === 'true';
const issue_number = context.issue.number;
const owner = context.repo.owner;
const repo = context.repo.repo;
const author = context.payload.pull_request.user.login;
// Check if contributor was on base but modified the file
// This may be valid but will require an admin to ok it
const invalidModify = signedOnBase && contributorsModified;
// Helper function to create or update a label with a specific COLOUR
async function ensureLabel(name, COLOUR, description) {
try {
await github.rest.issues.updateLabel({
owner: owner,
repo: repo,
name: name,
description: description,
color: COLOUR
});
console.log(`Updated label: ${name} with COLOUR ${COLOUR}`);
} catch (error) {
// If update fails (label doesn't exist), create it
try {
await github.rest.issues.createLabel({
owner: owner,
repo: repo,
name: name,
description: description,
color: COLOUR
});
console.log(`Created new label: ${name} with COLOUR ${COLOUR}`);
} catch (createError) {
console.log(`Error with label ${name}:`, createError.message);
}
}
}
// Define desired COLOURs and descriptions for consistency
const COLOUR_SIGNED = '0052cc'; // Blue
const COLOUR_REQUIRED = 'b60205'; // Red
const COLOUR_MODIFIED = 'f56f27'; // Orange
// Helper function to delete old CLA-related comments from this bot
async function deleteOldClaComments() {
try {
const comments = await github.rest.issues.listComments({
owner,
repo,
issue_number
});
// Filter comments from GitHub Actions bot that contain CLA-related content
// GitHub Actions bot username is 'github-actions[bot]'
const botComments = comments.data.filter(comment =>
(comment.user.login === 'github-actions[bot]' || comment.user.type === 'Bot') &&
(comment.body.includes('CLA') ||
comment.body.includes('CONTRIBUTORS') ||
comment.body.includes('Contributor Licence Agreement'))
);
console.log(`Found ${botComments.length} old CLA comment(s) to delete`);
// Delete all old CLA comments
for (const comment of botComments) {
await github.rest.issues.deleteComment({
owner,
repo,
comment_id: comment.id
});
console.log(`Deleted old CLA comment #${comment.id} from ${comment.user.login}`);
}
} catch (error) {
console.log('Error deleting old comments:', error.message);
}
}
console.log(`Base: ${signedOnBase}, PR: ${signedOnPr}, Modified: ${contributorsModified}, Invalid Modify: ${invalidModify}`);
// Handle case where contributor modified the file when already on it
if (invalidModify) {
await ensureLabel('cla-modified', COLOUR_MODIFIED, 'The CLA has been modified as part of this PR - added by GA');
console.log('⚠️ Contributor was in base branch but has modified the file.');
// Ensure labels are correct
await Promise.allSettled([
github.rest.issues.removeLabel({ owner, repo, issue_number, name: 'cla-signed' }),
github.rest.issues.removeLabel({ owner, repo, issue_number, name: 'cla-required' }),
github.rest.issues.addLabels({ owner, repo, issue_number, labels: ['cla-modified'] })
]);
// Delete old CLA comments before posting new one
await deleteOldClaComments();
// Post warning comment
const commentBody = `⚠️ Hello @${author}!\n\nYour CLA signature was found on the base branch, but you appear to have modified the _CONTRIBUTORS.md_ file in this PR.\n\nPlease do not edit the _CONTRIBUTORS.md_ file. If you have already signed the CLA, revert changes to the file and your signature will be picked up.`;
await github.rest.issues.createComment({ owner, repo, issue_number, body: commentBody });
// Fail the GitHub Action run
console.error("⚠️ Contributor edited the CONTRIBUTORS file when already on base.");
process.exit(1);
}
if (signedOnBase) {
// Different messages based on scenario
if (signedOnBase && !contributorsModified) {
console.log('✅ CLA already signed on base branch, and CONTRIBUTORS.md not modified in PR.');
} else {
console.log('✅ CLA condition met. Removing required label and adding signed label.');
}
// Use Promise.allSettled for robust label management
await Promise.allSettled([
github.rest.issues.removeLabel({ owner, repo, issue_number, name: 'cla-required' }),
]);
// Delete old CLA comments since CLA is satisfied
await deleteOldClaComments();
} else if (signedOnPr) {
// New contributor signing CLA for the first time
await ensureLabel('cla-signed', COLOUR_SIGNED, 'The CLA has been signed as part of this PR - added by GA');
console.log('✅ New contributor has signed the CLA in PR branch.');
await Promise.allSettled([
github.rest.issues.removeLabel({ owner, repo, issue_number, name: 'cla-required' }),
github.rest.issues.removeLabel({ owner, repo, issue_number, name: 'cla-modified' }),
github.rest.issues.addLabels({ owner, repo, issue_number, labels: ['cla-signed'] })
]);
// Delete old CLA comments since CLA is now signed
await deleteOldClaComments();
} else {
await ensureLabel('cla-required', COLOUR_REQUIRED, 'The CLA has not yet been signed by the author of this PR - added by GA');
console.log('❌ CLA condition NOT met. Adding required label and ensuring signed label is absent.');
// Ensure labels are correct
await Promise.allSettled([
github.rest.issues.removeLabel({ owner, repo, issue_number, name: 'cla-signed' }),
github.rest.issues.removeLabel({ owner, repo, issue_number, name: 'cla-modified' }),
github.rest.issues.addLabels({ owner, repo, issue_number, labels: ['cla-required'] })
]);
// Delete old CLA comments before posting new one
await deleteOldClaComments();
// Post CLA comment
const commentBody = `Hello @${author}! 👋\n\nThank you for your contribution. Since this is your first time contributing to this repository, we ask that you sign our Contributor Licence Agreement (CLA).\n\n📄 [You can read the CLA here](https://github.com/MetOffice/Momentum/blob/main/CLA.md).\n\nTo agree to the CLA, please add your details (**GitHub username**, Real Name, Affiliation, and Date) to the _CONTRIBUTORS.md_ file (create one, if required) in the development branch for this PR. After signing the CLA, you won't need to do this again for future PRs.`;
await github.rest.issues.createComment({ owner, repo, issue_number, body: commentBody });
// Fail the GitHub Action run
console.error("⚠️ Please add yourself to the CONTRIBUTORS.md file to sign the CLA.");
process.exit(1);
}