-
Notifications
You must be signed in to change notification settings - Fork 732
Expand file tree
/
Copy pathcurrentIssue.ts
More file actions
338 lines (301 loc) · 10.5 KB
/
currentIssue.ts
File metadata and controls
338 lines (301 loc) · 10.5 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
/*---------------------------------------------------------------------------------------------
* 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 { Branch, Repository } from '../api/api';
import { GitErrorCodes } from '../api/api1';
import { Remote } from '../common/remote';
import {
ASSIGN_WHEN_WORKING,
ISSUE_BRANCH_TITLE,
ISSUES_SETTINGS_NAMESPACE,
USE_BRANCH_FOR_ISSUES,
WORKING_ISSUE_FORMAT_SCM,
} from '../common/settingKeys';
import { FolderRepositoryManager, PullRequestDefaults } from '../github/folderRepositoryManager';
import { IssueModel } from '../github/issueModel';
import { variableSubstitution } from '../github/utils';
import { IssueState, StateManager } from './stateManager';
export class CurrentIssue {
private repoChangeDisposable: vscode.Disposable | undefined;
private _branchName: string | undefined;
private user: string | undefined;
private repo: Repository | undefined;
private _repoDefaults: PullRequestDefaults | undefined;
private _onDidChangeCurrentIssueState: vscode.EventEmitter<void> = new vscode.EventEmitter();
public readonly onDidChangeCurrentIssueState: vscode.Event<void> = this._onDidChangeCurrentIssueState.event;
constructor(
private issueModel: IssueModel,
public readonly manager: FolderRepositoryManager,
private stateManager: StateManager,
remote?: Remote,
private shouldPromptForBranch?: boolean,
) {
this.setRepo(remote ?? this.issueModel.githubRepository.remote);
}
private setRepo(repoRemote: Remote) {
for (let i = 0; i < this.stateManager.gitAPI.repositories.length; i++) {
const repo = this.stateManager.gitAPI.repositories[i];
for (let j = 0; j < repo.state.remotes.length; j++) {
const remote = repo.state.remotes[j];
if (
remote.name === repoRemote?.remoteName &&
remote.fetchUrl
?.toLowerCase()
.includes(`${repoRemote.owner.toLowerCase()}/${repoRemote.repositoryName.toLowerCase()}`)
) {
this.repo = repo;
return;
}
}
}
}
get branchName(): string | undefined {
return this._branchName;
}
get repoDefaults(): PullRequestDefaults | undefined {
return this._repoDefaults;
}
get issue(): IssueModel {
return this.issueModel;
}
public async startWorking(silent: boolean = false): Promise<boolean> {
try {
this._repoDefaults = await this.manager.getPullRequestDefaults();
if (await this.createIssueBranch(silent)) {
await this.setCommitMessageAndGitEvent();
this._onDidChangeCurrentIssueState.fire();
const login = (await this.manager.getCurrentUser(this.issueModel.githubRepository)).login;
if (
vscode.workspace.getConfiguration(ISSUES_SETTINGS_NAMESPACE).get(ASSIGN_WHEN_WORKING) &&
!this.issueModel.assignees?.find(value => value.login === login)
) {
if (
this.manager.gitHubRepositories.find(
(r) =>
r.remote.owner === this.issueModel.remote.owner &&
r.remote.repositoryName === this.issueModel.remote.repositoryName,
)
) {
await this.manager.assignIssue(this.issueModel, login);
}
await this.stateManager.refresh(this.manager);
}
return true;
}
} catch (e) {
vscode.window.showErrorMessage(
vscode.l10n.t("There is no remote. Can't start working on an issue."),
);
}
return false;
}
public dispose() {
this.repoChangeDisposable?.dispose();
}
public async stopWorking(checkoutDefaultBranch: boolean) {
if (this.repo) {
this.repo.inputBox.value = '';
}
if (this._repoDefaults && checkoutDefaultBranch) {
try {
await this.manager.repository.checkout(this._repoDefaults.base);
} catch (e: any) {
if (e.gitErrorCode === GitErrorCodes.DirtyWorkTree) {
vscode.window.showErrorMessage(
vscode.l10n.t(
'Your local changes would be overwritten by checkout, please commit your changes or stash them before you switch branches',
),
);
}
throw e;
}
}
this._onDidChangeCurrentIssueState.fire();
this.dispose();
}
private async getBranch(branch: string): Promise<Branch | undefined> {
try {
return await this.manager.repository.getBranch(branch);
} catch {
return undefined;
}
}
private async createOrCheckoutBranch(branch: string): Promise<boolean> {
let localBranchName = branch;
try {
const isRemoteBranch = branch.startsWith('origin/');
if (isRemoteBranch) {
localBranchName = branch.substring('origin/'.length);
}
const localBranch = await this.getBranch(localBranchName);
if (localBranch) {
await this.manager.repository.checkout(localBranchName);
} else if (isRemoteBranch) {
await this.manager.repository.createBranch(localBranchName, true, branch);
await this.manager.repository.setBranchUpstream(localBranchName, branch);
} else {
await this.manager.repository.createBranch(localBranchName, true);
}
return true;
} catch (e: any) {
if (e.message !== 'User aborted') {
vscode.window.showErrorMessage(
`Unable to checkout branch ${localBranchName}. There may be file conflicts that prevent this branch change. Git error: ${e.message}`,
);
}
return false;
}
}
private validateBranchName(branch: string): string | undefined {
const VALID_BRANCH_CHARACTERS = /[^ \\@\~\^\?\*\[]+/;
const match = branch.match(VALID_BRANCH_CHARACTERS);
if (match && match.length > 0 && match[0] !== branch) {
return vscode.l10n.t(
'Branch name cannot contain a space or the following characters: \\@~^?*[',
);
}
return undefined;
}
private showBranchNameError(error: string) {
const editSetting = 'Edit Setting';
vscode.window.showErrorMessage(error, editSetting).then((result) => {
if (result === editSetting) {
vscode.commands.executeCommand(
'workbench.action.openSettings',
`${ISSUES_SETTINGS_NAMESPACE}.${ISSUE_BRANCH_TITLE}`,
);
}
});
}
private async createIssueBranch(silent: boolean): Promise<boolean> {
const createBranchConfig = this.shouldPromptForBranch
? 'prompt'
: vscode.workspace
.getConfiguration(ISSUES_SETTINGS_NAMESPACE)
.get<string>(USE_BRANCH_FOR_ISSUES);
if (createBranchConfig === 'off') {
return true;
}
const state: IssueState = this.stateManager.getSavedIssueState(this.issueModel.number);
const issueNumberStr = this.issueModel.number.toString();
const suggestedBranchName = `issue${issueNumberStr}`;
this._branchName = undefined;
const branches = await this.manager.repository.getBranches({ remote: true });
const branchesWithIssueNumber = branches.filter((branch) =>
branch.name?.includes(issueNumberStr),
);
const otherBranches = branches.filter(
(branch) => !branch.name?.includes(issueNumberStr),
);
const branchItems: vscode.QuickPickItem[] = [];
if (branchesWithIssueNumber.length > 0) {
branchItems.push({
label: 'Branches containing issue number:',
kind: vscode.QuickPickItemKind.Separator,
});
for (const branch of branchesWithIssueNumber) {
const isRemote = branch.name?.startsWith('origin/');
branchItems.push({
label: `${isRemote ? '$(cloud)' : '$(git-branch)'} ${branch.name ?? ''}`,
description: `${isRemote ? 'Remote' : 'Local'} branch`,
});
}
}
if (!branches.find((branch) => branch.name === suggestedBranchName)) {
branchItems.push({
label: `$(lightbulb) ${suggestedBranchName}`,
description: 'Suggested branch name for this issue',
detail: 'Recommended branch name based on the issue number',
picked: true,
});
}
if (otherBranches.length > 0) {
branchItems.push({
label: 'Other branches:',
kind: vscode.QuickPickItemKind.Separator,
});
for (const branch of otherBranches) {
const isRemote = branch.name?.startsWith('origin/');
branchItems.push({
label: `${isRemote ? '$(cloud)' : '$(git-branch)'} ${branch.name ?? ''}`,
description: `${isRemote ? 'Remote' : 'Local'} branch`,
});
}
}
branchItems.push({
label: '$(pencil) Enter a custom branch name...',
description: 'Choose this to type your own branch name',
});
const quickPick = vscode.window.createQuickPick<vscode.QuickPickItem>();
quickPick.items = branchItems;
quickPick.placeholder = 'Select a branch or create a new one for this issue';
quickPick.ignoreFocusOut = true;
quickPick.canSelectMany = false;
const suggestedItem = branchItems.find((item) =>
item.label.includes(suggestedBranchName),
);
if (suggestedItem) {
quickPick.activeItems = [suggestedItem];
}
quickPick.show();
const selectedBranch = await new Promise<vscode.QuickPickItem | undefined>((resolve) => {
quickPick.onDidAccept(() => {
const selection = quickPick.selectedItems[0];
resolve(selection);
quickPick.hide();
});
quickPick.onDidHide(() => {
resolve(undefined);
});
});
quickPick.dispose();
if (!selectedBranch) {
vscode.window.showInformationMessage('Branch selection cancelled.');
return false;
}
if (selectedBranch.label === '$(pencil) Enter a custom branch name...') {
const customBranchName = await vscode.window.showInputBox({
prompt: 'Enter your custom branch name',
placeHolder: 'e.g., feature/my-custom-branch',
validateInput: (input) =>
input.trim() === '' ? 'Branch name cannot be empty.' : undefined,
});
if (!customBranchName) {
vscode.window.showInformationMessage('Branch creation cancelled.');
return false;
}
this._branchName = customBranchName.trim();
} else {
this._branchName = selectedBranch.label.replace(/^\$\([^\)]+\)\s*/, '').trim();
}
const validateBranchName = this.validateBranchName(this._branchName);
if (validateBranchName) {
this.showBranchNameError(validateBranchName);
return false;
}
state.branch = this._branchName;
await this.stateManager.setSavedIssueState(this.issueModel, state);
if (!(await this.createOrCheckoutBranch(this._branchName))) {
this._branchName = undefined;
return false;
}
return true;
}
public async getCommitMessage(): Promise<string | undefined> {
const configuration = vscode.workspace
.getConfiguration(ISSUES_SETTINGS_NAMESPACE)
.get(WORKING_ISSUE_FORMAT_SCM);
if (typeof configuration === 'string') {
return variableSubstitution(configuration, this.issueModel, this._repoDefaults);
}
return undefined;
}
private async setCommitMessageAndGitEvent() {
const message = await this.getCommitMessage();
if (this.repo && message) {
this.repo.inputBox.value = message;
}
}
}