commands.ts 27.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';
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
class BranchDeleteItem implements QuickPickItem {

65 66 67
	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 已提交
68 69
	get description(): string { return this.shortCommit; }

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

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

80 81 82 83 84 85 86 87 88
interface Command {
	commandId: string;
	key: string;
	method: Function;
	skipModelCheck: boolean;
	requiresDiffInformation: boolean;
}

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

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

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

J
Joao Moreno 已提交
100
export class CommandCenter {
J
Joao Moreno 已提交
101

J
Joao Moreno 已提交
102
	private model: Model;
J
Joao Moreno 已提交
103
	private disposables: Disposable[];
J
Joao Moreno 已提交
104

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

J
Joao Moreno 已提交
115
		this.disposables = Commands
116 117 118 119 120 121 122 123 124
			.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 已提交
125 126
	}

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

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

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

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

J
Joao Moreno 已提交
148 149
		const viewColumn = window.activeTextEditor && window.activeTextEditor.viewColumn || ViewColumn.One;

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

J
Joao Moreno 已提交
154 155 156 157 158 159
		const opts: TextDocumentShowOptions = {
			preview: true,
			viewColumn
		};

		return await commands.executeCommand<void>('vscode.diff', left, right, title, opts);
J
Joao Moreno 已提交
160 161 162 163 164 165
	}

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

			case Status.MODIFIED:
J
Joao Moreno 已提交
169
				return toGitUri(resource.resourceUri, '~');
J
Joao Moreno 已提交
170
		}
J
Joao Moreno 已提交
171
	}
J
Joao Moreno 已提交
172

J
Joao Moreno 已提交
173 174 175 176 177 178
	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 已提交
179
				return toGitUri(resource.resourceUri, '');
J
Joao Moreno 已提交
180 181 182

			case Status.INDEX_DELETED:
			case Status.DELETED:
J
Joao Moreno 已提交
183
				return toGitUri(resource.resourceUri, 'HEAD');
J
Joao Moreno 已提交
184 185 186 187

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

J
Joao Moreno 已提交
191 192
				if (indexStatus && indexStatus.renameResourceUri) {
					return indexStatus.renameResourceUri;
J
Joao Moreno 已提交
193 194
				}

J
Joao Moreno 已提交
195
				return resource.resourceUri;
J
Joao Moreno 已提交
196

J
Joao Moreno 已提交
197
			case Status.BOTH_MODIFIED:
J
Joao Moreno 已提交
198
				return resource.resourceUri;
J
Joao Moreno 已提交
199 200 201 202
		}
	}

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

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

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

		return '';
	}

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

		if (!url) {
225 226
			this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'no_URL' });
			return;
J
Joao Moreno 已提交
227 228
		}

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

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

		if (!parentPath) {
239 240
			this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'no_directory' });
			return;
J
Joao Moreno 已提交
241 242
		}

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

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

J
Joao Moreno 已提交
267 268 269 270 271
	@command('git.init')
	async init(): Promise<void> {
		await this.model.init();
	}

J
Joao Moreno 已提交
272
	@command('git.openFile')
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
	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 已提交
293 294
		}

295
		if (!uri) {
J
Joao Moreno 已提交
296
			return;
J
Joao Moreno 已提交
297 298
		}

J
Joao Moreno 已提交
299 300 301
		const viewColumn = window.activeTextEditor && window.activeTextEditor.viewColumn || ViewColumn.One;

		return await commands.executeCommand<void>('vscode.open', uri, viewColumn);
J
Joao Moreno 已提交
302 303 304
	}

	@command('git.openChange')
305 306 307 308 309 310 311 312
	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 已提交
313 314 315
			resource = this.getSCMResource();
		}

J
Joao Moreno 已提交
316 317
		if (!resource) {
			return;
J
Joao Moreno 已提交
318 319
		}

J
Joao Moreno 已提交
320
		return await this._openResource(resource);
J
Joao Moreno 已提交
321 322
	}

323 324 325
	@command('git.openFileFromUri')
	async openFileFromUri(uri?: Uri): Promise<void> {
		const resource = this.getSCMResource(uri);
J
Joao Moreno 已提交
326 327 328 329 330 331 332 333 334 335
		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;
		}
336

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

J
Joao Moreno 已提交
341 342 343
		const viewColumn = window.activeTextEditor && window.activeTextEditor.viewColumn || ViewColumn.One;

		return await commands.executeCommand<void>('vscode.open', uriToOpen, viewColumn);
344 345
	}

J
Joao Moreno 已提交
346
	@command('git.stage')
347
	async stage(...resourceStates: SourceControlResourceState[]): Promise<void> {
J
Joao Moreno 已提交
348
		if (resourceStates.length === 0 || !(resourceStates[0].resourceUri instanceof Uri)) {
349
			const resource = this.getSCMResource();
350 351 352 353 354 355 356 357

			if (!resource) {
				return;
			}

			resourceStates = [resource];
		}

358 359 360
		const resources = resourceStates
			.filter(s => s instanceof Resource && (s.resourceGroup instanceof WorkingTreeGroup || s.resourceGroup instanceof MergeGroup)) as Resource[];

361
		if (!resources.length) {
J
Joao Moreno 已提交
362 363
			return;
		}
J
Joao Moreno 已提交
364

365
		return await this.model.add(...resources);
J
Joao Moreno 已提交
366 367
	}

J
Joao Moreno 已提交
368
	@command('git.stageAll')
J
Joao Moreno 已提交
369
	async stageAll(): Promise<void> {
J
Joao Moreno 已提交
370 371 372
		return await this.model.add();
	}

373 374
	@command('git.stageSelectedRanges', false, true)
	async stageSelectedRanges(diffs: LineChange[]): Promise<void> {
J
Joao Moreno 已提交
375 376 377 378 379 380 381 382 383
		const textEditor = window.activeTextEditor;

		if (!textEditor) {
			return;
		}

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

J
Joao Moreno 已提交
384
		if (modifiedUri.scheme !== 'file') {
J
Joao Moreno 已提交
385 386 387
			return;
		}

J
Joao Moreno 已提交
388
		const originalUri = toGitUri(modifiedUri, '~');
J
Joao Moreno 已提交
389
		const originalDocument = await workspace.openTextDocument(originalUri);
390 391 392 393
		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 已提交
394 395 396 397 398

		if (!selectedDiffs.length) {
			return;
		}

399 400
		const result = applyLineChanges(originalDocument, modifiedDocument, selectedDiffs);

J
Joao Moreno 已提交
401
		await this.model.stage(modifiedUri, result);
J
Joao Moreno 已提交
402
	}
J
Joao Moreno 已提交
403

404 405
	@command('git.revertSelectedRanges', false, true)
	async revertSelectedRanges(diffs: LineChange[]): Promise<void> {
J
Joao Moreno 已提交
406 407 408 409 410 411 412 413 414 415 416 417 418
		const textEditor = window.activeTextEditor;

		if (!textEditor) {
			return;
		}

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

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

J
Joao Moreno 已提交
419
		const originalUri = toGitUri(modifiedUri, '~');
J
Joao Moreno 已提交
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
		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;
		}

443
		const result = applyLineChanges(originalDocument, modifiedDocument, selectedDiffs);
J
Joao Moreno 已提交
444 445 446 447 448
		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 已提交
449
	@command('git.unstage')
450
	async unstage(...resourceStates: SourceControlResourceState[]): Promise<void> {
J
Joao Moreno 已提交
451
		if (resourceStates.length === 0 || !(resourceStates[0].resourceUri instanceof Uri)) {
452
			const resource = this.getSCMResource();
453 454 455 456 457 458 459 460

			if (!resource) {
				return;
			}

			resourceStates = [resource];
		}

461 462 463
		const resources = resourceStates
			.filter(s => s instanceof Resource && s.resourceGroup instanceof IndexGroup) as Resource[];

464
		if (!resources.length) {
J
Joao Moreno 已提交
465 466 467
			return;
		}

468
		return await this.model.revertFiles(...resources);
J
Joao Moreno 已提交
469 470
	}

J
Joao Moreno 已提交
471
	@command('git.unstageAll')
J
Joao Moreno 已提交
472
	async unstageAll(): Promise<void> {
J
Joao Moreno 已提交
473
		return await this.model.revertFiles();
J
Joao Moreno 已提交
474
	}
J
Joao Moreno 已提交
475

476 477
	@command('git.unstageSelectedRanges', false, true)
	async unstageSelectedRanges(diffs: LineChange[]): Promise<void> {
J
Joao Moreno 已提交
478 479 480 481 482 483 484 485 486
		const textEditor = window.activeTextEditor;

		if (!textEditor) {
			return;
		}

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

487 488 489 490 491 492 493
		if (modifiedUri.scheme !== 'git') {
			return;
		}

		const { ref } = fromGitUri(modifiedUri);

		if (ref !== '') {
J
Joao Moreno 已提交
494 495 496
			return;
		}

J
Joao Moreno 已提交
497
		const originalUri = toGitUri(modifiedUri, 'HEAD');
J
Joao Moreno 已提交
498
		const originalDocument = await workspace.openTextDocument(originalUri);
499 500 501 502
		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 已提交
503 504 505 506 507

		if (!selectedDiffs.length) {
			return;
		}

508 509
		const invertedDiffs = selectedDiffs.map(invertLineChange);
		const result = applyLineChanges(modifiedDocument, originalDocument, invertedDiffs);
J
Joao Moreno 已提交
510 511 512 513

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

J
Joao Moreno 已提交
514
	@command('git.clean')
515
	async clean(...resourceStates: SourceControlResourceState[]): Promise<void> {
J
Joao Moreno 已提交
516
		if (resourceStates.length === 0 || !(resourceStates[0].resourceUri instanceof Uri)) {
517
			const resource = this.getSCMResource();
518 519 520 521 522 523 524 525

			if (!resource) {
				return;
			}

			resourceStates = [resource];
		}

526 527 528
		const resources = resourceStates
			.filter(s => s instanceof Resource && s.resourceGroup instanceof WorkingTreeGroup) as Resource[];

529
		if (!resources.length) {
J
Joao Moreno 已提交
530 531
			return;
		}
J
Joao Moreno 已提交
532

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

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

J
Joao Moreno 已提交
540 541 542 543
		if (pick !== yes) {
			return;
		}

544
		await this.model.clean(...resources);
J
Joao Moreno 已提交
545
	}
J
Joao Moreno 已提交
546

J
Joao Moreno 已提交
547
	@command('git.cleanAll')
J
Joao Moreno 已提交
548
	async cleanAll(): Promise<void> {
549 550
		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 已提交
551
		const pick = await window.showWarningMessage(message, { modal: true }, yes);
J
Joao Moreno 已提交
552 553 554 555 556

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

J
Joao Moreno 已提交
557
		await this.model.clean(...this.model.workingTreeGroup.resources);
J
Joao Moreno 已提交
558 559
	}

J
Joao Moreno 已提交
560
	private async smartCommit(
561
		getCommitMessage: () => Promise<string | undefined>,
J
Joao Moreno 已提交
562 563
		opts?: CommitOptions
	): Promise<boolean> {
564 565 566
		const config = workspace.getConfiguration('git');
		const enableSmartCommit = config.get<boolean>('enableSmartCommit') === true;
		const noStagedChanges = this.model.indexGroup.resources.length === 0;
567
		const noUnstagedChanges = this.model.workingTreeGroup.resources.length === 0;
568 569

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

J
Joao Moreno 已提交
572 573
			// 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?");
574 575 576 577 578
			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 已提交
579 580 581
				config.update('enableSmartCommit', true, true);
			} else if (pick !== yes) {
				return false; // do not commit on cancel
582 583 584
			}
		}

J
Joao Moreno 已提交
585
		if (!opts) {
586
			opts = { all: noStagedChanges };
J
Joao Moreno 已提交
587 588 589 590
		}

		if (
			// no changes
591
			(noStagedChanges && noUnstagedChanges)
J
Joao Moreno 已提交
592
			// or no staged changes and not `all`
593
			|| (!opts.all && noStagedChanges)
J
Joao Moreno 已提交
594
		) {
J
Joao Moreno 已提交
595 596 597 598
			window.showInformationMessage(localize('no changes', "There are no changes to commit."));
			return false;
		}

J
Joao Moreno 已提交
599
		const message = await getCommitMessage();
J
Joao Moreno 已提交
600 601 602 603 604 605

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

J
Joao Moreno 已提交
606
		await this.model.commit(message, opts);
J
Joao Moreno 已提交
607 608 609 610

		return true;
	}

J
Joao Moreno 已提交
611
	private async commitWithAnyInput(opts?: CommitOptions): Promise<void> {
612
		const message = scm.inputBox.value;
J
Joao Moreno 已提交
613
		const getCommitMessage = async () => {
J
Joao Moreno 已提交
614 615 616 617 618 619
			if (message) {
				return message;
			}

			return await window.showInputBox({
				placeHolder: localize('commit message', "Commit message"),
J
Joao Moreno 已提交
620 621
				prompt: localize('provide commit message', "Please provide a commit message"),
				ignoreFocusOut: true
J
Joao Moreno 已提交
622
			});
J
Joao Moreno 已提交
623 624 625
		};

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

		if (message && didCommit) {
J
Joao Moreno 已提交
628
			scm.inputBox.value = await this.model.getCommitTemplate();
J
Joao Moreno 已提交
629
		}
J
Joao Moreno 已提交
630 631
	}

J
Joao Moreno 已提交
632
	@command('git.commit')
J
Joao Moreno 已提交
633 634 635 636
	async commit(): Promise<void> {
		await this.commitWithAnyInput();
	}

J
Joao Moreno 已提交
637
	@command('git.commitWithInput')
J
Joao Moreno 已提交
638
	async commitWithInput(): Promise<void> {
J
Joao Moreno 已提交
639 640 641 642
		if (!scm.inputBox.value) {
			return;
		}

J
Joao Moreno 已提交
643
		const didCommit = await this.smartCommit(async () => scm.inputBox.value);
J
Joao Moreno 已提交
644 645

		if (didCommit) {
J
Joao Moreno 已提交
646
			scm.inputBox.value = await this.model.getCommitTemplate();
J
Joao Moreno 已提交
647
		}
J
Joao Moreno 已提交
648 649
	}

J
Joao Moreno 已提交
650
	@command('git.commitStaged')
J
Joao Moreno 已提交
651
	async commitStaged(): Promise<void> {
J
Joao Moreno 已提交
652
		await this.commitWithAnyInput({ all: false });
J
Joao Moreno 已提交
653 654
	}

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

J
Joao Moreno 已提交
660
	@command('git.commitAll')
J
Joao Moreno 已提交
661
	async commitAll(): Promise<void> {
J
Joao Moreno 已提交
662
		await this.commitWithAnyInput({ all: true });
J
Joao Moreno 已提交
663 664
	}

J
Joao Moreno 已提交
665
	@command('git.commitAllSigned')
J
Joao Moreno 已提交
666
	async commitAllSigned(): Promise<void> {
J
Joao Moreno 已提交
667
		await this.commitWithAnyInput({ all: true, signoff: true });
J
Joao Moreno 已提交
668 669
	}

J
Joao Moreno 已提交
670
	@command('git.undoCommit')
J
Joao Moreno 已提交
671
	async undoCommit(): Promise<void> {
J
Joao Moreno 已提交
672 673 674 675 676 677 678 679 680
		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 已提交
681 682
	}

J
Joao Moreno 已提交
683
	@command('git.checkout')
J
Joao Moreno 已提交
684 685 686 687 688
	async checkout(treeish: string): Promise<void> {
		if (typeof treeish === 'string') {
			return await this.model.checkout(treeish);
		}

J
Joao Moreno 已提交
689
		const config = workspace.getConfiguration('git');
J
Joao Moreno 已提交
690
		const checkoutType = config.get<string>('checkoutType') || 'all';
J
Joao Moreno 已提交
691 692 693 694 695 696 697 698 699 700 701 702
		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 已提交
703 704 705
		const picks = [...heads, ...tags, ...remoteHeads];
		const placeHolder = 'Select a ref to checkout';
		const choice = await window.showQuickPick<CheckoutItem>(picks, { placeHolder });
J
Joao Moreno 已提交
706 707 708 709 710 711

		if (!choice) {
			return;
		}

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

J
Joao Moreno 已提交
714
	@command('git.branch')
J
Joao Moreno 已提交
715 716
	async branch(): Promise<void> {
		const result = await window.showInputBox({
J
Joao Moreno 已提交
717
			placeHolder: localize('branch name', "Branch name"),
J
Joao Moreno 已提交
718 719
			prompt: localize('provide branch name', "Please provide a branch name"),
			ignoreFocusOut: true
J
Joao Moreno 已提交
720
		});
J
Joao Moreno 已提交
721

J
Joao Moreno 已提交
722 723 724
		if (!result) {
			return;
		}
J
Joao Moreno 已提交
725

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

M
Maik Riechert 已提交
730
	@command('git.deleteBranch')
731 732 733 734 735 736 737 738
	async deleteBranch(name: string, force?: boolean): Promise<void> {
		let run: (force?: boolean) => Promise<void>;
		if (typeof name === 'string') {
			run = force => this.model.deleteBranch(name, force);
		} else {
			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));
M
Maik Riechert 已提交
739

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

M
Maik Riechert 已提交
743
			if (!choice || !choice.branchName) {
744 745
				return;
			}
M
Maik Riechert 已提交
746
			name = choice.branchName;
747
			run = force => choice.run(this.model, force);
M
Maik Riechert 已提交
748 749
		}

750 751 752 753 754 755 756 757 758 759 760 761 762 763 764
		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 已提交
765 766
	}

J
Joao Moreno 已提交
767
	@command('git.pull')
J
Joao Moreno 已提交
768
	async pull(): Promise<void> {
J
Joao Moreno 已提交
769 770 771 772 773 774 775 776
		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 已提交
777 778
	}

J
Joao Moreno 已提交
779
	@command('git.pullRebase')
J
Joao Moreno 已提交
780
	async pullRebase(): Promise<void> {
J
Joao Moreno 已提交
781 782 783 784 785 786 787
		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;
		}

J
Joao Moreno 已提交
788
		await this.model.pullWithRebase();
J
Joao Moreno 已提交
789 790
	}

J
Joao Moreno 已提交
791
	@command('git.push')
J
Joao Moreno 已提交
792
	async push(): Promise<void> {
J
Joao Moreno 已提交
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;
		}

		await this.model.push();
J
Joao Moreno 已提交
801 802
	}

J
Joao Moreno 已提交
803
	@command('git.pushTo')
J
Joao Moreno 已提交
804
	async pushTo(): 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
		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;
		}

J
Joao Moreno 已提交
826
		this.model.pushTo(pick.label, branchName);
J
Joao Moreno 已提交
827 828
	}

J
Joao Moreno 已提交
829
	@command('git.sync')
J
Joao Moreno 已提交
830
	async sync(): Promise<void> {
J
Joao Moreno 已提交
831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852
		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 已提交
853 854 855
		await this.model.sync();
	}

J
Joao Moreno 已提交
856
	@command('git.publish')
J
Joao Moreno 已提交
857
	async publish(): Promise<void> {
J
Joao Moreno 已提交
858 859 860 861 862 863 864
		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 已提交
865 866
		const branchName = this.model.HEAD && this.model.HEAD.name || '';
		const picks = this.model.remotes.map(r => r.name);
J
Joao Moreno 已提交
867
		const placeHolder = localize('pick remote', "Pick a remote to publish the branch '{0}' to:", branchName);
J
Joao Moreno 已提交
868 869 870 871 872 873
		const choice = await window.showQuickPick(picks, { placeHolder });

		if (!choice) {
			return;
		}

J
Joao Moreno 已提交
874
		await this.model.pushTo(choice, branchName, true);
J
Joao Moreno 已提交
875 876
	}

J
Joao Moreno 已提交
877
	@command('git.showOutput')
J
Joao Moreno 已提交
878 879 880 881
	showOutput(): void {
		this.outputChannel.show();
	}

J
Joao Moreno 已提交
882
	private createCommand(id: string, key: string, method: Function, skipModelCheck: boolean): (...args: any[]) => any {
883
		const result = (...args) => {
J
Joao Moreno 已提交
884
			if (!skipModelCheck && !this.model) {
J
Joao Moreno 已提交
885 886 887 888
				window.showInformationMessage(localize('disabled', "Git is either disabled or not supported in this workspace"));
				return;
			}

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

J
Joao Moreno 已提交
891 892 893 894 895 896
			const result = Promise.resolve(method.apply(this, args));

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

				switch (err.gitErrorCode) {
897
					case GitErrorCodes.DirtyWorkTree:
J
Joao Moreno 已提交
898 899
						message = localize('clean repo', "Please clean your repository working tree before checkout.");
						break;
900 901 902
					case GitErrorCodes.PushRejected:
						message = localize('cant push', "Can't push refs to remote. Run 'Pull' first to integrate your changes.");
						break;
J
Joao Moreno 已提交
903
					default:
904 905 906
						const hint = (err.stderr || err.message || String(err))
							.replace(/^error: /mi, '')
							.replace(/^> husky.*$/mi, '')
J
Joao Moreno 已提交
907
							.split(/[\r\n]/)
908 909 910 911 912 913
							.filter(line => !!line)
						[0];

						message = hint
							? localize('git error details', "Git: {0}", hint)
							: localize('git error', "Git error");
J
Joao Moreno 已提交
914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931

						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();
				}
			});
		};
932 933 934 935 936

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

		return result;
J
Joao Moreno 已提交
937 938
	}

939 940
	private getSCMResource(uri?: Uri): Resource | undefined {
		uri = uri ? uri : window.activeTextEditor && window.activeTextEditor.document.uri;
J
Joao Moreno 已提交
941 942

		if (!uri) {
943
			return undefined;
J
Joao Moreno 已提交
944 945 946
		}

		if (uri.scheme === 'git') {
J
Joao Moreno 已提交
947 948
			const { path } = fromGitUri(uri);
			uri = Uri.file(path);
J
Joao Moreno 已提交
949 950 951 952 953
		}

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

J
Joao Moreno 已提交
954 955
			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 已提交
956 957 958
		}
	}

J
Joao Moreno 已提交
959 960 961
	dispose(): void {
		this.disposables.forEach(d => d.dispose());
	}
J
Joao Moreno 已提交
962
}