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

import * as nls from 'vs/nls';

15
import { TPromise } from 'vs/base/common/winjs.base';
E
Erich Gamma 已提交
16 17 18 19 20
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 已提交
21
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
A
Alex Dima 已提交
22
import { EventEmitter } from 'vs/base/common/eventEmitter';
E
Erich Gamma 已提交
23 24 25
import * as Builder from 'vs/base/browser/builder';
import * as Types from 'vs/base/common/types';
import { KeyMod, KeyCode } from 'vs/base/common/keyCodes';
D
Dirk Baeumer 已提交
26
import { TerminateResponse, TerminateResponseCode } from 'vs/base/common/processes';
27
import * as strings from 'vs/base/common/strings';
28
import { ValidationStatus, ValidationState } from 'vs/base/common/parsers';
29
import * as UUID from 'vs/base/common/uuid';
E
Erich Gamma 已提交
30 31 32

import { Registry } from 'vs/platform/platform';
import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle';
33
import { SyncActionDescriptor, MenuRegistry } from 'vs/platform/actions/common/actions';
E
Erich Gamma 已提交
34
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
35
import { IEditor } from 'vs/platform/editor/common/editor';
E
Erich Gamma 已提交
36 37 38
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';
39
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
40
import { IFileService } from 'vs/platform/files/common/files';
A
Alex Dima 已提交
41
import { IExtensionService } from 'vs/platform/extensions/common/extensions';
42
import { CommandsRegistry } from 'vs/platform/commands/common/commands';
43 44
import { KeybindingsRegistry } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
45
import { ProblemMatcherRegistry } from 'vs/platform/markers/common/problemMatcher';
46

E
Erich Gamma 已提交
47 48 49 50

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

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

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

J
Johannes Rieken 已提交
58
import { IQuickOpenService } from 'vs/platform/quickOpen/common/quickOpen';
59
import { IPanelService } from 'vs/workbench/services/panel/common/panelService';
60 61
import Constants from 'vs/workbench/parts/markers/common/constants';
import { IPartService } from 'vs/workbench/services/part/common/partService';
E
Erich Gamma 已提交
62
import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService';
63
import { IConfigurationResolverService } from 'vs/workbench/services/configurationResolver/common/configurationResolver';
64
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
E
Erich Gamma 已提交
65

66
import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
67
import { IOutputService, IOutputChannelRegistry, Extensions as OutputExt, IOutputChannel } from 'vs/workbench/parts/output/common/output';
E
Erich Gamma 已提交
68

69 70
import { ITerminalService } from 'vs/workbench/parts/terminal/common/terminal';

71
import { ITaskSystem, ITaskResolver, ITaskSummary, ITaskExecuteResult, TaskExecuteKind, TaskError, TaskErrors, TaskSystemEvents } from 'vs/workbench/parts/tasks/common/taskSystem';
72
import { Task, TaskSet, TaskGroup, ExecutionEngine, ShowOutput, TaskSourceKind } from 'vs/workbench/parts/tasks/common/tasks';
73
import { ITaskService, TaskServiceEvents, ITaskProvider } from 'vs/workbench/parts/tasks/common/taskService';
D
Dirk Baeumer 已提交
74
import { templates as taskTemplates } from 'vs/workbench/parts/tasks/common/taskTemplates';
E
Erich Gamma 已提交
75

76
import * as TaskConfig from 'vs/workbench/parts/tasks/common/taskConfiguration';
77
import { ProcessTaskSystem } from 'vs/workbench/parts/tasks/node/processTaskSystem';
78
import { TerminalTaskSystem } from './terminalTaskSystem';
J
Johannes Rieken 已提交
79
import { ProcessRunnerDetector } from 'vs/workbench/parts/tasks/node/processRunnerDetector';
80

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

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

86
abstract class OpenTaskConfigurationAction extends Action {
E
Erich Gamma 已提交
87 88 89 90 91 92 93 94

	private configurationService: IConfigurationService;
	private fileService: IFileService;

	private editorService: IWorkbenchEditorService;
	private contextService: IWorkspaceContextService;
	private outputService: IOutputService;
	private messageService: IMessageService;
D
Dirk Baeumer 已提交
95
	private quickOpenService: IQuickOpenService;
E
Erich Gamma 已提交
96 97 98 99

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

		super(id, label);
		this.configurationService = configurationService;
		this.editorService = editorService;
		this.fileService = fileService;
		this.contextService = contextService;
		this.outputService = outputService;
		this.messageService = messageService;
D
Dirk Baeumer 已提交
111
		this.quickOpenService = quickOpenService;
E
Erich Gamma 已提交
112 113
	}

J
Johannes Rieken 已提交
114
	public run(event?: any): TPromise<IEditor> {
B
Benjamin Pasero 已提交
115
		if (!this.contextService.hasWorkspace()) {
116 117 118
			this.messageService.show(Severity.Info, nls.localize('ConfigureTaskRunnerAction.noWorkspace', 'Tasks are only available on a workspace folder.'));
			return TPromise.as(undefined);
		}
E
Erich Gamma 已提交
119
		let sideBySide = !!(event && (event.ctrlKey || event.metaKey));
120
		let configFileCreated = false;
E
Erich Gamma 已提交
121 122
		return this.fileService.resolveFile(this.contextService.toResource('.vscode/tasks.json')).then((success) => {
			return success;
J
Johannes Rieken 已提交
123
		}, (err: any) => {
124
			;
J
Johannes Rieken 已提交
125
			return this.quickOpenService.pick(taskTemplates, { placeHolder: nls.localize('ConfigureTaskRunnerAction.quickPick.template', 'Select a Task Runner') }).then(selection => {
D
Dirk Baeumer 已提交
126 127
				if (!selection) {
					return undefined;
E
Erich Gamma 已提交
128 129
				}
				let contentPromise: TPromise<string>;
D
Dirk Baeumer 已提交
130
				if (selection.autoDetect) {
I
isidor 已提交
131
					const outputChannel = this.outputService.getChannel(TaskService.OutputChannelId);
132
					outputChannel.show(true);
I
isidor 已提交
133
					outputChannel.append(nls.localize('ConfigureTaskRunnerAction.autoDetecting', 'Auto detecting tasks for {0}', selection.id) + '\n');
134
					let detector = new ProcessRunnerDetector(this.fileService, this.contextService, this.configurationResolverService);
135
					contentPromise = detector.detect(false, selection.id).then((value) => {
D
Dirk Baeumer 已提交
136 137 138
						let config = value.config;
						if (value.stderr && value.stderr.length > 0) {
							value.stderr.forEach((line) => {
I
isidor 已提交
139
								outputChannel.append(line + '\n');
D
Dirk Baeumer 已提交
140
							});
141 142 143 144 145 146 147 148
							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) {
149
							if (value.stdout && value.stdout.length > 0) {
I
isidor 已提交
150
								value.stdout.forEach(line => outputChannel.append(line + '\n'));
151
							}
D
Dirk Baeumer 已提交
152 153 154
							let content = JSON.stringify(config, null, '\t');
							content = [
								'{',
J
Johannes Rieken 已提交
155 156
								'\t// See https://go.microsoft.com/fwlink/?LinkId=733558',
								'\t// for the documentation about the tasks.json format',
D
Dirk Baeumer 已提交
157 158 159 160 161
							].join('\n') + content.substr(1);
							return content;
						} else {
							return selection.content;
						}
E
Erich Gamma 已提交
162
					});
D
Dirk Baeumer 已提交
163 164
				} else {
					contentPromise = TPromise.as(selection.content);
E
Erich Gamma 已提交
165
				}
D
Dirk Baeumer 已提交
166
				return contentPromise.then(content => {
167
					let editorConfig = this.configurationService.getConfiguration<any>();
168 169
					if (editorConfig.editor.insertSpaces) {
						content = content.replace(/(\n)(\t+)/g, (_, s1, s2) => s1 + strings.repeat(' ', s2.length * editorConfig.editor.tabSize));
170
					}
171
					configFileCreated = true;
D
Dirk Baeumer 已提交
172
					return this.fileService.createFile(this.contextService.toResource('.vscode/tasks.json'), content);
E
Erich Gamma 已提交
173 174 175
				});
			});
		}).then((stat) => {
D
Dirk Baeumer 已提交
176 177 178 179
			if (!stat) {
				return undefined;
			}
			// // (2) Open editor with configuration file
E
Erich Gamma 已提交
180 181 182
			return this.editorService.openEditor({
				resource: stat.resource,
				options: {
183 184
					forceOpen: true,
					pinned: configFileCreated // pin only if config file is created #8727
E
Erich Gamma 已提交
185
				}
D
Dirk Baeumer 已提交
186
			}, sideBySide);
E
Erich Gamma 已提交
187 188 189 190 191 192
		}, (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."));
		});
	}
}

193 194 195 196 197 198 199 200
class ConfigureTaskRunnerAction extends OpenTaskConfigurationAction {
	public static ID = 'workbench.action.tasks.configureTaskRunner';
	public static TEXT = nls.localize('ConfigureTaskRunnerAction.label', "Configure Task Runner");

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

}

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

	constructor(id: string, label: string, @IConfigurationService configurationService: IConfigurationService,
		@IWorkbenchEditorService editorService: IWorkbenchEditorService, @IFileService fileService: IFileService,
		@IWorkspaceContextService contextService: IWorkspaceContextService, @IOutputService outputService: IOutputService,
		@IMessageService messageService: IMessageService, @IQuickOpenService quickOpenService: IQuickOpenService,
217 218
		@IEnvironmentService environmentService: IEnvironmentService,
		@IConfigurationResolverService configurationResolverService: IConfigurationResolverService) {
J
Johannes Rieken 已提交
219
		super(id, label, configurationService, editorService, fileService, contextService,
220
			outputService, messageService, quickOpenService, environmentService, configurationResolverService);
J
Johannes Rieken 已提交
221
	}
222 223
}

E
Erich Gamma 已提交
224 225 226 227 228 229 230 231 232 233
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);
	}
234
	public run(): TPromise<void> {
E
Erich Gamma 已提交
235 236 237
		if (this.closeFunction) {
			this.closeFunction();
		}
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
		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 已提交
254 255 256
	}
}

257
class StatusBarItem extends Themable implements IStatusbarItem {
E
Erich Gamma 已提交
258 259
	private intervalToken: any;
	private activeCount: number;
J
Johannes Rieken 已提交
260
	private static progressChars: string = '|/-\\';
261 262 263 264 265 266 267 268 269 270 271
	private icons: HTMLElement[];

	constructor(
		@IPanelService private panelService: IPanelService,
		@IMarkerService private markerService: IMarkerService,
		@IOutputService private outputService: IOutputService,
		@ITaskService private taskService: ITaskService,
		@IPartService private partService: IPartService,
		@IThemeService themeService: IThemeService
	) {
		super(themeService);
E
Erich Gamma 已提交
272 273

		this.activeCount = 0;
274
		this.icons = [];
E
Erich Gamma 已提交
275 276
	}

277 278
	protected updateStyles(): void {
		super.updateStyles();
E
Erich Gamma 已提交
279

280 281 282 283
		this.icons.forEach(icon => {
			icon.style.backgroundColor = this.getColor(STATUS_BAR_FOREGROUND);
		});
	}
E
Erich Gamma 已提交
284

285 286 287 288 289 290 291 292 293 294 295 296
	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 已提交
297

298
		Dom.addClass(element, 'task-statusbar-item');
E
Erich Gamma 已提交
299 300 301 302 303 304 305 306

		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 已提交
307
		element.title = nls.localize('problems', "Problems");
E
Erich Gamma 已提交
308

309 310 311 312 313
		Dom.addClass(errorIcon, 'task-statusbar-item-label-error');
		label.appendChild(errorIcon);
		this.icons.push(errorIcon);

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

317 318 319 320 321
		Dom.addClass(warningIcon, 'task-statusbar-item-label-warning');
		label.appendChild(warningIcon);
		this.icons.push(warningIcon);

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

325 326 327 328 329 330
		Dom.addClass(infoIcon, 'task-statusbar-item-label-info');
		label.appendChild(infoIcon);
		this.icons.push(infoIcon);
		$(infoIcon).hide();

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

J
Johannes Rieken 已提交
334 335
		callOnDispose.push(Dom.addDisposableListener(label, 'click', (e: MouseEvent) => {
			const panel = this.panelService.getActivePanel();
336 337 338 339 340
			if (panel && panel.getId() === Constants.MARKERS_PANEL_ID) {
				this.partService.setPanelHidden(true);
			} else {
				this.panelService.openPanel(Constants.MARKERS_PANEL_ID, true);
			}
J
Johannes Rieken 已提交
341
		}));
E
Erich Gamma 已提交
342

343
		let updateStatus = (element: HTMLDivElement, icon: HTMLDivElement, stats: number): boolean => {
E
Erich Gamma 已提交
344 345 346
			if (stats > 0) {
				element.innerHTML = stats.toString();
				$(element).show();
347
				$(icon).show();
E
Erich Gamma 已提交
348 349 350
				return true;
			} else {
				$(element).hide();
351
				$(icon).hide();
E
Erich Gamma 已提交
352 353 354 355 356 357 358 359
				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;
360
			updateStatus(info, infoIcon, stats.infos);
E
Erich Gamma 已提交
361 362 363 364 365 366
		};

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

A
Alex Dima 已提交
367
		callOnDispose.push(this.taskService.addListener(TaskServiceEvents.Active, () => {
E
Erich Gamma 已提交
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
			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();
			}
		}));

A
Alex Dima 已提交
384
		callOnDispose.push(this.taskService.addListener(TaskServiceEvents.Inactive, (data: TaskServiceEventData) => {
385 386 387 388 389 390 391 392 393 394 395
			// 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 已提交
396 397 398
			}
		}));

A
Alex Dima 已提交
399
		callOnDispose.push(this.taskService.addListener(TaskServiceEvents.Terminated, () => {
E
Erich Gamma 已提交
400 401 402 403 404 405 406 407 408 409 410 411
			if (this.activeCount !== 0) {
				$(progress).hide();
				if (this.intervalToken) {
					clearInterval(this.intervalToken);
					this.intervalToken = null;
				}
				this.activeCount = 0;
			}
		}));

		container.appendChild(element);

412 413
		this.updateStyles();

E
Erich Gamma 已提交
414
		return {
415
			dispose: () => {
J
Joao Moreno 已提交
416
				callOnDispose = dispose(callOnDispose);
417
			}
E
Erich Gamma 已提交
418 419 420 421 422 423 424 425
		};
	}
}

interface TaskServiceEventData {
	error?: any;
}

426
class NullTaskSystem extends EventEmitter implements ITaskSystem {
427
	public run(task: Task): ITaskExecuteResult {
428
		return {
429
			kind: TaskExecuteKind.Started,
430 431 432 433 434 435 436 437 438
			promise: TPromise.as<ITaskSummary>({})
		};
	}
	public isActive(): TPromise<boolean> {
		return TPromise.as(false);
	}
	public isActiveSync(): boolean {
		return false;
	}
439 440 441
	public getActiveTasks(): Task[] {
		return [];
	}
442 443 444
	public canAutoTerminate(): boolean {
		return true;
	}
445 446 447 448
	public terminate(task: string | Task): TPromise<TerminateResponse> {
		return TPromise.as<TerminateResponse>({ success: true });
	}
	public terminateAll(): TPromise<TerminateResponse> {
449 450 451 452
		return TPromise.as<TerminateResponse>({ success: true });
	}
}

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
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();
	}
}

490
interface WorkspaceTaskResult {
491
	set: TaskSet;
492 493 494 495
	annotatingTasks: {
		byIdentifier: IStringDictionary<Task>;
		byName: IStringDictionary<Task>;
	};
496 497 498
	hasErrors: boolean;
}

499 500 501 502 503
interface WorkspaceConfigurationResult {
	config: TaskConfig.ExternalTaskRunnerConfiguration;
	hasErrors: boolean;
}

E
Erich Gamma 已提交
504
class TaskService extends EventEmitter implements ITaskService {
505

506
	// private static autoDetectTelemetryName: string = 'taskServer.autoDetect';
507

508
	public _serviceBrand: any;
E
Erich Gamma 已提交
509
	public static SERVICE_ID: string = 'taskService';
J
Johannes Rieken 已提交
510 511
	public static OutputChannelId: string = 'tasks';
	public static OutputChannelLabel: string = nls.localize('tasks', "Tasks");
E
Erich Gamma 已提交
512 513 514 515 516 517 518 519 520 521 522 523

	private modeService: IModeService;
	private configurationService: IConfigurationService;
	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 已提交
524
	private extensionService: IExtensionService;
D
Dirk Baeumer 已提交
525
	private quickOpenService: IQuickOpenService;
E
Erich Gamma 已提交
526

527
	private _configHasErrors: boolean;
528
	private _providers: Map<number, ITaskProvider>;
529 530

	private _workspaceTasksPromise: TPromise<WorkspaceTaskResult>;
531

E
Erich Gamma 已提交
532
	private _taskSystem: ITaskSystem;
533
	private _taskSystemListeners: IDisposable[];
534

535
	private _outputChannel: IOutputChannel;
E
Erich Gamma 已提交
536

J
Johannes Rieken 已提交
537
	constructor( @IModeService modeService: IModeService, @IConfigurationService configurationService: IConfigurationService,
E
Erich Gamma 已提交
538
		@IMarkerService markerService: IMarkerService, @IOutputService outputService: IOutputService,
J
Johannes Rieken 已提交
539 540 541
		@IMessageService messageService: IMessageService, @IWorkbenchEditorService editorService: IWorkbenchEditorService,
		@IFileService fileService: IFileService, @IWorkspaceContextService contextService: IWorkspaceContextService,
		@ITelemetryService telemetryService: ITelemetryService, @ITextFileService textFileService: ITextFileService,
542
		@ILifecycleService lifecycleService: ILifecycleService,
A
Alex Dima 已提交
543
		@IModelService modelService: IModelService, @IExtensionService extensionService: IExtensionService,
544
		@IQuickOpenService quickOpenService: IQuickOpenService,
545
		@IEnvironmentService private environmentService: IEnvironmentService,
546
		@IConfigurationResolverService private configurationResolverService: IConfigurationResolverService,
547 548
		@ITerminalService private terminalService: ITerminalService,
		@IWorkbenchEditorService private workbenchEditorService: IWorkbenchEditorService
549
	) {
E
Erich Gamma 已提交
550 551 552 553 554 555 556 557 558 559 560 561 562

		super();
		this.modeService = modeService;
		this.configurationService = configurationService;
		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 已提交
563
		this.extensionService = extensionService;
D
Dirk Baeumer 已提交
564
		this.quickOpenService = quickOpenService;
E
Erich Gamma 已提交
565

566 567
		this._configHasErrors = false;
		this._workspaceTasksPromise = undefined;
568 569 570
		this._taskSystemListeners = [];
		this._outputChannel = this.outputService.getChannel(TaskService.OutputChannelId);
		this._providers = new Map<number, ITaskProvider>();
J
Johannes Rieken 已提交
571
		this.configurationService.onDidUpdateConfiguration(() => {
572
			if (!this._taskSystem && !this._workspaceTasksPromise) {
573 574
				return;
			}
575
			this.updateWorkspaceTasks();
576 577 578
			if (!this._taskSystem) {
				return;
			}
579 580 581 582 583 584
			let currentExecutionEngine = this._taskSystem instanceof TerminalTaskSystem
				? ExecutionEngine.Terminal
				: this._taskSystem instanceof ProcessTaskSystem
					? ExecutionEngine.Process
					: ExecutionEngine.Unknown;
			if (currentExecutionEngine !== this.getExecutionEngine()) {
585
				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 已提交
586
			}
E
Erich Gamma 已提交
587
		});
588
		lifecycleService.onWillShutdown(event => event.veto(this.beforeShutdown()));
589 590 591 592
		this.registerCommands();
	}

	private registerCommands(): void {
593
		CommandsRegistry.registerCommand('workbench.action.tasks.runTask', (accessor, arg) => {
594 595 596
			this.runTaskCommand(accessor, arg);
		});

597 598 599 600
		CommandsRegistry.registerCommand('workbench.action.tasks.restartTask', (accessor, arg) => {
			this.runRestartTaskCommand(accessor, arg);
		});

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
		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;
			}
			this.build();
		});

		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;
629
			}
630
			this.runTest();
631
		});
E
Erich Gamma 已提交
632 633
	}

634
	private showOutput(): void {
635
		this._outputChannel.show(true);
636 637
	}

E
Erich Gamma 已提交
638
	private disposeTaskSystemListeners(): void {
639
		this._taskSystemListeners = dispose(this._taskSystemListeners);
E
Erich Gamma 已提交
640 641
	}

642 643 644 645
	public registerTaskProvider(handle: number, provider: ITaskProvider): void {
		if (!provider) {
			return;
		}
646
		this._providers.set(handle, provider);
647 648 649
	}

	public unregisterTaskProvider(handle: number): boolean {
650
		return this._providers.delete(handle);
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
	}

	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();
	}

670 671 672 673 674 675 676 677
	public getActiveTasks(): TPromise<Task[]> {
		if (!this._taskSystem) {
			return TPromise.as([]);
		}
		return TPromise.as(this._taskSystem.getActiveTasks());
	}


678 679
	public build(): TPromise<ITaskSummary> {
		return this.getTaskSets().then((values) => {
680
			let runnable = this.createRunnableTask(values, TaskGroup.Build);
681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
			if (!runnable || !runnable.task) {
				throw new TaskError(Severity.Info, nls.localize('TaskService.noBuildTask', 'No build task defined. Mark a task with \'isBuildCommand\' in the tasks.json file.'), TaskErrors.NoBuildTask);
			}
			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) => {
701
			let runnable = this.createRunnableTask(values, TaskGroup.Test);
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
			if (!runnable || !runnable.task) {
				throw new TaskError(Severity.Info, nls.localize('TaskService.noTestTask', 'No test task defined. Mark a task with \'isTestCommand\' in the tasks.json file.'), TaskErrors.NoTestTask);
			}
			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);
720
			} else {
721 722 723 724 725 726 727
				requested = task.name;
				toExecute = resolver.resolve(task._id);
			}
			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);
728
			}
729 730 731 732 733 734
		}).then(value => value, (error) => {
			this.handleError(error);
			return TPromise.wrapError(error);
		});
	}

735
	private createRunnableTask(sets: TaskSet[], group: TaskGroup): { task: Task; resolver: ITaskResolver } {
736 737 738
		let uuidMap: IStringDictionary<Task> = Object.create(null);
		let identifierMap: IStringDictionary<Task> = Object.create(null);

739
		let primaryTasks: Task[] = [];
740 741 742 743
		sets.forEach((set) => {
			set.tasks.forEach((task) => {
				uuidMap[task._id] = task;
				identifierMap[task.identifier] = task;
744 745 746
				if (group && task.group === group) {
					primaryTasks.push(task);
				}
747 748
			});
		});
749
		if (primaryTasks.length === 0) {
750 751 752 753 754 755 756 757 758 759 760
			return undefined;
		}
		let resolver: ITaskResolver = {
			resolve: (id: string) => {
				let result = uuidMap[id];
				if (result) {
					return result;
				}
				return identifierMap[id];
			}
		};
761 762
		if (primaryTasks.length === 1) {
			return { task: primaryTasks[0], resolver };
763 764 765 766
		} else {
			let id: string = UUID.generateUuid();
			let task: Task = {
				_id: id,
767
				_source: { kind: TaskSourceKind.Generic },
768 769
				name: id,
				identifier: id,
770
				dependsOn: primaryTasks.map(task => task._id),
771 772 773 774
				command: undefined,
				showOutput: ShowOutput.Never
			};
			return { task, resolver };
E
Erich Gamma 已提交
775 776 777
		}
	}

778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
	private createResolver(sets: TaskSet[]): ITaskResolver {
		let uuidMap: IStringDictionary<Task> = Object.create(null);
		let identifierMap: IStringDictionary<Task> = Object.create(null);

		sets.forEach((set) => {
			set.tasks.forEach((task) => {
				uuidMap[task._id] = task;
				identifierMap[task.identifier] = task;
			});
		});
		return {
			resolve: (id: string) => {
				let result = uuidMap[id];
				if (result) {
					return result;
793
				}
794
				return identifierMap[id];
795
			}
796 797 798 799
		};
	}

	private executeTask(task: Task, resolver: ITaskResolver): TPromise<ITaskSummary> {
800 801 802 803 804 805 806 807 808 809
		return ProblemMatcherRegistry.onReady().then(() => {
			return this.textFileService.saveAll().then((value) => { // make sure all dirty files are saved
				let executeResult = this.getTaskSystem().run(task, resolver);
				if (executeResult.kind === TaskExecuteKind.Active) {
					let active = executeResult.active;
					if (active.same && active.background) {
						this.messageService.show(Severity.Info, nls.localize('TaskSystem.activeSame', 'The task is already active and in watch mode. To terminate the task use `F1 > terminate task`'));
					} 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);
					}
810
				}
811 812
				return executeResult.promise;
			});
813 814 815
		});
	}

816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831
	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;
		});
	}

832
	public terminate(task: string | Task): TPromise<TerminateResponse> {
833 834 835
		if (!this._taskSystem) {
			return TPromise.as({ success: true });
		}
836 837
		const id: string = Types.isString(task) ? task : task._id;
		return this._taskSystem.terminate(id).then((response) => {
838 839 840
			if (response.success) {
				this.emit(TaskServiceEvents.Terminated, {});
			}
841 842 843 844 845 846 847 848 849
			return response;
		});
	}

	public terminateAll(): TPromise<TerminateResponse> {
		if (!this._taskSystem) {
			return TPromise.as({ success: true });
		}
		return this._taskSystem.terminateAll().then((response) => {
850 851 852 853 854 855 856 857 858 859 860 861 862 863
			this.emit(TaskServiceEvents.Terminated, {});
			return response;
		});
	}

	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,
864
				this.workbenchEditorService,
865 866 867 868 869 870 871 872 873 874
				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 已提交
875 876
		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)));
877 878 879 880 881 882 883 884
		return this._taskSystem;
	}

	private getTaskSets(): TPromise<TaskSet[]> {
		return new TPromise<TaskSet[]>((resolve, reject) => {
			let result: TaskSet[] = [];
			let counter: number = 0;
			let done = (value: TaskSet) => {
885 886 887
				if (value) {
					result.push(value);
				}
888 889 890 891 892 893 894 895 896
				if (--counter === 0) {
					resolve(result);
				}
			};
			let error = () => {
				if (--counter === 0) {
					resolve(result);
				}
			};
897
			if (this.getExecutionEngine() === ExecutionEngine.Terminal && this._providers.size > 0) {
898
				this._providers.forEach((provider) => {
899 900 901
					counter++;
					provider.provideTasks().done(done, error);
				});
902 903
			} else {
				resolve(result);
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
		}).then((result) => {
			return this.getWorkspaceTasks().then((workspaceTaskResult) => {
				let workspaceTasksToDelete: Task[] = [];
				let annotatingTasks = workspaceTaskResult.annotatingTasks;
				let legacyAnnotatingTasks = workspaceTaskResult.set ? this.getLegacyAnnotatingTasks(workspaceTaskResult.set) : undefined;
				if (annotatingTasks || legacyAnnotatingTasks) {
					for (let set of result) {
						for (let task of set.tasks) {
							if (annotatingTasks) {
								let annotatingTask = annotatingTasks.byIdentifier[task.identifier] || annotatingTasks.byName[task.name];
								if (annotatingTask) {
									TaskConfig.mergeTasks(task, annotatingTask);
									task._source.kind = TaskSourceKind.Workspace;
									continue;
								}
							}
							if (legacyAnnotatingTasks) {
								let legacyAnnotatingTask = legacyAnnotatingTasks[task.identifier];
								if (legacyAnnotatingTask) {
									TaskConfig.mergeTasks(task, legacyAnnotatingTask);
									task._source.kind = TaskSourceKind.Workspace;
									workspaceTasksToDelete.push(legacyAnnotatingTask);
									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;
			});
955 956 957
		});
	}

958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978
	private getLegacyAnnotatingTasks(workspaceTasks: TaskSet): IStringDictionary<Task> {
		let result: IStringDictionary<Task>;
		function getResult() {
			if (result) {
				return result;
			}
			result = Object.create(null);
			return result;
		}
		for (let task of workspaceTasks.tasks) {
			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') {
				getResult()[`${commandName}.${task.name}`] = task;
			}
		}
		return result;
	}

	private getWorkspaceTasks(): TPromise<WorkspaceTaskResult> {
979 980 981
		if (this._workspaceTasksPromise) {
			return this._workspaceTasksPromise;
		}
982
		this.updateWorkspaceTasks();
983 984 985 986 987 988
		return this._workspaceTasksPromise;
	}

	private updateWorkspaceTasks(): void {
		this._workspaceTasksPromise = this.computeWorkspaceTasks().then(value => {
			this._configHasErrors = value.hasErrors;
989 990 991 992
			if (this._taskSystem instanceof ProcessTaskSystem) {
				this._taskSystem.hasErrors(this._configHasErrors);
			}
			return value;
993 994 995 996
		});
	}

	private computeWorkspaceTasks(): TPromise<WorkspaceTaskResult> {
997
		let configPromise: TPromise<WorkspaceConfigurationResult>;
998 999 1000
		{
			let { config, hasParseErrors } = this.getConfiguration();
			if (hasParseErrors) {
1001
				return TPromise.as({ set: undefined, hasErrors: true });
1002 1003 1004 1005
			}
			if (config) {
				let engine = TaskConfig.ExecutionEngine.from(config);
				if (engine === ExecutionEngine.Process && this.hasDetectorSupport(config)) {
1006
					configPromise = new ProcessRunnerDetector(this.fileService, this.contextService, this.configurationResolverService, config).detect(true).then((value): WorkspaceConfigurationResult => {
1007 1008 1009
						let hasErrors = this.printStderr(value.stderr);
						let detectedConfig = value.config;
						if (!detectedConfig) {
1010
							return { config, hasErrors };
1011
						}
1012 1013 1014 1015 1016
						let result: TaskConfig.ExternalTaskRunnerConfiguration = Objects.clone(config);
						let configuredTasks: IStringDictionary<TaskConfig.TaskDescription> = Object.create(null);
						if (!result.tasks) {
							if (detectedConfig.tasks) {
								result.tasks = detectedConfig.tasks;
1017
							}
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
						} 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 {
					configPromise = TPromise.as({ config, hasErrors: false });
				}
1031
			} else {
1032 1033 1034 1035
				configPromise = new ProcessRunnerDetector(this.fileService, this.contextService, this.configurationResolverService).detect(true).then((value) => {
					let hasErrors = this.printStderr(value.stderr);
					return { config: value.config, hasErrors };
				});
1036 1037
			}
		}
1038
		return configPromise.then((resolved) => {
1039
			return ProblemMatcherRegistry.onReady().then((): WorkspaceTaskResult => {
1040
				if (!resolved || !resolved.config) {
1041
					return { set: undefined, annotatingTasks: undefined, hasErrors: resolved !== void 0 ? resolved.hasErrors : false };
1042
				}
1043
				let problemReporter = new ProblemReporter(this._outputChannel);
1044
				let parseResult = TaskConfig.parse(resolved.config, problemReporter);
1045 1046 1047 1048 1049 1050 1051
				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.'));
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
					return { set: undefined, annotatingTasks: undefined, hasErrors };
				}
				let annotatingTasks: { byIdentifier: IStringDictionary<Task>; byName: IStringDictionary<Task>; };
				if (parseResult.annotatingTasks && parseResult.annotatingTasks.length > 0) {
					annotatingTasks = {
						byIdentifier: Object.create(null),
						byName: Object.create(null)
					};
					for (let task of parseResult.annotatingTasks) {
						annotatingTasks.byIdentifier[task.identifier] = task;
						if (task.name) {
							annotatingTasks.byName[task.name] = task;
						}
					}
1066
				}
1067
				return { set: { tasks: parseResult.tasks }, annotatingTasks: annotatingTasks, hasErrors };
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
			});
		});
	}

	private getExecutionEngine(): ExecutionEngine {
		let { config } = this.getConfiguration();
		if (!config) {
			return ExecutionEngine.Process;
		}
		return TaskConfig.ExecutionEngine.from(config);
	}

	private getConfiguration(): { config: TaskConfig.ExternalTaskRunnerConfiguration; hasParseErrors: boolean } {
		let result = this.configurationService.getConfiguration<TaskConfig.ExternalTaskRunnerConfiguration>('tasks');
		if (!result) {
1083
			return { config: undefined, hasParseErrors: false };
1084 1085 1086 1087 1088 1089 1090 1091 1092
		}
		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;
				}
1093
			}
1094
			if (isAffected) {
1095
				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'));
1096
				this.showOutput();
1097
				return { config: undefined, hasParseErrors: true };
1098
			}
1099 1100
		}
		return { config: result, hasParseErrors: false };
1101 1102
	}

E
Erich Gamma 已提交
1103
	private printStderr(stderr: string[]): boolean {
1104
		let result = false;
E
Erich Gamma 已提交
1105 1106
		if (stderr && stderr.length > 0) {
			stderr.forEach((line) => {
1107
				result = true;
1108
				this._outputChannel.append(line + '\n');
E
Erich Gamma 已提交
1109
			});
1110
			this._outputChannel.show(true);
E
Erich Gamma 已提交
1111 1112 1113 1114
		}
		return result;
	}

1115
	public inTerminal(): boolean {
1116
		return this._taskSystem instanceof TerminalTaskSystem;
1117 1118
	}

1119
	private hasDetectorSupport(config: TaskConfig.ExternalTaskRunnerConfiguration): boolean {
E
Erich Gamma 已提交
1120 1121 1122 1123 1124 1125
		if (!config.command) {
			return false;
		}
		return ProcessRunnerDetector.supports(config.command);
	}

1126 1127 1128
	public configureAction(): Action {
		return new ConfigureTaskRunnerAction(ConfigureTaskRunnerAction.ID, ConfigureTaskRunnerAction.TEXT,
			this.configurationService, this.editorService, this.fileService, this.contextService,
1129
			this.outputService, this.messageService, this.quickOpenService, this.environmentService, this.configurationResolverService);
1130 1131
	}

1132 1133 1134
	private configureBuildTask(): Action {
		return new ConfigureBuildTaskAction(ConfigureBuildTaskAction.ID, ConfigureBuildTaskAction.TEXT,
			this.configurationService, this.editorService, this.fileService, this.contextService,
1135
			this.outputService, this.messageService, this.quickOpenService, this.environmentService, this.configurationResolverService);
1136 1137
	}

E
Erich Gamma 已提交
1138 1139
	public beforeShutdown(): boolean | TPromise<boolean> {
		if (this._taskSystem && this._taskSystem.isActiveSync()) {
D
Dirk Baeumer 已提交
1140
			if (this._taskSystem.canAutoTerminate() || this.messageService.confirm({
E
Erich Gamma 已提交
1141
				message: nls.localize('TaskSystem.runningTask', 'There is a task running. Do you want to terminate it?'),
B
Benjamin Pasero 已提交
1142
				primaryButton: nls.localize({ key: 'TaskSystem.terminateTask', comment: ['&& denotes a mnemonic'] }, "&&Terminate Task")
E
Erich Gamma 已提交
1143
			})) {
1144
				return this._taskSystem.terminateAll().then((response) => {
E
Erich Gamma 已提交
1145 1146 1147 1148 1149
					if (response.success) {
						this.emit(TaskServiceEvents.Terminated, {});
						this._taskSystem = null;
						this.disposeTaskSystemListeners();
						return false; // no veto
D
Dirk Baeumer 已提交
1150 1151 1152 1153 1154
					} else if (response.code && response.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")
						});
E
Erich Gamma 已提交
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
					}
					return true; // veto
				}, (err) => {
					return true; // veto
				});
			} else {
				return true; // veto
			}
		}
		return false; // Nothing to do here
	}

1167
	private getConfigureAction(code: TaskErrors): Action {
J
Johannes Rieken 已提交
1168
		switch (code) {
1169 1170 1171 1172 1173 1174
			case TaskErrors.NoBuildTask:
				return this.configureBuildTask();
			default:
				return this.configureAction();
		}
	}
1175

J
Johannes Rieken 已提交
1176
	private handleError(err: any): void {
E
Erich Gamma 已提交
1177 1178 1179
		let showOutput = true;
		if (err instanceof TaskError) {
			let buildError = <TaskError>err;
1180 1181 1182
			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 已提交
1183
				let closeAction = new CloseMessageAction();
1184
				let action: Action = needsConfig
1185
					? this.getConfigureAction(buildError.code)
1186 1187 1188 1189
					: 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 已提交
1190
				closeAction.closeFunction = this.messageService.show(buildError.severity, { message: buildError.message, actions: [action, closeAction] });
E
Erich Gamma 已提交
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
			} 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) {
1203
			this._outputChannel.show(true);
E
Erich Gamma 已提交
1204 1205
		}
	}
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221

	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 已提交
1222
					if (task.identifier === arg) {
1223
						this.run(task);
1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
					}
				}
			});
		} else {
			this.quickOpenService.show('task ');
		}
	}

	private runTerminateCommand(): void {
		if (!this.canRunCommand()) {
			return;
		}
		if (this.inTerminal()) {
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
			this.getActiveTasks().then((activeTasks) => {
				if (activeTasks.length === 0) {
					return;
				}
				if (activeTasks.length === 1) {
					this.terminate(activeTasks[0]);
				} else {
					this.quickOpenService.show('terminate task ');
				}
			});
1247 1248 1249
		} else {
			this.isActive().then((active) => {
				if (active) {
1250
					this.terminateAll().then((response) => {
1251
						if (response.success) {
1252 1253 1254
							return;
						}
						if (response.code && response.code === TerminateResponseCode.ProcessNotFound) {
1255 1256
							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 {
1257
							this.messageService.show(Severity.Error, nls.localize('TerminateAction.failed', 'Failed to terminate running task'));
1258 1259 1260 1261 1262 1263
						}
					});
				}
			});
		}
	}
1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289

	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 已提交
1290 1291
}

1292

1293
let workbenchActionsRegistry = <IWorkbenchActionRegistry>Registry.as(WorkbenchActionExtensions.WorkbenchActions);
1294
workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(ConfigureTaskRunnerAction, ConfigureTaskRunnerAction.ID, ConfigureTaskRunnerAction.TEXT), 'Configure Task Runner', tasksCategory);
1295

1296 1297
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' } });
1298
MenuRegistry.addCommand({ id: 'workbench.action.tasks.restartTask', title: { value: nls.localize('RestartTaskAction.label', "Restart Task"), original: 'Restart Task' }, category: { value: tasksCategory, original: 'Tasks' } });
1299 1300 1301
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' } });
1302 1303
// 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 });
1304 1305 1306 1307 1308

// Task Service
registerSingleton(ITaskService, TaskService);

// Register Quick Open
1309 1310 1311
const quickOpenRegistry = (<IQuickOpenRegistry>Registry.as(QuickOpenExtensions.Quickopen));

quickOpenRegistry.registerQuickOpenHandler(
1312 1313 1314 1315
	new QuickOpenHandlerDescriptor(
		'vs/workbench/parts/tasks/browser/taskQuickOpen',
		'QuickOpenHandler',
		'task ',
1316 1317 1318 1319 1320 1321 1322 1323 1324 1325
		nls.localize('quickOpen.task', "Run Task")
	)
);

quickOpenRegistry.registerQuickOpenHandler(
	new QuickOpenHandlerDescriptor(
		'vs/workbench/parts/tasks/browser/terminateQuickOpen',
		'QuickOpenHandler',
		'terminate task ',
		nls.localize('quickOpen.terminateTask', "Terminate Task")
1326 1327 1328
	)
);

1329 1330 1331 1332 1333 1334 1335 1336 1337
quickOpenRegistry.registerQuickOpenHandler(
	new QuickOpenHandlerDescriptor(
		'vs/workbench/parts/tasks/browser/restartQuickOpen',
		'QuickOpenHandler',
		'restart task ',
		nls.localize('quickOpen.restartTask', "Restart Task")
	)
);

1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
// 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 已提交
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
let schema: IJSONSchema = {
	id: schemaId,
	description: 'Task definition file',
	type: 'object',
	default: {
		version: '0.1.0',
		command: 'myCommand',
		isShellCommand: false,
		args: [],
		showOutput: 'always',
		tasks: [
1361
			{
D
Dirk Baeumer 已提交
1362 1363 1364 1365
				taskName: 'build',
				showOutput: 'silent',
				isBuildCommand: true,
				problemMatcher: ['$tsc', '$lessCompile']
1366 1367
			}
		]
D
Dirk Baeumer 已提交
1368 1369 1370 1371 1372
	}
};

import schemaVersion1 from './jsonSchema_v1';
import schemaVersion2 from './jsonSchema_v2';
1373 1374
import { Themable, STATUS_BAR_FOREGROUND } from 'vs/workbench/common/theme';
import { IThemeService } from 'vs/platform/theme/common/themeService';
D
Dirk Baeumer 已提交
1375 1376 1377 1378 1379 1380 1381
schema.definitions = {
	...schemaVersion1.definitions,
	...schemaVersion2.definitions,
};
schema.oneOf = [...schemaVersion1.oneOf, ...schemaVersion2.oneOf];


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