forked from microsoft/vscode-pull-request-github
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpullRequestReviewCommon.ts
More file actions
527 lines (470 loc) · 19.9 KB
/
pullRequestReviewCommon.ts
File metadata and controls
527 lines (470 loc) · 19.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
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as vscode from 'vscode';
import { FolderRepositoryManager } from './folderRepositoryManager';
import { IAccount, isITeam, ITeam, MergeMethod, PullRequestMergeability, reviewerId, ReviewState } from './interface';
import { BranchInfo } from './pullRequestGitHelper';
import { PullRequestModel } from './pullRequestModel';
import { ConvertToDraftReply, PullRequest, ReadyForReviewReply, ReviewType, SubmitReviewReply } from './views';
import { DEFAULT_DELETION_METHOD, PR_SETTINGS_NAMESPACE, SELECT_LOCAL_BRANCH, SELECT_REMOTE } from '../common/settingKeys';
import { ReviewEvent, TimelineEvent } from '../common/timelineEvent';
import { Schemes } from '../common/uri';
import { formatError } from '../common/utils';
import { IRequestMessage } from '../common/webview';
/**
* Context required by review utility functions
*/
export interface ReviewContext {
item: PullRequestModel;
folderRepositoryManager: FolderRepositoryManager;
existingReviewers: ReviewState[];
postMessage(message: any): Promise<void>;
replyMessage(message: IRequestMessage<any>, response: any): void;
throwError(message: IRequestMessage<any> | undefined, error: string): void;
getTimeline(): Promise<TimelineEvent[]>;
}
/**
* Utility functions for handling pull request reviews.
* These are shared between PullRequestOverviewPanel and PullRequestViewProvider.
*/
export namespace PullRequestReviewCommon {
/**
* Find currently configured user's review status for the current PR
*/
export function getCurrentUserReviewState(reviewers: ReviewState[], currentUser: IAccount): string | undefined {
const review = reviewers.find(r => reviewerId(r.reviewer) === currentUser.login);
// There will always be a review. If not then the PR shouldn't have been or fetched/shown for the current user
return review?.state;
}
function updateReviewers(existingReviewers: ReviewState[], review?: ReviewEvent): void {
if (review && review.state) {
const existingReviewer = existingReviewers.find(
reviewer => review.user.login === reviewerId(reviewer.reviewer),
);
if (existingReviewer) {
existingReviewer.state = review.state;
} else {
existingReviewers.push({
reviewer: review.user,
state: review.state,
});
}
}
}
export async function doReviewCommand(
ctx: ReviewContext,
context: { body: string },
reviewType: ReviewType,
needsTimelineRefresh: boolean,
action: (body: string) => Promise<ReviewEvent>,
): Promise<ReviewEvent | undefined> {
const submittingMessage = {
command: 'pr.submitting-review',
lastReviewType: reviewType
};
ctx.postMessage(submittingMessage);
try {
const review = await action(context.body);
updateReviewers(ctx.existingReviewers, review);
const allEvents = needsTimelineRefresh ? await ctx.getTimeline() : [];
const reviewMessage: SubmitReviewReply & { command: string } = {
command: 'pr.append-review',
reviewedEvent: review,
events: allEvents,
reviewers: ctx.existingReviewers
};
await ctx.postMessage(reviewMessage);
return review;
} catch (e) {
vscode.window.showErrorMessage(vscode.l10n.t('Submitting review failed. {0}', formatError(e)));
ctx.throwError(undefined, `${formatError(e)}`);
await ctx.postMessage({ command: 'pr.append-review' });
}
}
export async function doReviewMessage(
ctx: ReviewContext,
message: IRequestMessage<string>,
needsTimelineRefresh: boolean,
action: (body: string) => Promise<ReviewEvent>,
): Promise<ReviewEvent | undefined> {
try {
const review = await action(message.args);
updateReviewers(ctx.existingReviewers, review);
const allEvents = needsTimelineRefresh ? await ctx.getTimeline() : [];
const reply: SubmitReviewReply = {
reviewedEvent: review,
events: allEvents,
reviewers: ctx.existingReviewers,
};
ctx.replyMessage(message, reply);
return review;
} catch (e) {
vscode.window.showErrorMessage(vscode.l10n.t('Submitting review failed. {0}', formatError(e)));
ctx.throwError(message, `${formatError(e)}`);
}
}
export function reRequestReview(ctx: ReviewContext, message: IRequestMessage<string>): void {
let targetReviewer: ReviewState | undefined;
const userReviewers: IAccount[] = [];
const teamReviewers: ITeam[] = [];
for (const reviewer of ctx.existingReviewers) {
let id = reviewer.reviewer.id;
if (id && ((reviewer.state === 'REQUESTED') || (id === message.args))) {
if (id === message.args) {
targetReviewer = reviewer;
}
}
}
if (targetReviewer && isITeam(targetReviewer.reviewer)) {
teamReviewers.push(targetReviewer.reviewer);
} else if (targetReviewer && !isITeam(targetReviewer.reviewer)) {
userReviewers.push(targetReviewer.reviewer);
}
ctx.item.requestReview(userReviewers, teamReviewers, true).then(() => {
if (targetReviewer) {
targetReviewer.state = 'REQUESTED';
}
ctx.replyMessage(message, {
reviewers: ctx.existingReviewers,
});
});
}
export async function checkoutDefaultBranch(ctx: ReviewContext, message: IRequestMessage<string>): Promise<void> {
try {
const prBranch = ctx.folderRepositoryManager.repository.state.HEAD?.name;
await ctx.folderRepositoryManager.checkoutDefaultBranch(message.args, ctx.item);
if (prBranch) {
await ctx.folderRepositoryManager.cleanupAfterPullRequest(prBranch, ctx.item);
}
} finally {
// Complete webview promise so that button becomes enabled again
ctx.replyMessage(message, {});
}
}
export async function updateBranch(
ctx: ReviewContext,
message: IRequestMessage<string>,
refreshAfterUpdate: () => Promise<void>,
checkUpdateEnabled?: () => boolean
): Promise<void> {
// When there are conflicts and the PR is not checked out, we need local checkout to resolve them
const hasConflicts = ctx.item.item.mergeable === PullRequestMergeability.Conflict;
if (hasConflicts && checkUpdateEnabled && !checkUpdateEnabled()) {
await vscode.window.showErrorMessage(vscode.l10n.t('The pull request branch must be checked out to resolve conflicts.'), { modal: true });
return ctx.replyMessage(message, {});
}
// Working tree/index checks only apply when the PR is checked out
if (ctx.item.isActive && (ctx.folderRepositoryManager.repository.state.workingTreeChanges.length > 0 || ctx.folderRepositoryManager.repository.state.indexChanges.length > 0)) {
await vscode.window.showErrorMessage(vscode.l10n.t('The pull request branch cannot be updated when there are changed files in the working tree or index. Stash or commit all change and then try again.'), { modal: true });
return ctx.replyMessage(message, {});
}
const mergeSucceeded = await ctx.folderRepositoryManager.tryMergeBaseIntoHead(ctx.item, true);
if (!mergeSucceeded) {
ctx.replyMessage(message, {});
}
// The mergability of the PR doesn't update immediately. Poll.
let mergability = PullRequestMergeability.Unknown;
let attemptsRemaining = 5;
do {
mergability = (await ctx.item.getMergeability()).mergeability;
attemptsRemaining--;
await new Promise(c => setTimeout(c, 1000));
} while (attemptsRemaining > 0 && mergability === PullRequestMergeability.Unknown);
const result: Partial<PullRequest> = {
events: await ctx.getTimeline(),
mergeable: mergability,
};
await refreshAfterUpdate();
ctx.replyMessage(message, result);
}
export async function setReadyForReview(ctx: ReviewContext, message: IRequestMessage<{}>): Promise<void> {
try {
const result = await ctx.item.setReadyForReview();
ctx.replyMessage(message, result);
} catch (e) {
vscode.window.showErrorMessage(vscode.l10n.t('Unable to set pull request ready for review. {0}', formatError(e)));
ctx.throwError(message, '');
}
}
export async function setReadyForReviewAndMerge(ctx: ReviewContext, message: IRequestMessage<{ mergeMethod: MergeMethod }>): Promise<void> {
try {
const readyResult = await ctx.item.setReadyForReview();
try {
await ctx.item.approve(ctx.folderRepositoryManager.repository, '');
} catch (e) {
vscode.window.showErrorMessage(`Pull request marked as ready for review, but failed to approve. ${formatError(e)}`);
ctx.replyMessage(message, readyResult);
return;
}
try {
await ctx.item.enableAutoMerge(message.args.mergeMethod);
} catch (e) {
vscode.window.showErrorMessage(`Pull request marked as ready and approved, but failed to enable auto-merge. ${formatError(e)}`);
ctx.replyMessage(message, readyResult);
return;
}
ctx.replyMessage(message, readyResult);
} catch (e) {
vscode.window.showErrorMessage(`Unable to mark pull request as ready for review. ${formatError(e)}`);
ctx.throwError(message, '');
}
}
export async function setConvertToDraft(ctx: ReviewContext, _message: IRequestMessage<{}>): Promise<void> {
try {
const result: ConvertToDraftReply = await ctx.item.convertToDraft();
ctx.replyMessage(_message, result);
} catch (e) {
vscode.window.showErrorMessage(vscode.l10n.t('Unable to convert pull request to draft. {0}', formatError(e)));
ctx.throwError(_message, '');
}
}
export async function readyForReviewCommand(ctx: ReviewContext): Promise<void> {
ctx.postMessage({
command: 'pr.readying-for-review'
});
try {
const result = await ctx.item.setReadyForReview();
const readiedResult: ReadyForReviewReply = {
isDraft: result.isDraft
};
await ctx.postMessage({
command: 'pr.readied-for-review',
result: readiedResult
});
} catch (e) {
vscode.window.showErrorMessage(`Unable to set pull request ready for review. ${formatError(e)}`);
ctx.throwError(undefined, e.message);
}
}
export async function readyForReviewAndMergeCommand(ctx: ReviewContext, context: { mergeMethod: MergeMethod }): Promise<void> {
ctx.postMessage({
command: 'pr.readying-for-review'
});
try {
const [readyResult, approveResult] = await Promise.all([ctx.item.setReadyForReview(), ctx.item.approve(ctx.folderRepositoryManager.repository)]);
await ctx.item.enableAutoMerge(context.mergeMethod);
updateReviewers(ctx.existingReviewers, approveResult);
const readiedResult: ReadyForReviewReply = {
isDraft: readyResult.isDraft,
autoMerge: true,
reviewEvent: approveResult,
reviewers: ctx.existingReviewers
};
await ctx.postMessage({
command: 'pr.readied-for-review',
result: readiedResult
});
} catch (e) {
vscode.window.showErrorMessage(`Unable to set pull request ready for review. ${formatError(e)}`);
ctx.throwError(undefined, e.message);
}
}
interface SelectedAction {
type: 'remoteHead' | 'local' | 'remote' | 'suspend'
};
export async function deleteBranch(folderRepositoryManager: FolderRepositoryManager, item: PullRequestModel): Promise<{ isReply: boolean, message: any }> {
const branchInfo = await folderRepositoryManager.getBranchNameForPullRequest(item);
const actions: (vscode.QuickPickItem & SelectedAction)[] = [];
const defaultBranch = await folderRepositoryManager.getPullRequestRepositoryDefaultBranch(item);
if (item.isResolved()) {
const branchHeadRef = item.head.ref;
const headRepo = folderRepositoryManager.findRepo(repo => repo.remote.owner === item.head.owner && repo.remote.repositoryName === item.remote.repositoryName);
const isDefaultBranch = defaultBranch === item.head.ref;
if (!isDefaultBranch && !item.isRemoteHeadDeleted) {
actions.push({
label: vscode.l10n.t('Delete remote branch {0}', `${headRepo?.remote.remoteName}/${branchHeadRef}`),
description: `${item.remote.normalizedHost}/${item.head.repositoryCloneUrl.owner}/${item.remote.repositoryName}`,
type: 'remoteHead',
picked: true,
});
}
}
if (branchInfo) {
const preferredLocalBranchDeletionMethod = vscode.workspace
.getConfiguration(PR_SETTINGS_NAMESPACE)
.get<boolean>(`${DEFAULT_DELETION_METHOD}.${SELECT_LOCAL_BRANCH}`);
actions.push({
label: vscode.l10n.t('Delete local branch {0}', branchInfo.branch),
type: 'local',
picked: !!preferredLocalBranchDeletionMethod,
});
const preferredRemoteDeletionMethod = vscode.workspace
.getConfiguration(PR_SETTINGS_NAMESPACE)
.get<boolean>(`${DEFAULT_DELETION_METHOD}.${SELECT_REMOTE}`);
if (branchInfo.remote && branchInfo.createdForPullRequest && !branchInfo.remoteInUse) {
actions.push({
label: vscode.l10n.t('Delete remote {0}, which is no longer used by any other branch', branchInfo.remote),
type: 'remote',
picked: !!preferredRemoteDeletionMethod,
});
}
}
if (vscode.env.remoteName === 'codespaces') {
actions.push({
label: vscode.l10n.t('Suspend Codespace'),
type: 'suspend'
});
}
if (!actions.length) {
vscode.window.showWarningMessage(
vscode.l10n.t('There is no longer an upstream or local branch for Pull Request #{0}', item.number),
);
return {
isReply: true,
message: {
cancelled: true
}
};
}
const selectedActions = await vscode.window.showQuickPick(actions, {
canPickMany: true,
ignoreFocusOut: true,
});
if (selectedActions) {
const deletedBranchTypes: string[] = await performBranchDeletion(folderRepositoryManager, item, defaultBranch, branchInfo!, selectedActions);
return {
isReply: false,
message: {
command: 'pr.deleteBranch',
branchTypes: deletedBranchTypes
}
};
} else {
return {
isReply: true,
message: {
cancelled: true
}
};
}
}
async function performBranchDeletion(folderRepositoryManager: FolderRepositoryManager, item: PullRequestModel, defaultBranch: string, branchInfo: BranchInfo, selectedActions: SelectedAction[]): Promise<string[]> {
const isBranchActive = item.equals(folderRepositoryManager.activePullRequest) || (folderRepositoryManager.repository.state.HEAD?.name && folderRepositoryManager.repository.state.HEAD.name === branchInfo?.branch);
const deletedBranchTypes: string[] = [];
const promises = selectedActions.map(async action => {
switch (action.type) {
case 'remoteHead':
await folderRepositoryManager.deleteBranch(item);
deletedBranchTypes.push(action.type);
await folderRepositoryManager.repository.fetch({ prune: true });
// If we're in a remote repository, then we should checkout the default branch.
if (folderRepositoryManager.repository.rootUri.scheme === Schemes.VscodeVfs) {
await folderRepositoryManager.repository.checkout(defaultBranch);
}
return;
case 'local':
if (isBranchActive) {
if (folderRepositoryManager.repository.state.workingTreeChanges.length) {
const yes = vscode.l10n.t('Yes');
const response = await vscode.window.showWarningMessage(
vscode.l10n.t('Your local changes will be lost, do you want to continue?'),
{ modal: true },
yes,
);
if (response === yes) {
await vscode.commands.executeCommand('git.cleanAll');
} else {
return;
}
}
await folderRepositoryManager.checkoutDefaultBranch(defaultBranch, item);
}
await folderRepositoryManager.repository.deleteBranch(branchInfo!.branch, true);
return deletedBranchTypes.push(action.type);
case 'remote':
deletedBranchTypes.push(action.type);
return folderRepositoryManager.repository.removeRemote(branchInfo!.remote!);
case 'suspend':
deletedBranchTypes.push(action.type);
return vscode.commands.executeCommand('github.codespaces.disconnectSuspend');
}
});
await Promise.all(promises);
return deletedBranchTypes;
}
/**
* Automatically delete the local branch after adding to a merge queue.
* Only deletes the local branch since the PR isn't merged yet.
*/
export async function autoDeleteLocalBranchAfterEnqueue(folderRepositoryManager: FolderRepositoryManager, item: PullRequestModel): Promise<void> {
const branchInfo = await folderRepositoryManager.getBranchNameForPullRequest(item);
const defaultBranch = await folderRepositoryManager.getPullRequestRepositoryDefaultBranch(item);
// Get user preference for local branch deletion
const deleteLocalBranch = vscode.workspace
.getConfiguration(PR_SETTINGS_NAMESPACE)
.get<boolean>(`${DEFAULT_DELETION_METHOD}.${SELECT_LOCAL_BRANCH}`, true);
if (!branchInfo || !deleteLocalBranch) {
return;
}
const selectedActions: SelectedAction[] = [{ type: 'local' }];
// Execute deletion
const deletedBranchTypes = await performBranchDeletion(folderRepositoryManager, item, defaultBranch, branchInfo, selectedActions);
// Show notification
if (deletedBranchTypes.includes('local')) {
const branchName = branchInfo.branch || item.head?.ref;
if (branchName) {
vscode.window.showInformationMessage(
vscode.l10n.t('Deleted local branch {0}.', branchName)
);
}
}
}
/**
* Automatically delete branches after merge based on user preferences.
* This function does not show any prompts - it uses the default deletion method preferences.
*/
export async function autoDeleteBranchesAfterMerge(folderRepositoryManager: FolderRepositoryManager, item: PullRequestModel): Promise<void> {
const branchInfo = await folderRepositoryManager.getBranchNameForPullRequest(item);
const defaultBranch = await folderRepositoryManager.getPullRequestRepositoryDefaultBranch(item);
// Get user preferences for automatic deletion
const deleteLocalBranch = vscode.workspace
.getConfiguration(PR_SETTINGS_NAMESPACE)
.get<boolean>(`${DEFAULT_DELETION_METHOD}.${SELECT_LOCAL_BRANCH}`, true);
const deleteRemote = vscode.workspace
.getConfiguration(PR_SETTINGS_NAMESPACE)
.get<boolean>(`${DEFAULT_DELETION_METHOD}.${SELECT_REMOTE}`, true);
const selectedActions: SelectedAction[] = [];
// Delete remote head branch if it's not the default branch
if (item.isResolved()) {
const isDefaultBranch = defaultBranch === item.head.ref;
if (!isDefaultBranch && !item.isRemoteHeadDeleted) {
selectedActions.push({ type: 'remoteHead' });
}
}
// Delete local branch if preference is set
if (branchInfo && deleteLocalBranch) {
selectedActions.push({ type: 'local' });
}
// Delete remote if it's no longer used and preference is set
if (branchInfo && branchInfo.remote && branchInfo.createdForPullRequest && !branchInfo.remoteInUse && deleteRemote) {
selectedActions.push({ type: 'remote' });
}
// Execute all deletions in parallel
const deletedBranchTypes = await performBranchDeletion(folderRepositoryManager, item, defaultBranch, branchInfo!, selectedActions);
// Show notification to the user about what was deleted
if (deletedBranchTypes.length > 0) {
const wasLocalDeleted = deletedBranchTypes.includes('local');
const wasRemoteDeleted = deletedBranchTypes.includes('remoteHead') || deletedBranchTypes.includes('remote');
const branchName = branchInfo?.branch || item.head?.ref;
// Only show notification if we have a branch name
if (branchName) {
if (wasLocalDeleted && wasRemoteDeleted) {
vscode.window.showInformationMessage(
vscode.l10n.t('Deleted local and remote branches for {0}.', branchName)
);
} else if (wasLocalDeleted) {
vscode.window.showInformationMessage(
vscode.l10n.t('Deleted local branch {0}.', branchName)
);
} else {
vscode.window.showInformationMessage(
vscode.l10n.t('Deleted remote branch {0}.', branchName)
);
}
}
}
}
}