gitActions.ts 31.0 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 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 109 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 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 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 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 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 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 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 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
/*---------------------------------------------------------------------------------------------
 *  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 { Promise } from 'vs/base/common/winjs.base';
import nls = require('vs/nls');
import { IEventEmitter } from 'vs/base/common/eventEmitter';
import { ITree } from 'vs/base/parts/tree/common/tree';
import { IDisposable, disposeAll } from 'vs/base/common/lifecycle';
import strings = require('vs/base/common/strings');
import { isString } from 'vs/base/common/types';
import { Action } from 'vs/base/common/actions';
import { IDiffEditor, ICodeEditor } from 'vs/editor/browser/editorBrowser';
import model = require('vs/workbench/parts/git/common/gitModel');
import inputs = require('vs/workbench/parts/git/browser/gitEditorInputs');
import { TextDiffEditorOptions } from 'vs/workbench/common/editor';
import errors = require('vs/base/common/errors');
import platform = require('vs/base/common/platform');
import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IWorkspaceContextService } from 'vs/workbench/services/workspace/common/contextService';
import { IEditor } from 'vs/platform/editor/common/editor';
import { IEventService } from 'vs/platform/event/common/event';
import { IFileService, IFileStat } from 'vs/platform/files/common/files';
import { IMessageService, IConfirmation } from 'vs/platform/message/common/message';
import Severity from 'vs/base/common/severity';
import { IGitService, IFileStatus, Status, StatusType, ServiceState,
	IModel, IBranch, GitErrorCodes, ServiceOperations }
	from 'vs/workbench/parts/git/common/git';

function flatten(context?: any, preferFocus = false): IFileStatus[] {
	if (!context) {
		return context;

	} else if (Array.isArray(context)) {
		if (context.some((c: any) => !(c instanceof model.FileStatus))) {
			throw new Error('Invalid context.');
		}
		return context;

	} else if (context instanceof model.FileStatus) {
		return [<model.FileStatus> context];

	} else if (context instanceof model.StatusGroup) {
		return (<model.StatusGroup> context).all();

	} else if (context.tree) {
		var elements = (<ITree> context.tree).getSelection();
		return elements.indexOf(context.fileStatus) > -1 ? elements : [context.fileStatus];

	} else if (context.selection) {
		return !preferFocus && context.selection.indexOf(context.focus) > -1 ? context.selection : [context.focus];

	} else {
		throw new Error('Invalid context.');
	}
}

export abstract class GitAction extends Action {

	protected gitService: IGitService;
	protected toDispose: IDisposable[];

	constructor(id: string, label: string, cssClass: string, gitService: IGitService) {
		this.gitService = gitService;
		super(id, label, cssClass, false);

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

	protected onGitServiceChange(): void {
		this.updateEnablement();
	}

	protected updateEnablement(): void {
		this.enabled = this.isEnabled();
	}

	protected isEnabled():boolean {
		return !!this.gitService;
	}

	public abstract run(e?: any):Promise;

	public dispose(): void {
		this.gitService = null;
		this.toDispose = disposeAll(this.toDispose);

		super.dispose();
	}
}

export class OpenChangeAction extends GitAction {

	static ID = 'workbench.action.openChange';
	protected editorService: IWorkbenchEditorService;

	constructor(@IWorkbenchEditorService editorService: IWorkbenchEditorService, @IGitService gitService: IGitService) {
		this.editorService = editorService;
		super(OpenChangeAction.ID, nls.localize('openChange', "Open Change"), 'git-action open-change', gitService);
	}

	protected isEnabled():boolean {
		return super.isEnabled() && !!this.editorService;
	}

	public run(context?: any):Promise {
		var statuses = flatten(context, true);

		return this.gitService.getInput(statuses[0]).then((input) => {
			var options = new TextDiffEditorOptions();

			options.forceOpen = true;

			return this.editorService.openEditor(input, options);
		});
	}
}

export class OpenFileAction extends GitAction {

	private static DELETED_STATES = [Status.BOTH_DELETED, Status.DELETED, Status.DELETED_BY_US, Status.INDEX_DELETED];
	static ID = 'workbench.action.openFile';

	private fileService: IFileService;
	private editorService: IWorkbenchEditorService;
	private contextService: IWorkspaceContextService;

	constructor(@IWorkbenchEditorService editorService: IWorkbenchEditorService, @IFileService fileService: IFileService, @IGitService gitService: IGitService, @IWorkspaceContextService contextService: IWorkspaceContextService) {
		this.fileService = fileService;
		this.editorService = editorService;
		this.contextService = contextService;
		super(OpenFileAction.ID, nls.localize('openFile', "Open File"), 'git-action open-file', gitService);
	}

	protected isEnabled():boolean {
		return super.isEnabled() && !!this.editorService || !!this.fileService;
	}

	private getPath(status: IFileStatus): string {
		if (status.getStatus() === Status.INDEX_RENAMED) {
			return status.getRename();
		} else {
			var indexStatus = this.gitService.getModel().getStatus().find(status.getPath(), StatusType.INDEX);

			if (indexStatus && indexStatus.getStatus() === Status.INDEX_RENAMED) {
				return status.getRename();
			} else {
				return status.getPath();
			}
		}
	}

	public run(context?: any):Promise {
		var statuses = flatten(context, true);
		var status = statuses[0];

		if (!(status instanceof model.FileStatus)) {
			return Promise.wrapError(new Error('Can\'t open file.'));
		}

		if (OpenFileAction.DELETED_STATES.indexOf(status.getStatus()) > -1) {
			return Promise.wrapError(new Error('Can\'t open file which is has been deleted.'));
		}

		var path = this.getPath(status);

		return this.fileService.resolveFile(this.contextService.toResource(path)).then((stat: IFileStat) => {
			return this.editorService.openEditor({
				resource: stat.resource,
				mime: stat.mime,
				options: {
					forceOpen: true
				}
			});
		});
	}
}

export class InitAction extends GitAction {

	static ID = 'workbench.action.init';

	constructor(@IGitService gitService: IGitService) {
		super(InitAction.ID, nls.localize('init', "Init"), 'git-action init', gitService);
	}

	protected isEnabled():boolean {
		return super.isEnabled() && this.gitService.getState() === ServiceState.NotARepo;
	}

	public run():Promise {
		return this.gitService.init();
	}
}

export class RefreshAction extends GitAction {

	static ID = 'workbench.action.refresh';

	constructor(@IGitService gitService: IGitService) {
		super(RefreshAction.ID, nls.localize('refresh', "Refresh"), 'git-action refresh', gitService);
	}

	public run():Promise {
		return this.gitService.status();
	}
}

export abstract class BaseStageAction extends GitAction {
	private editorService: IWorkbenchEditorService;

	constructor(id: string, label: string, className: string, gitService: IGitService, editorService: IWorkbenchEditorService) {
		super(id, label, className, gitService);
		this.editorService = editorService;
	}

	public run(context?: any):Promise {
		var flatContext = flatten(context);

		return this.gitService.add(flatten(context)).then((status: IModel) => {
			var targetEditor = this.findGitWorkingTreeEditor();
			if (!targetEditor) {
				return Promise.as(status);
			}

			var currentGitEditorInput = <inputs.IEditorInputWithStatus>(<any>targetEditor.input);
			var currentFileStatus = currentGitEditorInput.getFileStatus();

			if (flatContext && flatContext.every((f) => f !== currentFileStatus)) {
				return Promise.as(status);
			}

			var path = currentGitEditorInput.getFileStatus().getPath();
			var fileStatus = status.getStatus().find(path, StatusType.INDEX);

			if (!fileStatus) {
				return Promise.as(status);
			}

			var editorControl = <any>targetEditor.getControl();
			var viewState = editorControl ? editorControl.saveViewState() : null;

			return this.gitService.getInput(fileStatus).then((input) => {
				var options = new TextDiffEditorOptions();
				options.forceOpen = true;

				return this.editorService.openEditor(input, options, targetEditor.position).then((editor) => {
					if (viewState) {
						editorControl.restoreViewState(viewState);
					}

					return status;
				});
			});
		});
	}

	private findGitWorkingTreeEditor(): IEditor {
		var editors = this.editorService.getVisibleEditors();
		for (var i = 0; i < editors.length; i++) {
			var editor = editors[i];
			if (inputs.isGitEditorInput(editor.input)) {
				return editor;
			}
		}

		return null;
	}

	public dispose(): void {
		this.editorService = null;

		super.dispose();
	}
}

export class StageAction extends BaseStageAction {
	static ID = 'workbench.action.stage';
	static LABEL = nls.localize('stageChanges', "Stage");

	constructor(@IGitService gitService: IGitService, @IWorkbenchEditorService editorService: IWorkbenchEditorService) {
		super(StageAction.ID, StageAction.LABEL, 'git-action stage', gitService, editorService);
	}
}

export class GlobalStageAction extends BaseStageAction {

	static ID = 'workbench.action.stageAll';

	constructor(@IGitService gitService: IGitService, @IWorkbenchEditorService editorService: IWorkbenchEditorService) {
		super(GlobalStageAction.ID, nls.localize('stageAllChanges', "Stage All"), 'git-action stage', gitService, editorService);
	}

	protected isEnabled():boolean {
		return super.isEnabled() && this.gitService.getModel().getStatus().getWorkingTreeStatus().all().length > 0;
	}

	public run(context?: any):Promise {
		return super.run();
	}
}

export abstract class BaseUndoAction extends GitAction {

	private eventService: IEventService;
	private editorService: IWorkbenchEditorService;
	private messageService: IMessageService;
	private fileService: IFileService;
	private contextService: IWorkspaceContextService;

	constructor(id: string, label: string, className: string, gitService: IGitService, eventService: IEventService, messageService: IMessageService, fileService:IFileService, editorService: IWorkbenchEditorService, contextService: IWorkspaceContextService) {
		this.eventService = eventService;
		this.editorService = editorService;
		this.messageService = messageService;
		this.fileService = fileService;
		this.contextService = contextService;
		super(id, label, className, gitService);
	}

	protected isEnabled():boolean {
		return super.isEnabled() && !!this.eventService && !!this.editorService && !!this.fileService;
	}

	public run(context?: any):Promise {
		if (!this.messageService.confirm(this.getConfirm(context))) {
			return Promise.as(null);
		}

		var promises: Promise[] = [];

		if (context instanceof model.StatusGroup) {
			promises = [ this.gitService.undo() ];

		} else {
			var all: IFileStatus[] = flatten(context);
			var toClean: IFileStatus[] = [];
			var toCheckout: IFileStatus[] = [];

			for (var i = 0; i < all.length; i++) {
				var status = all[i].clone();

				switch (status.getStatus()) {
					case Status.UNTRACKED:
					case Status.IGNORED:
						toClean.push(status);
						break;

					default:
						toCheckout.push(status);
						break;
				}
			}

			if (toClean.length > 0) {
				promises.push(this.gitService.clean(toClean));
			}

			if (toCheckout.length > 0) {
				promises.push(this.gitService.checkout('', toCheckout));
			}
		}

		return Promise.join(promises).then((statuses: IModel[]) => {
			if (statuses.length === 0) {
				return Promise.as(null);
			}

			var status = statuses[statuses.length - 1];

			var targetEditor = this.findWorkingTreeDiffEditor();
			if (!targetEditor) {
				return Promise.as(status);
			}

			var currentGitEditorInput = <inputs.GitWorkingTreeDiffEditorInput> targetEditor.input;
			var currentFileStatus = currentGitEditorInput.getFileStatus();

			if (all && all.every((f) => f !== currentFileStatus)) {
				return Promise.as(status);
			}

			var path = currentGitEditorInput.getFileStatus().getPath();

			var editor = <IDiffEditor> targetEditor.getControl();
			var modifiedEditorControl = editor ? <any>editor.getModifiedEditor() : null;
			var modifiedViewState = modifiedEditorControl ? modifiedEditorControl.saveViewState() : null;

			return this.fileService.resolveFile(this.contextService.toResource(path)).then((stat: IFileStat) => {
				return this.editorService.openEditor({
					resource: stat.resource,
					mime: stat.mime,
					options: {
						forceOpen: true
					}
				}, targetEditor.position).then((editor) => {
					if (modifiedViewState) {
						var codeEditor = <ICodeEditor> targetEditor.getControl();

						if (codeEditor) {
							codeEditor.restoreViewState(modifiedViewState);
						}
					}
				});
			});
		}).then(null, (errors: any[]): Promise => {
409
			console.error('One or more errors occurred', errors);
E
Erich Gamma 已提交
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 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 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 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 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 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 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 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821
			return Promise.wrapError(errors[0]);
		});
	}

	private findWorkingTreeDiffEditor(): IEditor {
		var editors = this.editorService.getVisibleEditors();
		for (var i = 0; i < editors.length; i++) {
			var editor = editors[i];
			if (editor.input instanceof inputs.GitWorkingTreeDiffEditorInput) {
				return editor;
			}
		}

		return null;
	}

	private getConfirm(context: any): IConfirmation {
		const all = flatten(context);

		if (all.length > 1) {
			const count = all.length;

			return {
				message: nls.localize('confirmUndoMessage', "Are you sure you want to clean all changes?"),
				detail: count === 1
					? nls.localize('confirmUndoAllOne', "There are unstaged changes in {0} file.\n\nThis action is irreversible!", count)
					: nls.localize('confirmUndoAllMultiple', "There are unstaged changes in {0} files.\n\nThis action is irreversible!", count),
				primaryButton: nls.localize('cleanChangesLabel', "Clean Changes")
			};
		}

		const label = all[0].getPathComponents().reverse()[0];

		return {
			message: nls.localize('confirmUndo', "Are you sure you want to clean changes in '{0}'?", label),
			detail: nls.localize('irreversible', "This action is irreversible!"),
			primaryButton: nls.localize('cleanChangesLabel', "Clean Changes")
		};
	}

	public dispose(): void {
		this.eventService = null;
		this.editorService = null;
		this.fileService = null;

		super.dispose();
	}
}

export class UndoAction extends BaseUndoAction {
	static ID = 'workbench.action.undo';
	constructor( @IGitService gitService: IGitService, @IEventService eventService: IEventService, @IMessageService messageService: IMessageService, @IFileService fileService: IFileService, @IWorkbenchEditorService editorService: IWorkbenchEditorService, @IWorkspaceContextService contextService: IWorkspaceContextService) {
		super(UndoAction.ID, nls.localize('undoChanges', "Clean"), 'git-action undo', gitService, eventService, messageService, fileService, editorService, contextService);
	}
}

export class GlobalUndoAction extends BaseUndoAction {

	static ID = 'workbench.action.undoAll';

	constructor(@IGitService gitService: IGitService, @IEventService eventService: IEventService, @IMessageService messageService: IMessageService, @IFileService fileService: IFileService, @IWorkbenchEditorService editorService: IWorkbenchEditorService, @IWorkspaceContextService contextService: IWorkspaceContextService) {
		super(GlobalUndoAction.ID, nls.localize('undoAllChanges', "Clean All"), 'git-action undo', gitService, eventService, messageService, fileService, editorService, contextService);
	}

	protected isEnabled():boolean {
		return super.isEnabled() && this.gitService.getModel().getStatus().getWorkingTreeStatus().all().length > 0;
	}

	public run(context?: any):Promise {
		return super.run(this.gitService.getModel().getStatus().getWorkingTreeStatus());
	}
}

export abstract class BaseUnstageAction extends GitAction {

	private editorService: IWorkbenchEditorService;

	constructor(id: string, label: string, className: string, gitService: IGitService, editorService: IWorkbenchEditorService) {
		super(id, label, className, gitService);
		this.editorService = editorService;
	}

	protected isEnabled():boolean {
		return super.isEnabled() && !!this.editorService;
	}

	public run(context?: any):Promise {
		var flatContext = flatten(context);

		return this.gitService.revertFiles('HEAD', flatContext).then((status: IModel) => {
			var targetEditor = this.findGitIndexEditor();
			if (!targetEditor) {
				return Promise.as(status);
			}

			var currentGitEditorInput = <inputs.IEditorInputWithStatus>(<any>targetEditor.input);
			var currentFileStatus = currentGitEditorInput.getFileStatus();

			if (flatContext && flatContext.every((f) => f !== currentFileStatus)) {
				return Promise.as(status);
			}

			var path = currentGitEditorInput.getFileStatus().getPath();
			var fileStatus = status.getStatus().find(path, StatusType.WORKING_TREE);

			if (!fileStatus) {
				return Promise.as(status);
			}

			var editorControl = <any> targetEditor.getControl();
			var viewState = editorControl ? editorControl.saveViewState() : null;

			return this.gitService.getInput(fileStatus).then((input) => {
				var options = new TextDiffEditorOptions();
				options.forceOpen = true;

				return this.editorService.openEditor(input, options, targetEditor.position).then((editor) => {
					if (viewState) {
						editorControl.restoreViewState(viewState);
					}

					return status;
				});
			});
		});
	}

	private findGitIndexEditor(): IEditor {
		var editors = this.editorService.getVisibleEditors();
		for (var i = 0; i < editors.length; i++) {
			var editor = editors[i];
			if (inputs.isGitEditorInput(editor.input)) {
				return editor;
			}
		}

		return null;
	}

	public dispose(): void {
		this.editorService = null;

		super.dispose();
	}
}

export class UnstageAction extends BaseUnstageAction {
	static ID = 'workbench.action.unstage';

	constructor(@IGitService gitService: IGitService, @IWorkbenchEditorService editorService: IWorkbenchEditorService) {
		super(UnstageAction.ID, nls.localize('unstage', "Unstage"), 'git-action unstage', gitService, editorService);
	}
}

export class GlobalUnstageAction extends BaseUnstageAction {

	static ID = 'workbench.action.unstageAll';

	constructor(@IGitService gitService: IGitService, @IWorkbenchEditorService editorService: IWorkbenchEditorService) {
		super(GlobalUnstageAction.ID, nls.localize('unstageAllChanges', "Unstage All"), 'git-action unstage', gitService, editorService);
	}

	protected isEnabled():boolean {
		return super.isEnabled() && this.gitService.getModel().getStatus().getIndexStatus().all().length > 0;
	}

	public run(context?: any):Promise {
		return super.run();
	}
}

enum LifecycleState {
	Alive,
	Disposing,
	Disposed
}

export class CheckoutAction extends GitAction {

	static ID = 'workbench.action.checkout';
	private editorService: IWorkbenchEditorService;
	private branch: IBranch;
	private HEAD: IBranch;

	private state: LifecycleState;
	private runPromises: Promise[];

	constructor(branch: IBranch, @IGitService gitService: IGitService, @IWorkbenchEditorService editorService: IWorkbenchEditorService) {
		this.editorService = editorService;
		this.branch = branch;
		this.HEAD = null;
		this.state = LifecycleState.Alive;
		this.runPromises = [];

		super(CheckoutAction.ID, branch.name, 'git-action checkout', gitService);
	}

	protected onGitServiceChange(): void {
		if (this.gitService.getState() === ServiceState.OK) {
			this.HEAD = this.gitService.getModel().getHEAD();

			if (this.HEAD && this.HEAD.name === this.branch.name) {
				this.class = 'git-action checkout HEAD';
			} else {
				this.class = 'git-action checkout';
			}
		}

		super.onGitServiceChange();
	}

	protected isEnabled():boolean {
		return super.isEnabled() && !!this.HEAD;
	}

	public run(context?: any):Promise {
		if (this.state !== LifecycleState.Alive) {
			return Promise.wrapError('action disposed');
		} else if (this.HEAD && this.HEAD.name === this.branch.name) {
			return Promise.as(null);
		}

		var result = this.gitService.checkout(this.branch.name).then(null, (err) => {
			if (err.gitErrorCode === GitErrorCodes.DirtyWorkTree) {
				return Promise.wrapError(new Error(nls.localize('dirtyTreeCheckout', "Can't checkout. Please commit or stage your work first.")));
			}

			return Promise.wrapError(err);
		});

		this.runPromises.push(result);
		result.done(() => this.runPromises.splice(this.runPromises.indexOf(result), 1));

		return result;
	}

	public dispose(): void {
		if (this.state !== LifecycleState.Alive) {
			return;
		}

		this.state = LifecycleState.Disposing;
		Promise.join(this.runPromises).done(() => this.actuallyDispose());
	}

	private actuallyDispose(): void {
		this.editorService = null;
		this.branch = null;
		this.HEAD = null;

		super.dispose();

		this.state = LifecycleState.Disposed;
	}
}

export class BranchAction extends GitAction {

	static ID = 'workbench.action.branch';
	private checkout:boolean;

	constructor(checkout: boolean, @IGitService gitService: IGitService) {
		super(BranchAction.ID, nls.localize('branch', "Branch"), 'git-action checkout', gitService);
		this.checkout = checkout;
	}

	public run(context?: any):Promise {
		if (!isString(context)) {
			return Promise.as(false);
		}

		return this.gitService.branch(<string> context, this.checkout);
	}
}

export interface ICommitState extends IEventEmitter {
	getCommitMessage():string;
	onEmptyCommitMessage():void;
}

export abstract class BaseCommitAction extends GitAction {
	protected commitState: ICommitState;

	constructor(commitState: ICommitState, id: string, label: string, cssClass: string, gitService: IGitService) {
		super(id, label, cssClass, gitService);

		this.commitState = commitState;

		this.toDispose.push(commitState.addListener2('change/commitInputBox', () => {
			this.updateEnablement();
		}));
	}

	protected isEnabled():boolean {
		return super.isEnabled() && this.gitService.getModel().getStatus().getIndexStatus().all().length > 0;
	}

	public run(context?: any):Promise {
		if (!this.commitState.getCommitMessage()) {
			this.commitState.onEmptyCommitMessage();
			return Promise.as(null);
		}

		return this.gitService.commit(this.commitState.getCommitMessage());
	}
}

export class CommitAction extends BaseCommitAction {

	static ID = 'workbench.action.commit';

	constructor(commitState: ICommitState, @IGitService gitService: IGitService) {
		super(commitState, CommitAction.ID, nls.localize('commitStaged', "Commit Staged"), 'git-action commit', gitService);
	}

}

export class StageAndCommitAction extends BaseCommitAction {

	static ID = 'workbench.action.stageAndCommit';

	constructor(commitState: ICommitState, @IGitService gitService: IGitService) {
		super(commitState, StageAndCommitAction.ID, nls.localize('commitAll', "Commit All"), 'git-action stage-and-commit', gitService);
	}

	protected isEnabled():boolean {
		if (!this.gitService) {
			return false;
		}

		if (!this.gitService.isIdle()) {
			return false;
		}

		var status = this.gitService.getModel().getStatus();

		return status.getIndexStatus().all().length > 0
			|| status.getWorkingTreeStatus().all().length > 0;
	}

	public run(context?: any):Promise {
		if (!this.commitState.getCommitMessage()) {
			this.commitState.onEmptyCommitMessage();
			return Promise.as(null);
		}

		return this.gitService.commit(this.commitState.getCommitMessage(), false, true);
	}
}

export class SmartCommitAction extends BaseCommitAction {

	static ID = 'workbench.action.commitAll';
	private static ALL = nls.localize('commitAll2', "Commit All");
	private static STAGED = nls.localize('commitStaged2', "Commit Staged");

	private messageService: IMessageService;

	constructor(commitState: ICommitState, @IGitService gitService: IGitService, @IMessageService messageService: IMessageService) {
		this.messageService = messageService;
		super(commitState, SmartCommitAction.ID, SmartCommitAction.ALL, 'git-action smart-commit', gitService);
	}

	protected onGitServiceChange(): void {
		super.onGitServiceChange();

		if (!this.enabled) {
			this.label = SmartCommitAction.ALL;
			return;
		}

		var status = this.gitService.getModel().getStatus();

		if (status.getIndexStatus().all().length > 0) {
			this.label = SmartCommitAction.STAGED;
		} else {
			this.label = SmartCommitAction.ALL;
		}

		this.label += ' (' + (platform.isMacintosh ? 'Cmd+Enter' : 'Ctrl+Enter') + ')';
	}

	protected isEnabled():boolean {
		if (!this.gitService) {
			return false;
		}

		if (!this.gitService.isIdle()) {
			return false;
		}

		var status = this.gitService.getModel().getStatus();

		return status.getIndexStatus().all().length > 0
			|| status.getWorkingTreeStatus().all().length > 0;
	}

	public run(context?: any):Promise {
		if (!this.commitState.getCommitMessage()) {
			this.commitState.onEmptyCommitMessage();
			return Promise.as(null);
		}

		var status = this.gitService.getModel().getStatus();

		return this.gitService.commit(this.commitState.getCommitMessage(), false, status.getIndexStatus().all().length === 0);
	}
}

export class PullAction extends GitAction {

	static ID = 'workbench.action.pull';
822
	static LABEL = nls.localize('pull', "Pull");
E
Erich Gamma 已提交
823

824 825 826 827 828 829
	constructor(
		id = PullAction.ID,
		label = PullAction.LABEL,
		@IGitService gitService: IGitService
	) {
		super(id, label, 'git-action pull', gitService);
E
Erich Gamma 已提交
830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851
	}

	protected isEnabled():boolean {
		if (!super.isEnabled()) {
			return false;
		}

		if (!this.gitService.isIdle()) {
			return false;
		}

		var model = this.gitService.getModel();
		var HEAD = model.getHEAD();

		if (!HEAD || !HEAD.name || !HEAD.upstream) {
			return false;
		}

		return true;
	}

	public run(context?: any):Promise {
852 853 854 855 856
		return this.pull();
	}

	protected pull(rebase = false): Promise {
		return this.gitService.pull(rebase).then(null, (err) => {
E
Erich Gamma 已提交
857 858 859 860 861 862 863 864 865 866 867
			if (err.gitErrorCode === GitErrorCodes.DirtyWorkTree) {
				return Promise.wrapError(errors.create(nls.localize('dirtyTreePull', "Can't pull. Please commit or stage your work first."), { severity: Severity.Warning }));
			} else if (err.gitErrorCode === GitErrorCodes.AuthenticationFailed) {
				return Promise.wrapError(errors.create(nls.localize('authFailed', "Authentication failed on the git remote.")));
			}

			return Promise.wrapError(err);
		});
	}
}

868 869 870 871 872 873 874 875 876 877 878 879 880 881
export class PullWithRebaseAction extends PullAction {

	static ID = 'workbench.action.pull.rebase';
	static LABEL = nls.localize('pullWithRebase', "Pull (Rebase)");

	constructor(@IGitService gitService: IGitService) {
		super(PullWithRebaseAction.ID, PullWithRebaseAction.LABEL, gitService);
	}

	public run(context?: any):Promise {
		return this.pull(true);
	}
}

E
Erich Gamma 已提交
882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966
export class PushAction extends GitAction {

	static ID = 'workbench.action.push';

	constructor(@IGitService gitService: IGitService) {
		super(PushAction.ID, nls.localize('push', "Push"), 'git-action push', gitService);
	}

	protected isEnabled():boolean {
		if (!super.isEnabled()) {
			return false;
		}

		if (!this.gitService.isIdle()) {
			return false;
		}

		var model = this.gitService.getModel();
		var HEAD = model.getHEAD();

		if (!HEAD || !HEAD.name || !HEAD.upstream) {
			return false;
		}

		if (!HEAD.ahead) { // no commits to pull or push
			return false;
		}

		return true;
	}

	public run(context?: any):Promise {
		return this.gitService.push().then(null, (err) => {
			if (err.gitErrorCode === GitErrorCodes.AuthenticationFailed) {
				return Promise.wrapError(errors.create(nls.localize('authFailed', "Authentication failed on the git remote.")));
			}

			return Promise.wrapError(err);
		});
	}
}

export abstract class BaseSyncAction extends GitAction {

	constructor(id: string, label: string, className: string, gitService: IGitService) {
		super(id, label, className, gitService);
	}

	protected isEnabled():boolean {
		if (!super.isEnabled()) {
			return false;
		}

		if (!this.gitService.isIdle()) {
			return false;
		}

		var model = this.gitService.getModel();
		var HEAD = model.getHEAD();

		if (!HEAD || !HEAD.name || !HEAD.upstream) {
			return false;
		}

		return true;
	}

	public run(context?: any):Promise {
		if (!this.enabled) {
			return Promise.as(null);
		}

		return this.gitService.sync().then(null, (err) => {
			if (err.gitErrorCode === GitErrorCodes.AuthenticationFailed) {
				return Promise.wrapError(errors.create(nls.localize('authFailed', "Authentication failed on the git remote.")));
			}

			return Promise.wrapError(err);
		});
	}
}

export class SyncAction extends BaseSyncAction {

	static ID = 'workbench.action.sync';
967
	static LABEL = nls.localize('sync', "Sync");
E
Erich Gamma 已提交
968

969 970
	constructor(id: string, label: string, @IGitService gitService: IGitService) {
		super(id, label, 'git-action sync', gitService);
E
Erich Gamma 已提交
971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 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 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
	}
}

export class LiveSyncAction extends BaseSyncAction {

	static ID = 'workbench.action.liveSync';
	static CLASS_NAME = 'git-action live-sync';
	static CLASS_NAME_LOADING = 'git-action live-sync loading';

	constructor(@IGitService gitService: IGitService) {
		super(LiveSyncAction.ID, nls.localize('sync', "Sync"), LiveSyncAction.CLASS_NAME, gitService);
	}

	protected onGitServiceChange(): void {
		super.onGitServiceChange();

		if (this.gitService.getRunningOperations().some(op =>
			op.id === ServiceOperations.SYNC ||
			op.id === ServiceOperations.PULL ||
			op.id === ServiceOperations.PUSH))
		{
			this.label = '';
			this.class = LiveSyncAction.CLASS_NAME_LOADING;
			this.tooltip = nls.localize('synchronizing', "Synchronizing...");

		} else {
			this.class = LiveSyncAction.CLASS_NAME;

			var model = this.gitService.getModel();
			var HEAD = model.getHEAD();

			if (!HEAD) {
				this.label = '';
				this.tooltip = '';

			} else if (!HEAD.name) {
				this.label = '';
				this.tooltip = nls.localize('currentlyDetached', "Can't sync in detached mode.");

			} else if (!HEAD.upstream) {
				this.label = '';
				this.tooltip = nls.localize('noUpstream', "Current branch '{0} doesn't have an upstream branch configured.", HEAD.name);

			} else if (!HEAD.ahead && !HEAD.behind) {
				this.label = '';
				this.tooltip = nls.localize('currentBranch', "Current branch '{0}' is up to date.", HEAD.name);

			} else {
				this.label = strings.format('{0}↓ {1}↑', HEAD.behind, HEAD.ahead);

				if (model.getStatus().getGroups().some(g => g.all().length > 0)) {
					this.tooltip = nls.localize('dirtyChanges', "Please commit, undo or stash your changes before synchronizing.");
				} else if (HEAD.behind === 1 && HEAD.ahead === 1) {
					this.tooltip = nls.localize('currentBranchSingle', "Current branch '{0}' is {1} commit behind and {2} commit ahead of '{3}'.", HEAD.name, HEAD.behind, HEAD.ahead, HEAD.upstream);
				} else if (HEAD.behind === 1) {
					this.tooltip = nls.localize('currentBranchSinglePlural', "Current branch '{0}' is {1} commit behind and {2} commits ahead of '{3}'.", HEAD.name, HEAD.behind, HEAD.ahead, HEAD.upstream);
				} else if (HEAD.ahead === 1) {
					this.tooltip = nls.localize('currentBranchPluralSingle', "Current branch '{0}' is {1} commits behind and {2} commit ahead of '{3}'.", HEAD.name, HEAD.behind, HEAD.ahead, HEAD.upstream);
				} else {
					this.tooltip = nls.localize('currentBranchPlural', "Current branch '{0}' is {1} commits behind and {2} commits ahead of '{3}'.", HEAD.name, HEAD.behind, HEAD.ahead, HEAD.upstream);
				}
			}
		}
	}
}

export class UndoLastCommitAction extends GitAction {

	static ID = 'workbench.action.undoLastCommit';

	constructor(@IGitService gitService: IGitService) {
		super(UndoLastCommitAction.ID, nls.localize('undoLastCommit', "Undo Last Commit"), 'git-action undo-last-commit', gitService);
	}

	public run():Promise {
		return this.gitService.reset('HEAD~');
	}
}