repository.ts 47.7 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 { commands, Uri, Command, EventEmitter, Event, scm, SourceControl, SourceControlInputBox, SourceControlResourceGroup, SourceControlResourceState, SourceControlResourceDecorations, SourceControlInputBoxValidation, Disposable, ProgressLocation, window, workspace, WorkspaceEdit, ThemeColor, DecorationData, Memento, SourceControlInputBoxValidationType } from 'vscode';
J
Joao Moreno 已提交
7
import { Repository as BaseRepository, Commit, Stash, GitError, Submodule, CommitOptions, ForcePushMode } from './git';
J
Joao Moreno 已提交
8
import { anyEvent, filterEvent, eventToPromise, dispose, find, isDescendant, IDisposable, onceEvent, EmptyDisposable, debounceEvent } from './util';
J
Joao Moreno 已提交
9
import { memoize, throttle, debounce } from './decorators';
J
Joao Moreno 已提交
10
import { toGitUri } from './uri';
J
Joao Moreno 已提交
11
import { AutoFetcher } from './autofetch';
J
Joao Moreno 已提交
12
import * as path from 'path';
J
Joao Moreno 已提交
13
import * as nls from 'vscode-nls';
14
import * as fs from 'fs';
M
Matt Bierner 已提交
15
import { StatusBarCommands } from './statusbar';
I
Ilya Biryukov 已提交
16
import { Branch, Ref, Remote, RefType, GitErrorCodes, Status } from './api/git';
J
Joao Moreno 已提交
17

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

J
Joao Moreno 已提交
20
const localize = nls.loadMessageBundle();
J
Joao Moreno 已提交
21 22 23 24 25 26
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`));
}

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

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

J
Joao Moreno 已提交
38
export class Resource implements SourceControlResourceState {
J
Joao Moreno 已提交
39

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

		return this._resourceUri;
47 48 49
	}

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

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

63
	private static Icons: any = {
J
Joao Moreno 已提交
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
		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 已提交
86
	private getIconPath(theme: string): Uri {
J
Joao Moreno 已提交
87 88 89 90 91 92 93 94 95 96
		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;
97
			case Status.INTENT_TO_ADD: return Resource.Icons[theme].Added;
J
Joao Moreno 已提交
98 99 100 101 102 103 104
			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 已提交
105
			default: throw new Error('Unknown git status: ' + this.type);
J
Joao Moreno 已提交
106 107 108
		}
	}

109 110 111 112 113 114 115 116 117 118 119
	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");
120
			case Status.INTENT_TO_ADD: return localize('intent to add', "Intent to Add");
121 122 123 124 125 126 127 128 129 130 131
			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 已提交
132 133 134 135 136 137
	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 已提交
138
			case Status.INDEX_DELETED:
J
Joao Moreno 已提交
139 140 141 142 143 144
				return true;
			default:
				return false;
		}
	}

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

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

162
		return { strikeThrough, faded, tooltip, light, dark, letter, color, source: 'git.resource' /*todo@joh*/ };
163 164
	}

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

J
Joao Moreno 已提交
198
	get color(): ThemeColor {
199
		switch (this.type) {
200 201
			case Status.INDEX_MODIFIED:
			case Status.MODIFIED:
J
Johannes Rieken 已提交
202
				return new ThemeColor('gitDecoration.modifiedResourceForeground');
203 204
			case Status.INDEX_DELETED:
			case Status.DELETED:
J
Johannes Rieken 已提交
205
				return new ThemeColor('gitDecoration.deletedResourceForeground');
206
			case Status.INDEX_ADDED:
207
			case Status.INTENT_TO_ADD:
208
				return new ThemeColor('gitDecoration.addedResourceForeground');
209 210
			case Status.INDEX_RENAMED: // todo@joh - special color?
			case Status.UNTRACKED:
J
Johannes Rieken 已提交
211
				return new ThemeColor('gitDecoration.untrackedResourceForeground');
212
			case Status.IGNORED:
J
Johannes Rieken 已提交
213
				return new ThemeColor('gitDecoration.ignoredResourceForeground');
214 215 216 217 218 219 220 221
			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 已提交
222
				return new ThemeColor('gitDecoration.conflictingResourceForeground');
I
Ilya Biryukov 已提交
223
			default:
J
Joao Moreno 已提交
224
				throw new Error('Unknown git status: ' + this.type);
225
		}
J
Joao Moreno 已提交
226 227
	}

J
Johannes Rieken 已提交
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
	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;
		}
	}

N
Nick Snyder 已提交
249
	get resourceDecoration(): DecorationData {
250
		const title = this.tooltip;
251
		const letter = this.letter;
252
		const color = this.color;
J
Johannes Rieken 已提交
253
		const priority = this.priority;
254
		return { bubble: true, source: 'git.resource', title, letter, color, priority };
255 256
	}

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

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

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

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

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

class OperationsImpl implements Operations {

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

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

J
Joao Moreno 已提交
344 345 346 347 348 349 350 351
	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);
		}
352 353 354
	}

	isRunning(operation: Operation): boolean {
J
Joao Moreno 已提交
355
		return this.operations.has(operation);
356
	}
357 358

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

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

		return true;
368
	}
J
Joao Moreno 已提交
369 370 371 372 373 374 375 376 377 378 379 380

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

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

		return false;
	}
381 382
}

J
Joao Moreno 已提交
383 384 385 386
export interface GitResourceGroup extends SourceControlResourceGroup {
	resourceStates: Resource[];
}

J
Joao Moreno 已提交
387 388 389 390 391
export interface OperationResult {
	operation: Operation;
	error: any;
}

J
Joao Moreno 已提交
392 393
class ProgressManager {

J
Joao Moreno 已提交
394
	private enabled = false;
J
Joao Moreno 已提交
395 396
	private disposable: IDisposable = EmptyDisposable;

J
Joao Moreno 已提交
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
	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 已提交
420 421 422 423 424 425 426 427 428

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

		setup();
J
Joao Moreno 已提交
429
		this.enabled = true;
J
Joao Moreno 已提交
430 431
	}

J
Joao Moreno 已提交
432 433 434 435 436
	private disable(): void {
		if (!this.enabled) {
			return;
		}

J
Joao Moreno 已提交
437
		this.disposable.dispose();
J
Joao Moreno 已提交
438 439 440 441 442 443
		this.disposable = EmptyDisposable;
		this.enabled = false;
	}

	dispose(): void {
		this.disable();
J
Joao Moreno 已提交
444 445 446
	}
}

J
Joao Moreno 已提交
447
export class Repository implements Disposable {
J
Joao Moreno 已提交
448

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

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

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

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

461 462 463
	private _onRunOperation = new EventEmitter<Operation>();
	readonly onRunOperation: Event<Operation> = this._onRunOperation.event;

J
Joao Moreno 已提交
464 465
	private _onDidRunOperation = new EventEmitter<OperationResult>();
	readonly onDidRunOperation: Event<OperationResult> = this._onDidRunOperation.event;
466 467 468 469 470 471

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

J
Joao Moreno 已提交
472 473 474
	private _sourceControl: SourceControl;
	get sourceControl(): SourceControl { return this._sourceControl; }

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

J
Joao Moreno 已提交
477 478
	private _mergeGroup: SourceControlResourceGroup;
	get mergeGroup(): GitResourceGroup { return this._mergeGroup as GitResourceGroup; }
J
Joao Moreno 已提交
479

J
Joao Moreno 已提交
480 481
	private _indexGroup: SourceControlResourceGroup;
	get indexGroup(): GitResourceGroup { return this._indexGroup as GitResourceGroup; }
J
Joao Moreno 已提交
482

J
Joao Moreno 已提交
483 484
	private _workingTreeGroup: SourceControlResourceGroup;
	get workingTreeGroup(): GitResourceGroup { return this._workingTreeGroup as GitResourceGroup; }
J
Joao Moreno 已提交
485

J
Joao Moreno 已提交
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
	private _HEAD: Branch | undefined;
	get HEAD(): Branch | undefined {
		return this._HEAD;
	}

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

	private _remotes: Remote[] = [];
	get remotes(): Remote[] {
		return this._remotes;
	}

501 502 503 504 505
	private _submodules: Submodule[] = [];
	get submodules(): Submodule[] {
		return this._submodules;
	}

506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
	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;
	}

522 523 524
	private _operations = new OperationsImpl();
	get operations(): Operations { return this._operations; }

J
Joao 已提交
525 526 527
	private _state = RepositoryState.Idle;
	get state(): RepositoryState { return this._state; }
	set state(state: RepositoryState) {
J
Joao Moreno 已提交
528 529
		this._state = state;
		this._onDidChangeState.fire(state);
J
Joao Moreno 已提交
530 531 532 533

		this._HEAD = undefined;
		this._refs = [];
		this._remotes = [];
J
Joao Moreno 已提交
534 535 536 537
		this.mergeGroup.resourceStates = [];
		this.indexGroup.resourceStates = [];
		this.workingTreeGroup.resourceStates = [];
		this._sourceControl.count = 0;
J
Joao Moreno 已提交
538 539
	}

540 541 542 543
	get root(): string {
		return this.repository.root;
	}

544 545
	private isRepositoryHuge = false;
	private didWarnAboutLimit = false;
J
Joao Moreno 已提交
546
	private isFreshRepository: boolean | undefined = undefined;
J
Joao Moreno 已提交
547
	private disposables: Disposable[] = [];
J
Joao Moreno 已提交
548

549
	constructor(
J
Joao Moreno 已提交
550 551
		private readonly repository: BaseRepository,
		globalState: Memento
552
	) {
J
Joao Moreno 已提交
553 554 555
		const fsWatcher = workspace.createFileSystemWatcher('**');
		this.disposables.push(fsWatcher);

J
Joao Moreno 已提交
556 557 558 559 560 561 562 563 564 565 566 567 568 569
		const workspaceFilter = (uri: Uri) => isDescendant(repository.root, uri.fsPath);
		const onWorkspaceDelete = filterEvent(fsWatcher.onDidDelete, workspaceFilter);
		const onWorkspaceChange = filterEvent(anyEvent(fsWatcher.onDidChange, fsWatcher.onDidCreate), workspaceFilter);
		const onRepositoryDotGitDelete = filterEvent(onWorkspaceDelete, uri => /\/\.git$/.test(uri.path));
		const onRepositoryChange = anyEvent(onWorkspaceDelete, onWorkspaceChange);

		// relevant repository changes are:
		//  - DELETE .git folder
		//  - ANY CHANGE within .git folder except .git itself and .git/index.lock
		const onRelevantRepositoryChange = anyEvent(
			onRepositoryDotGitDelete,
			filterEvent(onRepositoryChange, uri => !/\/\.git(\/index\.lock)?$/.test(uri.path))
		);

J
Joao Moreno 已提交
570
		onRelevantRepositoryChange(this.onFSChange, this, this.disposables);
571

J
Joao Moreno 已提交
572
		const onRelevantGitChange = filterEvent(onRelevantRepositoryChange, uri => /\/\.git\//.test(uri.path));
J
Joao Moreno 已提交
573 574
		onRelevantGitChange(this._onDidChangeRepository.fire, this._onDidChangeRepository, this.disposables);

J
Joao Moreno 已提交
575 576
		const root = Uri.file(repository.root);
		this._sourceControl = scm.createSourceControl('git', 'Git', root);
577
		this._sourceControl.inputBox.placeholder = localize('commitMessage', "Message (press {0} to commit)");
J
Joao Moreno 已提交
578
		this._sourceControl.acceptInputCommand = { command: 'git.commitWithInput', title: localize('commit', "Commit"), arguments: [this._sourceControl] };
J
Joao Moreno 已提交
579
		this._sourceControl.quickDiffProvider = this;
J
Joao Moreno 已提交
580
		this._sourceControl.inputBox.validateInput = this.validateInput.bind(this);
J
Joao Moreno 已提交
581 582 583 584 585 586
		this.disposables.push(this._sourceControl);

		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"));

J
Joao Moreno 已提交
587 588 589 590 591 592 593 594
		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 已提交
595

J
Joao Moreno 已提交
596 597 598 599 600 601
		this.mergeGroup.hideWhenEmpty = true;

		this.disposables.push(this.mergeGroup);
		this.disposables.push(this.indexGroup);
		this.disposables.push(this.workingTreeGroup);

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

604 605 606 607 608 609 610 611 612 613
		// 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 已提交
614 615 616 617 618
		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 已提交
619 620 621
		const progressManager = new ProgressManager(this);
		this.disposables.push(progressManager);

J
Joao Moreno 已提交
622
		this.updateCommitTemplate();
J
Joao Moreno 已提交
623
		this.status();
J
Joao Moreno 已提交
624 625
	}

626
	validateInput(text: string, position: number): SourceControlInputBoxValidation | undefined {
627 628 629 630 631 632 633 634 635
		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
				};
			}
		}

636 637 638 639 640 641 642
		const config = workspace.getConfiguration('git');
		const setting = config.get<'always' | 'warn' | 'off'>('inputValidation');

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

J
Joao Moreno 已提交
643
		if (/^\s+$/.test(text)) {
644
			return {
J
Joao Moreno 已提交
645
				message: localize('commitMessageWhitespacesOnlyWarning', "Current commit message only contains whitespace characters"),
646 647 648 649
				type: SourceControlInputBoxValidationType.Warning
			};
		}

650
		let lineNumber = 0;
651 652 653 654 655 656
		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;
657
			lineNumber++;
658 659 660 661 662 663
		}

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

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

664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688
		let threshold = config.get<number>('inputValidationLength', 50);

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

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










		// const subjectThreshold =


		// 	Math.max(config.get<number>('inputValidationLength') || 50, config.get<number>('subjectValidationLength') || 50, 0) || 50;

		if (line.length <= threshold) {
689 690 691 692 693
			if (setting !== 'always') {
				return;
			}

			return {
694
				message: localize('commitMessageCountdown', "{0} characters left in current line", threshold - line.length),
695 696 697 698
				type: SourceControlInputBoxValidationType.Information
			};
		} else {
			return {
699
				message: localize('commitMessageWarning', "{0} characters over {1} in current line", line.length - threshold, threshold),
700 701 702 703 704
				type: SourceControlInputBoxValidationType.Warning
			};
		}
	}

J
Joao Moreno 已提交
705 706 707 708 709
	provideOriginalResource(uri: Uri): Uri | undefined {
		if (uri.scheme !== 'file') {
			return;
		}

710
		return toGitUri(uri, '', { replaceFileExtension: true });
J
Joao Moreno 已提交
711 712 713 714 715 716 717 718 719 720
	}

	private async updateCommitTemplate(): Promise<void> {
		try {
			this._sourceControl.commitTemplate = await this.repository.getCommitTemplate();
		} catch (e) {
			// noop
		}
	}

J
Joao Moreno 已提交
721 722 723 724 725 726 727 728 729 730 731 732
	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));
	}

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

J
Joao Moreno 已提交
733
	@throttle
J
Joao Moreno 已提交
734 735
	async status(): Promise<void> {
		await this.run(Operation.Status);
J
Joao Moreno 已提交
736
	}
J
Joao Moreno 已提交
737

738 739 740 741
	diff(cached?: boolean): Promise<string> {
		return this.run(Operation.Diff, () => this.repository.diff(cached));
	}

J
Joao Moreno 已提交
742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771
	diffWithHEAD(path: string): Promise<string> {
		return this.run(Operation.Diff, () => this.repository.diffWithHEAD(path));
	}

	diffWith(ref: string, path: string): Promise<string> {
		return this.run(Operation.Diff, () => this.repository.diffWith(ref, path));
	}

	diffIndexWithHEAD(path: string): Promise<string> {
		return this.run(Operation.Diff, () => this.repository.diffIndexWithHEAD(path));
	}

	diffIndexWith(ref: string, path: string): Promise<string> {
		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));
	}

	diffBetween(ref1: string, ref2: string, path: string): Promise<string> {
		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));
772 773
	}

J
Joao Moreno 已提交
774
	async add(resources: Uri[]): Promise<void> {
775
		await this.run(Operation.Add, () => this.repository.add(resources.map(r => r.fsPath)));
J
Joao Moreno 已提交
776 777
	}

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

J
Joao Moreno 已提交
782 783
	async stage(resource: Uri, contents: string): Promise<void> {
		const relativePath = path.relative(this.repository.root, resource.fsPath).replace(/\\/g, '/');
J
Joao Moreno 已提交
784
		await this.run(Operation.Stage, () => this.repository.stage(relativePath, contents));
J
Joao Moreno 已提交
785
		this._onDidChangeOriginalResource.fire(resource);
J
Joao Moreno 已提交
786 787
	}

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

J
Joao Moreno 已提交
792
	async commit(message: string, opts: CommitOptions = Object.create(null)): Promise<void> {
793 794 795 796 797
		if (this.rebaseCommit) {
			await this.run(Operation.RebaseContinue, async () => {
				if (opts.all) {
					await this.repository.add([]);
				}
J
Joao Moreno 已提交
798

799 800 801 802 803 804 805 806 807 808 809
				await this.repository.rebaseContinue();
			});
		} else {
			await this.run(Operation.Commit, async () => {
				if (opts.all) {
					await this.repository.add([]);
				}

				await this.repository.commit(message, opts);
			});
		}
J
Joao Moreno 已提交
810
	}
J
Joao Moreno 已提交
811

J
Joao Moreno 已提交
812
	async clean(resources: Uri[]): Promise<void> {
813 814 815
		await this.run(Operation.Clean, async () => {
			const toClean: string[] = [];
			const toCheckout: string[] = [];
816
			const submodulesToUpdate: string[] = [];
817 818

			resources.forEach(r => {
819 820 821 822 823 824 825 826 827
				const fsPath = r.fsPath;

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

828
				const raw = r.toString();
J
Joao Moreno 已提交
829
				const scmResource = find(this.workingTreeGroup.resourceStates, sr => sr.resourceUri.toString() === raw);
830 831 832 833 834 835

				if (!scmResource) {
					return;
				}

				switch (scmResource.type) {
836 837
					case Status.UNTRACKED:
					case Status.IGNORED:
838
						toClean.push(fsPath);
839 840 841
						break;

					default:
842
						toCheckout.push(fsPath);
843 844 845
						break;
				}
			});
J
Joao Moreno 已提交
846

847
			const promises: Promise<void>[] = [];
J
Joao Moreno 已提交
848

849 850 851
			if (toClean.length > 0) {
				promises.push(this.repository.clean(toClean));
			}
J
Joao Moreno 已提交
852

853 854 855
			if (toCheckout.length > 0) {
				promises.push(this.repository.checkout('', toCheckout));
			}
J
Joao Moreno 已提交
856

857 858 859 860
			if (submodulesToUpdate.length > 0) {
				promises.push(this.repository.updateSubmodules(submodulesToUpdate));
			}

861 862
			await Promise.all(promises);
		});
J
Joao Moreno 已提交
863
	}
J
Joao Moreno 已提交
864

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

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

873 874 875 876
	async renameBranch(name: string): Promise<void> {
		await this.run(Operation.RenameBranch, () => this.repository.renameBranch(name));
	}

J
Joao Moreno 已提交
877 878 879 880 881 882 883 884
	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 已提交
885 886
	async merge(ref: string): Promise<void> {
		await this.run(Operation.Merge, () => this.repository.merge(ref));
887 888
	}

J
Joao Moreno 已提交
889 890
	async tag(name: string, message?: string): Promise<void> {
		await this.run(Operation.Tag, () => this.repository.tag(name, message));
891 892
	}

J
Joao Moreno 已提交
893
	async checkout(treeish: string): Promise<void> {
J
Joao Moreno 已提交
894
		await this.run(Operation.Checkout, () => this.repository.checkout(treeish, []));
J
Joao Moreno 已提交
895
	}
J
Joao Moreno 已提交
896

897 898 899 900
	async checkoutTracking(treeish: string): Promise<void> {
		await this.run(Operation.CheckoutTracking, () => this.repository.checkout(treeish, [], { track: true }));
	}

J
Joao Moreno 已提交
901 902 903 904 905 906 907 908
	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));
	}

909 910 911 912
	async deleteRef(ref: string): Promise<void> {
		await this.run(Operation.DeleteRef, () => this.repository.deleteRef(ref));
	}

J
Joao Moreno 已提交
913 914 915 916 917 918 919 920
	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 已提交
921
	@throttle
J
Joao Moreno 已提交
922 923 924 925
	async fetchDefault(): Promise<void> {
		await this.run(Operation.Fetch, () => this.repository.fetch());
	}

R
Ryan Scott 已提交
926 927 928 929 930
	@throttle
	async fetchPrune(): Promise<void> {
		await this.run(Operation.Fetch, () => this.repository.fetch({ prune: true }));
	}

J
Joao Moreno 已提交
931 932 933 934 935
	@throttle
	async fetchAll(): Promise<void> {
		await this.run(Operation.Fetch, () => this.repository.fetch({ all: true }));
	}

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

J
Joao Moreno 已提交
940
	@throttle
J
Joao Moreno 已提交
941
	async pullWithRebase(head: Branch | undefined): Promise<void> {
J
Joao Moreno 已提交
942 943
		let remote: string | undefined;
		let branch: string | undefined;
J
Joao Moreno 已提交
944

J
Joao Moreno 已提交
945 946 947
		if (head && head.name && head.upstream) {
			remote = head.upstream.remote;
			branch = `${head.upstream.name}`;
J
Joao Moreno 已提交
948 949
		}

950
		return this.pullFrom(true, remote, branch);
J
Joao Moreno 已提交
951 952 953
	}

	@throttle
J
Joao Moreno 已提交
954
	async pull(head?: Branch): Promise<void> {
J
Joao Moreno 已提交
955 956 957
		let remote: string | undefined;
		let branch: string | undefined;

J
Joao Moreno 已提交
958 959 960
		if (head && head.name && head.upstream) {
			remote = head.upstream.remote;
			branch = `${head.upstream.name}`;
J
Joao Moreno 已提交
961 962
		}

963
		return this.pullFrom(false, remote, branch);
J
Joao Moreno 已提交
964 965
	}

966
	async pullFrom(rebase?: boolean, remote?: string, branch?: string): Promise<void> {
967
		await this.run(Operation.Pull, async () => {
J
Joao Moreno 已提交
968 969 970
			await this.maybeAutoStash(async () => {
				const config = workspace.getConfiguration('git', Uri.file(this.root));
				const fetchOnPull = config.get<boolean>('fetchOnPull');
971

J
Joao Moreno 已提交
972 973 974 975 976 977
				if (fetchOnPull) {
					await this.repository.pull(rebase);
				} else {
					await this.repository.pull(rebase, remote, branch);
				}
			});
978
		});
J
Joao Moreno 已提交
979 980
	}

J
Joao Moreno 已提交
981
	@throttle
982
	async push(head: Branch, forcePushMode?: ForcePushMode): Promise<void> {
J
Joao Moreno 已提交
983 984 985
		let remote: string | undefined;
		let branch: string | undefined;

J
Joao Moreno 已提交
986 987 988
		if (head && head.name && head.upstream) {
			remote = head.upstream.remote;
			branch = `${head.name}:${head.upstream.name}`;
J
Joao Moreno 已提交
989 990
		}

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

994 995
	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));
996 997
	}

998 999
	async pushTags(remote?: string, forcePushMode?: ForcePushMode): Promise<void> {
		await this.run(Operation.Push, () => this.repository.push(remote, undefined, false, true, forcePushMode));
1000 1001
	}

J
Joao Moreno 已提交
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
	@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> {
1013
		let remoteName: string | undefined;
J
Joao Moreno 已提交
1014 1015 1016 1017
		let pullBranch: string | undefined;
		let pushBranch: string | undefined;

		if (head.name && head.upstream) {
1018
			remoteName = head.upstream.remote;
J
Joao Moreno 已提交
1019 1020 1021 1022
			pullBranch = `${head.upstream.name}`;
			pushBranch = `${head.name}:${head.upstream.name}`;
		}

1023
		await this.run(Operation.Sync, async () => {
J
Joao Moreno 已提交
1024 1025 1026
			await this.maybeAutoStash(async () => {
				const config = workspace.getConfiguration('git', Uri.file(this.root));
				const fetchOnPull = config.get<boolean>('fetchOnPull');
1027

J
Joao Moreno 已提交
1028 1029 1030 1031 1032
				if (fetchOnPull) {
					await this.repository.pull(rebase);
				} else {
					await this.repository.pull(rebase, remoteName, pullBranch);
				}
1033

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

J
Joao Moreno 已提交
1036 1037 1038
				if (remote && remote.isReadOnly) {
					return;
				}
J
Joao Moreno 已提交
1039

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

J
Joao Moreno 已提交
1042 1043 1044 1045
				if (shouldPush) {
					await this.repository.push(remoteName, pushBranch);
				}
			});
1046
		});
J
Joao Moreno 已提交
1047 1048
	}

1049
	async show(ref: string, filePath: string): Promise<string> {
1050 1051
		return await this.run(Operation.Show, async () => {
			const relativePath = path.relative(this.repository.root, filePath).replace(/\\/g, '/');
J
Joao Moreno 已提交
1052
			const configFiles = workspace.getConfiguration('files', Uri.file(filePath));
J
Joao Moreno 已提交
1053
			const defaultEncoding = configFiles.get<string>('encoding');
1054 1055
			const autoGuessEncoding = configFiles.get<boolean>('autoGuessEncoding');

1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
			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 已提交
1066 1067 1068 1069
		});
	}

	async buffer(ref: string, filePath: string): Promise<Buffer> {
J
Joao Moreno 已提交
1070
		return this.run(Operation.Show, () => {
J
Joao Moreno 已提交
1071
			const relativePath = path.relative(this.repository.root, filePath).replace(/\\/g, '/');
J
Joao Moreno 已提交
1072
			return this.repository.buffer(`${ref}:${relativePath}`);
J
Joao Moreno 已提交
1073 1074 1075
		});
	}

J
Joao Moreno 已提交
1076 1077
	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 已提交
1078 1079 1080 1081 1082 1083
	}

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

1084 1085 1086 1087
	async apply(patch: string, reverse?: boolean): Promise<void> {
		return await this.run(Operation.Apply, () => this.repository.apply(patch, reverse));
	}

J
Joao Moreno 已提交
1088 1089 1090 1091
	async getStashes(): Promise<Stash[]> {
		return await this.repository.getStashes();
	}

1092 1093
	async createStash(message?: string, includeUntracked?: boolean): Promise<void> {
		return await this.run(Operation.Stash, () => this.repository.createStash(message, includeUntracked));
J
Joao Moreno 已提交
1094 1095 1096 1097
	}

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

1100 1101 1102 1103
	async applyStash(index?: number): Promise<void> {
		return await this.run(Operation.Stash, () => this.repository.applyStash(index));
	}

J
Joao Moreno 已提交
1104 1105 1106 1107
	async getCommitTemplate(): Promise<string> {
		return await this.run(Operation.GetCommitTemplate, async () => this.repository.getCommitTemplate());
	}

J
Joao Moreno 已提交
1108
	async ignore(files: Uri[]): Promise<void> {
N
NKumar2 已提交
1109
		return await this.run(Operation.Ignore, async () => {
J
Joao Moreno 已提交
1110 1111
			const ignoreFile = `${this.repository.root}${path.sep}.gitignore`;
			const textToAppend = files
J
Joao Moreno 已提交
1112
				.map(uri => path.relative(this.repository.root, uri.fsPath).replace(/\\/g, '/'))
J
Joao Moreno 已提交
1113
				.join('\n');
N
NKumar2 已提交
1114

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

J
Joao Moreno 已提交
1119
			await window.showTextDocument(document);
J
Joao Moreno 已提交
1120

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

J
Joao Moreno 已提交
1125
			edit.insert(document.uri, lastLine.range.end, text);
J
Joao Moreno 已提交
1126 1127
			await workspace.applyEdit(edit);
			await document.save();
N
NKumar2 已提交
1128 1129 1130
		});
	}

J
Johannes Rieken 已提交
1131
	checkIgnore(filePaths: string[]): Promise<Set<string>> {
1132
		return this.run(Operation.CheckIgnore, () => {
J
Johannes Rieken 已提交
1133 1134
			return new Promise<Set<string>>((resolve, reject) => {

J
Joao Moreno 已提交
1135 1136
				filePaths = filePaths
					.filter(filePath => isDescendant(this.root, filePath));
1137

1138 1139
				if (filePaths.length === 0) {
					// nothing left
C
cleidigh 已提交
1140
					return resolve(new Set<string>());
1141 1142
				}

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

1147
				const onExit = (exitCode: number) => {
J
Johannes Rieken 已提交
1148 1149 1150 1151
					if (exitCode === 1) {
						// nothing ignored
						resolve(new Set<string>());
					} else if (exitCode === 0) {
1152 1153
						// paths are separated by the null-character
						resolve(new Set<string>(data.split('\0')));
J
Johannes Rieken 已提交
1154
					} else {
J
Joao Moreno 已提交
1155 1156 1157 1158 1159
						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 已提交
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
					}
				};

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

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

1171 1172 1173
				let stderr: string = '';
				child.stderr.setEncoding('utf8');
				child.stderr.on('data', raw => stderr += raw);
J
Johannes Rieken 已提交
1174 1175 1176 1177 1178 1179 1180

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

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

J
Joao Moreno 已提交
1186
		let error: any = null;
J
Joao Moreno 已提交
1187

J
Joao Moreno 已提交
1188 1189
		this._operations.start(operation);
		this._onRunOperation.fire(operation);
J
Joao Moreno 已提交
1190

J
Joao Moreno 已提交
1191
		try {
J
Joao Moreno 已提交
1192
			const result = await this.retryRun(operation, runOperation);
J
Joao Moreno 已提交
1193

J
Joao Moreno 已提交
1194 1195 1196
			if (!isReadOnly(operation)) {
				await this.updateModelState();
			}
J
Joao Moreno 已提交
1197

J
Joao Moreno 已提交
1198 1199 1200
			return result;
		} catch (err) {
			error = err;
J
Joao Moreno 已提交
1201

J
Joao Moreno 已提交
1202 1203
			if (err.gitErrorCode === GitErrorCodes.NotAGitRepository) {
				this.state = RepositoryState.Disposed;
J
Joao Moreno 已提交
1204
			}
1205

J
Joao Moreno 已提交
1206 1207 1208 1209 1210
			throw err;
		} finally {
			this._operations.end(operation);
			this._onDidRunOperation.fire({ operation, error });
		}
J
Joao Moreno 已提交
1211
	}
1212

J
Joao Moreno 已提交
1213
	private async retryRun<T>(operation: Operation, runOperation: () => Promise<T> = () => Promise.resolve<any>(null)): Promise<T> {
1214 1215 1216 1217 1218 1219 1220
		let attempt = 0;

		while (true) {
			try {
				attempt++;
				return await runOperation();
			} catch (err) {
J
Joao Moreno 已提交
1221 1222
				const shouldRetry = attempt <= 10 && (
					(err.gitErrorCode === GitErrorCodes.RepositoryIsLocked)
J
Joao Moreno 已提交
1223
					|| ((operation === Operation.Pull || operation === Operation.Sync || operation === Operation.Fetch) && (err.gitErrorCode === GitErrorCodes.CantLockRef || err.gitErrorCode === GitErrorCodes.CantRebaseMultipleBranches))
J
Joao Moreno 已提交
1224 1225 1226
				);

				if (shouldRetry) {
1227 1228 1229 1230 1231 1232 1233 1234 1235
					// quatratic backoff
					await timeout(Math.pow(attempt, 2) * 50);
				} else {
					throw err;
				}
			}
		}
	}

J
Joao Moreno 已提交
1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253
	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 已提交
1254
	@throttle
1255
	private async updateModelState(): Promise<void> {
J
Joao Moreno 已提交
1256
		const { status, didHitLimit } = await this.repository.getStatus();
1257 1258
		const config = workspace.getConfiguration('git');
		const shouldIgnore = config.get<boolean>('ignoreLimitWarning') === true;
J
Johannes Rieken 已提交
1259
		const useIcons = !config.get<boolean>('decorations.enabled', true);
1260 1261 1262 1263

		this.isRepositoryHuge = didHitLimit;

		if (didHitLimit && !shouldIgnore && !this.didWarnAboutLimit) {
J
Joao Moreno 已提交
1264 1265
			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 已提交
1266
			const neverAgain = { title: localize('neveragain', "Don't Show Again") };
1267

J
Joao Moreno 已提交
1268 1269 1270
			if (knownHugeFolderPaths.length > 0) {
				const folderPath = knownHugeFolderPaths[0];
				const folderName = path.basename(folderPath);
M
Mrigank Krishan 已提交
1271

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

J
Joao Moreno 已提交
1275
				const result = await window.showWarningMessage(`${gitWarn} ${addKnown}`, yes, neverAgain);
1276 1277 1278

				if (result === neverAgain) {
					config.update('ignoreLimitWarning', true, false);
J
Joao Moreno 已提交
1279 1280 1281
					this.didWarnAboutLimit = true;
				} else if (result === yes) {
					this.ignore([Uri.file(folderPath)]);
1282
				}
M
Mrigank Krishan 已提交
1283
			} else {
J
Joao Moreno 已提交
1284
				const result = await window.showWarningMessage(gitWarn, neverAgain);
1285 1286 1287 1288 1289

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

J
Joao Moreno 已提交
1290 1291
				this.didWarnAboutLimit = true;
			}
1292 1293
		}

J
Joao Moreno 已提交
1294
		let HEAD: Branch | undefined;
J
Joao Moreno 已提交
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309

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

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

1310
		const [refs, remotes, submodules, rebaseCommit] = await Promise.all([this.repository.getRefs(), this.repository.getRemotes(), this.repository.getSubmodules(), this.getRebaseCommit()]);
J
Joao Moreno 已提交
1311 1312 1313 1314

		this._HEAD = HEAD;
		this._refs = refs;
		this._remotes = remotes;
1315
		this._submodules = submodules;
1316
		this.rebaseCommit = rebaseCommit;
J
Joao Moreno 已提交
1317 1318 1319 1320 1321 1322

		const index: Resource[] = [];
		const workingTree: Resource[] = [];
		const merge: Resource[] = [];

		status.forEach(raw => {
J
Joao Moreno 已提交
1323 1324
			const uri = Uri.file(path.join(this.repository.root, raw.path));
			const renameUri = raw.rename ? Uri.file(path.join(this.repository.root, raw.rename)) : undefined;
J
Joao Moreno 已提交
1325 1326

			switch (raw.x + raw.y) {
1327 1328 1329 1330 1331 1332 1333 1334 1335
				case '??': return workingTree.push(new Resource(ResourceGroupType.WorkingTree, uri, Status.UNTRACKED, useIcons));
				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 已提交
1336 1337 1338
			}

			switch (raw.x) {
J
Joao Moreno 已提交
1339
				case 'M': index.push(new Resource(ResourceGroupType.Index, uri, Status.INDEX_MODIFIED, useIcons)); break;
1340 1341 1342 1343
				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 已提交
1344 1345 1346
			}

			switch (raw.y) {
1347 1348
				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;
1349
				case 'A': workingTree.push(new Resource(ResourceGroupType.WorkingTree, uri, Status.INTENT_TO_ADD, useIcons, renameUri)); break;
J
Joao Moreno 已提交
1350
			}
1351
			return undefined;
J
Joao Moreno 已提交
1352 1353
		});

J
Joao Moreno 已提交
1354 1355 1356 1357 1358 1359 1360
		// set resource groups
		this.mergeGroup.resourceStates = merge;
		this.indexGroup.resourceStates = index;
		this.workingTreeGroup.resourceStates = workingTree;

		// set count badge
		const countBadge = workspace.getConfiguration('git').get<string>('countBadge');
J
Joao Moreno 已提交
1361 1362
		let count = merge.length + index.length + workingTree.length;

J
Joao Moreno 已提交
1363
		switch (countBadge) {
J
Joao Moreno 已提交
1364 1365
			case 'off': count = 0; break;
			case 'tracked': count = count - workingTree.filter(r => r.type === Status.UNTRACKED || r.type === Status.IGNORED).length; break;
J
Joao Moreno 已提交
1366 1367
		}

J
Joao Moreno 已提交
1368 1369
		this._sourceControl.count = count;

J
Joao Moreno 已提交
1370 1371
		// Disable `Discard All Changes` for "fresh" repositories
		// https://github.com/Microsoft/vscode/issues/43066
J
Joao Moreno 已提交
1372 1373 1374 1375 1376 1377
		const isFreshRepository = !this._HEAD || !this._HEAD.commit;

		if (this.isFreshRepository !== isFreshRepository) {
			commands.executeCommand('setContext', 'gitFreshRepository', isFreshRepository);
			this.isFreshRepository = isFreshRepository;
		}
J
Joao Moreno 已提交
1378

J
Joao Moreno 已提交
1379
		this._onDidChangeStatus.fire();
J
Joao Moreno 已提交
1380 1381
	}

1382 1383
	private async getRebaseCommit(): Promise<Commit | undefined> {
		const rebaseHeadPath = path.join(this.repository.root, '.git', 'REBASE_HEAD');
J
Jason Bright 已提交
1384 1385
		const rebaseApplyPath = path.join(this.repository.root, '.git', 'rebase-apply');
		const rebaseMergePath = path.join(this.repository.root, '.git', 'rebase-merge');
1386 1387

		try {
J
Jason Bright 已提交
1388 1389 1390 1391 1392 1393 1394 1395
			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;
			}
1396 1397 1398 1399 1400 1401
			return await this.getCommit(rebaseHead.trim());
		} catch (err) {
			return undefined;
		}
	}

J
Joao Moreno 已提交
1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417
	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;
	}

1418
	private onFSChange(_uri: Uri): void {
J
Joao Moreno 已提交
1419 1420 1421 1422 1423 1424 1425
		const config = workspace.getConfiguration('git');
		const autorefresh = config.get<boolean>('autorefresh');

		if (!autorefresh) {
			return;
		}

1426 1427 1428 1429
		if (this.isRepositoryHuge) {
			return;
		}

J
Joao Moreno 已提交
1430 1431 1432 1433 1434 1435 1436
		if (!this.operations.isIdle()) {
			return;
		}

		this.eventuallyUpdateWhenIdleAndWait();
	}

1437
	@debounce(1000)
J
Joao Moreno 已提交
1438
	private eventuallyUpdateWhenIdleAndWait(): void {
1439 1440 1441
		this.updateWhenIdleAndWait();
	}

J
Joao Moreno 已提交
1442
	@throttle
1443
	private async updateWhenIdleAndWait(): Promise<void> {
J
Joao 已提交
1444
		await this.whenIdleAndFocused();
J
Joao Moreno 已提交
1445
		await this.status();
J
Joao Moreno 已提交
1446
		await timeout(5000);
1447 1448
	}

J
Joao Moreno 已提交
1449
	async whenIdleAndFocused(): Promise<void> {
J
Joao 已提交
1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
		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;
1463 1464 1465
		}
	}

J
Joao 已提交
1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492
	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
			+ (this.workingTreeGroup.resourceStates.length > 0 ? '*' : '')
			+ (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 '';
		}

1493 1494 1495
		const remoteName = this.HEAD && this.HEAD.remote || this.HEAD.upstream.remote;
		const remote = this.remotes.find(r => r.name === remoteName);

J
Joao Moreno 已提交
1496
		if (remote && remote.isReadOnly) {
1497 1498 1499
			return `${this.HEAD.behind}↓`;
		}

J
Joao 已提交
1500 1501 1502
		return `${this.HEAD.behind}${this.HEAD.ahead}↑`;
	}

J
Joao Moreno 已提交
1503
	dispose(): void {
J
Joao Moreno 已提交
1504
		this.disposables = dispose(this.disposables);
J
Joao Moreno 已提交
1505
	}
1506
}