commands.ts 45.1 KB
Newer Older
J
Joao Moreno 已提交
1 2 3 4 5 6 7
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

'use strict';

J
Joao Moreno 已提交
8
import { Uri, commands, Disposable, window, workspace, QuickPickItem, OutputChannel, Range, WorkspaceEdit, Position, LineChange, SourceControlResourceState, TextDocumentShowOptions, ViewColumn, ProgressLocation } from 'vscode';
J
Joao Moreno 已提交
9
import { Ref, RefType, Git, GitErrorCodes, Branch } from './git';
J
Joao Moreno 已提交
10
import { Repository, Resource, Status, CommitOptions, ResourceGroupType } from './repository';
J
Joao Moreno 已提交
11
import { Model } from './model';
J
Joao Moreno 已提交
12
import { toGitUri, fromGitUri } from './uri';
13
import { applyLineChanges, intersectDiffWithRange, toLineRanges, invertLineChange } from './staging';
J
Joao Moreno 已提交
14
import * as path from 'path';
J
Joao Moreno 已提交
15
import * as os from 'os';
J
Joao Moreno 已提交
16
import TelemetryReporter from 'vscode-extension-telemetry';
J
Joao Moreno 已提交
17 18 19
import * as nls from 'vscode-nls';

const localize = nls.loadMessageBundle();
J
Joao Moreno 已提交
20

J
Joao Moreno 已提交
21 22 23 24 25 26 27
class CheckoutItem implements QuickPickItem {

	protected get shortCommit(): string { return (this.ref.commit || '').substr(0, 8); }
	protected get treeish(): string | undefined { return this.ref.name; }
	get label(): string { return this.ref.name || this.shortCommit; }
	get description(): string { return this.shortCommit; }

J
Joao Moreno 已提交
28
	constructor(protected ref: Ref) { }
J
Joao Moreno 已提交
29

J
Joao Moreno 已提交
30
	async run(repository: Repository): Promise<void> {
J
Joao Moreno 已提交
31 32 33 34 35 36
		const ref = this.treeish;

		if (!ref) {
			return;
		}

J
Joao Moreno 已提交
37
		await repository.checkout(ref);
J
Joao Moreno 已提交
38 39 40 41 42
	}
}

class CheckoutTagItem extends CheckoutItem {

J
Joao Moreno 已提交
43 44 45
	get description(): string {
		return localize('tag at', "Tag at {0}", this.shortCommit);
	}
J
Joao Moreno 已提交
46 47 48 49
}

class CheckoutRemoteHeadItem extends CheckoutItem {

J
Joao Moreno 已提交
50 51 52
	get description(): string {
		return localize('remote branch at', "Remote branch at {0}", this.shortCommit);
	}
J
Joao Moreno 已提交
53 54 55 56 57 58 59 60 61 62 63

	protected get treeish(): string | undefined {
		if (!this.ref.name) {
			return;
		}

		const match = /^[^/]+\/(.*)$/.exec(this.ref.name);
		return match ? match[1] : this.ref.name;
	}
}

M
Maik Riechert 已提交
64 65
class BranchDeleteItem implements QuickPickItem {

66 67 68
	private get shortCommit(): string { return (this.ref.commit || '').substr(0, 8); }
	get branchName(): string | undefined { return this.ref.name; }
	get label(): string { return this.branchName || ''; }
M
Maik Riechert 已提交
69 70
	get description(): string { return this.shortCommit; }

71
	constructor(private ref: Ref) { }
M
Maik Riechert 已提交
72

J
Joao Moreno 已提交
73
	async run(repository: Repository, force?: boolean): Promise<void> {
74
		if (!this.branchName) {
M
Maik Riechert 已提交
75 76
			return;
		}
J
Joao Moreno 已提交
77
		await repository.deleteBranch(this.branchName, force);
M
Maik Riechert 已提交
78 79 80
	}
}

81 82 83 84 85 86
class MergeItem implements QuickPickItem {

	get label(): string { return this.ref.name || ''; }
	get description(): string { return this.ref.name || ''; }

	constructor(protected ref: Ref) { }
J
Joao Moreno 已提交
87

J
Joao Moreno 已提交
88 89
	async run(repository: Repository): Promise<void> {
		await repository.merge(this.ref.name! || this.ref.commit!);
J
Joao Moreno 已提交
90
	}
91 92
}

J
Joao Moreno 已提交
93 94 95 96 97
class CreateBranchItem implements QuickPickItem {

	get label(): string { return localize('create branch', '$(plus) Create new branch'); }
	get description(): string { return ''; }

J
Joao Moreno 已提交
98
	async run(repository: Repository): Promise<void> {
J
Joao Moreno 已提交
99 100 101 102
		await commands.executeCommand('git.branch');
	}
}

J
Joao Moreno 已提交
103
interface CommandOptions {
J
Joao Moreno 已提交
104
	repository?: boolean;
J
Joao Moreno 已提交
105 106 107
	diff?: boolean;
}

108 109 110 111
interface Command {
	commandId: string;
	key: string;
	method: Function;
J
Joao Moreno 已提交
112
	options: CommandOptions;
113 114 115
}

const Commands: Command[] = [];
J
Joao Moreno 已提交
116

J
Joao Moreno 已提交
117
function command(commandId: string, options: CommandOptions = {}): Function {
J
Joao Moreno 已提交
118
	return (target: any, key: string, descriptor: any) => {
J
Joao Moreno 已提交
119 120 121 122
		if (!(typeof descriptor.value === 'function')) {
			throw new Error('not supported');
		}

J
Joao Moreno 已提交
123
		Commands.push({ commandId, key, method: descriptor.value, options });
J
Joao Moreno 已提交
124 125
	};
}
J
Joao Moreno 已提交
126

J
Joao Moreno 已提交
127
export class CommandCenter {
J
Joao Moreno 已提交
128 129

	private disposables: Disposable[];
J
Joao Moreno 已提交
130

J
Joao Moreno 已提交
131
	constructor(
J
Joao Moreno 已提交
132
		private git: Git,
J
Joao Moreno 已提交
133
		private model: Model,
J
Joao Moreno 已提交
134 135
		private outputChannel: OutputChannel,
		private telemetryReporter: TelemetryReporter
J
Joao Moreno 已提交
136
	) {
J
Joao Moreno 已提交
137 138
		this.disposables = Commands.map(({ commandId, key, method, options }) => {
			const command = this.createCommand(commandId, key, method, options);
139

J
Joao Moreno 已提交
140
			if (options.diff) {
J
Joao Moreno 已提交
141 142 143 144 145
				return commands.registerDiffInformationCommand(commandId, command);
			} else {
				return commands.registerCommand(commandId, command);
			}
		});
J
Joao Moreno 已提交
146 147
	}

J
Joao Moreno 已提交
148 149
	@command('git.refresh', { repository: true })
	async refresh(repository: Repository): Promise<void> {
J
Joao Moreno 已提交
150
		await repository.status();
J
Joao Moreno 已提交
151
	}
J
Joao Moreno 已提交
152

J
Joao Moreno 已提交
153 154
	@command('git.openResource')
	async openResource(resource: Resource): Promise<void> {
J
Joao 已提交
155
		await this._openResource(resource, undefined, true, false);
J
Joao Moreno 已提交
156 157
	}

J
Joao 已提交
158
	private async _openResource(resource: Resource, preview?: boolean, preserveFocus?: boolean, preserveSelection?: boolean): Promise<void> {
J
Joao Moreno 已提交
159
		const left = this.getLeftResource(resource);
J
Joao Moreno 已提交
160
		const right = this.getRightResource(resource);
J
Joao Moreno 已提交
161 162
		const title = this.getTitle(resource);

J
Joao Moreno 已提交
163 164 165 166 167
		if (!right) {
			// TODO
			console.error('oh no');
			return;
		}
J
Joao Moreno 已提交
168

J
Joao Moreno 已提交
169
		const opts: TextDocumentShowOptions = {
J
Joao Moreno 已提交
170 171
			preserveFocus,
			preview,
172
			viewColumn: ViewColumn.Active
J
Joao Moreno 已提交
173 174
		};

J
Joao Moreno 已提交
175 176
		const activeTextEditor = window.activeTextEditor;

177
		if (preserveSelection && activeTextEditor && activeTextEditor.document.uri.toString() === right.toString()) {
J
Joao Moreno 已提交
178 179 180
			opts.selection = activeTextEditor.selection;
		}

181 182 183 184 185 186
		if (!left) {
			const document = await workspace.openTextDocument(right);
			await window.showTextDocument(document, opts);
			return;
		}

J
Joao Moreno 已提交
187
		return await commands.executeCommand<void>('vscode.diff', left, right, title, opts);
J
Joao Moreno 已提交
188 189 190 191 192 193
	}

	private getLeftResource(resource: Resource): Uri | undefined {
		switch (resource.type) {
			case Status.INDEX_MODIFIED:
			case Status.INDEX_RENAMED:
J
Joao Moreno 已提交
194
				return toGitUri(resource.original, 'HEAD');
J
Joao Moreno 已提交
195 196

			case Status.MODIFIED:
J
Joao Moreno 已提交
197
				return toGitUri(resource.resourceUri, '~');
198 199 200

			case Status.DELETED_BY_THEM:
				return toGitUri(resource.resourceUri, '');
J
Joao Moreno 已提交
201
		}
J
Joao Moreno 已提交
202
	}
J
Joao Moreno 已提交
203

J
Joao Moreno 已提交
204
	private getRightResource(resource: Resource): Uri | undefined {
J
Joao Moreno 已提交
205 206 207 208 209
		switch (resource.type) {
			case Status.INDEX_MODIFIED:
			case Status.INDEX_ADDED:
			case Status.INDEX_COPIED:
			case Status.INDEX_RENAMED:
J
Joao Moreno 已提交
210
				return toGitUri(resource.resourceUri, '');
J
Joao Moreno 已提交
211 212

			case Status.INDEX_DELETED:
213
			case Status.DELETED_BY_THEM:
J
Joao Moreno 已提交
214
			case Status.DELETED:
J
Joao Moreno 已提交
215
				return toGitUri(resource.resourceUri, 'HEAD');
J
Joao Moreno 已提交
216 217 218 219

			case Status.MODIFIED:
			case Status.UNTRACKED:
			case Status.IGNORED:
J
Joao Moreno 已提交
220 221 222 223 224 225
				const repository = this.model.getRepository(resource.resourceUri);

				if (!repository) {
					return;
				}

J
Joao Moreno 已提交
226
				const uriString = resource.resourceUri.toString();
J
Joao Moreno 已提交
227
				const [indexStatus] = repository.indexGroup.resourceStates.filter(r => r.resourceUri.toString() === uriString);
J
Joao Moreno 已提交
228

J
Joao Moreno 已提交
229 230
				if (indexStatus && indexStatus.renameResourceUri) {
					return indexStatus.renameResourceUri;
J
Joao Moreno 已提交
231 232
				}

J
Joao Moreno 已提交
233
				return resource.resourceUri;
J
Joao Moreno 已提交
234

235
			case Status.BOTH_ADDED:
J
Joao Moreno 已提交
236
			case Status.BOTH_MODIFIED:
J
Joao Moreno 已提交
237
				return resource.resourceUri;
J
Joao Moreno 已提交
238 239 240 241
		}
	}

	private getTitle(resource: Resource): string {
J
Joao Moreno 已提交
242
		const basename = path.basename(resource.resourceUri.fsPath);
J
Joao Moreno 已提交
243 244 245 246

		switch (resource.type) {
			case Status.INDEX_MODIFIED:
			case Status.INDEX_RENAMED:
M
Marc Kassay 已提交
247
			case Status.DELETED_BY_THEM:
J
Joao Moreno 已提交
248 249 250
				return `${basename} (Index)`;

			case Status.MODIFIED:
M
Marc Kassay 已提交
251 252
			case Status.BOTH_ADDED:
			case Status.BOTH_MODIFIED:
J
Joao Moreno 已提交
253 254 255 256 257 258
				return `${basename} (Working Tree)`;
		}

		return '';
	}

J
Joao Moreno 已提交
259
	@command('git.clone')
260
	async clone(): Promise<void> {
J
Joao Moreno 已提交
261
		const url = await window.showInputBox({
J
Joao Moreno 已提交
262 263
			prompt: localize('repourl', "Repository URL"),
			ignoreFocusOut: true
J
Joao Moreno 已提交
264 265 266
		});

		if (!url) {
K
kieferrm 已提交
267
			/* __GDPR__
K
kieferrm 已提交
268 269 270 271
				"clone" : {
					"outcome" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
				}
			*/
272 273
			this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'no_URL' });
			return;
J
Joao Moreno 已提交
274 275
		}

276
		const config = workspace.getConfiguration('git');
J
Joao Moreno 已提交
277
		const value = config.get<string>('defaultCloneDirectory') || os.homedir();
278

J
Joao Moreno 已提交
279 280
		const parentPath = await window.showInputBox({
			prompt: localize('parent', "Parent Directory"),
J
Joao Moreno 已提交
281
			value,
J
Joao Moreno 已提交
282
			ignoreFocusOut: true
J
Joao Moreno 已提交
283 284 285
		});

		if (!parentPath) {
K
kieferrm 已提交
286
			/* __GDPR__
K
kieferrm 已提交
287 288 289 290
				"clone" : {
					"outcome" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
				}
			*/
291 292
			this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'no_directory' });
			return;
J
Joao Moreno 已提交
293 294
		}

J
Joao Moreno 已提交
295
		const clonePromise = this.git.clone(url, parentPath);
M
Maryam Archie 已提交
296

J
Joao Moreno 已提交
297

298
		try {
M
Maryam Archie 已提交
299 300 301
			window.withProgress({ location: ProgressLocation.SourceControl, title: localize('cloning', "Cloning git repository...") }, () => clonePromise);
			window.withProgress({ location: ProgressLocation.Window, title: localize('cloning', "Cloning git repository...") }, () => clonePromise);

302 303 304 305 306 307
			const repositoryPath = await clonePromise;

			const open = localize('openrepo', "Open Repository");
			const result = await window.showInformationMessage(localize('proposeopen', "Would you like to open the cloned repository?"), open);

			const openFolder = result === open;
K
kieferrm 已提交
308
			/* __GDPR__
K
kieferrm 已提交
309 310 311 312 313
				"clone" : {
					"outcome" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
					"openFolder": { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth", "isMeasurement": true }
				}
			*/
314 315 316 317
			this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'success' }, { openFolder: openFolder ? 1 : 0 });
			if (openFolder) {
				commands.executeCommand('vscode.openFolder', Uri.file(repositoryPath));
			}
318 319
		} catch (err) {
			if (/already exists and is not an empty directory/.test(err && err.stderr || '')) {
K
kieferrm 已提交
320
				/* __GDPR__
K
kieferrm 已提交
321 322 323 324
					"clone" : {
						"outcome" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
					}
				*/
325 326
				this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'directory_not_empty' });
			} else {
K
kieferrm 已提交
327
				/* __GDPR__
K
kieferrm 已提交
328 329 330 331
					"clone" : {
						"outcome" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
					}
				*/
332
				this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'error' });
333 334
			}
			throw err;
J
Joao Moreno 已提交
335 336 337
		}
	}

J
Joao Moreno 已提交
338
	@command('git.init')
J
Joao Moreno 已提交
339
	async init(): Promise<void> {
J
Joao Moreno 已提交
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
		const value = workspace.workspaceFolders && workspace.workspaceFolders.length > 0
			? workspace.workspaceFolders[0].uri.fsPath
			: os.homedir();

		const path = await window.showInputBox({
			placeHolder: localize('path to init', "Folder path"),
			prompt: localize('provide path', "Please provide a folder path to initialize a Git repository"),
			value,
			ignoreFocusOut: true
		});

		if (!path) {
			return;
		}

		await this.git.init(path);
		await this.model.tryOpenRepository(path);
J
Joao Moreno 已提交
357 358
	}

J
Joao Moreno 已提交
359 360
	@command('git.openFile')
	async openFile(arg?: Resource | Uri, ...resourceStates: SourceControlResourceState[]): Promise<void> {
361
		const preserveFocus = arg instanceof Resource;
J
Joao Moreno 已提交
362

363
		let uris: Uri[] | undefined;
364 365 366

		if (arg instanceof Uri) {
			if (arg.scheme === 'git') {
367
				uris = [Uri.file(fromGitUri(arg).path)];
368
			} else if (arg.scheme === 'file') {
369
				uris = [arg];
370 371 372 373 374 375
			}
		} else {
			let resource = arg;

			if (!(resource instanceof Resource)) {
				// can happen when called from a keybinding
376
				resource = this.getSCMResource();
377 378 379
			}

			if (resource) {
380
				uris = [...resourceStates.map(r => r.resourceUri), resource.resourceUri];
381
			}
J
Joao Moreno 已提交
382 383
		}

384
		if (!uris) {
J
Joao Moreno 已提交
385
			return;
J
Joao Moreno 已提交
386 387
		}

388 389 390 391
		const preview = uris.length === 1 ? true : false;
		const activeTextEditor = window.activeTextEditor;
		for (const uri of uris) {
			const opts: TextDocumentShowOptions = {
J
Joao Moreno 已提交
392
				preserveFocus,
393
				preview: preview,
394
				viewColumn: ViewColumn.Active
395 396
			};

397
			if (activeTextEditor && activeTextEditor.document.uri.toString() === uri.toString()) {
B
Benjamin Pasero 已提交
398 399 400
				opts.selection = activeTextEditor.selection;
			}

401 402
			const document = await workspace.openTextDocument(uri);
			await window.showTextDocument(document, opts);
J
Joao Moreno 已提交
403
		}
J
Joao Moreno 已提交
404 405
	}

J
Joao Moreno 已提交
406 407
	@command('git.openHEADFile')
	async openHEADFile(arg?: Resource | Uri): Promise<void> {
D
Duroktar 已提交
408 409 410 411 412
		let resource: Resource | undefined = undefined;

		if (arg instanceof Resource) {
			resource = arg;
		} else if (arg instanceof Uri) {
413
			resource = this.getSCMResource(arg);
D
Duroktar 已提交
414
		} else {
415
			resource = this.getSCMResource();
D
Duroktar 已提交
416 417 418 419 420 421
		}

		if (!resource) {
			return;
		}

J
Joao Moreno 已提交
422
		const HEAD = this.getLeftResource(resource);
D
Duroktar 已提交
423

J
Joao Moreno 已提交
424 425 426
		if (!HEAD) {
			window.showWarningMessage(localize('HEAD not available', "HEAD version of '{0}' is not available.", path.basename(resource.resourceUri.fsPath)));
			return;
D
Duroktar 已提交
427
		}
J
Joao Moreno 已提交
428 429

		return await commands.executeCommand<void>('vscode.open', HEAD);
D
Duroktar 已提交
430 431
	}

J
Joao Moreno 已提交
432 433
	@command('git.openChange')
	async openChange(arg?: Resource | Uri, ...resourceStates: SourceControlResourceState[]): Promise<void> {
434
		const preserveFocus = arg instanceof Resource;
J
Joao 已提交
435
		const preserveSelection = arg instanceof Uri || !arg;
436
		let resources: Resource[] | undefined = undefined;
437

438
		if (arg instanceof Uri) {
439
			const resource = this.getSCMResource(arg);
440 441 442
			if (resource !== undefined) {
				resources = [resource];
			}
443
		} else {
444
			let resource: Resource | undefined = undefined;
J
Joao Moreno 已提交
445

446 447 448
			if (arg instanceof Resource) {
				resource = arg;
			} else {
449
				resource = this.getSCMResource();
450 451 452 453 454
			}

			if (resource) {
				resources = [...resourceStates as Resource[], resource];
			}
J
Joao Moreno 已提交
455 456
		}

457
		if (!resources) {
J
Joao Moreno 已提交
458
			return;
J
Joao Moreno 已提交
459
		}
J
Joao Moreno 已提交
460

461 462
		const preview = resources.length === 1 ? undefined : false;
		for (const resource of resources) {
J
Joao 已提交
463
			await this._openResource(resource, preview, preserveFocus, preserveSelection);
464
		}
J
Joao Moreno 已提交
465 466
	}

467 468
	@command('git.stage')
	async stage(...resourceStates: SourceControlResourceState[]): Promise<void> {
J
Joao Moreno 已提交
469
		if (resourceStates.length === 0 || !(resourceStates[0].resourceUri instanceof Uri)) {
470
			const resource = this.getSCMResource();
471 472 473 474 475 476 477 478

			if (!resource) {
				return;
			}

			resourceStates = [resource];
		}

479 480 481
		const selection = resourceStates.filter(s => s instanceof Resource) as Resource[];
		const mergeConflicts = selection.filter(s => s.resourceGroupType === ResourceGroupType.Merge);

482 483
		if (mergeConflicts.length > 0) {
			const message = mergeConflicts.length > 1
484 485 486
				? localize('confirm stage files with merge conflicts', "Are you sure you want to stage {0} files with merge conflicts?", mergeConflicts.length)
				: localize('confirm stage file with merge conflicts', "Are you sure you want to stage {0} with merge conflicts?", path.basename(mergeConflicts[0].resourceUri.fsPath));

487 488 489 490 491 492 493 494
			const yes = localize('yes', "Yes");
			const pick = await window.showWarningMessage(message, { modal: true }, yes);

			if (pick !== yes) {
				return;
			}
		}

495 496 497 498
		const workingTree = selection
			.filter(s => s.resourceGroupType === ResourceGroupType.WorkingTree);

		const scmResources = [...workingTree, ...mergeConflicts];
499

500
		if (!scmResources.length) {
J
Joao Moreno 已提交
501 502
			return;
		}
J
Joao Moreno 已提交
503

504
		const resources = scmResources.map(r => r.resourceUri);
J
Joao Moreno 已提交
505
		await this.runByRepository(resources, async (repository, resources) => repository.add(resources));
J
Joao Moreno 已提交
506 507
	}

J
Joao Moreno 已提交
508 509
	@command('git.stageAll', { repository: true })
	async stageAll(repository: Repository): Promise<void> {
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
		const resources = repository.mergeGroup.resourceStates.filter(s => s instanceof Resource) as Resource[];
		const mergeConflicts = resources.filter(s => s.resourceGroupType === ResourceGroupType.Merge);

		if (mergeConflicts.length > 0) {
			const message = mergeConflicts.length > 1
				? localize('confirm stage files with merge conflicts', "Are you sure you want to stage {0} files with merge conflicts?", mergeConflicts.length)
				: localize('confirm stage file with merge conflicts', "Are you sure you want to stage {0} with merge conflicts?", path.basename(mergeConflicts[0].resourceUri.fsPath));

			const yes = localize('yes', "Yes");
			const pick = await window.showWarningMessage(message, { modal: true }, yes);

			if (pick !== yes) {
				return;
			}
		}

J
Joao Moreno 已提交
526
		await repository.add([]);
J
Joao Moreno 已提交
527 528
	}

J
Joao Moreno 已提交
529 530
	@command('git.stageSelectedRanges', { diff: true })
	async stageSelectedRanges(diffs: LineChange[]): Promise<void> {
J
Joao Moreno 已提交
531 532 533 534 535 536 537 538 539
		const textEditor = window.activeTextEditor;

		if (!textEditor) {
			return;
		}

		const modifiedDocument = textEditor.document;
		const modifiedUri = modifiedDocument.uri;

J
Joao Moreno 已提交
540
		if (modifiedUri.scheme !== 'file') {
J
Joao Moreno 已提交
541 542 543
			return;
		}

J
Joao Moreno 已提交
544
		const originalUri = toGitUri(modifiedUri, '~');
J
Joao Moreno 已提交
545
		const originalDocument = await workspace.openTextDocument(originalUri);
546 547 548 549
		const selectedLines = toLineRanges(textEditor.selections, modifiedDocument);
		const selectedDiffs = diffs
			.map(diff => selectedLines.reduce<LineChange | null>((result, range) => result || intersectDiffWithRange(modifiedDocument, diff, range), null))
			.filter(d => !!d) as LineChange[];
J
Joao Moreno 已提交
550 551 552 553 554

		if (!selectedDiffs.length) {
			return;
		}

555 556
		const result = applyLineChanges(originalDocument, modifiedDocument, selectedDiffs);

J
Joao Moreno 已提交
557
		await this.runByRepository(modifiedUri, async (repository, resource) => await repository.stage(resource, result));
J
Joao Moreno 已提交
558
	}
J
Joao Moreno 已提交
559

J
Joao Moreno 已提交
560 561
	@command('git.revertSelectedRanges', { diff: true })
	async revertSelectedRanges(diffs: LineChange[]): Promise<void> {
J
Joao Moreno 已提交
562 563 564 565 566 567 568 569 570 571 572 573 574
		const textEditor = window.activeTextEditor;

		if (!textEditor) {
			return;
		}

		const modifiedDocument = textEditor.document;
		const modifiedUri = modifiedDocument.uri;

		if (modifiedUri.scheme !== 'file') {
			return;
		}

J
Joao Moreno 已提交
575
		const originalUri = toGitUri(modifiedUri, '~');
J
Joao Moreno 已提交
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598
		const originalDocument = await workspace.openTextDocument(originalUri);
		const selections = textEditor.selections;
		const selectedDiffs = diffs.filter(diff => {
			const modifiedRange = diff.modifiedEndLineNumber === 0
				? new Range(modifiedDocument.lineAt(diff.modifiedStartLineNumber - 1).range.end, modifiedDocument.lineAt(diff.modifiedStartLineNumber).range.start)
				: new Range(modifiedDocument.lineAt(diff.modifiedStartLineNumber - 1).range.start, modifiedDocument.lineAt(diff.modifiedEndLineNumber - 1).range.end);

			return selections.every(selection => !selection.intersection(modifiedRange));
		});

		if (selectedDiffs.length === diffs.length) {
			return;
		}

		const basename = path.basename(modifiedUri.fsPath);
		const message = localize('confirm revert', "Are you sure you want to revert the selected changes in {0}?", basename);
		const yes = localize('revert', "Revert Changes");
		const pick = await window.showWarningMessage(message, { modal: true }, yes);

		if (pick !== yes) {
			return;
		}

599
		const result = applyLineChanges(originalDocument, modifiedDocument, selectedDiffs);
J
Joao Moreno 已提交
600 601 602 603 604
		const edit = new WorkspaceEdit();
		edit.replace(modifiedUri, new Range(new Position(0, 0), modifiedDocument.lineAt(modifiedDocument.lineCount - 1).range.end), result);
		workspace.applyEdit(edit);
	}

J
Joao Moreno 已提交
605 606
	@command('git.unstage')
	async unstage(...resourceStates: SourceControlResourceState[]): Promise<void> {
J
Joao Moreno 已提交
607
		if (resourceStates.length === 0 || !(resourceStates[0].resourceUri instanceof Uri)) {
608
			const resource = this.getSCMResource();
609 610 611 612 613 614 615 616

			if (!resource) {
				return;
			}

			resourceStates = [resource];
		}

617
		const scmResources = resourceStates
J
Joao Moreno 已提交
618
			.filter(s => s instanceof Resource && s.resourceGroupType === ResourceGroupType.Index) as Resource[];
619

620
		if (!scmResources.length) {
J
Joao Moreno 已提交
621 622 623
			return;
		}

624
		const resources = scmResources.map(r => r.resourceUri);
J
Joao Moreno 已提交
625
		await this.runByRepository(resources, async (repository, resources) => repository.revert(resources));
J
Joao Moreno 已提交
626 627
	}

J
Joao Moreno 已提交
628 629
	@command('git.unstageAll', { repository: true })
	async unstageAll(repository: Repository): Promise<void> {
630
		await repository.revert([]);
J
Joao Moreno 已提交
631
	}
J
Joao Moreno 已提交
632

J
Joao Moreno 已提交
633 634
	@command('git.unstageSelectedRanges', { diff: true })
	async unstageSelectedRanges(diffs: LineChange[]): Promise<void> {
J
Joao Moreno 已提交
635 636 637 638 639 640 641 642 643
		const textEditor = window.activeTextEditor;

		if (!textEditor) {
			return;
		}

		const modifiedDocument = textEditor.document;
		const modifiedUri = modifiedDocument.uri;

644 645 646 647 648 649 650
		if (modifiedUri.scheme !== 'git') {
			return;
		}

		const { ref } = fromGitUri(modifiedUri);

		if (ref !== '') {
J
Joao Moreno 已提交
651 652 653
			return;
		}

J
Joao Moreno 已提交
654
		const originalUri = toGitUri(modifiedUri, 'HEAD');
J
Joao Moreno 已提交
655
		const originalDocument = await workspace.openTextDocument(originalUri);
656 657 658 659
		const selectedLines = toLineRanges(textEditor.selections, modifiedDocument);
		const selectedDiffs = diffs
			.map(diff => selectedLines.reduce<LineChange | null>((result, range) => result || intersectDiffWithRange(modifiedDocument, diff, range), null))
			.filter(d => !!d) as LineChange[];
J
Joao Moreno 已提交
660 661 662 663 664

		if (!selectedDiffs.length) {
			return;
		}

665 666
		const invertedDiffs = selectedDiffs.map(invertLineChange);
		const result = applyLineChanges(modifiedDocument, originalDocument, invertedDiffs);
J
Joao Moreno 已提交
667

J
Joao Moreno 已提交
668
		await this.runByRepository(modifiedUri, async (repository, resource) => await repository.stage(resource, result));
J
Joao Moreno 已提交
669 670
	}

J
Joao Moreno 已提交
671 672
	@command('git.clean')
	async clean(...resourceStates: SourceControlResourceState[]): Promise<void> {
J
Joao Moreno 已提交
673
		if (resourceStates.length === 0 || !(resourceStates[0].resourceUri instanceof Uri)) {
674
			const resource = this.getSCMResource();
675 676 677 678 679 680 681 682

			if (!resource) {
				return;
			}

			resourceStates = [resource];
		}

J
Joao Moreno 已提交
683
		const scmResources = resourceStates
J
Joao Moreno 已提交
684
			.filter(s => s instanceof Resource && s.resourceGroupType === ResourceGroupType.WorkingTree) as Resource[];
685

J
Joao Moreno 已提交
686
		if (!scmResources.length) {
J
Joao Moreno 已提交
687 688
			return;
		}
J
Joao Moreno 已提交
689

J
Joao Moreno 已提交
690
		const untrackedCount = scmResources.reduce((s, r) => s + (r.type === Status.UNTRACKED ? 1 : 0), 0);
J
Joao Moreno 已提交
691 692 693
		let message: string;
		let yes = localize('discard', "Discard Changes");

J
Joao Moreno 已提交
694
		if (scmResources.length === 1) {
J
Joao Moreno 已提交
695
			if (untrackedCount > 0) {
J
Joao Moreno 已提交
696
				message = localize('confirm delete', "Are you sure you want to DELETE {0}?", path.basename(scmResources[0].resourceUri.fsPath));
J
Joao Moreno 已提交
697 698
				yes = localize('delete file', "Delete file");
			} else {
J
Joao Moreno 已提交
699
				message = localize('confirm discard', "Are you sure you want to discard changes in {0}?", path.basename(scmResources[0].resourceUri.fsPath));
J
Joao Moreno 已提交
700 701
			}
		} else {
J
Joao Moreno 已提交
702
			message = localize('confirm discard multiple', "Are you sure you want to discard changes in {0} files?", scmResources.length);
J
Joao Moreno 已提交
703 704 705 706 707

			if (untrackedCount > 0) {
				message = `${message}\n\n${localize('warn untracked', "This will DELETE {0} untracked files!", untrackedCount)}`;
			}
		}
708

J
Joao Moreno 已提交
709
		const pick = await window.showWarningMessage(message, { modal: true }, yes);
J
Joao Moreno 已提交
710

J
Joao Moreno 已提交
711 712 713 714
		if (pick !== yes) {
			return;
		}

J
Joao Moreno 已提交
715
		const resources = scmResources.map(r => r.resourceUri);
J
Joao Moreno 已提交
716
		await this.runByRepository(resources, async (repository, resources) => repository.clean(resources));
J
Joao Moreno 已提交
717
	}
J
Joao Moreno 已提交
718

J
Joao Moreno 已提交
719 720
	@command('git.cleanAll', { repository: true })
	async cleanAll(repository: Repository): Promise<void> {
J
Joao Moreno 已提交
721
		let resources = repository.workingTreeGroup.resourceStates;
J
Joao Moreno 已提交
722 723 724 725 726

		if (resources.length === 0) {
			return;
		}

J
Joao Moreno 已提交
727 728
		const trackedResources = resources.filter(r => r.type !== Status.UNTRACKED && r.type !== Status.IGNORED);
		const untrackedResources = resources.filter(r => r.type === Status.UNTRACKED || r.type === Status.IGNORED);
J
Joao Moreno 已提交
729

J
Joao Moreno 已提交
730 731 732 733 734 735
		if (untrackedResources.length === 0) {
			const message = resources.length === 1
				? localize('confirm discard all single', "Are you sure you want to discard changes in {0}?", path.basename(resources[0].resourceUri.fsPath))
				: localize('confirm discard all', "Are you sure you want to discard ALL changes in {0} files?\nThis is IRREVERSIBLE!\nYour current working set will be FOREVER LOST.", resources.length);
			const yes = resources.length === 1
				? localize('discardAll multiple', "Discard 1 File")
J
Joao Moreno 已提交
736
				: localize('discardAll', "Discard All {0} Files", resources.length);
J
Joao Moreno 已提交
737
			const pick = await window.showWarningMessage(message, { modal: true }, yes);
J
Joao Moreno 已提交
738

J
Joao Moreno 已提交
739
			if (pick !== yes) {
J
Joao Moreno 已提交
740 741 742
				return;
			}

J
Joao 已提交
743
			await repository.clean(resources.map(r => r.resourceUri));
J
Joao Moreno 已提交
744 745 746 747 748 749 750 751
			return;
		} else if (resources.length === 1) {
			const message = localize('confirm delete', "Are you sure you want to DELETE {0}?", path.basename(resources[0].resourceUri.fsPath));
			const yes = localize('delete file', "Delete file");
			const pick = await window.showWarningMessage(message, { modal: true }, yes);

			if (pick !== yes) {
				return;
J
Joao Moreno 已提交
752 753
			}

J
Joao 已提交
754
			await repository.clean(resources.map(r => r.resourceUri));
J
Joao Moreno 已提交
755 756 757 758
		} else if (trackedResources.length === 0) {
			const message = localize('confirm delete multiple', "Are you sure you want to DELETE {0} files?", resources.length);
			const yes = localize('delete files', "Delete Files");
			const pick = await window.showWarningMessage(message, { modal: true }, yes);
J
Joao Moreno 已提交
759

J
Joao Moreno 已提交
760 761 762
			if (pick !== yes) {
				return;
			}
J
Joao Moreno 已提交
763

J
Joao 已提交
764
			await repository.clean(resources.map(r => r.resourceUri));
J
Joao Moreno 已提交
765

J
Joao Moreno 已提交
766 767 768 769
		} else { // resources.length > 1 && untrackedResources.length > 0 && trackedResources.length > 0
			const untrackedMessage = untrackedResources.length === 1
				? localize('there are untracked files single', "The following untracked file will be DELETED FROM DISK if discarded: {0}.", path.basename(untrackedResources[0].resourceUri.fsPath))
				: localize('there are untracked files', "There are {0} untracked files which will be DELETED FROM DISK if discarded.", untrackedResources.length);
J
Joao Moreno 已提交
770

J
Joao Moreno 已提交
771 772 773 774 775
			const message = localize('confirm discard all 2', "{0}\n\nThis is IRREVERSIBLE, your current working set will be FOREVER LOST.", untrackedMessage, resources.length);

			const yesTracked = trackedResources.length === 1
				? localize('yes discard tracked', "Discard 1 Tracked File", trackedResources.length)
				: localize('yes discard tracked multiple', "Discard {0} Tracked Files", trackedResources.length);
J
Joao Moreno 已提交
776

J
Joao Moreno 已提交
777
			const yesAll = localize('discardAll', "Discard All {0} Files", resources.length);
J
Joao Moreno 已提交
778 779 780 781 782 783 784 785
			const pick = await window.showWarningMessage(message, { modal: true }, yesTracked, yesAll);

			if (pick === yesTracked) {
				resources = trackedResources;
			} else if (pick !== yesAll) {
				return;
			}

J
Joao 已提交
786
			await repository.clean(resources.map(r => r.resourceUri));
J
Joao Moreno 已提交
787
		}
J
Joao Moreno 已提交
788 789
	}

J
Joao Moreno 已提交
790
	private async smartCommit(
J
Joao Moreno 已提交
791
		repository: Repository,
792
		getCommitMessage: () => Promise<string | undefined>,
J
Joao Moreno 已提交
793 794
		opts?: CommitOptions
	): Promise<boolean> {
795 796
		const config = workspace.getConfiguration('git');
		const enableSmartCommit = config.get<boolean>('enableSmartCommit') === true;
797
		const enableCommitSigning = config.get<boolean>('enableCommitSigning') === true;
J
Joao Moreno 已提交
798 799
		const noStagedChanges = repository.indexGroup.resourceStates.length === 0;
		const noUnstagedChanges = repository.workingTreeGroup.resourceStates.length === 0;
800 801

		// no changes, and the user has not configured to commit all in this case
802
		if (!noUnstagedChanges && noStagedChanges && !enableSmartCommit) {
803

J
Joao Moreno 已提交
804 805
			// prompt the user if we want to commit all or not
			const message = localize('no staged changes', "There are no staged changes to commit.\n\nWould you like to automatically stage all your changes and commit them directly?");
806 807 808 809 810
			const yes = localize('yes', "Yes");
			const always = localize('always', "Always");
			const pick = await window.showWarningMessage(message, { modal: true }, yes, always);

			if (pick === always) {
J
Joao Moreno 已提交
811 812 813
				config.update('enableSmartCommit', true, true);
			} else if (pick !== yes) {
				return false; // do not commit on cancel
814 815 816
			}
		}

J
Joao Moreno 已提交
817
		if (!opts) {
818
			opts = { all: noStagedChanges };
J
Joao Moreno 已提交
819 820
		}

821 822 823
		// enable signing of commits if configurated
		opts.signCommit = enableCommitSigning;

J
Joao Moreno 已提交
824 825
		if (
			// no changes
826
			(noStagedChanges && noUnstagedChanges)
J
Joao Moreno 已提交
827
			// or no staged changes and not `all`
828
			|| (!opts.all && noStagedChanges)
J
Joao Moreno 已提交
829
		) {
J
Joao Moreno 已提交
830 831 832 833
			window.showInformationMessage(localize('no changes', "There are no changes to commit."));
			return false;
		}

J
Joao Moreno 已提交
834
		const message = await getCommitMessage();
J
Joao Moreno 已提交
835 836 837 838 839

		if (!message) {
			return false;
		}

J
Joao Moreno 已提交
840
		await repository.commit(message, opts);
J
Joao Moreno 已提交
841 842 843 844

		return true;
	}

J
Joao Moreno 已提交
845
	private async commitWithAnyInput(repository: Repository, opts?: CommitOptions): Promise<void> {
J
Joao Moreno 已提交
846
		const message = repository.inputBox.value;
J
Joao Moreno 已提交
847
		const getCommitMessage = async () => {
J
Joao Moreno 已提交
848 849 850 851 852 853
			if (message) {
				return message;
			}

			return await window.showInputBox({
				placeHolder: localize('commit message', "Commit message"),
J
Joao Moreno 已提交
854 855
				prompt: localize('provide commit message', "Please provide a commit message"),
				ignoreFocusOut: true
J
Joao Moreno 已提交
856
			});
J
Joao Moreno 已提交
857 858
		};

J
Joao Moreno 已提交
859
		const didCommit = await this.smartCommit(repository, getCommitMessage, opts);
J
Joao Moreno 已提交
860 861

		if (message && didCommit) {
J
Joao Moreno 已提交
862
			repository.inputBox.value = await repository.getCommitTemplate();
J
Joao Moreno 已提交
863
		}
J
Joao Moreno 已提交
864 865
	}

J
Joao Moreno 已提交
866
	@command('git.commit', { repository: true })
J
Joao Moreno 已提交
867 868
	async commit(repository: Repository): Promise<void> {
		await this.commitWithAnyInput(repository);
J
Joao Moreno 已提交
869 870
	}

J
Joao Moreno 已提交
871
	@command('git.commitWithInput', { repository: true })
J
Joao Moreno 已提交
872
	async commitWithInput(repository: Repository): Promise<void> {
J
Joao Moreno 已提交
873
		if (!repository.inputBox.value) {
J
Joao Moreno 已提交
874 875 876
			return;
		}

J
Joao Moreno 已提交
877
		const didCommit = await this.smartCommit(repository, async () => repository.inputBox.value);
J
Joao Moreno 已提交
878 879

		if (didCommit) {
J
Joao Moreno 已提交
880
			repository.inputBox.value = await repository.getCommitTemplate();
J
Joao Moreno 已提交
881
		}
J
Joao Moreno 已提交
882 883
	}

J
Joao Moreno 已提交
884
	@command('git.commitStaged', { repository: true })
J
Joao Moreno 已提交
885 886
	async commitStaged(repository: Repository): Promise<void> {
		await this.commitWithAnyInput(repository, { all: false });
J
Joao Moreno 已提交
887 888
	}

J
Joao Moreno 已提交
889
	@command('git.commitStagedSigned', { repository: true })
J
Joao Moreno 已提交
890 891
	async commitStagedSigned(repository: Repository): Promise<void> {
		await this.commitWithAnyInput(repository, { all: false, signoff: true });
J
Joao Moreno 已提交
892 893
	}

J
Joao Moreno 已提交
894
	@command('git.commitStagedAmend', { repository: true })
J
Joao Moreno 已提交
895 896
	async commitStagedAmend(repository: Repository): Promise<void> {
		await this.commitWithAnyInput(repository, { all: false, amend: true });
K
Krzysztof Cieślak 已提交
897 898
	}

J
Joao Moreno 已提交
899
	@command('git.commitAll', { repository: true })
J
Joao Moreno 已提交
900 901
	async commitAll(repository: Repository): Promise<void> {
		await this.commitWithAnyInput(repository, { all: true });
J
Joao Moreno 已提交
902 903
	}

J
Joao Moreno 已提交
904
	@command('git.commitAllSigned', { repository: true })
J
Joao Moreno 已提交
905 906
	async commitAllSigned(repository: Repository): Promise<void> {
		await this.commitWithAnyInput(repository, { all: true, signoff: true });
J
Joao Moreno 已提交
907 908
	}

J
Joao Moreno 已提交
909
	@command('git.commitAllAmend', { repository: true })
J
Joao Moreno 已提交
910 911
	async commitAllAmend(repository: Repository): Promise<void> {
		await this.commitWithAnyInput(repository, { all: true, amend: true });
K
Krzysztof Cieślak 已提交
912 913
	}

J
Joao Moreno 已提交
914
	@command('git.undoCommit', { repository: true })
J
Joao Moreno 已提交
915 916
	async undoCommit(repository: Repository): Promise<void> {
		const HEAD = repository.HEAD;
J
Joao Moreno 已提交
917 918 919 920 921

		if (!HEAD || !HEAD.commit) {
			return;
		}

J
Joao Moreno 已提交
922 923
		const commit = await repository.getCommit('HEAD');
		await repository.reset('HEAD~');
J
Joao Moreno 已提交
924
		repository.inputBox.value = commit.message;
J
Joao Moreno 已提交
925 926
	}

J
Joao Moreno 已提交
927
	@command('git.checkout', { repository: true })
J
Joao Moreno 已提交
928
	async checkout(repository: Repository, treeish: string): Promise<void> {
J
Joao Moreno 已提交
929
		if (typeof treeish === 'string') {
J
Joao Moreno 已提交
930
			return await repository.checkout(treeish);
J
Joao Moreno 已提交
931 932
		}

J
Joao Moreno 已提交
933
		const config = workspace.getConfiguration('git');
J
Joao Moreno 已提交
934
		const checkoutType = config.get<string>('checkoutType') || 'all';
J
Joao Moreno 已提交
935 936 937
		const includeTags = checkoutType === 'all' || checkoutType === 'tags';
		const includeRemotes = checkoutType === 'all' || checkoutType === 'remote';

J
Joao Moreno 已提交
938 939
		const createBranch = new CreateBranchItem();

J
Joao Moreno 已提交
940
		const heads = repository.refs.filter(ref => ref.type === RefType.Head)
J
Joao Moreno 已提交
941 942
			.map(ref => new CheckoutItem(ref));

J
Joao Moreno 已提交
943
		const tags = (includeTags ? repository.refs.filter(ref => ref.type === RefType.Tag) : [])
J
Joao Moreno 已提交
944 945
			.map(ref => new CheckoutTagItem(ref));

J
Joao Moreno 已提交
946
		const remoteHeads = (includeRemotes ? repository.refs.filter(ref => ref.type === RefType.RemoteHead) : [])
J
Joao Moreno 已提交
947 948
			.map(ref => new CheckoutRemoteHeadItem(ref));

J
Joao Moreno 已提交
949
		const picks = [createBranch, ...heads, ...tags, ...remoteHeads];
950
		const placeHolder = localize('select a ref to checkout', 'Select a ref to checkout');
J
Joao Moreno 已提交
951
		const choice = await window.showQuickPick(picks, { placeHolder });
J
Joao Moreno 已提交
952 953 954 955 956

		if (!choice) {
			return;
		}

J
Joao Moreno 已提交
957
		await choice.run(repository);
J
Joao Moreno 已提交
958 959
	}

J
Joao Moreno 已提交
960
	@command('git.branch', { repository: true })
J
Joao Moreno 已提交
961
	async branch(repository: Repository): Promise<void> {
J
Joao Moreno 已提交
962
		const result = await window.showInputBox({
J
Joao Moreno 已提交
963
			placeHolder: localize('branch name', "Branch name"),
J
Joao Moreno 已提交
964 965
			prompt: localize('provide branch name', "Please provide a branch name"),
			ignoreFocusOut: true
J
Joao Moreno 已提交
966
		});
J
Joao Moreno 已提交
967

J
Joao Moreno 已提交
968 969 970
		if (!result) {
			return;
		}
J
Joao Moreno 已提交
971

J
Joao Moreno 已提交
972
		const name = result.replace(/^\.|\/\.|\.\.|~|\^|:|\/$|\.lock$|\.lock\/|\\|\*|\s|^\s*$|\.$/g, '-');
J
Joao Moreno 已提交
973
		await repository.branch(name);
J
Joao Moreno 已提交
974 975
	}

J
Joao Moreno 已提交
976
	@command('git.deleteBranch', { repository: true })
J
Joao Moreno 已提交
977
	async deleteBranch(repository: Repository, name: string, force?: boolean): Promise<void> {
978 979
		let run: (force?: boolean) => Promise<void>;
		if (typeof name === 'string') {
J
Joao Moreno 已提交
980
			run = force => repository.deleteBranch(name, force);
981
		} else {
J
Joao Moreno 已提交
982 983
			const currentHead = repository.HEAD && repository.HEAD.name;
			const heads = repository.refs.filter(ref => ref.type === RefType.Head && ref.name !== currentHead)
984
				.map(ref => new BranchDeleteItem(ref));
M
Maik Riechert 已提交
985

M
Maik Riechert 已提交
986
			const placeHolder = localize('select branch to delete', 'Select a branch to delete');
987
			const choice = await window.showQuickPick<BranchDeleteItem>(heads, { placeHolder });
M
Maik Riechert 已提交
988

M
Maik Riechert 已提交
989
			if (!choice || !choice.branchName) {
990 991
				return;
			}
M
Maik Riechert 已提交
992
			name = choice.branchName;
J
Joao Moreno 已提交
993
			run = force => choice.run(repository, force);
M
Maik Riechert 已提交
994 995
		}

996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
		try {
			await run(force);
		} catch (err) {
			if (err.gitErrorCode !== GitErrorCodes.BranchNotFullyMerged) {
				throw err;
			}

			const message = localize('confirm force delete branch', "The branch '{0}' is not fully merged. Delete anyway?", name);
			const yes = localize('delete branch', "Delete Branch");
			const pick = await window.showWarningMessage(message, yes);

			if (pick === yes) {
				await run(true);
			}
		}
M
Maik Riechert 已提交
1011 1012
	}

J
Joao Moreno 已提交
1013
	@command('git.merge', { repository: true })
J
Joao Moreno 已提交
1014
	async merge(repository: Repository): Promise<void> {
1015 1016 1017 1018
		const config = workspace.getConfiguration('git');
		const checkoutType = config.get<string>('checkoutType') || 'all';
		const includeRemotes = checkoutType === 'all' || checkoutType === 'remote';

J
Joao Moreno 已提交
1019
		const heads = repository.refs.filter(ref => ref.type === RefType.Head)
J
Joao Moreno 已提交
1020 1021
			.filter(ref => ref.name || ref.commit)
			.map(ref => new MergeItem(ref as Branch));
1022

J
Joao Moreno 已提交
1023
		const remoteHeads = (includeRemotes ? repository.refs.filter(ref => ref.type === RefType.RemoteHead) : [])
J
Joao Moreno 已提交
1024 1025
			.filter(ref => ref.name || ref.commit)
			.map(ref => new MergeItem(ref as Branch));
1026 1027

		const picks = [...heads, ...remoteHeads];
1028 1029
		const placeHolder = localize('select a branch to merge from', 'Select a branch to merge from');
		const choice = await window.showQuickPick<MergeItem>(picks, { placeHolder });
1030 1031 1032 1033 1034

		if (!choice) {
			return;
		}

J
Joao Moreno 已提交
1035
		try {
J
Joao Moreno 已提交
1036
			await choice.run(repository);
J
Joao Moreno 已提交
1037 1038 1039 1040 1041 1042 1043 1044
		} catch (err) {
			if (err.gitErrorCode !== GitErrorCodes.Conflict) {
				throw err;
			}

			const message = localize('merge conflicts', "There are merge conflicts. Resolve them before committing.");
			await window.showWarningMessage(message);
		}
1045 1046
	}

J
Joao Moreno 已提交
1047
	@command('git.createTag', { repository: true })
J
Joao Moreno 已提交
1048
	async createTag(repository: Repository): Promise<void> {
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
		const inputTagName = await window.showInputBox({
			placeHolder: localize('tag name', "Tag name"),
			prompt: localize('provide tag name', "Please provide a tag name"),
			ignoreFocusOut: true
		});

		if (!inputTagName) {
			return;
		}

		const inputMessage = await window.showInputBox({
			placeHolder: localize('tag message', "Message"),
J
Joao Moreno 已提交
1061
			prompt: localize('provide tag message', "Please provide a message to annotate the tag"),
1062 1063 1064 1065 1066
			ignoreFocusOut: true
		});

		const name = inputTagName.replace(/^\.|\/\.|\.\.|~|\^|:|\/$|\.lock$|\.lock\/|\\|\*|\s|^\s*$|\.$/g, '-');
		const message = inputMessage || name;
J
Joao Moreno 已提交
1067
		await repository.tag(name, message);
1068 1069
	}

J
Joao Moreno 已提交
1070
	@command('git.pullFrom', { repository: true })
J
Joao Moreno 已提交
1071 1072
	async pullFrom(repository: Repository): Promise<void> {
		const remotes = repository.remotes;
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096

		if (remotes.length === 0) {
			window.showWarningMessage(localize('no remotes to pull', "Your repository has no remotes configured to pull from."));
			return;
		}

		const picks = remotes.map(r => ({ label: r.name, description: r.url }));
		const placeHolder = localize('pick remote pull repo', "Pick a remote to pull the branch from");
		const pick = await window.showQuickPick(picks, { placeHolder });

		if (!pick) {
			return;
		}

		const branchName = await window.showInputBox({
			placeHolder: localize('branch name', "Branch name"),
			prompt: localize('provide branch name', "Please provide a branch name"),
			ignoreFocusOut: true
		});

		if (!branchName) {
			return;
		}

J
Joao Moreno 已提交
1097
		repository.pull(false, pick.label, branchName);
1098 1099
	}

J
Joao Moreno 已提交
1100
	@command('git.pull', { repository: true })
J
Joao Moreno 已提交
1101 1102
	async pull(repository: Repository): Promise<void> {
		const remotes = repository.remotes;
J
Joao Moreno 已提交
1103 1104 1105 1106 1107 1108

		if (remotes.length === 0) {
			window.showWarningMessage(localize('no remotes to pull', "Your repository has no remotes configured to pull from."));
			return;
		}

J
Joao Moreno 已提交
1109
		await repository.pull();
J
Joao Moreno 已提交
1110 1111
	}

J
Joao Moreno 已提交
1112
	@command('git.pullRebase', { repository: true })
J
Joao Moreno 已提交
1113 1114
	async pullRebase(repository: Repository): Promise<void> {
		const remotes = repository.remotes;
J
Joao Moreno 已提交
1115 1116 1117 1118 1119 1120

		if (remotes.length === 0) {
			window.showWarningMessage(localize('no remotes to pull', "Your repository has no remotes configured to pull from."));
			return;
		}

J
Joao Moreno 已提交
1121
		await repository.pullWithRebase();
J
Joao Moreno 已提交
1122 1123
	}

J
Joao Moreno 已提交
1124
	@command('git.push', { repository: true })
J
Joao Moreno 已提交
1125 1126
	async push(repository: Repository): Promise<void> {
		const remotes = repository.remotes;
J
Joao Moreno 已提交
1127 1128 1129 1130 1131 1132

		if (remotes.length === 0) {
			window.showWarningMessage(localize('no remotes to push', "Your repository has no remotes configured to push to."));
			return;
		}

J
Joao Moreno 已提交
1133
		await repository.push();
J
Joao Moreno 已提交
1134 1135
	}

J
Joao Moreno 已提交
1136
	@command('git.pushWithTags', { repository: true })
J
Joao Moreno 已提交
1137 1138
	async pushWithTags(repository: Repository): Promise<void> {
		const remotes = repository.remotes;
1139 1140 1141 1142 1143 1144

		if (remotes.length === 0) {
			window.showWarningMessage(localize('no remotes to push', "Your repository has no remotes configured to push to."));
			return;
		}

J
Joao Moreno 已提交
1145
		await repository.pushTags();
1146 1147 1148 1149

		window.showInformationMessage(localize('push with tags success', "Successfully pushed with tags."));
	}

J
Joao Moreno 已提交
1150
	@command('git.pushTo', { repository: true })
J
Joao Moreno 已提交
1151 1152
	async pushTo(repository: Repository): Promise<void> {
		const remotes = repository.remotes;
J
Joao Moreno 已提交
1153 1154 1155 1156 1157 1158

		if (remotes.length === 0) {
			window.showWarningMessage(localize('no remotes to push', "Your repository has no remotes configured to push to."));
			return;
		}

J
Joao Moreno 已提交
1159
		if (!repository.HEAD || !repository.HEAD.name) {
J
Joao Moreno 已提交
1160 1161 1162 1163
			window.showWarningMessage(localize('nobranch', "Please check out a branch to push to a remote."));
			return;
		}

J
Joao Moreno 已提交
1164
		const branchName = repository.HEAD.name;
J
Joao Moreno 已提交
1165 1166 1167 1168 1169 1170 1171 1172
		const picks = remotes.map(r => ({ label: r.name, description: r.url }));
		const placeHolder = localize('pick remote', "Pick a remote to publish the branch '{0}' to:", branchName);
		const pick = await window.showQuickPick(picks, { placeHolder });

		if (!pick) {
			return;
		}

J
Joao Moreno 已提交
1173
		repository.pushTo(pick.label, branchName);
J
Joao Moreno 已提交
1174 1175
	}

J
Joao Moreno 已提交
1176
	@command('git.sync', { repository: true })
J
Joao Moreno 已提交
1177 1178
	async sync(repository: Repository): Promise<void> {
		const HEAD = repository.HEAD;
J
Joao Moreno 已提交
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199

		if (!HEAD || !HEAD.upstream) {
			return;
		}

		const config = workspace.getConfiguration('git');
		const shouldPrompt = config.get<boolean>('confirmSync') === true;

		if (shouldPrompt) {
			const message = localize('sync is unpredictable', "This action will push and pull commits to and from '{0}'.", HEAD.upstream);
			const yes = localize('ok', "OK");
			const neverAgain = localize('never again', "OK, Never Show Again");
			const pick = await window.showWarningMessage(message, { modal: true }, yes, neverAgain);

			if (pick === neverAgain) {
				await config.update('confirmSync', false, true);
			} else if (pick !== yes) {
				return;
			}
		}

J
Joao Moreno 已提交
1200
		await repository.sync();
J
Joao Moreno 已提交
1201 1202
	}

J
Joao 已提交
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
	@command('git._syncAll')
	async syncAll(): Promise<void> {
		await Promise.all(this.model.repositories.map(async repository => {
			const HEAD = repository.HEAD;

			if (!HEAD || !HEAD.upstream) {
				return;
			}

			await repository.sync();
		}));
	}

J
Joao Moreno 已提交
1216
	@command('git.publish', { repository: true })
J
Joao Moreno 已提交
1217 1218
	async publish(repository: Repository): Promise<void> {
		const remotes = repository.remotes;
J
Joao Moreno 已提交
1219 1220 1221 1222 1223 1224

		if (remotes.length === 0) {
			window.showWarningMessage(localize('no remotes to publish', "Your repository has no remotes configured to publish to."));
			return;
		}

J
Joao Moreno 已提交
1225 1226
		const branchName = repository.HEAD && repository.HEAD.name || '';
		const picks = repository.remotes.map(r => r.name);
J
Joao Moreno 已提交
1227
		const placeHolder = localize('pick remote', "Pick a remote to publish the branch '{0}' to:", branchName);
J
Joao Moreno 已提交
1228 1229 1230 1231 1232 1233
		const choice = await window.showQuickPick(picks, { placeHolder });

		if (!choice) {
			return;
		}

J
Joao Moreno 已提交
1234
		await repository.pushTo(choice, branchName, true);
J
Joao Moreno 已提交
1235 1236
	}

J
Joao Moreno 已提交
1237
	@command('git.showOutput')
J
Joao Moreno 已提交
1238 1239 1240 1241
	showOutput(): void {
		this.outputChannel.show();
	}

J
Joao Moreno 已提交
1242
	@command('git.ignore', { repository: true })
J
Joao Moreno 已提交
1243
	async ignore(repository: Repository, ...resourceStates: SourceControlResourceState[]): Promise<void> {
J
Joao Moreno 已提交
1244 1245
		if (resourceStates.length === 0 || !(resourceStates[0].resourceUri instanceof Uri)) {
			const uri = window.activeTextEditor && window.activeTextEditor.document.uri;
N
NKumar2 已提交
1246

J
Joao Moreno 已提交
1247 1248 1249 1250
			if (!uri) {
				return;
			}

J
Joao Moreno 已提交
1251
			return await repository.ignore([uri]);
J
Joao Moreno 已提交
1252 1253 1254 1255 1256 1257 1258
		}

		const uris = resourceStates
			.filter(s => s instanceof Resource)
			.map(r => r.resourceUri);

		if (!uris.length) {
N
NKumar2 已提交
1259 1260 1261
			return;
		}

J
Joao Moreno 已提交
1262
		await repository.ignore(uris);
N
NKumar2 已提交
1263 1264
	}

J
Joao Moreno 已提交
1265
	@command('git.stash', { repository: true })
J
Joao Moreno 已提交
1266 1267
	async stash(repository: Repository): Promise<void> {
		if (repository.workingTreeGroup.resourceStates.length === 0) {
K
Krzysztof Cieślak 已提交
1268 1269 1270
			window.showInformationMessage(localize('no changes stash', "There are no changes to stash."));
			return;
		}
J
Joao Moreno 已提交
1271 1272 1273 1274 1275 1276 1277 1278 1279 1280

		const message = await window.showInputBox({
			prompt: localize('provide stash message', "Optionally provide a stash message"),
			placeHolder: localize('stash message', "Stash message")
		});

		if (typeof message === 'undefined') {
			return;
		}

J
Joao Moreno 已提交
1281
		await repository.createStash(message);
K
Krzysztof Cieślak 已提交
1282 1283
	}

J
Joao Moreno 已提交
1284
	@command('git.stashPop', { repository: true })
J
Joao Moreno 已提交
1285 1286
	async stashPop(repository: Repository): Promise<void> {
		const stashes = await repository.getStashes();
J
Joao Moreno 已提交
1287 1288

		if (stashes.length === 0) {
K
Krzysztof Cieślak 已提交
1289 1290 1291 1292
			window.showInformationMessage(localize('no stashes', "There are no stashes to restore."));
			return;
		}

J
Joao Moreno 已提交
1293 1294
		const picks = stashes.map(r => ({ label: `#${r.index}:  ${r.description}`, description: '', details: '', id: r.index }));
		const placeHolder = localize('pick stash to pop', "Pick a stash to pop");
K
Krzysztof Cieślak 已提交
1295 1296 1297 1298 1299
		const choice = await window.showQuickPick(picks, { placeHolder });

		if (!choice) {
			return;
		}
J
Joao Moreno 已提交
1300

J
Joao Moreno 已提交
1301
		await repository.popStash(choice.id);
K
Krzysztof Cieślak 已提交
1302 1303
	}

J
Joao Moreno 已提交
1304
	@command('git.stashPopLatest', { repository: true })
J
Joao Moreno 已提交
1305 1306
	async stashPopLatest(repository: Repository): Promise<void> {
		const stashes = await repository.getStashes();
J
Joao Moreno 已提交
1307 1308

		if (stashes.length === 0) {
K
Krzysztof Cieślak 已提交
1309 1310 1311 1312
			window.showInformationMessage(localize('no stashes', "There are no stashes to restore."));
			return;
		}

J
Joao Moreno 已提交
1313
		await repository.popStash();
J
Joao Moreno 已提交
1314
	}
K
Krzysztof Cieślak 已提交
1315

J
Joao Moreno 已提交
1316
	private createCommand(id: string, key: string, method: Function, options: CommandOptions): (...args: any[]) => any {
1317
		const result = (...args) => {
J
Joao Moreno 已提交
1318 1319
			let result: Promise<any>;

J
Joao Moreno 已提交
1320
			if (!options.repository) {
J
Joao Moreno 已提交
1321 1322
				result = Promise.resolve(method.apply(this, args));
			} else {
J
Joao Moreno 已提交
1323 1324
				// try to guess the repository based on the first argument
				const repository = this.model.getRepository(args[0]);
J
Joao Moreno 已提交
1325 1326 1327 1328 1329 1330 1331 1332 1333
				let repositoryPromise: Promise<Repository | undefined>;

				if (repository) {
					repositoryPromise = Promise.resolve(repository);
				} else if (this.model.repositories.length === 1) {
					repositoryPromise = Promise.resolve(this.model.repositories[0]);
				} else {
					repositoryPromise = this.model.pickRepository();
				}
1334

J
Joao Moreno 已提交
1335
				result = repositoryPromise.then(repository => {
J
Joao Moreno 已提交
1336
					if (!repository) {
J
Joao 已提交
1337
						return Promise.resolve();
J
Joao Moreno 已提交
1338 1339
					}

J
Joao Moreno 已提交
1340
					return Promise.resolve(method.apply(this, [repository, ...args]));
J
Joao Moreno 已提交
1341
				});
J
Joao Moreno 已提交
1342 1343
			}

K
kieferrm 已提交
1344
			/* __GDPR__
K
kieferrm 已提交
1345 1346 1347 1348
				"git.command" : {
					"command" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
				}
			*/
J
Joao Moreno 已提交
1349 1350
			this.telemetryReporter.sendTelemetryEvent('git.command', { command: id });

J
Joao Moreno 已提交
1351 1352 1353 1354
			return result.catch(async err => {
				let message: string;

				switch (err.gitErrorCode) {
1355
					case GitErrorCodes.DirtyWorkTree:
J
Joao Moreno 已提交
1356 1357
						message = localize('clean repo', "Please clean your repository working tree before checkout.");
						break;
1358 1359 1360
					case GitErrorCodes.PushRejected:
						message = localize('cant push', "Can't push refs to remote. Run 'Pull' first to integrate your changes.");
						break;
J
Joao Moreno 已提交
1361
					default:
1362 1363 1364
						const hint = (err.stderr || err.message || String(err))
							.replace(/^error: /mi, '')
							.replace(/^> husky.*$/mi, '')
J
Joao Moreno 已提交
1365
							.split(/[\r\n]/)
1366 1367 1368 1369 1370 1371
							.filter(line => !!line)
						[0];

						message = hint
							? localize('git error details', "Git: {0}", hint)
							: localize('git error', "Git error");
J
Joao Moreno 已提交
1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389

						break;
				}

				if (!message) {
					console.error(err);
					return;
				}

				const outputChannel = this.outputChannel as OutputChannel;
				const openOutputChannelChoice = localize('open git log', "Open Git Log");
				const choice = await window.showErrorMessage(message, openOutputChannelChoice);

				if (choice === openOutputChannelChoice) {
					outputChannel.show();
				}
			});
		};
1390 1391 1392 1393 1394

		// patch this object, so people can call methods directly
		this[key] = result;

		return result;
J
Joao Moreno 已提交
1395 1396
	}

1397
	private getSCMResource(uri?: Uri): Resource | undefined {
1398
		uri = uri ? uri : window.activeTextEditor && window.activeTextEditor.document.uri;
J
Joao Moreno 已提交
1399 1400

		if (!uri) {
1401
			return undefined;
J
Joao Moreno 已提交
1402 1403 1404
		}

		if (uri.scheme === 'git') {
J
Joao Moreno 已提交
1405 1406
			const { path } = fromGitUri(uri);
			uri = Uri.file(path);
J
Joao Moreno 已提交
1407 1408 1409 1410
		}

		if (uri.scheme === 'file') {
			const uriString = uri.toString();
J
Joao Moreno 已提交
1411
			const repository = this.model.getRepository(uri);
1412

J
Joao Moreno 已提交
1413
			if (!repository) {
1414 1415
				return undefined;
			}
J
Joao Moreno 已提交
1416

J
Joao Moreno 已提交
1417 1418
			return repository.workingTreeGroup.resourceStates.filter(r => r.resourceUri.toString() === uriString)[0]
				|| repository.indexGroup.resourceStates.filter(r => r.resourceUri.toString() === uriString)[0];
J
Joao Moreno 已提交
1419 1420 1421
		}
	}

J
Joao Moreno 已提交
1422
	private runByRepository<T>(resource: Uri, fn: (repository: Repository, resource: Uri) => Promise<T>): Promise<T[]>;
J
Joao Moreno 已提交
1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452
	private runByRepository<T>(resources: Uri[], fn: (repository: Repository, resources: Uri[]) => Promise<T>): Promise<T[]>;
	private async runByRepository<T>(arg: Uri | Uri[], fn: (repository: Repository, resources: any) => Promise<T>): Promise<T[]> {
		const resources = arg instanceof Uri ? [arg] : arg;
		const isSingleResource = arg instanceof Uri;

		const groups = resources.reduce((result, resource) => {
			const repository = this.model.getRepository(resource);

			if (!repository) {
				console.warn('Could not find git repository for ', resource);
				return result;
			}

			const tuple = result.filter(p => p[0] === repository)[0];

			if (tuple) {
				tuple.resources.push(resource);
			} else {
				result.push({ repository, resources: [resource] });
			}

			return result;
		}, [] as { repository: Repository, resources: Uri[] }[]);

		const promises = groups
			.map(({ repository, resources }) => fn(repository as Repository, isSingleResource ? resources[0] : resources));

		return Promise.all(promises);
	}

J
Joao Moreno 已提交
1453 1454 1455
	dispose(): void {
		this.disposables.forEach(d => d.dispose());
	}
J
Joao Moreno 已提交
1456
}