commands.ts 74.2 KB
Newer Older
J
Joao Moreno 已提交
1 2 3 4 5
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

J
Joao Moreno 已提交
6
import { Uri, commands, Disposable, window, workspace, QuickPickItem, OutputChannel, Range, WorkspaceEdit, Position, LineChange, SourceControlResourceState, TextDocumentShowOptions, ViewColumn, ProgressLocation, TextEditor, MessageOptions, WorkspaceFolder } from 'vscode';
J
Joao Moreno 已提交
7
import { Git, CommitOptions, Stash, ForcePushMode } from './git';
I
Ilya Biryukov 已提交
8
import { Repository, Resource, ResourceGroupType } from './repository';
J
Joao Moreno 已提交
9
import { Model } from './model';
J
Joao Moreno 已提交
10
import { toGitUri, fromGitUri } from './uri';
11
import { grep, isDescendant, pathEquals } from './util';
J
Joao Moreno 已提交
12
import { applyLineChanges, intersectDiffWithRange, toLineRanges, invertLineChange, getModifiedRange } from './staging';
J
Joao Moreno 已提交
13
import * as path from 'path';
14
import { lstat, Stats } from 'fs';
J
Joao Moreno 已提交
15
import * as os from 'os';
J
Joao Moreno 已提交
16
import TelemetryReporter from 'vscode-extension-telemetry';
J
Joao Moreno 已提交
17
import * as nls from 'vscode-nls';
I
Ilya Biryukov 已提交
18
import { Ref, RefType, Branch, GitErrorCodes, Status } from './api/git';
J
Joao Moreno 已提交
19 20

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

J
Joao Moreno 已提交
22 23 24 25 26 27
class CheckoutItem implements QuickPickItem {

	protected get shortCommit(): string { return (this.ref.commit || '').substr(0, 8); }
	get label(): string { return this.ref.name || this.shortCommit; }
	get description(): string { return this.shortCommit; }

J
Joao Moreno 已提交
28
	constructor(protected ref: Ref) { }
J
Joao Moreno 已提交
29

J
Joao Moreno 已提交
30
	async run(repository: Repository): Promise<void> {
31
		const ref = this.ref.name;
J
Joao Moreno 已提交
32 33 34 35 36

		if (!ref) {
			return;
		}

J
Joao Moreno 已提交
37
		await repository.checkout(ref);
J
Joao Moreno 已提交
38 39 40 41 42
	}
}

class CheckoutTagItem extends CheckoutItem {

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

class CheckoutRemoteHeadItem extends CheckoutItem {

J
Joao Moreno 已提交
50 51 52
	get description(): string {
		return localize('remote branch at', "Remote branch at {0}", this.shortCommit);
	}
J
Joao Moreno 已提交
53

54
	async run(repository: Repository): Promise<void> {
J
Joao Moreno 已提交
55
		if (!this.ref.name) {
J
Joao Moreno 已提交
56 57 58
			return;
		}

J
Joao Moreno 已提交
59 60 61 62
		const branches = await repository.findTrackingBranches(this.ref.name);

		if (branches.length > 0) {
			await repository.checkout(branches[0].name!);
63
		} else {
J
Joao Moreno 已提交
64
			await repository.checkoutTracking(this.ref.name);
65
		}
J
Joao Moreno 已提交
66 67 68
	}
}

M
Maik Riechert 已提交
69 70
class BranchDeleteItem implements QuickPickItem {

71 72 73
	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 已提交
74 75
	get description(): string { return this.shortCommit; }

76
	constructor(private ref: Ref) { }
M
Maik Riechert 已提交
77

J
Joao Moreno 已提交
78
	async run(repository: Repository, force?: boolean): Promise<void> {
79
		if (!this.branchName) {
M
Maik Riechert 已提交
80 81
			return;
		}
J
Joao Moreno 已提交
82
		await repository.deleteBranch(this.branchName, force);
M
Maik Riechert 已提交
83 84 85
	}
}

86 87 88 89 90 91
class MergeItem implements QuickPickItem {

	get label(): string { return this.ref.name || ''; }
	get description(): string { return this.ref.name || ''; }

	constructor(protected ref: Ref) { }
J
Joao Moreno 已提交
92

J
Joao Moreno 已提交
93 94
	async run(repository: Repository): Promise<void> {
		await repository.merge(this.ref.name! || this.ref.commit!);
J
Joao Moreno 已提交
95
	}
96 97
}

J
Joao Moreno 已提交
98 99
class CreateBranchItem implements QuickPickItem {

J
Joao Moreno 已提交
100 101
	constructor(private cc: CommandCenter) { }

J
...  
Joao Moreno 已提交
102
	get label(): string { return localize('create branch', '$(plus) Create new branch...'); }
J
Joao Moreno 已提交
103 104
	get description(): string { return ''; }

C
Christof Marti 已提交
105
	get alwaysShow(): boolean { return true; }
106

J
Joao Moreno 已提交
107
	async run(repository: Repository): Promise<void> {
J
Joao Moreno 已提交
108
		await this.cc.branch(repository);
J
Joao Moreno 已提交
109 110 111
	}
}

J
Joao Moreno 已提交
112 113 114 115 116 117 118 119 120 121 122 123 124 125
class CreateBranchFromItem implements QuickPickItem {

	constructor(private cc: CommandCenter) { }

	get label(): string { return localize('create branch from', '$(plus) Create new branch from...'); }
	get description(): string { return ''; }

	get alwaysShow(): boolean { return true; }

	async run(repository: Repository): Promise<void> {
		await this.cc.branch(repository);
	}
}

J
Joao Moreno 已提交
126 127 128 129 130 131 132 133 134
class HEADItem implements QuickPickItem {

	constructor(private repository: Repository) { }

	get label(): string { return 'HEAD'; }
	get description(): string { return (this.repository.HEAD && this.repository.HEAD.commit || '').substr(0, 8); }
	get alwaysShow(): boolean { return true; }
}

J
Joao Moreno 已提交
135
interface CommandOptions {
J
Joao Moreno 已提交
136
	repository?: boolean;
J
Joao Moreno 已提交
137 138 139
	diff?: boolean;
}

140 141 142 143
interface Command {
	commandId: string;
	key: string;
	method: Function;
J
Joao Moreno 已提交
144
	options: CommandOptions;
145 146 147
}

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

J
Joao Moreno 已提交
149
function command(commandId: string, options: CommandOptions = {}): Function {
150
	return (_target: any, key: string, descriptor: any) => {
J
Joao Moreno 已提交
151 152 153 154
		if (!(typeof descriptor.value === 'function')) {
			throw new Error('not supported');
		}

J
Joao Moreno 已提交
155
		Commands.push({ commandId, key, method: descriptor.value, options });
J
Joao Moreno 已提交
156 157
	};
}
J
Joao Moreno 已提交
158

J
Joao Moreno 已提交
159 160 161 162 163 164 165 166 167
const ImageMimetypes = [
	'image/png',
	'image/gif',
	'image/jpeg',
	'image/webp',
	'image/tiff',
	'image/bmp'
];

J
Joao Moreno 已提交
168
async function categorizeResourceByResolution(resources: Resource[]): Promise<{ merge: Resource[], resolved: Resource[], unresolved: Resource[], deletionConflicts: Resource[] }> {
169 170 171
	const selection = resources.filter(s => s instanceof Resource) as Resource[];
	const merge = selection.filter(s => s.resourceGroupType === ResourceGroupType.Merge);
	const isBothAddedOrModified = (s: Resource) => s.type === Status.BOTH_MODIFIED || s.type === Status.BOTH_ADDED;
J
Joao Moreno 已提交
172
	const isAnyDeleted = (s: Resource) => s.type === Status.DELETED_BY_THEM || s.type === Status.DELETED_BY_US;
173 174 175
	const possibleUnresolved = merge.filter(isBothAddedOrModified);
	const promises = possibleUnresolved.map(s => grep(s.resourceUri.fsPath, /^<{7}|^={7}|^>{7}/));
	const unresolvedBothModified = await Promise.all<boolean>(promises);
176
	const resolved = possibleUnresolved.filter((_s, i) => !unresolvedBothModified[i]);
J
Joao Moreno 已提交
177
	const deletionConflicts = merge.filter(s => isAnyDeleted(s));
178
	const unresolved = [
J
Joao Moreno 已提交
179
		...merge.filter(s => !isBothAddedOrModified(s) && !isAnyDeleted(s)),
180
		...possibleUnresolved.filter((_s, i) => unresolvedBothModified[i])
181 182
	];

J
Joao Moreno 已提交
183
	return { merge, resolved, unresolved, deletionConflicts };
184 185
}

J
Joao Moreno 已提交
186
function createCheckoutItems(repository: Repository): CheckoutItem[] {
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
	const config = workspace.getConfiguration('git');
	const checkoutType = config.get<string>('checkoutType') || 'all';
	const includeTags = checkoutType === 'all' || checkoutType === 'tags';
	const includeRemotes = checkoutType === 'all' || checkoutType === 'remote';

	const heads = repository.refs.filter(ref => ref.type === RefType.Head)
		.map(ref => new CheckoutItem(ref));
	const tags = (includeTags ? repository.refs.filter(ref => ref.type === RefType.Tag) : [])
		.map(ref => new CheckoutTagItem(ref));
	const remoteHeads = (includeRemotes ? repository.refs.filter(ref => ref.type === RefType.RemoteHead) : [])
		.map(ref => new CheckoutRemoteHeadItem(ref));

	return [...heads, ...tags, ...remoteHeads];
}

202 203 204
enum PushType {
	Push,
	PushTo,
205
	PushFollowTags,
206 207 208 209 210
}

interface PushOptions {
	pushType: PushType;
	forcePush?: boolean;
J
Joao Moreno 已提交
211
	silent?: boolean;
212 213
}

J
Joao Moreno 已提交
214
export class CommandCenter {
J
Joao Moreno 已提交
215 216

	private disposables: Disposable[];
J
Joao Moreno 已提交
217

J
Joao Moreno 已提交
218
	constructor(
J
Joao Moreno 已提交
219
		private git: Git,
J
Joao Moreno 已提交
220
		private model: Model,
J
Joao Moreno 已提交
221 222
		private outputChannel: OutputChannel,
		private telemetryReporter: TelemetryReporter
J
Joao Moreno 已提交
223
	) {
J
Joao Moreno 已提交
224 225
		this.disposables = Commands.map(({ commandId, key, method, options }) => {
			const command = this.createCommand(commandId, key, method, options);
226

J
Joao Moreno 已提交
227
			if (options.diff) {
J
Joao Moreno 已提交
228 229 230 231 232
				return commands.registerDiffInformationCommand(commandId, command);
			} else {
				return commands.registerCommand(commandId, command);
			}
		});
J
Joao Moreno 已提交
233 234
	}

J
Joao Moreno 已提交
235 236
	@command('git.refresh', { repository: true })
	async refresh(repository: Repository): Promise<void> {
J
Joao Moreno 已提交
237
		await repository.status();
J
Joao Moreno 已提交
238
	}
J
Joao Moreno 已提交
239

J
Joao Moreno 已提交
240 241
	@command('git.openResource')
	async openResource(resource: Resource): Promise<void> {
J
Joao Moreno 已提交
242 243 244 245 246 247 248 249 250 251 252 253 254 255
		const repository = this.model.getRepository(resource.resourceUri);

		if (!repository) {
			return;
		}

		const config = workspace.getConfiguration('git', Uri.file(repository.root));
		const openDiffOnClick = config.get<boolean>('openDiffOnClick');

		if (openDiffOnClick) {
			await this._openResource(resource, undefined, true, false);
		} else {
			await this.openFile(resource);
		}
J
Joao Moreno 已提交
256 257
	}

J
Joao 已提交
258
	private async _openResource(resource: Resource, preview?: boolean, preserveFocus?: boolean, preserveSelection?: boolean): Promise<void> {
259
		let stat: Stats | undefined;
260

261 262 263 264
		try {
			stat = await new Promise<Stats>((c, e) => lstat(resource.resourceUri.fsPath, (err, stat) => err ? e(err) : c(stat)));
		} catch (err) {
			// noop
265
		}
266

267 268 269 270
		let left: Uri | undefined;
		let right: Uri | undefined;

		if (stat && stat.isDirectory()) {
271 272 273 274
			const repository = this.model.getRepositoryForSubmodule(resource.resourceUri);

			if (repository) {
				right = toGitUri(resource.resourceUri, resource.resourceGroupType === ResourceGroupType.Index ? 'index' : 'wt', { submoduleOf: repository.root });
275 276
			}
		} else {
J
Joao Moreno 已提交
277 278 279 280
			if (resource.type !== Status.DELETED_BY_THEM) {
				left = await this.getLeftResource(resource);
			}

281 282
			right = await this.getRightResource(resource);
		}
283

J
Joao Moreno 已提交
284 285
		const title = this.getTitle(resource);

J
Joao Moreno 已提交
286 287 288 289 290
		if (!right) {
			// TODO
			console.error('oh no');
			return;
		}
J
Joao Moreno 已提交
291

J
Joao Moreno 已提交
292
		const opts: TextDocumentShowOptions = {
J
Joao Moreno 已提交
293 294
			preserveFocus,
			preview,
295
			viewColumn: ViewColumn.Active
J
Joao Moreno 已提交
296 297
		};

J
Joao Moreno 已提交
298 299
		const activeTextEditor = window.activeTextEditor;

300 301 302
		// Check if active text editor has same path as other editor. we cannot compare via
		// URI.toString() here because the schemas can be different. Instead we just go by path.
		if (preserveSelection && activeTextEditor && activeTextEditor.document.uri.path === right.path) {
J
Joao Moreno 已提交
303 304 305
			opts.selection = activeTextEditor.selection;
		}

306
		if (!left) {
J
Joao Moreno 已提交
307
			await commands.executeCommand<void>('vscode.open', right, opts, title);
J
Joao Moreno 已提交
308 309 310 311
		} else {
			await commands.executeCommand<void>('vscode.diff', left, right, title, opts);
		}
	}
J
Joao Moreno 已提交
312

J
Joao Moreno 已提交
313 314
	private async getURI(uri: Uri, ref: string): Promise<Uri | undefined> {
		const repository = this.model.getRepository(uri);
J
Joao Moreno 已提交
315

J
Joao Moreno 已提交
316 317 318
		if (!repository) {
			return toGitUri(uri, ref);
		}
J
Joao Moreno 已提交
319

J
Joao Moreno 已提交
320
		try {
J
Joao Moreno 已提交
321 322 323
			let gitRef = ref;

			if (gitRef === '~') {
J
Joao Moreno 已提交
324
				const uriString = uri.toString();
J
Joao Moreno 已提交
325
				const [indexStatus] = repository.indexGroup.resourceStates.filter(r => r.resourceUri.toString() === uriString);
J
Joao Moreno 已提交
326
				gitRef = indexStatus ? '' : 'HEAD';
J
Joao Moreno 已提交
327 328
			}

J
Joao Moreno 已提交
329
			const { size, object } = await repository.getObjectDetails(gitRef, uri.fsPath);
J
Joao Moreno 已提交
330
			const { mimetype } = await repository.detectObjectType(object);
J
Joao Moreno 已提交
331

J
Joao Moreno 已提交
332 333 334
			if (mimetype === 'text/plain') {
				return toGitUri(uri, ref);
			}
335

J
Joao Moreno 已提交
336
			if (size > 1000000) { // 1 MB
J
Joao Moreno 已提交
337
				return Uri.parse(`data:;label:${path.basename(uri.fsPath)};description:${gitRef},`);
J
Joao Moreno 已提交
338 339
			}

J
Joao Moreno 已提交
340
			if (ImageMimetypes.indexOf(mimetype) > -1) {
J
Joao Moreno 已提交
341 342
				const contents = await repository.buffer(gitRef, uri.fsPath);
				return Uri.parse(`data:${mimetype};label:${path.basename(uri.fsPath)};description:${gitRef};size:${size};base64,${contents.toString('base64')}`);
J
Joao Moreno 已提交
343 344
			}

J
Joao Moreno 已提交
345
			return Uri.parse(`data:;label:${path.basename(uri.fsPath)};description:${gitRef},`);
J
Joao Moreno 已提交
346 347 348 349

		} catch (err) {
			return toGitUri(uri, ref);
		}
J
Joao Moreno 已提交
350 351
	}

J
Joao Moreno 已提交
352
	private async getLeftResource(resource: Resource): Promise<Uri | undefined> {
J
Joao Moreno 已提交
353 354 355
		switch (resource.type) {
			case Status.INDEX_MODIFIED:
			case Status.INDEX_RENAMED:
J
Joao Moreno 已提交
356
				return this.getURI(resource.original, 'HEAD');
J
Joao Moreno 已提交
357 358

			case Status.MODIFIED:
J
Joao Moreno 已提交
359
				return this.getURI(resource.resourceUri, '~');
360 361

			case Status.DELETED_BY_THEM:
J
Joao Moreno 已提交
362
				return this.getURI(resource.resourceUri, '');
J
Joao Moreno 已提交
363
		}
364
		return undefined;
J
Joao Moreno 已提交
365
	}
J
Joao Moreno 已提交
366

J
Joao Moreno 已提交
367
	private async getRightResource(resource: Resource): Promise<Uri | undefined> {
J
Joao Moreno 已提交
368 369 370 371 372
		switch (resource.type) {
			case Status.INDEX_MODIFIED:
			case Status.INDEX_ADDED:
			case Status.INDEX_COPIED:
			case Status.INDEX_RENAMED:
J
Joao Moreno 已提交
373
				return this.getURI(resource.resourceUri, '');
J
Joao Moreno 已提交
374 375 376

			case Status.INDEX_DELETED:
			case Status.DELETED:
J
Joao Moreno 已提交
377
				return this.getURI(resource.resourceUri, 'HEAD');
J
Joao Moreno 已提交
378

J
Joao Moreno 已提交
379 380 381 382 383 384
			case Status.DELETED_BY_US:
				return this.getURI(resource.resourceUri, '~3');

			case Status.DELETED_BY_THEM:
				return this.getURI(resource.resourceUri, '~2');

J
Joao Moreno 已提交
385 386 387
			case Status.MODIFIED:
			case Status.UNTRACKED:
			case Status.IGNORED:
388
			case Status.INTENT_TO_ADD:
J
Joao Moreno 已提交
389 390 391 392 393 394
				const repository = this.model.getRepository(resource.resourceUri);

				if (!repository) {
					return;
				}

J
Joao Moreno 已提交
395
				const uriString = resource.resourceUri.toString();
J
Joao Moreno 已提交
396
				const [indexStatus] = repository.indexGroup.resourceStates.filter(r => r.resourceUri.toString() === uriString);
J
Joao Moreno 已提交
397

J
Joao Moreno 已提交
398 399
				if (indexStatus && indexStatus.renameResourceUri) {
					return indexStatus.renameResourceUri;
J
Joao Moreno 已提交
400 401
				}

J
Joao Moreno 已提交
402
				return resource.resourceUri;
J
Joao Moreno 已提交
403

404
			case Status.BOTH_ADDED:
J
Joao Moreno 已提交
405
			case Status.BOTH_MODIFIED:
J
Joao Moreno 已提交
406
				return resource.resourceUri;
J
Joao Moreno 已提交
407
		}
408
		return undefined;
J
Joao Moreno 已提交
409 410 411
	}

	private getTitle(resource: Resource): string {
J
Joao Moreno 已提交
412
		const basename = path.basename(resource.resourceUri.fsPath);
J
Joao Moreno 已提交
413 414 415 416 417 418 419

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

			case Status.MODIFIED:
M
Marc Kassay 已提交
420 421
			case Status.BOTH_ADDED:
			case Status.BOTH_MODIFIED:
J
Joao Moreno 已提交
422
				return `${basename} (Working Tree)`;
J
Joao Moreno 已提交
423 424 425 426 427 428

			case Status.DELETED_BY_US:
				return `${basename} (Theirs)`;

			case Status.DELETED_BY_THEM:
				return `${basename} (Ours)`;
J
Joao Moreno 已提交
429 430 431 432 433
		}

		return '';
	}

J
Joao Moreno 已提交
434
	@command('git.clone')
435 436 437 438 439 440 441
	async clone(url?: string): Promise<void> {
		if (!url) {
			url = await window.showInputBox({
				prompt: localize('repourl', "Repository URL"),
				ignoreFocusOut: true
			});
		}
J
Joao Moreno 已提交
442 443

		if (!url) {
K
kieferrm 已提交
444
			/* __GDPR__
K
kieferrm 已提交
445 446 447 448
				"clone" : {
					"outcome" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
				}
			*/
449 450
			this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'no_URL' });
			return;
J
Joao Moreno 已提交
451 452
		}

453
		url = url.trim().replace(/^git\s+clone\s+/, '');
H
Howard Hung 已提交
454

455
		const config = workspace.getConfiguration('git');
J
Joao Moreno 已提交
456 457 458 459 460 461 462 463 464
		let defaultCloneDirectory = config.get<string>('defaultCloneDirectory') || os.homedir();
		defaultCloneDirectory = defaultCloneDirectory.replace(/^~/, os.homedir());

		const uris = await window.showOpenDialog({
			canSelectFiles: false,
			canSelectFolders: true,
			canSelectMany: false,
			defaultUri: Uri.file(defaultCloneDirectory),
			openLabel: localize('selectFolder', "Select Repository Location")
J
Joao Moreno 已提交
465 466
		});

J
Joao Moreno 已提交
467
		if (!uris || uris.length === 0) {
K
kieferrm 已提交
468
			/* __GDPR__
K
kieferrm 已提交
469 470 471 472
				"clone" : {
					"outcome" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
				}
			*/
473 474
			this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'no_directory' });
			return;
J
Joao Moreno 已提交
475 476
		}

J
Joao Moreno 已提交
477 478 479
		const uri = uris[0];
		const parentPath = uri.fsPath;

480
		try {
481 482 483 484 485
			const opts = {
				location: ProgressLocation.Notification,
				title: localize('cloning', "Cloning git repository '{0}'...", url),
				cancellable: true
			};
M
Maryam Archie 已提交
486

487 488
			const repositoryPath = await window.withProgress(
				opts,
J
Joao Moreno 已提交
489
				(_, token) => this.git.clone(url!, parentPath, token)
490
			);
491

J
Joao Moreno 已提交
492 493 494 495
			let message = localize('proposeopen', "Would you like to open the cloned repository?");
			const open = localize('openrepo', "Open");
			const openNewWindow = localize('openreponew', "Open in New Window");
			const choices = [open, openNewWindow];
496 497 498

			const addToWorkspace = localize('add', "Add to Workspace");
			if (workspace.workspaceFolders) {
J
Joao Moreno 已提交
499
				message = localize('proposeopen2', "Would you like to open the cloned repository, or add it to the current workspace?");
500 501 502 503
				choices.push(addToWorkspace);
			}

			const result = await window.showInformationMessage(message, ...choices);
504 505

			const openFolder = result === open;
K
kieferrm 已提交
506
			/* __GDPR__
K
kieferrm 已提交
507 508 509 510 511
				"clone" : {
					"outcome" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
					"openFolder": { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth", "isMeasurement": true }
				}
			*/
512
			this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'success' }, { openFolder: openFolder ? 1 : 0 });
513 514 515

			const uri = Uri.file(repositoryPath);

516
			if (openFolder) {
517 518 519
				commands.executeCommand('vscode.openFolder', uri);
			} else if (result === addToWorkspace) {
				workspace.updateWorkspaceFolders(workspace.workspaceFolders!.length, 0, { uri });
520 521
			} else if (result === openNewWindow) {
				commands.executeCommand('vscode.openFolder', uri, true);
522
			}
523 524
		} catch (err) {
			if (/already exists and is not an empty directory/.test(err && err.stderr || '')) {
K
kieferrm 已提交
525
				/* __GDPR__
K
kieferrm 已提交
526 527 528 529
					"clone" : {
						"outcome" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
					}
				*/
530
				this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'directory_not_empty' });
J
Joao Moreno 已提交
531 532
			} else if (/Cancelled/i.test(err && (err.message || err.stderr || ''))) {
				return;
533
			} else {
K
kieferrm 已提交
534
				/* __GDPR__
K
kieferrm 已提交
535 536 537 538
					"clone" : {
						"outcome" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
					}
				*/
539
				this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'error' });
540
			}
J
Joao Moreno 已提交
541

542
			throw err;
J
Joao Moreno 已提交
543 544 545
		}
	}

J
Joao Moreno 已提交
546
	@command('git.init')
J
Joao Moreno 已提交
547
	async init(): Promise<void> {
J
Joao Moreno 已提交
548
		let repositoryPath: string | undefined = undefined;
J
Joao Moreno 已提交
549
		let askToOpen = true;
J
Joao Moreno 已提交
550

J
Joao Moreno 已提交
551
		if (workspace.workspaceFolders) {
J
Joao Moreno 已提交
552
			const placeHolder = localize('init', "Pick workspace folder to initialize git repo in");
J
Joao Moreno 已提交
553 554 555 556 557
			const pick = { label: localize('choose', "Choose Folder...") };
			const items: { label: string, folder?: WorkspaceFolder }[] = [
				...workspace.workspaceFolders.map(folder => ({ label: folder.name, description: folder.uri.fsPath, folder })),
				pick
			];
J
Joao Moreno 已提交
558 559 560 561
			const item = await window.showQuickPick(items, { placeHolder, ignoreFocusOut: true });

			if (!item) {
				return;
J
Joao Moreno 已提交
562 563
			} else if (item.folder) {
				repositoryPath = item.folder.uri.fsPath;
J
Joao Moreno 已提交
564
				askToOpen = false;
J
Joao Moreno 已提交
565 566
			}
		}
J
Joao Moreno 已提交
567

J
Joao Moreno 已提交
568
		if (!repositoryPath) {
J
Joao Moreno 已提交
569 570 571 572 573 574 575 576 577 578 579 580
			const homeUri = Uri.file(os.homedir());
			const defaultUri = workspace.workspaceFolders && workspace.workspaceFolders.length > 0
				? Uri.file(workspace.workspaceFolders[0].uri.fsPath)
				: homeUri;

			const result = await window.showOpenDialog({
				canSelectFiles: false,
				canSelectFolders: true,
				canSelectMany: false,
				defaultUri,
				openLabel: localize('init repo', "Initialize Repository")
			});
J
Joao Moreno 已提交
581

J
Joao Moreno 已提交
582
			if (!result || result.length === 0) {
J
Joao Moreno 已提交
583 584
				return;
			}
J
Joao Moreno 已提交
585 586 587 588 589 590 591 592 593 594 595 596

			const uri = result[0];

			if (homeUri.toString().startsWith(uri.toString())) {
				const yes = localize('create repo', "Initialize Repository");
				const answer = await window.showWarningMessage(localize('are you sure', "This will create a Git repository in '{0}'. Are you sure you want to continue?", uri.fsPath), yes);

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

J
Joao Moreno 已提交
597
			repositoryPath = uri.fsPath;
J
Joao Moreno 已提交
598 599 600 601

			if (workspace.workspaceFolders && workspace.workspaceFolders.some(w => w.uri.toString() === uri.toString())) {
				askToOpen = false;
			}
J
Joao Moreno 已提交
602 603
		}

J
Joao Moreno 已提交
604
		await this.git.init(repositoryPath);
I
Ivan Sučić 已提交
605

J
Joao Moreno 已提交
606 607 608 609
		let message = localize('proposeopen init', "Would you like to open the initialized repository?");
		const open = localize('openrepo', "Open");
		const openNewWindow = localize('openreponew', "Open in New Window");
		const choices = [open, openNewWindow];
J
Joao Moreno 已提交
610

J
Joao Moreno 已提交
611 612 613 614
		if (!askToOpen) {
			return;
		}

J
Joao Moreno 已提交
615 616
		const addToWorkspace = localize('add', "Add to Workspace");
		if (workspace.workspaceFolders) {
J
Joao Moreno 已提交
617
			message = localize('proposeopen2 init', "Would you like to open the initialized repository, or add it to the current workspace?");
J
Joao Moreno 已提交
618 619
			choices.push(addToWorkspace);
		}
I
Ivan Sučić 已提交
620 621

		const result = await window.showInformationMessage(message, ...choices);
J
Joao Moreno 已提交
622
		const uri = Uri.file(repositoryPath);
I
Ivan Sučić 已提交
623

J
Joao Moreno 已提交
624 625 626 627
		if (result === open) {
			commands.executeCommand('vscode.openFolder', uri);
		} else if (result === addToWorkspace) {
			workspace.updateWorkspaceFolders(workspace.workspaceFolders!.length, 0, { uri });
628 629
		} else if (result === openNewWindow) {
			commands.executeCommand('vscode.openFolder', uri, true);
J
Joao Moreno 已提交
630 631
		} else {
			await this.model.openRepository(repositoryPath);
I
Ivan Sučić 已提交
632
		}
J
Joao Moreno 已提交
633 634
	}

J
Joao Moreno 已提交
635 636
	@command('git.openRepository', { repository: false })
	async openRepository(path?: string): Promise<void> {
637
		if (!path) {
J
Joao Moreno 已提交
638 639 640 641 642 643
			const result = await window.showOpenDialog({
				canSelectFiles: false,
				canSelectFolders: true,
				canSelectMany: false,
				defaultUri: Uri.file(os.homedir()),
				openLabel: localize('open repo', "Open Repository")
644 645
			});

J
Joao Moreno 已提交
646
			if (!result || result.length === 0) {
647 648 649
				return;
			}

J
Joao Moreno 已提交
650
			path = result[0].fsPath;
651
		}
J
Joao Moreno 已提交
652 653

		await this.model.openRepository(path);
654 655
	}

J
Joao Moreno 已提交
656 657 658 659 660
	@command('git.close', { repository: true })
	async close(repository: Repository): Promise<void> {
		this.model.close(repository);
	}

J
Joao Moreno 已提交
661 662
	@command('git.openFile')
	async openFile(arg?: Resource | Uri, ...resourceStates: SourceControlResourceState[]): Promise<void> {
663
		const preserveFocus = arg instanceof Resource;
J
Joao Moreno 已提交
664

665
		let uris: Uri[] | undefined;
666 667 668

		if (arg instanceof Uri) {
			if (arg.scheme === 'git') {
669
				uris = [Uri.file(fromGitUri(arg).path)];
670
			} else if (arg.scheme === 'file') {
671
				uris = [arg];
672 673 674 675 676 677
			}
		} else {
			let resource = arg;

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

			if (resource) {
J
Joao Moreno 已提交
682 683 684 685 686
				uris = ([resource, ...resourceStates] as Resource[])
					.filter(r => r.type !== Status.DELETED && r.type !== Status.INDEX_DELETED)
					.map(r => r.resourceUri);
			} else if (window.activeTextEditor) {
				uris = [window.activeTextEditor.document.uri];
687
			}
J
Joao Moreno 已提交
688 689
		}

690
		if (!uris) {
J
Joao Moreno 已提交
691
			return;
J
Joao Moreno 已提交
692 693
		}

694
		const activeTextEditor = window.activeTextEditor;
J
Joao Moreno 已提交
695

696 697
		for (const uri of uris) {
			const opts: TextDocumentShowOptions = {
J
Joao Moreno 已提交
698
				preserveFocus,
J
Joao Moreno 已提交
699
				preview: false,
700
				viewColumn: ViewColumn.Active
701 702
			};

M
Micah Smith 已提交
703 704 705 706 707 708 709
			let document;
			try {
				document = await workspace.openTextDocument(uri);
			} catch (error) {
				await commands.executeCommand<void>('vscode.open', uri, opts);
				continue;
			}
E
Eric Gang 已提交
710

711 712 713
			// Check if active text editor has same path as other editor. we cannot compare via
			// URI.toString() here because the schemas can be different. Instead we just go by path.
			if (activeTextEditor && activeTextEditor.document.uri.path === uri.path) {
E
Eric Gang 已提交
714
				// preserve not only selection but also visible range
B
Benjamin Pasero 已提交
715
				opts.selection = activeTextEditor.selection;
E
Eric Gang 已提交
716 717 718 719 720
				const previousVisibleRanges = activeTextEditor.visibleRanges;
				const editor = await window.showTextDocument(document, opts);
				editor.revealRange(previousVisibleRanges[0]);
			} else {
				await window.showTextDocument(document, opts);
B
Benjamin Pasero 已提交
721
			}
J
Joao Moreno 已提交
722
		}
J
Joao Moreno 已提交
723 724
	}

J
Joao Moreno 已提交
725 726 727 728 729
	@command('git.openFile2')
	async openFile2(arg?: Resource | Uri, ...resourceStates: SourceControlResourceState[]): Promise<void> {
		this.openFile(arg, ...resourceStates);
	}

J
Joao Moreno 已提交
730 731
	@command('git.openHEADFile')
	async openHEADFile(arg?: Resource | Uri): Promise<void> {
D
Duroktar 已提交
732
		let resource: Resource | undefined = undefined;
J
Joao Moreno 已提交
733
		const preview = !(arg instanceof Resource);
D
Duroktar 已提交
734 735 736 737

		if (arg instanceof Resource) {
			resource = arg;
		} else if (arg instanceof Uri) {
738
			resource = this.getSCMResource(arg);
D
Duroktar 已提交
739
		} else {
740
			resource = this.getSCMResource();
D
Duroktar 已提交
741 742 743 744 745 746
		}

		if (!resource) {
			return;
		}

J
Joao Moreno 已提交
747
		const HEAD = await this.getLeftResource(resource);
748 749
		const basename = path.basename(resource.resourceUri.fsPath);
		const title = `${basename} (HEAD)`;
D
Duroktar 已提交
750

J
Joao Moreno 已提交
751 752 753
		if (!HEAD) {
			window.showWarningMessage(localize('HEAD not available', "HEAD version of '{0}' is not available.", path.basename(resource.resourceUri.fsPath)));
			return;
D
Duroktar 已提交
754
		}
J
Joao Moreno 已提交
755

J
Joao Moreno 已提交
756 757 758 759
		const opts: TextDocumentShowOptions = {
			preview
		};

760
		return await commands.executeCommand<void>('vscode.open', HEAD, opts, title);
D
Duroktar 已提交
761 762
	}

J
Joao Moreno 已提交
763 764
	@command('git.openChange')
	async openChange(arg?: Resource | Uri, ...resourceStates: SourceControlResourceState[]): Promise<void> {
765
		const preserveFocus = arg instanceof Resource;
J
Joao Moreno 已提交
766 767
		const preview = !(arg instanceof Resource);

J
Joao 已提交
768
		const preserveSelection = arg instanceof Uri || !arg;
769
		let resources: Resource[] | undefined = undefined;
770

771
		if (arg instanceof Uri) {
772
			const resource = this.getSCMResource(arg);
773 774 775
			if (resource !== undefined) {
				resources = [resource];
			}
776
		} else {
777
			let resource: Resource | undefined = undefined;
J
Joao Moreno 已提交
778

779 780 781
			if (arg instanceof Resource) {
				resource = arg;
			} else {
782
				resource = this.getSCMResource();
783 784 785 786 787
			}

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

790
		if (!resources) {
J
Joao Moreno 已提交
791
			return;
J
Joao Moreno 已提交
792
		}
J
Joao Moreno 已提交
793

794
		for (const resource of resources) {
J
Joao 已提交
795
			await this._openResource(resource, preview, preserveFocus, preserveSelection);
796
		}
J
Joao Moreno 已提交
797 798
	}

799 800
	@command('git.stage')
	async stage(...resourceStates: SourceControlResourceState[]): Promise<void> {
J
Joao Moreno 已提交
801 802
		this.outputChannel.appendLine(`git.stage ${resourceStates.length}`);

803 804
		resourceStates = resourceStates.filter(s => !!s);

J
Joao Moreno 已提交
805
		if (resourceStates.length === 0 || (resourceStates[0] && !(resourceStates[0].resourceUri instanceof Uri))) {
806
			const resource = this.getSCMResource();
807

J
Joao Moreno 已提交
808 809
			this.outputChannel.appendLine(`git.stage.getSCMResource ${resource ? resource.resourceUri.toString() : null}`);

810 811 812 813 814 815 816
			if (!resource) {
				return;
			}

			resourceStates = [resource];
		}

817
		const selection = resourceStates.filter(s => s instanceof Resource) as Resource[];
J
Joao Moreno 已提交
818
		const { resolved, unresolved, deletionConflicts } = await categorizeResourceByResolution(selection);
819 820 821 822 823

		if (unresolved.length > 0) {
			const message = unresolved.length > 1
				? localize('confirm stage files with merge conflicts', "Are you sure you want to stage {0} files with merge conflicts?", unresolved.length)
				: localize('confirm stage file with merge conflicts', "Are you sure you want to stage {0} with merge conflicts?", path.basename(unresolved[0].resourceUri.fsPath));
824

825 826 827 828 829 830 831 832
			const yes = localize('yes', "Yes");
			const pick = await window.showWarningMessage(message, { modal: true }, yes);

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

J
Joao Moreno 已提交
833 834 835 836 837 838 839 840 841 842 843 844 845 846
		try {
			await this.runByRepository(deletionConflicts.map(r => r.resourceUri), async (repository, resources) => {
				for (const resource of resources) {
					await this._stageDeletionConflict(repository, resource);
				}
			});
		} catch (err) {
			if (/Cancelled/.test(err.message)) {
				return;
			}

			throw err;
		}

J
Joao Moreno 已提交
847
		const workingTree = selection.filter(s => s.resourceGroupType === ResourceGroupType.WorkingTree);
848
		const scmResources = [...workingTree, ...resolved, ...unresolved];
849

J
Joao Moreno 已提交
850
		this.outputChannel.appendLine(`git.stage.scmResources ${scmResources.length}`);
851
		if (!scmResources.length) {
J
Joao Moreno 已提交
852 853
			return;
		}
J
Joao Moreno 已提交
854

855
		const resources = scmResources.map(r => r.resourceUri);
J
Joao Moreno 已提交
856
		await this.runByRepository(resources, async (repository, resources) => repository.add(resources));
J
Joao Moreno 已提交
857 858
	}

J
Joao Moreno 已提交
859 860
	@command('git.stageAll', { repository: true })
	async stageAll(repository: Repository): Promise<void> {
861
		const resources = repository.mergeGroup.resourceStates.filter(s => s instanceof Resource) as Resource[];
J
Joao Moreno 已提交
862 863 864 865 866 867 868 869 870 871 872 873 874
		const { merge, unresolved, deletionConflicts } = await categorizeResourceByResolution(resources);

		try {
			for (const deletionConflict of deletionConflicts) {
				await this._stageDeletionConflict(repository, deletionConflict.resourceUri);
			}
		} catch (err) {
			if (/Cancelled/.test(err.message)) {
				return;
			}

			throw err;
		}
875 876 877

		if (unresolved.length > 0) {
			const message = unresolved.length > 1
J
Joao Moreno 已提交
878 879
				? localize('confirm stage files with merge conflicts', "Are you sure you want to stage {0} files with merge conflicts?", merge.length)
				: localize('confirm stage file with merge conflicts', "Are you sure you want to stage {0} with merge conflicts?", path.basename(merge[0].resourceUri.fsPath));
880 881 882 883 884 885 886 887 888

			const yes = localize('yes', "Yes");
			const pick = await window.showWarningMessage(message, { modal: true }, yes);

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

J
Joao Moreno 已提交
889
		await repository.add([]);
J
Joao Moreno 已提交
890 891
	}

J
Joao Moreno 已提交
892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926
	private async _stageDeletionConflict(repository: Repository, uri: Uri): Promise<void> {
		const uriString = uri.toString();
		const resource = repository.mergeGroup.resourceStates.filter(r => r.resourceUri.toString() === uriString)[0];

		if (!resource) {
			return;
		}

		if (resource.type === Status.DELETED_BY_THEM) {
			const keepIt = localize('keep ours', "Keep Our Version");
			const deleteIt = localize('delete', "Delete File");
			const result = await window.showInformationMessage(localize('deleted by them', "File '{0}' was deleted by them and modified by us.\n\nWhat would you like to do?", path.basename(uri.fsPath)), { modal: true }, keepIt, deleteIt);

			if (result === keepIt) {
				await repository.add([uri]);
			} else if (result === deleteIt) {
				await repository.rm([uri]);
			} else {
				throw new Error('Cancelled');
			}
		} else if (resource.type === Status.DELETED_BY_US) {
			const keepIt = localize('keep theirs', "Keep Their Version");
			const deleteIt = localize('delete', "Delete File");
			const result = await window.showInformationMessage(localize('deleted by us', "File '{0}' was deleted by us and modified by them.\n\nWhat would you like to do?", path.basename(uri.fsPath)), { modal: true }, keepIt, deleteIt);

			if (result === keepIt) {
				await repository.add([uri]);
			} else if (result === deleteIt) {
				await repository.rm([uri]);
			} else {
				throw new Error('Cancelled');
			}
		}
	}

J
Joao Moreno 已提交
927
	@command('git.stageChange')
J
Joao Moreno 已提交
928 929 930 931 932 933 934 935
	async stageChange(uri: Uri, changes: LineChange[], index: number): Promise<void> {
		const textEditor = window.visibleTextEditors.filter(e => e.document.uri.toString() === uri.toString())[0];

		if (!textEditor) {
			return;
		}

		await this._stageChanges(textEditor, [changes[index]]);
J
Joao Moreno 已提交
936 937
	}

J
Joao Moreno 已提交
938
	@command('git.stageSelectedRanges', { diff: true })
J
Joao Moreno 已提交
939
	async stageSelectedChanges(changes: LineChange[]): Promise<void> {
J
Joao Moreno 已提交
940 941 942 943 944 945 946
		const textEditor = window.activeTextEditor;

		if (!textEditor) {
			return;
		}

		const modifiedDocument = textEditor.document;
J
Joao Moreno 已提交
947 948 949 950
		const selectedLines = toLineRanges(textEditor.selections, modifiedDocument);
		const selectedChanges = changes
			.map(diff => selectedLines.reduce<LineChange | null>((result, range) => result || intersectDiffWithRange(modifiedDocument, diff, range), null))
			.filter(d => !!d) as LineChange[];
J
Joao Moreno 已提交
951

J
Joao Moreno 已提交
952
		if (!selectedChanges.length) {
J
Joao Moreno 已提交
953 954 955
			return;
		}

J
Joao Moreno 已提交
956 957
		await this._stageChanges(textEditor, selectedChanges);
	}
J
Joao Moreno 已提交
958

J
Joao Moreno 已提交
959
	private async _stageChanges(textEditor: TextEditor, changes: LineChange[]): Promise<void> {
J
Joao Moreno 已提交
960 961 962
		const modifiedDocument = textEditor.document;
		const modifiedUri = modifiedDocument.uri;

J
Joao Moreno 已提交
963
		if (modifiedUri.scheme !== 'file') {
J
Joao Moreno 已提交
964 965 966
			return;
		}

J
Joao Moreno 已提交
967
		const originalUri = toGitUri(modifiedUri, '~');
J
Joao Moreno 已提交
968
		const originalDocument = await workspace.openTextDocument(originalUri);
J
Joao Moreno 已提交
969
		const result = applyLineChanges(originalDocument, modifiedDocument, changes);
J
Joao Moreno 已提交
970

J
Joao Moreno 已提交
971
		await this.runByRepository(modifiedUri, async (repository, resource) => await repository.stage(resource, result));
J
Joao Moreno 已提交
972
	}
J
Joao Moreno 已提交
973

J
Joao Moreno 已提交
974
	@command('git.revertChange')
J
Joao Moreno 已提交
975 976 977 978
	async revertChange(uri: Uri, changes: LineChange[], index: number): Promise<void> {
		const textEditor = window.visibleTextEditors.filter(e => e.document.uri.toString() === uri.toString())[0];

		if (!textEditor) {
J
Joao Moreno 已提交
979 980 981
			return;
		}

J
Joao Moreno 已提交
982
		await this._revertChanges(textEditor, [...changes.slice(0, index), ...changes.slice(index + 1)]);
J
Joao Moreno 已提交
983
	}
J
Joao Moreno 已提交
984

J
Joao Moreno 已提交
985
	@command('git.revertSelectedRanges', { diff: true })
J
Joao Moreno 已提交
986
	async revertSelectedRanges(changes: LineChange[]): Promise<void> {
J
Joao Moreno 已提交
987 988 989 990 991 992 993
		const textEditor = window.activeTextEditor;

		if (!textEditor) {
			return;
		}

		const modifiedDocument = textEditor.document;
J
Joao Moreno 已提交
994 995
		const selections = textEditor.selections;
		const selectedChanges = changes.filter(change => {
J
Joao Moreno 已提交
996
			const modifiedRange = getModifiedRange(modifiedDocument, change);
J
Joao Moreno 已提交
997 998 999 1000
			return selections.every(selection => !selection.intersection(modifiedRange));
		});

		if (selectedChanges.length === changes.length) {
J
Joao Moreno 已提交
1001 1002 1003
			return;
		}

J
Joao Moreno 已提交
1004 1005
		await this._revertChanges(textEditor, selectedChanges);
	}
J
Joao Moreno 已提交
1006

J
Joao Moreno 已提交
1007 1008 1009
	private async _revertChanges(textEditor: TextEditor, changes: LineChange[]): Promise<void> {
		const modifiedDocument = textEditor.document;
		const modifiedUri = modifiedDocument.uri;
J
Joao Moreno 已提交
1010

J
Joao Moreno 已提交
1011
		if (modifiedUri.scheme !== 'file') {
J
Joao Moreno 已提交
1012 1013 1014
			return;
		}

J
Joao Moreno 已提交
1015 1016
		const originalUri = toGitUri(modifiedUri, '~');
		const originalDocument = await workspace.openTextDocument(originalUri);
1017 1018
		const selectionsBeforeRevert = textEditor.selections;
		const visibleRangesBeforeRevert = textEditor.visibleRanges;
J
Joao Moreno 已提交
1019
		const result = applyLineChanges(originalDocument, modifiedDocument, changes);
1020

J
Joao Moreno 已提交
1021 1022 1023
		const edit = new WorkspaceEdit();
		edit.replace(modifiedUri, new Range(new Position(0, 0), modifiedDocument.lineAt(modifiedDocument.lineCount - 1).range.end), result);
		workspace.applyEdit(edit);
1024

J
Joao Moreno 已提交
1025 1026
		await modifiedDocument.save();

1027 1028
		textEditor.selections = selectionsBeforeRevert;
		textEditor.revealRange(visibleRangesBeforeRevert[0]);
J
Joao Moreno 已提交
1029 1030
	}

J
Joao Moreno 已提交
1031 1032
	@command('git.unstage')
	async unstage(...resourceStates: SourceControlResourceState[]): Promise<void> {
1033 1034
		resourceStates = resourceStates.filter(s => !!s);

J
Joao Moreno 已提交
1035
		if (resourceStates.length === 0 || (resourceStates[0] && !(resourceStates[0].resourceUri instanceof Uri))) {
1036
			const resource = this.getSCMResource();
1037 1038 1039 1040 1041 1042 1043 1044

			if (!resource) {
				return;
			}

			resourceStates = [resource];
		}

1045
		const scmResources = resourceStates
J
Joao Moreno 已提交
1046
			.filter(s => s instanceof Resource && s.resourceGroupType === ResourceGroupType.Index) as Resource[];
1047

1048
		if (!scmResources.length) {
J
Joao Moreno 已提交
1049 1050 1051
			return;
		}

1052
		const resources = scmResources.map(r => r.resourceUri);
J
Joao Moreno 已提交
1053
		await this.runByRepository(resources, async (repository, resources) => repository.revert(resources));
J
Joao Moreno 已提交
1054 1055
	}

J
Joao Moreno 已提交
1056 1057
	@command('git.unstageAll', { repository: true })
	async unstageAll(repository: Repository): Promise<void> {
1058
		await repository.revert([]);
J
Joao Moreno 已提交
1059
	}
J
Joao Moreno 已提交
1060

J
Joao Moreno 已提交
1061 1062
	@command('git.unstageSelectedRanges', { diff: true })
	async unstageSelectedRanges(diffs: LineChange[]): Promise<void> {
J
Joao Moreno 已提交
1063 1064 1065 1066 1067 1068 1069 1070 1071
		const textEditor = window.activeTextEditor;

		if (!textEditor) {
			return;
		}

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

1072 1073 1074 1075 1076 1077 1078
		if (modifiedUri.scheme !== 'git') {
			return;
		}

		const { ref } = fromGitUri(modifiedUri);

		if (ref !== '') {
J
Joao Moreno 已提交
1079 1080 1081
			return;
		}

J
Joao Moreno 已提交
1082
		const originalUri = toGitUri(modifiedUri, 'HEAD');
J
Joao Moreno 已提交
1083
		const originalDocument = await workspace.openTextDocument(originalUri);
1084 1085 1086 1087
		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 已提交
1088 1089 1090 1091 1092

		if (!selectedDiffs.length) {
			return;
		}

1093 1094
		const invertedDiffs = selectedDiffs.map(invertLineChange);
		const result = applyLineChanges(modifiedDocument, originalDocument, invertedDiffs);
J
Joao Moreno 已提交
1095

J
Joao Moreno 已提交
1096
		await this.runByRepository(modifiedUri, async (repository, resource) => await repository.stage(resource, result));
J
Joao Moreno 已提交
1097 1098
	}

J
Joao Moreno 已提交
1099 1100
	@command('git.clean')
	async clean(...resourceStates: SourceControlResourceState[]): Promise<void> {
1101 1102
		resourceStates = resourceStates.filter(s => !!s);

J
Joao Moreno 已提交
1103
		if (resourceStates.length === 0 || (resourceStates[0] && !(resourceStates[0].resourceUri instanceof Uri))) {
1104
			const resource = this.getSCMResource();
1105 1106 1107 1108 1109 1110 1111 1112

			if (!resource) {
				return;
			}

			resourceStates = [resource];
		}

J
Joao Moreno 已提交
1113
		const scmResources = resourceStates
J
Joao Moreno 已提交
1114
			.filter(s => s instanceof Resource && s.resourceGroupType === ResourceGroupType.WorkingTree) as Resource[];
1115

J
Joao Moreno 已提交
1116
		if (!scmResources.length) {
J
Joao Moreno 已提交
1117 1118
			return;
		}
J
Joao Moreno 已提交
1119

J
Joao Moreno 已提交
1120
		const untrackedCount = scmResources.reduce((s, r) => s + (r.type === Status.UNTRACKED ? 1 : 0), 0);
J
Joao Moreno 已提交
1121 1122 1123
		let message: string;
		let yes = localize('discard', "Discard Changes");

J
Joao Moreno 已提交
1124
		if (scmResources.length === 1) {
J
Joao Moreno 已提交
1125
			if (untrackedCount > 0) {
J
Joao Moreno 已提交
1126
				message = localize('confirm delete', "Are you sure you want to DELETE {0}?\nThis is IRREVERSIBLE!\nThis file will be FOREVER LOST.", path.basename(scmResources[0].resourceUri.fsPath));
J
Joao Moreno 已提交
1127 1128
				yes = localize('delete file', "Delete file");
			} else {
1129 1130 1131 1132 1133 1134
				if (scmResources[0].type === Status.DELETED) {
					yes = localize('restore file', "Restore file");
					message = localize('confirm restore', "Are you sure you want to restore {0}?", path.basename(scmResources[0].resourceUri.fsPath));
				} else {
					message = localize('confirm discard', "Are you sure you want to discard changes in {0}?", path.basename(scmResources[0].resourceUri.fsPath));
				}
J
Joao Moreno 已提交
1135 1136
			}
		} else {
1137 1138 1139 1140 1141 1142
			if (scmResources.every(resource => resource.type === Status.DELETED)) {
				yes = localize('restore files', "Restore files");
				message = localize('confirm restore multiple', "Are you sure you want to restore {0} files?", scmResources.length);
			} else {
				message = localize('confirm discard multiple', "Are you sure you want to discard changes in {0} files?", scmResources.length);
			}
J
Joao Moreno 已提交
1143 1144

			if (untrackedCount > 0) {
J
Joao Moreno 已提交
1145
				message = `${message}\n\n${localize('warn untracked', "This will DELETE {0} untracked files!\nThis is IRREVERSIBLE!\nThese files will be FOREVER LOST.", untrackedCount)}`;
J
Joao Moreno 已提交
1146 1147
			}
		}
1148

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

J
Joao Moreno 已提交
1151 1152 1153 1154
		if (pick !== yes) {
			return;
		}

J
Joao Moreno 已提交
1155
		const resources = scmResources.map(r => r.resourceUri);
J
Joao Moreno 已提交
1156
		await this.runByRepository(resources, async (repository, resources) => repository.clean(resources));
J
Joao Moreno 已提交
1157
	}
J
Joao Moreno 已提交
1158

J
Joao Moreno 已提交
1159 1160
	@command('git.cleanAll', { repository: true })
	async cleanAll(repository: Repository): Promise<void> {
J
Joao Moreno 已提交
1161
		let resources = repository.workingTreeGroup.resourceStates;
J
Joao Moreno 已提交
1162 1163 1164 1165 1166

		if (resources.length === 0) {
			return;
		}

J
Joao Moreno 已提交
1167 1168
		const trackedResources = resources.filter(r => r.type !== Status.UNTRACKED && r.type !== Status.IGNORED);
		const untrackedResources = resources.filter(r => r.type === Status.UNTRACKED || r.type === Status.IGNORED);
J
Joao Moreno 已提交
1169

J
Joao Moreno 已提交
1170 1171 1172 1173 1174 1175
		if (untrackedResources.length === 0) {
			const message = resources.length === 1
				? localize('confirm discard all single', "Are you sure you want to discard changes in {0}?", path.basename(resources[0].resourceUri.fsPath))
				: localize('confirm discard all', "Are you sure you want to discard ALL changes in {0} files?\nThis is IRREVERSIBLE!\nYour current working set will be FOREVER LOST.", resources.length);
			const yes = resources.length === 1
				? localize('discardAll multiple', "Discard 1 File")
J
Joao Moreno 已提交
1176
				: localize('discardAll', "Discard All {0} Files", resources.length);
J
Joao Moreno 已提交
1177
			const pick = await window.showWarningMessage(message, { modal: true }, yes);
J
Joao Moreno 已提交
1178

J
Joao Moreno 已提交
1179
			if (pick !== yes) {
J
Joao Moreno 已提交
1180 1181 1182
				return;
			}

J
Joao 已提交
1183
			await repository.clean(resources.map(r => r.resourceUri));
J
Joao Moreno 已提交
1184 1185
			return;
		} else if (resources.length === 1) {
J
Joao Moreno 已提交
1186
			const message = localize('confirm delete', "Are you sure you want to DELETE {0}?\nThis is IRREVERSIBLE!\nThis file will be FOREVER LOST.", path.basename(resources[0].resourceUri.fsPath));
J
Joao Moreno 已提交
1187 1188 1189 1190 1191
			const yes = localize('delete file', "Delete file");
			const pick = await window.showWarningMessage(message, { modal: true }, yes);

			if (pick !== yes) {
				return;
J
Joao Moreno 已提交
1192 1193
			}

J
Joao 已提交
1194
			await repository.clean(resources.map(r => r.resourceUri));
J
Joao Moreno 已提交
1195 1196 1197 1198
		} else if (trackedResources.length === 0) {
			const message = localize('confirm delete multiple', "Are you sure you want to DELETE {0} files?", resources.length);
			const yes = localize('delete files', "Delete Files");
			const pick = await window.showWarningMessage(message, { modal: true }, yes);
J
Joao Moreno 已提交
1199

J
Joao Moreno 已提交
1200 1201 1202
			if (pick !== yes) {
				return;
			}
J
Joao Moreno 已提交
1203

J
Joao 已提交
1204
			await repository.clean(resources.map(r => r.resourceUri));
J
Joao Moreno 已提交
1205

J
Joao Moreno 已提交
1206 1207 1208 1209
		} else { // resources.length > 1 && untrackedResources.length > 0 && trackedResources.length > 0
			const untrackedMessage = untrackedResources.length === 1
				? localize('there are untracked files single', "The following untracked file will be DELETED FROM DISK if discarded: {0}.", path.basename(untrackedResources[0].resourceUri.fsPath))
				: localize('there are untracked files', "There are {0} untracked files which will be DELETED FROM DISK if discarded.", untrackedResources.length);
J
Joao Moreno 已提交
1210

J
Joao Moreno 已提交
1211 1212 1213 1214 1215
			const message = localize('confirm discard all 2', "{0}\n\nThis is IRREVERSIBLE, your current working set will be FOREVER LOST.", untrackedMessage, resources.length);

			const yesTracked = trackedResources.length === 1
				? localize('yes discard tracked', "Discard 1 Tracked File", trackedResources.length)
				: localize('yes discard tracked multiple', "Discard {0} Tracked Files", trackedResources.length);
J
Joao Moreno 已提交
1216

J
Joao Moreno 已提交
1217
			const yesAll = localize('discardAll', "Discard All {0} Files", resources.length);
J
Joao Moreno 已提交
1218 1219 1220 1221 1222 1223 1224 1225
			const pick = await window.showWarningMessage(message, { modal: true }, yesTracked, yesAll);

			if (pick === yesTracked) {
				resources = trackedResources;
			} else if (pick !== yesAll) {
				return;
			}

J
Joao 已提交
1226
			await repository.clean(resources.map(r => r.resourceUri));
J
Joao Moreno 已提交
1227
		}
J
Joao Moreno 已提交
1228 1229
	}

J
Joao Moreno 已提交
1230
	private async smartCommit(
J
Joao Moreno 已提交
1231
		repository: Repository,
1232
		getCommitMessage: () => Promise<string | undefined>,
J
Joao Moreno 已提交
1233 1234
		opts?: CommitOptions
	): Promise<boolean> {
1235
		const config = workspace.getConfiguration('git', Uri.file(repository.root));
J
Joao Moreno 已提交
1236 1237 1238 1239 1240 1241 1242 1243
		const promptToSaveFilesBeforeCommit = config.get<boolean>('promptToSaveFilesBeforeCommit') === true;

		if (promptToSaveFilesBeforeCommit) {
			const unsavedTextDocuments = workspace.textDocuments
				.filter(d => !d.isUntitled && d.isDirty && isDescendant(repository.root, d.uri.fsPath));

			if (unsavedTextDocuments.length > 0) {
				const message = unsavedTextDocuments.length === 1
J
Joao Moreno 已提交
1244 1245
					? localize('unsaved files single', "The following file is unsaved: {0}.\n\nWould you like to save it before committing?", path.basename(unsavedTextDocuments[0].uri.fsPath))
					: localize('unsaved files', "There are {0} unsaved files.\n\nWould you like to save them before committing?", unsavedTextDocuments.length);
J
Joao Moreno 已提交
1246 1247 1248 1249 1250 1251
				const saveAndCommit = localize('save and commit', "Save All & Commit");
				const commit = localize('commit', "Commit Anyway");
				const pick = await window.showWarningMessage(message, { modal: true }, saveAndCommit, commit);

				if (pick === saveAndCommit) {
					await Promise.all(unsavedTextDocuments.map(d => d.save()));
J
Joao Moreno 已提交
1252
					await repository.add(unsavedTextDocuments.map(d => d.uri));
J
Joao Moreno 已提交
1253 1254 1255 1256
					await repository.status();
				} else if (pick !== commit) {
					return false; // do not commit on cancel
				}
1257 1258 1259
			}
		}

1260
		const enableSmartCommit = config.get<boolean>('enableSmartCommit') === true;
1261
		const enableCommitSigning = config.get<boolean>('enableCommitSigning') === true;
J
Joao Moreno 已提交
1262 1263
		const noStagedChanges = repository.indexGroup.resourceStates.length === 0;
		const noUnstagedChanges = repository.workingTreeGroup.resourceStates.length === 0;
1264 1265

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

1268 1269 1270 1271 1272
			const suggestSmartCommit = config.get<boolean>('suggestSmartCommit') === true;
			if (!suggestSmartCommit) {
				return false;
			}

J
Joao Moreno 已提交
1273 1274
			// 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?");
1275 1276
			const yes = localize('yes', "Yes");
			const always = localize('always', "Always");
1277 1278
			const never = localize('never', "Never");
			const pick = await window.showWarningMessage(message, { modal: true }, yes, always, never);
1279 1280

			if (pick === always) {
J
Joao Moreno 已提交
1281
				config.update('enableSmartCommit', true, true);
1282 1283 1284
			} else if (pick === never) {
				config.update('suggestSmartCommit', false, true);
				return false;
J
Joao Moreno 已提交
1285 1286
			} else if (pick !== yes) {
				return false; // do not commit on cancel
1287 1288 1289
			}
		}

J
Joao Moreno 已提交
1290
		if (!opts) {
1291
			opts = { all: noStagedChanges };
J
Joao Moreno 已提交
1292 1293
		} else if (!opts.all && noStagedChanges) {
			opts = { ...opts, all: true };
J
Joao Moreno 已提交
1294 1295
		}

1296 1297 1298
		// enable signing of commits if configurated
		opts.signCommit = enableCommitSigning;

1299 1300 1301 1302
		if (config.get<boolean>('alwaysSignOff')) {
			opts.signoff = true;
		}

J
Joao Moreno 已提交
1303
		if (
1304
			(
J
Joao Moreno 已提交
1305 1306 1307 1308 1309
				// no changes
				(noStagedChanges && noUnstagedChanges)
				// or no staged changes and not `all`
				|| (!opts.all && noStagedChanges)
			)
1310
			&& !opts.empty
J
Joao Moreno 已提交
1311
		) {
J
Joao Moreno 已提交
1312 1313 1314 1315
			window.showInformationMessage(localize('no changes', "There are no changes to commit."));
			return false;
		}

J
Joao Moreno 已提交
1316
		const message = await getCommitMessage();
J
Joao Moreno 已提交
1317 1318 1319 1320 1321

		if (!message) {
			return false;
		}

J
Joao Moreno 已提交
1322
		await repository.commit(message, opts);
J
Joao Moreno 已提交
1323

J
Joao Moreno 已提交
1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334
		const postCommitCommand = config.get<'none' | 'push' | 'sync'>('postCommitCommand');

		switch (postCommitCommand) {
			case 'push':
				await this._push(repository, { pushType: PushType.Push, silent: true });
				break;
			case 'sync':
				await this.sync(repository);
				break;
		}

J
Joao Moreno 已提交
1335 1336 1337
		return true;
	}

J
Joao Moreno 已提交
1338
	private async commitWithAnyInput(repository: Repository, opts?: CommitOptions): Promise<void> {
J
Joao Moreno 已提交
1339
		const message = repository.inputBox.value;
J
Joao Moreno 已提交
1340
		const getCommitMessage = async () => {
J
Joao Moreno 已提交
1341 1342 1343 1344
			if (message) {
				return message;
			}

1345 1346 1347 1348 1349 1350
			let value: string | undefined = undefined;

			if (opts && opts.amend && repository.HEAD && repository.HEAD.commit) {
				value = (await repository.getCommit(repository.HEAD.commit)).message;
			}

J
Joao Moreno 已提交
1351
			return await window.showInputBox({
1352
				value,
J
Joao Moreno 已提交
1353
				placeHolder: localize('commit message', "Commit message"),
J
Joao Moreno 已提交
1354 1355
				prompt: localize('provide commit message', "Please provide a commit message"),
				ignoreFocusOut: true
J
Joao Moreno 已提交
1356
			});
J
Joao Moreno 已提交
1357 1358
		};

J
Joao Moreno 已提交
1359
		const didCommit = await this.smartCommit(repository, getCommitMessage, opts);
J
Joao Moreno 已提交
1360 1361

		if (message && didCommit) {
J
Joao Moreno 已提交
1362
			repository.inputBox.value = await repository.getCommitTemplate();
J
Joao Moreno 已提交
1363
		}
J
Joao Moreno 已提交
1364 1365
	}

J
Joao Moreno 已提交
1366
	@command('git.commit', { repository: true })
J
Joao Moreno 已提交
1367 1368
	async commit(repository: Repository): Promise<void> {
		await this.commitWithAnyInput(repository);
J
Joao Moreno 已提交
1369 1370
	}

J
Joao Moreno 已提交
1371
	@command('git.commitStaged', { repository: true })
J
Joao Moreno 已提交
1372 1373
	async commitStaged(repository: Repository): Promise<void> {
		await this.commitWithAnyInput(repository, { all: false });
J
Joao Moreno 已提交
1374 1375
	}

J
Joao Moreno 已提交
1376
	@command('git.commitStagedSigned', { repository: true })
J
Joao Moreno 已提交
1377 1378
	async commitStagedSigned(repository: Repository): Promise<void> {
		await this.commitWithAnyInput(repository, { all: false, signoff: true });
J
Joao Moreno 已提交
1379 1380
	}

J
Joao Moreno 已提交
1381
	@command('git.commitStagedAmend', { repository: true })
J
Joao Moreno 已提交
1382
	async commitStagedAmend(repository: Repository): Promise<void> {
1383
		await this.commitWithAnyInput(repository, { all: false, amend: true });
K
Krzysztof Cieślak 已提交
1384 1385
	}

J
Joao Moreno 已提交
1386
	@command('git.commitAll', { repository: true })
J
Joao Moreno 已提交
1387 1388
	async commitAll(repository: Repository): Promise<void> {
		await this.commitWithAnyInput(repository, { all: true });
J
Joao Moreno 已提交
1389 1390
	}

J
Joao Moreno 已提交
1391
	@command('git.commitAllSigned', { repository: true })
J
Joao Moreno 已提交
1392 1393
	async commitAllSigned(repository: Repository): Promise<void> {
		await this.commitWithAnyInput(repository, { all: true, signoff: true });
J
Joao Moreno 已提交
1394 1395
	}

J
Joao Moreno 已提交
1396
	@command('git.commitAllAmend', { repository: true })
J
Joao Moreno 已提交
1397 1398
	async commitAllAmend(repository: Repository): Promise<void> {
		await this.commitWithAnyInput(repository, { all: true, amend: true });
K
Krzysztof Cieślak 已提交
1399 1400
	}

J
Joao Moreno 已提交
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422
	@command('git.commitEmpty', { repository: true })
	async commitEmpty(repository: Repository): Promise<void> {
		const root = Uri.file(repository.root);
		const config = workspace.getConfiguration('git', root);
		const shouldPrompt = config.get<boolean>('confirmEmptyCommits') === true;

		if (shouldPrompt) {
			const message = localize('confirm emtpy commit', "Are you sure you want to create an empty commit?");
			const yes = localize('yes', "Yes");
			const neverAgain = localize('yes never again', "Yes, Don't Show Again");
			const pick = await window.showWarningMessage(message, { modal: true }, yes, neverAgain);

			if (pick === neverAgain) {
				await config.update('confirmEmptyCommits', false, true);
			} else if (pick !== yes) {
				return;
			}
		}

		await this.commitWithAnyInput(repository, { empty: true });
	}

J
Joao Moreno 已提交
1423 1424 1425 1426 1427
	@command('git.restoreCommitTemplate', { repository: true })
	async restoreCommitTemplate(repository: Repository): Promise<void> {
		repository.inputBox.value = await repository.getCommitTemplate();
	}

J
Joao Moreno 已提交
1428
	@command('git.undoCommit', { repository: true })
J
Joao Moreno 已提交
1429 1430
	async undoCommit(repository: Repository): Promise<void> {
		const HEAD = repository.HEAD;
J
Joao Moreno 已提交
1431 1432

		if (!HEAD || !HEAD.commit) {
J
Joao Moreno 已提交
1433
			window.showWarningMessage(localize('no more', "Can't undo because HEAD doesn't point to any commit."));
J
Joao Moreno 已提交
1434 1435 1436
			return;
		}

J
Joao Moreno 已提交
1437
		const commit = await repository.getCommit('HEAD');
J
Joao Moreno 已提交
1438 1439

		if (commit.parents.length > 0) {
1440 1441 1442 1443 1444
			await repository.reset('HEAD~');
		} else {
			await repository.deleteRef('HEAD');
			await this.unstageAll(repository);
		}
J
Joao Moreno 已提交
1445

J
Joao Moreno 已提交
1446
		repository.inputBox.value = commit.message;
J
Joao Moreno 已提交
1447 1448
	}

J
Joao Moreno 已提交
1449
	@command('git.checkout', { repository: true })
1450
	async checkout(repository: Repository, treeish: string): Promise<boolean> {
J
Joao Moreno 已提交
1451
		if (typeof treeish === 'string') {
1452 1453
			await repository.checkout(treeish);
			return true;
J
Joao Moreno 已提交
1454
		}
J
Joao Moreno 已提交
1455

J
Joao Moreno 已提交
1456 1457 1458
		const createBranch = new CreateBranchItem(this);
		const createBranchFrom = new CreateBranchFromItem(this);
		const picks = [createBranch, createBranchFrom, ...createCheckoutItems(repository)];
1459
		const placeHolder = localize('select a ref to checkout', 'Select a ref to checkout');
1460 1461 1462 1463

		const quickpick = window.createQuickPick();
		quickpick.items = picks;
		quickpick.placeholder = placeHolder;
J
Joao Moreno 已提交
1464
		quickpick.ignoreFocusOut = true;
1465 1466 1467 1468
		quickpick.show();

		const choice = await new Promise<QuickPickItem | undefined>(c => quickpick.onDidAccept(() => c(quickpick.activeItems[0])));
		quickpick.hide();
J
Joao Moreno 已提交
1469 1470

		if (!choice) {
1471
			return false;
J
Joao Moreno 已提交
1472 1473
		}

1474 1475
		if (choice === createBranch) {
			await this._branch(repository, quickpick.value);
J
Joao Moreno 已提交
1476 1477
		} else if (choice === createBranchFrom) {
			await this._branch(repository, quickpick.value, true);
1478 1479 1480 1481
		} else {
			await (choice as CheckoutItem).run(repository);
		}

1482
		return true;
J
Joao Moreno 已提交
1483 1484
	}

J
Joao Moreno 已提交
1485
	@command('git.branch', { repository: true })
J
Joao Moreno 已提交
1486
	async branch(repository: Repository): Promise<void> {
1487 1488
		await this._branch(repository);
	}
J
Joao Moreno 已提交
1489

J
Joao Moreno 已提交
1490 1491 1492 1493 1494
	@command('git.branchFrom', { repository: true })
	async branchFrom(repository: Repository): Promise<void> {
		await this._branch(repository, undefined, true);
	}

J
Joao Moreno 已提交
1495
	private async promptForBranchName(defaultName?: string): Promise<string> {
1496 1497 1498 1499
		const config = workspace.getConfiguration('git');
		const branchWhitespaceChar = config.get<string>('branchWhitespaceChar')!;
		const branchValidationRegex = config.get<string>('branchValidationRegex')!;
		const sanitize = (name: string) => name ?
J
Joao Moreno 已提交
1500
			name.trim().replace(/^-+/, '').replace(/^\.|\/\.|\.\.|~|\^|:|\/$|\.lock$|\.lock\/|\\|\*|\s|^\s*$|\.$|\[|\]$/g, branchWhitespaceChar)
1501 1502
			: name;

J
Joao Moreno 已提交
1503
		const rawBranchName = defaultName || await window.showInputBox({
1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516
			placeHolder: localize('branch name', "Branch name"),
			prompt: localize('provide branch name', "Please provide a branch name"),
			ignoreFocusOut: true,
			validateInput: (name: string) => {
				const validateName = new RegExp(branchValidationRegex);
				if (validateName.test(sanitize(name))) {
					return null;
				}

				return localize('branch name format invalid', "Branch name needs to match regex: {0}", branchValidationRegex);
			}
		});

J
Joao Moreno 已提交
1517 1518 1519 1520 1521
		return sanitize(rawBranchName || '');
	}

	private async _branch(repository: Repository, defaultName?: string, from = false): Promise<void> {
		const branchName = await this.promptForBranchName(defaultName);
1522 1523

		if (!branchName) {
1524 1525
			return;
		}
J
Joao Moreno 已提交
1526

J
Joao Moreno 已提交
1527
		let target = 'HEAD';
J
Joao Moreno 已提交
1528

J
Joao Moreno 已提交
1529 1530 1531 1532 1533 1534 1535 1536 1537 1538
		if (from) {
			const picks = [new HEADItem(repository), ...createCheckoutItems(repository)];
			const placeHolder = localize('select a ref to create a new branch from', 'Select a ref to create the \'{0}\' branch from', branchName);
			const choice = await window.showQuickPick(picks, { placeHolder });

			if (!choice) {
				return;
			}

			target = choice.label;
J
Joao Moreno 已提交
1539
		}
J
Joao Moreno 已提交
1540

J
Joao Moreno 已提交
1541
		await repository.branch(branchName, true, target);
J
Joao Moreno 已提交
1542 1543
	}

J
Joao Moreno 已提交
1544
	@command('git.deleteBranch', { repository: true })
J
Joao Moreno 已提交
1545
	async deleteBranch(repository: Repository, name: string, force?: boolean): Promise<void> {
1546 1547
		let run: (force?: boolean) => Promise<void>;
		if (typeof name === 'string') {
J
Joao Moreno 已提交
1548
			run = force => repository.deleteBranch(name, force);
1549
		} else {
J
Joao Moreno 已提交
1550 1551
			const currentHead = repository.HEAD && repository.HEAD.name;
			const heads = repository.refs.filter(ref => ref.type === RefType.Head && ref.name !== currentHead)
1552
				.map(ref => new BranchDeleteItem(ref));
M
Maik Riechert 已提交
1553

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

M
Maik Riechert 已提交
1557
			if (!choice || !choice.branchName) {
1558 1559
				return;
			}
M
Maik Riechert 已提交
1560
			name = choice.branchName;
J
Joao Moreno 已提交
1561
			run = force => choice.run(repository, force);
M
Maik Riechert 已提交
1562 1563
		}

1564 1565 1566 1567 1568 1569 1570 1571 1572
		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");
1573
			const pick = await window.showWarningMessage(message, { modal: true }, yes);
1574 1575 1576 1577 1578

			if (pick === yes) {
				await run(true);
			}
		}
M
Maik Riechert 已提交
1579 1580
	}

1581 1582
	@command('git.renameBranch', { repository: true })
	async renameBranch(repository: Repository): Promise<void> {
J
Joao Moreno 已提交
1583
		const branchName = await this.promptForBranchName();
J
Justin Horner 已提交
1584

J
Joao Moreno 已提交
1585
		if (!branchName) {
J
Justin Horner 已提交
1586 1587 1588 1589
			return;
		}

		try {
J
Joao Moreno 已提交
1590
			await repository.renameBranch(branchName);
J
Justin Horner 已提交
1591 1592 1593
		} catch (err) {
			switch (err.gitErrorCode) {
				case GitErrorCodes.InvalidBranchName:
1594 1595
					window.showErrorMessage(localize('invalid branch name', 'Invalid branch name'));
					return;
J
Justin Horner 已提交
1596
				case GitErrorCodes.BranchAlreadyExists:
J
Joao Moreno 已提交
1597
					window.showErrorMessage(localize('branch already exists', "A branch named '{0}' already exists", branchName));
1598 1599 1600
					return;
				default:
					throw err;
J
Justin Horner 已提交
1601 1602 1603 1604
			}
		}
	}

J
Joao Moreno 已提交
1605
	@command('git.merge', { repository: true })
J
Joao Moreno 已提交
1606
	async merge(repository: Repository): Promise<void> {
1607 1608 1609 1610
		const config = workspace.getConfiguration('git');
		const checkoutType = config.get<string>('checkoutType') || 'all';
		const includeRemotes = checkoutType === 'all' || checkoutType === 'remote';

J
Joao Moreno 已提交
1611
		const heads = repository.refs.filter(ref => ref.type === RefType.Head)
J
Joao Moreno 已提交
1612 1613
			.filter(ref => ref.name || ref.commit)
			.map(ref => new MergeItem(ref as Branch));
1614

J
Joao Moreno 已提交
1615
		const remoteHeads = (includeRemotes ? repository.refs.filter(ref => ref.type === RefType.RemoteHead) : [])
J
Joao Moreno 已提交
1616 1617
			.filter(ref => ref.name || ref.commit)
			.map(ref => new MergeItem(ref as Branch));
1618 1619

		const picks = [...heads, ...remoteHeads];
1620 1621
		const placeHolder = localize('select a branch to merge from', 'Select a branch to merge from');
		const choice = await window.showQuickPick<MergeItem>(picks, { placeHolder });
1622 1623 1624 1625 1626

		if (!choice) {
			return;
		}

1627
		await choice.run(repository);
1628 1629
	}

J
Joao Moreno 已提交
1630
	@command('git.createTag', { repository: true })
J
Joao Moreno 已提交
1631
	async createTag(repository: Repository): Promise<void> {
1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643
		const inputTagName = await window.showInputBox({
			placeHolder: localize('tag name', "Tag name"),
			prompt: localize('provide tag name', "Please provide a tag name"),
			ignoreFocusOut: true
		});

		if (!inputTagName) {
			return;
		}

		const inputMessage = await window.showInputBox({
			placeHolder: localize('tag message', "Message"),
J
Joao Moreno 已提交
1644
			prompt: localize('provide tag message', "Please provide a message to annotate the tag"),
1645 1646 1647 1648 1649
			ignoreFocusOut: true
		});

		const name = inputTagName.replace(/^\.|\/\.|\.\.|~|\^|:|\/$|\.lock$|\.lock\/|\\|\*|\s|^\s*$|\.$/g, '-');
		const message = inputMessage || name;
J
Joao Moreno 已提交
1650
		await repository.tag(name, message);
1651 1652
	}

J
Joao Moreno 已提交
1653 1654 1655 1656 1657 1658 1659
	@command('git.fetch', { repository: true })
	async fetch(repository: Repository): Promise<void> {
		if (repository.remotes.length === 0) {
			window.showWarningMessage(localize('no remotes to fetch', "This repository has no remotes configured to fetch from."));
			return;
		}

J
Joao Moreno 已提交
1660
		await repository.fetchDefault();
J
Joao Moreno 已提交
1661 1662
	}

R
Ryan Scott 已提交
1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673
	@command('git.fetchPrune', { repository: true })
	async fetchPrune(repository: Repository): Promise<void> {
		if (repository.remotes.length === 0) {
			window.showWarningMessage(localize('no remotes to fetch', "This repository has no remotes configured to fetch from."));
			return;
		}

		await repository.fetchPrune();
	}


J
Joao Moreno 已提交
1674 1675 1676 1677 1678 1679 1680 1681 1682 1683
	@command('git.fetchAll', { repository: true })
	async fetchAll(repository: Repository): Promise<void> {
		if (repository.remotes.length === 0) {
			window.showWarningMessage(localize('no remotes to fetch', "This repository has no remotes configured to fetch from."));
			return;
		}

		await repository.fetchAll();
	}

J
Joao Moreno 已提交
1684
	@command('git.pullFrom', { repository: true })
J
Joao Moreno 已提交
1685 1686
	async pullFrom(repository: Repository): Promise<void> {
		const remotes = repository.remotes;
1687 1688 1689 1690 1691 1692

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

1693
		const remotePicks = remotes.filter(r => r.fetchUrl !== undefined).map(r => ({ label: r.name, description: r.fetchUrl! }));
1694
		const placeHolder = localize('pick remote pull repo', "Pick a remote to pull the branch from");
D
Dozed12 已提交
1695
		const remotePick = await window.showQuickPick(remotePicks, { placeHolder });
1696

D
Dozed12 已提交
1697
		if (!remotePick) {
1698 1699 1700
			return;
		}

D
Dozed12 已提交
1701 1702
		const remoteRefs = repository.refs;
		const remoteRefsFiltered = remoteRefs.filter(r => (r.remote === remotePick.label));
J
Joao Moreno 已提交
1703
		const branchPicks = remoteRefsFiltered.map(r => ({ label: r.name })) as { label: string; description: string }[];
J
Joao Moreno 已提交
1704 1705
		const branchPlaceHolder = localize('pick branch pull', "Pick a branch to pull from");
		const branchPick = await window.showQuickPick(branchPicks, { placeHolder: branchPlaceHolder });
1706

D
Dozed12 已提交
1707
		if (!branchPick) {
1708 1709 1710
			return;
		}

F
Francisco Moreira 已提交
1711 1712
		const remoteCharCnt = remotePick.label.length;

1713
		await repository.pullFrom(false, remotePick.label, branchPick.label.slice(remoteCharCnt + 1));
1714 1715
	}

J
Joao Moreno 已提交
1716
	@command('git.pull', { repository: true })
J
Joao Moreno 已提交
1717 1718
	async pull(repository: Repository): Promise<void> {
		const remotes = repository.remotes;
J
Joao Moreno 已提交
1719 1720 1721 1722 1723 1724

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

J
Joao Moreno 已提交
1725
		await repository.pull(repository.HEAD);
J
Joao Moreno 已提交
1726 1727
	}

J
Joao Moreno 已提交
1728
	@command('git.pullRebase', { repository: true })
J
Joao Moreno 已提交
1729 1730
	async pullRebase(repository: Repository): Promise<void> {
		const remotes = repository.remotes;
J
Joao Moreno 已提交
1731 1732 1733 1734 1735 1736

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

J
Joao Moreno 已提交
1737
		await repository.pullWithRebase(repository.HEAD);
J
Joao Moreno 已提交
1738 1739
	}

J
Joao Moreno 已提交
1740
	private async _push(repository: Repository, pushOptions: PushOptions) {
J
Joao Moreno 已提交
1741
		const remotes = repository.remotes;
1742

J
Joao Moreno 已提交
1743
		if (remotes.length === 0) {
J
Joao Moreno 已提交
1744 1745 1746
			if (!pushOptions.silent) {
				window.showWarningMessage(localize('no remotes to push', "Your repository has no remotes configured to push to."));
			}
J
Joao Moreno 已提交
1747 1748
			return;
		}
1749

J
Joao Moreno 已提交
1750 1751 1752 1753 1754 1755
		const config = workspace.getConfiguration('git', Uri.file(repository.root));
		let forcePushMode: ForcePushMode | undefined = undefined;

		if (pushOptions.forcePush) {
			if (!config.get<boolean>('allowForcePush')) {
				await window.showErrorMessage(localize('force push not allowed', "Force push is not allowed, please enable it with the 'git.allowForcePush' setting."));
1756 1757
				return;
			}
J
Joao Moreno 已提交
1758

J
Joao Moreno 已提交
1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772
			forcePushMode = config.get<boolean>('useForcePushWithLease') === true ? ForcePushMode.ForceWithLease : ForcePushMode.Force;

			if (config.get<boolean>('confirmForcePush')) {
				const message = localize('confirm force push', "You are about to force push your changes, this can be destructive and could inadvertedly overwrite changes made by others.\n\nAre you sure to continue?");
				const yes = localize('ok', "OK");
				const neverAgain = localize('never ask again', "OK, Don't Ask Again");
				const pick = await window.showWarningMessage(message, { modal: true }, yes, neverAgain);

				if (pick === neverAgain) {
					config.update('confirmForcePush', false, true);
				} else if (pick !== yes) {
					return;
				}
			}
J
Joao Moreno 已提交
1773 1774
		}

1775 1776
		if (pushOptions.pushType === PushType.PushFollowTags) {
			await repository.pushFollowTags(undefined, forcePushMode);
1777 1778 1779
			return;
		}

1780
		if (!repository.HEAD || !repository.HEAD.name) {
J
Joao Moreno 已提交
1781 1782 1783
			if (!pushOptions.silent) {
				window.showWarningMessage(localize('nobranch', "Please check out a branch to push to a remote."));
			}
1784 1785 1786
			return;
		}

1787 1788 1789 1790 1791 1792 1793
		if (pushOptions.pushType === PushType.Push) {
			try {
				await repository.push(repository.HEAD, forcePushMode);
			} catch (err) {
				if (err.gitErrorCode !== GitErrorCodes.NoUpstreamBranch) {
					throw err;
				}
1794

J
Joao Moreno 已提交
1795 1796 1797 1798
				if (pushOptions.silent) {
					return;
				}

1799 1800 1801 1802 1803 1804 1805 1806 1807 1808
				const branchName = repository.HEAD.name;
				const message = localize('confirm publish branch', "The branch '{0}' has no upstream branch. Would you like to publish this branch?", branchName);
				const yes = localize('ok', "OK");
				const pick = await window.showWarningMessage(message, { modal: true }, yes);

				if (pick === yes) {
					await this.publish(repository);
				}
			}
		} else {
1809
			const branchName = repository.HEAD.name;
1810 1811 1812
			const picks = remotes.filter(r => r.pushUrl !== undefined).map(r => ({ label: r.name, description: r.pushUrl! }));
			const placeHolder = localize('pick remote', "Pick a remote to publish the branch '{0}' to:", branchName);
			const pick = await window.showQuickPick(picks, { placeHolder });
1813

1814 1815
			if (!pick) {
				return;
1816
			}
1817 1818

			await repository.pushTo(pick.label, branchName, undefined, forcePushMode);
1819
		}
J
Joao Moreno 已提交
1820 1821
	}

1822 1823
	@command('git.push', { repository: true })
	async push(repository: Repository): Promise<void> {
J
Joao Moreno 已提交
1824
		await this._push(repository, { pushType: PushType.Push });
1825
	}
1826

1827 1828
	@command('git.pushForce', { repository: true })
	async pushForce(repository: Repository): Promise<void> {
J
Joao Moreno 已提交
1829
		await this._push(repository, { pushType: PushType.Push, forcePush: true });
1830
	}
1831

1832
	@command('git.pushWithTags', { repository: true })
1833 1834
	async pushFollowTags(repository: Repository): Promise<void> {
		await this._push(repository, { pushType: PushType.PushFollowTags });
1835
	}
1836

1837
	@command('git.pushWithTagsForce', { repository: true })
1838 1839
	async pushFollowTagsForce(repository: Repository): Promise<void> {
		await this._push(repository, { pushType: PushType.PushFollowTags, forcePush: true });
1840 1841
	}

J
Joao Moreno 已提交
1842
	@command('git.pushTo', { repository: true })
J
Joao Moreno 已提交
1843
	async pushTo(repository: Repository): Promise<void> {
J
Joao Moreno 已提交
1844
		await this._push(repository, { pushType: PushType.PushTo });
1845
	}
J
Joao Moreno 已提交
1846

1847 1848
	@command('git.pushToForce', { repository: true })
	async pushToForce(repository: Repository): Promise<void> {
J
Joao Moreno 已提交
1849
		await this._push(repository, { pushType: PushType.PushTo, forcePush: true });
J
Joao Moreno 已提交
1850 1851
	}

O
Omkar Manjrekar 已提交
1852 1853
	@command('git.addRemote', { repository: true })
	async addRemote(repository: Repository): Promise<void> {
1854 1855
		const remotes = repository.remotes;

O
Omkar Manjrekar 已提交
1856 1857
		const sanitize = (name: string) => {
			name = name.trim();
J
Joao Moreno 已提交
1858
			return name && name.replace(/^\.|\/\.|\.\.|~|\^|:|\/$|\.lock$|\.lock\/|\\|\*|\s|^\s*$|\.$|\[|\]$/g, '-');
O
Omkar Manjrekar 已提交
1859
		};
O
Omkar Manjrekar 已提交
1860

O
Omkar Manjrekar 已提交
1861
		const resultName = await window.showInputBox({
O
Omkar Manjrekar 已提交
1862 1863 1864 1865
			placeHolder: localize('remote name', "Remote name"),
			prompt: localize('provide remote name', "Please provide a remote name"),
			ignoreFocusOut: true,
			validateInput: (name: string) => {
O
Omkar Manjrekar 已提交
1866
				if (sanitize(name)) {
O
Omkar Manjrekar 已提交
1867 1868
					return null;
				}
O
Omkar Manjrekar 已提交
1869
				return localize('remote name format invalid', "Remote name format invalid");
O
Omkar Manjrekar 已提交
1870
			}
O
Omkar Manjrekar 已提交
1871
		});
O
Omkar Manjrekar 已提交
1872

O
Omkar Manjrekar 已提交
1873
		const name = sanitize(resultName || '');
O
Omkar Manjrekar 已提交
1874

O
Omkar Manjrekar 已提交
1875 1876 1877 1878 1879
		if (!name) {
			return;
		}

		if (remotes.find(r => r.name === name)) {
J
Joao Moreno 已提交
1880
			window.showErrorMessage(localize('remote already exists', "Remote '{0}' already exists.", name));
O
Omkar Manjrekar 已提交
1881
			return;
O
Omkar Manjrekar 已提交
1882
		}
O
Omkar Manjrekar 已提交
1883

J
Joao Moreno 已提交
1884
		const url = await window.showInputBox({
O
Omkar Manjrekar 已提交
1885
			placeHolder: localize('remote url', "Remote URL"),
O
Omkar Manjrekar 已提交
1886
			prompt: localize('provide remote URL', "Enter URL for remote \"{0}\"", name),
1887
			ignoreFocusOut: true
O
Omkar Manjrekar 已提交
1888 1889 1890 1891 1892 1893 1894
		});

		if (!url) {
			return;
		}

		await repository.addRemote(name, url);
O
Omkar Manjrekar 已提交
1895 1896
	}

O
Omkar Manjrekar 已提交
1897 1898
	@command('git.removeRemote', { repository: true })
	async removeRemote(repository: Repository): Promise<void> {
O
Omkar Manjrekar 已提交
1899 1900 1901
		const remotes = repository.remotes;

		if (remotes.length === 0) {
1902
			window.showErrorMessage(localize('no remotes added', "Your repository has no remotes."));
O
Omkar Manjrekar 已提交
1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913
			return;
		}

		const picks = remotes.map(r => r.name);
		const placeHolder = localize('remove remote', "Pick a remote to remove");

		const remoteName = await window.showQuickPick(picks, { placeHolder });

		if (!remoteName) {
			return;
		}
O
Omkar Manjrekar 已提交
1914

O
Omkar Manjrekar 已提交
1915
		await repository.removeRemote(remoteName);
O
Omkar Manjrekar 已提交
1916
	}
O
Omkar Manjrekar 已提交
1917

J
Joao Moreno 已提交
1918
	private async _sync(repository: Repository, rebase: boolean): Promise<void> {
J
Joao Moreno 已提交
1919
		const HEAD = repository.HEAD;
J
Joao Moreno 已提交
1920

1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931
		if (!HEAD) {
			return;
		} else if (!HEAD.upstream) {
			const branchName = HEAD.name;
			const message = localize('confirm publish branch', "The branch '{0}' has no upstream branch. Would you like to publish this branch?", branchName);
			const yes = localize('ok', "OK");
			const pick = await window.showWarningMessage(message, { modal: true }, yes);

			if (pick === yes) {
				await this.publish(repository);
			}
J
Joao Moreno 已提交
1932 1933 1934
			return;
		}

J
Joao Moreno 已提交
1935 1936 1937 1938
		const remoteName = HEAD.remote || HEAD.upstream.remote;
		const remote = repository.remotes.find(r => r.name === remoteName);
		const isReadonly = remote && remote.isReadOnly;

J
Joao Moreno 已提交
1939
		const config = workspace.getConfiguration('git');
J
Joao Moreno 已提交
1940
		const shouldPrompt = !isReadonly && config.get<boolean>('confirmSync') === true;
J
Joao Moreno 已提交
1941 1942

		if (shouldPrompt) {
J
Joao Moreno 已提交
1943
			const message = localize('sync is unpredictable', "This action will push and pull commits to and from '{0}/{1}'.", HEAD.upstream.remote, HEAD.upstream.name);
J
Joao Moreno 已提交
1944
			const yes = localize('ok', "OK");
B
Benjamin Pasero 已提交
1945
			const neverAgain = localize('never again', "OK, Don't Show Again");
J
Joao Moreno 已提交
1946 1947 1948 1949 1950 1951 1952 1953 1954
			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 已提交
1955
		if (rebase) {
J
Joao Moreno 已提交
1956
			await repository.syncRebase(HEAD);
J
Joao Moreno 已提交
1957
		} else {
J
Joao Moreno 已提交
1958
			await repository.sync(HEAD);
J
Joao Moreno 已提交
1959 1960 1961 1962
		}
	}

	@command('git.sync', { repository: true })
1963 1964 1965 1966 1967 1968 1969 1970 1971 1972
	async sync(repository: Repository): Promise<void> {
		try {
			await this._sync(repository, false);
		} catch (err) {
			if (/Cancelled/i.test(err && (err.message || err.stderr || ''))) {
				return;
			}

			throw err;
		}
J
Joao Moreno 已提交
1973 1974
	}

J
Joao 已提交
1975 1976 1977 1978 1979 1980 1981 1982 1983
	@command('git._syncAll')
	async syncAll(): Promise<void> {
		await Promise.all(this.model.repositories.map(async repository => {
			const HEAD = repository.HEAD;

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

J
Joao Moreno 已提交
1984
			await repository.sync(HEAD);
J
Joao 已提交
1985 1986 1987
		}));
	}

1988
	@command('git.syncRebase', { repository: true })
1989 1990 1991 1992 1993 1994 1995 1996 1997 1998
	async syncRebase(repository: Repository): Promise<void> {
		try {
			await this._sync(repository, true);
		} catch (err) {
			if (/Cancelled/i.test(err && (err.message || err.stderr || ''))) {
				return;
			}

			throw err;
		}
J
Joao Moreno 已提交
1999 2000
	}

J
Joao Moreno 已提交
2001
	@command('git.publish', { repository: true })
J
Joao Moreno 已提交
2002 2003
	async publish(repository: Repository): Promise<void> {
		const remotes = repository.remotes;
J
Joao Moreno 已提交
2004 2005 2006 2007 2008 2009

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

J
Joao Moreno 已提交
2010
		const branchName = repository.HEAD && repository.HEAD.name || '';
M
Markus Wolf 已提交
2011 2012 2013 2014 2015 2016
		const selectRemote = async () => {
			const picks = repository.remotes.map(r => r.name);
			const placeHolder = localize('pick remote', "Pick a remote to publish the branch '{0}' to:", branchName);
			return await window.showQuickPick(picks, { placeHolder });
		};
		const choice = remotes.length === 1 ? remotes[0].name : await selectRemote();
J
Joao Moreno 已提交
2017 2018 2019 2020 2021

		if (!choice) {
			return;
		}

J
Joao Moreno 已提交
2022
		await repository.pushTo(choice, branchName, true);
J
Joao Moreno 已提交
2023 2024
	}

2025 2026
	@command('git.ignore')
	async ignore(...resourceStates: SourceControlResourceState[]): Promise<void> {
2027 2028
		resourceStates = resourceStates.filter(s => !!s);

J
Joao Moreno 已提交
2029
		if (resourceStates.length === 0 || (resourceStates[0] && !(resourceStates[0].resourceUri instanceof Uri))) {
2030
			const resource = this.getSCMResource();
N
NKumar2 已提交
2031

2032
			if (!resource) {
J
Joao Moreno 已提交
2033 2034 2035
				return;
			}

2036
			resourceStates = [resource];
J
Joao Moreno 已提交
2037 2038
		}

2039
		const resources = resourceStates
J
Joao Moreno 已提交
2040 2041 2042
			.filter(s => s instanceof Resource)
			.map(r => r.resourceUri);

2043
		if (!resources.length) {
N
NKumar2 已提交
2044 2045 2046
			return;
		}

2047
		await this.runByRepository(resources, async (repository, resources) => repository.ignore(resources));
N
NKumar2 已提交
2048 2049
	}

J
Joao Moreno 已提交
2050
	private async _stash(repository: Repository, includeUntracked = false): Promise<void> {
2051 2052
		const noUnstagedChanges = repository.workingTreeGroup.resourceStates.length === 0;
		const noStagedChanges = repository.indexGroup.resourceStates.length === 0;
2053

2054
		if (noUnstagedChanges && noStagedChanges) {
K
Krzysztof Cieślak 已提交
2055 2056 2057
			window.showInformationMessage(localize('no changes stash', "There are no changes to stash."));
			return;
		}
J
Joao Moreno 已提交
2058

2059
		const message = await this.getStashMessage();
J
Joao Moreno 已提交
2060 2061 2062 2063 2064

		if (typeof message === 'undefined') {
			return;
		}

J
Joao Moreno 已提交
2065
		await repository.createStash(message, includeUntracked);
K
Krzysztof Cieślak 已提交
2066 2067
	}

2068 2069 2070 2071 2072 2073 2074
	private async getStashMessage(): Promise<string | undefined> {
		return await window.showInputBox({
			prompt: localize('provide stash message', "Optionally provide a stash message"),
			placeHolder: localize('stash message', "Stash message")
		});
	}

J
Joao Moreno 已提交
2075 2076 2077 2078 2079 2080 2081 2082 2083 2084
	@command('git.stash', { repository: true })
	stash(repository: Repository): Promise<void> {
		return this._stash(repository);
	}

	@command('git.stashIncludeUntracked', { repository: true })
	stashIncludeUntracked(repository: Repository): Promise<void> {
		return this._stash(repository, true);
	}

J
Joao Moreno 已提交
2085
	@command('git.stashPop', { repository: true })
J
Joao Moreno 已提交
2086
	async stashPop(repository: Repository): Promise<void> {
2087
		const placeHolder = localize('pick stash to pop', "Pick a stash to pop");
J
Joao Moreno 已提交
2088
		const stash = await this.pickStash(repository, placeHolder);
2089

J
Joao Moreno 已提交
2090
		if (!stash) {
2091 2092 2093
			return;
		}

J
Joao Moreno 已提交
2094
		await repository.popStash(stash.index);
2095 2096 2097 2098
	}

	@command('git.stashPopLatest', { repository: true })
	async stashPopLatest(repository: Repository): Promise<void> {
J
Joao Moreno 已提交
2099
		const stashes = await repository.getStashes();
J
Joao Moreno 已提交
2100

J
Joao Moreno 已提交
2101 2102
		if (stashes.length === 0) {
			window.showInformationMessage(localize('no stashes', "There are no stashes in the repository."));
K
Krzysztof Cieślak 已提交
2103 2104 2105
			return;
		}

2106 2107 2108 2109 2110 2111
		await repository.popStash();
	}

	@command('git.stashApply', { repository: true })
	async stashApply(repository: Repository): Promise<void> {
		const placeHolder = localize('pick stash to apply', "Pick a stash to apply");
J
Joao Moreno 已提交
2112
		const stash = await this.pickStash(repository, placeHolder);
K
Krzysztof Cieślak 已提交
2113

J
Joao Moreno 已提交
2114
		if (!stash) {
K
Krzysztof Cieślak 已提交
2115 2116
			return;
		}
J
Joao Moreno 已提交
2117

J
Joao Moreno 已提交
2118
		await repository.applyStash(stash.index);
K
Krzysztof Cieślak 已提交
2119 2120
	}

2121 2122
	@command('git.stashApplyLatest', { repository: true })
	async stashApplyLatest(repository: Repository): Promise<void> {
J
Joao Moreno 已提交
2123
		const stashes = await repository.getStashes();
J
Joao Moreno 已提交
2124

J
Joao Moreno 已提交
2125 2126
		if (stashes.length === 0) {
			window.showInformationMessage(localize('no stashes', "There are no stashes in the repository."));
2127 2128 2129 2130 2131 2132
			return;
		}

		await repository.applyStash();
	}

J
Joao Moreno 已提交
2133
	private async pickStash(repository: Repository, placeHolder: string): Promise<Stash | undefined> {
2134 2135
		const stashes = await repository.getStashes();

J
Joao Moreno 已提交
2136 2137
		if (stashes.length === 0) {
			window.showInformationMessage(localize('no stashes', "There are no stashes in the repository."));
K
Krzysztof Cieślak 已提交
2138 2139 2140
			return;
		}

J
Joao Moreno 已提交
2141 2142 2143
		const picks = stashes.map(stash => ({ label: `#${stash.index}:  ${stash.description}`, description: '', details: '', stash }));
		const result = await window.showQuickPick(picks, { placeHolder });
		return result && result.stash;
J
Joao Moreno 已提交
2144
	}
K
Krzysztof Cieślak 已提交
2145

J
Joao Moreno 已提交
2146
	private createCommand(id: string, key: string, method: Function, options: CommandOptions): (...args: any[]) => any {
2147
		const result = (...args: any[]) => {
J
Joao Moreno 已提交
2148 2149
			let result: Promise<any>;

J
Joao Moreno 已提交
2150
			if (!options.repository) {
J
Joao Moreno 已提交
2151 2152
				result = Promise.resolve(method.apply(this, args));
			} else {
J
Joao Moreno 已提交
2153 2154
				// try to guess the repository based on the first argument
				const repository = this.model.getRepository(args[0]);
J
Joao Moreno 已提交
2155 2156 2157 2158 2159 2160 2161 2162 2163
				let repositoryPromise: Promise<Repository | undefined>;

				if (repository) {
					repositoryPromise = Promise.resolve(repository);
				} else if (this.model.repositories.length === 1) {
					repositoryPromise = Promise.resolve(this.model.repositories[0]);
				} else {
					repositoryPromise = this.model.pickRepository();
				}
2164

J
Joao Moreno 已提交
2165
				result = repositoryPromise.then(repository => {
J
Joao Moreno 已提交
2166
					if (!repository) {
J
Joao 已提交
2167
						return Promise.resolve();
J
Joao Moreno 已提交
2168 2169
					}

J
Joao Moreno 已提交
2170
					return Promise.resolve(method.apply(this, [repository, ...args]));
J
Joao Moreno 已提交
2171
				});
J
Joao Moreno 已提交
2172 2173
			}

K
kieferrm 已提交
2174
			/* __GDPR__
K
kieferrm 已提交
2175 2176 2177 2178
				"git.command" : {
					"command" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
				}
			*/
J
Joao Moreno 已提交
2179 2180
			this.telemetryReporter.sendTelemetryEvent('git.command', { command: id });

J
Joao Moreno 已提交
2181
			return result.catch(async err => {
J
Joao Moreno 已提交
2182
				const options: MessageOptions = {
2183
					modal: true
J
Joao Moreno 已提交
2184 2185
				};

J
Joao Moreno 已提交
2186
				let message: string;
2187
				let type: 'error' | 'warning' = 'error';
J
Joao Moreno 已提交
2188

J
Joao Moreno 已提交
2189 2190 2191 2192 2193
				const choices = new Map<string, () => void>();
				const openOutputChannelChoice = localize('open git log', "Open Git Log");
				const outputChannel = this.outputChannel as OutputChannel;
				choices.set(openOutputChannelChoice, () => outputChannel.show());

J
Joao Moreno 已提交
2194
				switch (err.gitErrorCode) {
2195
					case GitErrorCodes.DirtyWorkTree:
J
Joao Moreno 已提交
2196 2197
						message = localize('clean repo', "Please clean your repository working tree before checkout.");
						break;
2198
					case GitErrorCodes.PushRejected:
J
Joao Moreno 已提交
2199
						message = localize('cant push', "Can't push refs to remote. Try running 'Pull' first to integrate your changes.");
2200
						break;
2201 2202 2203 2204 2205
					case GitErrorCodes.Conflict:
						message = localize('merge conflicts', "There are merge conflicts. Resolve them before committing.");
						type = 'warning';
						options.modal = false;
						break;
J
Joao Moreno 已提交
2206 2207 2208 2209 2210
					case GitErrorCodes.StashConflict:
						message = localize('stash merge conflicts', "There were merge conflicts while applying the stash.");
						type = 'warning';
						options.modal = false;
						break;
2211 2212
					case GitErrorCodes.NoUserNameConfigured:
					case GitErrorCodes.NoUserEmailConfigured:
J
Joao Moreno 已提交
2213 2214
						message = localize('missing user info', "Make sure you configure your 'user.name' and 'user.email' in git.");
						choices.set(localize('learn more', "Learn More"), () => commands.executeCommand('vscode.open', Uri.parse('https://git-scm.com/book/en/v2/Getting-Started-First-Time-Git-Setup')));
2215
						break;
J
Joao Moreno 已提交
2216
					default:
2217 2218 2219
						const hint = (err.stderr || err.message || String(err))
							.replace(/^error: /mi, '')
							.replace(/^> husky.*$/mi, '')
J
Joao Moreno 已提交
2220
							.split(/[\r\n]/)
J
João Moreno 已提交
2221
							.filter((line: string) => !!line)
2222 2223 2224 2225 2226
						[0];

						message = hint
							? localize('git error details', "Git: {0}", hint)
							: localize('git error', "Git error");
J
Joao Moreno 已提交
2227 2228 2229 2230 2231 2232 2233 2234 2235

						break;
				}

				if (!message) {
					console.error(err);
					return;
				}

J
Joao Moreno 已提交
2236 2237 2238 2239 2240 2241 2242
				const allChoices = Array.from(choices.keys());
				const result = type === 'error'
					? await window.showErrorMessage(message, options, ...allChoices)
					: await window.showWarningMessage(message, options, ...allChoices);

				if (result) {
					const resultFn = choices.get(result);
J
Joao Moreno 已提交
2243

J
Joao Moreno 已提交
2244 2245 2246
					if (resultFn) {
						resultFn();
					}
J
Joao Moreno 已提交
2247 2248 2249
				}
			});
		};
2250 2251

		// patch this object, so people can call methods directly
2252
		(this as any)[key] = result;
2253 2254

		return result;
J
Joao Moreno 已提交
2255 2256
	}

2257
	private getSCMResource(uri?: Uri): Resource | undefined {
J
Joao Moreno 已提交
2258
		uri = uri ? uri : (window.activeTextEditor && window.activeTextEditor.document.uri);
J
Joao Moreno 已提交
2259

J
Joao Moreno 已提交
2260
		this.outputChannel.appendLine(`git.getSCMResource.uri ${uri && uri.toString()}`);
J
Joao Moreno 已提交
2261

J
Joao Moreno 已提交
2262 2263 2264
		for (const r of this.model.repositories.map(r => r.root)) {
			this.outputChannel.appendLine(`repo root ${r}`);
		}
J
Joao Moreno 已提交
2265

J
Joao Moreno 已提交
2266
		if (!uri) {
2267
			return undefined;
J
Joao Moreno 已提交
2268 2269 2270
		}

		if (uri.scheme === 'git') {
J
Joao Moreno 已提交
2271 2272
			const { path } = fromGitUri(uri);
			uri = Uri.file(path);
J
Joao Moreno 已提交
2273 2274 2275 2276
		}

		if (uri.scheme === 'file') {
			const uriString = uri.toString();
J
Joao Moreno 已提交
2277
			const repository = this.model.getRepository(uri);
2278

J
Joao Moreno 已提交
2279
			if (!repository) {
2280 2281
				return undefined;
			}
J
Joao Moreno 已提交
2282

J
Joao Moreno 已提交
2283 2284
			return repository.workingTreeGroup.resourceStates.filter(r => r.resourceUri.toString() === uriString)[0]
				|| repository.indexGroup.resourceStates.filter(r => r.resourceUri.toString() === uriString)[0];
J
Joao Moreno 已提交
2285
		}
2286
		return undefined;
J
Joao Moreno 已提交
2287 2288
	}

J
Joao Moreno 已提交
2289
	private runByRepository<T>(resource: Uri, fn: (repository: Repository, resource: Uri) => Promise<T>): Promise<T[]>;
J
Joao Moreno 已提交
2290 2291 2292 2293 2294 2295
	private runByRepository<T>(resources: Uri[], fn: (repository: Repository, resources: Uri[]) => Promise<T>): Promise<T[]>;
	private async runByRepository<T>(arg: Uri | Uri[], fn: (repository: Repository, resources: any) => Promise<T>): Promise<T[]> {
		const resources = arg instanceof Uri ? [arg] : arg;
		const isSingleResource = arg instanceof Uri;

		const groups = resources.reduce((result, resource) => {
2296
			let repository = this.model.getRepository(resource);
J
Joao Moreno 已提交
2297 2298 2299 2300 2301 2302

			if (!repository) {
				console.warn('Could not find git repository for ', resource);
				return result;
			}

2303
			// Could it be a submodule?
2304
			if (pathEquals(resource.fsPath, repository.root)) {
2305 2306 2307
				repository = this.model.getRepositoryForSubmodule(resource) || repository;
			}

J
Joao Moreno 已提交
2308
			const tuple = result.filter(p => p.repository === repository)[0];
J
Joao Moreno 已提交
2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324

			if (tuple) {
				tuple.resources.push(resource);
			} else {
				result.push({ repository, resources: [resource] });
			}

			return result;
		}, [] as { repository: Repository, resources: Uri[] }[]);

		const promises = groups
			.map(({ repository, resources }) => fn(repository as Repository, isSingleResource ? resources[0] : resources));

		return Promise.all(promises);
	}

J
Joao Moreno 已提交
2325 2326 2327
	dispose(): void {
		this.disposables.forEach(d => d.dispose());
	}
J
João Moreno 已提交
2328
}