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
297 lines (240 loc) · 10 KB
/
Copy pathcreatePRViewProvider.ts
File metadata and controls
297 lines (240 loc) · 10 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
/*---------------------------------------------------------------------------------------------
* 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 { byRemoteName, DetachedHeadError, FolderRepositoryManager, PullRequestDefaults, titleAndBodyFrom } from './folderRepositoryManager';
import webviewContent from '../../media/createPR-webviewIndex.js';
import { getNonce, IRequestMessage, WebviewBase } from '../common/webview';
import { PR_SETTINGS_NAMESPACE, PR_TITLE } from '../common/settingKeys';
import { OctokitCommon } from './common';
import { PullRequestModel } from './pullRequestModel';
import Logger from '../common/logger';
import { PullRequestGitHelper } from './pullRequestGitHelper';
export type PullRequestTitleSource = 'commit' | 'branch' | 'custom' | 'ask';
export enum PullRequestTitleSourceEnum {
Commit = 'commit',
Branch = 'branch',
Custom = 'custom',
Ask = 'ask'
}
export type PullRequestDescriptionSource = 'template' | 'commit' | 'custom' | 'ask';
export enum PullRequestDescriptionSourceEnum {
Template = 'template',
Commit = 'commit',
Custom = 'custom',
Ask = 'ask'
}
interface RemoteInfo {
owner: string;
repositoryName: string;
}
export class CreatePullRequestViewProvider extends WebviewBase implements vscode.WebviewViewProvider {
public static readonly viewType = 'github:createPullRequest';
private _webviewView: vscode.WebviewView | undefined;
private _onDone = new vscode.EventEmitter<PullRequestModel | undefined>();
readonly onDone: vscode.Event<PullRequestModel | undefined> = this._onDone.event;
private _onDidChangeSelectedRemote = new vscode.EventEmitter<RemoteInfo>();
readonly onDidChangeSelectedRemote: vscode.Event<RemoteInfo> = this._onDidChangeSelectedRemote.event;
private _onDidChangeSelectedBranch = new vscode.EventEmitter<string>();
readonly onDidChangeSelectedBranch: vscode.Event<string> = this._onDidChangeSelectedBranch.event;
constructor(
private readonly _extensionUri: vscode.Uri,
private readonly _folderRepositoryManager: FolderRepositoryManager,
private readonly _pullRequestDefaults: PullRequestDefaults,
private readonly _isDraft: boolean
) {
super();
}
public resolveWebviewView(
webviewView: vscode.WebviewView,
context: vscode.WebviewViewResolveContext,
_token: vscode.CancellationToken,
) {
this._webviewView = webviewView;
this._webview = webviewView.webview;
super.initialize();
webviewView.webview.options = {
// Allow scripts in the webview
enableScripts: true,
localResourceRoots: [
this._extensionUri
]
};
webviewView.webview.html = this._getHtmlForWebview();
this.initializeParams();
}
public show() {
if (this._webviewView) {
this._webviewView.show();
} else {
vscode.commands.executeCommand('github:createPullRequest.focus')
}
}
private async getTitle(): Promise<string> {
const method = vscode.workspace.getConfiguration(PR_SETTINGS_NAMESPACE).get<PullRequestTitleSource>(PR_TITLE, PullRequestTitleSourceEnum.Ask);
switch (method) {
case PullRequestTitleSourceEnum.Branch:
return this._folderRepositoryManager.repository.state.HEAD!.name!;
case PullRequestTitleSourceEnum.Commit:
return titleAndBodyFrom(await this._folderRepositoryManager.getHeadCommitMessage()).title;
case PullRequestTitleSourceEnum.Custom:
return '';
default:
// Use same default as GitHub, if there is only one commit, use the commit, otherwise use the branch name.
// By default, the base branch we use for comparison is the base branch of origin. Compare this to the
// current local branch if it has a GitHub remote.
const origin = await this._folderRepositoryManager.getOrigin();
const repositoryHead = this._folderRepositoryManager.repository.state.HEAD;
let hasMultipleCommits = true;
if (repositoryHead?.upstream) {
const headRepo = this._folderRepositoryManager.findRepo(byRemoteName(repositoryHead?.upstream.remote));
if (headRepo) {
const headBranch = `${headRepo.remote.owner}:${repositoryHead.name}`;
const commits = await origin.compareCommits(this._pullRequestDefaults.base, headBranch);
hasMultipleCommits = commits.total_commits > 1;
}
}
if (hasMultipleCommits) {
return this._folderRepositoryManager.repository.state.HEAD!.name!;
} else {
return titleAndBodyFrom(await this._folderRepositoryManager.getHeadCommitMessage()).title;
}
}
}
private async getPullRequestTemplate(): Promise<string> {
const templateUris = await this._folderRepositoryManager.getPullRequestTemplates();
if (templateUris[0]) {
try {
const templateContent = await vscode.workspace.fs.readFile(templateUris[0]);
return templateContent.toString();
} catch (e) {
Logger.appendLine(`Reading pull request template failed: ${e}`);
return '';
}
}
return '';
}
private async getDescription(): Promise<string> {
const method = vscode.workspace.getConfiguration('githubPullRequests').get<PullRequestDescriptionSource>('pullRequestDescription', PullRequestDescriptionSourceEnum.Ask);
switch (method) {
case PullRequestDescriptionSourceEnum.Template:
return this.getPullRequestTemplate();
case PullRequestDescriptionSourceEnum.Commit:
return titleAndBodyFrom(await this._folderRepositoryManager.getHeadCommitMessage()).body;
case PullRequestDescriptionSourceEnum.Custom:
return '';
default:
// Try to match github's default, first look for template, then use commit body if available.
const pullRequestTemplate = this.getPullRequestTemplate();
return pullRequestTemplate ?? titleAndBodyFrom(await this._folderRepositoryManager.getHeadCommitMessage()).body ?? '';
}
}
public async initializeParams(): Promise<void> {
if (!this._folderRepositoryManager.repository.state.HEAD) {
throw new DetachedHeadError(this._folderRepositoryManager.repository);
}
const defaultRemote: RemoteInfo = {
owner: this._pullRequestDefaults.owner,
repositoryName: this._pullRequestDefaults.repo
};
Promise.all([
this._folderRepositoryManager.getGitHubRemotes(),
this._folderRepositoryManager.listBranches(this._pullRequestDefaults.owner, this._pullRequestDefaults.repo),
this.getTitle(),
this.getDescription()
]).then(result => {
const [githubRemotes, branchesForRemote, defaultTitle, defaultDescription] = result;
const remotes: RemoteInfo[] = githubRemotes.map(remote => {
return {
owner: remote.owner,
repositoryName: remote.repositoryName
};
});
this._postMessage({
command: 'pr.initialize',
params: {
availableRemotes: remotes,
defaultRemote,
defaultBranch: this._pullRequestDefaults.base,
branchesForRemote,
defaultTitle,
defaultDescription
}
});
});
}
private async changeRemote(message: IRequestMessage<{ owner: string, repositoryName: string }>): Promise<void> {
const { owner, repositoryName } = message.args;
const githubRepository = this._folderRepositoryManager.findRepo(repo => owner === repo.remote.owner && repositoryName === repo.remote.repositoryName);
if (!githubRepository) {
throw new Error('No matching GitHub repository found.');
}
const defaultBranch = await githubRepository.getDefaultBranch();
const newBranches = await this._folderRepositoryManager.listBranches(owner, repositoryName);
this._onDidChangeSelectedRemote.fire({ owner, repositoryName });
return this._replyMessage(message, { branches: newBranches, defaultBranch });
}
private async create(message: IRequestMessage<OctokitCommon.PullsCreateParams>): Promise<void> {
try {
if (!this._folderRepositoryManager.repository.state.HEAD!.upstream) {
throw new DetachedHeadError(this._folderRepositoryManager.repository);
}
const branchName = this._folderRepositoryManager.repository.state.HEAD!.name!;
const headRepo = this._folderRepositoryManager.findRepo(byRemoteName(this._folderRepositoryManager.repository.state.HEAD!.upstream.remote));
if (!headRepo) {
throw new Error(`Unable to find GitHub repository matching '${this._folderRepositoryManager.repository.state.HEAD!.upstream.remote}'.`);
}
const head = `${headRepo.remote.owner}:${branchName}`;
const createdPR = await this._folderRepositoryManager.createPullRequest({ ...message.args, head, draft: this._isDraft });
// Create was cancelled
if (!createdPR) {
this._throwError(message, undefined);
} else {
await this._replyMessage(message, {});
await PullRequestGitHelper.associateBranchWithPullRequest(this._folderRepositoryManager.repository, createdPR, branchName);
this._onDone.fire(createdPR);
}
} catch (e) {
this._throwError(message, e.message);
}
}
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;
case 'pr.create':
return this.create(message);
case 'pr.changeRemote':
return this.changeRemote(message);
case 'pr.changeBranch':
this._onDidChangeSelectedBranch.fire(message.args);
return;
default:
// Log error
vscode.window.showErrorMessage('Unsupported webview message');
}
}
private _getHtmlForWebview() {
const nonce = getNonce();
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}">${webviewContent}</script>
</body>
</html>`;
}
}