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

import 'vs/css!./media/task.contribution';
import 'vs/workbench/parts/tasks/browser/taskQuickOpen';

import * as nls from 'vs/nls';

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

31
import { Registry } from 'vs/platform/registry/common/platform';
E
Erich Gamma 已提交
32
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, NamedProblemMatcher } from 'vs/platform/markers/common/problemMatcher';
46
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
47
import { IProgressService2, IProgressOptions, ProgressLocation } from 'vs/platform/progress/common/progress';
48
import { IOpenerService } from 'vs/platform/opener/common/opener';
49 50
import { IWindowService } from 'vs/platform/windows/common/windows';

E
Erich Gamma 已提交
51 52 53 54

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

55

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

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

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

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

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

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

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

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

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

94 95
import { ReloadWindowAction } from 'vs/workbench/electron-browser/actions';

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

99
abstract class OpenTaskConfigurationAction extends Action {
E
Erich Gamma 已提交
100

101 102 103 104 105 106 107 108
	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,
109 110
		private extensionService: IExtensionService,
		private telemetryService: ITelemetryService) {
E
Erich Gamma 已提交
111 112 113 114

		super(id, label);
	}

J
Johannes Rieken 已提交
115
	public run(event?: any): TPromise<IEditor> {
116
		if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) {
117 118 119
			this.messageService.show(Severity.Info, nls.localize('ConfigureTaskRunnerAction.noWorkspace', 'Tasks are only available on a workspace folder.'));
			return TPromise.as(undefined);
		}
E
Erich Gamma 已提交
120
		let sideBySide = !!(event && (event.ctrlKey || event.metaKey));
121
		let configFileCreated = false;
122
		return this.fileService.resolveFile(this.contextService.toResource('.vscode/tasks.json', this.contextService.getWorkspace().folders[0])).then((success) => { // TODO@Dirk (https://github.com/Microsoft/vscode/issues/29454)
123

E
Erich Gamma 已提交
124
			return success;
J
Johannes Rieken 已提交
125 126
		}, (err: any) => {
			return this.quickOpenService.pick(taskTemplates, { placeHolder: nls.localize('ConfigureTaskRunnerAction.quickPick.template', 'Select a Task Runner') }).then(selection => {
D
Dirk Baeumer 已提交
127 128
				if (!selection) {
					return undefined;
E
Erich Gamma 已提交
129
				}
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
				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;
173
					return this.fileService.createFile(this.contextService.toResource('.vscode/tasks.json', this.contextService.getWorkspace().folders[0]), content).then((result) => {
174 175 176 177 178 179
						this.telemetryService.publicLog(TaskService.TemplateTelemetryEventName, {
							templateId: selection.id,
							autoDetect: selection.autoDetect
						});
						return result;
					}); // TODO@Dirk (https://github.com/Microsoft/vscode/issues/29454)
180 181
				});
				/* 2.0 version
D
Dirk Baeumer 已提交
182 183 184 185
				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 已提交
186
				}
D
Dirk Baeumer 已提交
187 188
				configFileCreated = true;
				return this.fileService.createFile(this.contextService.toResource('.vscode/tasks.json'), content);
189
				*/
E
Erich Gamma 已提交
190 191
			});
		}).then((stat) => {
D
Dirk Baeumer 已提交
192 193 194 195
			if (!stat) {
				return undefined;
			}
			// // (2) Open editor with configuration file
E
Erich Gamma 已提交
196 197 198
			return this.editorService.openEditor({
				resource: stat.resource,
				options: {
199 200
					forceOpen: true,
					pinned: configFileCreated // pin only if config file is created #8727
E
Erich Gamma 已提交
201
				}
D
Dirk Baeumer 已提交
202
			}, sideBySide);
E
Erich Gamma 已提交
203 204 205 206 207 208
		}, (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."));
		});
	}
}

209 210 211 212
class ConfigureTaskRunnerAction extends OpenTaskConfigurationAction {
	public static ID = 'workbench.action.tasks.configureTaskRunner';
	public static TEXT = nls.localize('ConfigureTaskRunnerAction.label', "Configure Task Runner");

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

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

232
	constructor(id: string, label: string,
233
		@ITaskService taskService: ITaskService, @IConfigurationService configurationService: IConfigurationService,
234 235 236
		@IWorkbenchEditorService editorService: IWorkbenchEditorService, @IFileService fileService: IFileService,
		@IWorkspaceContextService contextService: IWorkspaceContextService, @IOutputService outputService: IOutputService,
		@IMessageService messageService: IMessageService, @IQuickOpenService quickOpenService: IQuickOpenService,
237
		@IEnvironmentService environmentService: IEnvironmentService,
238
		@IConfigurationResolverService configurationResolverService: IConfigurationResolverService,
239 240
		@IExtensionService extensionService: IExtensionService,
		@ITelemetryService telemetryService: ITelemetryService) {
241 242
		super(id, label, taskService, configurationService, editorService, fileService, contextService,
			outputService, messageService, quickOpenService, environmentService, configurationResolverService,
243
			extensionService, telemetryService);
J
Johannes Rieken 已提交
244
	}
245 246
}

E
Erich Gamma 已提交
247 248 249 250 251 252 253 254 255 256
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);
	}
257
	public run(): TPromise<void> {
E
Erich Gamma 已提交
258 259 260
		if (this.closeFunction) {
			this.closeFunction();
		}
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
		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 已提交
277 278 279
	}
}

280
class BuildStatusBarItem extends Themable implements IStatusbarItem {
E
Erich Gamma 已提交
281 282
	private intervalToken: any;
	private activeCount: number;
J
Johannes Rieken 已提交
283
	private static progressChars: string = '|/-\\';
284 285 286 287 288 289 290 291
	private icons: HTMLElement[];

	constructor(
		@IPanelService private panelService: IPanelService,
		@IMarkerService private markerService: IMarkerService,
		@IOutputService private outputService: IOutputService,
		@ITaskService private taskService: ITaskService,
		@IPartService private partService: IPartService,
292 293
		@IThemeService themeService: IThemeService,
		@IWorkspaceContextService private contextService: IWorkspaceContextService
294 295
	) {
		super(themeService);
E
Erich Gamma 已提交
296 297

		this.activeCount = 0;
298
		this.icons = [];
B
Benjamin Pasero 已提交
299 300 301 302 303

		this.registerListeners();
	}

	private registerListeners(): void {
S
Sandeep Somavarapu 已提交
304
		this.toUnbind.push(this.contextService.onDidChangeWorkspaceFolders(() => this.updateStyles()));
E
Erich Gamma 已提交
305 306
	}

307 308
	protected updateStyles(): void {
		super.updateStyles();
E
Erich Gamma 已提交
309

310
		this.icons.forEach(icon => {
311
			icon.style.backgroundColor = this.getColor(this.contextService.getWorkbenchState() !== WorkbenchState.EMPTY ? STATUS_BAR_FOREGROUND : STATUS_BAR_NO_FOLDER_FOREGROUND);
312 313
		});
	}
E
Erich Gamma 已提交
314

315 316 317 318 319 320 321 322 323 324 325 326
	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 已提交
327

328
		Dom.addClass(element, 'task-statusbar-item');
E
Erich Gamma 已提交
329 330 331

		Dom.addClass(progress, 'task-statusbar-item-progress');
		element.appendChild(progress);
332
		progress.innerHTML = BuildStatusBarItem.progressChars[0];
E
Erich Gamma 已提交
333 334 335 336
		$(progress).hide();

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

339
		Dom.addClass(errorIcon, 'task-statusbar-item-label-error');
340
		Dom.addClass(errorIcon, 'mask-icon');
341 342 343 344
		label.appendChild(errorIcon);
		this.icons.push(errorIcon);

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

348
		Dom.addClass(warningIcon, 'task-statusbar-item-label-warning');
349
		Dom.addClass(warningIcon, 'mask-icon');
350 351 352 353
		label.appendChild(warningIcon);
		this.icons.push(warningIcon);

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

357
		Dom.addClass(infoIcon, 'task-statusbar-item-label-info');
358
		Dom.addClass(infoIcon, 'mask-icon');
359 360 361 362 363
		label.appendChild(infoIcon);
		this.icons.push(infoIcon);
		$(infoIcon).hide();

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

J
Johannes Rieken 已提交
367 368
		callOnDispose.push(Dom.addDisposableListener(label, 'click', (e: MouseEvent) => {
			const panel = this.panelService.getActivePanel();
369 370 371 372 373
			if (panel && panel.getId() === Constants.MARKERS_PANEL_ID) {
				this.partService.setPanelHidden(true);
			} else {
				this.panelService.openPanel(Constants.MARKERS_PANEL_ID, true);
			}
J
Johannes Rieken 已提交
374
		}));
E
Erich Gamma 已提交
375

376
		let updateStatus = (element: HTMLDivElement, icon: HTMLDivElement, stats: number): boolean => {
E
Erich Gamma 已提交
377 378 379
			if (stats > 0) {
				element.innerHTML = stats.toString();
				$(element).show();
380
				$(icon).show();
E
Erich Gamma 已提交
381 382 383
				return true;
			} else {
				$(element).hide();
384
				$(icon).hide();
E
Erich Gamma 已提交
385 386 387 388 389 390 391 392
				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;
393
			updateStatus(info, infoIcon, stats.infos);
E
Erich Gamma 已提交
394 395 396 397 398 399
		};

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

400
		callOnDispose.push(this.taskService.addListener(TaskServiceEvents.Active, (event: TaskEvent) => {
401
			if (this.ignoreEvent(event)) {
402 403
				return;
			}
E
Erich Gamma 已提交
404 405 406
			this.activeCount++;
			if (this.activeCount === 1) {
				let index = 1;
407
				let chars = BuildStatusBarItem.progressChars;
E
Erich Gamma 已提交
408 409 410 411 412 413 414 415 416 417 418 419
				progress.innerHTML = chars[0];
				this.intervalToken = setInterval(() => {
					progress.innerHTML = chars[index];
					index++;
					if (index >= chars.length) {
						index = 0;
					}
				}, 50);
				$(progress).show();
			}
		}));

420
		callOnDispose.push(this.taskService.addListener(TaskServiceEvents.Inactive, (event: TaskEvent) => {
421
			if (this.ignoreEvent(event)) {
422 423
				return;
			}
424 425 426 427 428 429 430 431 432 433 434
			// 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 已提交
435 436 437
			}
		}));

438
		callOnDispose.push(this.taskService.addListener(TaskServiceEvents.Terminated, (event: TaskEvent) => {
439
			if (this.ignoreEvent(event)) {
440 441
				return;
			}
E
Erich Gamma 已提交
442 443 444 445 446 447 448 449 450 451 452 453
			if (this.activeCount !== 0) {
				$(progress).hide();
				if (this.intervalToken) {
					clearInterval(this.intervalToken);
					this.intervalToken = null;
				}
				this.activeCount = 0;
			}
		}));

		container.appendChild(element);

454 455
		this.updateStyles();

E
Erich Gamma 已提交
456
		return {
457
			dispose: () => {
J
Joao Moreno 已提交
458
				callOnDispose = dispose(callOnDispose);
459
			}
E
Erich Gamma 已提交
460 461
		};
	}
462 463 464 465 466 467 468 469 470 471 472 473 474

	private ignoreEvent(event: TaskEvent): boolean {
		if (!this.taskService.inTerminal()) {
			return false;
		}
		if (event.group !== TaskGroup.Build) {
			return true;
		}
		if (!event.__task) {
			return false;
		}
		return event.__task.problemMatchers === void 0 || event.__task.problemMatchers.length === 0;
	}
E
Erich Gamma 已提交
475 476
}

477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
class TaskStatusBarItem extends Themable implements IStatusbarItem {

	constructor(
		@IPanelService private panelService: IPanelService,
		@IMarkerService private markerService: IMarkerService,
		@IOutputService private outputService: IOutputService,
		@ITaskService private taskService: ITaskService,
		@IPartService private partService: IPartService,
		@IThemeService themeService: IThemeService,
		@IWorkspaceContextService private contextService: IWorkspaceContextService,
	) {
		super(themeService);
	}

	protected updateStyles(): void {
		super.updateStyles();
	}

	public render(container: HTMLElement): IDisposable {
496

497
		let callOnDispose: IDisposable[] = [];
498 499
		const element = document.createElement('a');
		Dom.addClass(element, 'task-statusbar-runningItem');
500

501 502 503
		let labelElement = document.createElement('div');
		Dom.addClass(labelElement, 'task-statusbar-runningItem-label');
		element.appendChild(labelElement);
504

505 506
		let label = new OcticonLabel(labelElement);
		label.title = nls.localize('runningTasks', "Show Running Tasks");
507

508
		$(element).hide();
509

510
		callOnDispose.push(Dom.addDisposableListener(labelElement, 'click', (e: MouseEvent) => {
511 512 513 514 515 516
			(this.taskService as TaskService).runShowTasks();
		}));

		let updateStatus = (): void => {
			this.taskService.getActiveTasks().then(tasks => {
				if (tasks.length === 0) {
517
					$(element).hide();
518
				} else {
519 520
					label.text = `$(tools) ${tasks.length}`;
					$(element).show();
521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
				}
			});
		};

		callOnDispose.push(this.taskService.addListener(TaskServiceEvents.Changed, (event: TaskEvent) => {
			updateStatus();
		}));

		container.appendChild(element);

		this.updateStyles();
		updateStatus();

		return {
			dispose: () => {
				callOnDispose = dispose(callOnDispose);
			}
		};
	}
}

E
Erich Gamma 已提交
542 543 544 545
interface TaskServiceEventData {
	error?: any;
}

546
class NullTaskSystem extends EventEmitter implements ITaskSystem {
547
	public run(task: Task): ITaskExecuteResult {
548
		return {
549
			kind: TaskExecuteKind.Started,
550 551 552
			promise: TPromise.as<ITaskSummary>({})
		};
	}
553 554 555
	public revealTask(task: Task): boolean {
		return false;
	}
556 557 558 559 560 561
	public isActive(): TPromise<boolean> {
		return TPromise.as(false);
	}
	public isActiveSync(): boolean {
		return false;
	}
562 563 564
	public getActiveTasks(): Task[] {
		return [];
	}
565 566 567
	public canAutoTerminate(): boolean {
		return true;
	}
568 569
	public terminate(task: string | Task): TPromise<TaskTerminateResponse> {
		return TPromise.as<TaskTerminateResponse>({ success: true, task: undefined });
570
	}
571 572
	public terminateAll(): TPromise<TaskTerminateResponse[]> {
		return TPromise.as<TaskTerminateResponse[]>([]);
573 574 575
	}
}

576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
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();
	}
}

613
interface WorkspaceTaskResult {
614
	set: TaskSet;
615 616
	configurations: {
		byIdentifier: IStringDictionary<ConfiguringTask>;
617
	};
618 619 620
	hasErrors: boolean;
}

621 622 623 624 625 626
interface WorkspaceFolderTaskResult extends WorkspaceTaskResult {
	workspaceFolder: WorkspaceFolder;
}

interface WorkspaceFolderConfigurationResult {
	workspaceFolder: WorkspaceFolder;
627 628 629 630
	config: TaskConfig.ExternalTaskRunnerConfiguration;
	hasErrors: boolean;
}

631 632 633 634
interface TaskCustomizationTelementryEvent {
	properties: string[];
}

E
Erich Gamma 已提交
635
class TaskService extends EventEmitter implements ITaskService {
636

637
	// private static autoDetectTelemetryName: string = 'taskServer.autoDetect';
638
	private static RecentlyUsedTasks_Key = 'workbench.tasks.recentlyUsedTasks';
T
t-amqi 已提交
639
	private static RanTaskBefore_Key = 'workbench.tasks.ranTaskBefore';
640

641
	private static CustomizationTelemetryEventName: string = 'taskService.customize';
642
	public static TemplateTelemetryEventName: string = 'taskService.template';
643

644
	public _serviceBrand: any;
E
Erich Gamma 已提交
645
	public static SERVICE_ID: string = 'taskService';
J
Johannes Rieken 已提交
646 647
	public static OutputChannelId: string = 'tasks';
	public static OutputChannelLabel: string = nls.localize('tasks', "Tasks");
E
Erich Gamma 已提交
648 649 650

	private modeService: IModeService;
	private configurationService: IConfigurationService;
D
Dirk Baeumer 已提交
651
	private configurationEditingService: IConfigurationEditingService;
E
Erich Gamma 已提交
652 653 654 655 656 657 658 659 660
	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 已提交
661
	private extensionService: IExtensionService;
D
Dirk Baeumer 已提交
662
	private quickOpenService: IQuickOpenService;
E
Erich Gamma 已提交
663

664
	private _configHasErrors: boolean;
665 666 667
	private _schemaVersion: JsonSchemaVersion;
	private _executionEngine: ExecutionEngine;
	private _workspaceFolders: WorkspaceFolder[];
668
	private _providers: Map<number, ITaskProvider>;
669

D
Dirk Baeumer 已提交
670
	private _workspaceTasksPromise: TPromise<Map<string, WorkspaceFolderTaskResult>>;
671

E
Erich Gamma 已提交
672
	private _taskSystem: ITaskSystem;
673
	private _taskSystemListeners: IDisposable[];
674
	private _recentlyUsedTasks: LinkedMap<string, string>;
675

676
	private _outputChannel: IOutputChannel;
E
Erich Gamma 已提交
677

J
Johannes Rieken 已提交
678
	constructor( @IModeService modeService: IModeService, @IConfigurationService configurationService: IConfigurationService,
D
Dirk Baeumer 已提交
679
		@IConfigurationEditingService configurationEditingService: IConfigurationEditingService,
E
Erich Gamma 已提交
680
		@IMarkerService markerService: IMarkerService, @IOutputService outputService: IOutputService,
J
Johannes Rieken 已提交
681 682 683
		@IMessageService messageService: IMessageService, @IWorkbenchEditorService editorService: IWorkbenchEditorService,
		@IFileService fileService: IFileService, @IWorkspaceContextService contextService: IWorkspaceContextService,
		@ITelemetryService telemetryService: ITelemetryService, @ITextFileService textFileService: ITextFileService,
684
		@ILifecycleService lifecycleService: ILifecycleService,
A
Alex Dima 已提交
685
		@IModelService modelService: IModelService, @IExtensionService extensionService: IExtensionService,
686
		@IQuickOpenService quickOpenService: IQuickOpenService,
687
		@IEnvironmentService private environmentService: IEnvironmentService,
688
		@IConfigurationResolverService private configurationResolverService: IConfigurationResolverService,
689
		@ITerminalService private terminalService: ITerminalService,
690
		@IWorkbenchEditorService private workbenchEditorService: IWorkbenchEditorService,
691
		@IStorageService private storageService: IStorageService,
692
		@IProgressService2 private progressService: IProgressService2,
693 694
		@IOpenerService private openerService: IOpenerService,
		@IWindowService private _windowServive: IWindowService
695
	) {
E
Erich Gamma 已提交
696 697 698 699

		super();
		this.modeService = modeService;
		this.configurationService = configurationService;
D
Dirk Baeumer 已提交
700
		this.configurationEditingService = configurationEditingService;
E
Erich Gamma 已提交
701 702 703 704 705 706 707 708 709
		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 已提交
710
		this.extensionService = extensionService;
D
Dirk Baeumer 已提交
711
		this.quickOpenService = quickOpenService;
E
Erich Gamma 已提交
712

713 714
		this._configHasErrors = false;
		this._workspaceTasksPromise = undefined;
715 716 717
		this._taskSystemListeners = [];
		this._outputChannel = this.outputService.getChannel(TaskService.OutputChannelId);
		this._providers = new Map<number, ITaskProvider>();
J
Johannes Rieken 已提交
718
		this.configurationService.onDidUpdateConfiguration(() => {
719
			if (!this._taskSystem && !this._workspaceTasksPromise) {
720 721
				return;
			}
D
Dirk Baeumer 已提交
722 723
			let folderSetup = this.computeWorkspaceFolders();
			if (this._executionEngine !== folderSetup[1] && this._taskSystem && this._taskSystem.getActiveTasks().length > 0) {
724 725 726 727 728
				this.messageService.show(
					Severity.Info,
					{
						message: nls.localize(
							'TaskSystem.noHotSwap',
D
Dirk Baeumer 已提交
729
							'Changing the task execution engine with an active task running requires to reload the Window'
730 731 732 733 734 735 736
						),
						actions: [
							new ReloadWindowAction(ReloadWindowAction.ID, ReloadWindowAction.LABEL, this._windowServive),
							new CloseMessageAction()
						]
					}
				);
D
Dirk Baeumer 已提交
737
				return;
D
Dirk Baeumer 已提交
738
			}
D
Dirk Baeumer 已提交
739 740 741 742
			this._workspaceFolders = folderSetup[0];
			this._executionEngine = folderSetup[1];
			this._schemaVersion = folderSetup[2];
			this.updateWorkspaceTasks();
E
Erich Gamma 已提交
743
		});
D
Dirk Baeumer 已提交
744 745 746 747
		let folderSetup = this.computeWorkspaceFolders();
		this._workspaceFolders = folderSetup[0];
		this._executionEngine = folderSetup[1];
		this._schemaVersion = folderSetup[2];
748
		lifecycleService.onWillShutdown(event => event.veto(this.beforeShutdown()));
749 750 751 752
		this.registerCommands();
	}

	private registerCommands(): void {
753
		CommandsRegistry.registerCommand('workbench.action.tasks.runTask', (accessor, arg) => {
754 755 756
			this.runTaskCommand(accessor, arg);
		});

757 758 759 760
		CommandsRegistry.registerCommand('workbench.action.tasks.restartTask', (accessor, arg) => {
			this.runRestartTaskCommand(accessor, arg);
		});

761 762 763 764 765 766 767 768 769 770 771 772 773 774 775
		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;
			}
776
			this.runBuildCommand();
777 778 779 780 781 782 783 784 785 786 787 788
		});

		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;
789
			}
790
			this.runTestCommand();
791
		});
792 793 794 795 796 797 798 799

		CommandsRegistry.registerCommand('workbench.action.tasks.configureDefaultBuildTask', () => {
			this.runConfigureDefaultBuildTask();
		});

		CommandsRegistry.registerCommand('workbench.action.tasks.configureDefaultTestTask', () => {
			this.runConfigureDefaultTestTask();
		});
800 801 802 803

		CommandsRegistry.registerCommand('workbench.action.tasks.showTasks', () => {
			this.runShowTasks();
		});
E
Erich Gamma 已提交
804 805
	}

806
	private showOutput(): void {
807
		this._outputChannel.show(true);
808 809
	}

E
Erich Gamma 已提交
810
	private disposeTaskSystemListeners(): void {
811
		this._taskSystemListeners = dispose(this._taskSystemListeners);
E
Erich Gamma 已提交
812 813
	}

814 815 816 817
	public registerTaskProvider(handle: number, provider: ITaskProvider): void {
		if (!provider) {
			return;
		}
818
		this._providers.set(handle, provider);
819 820 821
	}

	public unregisterTaskProvider(handle: number): boolean {
822
		return this._providers.delete(handle);
823 824
	}

825
	public getTask(identifier: string): TPromise<Task> {
D
Dirk Baeumer 已提交
826 827
		return this.getAllTasks().then((tasks) => {
			let resolver = this.createResolver(tasks);
828 829 830 831
			return resolver.resolve(identifier);
		});
	}

832
	public tasks(): TPromise<Task[]> {
D
Dirk Baeumer 已提交
833
		return this.getAllTasks();
834 835 836 837 838 839 840 841 842
	};

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

843 844 845 846 847 848 849
	public getActiveTasks(): TPromise<Task[]> {
		if (!this._taskSystem) {
			return TPromise.as([]);
		}
		return TPromise.as(this._taskSystem.getActiveTasks());
	}

850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880
	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);
	}
881

882
	private openDocumentation(): void {
883 884 885
		this.openerService.open(URI.parse('https://go.microsoft.com/fwlink/?LinkId=733558'));
	}

886
	public build(): TPromise<ITaskSummary> {
D
Dirk Baeumer 已提交
887 888
		return this.getAllTasks().then((tasks) => {
			let runnable = this.createRunnableTask(tasks, TaskGroup.Build);
889
			if (!runnable || !runnable.task) {
D
Dirk Baeumer 已提交
890
				if (this._schemaVersion === JsonSchemaVersion.V0_1_0) {
891 892 893 894
					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);
				}
895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911
			}
			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> {
D
Dirk Baeumer 已提交
912 913
		return this.getAllTasks().then((tasks) => {
			let runnable = this.createRunnableTask(tasks, TaskGroup.Test);
914
			if (!runnable || !runnable.task) {
D
Dirk Baeumer 已提交
915
				if (this._schemaVersion === JsonSchemaVersion.V0_1_0) {
916 917 918 919
					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);
				}
920 921 922 923 924 925 926 927
			}
			return this.executeTask(runnable.task, runnable.resolver);
		}).then(value => value, (error) => {
			this.handleError(error);
			return TPromise.wrapError(error);
		});
	}

928
	public run(task: string | Task, options?: RunOptions): TPromise<ITaskSummary> {
D
Dirk Baeumer 已提交
929 930
		return this.getAllTasks().then((tasks) => {
			let resolver = this.createResolver(tasks);
931 932 933 934 935
			let requested: string;
			let toExecute: Task;
			if (Types.isString(task)) {
				requested = task;
				toExecute = resolver.resolve(task);
936
			} else {
937
				requested = task.name;
D
Dirk Baeumer 已提交
938
				toExecute = task;
939 940 941 942
			}
			if (!toExecute) {
				throw new TaskError(Severity.Info, nls.localize('TaskServer.noTask', 'Requested task {0} to execute not found.', requested), TaskErrors.TaskNotFound);
			} else {
943
				if (options && options.attachProblemMatcher && this.shouldAttachProblemMatcher(toExecute) && !CompositeTask.is(toExecute)) {
944 945 946 947 948 949 950 951
					return this.attachProblemMatcher(toExecute).then((toExecute) => {
						if (toExecute) {
							return this.executeTask(toExecute, resolver);
						} else {
							return TPromise.as(undefined);
						}
					});
				}
952
				return this.executeTask(toExecute, resolver);
953
			}
954 955 956 957 958 959
		}).then(value => value, (error) => {
			this.handleError(error);
			return TPromise.wrapError(error);
		});
	}

960
	private shouldAttachProblemMatcher(task: Task): boolean {
D
Dirk Baeumer 已提交
961
		if (!this.canCustomize(task)) {
962 963
			return false;
		}
964 965 966
		if (task.group !== void 0 && task.group !== TaskGroup.Build) {
			return false;
		}
967 968 969
		if (task.problemMatchers !== void 0 && task.problemMatchers.length > 0) {
			return false;
		}
970
		if (ContributedTask.is(task)) {
971
			return !task.hasDefinedMatchers && task.problemMatchers.length === 0;
972
		}
973 974 975 976 977
		if (CustomTask.is(task)) {
			let configProperties: TaskConfig.ConfigurationProperties = task._source.config.element;
			return configProperties.problemMatcher === void 0;
		}
		return false;
978 979
	}

980
	private attachProblemMatcher(task: ContributedTask | CustomTask): TPromise<Task> {
981 982
		interface ProblemMatcherPickEntry extends IPickOpenEntry {
			matcher: NamedProblemMatcher;
983
			never?: boolean;
984 985 986 987 988
			learnMore?: boolean;
		}
		let entries: ProblemMatcherPickEntry[] = [];
		for (let key of ProblemMatcherRegistry.keys()) {
			let matcher = ProblemMatcherRegistry.get(key);
989 990 991
			if (matcher.deprecated) {
				continue;
			}
992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
			if (matcher.name === matcher.label) {
				entries.push({ label: matcher.name, matcher: matcher });
			} else {
				entries.push({
					label: matcher.label,
					description: `$${matcher.name}`,
					matcher: matcher
				});
			}
		}
		if (entries.length > 0) {
			entries = entries.sort((a, b) => a.label.localeCompare(b.label));
			entries[0].separator = { border: true };
			entries.unshift(
1006 1007 1008
				{ label: nls.localize('TaskService.attachProblemMatcher.continueWithout', 'Continue without scanning the task output'), matcher: undefined },
				{ label: nls.localize('TaskService.attachProblemMatcher.never', 'Never scan the task output'), matcher: undefined, never: true },
				{ label: nls.localize('TaskService.attachProblemMatcher.learnMoreAbout', 'Learn more about scanning the task output'), matcher: undefined, learnMore: true }
1009 1010
			);
			return this.quickOpenService.pick(entries, {
1011
				placeHolder: nls.localize('selectProblemMatcher', 'Select for which kind of errors and warnings to scan the task output'),
1012 1013 1014 1015 1016 1017
				autoFocus: { autoFocusFirstEntry: true }
			}).then((selected) => {
				if (selected) {
					if (selected.learnMore) {
						this.openDocumentation();
						return undefined;
1018 1019 1020
					} else if (selected.never) {
						this.customize(task, { problemMatcher: [] }, true);
						return task;
1021
					} else if (selected.matcher) {
1022
						let newTask = Task.clone(task);
1023 1024 1025 1026 1027 1028 1029 1030
						let matcherReference = `$${selected.matcher.name}`;
						newTask.problemMatchers = [matcherReference];
						this.customize(task, { problemMatcher: [matcherReference] }, true);
						return newTask;
					} else {
						return task;
					}
				} else {
1031
					return undefined;
1032 1033 1034 1035 1036 1037
				}
			});
		}
		return TPromise.as(task);
	}

1038
	public getTasksForGroup(group: string): TPromise<Task[]> {
D
Dirk Baeumer 已提交
1039
		return this.getAllTasks().then((tasks) => {
1040
			let result: Task[] = [];
D
Dirk Baeumer 已提交
1041 1042 1043
			for (let task of tasks) {
				if (task.group === group) {
					result.push(task);
1044 1045 1046 1047 1048 1049
				}
			}
			return result;
		});
	}

D
Dirk Baeumer 已提交
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
	public hasMultipleFolders(): boolean {
		return this._workspaceFolders && this._workspaceFolders.length > 1;
	}

	public canCustomize(task: Task): boolean {
		if (this._schemaVersion !== JsonSchemaVersion.V2_0_0) {
			return false;
		}
		if (CustomTask.is(task)) {
			return true;
		}
		if (ContributedTask.is(task)) {
			return !!Task.getWorkspaceFolder(task);
		}
		return false;
1065 1066
	}

1067
	public customize(task: ContributedTask | CustomTask, properties?: CustomizationProperties, openConfig?: boolean): TPromise<void> {
D
Dirk Baeumer 已提交
1068 1069 1070 1071 1072
		let workspaceFolder = Task.getWorkspaceFolder(task);
		if (!workspaceFolder) {
			return TPromise.as<void>(undefined);
		}
		let configuration = this.getConfiguration(workspaceFolder);
D
Dirk Baeumer 已提交
1073 1074 1075 1076
		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);
		}
1077

D
Dirk Baeumer 已提交
1078
		let fileConfig = configuration.config;
1079
		let index: number;
1080
		let toCustomize: TaskConfig.CustomTask | TaskConfig.ConfiguringTask;
1081
		let taskConfig = CustomTask.is(task) ? task._source.config : undefined;
1082 1083 1084
		if (taskConfig && taskConfig.element) {
			index = taskConfig.index;
			toCustomize = taskConfig.element;
1085 1086 1087 1088 1089 1090
		} else if (ContributedTask.is(task)) {
			toCustomize = {
			};
			let identifier: TaskConfig.TaskIdentifier = Objects.assign(Object.create(null), task.defines);
			delete identifier['_key'];
			Object.keys(identifier).forEach(key => toCustomize[key] = identifier[key]);
1091 1092 1093
			if (task.problemMatchers && task.problemMatchers.length > 0 && Types.isStringArray(task.problemMatchers)) {
				toCustomize.problemMatcher = task.problemMatchers;
			}
1094 1095 1096 1097
		}
		if (!toCustomize) {
			return TPromise.as(undefined);
		}
1098 1099 1100 1101
		if (properties) {
			for (let property of Object.getOwnPropertyNames(properties)) {
				let value = properties[property];
				if (value !== void 0 && value !== null) {
1102
					toCustomize[property] = value;
1103 1104 1105
				}
			}
		} else {
1106
			if (toCustomize.problemMatcher === void 0 && task.problemMatchers === void 0 || task.problemMatchers.length === 0) {
1107
				toCustomize.problemMatcher = [];
1108
			}
1109
		}
1110

1111
		let promise: TPromise<void>;
D
Dirk Baeumer 已提交
1112
		if (!fileConfig) {
1113
			let value = {
D
Dirk Baeumer 已提交
1114
				version: '2.0.0',
1115
				tasks: [toCustomize]
D
Dirk Baeumer 已提交
1116
			};
1117 1118 1119 1120 1121 1122 1123 1124 1125
			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));
			}
1126
			promise = this.fileService.createFile(this.contextService.toResource('.vscode/tasks.json', this.contextService.getWorkspace().folders[0]), content).then(() => { }); // TODO@Dirk (https://github.com/Microsoft/vscode/issues/29454)
D
Dirk Baeumer 已提交
1127
		} else {
1128
			let value: IConfigurationValue = { key: undefined, value: undefined };
1129 1130
			// We have a global task configuration
			if (index === -1) {
1131 1132 1133 1134
				if (properties.problemMatcher !== void 0) {
					fileConfig.problemMatcher = properties.problemMatcher;
					value.key = 'tasks.problemMatchers';
					value.value = fileConfig.problemMatcher;
D
Dirk Baeumer 已提交
1135
					promise = this.writeConfiguration(workspaceFolder, value);
1136 1137 1138 1139
				} else if (properties.group !== void 0) {
					fileConfig.group = properties.group;
					value.key = 'tasks.group';
					value.value = fileConfig.group;
D
Dirk Baeumer 已提交
1140
					promise = this.writeConfiguration(workspaceFolder, value);
1141
				}
1142 1143 1144 1145 1146 1147 1148
			} else {
				if (!Array.isArray(fileConfig.tasks)) {
					fileConfig.tasks = [];
				}
				value.key = 'tasks.tasks';
				value.value = fileConfig.tasks;
				if (index === void 0) {
1149 1150 1151 1152
					fileConfig.tasks.push(toCustomize);
				} else {
					fileConfig.tasks[index] = toCustomize;
				}
D
Dirk Baeumer 已提交
1153
				promise = this.writeConfiguration(workspaceFolder, value);
D
Dirk Baeumer 已提交
1154 1155
			}
		};
1156 1157 1158
		if (!promise) {
			return TPromise.as(undefined);
		}
1159
		return promise.then(() => {
1160 1161 1162 1163
			let event: TaskCustomizationTelementryEvent = {
				properties: properties ? Object.getOwnPropertyNames(properties) : []
			};
			this.telemetryService.publicLog(TaskService.CustomizationTelemetryEventName, event);
D
Dirk Baeumer 已提交
1164
			if (openConfig) {
1165
				let resource = this.contextService.toResource('.vscode/tasks.json', this.contextService.getWorkspace().folders[0]); // TODO@Dirk (https://github.com/Microsoft/vscode/issues/29454)
D
Dirk Baeumer 已提交
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
				this.editorService.openEditor({
					resource: resource,
					options: {
						forceOpen: true,
						pinned: false
					}
				}, false);
			}
		});
	}

D
Dirk Baeumer 已提交
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
	private writeConfiguration(workspaceFolder: WorkspaceFolder, value: IConfigurationValue): TPromise<void, any> {
		if (this.contextService.getWorkbenchState() === WorkbenchState.FOLDER) {
			return this.configurationEditingService.writeConfiguration(ConfigurationTarget.WORKSPACE, value);
		} else if (this.contextService.getWorkbenchState() === WorkbenchState.WORKSPACE) {
			return this.configurationEditingService.writeConfiguration(ConfigurationTarget.FOLDER, value, { scopes: { resource: workspaceFolder.uri } });
		} else {
			return undefined;
		}
	}

1187
	public openConfig(task: CustomTask): TPromise<void> {
D
Dirk Baeumer 已提交
1188
		// @ToDo need to adopt since this is not working anymore
1189
		let resource = this.contextService.toResource(task._source.config.file, this.contextService.getWorkspace().folders[0]);
1190 1191 1192 1193 1194 1195 1196 1197 1198
		return this.editorService.openEditor({
			resource: resource,
			options: {
				forceOpen: true,
				pinned: false
			}
		}, false).then(() => undefined);
	}

D
Dirk Baeumer 已提交
1199
	private createRunnableTask(tasks: Task[], group: TaskGroup): { task: Task; resolver: ITaskResolver } {
1200
		let idMap: IStringDictionary<Task> = Object.create(null);
D
Dirk Baeumer 已提交
1201
		let labelMap: IStringDictionary<Task> = Object.create(null);
1202 1203
		let identifierMap: IStringDictionary<Task> = Object.create(null);

1204 1205
		let workspaceTasks: Task[] = [];
		let extensionTasks: Task[] = [];
D
Dirk Baeumer 已提交
1206 1207 1208 1209 1210 1211 1212 1213 1214
		tasks.forEach((task) => {
			idMap[task._id] = task;
			labelMap[task._label] = task;
			identifierMap[task.identifier] = task;
			if (group && task.group === group) {
				if (task._source.kind === TaskSourceKind.Workspace) {
					workspaceTasks.push(task);
				} else {
					extensionTasks.push(task);
1215
				}
D
Dirk Baeumer 已提交
1216
			}
1217 1218 1219
		});
		let resolver: ITaskResolver = {
			resolve: (id: string) => {
1220
				return idMap[id] || labelMap[id] || identifierMap[id];
1221 1222
			}
		};
1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
		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;
		}

1233 1234
		// We can only have extension tasks if we are in version 2.0.0. Then we can even run
		// multiple build tasks.
1235 1236
		if (extensionTasks.length === 1) {
			return { task: extensionTasks[0], resolver };
1237 1238
		} else {
			let id: string = UUID.generateUuid();
1239
			let task: CompositeTask = {
1240
				_id: id,
1241
				_source: { kind: TaskSourceKind.Composite, label: 'composite' },
1242
				_label: id,
1243
				type: 'composite',
1244 1245
				name: id,
				identifier: id,
1246
				dependsOn: extensionTasks.map(task => task._id)
1247 1248
			};
			return { task, resolver };
E
Erich Gamma 已提交
1249 1250 1251
		}
	}

D
Dirk Baeumer 已提交
1252
	private createResolver(tasks: Task[]): ITaskResolver {
D
Dirk Baeumer 已提交
1253
		let labelMap: IStringDictionary<Task> = Object.create(null);
1254 1255
		let identifierMap: IStringDictionary<Task> = Object.create(null);

D
Dirk Baeumer 已提交
1256 1257 1258
		tasks.forEach((task) => {
			labelMap[task._label] = task;
			identifierMap[task.identifier] = task;
1259 1260 1261
		});
		return {
			resolve: (id: string) => {
D
Dirk Baeumer 已提交
1262
				return labelMap[id] || identifierMap[id];
1263
			}
1264 1265 1266 1267
		};
	}

	private executeTask(task: Task, resolver: ITaskResolver): TPromise<ITaskSummary> {
T
t-amqi 已提交
1268 1269
		if (!this.storageService.get(TaskService.RanTaskBefore_Key, StorageScope.GLOBAL)) {
			this.storageService.store(TaskService.RanTaskBefore_Key, true, StorageScope.GLOBAL);
T
t-amqi 已提交
1270
		}
1271 1272 1273
		return ProblemMatcherRegistry.onReady().then(() => {
			return this.textFileService.saveAll().then((value) => { // make sure all dirty files are saved
				let executeResult = this.getTaskSystem().run(task, resolver);
1274
				this.getRecentlyUsedTasks().set(Task.getKey(task), Task.getKey(task), Touch.First);
1275 1276
				if (executeResult.kind === TaskExecuteKind.Active) {
					let active = executeResult.active;
1277 1278
					if (active.same) {
						if (active.background) {
1279
							this.messageService.show(Severity.Info, nls.localize('TaskSystem.activeSame.background', 'The task \'{0}\' is already active and in background mode. To terminate it use `Terminate Task...` from the Tasks menu.', task._label));
1280
						} else {
D
Dirk Baeumer 已提交
1281
							this.messageService.show(Severity.Info, nls.localize('TaskSystem.activeSame.noBackground', 'The task \'{0}\' is already active. To terminate it use `Terminate Task...` from the Tasks menu.', task._label));
1282
						}
1283 1284 1285
					} 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);
					}
1286
				}
1287 1288
				return executeResult.promise;
			});
1289 1290 1291
		});
	}

1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
	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;
		});
	}

1308
	public terminate(task: string | Task): TPromise<TaskTerminateResponse> {
1309
		if (!this._taskSystem) {
1310
			return TPromise.as({ success: true, task: undefined });
1311
		}
1312
		const id: string = Types.isString(task) ? task : task._id;
1313
		return this._taskSystem.terminate(id);
1314 1315
	}

1316
	public terminateAll(): TPromise<TaskTerminateResponse[]> {
1317
		if (!this._taskSystem) {
1318
			return TPromise.as<TaskTerminateResponse[]>([]);
1319
		}
1320
		return this._taskSystem.terminateAll();
1321 1322 1323 1324 1325 1326
	}

	private getTaskSystem(): ITaskSystem {
		if (this._taskSystem) {
			return this._taskSystem;
		}
D
Dirk Baeumer 已提交
1327
		if (this._executionEngine === ExecutionEngine.Terminal) {
1328 1329 1330
			this._taskSystem = new TerminalTaskSystem(
				this.terminalService, this.outputService, this.markerService,
				this.modelService, this.configurationResolverService, this.telemetryService,
1331
				this.workbenchEditorService, this.contextService,
1332 1333 1334 1335 1336
				TaskService.OutputChannelId
			);
		} else {
			let system = new ProcessTaskSystem(
				this.markerService, this.modelService, this.telemetryService, this.outputService,
1337
				this.configurationResolverService, this.contextService, TaskService.OutputChannelId,
1338 1339 1340 1341
			);
			system.hasErrors(this._configHasErrors);
			this._taskSystem = system;
		}
A
Alex Dima 已提交
1342 1343
		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)));
1344
		this._taskSystemListeners.push(this._taskSystem.addListener(TaskSystemEvents.Terminated, (event) => this.emit(TaskServiceEvents.Terminated, event)));
1345
		this._taskSystemListeners.push(this._taskSystem.addListener(TaskSystemEvents.Changed, () => this.emit(TaskServiceEvents.Changed)));
1346 1347 1348
		return this._taskSystem;
	}

D
Dirk Baeumer 已提交
1349
	private getAllTasks(): TPromise<Task[]> {
D
Dirk Baeumer 已提交
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
		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);
					}
				};
D
Dirk Baeumer 已提交
1367
				if (this._schemaVersion === JsonSchemaVersion.V2_0_0 && this._providers.size > 0) {
D
Dirk Baeumer 已提交
1368 1369 1370 1371 1372
					this._providers.forEach((provider) => {
						counter++;
						provider.provideTasks().done(done, error);
					});
				} else {
1373 1374
					resolve(result);
				}
D
Dirk Baeumer 已提交
1375
			});
D
Dirk Baeumer 已提交
1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400
		}).then((contributedTaskSets) => {
			let result: Task[] = [];
			let contributedTasks: Map<string, Task[]> = new Map();
			for (let set of contributedTaskSets) {
				for (let task of set.tasks) {
					if (!ContributedTask.is(task)) {
						continue;
					}
					let workspaceFolder = task._source.workspaceFolder;
					if (workspaceFolder) {
						let values = contributedTasks.get(workspaceFolder.uri.toString());
						if (!values) {
							values = [task];
							contributedTasks.set(workspaceFolder.uri.toString(), values);
						} else {
							values.push(task);
						}
					} else {
						result.push(task);
					}
				}
			}
			return this.getWorkspaceTasks().then((customTasks) => {
				customTasks.forEach((folderTasks, key) => {
					let contributed = contributedTasks.get(key);
1401 1402 1403 1404 1405 1406 1407
					if (!folderTasks.set) {
						if (contributed) {
							result.push(...contributed);
						}
						return;
					}

D
Dirk Baeumer 已提交
1408 1409 1410 1411 1412 1413 1414 1415 1416
					if (!contributed) {
						result.push(...folderTasks.set.tasks);
					} else {
						let configurations = folderTasks.configurations;
						let legacyTaskConfigurations = folderTasks.set ? this.getLegacyTaskConfigurations(folderTasks.set) : undefined;
						let customTasksToDelete: Task[] = [];
						if (configurations || legacyTaskConfigurations) {
							for (let task of contributed) {
								if (!ContributedTask.is(task)) {
1417 1418
									continue;
								}
D
Dirk Baeumer 已提交
1419 1420 1421 1422
								if (configurations) {
									let configuringTask = configurations.byIdentifier[task.defines._key];
									if (configuringTask) {
										result.push(TaskConfig.createCustomTask(task, configuringTask));
D
Dirk Baeumer 已提交
1423 1424
									} else {
										result.push(task);
D
Dirk Baeumer 已提交
1425 1426 1427 1428 1429 1430
									}
								} else if (legacyTaskConfigurations) {
									let configuringTask = legacyTaskConfigurations[task.defines._key];
									if (configuringTask) {
										result.push(TaskConfig.createCustomTask(task, configuringTask));
										customTasksToDelete.push(configuringTask);
D
Dirk Baeumer 已提交
1431 1432
									} else {
										result.push(task);
D
Dirk Baeumer 已提交
1433 1434 1435 1436
									}
								} else {
									result.push(task);
								}
1437
							}
D
Dirk Baeumer 已提交
1438 1439 1440 1441 1442 1443 1444 1445 1446 1447
							if (customTasksToDelete.length > 0) {
								let toDelete = customTasksToDelete.reduce<IStringDictionary<boolean>>((map, task) => {
									map[task._id] = true;
									return map;
								}, Object.create(null));
								for (let task of folderTasks.set.tasks) {
									if (toDelete[task._id]) {
										continue;
									}
									result.push(task);
1448
								}
D
Dirk Baeumer 已提交
1449 1450
							} else {
								result.push(...folderTasks.set.tasks);
1451
							}
D
Dirk Baeumer 已提交
1452 1453
						} else {
							result.push(...folderTasks.set.tasks);
D
Dirk Baeumer 已提交
1454
							result.push(...contributed);
1455 1456
						}
					}
D
Dirk Baeumer 已提交
1457
				});
1458 1459 1460
				return result;
			}, () => {
				// If we can't read the tasks.json file provide at least the contributed tasks
D
Dirk Baeumer 已提交
1461 1462 1463 1464
				let result: Task[] = [];
				for (let set of contributedTaskSets) {
					result.push(...set.tasks);
				}
1465 1466
				return result;
			});
1467 1468 1469
		});
	}

1470 1471
	private getLegacyTaskConfigurations(workspaceTasks: TaskSet): IStringDictionary<CustomTask> {
		let result: IStringDictionary<CustomTask>;
1472 1473 1474 1475 1476 1477 1478 1479
		function getResult() {
			if (result) {
				return result;
			}
			result = Object.create(null);
			return result;
		}
		for (let task of workspaceTasks.tasks) {
1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490
			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;
				}
1491 1492 1493 1494 1495
			}
		}
		return result;
	}

D
Dirk Baeumer 已提交
1496
	private getWorkspaceTasks(): TPromise<Map<string, WorkspaceFolderTaskResult>> {
1497 1498 1499
		if (this._workspaceTasksPromise) {
			return this._workspaceTasksPromise;
		}
1500
		this.updateWorkspaceTasks();
1501 1502 1503 1504 1505
		return this._workspaceTasksPromise;
	}

	private updateWorkspaceTasks(): void {
		this._workspaceTasksPromise = this.computeWorkspaceTasks().then(value => {
D
Dirk Baeumer 已提交
1506 1507 1508 1509 1510 1511
			if (this._executionEngine === ExecutionEngine.Process && this._taskSystem instanceof ProcessTaskSystem) {
				// We can only have a process engine if we have one folder.
				value.forEach((value) => {
					this._configHasErrors = value.hasErrors;
					(this._taskSystem as ProcessTaskSystem).hasErrors(this._configHasErrors);
				});
1512 1513
			}
			return value;
1514 1515 1516
		});
	}

1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 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 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615
	private computeWorkspaceTasks(): TPromise<Map<string, WorkspaceFolderTaskResult>> {
		if (this._workspaceFolders.length === 0) {
			return TPromise.as(new Map<string, WorkspaceFolderTaskResult>());
		} else {
			let promises: TPromise<WorkspaceFolderTaskResult>[] = [];
			for (let folder of this._workspaceFolders) {
				promises.push(this.computeWorkspaceFolderTasks(folder).then((value) => value, () => undefined));
			}
			return TPromise.join(promises).then((values) => {
				let result = new Map<string, WorkspaceFolderTaskResult>();
				for (let value of values) {
					if (value) {
						result.set(value.workspaceFolder.uri.toString(), value);
					}
				}
				return result;
			});
		}
	}

	private computeWorkspaceFolderTasks(workspaceFolder: WorkspaceFolder): TPromise<WorkspaceFolderTaskResult> {
		return (this._executionEngine === ExecutionEngine.Process
			? this.computeLegacyConfiguration(workspaceFolder)
			: this.computeConfiguration(workspaceFolder)).
			then((workspaceFolderConfiguration) => {
				if (!workspaceFolderConfiguration || !workspaceFolderConfiguration.config || workspaceFolderConfiguration.hasErrors) {
					return TPromise.as({ workspaceFolder, set: undefined, configurations: undefined, hasErrors: workspaceFolderConfiguration ? workspaceFolderConfiguration.hasErrors : false });
				}
				return ProblemMatcherRegistry.onReady().then((): WorkspaceFolderTaskResult => {
					let problemReporter = new ProblemReporter(this._outputChannel);
					let parseResult = TaskConfig.parse(workspaceFolder, workspaceFolderConfiguration.config, problemReporter);
					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.'));
						return { workspaceFolder, set: undefined, configurations: undefined, hasErrors };
					}
					let customizedTasks: { byIdentifier: IStringDictionary<ConfiguringTask>; };
					if (parseResult.configured && parseResult.configured.length > 0) {
						customizedTasks = {
							byIdentifier: Object.create(null)
						};
						for (let task of parseResult.configured) {
							customizedTasks.byIdentifier[task.configures._key] = task;
						}
					}
					return { workspaceFolder, set: { tasks: parseResult.custom }, configurations: customizedTasks, hasErrors };
				});
			});
	}

	private computeConfiguration(workspaceFolder: WorkspaceFolder): TPromise<WorkspaceFolderConfigurationResult> {
		let { config, hasParseErrors } = this.getConfiguration(workspaceFolder);
		return TPromise.as<WorkspaceFolderConfigurationResult>({ workspaceFolder, config, hasErrors: hasParseErrors });
	}

	private computeLegacyConfiguration(workspaceFolder: WorkspaceFolder): TPromise<WorkspaceFolderConfigurationResult> {
		let { config, hasParseErrors } = this.getConfiguration(workspaceFolder);
		if (hasParseErrors) {
			return TPromise.as({ workspaceFolder: workspaceFolder, hasErrors: true, config: undefined });
		}
		if (config) {
			if (this.hasDetectorSupport(config)) {
				return new ProcessRunnerDetector(this.fileService, this.contextService, this.configurationResolverService, config).detect(true).then((value): WorkspaceFolderConfigurationResult => {
					let hasErrors = this.printStderr(value.stderr);
					let detectedConfig = value.config;
					if (!detectedConfig) {
						return { workspaceFolder, config, hasErrors };
					}
					let result: TaskConfig.ExternalTaskRunnerConfiguration = Objects.clone(config);
					let configuredTasks: IStringDictionary<TaskConfig.CustomTask> = Object.create(null);
					if (!result.tasks) {
						if (detectedConfig.tasks) {
							result.tasks = detectedConfig.tasks;
						}
					} else {
						result.tasks.forEach(task => configuredTasks[task.taskName] = task);
						detectedConfig.tasks.forEach((task) => {
							if (!configuredTasks[task.taskName]) {
								result.tasks.push(task);
							}
						});
					}
					return { workspaceFolder, config: result, hasErrors };
				});
			} else {
				return TPromise.as({ workspaceFolder, config, hasErrors: false });
			}
		} else {
			return new ProcessRunnerDetector(this.fileService, this.contextService, this.configurationResolverService).detect(true).then((value) => {
				let hasErrors = this.printStderr(value.stderr);
				return { workspaceFolder, config: value.config, hasErrors };
			});
		}
	}

D
Dirk Baeumer 已提交
1616 1617 1618 1619 1620
	private computeWorkspaceFolders(): [WorkspaceFolder[], ExecutionEngine, JsonSchemaVersion] {
		let workspaceFolders: WorkspaceFolder[] = [];
		let executionEngine = ExecutionEngine.Terminal;
		let schemaVersion = JsonSchemaVersion.V2_0_0;

D
Dirk Baeumer 已提交
1621
		if (this.contextService.getWorkbenchState() === WorkbenchState.FOLDER) {
1622
			let workspaceFolder: WorkspaceFolder = { uri: this.contextService.getWorkspace().folders[0].uri };
D
Dirk Baeumer 已提交
1623 1624 1625
			workspaceFolders.push(workspaceFolder);
			executionEngine = this.computeExecutionEngine(workspaceFolder);
			schemaVersion = this.computeJsonSchemaVersion(workspaceFolder);
D
Dirk Baeumer 已提交
1626 1627
		} else if (this.contextService.getWorkbenchState() === WorkbenchState.WORKSPACE) {
			for (let folder of this.contextService.getWorkspace().folders) {
1628
				let workspaceFolder = { uri: folder.uri };
D
Dirk Baeumer 已提交
1629
				if (schemaVersion === this.computeJsonSchemaVersion(workspaceFolder)) {
D
Dirk Baeumer 已提交
1630
					workspaceFolders.push(workspaceFolder);
1631 1632 1633 1634
				} else {
					this._outputChannel.append(nls.localize(
						'taskService.ignoreingFolder',
						'Ignoring task configurations for workspace folder {0}. Multi root folder support requires that all folders use task version 2.0.',
1635
						folder.uri.fsPath));
1636 1637 1638
				}
			}
		}
D
Dirk Baeumer 已提交
1639
		return [workspaceFolders, executionEngine, schemaVersion];
1640
	}
1641

1642 1643
	private computeExecutionEngine(workspaceFolder: WorkspaceFolder): ExecutionEngine {
		let { config } = this.getConfiguration(workspaceFolder);
1644
		if (!config) {
1645
			return ExecutionEngine._default;
1646 1647 1648 1649
		}
		return TaskConfig.ExecutionEngine.from(config);
	}

1650 1651
	private computeJsonSchemaVersion(workspaceFolder: WorkspaceFolder): JsonSchemaVersion {
		let { config } = this.getConfiguration(workspaceFolder);
1652 1653 1654 1655 1656 1657
		if (!config) {
			return JsonSchemaVersion.V2_0_0;
		}
		return TaskConfig.JsonSchemaVersion.from(config);
	}

1658
	private getConfiguration(workspaceFolder: WorkspaceFolder): { config: TaskConfig.ExternalTaskRunnerConfiguration; hasParseErrors: boolean } {
D
Dirk Baeumer 已提交
1659
		let result = this.contextService.getWorkbenchState() !== WorkbenchState.EMPTY
1660 1661
			? this.configurationService.getConfiguration<TaskConfig.ExternalTaskRunnerConfiguration>('tasks', { resource: workspaceFolder.uri })
			: undefined;
1662
		if (!result) {
1663
			return { config: undefined, hasParseErrors: false };
1664 1665 1666 1667 1668 1669 1670 1671 1672
		}
		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;
				}
1673
			}
1674
			if (isAffected) {
1675
				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'));
1676
				this.showOutput();
1677
				return { config: undefined, hasParseErrors: true };
1678
			}
1679 1680
		}
		return { config: result, hasParseErrors: false };
1681 1682
	}

E
Erich Gamma 已提交
1683
	private printStderr(stderr: string[]): boolean {
1684
		let result = false;
E
Erich Gamma 已提交
1685 1686
		if (stderr && stderr.length > 0) {
			stderr.forEach((line) => {
1687
				result = true;
1688
				this._outputChannel.append(line + '\n');
E
Erich Gamma 已提交
1689
			});
1690
			this._outputChannel.show(true);
E
Erich Gamma 已提交
1691 1692 1693 1694
		}
		return result;
	}

1695
	public inTerminal(): boolean {
1696 1697 1698
		if (this._taskSystem) {
			return this._taskSystem instanceof TerminalTaskSystem;
		}
D
Dirk Baeumer 已提交
1699
		return this._executionEngine === ExecutionEngine.Terminal;
1700 1701
	}

1702
	private hasDetectorSupport(config: TaskConfig.ExternalTaskRunnerConfiguration): boolean {
1703
		if (!config.command || this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) {
E
Erich Gamma 已提交
1704 1705 1706 1707 1708
			return false;
		}
		return ProcessRunnerDetector.supports(config.command);
	}

1709
	public configureAction(): Action {
1710
		return new ConfigureTaskRunnerAction(ConfigureTaskRunnerAction.ID, ConfigureTaskRunnerAction.TEXT, this,
1711
			this.configurationService, this.editorService, this.fileService, this.contextService,
1712
			this.outputService, this.messageService, this.quickOpenService, this.environmentService, this.configurationResolverService,
1713
			this.extensionService, this.telemetryService);
1714 1715
	}

1716
	private configureBuildTask(): Action {
1717
		return new ConfigureBuildTaskAction(ConfigureBuildTaskAction.ID, ConfigureBuildTaskAction.TEXT, this,
1718
			this.configurationService, this.editorService, this.fileService, this.contextService,
1719
			this.outputService, this.messageService, this.quickOpenService, this.environmentService, this.configurationResolverService,
1720
			this.extensionService, this.telemetryService);
1721 1722
	}

E
Erich Gamma 已提交
1723
	public beforeShutdown(): boolean | TPromise<boolean> {
1724 1725 1726
		if (!this._taskSystem) {
			return false;
		}
1727
		this.saveRecentlyUsedTasks();
1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749
		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 已提交
1750
					}
1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763
				}
				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 已提交
1764
				return true; // veto
1765 1766 1767 1768 1769
			}, (err) => {
				return true; // veto
			});
		} else {
			return true; // veto
E
Erich Gamma 已提交
1770 1771 1772
		}
	}

1773
	private getConfigureAction(code: TaskErrors): Action {
J
Johannes Rieken 已提交
1774
		switch (code) {
1775 1776 1777 1778 1779 1780
			case TaskErrors.NoBuildTask:
				return this.configureBuildTask();
			default:
				return this.configureAction();
		}
	}
1781

J
Johannes Rieken 已提交
1782
	private handleError(err: any): void {
E
Erich Gamma 已提交
1783 1784 1785
		let showOutput = true;
		if (err instanceof TaskError) {
			let buildError = <TaskError>err;
1786 1787 1788
			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 已提交
1789
				let closeAction = new CloseMessageAction();
1790
				let action: Action = needsConfig
1791
					? this.getConfigureAction(buildError.code)
1792 1793
					: new Action(
						'workbench.action.tasks.terminate',
1794
						nls.localize('TerminateAction.label', "Terminate Task"),
1795
						undefined, true, () => { this.runTerminateCommand(); return TPromise.as<void>(undefined); });
J
Johannes Rieken 已提交
1796
				closeAction.closeFunction = this.messageService.show(buildError.severity, { message: buildError.message, actions: [action, closeAction] });
E
Erich Gamma 已提交
1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808
			} 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) {
1809
			this._outputChannel.show(true);
E
Erich Gamma 已提交
1810 1811
		}
	}
1812 1813

	private canRunCommand(): boolean {
1814
		if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) {
1815 1816 1817 1818 1819 1820
			this.messageService.show(Severity.Info, nls.localize('TaskService.noWorkspace', 'Tasks are only available on a workspace folder.'));
			return false;
		}
		return true;
	}

1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887
	private showQuickPick(tasks: Task[], placeHolder: string, group: boolean = false, sort: boolean = false): TPromise<Task> {
		if (tasks === void 0 || tasks === null || tasks.length === 0) {
			return TPromise.as(undefined);
		}
		interface TaskQickPickEntry extends IPickOpenEntry {
			task: Task;
		}
		function TaskQickPickEntry(task: Task): TaskQickPickEntry {
			return { label: task._label, task };
		}
		function fillEntries(entries: TaskQickPickEntry[], tasks: Task[], groupLabel: string, withBorder: boolean = false): void {
			let first = true;
			for (let task of tasks) {
				if (first) {
					first = false;
					let entry = TaskQickPickEntry(task);
					entry.separator = { label: groupLabel, border: withBorder };
					entries.push(entry);
				} else {
					entries.push(TaskQickPickEntry(task));
				}
			}
		}
		let entries: TaskQickPickEntry[];
		if (group) {
			entries = [];
			if (tasks.length === 1) {
				entries.push(TaskQickPickEntry(tasks[0]));
			} else {
				let recentlyUsedTasks = this.getRecentlyUsedTasks();
				let recent: Task[] = [];
				let configured: Task[] = [];
				let detected: Task[] = [];
				let taskMap: IStringDictionary<Task> = Object.create(null);
				tasks.forEach(task => taskMap[Task.getKey(task)] = task);
				recentlyUsedTasks.keys().forEach(key => {
					let task = taskMap[key];
					if (task) {
						recent.push(task);
					}
				});
				for (let task of tasks) {
					if (!recentlyUsedTasks.has(Task.getKey(task))) {
						if (task._source.kind === TaskSourceKind.Workspace) {
							configured.push(task);
						} else {
							detected.push(task);
						}
					}
				}
				let hasRecentlyUsed: boolean = recent.length > 0;
				fillEntries(entries, recent, nls.localize('recentlyUsed', 'recently used tasks'));
				configured = configured.sort((a, b) => a._label.localeCompare(b._label));
				let hasConfigured = configured.length > 0;
				fillEntries(entries, configured, nls.localize('configured', 'configured tasks'), hasRecentlyUsed);
				detected = detected.sort((a, b) => a._label.localeCompare(b._label));
				fillEntries(entries, detected, nls.localize('detected', 'detected tasks'), hasRecentlyUsed || hasConfigured);
			}
		} else {
			entries = tasks.map<TaskQickPickEntry>(task => { return { label: task._label, task }; });
			if (sort) {
				entries = entries.sort((a, b) => a.task._label.localeCompare(b.task._label));
			}
		}
		return this.quickOpenService.pick(entries, { placeHolder, autoFocus: { autoFocusFirstEntry: true } }).then(entry => entry ? entry.task : undefined);
	}

1888 1889 1890 1891 1892
	private runTaskCommand(accessor: ServicesAccessor, arg: any): void {
		if (!this.canRunCommand()) {
			return;
		}
		if (Types.isString(arg)) {
1893 1894 1895 1896 1897
			this.getTask(arg).then((task) => {
				if (task) {
					this.run(task);
				} else {
					this.quickOpenService.show('task ');
1898
				}
1899 1900
			}, () => {
				this.quickOpenService.show('task ');
1901 1902 1903 1904 1905 1906
			});
		} else {
			this.quickOpenService.show('task ');
		}
	}

1907 1908 1909 1910
	private runBuildCommand(): void {
		if (!this.canRunCommand()) {
			return;
		}
D
Dirk Baeumer 已提交
1911
		if (this._schemaVersion === JsonSchemaVersion.V0_1_0) {
1912 1913 1914
			this.build();
			return;
		}
1915 1916 1917 1918 1919
		let options: IProgressOptions = {
			location: ProgressLocation.Window,
			title: nls.localize('TaskService.fetchingBuildTasks', 'Fetching build tasks...')
		};
		let promise = this.getTasksForGroup(TaskGroup.Build).then((tasks) => {
1920
			if (tasks.length === 0) {
1921 1922 1923 1924 1925 1926 1927
				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()]
					}
				);
1928 1929
				return;
			}
D
Dirk Baeumer 已提交
1930 1931
			let primaries: Task[] = [];
			for (let task of tasks) {
1932
				// We only have build tasks here
1933
				if (task.isDefaultGroupEntry) {
D
Dirk Baeumer 已提交
1934 1935 1936 1937 1938 1939 1940
					primaries.push(task);
				}
			}
			if (primaries.length === 1) {
				this.run(primaries[0]);
				return;
			}
1941 1942 1943 1944 1945
			this.showQuickPick(tasks, nls.localize('TaskService.pickBuildTask', 'Select the build task to run'), true).then((task) => {
				if (task) {
					this.run(task, { attachProblemMatcher: true });
				}
			});
1946
		});
1947
		this.progressService.withProgress(options, () => promise);
1948 1949 1950 1951 1952 1953
	}

	private runTestCommand(): void {
		if (!this.canRunCommand()) {
			return;
		}
D
Dirk Baeumer 已提交
1954
		if (this._schemaVersion === JsonSchemaVersion.V0_1_0) {
1955
			this.runTest();
1956 1957
			return;
		}
1958 1959 1960 1961 1962
		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 已提交
1963
			if (tasks.length === 0) {
1964 1965 1966 1967 1968 1969 1970
				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 已提交
1971 1972 1973 1974
				return;
			}
			let primaries: Task[] = [];
			for (let task of tasks) {
1975
				// We only have test task here.
1976
				if (task.isDefaultGroupEntry) {
D
Dirk Baeumer 已提交
1977 1978 1979 1980 1981
					primaries.push(task);
				}
			}
			if (primaries.length === 1) {
				this.run(primaries[0]);
1982 1983
				return;
			}
1984 1985 1986 1987 1988
			this.showQuickPick(tasks, nls.localize('TaskService.pickTestTask', 'Select the test task to run'), true).then((task) => {
				if (task) {
					this.run(task);
				}
			});
1989
		});
1990
		this.progressService.withProgress(options, () => promise);
1991 1992
	}

1993 1994 1995 1996 1997
	private runTerminateCommand(): void {
		if (!this.canRunCommand()) {
			return;
		}
		if (this.inTerminal()) {
1998 1999
			this.getActiveTasks().then((activeTasks) => {
				if (activeTasks.length === 0) {
D
Dirk Baeumer 已提交
2000
					this.messageService.show(Severity.Info, nls.localize('TaskService.noTaskRunning', 'No task is currently running.'));
2001 2002
					return;
				}
2003
				this.showQuickPick(activeTasks, nls.localize('TaskService.tastToTerminate', 'Select task to terminate'), false, true).then(task => {
2004 2005 2006 2007
					if (task) {
						this.terminate(task);
					}
				});
2008
			});
2009 2010 2011
		} else {
			this.isActive().then((active) => {
				if (active) {
2012 2013 2014
					this.terminateAll().then((responses) => {
						// the output runner has only one task
						let response = responses[0];
2015
						if (response.success) {
2016 2017 2018
							return;
						}
						if (response.code && response.code === TerminateResponseCode.ProcessNotFound) {
2019 2020
							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 {
2021
							this.messageService.show(Severity.Error, nls.localize('TerminateAction.failed', 'Failed to terminate running task'));
2022 2023 2024 2025 2026 2027
						}
					});
				}
			});
		}
	}
2028 2029 2030 2031 2032 2033 2034 2035

	private runRestartTaskCommand(accessor: ServicesAccessor, arg: any): void {
		if (!this.canRunCommand()) {
			return;
		}
		if (this.inTerminal()) {
			this.getActiveTasks().then((activeTasks) => {
				if (activeTasks.length === 0) {
2036
					this.messageService.show(Severity.Info, nls.localize('TaskService.noTaskToRestart', 'No task to restart.'));
2037 2038
					return;
				}
2039
				this.showQuickPick(activeTasks, nls.localize('TaskService.tastToRestart', 'Select the task to restart'), false, true).then(task => {
2040 2041 2042 2043
					if (task) {
						this.restart(task);
					}
				});
2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054
			});
		} else {
			this.getActiveTasks().then((activeTasks) => {
				if (activeTasks.length === 0) {
					return;
				}
				let task = activeTasks[0];
				this.restart(task);
			});
		}
	}
2055 2056 2057 2058 2059

	private runConfigureDefaultBuildTask(): void {
		if (!this.canRunCommand()) {
			return;
		}
D
Dirk Baeumer 已提交
2060
		if (this._schemaVersion === JsonSchemaVersion.V2_0_0) {
2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080
			this.tasks().then((tasks => {
				if (tasks.length === 0) {
					this.configureBuildTask().run();
					return;
				}
				let defaultTask: Task;
				for (let task of tasks) {
					if (task.group === TaskGroup.Build && task.isDefaultGroupEntry) {
						defaultTask = task;
						break;
					}
				}
				if (defaultTask) {
					this.messageService.show(Severity.Info, nls.localize('TaskService.defaultBuildTaskExists', '{0} is already marked as the default build task.', defaultTask._label));
					return;
				}
				this.showQuickPick(tasks, nls.localize('TaskService.pickDefaultBuildTask', 'Select the task to be used as the default build task'), true).then((task) => {
					if (!task) {
						return;
					}
2081 2082 2083
					if (!CompositeTask.is(task)) {
						this.customize(task, { group: { kind: 'build', isDefault: true } }, true);
					}
2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094
				});
			}));
		} else {
			this.configureBuildTask().run();
		}
	}

	private runConfigureDefaultTestTask(): void {
		if (!this.canRunCommand()) {
			return;
		}
D
Dirk Baeumer 已提交
2095
		if (this._schemaVersion === JsonSchemaVersion.V2_0_0) {
2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114
			this.tasks().then((tasks => {
				if (tasks.length === 0) {
					this.configureAction().run();
				}
				let defaultTask: Task;
				for (let task of tasks) {
					if (task.group === TaskGroup.Test && task.isDefaultGroupEntry) {
						defaultTask = task;
						break;
					}
				}
				if (defaultTask) {
					this.messageService.show(Severity.Info, nls.localize('TaskService.defaultTestTaskExists', '{0} is already marked as the default test task.', defaultTask._label));
					return;
				}
				this.showQuickPick(tasks, nls.localize('TaskService.pickDefaultTestTask', 'Select the task to be used as the default test task'), true).then((task) => {
					if (!task) {
						return;
					}
2115 2116 2117
					if (!CompositeTask.is(task)) {
						this.customize(task, { group: { kind: 'test', isDefault: true } }, true);
					}
2118 2119 2120 2121 2122 2123
				});
			}));
		} else {
			this.configureAction().run();
		}
	}
2124 2125 2126 2127 2128 2129 2130 2131 2132 2133

	public runShowTasks(): void {
		if (!this.canRunCommand()) {
			return;
		}
		if (!this._taskSystem) {
			this.messageService.show(Severity.Info, nls.localize('TaskService.noTaskIsRunning', 'No task is running.'));
			return;
		}
		this.getActiveTasks().then((tasks) => {
2134 2135 2136 2137 2138
			if (tasks.length === 0) {
				this.messageService.show(Severity.Info, nls.localize('TaskService.noTaskIsRunning', 'No task is running.'));
			} else if (tasks.length === 1) {
				if (this._taskSystem) {
					this._taskSystem.revealTask(tasks[0]);
2139
				}
2140 2141 2142 2143 2144 2145 2146 2147
			} else {
				this.showQuickPick(tasks, nls.localize('TaskService.pickShowTask', 'Select the task to show its output'), false, true).then((task) => {
					if (!task || !this._taskSystem) {
						return;
					}
					this._taskSystem.revealTask(task);
				});
			}
2148 2149
		});
	}
E
Erich Gamma 已提交
2150 2151
}

2152

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

2156 2157
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' } });
2158
MenuRegistry.addCommand({ id: 'workbench.action.tasks.restartTask', title: { value: nls.localize('RestartTaskAction.label', "Restart Running Task"), original: 'Restart Running Task' }, category: { value: tasksCategory, original: 'Tasks' } });
2159
MenuRegistry.addCommand({ id: 'workbench.action.tasks.showTasks', title: { value: nls.localize('ShowTasksAction.label', "Show Running Tasks"), original: 'Show Running Tasks' }, category: { value: tasksCategory, original: 'Tasks' } });
2160
MenuRegistry.addCommand({ id: 'workbench.action.tasks.terminate', title: { value: nls.localize('TerminateAction.label', "Terminate Task"), original: 'Terminate Task' }, category: { value: tasksCategory, original: 'Tasks' } });
2161 2162
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' } });
2163 2164
MenuRegistry.addCommand({ id: 'workbench.action.tasks.configureDefaultBuildTask', title: { value: nls.localize('ConfigureDefaultBuildTask.label', "Configure Default Build Task"), original: 'Configure Default Build Task' }, category: { value: tasksCategory, original: 'Tasks' } });
MenuRegistry.addCommand({ id: 'workbench.action.tasks.configureDefaultTestTask', title: { value: nls.localize('ConfigureDefaultTestTask.label', "Configure Default Test Task"), original: 'Configure Default Test Task' }, category: { value: tasksCategory, original: 'Tasks' } });
2165 2166
// 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 });
2167 2168 2169 2170 2171

// Task Service
registerSingleton(ITaskService, TaskService);

// Register Quick Open
2172
const quickOpenRegistry = (<IQuickOpenRegistry>Registry.as(QuickOpenExtensions.Quickopen));
2173
const tasksPickerContextKey = 'inTasksPicker';
2174 2175

quickOpenRegistry.registerQuickOpenHandler(
2176 2177 2178 2179
	new QuickOpenHandlerDescriptor(
		'vs/workbench/parts/tasks/browser/taskQuickOpen',
		'QuickOpenHandler',
		'task ',
2180
		tasksPickerContextKey,
2181 2182 2183 2184
		nls.localize('quickOpen.task', "Run Task")
	)
);

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

2188 2189
// Status bar
let statusbarRegistry = <IStatusbarRegistry>Registry.as(StatusbarExtensions.Statusbar);
2190 2191
statusbarRegistry.registerStatusbarItem(new StatusbarItemDescriptor(BuildStatusBarItem, StatusbarAlignment.LEFT, 50 /* Medium Priority */));
statusbarRegistry.registerStatusbarItem(new StatusbarItemDescriptor(TaskStatusBarItem, StatusbarAlignment.LEFT, 50 /* Medium Priority */));
2192 2193 2194 2195 2196 2197 2198 2199 2200

// 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 已提交
2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211
let schema: IJSONSchema = {
	id: schemaId,
	description: 'Task definition file',
	type: 'object',
	default: {
		version: '0.1.0',
		command: 'myCommand',
		isShellCommand: false,
		args: [],
		showOutput: 'always',
		tasks: [
2212
			{
D
Dirk Baeumer 已提交
2213 2214 2215 2216
				taskName: 'build',
				showOutput: 'silent',
				isBuildCommand: true,
				problemMatcher: ['$tsc', '$lessCompile']
2217 2218
			}
		]
D
Dirk Baeumer 已提交
2219 2220 2221 2222 2223 2224 2225 2226 2227
	}
};

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


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