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

8
import { Uri, commands, scm, Disposable, window, workspace, QuickPickItem, OutputChannel, Range, WorkspaceEdit, Position, LineChange } from 'vscode';
J
Joao Moreno 已提交
9
import { Ref, RefType, Git } 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';
14
import { uniqueFilter } from './util';
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;
	}
}

63 64 65 66 67 68 69 70 71
interface Command {
	commandId: string;
	key: string;
	method: Function;
	skipModelCheck: boolean;
	requiresDiffInformation: boolean;
}

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

73
function command(commandId: string, skipModelCheck = false, requiresDiffInformation = false): Function {
J
Joao Moreno 已提交
74
	return (target: any, key: string, descriptor: any) => {
J
Joao Moreno 已提交
75 76 77 78
		if (!(typeof descriptor.value === 'function')) {
			throw new Error('not supported');
		}

79
		Commands.push({ commandId, key, method: descriptor.value, skipModelCheck, requiresDiffInformation });
J
Joao Moreno 已提交
80 81
	};
}
J
Joao Moreno 已提交
82

J
Joao Moreno 已提交
83
export class CommandCenter {
J
Joao Moreno 已提交
84

J
Joao Moreno 已提交
85
	private model: Model;
J
Joao Moreno 已提交
86
	private disposables: Disposable[];
J
Joao Moreno 已提交
87

J
Joao Moreno 已提交
88
	constructor(
J
Joao Moreno 已提交
89
		private git: Git,
J
Joao Moreno 已提交
90
		model: Model | undefined,
J
Joao Moreno 已提交
91 92
		private outputChannel: OutputChannel,
		private telemetryReporter: TelemetryReporter
J
Joao Moreno 已提交
93
	) {
J
Joao Moreno 已提交
94 95 96 97
		if (model) {
			this.model = model;
		}

J
Joao Moreno 已提交
98
		this.disposables = Commands
99 100 101 102 103 104 105 106 107
			.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 已提交
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.sourceUri.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:
149
				return resource.sourceUri.with({ scheme: 'git' });
J
Joao Moreno 已提交
150

J
Joao Moreno 已提交
151
			case Status.INDEX_RENAMED:
152
				return resource.sourceUri.with({ scheme: 'git' });
J
Joao Moreno 已提交
153 154 155

			case Status.INDEX_DELETED:
			case Status.DELETED:
156
				return resource.sourceUri.with({ scheme: 'git', query: 'HEAD' });
J
Joao Moreno 已提交
157 158 159 160

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

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

168
				return resource.sourceUri;
J
Joao Moreno 已提交
169

J
Joao Moreno 已提交
170
			case Status.BOTH_MODIFIED:
171
				return resource.sourceUri;
J
Joao Moreno 已提交
172 173 174 175
		}
	}

	private getTitle(resource: Resource): string {
176
		const basename = path.basename(resource.sourceUri.fsPath);
J
Joao Moreno 已提交
177 178 179 180 181 182 183 184 185 186 187 188 189

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

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

		return '';
	}

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

		if (!url) {
198 199
			this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'no_URL' });
			return;
J
Joao Moreno 已提交
200 201 202 203
		}

		const parentPath = await window.showInputBox({
			prompt: localize('parent', "Parent Directory"),
J
Joao Moreno 已提交
204 205
			value: os.homedir(),
			ignoreFocusOut: true
J
Joao Moreno 已提交
206 207 208
		});

		if (!parentPath) {
209 210
			this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'no_directory' });
			return;
J
Joao Moreno 已提交
211 212
		}

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

216
		try {
217 218 219 220 221 222 223 224 225 226
			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));
			}
227 228
		} catch (err) {
			if (/already exists and is not an empty directory/.test(err && err.stderr || '')) {
229 230 231
				this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'directory_not_empty' });
			} else {
				this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'error' });
232 233
			}
			throw err;
J
Joao Moreno 已提交
234 235 236
		}
	}

J
Joao Moreno 已提交
237 238 239 240 241
	@command('git.init')
	async init(): Promise<void> {
		await this.model.init();
	}

J
Joao Moreno 已提交
242
	@command('git.openFile')
J
Joao Moreno 已提交
243
	async openFile(uri?: Uri): Promise<void> {
244 245 246 247
		if (uri && uri.scheme === 'file') {
			return await commands.executeCommand<void>('vscode.open', uri);
		}

J
Joao Moreno 已提交
248
		const resource = this.resolveSCMResource(uri);
J
Joao Moreno 已提交
249

J
Joao Moreno 已提交
250 251
		if (!resource) {
			return;
J
Joao Moreno 已提交
252 253
		}

254
		return await commands.executeCommand<void>('vscode.open', resource.sourceUri);
J
Joao Moreno 已提交
255 256 257
	}

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

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

J
Joao Moreno 已提交
265
		return await this.open(resource);
J
Joao Moreno 已提交
266 267
	}

J
Joao Moreno 已提交
268
	@command('git.stage')
269 270
	async stage(...uris: Uri[]): Promise<void> {
		const resources = this.toSCMResources(uris);
J
Joao Moreno 已提交
271

272
		if (!resources.length) {
J
Joao Moreno 已提交
273 274
			return;
		}
J
Joao Moreno 已提交
275

276
		return await this.model.add(...resources);
J
Joao Moreno 已提交
277 278
	}

J
Joao Moreno 已提交
279
	@command('git.stageAll')
J
Joao Moreno 已提交
280
	async stageAll(): Promise<void> {
J
Joao Moreno 已提交
281 282 283
		return await this.model.add();
	}

284 285
	@command('git.stageSelectedRanges', false, true)
	async stageSelectedRanges(diffs: LineChange[]): Promise<void> {
J
Joao Moreno 已提交
286 287 288 289 290 291 292 293 294
		const textEditor = window.activeTextEditor;

		if (!textEditor) {
			return;
		}

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

J
Joao Moreno 已提交
295
		if (modifiedUri.scheme !== 'file') {
J
Joao Moreno 已提交
296 297 298
			return;
		}

J
Joao Moreno 已提交
299
		const originalUri = modifiedUri.with({ scheme: 'git', query: '~' });
J
Joao Moreno 已提交
300 301 302 303
		const originalDocument = await workspace.openTextDocument(originalUri);
		const selections = textEditor.selections;
		const selectedDiffs = diffs.filter(diff => {
			const modifiedRange = diff.modifiedEndLineNumber === 0
304
				? new Range(modifiedDocument.lineAt(diff.modifiedStartLineNumber - 1).range.end, modifiedDocument.lineAt(diff.modifiedStartLineNumber).range.start)
J
Joao Moreno 已提交
305 306 307 308 309 310 311 312 313 314 315
				: 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 已提交
316
	}
J
Joao Moreno 已提交
317

318 319
	@command('git.revertSelectedRanges', false, true)
	async revertSelectedRanges(diffs: LineChange[]): Promise<void> {
J
Joao Moreno 已提交
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 355 356 357 358 359 360 361 362
		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 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 已提交
363
	@command('git.unstage')
364 365
	async unstage(...uris: Uri[]): Promise<void> {
		const resources = this.toSCMResources(uris);
J
Joao Moreno 已提交
366

367
		if (!resources.length) {
J
Joao Moreno 已提交
368 369 370
			return;
		}

371
		return await this.model.revertFiles(...resources);
J
Joao Moreno 已提交
372 373
	}

J
Joao Moreno 已提交
374
	@command('git.unstageAll')
J
Joao Moreno 已提交
375
	async unstageAll(): Promise<void> {
J
Joao Moreno 已提交
376
		return await this.model.revertFiles();
J
Joao Moreno 已提交
377
	}
J
Joao Moreno 已提交
378

379 380
	@command('git.unstageSelectedRanges', false, true)
	async unstageSelectedRanges(diffs: LineChange[]): Promise<void> {
J
Joao Moreno 已提交
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 413 414 415 416 417 418 419
		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 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 已提交
420
	@command('git.clean')
421 422
	async clean(...uris: Uri[]): Promise<void> {
		const resources = this.toSCMResources(uris);
J
Joao Moreno 已提交
423

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

428
		const message = resources.length === 1
429
			? localize('confirm discard', "Are you sure you want to discard changes in {0}?", path.basename(resources[0].sourceUri.fsPath))
430 431
			: localize('confirm discard multiple', "Are you sure you want to discard changes in {0} files?", resources.length);

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

J
Joao Moreno 已提交
435 436 437 438
		if (pick !== yes) {
			return;
		}

439
		await this.model.clean(...resources);
J
Joao Moreno 已提交
440
	}
J
Joao Moreno 已提交
441

J
Joao Moreno 已提交
442
	@command('git.cleanAll')
J
Joao Moreno 已提交
443
	async cleanAll(): Promise<void> {
444 445
		const message = localize('confirm discard all', "Are you sure you want to discard ALL changes?");
		const yes = localize('discard', "Discard Changes");
J
Joao Moreno 已提交
446
		const pick = await window.showWarningMessage(message, { modal: true }, yes);
J
Joao Moreno 已提交
447 448 449 450 451

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

J
Joao Moreno 已提交
452
		await this.model.clean(...this.model.workingTreeGroup.resources);
J
Joao Moreno 已提交
453 454
	}

J
Joao Moreno 已提交
455 456 457 458 459 460 461 462 463 464 465 466 467 468
	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 已提交
469 470 471 472
			window.showInformationMessage(localize('no changes', "There are no changes to commit."));
			return false;
		}

J
Joao Moreno 已提交
473
		const message = await getCommitMessage();
J
Joao Moreno 已提交
474 475 476 477 478 479

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

J
Joao Moreno 已提交
480
		await this.model.commit(message, opts);
J
Joao Moreno 已提交
481 482 483 484

		return true;
	}

J
Joao Moreno 已提交
485
	private async commitWithAnyInput(opts?: CommitOptions): Promise<void> {
486
		const message = scm.inputBox.value;
J
Joao Moreno 已提交
487
		const getCommitMessage = async () => {
J
Joao Moreno 已提交
488 489 490 491 492 493
			if (message) {
				return message;
			}

			return await window.showInputBox({
				placeHolder: localize('commit message', "Commit message"),
J
Joao Moreno 已提交
494 495
				prompt: localize('provide commit message', "Please provide a commit message"),
				ignoreFocusOut: true
J
Joao Moreno 已提交
496
			});
J
Joao Moreno 已提交
497 498 499
		};

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

		if (message && didCommit) {
J
Joao Moreno 已提交
502
			scm.inputBox.value = await this.model.getCommitTemplate();
J
Joao Moreno 已提交
503
		}
J
Joao Moreno 已提交
504 505
	}

J
Joao Moreno 已提交
506
	@command('git.commit')
J
Joao Moreno 已提交
507 508 509 510
	async commit(): Promise<void> {
		await this.commitWithAnyInput();
	}

J
Joao Moreno 已提交
511
	@command('git.commitWithInput')
J
Joao Moreno 已提交
512
	async commitWithInput(): Promise<void> {
J
Joao Moreno 已提交
513
		const didCommit = await this.smartCommit(async () => scm.inputBox.value);
J
Joao Moreno 已提交
514 515

		if (didCommit) {
J
Joao Moreno 已提交
516
			scm.inputBox.value = await this.model.getCommitTemplate();
J
Joao Moreno 已提交
517
		}
J
Joao Moreno 已提交
518 519
	}

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

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

J
Joao Moreno 已提交
530
	@command('git.commitAll')
J
Joao Moreno 已提交
531
	async commitAll(): Promise<void> {
J
Joao Moreno 已提交
532
		await this.commitWithAnyInput({ all: true });
J
Joao Moreno 已提交
533 534
	}

J
Joao Moreno 已提交
535
	@command('git.commitAllSigned')
J
Joao Moreno 已提交
536
	async commitAllSigned(): Promise<void> {
J
Joao Moreno 已提交
537
		await this.commitWithAnyInput({ all: true, signoff: true });
J
Joao Moreno 已提交
538 539
	}

J
Joao Moreno 已提交
540
	@command('git.undoCommit')
J
Joao Moreno 已提交
541
	async undoCommit(): Promise<void> {
J
Joao Moreno 已提交
542 543 544 545 546 547 548 549 550
		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 已提交
551 552
	}

J
Joao Moreno 已提交
553
	@command('git.checkout')
J
Joao Moreno 已提交
554 555
	async checkout(): Promise<void> {
		const config = workspace.getConfiguration('git');
J
Joao Moreno 已提交
556
		const checkoutType = config.get<string>('checkoutType') || 'all';
J
Joao Moreno 已提交
557 558 559 560 561 562 563 564 565 566 567 568
		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 已提交
569 570 571
		const picks = [...heads, ...tags, ...remoteHeads];
		const placeHolder = 'Select a ref to checkout';
		const choice = await window.showQuickPick<CheckoutItem>(picks, { placeHolder });
J
Joao Moreno 已提交
572 573 574 575 576 577

		if (!choice) {
			return;
		}

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

J
Joao Moreno 已提交
580
	@command('git.branch')
J
Joao Moreno 已提交
581 582
	async branch(): Promise<void> {
		const result = await window.showInputBox({
J
Joao Moreno 已提交
583
			placeHolder: localize('branch name', "Branch name"),
J
Joao Moreno 已提交
584 585
			prompt: localize('provide branch name', "Please provide a branch name"),
			ignoreFocusOut: true
J
Joao Moreno 已提交
586
		});
J
Joao Moreno 已提交
587

J
Joao Moreno 已提交
588 589 590
		if (!result) {
			return;
		}
J
Joao Moreno 已提交
591

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

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

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

J
Joao Moreno 已提交
620
	@command('git.push')
J
Joao Moreno 已提交
621
	async push(): Promise<void> {
J
Joao Moreno 已提交
622 623 624 625 626 627 628 629
		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 已提交
630 631
	}

J
Joao Moreno 已提交
632
	@command('git.pushTo')
J
Joao Moreno 已提交
633
	async pushTo(): Promise<void> {
J
Joao Moreno 已提交
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
		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 已提交
656 657
	}

J
Joao Moreno 已提交
658
	@command('git.sync')
J
Joao Moreno 已提交
659
	async sync(): Promise<void> {
J
Joao Moreno 已提交
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
		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 已提交
682 683 684
		await this.model.sync();
	}

J
Joao Moreno 已提交
685
	@command('git.publish')
J
Joao Moreno 已提交
686
	async publish(): Promise<void> {
J
Joao Moreno 已提交
687 688 689 690 691 692 693
		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 已提交
694 695
		const branchName = this.model.HEAD && this.model.HEAD.name || '';
		const picks = this.model.remotes.map(r => r.name);
J
Joao Moreno 已提交
696
		const placeHolder = localize('pick remote', "Pick a remote to publish the branch '{0}' to:", branchName);
J
Joao Moreno 已提交
697 698 699 700 701 702 703 704 705
		const choice = await window.showQuickPick(picks, { placeHolder });

		if (!choice) {
			return;
		}

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

J
Joao Moreno 已提交
706
	@command('git.showOutput')
J
Joao Moreno 已提交
707 708 709 710
	showOutput(): void {
		this.outputChannel.show();
	}

J
Joao Moreno 已提交
711
	private createCommand(id: string, key: string, method: Function, skipModelCheck: boolean): (...args: any[]) => any {
712
		const result = (...args) => {
J
Joao Moreno 已提交
713
			if (!skipModelCheck && !this.model) {
J
Joao Moreno 已提交
714 715 716 717
				window.showInformationMessage(localize('disabled', "Git is either disabled or not supported in this workspace"));
				return;
			}

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

J
Joao Moreno 已提交
720 721 722 723 724 725 726 727 728 729
			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:
730 731 732
						const hint = (err.stderr || err.message || String(err))
							.replace(/^error: /mi, '')
							.replace(/^> husky.*$/mi, '')
J
Joao Moreno 已提交
733
							.split(/[\r\n]/)
734 735 736 737 738 739
							.filter(line => !!line)
						[0];

						message = hint
							? localize('git error details', "Git: {0}", hint)
							: localize('git error', "Git error");
J
Joao Moreno 已提交
740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757

						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();
				}
			});
		};
758 759 760 761 762

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

		return result;
J
Joao Moreno 已提交
763 764
	}

J
Joao Moreno 已提交
765 766 767 768
	private resolveSCMResource(uri?: Uri): Resource | undefined {
		uri = uri || window.activeTextEditor && window.activeTextEditor.document.uri;

		if (!uri) {
769
			return undefined;
J
Joao Moreno 已提交
770 771
		}

772 773
		if (uri.scheme === 'git-resource') {
			const {resourceGroupId} = JSON.parse(uri.query) as { resourceGroupId: string, sourceUri: string };
J
Joao Moreno 已提交
774
			const [resourceGroup] = this.model.resources.filter(g => g.contextKey === resourceGroupId);
775 776 777 778 779 780 781 782 783

			if (!resourceGroup) {
				return;
			}

			const uriStr = uri.toString();
			const [resource] = resourceGroup.resources.filter(r => r.uri.toString() === uriStr);

			return resource;
J
Joao Moreno 已提交
784 785 786 787 788 789 790 791 792
		}

		if (uri.scheme === 'git') {
			uri = uri.with({ scheme: 'file' });
		}

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

793 794
			return this.model.workingTreeGroup.resources.filter(r => r.sourceUri.toString() === uriString)[0]
				|| this.model.indexGroup.resources.filter(r => r.sourceUri.toString() === uriString)[0];
J
Joao Moreno 已提交
795 796 797
		}
	}

798 799 800 801 802 803
	private toSCMResources(uris: Uri[]): Resource[] {
		return uris.filter(uniqueFilter(uri => uri.toString()))
			.map(uri => this.resolveSCMResource(uri))
			.filter(r => !!r) as Resource[];
	}

J
Joao Moreno 已提交
804 805 806
	dispose(): void {
		this.disposables.forEach(d => d.dispose());
	}
J
Joao Moreno 已提交
807
}