task.contribution.ts 62.3 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6 7 8
/*---------------------------------------------------------------------------------------------
 *  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/task.contribution';
import 'vs/workbench/parts/tasks/browser/taskQuickOpen';
9
import 'vs/workbench/parts/tasks/browser/terminateQuickOpen';
10
import 'vs/workbench/parts/tasks/browser/restartQuickOpen';
11 12
import 'vs/workbench/parts/tasks/browser/buildQuickOpen';
import 'vs/workbench/parts/tasks/browser/testQuickOpen';
E
Erich Gamma 已提交
13 14 15

import * as nls from 'vs/nls';

16
import { TPromise } from 'vs/base/common/winjs.base';
E
Erich Gamma 已提交
17 18 19 20 21
import Severity from 'vs/base/common/severity';
import * as Objects from 'vs/base/common/objects';
import { IStringDictionary } from 'vs/base/common/collections';
import { Action } from 'vs/base/common/actions';
import * as Dom from 'vs/base/browser/dom';
J
Joao Moreno 已提交
22
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
A
Alex Dima 已提交
23
import { EventEmitter } from 'vs/base/common/eventEmitter';
E
Erich Gamma 已提交
24 25 26
import * as Builder from 'vs/base/browser/builder';
import * as Types from 'vs/base/common/types';
import { KeyMod, KeyCode } from 'vs/base/common/keyCodes';
27
import { TerminateResponseCode } from 'vs/base/common/processes';
28
import * as strings from 'vs/base/common/strings';
29
import { ValidationStatus, ValidationState } from 'vs/base/common/parsers';
30
import * as UUID from 'vs/base/common/uuid';
D
Dirk Baeumer 已提交
31
import { LinkedMap, Touch } from 'vs/base/common/map';
E
Erich Gamma 已提交
32

33
import { Registry } from 'vs/platform/registry/common/platform';
E
Erich Gamma 已提交
34
import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle';
35
import { SyncActionDescriptor, MenuRegistry } from 'vs/platform/actions/common/actions';
E
Erich Gamma 已提交
36
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
37
import { IEditor } from 'vs/platform/editor/common/editor';
E
Erich Gamma 已提交
38 39 40
import { IMessageService } from 'vs/platform/message/common/message';
import { IMarkerService, MarkerStatistics } from 'vs/platform/markers/common/markers';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
41
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
42
import { IFileService } from 'vs/platform/files/common/files';
A
Alex Dima 已提交
43
import { IExtensionService } from 'vs/platform/extensions/common/extensions';
44
import { CommandsRegistry } from 'vs/platform/commands/common/commands';
45 46
import { KeybindingsRegistry } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
47
import { ProblemMatcherRegistry } from 'vs/platform/markers/common/problemMatcher';
48
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
49
import { IProgressService2, IProgressOptions, ProgressLocation } from 'vs/platform/progress/common/progress';
E
Erich Gamma 已提交
50 51 52 53

import { IModeService } from 'vs/editor/common/services/modeService';
import { IModelService } from 'vs/editor/common/services/modelService';

54

M
Martin Aeschlimann 已提交
55
import jsonContributionRegistry = require('vs/platform/jsonschemas/common/jsonContributionRegistry');
E
Erich Gamma 已提交
56 57
import { IJSONSchema } from 'vs/base/common/jsonSchema';

58
import { IWorkbenchActionRegistry, Extensions as WorkbenchActionExtensions } from 'vs/workbench/common/actionRegistry';
J
Johannes Rieken 已提交
59
import { IStatusbarItem, IStatusbarRegistry, Extensions as StatusbarExtensions, StatusbarItemDescriptor, StatusbarAlignment } from 'vs/workbench/browser/parts/statusbar/statusbar';
60
import { IQuickOpenRegistry, Extensions as QuickOpenExtensions, QuickOpenHandlerDescriptor } from 'vs/workbench/browser/quickopen';
E
Erich Gamma 已提交
61

J
Johannes Rieken 已提交
62
import { IQuickOpenService } from 'vs/platform/quickOpen/common/quickOpen';
63
import { IPanelService } from 'vs/workbench/services/panel/common/panelService';
64 65
import Constants from 'vs/workbench/parts/markers/common/constants';
import { IPartService } from 'vs/workbench/services/part/common/partService';
E
Erich Gamma 已提交
66
import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService';
67
import { IConfigurationResolverService } from 'vs/workbench/services/configurationResolver/common/configurationResolver';
68
import { IConfigurationEditingService, ConfigurationTarget, IConfigurationValue } from 'vs/workbench/services/configuration/common/configurationEditing';
69
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
E
Erich Gamma 已提交
70

71
import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
72
import { IOutputService, IOutputChannelRegistry, Extensions as OutputExt, IOutputChannel } from 'vs/workbench/parts/output/common/output';
73
import { Scope, IActionBarRegistry, Extensions as ActionBarExtensions } from 'vs/workbench/browser/actions';
E
Erich Gamma 已提交
74

75 76
import { ITerminalService } from 'vs/workbench/parts/terminal/common/terminal';

77
import { ITaskSystem, ITaskResolver, ITaskSummary, ITaskExecuteResult, TaskExecuteKind, TaskError, TaskErrors, TaskSystemEvents, TaskTerminateResponse } from 'vs/workbench/parts/tasks/common/taskSystem';
78
import { Task, CustomTask, ConfiguringTask, ContributedTask, TaskSet, TaskGroup, ExecutionEngine, JsonSchemaVersion, TaskSourceKind, TaskIdentifier } from 'vs/workbench/parts/tasks/common/tasks';
79
import { ITaskService, TaskServiceEvents, ITaskProvider, TaskEvent } from 'vs/workbench/parts/tasks/common/taskService';
D
Dirk Baeumer 已提交
80
import { templates as taskTemplates } from 'vs/workbench/parts/tasks/common/taskTemplates';
E
Erich Gamma 已提交
81

82
import * as TaskConfig from '../node/taskConfiguration';
83
import { ProcessTaskSystem } from 'vs/workbench/parts/tasks/node/processTaskSystem';
84
import { TerminalTaskSystem } from './terminalTaskSystem';
J
Johannes Rieken 已提交
85
import { ProcessRunnerDetector } from 'vs/workbench/parts/tasks/node/processRunnerDetector';
D
Dirk Baeumer 已提交
86
import { QuickOpenActionContributor } from '../browser/quickOpen';
87

J
Johannes Rieken 已提交
88
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
E
Erich Gamma 已提交
89

90
import { Themable, STATUS_BAR_FOREGROUND, STATUS_BAR_NO_FOLDER_FOREGROUND } from 'vs/workbench/common/theme';
91 92
import { IThemeService } from 'vs/platform/theme/common/themeService';

E
Erich Gamma 已提交
93
let $ = Builder.$;
94
let tasksCategory = nls.localize('tasksCategory', "Tasks");
E
Erich Gamma 已提交
95

96
abstract class OpenTaskConfigurationAction extends Action {
E
Erich Gamma 已提交
97

98 99 100 101 102 103 104 105 106
	constructor(id: string, label: string,
		private taskService: ITaskService,
		private configurationService: IConfigurationService,
		private editorService: IWorkbenchEditorService, private fileService: IFileService,
		private contextService: IWorkspaceContextService, private outputService: IOutputService,
		private messageService: IMessageService, private quickOpenService: IQuickOpenService,
		private environmentService: IEnvironmentService,
		private configurationResolverService: IConfigurationResolverService,
		private extensionService: IExtensionService) {
E
Erich Gamma 已提交
107 108 109 110

		super(id, label);
	}

J
Johannes Rieken 已提交
111
	public run(event?: any): TPromise<IEditor> {
B
Benjamin Pasero 已提交
112
		if (!this.contextService.hasWorkspace()) {
113 114 115
			this.messageService.show(Severity.Info, nls.localize('ConfigureTaskRunnerAction.noWorkspace', 'Tasks are only available on a workspace folder.'));
			return TPromise.as(undefined);
		}
E
Erich Gamma 已提交
116
		let sideBySide = !!(event && (event.ctrlKey || event.metaKey));
117
		let configFileCreated = false;
E
Erich Gamma 已提交
118 119
		return this.fileService.resolveFile(this.contextService.toResource('.vscode/tasks.json')).then((success) => {
			return success;
J
Johannes Rieken 已提交
120
		}, (err: any) => {
121
			;
J
Johannes Rieken 已提交
122
			return this.quickOpenService.pick(taskTemplates, { placeHolder: nls.localize('ConfigureTaskRunnerAction.quickPick.template', 'Select a Task Runner') }).then(selection => {
D
Dirk Baeumer 已提交
123 124
				if (!selection) {
					return undefined;
E
Erich Gamma 已提交
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
				let contentPromise: TPromise<string>;
				if (selection.autoDetect) {
					const outputChannel = this.outputService.getChannel(TaskService.OutputChannelId);
					outputChannel.show(true);
					outputChannel.append(nls.localize('ConfigureTaskRunnerAction.autoDetecting', 'Auto detecting tasks for {0}', selection.id) + '\n');
					let detector = new ProcessRunnerDetector(this.fileService, this.contextService, this.configurationResolverService);
					contentPromise = detector.detect(false, selection.id).then((value) => {
						let config = value.config;
						if (value.stderr && value.stderr.length > 0) {
							value.stderr.forEach((line) => {
								outputChannel.append(line + '\n');
							});
							if (config && (!config.tasks || config.tasks.length === 0)) {
								this.messageService.show(Severity.Warning, nls.localize('ConfigureTaskRunnerAction.autoDetect', 'Auto detecting the task system failed. Using default template. Consult the task output for details.'));
								return selection.content;
							} else {
								this.messageService.show(Severity.Warning, nls.localize('ConfigureTaskRunnerAction.autoDetectError', 'Auto detecting the task system produced errors. Consult the task output for details.'));
							}
						}
						if (config) {
							if (value.stdout && value.stdout.length > 0) {
								value.stdout.forEach(line => outputChannel.append(line + '\n'));
							}
							let content = JSON.stringify(config, null, '\t');
							content = [
								'{',
								'\t// See https://go.microsoft.com/fwlink/?LinkId=733558',
								'\t// for the documentation about the tasks.json format',
							].join('\n') + content.substr(1);
							return content;
						} else {
							return selection.content;
						}
					});
				} else {
					contentPromise = TPromise.as(selection.content);
				}
				return contentPromise.then(content => {
					let editorConfig = this.configurationService.getConfiguration<any>();
					if (editorConfig.editor.insertSpaces) {
						content = content.replace(/(\n)(\t+)/g, (_, s1, s2) => s1 + strings.repeat(' ', s2.length * editorConfig.editor.tabSize));
					}
					configFileCreated = true;
					return this.fileService.createFile(this.contextService.toResource('.vscode/tasks.json'), content);
				});
				/* 2.0 version
D
Dirk Baeumer 已提交
172 173 174 175
				let content = selection.content;
				let editorConfig = this.configurationService.getConfiguration<any>();
				if (editorConfig.editor.insertSpaces) {
					content = content.replace(/(\n)(\t+)/g, (_, s1, s2) => s1 + strings.repeat(' ', s2.length * editorConfig.editor.tabSize));
E
Erich Gamma 已提交
176
				}
D
Dirk Baeumer 已提交
177 178
				configFileCreated = true;
				return this.fileService.createFile(this.contextService.toResource('.vscode/tasks.json'), content);
179
				*/
E
Erich Gamma 已提交
180 181
			});
		}).then((stat) => {
D
Dirk Baeumer 已提交
182 183 184 185
			if (!stat) {
				return undefined;
			}
			// // (2) Open editor with configuration file
E
Erich Gamma 已提交
186 187 188
			return this.editorService.openEditor({
				resource: stat.resource,
				options: {
189 190
					forceOpen: true,
					pinned: configFileCreated // pin only if config file is created #8727
E
Erich Gamma 已提交
191
				}
D
Dirk Baeumer 已提交
192
			}, sideBySide);
E
Erich Gamma 已提交
193 194 195 196 197 198
		}, (error) => {
			throw new Error(nls.localize('ConfigureTaskRunnerAction.failed', "Unable to create the 'tasks.json' file inside the '.vscode' folder. Consult the task output for details."));
		});
	}
}

199 200 201 202
class ConfigureTaskRunnerAction extends OpenTaskConfigurationAction {
	public static ID = 'workbench.action.tasks.configureTaskRunner';
	public static TEXT = nls.localize('ConfigureTaskRunnerAction.label', "Configure Task Runner");

203 204
	constructor(id: string, label: string,
		@ITaskService taskService, @IConfigurationService configurationService: IConfigurationService,
205 206 207
		@IWorkbenchEditorService editorService: IWorkbenchEditorService, @IFileService fileService: IFileService,
		@IWorkspaceContextService contextService: IWorkspaceContextService, @IOutputService outputService: IOutputService,
		@IMessageService messageService: IMessageService, @IQuickOpenService quickOpenService: IQuickOpenService,
208
		@IEnvironmentService environmentService: IEnvironmentService,
209 210 211 212 213
		@IConfigurationResolverService configurationResolverService: IConfigurationResolverService,
		@IExtensionService extensionService) {
		super(id, label, taskService, configurationService, editorService, fileService, contextService,
			outputService, messageService, quickOpenService, environmentService, configurationResolverService,
			extensionService);
J
Johannes Rieken 已提交
214
	}
215 216 217 218 219 220
}

class ConfigureBuildTaskAction extends OpenTaskConfigurationAction {
	public static ID = 'workbench.action.tasks.configureBuildTask';
	public static TEXT = nls.localize('ConfigureBuildTaskAction.label', "Configure Build Task");

221 222
	constructor(id: string, label: string,
		@ITaskService taskService, @IConfigurationService configurationService: IConfigurationService,
223 224 225
		@IWorkbenchEditorService editorService: IWorkbenchEditorService, @IFileService fileService: IFileService,
		@IWorkspaceContextService contextService: IWorkspaceContextService, @IOutputService outputService: IOutputService,
		@IMessageService messageService: IMessageService, @IQuickOpenService quickOpenService: IQuickOpenService,
226
		@IEnvironmentService environmentService: IEnvironmentService,
227 228 229 230 231
		@IConfigurationResolverService configurationResolverService: IConfigurationResolverService,
		@IExtensionService extensionService) {
		super(id, label, taskService, configurationService, editorService, fileService, contextService,
			outputService, messageService, quickOpenService, environmentService, configurationResolverService,
			extensionService);
J
Johannes Rieken 已提交
232
	}
233 234
}

E
Erich Gamma 已提交
235 236 237 238 239 240 241 242 243 244
class CloseMessageAction extends Action {

	public static ID = 'workbench.action.build.closeMessage';
	public static TEXT = nls.localize('CloseMessageAction.label', 'Close');

	public closeFunction: () => void;

	constructor() {
		super(CloseMessageAction.ID, CloseMessageAction.TEXT);
	}
245
	public run(): TPromise<void> {
E
Erich Gamma 已提交
246 247 248
		if (this.closeFunction) {
			this.closeFunction();
		}
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
		return TPromise.as(undefined);
	}
}

class ViewTerminalAction extends Action {

	public static ID = 'workbench.action.build.viewTerminal';
	public static TEXT = nls.localize('ShowTerminalAction.label', 'View Terminal');

	constructor( @ITerminalService private terminalService: ITerminalService) {
		super(ViewTerminalAction.ID, ViewTerminalAction.TEXT);
	}

	public run(): TPromise<void> {
		this.terminalService.showPanel();
		return TPromise.as(undefined);
E
Erich Gamma 已提交
265 266 267
	}
}

268
class StatusBarItem extends Themable implements IStatusbarItem {
E
Erich Gamma 已提交
269 270
	private intervalToken: any;
	private activeCount: number;
J
Johannes Rieken 已提交
271
	private static progressChars: string = '|/-\\';
272 273 274 275 276 277 278 279
	private icons: HTMLElement[];

	constructor(
		@IPanelService private panelService: IPanelService,
		@IMarkerService private markerService: IMarkerService,
		@IOutputService private outputService: IOutputService,
		@ITaskService private taskService: ITaskService,
		@IPartService private partService: IPartService,
280 281
		@IThemeService themeService: IThemeService,
		@IWorkspaceContextService private contextService: IWorkspaceContextService
282 283
	) {
		super(themeService);
E
Erich Gamma 已提交
284 285

		this.activeCount = 0;
286
		this.icons = [];
E
Erich Gamma 已提交
287 288
	}

289 290
	protected updateStyles(): void {
		super.updateStyles();
E
Erich Gamma 已提交
291

292
		this.icons.forEach(icon => {
293
			icon.style.backgroundColor = this.getColor(this.contextService.hasWorkspace() ? STATUS_BAR_FOREGROUND : STATUS_BAR_NO_FOLDER_FOREGROUND);
294 295
		});
	}
E
Erich Gamma 已提交
296

297 298 299 300 301 302 303 304 305 306 307 308
	public render(container: HTMLElement): IDisposable {
		let callOnDispose: IDisposable[] = [];

		const element = document.createElement('div');
		const progress = document.createElement('div');
		const label = document.createElement('a');
		const errorIcon = document.createElement('div');
		const warningIcon = document.createElement('div');
		const infoIcon = document.createElement('div');
		const error = document.createElement('div');
		const warning = document.createElement('div');
		const info = document.createElement('div');
E
Erich Gamma 已提交
309

310
		Dom.addClass(element, 'task-statusbar-item');
E
Erich Gamma 已提交
311 312 313 314 315 316 317 318

		Dom.addClass(progress, 'task-statusbar-item-progress');
		element.appendChild(progress);
		progress.innerHTML = StatusBarItem.progressChars[0];
		$(progress).hide();

		Dom.addClass(label, 'task-statusbar-item-label');
		element.appendChild(label);
S
Sandeep Somavarapu 已提交
319
		element.title = nls.localize('problems', "Problems");
E
Erich Gamma 已提交
320

321
		Dom.addClass(errorIcon, 'task-statusbar-item-label-error');
322
		Dom.addClass(errorIcon, 'mask-icon');
323 324 325 326
		label.appendChild(errorIcon);
		this.icons.push(errorIcon);

		Dom.addClass(error, 'task-statusbar-item-label-counter');
E
Erich Gamma 已提交
327 328 329
		error.innerHTML = '0';
		label.appendChild(error);

330
		Dom.addClass(warningIcon, 'task-statusbar-item-label-warning');
331
		Dom.addClass(warningIcon, 'mask-icon');
332 333 334 335
		label.appendChild(warningIcon);
		this.icons.push(warningIcon);

		Dom.addClass(warning, 'task-statusbar-item-label-counter');
E
Erich Gamma 已提交
336 337 338
		warning.innerHTML = '0';
		label.appendChild(warning);

339
		Dom.addClass(infoIcon, 'task-statusbar-item-label-info');
340
		Dom.addClass(infoIcon, 'mask-icon');
341 342 343 344 345
		label.appendChild(infoIcon);
		this.icons.push(infoIcon);
		$(infoIcon).hide();

		Dom.addClass(info, 'task-statusbar-item-label-counter');
E
Erich Gamma 已提交
346 347 348
		label.appendChild(info);
		$(info).hide();

J
Johannes Rieken 已提交
349 350
		callOnDispose.push(Dom.addDisposableListener(label, 'click', (e: MouseEvent) => {
			const panel = this.panelService.getActivePanel();
351 352 353 354 355
			if (panel && panel.getId() === Constants.MARKERS_PANEL_ID) {
				this.partService.setPanelHidden(true);
			} else {
				this.panelService.openPanel(Constants.MARKERS_PANEL_ID, true);
			}
J
Johannes Rieken 已提交
356
		}));
E
Erich Gamma 已提交
357

358
		let updateStatus = (element: HTMLDivElement, icon: HTMLDivElement, stats: number): boolean => {
E
Erich Gamma 已提交
359 360 361
			if (stats > 0) {
				element.innerHTML = stats.toString();
				$(element).show();
362
				$(icon).show();
E
Erich Gamma 已提交
363 364 365
				return true;
			} else {
				$(element).hide();
366
				$(icon).hide();
E
Erich Gamma 已提交
367 368 369 370 371 372 373 374
				return false;
			}
		};

		let manyMarkers = nls.localize('manyMarkers', "99+");
		let updateLabel = (stats: MarkerStatistics) => {
			error.innerHTML = stats.errors < 100 ? stats.errors.toString() : manyMarkers;
			warning.innerHTML = stats.warnings < 100 ? stats.warnings.toString() : manyMarkers;
375
			updateStatus(info, infoIcon, stats.infos);
E
Erich Gamma 已提交
376 377 378 379 380 381
		};

		this.markerService.onMarkerChanged((changedResources) => {
			updateLabel(this.markerService.getStatistics());
		});

382 383 384 385
		callOnDispose.push(this.taskService.addListener(TaskServiceEvents.Active, (event: TaskEvent) => {
			if (event.group !== TaskGroup.Build) {
				return;
			}
E
Erich Gamma 已提交
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
			this.activeCount++;
			if (this.activeCount === 1) {
				let index = 1;
				let chars = StatusBarItem.progressChars;
				progress.innerHTML = chars[0];
				this.intervalToken = setInterval(() => {
					progress.innerHTML = chars[index];
					index++;
					if (index >= chars.length) {
						index = 0;
					}
				}, 50);
				$(progress).show();
			}
		}));

402 403 404 405
		callOnDispose.push(this.taskService.addListener(TaskServiceEvents.Inactive, (event: TaskEvent) => {
			if (event.group !== TaskGroup.Build) {
				return;
			}
406 407 408 409 410 411 412 413 414 415 416
			// Since the exiting of the sub process is communicated async we can't order inactive and terminate events.
			// So try to treat them accordingly.
			if (this.activeCount > 0) {
				this.activeCount--;
				if (this.activeCount === 0) {
					$(progress).hide();
					if (this.intervalToken) {
						clearInterval(this.intervalToken);
						this.intervalToken = null;
					}
				}
E
Erich Gamma 已提交
417 418 419
			}
		}));

420 421 422 423
		callOnDispose.push(this.taskService.addListener(TaskServiceEvents.Terminated, (event: TaskEvent) => {
			if (event.group !== TaskGroup.Build) {
				return;
			}
E
Erich Gamma 已提交
424 425 426 427 428 429 430 431 432 433 434 435
			if (this.activeCount !== 0) {
				$(progress).hide();
				if (this.intervalToken) {
					clearInterval(this.intervalToken);
					this.intervalToken = null;
				}
				this.activeCount = 0;
			}
		}));

		container.appendChild(element);

436 437
		this.updateStyles();

E
Erich Gamma 已提交
438
		return {
439
			dispose: () => {
J
Joao Moreno 已提交
440
				callOnDispose = dispose(callOnDispose);
441
			}
E
Erich Gamma 已提交
442 443 444 445 446 447 448 449
		};
	}
}

interface TaskServiceEventData {
	error?: any;
}

450
class NullTaskSystem extends EventEmitter implements ITaskSystem {
451
	public run(task: Task): ITaskExecuteResult {
452
		return {
453
			kind: TaskExecuteKind.Started,
454 455 456 457 458 459 460 461 462
			promise: TPromise.as<ITaskSummary>({})
		};
	}
	public isActive(): TPromise<boolean> {
		return TPromise.as(false);
	}
	public isActiveSync(): boolean {
		return false;
	}
463 464 465
	public getActiveTasks(): Task[] {
		return [];
	}
466 467 468
	public canAutoTerminate(): boolean {
		return true;
	}
469 470
	public terminate(task: string | Task): TPromise<TaskTerminateResponse> {
		return TPromise.as<TaskTerminateResponse>({ success: true, task: undefined });
471
	}
472 473
	public terminateAll(): TPromise<TaskTerminateResponse[]> {
		return TPromise.as<TaskTerminateResponse[]>([]);
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
class ProblemReporter implements TaskConfig.IProblemReporter {

	private _validationStatus: ValidationStatus;

	constructor(private _outputChannel: IOutputChannel) {
		this._validationStatus = new ValidationStatus();
	}

	public info(message: string): void {
		this._validationStatus.state = ValidationState.Info;
		this._outputChannel.append(message + '\n');
	}

	public warn(message: string): void {
		this._validationStatus.state = ValidationState.Warning;
		this._outputChannel.append(message + '\n');
	}

	public error(message: string): void {
		this._validationStatus.state = ValidationState.Error;
		this._outputChannel.append(message + '\n');
	}

	public fatal(message: string): void {
		this._validationStatus.state = ValidationState.Fatal;
		this._outputChannel.append(message + '\n');
	}

	public get status(): ValidationStatus {
		return this._validationStatus;
	}

	public clearOutput(): void {
		this._outputChannel.clear();
	}
}

514
interface WorkspaceTaskResult {
515
	set: TaskSet;
516 517
	configurations: {
		byIdentifier: IStringDictionary<ConfiguringTask>;
518
	};
519 520 521
	hasErrors: boolean;
}

522 523 524 525 526
interface WorkspaceConfigurationResult {
	config: TaskConfig.ExternalTaskRunnerConfiguration;
	hasErrors: boolean;
}

E
Erich Gamma 已提交
527
class TaskService extends EventEmitter implements ITaskService {
528

529
	// private static autoDetectTelemetryName: string = 'taskServer.autoDetect';
530
	private static RecentlyUsedTasks_Key = 'workbench.tasks.recentlyUsedTasks';
T
t-amqi 已提交
531
	private static RanTaskBefore_Key = 'workbench.tasks.ranTaskBefore';
532

533
	public _serviceBrand: any;
E
Erich Gamma 已提交
534
	public static SERVICE_ID: string = 'taskService';
J
Johannes Rieken 已提交
535 536
	public static OutputChannelId: string = 'tasks';
	public static OutputChannelLabel: string = nls.localize('tasks', "Tasks");
E
Erich Gamma 已提交
537 538 539

	private modeService: IModeService;
	private configurationService: IConfigurationService;
D
Dirk Baeumer 已提交
540
	private configurationEditingService: IConfigurationEditingService;
E
Erich Gamma 已提交
541 542 543 544 545 546 547 548 549
	private markerService: IMarkerService;
	private outputService: IOutputService;
	private messageService: IMessageService;
	private fileService: IFileService;
	private telemetryService: ITelemetryService;
	private editorService: IWorkbenchEditorService;
	private contextService: IWorkspaceContextService;
	private textFileService: ITextFileService;
	private modelService: IModelService;
A
Alex Dima 已提交
550
	private extensionService: IExtensionService;
D
Dirk Baeumer 已提交
551
	private quickOpenService: IQuickOpenService;
E
Erich Gamma 已提交
552

553
	private _configHasErrors: boolean;
554
	private _providers: Map<number, ITaskProvider>;
555 556

	private _workspaceTasksPromise: TPromise<WorkspaceTaskResult>;
557

E
Erich Gamma 已提交
558
	private _taskSystem: ITaskSystem;
559
	private _taskSystemListeners: IDisposable[];
560
	private _recentlyUsedTasks: LinkedMap<string, string>;
561

562
	private _outputChannel: IOutputChannel;
E
Erich Gamma 已提交
563

J
Johannes Rieken 已提交
564
	constructor( @IModeService modeService: IModeService, @IConfigurationService configurationService: IConfigurationService,
D
Dirk Baeumer 已提交
565
		@IConfigurationEditingService configurationEditingService: IConfigurationEditingService,
E
Erich Gamma 已提交
566
		@IMarkerService markerService: IMarkerService, @IOutputService outputService: IOutputService,
J
Johannes Rieken 已提交
567 568 569
		@IMessageService messageService: IMessageService, @IWorkbenchEditorService editorService: IWorkbenchEditorService,
		@IFileService fileService: IFileService, @IWorkspaceContextService contextService: IWorkspaceContextService,
		@ITelemetryService telemetryService: ITelemetryService, @ITextFileService textFileService: ITextFileService,
570
		@ILifecycleService lifecycleService: ILifecycleService,
A
Alex Dima 已提交
571
		@IModelService modelService: IModelService, @IExtensionService extensionService: IExtensionService,
572
		@IQuickOpenService quickOpenService: IQuickOpenService,
573
		@IEnvironmentService private environmentService: IEnvironmentService,
574
		@IConfigurationResolverService private configurationResolverService: IConfigurationResolverService,
575
		@ITerminalService private terminalService: ITerminalService,
576
		@IWorkbenchEditorService private workbenchEditorService: IWorkbenchEditorService,
577 578
		@IStorageService private storageService: IStorageService,
		@IProgressService2 private progressService: IProgressService2
579
	) {
E
Erich Gamma 已提交
580 581 582 583

		super();
		this.modeService = modeService;
		this.configurationService = configurationService;
D
Dirk Baeumer 已提交
584
		this.configurationEditingService = configurationEditingService;
E
Erich Gamma 已提交
585 586 587 588 589 590 591 592 593
		this.markerService = markerService;
		this.outputService = outputService;
		this.messageService = messageService;
		this.editorService = editorService;
		this.fileService = fileService;
		this.contextService = contextService;
		this.telemetryService = telemetryService;
		this.textFileService = textFileService;
		this.modelService = modelService;
A
Alex Dima 已提交
594
		this.extensionService = extensionService;
D
Dirk Baeumer 已提交
595
		this.quickOpenService = quickOpenService;
E
Erich Gamma 已提交
596

597 598
		this._configHasErrors = false;
		this._workspaceTasksPromise = undefined;
599 600 601
		this._taskSystemListeners = [];
		this._outputChannel = this.outputService.getChannel(TaskService.OutputChannelId);
		this._providers = new Map<number, ITaskProvider>();
J
Johannes Rieken 已提交
602
		this.configurationService.onDidUpdateConfiguration(() => {
603
			if (!this._taskSystem && !this._workspaceTasksPromise) {
604 605
				return;
			}
606
			this.updateWorkspaceTasks();
607 608 609
			if (!this._taskSystem) {
				return;
			}
610 611 612 613
			let currentExecutionEngine = this._taskSystem instanceof TerminalTaskSystem
				? ExecutionEngine.Terminal
				: this._taskSystem instanceof ProcessTaskSystem
					? ExecutionEngine.Process
614
					: ExecutionEngine._default;
615
			if (currentExecutionEngine !== this.getExecutionEngine()) {
616
				this.messageService.show(Severity.Info, nls.localize('TaskSystem.noHotSwap', 'Changing the task execution engine requires restarting VS Code. The change is ignored.'));
D
Dirk Baeumer 已提交
617
			}
E
Erich Gamma 已提交
618
		});
619
		lifecycleService.onWillShutdown(event => event.veto(this.beforeShutdown()));
620 621 622 623
		this.registerCommands();
	}

	private registerCommands(): void {
624
		CommandsRegistry.registerCommand('workbench.action.tasks.runTask', (accessor, arg) => {
625 626 627
			this.runTaskCommand(accessor, arg);
		});

628 629 630 631
		CommandsRegistry.registerCommand('workbench.action.tasks.restartTask', (accessor, arg) => {
			this.runRestartTaskCommand(accessor, arg);
		});

632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
		CommandsRegistry.registerCommand('workbench.action.tasks.terminate', (accessor, arg) => {
			this.runTerminateCommand();
		});

		CommandsRegistry.registerCommand('workbench.action.tasks.showLog', () => {
			if (!this.canRunCommand()) {
				return;
			}
			this.showOutput();
		});

		CommandsRegistry.registerCommand('workbench.action.tasks.build', () => {
			if (!this.canRunCommand()) {
				return;
			}
647
			this.runBuildCommand();
648 649 650 651 652 653 654 655 656 657 658 659
		});

		KeybindingsRegistry.registerKeybindingRule({
			id: 'workbench.action.tasks.build',
			weight: KeybindingsRegistry.WEIGHT.workbenchContrib(),
			when: undefined,
			primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_B
		});

		CommandsRegistry.registerCommand('workbench.action.tasks.test', () => {
			if (!this.canRunCommand()) {
				return;
660
			}
661
			this.runTestCommand();
662
		});
E
Erich Gamma 已提交
663 664
	}

665
	private showOutput(): void {
666
		this._outputChannel.show(true);
667 668
	}

E
Erich Gamma 已提交
669
	private disposeTaskSystemListeners(): void {
670
		this._taskSystemListeners = dispose(this._taskSystemListeners);
E
Erich Gamma 已提交
671 672
	}

673 674 675 676
	public registerTaskProvider(handle: number, provider: ITaskProvider): void {
		if (!provider) {
			return;
		}
677
		this._providers.set(handle, provider);
678 679 680
	}

	public unregisterTaskProvider(handle: number): boolean {
681
		return this._providers.delete(handle);
682 683
	}

684 685 686 687 688 689 690
	public getTask(identifier: string): TPromise<Task> {
		return this.getTaskSets().then((sets) => {
			let resolver = this.createResolver(sets);
			return resolver.resolve(identifier);
		});
	}

691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707
	public tasks(): TPromise<Task[]> {
		return this.getTaskSets().then((sets) => {
			let result: Task[] = [];
			for (let set of sets) {
				result.push(...set.tasks);
			}
			return result;
		});
	};

	public isActive(): TPromise<boolean> {
		if (!this._taskSystem) {
			return TPromise.as(false);
		}
		return this._taskSystem.isActive();
	}

708 709 710 711 712 713 714
	public getActiveTasks(): TPromise<Task[]> {
		if (!this._taskSystem) {
			return TPromise.as([]);
		}
		return TPromise.as(this._taskSystem.getActiveTasks());
	}

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
	public getRecentlyUsedTasks(): LinkedMap<string, string> {
		if (this._recentlyUsedTasks) {
			return this._recentlyUsedTasks;
		}
		this._recentlyUsedTasks = new LinkedMap<string, string>();
		let storageValue = this.storageService.get(TaskService.RecentlyUsedTasks_Key, StorageScope.WORKSPACE);
		if (storageValue) {
			try {
				let values: string[] = JSON.parse(storageValue);
				if (Array.isArray(values)) {
					for (let value of values) {
						this._recentlyUsedTasks.set(value, value);
					}
				}
			} catch (error) {
				// Ignore. We use the empty result
			}
		}
		return this._recentlyUsedTasks;
	}

	private saveRecentlyUsedTasks(): void {
		if (!this._recentlyUsedTasks) {
			return;
		}
		let values = this._recentlyUsedTasks.values();
		if (values.length > 30) {
			values = values.slice(0, 30);
		}
		this.storageService.store(TaskService.RecentlyUsedTasks_Key, JSON.stringify(values), StorageScope.WORKSPACE);
	}
746

747 748
	public build(): TPromise<ITaskSummary> {
		return this.getTaskSets().then((values) => {
749
			let runnable = this.createRunnableTask(values, TaskGroup.Build);
750
			if (!runnable || !runnable.task) {
751 752 753 754 755
				if (this.getJsonSchemaVersion() === JsonSchemaVersion.V0_1_0) {
					throw new TaskError(Severity.Info, nls.localize('TaskService.noBuildTask1', 'No build task defined. Mark a task with \'isBuildCommand\' in the tasks.json file.'), TaskErrors.NoBuildTask);
				} else {
					throw new TaskError(Severity.Info, nls.localize('TaskService.noBuildTask2', 'No build task defined. Mark a task with as a \'build\' group in the tasks.json file.'), TaskErrors.NoBuildTask);
				}
756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773
			}
			return this.executeTask(runnable.task, runnable.resolver);
		}).then(value => value, (error) => {
			this.handleError(error);
			return TPromise.wrapError(error);
		});
	}

	public rebuild(): TPromise<ITaskSummary> {
		return TPromise.wrapError<ITaskSummary>(new Error('Not implemented'));
	}

	public clean(): TPromise<ITaskSummary> {
		return TPromise.wrapError<ITaskSummary>(new Error('Not implemented'));
	}

	public runTest(): TPromise<ITaskSummary> {
		return this.getTaskSets().then((values) => {
774
			let runnable = this.createRunnableTask(values, TaskGroup.Test);
775
			if (!runnable || !runnable.task) {
776 777 778 779 780
				if (this.getJsonSchemaVersion() === JsonSchemaVersion.V0_1_0) {
					throw new TaskError(Severity.Info, nls.localize('TaskService.noTestTask1', 'No test task defined. Mark a task with \'isTestCommand\' in the tasks.json file.'), TaskErrors.NoTestTask);
				} else {
					throw new TaskError(Severity.Info, nls.localize('TaskService.noTestTask2', 'No test task defined. Mark a task with as a \'test\' group in the tasks.json file.'), TaskErrors.NoTestTask);
				}
781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
			}
			return this.executeTask(runnable.task, runnable.resolver);
		}).then(value => value, (error) => {
			this.handleError(error);
			return TPromise.wrapError(error);
		});
	}

	public run(task: string | Task): TPromise<ITaskSummary> {
		return this.getTaskSets().then((values) => {
			let resolver = this.createResolver(values);
			let requested: string;
			let toExecute: Task;
			if (Types.isString(task)) {
				requested = task;
				toExecute = resolver.resolve(task);
797
			} else {
798
				requested = task.name;
D
Dirk Baeumer 已提交
799
				toExecute = task;
800 801 802 803 804
			}
			if (!toExecute) {
				throw new TaskError(Severity.Info, nls.localize('TaskServer.noTask', 'Requested task {0} to execute not found.', requested), TaskErrors.TaskNotFound);
			} else {
				return this.executeTask(toExecute, resolver);
805
			}
806 807 808 809 810 811
		}).then(value => value, (error) => {
			this.handleError(error);
			return TPromise.wrapError(error);
		});
	}

812 813 814 815 816 817 818 819 820 821 822 823 824 825
	public getTasksForGroup(group: string): TPromise<Task[]> {
		return this.getTaskSets().then((values) => {
			let result: Task[] = [];
			for (let value of values) {
				for (let task of value.tasks) {
					if (task.group === group) {
						result.push(task);
					}
				}
			}
			return result;
		});
	}

826 827 828 829
	public canCustomize(): boolean {
		return this.getJsonSchemaVersion() === JsonSchemaVersion.V2_0_0;
	}

830
	public customize(task: Task, properties?: { problemMatcher: string | string[] }, openConfig?: boolean): TPromise<void> {
831
		if (!ContributedTask.is(task)) {
D
Dirk Baeumer 已提交
832 833 834 835 836 837 838 839
			return TPromise.as<void>(undefined);
		}
		let configuration = this.getConfiguration();
		if (configuration.hasParseErrors) {
			this.messageService.show(Severity.Warning, nls.localize('customizeParseErrors', 'The current task configuration has errors. Please fix the errors first before customizing a task.'));
			return TPromise.as<void>(undefined);
		}
		let fileConfig = configuration.config;
840 841 842 843 844 845
		let customizes: TaskConfig.ConfiguringTask = {
		};
		let identifier: TaskConfig.TaskIdentifier = Objects.assign(Object.create(null), task.defines);
		delete identifier['_key'];
		Object.keys(identifier).forEach(key => customizes[key] = identifier[key]);

846 847 848 849 850 851 852 853 854 855 856
		if (properties) {
			for (let property of Object.getOwnPropertyNames(properties)) {
				let value = properties[property];
				if (value !== void 0 && value !== null) {
					customizes[property] = value;
				}
			}
		} else {
			if (task.problemMatchers === void 0 || task.problemMatchers.length === 0) {
				customizes.problemMatcher = [];
			}
857
		}
858

859
		let promise: TPromise<void>;
D
Dirk Baeumer 已提交
860
		if (!fileConfig) {
861
			let value = {
D
Dirk Baeumer 已提交
862
				version: '2.0.0',
863
				tasks: [customizes]
D
Dirk Baeumer 已提交
864
			};
865 866 867 868 869 870 871 872 873 874
			let content = [
				'{',
				'\t// See https://go.microsoft.com/fwlink/?LinkId=733558',
				'\t// for the documentation about the tasks.json format',
			].join('\n') + JSON.stringify(value, null, '\t').substr(1);
			let editorConfig = this.configurationService.getConfiguration<any>();
			if (editorConfig.editor.insertSpaces) {
				content = content.replace(/(\n)(\t+)/g, (_, s1, s2) => s1 + strings.repeat(' ', s2.length * editorConfig.editor.tabSize));
			}
			promise = this.fileService.createFile(this.contextService.toResource('.vscode/tasks.json'), content).then(() => { });
D
Dirk Baeumer 已提交
875
		} else {
876
			let value: IConfigurationValue = { key: undefined, value: undefined };
D
Dirk Baeumer 已提交
877
			if (Array.isArray(fileConfig.tasks)) {
878
				fileConfig.tasks.push(customizes);
D
Dirk Baeumer 已提交
879
			} else {
880
				fileConfig.tasks = [customizes];
D
Dirk Baeumer 已提交
881
			}
882 883
			value.key = 'tasks.tasks';
			value.value = fileConfig.tasks;
884
			promise = this.configurationEditingService.writeConfiguration(ConfigurationTarget.WORKSPACE, value);
D
Dirk Baeumer 已提交
885
		};
886
		return promise.then(() => {
D
Dirk Baeumer 已提交
887 888 889 890 891 892 893 894 895 896 897 898 899
			if (openConfig) {
				let resource = this.contextService.toResource('.vscode/tasks.json');
				this.editorService.openEditor({
					resource: resource,
					options: {
						forceOpen: true,
						pinned: false
					}
				}, false);
			}
		});
	}

900
	private createRunnableTask(sets: TaskSet[], group: TaskGroup): { task: Task; resolver: ITaskResolver } {
901
		let idMap: IStringDictionary<Task> = Object.create(null);
D
Dirk Baeumer 已提交
902
		let labelMap: IStringDictionary<Task> = Object.create(null);
903 904
		let identifierMap: IStringDictionary<Task> = Object.create(null);

905 906
		let workspaceTasks: Task[] = [];
		let extensionTasks: Task[] = [];
907 908
		sets.forEach((set) => {
			set.tasks.forEach((task) => {
909
				idMap[task._id] = task;
910
				labelMap[task._label] = task;
911
				identifierMap[task.identifier] = task;
912
				if (group && task.group === group) {
913 914 915 916 917
					if (task._source.kind === TaskSourceKind.Workspace) {
						workspaceTasks.push(task);
					} else {
						extensionTasks.push(task);
					}
918
				}
919 920 921 922
			});
		});
		let resolver: ITaskResolver = {
			resolve: (id: string) => {
923
				return idMap[id] || labelMap[id] || identifierMap[id];
924 925
			}
		};
926 927 928 929 930 931 932 933 934 935
		if (workspaceTasks.length > 0) {
			if (workspaceTasks.length > 1) {
				this._outputChannel.append(nls.localize('moreThanOneBuildTask', 'There are many build tasks defined in the tasks.json. Executing the first one.\n'));
			}
			return { task: workspaceTasks[0], resolver };
		}
		if (extensionTasks.length === 0) {
			return undefined;
		}

936 937
		// We can only have extension tasks if we are in version 2.0.0. Then we can even run
		// multiple build tasks.
938 939
		if (extensionTasks.length === 1) {
			return { task: extensionTasks[0], resolver };
940 941
		} else {
			let id: string = UUID.generateUuid();
942
			let task: CustomTask = {
943
				_id: id,
944
				_source: { kind: TaskSourceKind.Generic, label: 'generic' },
945
				_label: id,
946
				type: 'custom',
947 948
				name: id,
				identifier: id,
949
				dependsOn: extensionTasks.map(task => task._id),
950 951 952
				command: undefined,
			};
			return { task, resolver };
E
Erich Gamma 已提交
953 954 955
		}
	}

956
	private createResolver(sets: TaskSet[]): ITaskResolver {
D
Dirk Baeumer 已提交
957
		let labelMap: IStringDictionary<Task> = Object.create(null);
958 959 960 961
		let identifierMap: IStringDictionary<Task> = Object.create(null);

		sets.forEach((set) => {
			set.tasks.forEach((task) => {
962
				labelMap[task._label] = task;
963 964 965 966 967
				identifierMap[task.identifier] = task;
			});
		});
		return {
			resolve: (id: string) => {
D
Dirk Baeumer 已提交
968
				return labelMap[id] || identifierMap[id];
969
			}
970 971 972 973
		};
	}

	private executeTask(task: Task, resolver: ITaskResolver): TPromise<ITaskSummary> {
T
t-amqi 已提交
974 975
		if (!this.storageService.get(TaskService.RanTaskBefore_Key, StorageScope.GLOBAL)) {
			this.storageService.store(TaskService.RanTaskBefore_Key, true, StorageScope.GLOBAL);
T
t-amqi 已提交
976
		}
977 978 979
		return ProblemMatcherRegistry.onReady().then(() => {
			return this.textFileService.saveAll().then((value) => { // make sure all dirty files are saved
				let executeResult = this.getTaskSystem().run(task, resolver);
980
				this.getRecentlyUsedTasks().set(Task.getKey(task), Task.getKey(task), Touch.First);
981 982
				if (executeResult.kind === TaskExecuteKind.Active) {
					let active = executeResult.active;
983 984 985 986
					if (active.same) {
						if (active.background) {
							this.messageService.show(Severity.Info, nls.localize('TaskSystem.activeSame.background', 'The task is already active and in background mode. To terminate the task use `F1 > terminate task`'));
						} else {
987
							this.messageService.show(Severity.Info, nls.localize('TaskSystem.activeSame.noBackground', 'The task is already active. To terminate the task use `F1 > terminate task`'));
988
						}
989 990 991
					} else {
						throw new TaskError(Severity.Warning, nls.localize('TaskSystem.active', 'There is already a task running. Terminate it first before executing another task.'), TaskErrors.RunningTask);
					}
992
				}
993 994
				return executeResult.promise;
			});
995 996 997
		});
	}

998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
	public restart(task: string | Task): void {
		if (!this._taskSystem) {
			return;
		}
		const id: string = Types.isString(task) ? task : task._id;
		this._taskSystem.terminate(id).then((response) => {
			if (response.success) {
				this.emit(TaskServiceEvents.Terminated, {});
				this.run(task);
			} else {
				this.messageService.show(Severity.Warning, nls.localize('TaskSystem.restartFailed', 'Failed to terminate and restart task {0}', Types.isString(task) ? task : task.name));
			}
			return response;
		});
	}

1014
	public terminate(task: string | Task): TPromise<TaskTerminateResponse> {
1015
		if (!this._taskSystem) {
1016
			return TPromise.as({ success: true, task: undefined });
1017
		}
1018
		const id: string = Types.isString(task) ? task : task._id;
1019
		return this._taskSystem.terminate(id);
1020 1021
	}

1022
	public terminateAll(): TPromise<TaskTerminateResponse[]> {
1023
		if (!this._taskSystem) {
1024
			return TPromise.as<TaskTerminateResponse[]>([]);
1025
		}
1026
		return this._taskSystem.terminateAll();
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
	}

	private getTaskSystem(): ITaskSystem {
		if (this._taskSystem) {
			return this._taskSystem;
		}
		let engine = this.getExecutionEngine();
		if (engine === ExecutionEngine.Terminal) {
			this._taskSystem = new TerminalTaskSystem(
				this.terminalService, this.outputService, this.markerService,
				this.modelService, this.configurationResolverService, this.telemetryService,
1038
				this.workbenchEditorService,
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
				TaskService.OutputChannelId
			);
		} else {
			let system = new ProcessTaskSystem(
				this.markerService, this.modelService, this.telemetryService, this.outputService,
				this.configurationResolverService, TaskService.OutputChannelId,
			);
			system.hasErrors(this._configHasErrors);
			this._taskSystem = system;
		}
A
Alex Dima 已提交
1049 1050
		this._taskSystemListeners.push(this._taskSystem.addListener(TaskSystemEvents.Active, (event) => this.emit(TaskServiceEvents.Active, event)));
		this._taskSystemListeners.push(this._taskSystem.addListener(TaskSystemEvents.Inactive, (event) => this.emit(TaskServiceEvents.Inactive, event)));
1051
		this._taskSystemListeners.push(this._taskSystem.addListener(TaskSystemEvents.Terminated, (event) => this.emit(TaskServiceEvents.Terminated, event)));
1052 1053 1054 1055
		return this._taskSystem;
	}

	private getTaskSets(): TPromise<TaskSet[]> {
D
Dirk Baeumer 已提交
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
		return this.extensionService.activateByEvent('onCommand:workbench.action.tasks.runTask').then(() => {
			return new TPromise<TaskSet[]>((resolve, reject) => {
				let result: TaskSet[] = [];
				let counter: number = 0;
				let done = (value: TaskSet) => {
					if (value) {
						result.push(value);
					}
					if (--counter === 0) {
						resolve(result);
					}
				};
				let error = () => {
					if (--counter === 0) {
						resolve(result);
					}
				};
1073
				if (this.getJsonSchemaVersion() === JsonSchemaVersion.V2_0_0 && this._providers.size > 0) {
D
Dirk Baeumer 已提交
1074 1075 1076 1077 1078
					this._providers.forEach((provider) => {
						counter++;
						provider.provideTasks().done(done, error);
					});
				} else {
1079 1080
					resolve(result);
				}
D
Dirk Baeumer 已提交
1081
			});
1082 1083 1084
		}).then((result) => {
			return this.getWorkspaceTasks().then((workspaceTaskResult) => {
				let workspaceTasksToDelete: Task[] = [];
1085 1086 1087
				let configurations = workspaceTaskResult.configurations;
				let legacyTaskConfigurations = workspaceTaskResult.set ? this.getLegacyTaskConfigurations(workspaceTaskResult.set) : undefined;
				if (configurations || legacyTaskConfigurations) {
1088
					for (let set of result) {
1089 1090 1091 1092 1093 1094 1095 1096 1097
						for (let i = 0; i < set.tasks.length; i++) {
							let task = set.tasks[i];
							if (!ContributedTask.is(task)) {
								continue;
							}
							if (configurations) {
								let configuredTask = configurations.byIdentifier[task.defines._key];
								if (configuredTask) {
									set.tasks[i] = TaskConfig.createCustomTask(task, configuredTask);
1098 1099 1100
									continue;
								}
							}
1101 1102 1103 1104 1105 1106
							if (legacyTaskConfigurations) {
								let configuredTask = legacyTaskConfigurations[task.defines._key];
								if (configuredTask) {
									set.tasks[i] = TaskConfig.createCustomTask(task, configuredTask);
									workspaceTasksToDelete.push(configuredTask);
									set.tasks[i] = configuredTask;
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
									continue;
								}
							}
						}
					}
				}
				if (workspaceTaskResult.set) {
					if (workspaceTasksToDelete.length > 0) {
						let tasks = workspaceTaskResult.set.tasks;
						let newSet: TaskSet = {
							extension: workspaceTaskResult.set.extension,
							tasks: []
						};
						let toDelete = workspaceTasksToDelete.reduce<IStringDictionary<boolean>>((map, task) => {
							map[task._id] = true;
							return map;
						}, Object.create(null));
						newSet.tasks = tasks.filter(task => !toDelete[task._id]);
						result.push(newSet);
					} else {
						result.push(workspaceTaskResult.set);
					}
				}
				return result;
			}, () => {
				// If we can't read the tasks.json file provide at least the contributed tasks
				return result;
			});
1135 1136 1137
		});
	}

1138
	private getLegacyTaskConfigurations(workspaceTasks: TaskSet): IStringDictionary<Task> {
1139 1140 1141 1142 1143 1144 1145 1146 1147
		let result: IStringDictionary<Task>;
		function getResult() {
			if (result) {
				return result;
			}
			result = Object.create(null);
			return result;
		}
		for (let task of workspaceTasks.tasks) {
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
			if (CustomTask.is(task)) {
				let commandName = task.command && task.command.name;
				// This is for backwards compatibility with the 0.1.0 task annotation code
				// if we had a gulp, jake or grunt command a task specification was a annotation
				if (commandName === 'gulp' || commandName === 'grunt' || commandName === 'jake') {
					let identifier: TaskIdentifier = TaskConfig.getTaskIdentifier({
						type: commandName,
						task: task.name
					} as TaskConfig.TaskIdentifier);
					getResult()[identifier._key] = task;
				}
1159 1160 1161 1162 1163 1164
			}
		}
		return result;
	}

	private getWorkspaceTasks(): TPromise<WorkspaceTaskResult> {
1165 1166 1167
		if (this._workspaceTasksPromise) {
			return this._workspaceTasksPromise;
		}
1168
		this.updateWorkspaceTasks();
1169 1170 1171 1172 1173 1174
		return this._workspaceTasksPromise;
	}

	private updateWorkspaceTasks(): void {
		this._workspaceTasksPromise = this.computeWorkspaceTasks().then(value => {
			this._configHasErrors = value.hasErrors;
1175 1176 1177 1178
			if (this._taskSystem instanceof ProcessTaskSystem) {
				this._taskSystem.hasErrors(this._configHasErrors);
			}
			return value;
1179 1180 1181 1182
		});
	}

	private computeWorkspaceTasks(): TPromise<WorkspaceTaskResult> {
1183
		let configPromise: TPromise<WorkspaceConfigurationResult>;
1184 1185 1186
		{
			let { config, hasParseErrors } = this.getConfiguration();
			if (hasParseErrors) {
1187
				return TPromise.as({ set: undefined, hasErrors: true, configurations: undefined });
1188
			}
1189
			let engine = ExecutionEngine._default;
1190
			if (config) {
1191
				engine = TaskConfig.ExecutionEngine.from(config);
1192 1193 1194 1195 1196 1197 1198
				if (engine === ExecutionEngine.Process) {
					if (this.hasDetectorSupport(config)) {
						configPromise = new ProcessRunnerDetector(this.fileService, this.contextService, this.configurationResolverService, config).detect(true).then((value): WorkspaceConfigurationResult => {
							let hasErrors = this.printStderr(value.stderr);
							let detectedConfig = value.config;
							if (!detectedConfig) {
								return { config, hasErrors };
1199
							}
1200
							let result: TaskConfig.ExternalTaskRunnerConfiguration = Objects.clone(config);
1201
							let configuredTasks: IStringDictionary<TaskConfig.CustomTask> = Object.create(null);
1202 1203 1204
							if (!result.tasks) {
								if (detectedConfig.tasks) {
									result.tasks = detectedConfig.tasks;
1205
								}
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
							} else {
								result.tasks.forEach(task => configuredTasks[task.taskName] = task);
								detectedConfig.tasks.forEach((task) => {
									if (!configuredTasks[task.taskName]) {
										result.tasks.push(task);
									}
								});
							}
							return { config: result, hasErrors };
						});
					} else {
1217
						configPromise = TPromise.as({ config, hasErrors: false });
1218
					}
1219 1220 1221
				} else {
					configPromise = TPromise.as({ config, hasErrors: false });
				}
1222
			} else {
1223 1224 1225 1226 1227 1228 1229 1230
				if (engine === ExecutionEngine.Terminal) {
					configPromise = TPromise.as({ config, hasErrors: false });
				} else {
					configPromise = new ProcessRunnerDetector(this.fileService, this.contextService, this.configurationResolverService).detect(true).then((value) => {
						let hasErrors = this.printStderr(value.stderr);
						return { config: value.config, hasErrors };
					});
				}
1231 1232
			}
		}
1233
		return configPromise.then((resolved) => {
1234
			return ProblemMatcherRegistry.onReady().then((): WorkspaceTaskResult => {
1235
				if (!resolved || !resolved.config) {
1236
					return { set: undefined, configurations: undefined, hasErrors: resolved !== void 0 ? resolved.hasErrors : false };
1237
				}
1238
				let problemReporter = new ProblemReporter(this._outputChannel);
1239
				let parseResult = TaskConfig.parse(resolved.config, problemReporter);
1240 1241 1242 1243 1244 1245 1246
				let hasErrors = false;
				if (!parseResult.validationStatus.isOK()) {
					hasErrors = true;
					this.showOutput();
				}
				if (problemReporter.status.isFatal()) {
					problemReporter.fatal(nls.localize('TaskSystem.configurationErrors', 'Error: the provided task configuration has validation errors and can\'t not be used. Please correct the errors first.'));
1247
					return { set: undefined, configurations: undefined, hasErrors };
1248
				}
1249 1250 1251
				let customizedTasks: { byIdentifier: IStringDictionary<ConfiguringTask>; };
				if (parseResult.configured && parseResult.configured.length > 0) {
					customizedTasks = {
1252
						byIdentifier: Object.create(null)
1253
					};
1254 1255
					for (let task of parseResult.configured) {
						customizedTasks.byIdentifier[task.configures._key] = task;
1256
					}
1257
				}
1258
				return { set: { tasks: parseResult.custom }, configurations: customizedTasks, hasErrors };
1259 1260 1261 1262 1263 1264 1265
			});
		});
	}

	private getExecutionEngine(): ExecutionEngine {
		let { config } = this.getConfiguration();
		if (!config) {
1266
			return ExecutionEngine._default;
1267 1268 1269 1270
		}
		return TaskConfig.ExecutionEngine.from(config);
	}

1271 1272 1273 1274 1275 1276 1277 1278
	private getJsonSchemaVersion(): JsonSchemaVersion {
		let { config } = this.getConfiguration();
		if (!config) {
			return JsonSchemaVersion.V2_0_0;
		}
		return TaskConfig.JsonSchemaVersion.from(config);
	}

1279
	private getConfiguration(): { config: TaskConfig.ExternalTaskRunnerConfiguration; hasParseErrors: boolean } {
I
isidor 已提交
1280
		let result = this.contextService.hasWorkspace() ? this.configurationService.getConfiguration<TaskConfig.ExternalTaskRunnerConfiguration>('tasks', { resource: this.contextService.getWorkspace().resource }) : undefined;
1281
		if (!result) {
1282
			return { config: undefined, hasParseErrors: false };
1283 1284 1285 1286 1287 1288 1289 1290 1291
		}
		let parseErrors: string[] = (result as any).$parseErrors;
		if (parseErrors) {
			let isAffected = false;
			for (let i = 0; i < parseErrors.length; i++) {
				if (/tasks\.json$/.test(parseErrors[i])) {
					isAffected = true;
					break;
				}
1292
			}
1293
			if (isAffected) {
1294
				this._outputChannel.append(nls.localize('TaskSystem.invalidTaskJson', 'Error: The content of the tasks.json file has syntax errors. Please correct them before executing a task.\n'));
1295
				this.showOutput();
1296
				return { config: undefined, hasParseErrors: true };
1297
			}
1298 1299
		}
		return { config: result, hasParseErrors: false };
1300 1301
	}

E
Erich Gamma 已提交
1302
	private printStderr(stderr: string[]): boolean {
1303
		let result = false;
E
Erich Gamma 已提交
1304 1305
		if (stderr && stderr.length > 0) {
			stderr.forEach((line) => {
1306
				result = true;
1307
				this._outputChannel.append(line + '\n');
E
Erich Gamma 已提交
1308
			});
1309
			this._outputChannel.show(true);
E
Erich Gamma 已提交
1310 1311 1312 1313
		}
		return result;
	}

1314
	public inTerminal(): boolean {
1315 1316 1317 1318
		if (this._taskSystem) {
			return this._taskSystem instanceof TerminalTaskSystem;
		}
		return this.getExecutionEngine() === ExecutionEngine.Terminal;
1319 1320
	}

1321
	private hasDetectorSupport(config: TaskConfig.ExternalTaskRunnerConfiguration): boolean {
1322
		if (!config.command || !this.contextService.hasWorkspace()) {
E
Erich Gamma 已提交
1323 1324 1325 1326 1327
			return false;
		}
		return ProcessRunnerDetector.supports(config.command);
	}

1328
	public configureAction(): Action {
1329
		return new ConfigureTaskRunnerAction(ConfigureTaskRunnerAction.ID, ConfigureTaskRunnerAction.TEXT, this,
1330
			this.configurationService, this.editorService, this.fileService, this.contextService,
1331 1332
			this.outputService, this.messageService, this.quickOpenService, this.environmentService, this.configurationResolverService,
			this.extensionService);
1333 1334
	}

1335
	private configureBuildTask(): Action {
1336
		return new ConfigureBuildTaskAction(ConfigureBuildTaskAction.ID, ConfigureBuildTaskAction.TEXT, this,
1337
			this.configurationService, this.editorService, this.fileService, this.contextService,
1338 1339
			this.outputService, this.messageService, this.quickOpenService, this.environmentService, this.configurationResolverService,
			this.extensionService);
1340 1341
	}

E
Erich Gamma 已提交
1342
	public beforeShutdown(): boolean | TPromise<boolean> {
1343 1344 1345
		if (!this._taskSystem) {
			return false;
		}
1346
		this.saveRecentlyUsedTasks();
1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368
		if (!this._taskSystem.isActiveSync()) {
			return false;
		}
		// The terminal service kills all terminal on shutdown. So there
		// is nothing we can do to prevent this here.
		if (this._taskSystem instanceof TerminalTaskSystem) {
			return false;
		}
		if (this._taskSystem.canAutoTerminate() || this.messageService.confirm({
			message: nls.localize('TaskSystem.runningTask', 'There is a task running. Do you want to terminate it?'),
			primaryButton: nls.localize({ key: 'TaskSystem.terminateTask', comment: ['&& denotes a mnemonic'] }, "&&Terminate Task"),
			type: 'question'
		})) {
			return this._taskSystem.terminateAll().then((responses) => {
				let success = true;
				let code: number = undefined;
				for (let response of responses) {
					success = success && response.success;
					// We only have a code in the old output runner which only has one task
					// So we can use the first code.
					if (code === void 0 && response.code !== void 0) {
						code = response.code;
E
Erich Gamma 已提交
1369
					}
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
				}
				if (success) {
					this.emit(TaskServiceEvents.Terminated, {});
					this._taskSystem = null;
					this.disposeTaskSystemListeners();
					return false; // no veto
				} else if (code && code === TerminateResponseCode.ProcessNotFound) {
					return !this.messageService.confirm({
						message: nls.localize('TaskSystem.noProcess', 'The launched task doesn\'t exist anymore. If the task spawned background processes exiting VS Code might result in orphaned processes. To avoid this start the last background process with a wait flag.'),
						primaryButton: nls.localize({ key: 'TaskSystem.exitAnyways', comment: ['&& denotes a mnemonic'] }, "&&Exit Anyways"),
						type: 'info'
					});
				}
E
Erich Gamma 已提交
1383
				return true; // veto
1384 1385 1386 1387 1388
			}, (err) => {
				return true; // veto
			});
		} else {
			return true; // veto
E
Erich Gamma 已提交
1389 1390 1391
		}
	}

1392
	private getConfigureAction(code: TaskErrors): Action {
J
Johannes Rieken 已提交
1393
		switch (code) {
1394 1395 1396 1397 1398 1399
			case TaskErrors.NoBuildTask:
				return this.configureBuildTask();
			default:
				return this.configureAction();
		}
	}
1400

J
Johannes Rieken 已提交
1401
	private handleError(err: any): void {
E
Erich Gamma 已提交
1402 1403 1404
		let showOutput = true;
		if (err instanceof TaskError) {
			let buildError = <TaskError>err;
1405 1406 1407
			let needsConfig = buildError.code === TaskErrors.NotConfigured || buildError.code === TaskErrors.NoBuildTask || buildError.code === TaskErrors.NoTestTask;
			let needsTerminate = buildError.code === TaskErrors.RunningTask;
			if (needsConfig || needsTerminate) {
E
Erich Gamma 已提交
1408
				let closeAction = new CloseMessageAction();
1409
				let action: Action = needsConfig
1410
					? this.getConfigureAction(buildError.code)
1411 1412 1413 1414
					: new Action(
						'workbench.action.tasks.terminate',
						nls.localize('TerminateAction.label', "Terminate Running Task"),
						undefined, true, () => { this.runTerminateCommand(); return TPromise.as<void>(undefined); });
J
Johannes Rieken 已提交
1415
				closeAction.closeFunction = this.messageService.show(buildError.severity, { message: buildError.message, actions: [action, closeAction] });
E
Erich Gamma 已提交
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
			} else {
				this.messageService.show(buildError.severity, buildError.message);
			}
		} else if (err instanceof Error) {
			let error = <Error>err;
			this.messageService.show(Severity.Error, error.message);
		} else if (Types.isString(err)) {
			this.messageService.show(Severity.Error, <string>err);
		} else {
			this.messageService.show(Severity.Error, nls.localize('TaskSystem.unknownError', 'An error has occurred while running a task. See task log for details.'));
		}
		if (showOutput) {
1428
			this._outputChannel.show(true);
E
Erich Gamma 已提交
1429 1430
		}
	}
1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446

	private canRunCommand(): boolean {
		if (!this.contextService.hasWorkspace()) {
			this.messageService.show(Severity.Info, nls.localize('TaskService.noWorkspace', 'Tasks are only available on a workspace folder.'));
			return false;
		}
		return true;
	}

	private runTaskCommand(accessor: ServicesAccessor, arg: any): void {
		if (!this.canRunCommand()) {
			return;
		}
		if (Types.isString(arg)) {
			this.tasks().then(tasks => {
				for (let task of tasks) {
D
Dirk Baeumer 已提交
1447
					if (task.identifier === arg) {
1448
						this.run(task);
1449 1450 1451 1452 1453 1454 1455 1456
					}
				}
			});
		} else {
			this.quickOpenService.show('task ');
		}
	}

1457 1458 1459 1460 1461 1462 1463 1464
	private runBuildCommand(): void {
		if (!this.canRunCommand()) {
			return;
		}
		if (!this.inTerminal()) {
			this.build();
			return;
		}
1465 1466 1467 1468 1469
		let options: IProgressOptions = {
			location: ProgressLocation.Window,
			title: nls.localize('TaskService.fetchingBuildTasks', 'Fetching build tasks...')
		};
		let promise = this.getTasksForGroup(TaskGroup.Build).then((tasks) => {
1470
			if (tasks.length === 0) {
1471 1472 1473 1474 1475 1476 1477
				this.messageService.show(
					Severity.Info,
					{
						message: nls.localize('TaskService.noBuildTaskTerminal', 'No Build Task found. Press \'Configure Build Task\' to define one.'),
						actions: [this.configureBuildTask(), new CloseMessageAction()]
					}
				);
1478 1479
				return;
			}
D
Dirk Baeumer 已提交
1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
			let primaries: Task[] = [];
			for (let task of tasks) {
				if (task.isPrimaryGroupEntry) {
					primaries.push(task);
				}
			}
			if (primaries.length === 1) {
				this.run(primaries[0]);
				return;
			}
1490
			this.quickOpenService.show('build task ');
1491
		});
1492
		this.progressService.withProgress(options, () => promise);
1493 1494 1495 1496 1497 1498 1499
	}

	private runTestCommand(): void {
		if (!this.canRunCommand()) {
			return;
		}
		if (!this.inTerminal()) {
1500
			this.runTest();
1501 1502
			return;
		}
1503 1504 1505 1506 1507
		let options: IProgressOptions = {
			location: ProgressLocation.Window,
			title: nls.localize('TaskService.fetchingTestTasks', 'Fetching test tasks...')
		};
		let promise = this.getTasksForGroup(TaskGroup.Test).then((tasks) => {
D
Dirk Baeumer 已提交
1508
			if (tasks.length === 0) {
1509 1510 1511 1512 1513 1514 1515
				this.messageService.show(
					Severity.Info,
					{
						message: nls.localize('TaskService.noTestTaskTerminal', 'No Test Task found. Press \'Configure Task Runner\' to define one.'),
						actions: [this.configureAction(), new CloseMessageAction()]
					}
				);
D
Dirk Baeumer 已提交
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525
				return;
			}
			let primaries: Task[] = [];
			for (let task of tasks) {
				if (task.isPrimaryGroupEntry) {
					primaries.push(task);
				}
			}
			if (primaries.length === 1) {
				this.run(primaries[0]);
1526 1527
				return;
			}
1528
			this.quickOpenService.show('test task ');
1529
		});
1530
		this.progressService.withProgress(options, () => promise);
1531 1532
	}

1533 1534 1535 1536 1537
	private runTerminateCommand(): void {
		if (!this.canRunCommand()) {
			return;
		}
		if (this.inTerminal()) {
1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
			this.getActiveTasks().then((activeTasks) => {
				if (activeTasks.length === 0) {
					return;
				}
				if (activeTasks.length === 1) {
					this.terminate(activeTasks[0]);
				} else {
					this.quickOpenService.show('terminate task ');
				}
			});
1548 1549 1550
		} else {
			this.isActive().then((active) => {
				if (active) {
1551 1552 1553
					this.terminateAll().then((responses) => {
						// the output runner has only one task
						let response = responses[0];
1554
						if (response.success) {
1555 1556 1557
							return;
						}
						if (response.code && response.code === TerminateResponseCode.ProcessNotFound) {
1558 1559
							this.messageService.show(Severity.Error, nls.localize('TerminateAction.noProcess', 'The launched process doesn\'t exist anymore. If the task spawned background tasks exiting VS Code might result in orphaned processes.'));
						} else {
1560
							this.messageService.show(Severity.Error, nls.localize('TerminateAction.failed', 'Failed to terminate running task'));
1561 1562 1563 1564 1565 1566
						}
					});
				}
			});
		}
	}
1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592

	private runRestartTaskCommand(accessor: ServicesAccessor, arg: any): void {
		if (!this.canRunCommand()) {
			return;
		}
		if (this.inTerminal()) {
			this.getActiveTasks().then((activeTasks) => {
				if (activeTasks.length === 0) {
					return;
				}
				if (activeTasks.length === 1) {
					this.restart(activeTasks[0]);
				} else {
					this.quickOpenService.show('restart task ');
				}
			});
		} else {
			this.getActiveTasks().then((activeTasks) => {
				if (activeTasks.length === 0) {
					return;
				}
				let task = activeTasks[0];
				this.restart(task);
			});
		}
	}
E
Erich Gamma 已提交
1593 1594
}

1595

1596
let workbenchActionsRegistry = <IWorkbenchActionRegistry>Registry.as(WorkbenchActionExtensions.WorkbenchActions);
1597
workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(ConfigureTaskRunnerAction, ConfigureTaskRunnerAction.ID, ConfigureTaskRunnerAction.TEXT), 'Tasks: Configure Task Runner', tasksCategory);
1598

1599 1600
MenuRegistry.addCommand({ id: 'workbench.action.tasks.showLog', title: { value: nls.localize('ShowLogAction.label', "Show Task Log"), original: 'Show Task Log' }, category: { value: tasksCategory, original: 'Tasks' } });
MenuRegistry.addCommand({ id: 'workbench.action.tasks.runTask', title: { value: nls.localize('RunTaskAction.label', "Run Task"), original: 'Run Task' }, category: { value: tasksCategory, original: 'Tasks' } });
1601
MenuRegistry.addCommand({ id: 'workbench.action.tasks.restartTask', title: { value: nls.localize('RestartTaskAction.label', "Restart Task"), original: 'Restart Task' }, category: { value: tasksCategory, original: 'Tasks' } });
1602 1603 1604
MenuRegistry.addCommand({ id: 'workbench.action.tasks.terminate', title: { value: nls.localize('TerminateAction.label', "Terminate Running Task"), original: 'Terminate Running Task' }, category: { value: tasksCategory, original: 'Tasks' } });
MenuRegistry.addCommand({ id: 'workbench.action.tasks.build', title: { value: nls.localize('BuildAction.label', "Run Build Task"), original: 'Run Build Task' }, category: { value: tasksCategory, original: 'Tasks' } });
MenuRegistry.addCommand({ id: 'workbench.action.tasks.test', title: { value: nls.localize('TestAction.label', "Run Test Task"), original: 'Run Test Task' }, category: { value: tasksCategory, original: 'Tasks' } });
1605 1606
// MenuRegistry.addCommand( { id: 'workbench.action.tasks.rebuild', title: nls.localize('RebuildAction.label', 'Run Rebuild Task'), category: tasksCategory });
// MenuRegistry.addCommand( { id: 'workbench.action.tasks.clean', title: nls.localize('CleanAction.label', 'Run Clean Task'), category: tasksCategory });
1607 1608 1609 1610 1611

// Task Service
registerSingleton(ITaskService, TaskService);

// Register Quick Open
1612
const quickOpenRegistry = (<IQuickOpenRegistry>Registry.as(QuickOpenExtensions.Quickopen));
1613
const tasksPickerContextKey = 'inTasksPicker';
1614 1615

quickOpenRegistry.registerQuickOpenHandler(
1616 1617 1618 1619
	new QuickOpenHandlerDescriptor(
		'vs/workbench/parts/tasks/browser/taskQuickOpen',
		'QuickOpenHandler',
		'task ',
1620
		tasksPickerContextKey,
1621 1622 1623 1624 1625 1626 1627 1628 1629
		nls.localize('quickOpen.task', "Run Task")
	)
);

quickOpenRegistry.registerQuickOpenHandler(
	new QuickOpenHandlerDescriptor(
		'vs/workbench/parts/tasks/browser/terminateQuickOpen',
		'QuickOpenHandler',
		'terminate task ',
1630
		tasksPickerContextKey,
1631
		nls.localize('quickOpen.terminateTask', "Terminate Task")
1632 1633 1634
	)
);

1635 1636 1637 1638 1639
quickOpenRegistry.registerQuickOpenHandler(
	new QuickOpenHandlerDescriptor(
		'vs/workbench/parts/tasks/browser/restartQuickOpen',
		'QuickOpenHandler',
		'restart task ',
1640
		tasksPickerContextKey,
1641 1642 1643 1644
		nls.localize('quickOpen.restartTask', "Restart Task")
	)
);

1645 1646 1647 1648 1649
quickOpenRegistry.registerQuickOpenHandler(
	new QuickOpenHandlerDescriptor(
		'vs/workbench/parts/tasks/browser/buildQuickOpen',
		'QuickOpenHandler',
		'build task ',
1650
		tasksPickerContextKey,
1651 1652 1653 1654 1655 1656 1657 1658 1659
		nls.localize('quickOpen.buildTask', "Build Task")
	)
);

quickOpenRegistry.registerQuickOpenHandler(
	new QuickOpenHandlerDescriptor(
		'vs/workbench/parts/tasks/browser/testQuickOpen',
		'QuickOpenHandler',
		'test task ',
1660
		tasksPickerContextKey,
1661 1662 1663 1664
		nls.localize('quickOpen.testTask', "Test Task")
	)
);

D
Dirk Baeumer 已提交
1665 1666 1667
const actionBarRegistry = Registry.as<IActionBarRegistry>(ActionBarExtensions.Actionbar);
actionBarRegistry.registerActionBarContributor(Scope.VIEWER, QuickOpenActionContributor);

1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679
// Status bar
let statusbarRegistry = <IStatusbarRegistry>Registry.as(StatusbarExtensions.Statusbar);
statusbarRegistry.registerStatusbarItem(new StatusbarItemDescriptor(StatusBarItem, StatusbarAlignment.LEFT, 50 /* Medium Priority */));

// Output channel
let outputChannelRegistry = <IOutputChannelRegistry>Registry.as(OutputExt.OutputChannels);
outputChannelRegistry.registerChannel(TaskService.OutputChannelId, TaskService.OutputChannelLabel);

// (<IWorkbenchContributionsRegistry>Registry.as(WorkbenchExtensions.Workbench)).registerWorkbenchContribution(TaskServiceParticipant);

// tasks.json validation
let schemaId = 'vscode://schemas/tasks';
D
Dirk Baeumer 已提交
1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690
let schema: IJSONSchema = {
	id: schemaId,
	description: 'Task definition file',
	type: 'object',
	default: {
		version: '0.1.0',
		command: 'myCommand',
		isShellCommand: false,
		args: [],
		showOutput: 'always',
		tasks: [
1691
			{
D
Dirk Baeumer 已提交
1692 1693 1694 1695
				taskName: 'build',
				showOutput: 'silent',
				isBuildCommand: true,
				problemMatcher: ['$tsc', '$lessCompile']
1696 1697
			}
		]
D
Dirk Baeumer 已提交
1698 1699 1700 1701 1702 1703 1704 1705 1706
	}
};

import schemaVersion1 from './jsonSchema_v1';
import schemaVersion2 from './jsonSchema_v2';
schema.definitions = {
	...schemaVersion1.definitions,
	...schemaVersion2.definitions,
};
1707
schema.oneOf = [...schemaVersion2.oneOf, ...schemaVersion1.oneOf];
D
Dirk Baeumer 已提交
1708 1709


1710
let jsonRegistry = <jsonContributionRegistry.IJSONContributionRegistry>Registry.as(jsonContributionRegistry.Extensions.JSONContribution);
1711
jsonRegistry.registerSchema(schemaId, schema);