repository.ts 56.9 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.
 *--------------------------------------------------------------------------------------------*/

6
import * as fs from 'fs';
J
Joao Moreno 已提交
7
import * as path from 'path';
8
import { CancellationToken, Command, Disposable, env, Event, EventEmitter, LogLevel, Memento, OutputChannel, ProgressLocation, ProgressOptions, scm, SourceControl, SourceControlInputBox, SourceControlInputBoxValidation, SourceControlInputBoxValidationType, SourceControlResourceDecorations, SourceControlResourceGroup, SourceControlResourceState, ThemeColor, Uri, window, workspace, WorkspaceEdit, Decoration } from 'vscode';
J
Joao Moreno 已提交
9
import * as nls from 'vscode-nls';
10 11 12 13
import { Branch, Change, GitErrorCodes, LogOptions, Ref, RefType, Remote, Status } from './api/git';
import { AutoFetcher } from './autofetch';
import { debounce, memoize, throttle } from './decorators';
import { Commit, CommitOptions, ForcePushMode, GitError, Repository as BaseRepository, Stash, Submodule } from './git';
M
Matt Bierner 已提交
14
import { StatusBarCommands } from './statusbar';
15 16
import { toGitUri } from './uri';
import { anyEvent, combinedDisposable, debounceEvent, dispose, EmptyDisposable, eventToPromise, filterEvent, find, IDisposable, isDescendant, onceEvent } from './util';
J
Joao Moreno 已提交
17
import { IFileWatcher, watch } from './watch';
J
Joao Moreno 已提交
18

J
Joao Moreno 已提交
19 20
const timeout = (millis: number) => new Promise(c => setTimeout(c, millis));

J
Joao Moreno 已提交
21
const localize = nls.loadMessageBundle();
J
Joao Moreno 已提交
22 23 24 25 26 27
const iconsRootPath = path.join(path.dirname(__dirname), 'resources', 'icons');

function getIconUri(iconName: string, theme: string): Uri {
	return Uri.file(path.join(iconsRootPath, theme, `${iconName}.svg`));
}

28
export const enum RepositoryState {
J
Joao Moreno 已提交
29
	Idle,
J
Joao Moreno 已提交
30
	Disposed
J
Joao Moreno 已提交
31 32
}

33
export const enum ResourceGroupType {
J
Joao Moreno 已提交
34 35
	Merge,
	Index,
36 37
	WorkingTree,
	Untracked
J
Joao Moreno 已提交
38 39
}

J
Joao Moreno 已提交
40
export class Resource implements SourceControlResourceState {
J
Joao Moreno 已提交
41

42
	@memoize
J
Joao Moreno 已提交
43
	get resourceUri(): Uri {
J
Joao Moreno 已提交
44
		if (this.renameResourceUri && (this._type === Status.MODIFIED || this._type === Status.DELETED || this._type === Status.INDEX_RENAMED || this._type === Status.INDEX_COPIED)) {
J
Joao Moreno 已提交
45 46 47 48
			return this.renameResourceUri;
		}

		return this._resourceUri;
49 50 51
	}

	@memoize
J
Joao Moreno 已提交
52 53 54 55 56 57
	get command(): Command {
		return {
			command: 'git.openResource',
			title: localize('open', "Open"),
			arguments: [this]
		};
J
Joao Moreno 已提交
58 59
	}

J
Joao Moreno 已提交
60
	get resourceGroupType(): ResourceGroupType { return this._resourceGroupType; }
J
Joao Moreno 已提交
61
	get type(): Status { return this._type; }
J
Joao Moreno 已提交
62 63
	get original(): Uri { return this._resourceUri; }
	get renameResourceUri(): Uri | undefined { return this._renameResourceUri; }
J
Joao Moreno 已提交
64

65
	private static Icons: any = {
J
Joao Moreno 已提交
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
		light: {
			Modified: getIconUri('status-modified', 'light'),
			Added: getIconUri('status-added', 'light'),
			Deleted: getIconUri('status-deleted', 'light'),
			Renamed: getIconUri('status-renamed', 'light'),
			Copied: getIconUri('status-copied', 'light'),
			Untracked: getIconUri('status-untracked', 'light'),
			Ignored: getIconUri('status-ignored', 'light'),
			Conflict: getIconUri('status-conflict', 'light'),
		},
		dark: {
			Modified: getIconUri('status-modified', 'dark'),
			Added: getIconUri('status-added', 'dark'),
			Deleted: getIconUri('status-deleted', 'dark'),
			Renamed: getIconUri('status-renamed', 'dark'),
			Copied: getIconUri('status-copied', 'dark'),
			Untracked: getIconUri('status-untracked', 'dark'),
			Ignored: getIconUri('status-ignored', 'dark'),
			Conflict: getIconUri('status-conflict', 'dark')
		}
	};

J
Joao Moreno 已提交
88
	private getIconPath(theme: string): Uri {
J
Joao Moreno 已提交
89 90 91 92 93 94 95 96 97 98
		switch (this.type) {
			case Status.INDEX_MODIFIED: return Resource.Icons[theme].Modified;
			case Status.MODIFIED: return Resource.Icons[theme].Modified;
			case Status.INDEX_ADDED: return Resource.Icons[theme].Added;
			case Status.INDEX_DELETED: return Resource.Icons[theme].Deleted;
			case Status.DELETED: return Resource.Icons[theme].Deleted;
			case Status.INDEX_RENAMED: return Resource.Icons[theme].Renamed;
			case Status.INDEX_COPIED: return Resource.Icons[theme].Copied;
			case Status.UNTRACKED: return Resource.Icons[theme].Untracked;
			case Status.IGNORED: return Resource.Icons[theme].Ignored;
99
			case Status.INTENT_TO_ADD: return Resource.Icons[theme].Added;
J
Joao Moreno 已提交
100 101 102 103 104 105 106
			case Status.BOTH_DELETED: return Resource.Icons[theme].Conflict;
			case Status.ADDED_BY_US: return Resource.Icons[theme].Conflict;
			case Status.DELETED_BY_THEM: return Resource.Icons[theme].Conflict;
			case Status.ADDED_BY_THEM: return Resource.Icons[theme].Conflict;
			case Status.DELETED_BY_US: return Resource.Icons[theme].Conflict;
			case Status.BOTH_ADDED: return Resource.Icons[theme].Conflict;
			case Status.BOTH_MODIFIED: return Resource.Icons[theme].Conflict;
J
Joao Moreno 已提交
107
			default: throw new Error('Unknown git status: ' + this.type);
J
Joao Moreno 已提交
108 109 110
		}
	}

111 112 113 114 115 116 117 118 119 120 121
	private get tooltip(): string {
		switch (this.type) {
			case Status.INDEX_MODIFIED: return localize('index modified', "Index Modified");
			case Status.MODIFIED: return localize('modified', "Modified");
			case Status.INDEX_ADDED: return localize('index added', "Index Added");
			case Status.INDEX_DELETED: return localize('index deleted', "Index Deleted");
			case Status.DELETED: return localize('deleted', "Deleted");
			case Status.INDEX_RENAMED: return localize('index renamed', "Index Renamed");
			case Status.INDEX_COPIED: return localize('index copied', "Index Copied");
			case Status.UNTRACKED: return localize('untracked', "Untracked");
			case Status.IGNORED: return localize('ignored', "Ignored");
122
			case Status.INTENT_TO_ADD: return localize('intent to add', "Intent to Add");
123 124 125 126 127 128 129 130 131 132 133
			case Status.BOTH_DELETED: return localize('both deleted', "Both Deleted");
			case Status.ADDED_BY_US: return localize('added by us', "Added By Us");
			case Status.DELETED_BY_THEM: return localize('deleted by them', "Deleted By Them");
			case Status.ADDED_BY_THEM: return localize('added by them', "Added By Them");
			case Status.DELETED_BY_US: return localize('deleted by us', "Deleted By Us");
			case Status.BOTH_ADDED: return localize('both added', "Both Added");
			case Status.BOTH_MODIFIED: return localize('both modified', "Both Modified");
			default: return '';
		}
	}

J
Joao Moreno 已提交
134 135 136 137 138 139
	private get strikeThrough(): boolean {
		switch (this.type) {
			case Status.DELETED:
			case Status.BOTH_DELETED:
			case Status.DELETED_BY_THEM:
			case Status.DELETED_BY_US:
J
Joao Moreno 已提交
140
			case Status.INDEX_DELETED:
J
Joao Moreno 已提交
141 142 143 144 145 146
				return true;
			default:
				return false;
		}
	}

147 148
	@memoize
	private get faded(): boolean {
149 150 151 152
		// TODO@joao
		return false;
		// const workspaceRootPath = this.workspaceRoot.fsPath;
		// return this.resourceUri.fsPath.substr(0, workspaceRootPath.length) !== workspaceRootPath;
153 154
	}

J
Joao Moreno 已提交
155
	get decorations(): SourceControlResourceDecorations {
156 157
		const light = this._useIcons ? { iconPath: this.getIconPath('light') } : undefined;
		const dark = this._useIcons ? { iconPath: this.getIconPath('dark') } : undefined;
158
		const tooltip = this.tooltip;
159 160
		const strikeThrough = this.strikeThrough;
		const faded = this.faded;
161
		return { strikeThrough, faded, tooltip, light, dark };
162 163
	}

J
Joao Moreno 已提交
164
	get letter(): string {
165
		switch (this.type) {
166 167 168 169
			case Status.INDEX_MODIFIED:
			case Status.MODIFIED:
				return 'M';
			case Status.INDEX_ADDED:
170
			case Status.INTENT_TO_ADD:
171 172 173 174 175 176
				return 'A';
			case Status.INDEX_DELETED:
			case Status.DELETED:
				return 'D';
			case Status.INDEX_RENAMED:
				return 'R';
177
			case Status.UNTRACKED:
178 179 180
				return 'U';
			case Status.IGNORED:
				return 'I';
J
Joao Moreno 已提交
181 182 183 184
			case Status.DELETED_BY_THEM:
				return 'D';
			case Status.DELETED_BY_US:
				return 'D';
185 186 187 188 189 190 191
			case Status.INDEX_COPIED:
			case Status.BOTH_DELETED:
			case Status.ADDED_BY_US:
			case Status.ADDED_BY_THEM:
			case Status.BOTH_ADDED:
			case Status.BOTH_MODIFIED:
				return 'C';
I
Ilya Biryukov 已提交
192
			default:
J
Joao Moreno 已提交
193
				throw new Error('Unknown git status: ' + this.type);
194 195 196
		}
	}

J
Joao Moreno 已提交
197
	get color(): ThemeColor {
198
		switch (this.type) {
199 200
			case Status.INDEX_MODIFIED:
			case Status.MODIFIED:
J
Johannes Rieken 已提交
201
				return new ThemeColor('gitDecoration.modifiedResourceForeground');
202 203
			case Status.INDEX_DELETED:
			case Status.DELETED:
J
Johannes Rieken 已提交
204
				return new ThemeColor('gitDecoration.deletedResourceForeground');
205
			case Status.INDEX_ADDED:
206
			case Status.INTENT_TO_ADD:
207
				return new ThemeColor('gitDecoration.addedResourceForeground');
J
Johannes Rieken 已提交
208
			case Status.INDEX_RENAMED:
209
			case Status.UNTRACKED:
J
Johannes Rieken 已提交
210
				return new ThemeColor('gitDecoration.untrackedResourceForeground');
211
			case Status.IGNORED:
J
Johannes Rieken 已提交
212
				return new ThemeColor('gitDecoration.ignoredResourceForeground');
213 214 215 216 217 218 219 220
			case Status.INDEX_COPIED:
			case Status.BOTH_DELETED:
			case Status.ADDED_BY_US:
			case Status.DELETED_BY_THEM:
			case Status.ADDED_BY_THEM:
			case Status.DELETED_BY_US:
			case Status.BOTH_ADDED:
			case Status.BOTH_MODIFIED:
J
Johannes Rieken 已提交
221
				return new ThemeColor('gitDecoration.conflictingResourceForeground');
I
Ilya Biryukov 已提交
222
			default:
J
Joao Moreno 已提交
223
				throw new Error('Unknown git status: ' + this.type);
224
		}
J
Joao Moreno 已提交
225 226
	}

J
Johannes Rieken 已提交
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
	get priority(): number {
		switch (this.type) {
			case Status.INDEX_MODIFIED:
			case Status.MODIFIED:
				return 2;
			case Status.IGNORED:
				return 3;
			case Status.INDEX_COPIED:
			case Status.BOTH_DELETED:
			case Status.ADDED_BY_US:
			case Status.DELETED_BY_THEM:
			case Status.ADDED_BY_THEM:
			case Status.DELETED_BY_US:
			case Status.BOTH_ADDED:
			case Status.BOTH_MODIFIED:
				return 4;
			default:
				return 1;
		}
	}

248
	get resourceDecoration(): Decoration {
249
		const title = this.tooltip;
250
		const letter = this.letter;
251
		const color = this.color;
J
Johannes Rieken 已提交
252
		const priority = this.priority;
253
		return { bubble: true, title, letter, color, priority };
254 255
	}

256
	constructor(
J
Joao Moreno 已提交
257
		private _resourceGroupType: ResourceGroupType,
258 259
		private _resourceUri: Uri,
		private _type: Status,
260
		private _useIcons: boolean,
261 262
		private _renameResourceUri?: Uri
	) { }
J
Joao Moreno 已提交
263 264
}

265
export const enum Operation {
J
Joao Moreno 已提交
266
	Status = 'Status',
J
Joao Moreno 已提交
267
	Config = 'Config',
268
	Diff = 'Diff',
J
Joao Moreno 已提交
269
	MergeBase = 'MergeBase',
J
Joao Moreno 已提交
270
	Add = 'Add',
J
Joao Moreno 已提交
271
	Remove = 'Remove',
J
Joao Moreno 已提交
272 273 274 275
	RevertFiles = 'RevertFiles',
	Commit = 'Commit',
	Clean = 'Clean',
	Branch = 'Branch',
J
Joao Moreno 已提交
276 277 278
	GetBranch = 'GetBranch',
	SetBranchUpstream = 'SetBranchUpstream',
	HashObject = 'HashObject',
J
Joao Moreno 已提交
279
	Checkout = 'Checkout',
280
	CheckoutTracking = 'CheckoutTracking',
J
Joao Moreno 已提交
281
	Reset = 'Reset',
J
Joao Moreno 已提交
282
	Remote = 'Remote',
J
Joao Moreno 已提交
283 284 285 286 287 288 289 290
	Fetch = 'Fetch',
	Pull = 'Pull',
	Push = 'Push',
	Sync = 'Sync',
	Show = 'Show',
	Stage = 'Stage',
	GetCommitTemplate = 'GetCommitTemplate',
	DeleteBranch = 'DeleteBranch',
291
	RenameBranch = 'RenameBranch',
292
	DeleteRef = 'DeleteRef',
J
Joao Moreno 已提交
293 294 295
	Merge = 'Merge',
	Ignore = 'Ignore',
	Tag = 'Tag',
X
Xhulio Hasani 已提交
296
	DeleteTag = 'DeleteTag',
J
Joao Moreno 已提交
297
	Stash = 'Stash',
J
Joao Moreno 已提交
298
	CheckIgnore = 'CheckIgnore',
J
Joao Moreno 已提交
299
	GetObjectDetails = 'GetObjectDetails',
300 301
	SubmoduleUpdate = 'SubmoduleUpdate',
	RebaseContinue = 'RebaseContinue',
J
Joao Moreno 已提交
302
	FindTrackingBranches = 'GetTracking',
R
rebornix 已提交
303
	Apply = 'Apply',
304
	Blame = 'Blame',
305
	Log = 'Log',
306 307
}

J
Joao Moreno 已提交
308 309 310 311
function isReadOnly(operation: Operation): boolean {
	switch (operation) {
		case Operation.Show:
		case Operation.GetCommitTemplate:
312
		case Operation.CheckIgnore:
J
Joao Moreno 已提交
313
		case Operation.GetObjectDetails:
314
		case Operation.MergeBase:
J
Joao Moreno 已提交
315 316 317 318 319 320
			return true;
		default:
			return false;
	}
}

321 322 323
function shouldShowProgress(operation: Operation): boolean {
	switch (operation) {
		case Operation.Fetch:
324
		case Operation.CheckIgnore:
J
Joao Moreno 已提交
325
		case Operation.GetObjectDetails:
J
Joao Moreno 已提交
326
		case Operation.Show:
327 328 329 330 331 332
			return false;
		default:
			return true;
	}
}

333
export interface Operations {
334
	isIdle(): boolean;
J
Joao Moreno 已提交
335
	shouldShowProgress(): boolean;
336 337 338 339 340
	isRunning(operation: Operation): boolean;
}

class OperationsImpl implements Operations {

J
Joao Moreno 已提交
341
	private operations = new Map<Operation, number>();
342

J
Joao Moreno 已提交
343 344
	start(operation: Operation): void {
		this.operations.set(operation, (this.operations.get(operation) || 0) + 1);
345 346
	}

J
Joao Moreno 已提交
347 348 349 350 351 352 353 354
	end(operation: Operation): void {
		const count = (this.operations.get(operation) || 0) - 1;

		if (count <= 0) {
			this.operations.delete(operation);
		} else {
			this.operations.set(operation, count);
		}
355 356 357
	}

	isRunning(operation: Operation): boolean {
J
Joao Moreno 已提交
358
		return this.operations.has(operation);
359
	}
360 361

	isIdle(): boolean {
J
Joao Moreno 已提交
362 363 364 365 366 367 368 369 370
		const operations = this.operations.keys();

		for (const operation of operations) {
			if (!isReadOnly(operation)) {
				return false;
			}
		}

		return true;
371
	}
J
Joao Moreno 已提交
372 373 374 375 376 377 378 379 380 381 382 383

	shouldShowProgress(): boolean {
		const operations = this.operations.keys();

		for (const operation of operations) {
			if (shouldShowProgress(operation)) {
				return true;
			}
		}

		return false;
	}
384 385
}

J
Joao Moreno 已提交
386 387 388 389
export interface GitResourceGroup extends SourceControlResourceGroup {
	resourceStates: Resource[];
}

J
Joao Moreno 已提交
390 391 392 393 394
export interface OperationResult {
	operation: Operation;
	error: any;
}

J
Joao Moreno 已提交
395 396
class ProgressManager {

J
Joao Moreno 已提交
397
	private enabled = false;
J
Joao Moreno 已提交
398 399
	private disposable: IDisposable = EmptyDisposable;

J
Joao Moreno 已提交
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
	constructor(private repository: Repository) {
		const onDidChange = filterEvent(workspace.onDidChangeConfiguration, e => e.affectsConfiguration('git', Uri.file(this.repository.root)));
		onDidChange(_ => this.updateEnablement());
		this.updateEnablement();
	}

	private updateEnablement(): void {
		const config = workspace.getConfiguration('git', Uri.file(this.repository.root));

		if (config.get<boolean>('showProgress')) {
			this.enable();
		} else {
			this.disable();
		}
	}

	private enable(): void {
		if (this.enabled) {
			return;
		}

		const start = onceEvent(filterEvent(this.repository.onDidChangeOperations, () => this.repository.operations.shouldShowProgress()));
		const end = onceEvent(filterEvent(debounceEvent(this.repository.onDidChangeOperations, 300), () => !this.repository.operations.shouldShowProgress()));
J
Joao Moreno 已提交
423 424 425 426 427 428 429 430 431

		const setup = () => {
			this.disposable = start(() => {
				const promise = eventToPromise(end).then(() => setup());
				window.withProgress({ location: ProgressLocation.SourceControl }, () => promise);
			});
		};

		setup();
J
Joao Moreno 已提交
432
		this.enabled = true;
J
Joao Moreno 已提交
433 434
	}

J
Joao Moreno 已提交
435 436 437 438 439
	private disable(): void {
		if (!this.enabled) {
			return;
		}

J
Joao Moreno 已提交
440
		this.disposable.dispose();
J
Joao Moreno 已提交
441 442 443 444 445 446
		this.disposable = EmptyDisposable;
		this.enabled = false;
	}

	dispose(): void {
		this.disable();
J
Joao Moreno 已提交
447 448 449
	}
}

450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
class FileEventLogger {

	private eventDisposable: IDisposable = EmptyDisposable;
	private logLevelDisposable: IDisposable = EmptyDisposable;

	constructor(
		private onWorkspaceWorkingTreeFileChange: Event<Uri>,
		private onDotGitFileChange: Event<Uri>,
		private outputChannel: OutputChannel
	) {
		this.logLevelDisposable = env.onDidChangeLogLevel(this.onDidChangeLogLevel, this);
		this.onDidChangeLogLevel(env.logLevel);
	}

	private onDidChangeLogLevel(level: LogLevel): void {
		this.eventDisposable.dispose();

		if (level > LogLevel.Debug) {
			return;
		}

		this.eventDisposable = combinedDisposable([
			this.onWorkspaceWorkingTreeFileChange(uri => this.outputChannel.appendLine(`[debug] [wt] Change: ${uri.fsPath}`)),
			this.onDotGitFileChange(uri => this.outputChannel.appendLine(`[debug] [.git] Change: ${uri.fsPath}`))
		]);
	}

	dispose(): void {
		this.eventDisposable.dispose();
		this.logLevelDisposable.dispose();
	}
}

J
Joao Moreno 已提交
483 484 485 486 487 488 489 490
class DotGitWatcher implements IFileWatcher {

	readonly event: Event<Uri>;

	private emitter = new EventEmitter<Uri>();
	private transientDisposables: IDisposable[] = [];
	private disposables: IDisposable[] = [];

J
Joao Moreno 已提交
491 492 493 494
	constructor(
		private repository: Repository,
		private outputChannel: OutputChannel
	) {
J
Joao Moreno 已提交
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
		const rootWatcher = watch(repository.dotGit);
		this.disposables.push(rootWatcher);

		const filteredRootWatcher = filterEvent(rootWatcher.event, uri => !/\/\.git(\/index\.lock)?$/.test(uri.path));
		this.event = anyEvent(filteredRootWatcher, this.emitter.event);

		repository.onDidRunGitStatus(this.updateTransientWatchers, this, this.disposables);
		this.updateTransientWatchers();
	}

	private updateTransientWatchers() {
		this.transientDisposables = dispose(this.transientDisposables);

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

		this.transientDisposables = dispose(this.transientDisposables);

		const { name, remote } = this.repository.HEAD.upstream;
		const upstreamPath = path.join(this.repository.dotGit, 'refs', 'remotes', remote, name);

J
Joao Moreno 已提交
517 518 519 520 521
		try {
			const upstreamWatcher = watch(upstreamPath);
			this.transientDisposables.push(upstreamWatcher);
			upstreamWatcher.event(this.emitter.fire, this.emitter, this.transientDisposables);
		} catch (err) {
J
Joao Moreno 已提交
522 523
			if (env.logLevel <= LogLevel.Error) {
				this.outputChannel.appendLine(`Failed to watch ref '${upstreamPath}', is most likely packed.\n${err.stack || err}`);
J
Joao Moreno 已提交
524 525
			}
		}
J
Joao Moreno 已提交
526 527 528 529 530 531 532 533 534
	}

	dispose() {
		this.emitter.dispose();
		this.transientDisposables = dispose(this.transientDisposables);
		this.disposables = dispose(this.disposables);
	}
}

J
Joao Moreno 已提交
535
export class Repository implements Disposable {
J
Joao Moreno 已提交
536

J
Joao Moreno 已提交
537 538 539
	private _onDidChangeRepository = new EventEmitter<Uri>();
	readonly onDidChangeRepository: Event<Uri> = this._onDidChangeRepository.event;

J
Joao 已提交
540 541
	private _onDidChangeState = new EventEmitter<RepositoryState>();
	readonly onDidChangeState: Event<RepositoryState> = this._onDidChangeState.event;
J
Joao Moreno 已提交
542

J
Joao Moreno 已提交
543
	private _onDidChangeStatus = new EventEmitter<void>();
J
Joao Moreno 已提交
544
	readonly onDidRunGitStatus: Event<void> = this._onDidChangeStatus.event;
J
Joao Moreno 已提交
545

J
Joao Moreno 已提交
546 547 548
	private _onDidChangeOriginalResource = new EventEmitter<Uri>();
	readonly onDidChangeOriginalResource: Event<Uri> = this._onDidChangeOriginalResource.event;

549 550 551
	private _onRunOperation = new EventEmitter<Operation>();
	readonly onRunOperation: Event<Operation> = this._onRunOperation.event;

J
Joao Moreno 已提交
552 553
	private _onDidRunOperation = new EventEmitter<OperationResult>();
	readonly onDidRunOperation: Event<OperationResult> = this._onDidRunOperation.event;
554 555 556 557 558 559

	@memoize
	get onDidChangeOperations(): Event<void> {
		return anyEvent(this.onRunOperation as Event<any>, this.onDidRunOperation as Event<any>);
	}

J
Joao Moreno 已提交
560 561 562
	private _sourceControl: SourceControl;
	get sourceControl(): SourceControl { return this._sourceControl; }

J
Joao Moreno 已提交
563 564
	get inputBox(): SourceControlInputBox { return this._sourceControl.inputBox; }

J
Joao Moreno 已提交
565 566
	private _mergeGroup: SourceControlResourceGroup;
	get mergeGroup(): GitResourceGroup { return this._mergeGroup as GitResourceGroup; }
J
Joao Moreno 已提交
567

J
Joao Moreno 已提交
568 569
	private _indexGroup: SourceControlResourceGroup;
	get indexGroup(): GitResourceGroup { return this._indexGroup as GitResourceGroup; }
J
Joao Moreno 已提交
570

J
Joao Moreno 已提交
571 572
	private _workingTreeGroup: SourceControlResourceGroup;
	get workingTreeGroup(): GitResourceGroup { return this._workingTreeGroup as GitResourceGroup; }
J
Joao Moreno 已提交
573

574 575 576
	private _untrackedGroup: SourceControlResourceGroup;
	get untrackedGroup(): GitResourceGroup { return this._untrackedGroup as GitResourceGroup; }

J
Joao Moreno 已提交
577 578 579 580 581 582 583 584 585 586
	private _HEAD: Branch | undefined;
	get HEAD(): Branch | undefined {
		return this._HEAD;
	}

	private _refs: Ref[] = [];
	get refs(): Ref[] {
		return this._refs;
	}

J
Joao Moreno 已提交
587 588 589 590 591 592
	get headShortName(): string | undefined {
		if (!this.HEAD) {
			return;
		}

		const HEAD = this.HEAD;
J
Joao Moreno 已提交
593 594 595 596 597

		if (HEAD.name) {
			return HEAD.name;
		}

J
Joao Moreno 已提交
598 599 600
		const tag = this.refs.filter(iref => iref.type === RefType.Tag && iref.commit === HEAD.commit)[0];
		const tagName = tag && tag.name;

J
Joao Moreno 已提交
601 602
		if (tagName) {
			return tagName;
J
Joao Moreno 已提交
603 604
		}

J
Joao Moreno 已提交
605
		return (HEAD.commit || '').substr(0, 8);
J
Joao Moreno 已提交
606 607
	}

J
Joao Moreno 已提交
608 609 610 611 612
	private _remotes: Remote[] = [];
	get remotes(): Remote[] {
		return this._remotes;
	}

613 614 615 616 617
	private _submodules: Submodule[] = [];
	get submodules(): Submodule[] {
		return this._submodules;
	}

618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
	private _rebaseCommit: Commit | undefined = undefined;

	set rebaseCommit(rebaseCommit: Commit | undefined) {
		if (this._rebaseCommit && !rebaseCommit) {
			this.inputBox.value = '';
		} else if (rebaseCommit && (!this._rebaseCommit || this._rebaseCommit.hash !== rebaseCommit.hash)) {
			this.inputBox.value = rebaseCommit.message;
		}

		this._rebaseCommit = rebaseCommit;
	}

	get rebaseCommit(): Commit | undefined {
		return this._rebaseCommit;
	}

634 635 636
	private _operations = new OperationsImpl();
	get operations(): Operations { return this._operations; }

J
Joao 已提交
637 638 639
	private _state = RepositoryState.Idle;
	get state(): RepositoryState { return this._state; }
	set state(state: RepositoryState) {
J
Joao Moreno 已提交
640 641
		this._state = state;
		this._onDidChangeState.fire(state);
J
Joao Moreno 已提交
642 643 644 645

		this._HEAD = undefined;
		this._refs = [];
		this._remotes = [];
J
Joao Moreno 已提交
646 647 648
		this.mergeGroup.resourceStates = [];
		this.indexGroup.resourceStates = [];
		this.workingTreeGroup.resourceStates = [];
649
		this.untrackedGroup.resourceStates = [];
J
Joao Moreno 已提交
650
		this._sourceControl.count = 0;
J
Joao Moreno 已提交
651 652
	}

653 654 655 656
	get root(): string {
		return this.repository.root;
	}

J
Joao Moreno 已提交
657 658 659 660
	get dotGit(): string {
		return this.repository.dotGit;
	}

661 662
	private isRepositoryHuge = false;
	private didWarnAboutLimit = false;
663

J
Joao Moreno 已提交
664
	private disposables: Disposable[] = [];
J
Joao Moreno 已提交
665

666
	constructor(
J
Joao Moreno 已提交
667
		private readonly repository: BaseRepository,
668 669
		globalState: Memento,
		outputChannel: OutputChannel
670
	) {
J
Joao Moreno 已提交
671 672 673
		const workspaceWatcher = workspace.createFileSystemWatcher('**');
		this.disposables.push(workspaceWatcher);

674 675 676
		const onWorkspaceFileChange = anyEvent(workspaceWatcher.onDidChange, workspaceWatcher.onDidCreate, workspaceWatcher.onDidDelete);
		const onWorkspaceRepositoryFileChange = filterEvent(onWorkspaceFileChange, uri => isDescendant(repository.root, uri.fsPath));
		const onWorkspaceWorkingTreeFileChange = filterEvent(onWorkspaceRepositoryFileChange, uri => !/\/\.git($|\/)/.test(uri.path));
J
Joao Moreno 已提交
677

J
Joao Moreno 已提交
678 679 680 681 682 683 684 685 686 687 688 689 690
		let onDotGitFileChange: Event<Uri>;

		try {
			const dotGitFileWatcher = new DotGitWatcher(this, outputChannel);
			onDotGitFileChange = dotGitFileWatcher.event;
			this.disposables.push(dotGitFileWatcher);
		} catch (err) {
			if (env.logLevel <= LogLevel.Error) {
				outputChannel.appendLine(`Failed to watch '${this.dotGit}', reverting to legacy API file watched. Some events might be lost.\n${err.stack || err}`);
			}

			onDotGitFileChange = filterEvent(onWorkspaceRepositoryFileChange, uri => /\/\.git($|\/)/.test(uri.path));
		}
J
Joao Moreno 已提交
691 692 693 694

		// FS changes should trigger `git status`:
		// 	- any change inside the repository working tree
		//	- any change whithin the first level of the `.git` folder, except the folder itself and `index.lock`
J
Joao Moreno 已提交
695
		const onFileChange = anyEvent(onWorkspaceWorkingTreeFileChange, onDotGitFileChange);
696
		onFileChange(this.onFileChange, this, this.disposables);
J
Joao Moreno 已提交
697 698

		// Relevate repository changes should trigger virtual document change events
J
Joao Moreno 已提交
699
		onDotGitFileChange(this._onDidChangeRepository.fire, this._onDidChangeRepository, this.disposables);
700

J
Joao Moreno 已提交
701
		this.disposables.push(new FileEventLogger(onWorkspaceWorkingTreeFileChange, onDotGitFileChange, outputChannel));
J
Joao Moreno 已提交
702

J
Joao Moreno 已提交
703
		const root = Uri.file(repository.root);
704
		this._sourceControl = scm.createSourceControl('git', 'Git', root);
705

J
Joao Moreno 已提交
706
		this._sourceControl.acceptInputCommand = { command: 'git.commit', title: localize('commit', "Commit"), arguments: [this._sourceControl] };
J
Joao Moreno 已提交
707
		this._sourceControl.quickDiffProvider = this;
J
Joao Moreno 已提交
708
		this._sourceControl.inputBox.validateInput = this.validateInput.bind(this);
J
Joao Moreno 已提交
709 710
		this.disposables.push(this._sourceControl);

711 712 713
		this.updateInputBoxPlaceholder();
		this.disposables.push(this.onDidRunGitStatus(() => this.updateInputBoxPlaceholder()));

714 715 716
		this._mergeGroup = this._sourceControl.createResourceGroup('merge', localize('merge changes', "MERGE CHANGES"));
		this._indexGroup = this._sourceControl.createResourceGroup('index', localize('staged changes', "STAGED CHANGES"));
		this._workingTreeGroup = this._sourceControl.createResourceGroup('workingTree', localize('changes', "CHANGES"));
717
		this._untrackedGroup = this._sourceControl.createResourceGroup('untracked', localize('untracked changes', 'UNTRACKED'));
J
Joao Moreno 已提交
718

J
Joao Moreno 已提交
719 720 721 722 723 724 725 726
		const updateIndexGroupVisibility = () => {
			const config = workspace.getConfiguration('git', root);
			this.indexGroup.hideWhenEmpty = !config.get<boolean>('alwaysShowStagedChangesResourceGroup');
		};

		const onConfigListener = filterEvent(workspace.onDidChangeConfiguration, e => e.affectsConfiguration('git.alwaysShowStagedChangesResourceGroup', root));
		onConfigListener(updateIndexGroupVisibility, this, this.disposables);
		updateIndexGroupVisibility();
W
wistcc 已提交
727

J
Joao Moreno 已提交
728
		const onConfigListenerForBranchSortOrder = filterEvent(workspace.onDidChangeConfiguration, e => e.affectsConfiguration('git.branchSortOrder', root));
S
skprabhanjan 已提交
729 730
		onConfigListenerForBranchSortOrder(this.updateModelState, this, this.disposables);

731 732 733
		const onConfigListenerForUntracked = filterEvent(workspace.onDidChangeConfiguration, e => e.affectsConfiguration('git.handleUntracked', root));
		onConfigListenerForUntracked(this.updateModelState, this, this.disposables);

J
Joao Moreno 已提交
734
		this.mergeGroup.hideWhenEmpty = true;
735
		this.untrackedGroup.hideWhenEmpty = true;
J
Joao Moreno 已提交
736 737 738 739

		this.disposables.push(this.mergeGroup);
		this.disposables.push(this.indexGroup);
		this.disposables.push(this.workingTreeGroup);
740
		this.disposables.push(this.untrackedGroup);
J
Joao Moreno 已提交
741

J
Joao Moreno 已提交
742
		this.disposables.push(new AutoFetcher(this, globalState));
J
Joao Moreno 已提交
743

744 745 746 747 748 749 750 751 752 753
		// https://github.com/Microsoft/vscode/issues/39039
		const onSuccessfulPush = filterEvent(this.onDidRunOperation, e => e.operation === Operation.Push && !e.error);
		onSuccessfulPush(() => {
			const gitConfig = workspace.getConfiguration('git');

			if (gitConfig.get<boolean>('showPushSuccessNotification')) {
				window.showInformationMessage(localize('push success', "Successfully pushed."));
			}
		}, null, this.disposables);

J
Joao Moreno 已提交
754 755 756 757 758
		const statusBar = new StatusBarCommands(this);
		this.disposables.push(statusBar);
		statusBar.onDidChange(() => this._sourceControl.statusBarCommands = statusBar.commands, null, this.disposables);
		this._sourceControl.statusBarCommands = statusBar.commands;

J
Joao Moreno 已提交
759 760 761
		const progressManager = new ProgressManager(this);
		this.disposables.push(progressManager);

762 763 764
		const onDidChangeCountBadge = filterEvent(workspace.onDidChangeConfiguration, e => e.affectsConfiguration('git.countBadge', root));
		onDidChangeCountBadge(this.setCountBadge, this, this.disposables);
		this.setCountBadge();
J
Joao Moreno 已提交
765 766
	}

767
	validateInput(text: string, position: number): SourceControlInputBoxValidation | undefined {
768 769 770 771 772 773 774 775 776
		if (this.rebaseCommit) {
			if (this.rebaseCommit.message !== text) {
				return {
					message: localize('commit in rebase', "It's not possible to change the commit message in the middle of a rebase. Please complete the rebase operation and use interactive rebase instead."),
					type: SourceControlInputBoxValidationType.Warning
				};
			}
		}

777 778 779 780 781 782 783
		const config = workspace.getConfiguration('git');
		const setting = config.get<'always' | 'warn' | 'off'>('inputValidation');

		if (setting === 'off') {
			return;
		}

J
Joao Moreno 已提交
784
		if (/^\s+$/.test(text)) {
785
			return {
J
Joao Moreno 已提交
786
				message: localize('commitMessageWhitespacesOnlyWarning', "Current commit message only contains whitespace characters"),
787 788 789 790
				type: SourceControlInputBoxValidationType.Warning
			};
		}

791
		let lineNumber = 0;
792 793 794 795 796 797
		let start = 0, end;
		let match: RegExpExecArray | null;
		const regex = /\r?\n/g;

		while ((match = regex.exec(text)) && position > match.index) {
			start = match.index + match[0].length;
798
			lineNumber++;
799 800 801 802 803 804
		}

		end = match ? match.index : text.length;

		const line = text.substring(start, end);

805 806 807 808 809 810 811 812 813 814 815
		let threshold = config.get<number>('inputValidationLength', 50);

		if (lineNumber === 0) {
			const inputValidationSubjectLength = config.get<number | null>('inputValidationSubjectLength', null);

			if (inputValidationSubjectLength !== null) {
				threshold = inputValidationSubjectLength;
			}
		}

		if (line.length <= threshold) {
816 817 818 819 820
			if (setting !== 'always') {
				return;
			}

			return {
821
				message: localize('commitMessageCountdown', "{0} characters left in current line", threshold - line.length),
822 823 824 825
				type: SourceControlInputBoxValidationType.Information
			};
		} else {
			return {
826
				message: localize('commitMessageWarning', "{0} characters over {1} in current line", line.length - threshold, threshold),
827 828 829 830 831
				type: SourceControlInputBoxValidationType.Warning
			};
		}
	}

J
Joao Moreno 已提交
832 833 834 835 836
	provideOriginalResource(uri: Uri): Uri | undefined {
		if (uri.scheme !== 'file') {
			return;
		}

837
		return toGitUri(uri, '', { replaceFileExtension: true });
J
Joao Moreno 已提交
838 839
	}

J
Joao Moreno 已提交
840 841 842 843 844
	async getInputTemplate(): Promise<string> {
		const mergeMessage = await this.repository.getMergeMessage();

		if (mergeMessage) {
			return mergeMessage;
J
Joao Moreno 已提交
845
		}
J
Joao Moreno 已提交
846 847

		return await this.repository.getCommitTemplate();
J
Joao Moreno 已提交
848 849
	}

J
Joao Moreno 已提交
850 851 852 853 854 855 856 857
	getConfigs(): Promise<{ key: string; value: string; }[]> {
		return this.run(Operation.Config, () => this.repository.getConfigs('local'));
	}

	getConfig(key: string): Promise<string> {
		return this.run(Operation.Config, () => this.repository.config('local', key));
	}

858 859 860 861
	getGlobalConfig(key: string): Promise<string> {
		return this.run(Operation.Config, () => this.repository.config('global', key));
	}

J
Joao Moreno 已提交
862 863 864 865
	setConfig(key: string, value: string): Promise<string> {
		return this.run(Operation.Config, () => this.repository.config('local', key, value));
	}

866 867
	log(options?: LogOptions): Promise<Commit[]> {
		return this.run(Operation.Log, () => this.repository.log(options));
868 869
	}

J
Joao Moreno 已提交
870
	@throttle
J
Joao Moreno 已提交
871 872
	async status(): Promise<void> {
		await this.run(Operation.Status);
J
Joao Moreno 已提交
873
	}
J
Joao Moreno 已提交
874

875 876 877 878
	diff(cached?: boolean): Promise<string> {
		return this.run(Operation.Diff, () => this.repository.diff(cached));
	}

879 880
	diffWithHEAD(): Promise<Change[]>;
	diffWithHEAD(path: string): Promise<string>;
881
	diffWithHEAD(path?: string | undefined): Promise<string | Change[]>;
882
	diffWithHEAD(path?: string | undefined): Promise<string | Change[]> {
J
Joao Moreno 已提交
883 884 885
		return this.run(Operation.Diff, () => this.repository.diffWithHEAD(path));
	}

886 887
	diffWith(ref: string): Promise<Change[]>;
	diffWith(ref: string, path: string): Promise<string>;
888
	diffWith(ref: string, path?: string | undefined): Promise<string | Change[]>;
889
	diffWith(ref: string, path?: string): Promise<string | Change[]> {
J
Joao Moreno 已提交
890 891 892
		return this.run(Operation.Diff, () => this.repository.diffWith(ref, path));
	}

893 894
	diffIndexWithHEAD(): Promise<Change[]>;
	diffIndexWithHEAD(path: string): Promise<string>;
895
	diffIndexWithHEAD(path?: string | undefined): Promise<string | Change[]>;
896
	diffIndexWithHEAD(path?: string): Promise<string | Change[]> {
J
Joao Moreno 已提交
897 898 899
		return this.run(Operation.Diff, () => this.repository.diffIndexWithHEAD(path));
	}

900 901
	diffIndexWith(ref: string): Promise<Change[]>;
	diffIndexWith(ref: string, path: string): Promise<string>;
902
	diffIndexWith(ref: string, path?: string | undefined): Promise<string | Change[]>;
903
	diffIndexWith(ref: string, path?: string): Promise<string | Change[]> {
J
Joao Moreno 已提交
904 905 906 907 908 909 910
		return this.run(Operation.Diff, () => this.repository.diffIndexWith(ref, path));
	}

	diffBlobs(object1: string, object2: string): Promise<string> {
		return this.run(Operation.Diff, () => this.repository.diffBlobs(object1, object2));
	}

911 912
	diffBetween(ref1: string, ref2: string): Promise<Change[]>;
	diffBetween(ref1: string, ref2: string, path: string): Promise<string>;
913
	diffBetween(ref1: string, ref2: string, path?: string | undefined): Promise<string | Change[]>;
914
	diffBetween(ref1: string, ref2: string, path?: string): Promise<string | Change[]> {
J
Joao Moreno 已提交
915 916 917 918 919 920 921 922 923
		return this.run(Operation.Diff, () => this.repository.diffBetween(ref1, ref2, path));
	}

	getMergeBase(ref1: string, ref2: string): Promise<string> {
		return this.run(Operation.MergeBase, () => this.repository.getMergeBase(ref1, ref2));
	}

	async hashObject(data: string): Promise<string> {
		return this.run(Operation.HashObject, () => this.repository.hashObject(data));
924 925
	}

926 927
	async add(resources: Uri[], opts?: { update?: boolean }): Promise<void> {
		await this.run(Operation.Add, () => this.repository.add(resources.map(r => r.fsPath), opts));
J
Joao Moreno 已提交
928 929
	}

J
Joao Moreno 已提交
930 931 932 933
	async rm(resources: Uri[]): Promise<void> {
		await this.run(Operation.Remove, () => this.repository.rm(resources.map(r => r.fsPath)));
	}

J
Joao Moreno 已提交
934 935
	async stage(resource: Uri, contents: string): Promise<void> {
		const relativePath = path.relative(this.repository.root, resource.fsPath).replace(/\\/g, '/');
J
Joao Moreno 已提交
936
		await this.run(Operation.Stage, () => this.repository.stage(relativePath, contents));
J
Joao Moreno 已提交
937
		this._onDidChangeOriginalResource.fire(resource);
J
Joao Moreno 已提交
938 939
	}

J
Joao Moreno 已提交
940 941
	async revert(resources: Uri[]): Promise<void> {
		await this.run(Operation.RevertFiles, () => this.repository.revert('HEAD', resources.map(r => r.fsPath)));
J
Joao Moreno 已提交
942
	}
J
Joao Moreno 已提交
943

J
Joao Moreno 已提交
944
	async commit(message: string, opts: CommitOptions = Object.create(null)): Promise<void> {
945 946 947
		if (this.rebaseCommit) {
			await this.run(Operation.RebaseContinue, async () => {
				if (opts.all) {
J
Joao Moreno 已提交
948 949
					const addOpts = opts.all === 'tracked' ? { update: true } : {};
					await this.repository.add([], addOpts);
950
				}
J
Joao Moreno 已提交
951

952 953 954 955 956
				await this.repository.rebaseContinue();
			});
		} else {
			await this.run(Operation.Commit, async () => {
				if (opts.all) {
J
Joao Moreno 已提交
957 958
					const addOpts = opts.all === 'tracked' ? { update: true } : {};
					await this.repository.add([], addOpts);
959 960
				}

J
Joao Moreno 已提交
961
				delete opts.all;
962 963 964
				await this.repository.commit(message, opts);
			});
		}
J
Joao Moreno 已提交
965
	}
J
Joao Moreno 已提交
966

J
Joao Moreno 已提交
967
	async clean(resources: Uri[]): Promise<void> {
968 969 970
		await this.run(Operation.Clean, async () => {
			const toClean: string[] = [];
			const toCheckout: string[] = [];
971
			const submodulesToUpdate: string[] = [];
972 973

			resources.forEach(r => {
974 975 976 977 978 979 980 981 982
				const fsPath = r.fsPath;

				for (const submodule of this.submodules) {
					if (path.join(this.root, submodule.path) === fsPath) {
						submodulesToUpdate.push(fsPath);
						return;
					}
				}

983
				const raw = r.toString();
J
Joao Moreno 已提交
984
				const scmResource = find(this.workingTreeGroup.resourceStates, sr => sr.resourceUri.toString() === raw);
985 986 987 988 989 990

				if (!scmResource) {
					return;
				}

				switch (scmResource.type) {
991 992
					case Status.UNTRACKED:
					case Status.IGNORED:
993
						toClean.push(fsPath);
994 995 996
						break;

					default:
997
						toCheckout.push(fsPath);
998 999 1000
						break;
				}
			});
J
Joao Moreno 已提交
1001

J
Joao Moreno 已提交
1002 1003 1004
			await this.repository.clean(toClean);
			await this.repository.checkout('', toCheckout);
			await this.repository.updateSubmodules(submodulesToUpdate);
1005
		});
J
Joao Moreno 已提交
1006
	}
J
Joao Moreno 已提交
1007

1008
	async branch(name: string, _checkout: boolean, _ref?: string): Promise<void> {
R
rebornix 已提交
1009
		await this.run(Operation.Branch, () => this.repository.branch(name, _checkout, _ref));
J
Joao Moreno 已提交
1010 1011
	}

1012 1013
	async deleteBranch(name: string, force?: boolean): Promise<void> {
		await this.run(Operation.DeleteBranch, () => this.repository.deleteBranch(name, force));
M
Maik Riechert 已提交
1014 1015
	}

1016 1017 1018 1019
	async renameBranch(name: string): Promise<void> {
		await this.run(Operation.RenameBranch, () => this.repository.renameBranch(name));
	}

J
Joao Moreno 已提交
1020 1021 1022 1023 1024 1025 1026 1027
	async getBranch(name: string): Promise<Branch> {
		return await this.run(Operation.GetBranch, () => this.repository.getBranch(name));
	}

	async setBranchUpstream(name: string, upstream: string): Promise<void> {
		await this.run(Operation.SetBranchUpstream, () => this.repository.setBranchUpstream(name, upstream));
	}

J
Joao Moreno 已提交
1028 1029
	async merge(ref: string): Promise<void> {
		await this.run(Operation.Merge, () => this.repository.merge(ref));
1030 1031
	}

J
Joao Moreno 已提交
1032 1033
	async tag(name: string, message?: string): Promise<void> {
		await this.run(Operation.Tag, () => this.repository.tag(name, message));
1034 1035
	}

X
Xhulio Hasani 已提交
1036 1037 1038 1039
	async deleteTag(name: string): Promise<void> {
		await this.run(Operation.DeleteTag, () => this.repository.deleteTag(name));
	}

J
Joao Moreno 已提交
1040
	async checkout(treeish: string): Promise<void> {
J
Joao Moreno 已提交
1041
		await this.run(Operation.Checkout, () => this.repository.checkout(treeish, []));
J
Joao Moreno 已提交
1042
	}
J
Joao Moreno 已提交
1043

1044 1045 1046 1047
	async checkoutTracking(treeish: string): Promise<void> {
		await this.run(Operation.CheckoutTracking, () => this.repository.checkout(treeish, [], { track: true }));
	}

J
Joao Moreno 已提交
1048 1049
	async findTrackingBranches(upstreamRef: string): Promise<Branch[]> {
		return await this.run(Operation.FindTrackingBranches, () => this.repository.findTrackingBranches(upstreamRef));
1050 1051
	}

J
Joao Moreno 已提交
1052 1053 1054 1055 1056 1057 1058 1059
	async getCommit(ref: string): Promise<Commit> {
		return await this.repository.getCommit(ref);
	}

	async reset(treeish: string, hard?: boolean): Promise<void> {
		await this.run(Operation.Reset, () => this.repository.reset(treeish, hard));
	}

1060 1061 1062 1063
	async deleteRef(ref: string): Promise<void> {
		await this.run(Operation.DeleteRef, () => this.repository.deleteRef(ref));
	}

J
Joao Moreno 已提交
1064 1065 1066 1067 1068 1069 1070 1071
	async addRemote(name: string, url: string): Promise<void> {
		await this.run(Operation.Remote, () => this.repository.addRemote(name, url));
	}

	async removeRemote(name: string): Promise<void> {
		await this.run(Operation.Remote, () => this.repository.removeRemote(name));
	}

J
Joao Moreno 已提交
1072
	@throttle
J
Joao Moreno 已提交
1073 1074
	async fetchDefault(options: { silent?: boolean } = {}): Promise<void> {
		await this.run(Operation.Fetch, () => this.repository.fetch(options));
J
Joao Moreno 已提交
1075 1076
	}

R
Ryan Scott 已提交
1077 1078 1079 1080 1081
	@throttle
	async fetchPrune(): Promise<void> {
		await this.run(Operation.Fetch, () => this.repository.fetch({ prune: true }));
	}

J
Joao Moreno 已提交
1082 1083 1084 1085 1086
	@throttle
	async fetchAll(): Promise<void> {
		await this.run(Operation.Fetch, () => this.repository.fetch({ all: true }));
	}

1087 1088
	async fetch(remote?: string, ref?: string, depth?: number): Promise<void> {
		await this.run(Operation.Fetch, () => this.repository.fetch({ remote, ref, depth }));
J
Joao Moreno 已提交
1089 1090
	}

J
Joao Moreno 已提交
1091
	@throttle
J
Joao Moreno 已提交
1092
	async pullWithRebase(head: Branch | undefined): Promise<void> {
J
Joao Moreno 已提交
1093 1094
		let remote: string | undefined;
		let branch: string | undefined;
J
Joao Moreno 已提交
1095

J
Joao Moreno 已提交
1096 1097 1098
		if (head && head.name && head.upstream) {
			remote = head.upstream.remote;
			branch = `${head.upstream.name}`;
J
Joao Moreno 已提交
1099 1100
		}

1101
		return this.pullFrom(true, remote, branch);
J
Joao Moreno 已提交
1102 1103 1104
	}

	@throttle
1105
	async pull(head?: Branch, unshallow?: boolean): Promise<void> {
J
Joao Moreno 已提交
1106 1107 1108
		let remote: string | undefined;
		let branch: string | undefined;

J
Joao Moreno 已提交
1109 1110 1111
		if (head && head.name && head.upstream) {
			remote = head.upstream.remote;
			branch = `${head.upstream.name}`;
J
Joao Moreno 已提交
1112 1113
		}

1114
		return this.pullFrom(false, remote, branch, unshallow);
J
Joao Moreno 已提交
1115 1116
	}

1117
	async pullFrom(rebase?: boolean, remote?: string, branch?: string, unshallow?: boolean): Promise<void> {
1118
		await this.run(Operation.Pull, async () => {
J
Joao Moreno 已提交
1119 1120 1121
			await this.maybeAutoStash(async () => {
				const config = workspace.getConfiguration('git', Uri.file(this.root));
				const fetchOnPull = config.get<boolean>('fetchOnPull');
J
Joao Moreno 已提交
1122
				const tags = config.get<boolean>('pullTags');
1123

J
Joao Moreno 已提交
1124
				if (fetchOnPull) {
J
Joao Moreno 已提交
1125
					await this.repository.pull(rebase, undefined, undefined, { unshallow, tags });
J
Joao Moreno 已提交
1126
				} else {
J
Joao Moreno 已提交
1127
					await this.repository.pull(rebase, remote, branch, { unshallow, tags });
J
Joao Moreno 已提交
1128 1129
				}
			});
1130
		});
J
Joao Moreno 已提交
1131 1132
	}

J
Joao Moreno 已提交
1133
	@throttle
1134
	async push(head: Branch, forcePushMode?: ForcePushMode): Promise<void> {
J
Joao Moreno 已提交
1135 1136 1137
		let remote: string | undefined;
		let branch: string | undefined;

J
Joao Moreno 已提交
1138 1139 1140
		if (head && head.name && head.upstream) {
			remote = head.upstream.remote;
			branch = `${head.name}:${head.upstream.name}`;
J
Joao Moreno 已提交
1141 1142
		}

1143
		await this.run(Operation.Push, () => this.repository.push(remote, branch, undefined, undefined, forcePushMode));
J
Joao Moreno 已提交
1144 1145
	}

1146 1147
	async pushTo(remote?: string, name?: string, setUpstream: boolean = false, forcePushMode?: ForcePushMode): Promise<void> {
		await this.run(Operation.Push, () => this.repository.push(remote, name, setUpstream, undefined, forcePushMode));
1148 1149
	}

1150
	async pushFollowTags(remote?: string, forcePushMode?: ForcePushMode): Promise<void> {
1151
		await this.run(Operation.Push, () => this.repository.push(remote, undefined, false, true, forcePushMode));
1152 1153
	}

R
rebornix 已提交
1154 1155 1156 1157
	async blame(path: string): Promise<string> {
		return await this.run(Operation.Blame, () => this.repository.blame(path));
	}

J
Joao Moreno 已提交
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
	@throttle
	sync(head: Branch): Promise<void> {
		return this._sync(head, false);
	}

	@throttle
	async syncRebase(head: Branch): Promise<void> {
		return this._sync(head, true);
	}

	private async _sync(head: Branch, rebase: boolean): Promise<void> {
1169
		let remoteName: string | undefined;
J
Joao Moreno 已提交
1170 1171 1172 1173
		let pullBranch: string | undefined;
		let pushBranch: string | undefined;

		if (head.name && head.upstream) {
1174
			remoteName = head.upstream.remote;
J
Joao Moreno 已提交
1175 1176 1177 1178
			pullBranch = `${head.upstream.name}`;
			pushBranch = `${head.name}:${head.upstream.name}`;
		}

1179
		await this.run(Operation.Sync, async () => {
J
Joao Moreno 已提交
1180 1181 1182
			await this.maybeAutoStash(async () => {
				const config = workspace.getConfiguration('git', Uri.file(this.root));
				const fetchOnPull = config.get<boolean>('fetchOnPull');
J
Joao Moreno 已提交
1183
				const tags = config.get<boolean>('pullTags');
1184
				const supportCancellation = config.get<boolean>('supportCancellation');
1185

1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
				const fn = fetchOnPull
					? async (cancellationToken?: CancellationToken) => await this.repository.pull(rebase, undefined, undefined, { tags, cancellationToken })
					: async (cancellationToken?: CancellationToken) => await this.repository.pull(rebase, remoteName, pullBranch, { tags, cancellationToken });

				if (supportCancellation) {
					const opts: ProgressOptions = {
						location: ProgressLocation.Notification,
						title: localize('sync is unpredictable', "Syncing. Cancelling may cause serious damages to the repository"),
						cancellable: true
					};

					await window.withProgress(opts, (_, token) => fn(token));
J
Joao Moreno 已提交
1198
				} else {
1199
					await fn();
J
Joao Moreno 已提交
1200
				}
1201

J
Joao Moreno 已提交
1202
				const remote = this.remotes.find(r => r.name === remoteName);
J
Joao Moreno 已提交
1203

J
Joao Moreno 已提交
1204 1205 1206
				if (remote && remote.isReadOnly) {
					return;
				}
J
Joao Moreno 已提交
1207

J
Joao Moreno 已提交
1208
				const shouldPush = this.HEAD && (typeof this.HEAD.ahead === 'number' ? this.HEAD.ahead > 0 : true);
1209

J
Joao Moreno 已提交
1210 1211 1212 1213
				if (shouldPush) {
					await this.repository.push(remoteName, pushBranch);
				}
			});
1214
		});
J
Joao Moreno 已提交
1215 1216
	}

1217
	async show(ref: string, filePath: string): Promise<string> {
1218 1219
		return await this.run(Operation.Show, async () => {
			const relativePath = path.relative(this.repository.root, filePath).replace(/\\/g, '/');
J
Joao Moreno 已提交
1220
			const configFiles = workspace.getConfiguration('files', Uri.file(filePath));
J
Joao Moreno 已提交
1221
			const defaultEncoding = configFiles.get<string>('encoding');
1222 1223
			const autoGuessEncoding = configFiles.get<boolean>('autoGuessEncoding');

1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
			try {
				return await this.repository.bufferString(`${ref}:${relativePath}`, defaultEncoding, autoGuessEncoding);
			} catch (err) {
				if (err.gitErrorCode === GitErrorCodes.WrongCase) {
					const gitRelativePath = await this.repository.getGitRelativePath(ref, relativePath);
					return await this.repository.bufferString(`${ref}:${gitRelativePath}`, defaultEncoding, autoGuessEncoding);
				}

				throw err;
			}
J
Joao Moreno 已提交
1234 1235 1236 1237
		});
	}

	async buffer(ref: string, filePath: string): Promise<Buffer> {
J
Joao Moreno 已提交
1238
		return this.run(Operation.Show, () => {
J
Joao Moreno 已提交
1239
			const relativePath = path.relative(this.repository.root, filePath).replace(/\\/g, '/');
J
Joao Moreno 已提交
1240
			return this.repository.buffer(`${ref}:${relativePath}`);
J
Joao Moreno 已提交
1241 1242 1243
		});
	}

J
Joao Moreno 已提交
1244 1245
	getObjectDetails(ref: string, filePath: string): Promise<{ mode: string, object: string, size: number }> {
		return this.run(Operation.GetObjectDetails, () => this.repository.getObjectDetails(ref, filePath));
J
Joao Moreno 已提交
1246 1247 1248 1249 1250 1251
	}

	detectObjectType(object: string): Promise<{ mimetype: string, encoding?: string }> {
		return this.run(Operation.Show, () => this.repository.detectObjectType(object));
	}

1252 1253 1254 1255
	async apply(patch: string, reverse?: boolean): Promise<void> {
		return await this.run(Operation.Apply, () => this.repository.apply(patch, reverse));
	}

J
Joao Moreno 已提交
1256 1257 1258 1259
	async getStashes(): Promise<Stash[]> {
		return await this.repository.getStashes();
	}

1260 1261
	async createStash(message?: string, includeUntracked?: boolean): Promise<void> {
		return await this.run(Operation.Stash, () => this.repository.createStash(message, includeUntracked));
J
Joao Moreno 已提交
1262 1263 1264 1265
	}

	async popStash(index?: number): Promise<void> {
		return await this.run(Operation.Stash, () => this.repository.popStash(index));
1266 1267
	}

1268 1269 1270 1271
	async dropStash(index?: number): Promise<void> {
		return await this.run(Operation.Stash, () => this.repository.dropStash(index));
	}

1272 1273 1274 1275
	async applyStash(index?: number): Promise<void> {
		return await this.run(Operation.Stash, () => this.repository.applyStash(index));
	}

J
Joao Moreno 已提交
1276 1277 1278 1279
	async getCommitTemplate(): Promise<string> {
		return await this.run(Operation.GetCommitTemplate, async () => this.repository.getCommitTemplate());
	}

1280 1281 1282 1283
	async cleanUpCommitEditMessage(editMessage: string): Promise<string> {
		return this.repository.cleanupCommitEditMessage(editMessage);
	}

J
Joao Moreno 已提交
1284
	async ignore(files: Uri[]): Promise<void> {
N
NKumar2 已提交
1285
		return await this.run(Operation.Ignore, async () => {
J
Joao Moreno 已提交
1286 1287
			const ignoreFile = `${this.repository.root}${path.sep}.gitignore`;
			const textToAppend = files
J
Joao Moreno 已提交
1288
				.map(uri => path.relative(this.repository.root, uri.fsPath).replace(/\\/g, '/'))
J
Joao Moreno 已提交
1289
				.join('\n');
N
NKumar2 已提交
1290

J
Joao Moreno 已提交
1291 1292 1293
			const document = await new Promise(c => fs.exists(ignoreFile, c))
				? await workspace.openTextDocument(ignoreFile)
				: await workspace.openTextDocument(Uri.file(ignoreFile).with({ scheme: 'untitled' }));
1294

J
Joao Moreno 已提交
1295
			await window.showTextDocument(document);
J
Joao Moreno 已提交
1296

J
Joao Moreno 已提交
1297
			const edit = new WorkspaceEdit();
J
Joao Moreno 已提交
1298 1299
			const lastLine = document.lineAt(document.lineCount - 1);
			const text = lastLine.isEmptyOrWhitespace ? `${textToAppend}\n` : `\n${textToAppend}\n`;
1300

J
Joao Moreno 已提交
1301
			edit.insert(document.uri, lastLine.range.end, text);
J
Joao Moreno 已提交
1302 1303
			await workspace.applyEdit(edit);
			await document.save();
N
NKumar2 已提交
1304 1305 1306
		});
	}

J
Johannes Rieken 已提交
1307
	checkIgnore(filePaths: string[]): Promise<Set<string>> {
1308
		return this.run(Operation.CheckIgnore, () => {
J
Johannes Rieken 已提交
1309 1310
			return new Promise<Set<string>>((resolve, reject) => {

J
Joao Moreno 已提交
1311 1312
				filePaths = filePaths
					.filter(filePath => isDescendant(this.root, filePath));
1313

1314 1315
				if (filePaths.length === 0) {
					// nothing left
C
cleidigh 已提交
1316
					return resolve(new Set<string>());
1317 1318
				}

1319
				// https://git-scm.com/docs/git-check-ignore#git-check-ignore--z
1320
				const child = this.repository.stream(['check-ignore', '-v', '-z', '--stdin'], { stdio: [null, null, null] });
1321
				child.stdin.end(filePaths.join('\0'), 'utf8');
J
Johannes Rieken 已提交
1322

1323
				const onExit = (exitCode: number) => {
J
Johannes Rieken 已提交
1324 1325 1326 1327
					if (exitCode === 1) {
						// nothing ignored
						resolve(new Set<string>());
					} else if (exitCode === 0) {
1328
						resolve(new Set<string>(this.parseIgnoreCheck(data)));
J
Johannes Rieken 已提交
1329
					} else {
J
Joao Moreno 已提交
1330 1331 1332 1333 1334
						if (/ is in submodule /.test(stderr)) {
							reject(new GitError({ stdout: data, stderr, exitCode, gitErrorCode: GitErrorCodes.IsInSubmodule }));
						} else {
							reject(new GitError({ stdout: data, stderr, exitCode }));
						}
J
Johannes Rieken 已提交
1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345
					}
				};

				let data = '';
				const onStdoutData = (raw: string) => {
					data += raw;
				};

				child.stdout.setEncoding('utf8');
				child.stdout.on('data', onStdoutData);

1346 1347 1348
				let stderr: string = '';
				child.stderr.setEncoding('utf8');
				child.stderr.on('data', raw => stderr += raw);
J
Johannes Rieken 已提交
1349 1350 1351 1352 1353 1354 1355

				child.on('error', reject);
				child.on('exit', onExit);
			});
		});
	}

1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372
	// Parses output of `git check-ignore -v -z` and returns only those paths
	// that are actually ignored by git.
	// Matches to a negative pattern (starting with '!') are filtered out.
	// See also https://git-scm.com/docs/git-check-ignore#_output.
	private parseIgnoreCheck(raw: string): string[] {
		const ignored = [];
		const elements = raw.split('\0');
		for (let i = 0; i < elements.length; i += 4) {
			const pattern = elements[i + 2];
			const path = elements[i + 3];
			if (pattern && !pattern.startsWith('!')) {
				ignored.push(path);
			}
		}
		return ignored;
	}

J
Joao Moreno 已提交
1373
	private async run<T>(operation: Operation, runOperation: () => Promise<T> = () => Promise.resolve<any>(null)): Promise<T> {
J
Joao 已提交
1374
		if (this.state !== RepositoryState.Idle) {
1375 1376 1377
			throw new Error('Repository not initialized');
		}

J
Joao Moreno 已提交
1378
		let error: any = null;
J
Joao Moreno 已提交
1379

J
Joao Moreno 已提交
1380 1381
		this._operations.start(operation);
		this._onRunOperation.fire(operation);
J
Joao Moreno 已提交
1382

J
Joao Moreno 已提交
1383
		try {
J
Joao Moreno 已提交
1384
			const result = await this.retryRun(operation, runOperation);
J
Joao Moreno 已提交
1385

J
Joao Moreno 已提交
1386 1387 1388
			if (!isReadOnly(operation)) {
				await this.updateModelState();
			}
J
Joao Moreno 已提交
1389

J
Joao Moreno 已提交
1390 1391 1392
			return result;
		} catch (err) {
			error = err;
J
Joao Moreno 已提交
1393

J
Joao Moreno 已提交
1394 1395
			if (err.gitErrorCode === GitErrorCodes.NotAGitRepository) {
				this.state = RepositoryState.Disposed;
J
Joao Moreno 已提交
1396
			}
1397

J
Joao Moreno 已提交
1398 1399 1400 1401 1402
			throw err;
		} finally {
			this._operations.end(operation);
			this._onDidRunOperation.fire({ operation, error });
		}
J
Joao Moreno 已提交
1403
	}
1404

J
Joao Moreno 已提交
1405
	private async retryRun<T>(operation: Operation, runOperation: () => Promise<T> = () => Promise.resolve<any>(null)): Promise<T> {
1406 1407 1408 1409 1410 1411 1412
		let attempt = 0;

		while (true) {
			try {
				attempt++;
				return await runOperation();
			} catch (err) {
J
Joao Moreno 已提交
1413 1414
				const shouldRetry = attempt <= 10 && (
					(err.gitErrorCode === GitErrorCodes.RepositoryIsLocked)
J
Joao Moreno 已提交
1415
					|| ((operation === Operation.Pull || operation === Operation.Sync || operation === Operation.Fetch) && (err.gitErrorCode === GitErrorCodes.CantLockRef || err.gitErrorCode === GitErrorCodes.CantRebaseMultipleBranches))
J
Joao Moreno 已提交
1416 1417 1418
				);

				if (shouldRetry) {
1419 1420 1421 1422 1423 1424 1425 1426 1427
					// quatratic backoff
					await timeout(Math.pow(attempt, 2) * 50);
				} else {
					throw err;
				}
			}
		}
	}

J
Joao Moreno 已提交
1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445
	private static KnownHugeFolderNames = ['node_modules'];

	private async findKnownHugeFolderPathsToIgnore(): Promise<string[]> {
		const folderPaths: string[] = [];

		for (const folderName of Repository.KnownHugeFolderNames) {
			const folderPath = path.join(this.repository.root, folderName);

			if (await new Promise<boolean>(c => fs.exists(folderPath, c))) {
				folderPaths.push(folderPath);
			}
		}

		const ignored = await this.checkIgnore(folderPaths);

		return folderPaths.filter(p => !ignored.has(p));
	}

J
Joao Moreno 已提交
1446
	@throttle
1447
	private async updateModelState(): Promise<void> {
J
Joao Moreno 已提交
1448
		const { status, didHitLimit } = await this.repository.getStatus();
1449
		const config = workspace.getConfiguration('git');
J
Joao Moreno 已提交
1450
		const scopedConfig = workspace.getConfiguration('git', Uri.file(this.repository.root));
1451
		const shouldIgnore = config.get<boolean>('ignoreLimitWarning') === true;
J
Johannes Rieken 已提交
1452
		const useIcons = !config.get<boolean>('decorations.enabled', true);
1453 1454 1455
		this.isRepositoryHuge = didHitLimit;

		if (didHitLimit && !shouldIgnore && !this.didWarnAboutLimit) {
J
Joao Moreno 已提交
1456 1457
			const knownHugeFolderPaths = await this.findKnownHugeFolderPathsToIgnore();
			const gitWarn = localize('huge', "The git repository at '{0}' has too many active changes, only a subset of Git features will be enabled.", this.repository.root);
B
Benjamin Pasero 已提交
1458
			const neverAgain = { title: localize('neveragain', "Don't Show Again") };
1459

J
Joao Moreno 已提交
1460 1461 1462
			if (knownHugeFolderPaths.length > 0) {
				const folderPath = knownHugeFolderPaths[0];
				const folderName = path.basename(folderPath);
M
Mrigank Krishan 已提交
1463

J
Joao Moreno 已提交
1464 1465
				const addKnown = localize('add known', "Would you like to add '{0}' to .gitignore?", folderName);
				const yes = { title: localize('yes', "Yes") };
M
Mrigank Krishan 已提交
1466

J
Joao Moreno 已提交
1467
				const result = await window.showWarningMessage(`${gitWarn} ${addKnown}`, yes, neverAgain);
1468 1469 1470

				if (result === neverAgain) {
					config.update('ignoreLimitWarning', true, false);
J
Joao Moreno 已提交
1471 1472 1473
					this.didWarnAboutLimit = true;
				} else if (result === yes) {
					this.ignore([Uri.file(folderPath)]);
1474
				}
M
Mrigank Krishan 已提交
1475
			} else {
J
Joao Moreno 已提交
1476
				const result = await window.showWarningMessage(gitWarn, neverAgain);
1477 1478 1479 1480 1481

				if (result === neverAgain) {
					config.update('ignoreLimitWarning', true, false);
				}

J
Joao Moreno 已提交
1482 1483
				this.didWarnAboutLimit = true;
			}
1484 1485
		}

J
Joao Moreno 已提交
1486
		let HEAD: Branch | undefined;
J
Joao Moreno 已提交
1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501

		try {
			HEAD = await this.repository.getHEAD();

			if (HEAD.name) {
				try {
					HEAD = await this.repository.getBranch(HEAD.name);
				} catch (err) {
					// noop
				}
			}
		} catch (err) {
			// noop
		}

J
Joao Moreno 已提交
1502 1503
		const sort = config.get<'alphabetically' | 'committerdate'>('branchSortOrder') || 'alphabetically';
		const [refs, remotes, submodules, rebaseCommit] = await Promise.all([this.repository.getRefs({ sort }), this.repository.getRemotes(), this.repository.getSubmodules(), this.getRebaseCommit()]);
J
Joao Moreno 已提交
1504 1505

		this._HEAD = HEAD;
M
Matt Bierner 已提交
1506 1507 1508
		this._refs = refs!;
		this._remotes = remotes!;
		this._submodules = submodules!;
1509
		this.rebaseCommit = rebaseCommit;
J
Joao Moreno 已提交
1510

J
Joao Moreno 已提交
1511
		const handleUntracked = scopedConfig.get<'withchanges' | 'separate' | 'hide'>('handleUntracked');
J
Joao Moreno 已提交
1512 1513 1514
		const index: Resource[] = [];
		const workingTree: Resource[] = [];
		const merge: Resource[] = [];
1515
		const untracked: Resource[] = [];
J
Joao Moreno 已提交
1516 1517

		status.forEach(raw => {
J
Joao Moreno 已提交
1518
			const uri = Uri.file(path.join(this.repository.root, raw.path));
1519 1520 1521
			const renameUri = raw.rename
				? Uri.file(path.join(this.repository.root, raw.rename))
				: undefined;
J
Joao Moreno 已提交
1522 1523

			switch (raw.x + raw.y) {
1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546
				case '??':
					switch (handleUntracked) {
						case 'withchanges':
							return workingTree.push(
								new Resource(
									ResourceGroupType.WorkingTree,
									uri,
									Status.UNTRACKED,
									useIcons
								)
							);
						case 'separate':
							return untracked.push(
								new Resource(
									ResourceGroupType.Untracked,
									uri,
									Status.UNTRACKED,
									useIcons
								)
							);
						case 'hide':
							return undefined;
					}
1547 1548 1549 1550 1551 1552 1553 1554
				case '!!': return workingTree.push(new Resource(ResourceGroupType.WorkingTree, uri, Status.IGNORED, useIcons));
				case 'DD': return merge.push(new Resource(ResourceGroupType.Merge, uri, Status.BOTH_DELETED, useIcons));
				case 'AU': return merge.push(new Resource(ResourceGroupType.Merge, uri, Status.ADDED_BY_US, useIcons));
				case 'UD': return merge.push(new Resource(ResourceGroupType.Merge, uri, Status.DELETED_BY_THEM, useIcons));
				case 'UA': return merge.push(new Resource(ResourceGroupType.Merge, uri, Status.ADDED_BY_THEM, useIcons));
				case 'DU': return merge.push(new Resource(ResourceGroupType.Merge, uri, Status.DELETED_BY_US, useIcons));
				case 'AA': return merge.push(new Resource(ResourceGroupType.Merge, uri, Status.BOTH_ADDED, useIcons));
				case 'UU': return merge.push(new Resource(ResourceGroupType.Merge, uri, Status.BOTH_MODIFIED, useIcons));
J
Joao Moreno 已提交
1555 1556 1557
			}

			switch (raw.x) {
J
Joao Moreno 已提交
1558
				case 'M': index.push(new Resource(ResourceGroupType.Index, uri, Status.INDEX_MODIFIED, useIcons)); break;
1559 1560 1561 1562
				case 'A': index.push(new Resource(ResourceGroupType.Index, uri, Status.INDEX_ADDED, useIcons)); break;
				case 'D': index.push(new Resource(ResourceGroupType.Index, uri, Status.INDEX_DELETED, useIcons)); break;
				case 'R': index.push(new Resource(ResourceGroupType.Index, uri, Status.INDEX_RENAMED, useIcons, renameUri)); break;
				case 'C': index.push(new Resource(ResourceGroupType.Index, uri, Status.INDEX_COPIED, useIcons, renameUri)); break;
J
Joao Moreno 已提交
1563 1564 1565
			}

			switch (raw.y) {
1566 1567
				case 'M': workingTree.push(new Resource(ResourceGroupType.WorkingTree, uri, Status.MODIFIED, useIcons, renameUri)); break;
				case 'D': workingTree.push(new Resource(ResourceGroupType.WorkingTree, uri, Status.DELETED, useIcons, renameUri)); break;
1568
				case 'A': workingTree.push(new Resource(ResourceGroupType.WorkingTree, uri, Status.INTENT_TO_ADD, useIcons, renameUri)); break;
J
Joao Moreno 已提交
1569
			}
1570
			return undefined;
J
Joao Moreno 已提交
1571 1572
		});

J
Joao Moreno 已提交
1573 1574 1575 1576
		// set resource groups
		this.mergeGroup.resourceStates = merge;
		this.indexGroup.resourceStates = index;
		this.workingTreeGroup.resourceStates = workingTree;
1577
		this.untrackedGroup.resourceStates = untracked;
J
Joao Moreno 已提交
1578 1579

		// set count badge
1580
		this.setCountBadge();
J
Joao Moreno 已提交
1581

J
Joao Moreno 已提交
1582
		this._onDidChangeStatus.fire();
J
Joao Moreno 已提交
1583 1584

		this._sourceControl.commitTemplate = await this.getInputTemplate();
J
Joao Moreno 已提交
1585 1586
	}

1587
	private setCountBadge(): void {
J
Joao Moreno 已提交
1588 1589 1590 1591
		const config = workspace.getConfiguration('git', Uri.file(this.repository.root));
		const countBadge = config.get<'all' | 'tracked' | 'off'>('countBadge');
		const handleUntracked = config.get<'withchanges' | 'separate' | 'hide'>('handleUntracked');

1592 1593 1594 1595
		let count =
			this.mergeGroup.resourceStates.length +
			this.indexGroup.resourceStates.length +
			this.workingTreeGroup.resourceStates.length;
1596 1597 1598

		switch (countBadge) {
			case 'off': count = 0; break;
1599 1600 1601 1602 1603 1604 1605 1606 1607 1608
			case 'tracked':
				if (handleUntracked === 'withchanges') {
					count -= this.workingTreeGroup.resourceStates.filter(r => r.type === Status.UNTRACKED || r.type === Status.IGNORED).length;
				}
				break;
			case 'all':
				if (handleUntracked === 'separate') {
					count += this.untrackedGroup.resourceStates.length;
				}
				break;
1609 1610 1611 1612 1613
		}

		this._sourceControl.count = count;
	}

1614 1615
	private async getRebaseCommit(): Promise<Commit | undefined> {
		const rebaseHeadPath = path.join(this.repository.root, '.git', 'REBASE_HEAD');
J
Jason Bright 已提交
1616 1617
		const rebaseApplyPath = path.join(this.repository.root, '.git', 'rebase-apply');
		const rebaseMergePath = path.join(this.repository.root, '.git', 'rebase-merge');
1618 1619

		try {
J
Jason Bright 已提交
1620 1621 1622 1623 1624 1625 1626 1627
			const [rebaseApplyExists, rebaseMergePathExists, rebaseHead] = await Promise.all([
				new Promise<boolean>(c => fs.exists(rebaseApplyPath, c)),
				new Promise<boolean>(c => fs.exists(rebaseMergePath, c)),
				new Promise<string>((c, e) => fs.readFile(rebaseHeadPath, 'utf8', (err, result) => err ? e(err) : c(result)))
			]);
			if (!rebaseApplyExists && !rebaseMergePathExists) {
				return undefined;
			}
1628 1629 1630 1631 1632 1633
			return await this.getCommit(rebaseHead.trim());
		} catch (err) {
			return undefined;
		}
	}

J
Joao Moreno 已提交
1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649
	private async maybeAutoStash<T>(runOperation: () => Promise<T>): Promise<T> {
		const config = workspace.getConfiguration('git', Uri.file(this.root));
		const shouldAutoStash = config.get<boolean>('autoStash')
			&& this.workingTreeGroup.resourceStates.some(r => r.type !== Status.UNTRACKED && r.type !== Status.IGNORED);

		if (!shouldAutoStash) {
			return await runOperation();
		}

		await this.repository.createStash(undefined, true);
		const result = await runOperation();
		await this.repository.popStash();

		return result;
	}

1650
	private onFileChange(_uri: Uri): void {
J
Joao Moreno 已提交
1651 1652 1653 1654 1655 1656 1657
		const config = workspace.getConfiguration('git');
		const autorefresh = config.get<boolean>('autorefresh');

		if (!autorefresh) {
			return;
		}

1658 1659 1660 1661
		if (this.isRepositoryHuge) {
			return;
		}

J
Joao Moreno 已提交
1662 1663 1664 1665 1666 1667 1668
		if (!this.operations.isIdle()) {
			return;
		}

		this.eventuallyUpdateWhenIdleAndWait();
	}

1669
	@debounce(1000)
J
Joao Moreno 已提交
1670
	private eventuallyUpdateWhenIdleAndWait(): void {
1671 1672 1673
		this.updateWhenIdleAndWait();
	}

J
Joao Moreno 已提交
1674
	@throttle
1675
	private async updateWhenIdleAndWait(): Promise<void> {
J
Joao 已提交
1676
		await this.whenIdleAndFocused();
J
Joao Moreno 已提交
1677
		await this.status();
J
Joao Moreno 已提交
1678
		await timeout(5000);
1679 1680
	}

J
Joao Moreno 已提交
1681
	async whenIdleAndFocused(): Promise<void> {
J
Joao 已提交
1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694
		while (true) {
			if (!this.operations.isIdle()) {
				await eventToPromise(this.onDidRunOperation);
				continue;
			}

			if (!window.state.focused) {
				const onDidFocusWindow = filterEvent(window.onDidChangeWindowState, e => e.focused);
				await eventToPromise(onDidFocusWindow);
				continue;
			}

			return;
1695 1696 1697
		}
	}

J
Joao 已提交
1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709
	get headLabel(): string {
		const HEAD = this.HEAD;

		if (!HEAD) {
			return '';
		}

		const tag = this.refs.filter(iref => iref.type === RefType.Tag && iref.commit === HEAD.commit)[0];
		const tagName = tag && tag.name;
		const head = HEAD.name || tagName || (HEAD.commit || '').substr(0, 8);

		return head
1710
			+ (this.workingTreeGroup.resourceStates.length + this.untrackedGroup.resourceStates.length > 0 ? '*' : '')
J
Joao 已提交
1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724
			+ (this.indexGroup.resourceStates.length > 0 ? '+' : '')
			+ (this.mergeGroup.resourceStates.length > 0 ? '!' : '');
	}

	get syncLabel(): string {
		if (!this.HEAD
			|| !this.HEAD.name
			|| !this.HEAD.commit
			|| !this.HEAD.upstream
			|| !(this.HEAD.ahead || this.HEAD.behind)
		) {
			return '';
		}

1725 1726 1727
		const remoteName = this.HEAD && this.HEAD.remote || this.HEAD.upstream.remote;
		const remote = this.remotes.find(r => r.name === remoteName);

J
Joao Moreno 已提交
1728
		if (remote && remote.isReadOnly) {
1729 1730 1731
			return `${this.HEAD.behind}↓`;
		}

J
Joao 已提交
1732 1733 1734
		return `${this.HEAD.behind}${this.HEAD.ahead}↑`;
	}

1735
	private updateInputBoxPlaceholder(): void {
J
Joao Moreno 已提交
1736
		const branchName = this.headShortName;
1737

A
al 已提交
1738
		if (branchName) {
1739
			// '{0}' will be replaced by the corresponding key-command later in the process, which is why it needs to stay.
A
al 已提交
1740
			this._sourceControl.inputBox.placeholder = localize('commitMessageWithHeadLabel', "Message ({0} to commit on '{1}')", "{0}", branchName);
1741 1742 1743 1744 1745
		} else {
			this._sourceControl.inputBox.placeholder = localize('commitMessage', "Message ({0} to commit)");
		}
	}

J
Joao Moreno 已提交
1746
	dispose(): void {
J
Joao Moreno 已提交
1747
		this.disposables = dispose(this.disposables);
J
Joao Moreno 已提交
1748
	}
1749
}