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
|
export type LintSeverity = "error" | "warning" | "info";
export type LintCode =
| "empty_pattern"
| "no_owners"
| "bad_owner_format"
| "unknown_user"
| "unknown_team"
| "duplicate_pattern"
| "duplicate_owner"
| "missing_catchall"
| "empty_file"
| "bad_pattern_syntax";
export interface LintFinding {
line: number;
code: LintCode;
severity: LintSeverity;
message: string;
pattern?: string;
token?: string;
}
export interface LexedRule {
line: number;
raw: string;
pattern: string;
owners: string[];
}
export interface LintReport {
totalLines: number;
totalRules: number;
rules: LexedRule[];
findings: LintFinding[];
errors: LintFinding[];
warnings: LintFinding[];
infos: LintFinding[];
ok: boolean;
}
export interface OwnerResolver {
isUser: (username: string) => boolean | Promise<boolean>;
isTeam: (org: string, team: string) => boolean | Promise<boolean>;
}
export function lexCodeowners(content: string): {
rules: LexedRule[];
malformedLines: Array<{ line: number; raw: string }>;
totalLines: number;
} {
const rules: LexedRule[] = [];
const malformed: Array<{ line: number; raw: string }> = [];
const lines = content.split(/\r?\n/);
lines.forEach((raw, idx) => {
const lineNo = idx + 1;
const trimmed = raw.replace(/#.*$/, "").trim();
if (!trimmed) return;
const parts = trimmed.split(/\s+/);
if (parts.length === 1) {
malformed.push({ line: lineNo, raw });
return;
}
const pattern = parts[0];
const owners = parts
.slice(1)
.map((o) => o.replace(/^@/, "").trim())
.filter(Boolean);
rules.push({ line: lineNo, raw, pattern, owners });
});
return { rules, malformedLines: malformed, totalLines: lines.length };
}
export type OwnerTokenKind = "user" | "team" | "email" | "invalid";
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const USER_RE = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/;
const TEAM_RE = /^[A-Za-z0-9][A-Za-z0-9-]{0,38}\/[A-Za-z0-9][A-Za-z0-9_-]{0,38}$/;
export function classifyOwnerToken(
tokenWithoutAt: string,
hadAt: boolean
): OwnerTokenKind {
if (!tokenWithoutAt) return "invalid";
if (!hadAt && EMAIL_RE.test(tokenWithoutAt)) return "email";
if (!hadAt) return "invalid";
if (tokenWithoutAt.includes("/")) {
return TEAM_RE.test(tokenWithoutAt) ? "team" : "invalid";
}
return USER_RE.test(tokenWithoutAt) ? "user" : "invalid";
}
export function isPlausiblePattern(pat: string): boolean {
if (!pat) return false;
if (/\s/.test(pat)) return false;
let depth = 0;
for (const ch of pat) {
if (ch === "[") depth++;
if (ch === "]") depth--;
if (depth < 0) return false;
}
if (depth !== 0) return false;
return true;
}
export async function validateCodeowners(
content: string,
resolver: OwnerResolver
): Promise<LintReport> {
const lex = lexCodeowners(content);
const findings: LintFinding[] = [];
if (content.trim().length === 0) {
findings.push({
line: 1,
code: "empty_file",
severity: "warning",
message:
"CODEOWNERS file is empty — no ownership rules are being enforced.",
});
return assembleReport(lex.rules, findings, lex.totalLines);
}
for (const m of lex.malformedLines) {
findings.push({
line: m.line,
code: "no_owners",
severity: "error",
message:
"Rule declares a pattern but no owners. Each rule must list at least one @user, @org/team, or email.",
});
}
const seenPatterns = new Map<string, number>();
for (const rule of lex.rules) {
if (!rule.pattern) {
findings.push({
line: rule.line,
code: "empty_pattern",
severity: "error",
message: "Rule has no pattern.",
});
continue;
}
if (!isPlausiblePattern(rule.pattern)) {
findings.push({
line: rule.line,
code: "bad_pattern_syntax",
severity: "error",
message: `Pattern \"${rule.pattern}\" looks malformed (unbalanced brackets or whitespace).`,
pattern: rule.pattern,
});
}
if (seenPatterns.has(rule.pattern)) {
findings.push({
line: rule.line,
code: "duplicate_pattern",
severity: "warning",
message: `Pattern \"${rule.pattern}\" was already declared on line ${seenPatterns.get(
rule.pattern
)}. The later rule wins.`,
pattern: rule.pattern,
});
} else {
seenPatterns.set(rule.pattern, rule.line);
}
const seenOwners = new Set<string>();
const rawOwners = rule.raw
.replace(/#.*$/, "")
.trim()
.split(/\s+/)
.slice(1);
for (let i = 0; i < rule.owners.length; i++) {
const owner = rule.owners[i];
const rawToken = rawOwners[i] ?? owner;
const hadAt = rawToken.startsWith("@");
if (seenOwners.has(owner)) {
findings.push({
line: rule.line,
code: "duplicate_owner",
severity: "warning",
message: `Owner \"${owner}\" listed more than once on this rule.`,
pattern: rule.pattern,
token: owner,
});
continue;
}
seenOwners.add(owner);
const kind = classifyOwnerToken(owner, hadAt);
if (kind === "invalid") {
findings.push({
line: rule.line,
code: "bad_owner_format",
severity: "error",
message: `Owner \"${rawToken}\" isn't a valid @user, @org/team, or email.`,
pattern: rule.pattern,
token: rawToken,
});
continue;
}
if (kind === "user") {
const ok = await resolver.isUser(owner);
if (!ok) {
findings.push({
line: rule.line,
code: "unknown_user",
severity: "error",
message: `User @${owner} does not exist on this instance.`,
pattern: rule.pattern,
token: owner,
});
}
} else if (kind === "team") {
const [orgSlug, teamSlug] = owner.split("/");
const ok = await resolver.isTeam(orgSlug, teamSlug);
if (!ok) {
findings.push({
line: rule.line,
code: "unknown_team",
severity: "error",
message: `Team @${owner} does not exist on this instance.`,
pattern: rule.pattern,
token: owner,
});
}
}
}
}
const hasCatchAll = lex.rules.some(
(r) => r.pattern === "*" || r.pattern === "/*"
);
if (!hasCatchAll && lex.rules.length > 0) {
findings.push({
line: 1,
code: "missing_catchall",
severity: "info",
message:
"No catch-all rule (`* @owner`). Files outside any pattern will have no reviewer auto-assigned.",
});
}
return assembleReport(lex.rules, findings, lex.totalLines);
}
function assembleReport(
rules: LexedRule[],
findings: LintFinding[],
totalLines: number
): LintReport {
const severityRank: Record<LintSeverity, number> = {
error: 0,
warning: 1,
info: 2,
};
findings.sort((a, b) => {
if (a.line !== b.line) return a.line - b.line;
return severityRank[a.severity] - severityRank[b.severity];
});
const errors = findings.filter((f) => f.severity === "error");
const warnings = findings.filter((f) => f.severity === "warning");
const infos = findings.filter((f) => f.severity === "info");
return {
totalLines,
totalRules: rules.length,
rules,
findings,
errors,
warnings,
infos,
ok: errors.length === 0,
};
}
export const __internal = {
EMAIL_RE,
USER_RE,
TEAM_RE,
lexCodeowners,
classifyOwnerToken,
isPlausiblePattern,
validateCodeowners,
assembleReport,
};
|