-
Notifications
You must be signed in to change notification settings - Fork 362
Expand file tree
/
Copy pathgithubCodeReviewProvider.ts
More file actions
317 lines (290 loc) · 10.9 KB
/
githubCodeReviewProvider.ts
File metadata and controls
317 lines (290 loc) · 10.9 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
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
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type {
CodeReviewSystem,
DiffComment,
DiffId,
DiffSignalSummary,
Disposable,
Hash,
Result,
} from 'isl/src/types';
import type {CodeReviewProvider} from '../CodeReviewProvider';
import type {Logger} from '../logger';
import type {
MergeQueueSupportQueryData,
MergeQueueSupportQueryVariables,
PullRequestCommentsQueryData,
PullRequestCommentsQueryVariables,
PullRequestReviewComment,
PullRequestReviewDecision,
ReactionContent,
YourPullRequestsQueryData,
YourPullRequestsQueryVariables,
YourPullRequestsWithoutMergeQueueQueryData,
YourPullRequestsWithoutMergeQueueQueryVariables,
} from './generated/graphql';
import {TypedEventEmitter} from 'shared/TypedEventEmitter';
import {debounce} from 'shared/debounce';
import {notEmpty} from 'shared/utils';
import {
MergeQueueSupportQuery,
PullRequestCommentsQuery,
PullRequestState,
StatusState,
YourPullRequestsQuery,
YourPullRequestsWithoutMergeQueueQuery,
} from './generated/graphql';
import {parseStackInfo, type StackEntry} from './parseStackInfo';
import queryGraphQL from './queryGraphQL';
export type GitHubDiffSummary = {
type: 'github';
title: string;
commitMessage: string;
state: PullRequestState | 'DRAFT' | 'MERGE_QUEUED';
number: DiffId;
url: string;
commentCount: number;
anyUnresolvedComments: false;
signalSummary?: DiffSignalSummary;
reviewDecision?: PullRequestReviewDecision;
/** Base of the Pull Request (public parent), as it is on GitHub (may be out of date) */
base: Hash;
/** Head of the Pull Request (topmost commit), as it is on GitHub (may be out of date) */
head: Hash;
/** Name of the branch on GitHub, which should match the local bookmark */
branchName?: string;
/** Stack info parsed from PR body Sapling footer. Top-to-bottom order (first = top of stack). */
stackInfo?: StackEntry[];
};
const DEFAULT_GH_FETCH_TIMEOUT = 60_000; // 1 minute
type GitHubCodeReviewSystem = CodeReviewSystem & {type: 'github'};
export class GitHubCodeReviewProvider implements CodeReviewProvider {
constructor(
private codeReviewSystem: GitHubCodeReviewSystem,
private logger: Logger,
) {}
private diffSummaries = new TypedEventEmitter<'data', Map<DiffId, GitHubDiffSummary>>();
private hasMergeQueueSupport: Promise<boolean> | null = null;
onChangeDiffSummaries(
callback: (result: Result<Map<DiffId, GitHubDiffSummary>>) => unknown,
): Disposable {
const handleData = (data: Map<DiffId, GitHubDiffSummary>) => callback({value: data});
const handleError = (error: Error) => callback({error});
this.diffSummaries.on('data', handleData);
this.diffSummaries.on('error', handleError);
return {
dispose: () => {
this.diffSummaries.off('data', handleData);
this.diffSummaries.off('error', handleError);
},
};
}
private detectMergeQueueSupport(): Promise<boolean> {
if (this.hasMergeQueueSupport == null) {
this.hasMergeQueueSupport = (async (): Promise<boolean> => {
this.logger.info('detecting if merge queue is supported');
const data = await this.query<MergeQueueSupportQueryData, MergeQueueSupportQueryVariables>(
MergeQueueSupportQuery,
{},
10_000,
).catch(err => {
this.logger.info('failed to detect merge queue support', err);
return undefined;
});
const hasMergeQueueSupport = data?.__type != null;
this.logger.info('set merge queue support to ' + hasMergeQueueSupport);
return hasMergeQueueSupport;
})();
}
return this.hasMergeQueueSupport;
}
private fetchYourPullRequestsGraphQL(
includeMergeQueue: boolean,
): Promise<YourPullRequestsQueryData | undefined> {
// Calculate date 30 days ago for the updated filter
const thirtyDaysAgo = new Date();
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
const dateFilter = thirtyDaysAgo.toISOString().split('T')[0];
const variables = {
// Fetch all open PRs in the repo updated in the last 30 days
searchQuery: `repo:${this.codeReviewSystem.owner}/${this.codeReviewSystem.repo} is:pr is:open updated:>=${dateFilter}`,
numToFetch: 50,
};
if (includeMergeQueue) {
return this.query<YourPullRequestsQueryData, YourPullRequestsQueryVariables>(
YourPullRequestsQuery,
variables,
);
} else {
return this.query<
YourPullRequestsWithoutMergeQueueQueryData,
YourPullRequestsWithoutMergeQueueQueryVariables
>(YourPullRequestsWithoutMergeQueueQuery, variables);
}
}
triggerDiffSummariesFetch = debounce(
async () => {
try {
const hasMergeQueueSupport = await this.detectMergeQueueSupport();
this.logger.info('fetching github PR summaries');
const allSummaries = await this.fetchYourPullRequestsGraphQL(hasMergeQueueSupport);
if (allSummaries?.search.nodes == null) {
this.diffSummaries.emit('data', new Map());
return;
}
const map = new Map<DiffId, GitHubDiffSummary>();
for (const summary of allSummaries.search.nodes) {
if (summary != null && summary.__typename === 'PullRequest') {
const id = String(summary.number);
const commitMessage = summary.body.slice(summary.title.length + 1);
if (summary.baseRef?.target == null || summary.headRef?.target == null) {
this.logger.warn(`PR #${id} is missing base or head ref, skipping.`);
continue;
}
// Parse stack info from the PR body (Sapling footer format)
const stackInfo = parseStackInfo(summary.body) ?? undefined;
map.set(id, {
type: 'github',
title: summary.title,
commitMessage,
// For some reason, `isDraft` is a separate boolean and not a state,
// but we generally treat it as its own state in the UI.
state:
summary.isDraft && summary.state === PullRequestState.Open
? 'DRAFT'
: summary.mergeQueueEntry != null
? 'MERGE_QUEUED'
: summary.state,
number: id,
url: summary.url,
commentCount: summary.comments.totalCount,
anyUnresolvedComments: false,
signalSummary: githubStatusRollupStateToCIStatus(
summary.commits.nodes?.[0]?.commit.statusCheckRollup?.state,
),
reviewDecision: summary.reviewDecision ?? undefined,
base: summary.baseRef.target.oid,
head: summary.headRef.target.oid,
branchName: summary.headRef.name,
stackInfo,
});
}
}
this.logger.info(`fetched ${map.size} github PR summaries`);
this.diffSummaries.emit('data', map);
} catch (error) {
this.logger.info('error fetching github PR summaries: ', error);
this.diffSummaries.emit('error', error as Error);
}
},
2000,
undefined,
/* leading */ true,
);
public async fetchComments(diffId: string): Promise<DiffComment[]> {
const response = await this.query<
PullRequestCommentsQueryData,
PullRequestCommentsQueryVariables
>(PullRequestCommentsQuery, {
url: this.getPrUrl(diffId),
numToFetch: 50,
});
if (response == null) {
throw new Error(`Failed to fetch comments for ${diffId}`);
}
const pr = response?.resource as
| (PullRequestCommentsQueryData['resource'] & {__typename: 'PullRequest'})
| undefined;
const comments = pr?.comments.nodes ?? [];
const inline =
pr?.reviews?.nodes?.filter(notEmpty).flatMap(review => review.comments.nodes) ?? [];
this.logger.info(`fetched ${comments?.length} comments for github PR ${diffId}}`);
return (
[...comments, ...inline]?.filter(notEmpty).map(comment => {
return {
author: comment.author?.login ?? '',
authorAvatarUri: comment.author?.avatarUrl,
html: comment.bodyHTML,
created: new Date(comment.createdAt),
filename: (comment as PullRequestReviewComment).path ?? undefined,
line: (comment as PullRequestReviewComment).line ?? undefined,
reactions:
comment.reactions?.nodes
?.filter(
(reaction): reaction is {user: {login: string}; content: ReactionContent} =>
reaction?.user?.login != null,
)
.map(reaction => ({
name: reaction.user.login,
reaction: reaction.content,
})) ?? [],
replies: [], // PR top level doesn't have nested replies, you just reply to their name
};
}) ?? []
);
}
private query<D, V>(query: string, variables: V, timeoutMs?: number): Promise<D | undefined> {
return queryGraphQL<D, V>(
query,
variables,
this.codeReviewSystem.hostname,
timeoutMs ?? DEFAULT_GH_FETCH_TIMEOUT,
);
}
public dispose() {
this.diffSummaries.removeAllListeners();
this.triggerDiffSummariesFetch.dispose();
}
public getSummaryName(): string {
return `github:${this.codeReviewSystem.hostname}/${this.codeReviewSystem.owner}/${this.codeReviewSystem.repo}`;
}
public getPrUrl(diffId: DiffId): string {
return `https://${this.codeReviewSystem.hostname}/${this.codeReviewSystem.owner}/${this.codeReviewSystem.repo}/pull/${diffId}`;
}
public getDiffUrlMarkdown(diffId: DiffId): string {
return `[#${diffId}](${this.getPrUrl(diffId)})`;
}
public getCommitHashUrlMarkdown(hash: string): string {
return `[\`${hash.slice(0, 12)}\`](https://${this.codeReviewSystem.hostname}/${
this.codeReviewSystem.owner
}/${this.codeReviewSystem.repo}/commit/${hash})`;
}
getRemoteFileURL(
path: string,
publicCommitHash: string | null,
selectionStart?: {line: number; char: number},
selectionEnd?: {line: number; char: number},
): string {
const {hostname, owner, repo} = this.codeReviewSystem;
let url = `https://${hostname}/${owner}/${repo}/blob/${publicCommitHash ?? 'HEAD'}/${path}`;
if (selectionStart != null) {
url += `#L${selectionStart.line + 1}`;
if (
selectionEnd &&
(selectionEnd.line !== selectionStart.line || selectionEnd.char !== selectionStart.char)
) {
url += `C${selectionStart.char + 1}-L${selectionEnd.line + 1}C${selectionEnd.char + 1}`;
}
}
return url;
}
}
function githubStatusRollupStateToCIStatus(state: StatusState | undefined): DiffSignalSummary {
switch (state) {
case undefined:
case StatusState.Expected:
return 'no-signal';
case StatusState.Pending:
return 'running';
case StatusState.Error:
case StatusState.Failure:
return 'failed';
case StatusState.Success:
return 'pass';
}
}