-
Notifications
You must be signed in to change notification settings - Fork 1.1k
186 lines (160 loc) · 7.07 KB
/
codeowner_review_status.yml
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
name: Code Owners Approval Check
on:
pull_request:
branches:
- master
types: [opened, synchronize, reopened, ready_for_review]
pull_request_review:
types: [submitted, dismissed]
permissions: {}
jobs:
check-code-owners-approval:
runs-on: ubuntu-latest
if: github.base_ref == 'master'
permissions:
pull-requests: write
contents: read
steps:
- name: Check Code Owners Approval
id: check_approvals
uses: actions/github-script@v7
with:
github-token: ${{secrets.GITHUB_TOKEN}}
script: |
const { owner, repo, number } = context.issue;
// Get pull request details and files
const { data: pr } = await github.rest.pulls.get({ owner, repo, pull_number: number });
const { data: files } = await github.rest.pulls.listFiles({ owner, repo, pull_number: number });
// Get CODEOWNERS file content
let codeowners;
try {
const { data } = await github.rest.repos.getContent({
owner,
repo,
path: '.github/CODEOWNERS',
});
codeowners = Buffer.from(data.content, 'base64').toString('utf8');
} catch (error) {
console.log('CODEOWNERS file not found in .github directory. Skipping check.');
return;
}
// Parse CODEOWNERS file
const codeownersRules = codeowners.split('\n')
.filter(line => line.trim() && !line.startsWith('#'))
.map(line => {
const [pattern, ...owners] = line.split(/\s+/);
return { pattern, owners: owners.map(o => o.trim()) };
});
// Function to check if a file matches a pattern
const matchesPattern = (file, pattern) => {
// Handle directory patterns
if (pattern.endsWith('/')) {
return file.startsWith(pattern);
}
// Handle glob patterns
let regexPattern = pattern
.replace(/\./g, '\\.')
.replace(/\*/g, '[^/]*')
.replace(/\?/g, '[^/]')
.replace(/\//g, '\\/')
.replace(/\*\*/g, '.*');
// For double-star patterns, match any depth
if (pattern.includes('**')) {
return new RegExp(`^${regexPattern}`).test(file);
}
// For patterns without wildcards, check if the file is in the directory or is the file itself
if (!pattern.includes('*') && !pattern.includes('?')) {
return file === pattern || file.startsWith(pattern + '/');
}
// For single-star patterns, don't match across directory boundaries
return new RegExp(`^${regexPattern}$`).test(file);
};
// Get relevant code owners for the changed files
const relevantOwners = new Set();
const defaultOwner = codeownersRules.find(rule => rule.pattern === '*')?.owners[0];
files.forEach(file => {
let fileOwners = new Set();
let hasSpecificOwner = false;
codeownersRules.forEach(rule => {
if (matchesPattern(file.filename, rule.pattern)) {
rule.owners.forEach(owner => {
fileOwners.add(owner);
if (rule.pattern !== '*') {
hasSpecificOwner = true;
}
});
}
});
// If no specific owners found or only the default owner was found, use the default owner
if (!hasSpecificOwner && defaultOwner) {
fileOwners.add(defaultOwner);
}
fileOwners.forEach(owner => relevantOwners.add(owner));
});
if (relevantOwners.size === 0) {
console.log('No relevant code owners found for the changed files. Skipping check.');
return;
}
// Get reviews
const { data: reviews } = await github.rest.pulls.listReviews({ owner, repo, pull_number: number });
const approvals = new Set(
reviews
.filter(review => review.state === 'APPROVED')
.map(review => `@DataDog/${review.user.login}`)
);
const codeOwnerStatus = Array.from(relevantOwners).map(owner => ({
owner,
approved: approvals.has(owner)
}));
const missingApprovals = codeOwnerStatus.filter(status => !status.approved);
if (missingApprovals.length > 0) {
core.setFailed(`Missing approvals from code owners: ${missingApprovals.map(status => status.owner).join(', ')}`);
} else {
console.log('All relevant code owners have approved the pull request.');
}
core.setOutput('codeOwnerStatus', JSON.stringify(codeOwnerStatus));
- name: Update PR status
if: always()
uses: actions/github-script@v7
with:
github-token: ${{secrets.GITHUB_TOKEN}}
script: |
const { owner, repo, number } = context.issue;
const codeOwnerStatus = JSON.parse(process.env.CODE_OWNER_STATUS);
const statusList = codeOwnerStatus.map(status => {
const emoji = status.approved ? '✅' : '❌';
return `${emoji} ${status.owner}`;
}).join('\n');
const commentBody = `## Code Owners Approval Status
${statusList}
${codeOwnerStatus.every(status => status.approved)
? '✅ All required code owners have approved this pull request.'
: '❌ This pull request is still missing approvals from one or more code owners.'}`;
// Find existing bot comment
const { data: comments } = await github.rest.issues.listComments({
owner,
repo,
issue_number: number,
});
const botComment = comments.find(comment =>
comment.user.type === 'Bot' && comment.body.includes('Code Owners Approval Status')
);
if (botComment) {
// Update existing comment
await github.rest.issues.updateComment({
owner,
repo,
comment_id: botComment.id,
body: commentBody,
});
} else {
// Create new comment
await github.rest.issues.createComment({
owner,
repo,
issue_number: number,
body: commentBody,
});
}
env:
CODE_OWNER_STATUS: ${{ steps.check_approvals.outputs.codeOwnerStatus }}