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

'use strict';

J
Joao Moreno 已提交
8
import { 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 已提交
9
import { Repository as BaseRepository, Commit, Stash, GitError, Submodule } from './git';
J
Joao Moreno 已提交
10
import { anyEvent, filterEvent, eventToPromise, dispose, find, isDescendant, IDisposable, onceEvent, EmptyDisposable, debounceEvent } from './util';
J
Joao Moreno 已提交
11
import { memoize, throttle, debounce } from './decorators';
J
Joao Moreno 已提交
12
import { toGitUri } from './uri';
J
Joao Moreno 已提交
13
import { AutoFetcher } from './autofetch';
J
Joao Moreno 已提交
14
import * as path from 'path';
J
Joao Moreno 已提交
15
import * as nls from 'vscode-nls';
16
import * as fs from 'fs';
M
Matt Bierner 已提交
17
import { StatusBarCommands } from './statusbar';
J
Joao Moreno 已提交
18
import { Branch, Ref, Remote, RefType, GitErrorCodes } from './api/git';
J
Joao Moreno 已提交
19

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

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

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

J
Joao Moreno 已提交
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
export enum Status {
	INDEX_MODIFIED,
	INDEX_ADDED,
	INDEX_DELETED,
	INDEX_RENAMED,
	INDEX_COPIED,

	MODIFIED,
	DELETED,
	UNTRACKED,
	IGNORED,

	ADDED_BY_US,
	ADDED_BY_THEM,
	DELETED_BY_US,
	DELETED_BY_THEM,
	BOTH_ADDED,
	BOTH_DELETED,
	BOTH_MODIFIED
}

J
Joao Moreno 已提交
55 56 57 58 59 60
export enum ResourceGroupType {
	Merge,
	Index,
	WorkingTree
}

J
Joao Moreno 已提交
61
export class Resource implements SourceControlResourceState {
J
Joao Moreno 已提交
62

63
	@memoize
J
Joao Moreno 已提交
64
	get resourceUri(): Uri {
J
Joao Moreno 已提交
65
		if (this.renameResourceUri && (this._type === Status.MODIFIED || this._type === Status.DELETED || this._type === Status.INDEX_RENAMED || this._type === Status.INDEX_COPIED)) {
J
Joao Moreno 已提交
66 67 68 69
			return this.renameResourceUri;
		}

		return this._resourceUri;
70 71 72
	}

	@memoize
J
Joao Moreno 已提交
73 74 75 76 77 78
	get command(): Command {
		return {
			command: 'git.openResource',
			title: localize('open', "Open"),
			arguments: [this]
		};
J
Joao Moreno 已提交
79 80
	}

J
Joao Moreno 已提交
81
	get resourceGroupType(): ResourceGroupType { return this._resourceGroupType; }
J
Joao Moreno 已提交
82
	get type(): Status { return this._type; }
J
Joao Moreno 已提交
83 84
	get original(): Uri { return this._resourceUri; }
	get renameResourceUri(): Uri | undefined { return this._renameResourceUri; }
J
Joao Moreno 已提交
85

86
	private static Icons: any = {
J
Joao Moreno 已提交
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
		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 已提交
109
	private getIconPath(theme: string): Uri {
J
Joao Moreno 已提交
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
		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;
			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;
		}
	}

130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
	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");
			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 已提交
152 153 154 155 156 157
	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 已提交
158
			case Status.INDEX_DELETED:
J
Joao Moreno 已提交
159 160 161 162 163 164
				return true;
			default:
				return false;
		}
	}

165 166
	@memoize
	private get faded(): boolean {
167 168 169 170
		// TODO@joao
		return false;
		// const workspaceRootPath = this.workspaceRoot.fsPath;
		// return this.resourceUri.fsPath.substr(0, workspaceRootPath.length) !== workspaceRootPath;
171 172
	}

J
Joao Moreno 已提交
173
	get decorations(): SourceControlResourceDecorations {
174 175
		const light = this._useIcons ? { iconPath: this.getIconPath('light') } : undefined;
		const dark = this._useIcons ? { iconPath: this.getIconPath('dark') } : undefined;
176
		const tooltip = this.tooltip;
177 178
		const strikeThrough = this.strikeThrough;
		const faded = this.faded;
179 180
		const letter = this.letter;
		const color = this.color;
J
Joao Moreno 已提交
181

182
		return { strikeThrough, faded, tooltip, light, dark, letter, color, source: 'git.resource' /*todo@joh*/ };
183 184
	}

N
Nick Snyder 已提交
185
	get letter(): string {
186
		switch (this.type) {
187 188 189 190 191 192 193 194 195 196
			case Status.INDEX_MODIFIED:
			case Status.MODIFIED:
				return 'M';
			case Status.INDEX_ADDED:
				return 'A';
			case Status.INDEX_DELETED:
			case Status.DELETED:
				return 'D';
			case Status.INDEX_RENAMED:
				return 'R';
197
			case Status.UNTRACKED:
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
				return 'U';
			case Status.IGNORED:
				return 'I';
			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 'C';
		}
	}

N
Nick Snyder 已提交
213
	get color(): ThemeColor {
214
		switch (this.type) {
215 216
			case Status.INDEX_MODIFIED:
			case Status.MODIFIED:
J
Johannes Rieken 已提交
217
				return new ThemeColor('gitDecoration.modifiedResourceForeground');
218 219
			case Status.INDEX_DELETED:
			case Status.DELETED:
J
Johannes Rieken 已提交
220
				return new ThemeColor('gitDecoration.deletedResourceForeground');
221 222
			case Status.INDEX_ADDED:
				return new ThemeColor('gitDecoration.addedResourceForeground');
223 224
			case Status.INDEX_RENAMED: // todo@joh - special color?
			case Status.UNTRACKED:
J
Johannes Rieken 已提交
225
				return new ThemeColor('gitDecoration.untrackedResourceForeground');
226
			case Status.IGNORED:
J
Johannes Rieken 已提交
227
				return new ThemeColor('gitDecoration.ignoredResourceForeground');
228 229 230 231 232 233 234 235
			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 已提交
236
				return new ThemeColor('gitDecoration.conflictingResourceForeground');
237
		}
J
Joao Moreno 已提交
238 239
	}

J
Johannes Rieken 已提交
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
	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 已提交
261
	get resourceDecoration(): DecorationData {
262
		const title = this.tooltip;
263
		const letter = this.letter;
264
		const color = this.color;
J
Johannes Rieken 已提交
265
		const priority = this.priority;
266
		return { bubble: true, source: 'git.resource', title, letter, color, priority };
267 268
	}

269
	constructor(
J
Joao Moreno 已提交
270
		private _resourceGroupType: ResourceGroupType,
271 272
		private _resourceUri: Uri,
		private _type: Status,
273
		private _useIcons: boolean,
274 275
		private _renameResourceUri?: Uri
	) { }
J
Joao Moreno 已提交
276 277
}

278
export enum Operation {
J
Joao Moreno 已提交
279
	Status = 'Status',
J
Joao Moreno 已提交
280
	Config = 'Config',
281
	Diff = 'Diff',
J
Joao Moreno 已提交
282
	MergeBase = 'MergeBase',
J
Joao Moreno 已提交
283 284 285 286 287
	Add = 'Add',
	RevertFiles = 'RevertFiles',
	Commit = 'Commit',
	Clean = 'Clean',
	Branch = 'Branch',
J
Joao Moreno 已提交
288 289 290
	GetBranch = 'GetBranch',
	SetBranchUpstream = 'SetBranchUpstream',
	HashObject = 'HashObject',
J
Joao Moreno 已提交
291 292
	Checkout = 'Checkout',
	Reset = 'Reset',
J
Joao Moreno 已提交
293
	Remote = 'Remote',
J
Joao Moreno 已提交
294 295 296 297 298 299 300 301
	Fetch = 'Fetch',
	Pull = 'Pull',
	Push = 'Push',
	Sync = 'Sync',
	Show = 'Show',
	Stage = 'Stage',
	GetCommitTemplate = 'GetCommitTemplate',
	DeleteBranch = 'DeleteBranch',
302
	RenameBranch = 'RenameBranch',
303
	DeleteRef = 'DeleteRef',
J
Joao Moreno 已提交
304 305 306 307
	Merge = 'Merge',
	Ignore = 'Ignore',
	Tag = 'Tag',
	Stash = 'Stash',
J
Joao Moreno 已提交
308
	CheckIgnore = 'CheckIgnore',
J
Joao Moreno 已提交
309
	GetObjectDetails = 'GetObjectDetails',
310 311
	SubmoduleUpdate = 'SubmoduleUpdate',
	RebaseContinue = 'RebaseContinue',
312 313
}

J
Joao Moreno 已提交
314 315 316 317
function isReadOnly(operation: Operation): boolean {
	switch (operation) {
		case Operation.Show:
		case Operation.GetCommitTemplate:
318
		case Operation.CheckIgnore:
J
Joao Moreno 已提交
319
		case Operation.GetObjectDetails:
J
Joao Moreno 已提交
320 321 322 323 324 325
			return true;
		default:
			return false;
	}
}

326 327 328
function shouldShowProgress(operation: Operation): boolean {
	switch (operation) {
		case Operation.Fetch:
329
		case Operation.CheckIgnore:
J
Joao Moreno 已提交
330
		case Operation.GetObjectDetails:
J
Joao Moreno 已提交
331
		case Operation.Show:
332 333 334 335 336 337
			return false;
		default:
			return true;
	}
}

338
export interface Operations {
339
	isIdle(): boolean;
J
Joao Moreno 已提交
340
	shouldShowProgress(): boolean;
341 342 343 344 345
	isRunning(operation: Operation): boolean;
}

class OperationsImpl implements Operations {

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

J
Joao Moreno 已提交
348 349
	start(operation: Operation): void {
		this.operations.set(operation, (this.operations.get(operation) || 0) + 1);
350 351
	}

J
Joao Moreno 已提交
352 353 354 355 356 357 358 359
	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);
		}
360 361 362
	}

	isRunning(operation: Operation): boolean {
J
Joao Moreno 已提交
363
		return this.operations.has(operation);
364
	}
365 366

	isIdle(): boolean {
J
Joao Moreno 已提交
367 368 369 370 371 372 373 374 375
		const operations = this.operations.keys();

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

		return true;
376
	}
J
Joao Moreno 已提交
377 378 379 380 381 382 383 384 385 386 387 388

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

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

		return false;
	}
389 390
}

J
Joao Moreno 已提交
391 392 393 394
export interface CommitOptions {
	all?: boolean;
	amend?: boolean;
	signoff?: boolean;
395
	signCommit?: boolean;
J
Joao Moreno 已提交
396 397
}

J
Joao Moreno 已提交
398 399 400 401
export interface GitResourceGroup extends SourceControlResourceGroup {
	resourceStates: Resource[];
}

J
Joao Moreno 已提交
402 403 404 405 406
export interface OperationResult {
	operation: Operation;
	error: any;
}

J
Joao Moreno 已提交
407 408 409 410
class ProgressManager {

	private disposable: IDisposable = EmptyDisposable;

J
Joao Moreno 已提交
411
	constructor(repository: Repository) {
J
Joao Moreno 已提交
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
		const start = onceEvent(filterEvent(repository.onDidChangeOperations, () => repository.operations.shouldShowProgress()));
		const end = onceEvent(filterEvent(debounceEvent(repository.onDidChangeOperations, 300), () => !repository.operations.shouldShowProgress()));

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

		setup();
	}

	dispose(): void {
		this.disposable.dispose();
	}
}

J
Joao Moreno 已提交
430
export class Repository implements Disposable {
J
Joao Moreno 已提交
431

432 433
	private static readonly InputValidationLength = 72;

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

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

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

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

446 447 448
	private _onRunOperation = new EventEmitter<Operation>();
	readonly onRunOperation: Event<Operation> = this._onRunOperation.event;

J
Joao Moreno 已提交
449 450
	private _onDidRunOperation = new EventEmitter<OperationResult>();
	readonly onDidRunOperation: Event<OperationResult> = this._onDidRunOperation.event;
451 452 453 454 455 456

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

J
Joao Moreno 已提交
457 458 459
	private _sourceControl: SourceControl;
	get sourceControl(): SourceControl { return this._sourceControl; }

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

J
Joao Moreno 已提交
462 463
	private _mergeGroup: SourceControlResourceGroup;
	get mergeGroup(): GitResourceGroup { return this._mergeGroup as GitResourceGroup; }
J
Joao Moreno 已提交
464

J
Joao Moreno 已提交
465 466
	private _indexGroup: SourceControlResourceGroup;
	get indexGroup(): GitResourceGroup { return this._indexGroup as GitResourceGroup; }
J
Joao Moreno 已提交
467

J
Joao Moreno 已提交
468 469
	private _workingTreeGroup: SourceControlResourceGroup;
	get workingTreeGroup(): GitResourceGroup { return this._workingTreeGroup as GitResourceGroup; }
J
Joao Moreno 已提交
470

J
Joao Moreno 已提交
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
	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;
	}

486 487 488 489 490
	private _submodules: Submodule[] = [];
	get submodules(): Submodule[] {
		return this._submodules;
	}

491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
	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;
	}

507 508 509
	private _operations = new OperationsImpl();
	get operations(): Operations { return this._operations; }

J
Joao 已提交
510 511 512
	private _state = RepositoryState.Idle;
	get state(): RepositoryState { return this._state; }
	set state(state: RepositoryState) {
J
Joao Moreno 已提交
513 514
		this._state = state;
		this._onDidChangeState.fire(state);
J
Joao Moreno 已提交
515 516 517 518

		this._HEAD = undefined;
		this._refs = [];
		this._remotes = [];
J
Joao Moreno 已提交
519 520 521 522
		this.mergeGroup.resourceStates = [];
		this.indexGroup.resourceStates = [];
		this.workingTreeGroup.resourceStates = [];
		this._sourceControl.count = 0;
J
Joao Moreno 已提交
523 524
	}

525 526 527 528
	get root(): string {
		return this.repository.root;
	}

529 530
	private isRepositoryHuge = false;
	private didWarnAboutLimit = false;
J
Joao Moreno 已提交
531
	private disposables: Disposable[] = [];
J
Joao Moreno 已提交
532

533
	constructor(
J
Joao Moreno 已提交
534 535
		private readonly repository: BaseRepository,
		globalState: Memento
536
	) {
J
Joao Moreno 已提交
537 538 539
		const fsWatcher = workspace.createFileSystemWatcher('**');
		this.disposables.push(fsWatcher);

540
		const onWorkspaceChange = anyEvent(fsWatcher.onDidChange, fsWatcher.onDidCreate, fsWatcher.onDidDelete);
J
Joao Moreno 已提交
541
		const onRepositoryChange = filterEvent(onWorkspaceChange, uri => isDescendant(repository.root, uri.fsPath));
J
Joao Moreno 已提交
542
		const onRelevantRepositoryChange = filterEvent(onRepositoryChange, uri => !/\/\.git(\/index\.lock)?$/.test(uri.path));
J
Joao Moreno 已提交
543
		onRelevantRepositoryChange(this.onFSChange, this, this.disposables);
544

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

J
Joao Moreno 已提交
548
		this._sourceControl = scm.createSourceControl('git', 'Git', Uri.file(repository.root));
549
		this._sourceControl.inputBox.placeholder = localize('commitMessage', "Message (press {0} to commit)");
J
Joao Moreno 已提交
550
		this._sourceControl.acceptInputCommand = { command: 'git.commitWithInput', title: localize('commit', "Commit"), arguments: [this._sourceControl] };
J
Joao Moreno 已提交
551
		this._sourceControl.quickDiffProvider = this;
J
Joao Moreno 已提交
552
		this._sourceControl.inputBox.validateInput = this.validateInput.bind(this);
J
Joao Moreno 已提交
553 554 555 556 557 558 559 560 561 562 563 564 565
		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"));

		this.mergeGroup.hideWhenEmpty = true;
		this.indexGroup.hideWhenEmpty = true;

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

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

568 569 570 571 572 573 574 575 576 577
		// 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 已提交
578 579 580 581 582
		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 已提交
583 584 585
		const progressManager = new ProgressManager(this);
		this.disposables.push(progressManager);

J
Joao Moreno 已提交
586
		this.updateCommitTemplate();
J
Joao Moreno 已提交
587
		this.status();
J
Joao Moreno 已提交
588 589
	}

590
	validateInput(text: string, position: number): SourceControlInputBoxValidation | undefined {
591 592 593 594 595 596 597 598 599
		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
				};
			}
		}

600 601 602 603 604 605 606
		const config = workspace.getConfiguration('git');
		const setting = config.get<'always' | 'warn' | 'off'>('inputValidation');

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

J
Joao Moreno 已提交
607
		if (/^\s+$/.test(text)) {
608
			return {
J
Joao Moreno 已提交
609
				message: localize('commitMessageWhitespacesOnlyWarning', "Current commit message only contains whitespace characters"),
610 611 612 613
				type: SourceControlInputBoxValidationType.Warning
			};
		}

614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
		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;
		}

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

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

		if (line.length <= Repository.InputValidationLength) {
			if (setting !== 'always') {
				return;
			}

			return {
				message: localize('commitMessageCountdown', "{0} characters left in current line", Repository.InputValidationLength - line.length),
				type: SourceControlInputBoxValidationType.Information
			};
		} else {
			return {
				message: localize('commitMessageWarning', "{0} characters over {1} in current line", line.length - Repository.InputValidationLength, Repository.InputValidationLength),
				type: SourceControlInputBoxValidationType.Warning
			};
		}
	}

J
Joao Moreno 已提交
643 644 645 646 647
	provideOriginalResource(uri: Uri): Uri | undefined {
		if (uri.scheme !== 'file') {
			return;
		}

648
		return toGitUri(uri, '', { replaceFileExtension: true });
J
Joao Moreno 已提交
649 650 651 652 653 654 655 656 657 658
	}

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

J
Joao Moreno 已提交
659 660 661 662 663 664 665 666 667 668 669 670
	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 已提交
671
	@throttle
J
Joao Moreno 已提交
672 673
	async status(): Promise<void> {
		await this.run(Operation.Status);
J
Joao Moreno 已提交
674
	}
J
Joao Moreno 已提交
675

J
Joao Moreno 已提交
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
	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));
706 707
	}

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

J
Joao Moreno 已提交
712 713
	async stage(resource: Uri, contents: string): Promise<void> {
		const relativePath = path.relative(this.repository.root, resource.fsPath).replace(/\\/g, '/');
J
Joao Moreno 已提交
714
		await this.run(Operation.Stage, () => this.repository.stage(relativePath, contents));
J
Joao Moreno 已提交
715
		this._onDidChangeOriginalResource.fire(resource);
J
Joao Moreno 已提交
716 717
	}

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

J
Joao Moreno 已提交
722
	async commit(message: string, opts: CommitOptions = Object.create(null)): Promise<void> {
723 724 725 726 727
		if (this.rebaseCommit) {
			await this.run(Operation.RebaseContinue, async () => {
				if (opts.all) {
					await this.repository.add([]);
				}
J
Joao Moreno 已提交
728

729 730 731 732 733 734 735 736 737 738 739
				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 已提交
740
	}
J
Joao Moreno 已提交
741

J
Joao Moreno 已提交
742
	async clean(resources: Uri[]): Promise<void> {
743 744 745
		await this.run(Operation.Clean, async () => {
			const toClean: string[] = [];
			const toCheckout: string[] = [];
746
			const submodulesToUpdate: string[] = [];
747 748

			resources.forEach(r => {
749 750 751 752 753 754 755 756 757
				const fsPath = r.fsPath;

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

758
				const raw = r.toString();
J
Joao Moreno 已提交
759
				const scmResource = find(this.workingTreeGroup.resourceStates, sr => sr.resourceUri.toString() === raw);
760 761 762 763 764 765

				if (!scmResource) {
					return;
				}

				switch (scmResource.type) {
766 767
					case Status.UNTRACKED:
					case Status.IGNORED:
768
						toClean.push(fsPath);
769 770 771
						break;

					default:
772
						toCheckout.push(fsPath);
773 774 775
						break;
				}
			});
J
Joao Moreno 已提交
776

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

779 780 781
			if (toClean.length > 0) {
				promises.push(this.repository.clean(toClean));
			}
J
Joao Moreno 已提交
782

783 784 785
			if (toCheckout.length > 0) {
				promises.push(this.repository.checkout('', toCheckout));
			}
J
Joao Moreno 已提交
786

787 788 789 790
			if (submodulesToUpdate.length > 0) {
				promises.push(this.repository.updateSubmodules(submodulesToUpdate));
			}

791 792
			await Promise.all(promises);
		});
J
Joao Moreno 已提交
793
	}
J
Joao Moreno 已提交
794

J
Joao Moreno 已提交
795
	async branch(name: string, checkout: boolean, ref?: string): Promise<void> {
J
Joao Moreno 已提交
796
		await this.run(Operation.Branch, () => this.repository.branch(name, true));
J
Joao Moreno 已提交
797 798
	}

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

803 804 805 806
	async renameBranch(name: string): Promise<void> {
		await this.run(Operation.RenameBranch, () => this.repository.renameBranch(name));
	}

J
Joao Moreno 已提交
807 808 809 810 811 812 813 814
	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 已提交
815 816
	async merge(ref: string): Promise<void> {
		await this.run(Operation.Merge, () => this.repository.merge(ref));
817 818
	}

J
Joao Moreno 已提交
819 820
	async tag(name: string, message?: string): Promise<void> {
		await this.run(Operation.Tag, () => this.repository.tag(name, message));
821 822
	}

J
Joao Moreno 已提交
823
	async checkout(treeish: string): Promise<void> {
J
Joao Moreno 已提交
824
		await this.run(Operation.Checkout, () => this.repository.checkout(treeish, []));
J
Joao Moreno 已提交
825
	}
J
Joao Moreno 已提交
826

J
Joao Moreno 已提交
827 828 829 830 831 832 833 834
	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));
	}

835 836 837 838
	async deleteRef(ref: string): Promise<void> {
		await this.run(Operation.DeleteRef, () => this.repository.deleteRef(ref));
	}

J
Joao Moreno 已提交
839 840 841 842 843 844 845 846
	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 已提交
847
	@throttle
J
Joao Moreno 已提交
848 849 850 851 852
	async fetchDefault(): Promise<void> {
		await this.run(Operation.Fetch, () => this.repository.fetch());
	}

	async fetch(remote?: string, ref?: string): Promise<void> {
K
Keegan Carruthers-Smith 已提交
853
		await this.run(Operation.Fetch, () => this.repository.fetch());
J
Joao Moreno 已提交
854 855
	}

J
Joao Moreno 已提交
856
	@throttle
J
Joao Moreno 已提交
857
	async pullWithRebase(head: Branch | undefined): Promise<void> {
J
Joao Moreno 已提交
858 859
		let remote: string | undefined;
		let branch: string | undefined;
J
Joao Moreno 已提交
860

J
Joao Moreno 已提交
861 862 863
		if (head && head.name && head.upstream) {
			remote = head.upstream.remote;
			branch = `${head.upstream.name}`;
J
Joao Moreno 已提交
864 865 866
		}

		await this.run(Operation.Pull, () => this.repository.pull(true, remote, branch));
J
Joao Moreno 已提交
867 868 869
	}

	@throttle
J
Joao Moreno 已提交
870
	async pull(head?: Branch): Promise<void> {
J
Joao Moreno 已提交
871 872 873
		let remote: string | undefined;
		let branch: string | undefined;

J
Joao Moreno 已提交
874 875 876
		if (head && head.name && head.upstream) {
			remote = head.upstream.remote;
			branch = `${head.upstream.name}`;
J
Joao Moreno 已提交
877 878 879
		}

		await this.run(Operation.Pull, () => this.repository.pull(false, remote, branch));
J
Joao Moreno 已提交
880 881
	}

882
	async pullFrom(rebase?: boolean, remote?: string, branch?: string): Promise<void> {
M
Matt Shirley 已提交
883
		await this.run(Operation.Pull, () => this.repository.pull(rebase, remote, branch));
J
Joao Moreno 已提交
884 885
	}

J
Joao Moreno 已提交
886
	@throttle
J
Joao Moreno 已提交
887
	async push(head: Branch): Promise<void> {
J
Joao Moreno 已提交
888 889 890
		let remote: string | undefined;
		let branch: string | undefined;

J
Joao Moreno 已提交
891 892 893
		if (head && head.name && head.upstream) {
			remote = head.upstream.remote;
			branch = `${head.name}:${head.upstream.name}`;
J
Joao Moreno 已提交
894 895 896 897 898
		}

		await this.run(Operation.Push, () => this.repository.push(remote, branch));
	}

J
Joao Moreno 已提交
899 900
	async pushTo(remote?: string, name?: string, setUpstream: boolean = false): Promise<void> {
		await this.run(Operation.Push, () => this.repository.push(remote, name, setUpstream));
901 902
	}

903 904
	async pushTags(remote?: string): Promise<void> {
		await this.run(Operation.Push, () => this.repository.push(remote, undefined, false, true));
905 906
	}

J
Joao Moreno 已提交
907 908 909 910 911 912 913 914 915 916 917
	@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> {
918
		let remoteName: string | undefined;
J
Joao Moreno 已提交
919 920 921 922
		let pullBranch: string | undefined;
		let pushBranch: string | undefined;

		if (head.name && head.upstream) {
923
			remoteName = head.upstream.remote;
J
Joao Moreno 已提交
924 925 926 927
			pullBranch = `${head.upstream.name}`;
			pushBranch = `${head.name}:${head.upstream.name}`;
		}

928
		await this.run(Operation.Sync, async () => {
929
			await this.repository.pull(rebase, remoteName, pullBranch);
930

931
			const remote = this.remotes.find(r => r.name === remoteName);
J
Joao Moreno 已提交
932 933 934 935 936 937

			if (remote && remote.isReadOnly) {
				return;
			}

			const shouldPush = this.HEAD && (typeof this.HEAD.ahead === 'number' ? this.HEAD.ahead > 0 : true);
938 939

			if (shouldPush) {
940
				await this.repository.push(remoteName, pushBranch);
941 942
			}
		});
J
Joao Moreno 已提交
943 944
	}

945
	async show(ref: string, filePath: string): Promise<string> {
946 947
		return await this.run(Operation.Show, async () => {
			const relativePath = path.relative(this.repository.root, filePath).replace(/\\/g, '/');
J
Joao Moreno 已提交
948
			const configFiles = workspace.getConfiguration('files', Uri.file(filePath));
J
Joao Moreno 已提交
949
			const defaultEncoding = configFiles.get<string>('encoding');
950 951
			const autoGuessEncoding = configFiles.get<boolean>('autoGuessEncoding');

952 953 954 955 956 957 958 959 960 961
			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 已提交
962 963 964 965
		});
	}

	async buffer(ref: string, filePath: string): Promise<Buffer> {
J
Joao Moreno 已提交
966
		return this.run(Operation.Show, () => {
J
Joao Moreno 已提交
967
			const relativePath = path.relative(this.repository.root, filePath).replace(/\\/g, '/');
J
Joao Moreno 已提交
968
			return this.repository.buffer(`${ref}:${relativePath}`);
J
Joao Moreno 已提交
969 970 971
		});
	}

J
Joao Moreno 已提交
972 973
	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 已提交
974 975 976 977 978 979
	}

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

J
Joao Moreno 已提交
980 981 982 983
	async getStashes(): Promise<Stash[]> {
		return await this.repository.getStashes();
	}

984 985
	async createStash(message?: string, includeUntracked?: boolean): Promise<void> {
		return await this.run(Operation.Stash, () => this.repository.createStash(message, includeUntracked));
J
Joao Moreno 已提交
986 987 988 989
	}

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

J
Joao Moreno 已提交
992 993 994 995
	async getCommitTemplate(): Promise<string> {
		return await this.run(Operation.GetCommitTemplate, async () => this.repository.getCommitTemplate());
	}

J
Joao Moreno 已提交
996
	async ignore(files: Uri[]): Promise<void> {
N
NKumar2 已提交
997
		return await this.run(Operation.Ignore, async () => {
J
Joao Moreno 已提交
998 999
			const ignoreFile = `${this.repository.root}${path.sep}.gitignore`;
			const textToAppend = files
J
Joao Moreno 已提交
1000
				.map(uri => path.relative(this.repository.root, uri.fsPath).replace(/\\/g, '/'))
J
Joao Moreno 已提交
1001
				.join('\n');
N
NKumar2 已提交
1002

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

J
Joao Moreno 已提交
1007
			await window.showTextDocument(document);
J
Joao Moreno 已提交
1008

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

J
Joao Moreno 已提交
1013
			edit.insert(document.uri, lastLine.range.end, text);
J
Joao Moreno 已提交
1014
			workspace.applyEdit(edit);
N
NKumar2 已提交
1015 1016 1017
		});
	}

J
Johannes Rieken 已提交
1018
	checkIgnore(filePaths: string[]): Promise<Set<string>> {
1019
		return this.run(Operation.CheckIgnore, () => {
J
Johannes Rieken 已提交
1020 1021
			return new Promise<Set<string>>((resolve, reject) => {

J
Joao Moreno 已提交
1022 1023
				filePaths = filePaths
					.filter(filePath => isDescendant(this.root, filePath));
1024

1025 1026
				if (filePaths.length === 0) {
					// nothing left
C
cleidigh 已提交
1027
					return resolve(new Set<string>());
1028 1029
				}

1030 1031 1032
				// 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 已提交
1033

1034
				const onExit = (exitCode: number) => {
J
Johannes Rieken 已提交
1035 1036 1037 1038
					if (exitCode === 1) {
						// nothing ignored
						resolve(new Set<string>());
					} else if (exitCode === 0) {
1039 1040
						// paths are separated by the null-character
						resolve(new Set<string>(data.split('\0')));
J
Johannes Rieken 已提交
1041
					} else {
J
Joao Moreno 已提交
1042 1043 1044 1045 1046
						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 已提交
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
					}
				};

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

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

1058 1059 1060
				let stderr: string = '';
				child.stderr.setEncoding('utf8');
				child.stderr.on('data', raw => stderr += raw);
J
Johannes Rieken 已提交
1061 1062 1063 1064 1065 1066 1067

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

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

J
Joao Moreno 已提交
1073
		let error: any = null;
J
Joao Moreno 已提交
1074

J
Joao Moreno 已提交
1075 1076
		this._operations.start(operation);
		this._onRunOperation.fire(operation);
J
Joao Moreno 已提交
1077

J
Joao Moreno 已提交
1078 1079
		try {
			const result = await this.retryRun(runOperation);
J
Joao Moreno 已提交
1080

J
Joao Moreno 已提交
1081 1082 1083
			if (!isReadOnly(operation)) {
				await this.updateModelState();
			}
J
Joao Moreno 已提交
1084

J
Joao Moreno 已提交
1085 1086 1087
			return result;
		} catch (err) {
			error = err;
J
Joao Moreno 已提交
1088

J
Joao Moreno 已提交
1089 1090
			if (err.gitErrorCode === GitErrorCodes.NotAGitRepository) {
				this.state = RepositoryState.Disposed;
J
Joao Moreno 已提交
1091
			}
1092

J
Joao Moreno 已提交
1093 1094 1095 1096 1097
			throw err;
		} finally {
			this._operations.end(operation);
			this._onDidRunOperation.fire({ operation, error });
		}
J
Joao Moreno 已提交
1098
	}
1099

1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
	private async retryRun<T>(runOperation: () => Promise<T> = () => Promise.resolve<any>(null)): Promise<T> {
		let attempt = 0;

		while (true) {
			try {
				attempt++;
				return await runOperation();
			} catch (err) {
				if (err.gitErrorCode === GitErrorCodes.RepositoryIsLocked && attempt <= 10) {
					// quatratic backoff
					await timeout(Math.pow(attempt, 2) * 50);
				} else {
					throw err;
				}
			}
		}
	}

J
Joao Moreno 已提交
1118
	@throttle
1119
	private async updateModelState(): Promise<void> {
1120 1121 1122
		const { status, didHitLimit } = await this.repository.getStatus();
		const config = workspace.getConfiguration('git');
		const shouldIgnore = config.get<boolean>('ignoreLimitWarning') === true;
J
Johannes Rieken 已提交
1123
		const useIcons = !config.get<boolean>('decorations.enabled', true);
1124 1125 1126 1127

		this.isRepositoryHuge = didHitLimit;

		if (didHitLimit && !shouldIgnore && !this.didWarnAboutLimit) {
B
Benjamin Pasero 已提交
1128
			const neverAgain = { title: localize('neveragain', "Don't Show Again") };
1129

1130
			window.showWarningMessage(localize('huge', "The git repository at '{0}' has too many active changes, only a subset of Git features will be enabled.", this.repository.root), neverAgain).then(result => {
1131 1132 1133 1134 1135 1136 1137 1138
				if (result === neverAgain) {
					config.update('ignoreLimitWarning', true, false);
				}
			});

			this.didWarnAboutLimit = true;
		}

J
Joao Moreno 已提交
1139
		let HEAD: Branch | undefined;
J
Joao Moreno 已提交
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154

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

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

1155
		const [refs, remotes, submodules, rebaseCommit] = await Promise.all([this.repository.getRefs(), this.repository.getRemotes(), this.repository.getSubmodules(), this.getRebaseCommit()]);
J
Joao Moreno 已提交
1156 1157 1158 1159

		this._HEAD = HEAD;
		this._refs = refs;
		this._remotes = remotes;
1160
		this._submodules = submodules;
1161
		this.rebaseCommit = rebaseCommit;
J
Joao Moreno 已提交
1162 1163 1164 1165 1166 1167

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

		status.forEach(raw => {
J
Joao Moreno 已提交
1168 1169
			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 已提交
1170 1171

			switch (raw.x + raw.y) {
1172 1173 1174 1175 1176 1177 1178 1179 1180
				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 已提交
1181 1182 1183
			}

			switch (raw.x) {
J
Joao Moreno 已提交
1184
				case 'M': index.push(new Resource(ResourceGroupType.Index, uri, Status.INDEX_MODIFIED, useIcons)); break;
1185 1186 1187 1188
				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 已提交
1189 1190 1191
			}

			switch (raw.y) {
1192 1193
				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;
J
Joao Moreno 已提交
1194 1195 1196
			}
		});

J
Joao Moreno 已提交
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212
		// 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');
		let count = merge.length + index.length + workingTree.length;

		switch (countBadge) {
			case 'off': count = 0; break;
			case 'tracked': count = count - workingTree.filter(r => r.type === Status.UNTRACKED || r.type === Status.IGNORED).length; break;
		}

		this._sourceControl.count = count;

J
Joao Moreno 已提交
1213 1214 1215
		// Disable `Discard All Changes` for "fresh" repositories
		// https://github.com/Microsoft/vscode/issues/43066
		commands.executeCommand('setContext', 'gitFreshRepository', !this._HEAD || !this._HEAD.commit);
J
Joao Moreno 已提交
1216

J
Joao Moreno 已提交
1217
		this._onDidChangeStatus.fire();
J
Joao Moreno 已提交
1218 1219
	}

1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
	private async getRebaseCommit(): Promise<Commit | undefined> {
		const rebaseHeadPath = path.join(this.repository.root, '.git', 'REBASE_HEAD');

		try {
			const rebaseHead = await new Promise<string>((c, e) => fs.readFile(rebaseHeadPath, 'utf8', (err, result) => err ? e(err) : c(result)));
			return await this.getCommit(rebaseHead.trim());
		} catch (err) {
			return undefined;
		}
	}

J
Joao Moreno 已提交
1231
	private onFSChange(uri: Uri): void {
J
Joao Moreno 已提交
1232 1233 1234 1235 1236 1237 1238
		const config = workspace.getConfiguration('git');
		const autorefresh = config.get<boolean>('autorefresh');

		if (!autorefresh) {
			return;
		}

1239 1240 1241 1242
		if (this.isRepositoryHuge) {
			return;
		}

J
Joao Moreno 已提交
1243 1244 1245 1246 1247 1248 1249
		if (!this.operations.isIdle()) {
			return;
		}

		this.eventuallyUpdateWhenIdleAndWait();
	}

1250
	@debounce(1000)
J
Joao Moreno 已提交
1251
	private eventuallyUpdateWhenIdleAndWait(): void {
1252 1253 1254
		this.updateWhenIdleAndWait();
	}

J
Joao Moreno 已提交
1255
	@throttle
1256
	private async updateWhenIdleAndWait(): Promise<void> {
J
Joao 已提交
1257
		await this.whenIdleAndFocused();
J
Joao Moreno 已提交
1258
		await this.status();
J
Joao Moreno 已提交
1259
		await timeout(5000);
1260 1261
	}

J
Joao Moreno 已提交
1262
	async whenIdleAndFocused(): Promise<void> {
J
Joao 已提交
1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
		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;
1276 1277 1278
		}
	}

J
Joao 已提交
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
	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 '';
		}

1306 1307 1308
		const remoteName = this.HEAD && this.HEAD.remote || this.HEAD.upstream.remote;
		const remote = this.remotes.find(r => r.name === remoteName);

J
Joao Moreno 已提交
1309
		if (remote && remote.isReadOnly) {
1310 1311 1312
			return `${this.HEAD.behind}↓`;
		}

J
Joao 已提交
1313 1314 1315
		return `${this.HEAD.behind}${this.HEAD.ahead}↑`;
	}

J
Joao Moreno 已提交
1316
	dispose(): void {
J
Joao Moreno 已提交
1317
		this.disposables = dispose(this.disposables);
J
Joao Moreno 已提交
1318
	}
1319
}