-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
code-owners.ts
169 lines (143 loc) · 5 KB
/
code-owners.ts
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
import is from '@sindresorhus/is';
import ignore from 'ignore';
import { logger } from '../../../../logger';
import type { Pr } from '../../../../modules/platform';
import { readLocalFile } from '../../../../util/fs';
import { getBranchFiles } from '../../../../util/git';
import { newlineRegex, regEx } from '../../../../util/regex';
interface FileOwnerRule {
usernames: string[];
pattern: string;
score: number;
match: (path: string) => boolean;
}
function extractOwnersFromLine(line: string): FileOwnerRule {
const [pattern, ...usernames] = line.split(regEx(/\s+/));
const matchPattern = ignore().add(pattern);
return {
usernames,
pattern,
score: pattern.length,
match: (path: string) => matchPattern.ignores(path),
};
}
interface FileOwnersScore {
file: string;
userScoreMap: Map<string, number>;
}
function matchFileToOwners(
file: string,
rules: FileOwnerRule[],
): FileOwnersScore {
const usernames = new Map<string, number>();
for (const rule of rules) {
if (!rule.match(file)) {
continue;
}
for (const user of rule.usernames) {
usernames.set(user, rule.score);
}
}
return { file, userScoreMap: usernames };
}
interface OwnerFileScore {
username: string;
fileScoreMap: Map<string, number>;
}
function getOwnerList(filesWithOwners: FileOwnersScore[]): OwnerFileScore[] {
const userFileMap = new Map<string, Map<string, number>>();
for (const fileMatch of filesWithOwners) {
for (const [username, score] of fileMatch.userScoreMap.entries()) {
// Get / create user file score
const fileMap = userFileMap.get(username) ?? new Map<string, number>();
if (!userFileMap.has(username)) {
userFileMap.set(username, fileMap);
}
// Add file to user
fileMap.set(fileMatch.file, (fileMap.get(fileMatch.file) ?? 0) + score);
}
}
return Array.from(userFileMap.entries()).map(([key, value]) => ({
username: key,
fileScoreMap: value,
}));
}
export async function codeOwnersForPr(pr: Pr): Promise<string[]> {
logger.debug('Searching for CODEOWNERS file');
try {
// Find CODEOWNERS file
const codeOwnersFile =
(await readLocalFile('CODEOWNERS', 'utf8')) ??
(await readLocalFile('.bitbucket/CODEOWNERS', 'utf8')) ??
(await readLocalFile('.github/CODEOWNERS', 'utf8')) ??
(await readLocalFile('.gitlab/CODEOWNERS', 'utf8')) ??
(await readLocalFile('docs/CODEOWNERS', 'utf8'));
if (!codeOwnersFile) {
logger.debug('No CODEOWNERS file found');
return [];
}
logger.debug(`Found CODEOWNERS file: ${codeOwnersFile}`);
// Get list of modified files in PR
const prFiles = await getBranchFiles(pr.sourceBranch);
if (!prFiles?.length) {
logger.debug('PR includes no files');
return [];
}
// Convert CODEOWNERS file into list of matching rules
const fileOwnerRules = codeOwnersFile
.split(newlineRegex)
// Remove comments
.map((line) => line.split('#')[0])
// Remove empty lines
.map((line) => line.trim())
.filter(is.nonEmptyString)
// Extract pattern & usernames
.map(extractOwnersFromLine);
logger.debug(
{ prFiles, fileOwnerRules },
'PR files and rules to match for CODEOWNERS',
);
// Apply rules & get list of owners for each prFile
const emptyRules = fileOwnerRules.filter(
(rule) => rule.usernames.length === 0,
);
const fileOwners =
// Map through all prFiles and match said file(s) with all the rules
prFiles
.map((file) => matchFileToOwners(file, fileOwnerRules))
// Match file again but this time only with emptyRules, to ensure that files which have no owner set remain owner-less
.map((fileMatch) => {
const matchEmpty = emptyRules.find((rule) =>
rule.match(fileMatch.file),
);
if (matchEmpty) {
return { ...fileMatch, userScoreMap: new Map<string, number>() };
}
return fileMatch;
});
logger.debug(
`CODEOWNERS matched the following files: ${fileOwners
.map((f) => f.file)
.join(', ')}`,
);
// Get list of all matched users and the files they own (reverse keys of fileOwners)
const usersWithOwnedFiles = getOwnerList(fileOwners);
// Calculate a match score for each user. This allows sorting of the final user array in a way that guarantees that users matched with more precise patterns are first and users matched with less precise patterns are last (wildcards)
const userScore = usersWithOwnedFiles
.map((userMatch) => ({
user: userMatch.username,
score: Array.from(userMatch.fileScoreMap.values()).reduce(
(acc, score) => acc + score,
0,
),
}))
.sort((a, b) => b.score - a.score);
logger.debug(
`CODEOWNERS matched the following users: ${JSON.stringify(userScore)}`,
);
return userScore.map((u) => u.user);
} catch (err) {
logger.warn({ err, pr }, 'Failed to determine CODEOWNERS for PR.');
return [];
}
}