commands.ts 41.4 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';

8
import { Uri, commands, scm, Disposable, window, workspace, QuickPickItem, OutputChannel, Range, WorkspaceEdit, Position, LineChange, SourceControlResourceGroup, SourceControlResourceState, TextDocumentShowOptions, ViewColumn } 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
	@command('git.refresh', { repository: true })
J
Joao Moreno 已提交
149 150
	async refresh(repository: Repository): Promise<void> {
		await repository.status();
J
Joao Moreno 已提交
151
	}
J
Joao Moreno 已提交
152

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

J
Joao Moreno 已提交
158
	private async _openResource(resource: Resource, preview?: 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 = {
170 171
			preserveFocus: true,
			preview: preview,
J
Joao Moreno 已提交
172
			viewColumn: window.activeTextEditor && window.activeTextEditor.viewColumn || ViewColumn.One
J
Joao Moreno 已提交
173 174
		};

J
Joao Moreno 已提交
175 176 177 178 179 180
		const activeTextEditor = window.activeTextEditor;

		if (activeTextEditor && activeTextEditor.document.uri.toString() === right.toString()) {
			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) {
267 268
			this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'no_URL' });
			return;
J
Joao Moreno 已提交
269 270
		}

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

J
Joao Moreno 已提交
274 275
		const parentPath = await window.showInputBox({
			prompt: localize('parent', "Parent Directory"),
J
Joao Moreno 已提交
276
			value,
J
Joao Moreno 已提交
277
			ignoreFocusOut: true
J
Joao Moreno 已提交
278 279 280
		});

		if (!parentPath) {
281 282
			this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'no_directory' });
			return;
J
Joao Moreno 已提交
283 284
		}

J
Joao Moreno 已提交
285
		const clonePromise = this.git.clone(url, parentPath);
J
Joao Moreno 已提交
286 287
		window.setStatusBarMessage(localize('cloning', "Cloning git repository..."), clonePromise);

288
		try {
289 290 291 292 293 294 295 296 297 298
			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;
			this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'success' }, { openFolder: openFolder ? 1 : 0 });
			if (openFolder) {
				commands.executeCommand('vscode.openFolder', Uri.file(repositoryPath));
			}
299 300
		} catch (err) {
			if (/already exists and is not an empty directory/.test(err && err.stderr || '')) {
301 302 303
				this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'directory_not_empty' });
			} else {
				this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'error' });
304 305
			}
			throw err;
J
Joao Moreno 已提交
306 307 308
		}
	}

J
Joao Moreno 已提交
309
	@command('git.init')
J
Joao Moreno 已提交
310
	async init(): Promise<void> {
J
Joao Moreno 已提交
311 312
		// TODO@joao
		// await model.init();
J
Joao Moreno 已提交
313 314
	}

J
Joao Moreno 已提交
315 316
	@command('git.openFile')
	async openFile(arg?: Resource | Uri, ...resourceStates: SourceControlResourceState[]): Promise<void> {
317
		let uris: Uri[] | undefined;
318 319 320

		if (arg instanceof Uri) {
			if (arg.scheme === 'git') {
321
				uris = [Uri.file(fromGitUri(arg).path)];
322
			} else if (arg.scheme === 'file') {
323
				uris = [arg];
324 325 326 327 328 329
			}
		} else {
			let resource = arg;

			if (!(resource instanceof Resource)) {
				// can happen when called from a keybinding
330
				resource = this.getSCMResource();
331 332 333
			}

			if (resource) {
334
				uris = [...resourceStates.map(r => r.resourceUri), resource.resourceUri];
335
			}
J
Joao Moreno 已提交
336 337
		}

338
		if (!uris) {
J
Joao Moreno 已提交
339
			return;
J
Joao Moreno 已提交
340 341
		}

342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
		const preview = uris.length === 1 ? true : false;
		const activeTextEditor = window.activeTextEditor;
		for (const uri of uris) {
			// If the active editor matches the current uri, get its selection
			const selections = activeTextEditor && activeTextEditor.document.uri.toString() === uri.toString()
				? activeTextEditor.selections
				: undefined;

			const opts: TextDocumentShowOptions = {
				preserveFocus: true,
				preview: preview,
				viewColumn: activeTextEditor && activeTextEditor.viewColumn || ViewColumn.One
			};

			const document = await workspace.openTextDocument(uri);
			await window.showTextDocument(document, opts);

			if (selections && window.activeTextEditor) {
				window.activeTextEditor.selections = selections;
			}
J
Joao Moreno 已提交
362
		}
J
Joao Moreno 已提交
363 364
	}

J
Joao Moreno 已提交
365 366
	@command('git.openHEADFile')
	async openHEADFile(arg?: Resource | Uri): Promise<void> {
D
Duroktar 已提交
367 368 369 370 371
		let resource: Resource | undefined = undefined;

		if (arg instanceof Resource) {
			resource = arg;
		} else if (arg instanceof Uri) {
372
			resource = this.getSCMResource(arg);
D
Duroktar 已提交
373
		} else {
374
			resource = this.getSCMResource();
D
Duroktar 已提交
375 376 377 378 379 380
		}

		if (!resource) {
			return;
		}

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

J
Joao Moreno 已提交
383 384 385
		if (!HEAD) {
			window.showWarningMessage(localize('HEAD not available', "HEAD version of '{0}' is not available.", path.basename(resource.resourceUri.fsPath)));
			return;
D
Duroktar 已提交
386
		}
J
Joao Moreno 已提交
387 388

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

J
Joao Moreno 已提交
391 392
	@command('git.openChange')
	async openChange(arg?: Resource | Uri, ...resourceStates: SourceControlResourceState[]): Promise<void> {
393
		let resources: Resource[] | undefined = undefined;
394

395
		if (arg instanceof Uri) {
396
			const resource = this.getSCMResource(arg);
397 398 399
			if (resource !== undefined) {
				resources = [resource];
			}
400
		} else {
401
			let resource: Resource | undefined = undefined;
J
Joao Moreno 已提交
402

403 404 405
			if (arg instanceof Resource) {
				resource = arg;
			} else {
406
				resource = this.getSCMResource();
407 408 409 410 411
			}

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

414
		if (!resources) {
J
Joao Moreno 已提交
415
			return;
J
Joao Moreno 已提交
416
		}
J
Joao Moreno 已提交
417

418 419
		const preview = resources.length === 1 ? undefined : false;
		for (const resource of resources) {
J
Joao Moreno 已提交
420
			await this._openResource(resource, preview);
421
		}
J
Joao Moreno 已提交
422 423
	}

424 425
	@command('git.stage')
	async stage(...resourceStates: SourceControlResourceState[]): Promise<void> {
J
Joao Moreno 已提交
426
		if (resourceStates.length === 0 || !(resourceStates[0].resourceUri instanceof Uri)) {
427
			const resource = this.getSCMResource();
428 429 430 431 432 433 434 435

			if (!resource) {
				return;
			}

			resourceStates = [resource];
		}

436
		const scmResources = resourceStates
J
Joao Moreno 已提交
437
			.filter(s => s instanceof Resource && (s.resourceGroupType === ResourceGroupType.WorkingTree || s.resourceGroupType === ResourceGroupType.Merge)) as Resource[];
438

439
		if (!scmResources.length) {
J
Joao Moreno 已提交
440 441
			return;
		}
J
Joao Moreno 已提交
442

443
		const resources = scmResources.map(r => r.resourceUri);
J
Joao Moreno 已提交
444
		await this.runByRepository(resources, async (repository, resources) => repository.add(resources));
J
Joao Moreno 已提交
445 446
	}

447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
	@command('git.stageAll')
	async stageAll(group?: SourceControlResourceGroup): Promise<void> {
		let repository: Repository | undefined = undefined;

		if (group) {
			repository = this.model.getRepositoryFromResourceGroup(group);
		}

		if (!repository) {
			repository = await this.model.pickRepository();
		}

		if (!repository) {
			return;
		}

J
Joao Moreno 已提交
463
		await repository.add([]);
J
Joao Moreno 已提交
464 465
	}

466
	// TODO@Joao does this command really receive a model?
J
Joao Moreno 已提交
467
	@command('git.stageSelectedRanges', { repository: true, diff: true })
J
Joao Moreno 已提交
468
	async stageSelectedRanges(repository: Repository, diffs: LineChange[]): Promise<void> {
J
Joao Moreno 已提交
469 470 471 472 473 474 475 476 477
		const textEditor = window.activeTextEditor;

		if (!textEditor) {
			return;
		}

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

J
Joao Moreno 已提交
478
		if (modifiedUri.scheme !== 'file') {
J
Joao Moreno 已提交
479 480 481
			return;
		}

J
Joao Moreno 已提交
482
		const originalUri = toGitUri(modifiedUri, '~');
J
Joao Moreno 已提交
483
		const originalDocument = await workspace.openTextDocument(originalUri);
484 485 486 487
		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 已提交
488 489 490 491 492

		if (!selectedDiffs.length) {
			return;
		}

493 494
		const result = applyLineChanges(originalDocument, modifiedDocument, selectedDiffs);

J
Joao Moreno 已提交
495
		await repository.stage(modifiedUri, result);
J
Joao Moreno 已提交
496
	}
J
Joao Moreno 已提交
497

498
	// TODO@Joao does this command really receive a model?
J
Joao Moreno 已提交
499
	@command('git.revertSelectedRanges', { repository: true, diff: true })
J
Joao Moreno 已提交
500
	async revertSelectedRanges(repository: Repository, diffs: LineChange[]): Promise<void> {
J
Joao Moreno 已提交
501 502 503 504 505 506 507 508 509 510 511 512 513
		const textEditor = window.activeTextEditor;

		if (!textEditor) {
			return;
		}

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

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

J
Joao Moreno 已提交
514
		const originalUri = toGitUri(modifiedUri, '~');
J
Joao Moreno 已提交
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
		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;
		}

538
		const result = applyLineChanges(originalDocument, modifiedDocument, selectedDiffs);
J
Joao Moreno 已提交
539 540 541 542 543
		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 已提交
544 545
	@command('git.unstage')
	async unstage(...resourceStates: SourceControlResourceState[]): Promise<void> {
J
Joao Moreno 已提交
546
		if (resourceStates.length === 0 || !(resourceStates[0].resourceUri instanceof Uri)) {
547
			const resource = this.getSCMResource();
548 549 550 551 552 553 554 555

			if (!resource) {
				return;
			}

			resourceStates = [resource];
		}

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

559
		if (!scmResources.length) {
J
Joao Moreno 已提交
560 561 562
			return;
		}

563
		const resources = scmResources.map(r => r.resourceUri);
J
Joao Moreno 已提交
564
		await this.runByRepository(resources, async (repository, resources) => repository.revert(resources));
J
Joao Moreno 已提交
565 566
	}

567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
	@command('git.unstageAll')
	async unstageAll(group?: SourceControlResourceGroup): Promise<void> {
		let repository: Repository | undefined = undefined;

		if (group) {
			repository = this.model.getRepositoryFromResourceGroup(group);
		}

		if (!repository) {
			repository = await this.model.pickRepository();
		}

		if (!repository) {
			return;
		}

		await repository.revert([]);
J
Joao Moreno 已提交
584
	}
J
Joao Moreno 已提交
585

586
	// TODO@Joao does this command really receive a model?
J
Joao Moreno 已提交
587
	@command('git.unstageSelectedRanges', { repository: true, diff: true })
J
Joao Moreno 已提交
588
	async unstageSelectedRanges(repository: Repository, diffs: LineChange[]): Promise<void> {
J
Joao Moreno 已提交
589 590 591 592 593 594 595 596 597
		const textEditor = window.activeTextEditor;

		if (!textEditor) {
			return;
		}

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

598 599 600 601 602 603 604
		if (modifiedUri.scheme !== 'git') {
			return;
		}

		const { ref } = fromGitUri(modifiedUri);

		if (ref !== '') {
J
Joao Moreno 已提交
605 606 607
			return;
		}

J
Joao Moreno 已提交
608
		const originalUri = toGitUri(modifiedUri, 'HEAD');
J
Joao Moreno 已提交
609
		const originalDocument = await workspace.openTextDocument(originalUri);
610 611 612 613
		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 已提交
614 615 616 617 618

		if (!selectedDiffs.length) {
			return;
		}

619 620
		const invertedDiffs = selectedDiffs.map(invertLineChange);
		const result = applyLineChanges(modifiedDocument, originalDocument, invertedDiffs);
J
Joao Moreno 已提交
621

J
Joao Moreno 已提交
622
		await repository.stage(modifiedUri, result);
J
Joao Moreno 已提交
623 624
	}

J
Joao Moreno 已提交
625 626
	@command('git.clean')
	async clean(...resourceStates: SourceControlResourceState[]): Promise<void> {
J
Joao Moreno 已提交
627
		if (resourceStates.length === 0 || !(resourceStates[0].resourceUri instanceof Uri)) {
628
			const resource = this.getSCMResource();
629 630 631 632 633 634 635 636

			if (!resource) {
				return;
			}

			resourceStates = [resource];
		}

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

J
Joao Moreno 已提交
640
		if (!scmResources.length) {
J
Joao Moreno 已提交
641 642
			return;
		}
J
Joao Moreno 已提交
643

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

J
Joao Moreno 已提交
648
		if (scmResources.length === 1) {
J
Joao Moreno 已提交
649
			if (untrackedCount > 0) {
J
Joao Moreno 已提交
650
				message = localize('confirm delete', "Are you sure you want to DELETE {0}?", path.basename(scmResources[0].resourceUri.fsPath));
J
Joao Moreno 已提交
651 652
				yes = localize('delete file', "Delete file");
			} else {
J
Joao Moreno 已提交
653
				message = localize('confirm discard', "Are you sure you want to discard changes in {0}?", path.basename(scmResources[0].resourceUri.fsPath));
J
Joao Moreno 已提交
654 655
			}
		} else {
J
Joao Moreno 已提交
656
			message = localize('confirm discard multiple', "Are you sure you want to discard changes in {0} files?", scmResources.length);
J
Joao Moreno 已提交
657 658 659 660 661

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

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

J
Joao Moreno 已提交
665 666 667 668
		if (pick !== yes) {
			return;
		}

J
Joao Moreno 已提交
669
		const resources = scmResources.map(r => r.resourceUri);
J
Joao Moreno 已提交
670
		await this.runByRepository(resources, async (repository, resources) => repository.clean(resources));
J
Joao Moreno 已提交
671
	}
J
Joao Moreno 已提交
672

673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688
	@command('git.cleanAll')
	async cleanAll(group?: SourceControlResourceGroup): Promise<void> {
		let repository: Repository | undefined = undefined;

		if (group) {
			repository = this.model.getRepositoryFromResourceGroup(group);
		}

		if (!repository) {
			repository = await this.model.pickRepository();
		}

		if (!repository) {
			return;
		}

J
Joao Moreno 已提交
689 690
		const config = workspace.getConfiguration('git');
		let scope = config.get<string>('discardAllScope') || 'prompt';
J
Joao Moreno 已提交
691
		let resources = repository.workingTreeGroup.resourceStates;
J
Joao Moreno 已提交
692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728

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

		const untrackedCount = resources.reduce((s, r) => s + (r.type === Status.UNTRACKED ? 1 : 0), 0);

		if (scope === 'prompt' && untrackedCount > 0) {
			const message = localize('there are untracked files', "There are untracked files ({0}) which will be DELETED if discarded.\n\nWould you like to delete untracked files when discarding all changes?", untrackedCount);
			const yes = localize('yes', "Yes");
			const always = localize('always', "Always");
			const no = localize('no', "No");
			const never = localize('never', "Never");
			const pick = await window.showWarningMessage(message, { modal: true }, yes, always, no, never);

			if (typeof pick === 'undefined') {
				return;
			} else if (pick === always) {
				await config.update('discardAllScope', 'all', true);
			} else if (pick === never) {
				await config.update('discardAllScope', 'tracked', true);
			}

			if (pick === never || pick === no) {
				scope = 'tracked';
			}
		}

		if (scope === 'tracked') {
			resources = resources.filter(r => r.type !== Status.UNTRACKED && r.type !== Status.IGNORED);
		}

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

		const message = localize('confirm discard all', "Are you sure you want to discard ALL ({0}) changes?\nThis is IRREVERSIBLE!\nYour current working set will be FOREVER LOST.", resources.length);
729
		const yes = localize('discardAll', "Discard ALL Changes");
J
Joao Moreno 已提交
730
		const pick = await window.showWarningMessage(message, { modal: true }, yes);
J
Joao Moreno 已提交
731 732 733 734 735

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

J
Joao Moreno 已提交
736
		await repository.clean(resources.map(r => r.resourceUri));
J
Joao Moreno 已提交
737 738
	}

J
Joao Moreno 已提交
739
	private async smartCommit(
J
Joao Moreno 已提交
740
		repository: Repository,
741
		getCommitMessage: () => Promise<string | undefined>,
J
Joao Moreno 已提交
742 743
		opts?: CommitOptions
	): Promise<boolean> {
744 745
		const config = workspace.getConfiguration('git');
		const enableSmartCommit = config.get<boolean>('enableSmartCommit') === true;
746
		const enableCommitSigning = config.get<boolean>('enableCommitSigning') === true;
J
Joao Moreno 已提交
747 748
		const noStagedChanges = repository.indexGroup.resourceStates.length === 0;
		const noUnstagedChanges = repository.workingTreeGroup.resourceStates.length === 0;
749 750

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

J
Joao Moreno 已提交
753 754
			// 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?");
755 756 757 758 759
			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 已提交
760 761 762
				config.update('enableSmartCommit', true, true);
			} else if (pick !== yes) {
				return false; // do not commit on cancel
763 764 765
			}
		}

J
Joao Moreno 已提交
766
		if (!opts) {
767
			opts = { all: noStagedChanges };
J
Joao Moreno 已提交
768 769
		}

770 771 772
		// enable signing of commits if configurated
		opts.signCommit = enableCommitSigning;

J
Joao Moreno 已提交
773 774
		if (
			// no changes
775
			(noStagedChanges && noUnstagedChanges)
J
Joao Moreno 已提交
776
			// or no staged changes and not `all`
777
			|| (!opts.all && noStagedChanges)
J
Joao Moreno 已提交
778
		) {
J
Joao Moreno 已提交
779 780 781 782
			window.showInformationMessage(localize('no changes', "There are no changes to commit."));
			return false;
		}

J
Joao Moreno 已提交
783
		const message = await getCommitMessage();
J
Joao Moreno 已提交
784 785 786 787 788 789

		if (!message) {
			// TODO@joao: show modal dialog to confirm empty message commit
			return false;
		}

J
Joao Moreno 已提交
790
		await repository.commit(message, opts);
J
Joao Moreno 已提交
791 792 793 794

		return true;
	}

J
Joao Moreno 已提交
795
	private async commitWithAnyInput(repository: Repository, opts?: CommitOptions): Promise<void> {
796
		const message = scm.inputBox.value;
J
Joao Moreno 已提交
797
		const getCommitMessage = async () => {
J
Joao Moreno 已提交
798 799 800 801 802 803
			if (message) {
				return message;
			}

			return await window.showInputBox({
				placeHolder: localize('commit message', "Commit message"),
J
Joao Moreno 已提交
804 805
				prompt: localize('provide commit message', "Please provide a commit message"),
				ignoreFocusOut: true
J
Joao Moreno 已提交
806
			});
J
Joao Moreno 已提交
807 808
		};

J
Joao Moreno 已提交
809
		const didCommit = await this.smartCommit(repository, getCommitMessage, opts);
J
Joao Moreno 已提交
810 811

		if (message && didCommit) {
J
Joao Moreno 已提交
812
			scm.inputBox.value = await repository.getCommitTemplate();
J
Joao Moreno 已提交
813
		}
J
Joao Moreno 已提交
814 815
	}

J
Joao Moreno 已提交
816
	@command('git.commit', { repository: true })
J
Joao Moreno 已提交
817 818
	async commit(repository: Repository): Promise<void> {
		await this.commitWithAnyInput(repository);
J
Joao Moreno 已提交
819 820
	}

J
Joao Moreno 已提交
821
	@command('git.commitWithInput', { repository: true })
J
Joao Moreno 已提交
822
	async commitWithInput(repository: Repository): Promise<void> {
J
Joao Moreno 已提交
823 824 825 826
		if (!scm.inputBox.value) {
			return;
		}

J
Joao Moreno 已提交
827
		const didCommit = await this.smartCommit(repository, async () => scm.inputBox.value);
J
Joao Moreno 已提交
828 829

		if (didCommit) {
J
Joao Moreno 已提交
830
			scm.inputBox.value = await repository.getCommitTemplate();
J
Joao Moreno 已提交
831
		}
J
Joao Moreno 已提交
832 833
	}

J
Joao Moreno 已提交
834
	@command('git.commitStaged', { repository: true })
J
Joao Moreno 已提交
835 836
	async commitStaged(repository: Repository): Promise<void> {
		await this.commitWithAnyInput(repository, { all: false });
J
Joao Moreno 已提交
837 838
	}

J
Joao Moreno 已提交
839
	@command('git.commitStagedSigned', { repository: true })
J
Joao Moreno 已提交
840 841
	async commitStagedSigned(repository: Repository): Promise<void> {
		await this.commitWithAnyInput(repository, { all: false, signoff: true });
J
Joao Moreno 已提交
842 843
	}

J
Joao Moreno 已提交
844
	@command('git.commitStagedAmend', { repository: true })
J
Joao Moreno 已提交
845 846
	async commitStagedAmend(repository: Repository): Promise<void> {
		await this.commitWithAnyInput(repository, { all: false, amend: true });
K
Krzysztof Cieślak 已提交
847 848
	}

J
Joao Moreno 已提交
849
	@command('git.commitAll', { repository: true })
J
Joao Moreno 已提交
850 851
	async commitAll(repository: Repository): Promise<void> {
		await this.commitWithAnyInput(repository, { all: true });
J
Joao Moreno 已提交
852 853
	}

J
Joao Moreno 已提交
854
	@command('git.commitAllSigned', { repository: true })
J
Joao Moreno 已提交
855 856
	async commitAllSigned(repository: Repository): Promise<void> {
		await this.commitWithAnyInput(repository, { all: true, signoff: true });
J
Joao Moreno 已提交
857 858
	}

J
Joao Moreno 已提交
859
	@command('git.commitAllAmend', { repository: true })
J
Joao Moreno 已提交
860 861
	async commitAllAmend(repository: Repository): Promise<void> {
		await this.commitWithAnyInput(repository, { all: true, amend: true });
K
Krzysztof Cieślak 已提交
862 863
	}

J
Joao Moreno 已提交
864
	@command('git.undoCommit', { repository: true })
J
Joao Moreno 已提交
865 866
	async undoCommit(repository: Repository): Promise<void> {
		const HEAD = repository.HEAD;
J
Joao Moreno 已提交
867 868 869 870 871

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

J
Joao Moreno 已提交
872 873
		const commit = await repository.getCommit('HEAD');
		await repository.reset('HEAD~');
J
Joao Moreno 已提交
874
		scm.inputBox.value = commit.message;
J
Joao Moreno 已提交
875 876
	}

J
Joao Moreno 已提交
877
	@command('git.checkout', { repository: true })
J
Joao Moreno 已提交
878
	async checkout(repository: Repository, treeish: string): Promise<void> {
J
Joao Moreno 已提交
879
		if (typeof treeish === 'string') {
J
Joao Moreno 已提交
880
			return await repository.checkout(treeish);
J
Joao Moreno 已提交
881 882
		}

J
Joao Moreno 已提交
883
		const config = workspace.getConfiguration('git');
J
Joao Moreno 已提交
884
		const checkoutType = config.get<string>('checkoutType') || 'all';
J
Joao Moreno 已提交
885 886 887
		const includeTags = checkoutType === 'all' || checkoutType === 'tags';
		const includeRemotes = checkoutType === 'all' || checkoutType === 'remote';

J
Joao Moreno 已提交
888 889
		const createBranch = new CreateBranchItem();

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

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

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

J
Joao Moreno 已提交
899
		const picks = [createBranch, ...heads, ...tags, ...remoteHeads];
900
		const placeHolder = localize('select a ref to checkout', 'Select a ref to checkout');
J
Joao Moreno 已提交
901
		const choice = await window.showQuickPick(picks, { placeHolder });
J
Joao Moreno 已提交
902 903 904 905 906

		if (!choice) {
			return;
		}

J
Joao Moreno 已提交
907
		await choice.run(repository);
J
Joao Moreno 已提交
908 909
	}

J
Joao Moreno 已提交
910
	@command('git.branch', { repository: true })
J
Joao Moreno 已提交
911
	async branch(repository: Repository): Promise<void> {
J
Joao Moreno 已提交
912
		const result = await window.showInputBox({
J
Joao Moreno 已提交
913
			placeHolder: localize('branch name', "Branch name"),
J
Joao Moreno 已提交
914 915
			prompt: localize('provide branch name', "Please provide a branch name"),
			ignoreFocusOut: true
J
Joao Moreno 已提交
916
		});
J
Joao Moreno 已提交
917

J
Joao Moreno 已提交
918 919 920
		if (!result) {
			return;
		}
J
Joao Moreno 已提交
921

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

J
Joao Moreno 已提交
926
	@command('git.deleteBranch', { repository: true })
J
Joao Moreno 已提交
927
	async deleteBranch(repository: Repository, name: string, force?: boolean): Promise<void> {
928 929
		let run: (force?: boolean) => Promise<void>;
		if (typeof name === 'string') {
J
Joao Moreno 已提交
930
			run = force => repository.deleteBranch(name, force);
931
		} else {
J
Joao Moreno 已提交
932 933
			const currentHead = repository.HEAD && repository.HEAD.name;
			const heads = repository.refs.filter(ref => ref.type === RefType.Head && ref.name !== currentHead)
934
				.map(ref => new BranchDeleteItem(ref));
M
Maik Riechert 已提交
935

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

M
Maik Riechert 已提交
939
			if (!choice || !choice.branchName) {
940 941
				return;
			}
M
Maik Riechert 已提交
942
			name = choice.branchName;
J
Joao Moreno 已提交
943
			run = force => choice.run(repository, force);
M
Maik Riechert 已提交
944 945
		}

946 947 948 949 950 951 952 953 954 955 956 957 958 959 960
		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 已提交
961 962
	}

J
Joao Moreno 已提交
963
	@command('git.merge', { repository: true })
J
Joao Moreno 已提交
964
	async merge(repository: Repository): Promise<void> {
965 966 967 968
		const config = workspace.getConfiguration('git');
		const checkoutType = config.get<string>('checkoutType') || 'all';
		const includeRemotes = checkoutType === 'all' || checkoutType === 'remote';

J
Joao Moreno 已提交
969
		const heads = repository.refs.filter(ref => ref.type === RefType.Head)
J
Joao Moreno 已提交
970 971
			.filter(ref => ref.name || ref.commit)
			.map(ref => new MergeItem(ref as Branch));
972

J
Joao Moreno 已提交
973
		const remoteHeads = (includeRemotes ? repository.refs.filter(ref => ref.type === RefType.RemoteHead) : [])
J
Joao Moreno 已提交
974 975
			.filter(ref => ref.name || ref.commit)
			.map(ref => new MergeItem(ref as Branch));
976 977

		const picks = [...heads, ...remoteHeads];
978 979
		const placeHolder = localize('select a branch to merge from', 'Select a branch to merge from');
		const choice = await window.showQuickPick<MergeItem>(picks, { placeHolder });
980 981 982 983 984

		if (!choice) {
			return;
		}

J
Joao Moreno 已提交
985
		try {
J
Joao Moreno 已提交
986
			await choice.run(repository);
J
Joao Moreno 已提交
987 988 989 990 991 992 993 994
		} 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);
		}
995 996
	}

J
Joao Moreno 已提交
997
	@command('git.createTag', { repository: true })
J
Joao Moreno 已提交
998
	async createTag(repository: Repository): Promise<void> {
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
		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 已提交
1011
			prompt: localize('provide tag message', "Please provide a message to annotate the tag"),
1012 1013 1014 1015 1016
			ignoreFocusOut: true
		});

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

J
Joao Moreno 已提交
1020
	@command('git.pullFrom', { repository: true })
J
Joao Moreno 已提交
1021 1022
	async pullFrom(repository: Repository): Promise<void> {
		const remotes = repository.remotes;
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046

		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 已提交
1047
		repository.pull(false, pick.label, branchName);
1048 1049
	}

J
Joao Moreno 已提交
1050
	@command('git.pull', { repository: true })
J
Joao Moreno 已提交
1051 1052
	async pull(repository: Repository): Promise<void> {
		const remotes = repository.remotes;
J
Joao Moreno 已提交
1053 1054 1055 1056 1057 1058

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

J
Joao Moreno 已提交
1059
		await repository.pull();
J
Joao Moreno 已提交
1060 1061
	}

J
Joao Moreno 已提交
1062
	@command('git.pullRebase', { repository: true })
J
Joao Moreno 已提交
1063 1064
	async pullRebase(repository: Repository): Promise<void> {
		const remotes = repository.remotes;
J
Joao Moreno 已提交
1065 1066 1067 1068 1069 1070

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

J
Joao Moreno 已提交
1071
		await repository.pullWithRebase();
J
Joao Moreno 已提交
1072 1073
	}

J
Joao Moreno 已提交
1074
	@command('git.push', { repository: true })
J
Joao Moreno 已提交
1075 1076
	async push(repository: Repository): Promise<void> {
		const remotes = repository.remotes;
J
Joao Moreno 已提交
1077 1078 1079 1080 1081 1082

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

J
Joao Moreno 已提交
1083
		await repository.push();
J
Joao Moreno 已提交
1084 1085
	}

J
Joao Moreno 已提交
1086
	@command('git.pushWithTags', { repository: true })
J
Joao Moreno 已提交
1087 1088
	async pushWithTags(repository: Repository): Promise<void> {
		const remotes = repository.remotes;
1089 1090 1091 1092 1093 1094

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

J
Joao Moreno 已提交
1095
		await repository.pushTags();
1096 1097 1098 1099

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

J
Joao Moreno 已提交
1100
	@command('git.pushTo', { repository: true })
J
Joao Moreno 已提交
1101 1102
	async pushTo(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 push', "Your repository has no remotes configured to push to."));
			return;
		}

J
Joao Moreno 已提交
1109
		if (!repository.HEAD || !repository.HEAD.name) {
J
Joao Moreno 已提交
1110 1111 1112 1113
			window.showWarningMessage(localize('nobranch', "Please check out a branch to push to a remote."));
			return;
		}

J
Joao Moreno 已提交
1114
		const branchName = repository.HEAD.name;
J
Joao Moreno 已提交
1115 1116 1117 1118 1119 1120 1121 1122
		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 已提交
1123
		repository.pushTo(pick.label, branchName);
J
Joao Moreno 已提交
1124 1125
	}

J
Joao Moreno 已提交
1126
	@command('git.sync', { repository: true })
J
Joao Moreno 已提交
1127 1128
	async sync(repository: Repository): Promise<void> {
		const HEAD = repository.HEAD;
J
Joao Moreno 已提交
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149

		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 已提交
1150
		await repository.sync();
J
Joao Moreno 已提交
1151 1152
	}

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

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

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

		if (!choice) {
			return;
		}

J
Joao Moreno 已提交
1171
		await repository.pushTo(choice, branchName, true);
J
Joao Moreno 已提交
1172 1173
	}

J
Joao Moreno 已提交
1174
	@command('git.showOutput')
J
Joao Moreno 已提交
1175 1176 1177 1178
	showOutput(): void {
		this.outputChannel.show();
	}

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

J
Joao Moreno 已提交
1184 1185 1186 1187
			if (!uri) {
				return;
			}

J
Joao Moreno 已提交
1188
			return await repository.ignore([uri]);
J
Joao Moreno 已提交
1189 1190 1191 1192 1193 1194 1195
		}

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

		if (!uris.length) {
N
NKumar2 已提交
1196 1197 1198
			return;
		}

J
Joao Moreno 已提交
1199
		await repository.ignore(uris);
N
NKumar2 已提交
1200 1201
	}

J
Joao Moreno 已提交
1202
	@command('git.stash', { repository: true })
J
Joao Moreno 已提交
1203 1204
	async stash(repository: Repository): Promise<void> {
		if (repository.workingTreeGroup.resourceStates.length === 0) {
K
Krzysztof Cieślak 已提交
1205 1206 1207
			window.showInformationMessage(localize('no changes stash', "There are no changes to stash."));
			return;
		}
J
Joao Moreno 已提交
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217

		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 已提交
1218
		await repository.createStash(message);
K
Krzysztof Cieślak 已提交
1219 1220
	}

J
Joao Moreno 已提交
1221
	@command('git.stashPop', { repository: true })
J
Joao Moreno 已提交
1222 1223
	async stashPop(repository: Repository): Promise<void> {
		const stashes = await repository.getStashes();
J
Joao Moreno 已提交
1224 1225

		if (stashes.length === 0) {
K
Krzysztof Cieślak 已提交
1226 1227 1228 1229
			window.showInformationMessage(localize('no stashes', "There are no stashes to restore."));
			return;
		}

J
Joao Moreno 已提交
1230 1231
		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 已提交
1232 1233 1234 1235 1236
		const choice = await window.showQuickPick(picks, { placeHolder });

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

J
Joao Moreno 已提交
1238
		await repository.popStash(choice.id);
K
Krzysztof Cieślak 已提交
1239 1240
	}

J
Joao Moreno 已提交
1241
	@command('git.stashPopLatest', { repository: true })
J
Joao Moreno 已提交
1242 1243
	async stashPopLatest(repository: Repository): Promise<void> {
		const stashes = await repository.getStashes();
J
Joao Moreno 已提交
1244 1245

		if (stashes.length === 0) {
K
Krzysztof Cieślak 已提交
1246 1247 1248 1249
			window.showInformationMessage(localize('no stashes', "There are no stashes to restore."));
			return;
		}

J
Joao Moreno 已提交
1250
		await repository.popStash();
J
Joao Moreno 已提交
1251
	}
K
Krzysztof Cieślak 已提交
1252

J
Joao Moreno 已提交
1253
	private createCommand(id: string, key: string, method: Function, options: CommandOptions): (...args: any[]) => any {
1254
		const result = (...args) => {
J
Joao Moreno 已提交
1255 1256 1257 1258 1259 1260 1261
			// if (!skipModelCheck && !this.model) {
			// 	window.showInformationMessage(localize('disabled', "Git is either disabled or not supported in this workspace"));
			// 	return;
			// }

			let result: Promise<any>;

J
Joao Moreno 已提交
1262
			if (!options.repository) {
J
Joao Moreno 已提交
1263 1264
				result = Promise.resolve(method.apply(this, args));
			} else {
1265 1266 1267 1268
				console.log(args[0]);
				// if (args[0] instanceof SourceControlResourceGroup) {
				// }

J
Joao Moreno 已提交
1269 1270
				result = this.model.pickRepository().then(repository => {
					if (!repository) {
J
Joao Moreno 已提交
1271 1272 1273
						return Promise.reject(localize('modelnotfound', "Git model not found"));
					}

J
Joao Moreno 已提交
1274
					return Promise.resolve(method.apply(this, [repository, ...args]));
J
Joao Moreno 已提交
1275
				});
J
Joao Moreno 已提交
1276 1277
			}

J
Joao Moreno 已提交
1278 1279
			this.telemetryReporter.sendTelemetryEvent('git.command', { command: id });

J
Joao Moreno 已提交
1280 1281 1282 1283
			return result.catch(async err => {
				let message: string;

				switch (err.gitErrorCode) {
1284
					case GitErrorCodes.DirtyWorkTree:
J
Joao Moreno 已提交
1285 1286
						message = localize('clean repo', "Please clean your repository working tree before checkout.");
						break;
1287 1288 1289
					case GitErrorCodes.PushRejected:
						message = localize('cant push', "Can't push refs to remote. Run 'Pull' first to integrate your changes.");
						break;
J
Joao Moreno 已提交
1290
					default:
1291 1292 1293
						const hint = (err.stderr || err.message || String(err))
							.replace(/^error: /mi, '')
							.replace(/^> husky.*$/mi, '')
J
Joao Moreno 已提交
1294
							.split(/[\r\n]/)
1295 1296 1297 1298 1299 1300
							.filter(line => !!line)
						[0];

						message = hint
							? localize('git error details', "Git: {0}", hint)
							: localize('git error', "Git error");
J
Joao Moreno 已提交
1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318

						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();
				}
			});
		};
1319 1320 1321 1322 1323

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

		return result;
J
Joao Moreno 已提交
1324 1325
	}

1326 1327
	// TODO@Joao: possibly remove? do we really need to return resources?
	private getSCMResource(uri?: Uri): Resource | undefined {
1328
		uri = uri ? uri : window.activeTextEditor && window.activeTextEditor.document.uri;
J
Joao Moreno 已提交
1329 1330

		if (!uri) {
1331
			return undefined;
J
Joao Moreno 已提交
1332 1333 1334
		}

		if (uri.scheme === 'git') {
J
Joao Moreno 已提交
1335 1336
			const { path } = fromGitUri(uri);
			uri = Uri.file(path);
J
Joao Moreno 已提交
1337 1338 1339 1340
		}

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

J
Joao Moreno 已提交
1343
			if (!repository) {
1344 1345
				return undefined;
			}
J
Joao Moreno 已提交
1346

J
Joao Moreno 已提交
1347 1348
			return repository.workingTreeGroup.resourceStates.filter(r => r.resourceUri.toString() === uriString)[0]
				|| repository.indexGroup.resourceStates.filter(r => r.resourceUri.toString() === uriString)[0];
J
Joao Moreno 已提交
1349 1350 1351
		}
	}

J
Joao Moreno 已提交
1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383
	private runByRepository<T>(resources: Uri, fn: (repository: Repository, resources: Uri) => Promise<T>): Promise<T[]>;
	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);

			// TODO@Joao: what should happen?
			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 已提交
1384 1385 1386
	dispose(): void {
		this.disposables.forEach(d => d.dispose());
	}
J
Joao Moreno 已提交
1387
}