task.contribution.ts 87.5 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6 7 8 9 10
/*---------------------------------------------------------------------------------------------
 *  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 * as nls from 'vs/nls';

11
import { QuickOpenHandler } from 'vs/workbench/parts/tasks/browser/taskQuickOpen';
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 { MenuRegistry } from 'vs/platform/actions/common/actions';
E
Erich Gamma 已提交
34
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
D
Dirk Baeumer 已提交
35
import { IMessageService, IChoiceService } from 'vs/platform/message/common/message';
E
Erich Gamma 已提交
36 37
import { IMarkerService, MarkerStatistics } from 'vs/platform/markers/common/markers';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
38
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
39
import { IFileService, IFileStat } from 'vs/platform/files/common/files';
A
Alex Dima 已提交
40
import { IExtensionService } from 'vs/platform/extensions/common/extensions';
41
import { CommandsRegistry } from 'vs/platform/commands/common/commands';
42 43
import { KeybindingsRegistry } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
44
import { ProblemMatcherRegistry, NamedProblemMatcher } from 'vs/platform/markers/common/problemMatcher';
45
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
46
import { IProgressService2, IProgressOptions, ProgressLocation } from 'vs/platform/progress/common/progress';
47
import { IOpenerService } from 'vs/platform/opener/common/opener';
48 49
import { IWindowService } from 'vs/platform/windows/common/windows';

E
Erich Gamma 已提交
50 51 52 53

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

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

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

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

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

73 74
import { ITerminalService } from 'vs/workbench/parts/terminal/common/terminal';

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

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

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

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

91 92
import { ReloadWindowAction } from 'vs/workbench/electron-browser/actions';

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

96 97 98
namespace ConfigureTaskAction {
	export const ID = 'workbench.action.tasks.configureTaskRunner';
	export const TEXT = nls.localize('ConfigureTaskRunnerAction.label', "Configure Task");
99 100
}

101 102 103
namespace ConfigureBuildTaskAction {
	export const ID = 'workbench.action.tasks.configureBuildTask';
	export const TEXT = nls.localize('ConfigureBuildTaskAction.label', "Configure Build Task");
104 105
}

E
Erich Gamma 已提交
106 107 108 109 110 111 112 113 114 115
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);
	}
116
	public run(): TPromise<void> {
E
Erich Gamma 已提交
117 118 119
		if (this.closeFunction) {
			this.closeFunction();
		}
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
		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 已提交
136 137 138
	}
}

139
class BuildStatusBarItem extends Themable implements IStatusbarItem {
E
Erich Gamma 已提交
140 141
	private intervalToken: any;
	private activeCount: number;
J
Johannes Rieken 已提交
142
	private static progressChars: string = '|/-\\';
143 144 145 146 147 148 149 150
	private icons: HTMLElement[];

	constructor(
		@IPanelService private panelService: IPanelService,
		@IMarkerService private markerService: IMarkerService,
		@IOutputService private outputService: IOutputService,
		@ITaskService private taskService: ITaskService,
		@IPartService private partService: IPartService,
151 152
		@IThemeService themeService: IThemeService,
		@IWorkspaceContextService private contextService: IWorkspaceContextService
153 154
	) {
		super(themeService);
E
Erich Gamma 已提交
155 156

		this.activeCount = 0;
157
		this.icons = [];
B
Benjamin Pasero 已提交
158 159 160 161 162

		this.registerListeners();
	}

	private registerListeners(): void {
163
		this.toUnbind.push(this.contextService.onDidChangeWorkbenchState(() => this.updateStyles()));
E
Erich Gamma 已提交
164 165
	}

166 167
	protected updateStyles(): void {
		super.updateStyles();
E
Erich Gamma 已提交
168

169
		this.icons.forEach(icon => {
170
			icon.style.backgroundColor = this.getColor(this.contextService.getWorkbenchState() !== WorkbenchState.EMPTY ? STATUS_BAR_FOREGROUND : STATUS_BAR_NO_FOLDER_FOREGROUND);
171 172
		});
	}
E
Erich Gamma 已提交
173

174 175 176 177 178 179 180 181 182 183 184 185
	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 已提交
186

187
		Dom.addClass(element, 'task-statusbar-item');
E
Erich Gamma 已提交
188 189 190

		Dom.addClass(progress, 'task-statusbar-item-progress');
		element.appendChild(progress);
191
		progress.innerHTML = BuildStatusBarItem.progressChars[0];
E
Erich Gamma 已提交
192 193 194 195
		$(progress).hide();

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

198
		Dom.addClass(errorIcon, 'task-statusbar-item-label-error');
199
		Dom.addClass(errorIcon, 'mask-icon');
200 201 202 203
		label.appendChild(errorIcon);
		this.icons.push(errorIcon);

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

207
		Dom.addClass(warningIcon, 'task-statusbar-item-label-warning');
208
		Dom.addClass(warningIcon, 'mask-icon');
209 210 211 212
		label.appendChild(warningIcon);
		this.icons.push(warningIcon);

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

216
		Dom.addClass(infoIcon, 'task-statusbar-item-label-info');
217
		Dom.addClass(infoIcon, 'mask-icon');
218 219 220 221 222
		label.appendChild(infoIcon);
		this.icons.push(infoIcon);
		$(infoIcon).hide();

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

J
Johannes Rieken 已提交
226 227
		callOnDispose.push(Dom.addDisposableListener(label, 'click', (e: MouseEvent) => {
			const panel = this.panelService.getActivePanel();
228 229 230 231 232
			if (panel && panel.getId() === Constants.MARKERS_PANEL_ID) {
				this.partService.setPanelHidden(true);
			} else {
				this.panelService.openPanel(Constants.MARKERS_PANEL_ID, true);
			}
J
Johannes Rieken 已提交
233
		}));
E
Erich Gamma 已提交
234

235
		let updateStatus = (element: HTMLDivElement, icon: HTMLDivElement, stats: number): boolean => {
E
Erich Gamma 已提交
236 237 238
			if (stats > 0) {
				element.innerHTML = stats.toString();
				$(element).show();
239
				$(icon).show();
E
Erich Gamma 已提交
240 241 242
				return true;
			} else {
				$(element).hide();
243
				$(icon).hide();
E
Erich Gamma 已提交
244 245 246 247 248 249 250 251
				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;
252
			updateStatus(info, infoIcon, stats.infos);
E
Erich Gamma 已提交
253 254 255 256 257 258
		};

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

259
		callOnDispose.push(this.taskService.addListener(TaskServiceEvents.Active, (event: TaskEvent) => {
260
			if (this.ignoreEvent(event)) {
261 262
				return;
			}
E
Erich Gamma 已提交
263 264 265
			this.activeCount++;
			if (this.activeCount === 1) {
				let index = 1;
266
				let chars = BuildStatusBarItem.progressChars;
E
Erich Gamma 已提交
267 268 269 270 271 272 273 274 275 276 277 278
				progress.innerHTML = chars[0];
				this.intervalToken = setInterval(() => {
					progress.innerHTML = chars[index];
					index++;
					if (index >= chars.length) {
						index = 0;
					}
				}, 50);
				$(progress).show();
			}
		}));

279
		callOnDispose.push(this.taskService.addListener(TaskServiceEvents.Inactive, (event: TaskEvent) => {
280
			if (this.ignoreEvent(event)) {
281 282
				return;
			}
283 284 285 286 287 288 289 290 291 292 293
			// 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 已提交
294 295 296
			}
		}));

297
		callOnDispose.push(this.taskService.addListener(TaskServiceEvents.Terminated, (event: TaskEvent) => {
298
			if (this.ignoreEvent(event)) {
299 300
				return;
			}
E
Erich Gamma 已提交
301 302 303 304 305 306 307 308 309 310 311 312
			if (this.activeCount !== 0) {
				$(progress).hide();
				if (this.intervalToken) {
					clearInterval(this.intervalToken);
					this.intervalToken = null;
				}
				this.activeCount = 0;
			}
		}));

		container.appendChild(element);

313 314
		this.updateStyles();

E
Erich Gamma 已提交
315
		return {
316
			dispose: () => {
J
Joao Moreno 已提交
317
				callOnDispose = dispose(callOnDispose);
318
			}
E
Erich Gamma 已提交
319 320
		};
	}
321 322 323 324 325 326 327 328 329 330 331 332 333

	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 已提交
334 335
}

336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
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 {
355

356
		let callOnDispose: IDisposable[] = [];
357 358
		const element = document.createElement('a');
		Dom.addClass(element, 'task-statusbar-runningItem');
359

360 361 362
		let labelElement = document.createElement('div');
		Dom.addClass(labelElement, 'task-statusbar-runningItem-label');
		element.appendChild(labelElement);
363

364 365
		let label = new OcticonLabel(labelElement);
		label.title = nls.localize('runningTasks', "Show Running Tasks");
366

367
		$(element).hide();
368

369
		callOnDispose.push(Dom.addDisposableListener(labelElement, 'click', (e: MouseEvent) => {
370 371 372 373 374 375
			(this.taskService as TaskService).runShowTasks();
		}));

		let updateStatus = (): void => {
			this.taskService.getActiveTasks().then(tasks => {
				if (tasks.length === 0) {
376
					$(element).hide();
377
				} else {
378 379
					label.text = `$(tools) ${tasks.length}`;
					$(element).show();
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
				}
			});
		};

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

		container.appendChild(element);

		this.updateStyles();
		updateStatus();

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

E
Erich Gamma 已提交
401 402 403 404
interface TaskServiceEventData {
	error?: any;
}

405
class NullTaskSystem extends EventEmitter implements ITaskSystem {
406
	public run(task: Task): ITaskExecuteResult {
407
		return {
408
			kind: TaskExecuteKind.Started,
409 410 411
			promise: TPromise.as<ITaskSummary>({})
		};
	}
412 413 414
	public revealTask(task: Task): boolean {
		return false;
	}
415 416 417 418 419 420
	public isActive(): TPromise<boolean> {
		return TPromise.as(false);
	}
	public isActiveSync(): boolean {
		return false;
	}
421 422 423
	public getActiveTasks(): Task[] {
		return [];
	}
424 425 426
	public canAutoTerminate(): boolean {
		return true;
	}
427 428
	public terminate(task: string | Task): TPromise<TaskTerminateResponse> {
		return TPromise.as<TaskTerminateResponse>({ success: true, task: undefined });
429
	}
430 431
	public terminateAll(): TPromise<TaskTerminateResponse[]> {
		return TPromise.as<TaskTerminateResponse[]>([]);
432 433 434
	}
}

435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
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();
	}
}

472
interface WorkspaceTaskResult {
473
	set: TaskSet;
474 475
	configurations: {
		byIdentifier: IStringDictionary<ConfiguringTask>;
476
	};
477 478 479
	hasErrors: boolean;
}

480
interface WorkspaceFolderTaskResult extends WorkspaceTaskResult {
S
Sandeep Somavarapu 已提交
481
	workspaceFolder: IWorkspaceFolder;
482 483 484
}

interface WorkspaceFolderConfigurationResult {
S
Sandeep Somavarapu 已提交
485
	workspaceFolder: IWorkspaceFolder;
486 487 488 489
	config: TaskConfig.ExternalTaskRunnerConfiguration;
	hasErrors: boolean;
}

490 491 492 493
interface TaskCustomizationTelementryEvent {
	properties: string[];
}

494 495 496 497 498 499 500 501 502 503
class TaskMap {
	private _store: Map<string, Task[]> = new Map();

	constructor() {
	}

	public forEach(callback: (value: Task[], folder: string) => void): void {
		this._store.forEach(callback);
	}

S
Sandeep Somavarapu 已提交
504
	public get(workspaceFolder: IWorkspaceFolder | string): Task[] {
505 506 507 508 509 510 511 512
		let result: Task[] = Types.isString(workspaceFolder) ? this._store.get(workspaceFolder) : this._store.get(workspaceFolder.uri.toString());
		if (!result) {
			result = [];
			Types.isString(workspaceFolder) ? this._store.set(workspaceFolder, result) : this._store.set(workspaceFolder.uri.toString(), result);
		}
		return result;
	}

S
Sandeep Somavarapu 已提交
513
	public has(workspaceFolder: IWorkspaceFolder): boolean {
514 515 516
		return this._store.has(workspaceFolder.uri.toString());
	}

S
Sandeep Somavarapu 已提交
517
	public add(workspaceFolder: IWorkspaceFolder | string, ...task: Task[]): void {
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
		let values = Types.isString(workspaceFolder) ? this._store.get(workspaceFolder) : this._store.get(workspaceFolder.uri.toString());
		if (!values) {
			values = [];
			Types.isString(workspaceFolder) ? this._store.set(workspaceFolder, values) : this._store.set(workspaceFolder.uri.toString(), values);
		}
		values.push(...task);
	}

	public all(): Task[] {
		let result: Task[] = [];
		this._store.forEach((values) => result.push(...values));
		return result;
	}
}

533 534 535 536
interface TaskQuickPickEntry extends IPickOpenEntry {
	task: Task;
}

E
Erich Gamma 已提交
537
class TaskService extends EventEmitter implements ITaskService {
538

539
	// private static autoDetectTelemetryName: string = 'taskServer.autoDetect';
540
	private static RecentlyUsedTasks_Key = 'workbench.tasks.recentlyUsedTasks';
T
t-amqi 已提交
541
	private static RanTaskBefore_Key = 'workbench.tasks.ranTaskBefore';
D
Dirk Baeumer 已提交
542
	private static IgnoreTask010DonotShowAgain_key = 'workbench.tasks.ignoreTask010Shown';
543

544
	private static CustomizationTelemetryEventName: string = 'taskService.customize';
545
	public static TemplateTelemetryEventName: string = 'taskService.template';
546

547
	public _serviceBrand: any;
E
Erich Gamma 已提交
548
	public static SERVICE_ID: string = 'taskService';
J
Johannes Rieken 已提交
549 550
	public static OutputChannelId: string = 'tasks';
	public static OutputChannelLabel: string = nls.localize('tasks', "Tasks");
E
Erich Gamma 已提交
551 552 553

	private modeService: IModeService;
	private configurationService: IConfigurationService;
D
Dirk Baeumer 已提交
554
	private configurationEditingService: IConfigurationEditingService;
E
Erich Gamma 已提交
555 556 557
	private markerService: IMarkerService;
	private outputService: IOutputService;
	private messageService: IMessageService;
D
Dirk Baeumer 已提交
558
	private choiceService: IChoiceService;
E
Erich Gamma 已提交
559 560 561 562 563 564
	private fileService: IFileService;
	private telemetryService: ITelemetryService;
	private editorService: IWorkbenchEditorService;
	private contextService: IWorkspaceContextService;
	private textFileService: ITextFileService;
	private modelService: IModelService;
A
Alex Dima 已提交
565
	private extensionService: IExtensionService;
D
Dirk Baeumer 已提交
566
	private quickOpenService: IQuickOpenService;
E
Erich Gamma 已提交
567

568
	private _configHasErrors: boolean;
D
Dirk Baeumer 已提交
569 570 571
	private __schemaVersion: JsonSchemaVersion;
	private __executionEngine: ExecutionEngine;
	private __workspaceFolders: IWorkspaceFolder[];
D
Dirk Baeumer 已提交
572 573
	private __ignoredWorkspaceFolders: IWorkspaceFolder[];
	private __showIgnoreMessage: boolean;
574
	private _providers: Map<number, ITaskProvider>;
575

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

E
Erich Gamma 已提交
578
	private _taskSystem: ITaskSystem;
579
	private _taskSystemListeners: IDisposable[];
580
	private _recentlyUsedTasks: LinkedMap<string, string>;
581

582
	private _outputChannel: IOutputChannel;
E
Erich Gamma 已提交
583

J
Johannes Rieken 已提交
584
	constructor( @IModeService modeService: IModeService, @IConfigurationService configurationService: IConfigurationService,
D
Dirk Baeumer 已提交
585
		@IConfigurationEditingService configurationEditingService: IConfigurationEditingService,
E
Erich Gamma 已提交
586
		@IMarkerService markerService: IMarkerService, @IOutputService outputService: IOutputService,
D
Dirk Baeumer 已提交
587 588
		@IMessageService messageService: IMessageService, @IChoiceService choiceService: IChoiceService,
		@IWorkbenchEditorService editorService: IWorkbenchEditorService,
J
Johannes Rieken 已提交
589 590
		@IFileService fileService: IFileService, @IWorkspaceContextService contextService: IWorkspaceContextService,
		@ITelemetryService telemetryService: ITelemetryService, @ITextFileService textFileService: ITextFileService,
591
		@ILifecycleService lifecycleService: ILifecycleService,
A
Alex Dima 已提交
592
		@IModelService modelService: IModelService, @IExtensionService extensionService: IExtensionService,
593
		@IQuickOpenService quickOpenService: IQuickOpenService,
594
		@IEnvironmentService private environmentService: IEnvironmentService,
595
		@IConfigurationResolverService private configurationResolverService: IConfigurationResolverService,
596
		@ITerminalService private terminalService: ITerminalService,
597
		@IWorkbenchEditorService private workbenchEditorService: IWorkbenchEditorService,
598
		@IStorageService private storageService: IStorageService,
599
		@IProgressService2 private progressService: IProgressService2,
600 601
		@IOpenerService private openerService: IOpenerService,
		@IWindowService private _windowServive: IWindowService
602
	) {
E
Erich Gamma 已提交
603 604 605 606

		super();
		this.modeService = modeService;
		this.configurationService = configurationService;
D
Dirk Baeumer 已提交
607
		this.configurationEditingService = configurationEditingService;
E
Erich Gamma 已提交
608 609 610
		this.markerService = markerService;
		this.outputService = outputService;
		this.messageService = messageService;
D
Dirk Baeumer 已提交
611
		this.choiceService = choiceService;
E
Erich Gamma 已提交
612 613 614 615 616 617
		this.editorService = editorService;
		this.fileService = fileService;
		this.contextService = contextService;
		this.telemetryService = telemetryService;
		this.textFileService = textFileService;
		this.modelService = modelService;
A
Alex Dima 已提交
618
		this.extensionService = extensionService;
D
Dirk Baeumer 已提交
619
		this.quickOpenService = quickOpenService;
E
Erich Gamma 已提交
620

621 622
		this._configHasErrors = false;
		this._workspaceTasksPromise = undefined;
623
		this._taskSystem = undefined;
624 625 626
		this._taskSystemListeners = [];
		this._outputChannel = this.outputService.getChannel(TaskService.OutputChannelId);
		this._providers = new Map<number, ITaskProvider>();
J
Johannes Rieken 已提交
627
		this.configurationService.onDidUpdateConfiguration(() => {
628
			if (!this._taskSystem && !this._workspaceTasksPromise) {
629 630
				return;
			}
631 632 633
			if (!this._taskSystem || this._taskSystem instanceof TerminalTaskSystem) {
				this._outputChannel.clear();
			}
D
Dirk Baeumer 已提交
634
			let folderSetup = this.computeWorkspaceFolderSetup();
D
Dirk Baeumer 已提交
635
			if (this.executionEngine !== folderSetup[2]) {
636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
				if (this._taskSystem && this._taskSystem.getActiveTasks().length > 0) {
					this.messageService.show(
						Severity.Info,
						{
							message: nls.localize(
								'TaskSystem.noHotSwap',
								'Changing the task execution engine with an active task running requires to reload the Window'
							),
							actions: [
								new ReloadWindowAction(ReloadWindowAction.ID, ReloadWindowAction.LABEL, this._windowServive),
								new CloseMessageAction()
							]
						}
					);
					return;
				} else {
					this.disposeTaskSystemListeners();
					this._taskSystem = undefined;
				}
D
Dirk Baeumer 已提交
655
			}
D
Dirk Baeumer 已提交
656
			this.updateSetup(folderSetup);
D
Dirk Baeumer 已提交
657
			this.updateWorkspaceTasks();
E
Erich Gamma 已提交
658
		});
659
		lifecycleService.onWillShutdown(event => event.veto(this.beforeShutdown()));
660 661 662 663
		this.registerCommands();
	}

	private registerCommands(): void {
664
		CommandsRegistry.registerCommand('workbench.action.tasks.runTask', (accessor, arg) => {
665 666 667
			this.runTaskCommand(accessor, arg);
		});

668 669 670 671
		CommandsRegistry.registerCommand('workbench.action.tasks.restartTask', (accessor, arg) => {
			this.runRestartTaskCommand(accessor, arg);
		});

672 673 674 675 676 677 678 679 680 681 682 683 684 685 686
		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;
			}
687
			this.runBuildCommand();
688 689 690 691 692 693 694 695 696 697 698 699
		});

		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;
700
			}
701
			this.runTestCommand();
702
		});
703

704 705 706 707
		CommandsRegistry.registerCommand('workbench.action.tasks.configureTaskRunner', () => {
			this.runConfigureTasks();
		});

708 709 710 711 712 713 714
		CommandsRegistry.registerCommand('workbench.action.tasks.configureDefaultBuildTask', () => {
			this.runConfigureDefaultBuildTask();
		});

		CommandsRegistry.registerCommand('workbench.action.tasks.configureDefaultTestTask', () => {
			this.runConfigureDefaultTestTask();
		});
715 716 717 718

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

D
Dirk Baeumer 已提交
721 722 723 724 725 726 727
	private get workspaceFolders(): IWorkspaceFolder[] {
		if (!this.__workspaceFolders) {
			this.updateSetup();
		}
		return this.__workspaceFolders;
	}

D
Dirk Baeumer 已提交
728 729 730 731 732 733 734
	private get ignoredWorkspaceFolders(): IWorkspaceFolder[] {
		if (!this.__ignoredWorkspaceFolders) {
			this.updateSetup();
		}
		return this.__ignoredWorkspaceFolders;
	}

D
Dirk Baeumer 已提交
735 736 737 738 739 740 741 742 743 744 745 746 747 748
	private get executionEngine(): ExecutionEngine {
		if (this.__executionEngine === void 0) {
			this.updateSetup();
		}
		return this.__executionEngine;
	}

	private get schemaVersion(): JsonSchemaVersion {
		if (this.__schemaVersion === void 0) {
			this.updateSetup();
		}
		return this.__schemaVersion;
	}

D
Dirk Baeumer 已提交
749 750 751 752 753 754 755 756
	private get showIgnoreMessage(): boolean {
		if (this.__showIgnoreMessage === void 0) {
			this.__showIgnoreMessage = !this.storageService.getBoolean(TaskService.IgnoreTask010DonotShowAgain_key, StorageScope.WORKSPACE, false);
		}
		return this.__showIgnoreMessage;
	}

	private updateSetup(setup?: [IWorkspaceFolder[], IWorkspaceFolder[], ExecutionEngine, JsonSchemaVersion]): void {
D
Dirk Baeumer 已提交
757 758 759 760
		if (!setup) {
			setup = this.computeWorkspaceFolderSetup();
		}
		this.__workspaceFolders = setup[0];
D
Dirk Baeumer 已提交
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
		if (this.__ignoredWorkspaceFolders) {
			if (this.__ignoredWorkspaceFolders.length !== setup[1].length) {
				this.__showIgnoreMessage = undefined;
			} else {
				let set: Set<string> = new Set();
				this.__ignoredWorkspaceFolders.forEach(folder => set.add(folder.uri.toString()));
				for (let folder of setup[1]) {
					if (!set.has(folder.uri.toString())) {
						this.__showIgnoreMessage = undefined;
						break;
					}
				}
			}
		}
		this.__ignoredWorkspaceFolders = setup[1];
		this.__executionEngine = setup[2];
		this.__schemaVersion = setup[3];
D
Dirk Baeumer 已提交
778 779
	}

780
	private showOutput(): void {
781
		this._outputChannel.show(true);
782 783
	}

E
Erich Gamma 已提交
784
	private disposeTaskSystemListeners(): void {
785
		this._taskSystemListeners = dispose(this._taskSystemListeners);
E
Erich Gamma 已提交
786 787
	}

788 789 790 791
	public registerTaskProvider(handle: number, provider: ITaskProvider): void {
		if (!provider) {
			return;
		}
792
		this._providers.set(handle, provider);
793 794 795
	}

	public unregisterTaskProvider(handle: number): boolean {
796
		return this._providers.delete(handle);
797 798
	}

S
Sandeep Somavarapu 已提交
799
	public getTask(folder: IWorkspaceFolder | string, alias: string): TPromise<Task> {
D
Dirk Baeumer 已提交
800 801 802 803
		let name = Types.isString(folder) ? folder : folder.name;
		if (this.ignoredWorkspaceFolders.some(ignored => ignored.name === name)) {
			return TPromise.wrapError(new Error(nls.localize('TaskServer.folderIgnored', 'The folder {0} is ignored since it uses task version 0.1.0', name)));
		}
804 805 806 807 808 809 810 811 812 813 814
		return this.getGroupedTasks().then((map) => {
			let values = map.get(folder);
			if (!values) {
				return undefined;
			}
			for (let task of values) {
				if (Task.matches(task, alias)) {
					return task;
				}
			};
			return undefined;
815 816 817
		});
	}

818
	public tasks(): TPromise<Task[]> {
819
		return this.getGroupedTasks().then(result => result.all());
820 821
	};

822 823 824 825
	public createSorter(): TaskSorter {
		return new TaskSorter(this.contextService.getWorkspace() ? this.contextService.getWorkspace().folders : []);
	}

826 827 828 829 830 831 832
	public isActive(): TPromise<boolean> {
		if (!this._taskSystem) {
			return TPromise.as(false);
		}
		return this._taskSystem.isActive();
	}

833 834 835 836 837 838 839
	public getActiveTasks(): TPromise<Task[]> {
		if (!this._taskSystem) {
			return TPromise.as([]);
		}
		return TPromise.as(this._taskSystem.getActiveTasks());
	}

840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870
	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);
	}
871

872
	private openDocumentation(): void {
873 874 875
		this.openerService.open(URI.parse('https://go.microsoft.com/fwlink/?LinkId=733558'));
	}

876
	public build(): TPromise<ITaskSummary> {
877
		return this.getGroupedTasks().then((tasks) => {
D
Dirk Baeumer 已提交
878
			let runnable = this.createRunnableTask(tasks, TaskGroup.Build);
879
			if (!runnable || !runnable.task) {
D
Dirk Baeumer 已提交
880
				if (this.schemaVersion === JsonSchemaVersion.V0_1_0) {
881 882 883 884
					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);
				}
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
			}
			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> {
902
		return this.getGroupedTasks().then((tasks) => {
D
Dirk Baeumer 已提交
903
			let runnable = this.createRunnableTask(tasks, TaskGroup.Test);
904
			if (!runnable || !runnable.task) {
D
Dirk Baeumer 已提交
905
				if (this.schemaVersion === JsonSchemaVersion.V0_1_0) {
906 907 908 909
					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);
				}
910 911 912 913 914 915 916 917
			}
			return this.executeTask(runnable.task, runnable.resolver);
		}).then(value => value, (error) => {
			this.handleError(error);
			return TPromise.wrapError(error);
		});
	}

918 919 920 921
	public run(task: Task, options?: RunOptions): TPromise<ITaskSummary> {
		return this.getGroupedTasks().then((grouped) => {
			if (!task) {
				throw new TaskError(Severity.Info, nls.localize('TaskServer.noTask', 'Requested task {0} to execute not found.', task.name), TaskErrors.TaskNotFound);
922
			} else {
923
				let resolver = this.createResolver(grouped);
924
				if (options && options.attachProblemMatcher && this.shouldAttachProblemMatcher(task) && !InMemoryTask.is(task)) {
925
					return this.attachProblemMatcher(task).then((toExecute) => {
926 927 928 929 930 931 932
						if (toExecute) {
							return this.executeTask(toExecute, resolver);
						} else {
							return TPromise.as(undefined);
						}
					});
				}
933
				return this.executeTask(task, resolver);
934
			}
935 936 937 938 939 940
		}).then(value => value, (error) => {
			this.handleError(error);
			return TPromise.wrapError(error);
		});
	}

941
	private shouldAttachProblemMatcher(task: Task): boolean {
D
Dirk Baeumer 已提交
942
		if (!this.canCustomize(task)) {
943 944
			return false;
		}
945 946 947
		if (task.group !== void 0 && task.group !== TaskGroup.Build) {
			return false;
		}
948 949 950
		if (task.problemMatchers !== void 0 && task.problemMatchers.length > 0) {
			return false;
		}
951
		if (ContributedTask.is(task)) {
952
			return !task.hasDefinedMatchers && task.problemMatchers.length === 0;
953
		}
954 955 956 957 958
		if (CustomTask.is(task)) {
			let configProperties: TaskConfig.ConfigurationProperties = task._source.config.element;
			return configProperties.problemMatcher === void 0;
		}
		return false;
959 960
	}

961
	private attachProblemMatcher(task: ContributedTask | CustomTask): TPromise<Task> {
962 963
		interface ProblemMatcherPickEntry extends IPickOpenEntry {
			matcher: NamedProblemMatcher;
964
			never?: boolean;
965 966 967 968 969
			learnMore?: boolean;
		}
		let entries: ProblemMatcherPickEntry[] = [];
		for (let key of ProblemMatcherRegistry.keys()) {
			let matcher = ProblemMatcherRegistry.get(key);
970 971 972
			if (matcher.deprecated) {
				continue;
			}
973 974 975 976 977 978 979 980 981 982 983 984
			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));
985
			entries[0].separator = { border: true, label: nls.localize('TaskService.associate', 'associate') };
986
			entries.unshift(
987 988 989
				{ 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 }
990 991
			);
			return this.quickOpenService.pick(entries, {
992
				placeHolder: nls.localize('selectProblemMatcher', 'Select for which kind of errors and warnings to scan the task output'),
993 994 995 996 997 998
				autoFocus: { autoFocusFirstEntry: true }
			}).then((selected) => {
				if (selected) {
					if (selected.learnMore) {
						this.openDocumentation();
						return undefined;
999 1000 1001
					} else if (selected.never) {
						this.customize(task, { problemMatcher: [] }, true);
						return task;
1002
					} else if (selected.matcher) {
1003
						let newTask = Task.clone(task);
1004 1005 1006 1007 1008 1009 1010 1011
						let matcherReference = `$${selected.matcher.name}`;
						newTask.problemMatchers = [matcherReference];
						this.customize(task, { problemMatcher: [matcherReference] }, true);
						return newTask;
					} else {
						return task;
					}
				} else {
1012
					return undefined;
1013 1014 1015 1016 1017 1018
				}
			});
		}
		return TPromise.as(task);
	}

1019
	public getTasksForGroup(group: string): TPromise<Task[]> {
1020
		return this.getGroupedTasks().then((groups) => {
1021
			let result: Task[] = [];
1022 1023 1024 1025 1026
			groups.forEach((tasks) => {
				for (let task of tasks) {
					if (task.group === group) {
						result.push(task);
					}
1027
				}
1028
			});
1029 1030 1031 1032
			return result;
		});
	}

1033 1034
	public needsFolderQualification(): boolean {
		return this.contextService.getWorkbenchState() === WorkbenchState.WORKSPACE;
D
Dirk Baeumer 已提交
1035 1036 1037
	}

	public canCustomize(task: Task): boolean {
D
Dirk Baeumer 已提交
1038
		if (this.schemaVersion !== JsonSchemaVersion.V2_0_0) {
D
Dirk Baeumer 已提交
1039 1040 1041 1042 1043 1044 1045 1046 1047
			return false;
		}
		if (CustomTask.is(task)) {
			return true;
		}
		if (ContributedTask.is(task)) {
			return !!Task.getWorkspaceFolder(task);
		}
		return false;
1048 1049
	}

1050
	public customize(task: ContributedTask | CustomTask, properties?: CustomizationProperties, openConfig?: boolean): TPromise<void> {
D
Dirk Baeumer 已提交
1051 1052 1053 1054 1055
		let workspaceFolder = Task.getWorkspaceFolder(task);
		if (!workspaceFolder) {
			return TPromise.as<void>(undefined);
		}
		let configuration = this.getConfiguration(workspaceFolder);
D
Dirk Baeumer 已提交
1056 1057 1058 1059
		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);
		}
1060

D
Dirk Baeumer 已提交
1061
		let fileConfig = configuration.config;
1062
		let index: number;
1063
		let toCustomize: TaskConfig.CustomTask | TaskConfig.ConfiguringTask;
1064
		let taskConfig = CustomTask.is(task) ? task._source.config : undefined;
1065 1066 1067
		if (taskConfig && taskConfig.element) {
			index = taskConfig.index;
			toCustomize = taskConfig.element;
1068 1069 1070 1071 1072 1073
		} 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]);
1074 1075 1076
			if (task.problemMatchers && task.problemMatchers.length > 0 && Types.isStringArray(task.problemMatchers)) {
				toCustomize.problemMatcher = task.problemMatchers;
			}
1077 1078 1079 1080
		}
		if (!toCustomize) {
			return TPromise.as(undefined);
		}
1081 1082 1083 1084
		if (properties) {
			for (let property of Object.getOwnPropertyNames(properties)) {
				let value = properties[property];
				if (value !== void 0 && value !== null) {
1085
					toCustomize[property] = value;
1086 1087 1088
				}
			}
		} else {
1089
			if (toCustomize.problemMatcher === void 0 && task.problemMatchers === void 0 || task.problemMatchers.length === 0) {
1090
				toCustomize.problemMatcher = [];
1091
			}
1092
		}
1093

1094
		let promise: TPromise<void>;
D
Dirk Baeumer 已提交
1095
		if (!fileConfig) {
1096
			let value = {
D
Dirk Baeumer 已提交
1097
				version: '2.0.0',
1098
				tasks: [toCustomize]
D
Dirk Baeumer 已提交
1099
			};
1100 1101 1102 1103 1104 1105 1106 1107 1108
			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));
			}
1109
			promise = this.fileService.createFile(workspaceFolder.toResource('.vscode/tasks.json'), content).then(() => { });
D
Dirk Baeumer 已提交
1110
		} else {
1111
			let value: IConfigurationValue = { key: undefined, value: undefined };
1112 1113
			// We have a global task configuration
			if (index === -1) {
1114 1115 1116 1117
				if (properties.problemMatcher !== void 0) {
					fileConfig.problemMatcher = properties.problemMatcher;
					value.key = 'tasks.problemMatchers';
					value.value = fileConfig.problemMatcher;
D
Dirk Baeumer 已提交
1118
					promise = this.writeConfiguration(workspaceFolder, value);
1119 1120 1121 1122
				} else if (properties.group !== void 0) {
					fileConfig.group = properties.group;
					value.key = 'tasks.group';
					value.value = fileConfig.group;
D
Dirk Baeumer 已提交
1123
					promise = this.writeConfiguration(workspaceFolder, value);
1124
				}
1125 1126 1127 1128 1129 1130 1131
			} else {
				if (!Array.isArray(fileConfig.tasks)) {
					fileConfig.tasks = [];
				}
				value.key = 'tasks.tasks';
				value.value = fileConfig.tasks;
				if (index === void 0) {
1132 1133 1134 1135
					fileConfig.tasks.push(toCustomize);
				} else {
					fileConfig.tasks[index] = toCustomize;
				}
D
Dirk Baeumer 已提交
1136
				promise = this.writeConfiguration(workspaceFolder, value);
D
Dirk Baeumer 已提交
1137 1138
			}
		};
1139 1140 1141
		if (!promise) {
			return TPromise.as(undefined);
		}
1142
		return promise.then(() => {
1143 1144 1145
			let event: TaskCustomizationTelementryEvent = {
				properties: properties ? Object.getOwnPropertyNames(properties) : []
			};
K
kieferrm 已提交
1146
			/* __GDPR__
K
kieferrm 已提交
1147 1148 1149 1150
				"taskService.customize" : {
					"properties" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
				}
			*/
1151
			this.telemetryService.publicLog(TaskService.CustomizationTelemetryEventName, event);
D
Dirk Baeumer 已提交
1152
			if (openConfig) {
1153
				let resource = workspaceFolder.toResource('.vscode/tasks.json');
D
Dirk Baeumer 已提交
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
				this.editorService.openEditor({
					resource: resource,
					options: {
						forceOpen: true,
						pinned: false
					}
				}, false);
			}
		});
	}

S
Sandeep Somavarapu 已提交
1165
	private writeConfiguration(workspaceFolder: IWorkspaceFolder, value: IConfigurationValue): TPromise<void, any> {
D
Dirk Baeumer 已提交
1166 1167 1168 1169 1170 1171 1172 1173 1174
		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;
		}
	}

1175
	public openConfig(task: CustomTask): TPromise<void> {
1176
		let resource = Task.getWorkspaceFolder(task).toResource(task._source.config.file);
1177 1178 1179 1180 1181 1182 1183 1184 1185
		return this.editorService.openEditor({
			resource: resource,
			options: {
				forceOpen: true,
				pinned: false
			}
		}, false).then(() => undefined);
	}

1186 1187 1188 1189 1190 1191
	private createRunnableTask(tasks: TaskMap, group: TaskGroup): { task: Task; resolver: ITaskResolver } {
		interface ResolverData {
			id: Map<string, Task>;
			label: Map<string, Task>;
			identifier: Map<string, Task>;
		}
1192

1193
		let resolverData: Map<string, ResolverData> = new Map();
1194 1195
		let workspaceTasks: Task[] = [];
		let extensionTasks: Task[] = [];
1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
		tasks.forEach((tasks, folder) => {
			let data = resolverData.get(folder);
			if (!data) {
				data = {
					id: new Map<string, Task>(),
					label: new Map<string, Task>(),
					identifier: new Map<string, Task>()
				};
				resolverData.set(folder, data);
			}
			for (let task of tasks) {
				data.id.set(task._id, task);
				data.label.set(task._label, task);
				data.identifier.set(task.identifier, task);
				if (group && task.group === group) {
					if (task._source.kind === TaskSourceKind.Workspace) {
						workspaceTasks.push(task);
					} else {
						extensionTasks.push(task);
					}
1216
				}
D
Dirk Baeumer 已提交
1217
			}
1218 1219
		});
		let resolver: ITaskResolver = {
S
Sandeep Somavarapu 已提交
1220
			resolve: (workspaceFolder: IWorkspaceFolder, alias: string) => {
1221 1222 1223 1224 1225
				let data = resolverData.get(workspaceFolder.uri.toString());
				if (!data) {
					return undefined;
				}
				return data.id.get(alias) || data.label.get(alias) || data.identifier.get(alias);
1226 1227
			}
		};
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
		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;
		}

1238 1239
		// We can only have extension tasks if we are in version 2.0.0. Then we can even run
		// multiple build tasks.
1240 1241
		if (extensionTasks.length === 1) {
			return { task: extensionTasks[0], resolver };
1242 1243
		} else {
			let id: string = UUID.generateUuid();
1244
			let task: InMemoryTask = {
1245
				_id: id,
1246
				_source: { kind: TaskSourceKind.InMemory, label: 'inMemory' },
1247
				_label: id,
1248
				type: 'inMemory',
1249 1250
				name: id,
				identifier: id,
1251
				dependsOn: extensionTasks.map((task) => { return { workspaceFolder: Task.getWorkspaceFolder(task), task: task._id }; })
1252 1253
			};
			return { task, resolver };
E
Erich Gamma 已提交
1254 1255 1256
		}
	}

1257 1258 1259 1260 1261
	private createResolver(grouped: TaskMap): ITaskResolver {
		interface ResolverData {
			label: Map<string, Task>;
			identifier: Map<string, Task>;
		}
1262

1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273
		let resolverData: Map<string, ResolverData> = new Map();
		grouped.forEach((tasks, folder) => {
			let data = resolverData.get(folder);
			if (!data) {
				data = { label: new Map<string, Task>(), identifier: new Map<string, Task>() };
				resolverData.set(folder, data);
			}
			for (let task of tasks) {
				data.label.set(task._label, task);
				data.identifier.set(task.identifier, task);
			}
1274 1275
		});
		return {
S
Sandeep Somavarapu 已提交
1276
			resolve: (workspaceFolder: IWorkspaceFolder, alias: string) => {
1277 1278 1279 1280 1281
				let data = resolverData.get(workspaceFolder.uri.toString());
				if (!data) {
					return undefined;
				}
				return data.label.get(alias) || data.identifier.get(alias);
1282
			}
1283 1284 1285 1286
		};
	}

	private executeTask(task: Task, resolver: ITaskResolver): TPromise<ITaskSummary> {
T
t-amqi 已提交
1287 1288
		if (!this.storageService.get(TaskService.RanTaskBefore_Key, StorageScope.GLOBAL)) {
			this.storageService.store(TaskService.RanTaskBefore_Key, true, StorageScope.GLOBAL);
T
t-amqi 已提交
1289
		}
1290 1291 1292
		return ProblemMatcherRegistry.onReady().then(() => {
			return this.textFileService.saveAll().then((value) => { // make sure all dirty files are saved
				let executeResult = this.getTaskSystem().run(task, resolver);
1293 1294 1295 1296
				let key = Task.getRecentlyUsedKey(task);
				if (key) {
					this.getRecentlyUsedTasks().set(key, key, Touch.First);
				}
1297 1298
				if (executeResult.kind === TaskExecuteKind.Active) {
					let active = executeResult.active;
1299 1300
					if (active.same) {
						if (active.background) {
1301
							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.getQualifiedLabel(task)));
1302
						} else {
1303
							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.getQualifiedLabel(task)));
1304
						}
1305 1306 1307
					} 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);
					}
1308
				}
1309 1310
				return executeResult.promise;
			});
1311 1312 1313
		});
	}

1314
	public restart(task: Task): void {
1315 1316 1317
		if (!this._taskSystem) {
			return;
		}
1318
		this._taskSystem.terminate(task).then((response) => {
1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
			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;
		});
	}

1329
	public terminate(task: Task): TPromise<TaskTerminateResponse> {
1330
		if (!this._taskSystem) {
1331
			return TPromise.as({ success: true, task: undefined });
1332
		}
1333
		return this._taskSystem.terminate(task);
1334 1335
	}

1336
	public terminateAll(): TPromise<TaskTerminateResponse[]> {
1337
		if (!this._taskSystem) {
1338
			return TPromise.as<TaskTerminateResponse[]>([]);
1339
		}
1340
		return this._taskSystem.terminateAll();
1341 1342 1343 1344 1345 1346
	}

	private getTaskSystem(): ITaskSystem {
		if (this._taskSystem) {
			return this._taskSystem;
		}
D
Dirk Baeumer 已提交
1347
		if (this.executionEngine === ExecutionEngine.Terminal) {
1348 1349 1350
			this._taskSystem = new TerminalTaskSystem(
				this.terminalService, this.outputService, this.markerService,
				this.modelService, this.configurationResolverService, this.telemetryService,
1351
				this.workbenchEditorService, this.contextService,
1352 1353 1354 1355 1356
				TaskService.OutputChannelId
			);
		} else {
			let system = new ProcessTaskSystem(
				this.markerService, this.modelService, this.telemetryService, this.outputService,
1357
				this.configurationResolverService, this.contextService, TaskService.OutputChannelId,
1358 1359 1360 1361
			);
			system.hasErrors(this._configHasErrors);
			this._taskSystem = system;
		}
A
Alex Dima 已提交
1362 1363
		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)));
1364
		this._taskSystemListeners.push(this._taskSystem.addListener(TaskSystemEvents.Terminated, (event) => this.emit(TaskServiceEvents.Terminated, event)));
1365
		this._taskSystemListeners.push(this._taskSystem.addListener(TaskSystemEvents.Changed, () => this.emit(TaskServiceEvents.Changed)));
1366 1367 1368
		return this._taskSystem;
	}

1369
	private getGroupedTasks(): TPromise<TaskMap> {
D
Dirk Baeumer 已提交
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
		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 已提交
1387
				if (this.schemaVersion === JsonSchemaVersion.V2_0_0 && this._providers.size > 0) {
D
Dirk Baeumer 已提交
1388 1389 1390 1391 1392
					this._providers.forEach((provider) => {
						counter++;
						provider.provideTasks().done(done, error);
					});
				} else {
1393 1394
					resolve(result);
				}
D
Dirk Baeumer 已提交
1395
			});
D
Dirk Baeumer 已提交
1396
		}).then((contributedTaskSets) => {
1397 1398
			let result: TaskMap = new TaskMap();
			let contributedTasks: TaskMap = new TaskMap();
D
Dirk Baeumer 已提交
1399 1400
			for (let set of contributedTaskSets) {
				for (let task of set.tasks) {
1401
					let workspaceFolder = Task.getWorkspaceFolder(task);
D
Dirk Baeumer 已提交
1402
					if (workspaceFolder) {
1403
						contributedTasks.add(workspaceFolder, task);
D
Dirk Baeumer 已提交
1404 1405 1406 1407 1408 1409
					}
				}
			}
			return this.getWorkspaceTasks().then((customTasks) => {
				customTasks.forEach((folderTasks, key) => {
					let contributed = contributedTasks.get(key);
1410 1411
					if (!folderTasks.set) {
						if (contributed) {
1412
							result.add(key, ...contributed);
1413 1414 1415 1416
						}
						return;
					}

D
Dirk Baeumer 已提交
1417
					if (!contributed) {
1418
						result.add(key, ...folderTasks.set.tasks);
D
Dirk Baeumer 已提交
1419 1420 1421 1422 1423 1424 1425
					} 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)) {
1426 1427
									continue;
								}
D
Dirk Baeumer 已提交
1428 1429 1430
								if (configurations) {
									let configuringTask = configurations.byIdentifier[task.defines._key];
									if (configuringTask) {
1431
										result.add(key, TaskConfig.createCustomTask(task, configuringTask));
D
Dirk Baeumer 已提交
1432
									} else {
1433
										result.add(key, task);
D
Dirk Baeumer 已提交
1434 1435 1436 1437
									}
								} else if (legacyTaskConfigurations) {
									let configuringTask = legacyTaskConfigurations[task.defines._key];
									if (configuringTask) {
1438
										result.add(key, TaskConfig.createCustomTask(task, configuringTask));
D
Dirk Baeumer 已提交
1439
										customTasksToDelete.push(configuringTask);
D
Dirk Baeumer 已提交
1440
									} else {
1441
										result.add(key, task);
D
Dirk Baeumer 已提交
1442 1443
									}
								} else {
1444
									result.add(key, task);
D
Dirk Baeumer 已提交
1445
								}
1446
							}
D
Dirk Baeumer 已提交
1447 1448 1449 1450 1451 1452 1453 1454 1455
							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;
									}
1456
									result.add(key, task);
1457
								}
D
Dirk Baeumer 已提交
1458
							} else {
1459
								result.add(key, ...folderTasks.set.tasks);
1460
							}
D
Dirk Baeumer 已提交
1461
						} else {
1462 1463
							result.add(key, ...folderTasks.set.tasks);
							result.add(key, ...contributed);
1464 1465
						}
					}
D
Dirk Baeumer 已提交
1466
				});
1467 1468 1469
				return result;
			}, () => {
				// If we can't read the tasks.json file provide at least the contributed tasks
1470
				let result: TaskMap = new TaskMap();
D
Dirk Baeumer 已提交
1471
				for (let set of contributedTaskSets) {
1472 1473 1474
					for (let task of set.tasks) {
						result.add(Task.getWorkspaceFolder(task), task);
					}
D
Dirk Baeumer 已提交
1475
				}
1476 1477
				return result;
			});
1478 1479 1480
		});
	}

1481 1482
	private getLegacyTaskConfigurations(workspaceTasks: TaskSet): IStringDictionary<CustomTask> {
		let result: IStringDictionary<CustomTask>;
1483 1484 1485 1486 1487 1488 1489 1490
		function getResult() {
			if (result) {
				return result;
			}
			result = Object.create(null);
			return result;
		}
		for (let task of workspaceTasks.tasks) {
1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501
			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;
				}
1502 1503 1504 1505 1506
			}
		}
		return result;
	}

D
Dirk Baeumer 已提交
1507
	private getWorkspaceTasks(): TPromise<Map<string, WorkspaceFolderTaskResult>> {
1508 1509 1510
		if (this._workspaceTasksPromise) {
			return this._workspaceTasksPromise;
		}
1511
		this.updateWorkspaceTasks();
1512 1513 1514 1515 1516
		return this._workspaceTasksPromise;
	}

	private updateWorkspaceTasks(): void {
		this._workspaceTasksPromise = this.computeWorkspaceTasks().then(value => {
D
Dirk Baeumer 已提交
1517
			if (this.executionEngine === ExecutionEngine.Process && this._taskSystem instanceof ProcessTaskSystem) {
D
Dirk Baeumer 已提交
1518 1519 1520 1521 1522
				// 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);
				});
1523 1524
			}
			return value;
1525 1526 1527
		});
	}

1528
	private computeWorkspaceTasks(): TPromise<Map<string, WorkspaceFolderTaskResult>> {
D
Dirk Baeumer 已提交
1529
		if (this.workspaceFolders.length === 0) {
1530 1531 1532
			return TPromise.as(new Map<string, WorkspaceFolderTaskResult>());
		} else {
			let promises: TPromise<WorkspaceFolderTaskResult>[] = [];
D
Dirk Baeumer 已提交
1533
			for (let folder of this.workspaceFolders) {
1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
				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;
			});
		}
	}

S
Sandeep Somavarapu 已提交
1548
	private computeWorkspaceFolderTasks(workspaceFolder: IWorkspaceFolder): TPromise<WorkspaceFolderTaskResult> {
D
Dirk Baeumer 已提交
1549
		return (this.executionEngine === ExecutionEngine.Process
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
			? 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 };
				});
			});
	}

S
Sandeep Somavarapu 已提交
1582
	private computeConfiguration(workspaceFolder: IWorkspaceFolder): TPromise<WorkspaceFolderConfigurationResult> {
1583 1584 1585 1586
		let { config, hasParseErrors } = this.getConfiguration(workspaceFolder);
		return TPromise.as<WorkspaceFolderConfigurationResult>({ workspaceFolder, config, hasErrors: hasParseErrors });
	}

S
Sandeep Somavarapu 已提交
1587
	private computeLegacyConfiguration(workspaceFolder: IWorkspaceFolder): TPromise<WorkspaceFolderConfigurationResult> {
1588 1589 1590 1591 1592 1593
		let { config, hasParseErrors } = this.getConfiguration(workspaceFolder);
		if (hasParseErrors) {
			return TPromise.as({ workspaceFolder: workspaceFolder, hasErrors: true, config: undefined });
		}
		if (config) {
			if (this.hasDetectorSupport(config)) {
D
Dirk Baeumer 已提交
1594
				return new ProcessRunnerDetector(workspaceFolder, this.fileService, this.contextService, this.configurationResolverService, config).detect(true).then((value): WorkspaceFolderConfigurationResult => {
1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619
					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 {
D
Dirk Baeumer 已提交
1620
			return new ProcessRunnerDetector(workspaceFolder, this.fileService, this.contextService, this.configurationResolverService).detect(true).then((value) => {
1621 1622 1623 1624 1625 1626
				let hasErrors = this.printStderr(value.stderr);
				return { workspaceFolder, config: value.config, hasErrors };
			});
		}
	}

D
Dirk Baeumer 已提交
1627
	private computeWorkspaceFolderSetup(): [IWorkspaceFolder[], IWorkspaceFolder[], ExecutionEngine, JsonSchemaVersion] {
S
Sandeep Somavarapu 已提交
1628
		let workspaceFolders: IWorkspaceFolder[] = [];
D
Dirk Baeumer 已提交
1629
		let ignoredWorkspaceFolders: IWorkspaceFolder[] = [];
D
Dirk Baeumer 已提交
1630 1631 1632
		let executionEngine = ExecutionEngine.Terminal;
		let schemaVersion = JsonSchemaVersion.V2_0_0;

D
Dirk Baeumer 已提交
1633
		if (this.contextService.getWorkbenchState() === WorkbenchState.FOLDER) {
S
Sandeep Somavarapu 已提交
1634
			let workspaceFolder: IWorkspaceFolder = this.contextService.getWorkspace().folders[0];
D
Dirk Baeumer 已提交
1635 1636 1637
			workspaceFolders.push(workspaceFolder);
			executionEngine = this.computeExecutionEngine(workspaceFolder);
			schemaVersion = this.computeJsonSchemaVersion(workspaceFolder);
D
Dirk Baeumer 已提交
1638
		} else if (this.contextService.getWorkbenchState() === WorkbenchState.WORKSPACE) {
1639
			for (let workspaceFolder of this.contextService.getWorkspace().folders) {
D
Dirk Baeumer 已提交
1640
				if (schemaVersion === this.computeJsonSchemaVersion(workspaceFolder)) {
D
Dirk Baeumer 已提交
1641
					workspaceFolders.push(workspaceFolder);
1642
				} else {
D
Dirk Baeumer 已提交
1643
					ignoredWorkspaceFolders.push(workspaceFolder);
1644 1645
					this._outputChannel.append(nls.localize(
						'taskService.ignoreingFolder',
1646
						'Ignoring task configurations for workspace folder {0}. Multi folder workspace task support requires that all folders use task version 2.0.0\n',
1647
						workspaceFolder.uri.fsPath));
1648 1649 1650
				}
			}
		}
D
Dirk Baeumer 已提交
1651
		return [workspaceFolders, ignoredWorkspaceFolders, executionEngine, schemaVersion];
1652
	}
1653

S
Sandeep Somavarapu 已提交
1654
	private computeExecutionEngine(workspaceFolder: IWorkspaceFolder): ExecutionEngine {
1655
		let { config } = this.getConfiguration(workspaceFolder);
1656
		if (!config) {
1657
			return ExecutionEngine._default;
1658 1659 1660 1661
		}
		return TaskConfig.ExecutionEngine.from(config);
	}

S
Sandeep Somavarapu 已提交
1662
	private computeJsonSchemaVersion(workspaceFolder: IWorkspaceFolder): JsonSchemaVersion {
1663
		let { config } = this.getConfiguration(workspaceFolder);
1664 1665 1666 1667 1668 1669
		if (!config) {
			return JsonSchemaVersion.V2_0_0;
		}
		return TaskConfig.JsonSchemaVersion.from(config);
	}

S
Sandeep Somavarapu 已提交
1670
	private getConfiguration(workspaceFolder: IWorkspaceFolder): { config: TaskConfig.ExternalTaskRunnerConfiguration; hasParseErrors: boolean } {
D
Dirk Baeumer 已提交
1671
		let result = this.contextService.getWorkbenchState() !== WorkbenchState.EMPTY
1672 1673
			? this.configurationService.getConfiguration<TaskConfig.ExternalTaskRunnerConfiguration>('tasks', { resource: workspaceFolder.uri })
			: undefined;
1674
		if (!result) {
1675
			return { config: undefined, hasParseErrors: false };
1676 1677 1678 1679 1680 1681 1682 1683 1684
		}
		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;
				}
1685
			}
1686
			if (isAffected) {
1687
				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'));
1688
				this.showOutput();
1689
				return { config: undefined, hasParseErrors: true };
1690
			}
1691 1692
		}
		return { config: result, hasParseErrors: false };
1693 1694
	}

E
Erich Gamma 已提交
1695
	private printStderr(stderr: string[]): boolean {
1696
		let result = false;
E
Erich Gamma 已提交
1697 1698
		if (stderr && stderr.length > 0) {
			stderr.forEach((line) => {
1699
				result = true;
1700
				this._outputChannel.append(line + '\n');
E
Erich Gamma 已提交
1701
			});
1702
			this._outputChannel.show(true);
E
Erich Gamma 已提交
1703 1704 1705 1706
		}
		return result;
	}

1707
	public inTerminal(): boolean {
1708 1709 1710
		if (this._taskSystem) {
			return this._taskSystem instanceof TerminalTaskSystem;
		}
D
Dirk Baeumer 已提交
1711
		return this.executionEngine === ExecutionEngine.Terminal;
1712 1713
	}

1714
	private hasDetectorSupport(config: TaskConfig.ExternalTaskRunnerConfiguration): boolean {
1715
		if (!config.command || this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) {
E
Erich Gamma 已提交
1716 1717 1718 1719 1720
			return false;
		}
		return ProcessRunnerDetector.supports(config.command);
	}

1721
	public configureAction(): Action {
1722 1723 1724 1725 1726 1727
		let run = () => { this.runConfigureTasks(); return TPromise.as(undefined); };
		return new class extends Action {
			constructor() {
				super(ConfigureTaskAction.ID, ConfigureTaskAction.TEXT, undefined, true, run);
			}
		};
1728 1729
	}

1730
	private configureBuildTask(): Action {
1731 1732 1733 1734 1735 1736
		let run = () => { this.runConfigureTasks(); return TPromise.as(undefined); };
		return new class extends Action {
			constructor() {
				super(ConfigureTaskAction.ID, ConfigureTaskAction.TEXT, undefined, true, run);
			}
		};
1737 1738
	}

E
Erich Gamma 已提交
1739
	public beforeShutdown(): boolean | TPromise<boolean> {
1740 1741 1742
		if (!this._taskSystem) {
			return false;
		}
1743
		this.saveRecentlyUsedTasks();
1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765
		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 已提交
1766
					}
1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779
				}
				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 已提交
1780
				return true; // veto
1781 1782 1783 1784 1785
			}, (err) => {
				return true; // veto
			});
		} else {
			return true; // veto
E
Erich Gamma 已提交
1786 1787 1788
		}
	}

1789
	private getConfigureAction(code: TaskErrors): Action {
J
Johannes Rieken 已提交
1790
		switch (code) {
1791 1792 1793 1794 1795 1796
			case TaskErrors.NoBuildTask:
				return this.configureBuildTask();
			default:
				return this.configureAction();
		}
	}
1797

J
Johannes Rieken 已提交
1798
	private handleError(err: any): void {
E
Erich Gamma 已提交
1799 1800 1801
		let showOutput = true;
		if (err instanceof TaskError) {
			let buildError = <TaskError>err;
1802 1803 1804
			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 已提交
1805
				let closeAction = new CloseMessageAction();
1806
				let action: Action = needsConfig
1807
					? this.getConfigureAction(buildError.code)
1808 1809
					: new Action(
						'workbench.action.tasks.terminate',
1810
						nls.localize('TerminateAction.label', "Terminate Task"),
1811
						undefined, true, () => { this.runTerminateCommand(); return TPromise.as<void>(undefined); });
J
Johannes Rieken 已提交
1812
				closeAction.closeFunction = this.messageService.show(buildError.severity, { message: buildError.message, actions: [action, closeAction] });
E
Erich Gamma 已提交
1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824
			} 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) {
1825
			this._outputChannel.show(true);
E
Erich Gamma 已提交
1826 1827
		}
	}
1828 1829

	private canRunCommand(): boolean {
1830
		if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) {
1831 1832 1833 1834 1835 1836
			this.messageService.show(Severity.Info, nls.localize('TaskService.noWorkspace', 'Tasks are only available on a workspace folder.'));
			return false;
		}
		return true;
	}

1837
	private createTaskQuickPickEntries(tasks: Task[], group: boolean = false, sort: boolean = false): TaskQuickPickEntry[] {
1838
		if (tasks === void 0 || tasks === null || tasks.length === 0) {
1839
			return [];
1840
		}
1841
		const TaskQuickPickEntry = (task: Task): TaskQuickPickEntry => {
1842
			let description: string;
1843
			if (this.needsFolderQualification()) {
1844 1845
				let workspaceFolder = Task.getWorkspaceFolder(task);
				if (workspaceFolder) {
1846
					description = workspaceFolder.name;
1847 1848 1849 1850
				}
			}
			return { label: task._label, description, task };
		};
1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867
		let taskService = this;
		let action = new class extends Action implements IPickOpenAction {
			constructor() {
				super('configureAction', 'Configure Task', 'quick-open-task-configure', true);
			}
			public run(item: IPickOpenItem): TPromise<boolean> {
				let task: Task = item.getPayload();
				taskService.quickOpenService.close();
				if (ContributedTask.is(task)) {
					taskService.customize(task, undefined, true);
				} else if (CustomTask.is(task)) {
					taskService.openConfig(task);
				}
				return TPromise.as(false);
			}
		};
		function fillEntries(entries: TaskQuickPickEntry[], tasks: Task[], groupLabel: string, withBorder: boolean = false): void {
1868 1869
			let first = true;
			for (let task of tasks) {
1870
				let entry: TaskQuickPickEntry = TaskQuickPickEntry(task);
1871 1872 1873 1874
				if (first) {
					first = false;
					entry.separator = { label: groupLabel, border: withBorder };
				}
1875 1876 1877
				entry.action = action;
				entry.payload = task;
				entries.push(entry);
1878 1879
			}
		}
1880
		let entries: TaskQuickPickEntry[];
1881 1882 1883
		if (group) {
			entries = [];
			if (tasks.length === 1) {
1884
				entries.push(TaskQuickPickEntry(tasks[0]));
1885 1886 1887 1888 1889 1890
			} else {
				let recentlyUsedTasks = this.getRecentlyUsedTasks();
				let recent: Task[] = [];
				let configured: Task[] = [];
				let detected: Task[] = [];
				let taskMap: IStringDictionary<Task> = Object.create(null);
1891 1892 1893 1894 1895 1896
				tasks.forEach(task => {
					let key = Task.getRecentlyUsedKey(task);
					if (key) {
						taskMap[key] = task;
					}
				});
1897 1898 1899 1900 1901 1902 1903
				recentlyUsedTasks.keys().forEach(key => {
					let task = taskMap[key];
					if (task) {
						recent.push(task);
					}
				});
				for (let task of tasks) {
1904 1905
					let key = Task.getRecentlyUsedKey(task);
					if (!key || !recentlyUsedTasks.has(key)) {
1906 1907 1908 1909 1910 1911 1912
						if (task._source.kind === TaskSourceKind.Workspace) {
							configured.push(task);
						} else {
							detected.push(task);
						}
					}
				}
1913
				const sorter = this.createSorter();
1914 1915
				let hasRecentlyUsed: boolean = recent.length > 0;
				fillEntries(entries, recent, nls.localize('recentlyUsed', 'recently used tasks'));
1916
				configured = configured.sort((a, b) => sorter.compare(a, b));
1917 1918
				let hasConfigured = configured.length > 0;
				fillEntries(entries, configured, nls.localize('configured', 'configured tasks'), hasRecentlyUsed);
1919
				detected = detected.sort((a, b) => sorter.compare(a, b));
1920 1921 1922 1923
				fillEntries(entries, detected, nls.localize('detected', 'detected tasks'), hasRecentlyUsed || hasConfigured);
			}
		} else {
			if (sort) {
1924 1925
				const sorter = this.createSorter();
				tasks = tasks.sort((a, b) => sorter.compare(a, b));
1926
			}
1927
			entries = tasks.map<TaskQuickPickEntry>(task => TaskQuickPickEntry(task));
1928
		}
1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945
		return entries;
	}

	private showQuickPick(tasks: TPromise<Task[]> | Task[], placeHolder: string, defaultEntry?: TaskQuickPickEntry, group: boolean = false, sort: boolean = false): TPromise<Task> {
		let _createEntries = (): TPromise<TaskQuickPickEntry[]> => {
			if (Array.isArray(tasks)) {
				return TPromise.as(this.createTaskQuickPickEntries(tasks, group, sort));
			} else {
				return tasks.then((tasks) => this.createTaskQuickPickEntries(tasks, group, sort));
			}
		};
		return this.quickOpenService.pick(_createEntries().then((entries) => {
			if (entries.length === 0 && defaultEntry) {
				entries.push(defaultEntry);
			}
			return entries;
		}), { placeHolder, autoFocus: { autoFocusFirstEntry: true } }).then(entry => entry ? entry.task : undefined);
1946 1947
	}

D
Dirk Baeumer 已提交
1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970
	private showIgnoredFoldersMessage(): TPromise<void> {
		if (this.ignoredWorkspaceFolders.length === 0 || !this.showIgnoreMessage) {
			return TPromise.as(undefined);
		}
		let message: string = nls.localize('TaskService.ignoredFolder', 'The following workspace folders are ignored since they use task version 0.1.0: ');
		for (let i = 0; i < this.ignoredWorkspaceFolders.length; i++) {
			message = message + this.ignoredWorkspaceFolders[i].name;
			if (i < this.ignoredWorkspaceFolders.length - 1) {
				message = message + ', ';
			}
		}

		let notAgain = nls.localize('TaskService.notAgain', 'Don\'t Show Again');
		let ok = nls.localize('TaskService.ok', 'OK');
		return this.choiceService.choose(Severity.Info, message, [notAgain, ok], 0).then((choice) => {
			if (choice === 0) {
				this.storageService.store(TaskService.IgnoreTask010DonotShowAgain_key, true, StorageScope.WORKSPACE);
			}
			this.__showIgnoreMessage = false;
			return undefined;
		}, () => undefined);
	}

1971 1972 1973 1974 1975
	private runTaskCommand(accessor: ServicesAccessor, arg: any): void {
		if (!this.canRunCommand()) {
			return;
		}
		if (Types.isString(arg)) {
1976 1977 1978 1979 1980 1981 1982 1983 1984
			this.getGroupedTasks().then((grouped) => {
				let resolver = this.createResolver(grouped);
				let folders = this.contextService.getWorkspace().folders;
				for (let folder of folders) {
					let task = resolver.resolve(folder, arg);
					if (task) {
						this.run(task);
						return;
					}
1985
				}
1986
				this.doRunTaskCommand(grouped.all());
1987
			}, () => {
1988
				this.doRunTaskCommand();
1989 1990
			});
		} else {
1991
			this.doRunTaskCommand();
1992 1993 1994
		}
	}

1995
	private doRunTaskCommand(tasks?: Task[]): void {
D
Dirk Baeumer 已提交
1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014
		this.showIgnoredFoldersMessage().then(() => {
			this.showQuickPick(tasks ? tasks : this.tasks(),
				nls.localize('TaskService.pickRunTask', 'Select the task to run'),
				{
					label: nls.localize('TaslService.noEntryToRun', 'No task to run found. Configure Tasks...'),
					task: null
				},
				true).
				then((task) => {
					if (task === void 0) {
						return;
					}
					if (task === null) {
						this.runConfigureTasks();
					} else {
						this.run(task, { attachProblemMatcher: true });
					}
				});
		});
2015 2016
	}

2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032
	private splitPerGroupType(tasks: Task[]): { none: Task[], defaults: Task[], users: Task[] } {
		let none: Task[] = [];
		let defaults: Task[] = [];
		let users: Task[] = [];
		for (let task of tasks) {
			if (task.groupType === GroupType.default) {
				defaults.push(task);
			} else if (task.groupType === GroupType.user) {
				users.push(task);
			} else {
				none.push(task);
			}
		}
		return { none, defaults, users };
	}

2033 2034 2035 2036
	private runBuildCommand(): void {
		if (!this.canRunCommand()) {
			return;
		}
D
Dirk Baeumer 已提交
2037
		if (this.schemaVersion === JsonSchemaVersion.V0_1_0) {
2038 2039 2040
			this.build();
			return;
		}
2041 2042 2043 2044 2045
		let options: IProgressOptions = {
			location: ProgressLocation.Window,
			title: nls.localize('TaskService.fetchingBuildTasks', 'Fetching build tasks...')
		};
		let promise = this.getTasksForGroup(TaskGroup.Build).then((tasks) => {
2046
			if (tasks.length > 0) {
2047 2048 2049
				let { none, defaults, users } = this.splitPerGroupType(tasks);
				if (defaults.length === 1) {
					this.run(defaults[0]);
2050
					return;
2051 2052
				} else if (defaults.length + users.length > 0) {
					tasks = defaults.concat(users);
D
Dirk Baeumer 已提交
2053 2054
				}
			}
D
Dirk Baeumer 已提交
2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072
			this.showIgnoredFoldersMessage().then(() => {
				this.showQuickPick(tasks,
					nls.localize('TaskService.pickBuildTask', 'Select the build task to run'),
					{
						label: nls.localize('TaskService.noBuildTask', 'No build task to run found. Configure Tasks...'),
						task: null
					},
					true).then((task) => {
						if (task === void 0) {
							return;
						}
						if (task === null) {
							this.runConfigureTasks();
							return;
						}
						this.run(task, { attachProblemMatcher: true });
					});
			});
2073
		});
2074
		this.progressService.withProgress(options, () => promise);
2075 2076 2077 2078 2079 2080
	}

	private runTestCommand(): void {
		if (!this.canRunCommand()) {
			return;
		}
D
Dirk Baeumer 已提交
2081
		if (this.schemaVersion === JsonSchemaVersion.V0_1_0) {
2082
			this.runTest();
2083 2084
			return;
		}
2085 2086 2087 2088 2089
		let options: IProgressOptions = {
			location: ProgressLocation.Window,
			title: nls.localize('TaskService.fetchingTestTasks', 'Fetching test tasks...')
		};
		let promise = this.getTasksForGroup(TaskGroup.Test).then((tasks) => {
2090
			if (tasks.length > 0) {
2091 2092 2093
				let { none, defaults, users } = this.splitPerGroupType(tasks);
				if (defaults.length === 1) {
					this.run(defaults[0]);
2094
					return;
2095 2096
				} else if (defaults.length + users.length > 0) {
					tasks = defaults.concat(users);
D
Dirk Baeumer 已提交
2097 2098
				}
			}
D
Dirk Baeumer 已提交
2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115
			this.showIgnoredFoldersMessage().then(() => {
				this.showQuickPick(tasks,
					nls.localize('TaskService.pickTestTask', 'Select the test task to run'),
					{
						label: nls.localize('TaskService.noTestTaskTerminal', 'No test task to run found. Configure Tasks...'),
						task: null
					}, true
				).then((task) => {
					if (task === void 0) {
						return;
					}
					if (task === null) {
						this.runConfigureTasks();
						return;
					}
					this.run(task);
				});
2116
			});
2117
		});
2118
		this.progressService.withProgress(options, () => promise);
2119 2120
	}

2121 2122 2123 2124 2125
	private runTerminateCommand(): void {
		if (!this.canRunCommand()) {
			return;
		}
		if (this.inTerminal()) {
2126 2127 2128 2129 2130 2131 2132 2133 2134
			this.showQuickPick(this.getActiveTasks(),
				nls.localize('TaskService.tastToTerminate', 'Select task to terminate'),
				{
					label: nls.localize('TaskService.noTaskRunning', 'No task is currently running'),
					task: null
				},
				false, true
			).then(task => {
				if (task === void 0 || task === null) {
2135 2136
					return;
				}
2137
				this.terminate(task);
2138
			});
2139 2140 2141
		} else {
			this.isActive().then((active) => {
				if (active) {
2142 2143 2144
					this.terminateAll().then((responses) => {
						// the output runner has only one task
						let response = responses[0];
2145
						if (response.success) {
2146 2147 2148
							return;
						}
						if (response.code && response.code === TerminateResponseCode.ProcessNotFound) {
2149 2150
							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 {
2151
							this.messageService.show(Severity.Error, nls.localize('TerminateAction.failed', 'Failed to terminate running task'));
2152 2153 2154 2155 2156 2157
						}
					});
				}
			});
		}
	}
2158 2159 2160 2161 2162 2163

	private runRestartTaskCommand(accessor: ServicesAccessor, arg: any): void {
		if (!this.canRunCommand()) {
			return;
		}
		if (this.inTerminal()) {
2164 2165 2166 2167 2168 2169 2170 2171 2172
			this.showQuickPick(this.getActiveTasks(),
				nls.localize('TaskService.tastToRestart', 'Select the task to restart'),
				{
					label: nls.localize('TaskService.noTaskToRestart', 'No task to restart'),
					task: null
				},
				false, true
			).then(task => {
				if (task === void 0 || task === null) {
2173 2174
					return;
				}
2175
				this.restart(task);
2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186
			});
		} else {
			this.getActiveTasks().then((activeTasks) => {
				if (activeTasks.length === 0) {
					return;
				}
				let task = activeTasks[0];
				this.restart(task);
			});
		}
	}
2187

2188 2189 2190 2191 2192
	private runConfigureTasks(): void {
		if (!this.canRunCommand()) {
			return undefined;
		}
		let taskPromise: TPromise<TaskMap>;
D
Dirk Baeumer 已提交
2193
		if (this.schemaVersion === JsonSchemaVersion.V2_0_0) {
2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277
			taskPromise = this.getGroupedTasks();
		} else {
			taskPromise = TPromise.as(new TaskMap());
		}

		let openTaskFile = (workspaceFolder: IWorkspaceFolder): void => {
			let resource = workspaceFolder.toResource('.vscode/tasks.json');
			let configFileCreated = false;
			this.fileService.resolveFile(resource).then((stat) => stat, () => undefined).then((stat) => {
				if (stat) {
					return stat.resource;
				}
				return this.quickOpenService.pick(taskTemplates, { placeHolder: nls.localize('TaskService.template', 'Select a Task Template') }).then((selection) => {
					if (!selection) {
						return undefined;
					}
					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));
					}
					configFileCreated = true;
					return this.fileService.createFile(resource, content).then((result): URI => {
						this.telemetryService.publicLog(TaskService.TemplateTelemetryEventName, {
							templateId: selection.id,
							autoDetect: selection.autoDetect
						});
						return result.resource;
					});
				});
			}).then((resource) => {
				if (!resource) {
					return;
				}
				this.editorService.openEditor({
					resource: resource,
					options: {
						forceOpen: true,
						pinned: configFileCreated // pin only if config file is created #8727
					}
				}, false);
			});
		};

		let configureTask = (task: Task): void => {
			if (ContributedTask.is(task)) {
				this.customize(task, undefined, true);
			} else if (CustomTask.is(task)) {
				this.openConfig(task);
			}
		};

		function isTaskEntry(value: IPickOpenEntry): value is IPickOpenEntry & { task: Task } {
			let candidate: IPickOpenEntry & { task: Task } = value as any;
			return candidate && !!candidate.task;
		}

		let stats = this.contextService.getWorkspace().folders.map<TPromise<IFileStat>>((folder) => {
			return this.fileService.resolveFile(folder.toResource('.vscode/tasks.json')).then(stat => stat, () => undefined);
		});

		let createLabel = nls.localize('TaskService.createJsonFile', 'Create tasks.json file from template');
		let openLabel = nls.localize('TaskService.openJsonFile', 'Open tasks.json file');
		let entries = TPromise.join(stats).then((stats) => {
			return taskPromise.then((taskMap) => {
				type EntryType = (IPickOpenEntry & { task: Task; }) | (IPickOpenEntry & { folder: IWorkspaceFolder; });
				let entries: EntryType[] = [];
				if (this.contextService.getWorkbenchState() === WorkbenchState.FOLDER) {
					let tasks = taskMap.all();
					if (tasks.length > 0) {
						tasks = tasks.sort((a, b) => a._label.localeCompare(b._label));
						entries = tasks.map(task => { return { label: task._label, task }; });
					} else {
						let label = stats[0] !== void 0 ? openLabel : createLabel;
						entries.push({ label, folder: this.contextService.getWorkspace().folders[0] });
					}
				} else {
					let folders = this.contextService.getWorkspace().folders;
					let index = 0;
					for (let folder of folders) {
						let tasks = taskMap.get(folder);
						if (tasks.length > 0) {
							tasks = tasks.slice().sort((a, b) => a._label.localeCompare(b._label));
							for (let i = 0; i < tasks.length; i++) {
2278
								let entry: EntryType = { label: tasks[i]._label, task: tasks[i], description: folder.name };
2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296
								if (i === 0) {
									entry.separator = { label: folder.name, border: index > 0 };
								}
								entries.push(entry);
							}
						} else {
							let label = stats[index] !== void 0 ? openLabel : createLabel;
							let entry: EntryType = { label, folder: folder };
							entry.separator = { label: folder.name, border: index > 0 };
							entries.push(entry);
						}
						index++;
					}
				}
				return entries;
			});
		});

D
Dirk Baeumer 已提交
2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308
		this.quickOpenService.pick(entries,
			{ placeHolder: nls.localize('TaskService.pickTask', 'Select a task to configure'), autoFocus: { autoFocusFirstEntry: true } }).
			then((selection) => {
				if (!selection) {
					return;
				}
				if (isTaskEntry(selection)) {
					configureTask(selection.task);
				} else {
					openTaskFile(selection.folder);
				}
			});
2309 2310
	}

2311 2312 2313 2314
	private runConfigureDefaultBuildTask(): void {
		if (!this.canRunCommand()) {
			return;
		}
D
Dirk Baeumer 已提交
2315
		if (this.schemaVersion === JsonSchemaVersion.V2_0_0) {
2316 2317
			this.tasks().then((tasks => {
				if (tasks.length === 0) {
2318
					this.runConfigureTasks();
2319 2320 2321
					return;
				}
				let defaultTask: Task;
2322
				let defaultEntry: TaskQuickPickEntry;
2323
				for (let task of tasks) {
2324
					if (task.group === TaskGroup.Build && task.groupType === GroupType.default) {
2325 2326 2327 2328 2329
						defaultTask = task;
						break;
					}
				}
				if (defaultTask) {
2330 2331 2332 2333 2334
					tasks = [];
					defaultEntry = {
						label: nls.localize('TaskService.defaultBuildTaskExists', '{0} is already marked as the default build task', Task.getQualifiedLabel(defaultTask)),
						task: defaultTask
					};
2335
				}
D
Dirk Baeumer 已提交
2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350
				this.showIgnoredFoldersMessage().then(() => {
					this.showQuickPick(tasks,
						nls.localize('TaskService.pickDefaultBuildTask', 'Select the task to be used as the default build task'), defaultEntry, true).
						then((task) => {
							if (task === void 0) {
								return;
							}
							if (task === defaultTask && CustomTask.is(task)) {
								this.openConfig(task);
							}
							if (!InMemoryTask.is(task)) {
								this.customize(task, { group: { kind: 'build', isDefault: true } }, true);
							}
						});
				});
2351 2352
			}));
		} else {
2353
			this.runConfigureTasks();
2354 2355 2356 2357 2358 2359 2360
		}
	}

	private runConfigureDefaultTestTask(): void {
		if (!this.canRunCommand()) {
			return;
		}
D
Dirk Baeumer 已提交
2361
		if (this.schemaVersion === JsonSchemaVersion.V2_0_0) {
2362 2363
			this.tasks().then((tasks => {
				if (tasks.length === 0) {
2364
					this.runConfigureTasks();
2365 2366 2367
				}
				let defaultTask: Task;
				for (let task of tasks) {
2368
					if (task.group === TaskGroup.Test && task.groupType === GroupType.default) {
2369 2370 2371 2372 2373
						defaultTask = task;
						break;
					}
				}
				if (defaultTask) {
2374
					this.messageService.show(Severity.Info, nls.localize('TaskService.defaultTestTaskExists', '{0} is already marked as the default test task.', Task.getQualifiedLabel(defaultTask)));
2375 2376
					return;
				}
D
Dirk Baeumer 已提交
2377 2378 2379 2380 2381 2382 2383 2384 2385
				this.showIgnoredFoldersMessage().then(() => {
					this.showQuickPick(tasks, nls.localize('TaskService.pickDefaultTestTask', 'Select the task to be used as the default test task'), undefined, true).then((task) => {
						if (!task) {
							return;
						}
						if (!InMemoryTask.is(task)) {
							this.customize(task, { group: { kind: 'test', isDefault: true } }, true);
						}
					});
2386 2387 2388
				});
			}));
		} else {
2389
			this.runConfigureTasks();
2390 2391
		}
	}
2392 2393 2394 2395 2396

	public runShowTasks(): void {
		if (!this.canRunCommand()) {
			return;
		}
2397 2398 2399 2400 2401 2402 2403 2404 2405 2406
		this.showQuickPick(this.getActiveTasks(),
			nls.localize('TaskService.pickShowTask', 'Select the task to show its output'),
			{
				label: nls.localize('TaskService.noTaskIsRunning', 'No task is running'),
				task: null
			},
			false, true
		).then((task) => {
			if (task === void 0 || task === null) {
				return;
2407
			}
2408
			this._taskSystem.revealTask(task);
2409 2410
		});
	}
E
Erich Gamma 已提交
2411 2412
}

2413
MenuRegistry.addCommand({ id: ConfigureTaskAction.ID, title: { value: ConfigureTaskAction.TEXT, original: 'Configure Task' }, category: { value: tasksCategory, original: 'Tasks' } });
2414 2415
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' } });
2416
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' } });
2417
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' } });
2418
MenuRegistry.addCommand({ id: 'workbench.action.tasks.terminate', title: { value: nls.localize('TerminateAction.label', "Terminate Task"), original: 'Terminate Task' }, category: { value: tasksCategory, original: 'Tasks' } });
2419 2420
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' } });
2421 2422
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' } });
2423 2424
// 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 });
2425 2426 2427 2428 2429

// Task Service
registerSingleton(ITaskService, TaskService);

// Register Quick Open
2430
const quickOpenRegistry = (<IQuickOpenRegistry>Registry.as(QuickOpenExtensions.Quickopen));
2431
const tasksPickerContextKey = 'inTasksPicker';
2432 2433

quickOpenRegistry.registerQuickOpenHandler(
2434
	new QuickOpenHandlerDescriptor(
2435 2436
		QuickOpenHandler,
		QuickOpenHandler.ID,
2437
		'task ',
2438
		tasksPickerContextKey,
2439 2440 2441 2442
		nls.localize('quickOpen.task', "Run Task")
	)
);

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

2446 2447
// Status bar
let statusbarRegistry = <IStatusbarRegistry>Registry.as(StatusbarExtensions.Statusbar);
2448 2449
statusbarRegistry.registerStatusbarItem(new StatusbarItemDescriptor(BuildStatusBarItem, StatusbarAlignment.LEFT, 50 /* Medium Priority */));
statusbarRegistry.registerStatusbarItem(new StatusbarItemDescriptor(TaskStatusBarItem, StatusbarAlignment.LEFT, 50 /* Medium Priority */));
2450 2451 2452 2453 2454 2455 2456 2457 2458

// 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 已提交
2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469
let schema: IJSONSchema = {
	id: schemaId,
	description: 'Task definition file',
	type: 'object',
	default: {
		version: '0.1.0',
		command: 'myCommand',
		isShellCommand: false,
		args: [],
		showOutput: 'always',
		tasks: [
2470
			{
D
Dirk Baeumer 已提交
2471 2472 2473 2474
				taskName: 'build',
				showOutput: 'silent',
				isBuildCommand: true,
				problemMatcher: ['$tsc', '$lessCompile']
2475 2476
			}
		]
D
Dirk Baeumer 已提交
2477 2478 2479 2480 2481 2482 2483 2484 2485
	}
};

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


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