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

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

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

J
Joao Moreno 已提交
20 21 22 23 24 25 26
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 已提交
27
	constructor(protected ref: Ref) { }
J
Joao Moreno 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40 41

	async run(model: Model): Promise<void> {
		const ref = this.treeish;

		if (!ref) {
			return;
		}

		await model.checkout(ref);
	}
}

class CheckoutTagItem extends CheckoutItem {

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

class CheckoutRemoteHeadItem extends CheckoutItem {

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

	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 已提交
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
class BranchDeleteItem 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; }

	constructor(protected ref: Ref) { }

	async run(model: Model): Promise<void> {
		const ref = this.treeish;

		if (!ref) {
			return;
		}

		await model.deleteBranch(ref);
	}
}

83 84 85 86 87 88 89 90 91
interface Command {
	commandId: string;
	key: string;
	method: Function;
	skipModelCheck: boolean;
	requiresDiffInformation: boolean;
}

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

93
function command(commandId: string, skipModelCheck = false, requiresDiffInformation = false): Function {
J
Joao Moreno 已提交
94
	return (target: any, key: string, descriptor: any) => {
J
Joao Moreno 已提交
95 96 97 98
		if (!(typeof descriptor.value === 'function')) {
			throw new Error('not supported');
		}

99
		Commands.push({ commandId, key, method: descriptor.value, skipModelCheck, requiresDiffInformation });
J
Joao Moreno 已提交
100 101
	};
}
J
Joao Moreno 已提交
102

J
Joao Moreno 已提交
103
export class CommandCenter {
J
Joao Moreno 已提交
104

J
Joao Moreno 已提交
105
	private model: Model;
J
Joao Moreno 已提交
106
	private disposables: Disposable[];
J
Joao Moreno 已提交
107

J
Joao Moreno 已提交
108
	constructor(
J
Joao Moreno 已提交
109
		private git: Git,
J
Joao Moreno 已提交
110
		model: Model | undefined,
J
Joao Moreno 已提交
111 112
		private outputChannel: OutputChannel,
		private telemetryReporter: TelemetryReporter
J
Joao Moreno 已提交
113
	) {
J
Joao Moreno 已提交
114 115 116 117
		if (model) {
			this.model = model;
		}

J
Joao Moreno 已提交
118
		this.disposables = Commands
119 120 121 122 123 124 125 126 127
			.map(({ commandId, key, method, skipModelCheck, requiresDiffInformation }) => {
				const command = this.createCommand(commandId, key, method, skipModelCheck);

				if (requiresDiffInformation) {
					return commands.registerDiffInformationCommand(commandId, command);
				} else {
					return commands.registerCommand(commandId, command);
				}
			});
J
Joao Moreno 已提交
128 129
	}

J
Joao Moreno 已提交
130
	@command('git.refresh')
J
Joao Moreno 已提交
131
	async refresh(): Promise<void> {
J
Joao Moreno 已提交
132
		await this.model.status();
J
Joao Moreno 已提交
133
	}
J
Joao Moreno 已提交
134

J
Joao Moreno 已提交
135 136 137 138 139 140
	@command('git.openResource')
	async openResource(resource: Resource): Promise<void> {
		await this._openResource(resource);
	}

	private async _openResource(resource: Resource): Promise<void> {
J
Joao Moreno 已提交
141 142 143 144
		const left = this.getLeftResource(resource);
		const right = this.getRightResource(resource);
		const title = this.getTitle(resource);

J
Joao Moreno 已提交
145 146 147 148 149
		if (!right) {
			// TODO
			console.error('oh no');
			return;
		}
J
Joao Moreno 已提交
150

J
Joao Moreno 已提交
151
		if (!left) {
J
Joao Moreno 已提交
152
			return await commands.executeCommand<void>('vscode.open', right);
J
Joao Moreno 已提交
153 154
		}

J
Joao Moreno 已提交
155
		return await commands.executeCommand<void>('vscode.diff', left, right, title);
J
Joao Moreno 已提交
156 157 158 159 160 161
	}

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

			case Status.MODIFIED:
J
Joao Moreno 已提交
165
				return toGitUri(resource.resourceUri, '~');
J
Joao Moreno 已提交
166
		}
J
Joao Moreno 已提交
167
	}
J
Joao Moreno 已提交
168

J
Joao Moreno 已提交
169 170 171 172 173 174
	private getRightResource(resource: Resource): Uri | undefined {
		switch (resource.type) {
			case Status.INDEX_MODIFIED:
			case Status.INDEX_ADDED:
			case Status.INDEX_COPIED:
			case Status.INDEX_RENAMED:
J
Joao Moreno 已提交
175
				return toGitUri(resource.resourceUri, '');
J
Joao Moreno 已提交
176 177 178

			case Status.INDEX_DELETED:
			case Status.DELETED:
J
Joao Moreno 已提交
179
				return toGitUri(resource.resourceUri, 'HEAD');
J
Joao Moreno 已提交
180 181 182 183

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

J
Joao Moreno 已提交
187 188
				if (indexStatus && indexStatus.renameResourceUri) {
					return indexStatus.renameResourceUri;
J
Joao Moreno 已提交
189 190
				}

J
Joao Moreno 已提交
191
				return resource.resourceUri;
J
Joao Moreno 已提交
192

J
Joao Moreno 已提交
193
			case Status.BOTH_MODIFIED:
J
Joao Moreno 已提交
194
				return resource.resourceUri;
J
Joao Moreno 已提交
195 196 197 198
		}
	}

	private getTitle(resource: Resource): string {
J
Joao Moreno 已提交
199
		const basename = path.basename(resource.resourceUri.fsPath);
J
Joao Moreno 已提交
200 201 202 203 204 205 206 207 208 209 210 211 212

		switch (resource.type) {
			case Status.INDEX_MODIFIED:
			case Status.INDEX_RENAMED:
				return `${basename} (Index)`;

			case Status.MODIFIED:
				return `${basename} (Working Tree)`;
		}

		return '';
	}

213 214
	@command('git.clone', true)
	async clone(): Promise<void> {
J
Joao Moreno 已提交
215
		const url = await window.showInputBox({
J
Joao Moreno 已提交
216 217
			prompt: localize('repourl', "Repository URL"),
			ignoreFocusOut: true
J
Joao Moreno 已提交
218 219 220
		});

		if (!url) {
221 222
			this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'no_URL' });
			return;
J
Joao Moreno 已提交
223 224
		}

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

J
Joao Moreno 已提交
228 229
		const parentPath = await window.showInputBox({
			prompt: localize('parent', "Parent Directory"),
J
Joao Moreno 已提交
230
			value,
J
Joao Moreno 已提交
231
			ignoreFocusOut: true
J
Joao Moreno 已提交
232 233 234
		});

		if (!parentPath) {
235 236
			this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'no_directory' });
			return;
J
Joao Moreno 已提交
237 238
		}

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

242
		try {
243 244 245 246 247 248 249 250 251 252
			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));
			}
253 254
		} catch (err) {
			if (/already exists and is not an empty directory/.test(err && err.stderr || '')) {
255 256 257
				this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'directory_not_empty' });
			} else {
				this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'error' });
258 259
			}
			throw err;
J
Joao Moreno 已提交
260 261 262
		}
	}

J
Joao Moreno 已提交
263 264 265 266 267
	@command('git.init')
	async init(): Promise<void> {
		await this.model.init();
	}

J
Joao Moreno 已提交
268
	@command('git.openFile')
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
	async openFile(arg?: Resource | Uri): Promise<void> {
		let uri: Uri | undefined;

		if (arg instanceof Uri) {
			if (arg.scheme === 'git') {
				uri = Uri.file(fromGitUri(arg).path);
			} else if (arg.scheme === 'file') {
				uri = arg;
			}
		} else {
			let resource = arg;

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

			if (resource) {
				uri = resource.resourceUri;
			}
J
Joao Moreno 已提交
289 290
		}

291
		if (!uri) {
J
Joao Moreno 已提交
292
			return;
J
Joao Moreno 已提交
293 294
		}

295
		return await commands.executeCommand<void>('vscode.open', uri);
J
Joao Moreno 已提交
296 297 298
	}

	@command('git.openChange')
299 300 301 302 303 304 305 306
	async openChange(arg?: Resource | Uri): Promise<void> {
		let resource: Resource | undefined = undefined;

		if (arg instanceof Resource) {
			resource = arg;
		} else if (arg instanceof Uri) {
			resource = this.getSCMResource(arg);
		} else {
J
Joao Moreno 已提交
307 308 309
			resource = this.getSCMResource();
		}

J
Joao Moreno 已提交
310 311
		if (!resource) {
			return;
J
Joao Moreno 已提交
312 313
		}

J
Joao Moreno 已提交
314
		return await this._openResource(resource);
J
Joao Moreno 已提交
315 316
	}

317 318 319
	@command('git.openFileFromUri')
	async openFileFromUri(uri?: Uri): Promise<void> {
		const resource = this.getSCMResource(uri);
J
Joao Moreno 已提交
320 321 322 323 324 325 326 327 328 329
		let uriToOpen: Uri | undefined;

		if (resource) {
			uriToOpen = resource.resourceUri;
		} else if (uri && uri.scheme === 'git') {
			const { path } = fromGitUri(uri);
			uriToOpen = Uri.file(path);
		} else if (uri && uri.scheme === 'file') {
			uriToOpen = uri;
		}
330

J
Joao Moreno 已提交
331
		if (!uriToOpen) {
332 333 334
			return;
		}

J
Joao Moreno 已提交
335
		return await commands.executeCommand<void>('vscode.open', uriToOpen);
336 337
	}

J
Joao Moreno 已提交
338
	@command('git.stage')
339
	async stage(...resourceStates: SourceControlResourceState[]): Promise<void> {
J
Joao Moreno 已提交
340
		if (resourceStates.length === 0 || !(resourceStates[0].resourceUri instanceof Uri)) {
341
			const resource = this.getSCMResource();
342 343 344 345 346 347 348 349

			if (!resource) {
				return;
			}

			resourceStates = [resource];
		}

350 351 352
		const resources = resourceStates
			.filter(s => s instanceof Resource && (s.resourceGroup instanceof WorkingTreeGroup || s.resourceGroup instanceof MergeGroup)) as Resource[];

353
		if (!resources.length) {
J
Joao Moreno 已提交
354 355
			return;
		}
J
Joao Moreno 已提交
356

357
		return await this.model.add(...resources);
J
Joao Moreno 已提交
358 359
	}

J
Joao Moreno 已提交
360
	@command('git.stageAll')
J
Joao Moreno 已提交
361
	async stageAll(): Promise<void> {
J
Joao Moreno 已提交
362 363 364
		return await this.model.add();
	}

365 366
	@command('git.stageSelectedRanges', false, true)
	async stageSelectedRanges(diffs: LineChange[]): Promise<void> {
J
Joao Moreno 已提交
367 368 369 370 371 372 373 374 375
		const textEditor = window.activeTextEditor;

		if (!textEditor) {
			return;
		}

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

J
Joao Moreno 已提交
376
		if (modifiedUri.scheme !== 'file') {
J
Joao Moreno 已提交
377 378 379
			return;
		}

J
Joao Moreno 已提交
380
		const originalUri = toGitUri(modifiedUri, '~');
J
Joao Moreno 已提交
381
		const originalDocument = await workspace.openTextDocument(originalUri);
382 383 384 385
		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 已提交
386 387 388 389 390

		if (!selectedDiffs.length) {
			return;
		}

391 392
		const result = applyLineChanges(originalDocument, modifiedDocument, selectedDiffs);

J
Joao Moreno 已提交
393
		await this.model.stage(modifiedUri, result);
J
Joao Moreno 已提交
394
	}
J
Joao Moreno 已提交
395

396 397
	@command('git.revertSelectedRanges', false, true)
	async revertSelectedRanges(diffs: LineChange[]): Promise<void> {
J
Joao Moreno 已提交
398 399 400 401 402 403 404 405 406 407 408 409 410
		const textEditor = window.activeTextEditor;

		if (!textEditor) {
			return;
		}

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

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

J
Joao Moreno 已提交
411
		const originalUri = toGitUri(modifiedUri, '~');
J
Joao Moreno 已提交
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
		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;
		}

435
		const result = applyLineChanges(originalDocument, modifiedDocument, selectedDiffs);
J
Joao Moreno 已提交
436 437 438 439 440
		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 已提交
441
	@command('git.unstage')
442
	async unstage(...resourceStates: SourceControlResourceState[]): Promise<void> {
J
Joao Moreno 已提交
443
		if (resourceStates.length === 0 || !(resourceStates[0].resourceUri instanceof Uri)) {
444
			const resource = this.getSCMResource();
445 446 447 448 449 450 451 452

			if (!resource) {
				return;
			}

			resourceStates = [resource];
		}

453 454 455
		const resources = resourceStates
			.filter(s => s instanceof Resource && s.resourceGroup instanceof IndexGroup) as Resource[];

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

460
		return await this.model.revertFiles(...resources);
J
Joao Moreno 已提交
461 462
	}

J
Joao Moreno 已提交
463
	@command('git.unstageAll')
J
Joao Moreno 已提交
464
	async unstageAll(): Promise<void> {
J
Joao Moreno 已提交
465
		return await this.model.revertFiles();
J
Joao Moreno 已提交
466
	}
J
Joao Moreno 已提交
467

468 469
	@command('git.unstageSelectedRanges', false, true)
	async unstageSelectedRanges(diffs: LineChange[]): Promise<void> {
J
Joao Moreno 已提交
470 471 472 473 474 475 476 477 478
		const textEditor = window.activeTextEditor;

		if (!textEditor) {
			return;
		}

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

479 480 481 482 483 484 485
		if (modifiedUri.scheme !== 'git') {
			return;
		}

		const { ref } = fromGitUri(modifiedUri);

		if (ref !== '') {
J
Joao Moreno 已提交
486 487 488
			return;
		}

J
Joao Moreno 已提交
489
		const originalUri = toGitUri(modifiedUri, 'HEAD');
J
Joao Moreno 已提交
490
		const originalDocument = await workspace.openTextDocument(originalUri);
491 492 493 494
		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 已提交
495 496 497 498 499

		if (!selectedDiffs.length) {
			return;
		}

500 501
		const invertedDiffs = selectedDiffs.map(invertLineChange);
		const result = applyLineChanges(modifiedDocument, originalDocument, invertedDiffs);
J
Joao Moreno 已提交
502 503 504 505

		await this.model.stage(modifiedUri, result);
	}

J
Joao Moreno 已提交
506
	@command('git.clean')
507
	async clean(...resourceStates: SourceControlResourceState[]): Promise<void> {
J
Joao Moreno 已提交
508
		if (resourceStates.length === 0 || !(resourceStates[0].resourceUri instanceof Uri)) {
509
			const resource = this.getSCMResource();
510 511 512 513 514 515 516 517

			if (!resource) {
				return;
			}

			resourceStates = [resource];
		}

518 519 520
		const resources = resourceStates
			.filter(s => s instanceof Resource && s.resourceGroup instanceof WorkingTreeGroup) as Resource[];

521
		if (!resources.length) {
J
Joao Moreno 已提交
522 523
			return;
		}
J
Joao Moreno 已提交
524

525
		const message = resources.length === 1
J
Joao Moreno 已提交
526
			? localize('confirm discard', "Are you sure you want to discard changes in {0}?", path.basename(resources[0].resourceUri.fsPath))
527 528
			: localize('confirm discard multiple', "Are you sure you want to discard changes in {0} files?", resources.length);

529
		const yes = localize('discard', "Discard Changes");
J
Joao Moreno 已提交
530
		const pick = await window.showWarningMessage(message, { modal: true }, yes);
J
Joao Moreno 已提交
531

J
Joao Moreno 已提交
532 533 534 535
		if (pick !== yes) {
			return;
		}

536
		await this.model.clean(...resources);
J
Joao Moreno 已提交
537
	}
J
Joao Moreno 已提交
538

J
Joao Moreno 已提交
539
	@command('git.cleanAll')
J
Joao Moreno 已提交
540
	async cleanAll(): Promise<void> {
541 542
		const message = localize('confirm discard all', "Are you sure you want to discard ALL changes? This is IRREVERSIBLE!");
		const yes = localize('discardAll', "Discard ALL Changes");
J
Joao Moreno 已提交
543
		const pick = await window.showWarningMessage(message, { modal: true }, yes);
J
Joao Moreno 已提交
544 545 546 547 548

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

J
Joao Moreno 已提交
549
		await this.model.clean(...this.model.workingTreeGroup.resources);
J
Joao Moreno 已提交
550 551
	}

J
Joao Moreno 已提交
552
	private async smartCommit(
553
		getCommitMessage: () => Promise<string | undefined>,
J
Joao Moreno 已提交
554 555
		opts?: CommitOptions
	): Promise<boolean> {
556 557 558
		const config = workspace.getConfiguration('git');
		const enableSmartCommit = config.get<boolean>('enableSmartCommit') === true;
		const noStagedChanges = this.model.indexGroup.resources.length === 0;
559
		const noUnstagedChanges = this.model.workingTreeGroup.resources.length === 0;
560 561

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

J
Joao Moreno 已提交
564 565
			// 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?");
566 567 568 569 570
			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 已提交
571 572 573
				config.update('enableSmartCommit', true, true);
			} else if (pick !== yes) {
				return false; // do not commit on cancel
574 575 576
			}
		}

J
Joao Moreno 已提交
577
		if (!opts) {
578
			opts = { all: noStagedChanges };
J
Joao Moreno 已提交
579 580 581 582
		}

		if (
			// no changes
583
			(noStagedChanges && noUnstagedChanges)
J
Joao Moreno 已提交
584
			// or no staged changes and not `all`
585
			|| (!opts.all && noStagedChanges)
J
Joao Moreno 已提交
586
		) {
J
Joao Moreno 已提交
587 588 589 590
			window.showInformationMessage(localize('no changes', "There are no changes to commit."));
			return false;
		}

J
Joao Moreno 已提交
591
		const message = await getCommitMessage();
J
Joao Moreno 已提交
592 593 594 595 596 597

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

J
Joao Moreno 已提交
598
		await this.model.commit(message, opts);
J
Joao Moreno 已提交
599 600 601 602

		return true;
	}

J
Joao Moreno 已提交
603
	private async commitWithAnyInput(opts?: CommitOptions): Promise<void> {
604
		const message = scm.inputBox.value;
J
Joao Moreno 已提交
605
		const getCommitMessage = async () => {
J
Joao Moreno 已提交
606 607 608 609 610 611
			if (message) {
				return message;
			}

			return await window.showInputBox({
				placeHolder: localize('commit message', "Commit message"),
J
Joao Moreno 已提交
612 613
				prompt: localize('provide commit message', "Please provide a commit message"),
				ignoreFocusOut: true
J
Joao Moreno 已提交
614
			});
J
Joao Moreno 已提交
615 616 617
		};

		const didCommit = await this.smartCommit(getCommitMessage, opts);
J
Joao Moreno 已提交
618 619

		if (message && didCommit) {
J
Joao Moreno 已提交
620
			scm.inputBox.value = await this.model.getCommitTemplate();
J
Joao Moreno 已提交
621
		}
J
Joao Moreno 已提交
622 623
	}

J
Joao Moreno 已提交
624
	@command('git.commit')
J
Joao Moreno 已提交
625 626 627 628
	async commit(): Promise<void> {
		await this.commitWithAnyInput();
	}

J
Joao Moreno 已提交
629
	@command('git.commitWithInput')
J
Joao Moreno 已提交
630
	async commitWithInput(): Promise<void> {
J
Joao Moreno 已提交
631 632 633 634
		if (!scm.inputBox.value) {
			return;
		}

J
Joao Moreno 已提交
635
		const didCommit = await this.smartCommit(async () => scm.inputBox.value);
J
Joao Moreno 已提交
636 637

		if (didCommit) {
J
Joao Moreno 已提交
638
			scm.inputBox.value = await this.model.getCommitTemplate();
J
Joao Moreno 已提交
639
		}
J
Joao Moreno 已提交
640 641
	}

J
Joao Moreno 已提交
642
	@command('git.commitStaged')
J
Joao Moreno 已提交
643
	async commitStaged(): Promise<void> {
J
Joao Moreno 已提交
644
		await this.commitWithAnyInput({ all: false });
J
Joao Moreno 已提交
645 646
	}

J
Joao Moreno 已提交
647
	@command('git.commitStagedSigned')
J
Joao Moreno 已提交
648
	async commitStagedSigned(): Promise<void> {
J
Joao Moreno 已提交
649
		await this.commitWithAnyInput({ all: false, signoff: true });
J
Joao Moreno 已提交
650 651
	}

J
Joao Moreno 已提交
652
	@command('git.commitAll')
J
Joao Moreno 已提交
653
	async commitAll(): Promise<void> {
J
Joao Moreno 已提交
654
		await this.commitWithAnyInput({ all: true });
J
Joao Moreno 已提交
655 656
	}

J
Joao Moreno 已提交
657
	@command('git.commitAllSigned')
J
Joao Moreno 已提交
658
	async commitAllSigned(): Promise<void> {
J
Joao Moreno 已提交
659
		await this.commitWithAnyInput({ all: true, signoff: true });
J
Joao Moreno 已提交
660 661
	}

J
Joao Moreno 已提交
662
	@command('git.undoCommit')
J
Joao Moreno 已提交
663
	async undoCommit(): Promise<void> {
J
Joao Moreno 已提交
664 665 666 667 668 669 670 671 672
		const HEAD = this.model.HEAD;

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

		const commit = await this.model.getCommit('HEAD');
		await this.model.reset('HEAD~');
		scm.inputBox.value = commit.message;
J
Joao Moreno 已提交
673 674
	}

J
Joao Moreno 已提交
675
	@command('git.checkout')
J
Joao Moreno 已提交
676 677 678 679 680
	async checkout(treeish: string): Promise<void> {
		if (typeof treeish === 'string') {
			return await this.model.checkout(treeish);
		}

J
Joao Moreno 已提交
681
		const config = workspace.getConfiguration('git');
J
Joao Moreno 已提交
682
		const checkoutType = config.get<string>('checkoutType') || 'all';
J
Joao Moreno 已提交
683 684 685 686 687 688 689 690 691 692 693 694
		const includeTags = checkoutType === 'all' || checkoutType === 'tags';
		const includeRemotes = checkoutType === 'all' || checkoutType === 'remote';

		const heads = this.model.refs.filter(ref => ref.type === RefType.Head)
			.map(ref => new CheckoutItem(ref));

		const tags = (includeTags ? this.model.refs.filter(ref => ref.type === RefType.Tag) : [])
			.map(ref => new CheckoutTagItem(ref));

		const remoteHeads = (includeRemotes ? this.model.refs.filter(ref => ref.type === RefType.RemoteHead) : [])
			.map(ref => new CheckoutRemoteHeadItem(ref));

J
Joao Moreno 已提交
695 696 697
		const picks = [...heads, ...tags, ...remoteHeads];
		const placeHolder = 'Select a ref to checkout';
		const choice = await window.showQuickPick<CheckoutItem>(picks, { placeHolder });
J
Joao Moreno 已提交
698 699 700 701 702 703

		if (!choice) {
			return;
		}

		await choice.run(this.model);
J
Joao Moreno 已提交
704 705
	}

J
Joao Moreno 已提交
706
	@command('git.branch')
J
Joao Moreno 已提交
707 708
	async branch(): Promise<void> {
		const result = await window.showInputBox({
J
Joao Moreno 已提交
709
			placeHolder: localize('branch name', "Branch name"),
J
Joao Moreno 已提交
710 711
			prompt: localize('provide branch name', "Please provide a branch name"),
			ignoreFocusOut: true
J
Joao Moreno 已提交
712
		});
J
Joao Moreno 已提交
713

J
Joao Moreno 已提交
714 715 716
		if (!result) {
			return;
		}
J
Joao Moreno 已提交
717

J
Joao Moreno 已提交
718 719
		const name = result.replace(/^\.|\/\.|\.\.|~|\^|:|\/$|\.lock$|\.lock\/|\\|\*|\s|^\s*$|\.$/g, '-');
		await this.model.branch(name);
J
Joao Moreno 已提交
720 721
	}

M
Maik Riechert 已提交
722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740
	@command('git.deleteBranch')
	async deleteBranch(branchName: string): Promise<void> {
		if (typeof branchName === 'string') {
			return await this.model.deleteBranch(branchName);
		}
		const currentHead = this.model.HEAD && this.model.HEAD.name;
		const heads = this.model.refs.filter(ref => ref.type === RefType.Head && ref.name !== currentHead)
			.map(ref => new BranchDeleteItem(ref));

		const placeHolder = 'Select a branch to delete';
		const choice = await window.showQuickPick<BranchDeleteItem>(heads, { placeHolder });

		if (!choice) {
			return;
		}

		await choice.run(this.model);
	}

J
Joao Moreno 已提交
741
	@command('git.pull')
J
Joao Moreno 已提交
742
	async pull(): Promise<void> {
J
Joao Moreno 已提交
743 744 745 746 747 748 749 750
		const remotes = this.model.remotes;

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

		await this.model.pull();
J
Joao Moreno 已提交
751 752
	}

J
Joao Moreno 已提交
753
	@command('git.pullRebase')
J
Joao Moreno 已提交
754
	async pullRebase(): Promise<void> {
J
Joao Moreno 已提交
755 756 757 758 759 760 761 762
		const remotes = this.model.remotes;

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

		await this.model.pull(true);
J
Joao Moreno 已提交
763 764
	}

J
Joao Moreno 已提交
765
	@command('git.push')
J
Joao Moreno 已提交
766
	async push(): Promise<void> {
J
Joao Moreno 已提交
767 768 769 770 771 772 773 774
		const remotes = this.model.remotes;

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

		await this.model.push();
J
Joao Moreno 已提交
775 776
	}

J
Joao Moreno 已提交
777
	@command('git.pushTo')
J
Joao Moreno 已提交
778
	async pushTo(): Promise<void> {
J
Joao Moreno 已提交
779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800
		const remotes = this.model.remotes;

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

		if (!this.model.HEAD || !this.model.HEAD.name) {
			window.showWarningMessage(localize('nobranch', "Please check out a branch to push to a remote."));
			return;
		}

		const branchName = this.model.HEAD.name;
		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;
		}

		this.model.push(pick.label, branchName);
J
Joao Moreno 已提交
801 802
	}

J
Joao Moreno 已提交
803
	@command('git.sync')
J
Joao Moreno 已提交
804
	async sync(): Promise<void> {
J
Joao Moreno 已提交
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826
		const HEAD = this.model.HEAD;

		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 已提交
827 828 829
		await this.model.sync();
	}

J
Joao Moreno 已提交
830
	@command('git.publish')
J
Joao Moreno 已提交
831
	async publish(): Promise<void> {
J
Joao Moreno 已提交
832 833 834 835 836 837 838
		const remotes = this.model.remotes;

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

J
Joao Moreno 已提交
839 840
		const branchName = this.model.HEAD && this.model.HEAD.name || '';
		const picks = this.model.remotes.map(r => r.name);
J
Joao Moreno 已提交
841
		const placeHolder = localize('pick remote', "Pick a remote to publish the branch '{0}' to:", branchName);
J
Joao Moreno 已提交
842 843 844 845 846 847 848 849 850
		const choice = await window.showQuickPick(picks, { placeHolder });

		if (!choice) {
			return;
		}

		await this.model.push(choice, branchName, { setUpstream: true });
	}

J
Joao Moreno 已提交
851
	@command('git.showOutput')
J
Joao Moreno 已提交
852 853 854 855
	showOutput(): void {
		this.outputChannel.show();
	}

J
Joao Moreno 已提交
856
	private createCommand(id: string, key: string, method: Function, skipModelCheck: boolean): (...args: any[]) => any {
857
		const result = (...args) => {
J
Joao Moreno 已提交
858
			if (!skipModelCheck && !this.model) {
J
Joao Moreno 已提交
859 860 861 862
				window.showInformationMessage(localize('disabled', "Git is either disabled or not supported in this workspace"));
				return;
			}

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

J
Joao Moreno 已提交
865 866 867 868 869 870
			const result = Promise.resolve(method.apply(this, args));

			return result.catch(async err => {
				let message: string;

				switch (err.gitErrorCode) {
871
					case GitErrorCodes.DirtyWorkTree:
J
Joao Moreno 已提交
872 873
						message = localize('clean repo', "Please clean your repository working tree before checkout.");
						break;
874 875 876
					case GitErrorCodes.PushRejected:
						message = localize('cant push', "Can't push refs to remote. Run 'Pull' first to integrate your changes.");
						break;
J
Joao Moreno 已提交
877
					default:
878 879 880
						const hint = (err.stderr || err.message || String(err))
							.replace(/^error: /mi, '')
							.replace(/^> husky.*$/mi, '')
J
Joao Moreno 已提交
881
							.split(/[\r\n]/)
882 883 884 885 886 887
							.filter(line => !!line)
						[0];

						message = hint
							? localize('git error details', "Git: {0}", hint)
							: localize('git error', "Git error");
J
Joao Moreno 已提交
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905

						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();
				}
			});
		};
906 907 908 909 910

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

		return result;
J
Joao Moreno 已提交
911 912
	}

913 914
	private getSCMResource(uri?: Uri): Resource | undefined {
		uri = uri ? uri : window.activeTextEditor && window.activeTextEditor.document.uri;
J
Joao Moreno 已提交
915 916

		if (!uri) {
917
			return undefined;
J
Joao Moreno 已提交
918 919 920
		}

		if (uri.scheme === 'git') {
J
Joao Moreno 已提交
921 922
			const { path } = fromGitUri(uri);
			uri = Uri.file(path);
J
Joao Moreno 已提交
923 924 925 926 927
		}

		if (uri.scheme === 'file') {
			const uriString = uri.toString();

J
Joao Moreno 已提交
928 929
			return this.model.workingTreeGroup.resources.filter(r => r.resourceUri.toString() === uriString)[0]
				|| this.model.indexGroup.resources.filter(r => r.resourceUri.toString() === uriString)[0];
J
Joao Moreno 已提交
930 931 932
		}
	}

J
Joao Moreno 已提交
933 934 935
	dispose(): void {
		this.disposables.forEach(d => d.dispose());
	}
J
Joao Moreno 已提交
936
}