-
Notifications
You must be signed in to change notification settings - Fork 588
/
commands.ts
530 lines (449 loc) · 19.7 KB
/
commands.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
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
528
529
530
/*---------------------------------------------------------------------------------------------
* 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 * as pathLib from 'path';
import { ReviewManager } from './view/reviewManager';
import { PullRequestOverviewPanel } from './github/pullRequestOverview';
import { fromReviewUri, ReviewUriParams, asImageDataURI, EMPTY_IMAGE_URI } from './common/uri';
import { GitFileChangeNode, InMemFileChangeNode } from './view/treeNodes/fileChangeNode';
import { CommitNode } from './view/treeNodes/commitNode';
import { PRNode } from './view/treeNodes/pullRequestNode';
import { PullRequest } from './github/interface';
import { formatError } from './common/utils';
import { GitChangeType } from './common/file';
import { getDiffLineByPosition, getZeroBased } from './common/diffPositionMapping';
import { DiffChangeType } from './common/diffHunk';
import { DescriptionNode } from './view/treeNodes/descriptionNode';
import { listHosts, deleteToken } from './authentication/keychain';
import { writeFile, unlink } from 'fs';
import Logger from './common/logger';
import { GitErrorCodes } from './api/api';
import { IComment } from './common/comment';
import { GHPRComment, TemporaryComment } from './github/prComment';
import { PullRequestManager } from './github/pullRequestManager';
import { PullRequestModel } from './github/pullRequestModel';
import { resolveCommentHandler, CommentReply } from './commentHandlerResolver';
import { ITelemetry } from './common/telemetry';
const _onDidUpdatePR = new vscode.EventEmitter<PullRequest | undefined>();
export const onDidUpdatePR: vscode.Event<PullRequest | undefined> = _onDidUpdatePR.event;
function ensurePR(prManager: PullRequestManager, pr?: PRNode | PullRequestModel): PullRequestModel {
// If the command is called from the command palette, no arguments are passed.
if (!pr) {
if (!prManager.activePullRequest) {
vscode.window.showErrorMessage('Unable to find current pull request.');
throw new Error('Unable to find current pull request.');
}
return prManager.activePullRequest;
} else {
return pr instanceof PRNode ? pr.pullRequestModel : pr;
}
}
export function registerCommands(context: vscode.ExtensionContext, prManager: PullRequestManager,
reviewManager: ReviewManager, telemetry: ITelemetry) {
context.subscriptions.push(vscode.commands.registerCommand('auth.signout', async () => {
const selection = await vscode.window.showQuickPick(await listHosts(), { canPickMany: true, ignoreFocusOut: true });
if (!selection) { return; }
await Promise.all(selection.map(host => deleteToken(host)));
}));
context.subscriptions.push(vscode.commands.registerCommand('pr.openPullRequestInGitHub', (e: PRNode | DescriptionNode | PullRequestModel) => {
if (!e) {
if (prManager.activePullRequest) {
vscode.commands.executeCommand('vscode.open', vscode.Uri.parse(prManager.activePullRequest.html_url));
}
} else if (e instanceof PRNode || e instanceof DescriptionNode) {
vscode.commands.executeCommand('vscode.open', vscode.Uri.parse(e.pullRequestModel.html_url));
} else {
vscode.commands.executeCommand('vscode.open', vscode.Uri.parse(e.html_url));
}
/* __GDPR__
"pr.openInGitHub" : {}
*/
telemetry.sendTelemetryEvent('pr.openInGitHub');
}));
context.subscriptions.push(vscode.commands.registerCommand('review.suggestDiff', async (e) => {
try {
if (!prManager.activePullRequest) {
return;
}
const { indexChanges, workingTreeChanges } = prManager.repository.state;
if (!indexChanges.length) {
if (workingTreeChanges.length) {
const stageAll = await vscode.window.showWarningMessage('There are no staged changes to suggest.\n\nWould you like to automatically stage all your of changes and suggest them?', { modal: true }, 'Yes');
if (stageAll === 'Yes') {
await vscode.commands.executeCommand('git.stageAll');
} else {
return;
}
} else {
vscode.window.showInformationMessage('There are no changes to suggest.');
return;
}
}
const diff = await prManager.repository.diff(true);
let suggestEditMessage = '';
if (e && e.inputBox && e.inputBox.value) {
suggestEditMessage = `${e.inputBox.value}\n`;
e.inputBox.value = '';
}
const suggestEditText = `${suggestEditMessage}\`\`\`diff\n${diff}\n\`\`\``;
await prManager.createIssueComment(prManager.activePullRequest, suggestEditText);
// Reset HEAD and then apply reverse diff
await vscode.commands.executeCommand('git.unstageAll');
const tempFilePath = pathLib.join(prManager.repository.rootUri.path, '.git', `${prManager.activePullRequest.number}.diff`);
writeFile(tempFilePath, diff, {}, async (writeError) => {
if (writeError) {
throw writeError;
}
try {
await prManager.repository.apply(tempFilePath, true);
unlink(tempFilePath, (err) => {
if (err) {
throw err;
}
});
} catch (err) {
Logger.appendLine(`Applying patch failed: ${err}`);
vscode.window.showErrorMessage(`Applying patch failed: ${formatError(err)}`);
}
});
} catch (err) {
Logger.appendLine(`Applying patch failed: ${err}`);
vscode.window.showErrorMessage(`Applying patch failed: ${formatError(err)}`);
}
}));
context.subscriptions.push(vscode.commands.registerCommand('pr.openFileInGitHub', (e: GitFileChangeNode) => {
vscode.commands.executeCommand('vscode.open', vscode.Uri.parse(e.blobUrl!));
}));
context.subscriptions.push(vscode.commands.registerCommand('pr.copyCommitHash', (e: CommitNode) => {
vscode.env.clipboard.writeText(e.sha);
}));
context.subscriptions.push(vscode.commands.registerCommand('pr.openOriginalFile', async (e: GitFileChangeNode) => {
// if this is an image, encode it as a base64 data URI
const imageDataURI = await asImageDataURI(e.parentFilePath, prManager.repository);
vscode.commands.executeCommand('vscode.open', imageDataURI || e.parentFilePath);
}));
context.subscriptions.push(vscode.commands.registerCommand('pr.openModifiedFile', (e: GitFileChangeNode) => {
vscode.commands.executeCommand('vscode.open', e.filePath);
}));
context.subscriptions.push(vscode.commands.registerCommand('pr.openDiffView', async (fileChangeNode: GitFileChangeNode | InMemFileChangeNode) => {
const parentFilePath = fileChangeNode.parentFilePath;
const filePath = fileChangeNode.filePath;
const fileName = fileChangeNode.fileName;
const isPartial = fileChangeNode.isPartial;
const opts = fileChangeNode.opts;
fileChangeNode.reveal(fileChangeNode, { select: true, focus: true });
if (isPartial) {
vscode.window.showInformationMessage('Your local repository is not up to date so only partial content is being displayed');
}
let parentURI = await asImageDataURI(parentFilePath, prManager.repository) || parentFilePath;
let headURI = await asImageDataURI(filePath, prManager.repository) || filePath;
if (parentURI.scheme === 'data' || headURI.scheme === 'data') {
if (fileChangeNode.status === GitChangeType.ADD) {
parentURI = EMPTY_IMAGE_URI;
}
if (fileChangeNode.status === GitChangeType.DELETE) {
headURI = EMPTY_IMAGE_URI;
}
}
vscode.commands.executeCommand('vscode.diff', parentURI, headURI, fileName, opts);
}));
context.subscriptions.push(vscode.commands.registerCommand('pr.deleteLocalBranch', async (e: PRNode) => {
const pullRequestModel = ensurePR(prManager, e);
const DELETE_BRANCH_FORCE = 'delete branch (even if not merged)';
let error = null;
try {
await prManager.deleteLocalPullRequest(pullRequestModel);
} catch (e) {
if (e.gitErrorCode === GitErrorCodes.BranchNotFullyMerged) {
const action = await vscode.window.showErrorMessage(`The branch '${pullRequestModel.localBranchName}' is not fully merged, are you sure you want to delete it? `, DELETE_BRANCH_FORCE);
if (action !== DELETE_BRANCH_FORCE) {
return;
}
try {
await prManager.deleteLocalPullRequest(pullRequestModel, true);
} catch (e) {
error = e;
}
} else {
error = e;
}
}
if (error) {
/* __GDPR__
"pr.deleteLocalPullRequest.failure" : {
"message" : { "classification": "CallstackOrException", "purpose": "PerformanceAndHealth" }
}
*/
telemetry.sendTelemetryEvent('pr.deleteLocalPullRequest.failure', {
message: error
});
await vscode.window.showErrorMessage(`Deleting local pull request branch failed: ${error}`);
} else {
/* __GDPR__
"pr.deleteLocalPullRequest.success" : {}
*/
telemetry.sendTelemetryEvent('pr.deleteLocalPullRequest.success');
// fire and forget
vscode.commands.executeCommand('pr.refreshList');
}
}));
context.subscriptions.push(vscode.commands.registerCommand('pr.create', async () => {
reviewManager.createPullRequest();
}));
context.subscriptions.push(vscode.commands.registerCommand('pr.createDraft', async () => {
reviewManager.createPullRequest(true);
}));
context.subscriptions.push(vscode.commands.registerCommand('pr.pick', async (pr: PRNode | DescriptionNode | PullRequestModel) => {
let pullRequestModel: PullRequestModel;
if (pr instanceof PRNode || pr instanceof DescriptionNode) {
pullRequestModel = pr.pullRequestModel;
} else {
pullRequestModel = pr;
}
const fromDescriptionPage = pr instanceof PullRequestModel;
/* __GDPR__
"pr.checkout" : {
"fromDescriptionPage" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
}
*/
telemetry.sendTelemetryEvent('pr.checkout', { fromDescription: fromDescriptionPage.toString() });
return vscode.window.withProgress({
location: vscode.ProgressLocation.SourceControl,
title: `Switching to Pull Request #${pullRequestModel.number}`,
}, async (progress, token) => {
await reviewManager.switch(pullRequestModel);
});
}));
context.subscriptions.push(vscode.commands.registerCommand('pr.merge', async (pr?: PRNode) => {
const pullRequest = ensurePR(prManager, pr);
return vscode.window.showWarningMessage(`Are you sure you want to merge this pull request on GitHub?`, { modal: true }, 'Yes').then(async value => {
let newPR;
if (value === 'Yes') {
try {
newPR = await prManager.mergePullRequest(pullRequest);
return newPR;
} catch (e) {
vscode.window.showErrorMessage(`Unable to merge pull request. ${formatError(e)}`);
return newPR;
}
}
});
}));
context.subscriptions.push(vscode.commands.registerCommand('pr.readyForReview', async (pr?: PRNode) => {
const pullRequest = ensurePR(prManager, pr);
return vscode.window.showWarningMessage(`Are you sure you want to mark this pull request as ready to review on GitHub?`, { modal: true }, 'Yes').then(async value => {
let isDraft;
if (value === 'Yes') {
try {
isDraft = await prManager.setReadyForReview(pullRequest);
vscode.commands.executeCommand('pr.refreshList');
return isDraft;
} catch (e) {
vscode.window.showErrorMessage(`Unable to mark pull request as ready to review. ${formatError(e)}`);
return isDraft;
}
}
});
}));
context.subscriptions.push(vscode.commands.registerCommand('pr.close', async (pr?: PRNode, message?: string) => {
const pullRequest = ensurePR(prManager, pr);
return vscode.window.showWarningMessage(`Are you sure you want to close this pull request on GitHub? This will close the pull request without merging.`, 'Yes', 'No').then(async value => {
if (value === 'Yes') {
try {
let newComment: IComment | undefined = undefined;
if (message) {
newComment = await prManager.createIssueComment(pullRequest, message);
}
const newPR = await prManager.closePullRequest(pullRequest);
vscode.commands.executeCommand('pr.refreshList');
_onDidUpdatePR.fire(newPR);
return newComment;
} catch (e) {
vscode.window.showErrorMessage(`Unable to close pull request. ${formatError(e)}`);
_onDidUpdatePR.fire();
}
}
_onDidUpdatePR.fire();
});
}));
context.subscriptions.push(vscode.commands.registerCommand('pr.approve', async (pr: PullRequestModel, message?: string) => {
return await prManager.approvePullRequest(pr, message);
}));
context.subscriptions.push(vscode.commands.registerCommand('pr.requestChanges', async (pr: PullRequestModel, message?: string) => {
return await prManager.requestChanges(pr, message);
}));
context.subscriptions.push(vscode.commands.registerCommand('pr.openDescription', async (descriptionNode: DescriptionNode) => {
if (!descriptionNode) {
// the command is triggerred from command palette or status bar, which means we are already in checkout mode.
const rootNodes = await reviewManager.prFileChangesProvider.getChildren();
descriptionNode = rootNodes[0] as DescriptionNode;
}
const pullRequest = ensurePR(prManager, descriptionNode.pullRequestModel);
descriptionNode.reveal(descriptionNode, { select: true, focus: true });
// Create and show a new webview
PullRequestOverviewPanel.createOrShow(context.extensionPath, prManager, pullRequest, descriptionNode);
/* __GDPR__
"pr.openDescription" : {}
*/
telemetry.sendTelemetryEvent('pr.openDescription');
}));
context.subscriptions.push(vscode.commands.registerCommand('pr.refreshDescription', async () => {
if (PullRequestOverviewPanel.currentPanel) {
PullRequestOverviewPanel.refresh();
}
}));
context.subscriptions.push(vscode.commands.registerCommand('pr.openDescriptionToTheSide', async (descriptionNode: DescriptionNode) => {
const pr = descriptionNode.pullRequestModel;
const pullRequest = ensurePR(prManager, pr);
descriptionNode.reveal(descriptionNode, { select: true, focus: true });
// Create and show a new webview
PullRequestOverviewPanel.createOrShow(context.extensionPath, prManager, pullRequest, descriptionNode, true);
/* __GDPR__
"pr.openDescriptionToTheSide" : {}
*/
telemetry.sendTelemetryEvent('pr.openDescriptionToTheSide');
}));
context.subscriptions.push(vscode.commands.registerCommand('pr.viewChanges', async (fileChange: GitFileChangeNode) => {
if (fileChange.status === GitChangeType.DELETE || fileChange.status === GitChangeType.ADD) {
// create an empty `review` uri without any path/commit info.
const emptyFileUri = fileChange.parentFilePath.with({
query: JSON.stringify({
path: null,
commit: null,
})
});
return fileChange.status === GitChangeType.DELETE
? vscode.commands.executeCommand('vscode.diff', fileChange.parentFilePath, emptyFileUri, `${fileChange.fileName}`, { preserveFocus: true })
: vscode.commands.executeCommand('vscode.diff', emptyFileUri, fileChange.parentFilePath, `${fileChange.fileName}`, { preserveFocus: true });
}
// Show the file change in a diff view.
const { path, ref, commit } = fromReviewUri(fileChange.filePath);
const previousCommit = `${commit}^`;
const query: ReviewUriParams = {
path: path,
ref: ref,
commit: previousCommit,
base: true,
isOutdated: true
};
const previousFileUri = fileChange.filePath.with({ query: JSON.stringify(query) });
const options: vscode.TextDocumentShowOptions = {
preserveFocus: true
};
if (fileChange.comments && fileChange.comments.length) {
const sortedOutdatedComments = fileChange.comments.filter(comment => comment.position === undefined).sort((a, b) => {
return a.originalPosition! - b.originalPosition!;
});
if (sortedOutdatedComments.length) {
const diffLine = getDiffLineByPosition(fileChange.diffHunks, sortedOutdatedComments[0].originalPosition!);
if (diffLine) {
const lineNumber = Math.max(getZeroBased(diffLine.type === DiffChangeType.Delete ? diffLine.oldLineNumber : diffLine.newLineNumber), 0);
options.selection = new vscode.Range(lineNumber, 0, lineNumber, 0);
}
}
}
return vscode.commands.executeCommand('vscode.diff', previousFileUri, fileChange.filePath, `${fileChange.fileName} from ${(commit || '').substr(0, 8)}`, options);
}));
context.subscriptions.push(vscode.commands.registerCommand('pr.signin', async () => {
await prManager.authenticate();
}));
context.subscriptions.push(vscode.commands.registerCommand('pr.deleteLocalBranchesNRemotes', async () => {
await prManager.deleteLocalBranchesNRemotes();
}));
context.subscriptions.push(vscode.commands.registerCommand('pr.signinAndRefreshList', async () => {
if (await prManager.authenticate()) {
vscode.commands.executeCommand('pr.refreshList');
}
}));
context.subscriptions.push(vscode.commands.registerCommand('pr.configureRemotes', async () => {
const { name, publisher } = require('../package.json') as { name: string, publisher: string };
const extensionId = `${publisher}.${name}`;
return vscode.commands.executeCommand('workbench.action.openSettings', `@ext:${extensionId} remotes`);
}));
context.subscriptions.push(vscode.commands.registerCommand('pr.startReview', async (reply: CommentReply) => {
/* __GDPR__
"pr.startReview" : {}
*/
telemetry.sendTelemetryEvent('pr.startReview');
const handler = resolveCommentHandler(reply.thread);
if (handler) {
handler.startReview(reply.thread, reply.text);
}
}));
context.subscriptions.push(vscode.commands.registerCommand('pr.finishReview', async (reply: CommentReply) => {
/* __GDPR__
"pr.finishReview" : {}
*/
telemetry.sendTelemetryEvent('pr.finishReview');
const handler = resolveCommentHandler(reply.thread);
if (handler) {
await handler.finishReview(reply.thread, reply.text);
}
}));
context.subscriptions.push(vscode.commands.registerCommand('pr.deleteReview', async (reply: CommentReply) => {
/* __GDPR__
"pr.deleteReview" : {}
*/
telemetry.sendTelemetryEvent('pr.deleteReview');
const shouldDelete = await vscode.window.showWarningMessage('Delete this review and all associated comments?', { modal: true }, 'Delete');
if (shouldDelete) {
const handler = resolveCommentHandler(reply.thread);
if (handler) {
await handler.deleteReview();
}
if (!reply.thread.comments.length) {
reply.thread.dispose();
}
}
}));
context.subscriptions.push(vscode.commands.registerCommand('pr.createComment', async (reply: CommentReply) => {
/* __GDPR__
"pr.createComment" : {}
*/
telemetry.sendTelemetryEvent('pr.createComment');
const handler = resolveCommentHandler(reply.thread);
if (handler) {
handler.createOrReplyComment(reply.thread, reply.text);
}
}));
context.subscriptions.push(vscode.commands.registerCommand('pr.editComment', async (comment: GHPRComment | TemporaryComment) => {
/* __GDPR__
"pr.editComment" : {}
*/
telemetry.sendTelemetryEvent('pr.editComment');
comment.startEdit();
}));
context.subscriptions.push(vscode.commands.registerCommand('pr.cancelEditComment', async (comment: GHPRComment | TemporaryComment) => {
/* __GDPR__
"pr.cancelEditComment" : {}
*/
telemetry.sendTelemetryEvent('pr.cancelEditComment');
comment.cancelEdit();
}));
context.subscriptions.push(vscode.commands.registerCommand('pr.saveComment', async (comment: GHPRComment | TemporaryComment) => {
/* __GDPR__
"pr.saveComment" : {}
*/
telemetry.sendTelemetryEvent('pr.saveComment');
const handler = resolveCommentHandler(comment.parent);
if (handler) {
await handler.editComment(comment.parent, comment);
}
}));
context.subscriptions.push(vscode.commands.registerCommand('pr.deleteComment', async (comment: GHPRComment | TemporaryComment) => {
/* __GDPR__
"pr.deleteComment" : {}
*/
telemetry.sendTelemetryEvent('pr.deleteComment');
const shouldDelete = await vscode.window.showWarningMessage('Delete comment?', { modal: true }, 'Delete');
if (shouldDelete === 'Delete') {
const handler = resolveCommentHandler(comment.parent);
if (handler) {
await handler.deleteComment(comment.parent, comment);
}
}
}));
}