-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidate.ts
More file actions
223 lines (193 loc) · 6.63 KB
/
Copy pathvalidate.ts
File metadata and controls
223 lines (193 loc) · 6.63 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
import { groupBy, uniq } from "es-toolkit";
import type {
InfraConfig,
LabelGroups,
MembersFileInput,
RulesetConfig,
TeamsFile,
} from "@/types";
import { rulesetAppliesToRepo } from "./rulesets";
import type { ValidationIssue } from "./types";
import { issue, normalizeBranchPattern } from "./utils";
const compareStrings = (a: string, b: string) => a.localeCompare(b);
function rulesetStatusContexts(r: RulesetConfig): string[] {
const checks = r.rules.requiredStatusChecks;
if (!checks?.enabled) return [];
if (checks.requiredChecks?.length) {
return checks.requiredChecks.map((c) => c.context);
}
return checks.acceptAnyOf ?? [];
}
function statusCheckSetsCompatible(
rulesetContexts: string[],
bpContexts: string[],
): boolean {
if (rulesetContexts.length === 0 || bpContexts.length === 0) return true;
const rulesetSorted = [...rulesetContexts].sort(compareStrings);
const bpSorted = [...bpContexts].sort(compareStrings);
if (rulesetSorted.join() === bpSorted.join()) return true;
// acceptAnyOf: any listed name is valid; branch protection may pin one.
const rulesetSet = new Set(rulesetContexts);
return bpSorted.every((ctx) => rulesetSet.has(ctx));
}
type RepoCondition = { includes: string[]; excludes: string[] };
function repoCondition(r: RulesetConfig): RepoCondition {
return {
includes: r.conditions.repositoryName?.includes ?? ["~ALL"],
excludes: r.conditions.repositoryName?.excludes ?? [],
};
}
// Conservative overlap test: ~ALL overlaps everything; otherwise the
// include lists must intersect. Excludes are ignored (may report a
// theoretical overlap that excludes actually prevent — acceptable:
// false positive here is a warning to a human, not a failure).
function repoSetsOverlap(a: RepoCondition, b: RepoCondition): boolean {
if (a.includes.includes("~ALL") || b.includes.includes("~ALL")) return true;
return a.includes.some((name) => b.includes.includes(name));
}
function validateTeamRefs(config: InfraConfig): ValidationIssue[] {
const { repos, teams } = config;
const teamSlugs = new Set(teams.teams.map((t) => t.slug));
const repoNames = new Set(repos.map((r) => r.name));
return [
...Object.keys(teams.repoAccess)
.filter((name) => !repoNames.has(name))
.map((name) =>
issue(`teams.repoAccess.${name}`, `unknown repo "${name}"`),
),
...Object.entries(teams.repoAccess).flatMap(([repoName, access]) =>
access
.filter((e) => !teamSlugs.has(e.team))
.map((e) =>
issue(`teams.repoAccess.${repoName}`, `unknown team "${e.team}"`),
),
),
...repos.flatMap((repo) =>
(repo.environments ?? []).flatMap((env) =>
(env.requiredReviewerTeamSlugs ?? [])
.filter((slug) => !teamSlugs.has(slug))
.map((slug) =>
issue(
`repos.${repo.name}.environments.${env.name}`,
`unknown team "${slug}"`,
),
),
),
),
];
}
export function validateMemberRefs(
teamsFile: TeamsFile,
membersFile: MembersFileInput,
): ValidationIssue[] {
const teamSlugs = new Set(teamsFile.teams.map((t) => t.slug));
return membersFile.members.flatMap((member, i) =>
member.teams
.filter(({ slug }) => !teamSlugs.has(slug))
.map(({ slug }, j) =>
issue(`members.${i}.teams.${j}.slug`, `unknown team "${slug}"`),
),
);
}
function validateRulesetPatterns(config: InfraConfig): ValidationIssue[] {
const { org, rulesets } = config;
const defaultBranch = org.defaults.defaultBranch;
const patternOwners = groupBy(
rulesets
.filter((r) => r.target === "branch" && r.enforcement !== "disabled")
.flatMap((r) =>
r.conditions.refName.includes.map((raw) => ({
pattern: normalizeBranchPattern(raw, defaultBranch),
ruleset: r,
})),
),
(x) => x.pattern,
);
return Object.entries(patternOwners).flatMap(([pattern, entries]) => {
const rulesetsAtPattern = uniq(entries.map((e) => e.ruleset));
if (rulesetsAtPattern.length <= 1) return [];
const conflicting = rulesetsAtPattern.filter((r) =>
rulesetsAtPattern.some(
(other) =>
other.id !== r.id &&
repoSetsOverlap(repoCondition(r), repoCondition(other)),
),
);
if (conflicting.length <= 1) return [];
return [
issue(
"rulesets",
`branch pattern "${pattern}" appears in multiple rulesets (${uniq(conflicting.map((r) => r.id)).join(", ")})`,
),
];
});
}
function validateRulesetBranchProtectionOverlap(
config: InfraConfig,
): ValidationIssue[] {
const { org, repos, rulesets } = config;
const defaultBranch = org.defaults.defaultBranch;
const activeBranchRulesets = rulesets.filter(
(r) => r.target === "branch" && r.enforcement !== "disabled",
);
return activeBranchRulesets.flatMap((r) => {
const rulesetPatterns = new Set(
r.conditions.refName.includes.map((raw) =>
normalizeBranchPattern(raw, defaultBranch),
),
);
const rulesetContexts = rulesetStatusContexts(r);
return repos.flatMap((repo) => {
if (!rulesetAppliesToRepo(r, repo.name) || !repo.branchProtection) {
return [];
}
return Object.entries(repo.branchProtection).flatMap(([pattern, bp]) => {
// Exact match after normalization only — glob-pattern overlap
// (e.g. BP release/* vs ruleset release/v*) is out of scope.
const normalizedBp = normalizeBranchPattern(pattern, defaultBranch);
if (!rulesetPatterns.has(normalizedBp)) return [];
const bpContexts = bp.requiredStatusChecks ?? [];
if (rulesetContexts.length === 0 || bpContexts.length === 0) {
return [];
}
if (statusCheckSetsCompatible(rulesetContexts, bpContexts)) return [];
const rulesetSorted = [...rulesetContexts].sort(compareStrings);
const bpSorted = [...bpContexts].sort(compareStrings);
return [
issue(
`repos.${repo.name}.branchProtection.${pattern}`,
`org ruleset "${r.id}" also targets "${pattern}" with different required status checks (ruleset: [${rulesetSorted.join(", ")}], repo: [${bpSorted.join(", ")}]); PRs must satisfy the union of both`,
"warning",
),
];
});
});
});
}
function validateLabelGroups(labelGroups: LabelGroups): ValidationIssue[] {
const labelOwners = groupBy(
Object.entries(labelGroups).flatMap(([group, labels]) =>
Object.keys(labels).map((name) => ({ name, group })),
),
(x) => x.name,
);
return Object.entries(labelOwners)
.filter(([, owners]) => owners.length > 1)
.map(([name, owners]) =>
issue(
`labels.${name}`,
`defined in multiple groups (${owners.map((o) => o.group).join(", ")})`,
),
);
}
export function validateCrossRefs(
config: InfraConfig,
labelGroups: LabelGroups,
): ValidationIssue[] {
return [
...validateTeamRefs(config),
...validateRulesetPatterns(config),
...validateRulesetBranchProtectionOverlap(config),
...validateLabelGroups(labelGroups),
];
}