♻️ refactor: update codeowners-enforcement.ts
swadhinbiswas committed 3 months ago
2816e0e
1 parent 4647d12
commit 2816e0e
1 file changed
+43 -0
Showing 1 changed file+43-0
▼src/lib/codeowners-enforcement.ts
+43-0
| @@ -18,6 +18,49 @@ interface CodeOwnerCheck { | ||
18 | 18 | }[]; |
19 | 19 | } |
20 | 20 | |
21 | +export function branchRuleMatches(pattern: string, branch: string): boolean { | |
22 | + if (pattern === branch) return true; | |
23 | + if (pattern.endsWith("*")) return branch.startsWith(pattern.slice(0, -1)); | |
24 | + return false; | |
25 | +} | |
26 | + | |
27 | +export async function isCodeOwnerEnforced( | |
28 | + repositoryId: string, | |
29 | + baseBranch: string, | |
30 | + prStateId?: string | null | |
31 | +): Promise<boolean> { | |
32 | + const db = getDatabase(); | |
33 | + | |
34 | + // 1. Check Custom PR State | |
35 | + if (prStateId) { | |
36 | + const stateDef = await db.query.prStateDefinitions?.findFirst({ | |
37 | + where: eq(schema.prStateDefinitions.id, prStateId) | |
38 | + }); | |
39 | + if (stateDef?.requireCodeOwner) return true; | |
40 | + } | |
41 | + | |
42 | + // 2. Check Global Review Policy | |
43 | + const reviewRequirements = await db.query.reviewRequirements?.findFirst({ | |
44 | + where: eq(schema.reviewRequirements.repositoryId, repositoryId) | |
45 | + }); | |
46 | + if (reviewRequirements?.requireCodeOwner) return true; | |
47 | + | |
48 | + // 3. Check Branch Protection Rules | |
49 | + const protectionRules = await db.query.branchProtection?.findMany({ | |
50 | + where: and( | |
51 | + eq(schema.branchProtection.repositoryId, repositoryId), | |
52 | + eq(schema.branchProtection.active, true) | |
53 | + ) | |
54 | + }); | |
55 | + | |
56 | + if (protectionRules) { | |
57 | + const matchingRule = protectionRules.find(rule => branchRuleMatches(rule.pattern, baseBranch)); | |
58 | + if (matchingRule?.requireCodeOwnerReviews) return true; | |
59 | + } | |
60 | + | |
61 | + return false; | |
62 | +} | |
63 | + | |
21 | 64 | /** |
22 | 65 | * Check if all required code owners have approved a PR |
23 | 66 | */ |
24 | 67 | |