-
Notifications
You must be signed in to change notification settings - Fork 31.8k
/
Copy pathbranchProtection.ts
244 lines (202 loc) · 8.6 KB
/
branchProtection.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
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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { authentication, EventEmitter, LogOutputChannel, Memento, Uri, workspace } from 'vscode';
import { Repository as GitHubRepository, RepositoryRuleset } from '@octokit/graphql-schema';
import { AuthenticationError, getOctokitGraphql } from './auth.js';
import { API, BranchProtection, BranchProtectionProvider, BranchProtectionRule, Repository } from './typings/git.js';
import { DisposableStore, getRepositoryFromUrl } from './util.js';
import TelemetryReporter from '@vscode/extension-telemetry';
const REPOSITORY_QUERY = `
query repositoryPermissions($owner: String!, $repo: String!) {
repository(owner: $owner, name: $repo) {
defaultBranchRef {
name
},
viewerPermission
}
}
`;
const REPOSITORY_RULESETS_QUERY = `
query repositoryRulesets($owner: String!, $repo: String!, $cursor: String, $limit: Int = 100) {
repository(owner: $owner, name: $repo) {
rulesets(includeParents: true, first: $limit, after: $cursor) {
nodes {
name
enforcement
rules(type: PULL_REQUEST) {
totalCount
}
conditions {
refName {
include
exclude
}
}
target
},
pageInfo {
endCursor,
hasNextPage
}
}
}
}
`;
export class GitHubBranchProtectionProviderManager {
private readonly disposables = new DisposableStore();
private readonly providerDisposables = new DisposableStore();
private _enabled = false;
private set enabled(enabled: boolean) {
if (this._enabled === enabled) {
return;
}
if (enabled) {
for (const repository of this.gitAPI.repositories) {
this.providerDisposables.add(this.gitAPI.registerBranchProtectionProvider(repository.rootUri, new GitHubBranchProtectionProvider(repository, this.globalState, this.logger, this.telemetryReporter)));
}
} else {
this.providerDisposables.dispose();
}
this._enabled = enabled;
}
constructor(
private readonly gitAPI: API,
private readonly globalState: Memento,
private readonly logger: LogOutputChannel,
private readonly telemetryReporter: TelemetryReporter.default) {
this.disposables.add(this.gitAPI.onDidOpenRepository(repository => {
if (this._enabled) {
this.providerDisposables.add(gitAPI.registerBranchProtectionProvider(repository.rootUri, new GitHubBranchProtectionProvider(repository, this.globalState, this.logger, this.telemetryReporter)));
}
}));
this.disposables.add(workspace.onDidChangeConfiguration(e => {
if (e.affectsConfiguration('github.branchProtection')) {
this.updateEnablement();
}
}));
this.updateEnablement();
}
private updateEnablement(): void {
const config = workspace.getConfiguration('github', null);
this.enabled = config.get<boolean>('branchProtection', true) === true;
}
dispose(): void {
this.enabled = false;
this.disposables.dispose();
}
}
export class GitHubBranchProtectionProvider implements BranchProtectionProvider {
private readonly _onDidChangeBranchProtection = new EventEmitter<Uri>();
onDidChangeBranchProtection = this._onDidChangeBranchProtection.event;
private branchProtection: BranchProtection[];
private readonly globalStateKey = `branchProtection:${this.repository.rootUri.toString()}`;
constructor(
private readonly repository: Repository,
private readonly globalState: Memento,
private readonly logger: LogOutputChannel,
private readonly telemetryReporter: TelemetryReporter.default) {
// Restore branch protection from global state
this.branchProtection = this.globalState.get<BranchProtection[]>(this.globalStateKey, []);
repository.status().then(() => {
authentication.onDidChangeSessions(e => {
if (e.provider.id === 'github') {
this.updateRepositoryBranchProtection();
}
});
this.updateRepositoryBranchProtection();
});
}
provideBranchProtection(): BranchProtection[] {
return this.branchProtection;
}
private async getRepositoryDetails(owner: string, repo: string): Promise<GitHubRepository> {
const graphql = await getOctokitGraphql();
const { repository } = await graphql<{ repository: GitHubRepository }>(REPOSITORY_QUERY, { owner, repo });
return repository;
}
private async getRepositoryRulesets(owner: string, repo: string): Promise<RepositoryRuleset[]> {
const rulesets: RepositoryRuleset[] = [];
let cursor: string | undefined = undefined;
const graphql = await getOctokitGraphql();
while (true) {
const { repository } = await graphql<{ repository: GitHubRepository }>(REPOSITORY_RULESETS_QUERY, { owner, repo, cursor });
rulesets.push(...(repository.rulesets?.nodes ?? [])
// Active branch ruleset that contains the pull request required rule
.filter(node => node && node.target === 'BRANCH' && node.enforcement === 'ACTIVE' && (node.rules?.totalCount ?? 0) > 0) as RepositoryRuleset[]);
if (repository.rulesets?.pageInfo.hasNextPage) {
cursor = repository.rulesets.pageInfo.endCursor as string | undefined;
} else {
break;
}
}
return rulesets;
}
private async updateRepositoryBranchProtection(): Promise<void> {
const branchProtection: BranchProtection[] = [];
try {
for (const remote of this.repository.state.remotes) {
const repository = getRepositoryFromUrl(remote.pushUrl ?? remote.fetchUrl ?? '');
if (!repository) {
continue;
}
// Repository details
this.logger.trace(`[GitHubBranchProtectionProvider][updateRepositoryBranchProtection] Fetching repository details for "${repository.owner}/${repository.repo}".`);
const repositoryDetails = await this.getRepositoryDetails(repository.owner, repository.repo);
// Check repository write permission
if (repositoryDetails.viewerPermission !== 'ADMIN' && repositoryDetails.viewerPermission !== 'MAINTAIN' && repositoryDetails.viewerPermission !== 'WRITE') {
this.logger.trace(`[GitHubBranchProtectionProvider][updateRepositoryBranchProtection] Skipping branch protection for "${repository.owner}/${repository.repo}" due to missing repository write permission.`);
continue;
}
// Get repository rulesets
const branchProtectionRules: BranchProtectionRule[] = [];
const repositoryRulesets = await this.getRepositoryRulesets(repository.owner, repository.repo);
for (const ruleset of repositoryRulesets) {
branchProtectionRules.push({
include: (ruleset.conditions.refName?.include ?? []).map(r => this.parseRulesetRefName(repositoryDetails, r)),
exclude: (ruleset.conditions.refName?.exclude ?? []).map(r => this.parseRulesetRefName(repositoryDetails, r))
});
}
branchProtection.push({ remote: remote.name, rules: branchProtectionRules });
}
this.branchProtection = branchProtection;
this._onDidChangeBranchProtection.fire(this.repository.rootUri);
// Save branch protection to global state
await this.globalState.update(this.globalStateKey, branchProtection);
this.logger.trace(`[GitHubBranchProtectionProvider][updateRepositoryBranchProtection] Branch protection for "${this.repository.rootUri.toString()}": ${JSON.stringify(branchProtection)}.`);
/* __GDPR__
"branchProtection" : {
"owner": "lszomoru",
"rulesetCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true, "comment": "Number of repository rulesets" }
}
*/
this.telemetryReporter.sendTelemetryEvent('branchProtection', undefined, { rulesetCount: this.branchProtection.length });
} catch (err) {
this.logger.warn(`[GitHubBranchProtectionProvider][updateRepositoryBranchProtection] Failed to update repository branch protection: ${err.message}`);
if (err instanceof AuthenticationError) {
// A GitHub authentication session could be missing if the user has not yet
// signed in with their GitHub account or they have signed out. If there is
// branch protection information we have to clear it.
if (this.branchProtection.length !== 0) {
this.branchProtection = branchProtection;
this._onDidChangeBranchProtection.fire(this.repository.rootUri);
await this.globalState.update(this.globalStateKey, undefined);
}
}
}
}
private parseRulesetRefName(repository: GitHubRepository, refName: string): string {
if (refName.startsWith('refs/heads/')) {
return refName.substring(11);
}
switch (refName) {
case '~ALL':
return '**/*';
case '~DEFAULT_BRANCH':
return repository.defaultBranchRef!.name;
default:
return refName;
}
}
}