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

'use strict';

8
import { Uri, Command, EventEmitter, Event, scm, SourceControl, SourceControlInputBox, SourceControlResourceGroup, SourceControlResourceState, SourceControlResourceDecorations, Disposable, ProgressLocation, window, workspace, WorkspaceEdit, ThemeColor, DecorationData } from 'vscode';
9
import { Repository as BaseRepository, Ref, Branch, Remote, Commit, GitErrorCodes, Stash, RefType, GitError } from './git';
J
Joao Moreno 已提交
10
import { anyEvent, filterEvent, eventToPromise, dispose, find } 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

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

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

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

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

J
Joao Moreno 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
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 已提交
54 55 56 57 58 59
export enum ResourceGroupType {
	Merge,
	Index,
	WorkingTree
}

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

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

		return this._resourceUri;
69 70 71
	}

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

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

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

	private getIconPath(theme: string): Uri | undefined {
		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;
			default: return void 0;
		}
	}

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 176 177
		// TODO@joh, still requires restart/redraw in the SCM viewlet
		const decorations = workspace.getConfiguration().get<boolean>('git.decorations.enabled');
		const light = !decorations ? { iconPath: this.getIconPath('light') } : undefined;
		const dark = !decorations ? { iconPath: this.getIconPath('dark') } : undefined;
178
		const tooltip = this.tooltip;
179 180
		const strikeThrough = this.strikeThrough;
		const faded = this.faded;
181 182
		const letter = this.letter;
		const color = this.color;
J
Joao Moreno 已提交
183

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

187
	get letter(): string | undefined {
188
		switch (this.type) {
189 190 191 192 193 194 195 196 197 198
			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';
199
			case Status.UNTRACKED:
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
				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';
			default:
				return undefined;
		}
	}

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

J
Johannes Rieken 已提交
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
	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;
		}
	}

266 267 268 269
	get resourceDecoration(): DecorationData | undefined {
		const title = this.tooltip;
		const abbreviation = this.letter;
		const color = this.color;
J
Johannes Rieken 已提交
270
		const priority = this.priority;
271
		return { bubble: true, source: 'git.resource', title, abbreviation, color, priority };
272 273
	}

274
	constructor(
J
Joao Moreno 已提交
275
		private _resourceGroupType: ResourceGroupType,
276 277 278 279
		private _resourceUri: Uri,
		private _type: Status,
		private _renameResourceUri?: Uri
	) { }
J
Joao Moreno 已提交
280 281
}

282
export enum Operation {
J
Joao Moreno 已提交
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
	Status = 'Status',
	Add = 'Add',
	RevertFiles = 'RevertFiles',
	Commit = 'Commit',
	Clean = 'Clean',
	Branch = 'Branch',
	Checkout = 'Checkout',
	Reset = 'Reset',
	Fetch = 'Fetch',
	Pull = 'Pull',
	Push = 'Push',
	Sync = 'Sync',
	Show = 'Show',
	Stage = 'Stage',
	GetCommitTemplate = 'GetCommitTemplate',
	DeleteBranch = 'DeleteBranch',
299
	RenameBranch = 'RenameBranch',
J
Joao Moreno 已提交
300 301 302 303
	Merge = 'Merge',
	Ignore = 'Ignore',
	Tag = 'Tag',
	Stash = 'Stash',
J
Joao Moreno 已提交
304 305
	CheckIgnore = 'CheckIgnore',
	LSTree = 'LSTree'
306 307
}

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

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

332
export interface Operations {
333
	isIdle(): boolean;
334 335 336 337 338
	isRunning(operation: Operation): boolean;
}

class OperationsImpl implements Operations {

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

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

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

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

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

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

		return true;
369
	}
370 371
}

J
Joao Moreno 已提交
372 373 374 375
export interface CommitOptions {
	all?: boolean;
	amend?: boolean;
	signoff?: boolean;
376
	signCommit?: boolean;
J
Joao Moreno 已提交
377 378
}

J
Joao Moreno 已提交
379 380 381 382
export interface GitResourceGroup extends SourceControlResourceGroup {
	resourceStates: Resource[];
}

J
Joao Moreno 已提交
383
export class Repository implements Disposable {
J
Joao Moreno 已提交
384

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

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

J
Joao Moreno 已提交
391 392
	private _onDidChangeStatus = new EventEmitter<void>();
	readonly onDidChangeStatus: Event<void> = this._onDidChangeStatus.event;
J
Joao Moreno 已提交
393

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

397 398 399 400 401 402 403 404 405 406 407
	private _onRunOperation = new EventEmitter<Operation>();
	readonly onRunOperation: Event<Operation> = this._onRunOperation.event;

	private _onDidRunOperation = new EventEmitter<Operation>();
	readonly onDidRunOperation: Event<Operation> = this._onDidRunOperation.event;

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

J
Joao Moreno 已提交
408 409 410
	private _sourceControl: SourceControl;
	get sourceControl(): SourceControl { return this._sourceControl; }

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

J
Joao Moreno 已提交
413 414
	private _mergeGroup: SourceControlResourceGroup;
	get mergeGroup(): GitResourceGroup { return this._mergeGroup as GitResourceGroup; }
J
Joao Moreno 已提交
415

J
Joao Moreno 已提交
416 417
	private _indexGroup: SourceControlResourceGroup;
	get indexGroup(): GitResourceGroup { return this._indexGroup as GitResourceGroup; }
J
Joao Moreno 已提交
418

J
Joao Moreno 已提交
419 420
	private _workingTreeGroup: SourceControlResourceGroup;
	get workingTreeGroup(): GitResourceGroup { return this._workingTreeGroup as GitResourceGroup; }
J
Joao Moreno 已提交
421

J
Joao Moreno 已提交
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
	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;
	}

437 438 439
	private _operations = new OperationsImpl();
	get operations(): Operations { return this._operations; }

J
Joao 已提交
440 441 442
	private _state = RepositoryState.Idle;
	get state(): RepositoryState { return this._state; }
	set state(state: RepositoryState) {
J
Joao Moreno 已提交
443 444
		this._state = state;
		this._onDidChangeState.fire(state);
J
Joao Moreno 已提交
445 446 447 448

		this._HEAD = undefined;
		this._refs = [];
		this._remotes = [];
J
Joao Moreno 已提交
449 450 451 452
		this.mergeGroup.resourceStates = [];
		this.indexGroup.resourceStates = [];
		this.workingTreeGroup.resourceStates = [];
		this._sourceControl.count = 0;
J
Joao Moreno 已提交
453 454
	}

455 456 457 458
	get root(): string {
		return this.repository.root;
	}

459 460
	private isRepositoryHuge = false;
	private didWarnAboutLimit = false;
J
Joao Moreno 已提交
461
	private disposables: Disposable[] = [];
J
Joao Moreno 已提交
462

463
	constructor(
464
		private readonly repository: BaseRepository
465
	) {
J
Joao Moreno 已提交
466 467 468
		const fsWatcher = workspace.createFileSystemWatcher('**');
		this.disposables.push(fsWatcher);

469
		const onWorkspaceChange = anyEvent(fsWatcher.onDidChange, fsWatcher.onDidCreate, fsWatcher.onDidDelete);
J
Joao 已提交
470
		const onRepositoryChange = filterEvent(onWorkspaceChange, uri => !/^\.\./.test(path.relative(repository.root, uri.fsPath)));
J
Joao Moreno 已提交
471 472
		const onRelevantRepositoryChange = filterEvent(onRepositoryChange, uri => !/\/\.git\/index\.lock$/.test(uri.path));
		onRelevantRepositoryChange(this.onFSChange, this, this.disposables);
473

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

J
Joao Moreno 已提交
477
		this._sourceControl = scm.createSourceControl('git', 'Git', Uri.file(repository.root));
478
		this._sourceControl.inputBox.placeholder = localize('commitMessage', "Message (press {0} to commit)");
J
Joao Moreno 已提交
479
		this._sourceControl.acceptInputCommand = { command: 'git.commitWithInput', title: localize('commit', "Commit"), arguments: [this._sourceControl] };
J
Joao Moreno 已提交
480 481 482 483 484 485 486 487 488 489 490 491 492 493
		this._sourceControl.quickDiffProvider = this;
		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 已提交
494 495
		this.disposables.push(new AutoFetcher(this));

J
Joao Moreno 已提交
496 497 498 499 500
		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 已提交
501
		this.updateCommitTemplate();
J
Joao Moreno 已提交
502
		this.status();
J
Joao Moreno 已提交
503 504
	}

J
Joao Moreno 已提交
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
	provideOriginalResource(uri: Uri): Uri | undefined {
		if (uri.scheme !== 'file') {
			return;
		}

		return toGitUri(uri, '', true);
	}

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

521 522 523 524 525
	// @throttle
	// async init(): Promise<void> {
	// 	if (this.state !== State.NotAGitRepository) {
	// 		return;
	// 	}
J
Joao Moreno 已提交
526

527 528 529
	// 	await this.git.init(this.workspaceRoot.fsPath);
	// 	await this.status();
	// }
J
Joao Moreno 已提交
530

J
Joao Moreno 已提交
531
	@throttle
J
Joao Moreno 已提交
532 533
	async status(): Promise<void> {
		await this.run(Operation.Status);
J
Joao Moreno 已提交
534
	}
J
Joao Moreno 已提交
535

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

J
Joao Moreno 已提交
540 541
	async stage(resource: Uri, contents: string): Promise<void> {
		const relativePath = path.relative(this.repository.root, resource.fsPath).replace(/\\/g, '/');
J
Joao Moreno 已提交
542
		await this.run(Operation.Stage, () => this.repository.stage(relativePath, contents));
J
Joao Moreno 已提交
543
		this._onDidChangeOriginalResource.fire(resource);
J
Joao Moreno 已提交
544 545
	}

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

J
Joao Moreno 已提交
550
	async commit(message: string, opts: CommitOptions = Object.create(null)): Promise<void> {
551 552 553 554
		await this.run(Operation.Commit, async () => {
			if (opts.all) {
				await this.repository.add([]);
			}
J
Joao Moreno 已提交
555

556 557
			await this.repository.commit(message, opts);
		});
J
Joao Moreno 已提交
558
	}
J
Joao Moreno 已提交
559

J
Joao Moreno 已提交
560
	async clean(resources: Uri[]): Promise<void> {
561 562 563 564 565
		await this.run(Operation.Clean, async () => {
			const toClean: string[] = [];
			const toCheckout: string[] = [];

			resources.forEach(r => {
566
				const raw = r.toString();
J
Joao Moreno 已提交
567
				const scmResource = find(this.workingTreeGroup.resourceStates, sr => sr.resourceUri.toString() === raw);
568 569 570 571 572 573

				if (!scmResource) {
					return;
				}

				switch (scmResource.type) {
574 575
					case Status.UNTRACKED:
					case Status.IGNORED:
576
						toClean.push(r.fsPath);
577 578 579
						break;

					default:
580
						toCheckout.push(r.fsPath);
581 582 583
						break;
				}
			});
J
Joao Moreno 已提交
584

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

587 588 589
			if (toClean.length > 0) {
				promises.push(this.repository.clean(toClean));
			}
J
Joao Moreno 已提交
590

591 592 593
			if (toCheckout.length > 0) {
				promises.push(this.repository.checkout('', toCheckout));
			}
J
Joao Moreno 已提交
594

595 596
			await Promise.all(promises);
		});
J
Joao Moreno 已提交
597
	}
J
Joao Moreno 已提交
598

J
Joao Moreno 已提交
599
	async branch(name: string): Promise<void> {
J
Joao Moreno 已提交
600
		await this.run(Operation.Branch, () => this.repository.branch(name, true));
J
Joao Moreno 已提交
601 602
	}

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

607 608 609 610
	async renameBranch(name: string): Promise<void> {
		await this.run(Operation.RenameBranch, () => this.repository.renameBranch(name));
	}

J
Joao Moreno 已提交
611 612
	async merge(ref: string): Promise<void> {
		await this.run(Operation.Merge, () => this.repository.merge(ref));
613 614
	}

J
Joao Moreno 已提交
615 616
	async tag(name: string, message?: string): Promise<void> {
		await this.run(Operation.Tag, () => this.repository.tag(name, message));
617 618
	}

J
Joao Moreno 已提交
619
	async checkout(treeish: string): Promise<void> {
J
Joao Moreno 已提交
620
		await this.run(Operation.Checkout, () => this.repository.checkout(treeish, []));
J
Joao Moreno 已提交
621
	}
J
Joao Moreno 已提交
622

J
Joao Moreno 已提交
623 624 625 626 627 628 629 630
	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));
	}

J
Joao Moreno 已提交
631
	@throttle
J
Joao Moreno 已提交
632
	async fetch(): Promise<void> {
K
Keegan Carruthers-Smith 已提交
633
		await this.run(Operation.Fetch, () => this.repository.fetch());
J
Joao Moreno 已提交
634 635
	}

J
Joao Moreno 已提交
636
	@throttle
637 638
	async pullWithRebase(): Promise<void> {
		await this.run(Operation.Pull, () => this.repository.pull(true));
J
Joao Moreno 已提交
639 640 641
	}

	@throttle
642 643
	async pull(rebase?: boolean, remote?: string, name?: string): Promise<void> {
		await this.run(Operation.Pull, () => this.repository.pull(rebase, remote, name));
J
Joao Moreno 已提交
644 645 646 647 648
	}

	@throttle
	async push(): Promise<void> {
		await this.run(Operation.Push, () => this.repository.push());
J
Joao Moreno 已提交
649 650
	}

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

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

659 660
	async pushTags(remote?: string): Promise<void> {
		await this.run(Operation.Push, () => this.repository.push(remote, undefined, false, true));
661 662
	}

J
Joao Moreno 已提交
663
	private async _sync(rebase: boolean): Promise<void> {
664
		await this.run(Operation.Sync, async () => {
J
Joao Moreno 已提交
665
			await this.repository.pull(rebase);
666

667
			const shouldPush = this.HEAD && typeof this.HEAD.ahead === 'number' ? this.HEAD.ahead > 0 : true;
668 669 670 671 672

			if (shouldPush) {
				await this.repository.push();
			}
		});
J
Joao Moreno 已提交
673 674
	}

675
	@throttle
J
Joao Moreno 已提交
676 677 678
	sync(): Promise<void> {
		return this._sync(false);
	}
679

J
Joao Moreno 已提交
680 681 682
	@throttle
	async syncRebase(): Promise<void> {
		return this._sync(true);
683 684
	}

685
	async show(ref: string, filePath: string): Promise<string> {
J
Joao Moreno 已提交
686
		return await this.run(Operation.Show, async () => {
687
			const relativePath = path.relative(this.repository.root, filePath).replace(/\\/g, '/');
J
Joao Moreno 已提交
688
			const configFiles = workspace.getConfiguration('files', Uri.file(filePath));
J
Joao Moreno 已提交
689
			const encoding = configFiles.get<string>('encoding');
J
Joao Moreno 已提交
690

J
Joao Moreno 已提交
691
			// TODO@joao: Resource config api
J
Joao Moreno 已提交
692 693 694 695 696 697 698 699
			return await this.repository.bufferString(`${ref}:${relativePath}`, encoding);
		});
	}

	async buffer(ref: string, filePath: string): Promise<Buffer> {
		return await this.run(Operation.Show, async () => {
			const relativePath = path.relative(this.repository.root, filePath).replace(/\\/g, '/');
			const configFiles = workspace.getConfiguration('files', Uri.file(filePath));
J
Joao Moreno 已提交
700
			const encoding = configFiles.get<string>('encoding');
J
Joao Moreno 已提交
701

J
Joao Moreno 已提交
702
			// TODO@joao: REsource config api
J
Joao Moreno 已提交
703
			return await this.repository.buffer(`${ref}:${relativePath}`);
J
Joao Moreno 已提交
704 705 706
		});
	}

J
Joao Moreno 已提交
707
	lstree(ref: string, filePath: string): Promise<{ mode: number, object: string, size: number }> {
J
Joao Moreno 已提交
708 709 710 711 712 713 714
		return this.run(Operation.LSTree, () => this.repository.lstree(ref, filePath));
	}

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

J
Joao Moreno 已提交
715 716 717 718
	async getStashes(): Promise<Stash[]> {
		return await this.repository.getStashes();
	}

719 720
	async createStash(message?: string, includeUntracked?: boolean): Promise<void> {
		return await this.run(Operation.Stash, () => this.repository.createStash(message, includeUntracked));
J
Joao Moreno 已提交
721 722 723 724
	}

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

J
Joao Moreno 已提交
727 728 729 730
	async getCommitTemplate(): Promise<string> {
		return await this.run(Operation.GetCommitTemplate, async () => this.repository.getCommitTemplate());
	}

J
Joao Moreno 已提交
731
	async ignore(files: Uri[]): Promise<void> {
N
NKumar2 已提交
732
		return await this.run(Operation.Ignore, async () => {
J
Joao Moreno 已提交
733 734
			const ignoreFile = `${this.repository.root}${path.sep}.gitignore`;
			const textToAppend = files
J
Joao Moreno 已提交
735
				.map(uri => path.relative(this.repository.root, uri.fsPath).replace(/\\/g, '/'))
J
Joao Moreno 已提交
736
				.join('\n');
N
NKumar2 已提交
737

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

J
Joao Moreno 已提交
742
			await window.showTextDocument(document);
J
Joao Moreno 已提交
743

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

J
Joao Moreno 已提交
748
			edit.insert(document.uri, lastLine.range.end, text);
J
Joao Moreno 已提交
749
			workspace.applyEdit(edit);
N
NKumar2 已提交
750 751 752
		});
	}

J
Johannes Rieken 已提交
753
	checkIgnore(filePaths: string[]): Promise<Set<string>> {
754
		return this.run(Operation.CheckIgnore, () => {
J
Johannes Rieken 已提交
755 756
			return new Promise<Set<string>>((resolve, reject) => {

757 758
				filePaths = filePaths.filter(filePath => !path.relative(this.root, filePath).startsWith('..'));

759 760
				if (filePaths.length === 0) {
					// nothing left
C
cleidigh 已提交
761
					return resolve(new Set<string>());
762 763
				}

764 765 766
				// 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 已提交
767

768
				const onExit = (exitCode: number) => {
J
Johannes Rieken 已提交
769 770 771 772
					if (exitCode === 1) {
						// nothing ignored
						resolve(new Set<string>());
					} else if (exitCode === 0) {
773 774
						// paths are separated by the null-character
						resolve(new Set<string>(data.split('\0')));
J
Johannes Rieken 已提交
775
					} else {
776
						reject(new GitError({ stdout: data, stderr, exitCode }));
J
Johannes Rieken 已提交
777 778 779 780 781 782 783 784 785 786 787
					}
				};

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

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

788 789 790
				let stderr: string = '';
				child.stderr.setEncoding('utf8');
				child.stderr.on('data', raw => stderr += raw);
J
Johannes Rieken 已提交
791 792 793 794 795 796 797

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

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

803
		const run = async () => {
J
Joao Moreno 已提交
804
			this._operations.start(operation);
J
Joao Moreno 已提交
805 806 807
			this._onRunOperation.fire(operation);

			try {
808
				const result = await this.retryRun(runOperation);
J
Joao Moreno 已提交
809 810

				if (!isReadOnly(operation)) {
811
					await this.updateModelState();
J
Joao Moreno 已提交
812 813
				}

J
Joao Moreno 已提交
814
				return result;
J
Joao Moreno 已提交
815 816
			} catch (err) {
				if (err.gitErrorCode === GitErrorCodes.NotAGitRepository) {
J
Joao 已提交
817
					this.state = RepositoryState.Disposed;
J
Joao Moreno 已提交
818
				}
J
Joao Moreno 已提交
819 820

				throw err;
J
Joao Moreno 已提交
821
			} finally {
J
Joao Moreno 已提交
822
				this._operations.end(operation);
J
Joao Moreno 已提交
823 824
				this._onDidRunOperation.fire(operation);
			}
825 826 827
		};

		return shouldShowProgress(operation)
828
			? window.withProgress({ location: ProgressLocation.SourceControl }, run)
829
			: run();
J
Joao Moreno 已提交
830
	}
831

832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849
	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 已提交
850
	@throttle
851
	private async updateModelState(): Promise<void> {
852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870
		const { status, didHitLimit } = await this.repository.getStatus();
		const config = workspace.getConfiguration('git');
		const shouldIgnore = config.get<boolean>('ignoreLimitWarning') === true;

		this.isRepositoryHuge = didHitLimit;

		if (didHitLimit && !shouldIgnore && !this.didWarnAboutLimit) {
			const ok = { title: localize('ok', "OK"), isCloseAffordance: true };
			const neverAgain = { title: localize('neveragain', "Never Show Again") };

			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), ok, neverAgain).then(result => {
				if (result === neverAgain) {
					config.update('ignoreLimitWarning', true, false);
				}
			});

			this.didWarnAboutLimit = true;
		}

J
Joao Moreno 已提交
871
		let HEAD: Branch | undefined;
J
Joao Moreno 已提交
872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897

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

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

		const [refs, remotes] = await Promise.all([this.repository.getRefs(), this.repository.getRemotes()]);

		this._HEAD = HEAD;
		this._refs = refs;
		this._remotes = remotes;

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

		status.forEach(raw => {
J
Joao Moreno 已提交
898 899
			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 已提交
900 901

			switch (raw.x + raw.y) {
902 903 904 905 906 907 908 909 910
				case '??': return workingTree.push(new Resource(ResourceGroupType.WorkingTree, uri, Status.UNTRACKED));
				case '!!': return workingTree.push(new Resource(ResourceGroupType.WorkingTree, uri, Status.IGNORED));
				case 'DD': return merge.push(new Resource(ResourceGroupType.Merge, uri, Status.BOTH_DELETED));
				case 'AU': return merge.push(new Resource(ResourceGroupType.Merge, uri, Status.ADDED_BY_US));
				case 'UD': return merge.push(new Resource(ResourceGroupType.Merge, uri, Status.DELETED_BY_THEM));
				case 'UA': return merge.push(new Resource(ResourceGroupType.Merge, uri, Status.ADDED_BY_THEM));
				case 'DU': return merge.push(new Resource(ResourceGroupType.Merge, uri, Status.DELETED_BY_US));
				case 'AA': return merge.push(new Resource(ResourceGroupType.Merge, uri, Status.BOTH_ADDED));
				case 'UU': return merge.push(new Resource(ResourceGroupType.Merge, uri, Status.BOTH_MODIFIED));
J
Joao Moreno 已提交
911 912 913 914 915
			}

			let isModifiedInIndex = false;

			switch (raw.x) {
916 917 918 919 920
				case 'M': index.push(new Resource(ResourceGroupType.Index, uri, Status.INDEX_MODIFIED)); isModifiedInIndex = true; break;
				case 'A': index.push(new Resource(ResourceGroupType.Index, uri, Status.INDEX_ADDED)); break;
				case 'D': index.push(new Resource(ResourceGroupType.Index, uri, Status.INDEX_DELETED)); break;
				case 'R': index.push(new Resource(ResourceGroupType.Index, uri, Status.INDEX_RENAMED, renameUri)); break;
				case 'C': index.push(new Resource(ResourceGroupType.Index, uri, Status.INDEX_COPIED, renameUri)); break;
J
Joao Moreno 已提交
921 922 923
			}

			switch (raw.y) {
924 925
				case 'M': workingTree.push(new Resource(ResourceGroupType.WorkingTree, uri, Status.MODIFIED, renameUri)); break;
				case 'D': workingTree.push(new Resource(ResourceGroupType.WorkingTree, uri, Status.DELETED, renameUri)); break;
J
Joao Moreno 已提交
926 927 928
			}
		});

J
Joao Moreno 已提交
929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948
		// 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;

		// set context key
		let stateContextKey = '';

		switch (this.state) {
J
Joao 已提交
949 950
			case RepositoryState.Idle: stateContextKey = 'idle'; break;
			case RepositoryState.Disposed: stateContextKey = 'norepo'; break;
J
Joao Moreno 已提交
951 952
		}

J
Joao Moreno 已提交
953
		this._onDidChangeStatus.fire();
J
Joao Moreno 已提交
954 955 956
	}

	private onFSChange(uri: Uri): void {
J
Joao Moreno 已提交
957 958 959 960 961 962 963
		const config = workspace.getConfiguration('git');
		const autorefresh = config.get<boolean>('autorefresh');

		if (!autorefresh) {
			return;
		}

964 965 966 967
		if (this.isRepositoryHuge) {
			return;
		}

J
Joao Moreno 已提交
968 969 970 971 972 973 974
		if (!this.operations.isIdle()) {
			return;
		}

		this.eventuallyUpdateWhenIdleAndWait();
	}

975
	@debounce(1000)
J
Joao Moreno 已提交
976
	private eventuallyUpdateWhenIdleAndWait(): void {
977 978 979
		this.updateWhenIdleAndWait();
	}

J
Joao Moreno 已提交
980
	@throttle
981
	private async updateWhenIdleAndWait(): Promise<void> {
J
Joao 已提交
982
		await this.whenIdleAndFocused();
J
Joao Moreno 已提交
983
		await this.status();
J
Joao Moreno 已提交
984
		await timeout(5000);
985 986
	}

J
Joao Moreno 已提交
987
	async whenIdleAndFocused(): Promise<void> {
J
Joao 已提交
988 989 990 991 992 993 994 995 996 997 998 999 1000
		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;
1001 1002 1003
		}
	}

J
Joao 已提交
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
	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 '';
		}

		return `${this.HEAD.behind}${this.HEAD.ahead}↑`;
	}

J
Joao Moreno 已提交
1034
	dispose(): void {
J
Joao Moreno 已提交
1035
		this.disposables = dispose(this.disposables);
J
Joao Moreno 已提交
1036
	}
1037
}