forked from microsoft/vscode-pull-request-github
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreatePRViewProvider.ts
More file actions
521 lines (446 loc) · 20.1 KB
/
createPRViewProvider.ts
File metadata and controls
521 lines (446 loc) · 20.1 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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import { CreateParams, CreatePullRequest, RemoteInfo } from '../../common/views';
import type { Branch } from '../api/api';
import Logger from '../common/logger';
import { Protocol } from '../common/protocol';
import { Remote } from '../common/remote';
import { ASSIGN_TO, PUSH_BRANCH } from '../common/settingKeys';
import { getNonce, IRequestMessage, WebviewViewBase } from '../common/webview';
import {
byRemoteName,
DetachedHeadError,
FolderRepositoryManager,
PullRequestDefaults,
SETTINGS_NAMESPACE,
titleAndBodyFrom,
} from './folderRepositoryManager';
import { GitHubRepository } from './githubRepository';
import { RepoAccessAndMergeMethods } from './interface';
import { PullRequestModel } from './pullRequestModel';
import { getDefaultMergeMethod } from './pullRequestOverview';
import { variableSubstitution } from './utils';
export class CreatePullRequestViewProvider extends WebviewViewBase implements vscode.WebviewViewProvider {
public readonly viewType = 'github:createPullRequest';
private _onDone = new vscode.EventEmitter<PullRequestModel | undefined>();
readonly onDone: vscode.Event<PullRequestModel | undefined> = this._onDone.event;
private _onDidChangeBaseRemote = new vscode.EventEmitter<RemoteInfo>();
readonly onDidChangeBaseRemote: vscode.Event<RemoteInfo> = this._onDidChangeBaseRemote.event;
private _onDidChangeBaseBranch = new vscode.EventEmitter<string>();
readonly onDidChangeBaseBranch: vscode.Event<string> = this._onDidChangeBaseBranch.event;
private _onDidChangeCompareRemote = new vscode.EventEmitter<RemoteInfo>();
readonly onDidChangeCompareRemote: vscode.Event<RemoteInfo> = this._onDidChangeCompareRemote.event;
private _onDidChangeCompareBranch = new vscode.EventEmitter<string>();
readonly onDidChangeCompareBranch: vscode.Event<string> = this._onDidChangeCompareBranch.event;
private _compareBranch: string;
private _baseBranch: string;
private _firstLoad: boolean = true;
constructor(
extensionUri: vscode.Uri,
private readonly _folderRepositoryManager: FolderRepositoryManager,
private readonly _pullRequestDefaults: PullRequestDefaults,
compareBranch: Branch,
) {
super(extensionUri);
this._defaultCompareBranch = compareBranch;
}
public resolveWebviewView(
webviewView: vscode.WebviewView,
_context: vscode.WebviewViewResolveContext,
_token: vscode.CancellationToken,
) {
super.resolveWebviewView(webviewView, _context, _token);
webviewView.webview.html = this._getHtmlForWebview();
if (this._firstLoad) {
this._firstLoad = false;
// Reset any stored state.
// TODO @RMacfarlane Clear stored state on extension deactivation instead.
this.initializeParams(true);
} else {
this.initializeParams();
}
}
private _defaultCompareBranch: Branch;
get defaultCompareBranch() {
return this._defaultCompareBranch;
}
set defaultCompareBranch(compareBranch: Branch | undefined) {
if (
compareBranch &&
(compareBranch?.name !== this._defaultCompareBranch.name ||
compareBranch?.upstream?.remote !== this._defaultCompareBranch.upstream?.remote)
) {
this._defaultCompareBranch = compareBranch;
void this.initializeParams();
this._onDidChangeCompareBranch.fire(this._defaultCompareBranch.name!);
}
}
public show(compareBranch?: Branch): void {
if (compareBranch) {
this.defaultCompareBranch = compareBranch;
}
super.show();
}
private async getTotalGitHubCommits(compareBranch: Branch, baseBranchName: string): Promise<number | undefined> {
const origin = await this._folderRepositoryManager.getOrigin(compareBranch);
if (compareBranch.upstream) {
const headRepo = this._folderRepositoryManager.findRepo(byRemoteName(compareBranch.upstream.remote));
if (headRepo) {
const headBranch = `${headRepo.remote.owner}:${compareBranch.name ?? ''}`;
const baseBranch = `${this._pullRequestDefaults.owner}:${baseBranchName}`;
const compareResult = await origin.compareCommits(baseBranch, headBranch);
return compareResult?.total_commits;
}
}
return undefined;
}
private async getTitleAndDescription(compareBranch: Branch, baseBranch: string): Promise<{ title: string, description: string }> {
let title: string = '';
let description: string = '';
// Use same default as GitHub, if there is only one commit, use the commit, otherwise use the branch name, as long as it is not the default branch.
// By default, the base branch we use for comparison is the base branch of origin. Compare this to the
// compare branch if it has a GitHub remote.
const origin = await this._folderRepositoryManager.getOrigin(compareBranch);
let useBranchName = this._pullRequestDefaults.base === compareBranch.name;
Logger.debug(`Compare branch name: ${compareBranch.name}, Base branch name: ${this._pullRequestDefaults.base}`, 'CreatePullRequestViewProvider');
try {
const name = compareBranch.name;
const [totalCommits, lastCommit, pullRequestTemplate] = await Promise.all([
this.getTotalGitHubCommits(compareBranch, baseBranch),
name ? titleAndBodyFrom(await this._folderRepositoryManager.getTipCommitMessage(name)) : undefined,
await this.getPullRequestTemplate()
]);
Logger.debug(`Total commits: ${totalCommits}`, 'CreatePullRequestViewProvider');
if (totalCommits === undefined) {
// There is no upstream branch. Use the last commit as the title and description.
useBranchName = false;
} else if (totalCommits > 1) {
const defaultBranch = await origin.getDefaultBranch();
useBranchName = defaultBranch !== compareBranch.name;
}
// Set title
if (useBranchName && name) {
title = `${name.charAt(0).toUpperCase()}${name.slice(1)}`;
} else if (name && lastCommit) {
title = lastCommit.title;
}
// Set description
if (pullRequestTemplate && lastCommit?.body) {
description = `${lastCommit.body}\n\n${pullRequestTemplate}`;
} else if (pullRequestTemplate) {
description = pullRequestTemplate;
} else if (lastCommit?.body && (this._pullRequestDefaults.base !== compareBranch.name)) {
description = lastCommit.body;
}
} catch (e) {
// Ignore and fall back to commit message
Logger.debug(`Error while getting total commits: ${e}`, 'CreatePullRequestViewProvider');
}
return { title, description };
}
private async getPullRequestTemplate(): Promise<string | undefined> {
const templateUris = await this._folderRepositoryManager.getPullRequestTemplates();
if (templateUris[0]) {
try {
const templateContent = await vscode.workspace.fs.readFile(templateUris[0]);
return new TextDecoder('utf-8').decode(templateContent);
} catch (e) {
Logger.appendLine(`Reading pull request template failed: ${e}`);
return undefined;
}
}
return undefined;
}
private async getMergeConfiguration(owner: string, name: string): Promise<RepoAccessAndMergeMethods> {
const repo = this._folderRepositoryManager.createGitHubRepositoryFromOwnerName(owner, name);
return repo.getRepoAccessAndMergeMethods();
}
public async initializeParams(reset: boolean = false): Promise<void> {
// Do the fast initialization first, then update with the slower initialization.
const params = await this.initializeParamsFast(reset);
this.initializeParamsSlow(params);
}
private async initializeParamsSlow(params: CreateParams): Promise<void> {
if (!this.defaultCompareBranch) {
throw new DetachedHeadError(this._folderRepositoryManager.repository);
}
if (!params.defaultBaseRemote || !params.defaultCompareRemote) {
throw new Error('Create Pull Request view unable to initialize without default remotes.');
}
const defaultOrigin = await this._folderRepositoryManager.getOrigin(this.defaultCompareBranch);
const branchesForRemote = await defaultOrigin.listBranches(this._pullRequestDefaults.owner, this._pullRequestDefaults.repo);
// Ensure default into branch is in the remotes list
if (!branchesForRemote.includes(this._pullRequestDefaults.base)) {
branchesForRemote.push(this._pullRequestDefaults.base);
branchesForRemote.sort();
}
let branchesForCompare = branchesForRemote;
if (params.defaultCompareRemote.owner !== params.defaultBaseRemote.owner) {
branchesForCompare = await defaultOrigin.listBranches(
params.defaultCompareRemote.owner,
params.defaultCompareRemote.repositoryName,
);
}
// Ensure default from branch is in the remotes list
if (this.defaultCompareBranch.name && !branchesForCompare.includes(this.defaultCompareBranch.name)) {
branchesForCompare.push(this.defaultCompareBranch.name);
branchesForCompare.sort();
}
params.branchesForRemote = branchesForRemote;
params.branchesForCompare = branchesForCompare;
this._postMessage({
command: 'pr.initialize',
params,
});
}
private async initializeParamsFast(reset: boolean = false): Promise<CreateParams> {
if (!this.defaultCompareBranch) {
throw new DetachedHeadError(this._folderRepositoryManager.repository);
}
const defaultBaseRemote: RemoteInfo = {
owner: this._pullRequestDefaults.owner,
repositoryName: this._pullRequestDefaults.repo,
};
const defaultOrigin = await this._folderRepositoryManager.getOrigin(this.defaultCompareBranch);
const defaultCompareRemote: RemoteInfo = {
owner: defaultOrigin.remote.owner,
repositoryName: defaultOrigin.remote.repositoryName,
};
const defaultBaseBranch = this._pullRequestDefaults.base;
const [configuredGitHubRemotes, allGitHubRemotes, defaultTitleAndDescription, mergeConfiguration] = await Promise.all([
this._folderRepositoryManager.getGitHubRemotes(),
this._folderRepositoryManager.getAllGitHubRemotes(),
this.getTitleAndDescription(this.defaultCompareBranch, defaultBaseBranch),
this.getMergeConfiguration(defaultBaseRemote.owner, defaultBaseRemote.repositoryName)
]);
const configuredRemotes: RemoteInfo[] = configuredGitHubRemotes.map(remote => {
return {
owner: remote.owner,
repositoryName: remote.repositoryName,
};
});
const allRemotes: RemoteInfo[] = allGitHubRemotes.map(remote => {
return {
owner: remote.owner,
repositoryName: remote.repositoryName,
};
});
const defaultCompareBranch = this.defaultCompareBranch.name ?? '';
const params: CreateParams = {
availableBaseRemotes: configuredRemotes,
availableCompareRemotes: allRemotes,
defaultBaseRemote,
defaultBaseBranch,
defaultCompareRemote,
defaultCompareBranch,
branchesForRemote: [defaultBaseBranch], // We'll populate the branches in the slow phase as they are less likely to be needed.
branchesForCompare: [defaultCompareBranch],
defaultTitle: defaultTitleAndDescription.title,
defaultDescription: defaultTitleAndDescription.description,
isDraft: false,
defaultMergeMethod: getDefaultMergeMethod(mergeConfiguration.mergeMethodsAvailability),
allowAutoMerge: mergeConfiguration.viewerCanAutoMerge,
mergeMethodsAvailability: mergeConfiguration.mergeMethodsAvailability,
createError: ''
};
this._compareBranch = this.defaultCompareBranch.name ?? '';
this._baseBranch = defaultBaseBranch;
this._postMessage({
command: reset ? 'reset' : 'pr.initialize',
params,
});
return params;
}
private async changeRemote(
message: IRequestMessage<{ owner: string; repositoryName: string }>,
isBase: boolean,
): Promise<void> {
const { owner, repositoryName } = message.args;
let githubRepository = this._folderRepositoryManager.findRepo(
repo => owner === repo.remote.owner && repositoryName === repo.remote.repositoryName,
);
if (!githubRepository) {
githubRepository = this._folderRepositoryManager.createGitHubRepositoryFromOwnerName(owner, repositoryName);
}
if (!githubRepository) {
throw new Error('No matching GitHub repository found.');
}
const defaultBranch = await githubRepository.getDefaultBranch();
const newBranches = await githubRepository.listBranches(owner, repositoryName);
if (!isBase && this.defaultCompareBranch?.name && !newBranches.includes(this.defaultCompareBranch.name)) {
newBranches.push(this.defaultCompareBranch.name);
newBranches.sort();
}
let newBranch: string | undefined;
if (isBase) {
newBranch = defaultBranch;
this._baseBranch = defaultBranch;
this._onDidChangeBaseRemote.fire({ owner, repositoryName });
this._onDidChangeBaseBranch.fire(defaultBranch);
} else {
if (this.defaultCompareBranch?.name) {
newBranch = this.defaultCompareBranch?.name;
this._compareBranch = this.defaultCompareBranch?.name;
}
this._onDidChangeCompareRemote.fire({ owner, repositoryName });
}
// TODO: if base is change need to update auto merge
return this._replyMessage(message, { branches: newBranches, defaultBranch: newBranch });
}
private async autoAssign(pr: PullRequestModel): Promise<void> {
const configuration = vscode.workspace.getConfiguration(SETTINGS_NAMESPACE).get<string | undefined>(ASSIGN_TO);
if (!configuration) {
return;
}
const resolved = await variableSubstitution(configuration, pr, undefined, this._folderRepositoryManager.getCurrentUser(pr.githubRepository)?.login);
if (!resolved) {
return;
}
try {
await pr.updateAssignees([resolved]);
} catch (e) {
vscode.window.showErrorMessage(`Unable to assign pull request to user ${resolved}.`);
}
}
private async pushUpstream(compareOwner: string, compareRepositoryName: string, compareBranchName: string): Promise<{ compareUpstream: Remote, repo: GitHubRepository | undefined } | undefined> {
let createdPushRemote: Remote | undefined;
const pushRemote = this._folderRepositoryManager.repository.state.remotes.find(localRemote => {
if (!localRemote.pushUrl) {
return false;
}
const testRemote = new Remote(localRemote.name, localRemote.pushUrl, new Protocol(localRemote.pushUrl));
if ((testRemote.owner.toLowerCase() === compareOwner.toLowerCase()) && (testRemote.repositoryName.toLowerCase() === compareRepositoryName.toLowerCase())) {
createdPushRemote = testRemote;
return true;
}
return false;
});
if (pushRemote && createdPushRemote) {
Logger.appendLine(`Found push remote ${pushRemote.name} for ${compareOwner}/${compareRepositoryName} and branch ${compareBranchName}`, 'CreatePullRequestViewProvider');
await this._folderRepositoryManager.repository.push(pushRemote.name, compareBranchName, true);
return { compareUpstream: createdPushRemote, repo: this._folderRepositoryManager.findRepo(byRemoteName(createdPushRemote.remoteName)) };
}
}
private async create(message: IRequestMessage<CreatePullRequest>): Promise<void> {
try {
const compareOwner = message.args.compareOwner;
const compareRepositoryName = message.args.compareRepo;
const compareBranchName = message.args.compareBranch;
const compareGithubRemoteName = `${compareOwner}/${compareRepositoryName}`;
const compareBranch = await this._folderRepositoryManager.repository.getBranch(compareBranchName);
let headRepo = compareBranch.upstream ? this._folderRepositoryManager.findRepo((githubRepo) => {
return (githubRepo.remote.owner === compareOwner) && (githubRepo.remote.repositoryName === compareRepositoryName);
}) : undefined;
let existingCompareUpstream = headRepo?.remote;
if (!existingCompareUpstream
|| (existingCompareUpstream.owner !== compareOwner)
|| (existingCompareUpstream.repositoryName !== compareRepositoryName)) {
// We assume this happens only when the compare branch is based on the current branch.
const pushBranchSetting = vscode.workspace.getConfiguration(SETTINGS_NAMESPACE).get(PUSH_BRANCH) === 'always';
const messageResult = !pushBranchSetting ? await vscode.window.showInformationMessage(
`There is no upstream branch for '${compareBranchName}'.\n\nDo you want to publish it and then create the pull request?`,
{ modal: true },
'Publish Branch',
'Always Publish Branch')
: 'Publish Branch';
if (messageResult === 'Always Publish Branch') {
await vscode.workspace.getConfiguration(SETTINGS_NAMESPACE).update(PUSH_BRANCH, 'always', vscode.ConfigurationTarget.Global);
}
if ((messageResult === 'Always Publish Branch') || (messageResult === 'Publish Branch')) {
const pushResult = await this.pushUpstream(compareOwner, compareRepositoryName, compareBranchName);
if (pushResult) {
existingCompareUpstream = pushResult.compareUpstream;
headRepo = pushResult.repo;
} else {
this._throwError(message, `The current repository does not have a push remote for ${compareGithubRemoteName}`);
}
}
}
if (!existingCompareUpstream) {
this._throwError(message, 'No upstream for the compare branch.');
return;
}
if (!headRepo) {
throw new Error(`Unable to find GitHub repository matching '${existingCompareUpstream.remoteName}'. You can add '${existingCompareUpstream.remoteName}' to the setting "githubPullRequests.remotes" to ensure '${existingCompareUpstream.remoteName}' is found.`);
}
const head = `${headRepo.remote.owner}:${compareBranchName}`;
const createdPR = await this._folderRepositoryManager.createPullRequest({ ...message.args, head });
// Create was cancelled
if (!createdPR) {
this._throwError(message, 'There must be a difference in commits to create a pull request.');
} else {
if (message.args.autoMerge) {
await createdPR.enableAutoMerge(message.args.mergeMethod);
}
await this.autoAssign(createdPR);
await this._replyMessage(message, {});
this._onDone.fire(createdPR);
}
} catch (e) {
this._throwError(message, e.message);
}
}
private async changeBranch(message: IRequestMessage<string | { name: string }>, isBase: boolean): Promise<void> {
const newBranch = (typeof message.args === 'string') ? message.args : message.args.name;
let compareBranch: Branch | undefined;
if (isBase) {
this._baseBranch = newBranch;
this._onDidChangeBaseBranch.fire(newBranch);
} else {
try {
compareBranch = await this._folderRepositoryManager.repository.getBranch(newBranch);
this._onDidChangeCompareBranch.fire(compareBranch.name!);
} catch (e) {
vscode.window.showErrorMessage('Branch does not exist locally.');
}
}
compareBranch = compareBranch ?? await this._folderRepositoryManager.repository.getBranch(this._compareBranch);
const titleAndDescription = await this.getTitleAndDescription(compareBranch, this._baseBranch);
return this._replyMessage(message, { title: titleAndDescription.title, description: titleAndDescription.description });
}
protected async _onDidReceiveMessage(message: IRequestMessage<any>) {
const result = await super._onDidReceiveMessage(message);
if (result !== this.MESSAGE_UNHANDLED) {
return;
}
switch (message.command) {
case 'pr.cancelCreate':
vscode.commands.executeCommand('setContext', 'github:createPullRequest', false);
this._onDone.fire(undefined);
return this._replyMessage(message, undefined);
case 'pr.create':
return this.create(message);
case 'pr.changeBaseRemote':
return this.changeRemote(message, true);
case 'pr.changeBaseBranch':
return this.changeBranch(message, true);
case 'pr.changeCompareRemote':
return this.changeRemote(message, false);
case 'pr.changeCompareBranch':
return this.changeBranch(message, false);
default:
// Log error
vscode.window.showErrorMessage('Unsupported webview message');
}
}
private _getHtmlForWebview() {
const nonce = getNonce();
const uri = vscode.Uri.joinPath(this._extensionUri, 'dist', 'webview-create-pr-view.js');
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src vscode-resource: https:; script-src 'nonce-${nonce}'; style-src vscode-resource: 'unsafe-inline' http: https: data:;">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create Pull Request</title>
</head>
<body>
<div id="app"></div>
<script nonce="${nonce}" src="${this._webview!.asWebviewUri(uri).toString()}"></script>
</body>
</html>`;
}
}