gitWorkbenchContributions.ts 18.9 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
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');
17
import workbenchEvents = require('vs/workbench/common/events');
E
Erich Gamma 已提交
18 19 20 21 22 23
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');
24
import wbar = require('vs/workbench/common/actionRegistry');
E
Erich Gamma 已提交
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
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';
40 41 42 43
import {IModelService} from 'vs/editor/common/services/modelService';
import {TextModel} from 'vs/editor/common/model/textModel';
import {IEditorWorkerService} from 'vs/editor/common/services/editorWorkerService';
import URI from 'vs/base/common/uri';
E
Erich Gamma 已提交
44 45 46 47 48 49 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 104 105 106 107 108

import IGitService = git.IGitService;

export class StatusUpdater implements ext.IWorkbenchContribution
{
	static ID = 'Monaco.IDE.UI.Viewlets.GitViewlet.Workbench.StatusUpdater';

	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 {
		this.toDispose = lifecycle.disposeAll(this.toDispose);
	}
}

class DirtyDiffModelDecorator {
109
	static GIT_ORIGINAL_SCHEME = 'git-index';
E
Erich Gamma 已提交
110 111 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 ID = 'Monaco.IDE.UI.Viewlets.GitViewlet.Editor.DirtyDiffDecorator';
	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.getAssociatedResource().withScheme(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 177 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 = [];
		this.toDispose.push(model.addListener2(common.EventType.ModelContentChanged, () => this.triggerDiff()));
		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);
	}

207 208 209 210 211 212 213 214 215 216 217 218
	private static _stringArrEquals(a:string[], b:string[]): boolean {
		if (a.length !== b.length) {
			return false;
		}
		for (let i = 0, len = a.length; i < len; i++) {
			if (a[i] !== b[i]) {
				return false;
			}
		}
		return true;
	}

219 220
	private static _equals(a:common.IRawText, b:common.IRawText): boolean {
		return this._stringArrEquals(a.lines, b.lines);
221 222
	}

J
Joao Moreno 已提交
223
	private diffOriginalContents(): winjs.TPromise<void> {
E
Erich Gamma 已提交
224 225 226 227 228 229
		return this.getOriginalContents()
			.then(contents => {
				if (!this.model || this.model.isDisposed()) {
					return; // disposed
				}

230 231 232 233 234 235
				if (!contents) {
					// untracked file
					this.modelService.destroyModel(this._originalContentsURI);
					return this.triggerDiff();
				}

236
				let originalModel = this.modelService.getModel(this._originalContentsURI);
237 238
				if (originalModel) {
					let originalRawText = originalModel.toRawText();
239 240 241
					let contentsRawText = TextModel.toRawText(contents, {
						tabSize: originalRawText.options.tabSize,
						insertSpaces: originalRawText.options.insertSpaces,
242
						detectIndentation: false,
243 244
						defaultEOL: originalRawText.options.defaultEOL
					});
245 246 247 248 249

					// return early if nothing has changed
					if (DirtyDiffModelDecorator._equals(originalRawText, contentsRawText)) {
						return winjs.TPromise.as(null);
					}
E
Erich Gamma 已提交
250 251
				}

252 253 254 255 256 257 258
				if (!originalModel) {
					// this is the first time we load the original contents
					this.modelService.createModel(contents, null, this._originalContentsURI);
				} else {
					// we already have the original contents
					originalModel.setValue(contents);
				}
E
Erich Gamma 已提交
259

260
				return this.triggerDiff();
E
Erich Gamma 已提交
261 262 263 264 265 266 267 268 269 270 271
			});
	}

	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 已提交
272
		if (!this.diffDelayer) {
A
Alex Dima 已提交
273
			return winjs.TPromise.as(null);
J
Joao Moreno 已提交
274 275
		}

E
Erich Gamma 已提交
276 277
		return this.diffDelayer.trigger(() => {
			if (!this.model || this.model.isDisposed()) {
A
Alex Dima 已提交
278
				return winjs.TPromise.as<any>([]); // disposed
E
Erich Gamma 已提交
279 280
			}

281
			return this.editorWorkerService.computeDirtyDiff(this._originalContentsURI, this.model.getAssociatedResource(), true);
A
Alex Dima 已提交
282
		}).then((diff:common.IChange[]) => {
E
Erich Gamma 已提交
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
			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 {
330
		this.modelService.destroyModel(this._originalContentsURI);
E
Erich Gamma 已提交
331 332 333 334 335 336
		this.toDispose = lifecycle.disposeAll(this.toDispose);
		if (this.model && !this.model.isDisposed()) {
			this.model.deltaDecorations(this.decorations, []);
		}
		this.model = null;
		this.decorations = null;
J
Joao Moreno 已提交
337 338 339 340 341 342 343 344
		if (this.delayer) {
			this.delayer.cancel();
			this.delayer = null;
		}
		if (this.diffDelayer) {
			this.diffDelayer.cancel();
			this.diffDelayer = null;
		}
E
Erich Gamma 已提交
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
	}
}

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,
		@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 = [];
		this.toDispose.push(eventService.addListener2(workbenchEvents.EventType.EDITOR_INPUT_CHANGED, () => this.onEditorInputChange()));
J
Joao Moreno 已提交
379
		this.toDispose.push(gitService.addListener2(git.ServiceEvents.DISPOSE, () => this.dispose()));
E
Erich Gamma 已提交
380 381 382 383 384 385 386 387 388 389
	}

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

	private onEditorInputChange(): void {
		// 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 已提交
390 391 392 393 394 395 396 397 398 399 400 401 402

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

		// If there is no repository root, just wait until that changes
		if (typeof repositoryRoot !== 'string') {
			this.gitService.addOneTimeListener(git.ServiceEvents.STATE_CHANGED, () => this.onEditorInputChange());

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

		const models = this.editorService.getVisibleEditors()
E
Erich Gamma 已提交
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420

			// 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
			.map(m => ({ model: m, resource: m.getAssociatedResource() }))

			// remove nulls
			.filter(p => !!p.resource &&
J
Joao Moreno 已提交
421 422
				// and invalid resources
				(p.resource.scheme === 'file' && paths.isEqualOrParent(p.resource.fsPath, repositoryRoot))
E
Erich Gamma 已提交
423 424 425
			)

			// get paths
J
Joao Moreno 已提交
426
			.map(p => ({ model: p.model, path: paths.normalize(paths.relative(repositoryRoot, p.resource.fsPath)) }))
E
Erich Gamma 已提交
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449

			// 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 已提交
450
		this.toDispose = lifecycle.disposeAll(this.toDispose);
E
Erich Gamma 已提交
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
		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);
	outputChannelRegistry.registerChannel('Git');

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

	// Register Viewlet
I
isidor 已提交
487
	(<viewlet.ViewletRegistry>platform.Registry.as(viewlet.Extensions.Viewlets)).registerViewlet(new viewlet.ViewletDescriptor(
E
Erich Gamma 已提交
488 489 490 491 492 493 494 495 496 497 498 499 500
		'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 已提交
501 502
			linux: { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_G },
			mac: { primary: KeyMod.WinCtrl | KeyMod.Shift | KeyCode.KEY_G }
E
Erich Gamma 已提交
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
		}),
		nls.localize('view', "View")
	);

	// 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',
			'CommandQuickOpenHandler',
			'git ',
			nls.localize('gitCommands', "Git Commands")
		)
	);

	// Register configuration
	var configurationRegistry = <confregistry.IConfigurationRegistry>platform.Registry.as(confregistry.Extensions.Configuration);
	configurationRegistry.registerConfiguration({
		id: 'git',
		order: 10,
		title: nls.localize('gitConfigurationTitle', "Git configuration"),
		type: 'object',
		properties: {
J
Joao Moreno 已提交
538
			'git.enabled': {
E
Erich Gamma 已提交
539 540 541 542
				type: 'boolean',
				description: nls.localize('gitEnabled', "Is git enabled"),
				default: true
			},
J
Joao Moreno 已提交
543
			'git.path': {
544
				type: ['string', 'null'],
E
Erich Gamma 已提交
545 546 547
				description: nls.localize('gitPath', "Path to the git executable"),
				default: null
			},
J
Joao Moreno 已提交
548
			'git.autofetch': {
E
Erich Gamma 已提交
549 550 551 552 553 554 555
				type: 'boolean',
				description: nls.localize('gitAutoFetch', "Whether auto fetching is enabled."),
				default: true
			}
		}
	});
}