commands.ts 39.2 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, scm, Disposable, window, workspace, QuickPickItem, OutputChannel, Range, WorkspaceEdit, Position, LineChange, 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, WorkingTreeGroup, IndexGroup, MergeGroup } from './repository';
J
Joao Moreno 已提交
11
import { ModelRegistry } from './modelRegistry';
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(model: Repository): Promise<void> {
J
Joao Moreno 已提交
31 32 33 34 35 36 37 38 39 40 41 42
		const ref = this.treeish;

		if (!ref) {
			return;
		}

		await model.checkout(ref);
	}
}

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(model: Repository, force?: boolean): Promise<void> {
74
		if (!this.branchName) {
M
Maik Riechert 已提交
75 76
			return;
		}
77
		await model.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
	async run(model: Repository): Promise<void> {
J
Joao Moreno 已提交
89
		await model.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(model: Repository): Promise<void> {
J
Joao Moreno 已提交
99 100 101 102
		await commands.executeCommand('git.branch');
	}
}

J
Joao Moreno 已提交
103 104 105 106 107
interface CommandOptions {
	model?: boolean;
	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 modelRegistry: ModelRegistry,
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
	private groupByModel(resources: Uri[]): [Repository | undefined, Uri[]][] {
149
		return resources.reduce((result, resource) => {
150
			const model = this.modelRegistry.getModel(resource);
151 152 153 154 155 156 157 158 159
			const pair = result.filter(p => p[0] === model)[0];

			if (pair) {
				pair[1].push(resource);
			} else {
				result.push([model, [resource]]);
			}

			return result;
J
Joao Moreno 已提交
160
		}, [] as [Repository | undefined, Uri[]][]);
161 162
	}

J
Joao Moreno 已提交
163
	@command('git.refresh', { model: true })
J
Joao Moreno 已提交
164
	async refresh(model: Repository): Promise<void> {
J
Joao Moreno 已提交
165
		await model.status();
J
Joao Moreno 已提交
166
	}
J
Joao Moreno 已提交
167

J
Joao Moreno 已提交
168
	@command('git.openResource', { model: true })
J
Joao Moreno 已提交
169
	async openResource(model: Repository, resource: Resource): Promise<void> {
J
Joao Moreno 已提交
170
		await this._openResource(model, resource);
J
Joao Moreno 已提交
171 172
	}

J
Joao Moreno 已提交
173
	private async _openResource(model: Repository, resource: Resource, preview?: boolean): Promise<void> {
J
Joao Moreno 已提交
174
		const left = this.getLeftResource(resource);
J
Joao Moreno 已提交
175
		const right = this.getRightResource(model, resource);
J
Joao Moreno 已提交
176 177
		const title = this.getTitle(resource);

J
Joao Moreno 已提交
178 179 180 181 182
		if (!right) {
			// TODO
			console.error('oh no');
			return;
		}
J
Joao Moreno 已提交
183

J
Joao Moreno 已提交
184
		const opts: TextDocumentShowOptions = {
185 186
			preserveFocus: true,
			preview: preview,
J
Joao Moreno 已提交
187
			viewColumn: window.activeTextEditor && window.activeTextEditor.viewColumn || ViewColumn.One
J
Joao Moreno 已提交
188 189
		};

J
Joao Moreno 已提交
190 191 192 193 194 195
		const activeTextEditor = window.activeTextEditor;

		if (activeTextEditor && activeTextEditor.document.uri.toString() === right.toString()) {
			opts.selection = activeTextEditor.selection;
		}

196 197 198 199 200 201
		if (!left) {
			const document = await workspace.openTextDocument(right);
			await window.showTextDocument(document, opts);
			return;
		}

J
Joao Moreno 已提交
202
		return await commands.executeCommand<void>('vscode.diff', left, right, title, opts);
J
Joao Moreno 已提交
203 204 205 206 207 208
	}

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

			case Status.MODIFIED:
J
Joao Moreno 已提交
212
				return toGitUri(resource.resourceUri, '~');
213 214 215

			case Status.DELETED_BY_THEM:
				return toGitUri(resource.resourceUri, '');
J
Joao Moreno 已提交
216
		}
J
Joao Moreno 已提交
217
	}
J
Joao Moreno 已提交
218

J
Joao Moreno 已提交
219
	private getRightResource(model: Repository, resource: Resource): Uri | undefined {
J
Joao Moreno 已提交
220 221 222 223 224
		switch (resource.type) {
			case Status.INDEX_MODIFIED:
			case Status.INDEX_ADDED:
			case Status.INDEX_COPIED:
			case Status.INDEX_RENAMED:
J
Joao Moreno 已提交
225
				return toGitUri(resource.resourceUri, '');
J
Joao Moreno 已提交
226 227

			case Status.INDEX_DELETED:
228
			case Status.DELETED_BY_THEM:
J
Joao Moreno 已提交
229
			case Status.DELETED:
J
Joao Moreno 已提交
230
				return toGitUri(resource.resourceUri, 'HEAD');
J
Joao Moreno 已提交
231 232 233 234

			case Status.MODIFIED:
			case Status.UNTRACKED:
			case Status.IGNORED:
J
Joao Moreno 已提交
235
				const uriString = resource.resourceUri.toString();
J
Joao Moreno 已提交
236
				const [indexStatus] = model.indexGroup.resources.filter(r => r.resourceUri.toString() === uriString);
J
Joao Moreno 已提交
237

J
Joao Moreno 已提交
238 239
				if (indexStatus && indexStatus.renameResourceUri) {
					return indexStatus.renameResourceUri;
J
Joao Moreno 已提交
240 241
				}

J
Joao Moreno 已提交
242
				return resource.resourceUri;
J
Joao Moreno 已提交
243

244
			case Status.BOTH_ADDED:
J
Joao Moreno 已提交
245
			case Status.BOTH_MODIFIED:
J
Joao Moreno 已提交
246
				return resource.resourceUri;
J
Joao Moreno 已提交
247 248 249 250
		}
	}

	private getTitle(resource: Resource): string {
J
Joao Moreno 已提交
251
		const basename = path.basename(resource.resourceUri.fsPath);
J
Joao Moreno 已提交
252 253 254 255

		switch (resource.type) {
			case Status.INDEX_MODIFIED:
			case Status.INDEX_RENAMED:
M
Marc Kassay 已提交
256
			case Status.DELETED_BY_THEM:
J
Joao Moreno 已提交
257 258 259
				return `${basename} (Index)`;

			case Status.MODIFIED:
M
Marc Kassay 已提交
260 261
			case Status.BOTH_ADDED:
			case Status.BOTH_MODIFIED:
J
Joao Moreno 已提交
262 263 264 265 266 267
				return `${basename} (Working Tree)`;
		}

		return '';
	}

J
Joao Moreno 已提交
268
	@command('git.clone')
269
	async clone(): Promise<void> {
J
Joao Moreno 已提交
270
		const url = await window.showInputBox({
J
Joao Moreno 已提交
271 272
			prompt: localize('repourl', "Repository URL"),
			ignoreFocusOut: true
J
Joao Moreno 已提交
273 274 275
		});

		if (!url) {
276 277
			this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'no_URL' });
			return;
J
Joao Moreno 已提交
278 279
		}

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

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

		if (!parentPath) {
290 291
			this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'no_directory' });
			return;
J
Joao Moreno 已提交
292 293
		}

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

297
		try {
298 299 300 301 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;
			this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'success' }, { openFolder: openFolder ? 1 : 0 });
			if (openFolder) {
				commands.executeCommand('vscode.openFolder', Uri.file(repositoryPath));
			}
308 309
		} catch (err) {
			if (/already exists and is not an empty directory/.test(err && err.stderr || '')) {
310 311 312
				this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'directory_not_empty' });
			} else {
				this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'error' });
313 314
			}
			throw err;
J
Joao Moreno 已提交
315 316 317
		}
	}

J
Joao Moreno 已提交
318
	@command('git.init')
J
Joao Moreno 已提交
319
	async init(): Promise<void> {
J
Joao Moreno 已提交
320 321
		// TODO@joao
		// await model.init();
J
Joao Moreno 已提交
322 323
	}

J
Joao Moreno 已提交
324
	@command('git.openFile', { model: true })
J
Joao Moreno 已提交
325
	async openFile(model: Repository, arg?: Resource | Uri, ...resourceStates: SourceControlResourceState[]): Promise<void> {
326
		let uris: Uri[] | undefined;
327 328 329

		if (arg instanceof Uri) {
			if (arg.scheme === 'git') {
330
				uris = [Uri.file(fromGitUri(arg).path)];
331
			} else if (arg.scheme === 'file') {
332
				uris = [arg];
333 334 335 336 337 338
			}
		} else {
			let resource = arg;

			if (!(resource instanceof Resource)) {
				// can happen when called from a keybinding
339
				resource = this.getSCMResource();
340 341 342
			}

			if (resource) {
343
				uris = [...resourceStates.map(r => r.resourceUri), resource.resourceUri];
344
			}
J
Joao Moreno 已提交
345 346
		}

347
		if (!uris) {
J
Joao Moreno 已提交
348
			return;
J
Joao Moreno 已提交
349 350
		}

351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
		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 已提交
371
		}
J
Joao Moreno 已提交
372 373
	}

J
Joao Moreno 已提交
374
	@command('git.openHEADFile', { model: true })
J
Joao Moreno 已提交
375
	async openHEADFile(model: Repository, arg?: Resource | Uri): Promise<void> {
D
Duroktar 已提交
376 377 378 379 380
		let resource: Resource | undefined = undefined;

		if (arg instanceof Resource) {
			resource = arg;
		} else if (arg instanceof Uri) {
381
			resource = this.getSCMResource(arg);
D
Duroktar 已提交
382
		} else {
383
			resource = this.getSCMResource();
D
Duroktar 已提交
384 385 386 387 388 389
		}

		if (!resource) {
			return;
		}

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

J
Joao Moreno 已提交
392 393 394
		if (!HEAD) {
			window.showWarningMessage(localize('HEAD not available', "HEAD version of '{0}' is not available.", path.basename(resource.resourceUri.fsPath)));
			return;
D
Duroktar 已提交
395
		}
J
Joao Moreno 已提交
396 397

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

J
Joao Moreno 已提交
400
	@command('git.openChange', { model: true })
J
Joao Moreno 已提交
401
	async openChange(model: Repository, arg?: Resource | Uri, ...resourceStates: SourceControlResourceState[]): Promise<void> {
402
		let resources: Resource[] | undefined = undefined;
403

404
		if (arg instanceof Uri) {
405
			const resource = this.getSCMResource(arg);
406 407 408
			if (resource !== undefined) {
				resources = [resource];
			}
409
		} else {
410
			let resource: Resource | undefined = undefined;
J
Joao Moreno 已提交
411

412 413 414
			if (arg instanceof Resource) {
				resource = arg;
			} else {
415
				resource = this.getSCMResource();
416 417 418 419 420
			}

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

423
		if (!resources) {
J
Joao Moreno 已提交
424
			return;
J
Joao Moreno 已提交
425
		}
J
Joao Moreno 已提交
426

427 428
		const preview = resources.length === 1 ? undefined : false;
		for (const resource of resources) {
429
			await this._openResource(model, resource, preview);
430
		}
J
Joao Moreno 已提交
431 432
	}

433 434
	@command('git.stage')
	async stage(...resourceStates: SourceControlResourceState[]): Promise<void> {
J
Joao Moreno 已提交
435
		if (resourceStates.length === 0 || !(resourceStates[0].resourceUri instanceof Uri)) {
436
			const resource = this.getSCMResource();
437 438 439 440 441 442 443 444

			if (!resource) {
				return;
			}

			resourceStates = [resource];
		}

445
		const scmResources = resourceStates
446 447
			.filter(s => s instanceof Resource && (s.resourceGroup instanceof WorkingTreeGroup || s.resourceGroup instanceof MergeGroup)) as Resource[];

448
		if (!scmResources.length) {
J
Joao Moreno 已提交
449 450
			return;
		}
J
Joao Moreno 已提交
451

452 453 454 455
		const resources = scmResources.map(r => r.resourceUri);
		const resourcesByModel = this.groupByModel(resources);

		await Promise.all(resourcesByModel.map(async ([model, resources]) => {
456
			if (!model) {
457
				return; // TODO@joao
458 459 460 461
			}

			await model.add(...resources);
		}));
J
Joao Moreno 已提交
462 463
	}

J
Joao Moreno 已提交
464
	@command('git.stageAll', { model: true })
J
Joao Moreno 已提交
465
	async stageAll(model: Repository): Promise<void> {
J
Joao Moreno 已提交
466
		return await model.add();
J
Joao Moreno 已提交
467 468
	}

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

		if (!textEditor) {
			return;
		}

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

J
Joao Moreno 已提交
481
		if (modifiedUri.scheme !== 'file') {
J
Joao Moreno 已提交
482 483 484
			return;
		}

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

		if (!selectedDiffs.length) {
			return;
		}

496 497
		const result = applyLineChanges(originalDocument, modifiedDocument, selectedDiffs);

J
Joao Moreno 已提交
498
		await model.stage(modifiedUri, result);
J
Joao Moreno 已提交
499
	}
J
Joao Moreno 已提交
500

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

		if (!textEditor) {
			return;
		}

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

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

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

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

			if (!resource) {
				return;
			}

			resourceStates = [resource];
		}

559
		const scmResources = resourceStates
560 561
			.filter(s => s instanceof Resource && s.resourceGroup instanceof IndexGroup) as Resource[];

562
		if (!scmResources.length) {
J
Joao Moreno 已提交
563 564 565
			return;
		}

566 567
		const resources = scmResources.map(r => r.resourceUri);

J
Joao Moreno 已提交
568
		return await model.revertFiles(...resources);
J
Joao Moreno 已提交
569 570
	}

J
Joao Moreno 已提交
571
	@command('git.unstageAll', { model: true })
J
Joao Moreno 已提交
572
	async unstageAll(model: Repository): Promise<void> {
J
Joao Moreno 已提交
573
		return await model.revertFiles();
J
Joao Moreno 已提交
574
	}
J
Joao Moreno 已提交
575

576
	// TODO@Joao does this command really receive a model?
J
Joao Moreno 已提交
577
	@command('git.unstageSelectedRanges', { model: true, diff: true })
J
Joao Moreno 已提交
578
	async unstageSelectedRanges(model: Repository, diffs: LineChange[]): Promise<void> {
J
Joao Moreno 已提交
579 580 581 582 583 584 585 586 587
		const textEditor = window.activeTextEditor;

		if (!textEditor) {
			return;
		}

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

588 589 590 591 592 593 594
		if (modifiedUri.scheme !== 'git') {
			return;
		}

		const { ref } = fromGitUri(modifiedUri);

		if (ref !== '') {
J
Joao Moreno 已提交
595 596 597
			return;
		}

J
Joao Moreno 已提交
598
		const originalUri = toGitUri(modifiedUri, 'HEAD');
J
Joao Moreno 已提交
599
		const originalDocument = await workspace.openTextDocument(originalUri);
600 601 602 603
		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 已提交
604 605 606 607 608

		if (!selectedDiffs.length) {
			return;
		}

609 610
		const invertedDiffs = selectedDiffs.map(invertLineChange);
		const result = applyLineChanges(modifiedDocument, originalDocument, invertedDiffs);
J
Joao Moreno 已提交
611

J
Joao Moreno 已提交
612
		await model.stage(modifiedUri, result);
J
Joao Moreno 已提交
613 614
	}

J
Joao Moreno 已提交
615
	@command('git.clean', { model: true })
J
Joao Moreno 已提交
616
	async clean(model: Repository, ...resourceStates: SourceControlResourceState[]): Promise<void> {
J
Joao Moreno 已提交
617
		if (resourceStates.length === 0 || !(resourceStates[0].resourceUri instanceof Uri)) {
618
			const resource = this.getSCMResource();
619 620 621 622 623 624 625 626

			if (!resource) {
				return;
			}

			resourceStates = [resource];
		}

627 628 629
		const resources = resourceStates
			.filter(s => s instanceof Resource && s.resourceGroup instanceof WorkingTreeGroup) as Resource[];

630
		if (!resources.length) {
J
Joao Moreno 已提交
631 632
			return;
		}
J
Joao Moreno 已提交
633

J
Joao Moreno 已提交
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
		const untrackedCount = resources.reduce((s, r) => s + (r.type === Status.UNTRACKED ? 1 : 0), 0);
		let message: string;
		let yes = localize('discard', "Discard Changes");

		if (resources.length === 1) {
			if (untrackedCount > 0) {
				message = localize('confirm delete', "Are you sure you want to DELETE {0}?", path.basename(resources[0].resourceUri.fsPath));
				yes = localize('delete file', "Delete file");
			} else {
				message = localize('confirm discard', "Are you sure you want to discard changes in {0}?", path.basename(resources[0].resourceUri.fsPath));
			}
		} else {
			message = localize('confirm discard multiple', "Are you sure you want to discard changes in {0} files?", resources.length);

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

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

J
Joao Moreno 已提交
655 656 657 658
		if (pick !== yes) {
			return;
		}

659
		await model.clean(...resources.map(r => r.resourceUri));
J
Joao Moreno 已提交
660
	}
J
Joao Moreno 已提交
661

J
Joao Moreno 已提交
662
	@command('git.cleanAll', { model: true })
J
Joao Moreno 已提交
663
	async cleanAll(model: Repository): Promise<void> {
J
Joao Moreno 已提交
664 665
		const config = workspace.getConfiguration('git');
		let scope = config.get<string>('discardAllScope') || 'prompt';
666
		let resources = model.workingTreeGroup.resources;
J
Joao Moreno 已提交
667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703

		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);
704
		const yes = localize('discardAll', "Discard ALL Changes");
J
Joao Moreno 已提交
705
		const pick = await window.showWarningMessage(message, { modal: true }, yes);
J
Joao Moreno 已提交
706 707 708 709 710

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

711
		await model.clean(...resources.map(r => r.resourceUri));
J
Joao Moreno 已提交
712 713
	}

J
Joao Moreno 已提交
714
	private async smartCommit(
J
Joao Moreno 已提交
715
		model: Repository,
716
		getCommitMessage: () => Promise<string | undefined>,
J
Joao Moreno 已提交
717 718
		opts?: CommitOptions
	): Promise<boolean> {
719 720
		const config = workspace.getConfiguration('git');
		const enableSmartCommit = config.get<boolean>('enableSmartCommit') === true;
721
		const enableCommitSigning = config.get<boolean>('enableCommitSigning') === true;
J
Joao Moreno 已提交
722 723
		const noStagedChanges = model.indexGroup.resources.length === 0;
		const noUnstagedChanges = model.workingTreeGroup.resources.length === 0;
724 725

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

J
Joao Moreno 已提交
728 729
			// 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?");
730 731 732 733 734
			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 已提交
735 736 737
				config.update('enableSmartCommit', true, true);
			} else if (pick !== yes) {
				return false; // do not commit on cancel
738 739 740
			}
		}

J
Joao Moreno 已提交
741
		if (!opts) {
742
			opts = { all: noStagedChanges };
J
Joao Moreno 已提交
743 744
		}

745 746 747
		// enable signing of commits if configurated
		opts.signCommit = enableCommitSigning;

J
Joao Moreno 已提交
748 749
		if (
			// no changes
750
			(noStagedChanges && noUnstagedChanges)
J
Joao Moreno 已提交
751
			// or no staged changes and not `all`
752
			|| (!opts.all && noStagedChanges)
J
Joao Moreno 已提交
753
		) {
J
Joao Moreno 已提交
754 755 756 757
			window.showInformationMessage(localize('no changes', "There are no changes to commit."));
			return false;
		}

J
Joao Moreno 已提交
758
		const message = await getCommitMessage();
J
Joao Moreno 已提交
759 760 761 762 763 764

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

J
Joao Moreno 已提交
765
		await model.commit(message, opts);
J
Joao Moreno 已提交
766 767 768 769

		return true;
	}

J
Joao Moreno 已提交
770
	private async commitWithAnyInput(model: Repository, opts?: CommitOptions): Promise<void> {
771
		const message = scm.inputBox.value;
J
Joao Moreno 已提交
772
		const getCommitMessage = async () => {
J
Joao Moreno 已提交
773 774 775 776 777 778
			if (message) {
				return message;
			}

			return await window.showInputBox({
				placeHolder: localize('commit message', "Commit message"),
J
Joao Moreno 已提交
779 780
				prompt: localize('provide commit message', "Please provide a commit message"),
				ignoreFocusOut: true
J
Joao Moreno 已提交
781
			});
J
Joao Moreno 已提交
782 783
		};

J
Joao Moreno 已提交
784
		const didCommit = await this.smartCommit(model, getCommitMessage, opts);
J
Joao Moreno 已提交
785 786

		if (message && didCommit) {
J
Joao Moreno 已提交
787
			scm.inputBox.value = await model.getCommitTemplate();
J
Joao Moreno 已提交
788
		}
J
Joao Moreno 已提交
789 790
	}

J
Joao Moreno 已提交
791
	@command('git.commit', { model: true })
J
Joao Moreno 已提交
792
	async commit(model: Repository): Promise<void> {
J
Joao Moreno 已提交
793
		await this.commitWithAnyInput(model);
J
Joao Moreno 已提交
794 795
	}

J
Joao Moreno 已提交
796
	@command('git.commitWithInput', { model: true })
J
Joao Moreno 已提交
797
	async commitWithInput(model: Repository): Promise<void> {
J
Joao Moreno 已提交
798 799 800 801
		if (!scm.inputBox.value) {
			return;
		}

J
Joao Moreno 已提交
802
		const didCommit = await this.smartCommit(model, async () => scm.inputBox.value);
J
Joao Moreno 已提交
803 804

		if (didCommit) {
J
Joao Moreno 已提交
805
			scm.inputBox.value = await model.getCommitTemplate();
J
Joao Moreno 已提交
806
		}
J
Joao Moreno 已提交
807 808
	}

J
Joao Moreno 已提交
809
	@command('git.commitStaged', { model: true })
J
Joao Moreno 已提交
810
	async commitStaged(model: Repository): Promise<void> {
J
Joao Moreno 已提交
811
		await this.commitWithAnyInput(model, { all: false });
J
Joao Moreno 已提交
812 813
	}

J
Joao Moreno 已提交
814
	@command('git.commitStagedSigned', { model: true })
J
Joao Moreno 已提交
815
	async commitStagedSigned(model: Repository): Promise<void> {
J
Joao Moreno 已提交
816
		await this.commitWithAnyInput(model, { all: false, signoff: true });
J
Joao Moreno 已提交
817 818
	}

J
Joao Moreno 已提交
819
	@command('git.commitStagedAmend', { model: true })
J
Joao Moreno 已提交
820
	async commitStagedAmend(model: Repository): Promise<void> {
821
		await this.commitWithAnyInput(model, { all: false, amend: true });
K
Krzysztof Cieślak 已提交
822 823
	}

J
Joao Moreno 已提交
824
	@command('git.commitAll', { model: true })
J
Joao Moreno 已提交
825
	async commitAll(model: Repository): Promise<void> {
J
Joao Moreno 已提交
826
		await this.commitWithAnyInput(model, { all: true });
J
Joao Moreno 已提交
827 828
	}

J
Joao Moreno 已提交
829
	@command('git.commitAllSigned', { model: true })
J
Joao Moreno 已提交
830
	async commitAllSigned(model: Repository): Promise<void> {
J
Joao Moreno 已提交
831
		await this.commitWithAnyInput(model, { all: true, signoff: true });
J
Joao Moreno 已提交
832 833
	}

J
Joao Moreno 已提交
834
	@command('git.commitAllAmend', { model: true })
J
Joao Moreno 已提交
835
	async commitAllAmend(model: Repository): Promise<void> {
836
		await this.commitWithAnyInput(model, { all: true, amend: true });
K
Krzysztof Cieślak 已提交
837 838
	}

J
Joao Moreno 已提交
839
	@command('git.undoCommit', { model: true })
J
Joao Moreno 已提交
840
	async undoCommit(model: Repository): Promise<void> {
J
Joao Moreno 已提交
841
		const HEAD = model.HEAD;
J
Joao Moreno 已提交
842 843 844 845 846

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

J
Joao Moreno 已提交
847 848
		const commit = await model.getCommit('HEAD');
		await model.reset('HEAD~');
J
Joao Moreno 已提交
849
		scm.inputBox.value = commit.message;
J
Joao Moreno 已提交
850 851
	}

J
Joao Moreno 已提交
852
	@command('git.checkout', { model: true })
J
Joao Moreno 已提交
853
	async checkout(model: Repository, treeish: string): Promise<void> {
J
Joao Moreno 已提交
854
		if (typeof treeish === 'string') {
J
Joao Moreno 已提交
855
			return await model.checkout(treeish);
J
Joao Moreno 已提交
856 857
		}

J
Joao Moreno 已提交
858
		const config = workspace.getConfiguration('git');
J
Joao Moreno 已提交
859
		const checkoutType = config.get<string>('checkoutType') || 'all';
J
Joao Moreno 已提交
860 861 862
		const includeTags = checkoutType === 'all' || checkoutType === 'tags';
		const includeRemotes = checkoutType === 'all' || checkoutType === 'remote';

J
Joao Moreno 已提交
863 864
		const createBranch = new CreateBranchItem();

J
Joao Moreno 已提交
865
		const heads = model.refs.filter(ref => ref.type === RefType.Head)
J
Joao Moreno 已提交
866 867
			.map(ref => new CheckoutItem(ref));

J
Joao Moreno 已提交
868
		const tags = (includeTags ? model.refs.filter(ref => ref.type === RefType.Tag) : [])
J
Joao Moreno 已提交
869 870
			.map(ref => new CheckoutTagItem(ref));

J
Joao Moreno 已提交
871
		const remoteHeads = (includeRemotes ? model.refs.filter(ref => ref.type === RefType.RemoteHead) : [])
J
Joao Moreno 已提交
872 873
			.map(ref => new CheckoutRemoteHeadItem(ref));

J
Joao Moreno 已提交
874
		const picks = [createBranch, ...heads, ...tags, ...remoteHeads];
875
		const placeHolder = localize('select a ref to checkout', 'Select a ref to checkout');
J
Joao Moreno 已提交
876
		const choice = await window.showQuickPick(picks, { placeHolder });
J
Joao Moreno 已提交
877 878 879 880 881

		if (!choice) {
			return;
		}

J
Joao Moreno 已提交
882
		await choice.run(model);
J
Joao Moreno 已提交
883 884
	}

J
Joao Moreno 已提交
885
	@command('git.branch', { model: true })
J
Joao Moreno 已提交
886
	async branch(model: Repository): Promise<void> {
J
Joao Moreno 已提交
887
		const result = await window.showInputBox({
J
Joao Moreno 已提交
888
			placeHolder: localize('branch name', "Branch name"),
J
Joao Moreno 已提交
889 890
			prompt: localize('provide branch name', "Please provide a branch name"),
			ignoreFocusOut: true
J
Joao Moreno 已提交
891
		});
J
Joao Moreno 已提交
892

J
Joao Moreno 已提交
893 894 895
		if (!result) {
			return;
		}
J
Joao Moreno 已提交
896

J
Joao Moreno 已提交
897
		const name = result.replace(/^\.|\/\.|\.\.|~|\^|:|\/$|\.lock$|\.lock\/|\\|\*|\s|^\s*$|\.$/g, '-');
J
Joao Moreno 已提交
898
		await model.branch(name);
J
Joao Moreno 已提交
899 900
	}

J
Joao Moreno 已提交
901
	@command('git.deleteBranch', { model: true })
J
Joao Moreno 已提交
902
	async deleteBranch(model: Repository, name: string, force?: boolean): Promise<void> {
903 904
		let run: (force?: boolean) => Promise<void>;
		if (typeof name === 'string') {
J
Joao Moreno 已提交
905
			run = force => model.deleteBranch(name, force);
906
		} else {
J
Joao Moreno 已提交
907 908
			const currentHead = model.HEAD && model.HEAD.name;
			const heads = model.refs.filter(ref => ref.type === RefType.Head && ref.name !== currentHead)
909
				.map(ref => new BranchDeleteItem(ref));
M
Maik Riechert 已提交
910

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

M
Maik Riechert 已提交
914
			if (!choice || !choice.branchName) {
915 916
				return;
			}
M
Maik Riechert 已提交
917
			name = choice.branchName;
J
Joao Moreno 已提交
918
			run = force => choice.run(model, force);
M
Maik Riechert 已提交
919 920
		}

921 922 923 924 925 926 927 928 929 930 931 932 933 934 935
		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 已提交
936 937
	}

J
Joao Moreno 已提交
938
	@command('git.merge', { model: true })
J
Joao Moreno 已提交
939
	async merge(model: Repository): Promise<void> {
940 941 942 943
		const config = workspace.getConfiguration('git');
		const checkoutType = config.get<string>('checkoutType') || 'all';
		const includeRemotes = checkoutType === 'all' || checkoutType === 'remote';

J
Joao Moreno 已提交
944
		const heads = model.refs.filter(ref => ref.type === RefType.Head)
J
Joao Moreno 已提交
945 946
			.filter(ref => ref.name || ref.commit)
			.map(ref => new MergeItem(ref as Branch));
947

J
Joao Moreno 已提交
948
		const remoteHeads = (includeRemotes ? model.refs.filter(ref => ref.type === RefType.RemoteHead) : [])
J
Joao Moreno 已提交
949 950
			.filter(ref => ref.name || ref.commit)
			.map(ref => new MergeItem(ref as Branch));
951 952

		const picks = [...heads, ...remoteHeads];
953 954
		const placeHolder = localize('select a branch to merge from', 'Select a branch to merge from');
		const choice = await window.showQuickPick<MergeItem>(picks, { placeHolder });
955 956 957 958 959

		if (!choice) {
			return;
		}

J
Joao Moreno 已提交
960
		try {
J
Joao Moreno 已提交
961
			await choice.run(model);
J
Joao Moreno 已提交
962 963 964 965 966 967 968 969
		} 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);
		}
970 971
	}

J
Joao Moreno 已提交
972
	@command('git.createTag', { model: true })
J
Joao Moreno 已提交
973
	async createTag(model: Repository): Promise<void> {
974 975 976 977 978 979 980 981 982 983 984 985
		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 已提交
986
			prompt: localize('provide tag message', "Please provide a message to annotate the tag"),
987 988 989 990 991
			ignoreFocusOut: true
		});

		const name = inputTagName.replace(/^\.|\/\.|\.\.|~|\^|:|\/$|\.lock$|\.lock\/|\\|\*|\s|^\s*$|\.$/g, '-');
		const message = inputMessage || name;
992
		await model.tag(name, message);
993 994
	}

J
Joao Moreno 已提交
995
	@command('git.pullFrom', { model: true })
J
Joao Moreno 已提交
996
	async pullFrom(model: Repository): Promise<void> {
J
Joao Moreno 已提交
997
		const remotes = model.remotes;
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021

		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 已提交
1022
		model.pull(false, pick.label, branchName);
1023 1024
	}

J
Joao Moreno 已提交
1025
	@command('git.pull', { model: true })
J
Joao Moreno 已提交
1026
	async pull(model: Repository): Promise<void> {
J
Joao Moreno 已提交
1027
		const remotes = model.remotes;
J
Joao Moreno 已提交
1028 1029 1030 1031 1032 1033

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

J
Joao Moreno 已提交
1034
		await model.pull();
J
Joao Moreno 已提交
1035 1036
	}

J
Joao Moreno 已提交
1037
	@command('git.pullRebase', { model: true })
J
Joao Moreno 已提交
1038
	async pullRebase(model: Repository): Promise<void> {
J
Joao Moreno 已提交
1039
		const remotes = model.remotes;
J
Joao Moreno 已提交
1040 1041 1042 1043 1044 1045

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

J
Joao Moreno 已提交
1046
		await model.pullWithRebase();
J
Joao Moreno 已提交
1047 1048
	}

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

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

J
Joao Moreno 已提交
1058
		await model.push();
J
Joao Moreno 已提交
1059 1060
	}

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

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

1070
		await model.pushTags();
1071 1072 1073 1074

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

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

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

J
Joao Moreno 已提交
1084
		if (!model.HEAD || !model.HEAD.name) {
J
Joao Moreno 已提交
1085 1086 1087 1088
			window.showWarningMessage(localize('nobranch', "Please check out a branch to push to a remote."));
			return;
		}

J
Joao Moreno 已提交
1089
		const branchName = model.HEAD.name;
J
Joao Moreno 已提交
1090 1091 1092 1093 1094 1095 1096 1097
		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 已提交
1098
		model.pushTo(pick.label, branchName);
J
Joao Moreno 已提交
1099 1100
	}

J
Joao Moreno 已提交
1101
	@command('git.sync', { model: true })
J
Joao Moreno 已提交
1102
	async sync(model: Repository): Promise<void> {
J
Joao Moreno 已提交
1103
		const HEAD = model.HEAD;
J
Joao Moreno 已提交
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124

		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 已提交
1125
		await model.sync();
J
Joao Moreno 已提交
1126 1127
	}

J
Joao Moreno 已提交
1128
	@command('git.publish', { model: true })
J
Joao Moreno 已提交
1129
	async publish(model: Repository): Promise<void> {
J
Joao Moreno 已提交
1130
		const remotes = model.remotes;
J
Joao Moreno 已提交
1131 1132 1133 1134 1135 1136

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

J
Joao Moreno 已提交
1137 1138
		const branchName = model.HEAD && model.HEAD.name || '';
		const picks = model.remotes.map(r => r.name);
J
Joao Moreno 已提交
1139
		const placeHolder = localize('pick remote', "Pick a remote to publish the branch '{0}' to:", branchName);
J
Joao Moreno 已提交
1140 1141 1142 1143 1144 1145
		const choice = await window.showQuickPick(picks, { placeHolder });

		if (!choice) {
			return;
		}

J
Joao Moreno 已提交
1146
		await model.pushTo(choice, branchName, true);
J
Joao Moreno 已提交
1147 1148
	}

J
Joao Moreno 已提交
1149
	@command('git.showOutput')
J
Joao Moreno 已提交
1150 1151 1152 1153
	showOutput(): void {
		this.outputChannel.show();
	}

J
Joao Moreno 已提交
1154
	@command('git.ignore', { model: true })
J
Joao Moreno 已提交
1155
	async ignore(model: Repository, ...resourceStates: SourceControlResourceState[]): Promise<void> {
J
Joao Moreno 已提交
1156 1157
		if (resourceStates.length === 0 || !(resourceStates[0].resourceUri instanceof Uri)) {
			const uri = window.activeTextEditor && window.activeTextEditor.document.uri;
N
NKumar2 已提交
1158

J
Joao Moreno 已提交
1159 1160 1161 1162
			if (!uri) {
				return;
			}

J
Joao Moreno 已提交
1163
			return await model.ignore([uri]);
J
Joao Moreno 已提交
1164 1165 1166 1167 1168 1169 1170
		}

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

		if (!uris.length) {
N
NKumar2 已提交
1171 1172 1173
			return;
		}

J
Joao Moreno 已提交
1174
		await model.ignore(uris);
N
NKumar2 已提交
1175 1176
	}

1177
	@command('git.stash', { model: true })
J
Joao Moreno 已提交
1178
	async stash(model: Repository): Promise<void> {
1179
		if (model.workingTreeGroup.resources.length === 0) {
K
Krzysztof Cieślak 已提交
1180 1181 1182
			window.showInformationMessage(localize('no changes stash', "There are no changes to stash."));
			return;
		}
J
Joao Moreno 已提交
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192

		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;
		}

1193
		await model.createStash(message);
K
Krzysztof Cieślak 已提交
1194 1195
	}

1196
	@command('git.stashPop', { model: true })
J
Joao Moreno 已提交
1197
	async stashPop(model: Repository): Promise<void> {
1198
		const stashes = await model.getStashes();
J
Joao Moreno 已提交
1199 1200

		if (stashes.length === 0) {
K
Krzysztof Cieślak 已提交
1201 1202 1203 1204
			window.showInformationMessage(localize('no stashes', "There are no stashes to restore."));
			return;
		}

J
Joao Moreno 已提交
1205 1206
		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 已提交
1207 1208 1209 1210 1211
		const choice = await window.showQuickPick(picks, { placeHolder });

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

1213
		await model.popStash(choice.id);
K
Krzysztof Cieślak 已提交
1214 1215
	}

1216
	@command('git.stashPopLatest', { model: true })
J
Joao Moreno 已提交
1217
	async stashPopLatest(model: Repository): Promise<void> {
1218
		const stashes = await model.getStashes();
J
Joao Moreno 已提交
1219 1220

		if (stashes.length === 0) {
K
Krzysztof Cieślak 已提交
1221 1222 1223 1224
			window.showInformationMessage(localize('no stashes', "There are no stashes to restore."));
			return;
		}

1225
		await model.popStash();
J
Joao Moreno 已提交
1226
	}
K
Krzysztof Cieślak 已提交
1227

J
Joao Moreno 已提交
1228
	private createCommand(id: string, key: string, method: Function, options: CommandOptions): (...args: any[]) => any {
1229
		const result = (...args) => {
J
Joao Moreno 已提交
1230 1231 1232 1233 1234 1235 1236
			// 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 已提交
1237
			if (!options.model) {
J
Joao Moreno 已提交
1238 1239 1240 1241 1242 1243 1244 1245 1246
				result = Promise.resolve(method.apply(this, args));
			} else {
				result = this.modelRegistry.pickModel().then(model => {
					if (!model) {
						return Promise.reject(localize('modelnotfound', "Git model not found"));
					}

					return Promise.resolve(method.apply(this, [model, ...args]));
				});
J
Joao Moreno 已提交
1247 1248
			}

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

J
Joao Moreno 已提交
1251 1252 1253 1254
			return result.catch(async err => {
				let message: string;

				switch (err.gitErrorCode) {
1255
					case GitErrorCodes.DirtyWorkTree:
J
Joao Moreno 已提交
1256 1257
						message = localize('clean repo', "Please clean your repository working tree before checkout.");
						break;
1258 1259 1260
					case GitErrorCodes.PushRejected:
						message = localize('cant push', "Can't push refs to remote. Run 'Pull' first to integrate your changes.");
						break;
J
Joao Moreno 已提交
1261
					default:
1262 1263 1264
						const hint = (err.stderr || err.message || String(err))
							.replace(/^error: /mi, '')
							.replace(/^> husky.*$/mi, '')
J
Joao Moreno 已提交
1265
							.split(/[\r\n]/)
1266 1267 1268 1269 1270 1271
							.filter(line => !!line)
						[0];

						message = hint
							? localize('git error details', "Git: {0}", hint)
							: localize('git error', "Git error");
J
Joao Moreno 已提交
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289

						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();
				}
			});
		};
1290 1291 1292 1293 1294

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

		return result;
J
Joao Moreno 已提交
1295 1296
	}

1297 1298
	// TODO@Joao: possibly remove? do we really need to return resources?
	private getSCMResource(uri?: Uri): Resource | undefined {
1299
		uri = uri ? uri : window.activeTextEditor && window.activeTextEditor.document.uri;
J
Joao Moreno 已提交
1300 1301

		if (!uri) {
1302
			return undefined;
J
Joao Moreno 已提交
1303 1304 1305
		}

		if (uri.scheme === 'git') {
J
Joao Moreno 已提交
1306 1307
			const { path } = fromGitUri(uri);
			uri = Uri.file(path);
J
Joao Moreno 已提交
1308 1309 1310 1311
		}

		if (uri.scheme === 'file') {
			const uriString = uri.toString();
1312 1313 1314 1315 1316
			const model = this.modelRegistry.getModel(uri);

			if (!model) {
				return undefined;
			}
J
Joao Moreno 已提交
1317

J
Joao Moreno 已提交
1318 1319
			return model.workingTreeGroup.resources.filter(r => r.resourceUri.toString() === uriString)[0]
				|| model.indexGroup.resources.filter(r => r.resourceUri.toString() === uriString)[0];
J
Joao Moreno 已提交
1320 1321 1322
		}
	}

J
Joao Moreno 已提交
1323 1324 1325
	dispose(): void {
		this.disposables.forEach(d => d.dispose());
	}
J
Joao Moreno 已提交
1326
}