gitWorkbenchContributions.ts 18.6 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6 7 8 9 10 11
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

'use strict';

import 'vs/css!./media/git.contribution';
import nls = require('vs/nls');
import async = require('vs/base/common/async');
import errors = require('vs/base/common/errors');
J
Joao Moreno 已提交
12
import paths = require('vs/base/common/paths');
E
Erich Gamma 已提交
13 14 15 16 17 18 19 20 21 22
import lifecycle = require('vs/base/common/lifecycle');
import winjs = require('vs/base/common/winjs.base');
import ext = require('vs/workbench/common/contributions');
import git = require('vs/workbench/parts/git/common/git');
import common = require('vs/editor/common/editorCommon');
import widget = require('vs/editor/browser/widget/codeEditorWidget');
import viewlet = require('vs/workbench/browser/viewlet');
import statusbar = require('vs/workbench/browser/parts/statusbar/statusbar');
import platform = require('vs/platform/platform');
import widgets = require('vs/workbench/parts/git/browser/gitWidgets');
23
import wbar = require('vs/workbench/common/actionRegistry');
E
Erich Gamma 已提交
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
import gitoutput = require('vs/workbench/parts/git/browser/gitOutput');
import output = require('vs/workbench/parts/output/common/output');
import {SyncActionDescriptor} from 'vs/platform/actions/common/actions';
import {EditorBrowserRegistry} from 'vs/editor/browser/editorBrowserExtensions';
import confregistry = require('vs/platform/configuration/common/configurationRegistry');
import quickopen = require('vs/workbench/browser/quickopen');
import editorcontrib = require('vs/workbench/parts/git/browser/gitEditorContributions');
import {IActivityService, ProgressBadge, NumberBadge} from 'vs/workbench/services/activity/common/activityService';
import {IEventService} from 'vs/platform/event/common/event';
import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation';
import {IMessageService} from 'vs/platform/message/common/message';
import {IWorkspaceContextService} from 'vs/platform/workspace/common/workspace';
import {IViewletService} from 'vs/workbench/services/viewlet/common/viewletService';
import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService';
import {KeyMod, KeyCode} from 'vs/base/common/keyCodes';
39
import {IModelService} from 'vs/editor/common/services/modelService';
40
import {RawText} from 'vs/editor/common/model/textModel';
41 42
import {IEditorWorkerService} from 'vs/editor/common/services/editorWorkerService';
import URI from 'vs/base/common/uri';
43
import {IEditorGroupService} from 'vs/workbench/services/group/common/groupService';
E
Erich Gamma 已提交
44 45 46 47 48

import IGitService = git.IGitService;

export class StatusUpdater implements ext.IWorkbenchContribution
{
B
Benjamin Pasero 已提交
49
	static ID = 'vs.git.statusUpdater';
E
Erich Gamma 已提交
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103

	private gitService: IGitService;
	private eventService: IEventService;
	private activityService:IActivityService;
	private messageService:IMessageService;
	private progressBadgeDelayer: async.Delayer<void>;
	private toDispose: lifecycle.IDisposable[];

	constructor(
		@IGitService gitService: IGitService,
		@IEventService eventService: IEventService,
		@IActivityService activityService: IActivityService,
		@IMessageService messageService: IMessageService
	) {
		this.gitService = gitService;
		this.eventService = eventService;
		this.activityService = activityService;
		this.messageService = messageService;

		this.progressBadgeDelayer = new async.Delayer<void>(200);

		this.toDispose = [];
		this.toDispose.push(this.gitService.addBulkListener2(e => this.onGitServiceChange()));
	}

	private onGitServiceChange(): void {
		if (this.gitService.getState() !== git.ServiceState.OK) {
			this.progressBadgeDelayer.cancel();
			this.activityService.showActivity('workbench.view.git', null, 'git-viewlet-label');
		} else if (this.gitService.isIdle()) {
			this.showChangesBadge();
		} else {
			this.progressBadgeDelayer.trigger(() => {
				this.activityService.showActivity('workbench.view.git', new ProgressBadge(() => nls.localize('gitProgressBadge', 'Running git status')), 'git-viewlet-label-progress');
			});
		}
	}

	private showChangesBadge(): void {
		var count = this.gitService.getModel().getStatus().getGroups().map((g1: git.IStatusGroup) => {
			return g1.all().length;
		}).reduce((a, b) => a + b, 0);

		var badge = new NumberBadge(count, (num)=>{ return nls.localize('gitPendingChangesBadge', '{0} pending changes', num); });

		this.progressBadgeDelayer.cancel();
		this.activityService.showActivity('workbench.view.git', badge, 'git-viewlet-label');
	}

	public getId(): string {
		return StatusUpdater.ID;
	}

	public dispose(): void {
J
Joao Moreno 已提交
104
		this.toDispose = lifecycle.dispose(this.toDispose);
E
Erich Gamma 已提交
105 106 107 108
	}
}

class DirtyDiffModelDecorator {
109
	static GIT_ORIGINAL_SCHEME = 'git-index';
E
Erich Gamma 已提交
110

B
Benjamin Pasero 已提交
111
	static ID = 'vs.git.editor.dirtyDiffDecorator';
E
Erich Gamma 已提交
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
	static MODIFIED_DECORATION_OPTIONS: common.IModelDecorationOptions = {
		linesDecorationsClassName: 'git-dirty-modified-diff-glyph',
		isWholeLine: true,
		overviewRuler: {
			color: 'rgba(0, 122, 204, 0.6)',
			darkColor: 'rgba(0, 122, 204, 0.6)',
			position: common.OverviewRulerLane.Left
		}
	};
	static ADDED_DECORATION_OPTIONS: common.IModelDecorationOptions = {
		linesDecorationsClassName: 'git-dirty-added-diff-glyph',
		isWholeLine: true,
		overviewRuler: {
			color: 'rgba(0, 122, 204, 0.6)',
			darkColor: 'rgba(0, 122, 204, 0.6)',
			position: common.OverviewRulerLane.Left
		}
	};
	static DELETED_DECORATION_OPTIONS: common.IModelDecorationOptions = {
		linesDecorationsClassName: 'git-dirty-deleted-diff-glyph',
		isWholeLine: true,
		overviewRuler: {
			color: 'rgba(0, 122, 204, 0.6)',
			darkColor: 'rgba(0, 122, 204, 0.6)',
			position: common.OverviewRulerLane.Left
		}
	};

140 141
	private modelService: IModelService;
	private editorWorkerService: IEditorWorkerService;
E
Erich Gamma 已提交
142 143 144 145 146
	private editorService: IWorkbenchEditorService;
	private contextService: IWorkspaceContextService;
	private gitService: IGitService;

	private model: common.IModel;
147
	private _originalContentsURI: URI;
E
Erich Gamma 已提交
148 149 150
	private path: string;
	private decorations: string[];

J
Joao Moreno 已提交
151 152
	private delayer: async.ThrottledDelayer<void>;
	private diffDelayer: async.ThrottledDelayer<void>;
E
Erich Gamma 已提交
153 154 155
	private toDispose: lifecycle.IDisposable[];

	constructor(model: common.IModel, path: string,
156 157
		@IModelService modelService: IModelService,
		@IEditorWorkerService editorWorkerService: IEditorWorkerService,
E
Erich Gamma 已提交
158 159 160 161
		@IWorkbenchEditorService editorService: IWorkbenchEditorService,
		@IWorkspaceContextService contextService: IWorkspaceContextService,
		@IGitService gitService: IGitService
	) {
162 163
		this.modelService = modelService;
		this.editorWorkerService = editorWorkerService;
E
Erich Gamma 已提交
164 165 166 167 168
		this.editorService = editorService;
		this.contextService = contextService;
		this.gitService = gitService;

		this.model = model;
169
		this._originalContentsURI = model.uri.with({ scheme: DirtyDiffModelDecorator.GIT_ORIGINAL_SCHEME });
E
Erich Gamma 已提交
170 171 172
		this.path = path;
		this.decorations = [];

J
Joao Moreno 已提交
173 174
		this.delayer = new async.ThrottledDelayer<void>(500);
		this.diffDelayer = new async.ThrottledDelayer<void>(200);
E
Erich Gamma 已提交
175 176

		this.toDispose = [];
A
Alex Dima 已提交
177
		this.toDispose.push(model.onDidChangeContent(() => this.triggerDiff()));
E
Erich Gamma 已提交
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
		this.toDispose.push(this.gitService.addListener2(git.ServiceEvents.STATE_CHANGED, () => this.onChanges()));
		this.toDispose.push(this.gitService.addListener2(git.ServiceEvents.OPERATION_END, e => {
			if (e.operation.id !== git.ServiceOperations.BACKGROUND_FETCH) {
				this.onChanges();
			}
		}));

		this.onChanges();
	}

	private onChanges(): void {
		if (!this.gitService) {
			return;
		}

		if (this.gitService.getState() !== git.ServiceState.OK) {
			return;
		}

		// go through all interesting models
		this.trigger();
	}

	private trigger(): void {
		this.delayer
			.trigger(() => this.diffOriginalContents())
			.done(null, errors.onUnexpectedError);
	}

J
Joao Moreno 已提交
207
	private diffOriginalContents(): winjs.TPromise<void> {
E
Erich Gamma 已提交
208 209 210 211 212 213
		return this.getOriginalContents()
			.then(contents => {
				if (!this.model || this.model.isDisposed()) {
					return; // disposed
				}

214 215 216 217 218 219
				if (!contents) {
					// untracked file
					this.modelService.destroyModel(this._originalContentsURI);
					return this.triggerDiff();
				}

220
				let originalModel = this.modelService.getModel(this._originalContentsURI);
221
				if (originalModel) {
222
					let contentsRawText = RawText.fromStringWithModelOptions(contents, originalModel);
223 224

					// return early if nothing has changed
225
					if (originalModel.equals(contentsRawText)) {
226 227
						return winjs.TPromise.as(null);
					}
E
Erich Gamma 已提交
228

229 230 231
					// we already have the original contents
					originalModel.setValueFromRawText(contentsRawText);
				} else {
232 233 234
					// this is the first time we load the original contents
					this.modelService.createModel(contents, null, this._originalContentsURI);
				}
E
Erich Gamma 已提交
235

236
				return this.triggerDiff();
E
Erich Gamma 已提交
237 238 239 240 241 242 243 244 245 246 247
			});
	}

	private getOriginalContents(): winjs.TPromise<string> {
		var gitModel = this.gitService.getModel();
		var treeish = gitModel.getStatus().find(this.path, git.StatusType.INDEX) ? '~' : 'HEAD';

		return this.gitService.buffer(this.path, treeish);
	}

	private triggerDiff(): winjs.Promise {
J
Joao Moreno 已提交
248
		if (!this.diffDelayer) {
A
Alex Dima 已提交
249
			return winjs.TPromise.as(null);
J
Joao Moreno 已提交
250 251
		}

E
Erich Gamma 已提交
252 253
		return this.diffDelayer.trigger(() => {
			if (!this.model || this.model.isDisposed()) {
A
Alex Dima 已提交
254
				return winjs.TPromise.as<any>([]); // disposed
E
Erich Gamma 已提交
255 256
			}

257
			return this.editorWorkerService.computeDirtyDiff(this._originalContentsURI, this.model.uri, true);
A
Alex Dima 已提交
258
		}).then((diff:common.IChange[]) => {
E
Erich Gamma 已提交
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
			if (!this.model || this.model.isDisposed()) {
				return; // disposed
			}

			return this.decorations = this.model.deltaDecorations(this.decorations, DirtyDiffModelDecorator.changesToDecorations(diff || []));
		});
	}

	private static changesToDecorations(diff:common.IChange[]): common.IModelDeltaDecoration[] {
		return diff.map((change) => {
			var startLineNumber = change.modifiedStartLineNumber;
			var endLineNumber = change.modifiedEndLineNumber || startLineNumber;

			// Added
			if (change.originalEndLineNumber === 0) {
				return {
					range: {
						startLineNumber: startLineNumber, startColumn: 1,
						endLineNumber: endLineNumber, endColumn: 1
					},
					options: DirtyDiffModelDecorator.ADDED_DECORATION_OPTIONS
				};
			}

			// Removed
			if (change.modifiedEndLineNumber === 0) {
				return {
					range: {
						startLineNumber: startLineNumber, startColumn: 1,
						endLineNumber: startLineNumber, endColumn: 1
					},
					options: DirtyDiffModelDecorator.DELETED_DECORATION_OPTIONS
				};
			}

			// Modified
			return {
				range: {
					startLineNumber: startLineNumber, startColumn: 1,
					endLineNumber: endLineNumber, endColumn: 1
				},
				options: DirtyDiffModelDecorator.MODIFIED_DECORATION_OPTIONS
			};
		});
	}

	public dispose(): void {
306
		this.modelService.destroyModel(this._originalContentsURI);
J
Joao Moreno 已提交
307
		this.toDispose = lifecycle.dispose(this.toDispose);
E
Erich Gamma 已提交
308 309 310 311 312
		if (this.model && !this.model.isDisposed()) {
			this.model.deltaDecorations(this.decorations, []);
		}
		this.model = null;
		this.decorations = null;
J
Joao Moreno 已提交
313 314 315 316 317 318 319 320
		if (this.delayer) {
			this.delayer.cancel();
			this.delayer = null;
		}
		if (this.diffDelayer) {
			this.diffDelayer.cancel();
			this.diffDelayer = null;
		}
E
Erich Gamma 已提交
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
	}
}

export class DirtyDiffDecorator implements ext.IWorkbenchContribution {

	private gitService: IGitService;
	private messageService: IMessageService;
	private editorService: IWorkbenchEditorService;
	private eventService: IEventService;
	private contextService: IWorkspaceContextService;
	private instantiationService: IInstantiationService;
	private models: common.IModel[];
	private decorators: { [modelId:string]: DirtyDiffModelDecorator };
	private toDispose: lifecycle.IDisposable[];

	constructor(
		@IGitService gitService: IGitService,
		@IMessageService messageService: IMessageService,
		@IWorkbenchEditorService editorService: IWorkbenchEditorService,
340
		@IEditorGroupService editorGroupService: IEditorGroupService,
E
Erich Gamma 已提交
341 342 343 344 345 346 347 348 349 350 351 352 353 354
		@IEventService eventService: IEventService,
		@IWorkspaceContextService contextService: IWorkspaceContextService,
		@IInstantiationService instantiationService: IInstantiationService
	) {
		this.gitService = gitService;
		this.messageService = messageService;
		this.editorService = editorService;
		this.eventService = eventService;
		this.contextService = contextService;
		this.instantiationService = instantiationService;

		this.models = [];
		this.decorators = Object.create(null);
		this.toDispose = [];
355
		this.toDispose.push(editorGroupService.onEditorsChanged(() => this.onEditorsChanged()));
J
Joao Moreno 已提交
356
		this.toDispose.push(gitService.addListener2(git.ServiceEvents.DISPOSE, () => this.dispose()));
E
Erich Gamma 已提交
357 358 359 360 361 362
	}

	public getId(): string {
		return 'git.DirtyDiffModelDecorator';
	}

363
	private onEditorsChanged(): void {
E
Erich Gamma 已提交
364 365 366
		// HACK: This is the best current way of figuring out whether to draw these decorations
		// or not. Needs context from the editor, to know whether it is a diff editor, in place editor
		// etc.
J
Joao Moreno 已提交
367 368 369 370 371

		const repositoryRoot = this.gitService.getModel().getRepositoryRoot();

		// If there is no repository root, just wait until that changes
		if (typeof repositoryRoot !== 'string') {
372
			this.gitService.addOneTimeDisposableListener(git.ServiceEvents.STATE_CHANGED, () => this.onEditorsChanged());
J
Joao Moreno 已提交
373 374 375 376 377 378 379

			this.models.forEach(m => this.onModelInvisible(m));
			this.models = [];
			return;
		}

		const models = this.editorService.getVisibleEditors()
E
Erich Gamma 已提交
380 381 382 383 384 385 386 387 388 389 390 391 392 393

			// map to the editor controls
			.map(e => e.getControl())

			// only interested in code editor widgets
			.filter(c => c instanceof widget.CodeEditorWidget)

			// map to models
			.map(e => (<widget.CodeEditorWidget> e).getModel())

			// remove nulls and duplicates
			.filter((m, i, a) => !!m && a.indexOf(m, i + 1) === -1)

			// get the associated resource
394
			.map(m => ({ model: m, resource: m.uri }))
E
Erich Gamma 已提交
395 396 397

			// remove nulls
			.filter(p => !!p.resource &&
J
Joao Moreno 已提交
398 399
				// and invalid resources
				(p.resource.scheme === 'file' && paths.isEqualOrParent(p.resource.fsPath, repositoryRoot))
E
Erich Gamma 已提交
400 401 402
			)

			// get paths
J
Joao Moreno 已提交
403
			.map(p => ({ model: p.model, path: paths.normalize(paths.relative(repositoryRoot, p.resource.fsPath)) }))
E
Erich Gamma 已提交
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426

			// remove nulls and inside .git files
			.filter(p => !!p.path && p.path.indexOf('.git/') === -1);

		var newModels = models.filter(p => this.models.every(m => p.model !== m));
		var oldModels = this.models.filter(m => models.every(p => p.model !== m));

		newModels.forEach(p => this.onModelVisible(p.model, p.path));
		oldModels.forEach(m => this.onModelInvisible(m));

		this.models = models.map(p => p.model);
	}

	private onModelVisible(model: common.IModel, path: string): void {
		this.decorators[model.id] = this.instantiationService.createInstance(DirtyDiffModelDecorator, model, path);
	}

	private onModelInvisible(model: common.IModel): void {
		this.decorators[model.id].dispose();
		delete this.decorators[model.id];
	}

	public dispose(): void {
J
Joao Moreno 已提交
427
		this.toDispose = lifecycle.dispose(this.toDispose);
E
Erich Gamma 已提交
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
		this.models.forEach(m => this.decorators[m.id].dispose());
		this.models = null;
		this.decorators = null;
	}
}

export var VIEWLET_ID = 'workbench.view.git';

class OpenGitViewletAction extends viewlet.ToggleViewletAction {
	public static ID = VIEWLET_ID;
	public static LABEL = nls.localize('toggleGitViewlet', "Show Git");

	constructor(id: string, label: string, @IViewletService viewletService: IViewletService, @IWorkbenchEditorService editorService: IWorkbenchEditorService) {
		super(id, label, VIEWLET_ID, viewletService, editorService);
	}
}

export function registerContributions(): void {

	// Register Statusbar item
	(<statusbar.IStatusbarRegistry>platform.Registry.as(statusbar.Extensions.Statusbar)).registerStatusbarItem(new statusbar.StatusbarItemDescriptor(
		widgets.GitStatusbarItem,
		statusbar.StatusbarAlignment.LEFT,
		100 /* High Priority */
	));

	// Register Output Channel
	var outputChannelRegistry = <output.IOutputChannelRegistry>platform.Registry.as(output.Extensions.OutputChannels);
456
	outputChannelRegistry.registerChannel('Git', nls.localize('git', "Git"));
E
Erich Gamma 已提交
457 458 459 460 461 462 463

	// Register Git Output
	(<ext.IWorkbenchContributionsRegistry>platform.Registry.as(ext.Extensions.Workbench)).registerWorkbenchContribution(
		gitoutput.GitOutput
	);

	// Register Viewlet
I
isidor 已提交
464
	(<viewlet.ViewletRegistry>platform.Registry.as(viewlet.Extensions.Viewlets)).registerViewlet(new viewlet.ViewletDescriptor(
E
Erich Gamma 已提交
465 466 467 468 469 470 471 472 473 474 475 476 477
		'vs/workbench/parts/git/browser/gitViewlet',
		'GitViewlet',
		VIEWLET_ID,
		nls.localize('git', "Git"),
		'git',
		35
	));

	// Register Action to Open Viewlet
	(<wbar.IWorkbenchActionRegistry> platform.Registry.as(wbar.Extensions.WorkbenchActions)).registerWorkbenchAction(
		new SyncActionDescriptor(OpenGitViewletAction, OpenGitViewletAction.ID, OpenGitViewletAction.LABEL, {
			primary: null,
			win: { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_G },
B
Benjamin Pasero 已提交
478 479
			linux: { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_G },
			mac: { primary: KeyMod.WinCtrl | KeyMod.Shift | KeyCode.KEY_G }
E
Erich Gamma 已提交
480
		}),
481
		'View: Show Git',
482
		nls.localize('view', "View")
E
Erich Gamma 已提交
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
	);

	// Register MergeDecorator
	EditorBrowserRegistry.registerEditorContribution(editorcontrib.MergeDecorator);

	// Register StatusUpdater
	(<ext.IWorkbenchContributionsRegistry>platform.Registry.as(ext.Extensions.Workbench)).registerWorkbenchContribution(
		StatusUpdater
	);

	// Register DirtyDiffDecorator
	(<ext.IWorkbenchContributionsRegistry>platform.Registry.as(ext.Extensions.Workbench)).registerWorkbenchContribution(
		DirtyDiffDecorator
	);

	// Register Quick Open for git
	(<quickopen.IQuickOpenRegistry>platform.Registry.as(quickopen.Extensions.Quickopen)).registerQuickOpenHandler(
		new quickopen.QuickOpenHandlerDescriptor(
			'vs/workbench/parts/git/browser/gitQuickOpen',
J
Joao Moreno 已提交
502
			'GitCommandQuickOpenHandler',
E
Erich Gamma 已提交
503 504 505 506 507 508 509 510 511
			'git ',
			nls.localize('gitCommands', "Git Commands")
		)
	);

	// Register configuration
	var configurationRegistry = <confregistry.IConfigurationRegistry>platform.Registry.as(confregistry.Extensions.Configuration);
	configurationRegistry.registerConfiguration({
		id: 'git',
512
		order: 15,
513
		title: nls.localize('gitConfigurationTitle', "Git"),
E
Erich Gamma 已提交
514 515
		type: 'object',
		properties: {
J
Joao Moreno 已提交
516
			'git.enabled': {
E
Erich Gamma 已提交
517 518 519 520
				type: 'boolean',
				description: nls.localize('gitEnabled', "Is git enabled"),
				default: true
			},
J
Joao Moreno 已提交
521
			'git.path': {
522
				type: ['string', 'null'],
E
Erich Gamma 已提交
523 524 525
				description: nls.localize('gitPath', "Path to the git executable"),
				default: null
			},
J
Joao Moreno 已提交
526
			'git.autofetch': {
E
Erich Gamma 已提交
527 528 529
				type: 'boolean',
				description: nls.localize('gitAutoFetch', "Whether auto fetching is enabled."),
				default: true
530 531 532 533 534
			},
			'git.enableLongCommitWarning': {
				type: 'boolean',
				description: nls.localize('gitLongCommit', "Whether long commit messages should be warned about."),
				default: true
535 536 537 538 539
			},
			'git.allowLargeRepositories': {
				type: 'boolean',
				description: nls.localize('gitLargeRepos', "Always allow large repositories to be managed by Code."),
				default: false
E
Erich Gamma 已提交
540 541 542 543
			}
		}
	});
}