forked from MetOffice/growss
-
Notifications
You must be signed in to change notification settings - Fork 0
248 lines (211 loc) · 11.8 KB
/
Copy pathcla-check.yaml
File metadata and controls
248 lines (211 loc) · 11.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
# ------------------------------------------------------------------------------
# (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:
# --- Step 1: Check Base Branch ---
- name: Checkout base branch and check for contributor status
uses: actions/checkout@v6
with:
token: ${{ secrets.GITHUB_TOKEN }}
ref: ${{ github.ref }}
- name: Determine if contributor exists in base (new)
id: check_contributor_base
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
# --- Step 2: Check PR Branch ---
- name: Checkout PR branch and check for contributor status
# Always check PR branch to detect if contributor removed themselves
uses: actions/checkout@v6
with:
token: ${{ secrets.GITHUB_TOKEN }}
- name: Determine if contributor exists in PR branch
id: check_contributor_pr
# Always check PR branch to detect if contributor removed themselves
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
# -- Check if CONTRIBUTORS.md was modified in this PR
- name: Check if CONTRIBUTORS.md was modified in PR
id: check_contributors_modified
run: |
# Fetch the base branch
git fetch origin ${{ github.event.pull_request.base.ref }}
# Use the base SHA directly for comparison (works with forks)
BASE_SHA="${{ github.event.pull_request.base.sha }}"
CHANGED_FILES=$(git diff --name-only $BASE_SHA)
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
# -- 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 removed themselves from PR
const removedFromPr = signedOnBase && !signedOnPr && contributorsModified;
// CLA is met if: (1) signed on both base and PR, OR (2) signed on base and didn't modify CONTRIBUTORS.md
const cla_met = (signedOnBase && signedOnPr) || (signedOnBase && !contributorsModified);
// Helper function to create or update a label with a specific color
async function ensureLabel(name, color, description) {
try {
await github.rest.issues.updateLabel({ owner, repo, name, color, description });
console.log(`Updated label: ${name} with color ${color}`);
} catch (error) {
// If update fails (label doesn't exist), create it
try {
await github.rest.issues.createLabel({ owner, repo, name, color, description });
console.log(`Created new label: ${name} with color ${color}`);
} catch (createError) {
console.log(`Error with label ${name}:`, createError.message);
}
}
}
// Define desired colors and descriptions for consistency
const COLOR_SIGNED = '0052cc'; // Blue
const COLOR_REQUIRED = 'b60205'; // Red
// 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(`CLA Met: ${cla_met} (Base: ${signedOnBase}, PR: ${signedOnPr}, Modified: ${contributorsModified}, Removed: ${removedFromPr})`);
// Handle case where contributor removed themselves from CONTRIBUTORS file
if (removedFromPr) {
await ensureLabel('cla-required', COLOR_REQUIRED, 'CLA signature is required for this PR.');
console.log('⚠️ Contributor was in base branch but removed from PR branch.');
// Ensure labels are correct
await Promise.allSettled([
github.rest.issues.removeLabel({ owner, repo, issue_number, name: 'cla-signed' }),
github.rest.issues.addLabels({ owner, repo, issue_number, labels: ['cla-required'] })
]);
// 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 removed yourself from the _CONTRIBUTORS.md_ file in this PR.\n\nPlease ensure your entry remains in the _CONTRIBUTORS.md_ file. If you have already signed the CLA, you should not remove your details from the file.`;
await github.rest.issues.createComment({ owner, repo, issue_number, body: commentBody });
// Fail the GitHub Action run
console.error("⚠️ Contributor removed themselves from CONTRIBUTORS file.");
process.exit(1);
}
if (cla_met) {
// 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' }),
github.rest.issues.addLabels({ owner, repo, issue_number, labels: ['cla-signed'] })
]);
// Delete old CLA comments since CLA is satisfied
await deleteOldClaComments();
} else if (!signedOnBase && signedOnPr) {
// New contributor signing CLA for the first time
await ensureLabel('cla-signed', COLOR_SIGNED, 'This contributor has signed the CLA.');
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.addLabels({ owner, repo, issue_number, labels: ['cla-signed'] })
]);
// Delete old CLA comments since CLA is now signed
await deleteOldClaComments();
} else {
await ensureLabel('cla-required', COLOR_REQUIRED, 'CLA signature is required for this PR.');
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.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);
}