commands.ts 20.8 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, SCMResourceGroup, SCMResource, window, workspace, QuickPickItem, OutputChannel, computeDiff, Range, WorkspaceEdit, Position } from 'vscode';
J
Joao Moreno 已提交
9
import { Ref, RefType } from './git';
J
Joao Moreno 已提交
10
import { Model, Resource, Status, CommitOptions } from './model';
J
Joao Moreno 已提交
11
import * as staging from './staging';
J
Joao Moreno 已提交
12
import * as path from 'path';
J
Joao Moreno 已提交
13
import * as os from 'os';
J
Joao Moreno 已提交
14
import TelemetryReporter from 'vscode-extension-telemetry';
J
Joao Moreno 已提交
15 16 17
import * as nls from 'vscode-nls';

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

J
Joao Moreno 已提交
19 20 21 22
function resolveGitURI(uri: Uri): SCMResource | SCMResourceGroup | undefined {
	if (uri.authority !== 'git') {
		return;
	}
J
Joao Moreno 已提交
23

J
Joao Moreno 已提交
24
	return scm.getResourceFromURI(uri);
J
Joao Moreno 已提交
25 26
}

J
Joao Moreno 已提交
27 28
function resolveGitResource(uri: Uri): Resource | undefined {
	const resource = resolveGitURI(uri);
J
Joao Moreno 已提交
29

J
Joao Moreno 已提交
30 31 32
	if (!(resource instanceof Resource)) {
		return;
	}
J
Joao Moreno 已提交
33

J
Joao Moreno 已提交
34
	return resource;
J
Joao Moreno 已提交
35 36
}

J
Joao Moreno 已提交
37 38 39 40 41 42 43
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 已提交
44
	constructor(protected ref: Ref) { }
J
Joao Moreno 已提交
45 46 47 48 49 50 51 52 53 54 55 56 57 58

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

		if (!ref) {
			return;
		}

		await model.checkout(ref);
	}
}

class CheckoutTagItem extends CheckoutItem {

J
Joao Moreno 已提交
59 60 61
	get description(): string {
		return localize('tag at', "Tag at {0}", this.shortCommit);
	}
J
Joao Moreno 已提交
62 63 64 65
}

class CheckoutRemoteHeadItem extends CheckoutItem {

J
Joao Moreno 已提交
66 67 68
	get description(): string {
		return localize('remote branch at', "Remote branch at {0}", this.shortCommit);
	}
J
Joao Moreno 已提交
69 70 71 72 73 74 75 76 77 78 79

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

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

J
Joao Moreno 已提交
80
const Commands: { commandId: string; method: Function; }[] = [];
J
Joao Moreno 已提交
81

J
Joao Moreno 已提交
82 83
function command(commandId: string): Function {
	return (target: any, key: string, descriptor: any) => {
J
Joao Moreno 已提交
84 85 86 87
		if (!(typeof descriptor.value === 'function')) {
			throw new Error('not supported');
		}

J
Joao Moreno 已提交
88 89 90
		Commands.push({ commandId, method: descriptor.value });
	};
}
J
Joao Moreno 已提交
91

J
Joao Moreno 已提交
92
export class CommandCenter {
J
Joao Moreno 已提交
93

J
Joao Moreno 已提交
94
	private model: Model;
J
Joao Moreno 已提交
95
	private disposables: Disposable[];
J
Joao Moreno 已提交
96

J
Joao Moreno 已提交
97
	constructor(
J
Joao Moreno 已提交
98
		model: Model | undefined,
J
Joao Moreno 已提交
99 100
		private outputChannel: OutputChannel,
		private telemetryReporter: TelemetryReporter
J
Joao Moreno 已提交
101
	) {
J
Joao Moreno 已提交
102 103 104 105
		if (model) {
			this.model = model;
		}

J
Joao Moreno 已提交
106
		this.disposables = Commands
J
Joao Moreno 已提交
107
			.map(({ commandId, method }) => commands.registerCommand(commandId, this.createCommand(commandId, method)));
J
Joao Moreno 已提交
108 109
	}

J
Joao Moreno 已提交
110
	@command('git.refresh')
J
Joao Moreno 已提交
111
	async refresh(): Promise<void> {
J
Joao Moreno 已提交
112
		await this.model.status();
J
Joao Moreno 已提交
113
	}
J
Joao Moreno 已提交
114

J
Joao Moreno 已提交
115 116 117 118 119
	async open(resource: Resource): Promise<void> {
		const left = this.getLeftResource(resource);
		const right = this.getRightResource(resource);
		const title = this.getTitle(resource);

J
Joao Moreno 已提交
120 121 122 123 124
		if (!right) {
			// TODO
			console.error('oh no');
			return;
		}
J
Joao Moreno 已提交
125

J
Joao Moreno 已提交
126
		if (!left) {
J
Joao Moreno 已提交
127
			return await commands.executeCommand<void>('vscode.open', right);
J
Joao Moreno 已提交
128 129
		}

J
Joao Moreno 已提交
130
		return await commands.executeCommand<void>('vscode.diff', left, right, title);
J
Joao Moreno 已提交
131 132 133 134 135 136
	}

	private getLeftResource(resource: Resource): Uri | undefined {
		switch (resource.type) {
			case Status.INDEX_MODIFIED:
			case Status.INDEX_RENAMED:
J
Joao Moreno 已提交
137
				return resource.original.with({ scheme: 'git', query: 'HEAD' });
J
Joao Moreno 已提交
138 139

			case Status.MODIFIED:
140
				return resource.uri.with({ scheme: 'git', query: '~' });
J
Joao Moreno 已提交
141
		}
J
Joao Moreno 已提交
142
	}
J
Joao Moreno 已提交
143

J
Joao Moreno 已提交
144 145 146 147 148
	private getRightResource(resource: Resource): Uri | undefined {
		switch (resource.type) {
			case Status.INDEX_MODIFIED:
			case Status.INDEX_ADDED:
			case Status.INDEX_COPIED:
J
Joao Moreno 已提交
149 150
				return resource.uri.with({ scheme: 'git' });

J
Joao Moreno 已提交
151 152 153 154 155 156 157 158 159 160
			case Status.INDEX_RENAMED:
				return resource.uri.with({ scheme: 'git' });

			case Status.INDEX_DELETED:
			case Status.DELETED:
				return resource.uri.with({ scheme: 'git', query: 'HEAD' });

			case Status.MODIFIED:
			case Status.UNTRACKED:
			case Status.IGNORED:
J
Joao Moreno 已提交
161 162 163 164 165 166 167 168 169
				const uriString = resource.uri.toString();
				const [indexStatus] = this.model.indexGroup.resources.filter(r => r.uri.toString() === uriString);

				if (indexStatus && indexStatus.rename) {
					return indexStatus.rename;
				}

				return resource.uri;

J
Joao Moreno 已提交
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
			case Status.BOTH_MODIFIED:
				return resource.uri;
		}
	}

	private getTitle(resource: Resource): string {
		const basename = path.basename(resource.uri.fsPath);

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

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

		return '';
	}

J
Joao Moreno 已提交
190 191 192
	@command('git.clone')
	async clone(): Promise<void> {
		const url = await window.showInputBox({
J
Joao Moreno 已提交
193 194
			prompt: localize('repourl', "Repository URL"),
			ignoreFocusOut: true
J
Joao Moreno 已提交
195 196 197 198 199 200 201 202
		});

		if (!url) {
			return;
		}

		const parentPath = await window.showInputBox({
			prompt: localize('parent', "Parent Directory"),
J
Joao Moreno 已提交
203 204
			value: os.homedir(),
			ignoreFocusOut: true
J
Joao Moreno 已提交
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
		});

		if (!parentPath) {
			return;
		}

		const clonePromise = this.model.git.clone(url, parentPath);
		window.setStatusBarMessage(localize('cloning', "Cloning git repository..."), clonePromise);
		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);

		if (result === open) {
			commands.executeCommand('vscode.openFolder', Uri.file(repositoryPath));
		}
	}

J
Joao Moreno 已提交
223 224 225 226 227
	@command('git.init')
	async init(): Promise<void> {
		await this.model.init();
	}

J
Joao Moreno 已提交
228
	@command('git.openFile')
J
Joao Moreno 已提交
229
	async openFile(uri: Uri): Promise<void> {
J
Joao Moreno 已提交
230
		const scmResource = resolveGitResource(uri);
J
Joao Moreno 已提交
231

J
Joao Moreno 已提交
232 233
		if (scmResource) {
			return await commands.executeCommand<void>('vscode.open', scmResource.uri);
J
Joao Moreno 已提交
234 235
		}

J
Joao Moreno 已提交
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
		return await commands.executeCommand<void>('vscode.open', uri.with({ scheme: 'file' }));
	}

	@command('git.openChange')
	async openChange(uri: Uri): Promise<void> {
		const scmResource = resolveGitResource(uri);

		if (scmResource) {
			return await this.open(scmResource);
		}

		if (uri.scheme === 'file') {
			const uriString = uri.toString();
			const resource = this.model.workingTreeGroup.resources.filter(r => r.uri.toString() === uriString)[0]
				|| this.model.indexGroup.resources.filter(r => r.uri.toString() === uriString)[0];

			if (resource) {
				return await this.open(resource);
			}
		}
J
Joao Moreno 已提交
256 257
	}

J
Joao Moreno 已提交
258
	@command('git.stage')
J
Joao Moreno 已提交
259 260
	async stage(uri: Uri): Promise<void> {
		const resource = resolveGitResource(uri);
J
Joao Moreno 已提交
261

J
Joao Moreno 已提交
262 263 264
		if (!resource) {
			return;
		}
J
Joao Moreno 已提交
265

J
Joao Moreno 已提交
266
		return await this.model.add(resource);
J
Joao Moreno 已提交
267 268
	}

J
Joao Moreno 已提交
269
	@command('git.stageAll')
J
Joao Moreno 已提交
270
	async stageAll(): Promise<void> {
J
Joao Moreno 已提交
271 272 273 274 275 276 277 278 279 280 281 282 283 284
		return await this.model.add();
	}

	@command('git.stageSelectedRanges')
	async stageSelectedRanges(): Promise<void> {
		const textEditor = window.activeTextEditor;

		if (!textEditor) {
			return;
		}

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

J
Joao Moreno 已提交
285
		if (modifiedUri.scheme !== 'file') {
J
Joao Moreno 已提交
286 287 288
			return;
		}

J
Joao Moreno 已提交
289
		const originalUri = modifiedUri.with({ scheme: 'git', query: '~' });
J
Joao Moreno 已提交
290 291 292 293 294
		const originalDocument = await workspace.openTextDocument(originalUri);
		const diffs = await computeDiff(originalDocument, modifiedDocument);
		const selections = textEditor.selections;
		const selectedDiffs = diffs.filter(diff => {
			const modifiedRange = diff.modifiedEndLineNumber === 0
295
				? new Range(modifiedDocument.lineAt(diff.modifiedStartLineNumber - 1).range.end, modifiedDocument.lineAt(diff.modifiedStartLineNumber).range.start)
J
Joao Moreno 已提交
296 297 298 299 300 301 302 303 304 305 306
				: new Range(modifiedDocument.lineAt(diff.modifiedStartLineNumber - 1).range.start, modifiedDocument.lineAt(diff.modifiedEndLineNumber - 1).range.end);

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

		if (!selectedDiffs.length) {
			return;
		}

		const result = staging.applyChanges(originalDocument, modifiedDocument, selectedDiffs);
		await this.model.stage(modifiedUri, result);
J
Joao Moreno 已提交
307
	}
J
Joao Moreno 已提交
308

J
Joao Moreno 已提交
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
	@command('git.revertSelectedRanges')
	async revertSelectedRanges(): Promise<void> {
		const textEditor = window.activeTextEditor;

		if (!textEditor) {
			return;
		}

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

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

		const originalUri = modifiedUri.with({ scheme: 'git', query: '~' });
		const originalDocument = await workspace.openTextDocument(originalUri);
		const diffs = await computeDiff(originalDocument, modifiedDocument);
		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;
		}

		const result = staging.applyChanges(originalDocument, modifiedDocument, selectedDiffs);
		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 已提交
355
	@command('git.unstage')
J
Joao Moreno 已提交
356 357
	async unstage(uri: Uri): Promise<void> {
		const resource = resolveGitResource(uri);
J
Joao Moreno 已提交
358

J
Joao Moreno 已提交
359
		if (!resource) {
J
Joao Moreno 已提交
360 361 362
			return;
		}

J
Joao Moreno 已提交
363
		return await this.model.revertFiles(resource);
J
Joao Moreno 已提交
364 365
	}

J
Joao Moreno 已提交
366
	@command('git.unstageAll')
J
Joao Moreno 已提交
367
	async unstageAll(): Promise<void> {
J
Joao Moreno 已提交
368
		return await this.model.revertFiles();
J
Joao Moreno 已提交
369
	}
J
Joao Moreno 已提交
370

J
Joao Moreno 已提交
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
	@command('git.unstageSelectedRanges')
	async unstageSelectedRanges(): Promise<void> {
		const textEditor = window.activeTextEditor;

		if (!textEditor) {
			return;
		}

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

		if (modifiedUri.scheme !== 'git' || modifiedUri.query !== '') {
			return;
		}

		const originalUri = modifiedUri.with({ scheme: 'git', query: 'HEAD' });
		const originalDocument = await workspace.openTextDocument(originalUri);
		const diffs = await computeDiff(originalDocument, modifiedDocument);
		const selections = textEditor.selections;
		const selectedDiffs = diffs.filter(diff => {
			const modifiedRange = diff.modifiedEndLineNumber === 0
				? new Range(diff.modifiedStartLineNumber - 1, 0, diff.modifiedStartLineNumber - 1, 0)
				: new Range(modifiedDocument.lineAt(diff.modifiedStartLineNumber - 1).range.start, modifiedDocument.lineAt(diff.modifiedEndLineNumber - 1).range.end);

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

		if (!selectedDiffs.length) {
			return;
		}

		const invertedDiffs = selectedDiffs.map(c => ({
			modifiedStartLineNumber: c.originalStartLineNumber,
			modifiedEndLineNumber: c.originalEndLineNumber,
			originalStartLineNumber: c.modifiedStartLineNumber,
			originalEndLineNumber: c.modifiedEndLineNumber
		}));

		const result = staging.applyChanges(modifiedDocument, originalDocument, invertedDiffs);
		await this.model.stage(modifiedUri, result);
	}

J
Joao Moreno 已提交
413
	@command('git.clean')
J
Joao Moreno 已提交
414 415 416 417
	async clean(uri: Uri): Promise<void> {
		const resource = resolveGitResource(uri);

		if (!resource) {
J
Joao Moreno 已提交
418 419
			return;
		}
J
Joao Moreno 已提交
420

J
Joao Moreno 已提交
421
		const basename = path.basename(resource.uri.fsPath);
J
Joao Moreno 已提交
422
		const message = localize('confirm clean', "Are you sure you want to clean changes in {0}?", basename);
J
Joao Moreno 已提交
423 424
		const yes = localize('clean', "Clean Changes");
		const pick = await window.showWarningMessage(message, { modal: true }, yes);
J
Joao Moreno 已提交
425

J
Joao Moreno 已提交
426 427 428 429
		if (pick !== yes) {
			return;
		}

J
Joao Moreno 已提交
430
		await this.model.clean(resource);
J
Joao Moreno 已提交
431
	}
J
Joao Moreno 已提交
432

J
Joao Moreno 已提交
433
	@command('git.cleanAll')
J
Joao Moreno 已提交
434
	async cleanAll(): Promise<void> {
J
Joao Moreno 已提交
435
		const message = localize('confirm clean all', "Are you sure you want to clean all changes?");
J
Joao Moreno 已提交
436 437
		const yes = localize('clean', "Clean Changes");
		const pick = await window.showWarningMessage(message, { modal: true }, yes);
J
Joao Moreno 已提交
438 439 440 441 442

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

J
Joao Moreno 已提交
443
		await this.model.clean(...this.model.workingTreeGroup.resources);
J
Joao Moreno 已提交
444 445
	}

J
Joao Moreno 已提交
446 447 448 449 450 451 452 453 454 455 456 457 458 459
	private async smartCommit(
		getCommitMessage: () => Promise<string>,
		opts?: CommitOptions
	): Promise<boolean> {
		if (!opts) {
			opts = { all: this.model.indexGroup.resources.length === 0 };
		}

		if (
			// no changes
			(this.model.indexGroup.resources.length === 0 && this.model.workingTreeGroup.resources.length === 0)
			// or no staged changes and not `all`
			|| (!opts.all && this.model.indexGroup.resources.length === 0)
		) {
J
Joao Moreno 已提交
460 461 462 463
			window.showInformationMessage(localize('no changes', "There are no changes to commit."));
			return false;
		}

J
Joao Moreno 已提交
464
		const message = await getCommitMessage();
J
Joao Moreno 已提交
465 466 467 468 469 470

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

J
Joao Moreno 已提交
471
		await this.model.commit(message, opts);
J
Joao Moreno 已提交
472 473 474 475

		return true;
	}

J
Joao Moreno 已提交
476
	private async commitWithAnyInput(opts?: CommitOptions): Promise<void> {
477
		const message = scm.inputBox.value;
J
Joao Moreno 已提交
478
		const getCommitMessage = async () => {
J
Joao Moreno 已提交
479 480 481 482 483 484
			if (message) {
				return message;
			}

			return await window.showInputBox({
				placeHolder: localize('commit message', "Commit message"),
J
Joao Moreno 已提交
485 486
				prompt: localize('provide commit message', "Please provide a commit message"),
				ignoreFocusOut: true
J
Joao Moreno 已提交
487
			});
J
Joao Moreno 已提交
488 489 490
		};

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

		if (message && didCommit) {
J
Joao Moreno 已提交
493
			scm.inputBox.value = await this.model.getCommitTemplate();
J
Joao Moreno 已提交
494
		}
J
Joao Moreno 已提交
495 496
	}

J
Joao Moreno 已提交
497
	@command('git.commit')
J
Joao Moreno 已提交
498 499 500 501
	async commit(): Promise<void> {
		await this.commitWithAnyInput();
	}

J
Joao Moreno 已提交
502
	@command('git.commitWithInput')
J
Joao Moreno 已提交
503
	async commitWithInput(): Promise<void> {
J
Joao Moreno 已提交
504
		const didCommit = await this.smartCommit(async () => scm.inputBox.value);
J
Joao Moreno 已提交
505 506

		if (didCommit) {
J
Joao Moreno 已提交
507
			scm.inputBox.value = await this.model.getCommitTemplate();
J
Joao Moreno 已提交
508
		}
J
Joao Moreno 已提交
509 510
	}

J
Joao Moreno 已提交
511
	@command('git.commitStaged')
J
Joao Moreno 已提交
512
	async commitStaged(): Promise<void> {
J
Joao Moreno 已提交
513
		await this.commitWithAnyInput({ all: false });
J
Joao Moreno 已提交
514 515
	}

J
Joao Moreno 已提交
516
	@command('git.commitStagedSigned')
J
Joao Moreno 已提交
517
	async commitStagedSigned(): Promise<void> {
J
Joao Moreno 已提交
518
		await this.commitWithAnyInput({ all: false, signoff: true });
J
Joao Moreno 已提交
519 520
	}

J
Joao Moreno 已提交
521
	@command('git.commitAll')
J
Joao Moreno 已提交
522
	async commitAll(): Promise<void> {
J
Joao Moreno 已提交
523
		await this.commitWithAnyInput({ all: true });
J
Joao Moreno 已提交
524 525
	}

J
Joao Moreno 已提交
526
	@command('git.commitAllSigned')
J
Joao Moreno 已提交
527
	async commitAllSigned(): Promise<void> {
J
Joao Moreno 已提交
528
		await this.commitWithAnyInput({ all: true, signoff: true });
J
Joao Moreno 已提交
529 530
	}

J
Joao Moreno 已提交
531
	@command('git.undoCommit')
J
Joao Moreno 已提交
532
	async undoCommit(): Promise<void> {
J
Joao Moreno 已提交
533 534 535 536 537 538 539 540 541
		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 已提交
542 543
	}

J
Joao Moreno 已提交
544
	@command('git.checkout')
J
Joao Moreno 已提交
545 546
	async checkout(): Promise<void> {
		const config = workspace.getConfiguration('git');
J
Joao Moreno 已提交
547
		const checkoutType = config.get<string>('checkoutType') || 'all';
J
Joao Moreno 已提交
548 549 550 551 552 553 554 555 556 557 558 559
		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 已提交
560 561 562
		const picks = [...heads, ...tags, ...remoteHeads];
		const placeHolder = 'Select a ref to checkout';
		const choice = await window.showQuickPick<CheckoutItem>(picks, { placeHolder });
J
Joao Moreno 已提交
563 564 565 566 567 568

		if (!choice) {
			return;
		}

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

J
Joao Moreno 已提交
571
	@command('git.branch')
J
Joao Moreno 已提交
572 573
	async branch(): Promise<void> {
		const result = await window.showInputBox({
J
Joao Moreno 已提交
574
			placeHolder: localize('branch name', "Branch name"),
J
Joao Moreno 已提交
575 576
			prompt: localize('provide branch name', "Please provide a branch name"),
			ignoreFocusOut: true
J
Joao Moreno 已提交
577
		});
J
Joao Moreno 已提交
578

J
Joao Moreno 已提交
579 580 581
		if (!result) {
			return;
		}
J
Joao Moreno 已提交
582

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

J
Joao Moreno 已提交
587
	@command('git.pull')
J
Joao Moreno 已提交
588
	async pull(): Promise<void> {
J
Joao Moreno 已提交
589 590 591 592 593 594 595 596
		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 已提交
597 598
	}

J
Joao Moreno 已提交
599
	@command('git.pullRebase')
J
Joao Moreno 已提交
600
	async pullRebase(): Promise<void> {
J
Joao Moreno 已提交
601 602 603 604 605 606 607 608
		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 已提交
609 610
	}

J
Joao Moreno 已提交
611
	@command('git.push')
J
Joao Moreno 已提交
612
	async push(): Promise<void> {
J
Joao Moreno 已提交
613 614 615 616 617 618 619 620
		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 已提交
621 622
	}

J
Joao Moreno 已提交
623
	@command('git.pushTo')
J
Joao Moreno 已提交
624
	async pushTo(): Promise<void> {
J
Joao Moreno 已提交
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
		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 已提交
647 648
	}

J
Joao Moreno 已提交
649
	@command('git.sync')
J
Joao Moreno 已提交
650
	async sync(): Promise<void> {
J
Joao Moreno 已提交
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672
		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 已提交
673 674 675
		await this.model.sync();
	}

J
Joao Moreno 已提交
676
	@command('git.publish')
J
Joao Moreno 已提交
677
	async publish(): Promise<void> {
J
Joao Moreno 已提交
678 679 680 681 682 683 684
		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 已提交
685 686
		const branchName = this.model.HEAD && this.model.HEAD.name || '';
		const picks = this.model.remotes.map(r => r.name);
J
Joao Moreno 已提交
687
		const placeHolder = localize('pick remote', "Pick a remote to publish the branch '{0}' to:", branchName);
J
Joao Moreno 已提交
688 689 690 691 692 693 694 695 696
		const choice = await window.showQuickPick(picks, { placeHolder });

		if (!choice) {
			return;
		}

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

J
Joao Moreno 已提交
697
	@command('git.showOutput')
J
Joao Moreno 已提交
698 699 700 701
	showOutput(): void {
		this.outputChannel.show();
	}

J
Joao Moreno 已提交
702
	private createCommand(id: string, method: Function): (...args: any[]) => any {
J
Joao Moreno 已提交
703 704 705 706 707 708
		return (...args) => {
			if (!this.model) {
				window.showInformationMessage(localize('disabled', "Git is either disabled or not supported in this workspace"));
				return;
			}

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

J
Joao Moreno 已提交
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745
			const result = Promise.resolve(method.apply(this, args));

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

				switch (err.gitErrorCode) {
					case 'DirtyWorkTree':
						message = localize('clean repo', "Please clean your repository working tree before checkout.");
						break;
					default:
						const lines = (err.stderr || err.message || String(err))
							.replace(/^error: /, '')
							.split(/[\r\n]/)
							.filter(line => !!line);

						message = lines[0] || 'Git error';
						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();
				}
			});
		};
	}

J
Joao Moreno 已提交
746 747 748
	dispose(): void {
		this.disposables.forEach(d => d.dispose());
	}
J
Joao Moreno 已提交
749
}